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): add realized stable layout checks (#123)

rponeawad0641a474512
diff --git a/.agents/skills/hypit/references/element-review.md b/.agents/skills/hypit/references/element-review.md
index f6adce6f..f6c6e194 100644
--- a/.agents/skills/hypit/references/element-review.md
+++ b/.agents/skills/hypit/references/element-review.md
@@ -109,24 +109,11 @@ inside it. For each level, check the following explicitly:
- **Canvas safety:** check the final visible bounds against all four Canvas edges. Nothing should be
clipped unless the reference/intent clearly calls for it.
-`authoring_check` and `reconstruction_check` return a deterministic `layout_geometry` report with
-Canvas/Frame bounds, sizes, centres, parent/Canvas vertical centre offsets, containment overflow, and
-bound element ids. Use those numbers as mechanical facts and let the observer decide whether the
-alignment, offset or overflow matches the reference/intent. The report cannot measure renderer-shaped glyph
-bounds or infer intent, so the visual pass must still confirm text and marks in the rendered image.
-
-The same report includes `layout_geometry.overlaps`. It is an advisory list of independent component
-placements that are on the same Canvas, present during an overlapping timing scope, and have a
-positive-area rectangle intersection without either rectangle fully containing the other. Nested
-placements owned by the same component are excluded; their internal layout is judged against that
-component's own parent/Frame. Full containment is omitted because a background or parent Frame commonly
-covers its child intentionally. Treat each entry as a candidate finding: confirm it in the rendered
-frame and against the author intent before changing Source. For reconstruction, reference observation
-is authoritative; for original authoring, the user's brief and settled creative intent are authoritative.
-Never move an element merely to satisfy this report, and never remove an intentional overlap merely
-because it was listed.
-The check compares only declared Canvas/Frame placement bounds; it cannot see glyph-level or other
-package-internal bounds that a Producer does not expose.
+Run and settle `layout_check` before this visual round. **Read now:** `layout-checks.md`. Its realized
+Producer/DOM measurements accompany the render as candidate evidence only.
+They help locate a relationship worth inspecting but never decide that alignment, offset, crop or
+overlap is wrong. For reconstruction, reference observation is authoritative; for original authoring,
+the user's brief and settled creative intent are authoritative.
Do not treat a clearly platform/player/export-tool watermark as authored content. Ignore it when its
provenance is obvious; if it could be part of the design, record the uncertainty instead of inventing
@@ -159,10 +146,8 @@ one default Style and a `caption:Use` override for one Selection is two looks, w
two first appear, not one per Segment. This is the same reading `script-time.md` applies to every
other system that spans cuts: the system is authored once, so it is read once.
-Source-level Canvas safety is checked separately. `authoring_check` and `reconstruction_check` resolve
-every declared Frame into Canvas coordinates and report the elements bound to any Frame that crosses
-a Canvas edge. Package-internal glyph or private layout bounds remain visible-review facts because
-the Source does not expose geometry that a mechanical check could measure.
+Stable package-internal realized bounds are checked separately by `layout_check`; this visual selection
+remains one full clip per distinct declaration at first appearance and therefore covers motion as well.
### Render every stretch first, then send them all at once
diff --git a/.agents/skills/hypit/references/layout-checks.md b/.agents/skills/hypit/references/layout-checks.md
new file mode 100644
index 00000000..bd672f58
--- /dev/null
+++ b/.agents/skills/hypit/references/layout-checks.md
@@ -0,0 +1,49 @@
+# Layout checks are evidence, not design authority
+
+Run this after `preview_check` whenever Source, SVS, runtime, fonts or a package can affect layout:
+
+```bash
+hypit-reference-video-tools layout_check --run <build.svrun>
+```
+
+The command does not render media, call a visual observer or invoke a paid Provider. It first realizes
+the same preview-mock Run and Producer-generated Composition that the later visual render reuses, then
+writes atomic state to
+`.hypit/layout-check.json` and `.hypit/layout-decisions.json`.
+
+It reports only `realized_layout`: DOM bounds after official or project-local Producers run, including
+parent or Canvas overflow, vertical offset of package-internal content, and partial overlap between
+independent top-level tracks. It does not use literal SVML Canvas/Frame arithmetic as a quality gate.
+
+`Present` is the Composition IR's time-bounded visual unit: one Producer output with its internal
+text, icons, boxes and other elements. For each Present/content state, the checker derives its longest interval in which layout-affecting IR
+does not change and measures the interval's middle frame. Findings for that sample are restricted to
+that Present. Peer overlap is reported only when both Presents share a sampled stable frame. A Present
+with no stable interval of at least two consecutive frames is skipped and left to the full-clip visual
+review; moving entry and exit frames are not treated as layout evidence.
+
+Every reported item is a **candidate measurement**, never a declaration that the design is wrong.
+Cropping, bleed, overlap, off-screen entry motion and optical offset can all be intentional. Read the
+measured relation, the relevant brief/reference and the rendered visual evidence, then either repair a
+real problem or accept the intentional geometry:
+
+```bash
+hypit-reference-video-tools layout_accept --run <build.svrun> \
+ --finding <id> --reason '<why this measured relationship is correct here>'
+hypit-reference-video-tools layout_check --run <build.svrun>
+```
+
+`layout-checked` means the browser/Producer pass executed and every candidate has been judged: repaired
+candidates disappeared and intentional candidates carry a persisted reason. It does **not** mean the
+mechanical checker reported zero candidates. A browser, font or Producer execution failure is a hard
+failure because no measurement was made; it must never be converted into an empty passing report.
+
+Finding identities include the relevant layout digest. A Source, SVS, package, runtime, font or
+composition change invalidates affected acceptances. Rerun `layout_check` after any visual repair, and
+rerun the affected declaration's visual review when the repair changed its look. The final gate needs
+both settled layout evidence and current visual evidence where that route performs visual review.
+
+The 1 CSS px tolerance removes only browser numeric noise. It is not a design threshold and does not
+turn measurements beyond it into mandatory fixes. Do not copy or edit an installed package after a
+candidate appears; adjust legal SVS, choose another component, or use the formal project-local package
+path.
diff --git a/.agents/skills/hypit/references/original-authoring/conformance-round.md b/.agents/skills/hypit/references/original-authoring/conformance-round.md
index 9a70242d..af968d02 100644
--- a/.agents/skills/hypit/references/original-authoring/conformance-round.md
+++ b/.agents/skills/hypit/references/original-authoring/conformance-round.md
@@ -76,15 +76,10 @@ the longest line/mark plus padding, stroke, shadow, and corner treatment; correc
an undersized box acceptable. Separate intentional bleed/crop or enter/exit motion from accidental
overflow, and check the final visible bounds against all four Canvas edges.
-`authoring_check` returns `layout_geometry` with deterministic Canvas/Frame bounds, centres, parent and
-Canvas offsets, containment overflow, and bound element ids. Use it as the mechanical report and make
-the conformance decision from the rendered picture and intent. It also reports
-`layout_geometry.overlaps` for independent same-Canvas component placements that are simultaneous and
-partially intersecting; nested placements owned by one component are excluded and remain subject to
-component-local parent/Frame centring. Full containment is omitted and the entries are advisory
-candidates, not automatic failures. Judge them against the user's brief and settled creative intent; do
-not force centring or remove an intentional overlap. It cannot measure actual glyph or package-internal
-bounds or infer intent, so those still require the reader.
+The settled `../layout-checks.md` report supplies realized stable-state measurements alongside this
+round. They are advisory candidates, not automatic failures. Make the conformance decision from the
+rendered picture and intent; do not force centring, remove an intentional overlap or undo a deliberate
+crop merely because the mechanical pass measured it.
Clearly platform/player/export-tool watermarks are not authored content and should be ignored. If a mark
could be intentional design, preserve the uncertainty and do not silently remove it.
diff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.md
index d8bf74ef..a90251ba 100644
--- a/.agents/skills/hypit/references/original-authoring/route.md
+++ b/.agents/skills/hypit/references/original-authoring/route.md
@@ -51,6 +51,7 @@ interruption or context compaction, read `../recovery.md`, run `route_state --ac
| `script-checked` | every caption Cue has at most four visible words | `validate_script_cues --run <run>` |
| `source-authored` | explicit checkpoint naming `main.svml` (and Recipe/Run when available) | `hypit check <run>` |
| `graph-checked` | `preview_check` returns `sound: true` after package and Cue gates | `preview_check <run>` |
+| `layout-checked` | `layout_check` executed and every candidate was repaired or explicitly accepted | `layout_check --run <run>` / `layout_accept` |
| `review-planned` | `authoring_check` writes a plan | `authoring_check <run>` |
| `preview-rendered` | render output and timing sidecar both exist | `render_element --batch <round.json>` |
| `review-complete` | review log contains a complete record for the planned element | `review_element` / `record_review` |
@@ -182,6 +183,10 @@ attempt ceiling: a graph that does not trace is work that is not done.
### 9. Ask the check what to render, then render it
+First run `layout_check --run <run>` and settle its candidates. **Read now:** `../layout-checks.md`.
+The check is an assistant to judgement, not the source of truth: intentional crop, overlap or offset
+may be accepted with a reason. Then ask the authoring check for the visual review plan.
+
```bash
hypit-reference-video-tools authoring_check projects/<name>/build.svrun
```
@@ -189,10 +194,8 @@ hypit-reference-video-tools authoring_check projects/<name>/build.svrun
Its `plan` is the list: each entry an element and a word range, with the reason. Feed it to
`render_element --batch` — the program is drawn once and every entry is cut out of those frames.
-Keep the check JSON's `layout_geometry` with the renders. It is the deterministic Canvas/Frame report
-for vertical centre offsets, frame capacity, and containment; horizontal left/right placement is not
-judged mechanically. The reader still decides whether visible text or marks fit the intent and whether
-any offset, overlap or bleed is deliberate.
+Keep `.hypit/layout-check.json` with the renders. The reader still decides whether visible text or
+marks fit the intent and whether any measured offset, overlap or bleed is deliberate.
**Read now:** `../element-review.md` — why each distinct visual declaration is read where it first appears.
`../preview.md` holds `render_element` itself.
diff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.md
index f5fe9e42..197c2253 100644
--- a/.agents/skills/hypit/references/preview.md
+++ b/.agents/skills/hypit/references/preview.md
@@ -108,17 +108,12 @@ well.
Each Segment's length comes from the Source's own `estimate:Speech`; `--reference-id` selects reference
evidence and comparison windows only. The sidecar records `"timing_basis": "estimate"`.
-Before reading the picture, run the route's `reconstruction_check` or `authoring_check` and keep its
-`layout_geometry` object with the render. It is the mechanical Canvas/Frame report used to check vertical
-centre offsets, frame capacity, and Canvas containment; horizontal left/right placement is not judged;
-the observer still confirms rendered text bounds and
-whether any bleed is intentional. Also inspect `layout_geometry.overlaps`: it lists only partial
-rectangle intersections between independent same-Canvas component placements whose timing scopes
-overlap. Nested placements owned by one component are excluded so its internal centring is checked
-against its own parent/Frame. Full containment is omitted as a likely intentional parent/background
-relationship. These are candidates, not automatic failures; verify them in the frame and against the
-reference or settled brief/intent. Do not fix a deliberate offset or overlap merely because it was
-reported. Package-internal glyph bounds are not available to the mechanical check.
+Before reading the picture, run and settle `layout_check` and keep `.hypit/layout-check.json` with the
+render. **Read now:** `layout-checks.md`. Its realized stable-state measurements are candidates for the
+Agent to interpret, not automatic failures or instructions to edit. `layout_check` creates and records
+the preview-mock Run and live Composition without encoding media; this later render reuses that same
+upstream. The observer still confirms the look and the Agent decides whether any crop, offset or overlap
+is intentional.
## Open the whole Run for a person
diff --git a/.agents/skills/hypit/references/reconstruction/comparison-round.md b/.agents/skills/hypit/references/reconstruction/comparison-round.md
index c7378e1b..c105cef8 100644
--- a/.agents/skills/hypit/references/reconstruction/comparison-round.md
+++ b/.agents/skills/hypit/references/reconstruction/comparison-round.md
@@ -165,17 +165,10 @@ watermark/overlay; it is not authored video content and must not become a repair
provenance is uncertain or it may be an authored design element, keep it as an uncertainty and ask
for confirmation rather than silently discarding it.
-The `reconstruction_check` JSON includes `layout_geometry`, a mechanical report of Canvas/Frame bounds,
-centres, parent/Canvas vertical centre offsets, containment overflow, and bound element ids. The agent
-should use those facts alongside the comparison text. They are deterministic Source facts, not a decision:
-horizontal left/right placement is not judged mechanically, and rendered
-glyph bounds and whether an overhang is intentional still require the observer. Its
-`layout_geometry.overlaps` list is an advisory set of independent same-Canvas component placements that
-are temporally simultaneous and partially intersecting. Nested placements owned by one component are
-excluded; their internal centring remains a component-local parent/Frame comparison. Full containment
-is intentionally omitted; confirm each candidate against the rendered frame and intent, and do not treat
-it as an automatic gate failure or a command to remove an intentional overlap. The list cannot detect overlap between package-internal glyphs or other
-bounds not exposed by Source placement.
+The settled `../layout-checks.md` report supplies realized stable-state measurements alongside the
+comparison. They are deterministic evidence, not a decision. Confirm each candidate against the
+reference and rendered clip; do not treat it as an automatic failure or a command to remove intentional
+overlap, crop, bleed, optical offset or enter/exit motion.
## Measuring, on this route
diff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.md
index 6053bf7a..ad836e4b 100644
--- a/.agents/skills/hypit/references/reconstruction/route.md
+++ b/.agents/skills/hypit/references/reconstruction/route.md
@@ -91,6 +91,7 @@ of intent; files and check results remain the authority.
| `script-checked` | every caption Cue has at most four visible words | `validate_script_cues --run <run>` |
| `source-authored` | explicit checkpoint naming `main.svml` (and Recipe/Run when available) | `hypit check <run>` |
| `graph-checked` | `preview_check` returns `sound: true` after package and Cue gates | `preview_check <run>` |
+| `layout-checked` | `layout_check` executed and every candidate was repaired or explicitly accepted | `layout_check --run <run>` / `layout_accept` |
| `review-planned` | `reconstruction_check` writes a plan | `reconstruction_check <run>` |
| `preview-rendered` | render output and timing sidecar both exist | `render_element --batch <round.json>` |
| `comparison-complete` | comparison log contains a complete record for the planned element | `compare_reconstruction` / `record_observation` |
@@ -325,7 +326,10 @@ first written. This gate is not bounded by the round's attempt ceilings.
### 17. Create the comparison plan
-Run `reconstruction_check` once to persist the element/window plan. Do not invent a render list from
+Run `layout_check --run <run>` first and settle its candidates. **Read now:** `../layout-checks.md`.
+Mechanical measurements only point the Agent toward relationships worth judging; the reference and
+design intent decide whether any crop, offset or overlap is a problem. Then run
+`reconstruction_check` once to persist the element/window plan. Do not invent a render list from
the Source; the check's plan is the durable handoff to the comparison round.
---
@@ -354,10 +358,8 @@ hypit-reference-video-tools render_element projects/<name>/build.svrun --batch r
The program is drawn once and every entry is cut out of those frames, so render
the whole list in one `--batch` call.
-Keep the check JSON's `layout_geometry` beside the round. It gives the observer/agent deterministic
-Canvas and Frame centres, parent/Canvas vertical centre offsets, overflow edges, and bound element ids
-to use when judging vertical centring, frame capacity, and Canvas safety. Horizontal placement and
-overlap candidates remain subject to the reference and observer intent judgement.
+Keep `.hypit/layout-check.json` beside the round. Its realized stable-state measurements remain
+candidate evidence; the reference and observer/Agent intent judgement remain authoritative.
### 20. Send every comparison at once
diff --git a/.agents/skills/hypit/references/recovery.md b/.agents/skills/hypit/references/recovery.md
index 0ed47215..e4229204 100644
--- a/.agents/skills/hypit/references/recovery.md
+++ b/.agents/skills/hypit/references/recovery.md
@@ -79,9 +79,12 @@ checkpoint:
hypit-reference-video-tools route_state --action checkpoint \
--project-root <project> --route reconstruction --state review-planned \
--status complete --next-action 'run final reconstruction_check' \
- --decision 'caption box is intentionally centred'
+ --decision 'visual review completed against the reference'
```
+Layout candidates use their dedicated persisted decision file instead of a prose route checkpoint:
+run `layout_accept --run <run> --finding <id> --reason <text>`, rerun `layout_check`, then reconcile.
+
`reconcile` never guesses a creative decision. It can advance from durable files and passing checks,
but leaves an unrecorded manual step as the next action. If a recorded artifact disappeared, the next
reconciliation moves the route back to the first step whose evidence is missing.
diff --git a/.agents/skills/hypit/references/revision/route.md b/.agents/skills/hypit/references/revision/route.md
index f7e500a4..fd7adcab 100644
--- a/.agents/skills/hypit/references/revision/route.md
+++ b/.agents/skills/hypit/references/revision/route.md
@@ -6,7 +6,8 @@ over an already completed project directory directly. Revision does not require
have created the project and does not require a parent creation route to exist.
For a directly supplied directory, first locate its canonical Run and Source/Recipe closure, then
-run `validate_local_author_packages`, `validate_script_cues`, `hypit check` and `preview_check` to
+run `validate_local_author_packages`, `validate_script_cues`, `hypit check`, `preview_check` and
+`layout_check` to
confirm the existing project is a sound revision baseline. If `.hypit/route-state.json` exists, read
and reconcile it; if it does not, do not invent a reconstruction or description history. Start
`revision_state` without `--parent-route` and persist the baseline check evidence with the first
@@ -88,11 +89,14 @@ and give the author the exact URL with the updated result.
Cue/SemanticTake/timing change; a new
component is a vocabulary-gap and package change. A Hook or opening change also requires checking
that later beats still fulfil its promise.
-4. Edit only Source, Recipe or Run. Re-run package/Cue gates, `hypit check` and `preview_check`, then
+4. Edit only Source, Recipe or Run. Re-run package/Cue gates, `hypit check`, `preview_check` and
+ `layout_check`, then
checkpoint their immutable evidence as the Revision final gate. When the parent is `variant`, do
**not** run `variant_check`: that command belongs only to initial batch production and would
reapply the old `allowed_changes` to a new user-authorized request. Do not render, compare, review
- or inspect any frame during revision;
+ or inspect any frame during revision. **Read now:** `../layout-checks.md`. Its browser measurements
+ are mechanical candidate evidence rather than visual judgement; repair genuine issues or persist a
+ reason for intentional geometry before completing `gates-checked`;
existing unchanged artifacts may be reused by digest. Once the gates pass, follow
`../studio-confirmation.md`'s conditional Studio handoff.
5. Check the final gate. Confirm cost again only when an image/video/voice generation input changed;
diff --git a/.agents/skills/hypit/references/variant-expansion/route.md b/.agents/skills/hypit/references/variant-expansion/route.md
index 025c515e..b42f4870 100644
--- a/.agents/skills/hypit/references/variant-expansion/route.md
+++ b/.agents/skills/hypit/references/variant-expansion/route.md
@@ -173,12 +173,13 @@ craft documents, `../authoring.md` and `../preview.md`. Its route is:
```text
gap-confirmed → guidance-loaded → types-frozen → implemented
-→ vocabulary-inspected → package-validated → graph-checked → package-ready
+→ vocabulary-inspected → package-validated → graph-checked → layout-checked → package-ready
```
It must repeat `list_svml_packages` and `inspect_svml_vocabulary` to confirm the gap, freeze Types and
-Manifest before implementation, then run Run-scoped inspection, `validate_local_author_packages` and
-`preview_check`. If package assets require paid generation, obtain cost approval first.
+Manifest before implementation, then run Run-scoped inspection, `validate_local_author_packages`,
+`preview_check` and `layout_check`. Read `../layout-checks.md`; its candidates are judged, not blindly
+fixed. If package assets require paid generation, obtain cost approval first.
When the route has passed through `graph-checked`, checkpoint the batch package entry with
`status: "ready"` and name the package directory as `package_root` when it is below the staging
@@ -248,7 +249,7 @@ The variant route is:
```text
baseline-copied → brief-frozen → change-scope-frozen → guidance-loaded
→ vocabulary-verified → package-ready → script-checked → source-updated
-→ graph-checked → final-checked → variant-complete
+→ graph-checked → layout-checked → final-checked → variant-complete
```
Change only the files named by `allowed_changes`:
@@ -260,16 +261,17 @@ Change only the files named by `allowed_changes`:
- confirmed component changes in imports, project packages or dependencies.
Do not reformat, rename or rewrite unaffected files. Then run the package/Cue gates, `hypit check`,
-`preview_check`, and:
+`preview_check`, `layout_check --run <variant>/build.svrun`, settle every candidate by repair or an
+explicit acceptance reason, and then run:
```bash
hypit-reference-video-tools variant_check --run <variant>/build.svrun
```
-`variant_check` is mechanical only. It verifies vocabulary evidence, package use, Cue lengths, source
+`variant_check` is mechanical only. It verifies settled layout evidence, vocabulary evidence, package use, Cue lengths, source
legality, graph tracing, frame-coverage/playback facts, generated-result leakage and the digest diff
-against `allowed_changes`. It reports Frame/Canvas boundary and layout geometry facts without making
-a visual judgement. It never renders or invokes a VLM.
+against `allowed_changes`. Layout candidates remain evidence for the Agent, not mandatory edits. It
+never renders media or invokes a VLM.
If the diff escapes `allowed_changes`, the route becomes blocked and the batch records
`scope-expansion-required`. The main agent decides whether the requested brief genuinely requires the
diff --git a/packages/reference-video-tools/package.json b/packages/reference-video-tools/package.json
index 596deca7..6b457a4f 100644
--- a/packages/reference-video-tools/package.json
+++ b/packages/reference-video-tools/package.json
@@ -36,6 +36,7 @@
"@hypit/video-cli": "workspace:*",
"@hypit/whisperx": "workspace:*",
"@hypit/yt-dlp": "workspace:*",
+ "puppeteer-core": "25.5.0",
"tsx": "4.21.0"
},
"devDependencies": {
diff --git a/packages/reference-video-tools/src/authoring.ts b/packages/reference-video-tools/src/authoring.ts
index ead02ad1..8eb6bf4f 100644
--- a/packages/reference-video-tools/src/authoring.ts
+++ b/packages/reference-video-tools/src/authoring.ts
@@ -112,7 +112,7 @@ function nearestTree(start: string): string | undefined {
}
}
-function repositoryRoot(): string {
+export function repositoryRoot(): string {
// An explicit override is taken as given. Re-deriving it would refuse a layout the caller can see
// and this cannot, which leaves no way out of a wrong guess.
const override = process.env.HYPIT_REPOSITORY?.trim();
@@ -537,64 +537,49 @@ function timingReport(reference: string | undefined, segments: readonly StandInT
};
}
+export type RealizedAuthoringPreview = {
+ readonly runPath: string;
+ readonly runRoot: string;
+ readonly projectRoot: string;
+ readonly packageRoot: string;
+ readonly svmlPath: string;
+ readonly svml: string;
+ readonly built: Preview;
+ readonly previewMock: Awaited<ReturnType<typeof realizePreviewMock>>;
+ readonly programFrames: number;
+ readonly frameOfToken: readonly { readonly frame: number; readonly end: number }[];
+ readonly selections: ReadonlyMap<string, AuthoringWindow>;
+ readonly segmentTokenCounts: ReadonlyMap<string, number>;
+};
+
/**
- * Render one element through the native preview realization path.
- *
- * The original Run is compiled once, its Author/Run Graph is handed to `@hypit/preview-mock`, and
- * the resulting temporary Run is previewed by Studio with only the local mock-media Provider. The
- * reference transcript remains comparison evidence; it never supplies preview timing.
+ * Realize the Author + Run graph with deterministic preview mocks, without drawing or encoding media.
+ * Layout inspection and render_element share this path so they inspect the same Producer output.
*/
-export async function renderElement(input: RenderElementInput): Promise<Record<string, unknown>> {
- // A round carries these per entry; one render has to name all three itself.
- assert(input.run !== undefined, "run is required");
- assert(input.element !== undefined, "element is required");
- assert(input.out !== undefined, "out is required");
- const element = input.element;
- const out = input.out;
- const run = input.run;
+export async function realizeAuthoringPreview(input: {
+ readonly run: string;
+ readonly package_root?: string;
+}): Promise<RealizedAuthoringPreview> {
const cwd = invokedFrom();
- const runPath = resolve(cwd, run);
+ const runPath = resolve(cwd, input.run);
const runRoot = dirname(runPath);
const projectRoot = input.package_root === undefined
? (nearestPackageRoot(runRoot) ?? repositoryRoot())
: resolve(cwd, input.package_root);
- // Where installed packages are found, which is not where the Hypit tree is. A project carries its
- // own packages, so the search starts at the project and walks up the way the CLI's does —
- // resolving against the tree instead would miss every package the project installed for itself.
const packageRoot = projectRoot;
- const outPath = resolve(cwd, out);
- // The directory the caller named, made rather than required. `out` is resolved against the working
- // directory the way `run` is, so a round whose entries name `renders/<element>.mp4` writes them
- // beside wherever it was launched from — and if nothing has created that directory, ffmpeg is the
- // one that reports it, as `Error opening output …: No such file or directory` against a path the
- // caller never typed.
- await ensureDir(dirname(outPath));
-
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, `${run} declares no <author source="…"/>`);
+ assert(author !== undefined, `${input.run} declares no <author source="…"/>`);
const svmlPath = resolve(runRoot, author);
- let svml = await readFile(svmlPath, "utf8").catch(() => undefined);
+ const svml = await readFile(svmlPath, "utf8").catch(() => undefined);
assert(svml !== undefined, `cannot read ${svmlPath}`);
- // Preview is realized from the compiled Author + Run Graph. No reference transcript, placeholder
- // files, or hand-written SemanticTake values participate in this path.
- const segmentArgument = input.segment;
- const selectionArgument = input.selection;
- const tokensArgument = input.tokens === undefined ? undefined : tokenWindow(input.tokens, "tokens");
const distributionPackageRoot = videoCliDistribution.packageRoot;
if (distributionPackageRoot === undefined) throw new Error("active Hypit Distribution has no package root");
- const renderKey = createHash("sha256").update(`${resolve(runPath)}\u0000${input.reference_id ?? ""}`).digest("hex").slice(0, 12);
const registry = await loadStudioCompanionRegistry({ workspaceRoot: projectRoot, packageRoot, distributionPackageRoot });
const domain = await loadStudioDomain({ run: runPath, workspaceRoot: projectRoot, packageRoot });
const archive = await openStudioArchive(undefined, packageRoot, projectRoot, distributionPackageRoot);
- let built: Preview;
- let previewMock: Awaited<ReturnType<typeof realizePreviewMock>>;
- let programFrames = 0;
- let frameOfToken: readonly { readonly frame: number; readonly end: number }[] = [];
- let selections = new Map<string, AuthoringWindow>();
- let segmentTokenCounts = new Map<string, number>();
try {
const original = await loadStudioRun({ run: runPath, domain, registry, ...(archive === undefined ? {} : { archive }) });
const graph: CompiledGraph = {
@@ -606,50 +591,143 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s
const aliases = new Map(original.source.exports.map((item) => [item.ref, item.name] as const));
for (const record of original.source.compiled.program.records) {
const local = original.source.compiled.provenance.elements.flatMap((element) => element.records)
- .find((item) => item.id === record.id)?.local
- ?? record.id.split("::record::")[1];
+ .find((item) => item.id === record.id)?.local ?? record.id.split("::record::")[1];
if (local !== undefined) aliases.set(record.id, local);
}
- previewMock = await realizePreviewMock({ run: runPath, graph, records: original.source.compiled.program.records, targets: original.targets, timing: "estimate", author, aliases });
+ const previewMock = await realizePreviewMock({
+ run: runPath, graph, records: original.source.compiled.program.records,
+ targets: original.targets, timing: "estimate", author, aliases,
+ });
const previewRegistry = await loadStudioCompanionRegistry({ workspaceRoot: projectRoot, packageRoot, distributionPackageRoot });
const previewDomain = await loadStudioDomain({ run: previewMock.previewRun, workspaceRoot: projectRoot, packageRoot });
const previewArchive = await openStudioArchive(undefined, packageRoot, projectRoot, distributionPackageRoot);
- const loadedPreview = await loadStudioRun({ run: previewMock.previewRun, domain: previewDomain, registry: previewRegistry, ...(previewArchive === undefined ? {} : { archive: previewArchive }) });
- const previewRun = { ...loadedPreview, attachments: [...loadedPreview.attachments, ...previewMock.attachments] };
- const inspection = inspectStudioRun(previewRegistry, previewRun.source, previewRun, new Set([
- "@hypit/mock-media@1#render-mock-image",
- "@hypit/mock-media@1#render-mock-video",
- "@hypit/mock-media@1#render-mock-silence",
- "@hypit/media-pipeline@1#inspect-media",
- "@hypit/media-pipeline@1#normalize-media",
- ]));
- const deterministicEndpoints = new EndpointRegistry();
- await createLocalMediaProvider({}).install(deterministicEndpoints);
- built = await preview({
- source: previewRun.source,
- run: previewRun,
- domain: previewDomain,
- outputRefs: [inspection.filmComposition, ...inspection.projections.map((item) => item.ref)],
- compositionRef: inspection.filmComposition,
- projections: inspection.projections,
- ...(previewArchive === undefined ? {} : { archive: previewArchive }),
- endpoints: deterministicEndpoints,
- });
- programFrames = Math.max(1, ...built.anchors.values());
- frameOfToken = built.tokens.map((token) => ({ frame: built.anchors.get(token.startAnchorId) ?? 0, end: built.anchors.get(token.endAnchorId) ?? 0 }));
- const parsed = parseScript(svmlPath, scriptBody(svml).text, scriptBody(svml).offset);
- const cursor = (from: number, to: number): AuthoringWindow => ({ startFrame: frameOfToken[from]?.frame ?? 0, endFrameExclusive: frameOfToken[to - 1]?.end ?? programFrames });
- for (const segment of parsed.segments) {
- const window = cursor(segment.tokenStart, segment.tokenEndExclusive);
- selections.set(`segment:${segment.id}`, window);
- segmentTokenCounts.set(segment.id, segment.tokenEndExclusive - segment.tokenStart);
+ try {
+ const loadedPreview = await loadStudioRun({
+ run: previewMock.previewRun, domain: previewDomain, registry: previewRegistry,
+ ...(previewArchive === undefined ? {} : { archive: previewArchive }),
+ });
+ const previewRun = { ...loadedPreview, attachments: [...loadedPreview.attachments, ...previewMock.attachments] };
+ const inspection = inspectStudioRun(previewRegistry, previewRun.source, previewRun, new Set([
+ "@hypit/mock-media@1#render-mock-image",
+ "@hypit/mock-media@1#render-mock-video",
+ "@hypit/mock-media@1#render-mock-silence",
+ "@hypit/media-pipeline@1#inspect-media",
+ "@hypit/media-pipeline@1#normalize-media",
+ ]));
+ const deterministicEndpoints = new EndpointRegistry();
+ await createLocalMediaProvider({}).install(deterministicEndpoints);
+ const built = await preview({
+ source: previewRun.source,
+ run: previewRun,
+ domain: previewDomain,
+ outputRefs: [inspection.filmComposition, ...inspection.projections.map((item) => item.ref)],
+ compositionRef: inspection.filmComposition,
+ projections: inspection.projections,
+ ...(previewArchive === undefined ? {} : { archive: previewArchive }),
+ endpoints: deterministicEndpoints,
+ });
+ const programFrames = Math.max(1, ...built.anchors.values());
+ const frameOfToken = built.tokens.map((token) => ({
+ frame: built.anchors.get(token.startAnchorId) ?? 0,
+ end: built.anchors.get(token.endAnchorId) ?? 0,
+ }));
+ const parsed = parseScript(svmlPath, scriptBody(svml).text, scriptBody(svml).offset);
+ const cursor = (from: number, to: number): AuthoringWindow => ({
+ startFrame: frameOfToken[from]?.frame ?? 0,
+ endFrameExclusive: frameOfToken[to - 1]?.end ?? programFrames,
+ });
+ const selections = new Map<string, AuthoringWindow>();
+ const segmentTokenCounts = new Map<string, number>();
+ for (const segment of parsed.segments) {
+ selections.set(`segment:${segment.id}`, cursor(segment.tokenStart, segment.tokenEndExclusive));
+ segmentTokenCounts.set(segment.id, segment.tokenEndExclusive - segment.tokenStart);
+ }
+ for (const selection of parsed.selections) {
+ selections.set(selection.id, cursor(selection.open.boundary.tokenIndex, selection.close.boundary.tokenIndex));
+ }
+ return {
+ runPath, runRoot, projectRoot, packageRoot, svmlPath, svml, built, previewMock,
+ programFrames, frameOfToken, selections, segmentTokenCounts,
+ };
+ } finally {
+ await previewArchive?.close();
}
- for (const selection of parsed.selections) selections.set(selection.id, cursor(selection.open.boundary.tokenIndex, selection.close.boundary.tokenIndex));
} 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"));
+ 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));
+ } finally {
+ await archive?.close();
+ }
+}
+
+/** Materialize a realized composition and its served artifacts without opening a browser. */
+export async function stageAuthoringPreview(realized: Pick<RealizedAuthoringPreview, "built" | "previewMock">): Promise<{
+ readonly stage: string;
+ readonly document: ReturnType<typeof compileHyperframesDocument>;
+ readonly mediaTypes: ReadonlyMap<string, string>;
+}> {
+ const stage = join(realized.previewMock.root, "stage");
+ const document = compileHyperframesDocument(realized.built.composition, realized.built.space as ProgramSpace);
+ await mkdir(stage, { recursive: true });
+ const names = new Map<string, string>();
+ const mediaTypes = new Map<string, string>();
+ for (const [digest, file] of realized.built.served) {
+ const extension = file.mediaType === "text/css" ? ".css"
+ : file.mediaType === "application/javascript" || file.mediaType === "text/javascript" ? ".js"
+ : "";
+ const name = `${digest.replace(/[^a-z0-9]/giu, "")}${extension}`;
+ await writeFile(join(stage, name), file.bytes);
+ names.set(digest, name);
+ mediaTypes.set(name, file.mediaType);
}
+ 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");
+ return { stage, document, mediaTypes };
+}
+
+/**
+ * Render one element through the native preview realization path.
+ *
+ * The original Run is compiled once, its Author/Run Graph is handed to `@hypit/preview-mock`, and
+ * the resulting temporary Run is previewed by Studio with only the local mock-media Provider. The
+ * reference transcript remains comparison evidence; it never supplies preview timing.
+ */
+export async function renderElement(input: RenderElementInput): Promise<Record<string, unknown>> {
+ // A round carries these per entry; one render has to name all three itself.
+ assert(input.run !== undefined, "run is required");
+ assert(input.element !== undefined, "element is required");
+ assert(input.out !== undefined, "out is required");
+ const element = input.element;
+ const out = input.out;
+ const run = input.run;
+ const cwd = invokedFrom();
+ const outPath = resolve(cwd, out);
+ // The directory the caller named, made rather than required. `out` is resolved against the working
+ // directory the way `run` is, so a round whose entries name `renders/<element>.mp4` writes them
+ // beside wherever it was launched from — and if nothing has created that directory, ffmpeg is the
+ // one that reports it, as `Error opening output …: No such file or directory` against a path the
+ // caller never typed.
+ await ensureDir(dirname(outPath));
+
+ // Preview is realized from the compiled Author + Run Graph. No reference transcript, placeholder
+ // files, or hand-written SemanticTake values participate in this path.
+ const segmentArgument = input.segment;
+ const selectionArgument = input.selection;
+ const tokensArgument = input.tokens === undefined ? undefined : tokenWindow(input.tokens, "tokens");
+ const realized = await realizeAuthoringPreview({
+ run,
+ ...(input.package_root === undefined ? {} : { package_root: input.package_root }),
+ });
+ const {
+ runPath, built, previewMock, programFrames, frameOfToken, selections, segmentTokenCounts,
+ } = realized;
+ const renderKey = createHash("sha256").update(`${resolve(runPath)}\u0000${input.reference_id ?? ""}`).digest("hex").slice(0, 12);
const compareRoot = previewMock.root;
const canvas = built.canvas;
const frameRate = built.frameRate.numerator / built.frameRate.denominator;
@@ -710,22 +788,8 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s
// loads it hands the runtime a file with no timeline in it, reported as
// `Composition has zero duration`.
await once(`draw:${renderKey}`, async () => {
- // Compile once, materialize with the artifact bytes written beside the document, and let the
- // HyperFrames runtime draw it. This remains the same public rendering path used by Studio;
- // nothing here is a private renderer.
- const document = compileHyperframesDocument(built.composition, built.space as ProgramSpace);
- 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");
+ // Compile and materialize through the same no-media staging helper used by layout_check.
+ await stageAuthoringPreview({ built, previewMock });
await rm(frames, { recursive: true, force: true });
await mkdir(frames, { recursive: true });
diff --git a/packages/reference-video-tools/src/checks.ts b/packages/reference-video-tools/src/checks.ts
index d82e2e57..696313a6 100644
--- a/packages/reference-video-tools/src/checks.ts
+++ b/packages/reference-video-tools/src/checks.ts
@@ -332,74 +332,6 @@ type CoverageReport = {
readonly gaps: readonly CoverageGap[];
};
-type Edge = "left" | "top" | "right" | "bottom";
-
-/** One edge of a Frame that lands outside the Canvas, and how far past it reaches. */
-type FrameEdge = {
- readonly edge: Edge;
- /** The value as the Source writes it. */
- readonly declared: string;
- /** How far past the Canvas edge it sits, as a share of the Canvas and in Canvas pixels. */
- readonly outside_percent: number;
- readonly outside_pixels: number;
-};
-
-/** One Frame that does not sit wholly inside its Canvas, and the elements drawn into it. */
-type OutOfBoundsFrame = {
- readonly frame: string;
- readonly canvas: string;
- /** Every element that names this Frame, by its own id. */
- readonly elements: readonly string[];
- readonly edges: readonly FrameEdge[];
- /** How much of the Frame's area lands off the Canvas, from 0 to 1. */
- readonly outside_fraction: number;
-};
-
-/**
- * Deterministic geometry facts handed to the observer alongside the human-readable round.
- *
- * This deliberately reports only what the Source can prove: Canvas/Frame rectangles, parent and
- * Canvas containment, and vertical centre offsets. Whether a particular box *ought* to be centred, or whether
- * a child is intentionally clipped (for example during an enter animation), remains a visual and
- * intent judgement. Text glyph bounds are renderer-dependent and therefore are not invented here.
- */
-type LayoutGeometryEntry = {
- readonly id: string;
- readonly kind: "canvas" | "frame";
- readonly within?: string;
- readonly canvas?: string;
- readonly bounds?: Box;
- readonly size?: { readonly width: number; readonly height: number };
- readonly center?: { readonly x: number; readonly y: number };
- /** Signed vertical centre offset: positive means below the parent/Canvas centre. */
- readonly vertical_center_offset_from_within?: number;
- readonly vertical_center_offset_from_canvas?: number;
- readonly outside_within?: { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number };
- readonly outside_canvas?: { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number };
- readonly bound_elements?: readonly string[];
- readonly unresolved?: string;
-};
-
-/** A mechanically detected partial intersection between two Source-level placements. */
-type LayoutOverlap = {
- readonly first: string;
- readonly second: string;
- readonly canvas: string;
- readonly first_bounds: Box;
- readonly second_bounds: Box;
- readonly intersection: Box;
- readonly scope: string;
- readonly note: string;
-};
-
-type LayoutGeometryReport = {
- readonly coordinate_system: "Canvas pixels, origin top-left, y increases downward";
- readonly note: string;
- readonly entries: readonly LayoutGeometryEntry[];
- /** Partial overlaps only; full containment is intentionally omitted. */
- readonly overlaps: readonly LayoutOverlap[];
-};
-
/** A rectangle in Canvas pixels. The origin is top-left and y increases downward. */
type Box = { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number };
@@ -451,7 +383,8 @@ function fillsACanvas(
return false;
}
-type FrameDeclaration ={ readonly within: string; readonly edges: Readonly<Record<Edge, string>> };
+type FrameEdgeName = "left" | "top" | "right" | "bottom";
+type FrameDeclaration ={ readonly within: string; readonly edges: Readonly<Record<FrameEdgeName, string>> };
type FrameGeometry = {
readonly canvases: ReadonlyMap<string, Box>;
readonly declared: ReadonlyMap<string, FrameDeclaration>;
@@ -469,8 +402,9 @@ type FrameGeometry = {
* Frame is resolved by resolving whatever it is written inside and measuring its own edges against
* that rectangle, however deep the chain runs.
*
- * Two readings need this: whether a Frame reaches outside its Canvas, and whether the Frames drawn
- * over a word add up to the whole picture.
+ * The remaining Source-level checks use this only to determine which declared placements cover the
+ * Canvas and whether the Canvas has the reference's aspect ratio. Layout quality is measured later
+ * from the realized Composition DOM.
*/
function frameGeometry(svml: string): FrameGeometry {
const space = aliasPattern(svml, "@hypit/spatial", "space");
@@ -490,7 +424,7 @@ function frameGeometry(svml: string): FrameGeometry {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const within = /\bwithin=\{([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- const written = (name: Edge): string | undefined => new RegExp(`\\b${name}="([^"]+)"`, "u").exec(attributes)?.[1];
+ const written = (name: FrameEdgeName): string | undefined => new RegExp(`\\b${name}="([^"]+)"`, "u").exec(attributes)?.[1];
const left = written("left");
const top = written("top");
const right = written("right");
@@ -550,283 +484,6 @@ function frameGeometry(svml: string): FrameGeometry {
return { canvases, declared, resolve, canvasOf };
}
-/**
- * Every Frame that reaches past the Canvas it is measured inside.
- *
- * A Frame places its four edges against a Canvas, and an edge outside 0%–100% puts that much of
- * whatever is drawn into it off the picture. This is arithmetic on the Source: no threshold, no
- * measurement of a rendered frame, no observer.
- *
- * It is the one thing on this route a comparison cannot see. An element authored mostly below the
- * bottom edge is drawn at the Canvas the Source declares, and so is the stand-in it is compared
- * against, so the render and the reference both put it in the same place off the edge and agree with
- * each other. Both are wrong the same way, which reads as correct.
- *
- * Reaching past the edge is also how a great deal of correct authoring works: an element that slides
- * in from off-screen is outside at the start of its window, and a full-bleed picture is routinely
- * declared past the edge so a `fit` crops it rather than letterboxing it. The arithmetic is the same
- * either way, so what this produces is a list of candidates for a reader to answer one at a time. It
- * never decides `passed`: the Source cannot tell an intended overhang from an unintended one, and a
- * gate that ruled on it would be ruling on something it cannot see.
- */
-function framesPastTheCanvas(svml: string): readonly OutOfBoundsFrame[] {
- const { canvases, declared, resolve, canvasOf } = frameGeometry(svml);
-
- // Which elements draw into each Frame. A Track names it `frame=`, and a speech Track names the Frame
- // it draws each Take into `visual-frame=`, so any attribute whose name ends in `frame` counts.
- const bound = new Map<string, string[]>();
- 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] ?? "";
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1] ?? tag;
- for (const reference of attributes.matchAll(/\b[a-z-]*frame=\{([A-Za-z0-9_-]+)\}/gu)) {
- const frame = reference[1] ?? "";
- const named = bound.get(frame) ?? [];
- if (!named.includes(id)) named.push(id);
- bound.set(frame, named);
- }
- }
-
- const report: OutOfBoundsFrame[] = [];
- for (const [id, frame] of declared) {
- const box = resolve(id);
- const canvasId = canvasOf(id);
- const canvas = canvasId === undefined ? undefined : canvases.get(canvasId);
- if (box === undefined || canvas === undefined || canvasId === undefined) continue;
- const width = canvas.right - canvas.left;
- const height = canvas.bottom - canvas.top;
- // An edge is outside when it is outside the Canvas at all, on either side. A Frame parked wholly
- // off the left has both its x edges past the left edge, and naming only the one on its own side
- // would report half of where it sits.
- const outside = (value: number, low: number, high: number): number => Math.max(low - value, value - high, 0);
- const past: readonly { readonly edge: Edge; readonly outside: number; readonly span: number }[] = [
- { edge: "left", outside: outside(box.left, canvas.left, canvas.right), span: width },
- { edge: "top", outside: outside(box.top, canvas.top, canvas.bottom), span: height },
- { edge: "right", outside: outside(box.right, canvas.left, canvas.right), span: width },
- { edge: "bottom", outside: outside(box.bottom, canvas.top, canvas.bottom), span: height },
- ];
- const edges = past.filter((item) => item.outside > 0).map((item) => ({
- edge: item.edge,
- declared: frame.edges[item.edge],
- outside_percent: round(item.outside / item.span * 100),
- outside_pixels: round(item.outside),
- }));
- if (edges.length === 0) continue;
- const area = Math.max(0, box.right - box.left) * Math.max(0, box.bottom - box.top);
- const inside = Math.max(0, Math.min(box.right, canvas.right) - Math.max(box.left, canvas.left))
- * Math.max(0, Math.min(box.bottom, canvas.bottom) - Math.max(box.top, canvas.top));
- report.push({
- frame: id,
- canvas: canvasId,
- elements: bound.get(id) ?? [],
- edges,
- outside_fraction: round(area === 0 ? 1 : 1 - inside / area),
- });
- }
- return report;
-}
-
-type PlacementClaim = {
- readonly id: string;
- /** The outer Source placement that owns this claim; nested Surface elements share it. */
- readonly owner: string;
- readonly canvas: string;
- readonly box: Box;
- readonly start: number;
- readonly end: number;
- readonly scope: string;
-};
-
-/**
- * Resolve the outer component placement for each namespaced opening tag.
- *
- * A structured Surface may contain its own placed children (for example an Image with several Layers).
- * Those children are part of one component's internal layout and must not be compared as peer
- * components. The owner is therefore the nearest ancestor that declares an id and a placement port;
- * a top-level placement owns itself. This is Source structure only, not a guess based on rectangle size.
- */
-function placementOwners(svml: string): ReadonlyMap<number, string> {
- const owners = new Map<number, string>();
- const stack: { readonly tag: string; readonly owner?: string }[] = [];
- for (const match of svml.matchAll(/<\/?([a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*)\b([^>]*?)>/gsu)) {
- const full = match[0] ?? "";
- const tag = match[1] ?? "";
- if (full.startsWith("</")) {
- for (let index = stack.length - 1; index >= 0; index -= 1) {
- if (stack[index]!.tag === tag) {
- stack.length = index;
- break;
- }
- }
- continue;
- }
- const attributes = match[2] ?? "";
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
- const placement = /\b(?:frame|visual-frame|canvas)=\{([A-Za-z0-9_-]+)\}/u.test(attributes);
- const inherited = [...stack].reverse().find((entry) => entry.owner !== undefined)?.owner;
- const owner = inherited ?? (id !== undefined && placement ? id : undefined);
- if (id !== undefined && placement && owner !== undefined) owners.set(match.index!, owner);
- if (!/\/\s*>$/u.test(full)) stack.push({ tag, ...(owner === undefined ? {} : { owner }) });
- }
- return owners;
-}
-
-function overlapArea(left: Box, right: Box): Box | undefined {
- const intersection = {
- left: Math.max(left.left, right.left),
- top: Math.max(left.top, right.top),
- right: Math.min(left.right, right.right),
- bottom: Math.min(left.bottom, right.bottom),
- };
- return intersection.right > intersection.left && intersection.bottom > intersection.top ? intersection : undefined;
-}
-
-function containsBox(outer: Box, inner: Box): boolean {
- return outer.left <= inner.left && outer.top <= inner.top
- && outer.right >= inner.right && outer.bottom >= inner.bottom;
-}
-
-function placementTiming(attributes: string, parsed: ReturnType<typeof parseScript> | undefined): { start: number; end: number; scope: string } {
- const total = parsed?.tokens.length ?? 1;
- const during = /\bduring=\{story\.(segment|selection)\.([A-Za-z0-9_-]+)\}/u.exec(attributes);
- let start = 0;
- let end = total;
- let scope = "program";
- if (during !== null && parsed !== undefined) {
- const collection = during[1] === "segment" ? parsed.segments : parsed.selections;
- const found = collection.find((item) => item.id === during[2]);
- if (found !== undefined) {
- if ("tokenStart" in found) {
- start = found.tokenStart;
- end = found.tokenEndExclusive;
- } else {
- start = found.open.boundary.tokenIndex;
- end = found.close.boundary.tokenIndex;
- }
- }
- scope = `${during[1]}:${during[2]}`;
- }
- const until = /\buntil=\{story\.moment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- if (until !== undefined && parsed !== undefined) {
- const moment = parsed.moments.find((item) => item.id === until);
- if (moment !== undefined) end = Math.min(end, moment.boundary.tokenIndex);
- scope = `${scope} until ${until}`;
- }
- return { start, end, scope };
-}
-
-function layoutOverlaps(svml: string, geometry: FrameGeometry): readonly LayoutOverlap[] {
- let parsed: ReturnType<typeof parseScript> | undefined;
- try {
- const body = scriptBody(svml);
- parsed = parseScript("<layout-geometry>", body.text, body.offset);
- } catch {
- // Keep spatial findings useful while another check reports the malformed Script.
- }
- const owners = placementOwners(svml);
- const claims: PlacementClaim[] = [];
- for (const match of svml.matchAll(/<([a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*)\b([^>]*?)\/?\s*>/gsu)) {
- const tag = match[1] ?? "";
- const attributes = match[2] ?? "";
- if (/:(?:Canvas|Frame|Track|Film|Video|Clock|SemanticTake|Normalize|Take|Item)$/u.test(tag)) continue;
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
- // `visual-frame` is the speech/media Track placement port. Do not treat `first-frame` or
- // `last-frame` generation inputs as a placement claim.
- const named = /\b(?:frame|visual-frame|canvas)=\{([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- if (id === undefined || named === undefined) continue;
- const canvas = geometry.canvasOf(named);
- const box = geometry.resolve(named);
- if (canvas === undefined || box === undefined) continue;
- const timing = placementTiming(attributes, parsed);
- if (timing.end <= timing.start) continue;
- claims.push({ id, owner: owners.get(match.index!) ?? id, canvas, box, ...timing });
- }
- const report: LayoutOverlap[] = [];
- for (let first = 0; first < claims.length; first += 1) {
- for (let second = first + 1; second < claims.length; second += 1) {
- const left = claims[first]!;
- const right = claims[second]!;
- if (left.owner === right.owner || left.canvas !== right.canvas || left.end <= right.start || right.end <= left.start) continue;
- const intersection = overlapArea(left.box, right.box);
- if (intersection === undefined || containsBox(left.box, right.box) || containsBox(right.box, left.box)) continue;
- report.push({
- first: left.id,
- second: right.id,
- canvas: left.canvas,
- first_bounds: left.box,
- second_bounds: right.box,
- intersection,
- scope: left.scope === right.scope ? left.scope : `${left.scope} ∩ ${right.scope}`,
- note: "Mechanical partial-overlap candidate. Confirm whether the overlap is intentional before editing Source.",
- });
- }
- }
- return report;
-}
-
-/** Build a machine-readable layout report for the agent/observer to interpret. */
-function layoutGeometry(svml: string): LayoutGeometryReport {
- const geometry = frameGeometry(svml);
- const bound = new Map<string, string[]>();
- for (const match of svml.matchAll(/<([a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*)\b([^>]*?)\/?\s*>/gsu)) {
- const tag = match[1] ?? "";
- const attributes = match[2] ?? "";
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1] ?? tag;
- for (const reference of attributes.matchAll(/\b[a-z-]*frame=\{([A-Za-z0-9_-]+)\}/gu)) {
- const frame = reference[1] ?? "";
- const names = bound.get(frame) ?? [];
- if (!names.includes(id)) names.push(id);
- bound.set(frame, names);
- }
- }
-
- const outside = (child: Box, parent: Box) => ({
- left: round(Math.max(parent.left - child.left, 0)),
- top: round(Math.max(parent.top - child.top, 0)),
- right: round(Math.max(child.right - parent.right, 0)),
- bottom: round(Math.max(child.bottom - parent.bottom, 0)),
- });
- const centre = (box: Box) => ({ x: round((box.left + box.right) / 2), y: round((box.top + box.bottom) / 2) });
- // Horizontal placement is often intentionally left- or right-biased (labels, rails, icons). Only
- // report vertical centring mechanically; the visual/author intent remains the authority.
- const verticalDelta = (a: Box, b: Box) => round((a.top + a.bottom - b.top - b.bottom) / 2);
- const entries: LayoutGeometryEntry[] = [];
-
- for (const [id, canvas] of geometry.canvases) {
- entries.push({
- id, kind: "canvas", bounds: canvas,
- size: { width: round(canvas.right - canvas.left), height: round(canvas.bottom - canvas.top) },
- center: centre(canvas),
- });
- }
- for (const [id, declaration] of geometry.declared) {
- const box = geometry.resolve(id);
- const canvasId = geometry.canvasOf(id);
- const parent = geometry.resolve(declaration.within);
- const canvas = canvasId === undefined ? undefined : geometry.canvases.get(canvasId);
- if (box === undefined) {
- entries.push({ id, kind: "frame", within: declaration.within, ...(canvasId === undefined ? {} : { canvas: canvasId }),
- bound_elements: bound.get(id) ?? [], unresolved: "frame edges or its parent could not be resolved to Canvas pixels" });
- continue;
- }
- entries.push({
- id, kind: "frame", within: declaration.within,
- ...(canvasId === undefined ? {} : { canvas: canvasId }), bounds: box,
- size: { width: round(box.right - box.left), height: round(box.bottom - box.top) },
- center: centre(box),
- ...(parent === undefined ? {} : { vertical_center_offset_from_within: verticalDelta(box, parent), outside_within: outside(box, parent) }),
- ...(canvas === undefined ? {} : { vertical_center_offset_from_canvas: verticalDelta(box, canvas), outside_canvas: outside(box, canvas) }),
- bound_elements: bound.get(id) ?? [],
- });
- }
- return {
- coordinate_system: "Canvas pixels, origin top-left, y increases downward",
- note: "Use vertical centre offsets and containment as mechanical facts; horizontal left/right placement is not judged. Visual observation and author intent decide whether any offset or overlap is correct. The report does not measure rendered glyph bounds or decide whether an overhang is intentional.",
- entries,
- overlaps: layoutOverlaps(svml, geometry),
- };
-}
-
/**
* Report what a route can still settle after the Source is written and before a Build runs: which
* drawing elements nobody has looked at, which words of the Script nothing draws a full-frame
@@ -864,9 +521,6 @@ function layoutGeometry(svml: string): LayoutGeometryReport {
* comparison is a comparison. What it says is which elements have had their behaviour over their
* window looked at and which have only had their layout looked at.
*
- * Where each Frame sits is decided from the Source alone and is reported rather than required.
- * `framesPastTheCanvas` above says why an overhang cannot decide `passed`.
- *
* Frame coverage is decided from the Source alone and is required: a word is either drawn over by
* something bound to the whole picture or it is not. What covers is read from an element's own
* opening tag — a full-bleed `frame=`, the `canvas=`, or a speech Track's full-frame `visual-frame=`
@@ -904,11 +558,6 @@ export async function authoringCheck(
const svml = await readFile(svmlPath, "utf8").catch(() => undefined);
assert(svml !== undefined, `cannot read ${svmlPath}`);
- // Read from the Source alone, so every answer below carries it, including the ones that stop early.
- const overhang = framesPastTheCanvas(svml);
- // Deterministic facts for a geometry-first visual review. The observer still decides intent.
- const geometry = layoutGeometry(svml);
-
// Every package this Source imports. The scope is whatever the Source wrote: a project that declares
// a vocabulary gap and fills it publishes under its own scope, and those elements draw exactly as an
// installed one does.
@@ -932,8 +581,6 @@ export async function authoringCheck(
elements: [],
playback: [],
uncovered: [],
- out_of_bounds: overhang,
- layout_geometry: geometry,
};
}
@@ -1196,8 +843,6 @@ export async function authoringCheck(
elements: [],
playback: [],
uncovered: [],
- out_of_bounds: overhang,
- layout_geometry: geometry,
...(unresolved.length === 0 ? {} : {
unresolved_packages: {
names: unresolved,
@@ -1238,7 +883,7 @@ export async function authoringCheck(
//
// Only on the route that has a reference. A description-authored project has none, and resolving
// one here is what used to stop this command before it reached the checks that have nothing to do
- // with a reference — the `playback` refusal, frame coverage and the Canvas overhang are read from
+ // with a reference — the `playback` refusal and frame coverage are read from
// the Source alone, and were unreachable to that route for no reason but this block.
const preparedRoot = referenceRoot();
let reference: string | undefined;
@@ -1432,10 +1077,6 @@ export async function authoringCheck(
summary.push(uncoveredWords === 0
? `every word of the Script is drawn over by something that fills the frame (${coverage.words}).`
: `${uncoveredWords} of ${coverage.words} words are drawn over by nothing that fills the frame.`);
- if (overhang.length > 0) {
- summary.push(`${overhang.length} Frame${overhang.length === 1 ? "" : "s"} `
- + `${overhang.length === 1 ? "reaches" : "reach"} past the Canvas; read each one against the reference.`);
- }
const compared = elements.filter((element) => element.comparisons > 0).length;
if (compared > 0 && mode === "reconstruction") {
summary.push(untimed.length === 0
@@ -1612,25 +1253,6 @@ export async function authoringCheck(
+ "something beneath the stretch instead changes which wrong picture appears and leaves the stretch "
+ "unclaimed.",
}),
- out_of_bounds: overhang,
- layout_geometry: geometry,
- ...(overhang.length === 0 ? {} : {
- out_of_bounds_note: "Each Frame here places part of what is drawn into it off the picture, by the amount "
- + "beside each edge. `outside_fraction` is how much of the Frame's own area lands off the Canvas. This "
- + "is read from the Source's own `space:Canvas` and `space:Frame` arithmetic — no rendered frame is "
- + "measured and no observer is asked.\n\n"
- + "Answer each one: is this overhang intended? Two shapes of it are, and both are visible in the "
- + "Source. An element that travels in from off-screen is outside for part of its window, so its "
- + "Recipe carries the movement — an `enter`, a fly-from origin, an animated offset — and the Frame is "
- + "where it starts rather than where it stays. A full-bleed picture is declared past the edge on "
- + "purpose so a `fit` crops it instead of letterboxing it, so its Recipe carries that `fit`. A Frame "
- + "with neither, holding something the reference shows whole, is placed wrong: the part past the edge "
- + "is the part nobody will see.\n\n"
- + "This decides nothing on its own, because the Source cannot tell the two apart. It is here because "
- + "comparison cannot see it at all: an element authored mostly off the picture is drawn at the Canvas "
- + "the Source declares, and the stand-in it is compared against is drawn at that same Canvas, so both "
- + "put it in the same place off the edge and agree with each other.",
- }),
playback: running,
...(running.length === 0 ? {} : {
playback_next: "Only moving/generated media with a duration-bearing timeline needs playback. Still images have no timeline and must not be given playback. For a generated take, the take is ordered in whole seconds and its window is measured from speech the "
@@ -1648,8 +1270,8 @@ export async function authoringCheck(
* Source-only delivery gate for variant expansion.
*
* It reuses the authoring check's graph-independent analysis but deliberately does not require a
- * render, comparison, review log or VLM judgement. The returned geometry remains evidence for the
- * caller; only deterministic failures (unresolved vocabulary, uncovered Script words and timed
+ * render, comparison, review log or VLM judgement. Only deterministic failures (unresolved vocabulary,
+ * uncovered Script words and timed
* pictures that empty their windows) decide `passed` here.
*/
export async function mechanicalAuthoringCheck(
@@ -1670,8 +1292,6 @@ export async function mechanicalAuthoringCheck(
summary,
playback,
uncovered,
- out_of_bounds: result.out_of_bounds ?? [],
- layout_geometry: result.layout_geometry,
...(unresolved === undefined ? {} : { unresolved_packages: unresolved }),
note: "Mechanical variant gate only; no render, VLM comparison or visual review was performed.",
};
diff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.ts
index 4b0a5bdd..e709a914 100644
--- a/packages/reference-video-tools/src/cli.ts
+++ b/packages/reference-video-tools/src/cli.ts
@@ -56,6 +56,8 @@ function usage(): string {
" hypit-reference-video-tools render_element <build.svrun> --batch <renders.json> [--reference-id <id>]",
" hypit-reference-video-tools render_previews <package-dir> [...]",
" hypit-reference-video-tools preview_check <build.svrun> [<hypit.runtime.json>]",
+ " hypit-reference-video-tools layout_check --run <build.svrun>",
+ " hypit-reference-video-tools layout_accept --run <build.svrun> --finding <id> --reason <text>",
" hypit-reference-video-tools reconstruction_check <build.svrun> [--reference-id <id>]",
" hypit-reference-video-tools authoring_check <build.svrun>",
"",
@@ -73,18 +75,9 @@ function usage(): string {
"not recorded — which says whether anything that changes with elapsed time inside its window has",
"been looked at, or only its layout.",
"",
- "It also reports every Frame with an edge outside 0%-100% of its Canvas, which places part of what",
- "is drawn into it off the picture. That is reported rather than required: an overhang is how an",
- "element slides in from off-screen and how a full-bleed picture is cropped by a fit, and a mistake",
- "looks the same. A comparison cannot answer it either way, because the render and reference are",
- "drawn at the same Canvas and put the element in the same place off the edge.",
- "Both checks also return layout_geometry: deterministic Canvas/Frame bounds, centres, parent and",
- "Canvas vertical centre offsets, containment overflow and bound element ids. Use it as a mechanical",
- "geometry report for vertical centring, frame capacity and Canvas safety; horizontal left/right placement",
- "is not judged. layout_geometry.overlaps adds",
- "advisory independent same-Canvas, simultaneous partial-intersection candidates; nested placements",
- "owned by one component are excluded (full containment is omitted).",
- "It does not measure rendered glyph bounds or decide whether an overhang or overlap is intentional.",
+ "layout_check performs a realized Composition/DOM stable-state pass without writing media or calling",
+ "paid Providers. Every result is candidate evidence only: the Agent decides whether it is a genuine",
+ "problem, repairs it, or records an intentional exception with layout_accept and a reason.",
"",
"render_element draws one element of a Source the way that Source configures it, without a Build.",
"The Canvas, frame rate, Recipe values and bindings come from the compiled Graph; missing media is",
@@ -656,6 +649,12 @@ async function main(): Promise<void> {
...(operands[1] === undefined ? {} : { runtime: operands[1] }),
};
result = await tools.preview_check(input as { run: string; runtime?: string });
+ } else if (command === "layout_check") {
+ result = await tools.layout_check((supplied ?? { run: required(flags, "run") }) as { run: string });
+ } else if (command === "layout_accept") {
+ result = await tools.layout_accept((supplied ?? {
+ run: required(flags, "run"), finding: required(flags, "finding"), reason: required(flags, "reason"),
+ }) as { run: string; finding: string; reason: 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()}`);
diff --git a/packages/reference-video-tools/src/layout.ts b/packages/reference-video-tools/src/layout.ts
new file mode 100644
index 00000000..ad499c63
--- /dev/null
+++ b/packages/reference-video-tools/src/layout.ts
@@ -0,0 +1,503 @@
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { readFile, readdir, stat } from "node:fs/promises";
+import { createServer } from "node:http";
+import { createRequire } from "node:module";
+import { dirname, extname, join, normalize, resolve, sep } from "node:path";
+import { spawnSync } from "node:child_process";
+
+import puppeteer from "puppeteer-core";
+
+import { authorSource, invokedFrom, realizeAuthoringPreview, repositoryRoot, stageAuthoringPreview } from "./authoring.js";
+import { atomicJson } from "./state-files.js";
+
+export type LayoutCheckInput = { readonly run: string; readonly package_root?: string };
+export type LayoutAcceptInput = { readonly run: string; readonly finding: string; readonly reason: string };
+const LAYOUT_CHECKER_VERSION = 3 as const;
+
+type Bounds = { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number; readonly width: number; readonly height: number };
+type RawFinding = {
+ readonly kind: "vertical-offset" | "parent-overflow" | "canvas-overflow" | "peer-overlap";
+ readonly layer: "realized_layout";
+ readonly track?: string;
+ readonly present?: string;
+ readonly element: string;
+ readonly related?: string;
+ readonly frame?: number;
+ readonly pixels: number;
+ readonly ratio: number;
+ readonly bounds?: Bounds;
+ readonly related_bounds?: Bounds;
+ readonly message: string;
+};
+
+type LayoutDecision = {
+ readonly finding: string;
+ readonly layout_digest: string;
+ readonly reason: string;
+ readonly accepted_at: string;
+};
+
+type LayoutDecisions = { readonly version: 1; readonly decisions: readonly LayoutDecision[] };
+
+function projectRoot(runPath: string): string { return dirname(runPath); }
+export function layoutCheckPath(runPath: string): string { return join(projectRoot(runPath), ".hypit", "layout-check.json"); }
+export function layoutDecisionsPath(runPath: string): string { return join(projectRoot(runPath), ".hypit", "layout-decisions.json"); }
+
+function hash(value: unknown): string {
+ return `sha256:${createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex")}`;
+}
+
+async function inputDigests(runPath: string, sourcePath: string): Promise<Readonly<Record<string, string>>> {
+ const files = new Set<string>([runPath]);
+ const queue = [sourcePath];
+ while (queue.length > 0) {
+ const path = queue.shift()!;
+ if (files.has(path)) continue;
+ files.add(path);
+ const source = await readFile(path, "utf8").catch(() => undefined);
+ if (source === undefined) continue;
+ for (const match of source.matchAll(/<import\s+[^>]*\bsource="([^"]+)"[^>]*\/?\s*>/gu)) {
+ queue.push(resolve(dirname(path), match[1]!));
+ }
+ }
+ const root = dirname(runPath);
+ for (const name of ["package.json", "pnpm-lock.yaml", "hypit.runtime.json"]) {
+ const path = join(root, name);
+ if (await stat(path).then((value) => value.isFile(), () => false)) files.add(path);
+ }
+ const localPackages = join(root, "packages");
+ const visit = async (directory: string): Promise<void> => {
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (entry.name === "node_modules" || entry.name === ".hypit") continue;
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) await visit(path);
+ else if (entry.isFile()) files.add(path);
+ }
+ };
+ await visit(localPackages);
+ const result: Record<string, string> = {};
+ for (const path of [...files].sort()) {
+ const bytes = await readFile(path).catch(() => undefined);
+ if (bytes !== undefined) result[path] = hash(bytes);
+ }
+ return result;
+}
+
+function round(value: number): number { return Math.round(value * 1000) / 1000; }
+
+async function readDecisions(path: string): Promise<LayoutDecisions> {
+ const source = await readFile(path, "utf8").catch((error: unknown) => {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ throw error;
+ });
+ if (source === undefined) return { version: 1, decisions: [] };
+ let value: unknown;
+ try { value = JSON.parse(source); }
+ catch (error) { throw new Error(`layout decisions at ${path} are invalid JSON; original file was preserved: ${error instanceof Error ? error.message : String(error)}`); }
+ const decisions = value as Partial<LayoutDecisions>;
+ if (decisions.version !== 1 || !Array.isArray(decisions.decisions)) throw new Error(`layout decisions at ${path} have an unsupported shape`);
+ return decisions as LayoutDecisions;
+}
+
+function contentType(path: string): string {
+ const extension = extname(path).toLowerCase();
+ if (extension === ".html") return "text/html; charset=utf-8";
+ if (extension === ".css") return "text/css; charset=utf-8";
+ if (extension === ".js") return "text/javascript; charset=utf-8";
+ return "application/octet-stream";
+}
+
+async function serve(directory: string, mediaTypes: ReadonlyMap<string, string>): Promise<{ readonly url: string; close(): Promise<void> }> {
+ const root = resolve(directory);
+ const server = createServer(async (request, response) => {
+ const pathname = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname);
+ const relative = pathname === "/" ? "index.html" : pathname.slice(1);
+ const path = resolve(root, normalize(relative));
+ if (path !== root && !path.startsWith(`${root}${sep}`)) { response.writeHead(403).end(); return; }
+ const info = await stat(path).catch(() => undefined);
+ if (info === undefined || !info.isFile()) { response.writeHead(404).end(); return; }
+ response.writeHead(200, { "content-type": mediaTypes.get(relative) ?? contentType(path), "cache-control": "no-store" });
+ createReadStream(path).pipe(response);
+ });
+ await new Promise<void>((accept, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => accept());
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") throw new Error("layout browser server did not bind a local port");
+ return {
+ url: `http://127.0.0.1:${address.port}/`,
+ close: async () => await new Promise<void>((accept, reject) => server.close((error) => error === undefined ? accept() : reject(error))),
+ };
+}
+
+function browserPath(): string {
+ const cli = createRequire(join(repositoryRoot(), "packages/provider-hyperframes-local/package.json"))
+ .resolve("hyperframes/bin/hyperframes.mjs");
+ const result = spawnSync(process.execPath, [cli, "browser", "path"], { encoding: "utf8", windowsHide: true, timeout: 60_000 });
+ if (result.status !== 0) throw new Error(`cannot resolve the fixed HyperFrames browser: ${(result.stderr ?? "").trim()}`);
+ const path = (result.stdout ?? "").trim().split("\n").at(-1)?.trim();
+ if (path === undefined || path.length === 0) throw new Error("HyperFrames returned no browser path");
+ return path;
+}
+
+type StableSample = {
+ readonly frame: number;
+ readonly subjects: readonly { readonly track: string; readonly present: string }[];
+ readonly overlap_subjects: readonly { readonly track: string; readonly present: string }[];
+};
+
+function framePlan(composition: Awaited<ReturnType<typeof realizeAuthoringPreview>>["built"]["composition"]): readonly StableSample[] {
+ const intervals: { readonly track: string; readonly present: string; readonly startFrame: number; readonly endFrameExclusive: number; readonly frame: number }[] = [];
+ for (const track of composition.tracks) {
+ if (track.kind !== "visual") continue;
+ for (const present of track.presents) {
+ const duration = present.span.endFrameExclusive - present.span.startFrame;
+ const changing = Array.from({ length: duration }, () => false);
+ const mark = (start: number, endExclusive: number): void => {
+ for (let frame = Math.max(0, Math.floor(start)); frame < Math.min(duration, Math.ceil(endExclusive)); frame += 1) changing[frame] = true;
+ };
+ const signature = (style: readonly { readonly name: string; readonly value: unknown }[]): string => JSON.stringify(
+ [...style].map((item) => [item.name, item.value]).sort(([left], [right]) => String(left).localeCompare(String(right))),
+ );
+ for (const element of present.elements) {
+ const keyframes = element.animation?.keyframes ?? [];
+ for (let index = 0; index + 1 < keyframes.length; index += 1) {
+ const left = keyframes[index]!;
+ const right = keyframes[index + 1]!;
+ if (signature(left.style) !== signature(right.style)) mark(left.atFrame, right.atFrame);
+ }
+ if (element.kind === "text-flow" || element.kind === "path-text") {
+ for (const sequence of element.sequences) {
+ const units = Math.max(1, sequence.range.endExclusive - sequence.range.start);
+ const lastStart = sequence.startFrame + (units - 1) * sequence.staggerFrames;
+ const start = Math.min(sequence.startFrame, lastStart);
+ const end = Math.max(sequence.startFrame, lastStart) + sequence.unitDurationFrames * sequence.cycles;
+ mark(start, end);
+ }
+ }
+ if (element.kind === "path-text" && element.marginAnimation !== undefined) {
+ const keyframes = element.marginAnimation.keyframes;
+ for (let index = 0; index + 1 < keyframes.length; index += 1) {
+ const left = keyframes[index]!;
+ const right = keyframes[index + 1]!;
+ if (left.startMarginPx !== right.startMarginPx) mark(left.atFrame, right.atFrame);
+ }
+ }
+ }
+ let best: { readonly start: number; readonly endExclusive: number } | undefined;
+ let start = 0;
+ while (start < duration) {
+ while (start < duration && changing[start]) start += 1;
+ if (start >= duration) break;
+ let end = start + 1;
+ while (end < duration && !changing[end]) end += 1;
+ if (end - start >= 2 && (best === undefined || end - start > best.endExclusive - best.start)) {
+ best = { start, endExclusive: end };
+ }
+ start = end;
+ }
+ if (best !== undefined) intervals.push({
+ track: track.id,
+ present: present.id,
+ startFrame: present.span.startFrame + best.start,
+ endFrameExclusive: present.span.startFrame + best.endExclusive,
+ frame: present.span.startFrame + Math.floor((best.start + best.endExclusive - 1) / 2),
+ });
+ }
+ }
+ const byFrame = new Map<number, { readonly frame: number; readonly subjects: { track: string; present: string }[] }>();
+ for (const interval of intervals) {
+ const subject = { track: interval.track, present: interval.present };
+ const existing = byFrame.get(interval.frame);
+ if (existing === undefined) byFrame.set(interval.frame, { frame: interval.frame, subjects: [subject] });
+ else existing.subjects.push(subject);
+ }
+ return [...byFrame.values()]
+ .map((sample) => ({
+ frame: sample.frame,
+ subjects: sample.subjects.sort((left, right) => `${left.track}/${left.present}`.localeCompare(`${right.track}/${right.present}`)),
+ overlap_subjects: intervals
+ .filter((interval) => sample.frame >= interval.startFrame && sample.frame < interval.endFrameExclusive)
+ .map((interval) => ({ track: interval.track, present: interval.present }))
+ .sort((left, right) => `${left.track}/${left.present}`.localeCompare(`${right.track}/${right.present}`)),
+ }))
+ .sort((left, right) => left.frame - right.frame);
+}
+
+function packageByTrack(realized: Awaited<ReturnType<typeof realizeAuthoringPreview>>): ReadonlyMap<string, string> {
+ const result = new Map<string, string>();
+ for (const item of realized.built.tracks) {
+ const id = (item.value as { readonly id?: unknown } | null)?.id;
+ if (typeof id !== "string") continue;
+ const packageName = item.trace.module?.name ?? item.typeRef.module.name;
+ if (packageName !== undefined) result.set(id, packageName);
+ }
+ return result;
+}
+
+async function realizedFindings(
+ realized: Awaited<ReturnType<typeof realizeAuthoringPreview>>,
+ stage: string,
+ mediaTypes: ReadonlyMap<string, string>,
+ samples: readonly StableSample[],
+): Promise<RawFinding[]> {
+ const local = await serve(stage, mediaTypes);
+ const browser = await puppeteer.launch({ executablePath: browserPath(), headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] });
+ const page = await browser.newPage();
+ const findings: RawFinding[] = [];
+ try {
+ await page.setViewport({ width: realized.built.canvas.width, height: realized.built.canvas.height, deviceScaleFactor: 1 });
+ await page.goto(local.url, { waitUntil: "load", timeout: 60_000 });
+ await page.evaluate("window.__name = window.__name || ((target) => target)");
+ await page.evaluate(() => {
+ for (const root of Array.from(document.querySelectorAll("[data-composition-id][data-width][data-height]"))) {
+ const width = Number(root.getAttribute("data-width"));
+ const height = Number(root.getAttribute("data-height"));
+ if (root instanceof HTMLElement && Number.isFinite(width) && Number.isFinite(height)) {
+ root.style.width = `${width}px`;
+ root.style.height = `${height}px`;
+ }
+ }
+ });
+ await page.evaluate(async () => { await document.fonts.ready; });
+ const fps = realized.built.frameRate.numerator / realized.built.frameRate.denominator;
+ for (const sample of samples) {
+ const frame = sample.frame;
+ const measured = await page.evaluate(async ({ frame: at, fps: rate, subjects: subjectKeys, overlapSubjects: overlapKeys }: { frame: number; fps: number; subjects: readonly string[]; overlapSubjects: readonly string[] }) => {
+ type Box = { left: number; top: number; right: number; bottom: number; width: number; height: number };
+ type Finding = RawFinding;
+ const runtime = window as unknown as { __hf?: { seek?: (seconds: number) => unknown }; __player?: { renderSeek?: (seconds: number) => unknown } };
+ const seconds = at / rate;
+ const seek = runtime.__player?.renderSeek ?? runtime.__hf?.seek;
+ if (typeof seek === "function") await seek.call(runtime.__player ?? runtime.__hf, seconds);
+ else window.dispatchEvent(new CustomEvent("hf-seek", { detail: { time: seconds } }));
+ for (const clip of Array.from(document.querySelectorAll(".hypit-visual-present[data-start][data-duration]"))) {
+ const start = Number(clip.getAttribute("data-start"));
+ const duration = Number(clip.getAttribute("data-duration"));
+ (clip as HTMLElement).style.display = seconds >= start && seconds < start + duration ? "" : "none";
+ }
+ await new Promise<void>((accept) => requestAnimationFrame(() => requestAnimationFrame(() => accept())));
+ const box = (rect: DOMRect): Box => ({ left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, width: rect.width, height: rect.height });
+ const visible = (element: Element): element is HTMLElement | SVGElement => {
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity || "1") > 0.001 && rect.width > 0 && rect.height > 0;
+ };
+ const over = (child: Box, parent: Box) => Math.max(parent.left - child.left, parent.top - child.top, child.right - parent.right, child.bottom - parent.bottom, 0);
+ const contains = (outer: Box, inner: Box) => outer.left <= inner.left && outer.top <= inner.top && outer.right >= inner.right && outer.bottom >= inner.bottom;
+ const intersection = (a: Box, b: Box): Box | undefined => {
+ const left = Math.max(a.left, b.left), top = Math.max(a.top, b.top), right = Math.min(a.right, b.right), bottom = Math.min(a.bottom, b.bottom);
+ return right > left && bottom > top ? { left, top, right, bottom, width: right - left, height: bottom - top } : undefined;
+ };
+ const root = document.querySelector("[data-composition-id]") ?? document.body;
+ const canvas = box(root.getBoundingClientRect());
+ const result: Finding[] = [];
+ const subjects = new Set(subjectKeys);
+ const overlapSubjects = new Set(overlapKeys);
+ const activePresents = Array.from(document.querySelectorAll("[data-hypit-track-id][data-hypit-present-id]")).filter(visible);
+ const keyOf = (present: Element): string => `${present.getAttribute("data-hypit-track-id") ?? "unknown-track"}/${present.getAttribute("data-hypit-present-id") ?? "unknown-present"}`;
+ const presents = activePresents.filter((present) => {
+ if (!visible(present)) return false;
+ return subjects.has(keyOf(present));
+ });
+ for (const present of presents) {
+ const track = present.getAttribute("data-hypit-track-id") ?? "unknown-track";
+ const presentId = present.getAttribute("data-hypit-present-id") ?? "unknown-present";
+ const elements = Array.from(present.querySelectorAll("[data-hypit-element-id]")).filter(visible);
+ for (const element of elements) {
+ const id = element.getAttribute("data-hypit-element-id") ?? "unknown-element";
+ const elementBox = box(element.getBoundingClientRect());
+ const parentElement = element.parentElement?.closest("[data-hypit-element-id]") ?? null;
+ const parent: Element = parentElement !== null && parentElement !== element ? parentElement : present;
+ const parentBox = box(parent.getBoundingClientRect());
+ const overflow = over(elementBox, parentBox);
+ if (overflow > 1) result.push({
+ kind: "parent-overflow", layer: "realized_layout", track, present: presentId, element: id,
+ related: parent.getAttribute("data-hypit-element-id") ?? "present", frame: at,
+ pixels: overflow, ratio: overflow / Math.max(1, parentBox.height), bounds: elementBox, related_bounds: parentBox,
+ message: "Rendered content extends beyond its direct parent. This is a measured candidate; clipping or motion may be intentional.",
+ });
+ const canvasOverflow = over(elementBox, canvas);
+ if (canvasOverflow > 1) result.push({
+ kind: "canvas-overflow", layer: "realized_layout", track, present: presentId, element: id,
+ related: "canvas", frame: at, pixels: canvasOverflow, ratio: canvasOverflow / Math.max(1, canvas.height),
+ bounds: elementBox, related_bounds: canvas,
+ message: "Rendered content extends beyond the Canvas. This is a measured candidate; cropping or off-screen motion may be intentional.",
+ });
+ let contentBox: Box | undefined;
+ let container: Element | undefined;
+ let verticalRelated: string | undefined;
+ if (element.matches("[data-hypit-text-flow], [data-hypit-text-clock]") || Array.from(element.childNodes).some((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim())) {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const rects = Array.from(range.getClientRects()).filter((rect) => rect.width > 0 && rect.height > 0);
+ if (rects.length > 0) {
+ const left = Math.min(...rects.map((rect) => rect.left)), top = Math.min(...rects.map((rect) => rect.top));
+ const right = Math.max(...rects.map((rect) => rect.right)), bottom = Math.max(...rects.map((rect) => rect.bottom));
+ contentBox = { left, top, right, bottom, width: right - left, height: bottom - top };
+ container = element;
+ verticalRelated = `${id}:content-box`;
+ }
+ } else if (parent !== present) {
+ contentBox = elementBox;
+ container = parent;
+ verticalRelated = parent.getAttribute("data-hypit-element-id") ?? "parent";
+ }
+ if (contentBox !== undefined && container !== undefined) {
+ const containerBox = box(container.getBoundingClientRect());
+ const style = getComputedStyle(container);
+ const contentParent = {
+ left: containerBox.left + Number.parseFloat(style.paddingLeft || "0"),
+ top: containerBox.top + Number.parseFloat(style.paddingTop || "0"),
+ right: containerBox.right - Number.parseFloat(style.paddingRight || "0"),
+ bottom: containerBox.bottom - Number.parseFloat(style.paddingBottom || "0"),
+ width: 0, height: 0,
+ };
+ contentParent.width = contentParent.right - contentParent.left;
+ contentParent.height = contentParent.bottom - contentParent.top;
+ const offset = (contentBox.top + contentBox.bottom - contentParent.top - contentParent.bottom) / 2;
+ if (Math.abs(offset) > 1) result.push({
+ kind: "vertical-offset", layer: "realized_layout", track, present: presentId, element: id,
+ ...(verticalRelated === undefined ? {} : { related: verticalRelated }), frame: at,
+ pixels: Math.abs(offset), ratio: Math.abs(offset) / Math.max(1, contentParent.height),
+ bounds: contentBox, related_bounds: contentParent,
+ message: "Rendered inner content is vertically offset within its measured box. This is a candidate, not proof of a layout error.",
+ });
+ }
+ }
+ }
+ const roots = activePresents.filter((present) => overlapSubjects.has(keyOf(present))).flatMap((present) => {
+ const rootElement = Array.from(present.querySelectorAll("[data-hypit-element-id]")).find((element) => visible(element) && element.parentElement?.closest("[data-hypit-element-id]") === null);
+ return rootElement === undefined ? [] : [{
+ track: present.getAttribute("data-hypit-track-id") ?? "unknown-track",
+ present: present.getAttribute("data-hypit-present-id") ?? "unknown-present",
+ element: rootElement.getAttribute("data-hypit-element-id") ?? "unknown-element",
+ bounds: box(rootElement.getBoundingClientRect()),
+ }];
+ });
+ for (let first = 0; first < roots.length; first += 1) for (let second = first + 1; second < roots.length; second += 1) {
+ const left = roots[first]!, right = roots[second]!;
+ if (left.track === right.track || contains(left.bounds, right.bounds) || contains(right.bounds, left.bounds)) continue;
+ const shared = intersection(left.bounds, right.bounds);
+ if (shared === undefined || shared.width <= 1 || shared.height <= 1) continue;
+ const area = shared.width * shared.height;
+ result.push({
+ kind: "peer-overlap", layer: "realized_layout", track: left.track, present: left.present,
+ element: left.element, related: `${right.track}/${right.present}/${right.element}`, frame: at,
+ pixels: Math.max(shared.width, shared.height),
+ ratio: area / Math.max(1, Math.min(left.bounds.width * left.bounds.height, right.bounds.width * right.bounds.height)),
+ bounds: left.bounds, related_bounds: right.bounds,
+ message: "Rendered top-level content from independent tracks partially overlaps. This is a candidate; intentional layering remains valid.",
+ });
+ }
+ return result;
+ }, {
+ frame,
+ fps,
+ subjects: sample.subjects.map((subject) => `${subject.track}/${subject.present}`),
+ overlapSubjects: sample.overlap_subjects.map((subject) => `${subject.track}/${subject.present}`),
+ });
+ findings.push(...measured);
+ }
+ } finally {
+ await page.close().catch(() => undefined);
+ await browser.close().catch(() => undefined);
+ await local.close().catch(() => undefined);
+ }
+ return findings;
+}
+
+function aggregate(findings: readonly RawFinding[]): RawFinding[] {
+ const grouped = new Map<string, RawFinding>();
+ for (const finding of findings) {
+ const key = JSON.stringify([finding.layer, finding.kind, finding.track ?? "", finding.present ?? "", finding.element, finding.related ?? ""]);
+ const current = grouped.get(key);
+ if (current === undefined || finding.pixels > current.pixels) grouped.set(key, finding);
+ }
+ return [...grouped.values()].map((finding) => ({ ...finding, pixels: round(finding.pixels), ratio: round(finding.ratio) }));
+}
+
+function withIdentity(findings: readonly RawFinding[], digest: string, packages: ReadonlyMap<string, string>, decisions: LayoutDecisions): readonly Record<string, unknown>[] {
+ const accepted = new Map(decisions.decisions.filter((item) => item.layout_digest === digest).map((item) => [item.finding, item] as const));
+ return findings.map((finding) => {
+ const packageName = finding.track === undefined ? undefined : packages.get(finding.track);
+ const id = hash([finding.kind, finding.layer, packageName ?? "", finding.track ?? "", finding.present ?? "", finding.element, finding.related ?? "", digest]);
+ const decision = accepted.get(id);
+ return {
+ id, ...finding, ...(packageName === undefined ? {} : { package: packageName }),
+ disposition: decision === undefined ? "agent-review-required" : "accepted-intentional",
+ ...(decision === undefined ? {} : { acceptance_reason: decision.reason, accepted_at: decision.accepted_at }),
+ };
+ });
+}
+
+export async function layoutCheck(input: LayoutCheckInput): Promise<Record<string, unknown>> {
+ const runPath = resolve(invokedFrom(), input.run);
+ const source = await authorSource(runPath);
+ const inputs = await inputDigests(runPath, source.path);
+ const realized = await realizeAuthoringPreview(input);
+ const { stage, document, mediaTypes } = await stageAuthoringPreview(realized);
+ const digest = hash({
+ checker: LAYOUT_CHECKER_VERSION,
+ inputs,
+ graph: realized.built.source.compiled.graph,
+ program: realized.built.source.compiled.program.records,
+ composition: realized.built.composition,
+ served: [...realized.built.served.keys()].sort(),
+ });
+ const decisionsPath = layoutDecisionsPath(runPath);
+ const decisions = await readDecisions(decisionsPath);
+ await atomicJson(decisionsPath, decisions);
+ const currentPath = layoutCheckPath(runPath);
+ const cached = await readFile(currentPath, "utf8").then((text) => JSON.parse(text) as Record<string, unknown>, () => undefined);
+ let raw: RawFinding[];
+ let samples: readonly StableSample[];
+ if (cached?.layout_digest === digest && Array.isArray(cached.raw_findings) && Array.isArray(cached.samples)) {
+ raw = cached.raw_findings as RawFinding[];
+ samples = cached.samples as StableSample[];
+ } else {
+ samples = framePlan(realized.built.composition).filter((sample) => sample.frame < document.frameCount);
+ raw = aggregate(await realizedFindings(realized, stage, mediaTypes, samples));
+ }
+ const findings = withIdentity(raw, digest, packageByTrack(realized), decisions);
+ const pending = findings.filter((finding) => finding.disposition === "agent-review-required");
+ const result = {
+ version: LAYOUT_CHECKER_VERSION,
+ run: runPath,
+ source: source.path,
+ input_digests: inputs,
+ layout_digest: digest,
+ executed: true,
+ settled: pending.length === 0,
+ semantics: "candidate-evidence-only",
+ note: "Mechanical measurements assist the Agent; they are not findings of fault and never override design intent. Repair a genuine issue or use layout_accept with a reason for intentional geometry.",
+ samples,
+ raw_findings: raw,
+ findings,
+ pending_count: pending.length,
+ accepted_count: findings.length - pending.length,
+ checked_at: new Date().toISOString(),
+ };
+ await atomicJson(currentPath, result);
+ return { ...result, evidence: currentPath, decisions: decisionsPath };
+}
+
+export async function layoutAccept(input: LayoutAcceptInput): Promise<Record<string, unknown>> {
+ const runPath = resolve(invokedFrom(), input.run);
+ const reason = input.reason.trim();
+ if (reason.length === 0) throw new Error("layout_accept requires a non-empty reason explaining why the measured geometry is intentional");
+ const reportPath = layoutCheckPath(runPath);
+ const report = JSON.parse(await readFile(reportPath, "utf8")) as { layout_digest?: unknown; findings?: unknown };
+ if (typeof report.layout_digest !== "string" || !Array.isArray(report.findings)) throw new Error(`run layout_check first; ${reportPath} has no usable report`);
+ const finding = report.findings.find((item) => item !== null && typeof item === "object" && (item as { id?: unknown }).id === input.finding);
+ if (finding === undefined) throw new Error(`layout report contains no finding ${input.finding}`);
+ const path = layoutDecisionsPath(runPath);
+ const existing = await readDecisions(path);
+ const decision: LayoutDecision = { finding: input.finding, layout_digest: report.layout_digest, reason, accepted_at: new Date().toISOString() };
+ const decisions = [...existing.decisions.filter((item) => !(item.finding === decision.finding && item.layout_digest === decision.layout_digest)), decision];
+ await atomicJson(path, { version: 1, decisions });
+ return { accepted: true, finding: input.finding, layout_digest: report.layout_digest, reason, decisions: path, next_action: `rerun layout_check --run ${runPath}` };
+}
diff --git a/packages/reference-video-tools/src/revision-state.ts b/packages/reference-video-tools/src/revision-state.ts
index dee87678..c99a180d 100644
--- a/packages/reference-video-tools/src/revision-state.ts
+++ b/packages/reference-video-tools/src/revision-state.ts
@@ -234,18 +234,25 @@ export async function checkpointRevisionState(input: RevisionCheckpointInput): P
if (existing === undefined) throw new Error(`no revision state at ${revisionStatePath(projectRoot)}; run revision_state start first`);
if (input.request !== undefined && input.request !== existing.request) throw new Error("a revision request is immutable after revision_state start; start a new revision instead");
const step = stepNumber(input.step);
+ const artifacts = input.artifacts === undefined ? existing.artifacts : {
+ ...existing.artifacts,
+ ...Object.fromEntries(Object.entries(input.artifacts).map(([key, value]) => [key, resolve(projectRoot, value)])),
+ };
+ if (step === stepNumber("gates-checked") && input.status === "complete") {
+ const layout = artifacts.layout_check;
+ const value = layout === undefined ? undefined : await readFile(layout, "utf8").then((source) => JSON.parse(source) as { executed?: unknown; settled?: unknown }, () => undefined);
+ if (value?.executed !== true || value.settled !== true || !(await layoutEvidenceCurrent(layout))) {
+ throw new Error("gates-checked requires a successful layout_check whose candidates are repaired or explicitly accepted");
+ }
+ }
const completed = new Set(existing.completed_steps);
if (input.status === "complete") completed.add(step);
const completedSteps = [...completed].sort((a, b) => a - b);
const next = input.status === "complete" ? nextUncompleted(completedSteps) : step;
const now = new Date().toISOString();
- const artifacts = input.artifacts === undefined ? existing.artifacts : {
- ...existing.artifacts,
- ...Object.fromEntries(Object.entries(input.artifacts).map(([key, value]) => [key, resolve(projectRoot, value)])),
- };
const artifactDigests: Record<string, string> = { ...existing.artifact_digests };
for (const [key, value] of Object.entries(artifacts)) {
- if (key !== "revision_request" && !value.includes(`${sep}.hypit${sep}evidence${sep}`)) continue;
+ if (key !== "revision_request" && key !== "layout_check" && key !== "layout_decisions" && !value.includes(`${sep}.hypit${sep}evidence${sep}`)) continue;
const digest = await digestPath(value);
if (digest !== undefined) artifactDigests[key] = digest;
}
@@ -274,6 +281,18 @@ async function fileExists(path: string | undefined): Promise<boolean> {
return path !== undefined && await stat(path).then((value) => value.isFile(), () => false);
}
+async function layoutEvidenceCurrent(path: string | undefined): Promise<boolean> {
+ if (path === undefined) return false;
+ try {
+ const report = JSON.parse(await readFile(path, "utf8")) as { executed?: unknown; settled?: unknown; input_digests?: Record<string, unknown> };
+ if (report.executed !== true || report.settled !== true || report.input_digests === undefined) return false;
+ for (const [file, expected] of Object.entries(report.input_digests)) {
+ if (typeof expected !== "string" || await digestPath(file) !== expected) return false;
+ }
+ return true;
+ } catch { return false; }
+}
+
/** Reconcile only machine-verifiable revision stages; creative mapping and review stay explicit. */
export async function reconcileRevisionState(projectRoot: string): Promise<RevisionState | undefined> {
const existing = await readRevisionState(projectRoot);
@@ -299,7 +318,15 @@ export async function reconcileRevisionState(projectRoot: string): Promise<Revis
for (const [rawStep, key] of Object.entries(checks)) {
const step = Number(rawStep);
const present = await fileExists(existing.artifacts[key]);
- if (present) completed.add(step);
+ const layoutSatisfied = step !== 5 || existing.status === "complete" || await (async () => {
+ const path = existing.artifacts.layout_check;
+ if (path === undefined) return false;
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as { executed?: unknown; settled?: unknown };
+ return value.executed === true && value.settled === true && await layoutEvidenceCurrent(path);
+ } catch { return false; }
+ })();
+ if (present && layoutSatisfied) completed.add(step);
else if (completed.has(step)) { completed.delete(step); conflicts.push(`step ${step} (${key}) was marked complete but its evidence is missing`); }
}
// A later machine artifact cannot silently credit the manual intent/source stages.
diff --git a/packages/reference-video-tools/src/route-state.ts b/packages/reference-video-tools/src/route-state.ts
index c29f7cc0..77615c81 100644
--- a/packages/reference-video-tools/src/route-state.ts
+++ b/packages/reference-video-tools/src/route-state.ts
@@ -7,25 +7,25 @@ export type RouteKind = "reconstruction" | "description" | "variant" | "variant-
export type RouteStatus = "active" | "complete" | "blocked";
export type ReconstructionRouteStep =
| "environment" | "reference-prepared" | "reference-observed" | "vocabulary-checked"
- | "package-ready" | "script-checked" | "source-authored" | "graph-checked"
+ | "package-ready" | "script-checked" | "source-authored" | "graph-checked" | "layout-checked"
| "review-planned" | "preview-rendered" | "comparison-complete" | "repairs-complete"
| "final-checked" | "build-complete";
export type DescriptionRouteStep =
| "environment" | "brief-frozen" | "vocabulary-checked" | "package-ready"
- | "script-checked" | "source-authored" | "graph-checked" | "review-planned"
+ | "script-checked" | "source-authored" | "graph-checked" | "layout-checked" | "review-planned"
| "preview-rendered" | "review-complete" | "repairs-complete" | "final-checked"
| "build-complete";
export type VariantRouteStep =
| "baseline-copied" | "brief-frozen" | "change-scope-frozen" | "guidance-loaded"
| "vocabulary-verified" | "package-ready" | "script-checked" | "source-updated"
- | "graph-checked" | "final-checked" | "variant-complete";
+ | "graph-checked" | "layout-checked" | "final-checked" | "variant-complete";
export type VariantPackageRouteStep =
| "gap-confirmed" | "guidance-loaded" | "types-frozen" | "implemented"
- | "vocabulary-inspected" | "package-validated" | "graph-checked" | "package-ready";
+ | "vocabulary-inspected" | "package-validated" | "graph-checked" | "layout-checked" | "package-ready";
export type RouteStep = ReconstructionRouteStep | DescriptionRouteStep | VariantRouteStep | VariantPackageRouteStep;
export type RouteState = {
- readonly version: 3;
+ readonly version: 4;
readonly route_id: string;
readonly route: RouteKind;
readonly project_root: string;
@@ -70,8 +70,9 @@ const COMPONENT_FIT_DECISIONS = new Set([
"project-local-package",
]);
-export const ROUTE_STATE_VERSION = 3 as const;
-const PREVIOUS_ROUTE_STATE_VERSION = 2 as const;
+export const ROUTE_STATE_VERSION = 4 as const;
+const PREVIOUS_ROUTE_STATE_VERSION = 3 as const;
+const EARLIER_ROUTE_STATE_VERSION = 2 as const;
const LEGACY_ROUTE_STATE_VERSION = 1 as const;
const LEGACY_ROUTE_STATE_STEPS: Readonly<Record<RouteKind, readonly string[]>> = {
reconstruction: [
@@ -89,23 +90,30 @@ const LEGACY_ROUTE_STATE_STEPS: Readonly<Record<RouteKind, readonly string[]>> =
export const ROUTE_STATE_STEPS: Readonly<Record<RouteKind, readonly string[]>> = {
reconstruction: [
"environment", "reference-prepared", "reference-observed", "vocabulary-checked", "package-ready",
- "script-checked", "source-authored", "graph-checked", "review-planned", "preview-rendered",
+ "script-checked", "source-authored", "graph-checked", "layout-checked", "review-planned", "preview-rendered",
"comparison-complete", "repairs-complete", "final-checked", "build-complete",
],
description: [
"environment", "brief-frozen", "vocabulary-checked", "package-ready", "script-checked", "source-authored",
- "graph-checked", "review-planned", "preview-rendered", "review-complete", "repairs-complete", "final-checked", "build-complete",
+ "graph-checked", "layout-checked", "review-planned", "preview-rendered", "review-complete", "repairs-complete", "final-checked", "build-complete",
],
variant: [
"baseline-copied", "brief-frozen", "change-scope-frozen", "guidance-loaded", "vocabulary-verified",
- "package-ready", "script-checked", "source-updated", "graph-checked", "final-checked", "variant-complete",
+ "package-ready", "script-checked", "source-updated", "graph-checked", "layout-checked", "final-checked", "variant-complete",
],
"variant-package": [
"gap-confirmed", "guidance-loaded", "types-frozen", "implemented", "vocabulary-inspected",
- "package-validated", "graph-checked", "package-ready",
+ "package-validated", "graph-checked", "layout-checked", "package-ready",
],
};
+const PREVIOUS_ROUTE_STATE_STEPS: Readonly<Record<RouteKind, readonly string[]>> = {
+ reconstruction: ["environment", "reference-prepared", "reference-observed", "vocabulary-checked", "package-ready", "script-checked", "source-authored", "graph-checked", "review-planned", "preview-rendered", "comparison-complete", "repairs-complete", "final-checked", "build-complete"],
+ description: ["environment", "brief-frozen", "vocabulary-checked", "package-ready", "script-checked", "source-authored", "graph-checked", "review-planned", "preview-rendered", "review-complete", "repairs-complete", "final-checked", "build-complete"],
+ variant: ["baseline-copied", "brief-frozen", "change-scope-frozen", "guidance-loaded", "vocabulary-verified", "package-ready", "script-checked", "source-updated", "graph-checked", "final-checked", "variant-complete"],
+ "variant-package": ["gap-confirmed", "guidance-loaded", "types-frozen", "implemented", "vocabulary-inspected", "package-validated", "graph-checked", "package-ready"],
+};
+
export function routeStatePath(projectRoot: string): string {
return join(resolve(projectRoot), ".hypit", "route-state.json");
}
@@ -199,14 +207,55 @@ function migrateLegacyRouteState(value: unknown, path: string): RouteState | und
if (value === null || typeof value !== "object") return undefined;
const version = (value as { version?: unknown }).version;
if (version === PREVIOUS_ROUTE_STATE_VERSION) {
- const previous = value as Omit<RouteState, "version" | "route_id" | "artifact_digests" | "created_at"> & { readonly version: 2 };
+ const previous = value as Omit<RouteState, "version" | "completed_steps" | "current_step" | "in_progress"> & {
+ readonly version: 3;
+ readonly completed_steps: readonly number[];
+ readonly current_step: number;
+ readonly in_progress: { readonly step: number; readonly started_at: string } | null;
+ };
+ const names = previous.completed_steps.map((step) => PREVIOUS_ROUTE_STATE_STEPS[previous.route][step - 1]).filter((name): name is string => name !== undefined);
+ const completed = previous.status === "complete"
+ ? ROUTE_STATE_STEPS[previous.route].map((_name, index) => index + 1)
+ : names.flatMap((name) => {
+ const index = ROUTE_STATE_STEPS[previous.route].indexOf(name);
+ return index < 0 ? [] : [index + 1];
+ });
+ const currentStep = nextUncompleted(previous.route, completed);
+ return {
+ ...previous,
+ version: ROUTE_STATE_VERSION,
+ current_step: currentStep,
+ completed_steps: completed,
+ in_progress: currentStep > ROUTE_STATE_STEPS[previous.route].length ? null : { step: currentStep, started_at: previous.updated_at },
+ next_action: currentStep > ROUTE_STATE_STEPS[previous.route].length ? "route complete" : `complete ${ROUTE_STATE_STEPS[previous.route][currentStep - 1]}`,
+ };
+ }
+ if (version === EARLIER_ROUTE_STATE_VERSION) {
+ const previous = value as Omit<RouteState, "version" | "route_id" | "artifact_digests" | "created_at" | "completed_steps" | "current_step" | "in_progress"> & {
+ readonly version: 2;
+ readonly completed_steps: readonly number[];
+ readonly current_step: number;
+ readonly in_progress: { readonly step: number; readonly started_at: string } | null;
+ };
const createdAt = typeof previous.updated_at === "string" ? previous.updated_at : new Date().toISOString();
+ const names = previous.completed_steps.map((step) => PREVIOUS_ROUTE_STATE_STEPS[previous.route][step - 1]).filter((name): name is string => name !== undefined);
+ const completed = previous.status === "complete"
+ ? ROUTE_STATE_STEPS[previous.route].map((_name, index) => index + 1)
+ : names.flatMap((name) => {
+ const index = ROUTE_STATE_STEPS[previous.route].indexOf(name);
+ return index < 0 ? [] : [index + 1];
+ });
+ const currentStep = nextUncompleted(previous.route, completed);
return {
...previous,
version: ROUTE_STATE_VERSION,
route_id: executionId(previous.route ?? "route"),
artifact_digests: {},
created_at: createdAt,
+ current_step: currentStep,
+ completed_steps: completed,
+ in_progress: currentStep > ROUTE_STATE_STEPS[previous.route].length ? null : { step: currentStep, started_at: createdAt },
+ next_action: currentStep > ROUTE_STATE_STEPS[previous.route].length ? "route complete" : `complete ${ROUTE_STATE_STEPS[previous.route][currentStep - 1]}`,
};
}
if (version !== LEGACY_ROUTE_STATE_VERSION) return undefined;
@@ -442,7 +491,7 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promise
? existing.decisions
: [...existing.decisions, input.decision.trim()];
const artifactDigests: Record<string, string> = { ...existing.artifact_digests };
- const frozenKeys = new Set(["brief", "vocabulary", "component_fit", "baseline_manifest", "variant_brief", "allowed_changes", "guidance", "gap_plan", "types", "package_digest"]);
+ const frozenKeys = new Set(["brief", "vocabulary", "component_fit", "baseline_manifest", "variant_brief", "allowed_changes", "guidance", "gap_plan", "types", "package_digest", "layout_check", "layout_decisions"]);
for (const [key, value] of Object.entries(artifacts)) {
if (!frozenKeys.has(key) && !value.includes(`${sep}.hypit${sep}evidence${sep}`)) continue;
if (key === "component_fit" && input.artifacts?.component_fit === undefined) continue;
@@ -507,6 +556,12 @@ async function evidenceSatisfied(key: string, path: string | undefined): Promise
return value.passed === true;
} catch { return false; }
}
+ if (key === "layout_check") {
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as { executed?: unknown; settled?: unknown };
+ return value.executed === true && value.settled === true;
+ } catch { return false; }
+ }
if (key === "comparison_log" || key === "review_log") {
try {
const lines = (await readFile(path, "utf8")).split("\n").filter((line) => line.trim().length > 0);
@@ -534,6 +589,18 @@ async function evidenceSatisfied(key: string, path: string | undefined): Promise
return true;
}
+async function layoutEvidenceCurrent(path: string | undefined): Promise<boolean> {
+ if (path === undefined) return false;
+ try {
+ const report = JSON.parse(await readFile(path, "utf8")) as { executed?: unknown; settled?: unknown; input_digests?: Record<string, unknown> };
+ if (report.executed !== true || report.settled !== true || report.input_digests === undefined) return false;
+ for (const [file, expected] of Object.entries(report.input_digests)) {
+ if (typeof expected !== "string" || await digestPath(file) !== expected) return false;
+ }
+ return true;
+ } catch { return false; }
+}
+
/** Reconcile a snapshot with the small, durable evidence pointers it records. */
export async function reconcileRouteState(projectRoot: string): Promise<RouteState | undefined> {
const existing = await readRouteState(projectRoot);
@@ -550,7 +617,8 @@ export async function reconcileRouteState(projectRoot: string): Promise<RouteSta
const renderComplete = key === "preview_render"
? await evidenceSatisfied("render_sidecar", artifact("render_sidecar"))
: true;
- const satisfied = renderComplete && await evidenceSatisfied(key, artifact(key));
+ const satisfied = renderComplete && await evidenceSatisfied(key, artifact(key))
+ && (key !== "layout_check" || await layoutEvidenceCurrent(artifact(key)));
if (satisfied) completed.add(step);
else {
if (completed.has(step)) conflicts.push(`step ${step} (${key}) was marked complete but its evidence is missing or failed`);
@@ -560,20 +628,20 @@ export async function reconcileRouteState(projectRoot: string): Promise<RouteSta
const evidenceByStep: Readonly<Record<RouteKind, Readonly<Record<number, string>>>> = {
reconstruction: {
2: "reference_state", 3: "reference_observations", 4: "vocabulary", 5: "package_ready", 6: "script_cues",
- 7: "author_source", 8: "preview_check", 9: "review_plan", 10: "preview_render", 11: "comparison_log", 13: "final_check", 14: "build",
+ 7: "author_source", 8: "preview_check", 9: "layout_check", 10: "review_plan", 11: "preview_render", 12: "comparison_log", 14: "final_check", 15: "build",
},
description: {
2: "brief", 3: "vocabulary", 4: "package_ready", 5: "script_cues", 6: "author_source", 7: "preview_check",
- 8: "review_plan", 9: "preview_render", 10: "review_log", 12: "final_check", 13: "build",
+ 8: "layout_check", 9: "review_plan", 10: "preview_render", 11: "review_log", 13: "final_check", 14: "build",
},
variant: {
1: "baseline_manifest", 2: "variant_brief", 3: "allowed_changes", 4: "guidance",
5: "vocabulary", 6: "package_ready", 7: "script_cues", 8: "author_source",
- 9: "preview_check", 10: "variant_check", 11: "variant_check",
+ 9: "preview_check", 10: "layout_check", 11: "variant_check", 12: "variant_check",
},
"variant-package": {
1: "gap_plan", 2: "guidance", 3: "types", 4: "package_source", 5: "vocabulary",
- 6: "package_ready", 7: "preview_check", 8: "package_digest",
+ 6: "package_ready", 7: "preview_check", 8: "layout_check", 9: "package_digest",
},
};
for (const [step, key] of Object.entries(evidenceByStep[existing.route])) {
diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.ts
index 617fb24f..0e1922db 100644
--- a/packages/reference-video-tools/src/tools.ts
+++ b/packages/reference-video-tools/src/tools.ts
@@ -52,6 +52,8 @@ import {
} from "./revision-state.js";
import type { RevisionParentRoute, RevisionState, RevisionStep } from "./revision-state.js";
import { persistEvidence } from "./state-files.js";
+import { layoutAccept, layoutCheck } from "./layout.js";
+import type { LayoutAcceptInput, LayoutCheckInput } from "./layout.js";
import {
checkpointVariantExpansion,
discoverVariantExpansions,
@@ -265,6 +267,8 @@ export type ReferenceVideoTools = {
render_element(input: RenderElementInput): Promise<Record<string, unknown>>;
render_previews(input: RenderPreviewsInput): Promise<Record<string, unknown>>;
preview_check(input: PreviewCheckInput): Promise<Record<string, unknown>>;
+ layout_check(input: LayoutCheckInput): Promise<Record<string, unknown>>;
+ layout_accept(input: LayoutAcceptInput): Promise<Record<string, unknown>>;
reconstruction_check(input: ReconstructionCheckInput): Promise<Record<string, unknown>>;
/**
* The same gate for a program authored from a description. It resolves no reference, credits an
@@ -445,6 +449,23 @@ async function persistRouteEvidence(runPath: string, name: string, result: Recor
return persistEvidence(dirname(resolve(runPath)), name, result);
}
+async function readSettledLayout(runPath: string): Promise<Record<string, unknown>> {
+ const path = join(dirname(resolve(runPath)), ".hypit", "layout-check.json");
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
+ return {
+ passed: value.executed === true && value.settled === true,
+ evidence: path,
+ executed: value.executed === true,
+ settled: value.settled === true,
+ pending_count: value.pending_count,
+ semantics: value.semantics,
+ };
+ } catch {
+ return { passed: false, evidence: path, executed: false, settled: false, reason: "run layout_check first" };
+ }
+}
+
async function autoRouteError(runPath: string | undefined, command: string, error: unknown): Promise<void> {
if (runPath === undefined) return;
const resolved = resolve(invokedFrom(), runPath);
@@ -2522,9 +2543,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
const source = await authorSource(runPath).catch(() => undefined);
const route = await readRouteState(dirname(runPath));
const sourceStep = routeStepFor(route?.route ?? "reconstruction", "source-authored");
- const next = route?.route === "variant" ? "run variant_check --run <build.svrun>"
- : route?.route === "variant-package" ? "freeze the package digest and checkpoint package-ready"
- : "run reconstruction_check or authoring_check";
+ const next = "run layout_check --run <build.svrun>";
await autoRouteCheckpoint(runPath, sourceStep, source === undefined ? {} : { author_source: source.path }, next);
const routeAfterSource = await readRouteState(dirname(runPath));
await autoRouteCheckpoint(runPath, routeStepFor(routeAfterSource?.route ?? "reconstruction", "graph-checked"), { preview_check: evidence }, next);
@@ -2536,6 +2555,51 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
}
},
+ async layout_check(input): Promise<Record<string, unknown>> {
+ const runPath = resolve(invokedFrom(), input.run);
+ try {
+ const result = await layoutCheck(input);
+ const evidence = typeof result.evidence === "string" ? result.evidence : join(dirname(runPath), ".hypit", "layout-check.json");
+ const decisions = typeof result.decisions === "string" ? result.decisions : join(dirname(runPath), ".hypit", "layout-decisions.json");
+ const route = await readRouteState(dirname(runPath));
+ if (route !== undefined && route.status !== "complete") {
+ const step = routeStepFor(route.route, "layout-checked");
+ if (step !== undefined) {
+ if (result.settled === true) {
+ await autoRouteCheckpoint(runPath, step, { layout_check: evidence, layout_decisions: decisions },
+ route.route === "variant" ? "run variant_check --run <build.svrun>"
+ : route.route === "variant-package" ? "freeze the package digest and checkpoint package-ready"
+ : "plan the visual declaration review");
+ } else {
+ await checkpointRouteState({
+ projectRoot: dirname(runPath), route: route.route, step, status: "in_progress", run: runPath,
+ artifacts: { layout_check: evidence, layout_decisions: decisions }, command: "layout_check",
+ nextAction: "Agent reviews each layout candidate, repairs genuine issues or records intentional geometry with layout_accept, then reruns layout_check",
+ });
+ }
+ }
+ }
+ const revision = await readRevisionState(dirname(runPath));
+ if (revision !== undefined && revision.status !== "complete") {
+ await checkpointRevisionState({
+ projectRoot: dirname(runPath), step: "gates-checked", status: "in_progress", run: runPath,
+ artifacts: { layout_check: evidence, layout_decisions: decisions }, command: "layout_check",
+ nextAction: result.settled === true
+ ? "complete the remaining revision gates"
+ : "Agent reviews layout candidates; repair or accept them, then rerun layout_check",
+ });
+ }
+ return result;
+ } catch (error) {
+ await autoRouteError(runPath, "layout_check", error);
+ throw error;
+ }
+ },
+
+ async layout_accept(input): Promise<Record<string, unknown>> {
+ return await layoutAccept(input);
+ },
+
async reconstruction_check(input): Promise<Record<string, unknown>> {
const runPath = resolve(invokedFrom(), input.run);
try {
@@ -2547,7 +2611,10 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
await autoRouteError(runPath, "reconstruction_check", refused.issues);
return { ...refused, evidence };
}
- const result = await authoringCheck({ ...input, mode: "reconstruction" }, { packageRoot });
+ const authored = await authoringCheck({ ...input, mode: "reconstruction" }, { packageRoot });
+ const layout = await readSettledLayout(runPath);
+ const result: Record<string, unknown> = layout.passed === true ? { ...authored, layout }
+ : { ...authored, passed: false, layout, issues: [...(Array.isArray(authored.issues) ? authored.issues : []), "layout candidates are unresolved or layout_check has not run"] };
const evidence = await persistRouteEvidence(runPath, "final-check.json", result);
if (Array.isArray(result.plan)) {
const planPath = await persistRoutePlan(runPath, result);
@@ -2574,7 +2641,10 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
await autoRouteError(runPath, "authoring_check", refused.issues);
return { ...refused, evidence };
}
- const result = await authoringCheck({ ...input, mode: "description" }, { packageRoot });
+ const authored = await authoringCheck({ ...input, mode: "description" }, { packageRoot });
+ const layout = await readSettledLayout(runPath);
+ const result: Record<string, unknown> = layout.passed === true ? { ...authored, layout }
+ : { ...authored, passed: false, layout, issues: [...(Array.isArray(authored.issues) ? authored.issues : []), "layout candidates are unresolved or layout_check has not run"] };
const evidence = await persistRouteEvidence(runPath, "final-check.json", result);
if (Array.isArray(result.plan)) {
const planPath = await persistRoutePlan(runPath, result);
@@ -2737,10 +2807,11 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
.catch((error) => ({ passed: false, error: error instanceof Error ? error.message : String(error) }));
const generatedLeakage = await findGeneratedLeakage(projectRoot, runPath)
.catch((error) => ({ passed: false, error: error instanceof Error ? error.message : String(error) }));
+ const layoutGate = await readSettledLayout(runPath);
const result: Record<string, unknown> = {
run: runPath,
passed: vocabularyPassed && packageGate.passed === true && cueGate.passed === true
- && graphGate.sound === true && mechanics.passed === true && minimalDiff.passed === true && generatedLeakage.passed === true,
+ && graphGate.sound === true && layoutGate.passed === true && mechanics.passed === true && minimalDiff.passed === true && generatedLeakage.passed === true,
vocabulary: {
passed: vocabularyPassed, mode: vocabularyMode, required_packages: requiredPackages, evidence: vocabularyPath,
evidence_digest: vocabularyDigest, baseline_digest: manifest?.vocabulary_digest,
@@ -2750,7 +2821,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
required_packages_imported_and_used: requiredImportedAndUsed,
package_bindings: packageBindings,
},
- package_gate: packageGate, script_cue_gate: cueGate, graph: graphGate, mechanics, minimal_diff: minimalDiff,
+ package_gate: packageGate, script_cue_gate: cueGate, graph: graphGate, layout: layoutGate, mechanics, minimal_diff: minimalDiff,
generated_result_leakage: generatedLeakage,
visual_review: "not performed",
};
@@ -2767,6 +2838,11 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
await autoRouteCheckpoint(runPath, routeStepFor("variant", "source-authored"), source === undefined ? {} : { author_source: source.path });
await autoRouteCheckpoint(runPath, routeStepFor("variant", "graph-checked"), { preview_check: previewEvidence });
}
+ if (layoutGate.passed === true) {
+ await autoRouteCheckpoint(runPath, routeStepFor("variant", "layout-checked"), {
+ layout_check: String(layoutGate.evidence), layout_decisions: join(projectRoot, ".hypit", "layout-decisions.json"),
+ });
+ }
if (result.passed === true) {
await autoRouteCheckpoint(runPath, routeStepFor("variant", "final-checked"), { variant_check: finalEvidence });
const readyToComplete = await readRouteState(projectRoot);
diff --git a/packages/reference-video-tools/test/route-state.test.ts b/packages/reference-video-tools/test/route-state.test.ts
index b92fe785..1690af84 100644
--- a/packages/reference-video-tools/test/route-state.test.ts
+++ b/packages/reference-video-tools/test/route-state.test.ts
@@ -187,7 +187,7 @@ test("v1 route snapshots migrate by stage name and re-open new gates", async ()
artifacts: {}, decisions: [], next_action: "write Source", updated_at: new Date().toISOString(),
}), "utf8");
const migrated = await readRouteState(root);
- assert.equal(migrated?.version, 3);
+ assert.equal(migrated?.version, 4);
assert.equal(migrated?.completed_steps.includes(3), true);
assert.equal(migrated?.completed_steps.includes(4), false, "new vocabulary gate is not guessed from old source state");
assert.equal(migrated?.current_step, 4);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 32744ddf..8ab8f330 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2315,6 +2315,9 @@ importers:
'@hypit/yt-dlp':
specifier: workspace:*
version: link:../yt-dlp
+ puppeteer-core:
+ specifier: 25.5.0
+ version: 25.5.0
tsx:
specifier: 4.21.0
version: 4.21.0