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
feat: enforce package and cue gates in routes
rponec681636ba764
diff --git a/.agents/skills/hypit/SKILL.md b/.agents/skills/hypit/SKILL.mdindex 22ce0e4d..0b1dc772 100644--- a/.agents/skills/hypit/SKILL.md+++ b/.agents/skills/hypit/SKILL.md@@ -28,12 +28,25 @@ names the files it needs; read those when you reach that step rather than all ofKeep `.svml` Author Source, `.svs` Recipe Source, `.svrun` Run Source, and`hypit.runtime.json` Runtime Profile as separate languages and responsibilities.+Non-negotiable Script rule: every captioned or on-screen spoken passage must be split into short,+complete Cues with `||` in the Script. As the default, cut after roughly 3–4 spoken words (fewer when+the words are long or visually dense); longer runs require an explicit visual reason. Never rely on+renderer line wrapping or a wide Caption box to rescue a long Segment: a Segment without `||` is one+Cue and will overflow the Canvas. Read+`references/script-time.md` and the caption craft before writing Script text; put breaks between+complete Alignment Units, never inside Dual Text.+Every route is resumable. At the start of a route, create the project's`.hypit/route-state.json`; after any new turn, interruption, or context compaction, read`references/recovery.md`, inspect that snapshot and reconcile it against the artifacts and checksbefore continuing. Never resume from chat memory alone, and never repeat a completed or paid stepwithout verifying its durable evidence.+Before Source is accepted, every route must complete persisted vocabulary inspection,+`validate_local_author_packages` for every `packages/local-*` package, and+`validate_script_cues` (maximum four visible words per Cue). `preview_check` and the route's final+check repeat these gates even if route-state claims they were completed.+Do not create or hand-author SVG images anywhere in an author project or project-local package.This includes `.svg` assets, inline `<svg>` markup, and SVG data URLs.diff --git a/.agents/skills/hypit/references/authoring.md b/.agents/skills/hypit/references/authoring.mdindex 4247c423..eb6c9d0f 100644--- a/.agents/skills/hypit/references/authoring.md+++ b/.agents/skills/hypit/references/authoring.md@@ -17,6 +17,10 @@ Install dependencies after package selections change. Validate with one command:hypit-reference-video-tools preview_check path/to/project/build.svrun```+Before that command, persist vocabulary inspection and run `validate_local_author_packages --run`+and `validate_script_cues --run`. Local packages must have real Surface/Producer/Fragment exports and+be used by the compiled Graph; every caption Cue must be four or fewer visible words.+It checks every Source the Run reaches before it proves the graph traces — the Run, the Author itnames, and the Recipe sheets and kits the Author imports — then goes on to the wiring itself. One`hypit check` of the Run covers that same closure, but running it separately would only report thediff --git a/.agents/skills/hypit/references/local-author-package.md b/.agents/skills/hypit/references/local-author-package.mdindex 11f8a9ee..181557ce 100644--- a/.agents/skills/hypit/references/local-author-package.md+++ b/.agents/skills/hypit/references/local-author-package.md@@ -219,6 +219,21 @@ is expensive to read.## Install and validate+### Mechanical completion gate++Before Source can be considered authored, run:++```bash+hypit-reference-video-tools validate_local_author_packages --run <path/to/build.svrun>+```++Every project-local `packages/local-*` package 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+local package in the project.+The Host resolves the explicitly selected physical package name directly at`<project>/packages/<package-basename>/` and supplies official `@hypit/*` imports from the read-onlytool Distribution. The `@hypit/*` namespace is reserved for that active Distribution; a project usesdiff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.mdindex d60af57d..347778d7 100644--- a/.agents/skills/hypit/references/original-authoring/route.md+++ b/.agents/skills/hypit/references/original-authoring/route.md@@ -36,9 +36,11 @@ interruption or context compaction, read `../recovery.md`, run `route_state --ac| --- | --- | --- || `environment` | explicit checkpoint after Distribution, project and credentials are selected | `hypit paths --json` || `brief-frozen` | explicit checkpoint naming the frozen brief, audience, format and claims | return to the brief checkpoint |+| `vocabulary-checked` | vocabulary inspection is persisted for the Run | `inspect_svml_vocabulary --run <run>` |+| `package-ready` | every `packages/local-*` package has real Surface/Producer/Fragment and is used by the compiled Graph | `validate_local_author_packages --run <run>` |+| `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>` |-| `vocabulary-checked` | explicit checkpoint after package vocabulary is inspected and any gap is resolved | `inspect_svml_vocabulary` |-| `graph-checked` | `preview_check` returns `sound: true` | `preview_check <run>` |+| `graph-checked` | `preview_check` returns `sound: true` after package and Cue gates | `preview_check <run>` || `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` |@@ -95,6 +97,8 @@ and whether any is genuinely missing. That file states why a system nobody inspeabout to invent, and this route is where that is easiest: there is no reference to contradict you.For a proven gap, read `../local-author-package.md` completely and build the package.+Persist inspection with `inspect_svml_vocabulary --run <build.svrun>` and prove every local package+with `validate_local_author_packages --run <build.svrun>` before writing Source.### 6. Write the Script@@ -105,8 +109,13 @@ seams fall.**Read now:** `../script-time.md` — where a Segment ends, where a forced seam goes, and why eachtake's duration comes from `estimate:Speech` rather than from the duration the author asked for.+Hard layout gate: captioned speech must use `||` Cue breaks in the Script, normally every 3–4 spoken+words. A long Segment without breaks is not acceptable; it becomes one overflowing Cue.+Give every planned shot one job — hook, context, evidence, mechanism, reaction, payoff, transition,or CTA. Delete shots with no distinct job.+Run `validate_script_cues --run <build.svrun>` before `hypit check`; split every Cue longer than four+visible words with `||` between complete Alignment Units.### 7. Write the four sourcesdiff --git a/.agents/skills/hypit/references/playbooks/craft/captions.md b/.agents/skills/hypit/references/playbooks/craft/captions.mdindex 025026c0..ca342f14 100644--- a/.agents/skills/hypit/references/playbooks/craft/captions.md+++ b/.agents/skills/hypit/references/playbooks/craft/captions.md@@ -103,6 +103,13 @@ single line and runs off both edges of the frame. That is the shape to recogniseoverflows is a Segment nobody broke, not a Style whose width or size is wrong, and widening the boxor shrinking the type will not close it.+Treat roughly **3–4 spoken words per Cue as the hard default** (fewer for long words, large type, or+dense designs). A longer Cue is an explicit exception that must be justified by the reference and+verified in the rendered bounds; it is never the result of forgetting `||`.++The route's mechanical gate is stricter: `validate_script_cues --run <build.svrun>` rejects every Cue+over four visible words, including Dual Text display words. Split it with `||` between complete units.+Mark the breaks where the reference breaks. The observation for a shot says what is on screen atonce, and that is the Cue.diff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.mdindex 52a4e6d9..a5d145bf 100644--- a/.agents/skills/hypit/references/preview.md+++ b/.agents/skills/hypit/references/preview.md@@ -4,6 +4,9 @@success predicates hold. After a new turn or interruption, read `../recovery.md`, reconcile the state,and resume from its `next_action`; do not rely on chat history.+Before preview, the command repeats `validate_local_author_packages` and `validate_script_cues`; a+failed package or Cue gate is a hard refusal and cannot be hidden by a passing Graph trace.+Three ways to look at a Source before a Provider is ever reached: prove the graph traces, render oneelement to a still, and open the whole Run for a person. They answer different questions, and none ofthem costs a generation.diff --git a/.agents/skills/hypit/references/quickstart.md b/.agents/skills/hypit/references/quickstart.mdindex 44fd68dc..c2506a3d 100644--- a/.agents/skills/hypit/references/quickstart.md+++ b/.agents/skills/hypit/references/quickstart.md@@ -38,4 +38,6 @@ For execution, preserve the full lifecycle: select the Profile, inspect the frozaccepted Records, retrieve Artifacts, and declare any reuse explicitly in a new Run Source.Both production routes persist progress in `.hypit/route-state.json`; after an interruption, follow-`references/recovery.md` and reconcile before resuming.+`references/recovery.md` and reconcile before resuming. Before `preview_check`, run+`inspect_svml_vocabulary --run`, `validate_local_author_packages --run` and+`validate_script_cues --run`; the preview and final checks repeat these gates.diff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.mdindex 91b44900..6a2cd201 100644--- a/.agents/skills/hypit/references/reconstruction/route.md+++ b/.agents/skills/hypit/references/reconstruction/route.md@@ -75,13 +75,16 @@ of intent; files and check results remain the authority.| `environment` | explicit checkpoint after Distribution, project and credentials are selected | `hypit paths --json` || `reference-prepared` | checkpoint after `prepare_reference` reports ready `state.json` | `prepare_reference` or `route_state reconcile` || `reference-observed` | explicit observer checkpoint; all required observation answers are complete | `observe_reference` / `record_observation` |+| `vocabulary-checked` | vocabulary inspection is persisted for the Run | `inspect_svml_vocabulary --run <run>` |+| `package-ready` | every `packages/local-*` package has real Surface/Producer/Fragment and is used by the compiled Graph | `validate_local_author_packages --run <run>` |+| `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` | `preview_check <run>` |+| `graph-checked` | `preview_check` returns `sound: true` after package and Cue gates | `preview_check <run>` || `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` || `repairs-complete` | explicit checkpoint after applying comparison findings | edit Source, then rerun the checks |-| `final-checked` | final `reconstruction_check` returns `passed: true` | `reconstruction_check <run>` |+| `final-checked` | final `reconstruction_check` returns `passed: true` after all gates | `reconstruction_check <run>` || `build-complete` | explicit checkpoint after the durable Build record is accepted | `hypit build` (confirm cost first) |The numeric `current_step` is only a cursor; `reconcile` starts at the first unmet predicate. It never@@ -232,18 +235,22 @@ defaulted, and every conflict between observations is settled.### 13. Inspect candidate packages```bash-hypit-reference-video-tools inspect_svml_vocabulary --package @hypit/<name> [--package …]+hypit-reference-video-tools inspect_svml_vocabulary --package @hypit/<name> [--package …] --run <build.svrun>```Enumerate the systems from the observations, then inspect a candidate for each. A system you neverinspected is a system you are about to invent.+When the Run exists, persist this evidence with `inspect_svml_vocabulary --run <build.svrun>` before+claiming a vocabulary gap or writing Source.### 14. Develop a project-local package, only for a proven gap**Read now:** `../local-author-package.md`, completely.-**Done when:** the package installs and `inspect_svml_vocabulary` reads its declaration. A component-that loads is not yet a component that looks like the reference.+**Done when:** the package has a real Manifest, Types, Producers, Validators, Surface, decoder,+Fragment, activation, README and preview, and `validate_local_author_packages --run <build.svrun>`+reports that the Source imports and compiled Graph uses it. A component that merely loads is not done.+If no gap remains, remove unused `packages/local-*` directories.---@@ -258,6 +265,8 @@ deliverable even though this route runs nothing: without it the first thing the**Read now:**- `final-sources.md` — Segment boundaries, the forced seam, and take durations from `estimate:Speech`.+- `../script-time.md` and `../playbooks/craft/captions.md` — every captioned passage must be split+ with `||`, normally every 3–4 spoken words; do not rely on renderer wrapping.- `../authoring.md` — never invent a component, attribute, child, port, Recipe property or literalvalue, and how an accepted Record is reused in the Run Source.- `../playbooks/craft/captions.md` — Cue breaks, the Recipe keys, and what recomputes when speech@@ -268,6 +277,8 @@ deliverable even though this route runs nothing: without it the first thing thecontains. Those conditions can only be evaluated now, with the evidence in.Do not author one source fragment per shot.+Before `hypit check`, run `validate_script_cues --run <build.svrun>`; every Cue must contain at most+four visible words and use `||` between complete Alignment Units.### 16. Check every source, then prove the graph tracesdiff --git a/.agents/skills/hypit/references/recovery.md b/.agents/skills/hypit/references/recovery.mdindex 23a1642f..e841515f 100644--- a/.agents/skills/hypit/references/recovery.md+++ b/.agents/skills/hypit/references/recovery.md@@ -11,7 +11,8 @@ is the artifacts and checks it points to.3. Read `<project>/.hypit/route-state.json` with `route_state --action read`.4. Inspect `git status`, the recorded artifacts, and the last command.5. Run `route_state --action reconcile --project-root <project>` (and inspect its conflict report).-6. Re-run the first unmet check or idempotent route command named by `next_action`.+6. Re-run the first unmet check or idempotent route command named by `next_action`; package and Cue+gates must be rerun before any preview or final check.7. Continue only after the state reports the next step explicitly.If the snapshot is missing, start one before continuing:diff --git a/.agents/skills/hypit/references/script-time.md b/.agents/skills/hypit/references/script-time.mdindex 2f798953..5f67a42f 100644--- a/.agents/skills/hypit/references/script-time.md+++ b/.agents/skills/hypit/references/script-time.md@@ -8,6 +8,20 @@ Both routes reach this file. What differs is only where the temptation to use areference video hands you a table of seconds, and a brief hands you a duration — and the answer is thesame either way.+## Mandatory Cue breaks for readable captions++Whenever a Segment will appear as captions or other spoken on-screen text, author explicit short Cues+with `||` between complete Alignment Units. As the default, cut every roughly 3–4 spoken words (fewer+for long words, large type, or dense designs); permit a longer Cue only when the reference clearly+holds it and the rendered bounds prove it fits. This is a hard layout requirement, not an optional+style preference: a Segment with no `||` becomes one Cue, and the entire long passage can render beyond+the screen. Do not depend on automatic wrapping, a larger box, or a smaller font to fix it. Choose+breaks at natural phrase or sentence boundaries, and never place `||` inside Dual Text or through an+N:M Alignment Unit.++The mechanical gate `validate_script_cues --run <build.svrun>` enforces a maximum of four visible+words per Cue. Fix the Script before `hypit check` or preview.+## A Segment is a stretch that is spoken as oneCut the Script into Segments the way the program is *spoken*, not the way its pictures are numbered:diff --git a/.agents/skills/hypit/references/vocabulary.md b/.agents/skills/hypit/references/vocabulary.mdindex 2da26d60..c459f9a3 100644--- a/.agents/skills/hypit/references/vocabulary.md+++ b/.agents/skills/hypit/references/vocabulary.md@@ -128,3 +128,8 @@ composition always shows — is committed inside the package as a file, never deOnly pictures that differ between videos are edges the source supplies.`playbooks/craft/graphic-compositions.md` draws that line; a component that cannot draw itselfwithout a project document is on the wrong side of it.++After inspection, persist the result with `inspect_svml_vocabulary --run <build.svrun>`. Before+writing or checking Source, run `validate_local_author_packages --run <build.svrun>`. Every+`packages/local-*` directory must expose a real Surface, Producer and Fragment and must be imported+and used by the compiled Graph; otherwise the route stops with a machine-readable diagnostic.diff --git a/packages/reference-video-tools/src/checks.ts b/packages/reference-video-tools/src/checks.tsindex ad5ed1f8..d02ce5b3 100644--- a/packages/reference-video-tools/src/checks.ts+++ b/packages/reference-video-tools/src/checks.ts@@ -5,7 +5,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 { parseScript } from "@hypit/script";+import { parseScript, validateCaptionCueLengths } from "@hypit/script";import { videoCliDistribution } from "@hypit/video-cli";import { loadStudioCompanionRegistry } from "@hypit/studio/src/companion-profile.js";import { openStudioArchive } from "@hypit/studio/src/archive.js";@@ -25,6 +25,81 @@ export type PreviewCheckInput = {readonly runtime?: string;};+export type ScriptCueCheckInput = { readonly run: string };++type ScriptSource = { readonly path: string; readonly source: string };++/** Read the Run's reachable Author Source closure without relying on compiler internals. */+async function reachableAuthorSources(runPath: string): Promise<readonly ScriptSource[]> {+ const runSource = await readFile(runPath, "utf8");+ const author = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];+ if (author === undefined) throw new Error("AUTHOR_NOT_DECLARED");+ const queue = [resolve(dirname(runPath), author)];+ const seen = new Set<string>();+ const sources: ScriptSource[] = [];+ while (queue.length > 0) {+ const path = queue.shift()!;+ if (seen.has(path)) continue;+ seen.add(path);+ const source = await readFile(path, "utf8").catch(() => undefined);+ if (source === undefined) continue;+ sources.push({ path, source });+ for (const match of source.matchAll(/<import\s+[^>]*\bsource="([^"]+)"[^>]*\/?\s*>/gu)) {+ queue.push(resolve(dirname(path), match[1]!));+ }+ }+ return sources;+}++function scriptBodies(source: string): readonly { readonly text: string; readonly offset: number }[] {+ const bodies: { text: string; offset: number }[] = [];+ for (const opening of source.matchAll(/<script\b[^>]*>/gu)) {+ const start = opening.index! + opening[0].length;+ const end = source.indexOf("</script>", start);+ if (end < 0) throw new Error("SCRIPT_NOT_CLOSED");+ bodies.push({ text: source.slice(start, end), offset: start });+ }+ return bodies;+}++/** Validate every authored caption Cue before any preview or coverage work is attempted. */+export async function scriptCueCheck(input: ScriptCueCheckInput): Promise<Record<string, unknown>> {+ const runPath = resolve(invokedFrom(), input.run);+ const runSource = await readFile(runPath, "utf8").catch(() => undefined);+ if (runSource === undefined) return { run: runPath, passed: false, errors: [{ code: "RUN_NOT_FOUND" }] };+ try {+ const sources = await reachableAuthorSources(runPath);+ if (sources.length === 0) {+ const author = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];+ return { run: runPath, passed: false, errors: [{ code: author === undefined ? "AUTHOR_NOT_DECLARED" : "AUTHOR_NOT_FOUND", ...(author === undefined ? {} : { path: resolve(dirname(runPath), author) }) }] };+ }+ const violations: Record<string, unknown>[] = [];+ const errors: Record<string, unknown>[] = [];+ const scriptSources: string[] = [];+ for (const item of sources) {+ let bodies: readonly { readonly text: string; readonly offset: number }[];+ try { bodies = scriptBodies(item.source); }+ catch (error) {+ errors.push({ code: "SCRIPT_PARSE", path: item.path, message: error instanceof Error ? error.message : String(error) });+ continue;+ }+ for (const body of bodies) {+ scriptSources.push(item.path);+ try {+ const parsed = parseScript(item.path, body.text, body.offset);+ violations.push(...validateCaptionCueLengths(parsed));+ } catch (error) {+ errors.push({ code: "SCRIPT_PARSE", path: item.path, message: error instanceof Error ? error.message : String(error) });+ }+ }+ }+ return { run: runPath, author: sources[0]!.path, sources: [...new Set(scriptSources)], passed: violations.length === 0 && errors.length === 0, max_words: 4, violations, ...(errors.length === 0 ? {} : { errors }) };+ } catch (error) {+ const code = error instanceof Error && error.message === "AUTHOR_NOT_DECLARED" ? "AUTHOR_NOT_DECLARED" : "AUTHOR_NOT_FOUND";+ return { run: runPath, passed: false, errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };+ }+}+const AWAITING = "the Studio projection closure requires unresolved capabilities:";/**@@ -53,6 +128,7 @@ async function checkedSources(runPath: string): Promise<{ readonly ok: boolean;// project inside a larger tree resolves none of its own `packages/local-*` without this.const checked = spawnSync(process.execPath, [hypit, "check", runPath, "--package-root", dirname(runPath)], {encoding: "utf8", windowsHide: true, timeout: 600_000,+ env: { ...process.env, HYPIT_STRICT_SCRIPT_CUES: "1" },});// Node writes its own deprecation warnings to the same stream the refusal arrives on, and this// output is read as the reason a check failed. Two lines about `module.register()` above the filediff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.tsindex f8fa94fb..fbdd39fe 100644--- a/packages/reference-video-tools/src/cli.ts+++ b/packages/reference-video-tools/src/cli.ts@@ -36,7 +36,9 @@ function usage(): string {" hypit-reference-video-tools observe_reference --reference-id <id> --batch <questions.json>"," hypit-reference-video-tools record_observation --reference-id <id> [--run <build.svrun>] --key <key> --text <text>|--text-file <path>"," hypit-reference-video-tools record_observation --reference-id <id> [--run <build.svrun>] --batch <answers.json>",- " hypit-reference-video-tools inspect_svml_vocabulary --package <name> [--package <name> ...] [--tag <tag> ...] [--without-previews]",+ " hypit-reference-video-tools inspect_svml_vocabulary --package <name> [--package <name> ...] [--tag <tag> ...] [--without-previews] [--run <build.svrun>]",+ " hypit-reference-video-tools validate_local_author_packages --run <build.svrun> [--expected-package <name> ...]",+ " 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>]",@@ -450,8 +452,13 @@ async function main(): Promise<void> {package_names: packages.length > 0 ? packages : [required(flags, "package-name")],...(many(flags, "tag").length === 0 ? {} : { tags: many(flags, "tag") }),...(flags.get("without-previews") === true ? { include_previews: false } : {}),+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),};- result = await tools.inspect_svml_vocabulary(input as { package_names: readonly string[]; tags?: readonly string[]; include_previews?: boolean });+ result = await tools.inspect_svml_vocabulary(input as { package_names: readonly string[]; tags?: readonly string[]; include_previews?: boolean; run?: string });+ } else if (command === "validate_local_author_packages") {+ result = await tools.validate_local_author_packages({ run: required(flags, "run"), ...(many(flags, "expected-package").length === 0 ? {} : { expected_packages: many(flags, "expected-package") }) });+ } else if (command === "validate_script_cues") {+ result = await tools.validate_script_cues({ run: required(flags, "run") });} else if (command === "render_element") {const renderFile = one(flags, "batch");if (renderFile !== undefined) {diff --git a/packages/reference-video-tools/src/index.ts b/packages/reference-video-tools/src/index.tsindex 0a37400d..cfb9d41b 100644--- a/packages/reference-video-tools/src/index.ts+++ b/packages/reference-video-tools/src/index.ts@@ -5,8 +5,10 @@ export type {ObserveReferenceInput,RecordObservationInput,InspectVocabularyInput,+ ValidateLocalAuthorPackagesInput,RouteStateCommandInput,} from "./tools.js";+export type { ScriptCueCheckInput } from "./checks.js";export {checkpointRouteState,readRouteState,diff --git a/packages/reference-video-tools/src/route-state.ts b/packages/reference-video-tools/src/route-state.tsindex 9f511d9e..8b2973da 100644--- a/packages/reference-video-tools/src/route-state.ts+++ b/packages/reference-video-tools/src/route-state.ts@@ -5,7 +5,7 @@ export type RouteKind = "reconstruction" | "description";export type RouteStatus = "active" | "complete" | "blocked";export type RouteState = {- readonly version: 1;+ readonly version: 2;readonly route: RouteKind;readonly project_root: string;readonly run?: string;@@ -40,9 +40,9 @@ export type RouteCheckpointInput = RouteStateInput & {readonly error?: string;};-export const ROUTE_STATE_VERSION = 1 as const;--export const ROUTE_STATE_STEPS: Readonly<Record<RouteKind, readonly string[]>> = {+export const 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: ["environment", "reference-prepared", "reference-observed", "source-authored", "graph-checked","review-planned", "preview-rendered", "comparison-complete", "repairs-complete", "final-checked", "build-complete",@@ -53,6 +53,18 @@ export const 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",+ "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",+ ],+};+export function routeStatePath(projectRoot: string): string {return join(resolve(projectRoot), ".hypit", "route-state.json");}@@ -74,6 +86,43 @@ function assertRouteState(value: unknown, path: string): asserts value is RouteSif (typeof state.next_action !== "string" || typeof state.updated_at !== "string") throw new Error(`route state at ${path} is missing recovery fields`);}+function migrateLegacyRouteState(value: unknown, path: string): RouteState | undefined {+ if (value === null || typeof value !== "object" || (value as { version?: unknown }).version !== LEGACY_ROUTE_STATE_VERSION) return undefined;+ const legacy = value as Partial<RouteState>;+ if (legacy.route !== "reconstruction" && legacy.route !== "description") throw new Error(`route state at ${path} has an invalid route`);+ if (typeof legacy.project_root !== "string" || legacy.project_root.length === 0) throw new Error(`route state at ${path} has no project_root`);+ const oldSteps = LEGACY_ROUTE_STATE_STEPS[legacy.route];+ if (!Array.isArray(legacy.completed_steps) || legacy.completed_steps.some((step) => !Number.isSafeInteger(step) || step < 1 || step > oldSteps.length)) {+ throw new Error(`route state at ${path} has invalid legacy completed_steps`);+ }+ const completedNames = legacy.completed_steps.map((step) => oldSteps[step - 1]!).filter(Boolean);+ const completed = completedNames.flatMap((name) => {+ const index = ROUTE_STATE_STEPS[legacy.route!].indexOf(name);+ return index < 0 ? [] : [index + 1];+ });+ // New gates are intentionally re-opened during migration. The first unmet predicate, not the+ // legacy numeric cursor, is the only safe recovery point.+ const currentStep = nextUncompleted(legacy.route, completed);+ const now = new Date().toISOString();+ return {+ version: ROUTE_STATE_VERSION,+ route: legacy.route,+ project_root: legacy.project_root!,+ ...(legacy.run === undefined ? {} : { run: legacy.run }),+ ...(legacy.reference_id === undefined ? {} : { reference_id: legacy.reference_id }),+ status: currentStep > ROUTE_STATE_STEPS[legacy.route].length ? "complete" : "active",+ current_step: currentStep,+ completed_steps: [...new Set(completed)].sort((a, b) => a - b),+ in_progress: currentStep > ROUTE_STATE_STEPS[legacy.route].length ? null : { step: currentStep, started_at: now },+ artifacts: legacy.artifacts ?? {},+ decisions: legacy.decisions ?? [],+ next_action: legacy.next_action ?? `complete ${ROUTE_STATE_STEPS[legacy.route][currentStep - 1] ?? "route"}`,+ ...(legacy.last_command === undefined ? {} : { last_command: legacy.last_command }),+ ...(legacy.last_error === undefined ? {} : { last_error: legacy.last_error }),+ updated_at: now,+ };+}+export async function readRouteState(projectRoot: string): Promise<RouteState | undefined> {const path = routeStatePath(projectRoot);const text = await readFile(path, "utf8").catch((error: unknown) => {@@ -85,6 +134,11 @@ export async function readRouteState(projectRoot: string): Promise<RouteState |try { parsed = JSON.parse(text); } catch (error) {throw new Error(`route state at ${path} is invalid JSON; original file was preserved: ${error instanceof Error ? error.message : String(error)}`);}+ const migrated = migrateLegacyRouteState(parsed, path);+ if (migrated !== undefined) {+ await writeRouteState(migrated);+ return migrated;+ }assertRouteState(parsed, path);return parsed;}@@ -105,6 +159,24 @@ function nextUncompleted(route: RouteKind, completed: readonly number[]): numberreturn steps.length + 1;}+function stageNumber(route: RouteKind, name: string): number {+ const index = ROUTE_STATE_STEPS[route].indexOf(name);+ if (index < 0) throw new Error(`route ${route} has no ${name} stage`);+ return index + 1;+}++/** Source cannot be accepted until vocabulary, package and Script gates are durable. */+function assertSourcePrerequisites(route: RouteKind, step: number, completed: ReadonlySet<number>): void {+ if (step !== stageNumber(route, "source-authored")) return;+ const required = ["vocabulary-checked", "package-ready", "script-checked"]+ .map((name) => stageNumber(route, name));+ const missing = required.filter((item) => !completed.has(item));+ if (missing.length > 0) {+ const names = missing.map((item) => ROUTE_STATE_STEPS[route][item - 1]).join(", ");+ throw new Error(`source-authored cannot be completed before ${names}`);+ }+}+export async function startRouteState(input: RouteStateInput): Promise<RouteState> {const projectRoot = resolve(input.projectRoot);const existing = await readRouteState(projectRoot);@@ -137,7 +209,10 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promiseif (existing.route !== input.route) throw new Error(`route state is ${existing.route}, not ${input.route}`);if (input.step < 1 || input.step > ROUTE_STATE_STEPS[input.route].length) throw new Error(`step ${input.step} is outside the ${input.route} route`);const completed = new Set(existing.completed_steps);- if (input.status === "complete") completed.add(input.step);+ if (input.status === "complete") {+ assertSourcePrerequisites(input.route, input.step, completed);+ completed.add(input.step);+ }const completedSteps = [...completed].sort((a, b) => a - b);const next = input.status === "complete" ? nextUncompleted(input.route, completedSteps) : input.step;const now = new Date().toISOString();@@ -188,6 +263,13 @@ async function evidenceSatisfied(key: string, path: string | undefined): Promisereturn value.sound === true;} catch { return false; }}+ if (key === "package_ready" || key === "script_cues" || key === "vocabulary") {+ try {+ const value = JSON.parse(await readFile(path, "utf8")) as { passed?: unknown; surfaces?: unknown[]; packages?: unknown[] };+ if (key === "vocabulary") return Array.isArray(value.surfaces) || Array.isArray(value.packages);+ return value.passed === true;+ } catch { return false; }+ }if (key === "final_check") {try {const value = JSON.parse(await readFile(path, "utf8")) as { passed?: unknown };@@ -241,17 +323,24 @@ 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: "author_source", 5: "preview_check",- 6: "review_plan", 7: "preview_render", 8: "comparison_log", 10: "final_check", 11: "build",+ 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",},description: {- 2: "brief", 3: "author_source", 4: "vocabulary", 5: "preview_check",- 6: "review_plan", 7: "preview_render", 8: "review_log", 10: "final_check", 11: "build",+ 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",},};for (const [step, key] of Object.entries(evidenceByStep[existing.route])) {await reconcileStep(Number(step), key);}+ const sourceStep = stageNumber(existing.route, "source-authored");+ const gateSteps = ["vocabulary-checked", "package-ready", "script-checked"]+ .map((name) => stageNumber(existing.route, name));+ if (completed.has(sourceStep) && gateSteps.some((step) => !completed.has(step))) {+ conflicts.push(`step ${sourceStep} (source-authored) was marked complete before vocabulary/package/Script gates`);+ completed.delete(sourceStep);+ }const completedSteps = [...completed].sort((a, b) => a - b);const next = nextUncompleted(existing.route, completedSteps);const now = new Date().toISOString();diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.tsindex cb5cf7d5..cf68f8c3 100644--- a/packages/reference-video-tools/src/tools.ts+++ b/packages/reference-video-tools/src/tools.ts@@ -18,11 +18,15 @@ import {import { describeSchema } from "./contract.js";import { videoCliDistribution } from "@hypit/video-cli";-import { authorSource, invokedFrom, referenceRoot, referenceWords, renderElement, renderPreviews, spokenRange, standInSidecarPath, tokenWindow } from "./authoring.js";+import { authorSource, invokedFrom, nearestPackageRoot, referenceRoot, referenceWords, renderElement, renderPreviews, spokenRange, standInSidecarPath, tokenWindow } from "./authoring.js";import type { RenderElementInput, RenderPreviewsInput, SpokenRange, StandInFocus, StandInSidecar } from "./authoring.js";import { downloadReferenceVideo, isReferenceUrl } from "@hypit/yt-dlp";-import { authoringCheck, previewCheck, reviewLogPath } from "./checks.js";-import type { AuthoringCheckInput, PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";+import { loadStudioCompanionRegistry } from "@hypit/studio/src/companion-profile.js";+import { openStudioArchive } from "@hypit/studio/src/archive.js";+import { loadStudioDomain } from "@hypit/studio/src/domain.js";+import { loadStudioRun } from "@hypit/studio/src/run.js";+import { authoringCheck, previewCheck, reviewLogPath, scriptCueCheck } from "./checks.js";+import type { AuthoringCheckInput, PreviewCheckInput, ReconstructionCheckInput, ScriptCueCheckInput } from "./checks.js";import {checkpointRouteState,readRouteState,@@ -86,6 +90,11 @@ export type InspectVocabularyInput = {readonly package_names: readonly string[];readonly tags?: readonly string[];readonly include_previews?: boolean;+ readonly run?: string;+};+export type ValidateLocalAuthorPackagesInput = {+ readonly run: string;+ readonly expected_packages?: readonly string[];};export type CompareReconstructionInput = {readonly reference_id: string;@@ -187,6 +196,8 @@ export type ReferenceVideoTools = {prepare_reference(input: PrepareReferenceInput): Promise<PrepareResult>;observe_reference(input: ObserveReferenceInput): Promise<Record<string, unknown>>;inspect_svml_vocabulary(input: InspectVocabularyInput): Promise<Record<string, unknown>>;+ validate_local_author_packages(input: ValidateLocalAuthorPackagesInput): Promise<Record<string, unknown>>;+ validate_script_cues(input: ScriptCueCheckInput): Promise<Record<string, unknown>>;inspect_visual_contract(input: { readonly shape?: string; readonly producers?: readonly string[] }): Promise<Record<string, unknown>>;paths(): Promise<Record<string, unknown>>;compare_reconstruction(input: CompareReconstructionInput): Promise<Record<string, unknown>>;@@ -222,6 +233,12 @@ function routeStateResult(state: RouteState | undefined): Record<string, unknownreturn state === undefined ? { state: null } : { state, path: routeStatePath(state.project_root) };}+function routeStepFor(route: RouteKind, name: string): number {+ const index = ROUTE_STATE_STEPS[route].indexOf(name);+ if (index < 0) throw new Error(`route ${route} has no ${name} stage`);+ return index + 1;+}+async function runRouteStateCommand(input: RouteStateCommandInput): Promise<Record<string, unknown>> {if (input.action === "start") {const state = await startRouteState({ projectRoot: input.project_root, route: input.route, ...(input.run === undefined ? {} : { run: input.run }), ...(input.reference_id === undefined ? {} : { referenceId: input.reference_id }) });@@ -319,7 +336,7 @@ async function referenceObservationComplete(referenceId: string): Promise<booleaasync function maybeCheckpointReferenceObservation(input: RecordObservationInput): Promise<void> {if (input.run === undefined || !(await referenceObservationComplete(input.reference_id))) return;const runPath = resolve(invokedFrom(), input.run);- await autoRouteCheckpoint(runPath, 3, { reference_observations: join(stateRoot(input.reference_id), "observations.json") }, "write or repair the reconstruction Source");+ await autoRouteCheckpoint(runPath, routeStepFor("reconstruction", "reference-observed"), { reference_observations: join(stateRoot(input.reference_id), "observations.json") }, "inspect vocabulary and resolve any package gap");}async function persistRoutePlan(runPath: string, result: Record<string, unknown>): Promise<string> {@@ -1036,6 +1053,99 @@ function publicPrepare(state: ReferenceState): PrepareResult {export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVideoTools {const packageRoot = resolve(options.packageRoot ?? process.cwd());++ async function validateLocalAuthorPackages(input: ValidateLocalAuthorPackagesInput): Promise<Record<string, unknown>> {+ const runPath = resolve(invokedFrom(), input.run);+ const projectRoot = nearestPackageRoot(dirname(runPath)) ?? packageRoot;+ const packagesRoot = join(projectRoot, "packages");+ const localDirectories = (await readdir(packagesRoot, { withFileTypes: true }).catch(() => []))+ .filter((entry) => entry.isDirectory() && entry.name.startsWith("local-"))+ .map((entry) => join(packagesRoot, entry.name));+ const expected = new Set(input.expected_packages ?? []);+ const distributionPackageRoot = videoCliDistribution.packageRoot;+ const 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]!),+ ]);+ let graphModules = new Set<string>();+ try {+ if (distributionPackageRoot !== undefined) {+ const registry = await loadStudioCompanionRegistry({ workspaceRoot: projectRoot, packageRoot: projectRoot, distributionPackageRoot });+ const domain = await loadStudioDomain({ run: runPath, workspaceRoot: projectRoot, packageRoot: projectRoot });+ const archive = await openStudioArchive(undefined, projectRoot, projectRoot, distributionPackageRoot);+ const loaded = await loadStudioRun({ run: runPath, domain, registry, ...(archive === undefined ? {} : { archive }) });+ graphModules = new Set([+ ...loaded.source.compiled.graph.operations.map((operation) => `${operation.producer.module.name}@${operation.producer.module.version}`),+ ...loaded.run.graph.operations.map((operation) => `${operation.producer.module.name}@${operation.producer.module.version}`),+ ]);+ }+ } catch {+ // The normal check reports the compiler failure; package validation still returns precise+ // structural diagnostics for every local package instead of hiding them behind one exception.+ }+ const results: Record<string, unknown>[] = [];+ for (const directory of localDirectories) {+ const manifestPath = join(directory, "package.json");+ const manifest = await readJson<{ name?: string; hypit?: { activation?: string } }>(manifestPath);+ const specifier = manifest?.name ?? basename(directory);+ const errors: string[] = [];+ if (manifest === undefined) errors.push("PACKAGE_MANIFEST_MISSING");+ else if (manifest.hypit?.activation === undefined) errors.push("PACKAGE_ACTIVATION_MISSING");+ let loaded: Awaited<ReturnType<typeof loadNodePackageSelection>> = [];+ try { loaded = await loadNodePackageSelection([specifier], projectRoot, loading); }+ catch { errors.push("PACKAGE_ACTIVATION_INVALID"); }+ const 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");+ 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 ?? {}));+ 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");+ 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 ?? []) {+ const producer = (operation as { producer?: { module?: { name?: string; version?: string }; name?: string } }).producer;+ const key = producer?.module?.name !== undefined && producer.module.version !== undefined && producer.name !== undefined+ ? `${producer.module.name}@${producer.module.version}#${producer.name}`+ : undefined;+ if (key === undefined || !declaredProducers.has(key)) errors.push("PACKAGE_FRAGMENT_PRODUCER_UNDECLARED");+ }+ }+ for (const facet of surfaces) {+ const surface = (facet.implementation as Partial<RegisteredSurface>);+ if (surface.module?.name === undefined || surface.module.version === undefined || surface.surface?.trim().length === 0+ || surface.tag?.trim().length === 0 || !Array.isArray(surface.outputs) || surface.outputs.length === 0+ || surface.outputs.some((output) => output?.module?.name === undefined || output.module.version === undefined || output.name?.trim().length === 0)) {+ errors.push("PACKAGE_SURFACE_INVALID");+ }+ }+ const sourceImported = imported.has(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 }) });+ }+ for (const specifier of expected) {+ if (!results.some((item) => item.specifier === specifier)) results.push({ specifier, status: "failed", errors: ["PACKAGE_EXPECTED_BUT_MISSING"] });+ }+ const vocabularyEvidence = await stat(join(projectRoot, ".hypit", "vocabulary.json")).then(() => true, () => false);+ const passed = results.every((item) => item.status === "passed") && vocabularyEvidence;+ return {+ run: runPath,+ package_root: projectRoot,+ passed,+ vocabulary_checked: vocabularyEvidence,+ ...(vocabularyEvidence ? {} : { errors: ["VOCABULARY_NOT_CHECKED"] }),+ packages: results,+ ...(localDirectories.length === 0 && expected.size === 0 ? { note: "no project-local packages declared" } : {}),+ };+ }const model = options.model ?? process.env.GEMINI_MODEL?.trim() ?? "gemini-3.1-pro-preview";// Pacing is deployment policy, not author intent: it depends on the quota behind the credentials,// which the calling agent has no way to know. It is settable here and through the environment, and@@ -1571,7 +1681,39 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV});}}- return { packages: input.package_names, surfaces };+ const result = { packages: input.package_names, surfaces };+ if (input.run !== undefined) {+ const runPath = resolve(invokedFrom(), input.run);+ const evidence = await persistRouteEvidence(runPath, "vocabulary.json", result);+ const route = await readRouteState(dirname(runPath));+ const step = route?.route === "description" ? 3 : 4;+ await autoRouteCheckpoint(runPath, step, { vocabulary: evidence }, "validate_local_author_packages --run <build.svrun>");+ }+ return result;+ },++ async validate_local_author_packages(input): Promise<Record<string, unknown>> {+ const result = await validateLocalAuthorPackages(input);+ const runPath = resolve(invokedFrom(), input.run);+ const evidence = await persistRouteEvidence(runPath, "package-ready.json", result);+ if (result.passed === true) {+ const route = await readRouteState(dirname(runPath));+ const step = route?.route === "description" ? 4 : 5;+ await autoRouteCheckpoint(runPath, step, { package_ready: evidence }, "validate_script_cues --run <build.svrun>");+ } else await autoRouteError(runPath, "validate_local_author_packages", (result.packages as unknown[] ?? []));+ return result;+ },++ async validate_script_cues(input): Promise<Record<string, unknown>> {+ const result = await scriptCueCheck(input);+ const runPath = resolve(invokedFrom(), input.run);+ const evidence = await persistRouteEvidence(runPath, "script-cues.json", result);+ if (result.passed === true) {+ const route = await readRouteState(dirname(runPath));+ const step = route?.route === "description" ? 5 : 6;+ await autoRouteCheckpoint(runPath, step, { script_cues: evidence }, "write main.svml, recipes.svs and build.svrun");+ } else await autoRouteError(runPath, "validate_script_cues", result.violations ?? result.errors ?? "cue validation failed");+ return result;},/**@@ -1800,7 +1942,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVscope,});if (already !== undefined) {- if (input.run !== undefined) await autoRouteCheckpoint(resolve(invokedFrom(), input.run), 8, { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");+ if (input.run !== undefined) await autoRouteCheckpoint(resolve(invokedFrom(), input.run), routeStepFor("reconstruction", "comparison-complete"), { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");return {reference_id: state.reference_id,observer,@@ -1846,7 +1988,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV...(differences.status === "complete" ? { differences: differences.text } : {}),});if (differences.status === "complete" && input.run !== undefined) {- await autoRouteCheckpoint(resolve(invokedFrom(), input.run), 8, { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");+ await autoRouteCheckpoint(resolve(invokedFrom(), input.run), routeStepFor("reconstruction", "comparison-complete"), { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");}return {reference_id: state.reference_id,@@ -1926,7 +2068,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV.split("\n").filter((line) => line.trim().length > 0).flatMap((line) => {try { return [JSON.parse(line) as ComparisonRecord]; } catch { return []; }}).find((entry) => entry.id === comparisonId);- if (comparison?.run !== undefined) await autoRouteCheckpoint(comparison.run, 8, { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");+ if (comparison?.run !== undefined) await autoRouteCheckpoint(comparison.run, routeStepFor("reconstruction", "comparison-complete"), { comparison_log: join(root, "comparisons.jsonl") }, "repair differences, then rerun reconstruction_check");await maybeCheckpointReferenceObservation(input);return { reference_id: state.reference_id, key, stored_in: "comparisons" };}@@ -2100,7 +2242,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVassert(text.length > 0, "text is required; a review that found nothing wrong says so in words");const closed = await closeLooked(reviewLog(root), id, text);assert(closed, `${id} names no open review of ${runPath}`);- await autoRouteCheckpoint(runPath, 8, { review_log: reviewLogPath(runPath) }, "repair findings, then rerun authoring_check");+ await autoRouteCheckpoint(runPath, routeStepFor("description", "review-complete"), { review_log: reviewLogPath(runPath) }, "repair findings, then rerun authoring_check");return { run: runPath, review_id: id, stored_in: reviewLogPath(runPath) };},@@ -2120,7 +2262,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVconst first = done[0] as Record<string, unknown>;const evidence = await renderEvidence(first.out);if (Object.keys(evidence).length > 0) {- await autoRouteCheckpoint(run === undefined ? undefined : resolve(invokedFrom(), run), 7,+ await autoRouteCheckpoint(run === undefined ? undefined : resolve(invokedFrom(), run), routeStepFor((await readRouteState(dirname(resolve(invokedFrom(), run ?? ""))))?.route ?? "reconstruction", "preview-rendered"),evidence, "compare_reconstruction or review_element");}} else if (failures.length > 0) {@@ -2138,7 +2280,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVconst result = await renderElement(input);const evidence = await renderEvidence(result.out);if (Object.keys(evidence).length > 0) {- await autoRouteCheckpoint(input.run === undefined ? undefined : resolve(invokedFrom(), input.run), 7,+ await autoRouteCheckpoint(input.run === undefined ? undefined : resolve(invokedFrom(), input.run), routeStepFor((await readRouteState(dirname(resolve(invokedFrom(), input.run ?? ""))))?.route ?? "reconstruction", "preview-rendered"),evidence, "compare_reconstruction or review_element");}return result;@@ -2155,14 +2297,23 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVasync preview_check(input): Promise<Record<string, unknown>> {const runPath = resolve(invokedFrom(), input.run);try {+ const packageGate = await validateLocalAuthorPackages({ run: input.run });+ const cueGate = await scriptCueCheck({ run: input.run });+ if (packageGate.passed !== true || cueGate.passed !== true) {+ const refused = { run: runPath, sound: false, package_gate: packageGate, script_cue_gate: cueGate, refused: "package or Script Cue gate failed" };+ await persistRouteEvidence(runPath, "preview-check.json", refused);+ await autoRouteError(runPath, "preview_check", refused.refused);+ return refused;+ }const result = await previewCheck(input, { packageRoot });const evidence = await persistRouteEvidence(runPath, "preview-check.json", result);if (result.sound === true) {const source = await authorSource(runPath).catch(() => undefined);const route = await readRouteState(dirname(runPath));- const sourceStep = route?.route === "description" ? 3 : 4;+ const sourceStep = routeStepFor(route?.route ?? "reconstruction", "source-authored");await autoRouteCheckpoint(runPath, sourceStep, source === undefined ? {} : { author_source: source.path }, "run reconstruction_check or authoring_check");- await autoRouteCheckpoint(runPath, 5, { preview_check: evidence }, "run reconstruction_check or authoring_check");+ const routeAfterSource = await readRouteState(dirname(runPath));+ await autoRouteCheckpoint(runPath, routeStepFor(routeAfterSource?.route ?? "reconstruction", "graph-checked"), { preview_check: evidence }, "run reconstruction_check or authoring_check");} else await autoRouteError(runPath, "preview_check", result.refused ?? result.problems ?? "preview check failed");return result;} catch (error) {@@ -2174,13 +2325,22 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVasync reconstruction_check(input): Promise<Record<string, unknown>> {const runPath = resolve(invokedFrom(), input.run);try {+ const packageGate = await validateLocalAuthorPackages({ run: input.run });+ const cueGate = await scriptCueCheck({ run: input.run });+ if (packageGate.passed !== true || cueGate.passed !== true) {+ const refused = { run: runPath, passed: false, package_gate: packageGate, script_cue_gate: cueGate, issues: ["package or Script Cue gate failed"] };+ await persistRouteEvidence(runPath, "final-check.json", refused);+ await autoRouteError(runPath, "reconstruction_check", refused.issues);+ return refused;+ }const result = await authoringCheck({ ...input, mode: "reconstruction" }, { packageRoot });const evidence = await persistRouteEvidence(runPath, "final-check.json", result);if (Array.isArray(result.plan)) {const planPath = await persistRoutePlan(runPath, result);- await autoRouteCheckpoint(runPath, 6, { review_plan: planPath }, "render_element --batch <round.json>");+ const route = await readRouteState(dirname(runPath));+ await autoRouteCheckpoint(runPath, routeStepFor(route?.route ?? "reconstruction", "review-planned"), { review_plan: planPath }, "render_element --batch <round.json>");}- if (result.passed === true) await autoRouteCheckpoint(runPath, 10, { final_check: evidence }, "submit the approved Build");+ if (result.passed === true) { const route = await readRouteState(dirname(runPath)); await autoRouteCheckpoint(runPath, routeStepFor(route?.route ?? "reconstruction", "final-checked"), { final_check: evidence }, "submit the approved Build"); }else await autoRouteError(runPath, "reconstruction_check", result.issues ?? result.unresolved ?? "reconstruction check failed");return result;} catch (error) {@@ -2192,13 +2352,22 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVasync authoring_check(input): Promise<Record<string, unknown>> {const runPath = resolve(invokedFrom(), input.run);try {+ const packageGate = await validateLocalAuthorPackages({ run: input.run });+ const cueGate = await scriptCueCheck({ run: input.run });+ if (packageGate.passed !== true || cueGate.passed !== true) {+ const refused = { run: runPath, passed: false, package_gate: packageGate, script_cue_gate: cueGate, issues: ["package or Script Cue gate failed"] };+ await persistRouteEvidence(runPath, "final-check.json", refused);+ await autoRouteError(runPath, "authoring_check", refused.issues);+ return refused;+ }const result = await authoringCheck({ ...input, mode: "description" }, { packageRoot });const evidence = await persistRouteEvidence(runPath, "final-check.json", result);if (Array.isArray(result.plan)) {const planPath = await persistRoutePlan(runPath, result);- await autoRouteCheckpoint(runPath, 6, { review_plan: planPath }, "render_element --batch <round.json>");+ const route = await readRouteState(dirname(runPath));+ await autoRouteCheckpoint(runPath, routeStepFor(route?.route ?? "description", "review-planned"), { review_plan: planPath }, "render_element --batch <round.json>");}- if (result.passed === true) await autoRouteCheckpoint(runPath, 10, { final_check: evidence }, "submit the approved Build");+ if (result.passed === true) { const route = await readRouteState(dirname(runPath)); await autoRouteCheckpoint(runPath, routeStepFor(route?.route ?? "description", "final-checked"), { final_check: evidence }, "submit the approved Build"); }else await autoRouteError(runPath, "authoring_check", result.issues ?? result.unresolved ?? "authoring check failed");return result;} catch (error) {diff --git a/packages/reference-video-tools/test/gates.test.ts b/packages/reference-video-tools/test/gates.test.tsnew file mode 100644index 00000000..c3e29f7f--- /dev/null+++ b/packages/reference-video-tools/test/gates.test.ts@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createReferenceVideoTools } from "../src/tools.js";++async function project(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "hypit-gates-"));+ await writeFile(join(root, "package.json"), JSON.stringify({ name: "gate-fixture", private: true }), "utf8");+ await mkdir(join(root, "packages", "local-empty", "src"), { recursive: true });+ await writeFile(join(root, "packages", "local-empty", "package.json"), JSON.stringify({+ name: "@fixture/local-empty", version: "0.0.0-dev", type: "module", exports: { ".": "./src/index.ts" },+ hypit: { activation: "./src/activation.ts" }, dependencies: {},+ }), "utf8");+ await writeFile(join(root, "packages", "local-empty", "src", "index.ts"), "export const empty = true;\n", "utf8");+ await writeFile(join(root, "packages", "local-empty", "src", "activation.ts"), "export default { format: 'hypit.node-package@1', modules: [], hostFacets: [] };\n", "utf8");+ await writeFile(join(root, "main.svml"), `<svml><import as="script" from="@hypit/script@1"/><script:Script id="story"><opening>one two three four five</opening></script></svml>\n`, "utf8");+ await writeFile(join(root, "build.svrun"), `<svrun><author source="main.svml"/></svrun>\n`, "utf8");+ return root;+}++test("local package gate rejects an empty activation and an unbroken long Cue", async () => {+ const root = await project();+ const tools = createReferenceVideoTools({ packageRoot: root });+ const packageResult = await tools.validate_local_author_packages({ run: join(root, "build.svrun") });+ assert.equal(packageResult.passed, false);+ assert.match(JSON.stringify(packageResult), /PACKAGE_NO_SURFACE/u);+ const cueResult = await tools.validate_script_cues({ run: join(root, "build.svrun") });+ assert.equal(cueResult.passed, false);+ assert.equal((cueResult.violations as { wordCount: number }[])[0]?.wordCount, 5);+});diff --git a/packages/reference-video-tools/test/route-state.test.ts b/packages/reference-video-tools/test/route-state.test.tsindex 83809694..8c655350 100644--- a/packages/reference-video-tools/test/route-state.test.ts+++ b/packages/reference-video-tools/test/route-state.test.ts@@ -10,8 +10,21 @@ import {reconcileRouteState,routeStatePath,startRouteState,+ ROUTE_STATE_STEPS,} from "../src/route-state.js";+async function completeDescriptionSourceGates(root: string): Promise<void> {+ const vocabulary = join(root, "vocabulary.json");+ const packageReady = join(root, "package-ready.json");+ const scriptCues = join(root, "script-cues.json");+ await writeFile(vocabulary, JSON.stringify({ packages: [], surfaces: [] }), "utf8");+ await writeFile(packageReady, JSON.stringify({ passed: true }), "utf8");+ await writeFile(scriptCues, JSON.stringify({ passed: true }), "utf8");+ await checkpointRouteState({ projectRoot: root, route: "description", step: 3, status: "complete", artifacts: { vocabulary } });+ await checkpointRouteState({ projectRoot: root, route: "description", step: 4, status: "complete", artifacts: { package_ready: packageReady } });+ await checkpointRouteState({ projectRoot: root, route: "description", step: 5, status: "complete", artifacts: { script_cues: scriptCues } });+}+test("route state starts once, checkpoints idempotently, and advances to the next step", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));const started = await startRouteState({ projectRoot: root, route: "reconstruction", run: "build.svrun" });@@ -30,9 +43,10 @@ test("reconcile uses durable artifact pointers and preserves manual gaps", asyncconst source = join(root, "main.svml");await writeFile(source, "source", "utf8");await startRouteState({ projectRoot: root, route: "description" });- await checkpointRouteState({ projectRoot: root, route: "description", step: 3, status: "complete", artifacts: { author_source: source } });+ await completeDescriptionSourceGates(root);+ await checkpointRouteState({ projectRoot: root, route: "description", step: 6, status: "complete", artifacts: { author_source: source } });const reconciled = await reconcileRouteState(root);- assert.equal(reconciled?.completed_steps.includes(3), true);+ assert.equal(reconciled?.completed_steps.includes(6), true);assert.equal(reconciled?.current_step, 1, "manual earlier steps remain owed instead of being guessed from a later file");});@@ -53,7 +67,7 @@ test("a project cannot switch an active route", async () => {test("a completed route no longer blocks a new route", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));await startRouteState({ projectRoot: root, route: "reconstruction" });- for (let step = 1; step <= 11; step += 1) {+ for (let step = 1; step <= ROUTE_STATE_STEPS.reconstruction.length; step += 1) {await checkpointRouteState({ projectRoot: root, route: "reconstruction", step, status: "complete" });}assert.equal((await readRouteState(root))?.status, "complete");@@ -69,16 +83,19 @@ test("checkpoint artifacts are merged and stale machine evidence is rolled back"await writeFile(source, "source", "utf8");await writeFile(check, JSON.stringify({ sound: true }), "utf8");await startRouteState({ projectRoot: root, route: "description" });- await checkpointRouteState({ projectRoot: root, route: "description", step: 3, status: "complete", artifacts: { author_source: source } });- await checkpointRouteState({ projectRoot: root, route: "description", step: 5, status: "complete", artifacts: { preview_check: check } });- assert.deepEqual((await readRouteState(root))?.artifacts, { author_source: source, preview_check: check });+ await completeDescriptionSourceGates(root);+ await checkpointRouteState({ projectRoot: root, route: "description", step: 6, status: "complete", artifacts: { author_source: source } });+ await checkpointRouteState({ projectRoot: root, route: "description", step: 7, status: "complete", artifacts: { preview_check: check } });+ const mergedArtifacts = (await readRouteState(root))?.artifacts ?? {};+ assert.equal(mergedArtifacts.author_source, source);+ assert.equal(mergedArtifacts.preview_check, check);await reconcileRouteState(root);- assert.equal((await readRouteState(root))?.completed_steps.includes(5), true);+ assert.equal((await readRouteState(root))?.completed_steps.includes(7), true);await writeFile(check, JSON.stringify({ sound: false }), "utf8");const rolledBack = await reconcileRouteState(root);- assert.equal(rolledBack?.completed_steps.includes(5), false);+ assert.equal(rolledBack?.completed_steps.includes(7), false);assert.equal(rolledBack?.current_step, 1);- assert.match(rolledBack?.conflicts?.[0] ?? "", /step 5.*preview_check/u);+ assert.match(rolledBack?.conflicts?.[0] ?? "", /step 7.*preview_check/u);});test("description reconciliation uses brief and vocabulary evidence rather than reference artifacts", async () => {@@ -86,14 +103,14 @@ test("description reconciliation uses brief and vocabulary evidence rather thanconst brief = join(root, "brief.md");const vocabulary = join(root, "vocabulary.json");await writeFile(brief, "brief", "utf8");- await writeFile(vocabulary, "{}", "utf8");+ await writeFile(vocabulary, JSON.stringify({ packages: [], surfaces: [] }), "utf8");await startRouteState({ projectRoot: root, route: "description" });await checkpointRouteState({ projectRoot: root, route: "description", step: 2, status: "complete", artifacts: { brief } });- await checkpointRouteState({ projectRoot: root, route: "description", step: 4, status: "complete", artifacts: { vocabulary } });+ await checkpointRouteState({ projectRoot: root, route: "description", step: 3, status: "complete", artifacts: { vocabulary } });const state = await reconcileRouteState(root);assert.equal(state?.completed_steps.includes(2), true);- assert.equal(state?.completed_steps.includes(4), true);- assert.equal(state?.completed_steps.includes(3), false);+ assert.equal(state?.completed_steps.includes(3), true);+ assert.equal(state?.completed_steps.includes(6), false);});test("an interrupted in-progress step resumes at the first unmet step", async () => {@@ -107,3 +124,35 @@ test("an interrupted in-progress step resumes at the first unmet step", async ()assert.equal(resumed?.in_progress?.step, 2);assert.equal(resumed?.next_action, "complete reference-prepared");});++test("v1 route snapshots migrate by stage name and re-open new gates", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));+ await mkdir(join(root, ".hypit"), { recursive: true });+ await writeFile(routeStatePath(root), JSON.stringify({+ version: 1, route: "reconstruction", project_root: root, status: "active", current_step: 4,+ completed_steps: [1, 2, 3, 4], in_progress: { step: 4, started_at: new Date().toISOString() },+ artifacts: {}, decisions: [], next_action: "write Source", updated_at: new Date().toISOString(),+ }), "utf8");+ const migrated = await readRouteState(root);+ assert.equal(migrated?.version, 2);+ 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);+});++test("source-authored cannot bypass vocabulary, package and Script gates", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));+ await startRouteState({ projectRoot: root, route: "reconstruction" });+ const sourceStep = ROUTE_STATE_STEPS.reconstruction.indexOf("source-authored") + 1;+ await assert.rejects(+ checkpointRouteState({ projectRoot: root, route: "reconstruction", step: sourceStep, status: "complete" }),+ /source-authored cannot be completed before/u,+ );+ const statePath = routeStatePath(root);+ const raw = JSON.parse(await readFile(statePath, "utf8")) as Record<string, unknown>;+ raw.completed_steps = [4, 5, 6, sourceStep];+ await writeFile(statePath, `${JSON.stringify(raw)}\n`, "utf8");+ const reconciled = await reconcileRouteState(root);+ assert.equal(reconciled?.completed_steps.includes(sourceStep), false);+ assert.equal((reconciled?.conflicts?.length ?? 0) > 0, true);+});diff --git a/packages/script/src/cue-lint.ts b/packages/script/src/cue-lint.tsnew file mode 100644index 00000000..a0eb2090--- /dev/null+++ b/packages/script/src/cue-lint.ts@@ -0,0 +1,60 @@+import type { ParsedNarrative } from "./types.js";+import { captionDocument } from "./narrative.js";++export type CaptionCueLengthViolation = {+ readonly segment: string;+ readonly cue: number;+ readonly wordCount: number;+ readonly maxWords: number;+ readonly sourceRange: { readonly start: number; readonly end: number };+ readonly message: string;+};++/**+ * Mechanical layout guard for authored caption Cues. The count is based on visible display words,+ * not punctuation or renderer line wrapping, and therefore also covers Dual Text aliases.+ */+export function validateCaptionCueLengths(+ parsed: ParsedNarrative,+ options: { readonly maxWords?: number } = {},+): readonly CaptionCueLengthViolation[] {+ const maxWords = options.maxWords ?? 4;+ if (!Number.isSafeInteger(maxWords) || maxWords < 1) throw new Error("maxWords must be a positive integer");+ const document = captionDocument(parsed, "__cue_lint__", parsed.segments[0]?.id ?? "__cue_lint__");+ const breaks = new Set(document.cueBreaks.map((item) => item.afterUnitId));+ const violations: CaptionCueLengthViolation[] = [];+ let cueWords = 0;+ let cueStart = 0;+ let cueOrdinal = 1;+ const flush = (endExclusive: number): void => {+ if (cueWords <= maxWords || document.units.length === 0) return;+ const first = document.units[cueStart];+ const last = document.units[Math.max(cueStart, endExclusive - 1)];+ const tokenIds = [...(first?.sourceTokenIds ?? []), ...(last?.sourceTokenIds ?? [])];+ const tokenById = new Map(parsed.tokens.map((token) => [token.id, token]));+ const ranges = tokenIds.map((id) => tokenById.get(id)?.range).filter((range): range is { start: number; end: number } => range !== undefined);+ const sourceRange = ranges.length === 0+ ? { start: parsed.sourceRange.start, end: parsed.sourceRange.end }+ : { start: Math.min(...ranges.map((range) => range.start)), end: Math.max(...ranges.map((range) => range.end)) };+ violations.push({+ segment: first?.segmentId ?? "unknown",+ cue: cueOrdinal,+ wordCount: cueWords,+ maxWords,+ sourceRange,+ message: "Split this Cue with ||; captions normally contain no more than four spoken words.",+ });+ };+ for (let index = 0; index < document.units.length; index += 1) {+ const unit = document.units[index]!;+ cueWords += unit.wordIds.length;+ if (breaks.has(unit.id)) {+ flush(index + 1);+ cueWords = 0;+ cueStart = index + 1;+ cueOrdinal += 1;+ }+ }+ flush(document.units.length);+ return violations;+}diff --git a/packages/script/src/index.ts b/packages/script/src/index.tsindex f502de57..5d2d642c 100644--- a/packages/script/src/index.ts+++ b/packages/script/src/index.ts@@ -16,5 +16,6 @@ export {serializeSpeech,} from "./narrative.js";export { parseScript } from "./parser.js";+export { validateCaptionCueLengths } from "./cue-lint.js";export { decodeScriptSurface } from "./surface.js";export type * from "./types.js";diff --git a/packages/script/src/surface.ts b/packages/script/src/surface.tsindex 096cdca8..bfdc2692 100644--- a/packages/script/src/surface.ts+++ b/packages/script/src/surface.ts@@ -17,6 +17,7 @@ import {} from "./manifest.js";import { textTypes } from "@hypit/text";import { parseScript } from "./parser.js";+import { validateCaptionCueLengths } from "./cue-lint.js";import type { ScriptSurfaceInput, ScriptSurfaceOutput } from "./types.js";const RECORD_ID = /^[a-z][a-z0-9_-]{0,63}$/u;@@ -73,6 +74,17 @@ export function decodeScriptSurface(input: ScriptSurfaceInput): ScriptSurfaceOutinput.source.slice(input.contentStart, close.start),input.contentStart,);+ if (process.env.HYPIT_STRICT_SCRIPT_CUES === "1") {+ const cueViolation = validateCaptionCueLengths(parsed)[0];+ if (cueViolation !== undefined) {+ throw new ScriptSyntaxError(+ "SCRIPT_CUE_TOO_LONG",+ `${cueViolation.message} Cue ${cueViolation.cue} in Segment ${cueViolation.segment} has ${cueViolation.wordCount} words (maximum ${cueViolation.maxWords}).`,+ input.sourceName,+ cueViolation.sourceRange.start,+ );+ }+ }const captionId = `${rawId}.caption`;return {nextOffset: close.end,diff --git a/packages/script/test/cue-lint.test.ts b/packages/script/test/cue-lint.test.tsnew file mode 100644index 00000000..6bd38972--- /dev/null+++ b/packages/script/test/cue-lint.test.ts@@ -0,0 +1,22 @@+import assert from "node:assert/strict";+import test from "node:test";+import { parseScript, validateCaptionCueLengths } from "../src/index.js";++function parsed(body: string) { return parseScript("test.svml", body); }++test("Cue lint accepts four words and rejects an unbroken five-word Cue", () => {+ const good = validateCaptionCueLengths(parsed("<one>one two three four</one>"));+ assert.deepEqual(good, []);+ const bad = validateCaptionCueLengths(parsed("<one>one two three four five</one>"));+ assert.equal(bad.length, 1);+ assert.equal(bad[0]?.wordCount, 5);+ assert.equal(bad[0]?.segment, "one");+});++test("Cue lint counts visible Dual Text words and respects authored breaks", () => {+ assert.equal(validateCaptionCueLengths(parsed("<one>one two || three four</one>")).length, 0);+ const bad = validateCaptionCueLengths(parsed("<one>one two three four five || six</one>"));+ assert.equal(bad[0]?.wordCount, 5);+ const dual = validateCaptionCueLengths(parsed("<one><one two three four five | uno dos tres cuatro cinco></one>"));+ assert.equal(dual[0]?.wordCount, 5);+});