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.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
Close package resolution preview timing and geometry gates
rpone45ec7712b44c
diff --git a/.agents/skills/hypit/SKILL.md b/.agents/skills/hypit/SKILL.mdindex 71b426fe..7130b112 100644--- a/.agents/skills/hypit/SKILL.md+++ b/.agents/skills/hypit/SKILL.md@@ -126,3 +126,8 @@ invalid. Never commit `.env` or copy its secret values into route state, Source,Preserve unrelated changes. Keep credentials, generated media, runtime state, and logs out ofcommits. Installed package declarations and published docs remain authoritative; repositorymaintenance instructions apply only to contributors who deliberately cloned the repository.++Studio URL handoff is mandatory: whenever a Studio process is started, capture the URL printed by+the server and include the exact URL in the user-facing response. A statement that Studio started+without the URL is incomplete; if the startup parameters change, stop the old process first and+report the new URL after the replacement is listening.diff --git a/.agents/skills/hypit/references/element-review.md b/.agents/skills/hypit/references/element-review.mdindex f01bcad0..b48cfe85 100644--- a/.agents/skills/hypit/references/element-review.md+++ b/.agents/skills/hypit/references/element-review.md@@ -119,6 +119,10 @@ element ids. Use those numbers as the mechanical findings and let the observer dalignment or overflow matches the reference/intent. The report cannot measure renderer-shaped glyphbounds or infer intent, so the visual pass must still confirm text and marks in the rendered image.+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+a repair.+A mock lives only in this render. It is never written into the Source, and no gate reads it: the`playback` check reads the Source's Recipes, so a mock cannot be mistaken for coverage.diff --git a/.agents/skills/hypit/references/local-author-package.md b/.agents/skills/hypit/references/local-author-package.mdindex 89951d5e..4d3770f6 100644--- a/.agents/skills/hypit/references/local-author-package.md+++ b/.agents/skills/hypit/references/local-author-package.md@@ -236,12 +236,15 @@ Before Source can be considered authored, run:hypit-reference-video-tools validate_local_author_packages --run <path/to/build.svrun>```-Every project-owned package under `<project>/packages/` must expose a non-empty Manifest, at least one-Markup Surface, at least one Producer and at least one Run Fragment with operations and exports. The-Run's compiled Graph must contain an operation from that package, and the Author Source must import-and use its Surface. An import without use, a marker-only package, or a package replaced by a similar-official component fails with a machine-readable diagnostic. If no gap exists, do not leave an unused-package in the project. `validate_local_author_packages` discovers these package directories from+Every project-owned author package under `<project>/packages/` must expose a non-empty Manifest, at least one+Markup Surface and at least one Producer. Its Surface decoder must expand to a real Graph Fragment with+operations and exports, and every Fragment operation Producer must belong to the package's own Module.+Run-fragment host facets are required only by packages that explicitly provide Run-side replacements such+as preview mocks; an author package is not required to expose one. The Run's compiled Graph must contain+an operation from that package, and the Author Source must import and use its Surface. An import without+use, a marker-only package, or a package replaced by a similar official component fails with a+machine-readable diagnostic. If no gap exists, do not leave an unused package in the project.+`validate_local_author_packages` discovers these package directories fromtheir manifests; the directory name is not a validation signal.The Host resolves the explicitly selected physical package name directly atdiff --git a/.agents/skills/hypit/references/original-authoring/conformance-round.md b/.agents/skills/hypit/references/original-authoring/conformance-round.mdindex 9db50a0f..e31908c6 100644--- a/.agents/skills/hypit/references/original-authoring/conformance-round.md+++ b/.agents/skills/hypit/references/original-authoring/conformance-round.md@@ -76,6 +76,9 @@ Canvas offsets, containment overflow, and bound element ids. Use it as the mechathe conformance decision from the rendered picture and intent. It cannot measure actual glyph bounds orinfer intent, so those still require the reader.+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.+`--question` is available and means what it means on the other route: which region to read, never whatto conclude.diff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.mdindex 6e4b320e..2752f3b8 100644--- a/.agents/skills/hypit/references/original-authoring/route.md+++ b/.agents/skills/hypit/references/original-authoring/route.md@@ -215,10 +215,10 @@ configured to empty its window.**Read now:** `../studio-confirmation.md`. Before the paid gate, call the preview-mock realizer andstart Studio with its returned temporary `preview.svrun` (not the unresolved author Run). Show the-complete estimate-timed mock, then obtain explicit acceptance and cost approval. If the author-declines, enter `../revision.md` and do not submit a Build. After acceptance and paid Build-submission, persist the accepted Build-Record Run, start Studio for that Run, and start the-HyperFrames/final render concurrently.+complete estimate-timed mock, return the exact URL printed by Studio, and obtain explicit acceptance+and cost approval. If the author declines, enter `../revision.md` and do not submit a Build. After+acceptance and paid Build submission, persist the accepted Build-Record Run, start Studio for that+Run, return its exact URL, and start the HyperFrames/final render concurrently.Confirm credentials, the Runtime Profile, the installed packages, model limits, resolution andEndpoint prerequisites. Run `doctor`, `check` and `plan`.diff --git a/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md b/.agents/skills/hypit/references/playbooks/craft/frame-coverage.mdindex 3a2a79e3..0c71e534 100644--- a/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md+++ b/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md@@ -17,6 +17,8 @@ an interval inherits its edges whenever its length comes from something other th- a window derived from speech, which starts and stops with words and therefore excludes the silencearound and between them;+- a still image has no duration-bearing timeline and must not receive a `playback` value; the+ playback gate applies only to moving/generated media whose material can end before its window;- an insert, whose material ends where the generator stopped rather than where its window does — andthen draws nothing for the rest of it, because `playback` defaults to `once-start`, so whatever itwas covering is alone again mid-phrase. This is the one edge on the list a machine can find before a Build:diff --git a/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md b/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.mdindex 8dfab6e7..d6ae9d02 100644--- a/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md+++ b/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md@@ -269,7 +269,11 @@ Selection and Moment share one name namespace, so the same id cannot be both.## A short stretch is not a short takeAn authored take stays inside the selected model's declared duration range — read the range from the-model, since it differs between them and a literal in a document goes stale.+model, since it differs between them and a literal in a document goes stale. `estimate:Speech` is a+separate speech clock and may be shorter than a paid model's minimum: the generation request must use+the model-valid floor (or a shared longer take), while the SemanticTake remains aligned to the speech+estimate. Trim or hold the visual material as needed; never pad the SemanticTake or substitute reference+timings for it.This too is about a generation that carries no speech. A Segment always has its own speaking take,however short its words are.diff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.mdindex 15cca096..c83f7174 100644--- a/.agents/skills/hypit/references/preview.md+++ b/.agents/skills/hypit/references/preview.md@@ -131,7 +131,8 @@ hypit-studio --run .hypit/preview/<digest>/preview.svrun --runtime hypit.runtimeIf another Studio process is already using a different Run or startup parameters, stop that processbefore launching this command; otherwise reuse the existing process and let its Source watcher reload.-Read the startup output for the chosen port. `--run` is required: Studio's unit of work is the Run+Read the startup output for the chosen port and return the exact Studio URL to the author. `--run` is+required: Studio's unit of work is the RunSource, and it reads the Author SVML back out of it. Pass `--runtime` only when the Author Sourcereuses accepted Build records. `--workspace` selects the Source Workspace and defaults to the Run'sown directory, so pass it when the Run's relative Sources resolve against a different root.diff --git a/.agents/skills/hypit/references/reconstruction/comparison-round.md b/.agents/skills/hypit/references/reconstruction/comparison-round.mdindex 64a44c64..cc255d78 100644--- a/.agents/skills/hypit/references/reconstruction/comparison-round.md+++ b/.agents/skills/hypit/references/reconstruction/comparison-round.md@@ -33,7 +33,10 @@ source edge is edited.`render_element` uses `@hypit/preview-mock` with the Source's `estimate:Speech` timing. `--reference-id`is reserved for selecting reference evidence and comparison windows, not for constructing mock tracks.The comparison still cuts both sides to the same words and refuses a pair whose two halves are different-lengths. Animated elements are assessed against the deterministic estimate clock used by preview.+lengths. Animated elements are assessed against the deterministic estimate clock used by preview. The+container-duration allowance defaults to three frames and may be set explicitly with+`tolerance_frames` (or CLI `--tolerance-frames`) when a known encoder/container boundary requires it;+do not use a large tolerance to hide a wrong estimate or a missing segment.A `--batch` round inherits the reference along with the Run, and `reconstruction_check`'s output isthe batch file.@@ -152,6 +155,11 @@ shadow, and corner treatment. A box can be centred and still be too small. Treatcrop, and enter/exit motion as a separate possibility and only call it a defect when the referencedoes not show that intention.+Ignore any mark that is clearly platform UI, player chrome, an export-tool or editing-software+watermark/overlay; it is not authored video content and must not become a repair target. If its+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 offsets, containment overflow, and bound element ids. The agent should use thosefacts alongside the comparison text. They are deterministic Source facts, not a decision: rendereddiff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.mdindex b3f0e067..723c401a 100644--- a/.agents/skills/hypit/references/reconstruction/route.md+++ b/.agents/skills/hypit/references/reconstruction/route.md@@ -173,9 +173,10 @@ One line, before any evidence starts.hypit-reference-video-tools list_svml_packages```-It reads `node_modules/@hypit` relative to the working directory and refuses when it is empty, so run-it from the repository root. Name the project with `--package-root` when the command is not run from-inside it. This is instant and may run before or during the sweep.+It resolves project-owned packages from the working directory (or the directory named by+`--package-root`) and resolves installed `@hypit/*` packages from the active Hypit Distribution+fallback. `--package-root` never replaces that Distribution root, so no `npm link` or package self-link+is needed. This is instant and may run before or during the sweep.### 8. Prepare the reference@@ -400,10 +401,10 @@ After any requested change (or when there was none), run `reconstruction_check`**Read now:** `../studio-confirmation.md`. Realize the preview-mock Run first, then start Studio withthe returned temporary `preview.svrun` (never the original unresolved Run), show the complete-estimate-timed mock, and obtain explicit acceptance and cost approval. If the author declines, enter+estimate-timed mock, return the exact URL printed by Studio, and obtain explicit acceptance and cost approval. If the author declines, enter`../revision.md` and do not Build. Once accepted, submit the paid Build and persist its accepted-Build-Record Run; start Studio for that accepted Run while the HyperFrames/final render proceeds-concurrently.+Build-Record Run; start Studio for that accepted Run, return the exact URL printed by Studio, while+the HyperFrames/final render proceeds concurrently.After acceptance, continue with `../runtime.md` for the approved paid Build and retrieval lifecycle.diff --git a/.agents/skills/hypit/references/revision.md b/.agents/skills/hypit/references/revision.mdindex f23448e9..f515c679 100644--- a/.agents/skills/hypit/references/revision.md+++ b/.agents/skills/hypit/references/revision.md@@ -34,7 +34,8 @@ deliberately not a VLM/observer step. Revision does not call`review_element`, `compare_reconstruction`, Vertex, WhisperX or any other visual observer. Mark thatstage only as an explicit mechanical checkpoint when the requested source change has been covered bythe deterministic checks. Revision itself performs no visual judgement; after it completes, if no-Studio session is running for the current Run, start Studio and show the author the updated result.+Studio session is running for the current Run, start Studio, capture the URL printed by the server,+and give the author the exact URL with the updated result.## Work sequencediff --git a/.agents/skills/hypit/references/script-time.md b/.agents/skills/hypit/references/script-time.mdindex 5f67a42f..76607ad3 100644--- a/.agents/skills/hypit/references/script-time.md+++ b/.agents/skills/hypit/references/script-time.md@@ -17,7 +17,9 @@ holds it and the rendered bounds prove it fits. This is a hard layout requiremenstyle preference: a Segment with no `||` becomes one Cue, and the entire long passage can render beyondthe screen. Do not depend on automatic wrapping, a larger box, or a smaller font to fix it. Choosebreaks at natural phrase or sentence boundaries, and never place `||` inside Dual Text or through an-N:M Alignment Unit.+N:M Alignment Unit. A closing `</segment>` is also a hard Cue boundary: Cue counting and timing+restart at the next Segment, so a trailing `||` is not required merely to prevent a Cue crossing+Segments.The mechanical gate `validate_script_cues --run <build.svrun>` enforces a maximum of four visiblewords per Cue. Fix the Script before `hypit check` or preview.diff --git a/.agents/skills/hypit/references/studio-confirmation.md b/.agents/skills/hypit/references/studio-confirmation.mdindex a67620e0..f0792769 100644--- a/.agents/skills/hypit/references/studio-confirmation.md+++ b/.agents/skills/hypit/references/studio-confirmation.md@@ -11,7 +11,9 @@ After the route-specific final check passes, but before submitting any paid Buildurable `.hypit/preview/<digest>/mock.svrun` (the native mock materialization Run), itscontent-addressed Artifacts, and a second `preview.svrun` whose relative file Candidates pointat those results.-2. Start Hypit Studio with that returned `previewRun` path and give the author its URL. Studio can+2. Start Hypit Studio with that returned `previewRun` path. Capture the URL printed by+ `server.printUrls()` and give the author the exact URL (for example,+ `http://localhost:5179/`) in the handoff. Studio cantherefore be started as a separate process and reopen the same bytes; it does not depend on anin-memory attachment list or a mock-media endpoint (Studio may use the local FFmpeg endpoint fordeterministic inspect/normalize operations).@@ -43,7 +45,8 @@ reruns only the deterministic gates before the next Studio handoff or paid BuildWhen a user-requested revision completes its deterministic gates, preserve a running Studio sessionand let its file watcher hot-reload the updated SVML/SVS/SVRun. If the current Run has no Studio-session, start one for that Run and give the author the URL so they can see the change. Do not invoke a+session, start one for that Run, capture the URL printed by the server, and give the author the exact+URL so they can see the change. Do not invoke aVLM, comparison, observer or visual judgement as part of Revision. Do not restart an already-runningStudio merely because Source changed. If the startup parameters change (for example a different Run,workspace or port), stop the previous Studio first so the new server cannot collide with its port.diff --git a/docs/guide/author-packages.md b/docs/guide/author-packages.mdindex 79160548..f5095740 100644--- a/docs/guide/author-packages.md+++ b/docs/guide/author-packages.md@@ -166,22 +166,14 @@ package's own README and vocabulary first, then only the role files needed for tThe preview is a real frame of your own component, rendered locally. Nothing generates it for you,and a mock-up drawn by hand is worse than no preview at all, because it claims to be output.-Render the fixture's preview Source with `hypit-reference-video-tools render_previews`. For a new-package, use the same package-owned preview Source and keep one representative rendered frame. The-sequence is:--1. build the Track value with your package's own render function, over a sealed ProgramSpace;-2. `sealComposition({ id, canvas, tracks })`, then `compileHyperframesDocument(composition, space)`- from `@hypit/hyperframes`;-3. `materializeHyperframesHtml(document, resolve)` into a temporary directory, where `resolve` maps- each declared Artifact — fonts, images — to a local file;-4. run the pinned HyperFrames CLI's `render` on that directory with a PNG-sequence output, resolved- through `@hypit/provider-hyperframes-local`;-5. keep one frame that shows the component in a representative state, and commit it under- `preview/`.--The alternative is a narrow `.svrun` Target rendered by the local HyperFrames Provider, then one-frame taken with `ffmpeg`. That is a Build; it needs a Runtime Profile, and it is the heavier route.+Render the fixture's preview Source with+`hypit-reference-video-tools render_previews <package-dir>`. For a new package, use the same+package-owned `preview/preview.svml`, `preview/recipes.svs` and `preview/build.svrun` shape, then keep+one representative frame under `preview/`. The command resolves the package from its explicit+workspace/package root and the active Distribution fallback; it does not require a+`packages/<slug>/node_modules` self-link or a manual `npm link`. It compiles the preview Run, lets the+native preview-mock path satisfy undeclared media, renders the complete deterministic composition+through the local HyperFrames Provider, and writes the promised image named by the Surface Manifest.Choose a frame mid-behaviour rather than at rest. A preview of an element that has not entered yet,or has already settled into a static end state, shows the least useful thing about it.@@ -291,4 +283,14 @@ const decoded: SurfaceDecodeOutput = {For temporal elements, the Surface side is `@hypit/temporal-markup`, not the graph-side`@hypit/temporal` module. Use `createTemporalWindowProjection` or`createTemporalInstantProjection` with the element, semantic reference and resolver, then append-the returned `records`, `components` and `fragments` to the same `SurfaceDecodeOutput`.+the returned `records`, `components` and `fragments` to the same `SurfaceDecodeOutput`. Because those+projections publish records that other Surface code may reference, the declaration's `outputs` must+include every generated public type (`TemporalInstantSpec`, `TemporalWindowSpec`, `TemporalInstant`+and `TemporalWindow`) in addition to the component's own records and terminal Track. The minimal+fixture's temporal helper shows the two packages and the attribute vocabulary without requiring a+business package source read.++Producer ports are exact, not variadic: the keys supplied by a Fragment operation must match the+Manifest's `inputs`, `outputs` and `needs` exactly. For a variable number of child items, emit one+operation per item and feed those operations into an append/merge Producer with fixed named ports;+do not invent an `items[]` port that the Manifest did not declare.diff --git a/docs/guide/component-anatomy.md b/docs/guide/component-anatomy.mdindex b5b340fe..cd67a741 100644--- a/docs/guide/component-anatomy.md+++ b/docs/guide/component-anatomy.md@@ -58,6 +58,11 @@ typed records, and returns the graph declarations. It is the only place that knooperations run, and which outputs the element publishes. Producers do the work; the Fragment says howthey are wired.+An author package's Surface returns this Graph Fragment; it is not the `run-fragment-host` facet used+by preview or other Run-side replacement packages. Every operation must use a Producer declared by+the same Module. Producer port bindings are exact: variable-length collections require repeated+operations followed by a fixed-port append/merge Producer rather than an undeclared variadic input.+## Assets a package shipsA component's own chrome — its paper, board, panel, texture or default backdrop — is a file insidediff --git a/examples/minimal-author-package/packages/example-component/README.md b/examples/minimal-author-package/packages/example-component/README.mdindex 61bc1c12..2d4c9232 100644--- a/examples/minimal-author-package/packages/example-component/README.md+++ b/examples/minimal-author-package/packages/example-component/README.md@@ -10,5 +10,5 @@ Surface-side `@hypit/temporal-markup` Window/Moment projections; that package isgraph-side `@hypit/temporal` Producers.The three Surfaces demonstrate a box, a text surface and a media slot. The slot is a graph input; it is-not a file bundled by the package. `preview/Example.png` is a real catalogue frame supplied by the+not a file bundled by the package. `preview/Box.png` is a real catalogue frame supplied by thepackage's vocabulary.diff --git a/examples/minimal-author-package/packages/example-component/package.json b/examples/minimal-author-package/packages/example-component/package.jsonindex 3c9ca445..5cf0d7bf 100644--- a/examples/minimal-author-package/packages/example-component/package.json+++ b/examples/minimal-author-package/packages/example-component/package.json@@ -12,6 +12,7 @@"@hypit/markup": "workspace:*","@hypit/protocol": "workspace:*","@hypit/program-space": "workspace:*",+ "@hypit/semantic-track": "workspace:*","@hypit/temporal": "workspace:*","@hypit/temporal-markup": "workspace:*","@hypit/visual-ir": "workspace:*"diff --git a/examples/minimal-author-package/packages/example-component/preview/Box.png b/examples/minimal-author-package/packages/example-component/preview/Box.pngnew file mode 100644index 00000000..758719a5Binary files /dev/null and b/examples/minimal-author-package/packages/example-component/preview/Box.png differdiff --git a/examples/minimal-author-package/packages/example-component/preview/build.svrun b/examples/minimal-author-package/packages/example-component/preview/build.svrunindex e2611870..35fd619c 100644--- a/examples/minimal-author-package/packages/example-component/preview/build.svrun+++ b/examples/minimal-author-package/packages/example-component/preview/build.svrun@@ -2,5 +2,5 @@<svrun version="1"><author source="./preview.svml"/>- <target output="box.track"/>+ <target output="final.video"/></svrun>diff --git a/examples/minimal-author-package/packages/example-component/preview/preview.svml b/examples/minimal-author-package/packages/example-component/preview/preview.svmlindex 7d617e97..5a67ae29 100644--- a/examples/minimal-author-package/packages/example-component/preview/preview.svml+++ b/examples/minimal-author-package/packages/example-component/preview/preview.svml@@ -1,8 +1,44 @@<?svml using="@hypit/markup@1"?>-<!-- Catalogue Source for the fixture. A host project supplies the ProgramSpace record named `space.main`.- The real catalogue frame is preview/Example.png; this file documents the smallest Surface call. -->+<!-- A complete, self-contained catalogue Source. The generated take is preview-mocked; the+ remaining deterministic graph is compiled and rendered through the normal Studio path. --><svml>+ <import from="@hypit/script@1"/>+ <import as="wording" from="@hypit/text@1"/>+ <import as="seedance" from="@hypit/seedance@1"/>+ <import as="pipeline" from="@hypit/media-pipeline@1"/>+ <import as="speech" from="@hypit/speech-track@1"/>+ <import as="whisperx" from="@hypit/whisperx@1"/>+ <import as="estimate" from="@hypit/estimate@1"/>+ <import as="space" from="@hypit/spatial@1"/>+ <import as="program" from="@hypit/program-space@1"/>+ <import as="film" from="@hypit/film@1"/>+ <import as="render" from="@hypit/render-hyperframes@1"/><import as="example" from="@example/example-component@1"/>- <example:Box id="box" space={space.main}/>+ <import as="recipes" source="./recipes.svs"/>++ <script id="story">+ <showcase><HOST>A deterministic example surface for the package catalogue.</showcase>+ </script>++ <space:Canvas id="vertical" width="720" height="1280"/>+ <program:Clock id="clock" frame-rate="30"/>+ <space:Frame id="speech-frame" within={vertical} left="0%" top="0%" right="100%" bottom="100%"/>++ <wording:Value id="direction">A neutral catalogue card in a quiet studio.</wording:Value>+ <estimate:Speech id="showcase-duration" source={story.segment.showcase.speech} policy={recipes.speech.normal}/>+ <seedance:TextVideo id="take" model="mini" prompt={direction} duration={showcase-duration.duration} generate-audio="true"/>+ <pipeline:Normalize id="take-media" source={take.video} recipe={recipes.media.aroll} clock={clock}/>+ <whisperx:SemanticTake id="showcase-semantic" narrative={story} segment={story.segment.showcase} media={take-media.media} language="en"/>+ <speech:Track id="speech" visual-frame={speech-frame} visual-appearance={recipes.speech.visual} visual-z="0">+ <speech:Take source={showcase-semantic.take}/>+ </speech:Track>++ <example:Box id="box" semantic={speech.semantic}/>+ <film:Film id="main" canvas={vertical} semantic={speech.semantic} appearance={recipes.film.vertical}>+ <film:Track source={speech.visual}/>+ <film:Track source={speech.audio}/>+ <film:Track source={box.track}/>+ </film:Film>+ <render:Video id="final" composition={main.composition} semantic={speech.semantic}/></svml>diff --git a/examples/minimal-author-package/packages/example-component/preview/recipes.svs b/examples/minimal-author-package/packages/example-component/preview/recipes.svsindex b7bb15d5..74d90f0f 100644--- a/examples/minimal-author-package/packages/example-component/preview/recipes.svs+++ b/examples/minimal-author-package/packages/example-component/preview/recipes.svs@@ -1,5 +1,8 @@<?svml using="@hypit/svs@1"?><sheet version="1">- example.default { background: #6b7280; }+ film.vertical { background: #09090B; }+ speech.visual { fit: cover; }+ speech.normal { language: en; pace: normal; min: 4; max: 30; rounding: round; }+ media.aroll { video: primary-moving; audio: default; span-authority: video; }</sheet>diff --git a/examples/minimal-author-package/packages/example-component/src/fragment.ts b/examples/minimal-author-package/packages/example-component/src/fragment.tsindex 7b68584e..24358adf 100644--- a/examples/minimal-author-package/packages/example-component/src/fragment.ts+++ b/examples/minimal-author-package/packages/example-component/src/fragment.ts@@ -1,5 +1,6 @@import { compositionTypes } from "@hypit/composition";import { sealGraphFragment } from "@hypit/elaborator";+import { semanticTrackProducers, semanticTrackTypes } from "@hypit/semantic-track";import { programSpaceTypes } from "@hypit/program-space";import { exampleProducers } from "./manifest.js";@@ -8,13 +9,11 @@ const operation = (id: string) => ({ kind: "fragment-operation" as const, operatexport function createExampleFragment(producer: typeof exampleProducers[keyof typeof exampleProducers], id: string) {return sealGraphFragment({- inputs: [{ name: "space", type: programSpaceTypes.programSpace }],- operations: [{- id,- producer,- inputs: { space: input("space") },- result: { kind: "output", name: "track" },- }],+ inputs: [{ name: "semantic", type: semanticTrackTypes.track }],+ operations: [+ { id: "space", producer: semanticTrackProducers.projectProgramSpace, inputs: { track: input("semantic") }, result: { kind: "output", name: "space" } },+ { id, producer, inputs: { space: operation("space") }, result: { kind: "output", name: "track" } },+ ],exports: [{ name: "track", type: compositionTypes.visualTrack, root: operation(id) }],});}diff --git a/examples/minimal-author-package/packages/example-component/src/manifest.ts b/examples/minimal-author-package/packages/example-component/src/manifest.tsindex e60c57f6..fb60b72b 100644--- a/examples/minimal-author-package/packages/example-component/src/manifest.ts+++ b/examples/minimal-author-package/packages/example-component/src/manifest.ts@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";import { compositionTypes } from "@hypit/composition";import type { ModuleManifest, ProducerRef, TypeRef } from "@hypit/protocol";import { programSpaceTypes } from "@hypit/program-space";+import { semanticTrackTypes } from "@hypit/semantic-track";import { temporalTypes } from "@hypit/temporal";const previewImage = (file: string) => ({@@ -27,6 +28,7 @@ export const exampleManifest: ModuleManifest = {dependencies: [{ module: compositionTypes.visualTrack.module },{ module: programSpaceTypes.programSpace.module },+ { module: semanticTrackTypes.track.module },{ module: temporalTypes.window.module },],types: Object.values(exampleTypes).map(({ name }) => ({ name })),@@ -42,10 +44,10 @@ export const exampleManifest: ModuleManifest = {const vocabulary = (summary: string, example: string) => ({summary,appearance: "A deterministic, self-contained example surface rendered on the supplied ProgramSpace.",- preview: previewImage("Example.png"),+ preview: previewImage("Box.png"),attributes: [{ name: "id", kind: "identifier" as const, required: true, summary: "Names this instance." },- { name: "space", kind: "reference" as const, required: true, accepts: [programSpaceTypes.programSpace], summary: "Selects the time space." },+ { name: "semantic", kind: "reference" as const, required: true, accepts: [semanticTrackTypes.track], summary: "Selects the semantic timing track." },],ports: [{ name: "track", type: compositionTypes.visualTrack, summary: "The terminal VisualTrack." }],example,@@ -53,7 +55,7 @@ const vocabulary = (summary: string, example: string) => ({});export const exampleMarkupSurfaces = [- { name: "box", tag: "Box", mode: "structured", outputs: [exampleTypes.box, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A framed box surface.", "<example:Box id=\"box\" space={space.main}/>") , preview: previewImage("Example.png") } },- { name: "text", tag: "Text", mode: "structured", outputs: [exampleTypes.text, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A text-bearing surface.", "<example:Text id=\"title\" space={space.main}>Hello</example:Text>"), preview: previewImage("Example.png") } },- { name: "media-slot", tag: "MediaSlot", mode: "structured", outputs: [exampleTypes.mediaSlot, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A media slot whose content is a graph input.", "<example:MediaSlot id=\"shot\" space={space.main}/>") , preview: previewImage("Example.png") } },+ { name: "box", tag: "Box", mode: "structured", outputs: [exampleTypes.box, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A framed box surface.", "<example:Box id=\"box\" semantic={speech.semantic}/>") , preview: previewImage("Box.png") } },+ { name: "text", tag: "Text", mode: "structured", outputs: [exampleTypes.text, temporalTypes.instantSpec, temporalTypes.windowSpec, temporalTypes.instant, temporalTypes.window, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A text-bearing surface.", "<example:Text id=\"title\" semantic={speech.semantic}>Hello</example:Text>"), preview: previewImage("Box.png") } },+ { name: "media-slot", tag: "MediaSlot", mode: "structured", outputs: [exampleTypes.mediaSlot, compositionTypes.visualTrack], vocabulary: { ...vocabulary("A media slot whose content is a graph input.", "<example:MediaSlot id=\"shot\" semantic={speech.semantic}/>") , preview: previewImage("Box.png") } },] as const;diff --git a/examples/minimal-author-package/packages/example-component/src/surface.ts b/examples/minimal-author-package/packages/example-component/src/surface.tsindex 92a21062..6a16e8c5 100644--- a/examples/minimal-author-package/packages/example-component/src/surface.ts+++ b/examples/minimal-author-package/packages/example-component/src/surface.ts@@ -17,12 +17,12 @@ function reference(element: StructuredElement, name: string, resolve: (path: strexport const decodeExampleSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {const id = text(element, "id");- const space = reference(element, "space", resolveReference);+ const semantic = reference(element, "semantic", resolveReference);const surface = exampleMarkupSurfaces.find((item) => item.tag === element.name.split(":").at(-1));if (surface === undefined) throw new Error(`Unknown example surface ${element.name}`);const fragment = surface.name === "box" ? exampleBoxFragment : surface.name === "text" ? exampleTextFragment : exampleMediaFragment;const type = surface.name === "box" ? exampleTypes.box : surface.name === "text" ? exampleTypes.text : exampleTypes.mediaSlot;const record: SurfaceRecordDraft = { id: `${id}.value`, type, value: { kind: "inline", value: { id } }, range: element.range };- const component: SurfaceComponentDraft = { id, fragment: fragment.id, inputs: { space: space.ref }, outputs: { track: `${id}.track` }, range: element.range };+ const component: SurfaceComponentDraft = { id, fragment: fragment.id, inputs: { semantic: semantic.ref }, outputs: { track: `${id}.track` }, range: element.range };return { records: [record], components: [component], fragments: [fragment], exports: [`${id}.value`, `${id}.track`] };};diff --git a/packages/composition/src/index.ts b/packages/composition/src/index.tsindex 65961148..c360d462 100644--- a/packages/composition/src/index.ts+++ b/packages/composition/src/index.ts@@ -13,4 +13,5 @@ export {visualTrackSchema,} from "./schema.js";export { assertAudioTrackIdentity, assertCompositionIdentity, assertVisualTrackIdentity, sealAudioTrack, sealComposition, sealVisualTrack } from "./track.js";+export { animatableLocalStyles } from "./track.js";export type * from "./track.js";diff --git a/packages/composition/src/track.ts b/packages/composition/src/track.tsindex 33ce4af3..6a0ff0f6 100644--- a/packages/composition/src/track.ts+++ b/packages/composition/src/track.ts@@ -421,12 +421,14 @@ export type Composition = {readonly tracks: readonly Track[];};-const ANIMATABLE_LOCAL_STYLES = new Set([+/** The only local style properties accepted in element keyframes. */+export const animatableLocalStyles = ["clip-path","filter","opacity","transform",-]);+] as const;+const ANIMATABLE_LOCAL_STYLES = new Set<string>(animatableLocalStyles);const ANIMATABLE_TEXT_UNIT_STYLES = new Set(["-webkit-text-fill-color",diff --git a/packages/preview-mock/package.json b/packages/preview-mock/package.jsonindex 94710154..126d6da3 100644--- a/packages/preview-mock/package.json+++ b/packages/preview-mock/package.json@@ -10,6 +10,7 @@"@hypit/artifact": "workspace:*","@hypit/artifact-store-fs": "workspace:*","@hypit/compiler-node": "workspace:*",+ "@hypit/estimate": "workspace:*","@hypit/driver-node": "workspace:*","@hypit/mock-media": "workspace:*","@hypit/provider-media-local": "workspace:*",@@ -18,6 +19,7 @@"@hypit/media": "workspace:*","@hypit/program-space": "workspace:*","@hypit/speech": "workspace:*",+ "@hypit/text": "workspace:*","@hypit/semantic-take-estimate": "workspace:*","@hypit/workspace": "workspace:*"}diff --git a/packages/preview-mock/src/graph.ts b/packages/preview-mock/src/graph.tsindex 8de7672e..91f750c1 100644--- a/packages/preview-mock/src/graph.ts+++ b/packages/preview-mock/src/graph.ts@@ -1,9 +1,27 @@import type { CompiledGraph, Candidate, TypedRecord } from "@hypit/protocol";import { findLogicalOutput, findCandidate, findOperation } from "@hypit/compiler-node";import type { GraphValueRef, TypeRef } from "@hypit/protocol";+import { estimateSpeechDuration } from "@hypit/estimate";+import type { SpeechEstimatePolicy } from "@hypit/estimate";+import type { Text } from "@hypit/text";export type MockKind = "image" | "video" | "audio" | "semantic-take";-export type MockTarget = { readonly output: string; readonly candidate: Candidate; readonly kind: MockKind; readonly inputs: Readonly<Record<string, string>> };+export type MockTarget = { readonly output: string; readonly candidate: Candidate; readonly kind: MockKind; readonly inputs: Readonly<Record<string, string>>; readonly durationSeconds?: number };++export function estimatedProgramDurationSeconds(graph: CompiledGraph, records: readonly TypedRecord[] = []): number | undefined {+ const values: unknown[] = [+ ...records.filter((item) => sameType(item.type, "@hypit/speech", "SpeechDuration")).map((item) => item.value),+ ...graph.candidates.filter((item) => sameType(item.type, "@hypit/speech", "SpeechDuration") && item.root.kind === "value")+ .map((item) => item.root.kind === "value" ? item.root.value.value : undefined),+ ];+ const durations = values.map(inlineNumber).filter((value): value is number => value !== undefined);+ for (const operation of graph.operations) {+ if (operation.producer.module.name !== "@hypit/estimate" || operation.producer.name !== "estimate-speech-duration") continue;+ const duration = estimateOperationDuration(graph, operation, records);+ if (duration !== undefined) durations.push(duration);+ }+ return durations.length === 0 ? undefined : Math.max(...durations);+}function sameType(left: TypeRef | undefined, module: string, name: string): boolean {return left?.module.name === module && left.name === name;@@ -42,6 +60,92 @@ function logicalId(graph: CompiledGraph, ref: GraphValueRef | undefined): stringreturn candidate === undefined ? undefined : graph.outputs.find((output) => output.primary === candidate.id)?.id;}+function inlineNumber(value: unknown): number | undefined {+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;+ if (value !== null && typeof value === "object" && "value" in value) return inlineNumber((value as { value?: unknown }).value);+ return undefined;+}++function recordValue(records: readonly TypedRecord[], id: string): unknown {+ const record = records.find((item) => item.id === id);+ return record?.value.kind === "inline" ? record.value.value : undefined;+}++function inlineDuration(value: unknown): number | undefined {+ const direct = inlineNumber(value);+ if (direct !== undefined) return direct;+ if (Array.isArray(value)) {+ for (const item of value) {+ const candidate = inlineDuration(item);+ if (candidate !== undefined) return candidate;+ }+ return undefined;+ }+ if (value === null || typeof value !== "object") return undefined;+ const object = value as Record<string, unknown>;+ for (const key of ["duration", "durationSec", "durationSeconds"]) {+ const candidate = inlineNumber(object[key]);+ if (candidate !== undefined) return candidate;+ }+ const ports = object.ports;+ if (ports !== null && typeof ports === "object") {+ const candidate = inlineDuration((ports as Record<string, unknown>).duration);+ if (candidate !== undefined) return candidate;+ }+ return undefined;+}++function operationRecordRefs(graph: CompiledGraph, operation: ReturnType<typeof findOperation>): readonly string[] {+ if (operation === undefined) return [];+ const seen = new Set<string>();+ const records = new Set<string>();+ const visit = (operationId: string): void => {+ if (seen.has(operationId)) return;+ seen.add(operationId);+ const current = findOperation(graph, operationId);+ if (current === undefined) return;+ for (const ref of Object.values(current.inputs)) {+ if (ref.kind === "record") records.add(ref.id);+ else if (ref.kind === "operation-result") visit(ref.operation);+ }+ };+ visit(operation.id);+ return [...records];+}++function estimateOperationDuration(graph: CompiledGraph, operation: ReturnType<typeof findOperation>, records: readonly TypedRecord[]): number | undefined {+ if (operation === undefined) return undefined;+ const speechRef = operation.inputs.speech;+ const policyRef = operation.inputs.policy;+ if (speechRef?.kind !== "record" || policyRef?.kind !== "record") return undefined;+ const speech = recordValue(records, speechRef.id);+ const policy = recordValue(records, policyRef.id);+ if (speech === undefined || policy === undefined || typeof speech !== "object" || typeof policy !== "object") return undefined;+ try {+ return estimateSpeechDuration(speech as Text, policy as SpeechEstimatePolicy);+ } catch {+ return undefined;+ }+}++function durationForTarget(graph: CompiledGraph, operation: ReturnType<typeof findOperation>, inputs: Readonly<Record<string, string>>, records: readonly TypedRecord[]): number | undefined {+ const durationId = inputs.duration;+ if (durationId === undefined) return undefined;+ const candidate = graph.candidates.find((item) => item.root.kind === "value" && item.root.value.id === durationId)+ ?? graph.candidates.find((item) => graph.outputs.some((output) => output.id === durationId && output.primary === item.id));+ if (candidate?.root.kind === "value") return inlineDuration(candidate.root.value.value);+ // Some compilers retain the duration as an operation result candidate. Resolve the referenced+ // operation's value when it was already evaluated deterministically; never consult reference media.+ const operationId = operation?.inputs.duration?.kind === "operation-result" ? operation.inputs.duration.operation : undefined;+ const estimated = operationId === undefined ? undefined : estimateOperationDuration(graph, findOperation(graph, operationId), records);+ if (estimated !== undefined) return estimated;+ for (const id of operationRecordRefs(graph, operation)) {+ const duration = inlineDuration(recordValue(records, id));+ if (duration !== undefined) return duration;+ }+ return undefined;+}+function mockInputs(graph: CompiledGraph, kind: MockKind, operation: ReturnType<typeof findOperation>, records: readonly TypedRecord[] = []): Readonly<Record<string, string>> {const refs = operation?.inputs ?? {};const byName = (name: string): string | undefined => logicalId(graph, refs[name]!);@@ -130,7 +234,11 @@ export function findMockTargets(graph: CompiledGraph, targets?: readonly string[: name.includes("audio") || name.includes("speech") || name.includes("tts") || name.includes("wav") ? "audio" : undefined;}const operation = candidate.root.kind === "operation" ? findOperation(graph, candidate.root.result.operation) : undefined;- if (resolved !== undefined) result.push({ output: id, candidate, kind: resolved, inputs: mockInputs(graph, resolved, operation, records) });+ if (resolved !== undefined) {+ const inputs = mockInputs(graph, resolved, operation, records);+ const durationSeconds = resolved === "video" ? durationForTarget(graph, operation, inputs, records) : undefined;+ result.push({ output: id, candidate, kind: resolved, inputs, ...(durationSeconds === undefined ? {} : { durationSeconds }) });+ }}return result;}diff --git a/packages/preview-mock/src/realizer.ts b/packages/preview-mock/src/realizer.tsindex eed58f96..1e82e0d9 100644--- a/packages/preview-mock/src/realizer.ts+++ b/packages/preview-mock/src/realizer.ts@@ -3,7 +3,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";import { dirname, join, relative, resolve } from "node:path";import type { ArtifactAttachment } from "@hypit/workspace";import type { CompiledGraph, TypedRecord } from "@hypit/protocol";-import { findMockTargets } from "./graph.js";+import { estimatedProgramDurationSeconds, findMockTargets } from "./graph.js";import { deriveGeometry } from "./geometry.js";import { previewRunSource } from "./run-source.js";import { materializeMockNeed } from "./materialize.js";@@ -44,6 +44,7 @@ export async function realizePreviewMock(input: PreviewMockRequest): Promise<Pre}const alias = (ref: string): string => input.aliases?.get(ref) ?? ref;const rawTargets = findMockTargets(input.graph, input.targets, input.records);+ const fallbackDurationSeconds = estimatedProgramDurationSeconds(input.graph, input.records);const targets = rawTargets.map((target) => ({...target,output: alias(target.output),@@ -95,11 +96,17 @@ export async function realizePreviewMock(input: PreviewMockRequest): Promise<Preconst constraints = target.kind === "image"? { width: geometry.width, height: geometry.height, color: "#9AA0A6" }: target.kind === "video"- // A mock video needs enough frames for the estimate-timed SemanticTake- // to place every token. The real duration remains owned by the graph;- // this conservative preview domain avoids squeezing long Scripts into- // the old 30-frame placeholder.- ? { width: geometry.width, height: geometry.height, frameRate: { numerator: 30, denominator: 1 }, frameCount: 300, color: "#9AA0A6", audio: "silence" }+ // The mock video domain follows the deterministic SpeechDuration carried by this target.+ // It must not invent a ten-second clock per Segment: SemanticTake owns the estimate timing+ // and the generated preview material only needs enough frames for that estimate.+ ? {+ width: geometry.width,+ height: geometry.height,+ frameRate: { numerator: 30, denominator: 1 },+ frameCount: Math.max(1, Math.ceil((target.durationSeconds ?? fallbackDurationSeconds ?? 1) * 30)),+ color: "#9AA0A6",+ audio: "silence",+ }: { sampleRate: 48_000, channels: 2, sampleFrames: 48_000 };const materialized = await materializeMockNeed({ capability, constraints, artifacts: artifactStore });if (!attached.has(materialized.artifact.digest)) {diff --git a/packages/reference-video-tools/src/authoring.ts b/packages/reference-video-tools/src/authoring.tsindex 2be20262..ead02ad1 100644--- a/packages/reference-video-tools/src/authoring.ts+++ b/packages/reference-video-tools/src/authoring.ts@@ -498,6 +498,8 @@ export type RenderElementInput = {* preview timing, which is always the Source's own `estimate:Speech` policy.*/readonly reference_id?: string;+ /** Optional workspace root used by package-owned preview Sources. */+ readonly package_root?: string;};/** Timing metadata recorded beside one render, per Segment. */@@ -552,11 +554,14 @@ export async function renderElement(input: RenderElementInput): Promise<Record<sconst run = input.run;const cwd = invokedFrom();const runPath = resolve(cwd, run);- const projectRoot = dirname(runPath);+ 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 = nearestPackageRoot(projectRoot) ?? repositoryRoot();+ 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@@ -569,7 +574,7 @@ export async function renderElement(input: RenderElementInput): Promise<Record<sassert(runSource !== undefined, `cannot read ${runPath}`);const author = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];assert(author !== undefined, `${run} declares no <author source="…"/>`);- const svmlPath = resolve(projectRoot, author);+ const svmlPath = resolve(runRoot, author);let svml = await readFile(svmlPath, "utf8").catch(() => undefined);assert(svml !== undefined, `cannot read ${svmlPath}`);@@ -706,8 +711,8 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s// `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 is the path packages/hyperframes/test/browser-visual.test.ts- // takes; nothing here is a private renderer.+ // 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>();@@ -851,7 +856,13 @@ export async function renderPreviews(input: RenderPreviewsInput): Promise<Record`${directory} promises ${picture} but its preview Source places no <${alias}:${tag}> to draw it from`);const out = join(previewDir, picture);try {- await renderElement({ run, element, out });+ // Resolve the package from its workspace root rather than requiring a self-link under+ // packages/<slug>/node_modules. The preview Run still lives inside the package directory;+ // only dependency discovery needs the parent workspace.+ // The resolver root is the project/workspace containing `packages/`, not that directory+ // itself. Keeping this explicit also lets the canonical fixture render without a+ // package-manager self-link under the package it is previewing.+ await renderElement({ run, element, out, package_root: dirname(dirname(packageDir)) });} catch (error) {throw new Error(`${directory} could not draw ${picture}: ${error instanceof Error ? error.message : String(error)}`);}diff --git a/packages/reference-video-tools/src/checks.ts b/packages/reference-video-tools/src/checks.tsindex 81ff6e61..ae8aa01d 100644--- a/packages/reference-video-tools/src/checks.ts+++ b/packages/reference-video-tools/src/checks.ts@@ -4,7 +4,7 @@ import { dirname, join, resolve, sep } from "node:path";import { markupSurfaceHostFacetAbi } from "@hypit/markup";import type { RegisteredSurface } from "@hypit/markup";-import { loadNodePackageSelection } from "@hypit/package-loader-node";+import { loadNodePackageSelection, physicalPackageName } from "@hypit/package-loader-node";import { parseScript, validateCaptionCueLengths } from "@hypit/script";import { videoCliDistribution } from "@hypit/video-cli";import { loadStudioCompanionRegistry } from "@hypit/studio/src/companion-profile.js";@@ -782,6 +782,11 @@ export async function authoringCheck(// Which of their Surfaces draw a Track. A Style Surface publishes a Style and draws nothing, so// requiring a comparison of it would be asking for a picture that does not exist.const specifiers = [...new Set(imports.map((item) => item.specifier))];+ // Logical submodules (for example @hypit/gpt-image/clean) are aliases owned by the+ // physical package (@hypit/gpt-image). Load the physical owner, but retain the logical+ // spelling for Source diagnostics and map drawing tags back to that owner.+ const physicalByLogical = new Map(specifiers.map((specifier) => [specifier, physicalPackageName(specifier)] as const));+ const physicalSpecifiers = [...new Set(specifiers.map((specifier) => physicalByLogical.get(specifier)!))];// One unresolvable package used to take the rest with it: the whole selection loads or none of it// does, and a swallowed failure left `drawingTags` empty, so every element in the Source read as// drawing nothing and the check passed on an empty answer. Fall back to loading them one at a time so@@ -792,10 +797,10 @@ export async function authoringCheck(// with nowhere to resolve from, so a project whose Source imports the standard vocabulary reports// every one of those imports as a package that does not exist.const loading = { ...(distributionPackageRoot === undefined ? {} : { fallbackRoots: [distributionPackageRoot] }) };- const loaded = await loadNodePackageSelection(specifiers, packageRoot, loading).catch(async () => {- const each = await Promise.all(specifiers.map(async (specifier) =>+ const loaded = await loadNodePackageSelection(physicalSpecifiers, packageRoot, loading).catch(async () => {+ const each = await Promise.all(physicalSpecifiers.map(async (specifier) =>await loadNodePackageSelection([specifier], packageRoot, loading).catch(() => {- unresolved.push(specifier);+ unresolved.push(...specifiers.filter((logical) => physicalByLogical.get(logical) === specifier));return [];})));return each.flat();@@ -814,11 +819,12 @@ export async function authoringCheck(// Every use of one of those tags, by the id the Source gave it.const drawn: { readonly id: string; readonly tag: string; readonly alias: string; readonly specifier: string }[] = [];for (const { alias, specifier } of imports) {+ const physical = physicalByLogical.get(specifier) ?? specifier;const pattern = new RegExp(`<${alias}:([A-Za-z][A-Za-z0-9]*)\\b[^>]*?\\bid="([^"]+)"`, "gu");for (const match of svml.matchAll(pattern)) {const tag = match[1] ?? "";const id = match[2] ?? "";- if (!drawingTags.has(`${specifier}#${tag}`)) continue;+ if (!drawingTags.has(`${physical}#${tag}`)) continue;if (!drawn.some((item) => item.id === id)) drawn.push({ id, tag, alias, specifier });}}@@ -1325,7 +1331,11 @@ export async function authoringCheck(// and that is written rather than derived....(owed.length === 0 || mode !== "reconstruction" ? {} : {comparisons: owed.map((entry) => ({- run: runPath, tokens: entry.tokens, video_path: entry.out, element: entry.element,+ run: runPath,+ tokens: entry.tokens,+ video_path: entry.out,+ element: entry.element,+ question: "Ignore flat preview-mock regions standing in for declared-but-unbuilt media; compare authored layout, typography, motion and timing only.",})),}),// Where this command actually read and resolved from. Said here, no document has to describe it@@ -1475,7 +1485,7 @@ export async function authoringCheck(}),playback: running,...(running.length === 0 ? {} : {- playback_next: "A generated take is ordered in whole seconds and its window is measured from speech the "+ 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 "+ "Build has yet to synthesize, so the material is shorter than the window it fills more "+ "often than not. Under a full-frame picture the remainder is the Film background, which "+ "reads as a black gap; under a cutaway it is the layer beneath blinking through.\n\n"diff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.tsindex 0e8eeebf..8d1deaed 100644--- a/packages/reference-video-tools/src/cli.ts+++ b/packages/reference-video-tools/src/cli.ts@@ -42,8 +42,8 @@ function usage(): string {" hypit-reference-video-tools validate_script_cues --run <build.svrun>"," hypit-reference-video-tools inspect_visual_contract [--shape visual-track|text-flow|text-typography|text-paint|text-document|path-command] [--producers-of <package> ...]"," hypit-reference-video-tools paths",- " hypit-reference-video-tools compare_reconstruction --reference-id <id> --run <build.svrun> --segment <id>|--selection <id>|--tokens <from:to> --video <path>|--image <path> [--question <scope>] [--element <id>]",- " hypit-reference-video-tools compare_reconstruction --reference-id <id> --shot-id <id> --video <path>|--image <path> [--question <scope>] [--element <id>]",+ " hypit-reference-video-tools compare_reconstruction --reference-id <id> --run <build.svrun> --segment <id>|--selection <id>|--tokens <from:to> --video <path>|--image <path> [--question <scope>] [--element <id>] [--tolerance-frames <n>]",+ " hypit-reference-video-tools compare_reconstruction --reference-id <id> --shot-id <id> --video <path>|--image <path> [--question <scope>] [--element <id>] [--tolerance-frames <n>]"," hypit-reference-video-tools compare_reconstruction --reference-id <id> --batch <comparisons.json>"," hypit-reference-video-tools review_element --run <build.svrun> --element <id> --segment <id>|--selection <id>|--tokens <from:to> --video <path>|--image <path> --intent-file <path> [--question <scope>]"," hypit-reference-video-tools review_element --run <build.svrun> --batch <reviews.json>",@@ -174,15 +174,17 @@ function usage(): string {"file — since that observer reads pictures and the words are the only record of when speech happens.","","inspect_visual_contract answers what a Producer that draws may return: the element kinds, the style",- "names admitted on them, which take an enum, and how few keyframes an animation carries. Every line is",+ "names admitted on them, which take an enum, the only local styles allowed in keyframes",+ "(clip-path, filter, opacity and transform), and how few keyframes an animation carries. Every line is","generated from the Composition schema, so it says what the seal will accept rather than what one","package happened to do. inspect_svml_vocabulary answers the other half — what a Source may write.","","paths reports where this command reads reference state and resolves packages from, and which","references are prepared. Use it when a check reports something it cannot see.","",- "--package-root <dir> is where the packages a Source imports are resolved from, and it is accepted by",- "every command. It defaults to the working directory. A project that declares a vocabulary gap and",+ "--package-root <dir> is where the project packages a Source imports are resolved from, and it is",+ "accepted by every command. It defaults to the working directory and never replaces the active",+ "Hypit Distribution root, which remains an independent fallback for @hypit/* packages. A project that declares a vocabulary gap and","fills it publishes those packages under its own scope and installs them against the project root, so","run these commands from the project directory or name it here: resolved from anywhere else, the","project's own packages are not found, and reconstruction_check reports them under",@@ -280,7 +282,9 @@ async function main(): Promise<void> {// against the project root, so a root taken from anywhere else resolves none of them: --package-root// is how a command run from elsewhere reaches them. HYPIT_DISTRIBUTION_ROOT names an installed// Distribution and is the fallback for the installed packages a project does not carry.- const resolveFrom = one(flags, "package-root") ?? process.env.HYPIT_DISTRIBUTION_ROOT;+ // --package-root selects only the project/source package root. The active Distribution root is+ // discovered independently by video-cli and is always supplied as a loader fallback.+ const resolveFrom = one(flags, "package-root");const tools = createReferenceVideoTools({...(resolveFrom === undefined ? {} : { packageRoot: resolveFrom }),});@@ -509,8 +513,9 @@ async function main(): Promise<void> {...(video === undefined ? { image_path: required(flags, "image") } : { video_path: video }),...(one(flags, "question") === undefined ? {} : { question: one(flags, "question") }),...(one(flags, "element") === undefined ? {} : { element: one(flags, "element") }),+ ...(one(flags, "tolerance-frames") === undefined ? {} : { tolerance_frames: Number(one(flags, "tolerance-frames")) }),};- result = await tools.compare_reconstruction(input as { reference_id: string; shot_id?: string; segment?: string; selection?: string; run?: string; image_path?: string; video_path?: string; question?: string; element?: string });+ result = await tools.compare_reconstruction(input as CompareReconstructionInput);} else if (command === "inspect_visual_contract") {result = await tools.inspect_visual_contract({...(one(flags, "shape") === undefined ? {} : { shape: one(flags, "shape")! }),diff --git a/packages/reference-video-tools/src/route-state.ts b/packages/reference-video-tools/src/route-state.tsindex cdbda470..a9c9d60d 100644--- a/packages/reference-video-tools/src/route-state.ts+++ b/packages/reference-video-tools/src/route-state.ts@@ -190,6 +190,13 @@ function stageNumber(route: RouteKind, name: string): number {return index + 1;}+const SCALAR_ARTIFACT_KEYS = new Set(["observer", "timing_basis", "timingBasis", "mode", "status"]);+function normalizeArtifact(projectRoot: string, key: string, value: string): string {+ // Artifact maps historically accepted strings for both file references and tiny metadata values.+ // Preserve the latter; resolving `observer: "gemini"` as a filesystem path corrupts the snapshot.+ return SCALAR_ARTIFACT_KEYS.has(key) ? value : resolve(projectRoot, value);+}+function stepNumber(route: RouteKind, step: number | RouteStep): number {if (typeof step === "number") {if (!Number.isSafeInteger(step) || step < 1 || step > ROUTE_STATE_STEPS[route].length) {@@ -271,7 +278,7 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promiseconst artifacts = input.artifacts === undefined ? existing.artifacts : {...existing.artifacts,...Object.fromEntries(- Object.entries(input.artifacts).map(([key, value]) => [key, resolve(projectRoot, value)]),+ Object.entries(input.artifacts).map(([key, value]) => [key, normalizeArtifact(projectRoot, key, value)]),),};const state: RouteState = {diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.tsindex 8c6dfcc0..56d6a7e2 100644--- a/packages/reference-video-tools/src/tools.ts+++ b/packages/reference-video-tools/src/tools.ts@@ -5,7 +5,7 @@ import { cpus } from "node:os";import { createHash } from "node:crypto";import { deflateSync } from "node:zlib";import { basename, dirname, join, resolve } from "node:path";-import { loadNodePackageSelection, locateNodePackage } from "@hypit/package-loader-node";+import { loadNodePackageSelection, locateNodePackage, physicalPackageName } from "@hypit/package-loader-node";import { markupSurfaceHostFacetAbi } from "@hypit/markup";import type { RegisteredSurface, SurfaceVocabulary } from "@hypit/markup";import { exactModelHostAbi } from "@hypit/model-kit";@@ -13,6 +13,7 @@ import type { ValueSchema } from "@hypit/protocol";import {visualPathCommandSchema, visualTextDocumentSchema, visualTextFlowSchema,visualTextPaintSchema, visualTextTypographySchema, visualTrackSchema,+ animatableLocalStyles,} from "@hypit/composition";import { describeSchema } from "./contract.js";@@ -138,6 +139,8 @@ export type CompareReconstructionInput = {* elements have been compared and which have never been looked at.*/readonly element?: string;+ /** Maximum frame-domain difference tolerated when matching the two independently encoded cuts. */+ readonly tolerance_frames?: number;/*** A whole round of comparisons, run together. Each entry names its own stretch, render and element* exactly as a single call does, and inherits `reference_id` from the outer input. The route renders@@ -789,6 +792,7 @@ function asPictures(media: readonly string[], state: ReferenceState): readonly sconst TILE_PREAMBLE = "Each supplied picture that shows a grid of frames is one shot, sampled evenly"+ " across its duration and laid out in reading order: left to right, then top to bottom. Read the"+ " grid as time passing. A single picture that is not a grid is one moment.";+const WATERMARK_RULE = "If a visible mark is clearly a platform UI, player chrome, export-tool or editing-software watermark/overlay rather than authored video content, ignore it and do not report it as a difference or repair target. If its provenance is uncertain or it may be an authored design element, keep it as an uncertainty instead of silently ignoring it.";// There is no second source of sound to fall back to, so this says how to answer from what there is// rather than leaving the observation short. The transcript settles when speech happens; the picture// settles who is on screen while it does. Read together they carry the question far enough to answer.@@ -978,6 +982,7 @@ async function cutWordRange(renderedPath: string,clip: boolean,slot: string,+ toleranceFrames = 3,): Promise<RangeCut> {const cuts = referenceCuts(state);const head = cuts.find((at) => at >= range.first.startSeconds && at < range.first.endSeconds);@@ -1022,7 +1027,7 @@ async function cutWordRange(// rounded up to a whole audio frame — 1024 samples, so 21ms at 48kHz — which neither side's frame// grid divides. Three frames covers both; anything larger is the cut disagreeing with the render// about which words the stretch holds.- const slack = 3 / drawn.frameRate;+ const slack = toleranceFrames / drawn.frameRate;assert(Math.abs(referenceSeconds - renderedSeconds) <= slack,`the cut reference runs ${round(referenceSeconds)}s and the trimmed render ${round(renderedSeconds)}s, `+ `which is more than ${round(slack)}s apart; they must cover the same stretch`);@@ -1108,6 +1113,12 @@ function publicPrepare(state: ReferenceState): PrepareResult {export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVideoTools {const packageRoot = resolve(options.packageRoot ?? process.cwd());+ // Project-owned packages and the active Distribution are separate roots. A project may import+ // @hypit modules without installing or linking them locally; every direct inspection path must+ // therefore carry the same Distribution fallback used by the compiler/Studio loaders.+ const packageLoading = () => videoCliDistribution.packageRoot === undefined+ ? {}+ : { fallbackRoots: [videoCliDistribution.packageRoot] };async function validateLocalAuthorPackages(input: ValidateLocalAuthorPackagesInput): Promise<Record<string, unknown>> {const runPath = resolve(invokedFrom(), input.run);@@ -1124,11 +1135,28 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVconst loading = distributionPackageRoot === undefined ? {} : { fallbackRoots: [distributionPackageRoot] };const runSource = await readFile(runPath, "utf8").catch(() => "");const authorSourcePath = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];- const authorSource = authorSourcePath === undefined ? "" : await readFile(resolve(dirname(runPath), authorSourcePath), "utf8").catch(() => "");- const imported = new Set([- ...[...runSource.matchAll(/\bfrom="([^"]+)@\d+"/gu)].map((match) => match[1]!),- ...[...authorSource.matchAll(/\bfrom="([^"]+)@\d+"/gu)].map((match) => match[1]!),- ]);+ const authorFile = authorSourcePath === undefined ? undefined : resolve(dirname(runPath), authorSourcePath);+ const imported = new Set<string>();+ const visitedSources = new Set<string>();+ const collectSourceClosure = async (file: string): Promise<void> => {+ const absolute = resolve(file);+ if (visitedSources.has(absolute)) return;+ visitedSources.add(absolute);+ const source = await readFile(absolute, "utf8").catch(() => "");+ for (const match of source.matchAll(/\bfrom="([^"]+)@\d+"/gu)) {+ const specifier = match[1]!;+ if (specifier.startsWith("@")) imported.add(specifier);+ }+ // Author/Recipe/Run child Sources use `source=`, while package imports use `from=`. Walk only+ // local files so package declarations remain data and cannot escape the project root.+ for (const match of source.matchAll(/\bsource="([^"#]+)"/gu)) {+ const child = match[1]!;+ if (child.startsWith("@") || child.startsWith("http://") || child.startsWith("https://")) continue;+ await collectSourceClosure(resolve(dirname(absolute), child));+ }+ };+ await collectSourceClosure(runPath);+ if (authorFile !== undefined) await collectSourceClosure(authorFile);let graphModules = new Set<string>();try {if (distributionPackageRoot !== undefined) {@@ -1159,12 +1187,14 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVconst contribution = loaded[0]?.contribution;const modules = contribution?.modules ?? [];const surfaces = (contribution?.hostFacets ?? []).filter((facet) => facet.abi === markupSurfaceHostFacetAbi);- const fragments = (contribution?.hostFacets ?? []).filter((facet) => facet.abi === "hypit.run-fragment-host@1");+ // Author packages expand Markup Surfaces into Graph Fragments; they do not need the separate+ // run-fragment host facet used by preview/mock replacement packages.+ const runFragmentFacets = (contribution?.hostFacets ?? []).filter((facet) => facet.abi === "hypit.run-fragment-host@1");const producers = modules.flatMap((module) => module.manifest.producers);- const fragmentValues = fragments.flatMap((facet) => Object.values((facet.implementation as { fragments?: Record<string, { operations?: readonly unknown[]; exports?: readonly unknown[] }> }).fragments ?? {}));+ const fragmentValues = runFragmentFacets.flatMap((facet) => Object.values((facet.implementation as { fragments?: Record<string, { operations?: readonly unknown[]; exports?: readonly unknown[] }> }).fragments ?? {}));if (surfaces.length === 0) errors.push("PACKAGE_NO_SURFACE");if (producers.length === 0) errors.push("PACKAGE_NO_PRODUCER");- if (fragments.length === 0 || fragmentValues.every((fragment) => (fragment.operations?.length ?? 0) === 0 || (fragment.exports?.length ?? 0) === 0)) errors.push("PACKAGE_NO_FRAGMENT");+ if (runFragmentFacets.length > 0 && fragmentValues.every((fragment) => (fragment.operations?.length ?? 0) === 0 || (fragment.exports?.length ?? 0) === 0)) errors.push("PACKAGE_NO_FRAGMENT");const declaredProducers = new Set(modules.flatMap((module) => module.manifest.producers.map((producer) => `${module.manifest.name}@${module.manifest.version}#${producer.name}`)));for (const fragment of fragmentValues) {for (const operation of fragment.operations ?? []) {@@ -1183,11 +1213,11 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVerrors.push("PACKAGE_SURFACE_INVALID");}}- const sourceImported = imported.has(specifier);+ const sourceImported = imported.has(specifier) || [...imported].some((name) => physicalPackageName(name) === specifier);const graphUsed = modules.some((module) => graphModules.has(`${module.manifest.name}@${module.manifest.version}`));if (!sourceImported) errors.push("PACKAGE_NOT_IMPORTED");else if (!graphUsed) errors.push("PACKAGE_IMPORTED_BUT_UNUSED");- results.push({ specifier, manifest: modules.length > 0, surfaces: surfaces.length, producers: producers.length, fragments: fragmentValues.length, source_imported: sourceImported, source_used: graphUsed, graph_used: graphUsed, status: errors.length === 0 ? "passed" : "failed", ...(errors.length === 0 ? {} : { errors }) });+ results.push({ specifier, manifest: modules.length > 0, surfaces: surfaces.length, producers: producers.length, fragments: fragmentValues.length, run_fragment_facets: runFragmentFacets.length, source_imported: sourceImported, source_used: graphUsed, graph_used: graphUsed, status: errors.length === 0 ? "passed" : "failed", ...(errors.length === 0 ? {} : { errors }) });}for (const specifier of expected) {if (!results.some((item) => item.specifier === specifier)) results.push({ specifier, status: "failed", errors: ["PACKAGE_EXPECTED_BUT_MISSING"] });@@ -1270,7 +1300,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV.filter((word) => shots.some((shot) => word.endSeconds > shot.start_seconds && word.startSeconds < shot.end_seconds)).map((word) => word.text).join(" ");pending.push({- key, instruction, prompt: [...parts, prompt].join("\n\n"), image_refs: asPictures(media, state),+ key, instruction, prompt: [...parts, prompt, WATERMARK_RULE].join("\n\n"), image_refs: asPictures(media, state),...(sound === true && words.length > 0 ? { transcript_ref: transcriptRef } : {}),...(spoken.length === 0 ? {} : { transcript_words: spoken }),record_with: `record_observation --reference-id ${state.reference_id} --key ${key} --text-file <the answer>`,@@ -1286,7 +1316,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVask: async (_key, { media, prompt, instruction }) => {const parts: Part[] = [];for (const path of media) parts.push(await mediaPart(path));- parts.push({ text: prompt });+ parts.push({ text: `${prompt}\n\n${WATERMARK_RULE}` });return await callSafely(retryDelayMs, generate, parts, instruction);},};@@ -1343,7 +1373,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVconst models: string[] = [];let note: string | undefined;try {- for (const pack of await loadNodePackageSelection([specifier], packageRoot)) {+ for (const pack of await loadNodePackageSelection([specifier], packageRoot, packageLoading())) {for (const facet of pack.contribution.hostFacets ?? []) {if (facet.abi === markupSurfaceHostFacetAbi) {tags.push((facet.implementation as RegisteredSurface).tag);@@ -1721,7 +1751,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVasync inspect_svml_vocabulary(input): Promise<Record<string, unknown>> {assert(input.package_names.length > 0, "package_names must not be empty");- const loaded = await loadNodePackageSelection(input.package_names, packageRoot);+ const loaded = await loadNodePackageSelection(input.package_names, packageRoot, packageLoading());const requested = input.tags === undefined ? undefined : new Set(input.tags);// The answer is about the packages that were named. Loading one brings its dependencies with// it, and every one of their Surfaces used to be returned as well — asking what `@hypit/ranking`@@ -1743,7 +1773,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVmode: implementation.mode,outputs: implementation.outputs,vocabulary: vocabularyForResult(input.include_previews === false ? withoutPreview(implementation.vocabulary) : implementation.vocabulary),- readme_path: readmePath(pack.specifier, packageRoot),+ readme_path: readmePath(pack.specifier, packageRoot, packageLoading()),});}}@@ -1808,7 +1838,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV// component's Fragment names one per operation, and the names were reachable only by opening a// package that already called them.const wanted = input.producers ?? [];- const calls = wanted.length === 0 ? [] : (await loadNodePackageSelection(wanted, packageRoot).catch(() => []))+ const calls = wanted.length === 0 ? [] : (await loadNodePackageSelection(wanted, packageRoot, packageLoading()).catch(() => [])).flatMap((pack) => (pack.contribution.modules ?? []).flatMap((module) =>module.manifest.producers.map((producer) => ({module: `${module.manifest.name}@${module.manifest.version}`,@@ -1819,6 +1849,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV}))));return {shapes: chosen.map((name) => ({ shape: name, describes: describeSchema(shapes[name]!).join("\n") })),+ animatable_local_styles: [...animatableLocalStyles],...(calls.length === 0 ? {} : { producers: calls }),// Each of these is refused somewhere, or follows from how the emitted CSS is written. None is// a convention: a rule stated here that the code does not hold would be worse than silence.@@ -1912,7 +1943,9 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV...(input.tokens === undefined ? {} : { tokens: input.tokens }),};const range = await spokenRange(svmlPath, focus, await referenceWords(state.reference_id));- cut = await cutWordRange(state, root, focus, range, renderedPath, clip, slot);+ const toleranceFrames = input.tolerance_frames ?? 3;+ assert(Number.isSafeInteger(toleranceFrames) && toleranceFrames >= 0, "tolerance_frames must be a non-negative integer");+ cut = await cutWordRange(state, root, focus, range, renderedPath, clip, slot, toleranceFrames);referenceMedia = cut.reference;renderedMedia = cut.rendered;stretchSeconds = cut.seconds;@@ -1949,7 +1982,9 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV// `cutWordRange`; this is the path that had no check at all.if (asClip && shot !== undefined) {const drawn = await probe(renderedPath);- const slack = drawn.frameRate > 0 ? 3 / drawn.frameRate : 0.1;+ const toleranceFrames = input.tolerance_frames ?? 3;+ assert(Number.isSafeInteger(toleranceFrames) && toleranceFrames >= 0, "tolerance_frames must be a non-negative integer");+ const slack = drawn.frameRate > 0 ? toleranceFrames / drawn.frameRate : 0.1;assert(Math.abs(drawn.duration - shot.duration_seconds) <= slack,`shot ${shot.shot_id} runs ${round(shot.duration_seconds)}s and the render ${round(drawn.duration)}s, `+ `which is more than ${round(slack)}s apart; the two sides would cover different amounts of the video`);@@ -2471,11 +2506,16 @@ function withoutPreview(value: SurfaceVocabulary | undefined): SurfaceVocabularyreturn rest;}-function readmePath(specifier: string, root: string): string | undefined {+function readmePath(+ specifier: string,+ root: string,+ loading: Parameters<typeof loadNodePackageSelection>[2] = {},+): string | undefined {try {const located = locateNodePackage(specifier, {from: join(root, "__hypit_reference_tools__.mjs"),workspaceRoots: [root],+ ...(loading.fallbackRoots === undefined ? {} : { distributionRoots: loading.fallbackRoots }),});return join(located.root, "README.md");} catch { return undefined; }diff --git a/packages/reference-video-tools/test/tools.test.ts b/packages/reference-video-tools/test/tools.test.tsindex 40a8dc3c..23da1ded 100644--- a/packages/reference-video-tools/test/tools.test.ts+++ b/packages/reference-video-tools/test/tools.test.ts@@ -163,7 +163,8 @@ test("a narrow question costs one call, answers from the named shots and is answassert.equal(calls.length, 1);assert.deepEqual(calls[0]!.mimeTypes, ["video/mp4", "image/jpeg"]);- assert.equal(calls[0]!.text, "How thick is the caption outline?");+ assert.match(calls[0]!.text, /^How thick is the caption outline\?/u);+ assert.match(calls[0]!.text, /platform UI|editing-software watermark/u);assert.deepEqual(result["shot_ids"], ["shot-003"]);assert.deepEqual(result["result"], { status: "complete", text: "the caption sits above the lower edge" });assert.deepEqual(result["answer"], result["result"], "answer remains only as a compatibility alias");@@ -218,7 +219,7 @@ test("reconstruction comparison sends an unlabelled pair and accepts rendered PNassert.match(calls[0]!.text, /geometry pass/u);assert.match(calls[0]!.text, /outer frame/u);assert.match(calls[0]!.text, /overflow/u);- assert.doesNotMatch(calls[0]!.text, /reconstruction|rendered|generated|authored|component|SVML/iu,+ assert.doesNotMatch(calls[0]!.text, /reconstruction|rendered|generated|component|SVML/iu,"the comparison must never say which image was built or how");assert.match(calls[0]!.instruction, /You are not told how either was made/u);assert.deepEqual(result["differences"], { status: "complete", text: "the list starts lower in one image" });diff --git a/packages/script/src/cue-lint.ts b/packages/script/src/cue-lint.tsindex a0eb2090..5b6acb70 100644--- a/packages/script/src/cue-lint.ts+++ b/packages/script/src/cue-lint.ts@@ -26,6 +26,7 @@ export function validateCaptionCueLengths(let cueWords = 0;let cueStart = 0;let cueOrdinal = 1;+ let cueSegment = document.units[0]?.segmentId;const flush = (endExclusive: number): void => {if (cueWords <= maxWords || document.units.length === 0) return;const first = document.units[cueStart];@@ -47,6 +48,14 @@ export function validateCaptionCueLengths(};for (let index = 0; index < document.units.length; index += 1) {const unit = document.units[index]!;+ if (cueSegment !== undefined && unit.segmentId !== cueSegment) {+ // Segment close is an implicit hard boundary. Diagnostics are numbered within the+ // Segment that owns the Cue, rather than carrying an ordinal across independent takes.+ cueWords = 0;+ cueStart = index;+ cueOrdinal = 1;+ cueSegment = unit.segmentId;+ }cueWords += unit.wordIds.length;if (breaks.has(unit.id)) {flush(index + 1);diff --git a/packages/script/src/narrative.ts b/packages/script/src/narrative.tsindex dca3fa93..a5ad449c 100644--- a/packages/script/src/narrative.ts+++ b/packages/script/src/narrative.ts@@ -89,7 +89,22 @@ function projectCaption(parsed: ParsedNarrative, id: string, narrativeId: string}return { afterUnitId: previous.id };});- return { narrativeId, id, units, words, cueBreaks };+ // Segment close is a hard cue boundary. A cue cannot carry words across two+ // independent speech takes even when the author omitted an explicit `||`.+ // Keep explicit breaks, but de-duplicate the boundary when `||` was placed+ // immediately before `</segment>`.+ const breaks = new Set(cueBreaks.map((item) => item.afterUnitId));+ for (let index = 0; index < units.length - 1; index += 1) {+ if (units[index]!.segmentId === units[index + 1]!.segmentId) continue;+ breaks.add(units[index]!.id);+ }+ return {+ narrativeId,+ id,+ units,+ words,+ cueBreaks: units.filter((unit) => breaks.has(unit.id)).map((unit) => ({ afterUnitId: unit.id })),+ };}export function captionDocument(parsed: ParsedNarrative, id: string, narrativeId: string): CaptionDocument {diff --git a/packages/script/test/cue-lint.test.ts b/packages/script/test/cue-lint.test.tsindex 6bd38972..9695fdad 100644--- a/packages/script/test/cue-lint.test.ts+++ b/packages/script/test/cue-lint.test.ts@@ -20,3 +20,8 @@ test("Cue lint counts visible Dual Text words and respects authored breaks", ()const dual = validateCaptionCueLengths(parsed("<one><one two three four five | uno dos tres cuatro cinco></one>"));assert.equal(dual[0]?.wordCount, 5);});++test("Segment boundaries are hard Cue boundaries", () => {+ const violations = validateCaptionCueLengths(parsed("<one>one two three</one><two>four five</two>"));+ assert.equal(violations.length, 0);+});diff --git a/packages/seedance/src/index.ts b/packages/seedance/src/index.tsindex df337273..a62671fa 100644--- a/packages/seedance/src/index.ts+++ b/packages/seedance/src/index.ts@@ -148,9 +148,22 @@ export function compileSeedanceDurationRequestDraft(): GenerationRequestDraft {verifySeedanceDurationProgram(program);assertSpeechDurationIdentity(duration);+ // Speech estimation and paid video generation have different clocks. A short spoken Segment+ // (including fractional seconds) must remain short for SemanticTake alignment, while the remote+ // model still requires an integer duration inside its declared range. Clamp only the generation+ // request to that legal range; never rewrite the speech estimate itself.+ const durationPort = seedancePorts[program.model].ports.find((port) => port.name === "duration");+ const legalDuration = durationPort?.value.kind === "number"+ ? Math.min(durationPort.value.maximum ?? Number.MAX_SAFE_INTEGER, Math.max(durationPort.value.minimum ?? 0, Math.ceil(duration)))+ : durationPort?.value.kind === "enum"+ ? (() => {+ const allowed = durationPort.value.values.filter((value): value is number => typeof value === "number" && value >= 0);+ return allowed.find((value) => value >= duration) ?? Math.max(...allowed);+ })()+ : Math.ceil(duration);return sealGenerationRequestDraft(seedancePorts[program.model], {...program.ports,- duration: [duration],+ duration: [Number.isFinite(legalDuration) ? legalDuration : Math.ceil(duration)],});}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0ee2e9c0..5bda5174 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -510,6 +510,9 @@ importers:'@hypit/compiler-node':specifier: workspace:*version: link:../compiler-node+ '@hypit/estimate':+ specifier: workspace:*+ version: link:../estimate'@hypit/elaborator':specifier: workspace:*version: link:../elaborator@@ -703,6 +706,9 @@ importers:'@hypit/speech':specifier: workspace:*version: link:../speech+ '@hypit/text':+ specifier: workspace:*+ version: link:../text'@hypit/speech-evidence':specifier: workspace:*version: link:../speech-evidence