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(hypit): persist shared component fit (#120)
rponeawa015ef781ad75
diff --git a/.agents/skills/hypit/references/element-review.md b/.agents/skills/hypit/references/element-review.mdindex 5cb2b346..04b68596 100644--- a/.agents/skills/hypit/references/element-review.md+++ b/.agents/skills/hypit/references/element-review.md@@ -234,13 +234,21 @@ Something nobody can close is not a failure to record as one. A typeface the genreproduce, a texture it will not hold, a grain that is not available — write it into the report andleave it.+Read the frozen `.hypit/component-fit.json` only after the independent reader has returned its+findings. A difference that exactly matches a named accepted variance is recorded in the completion+report, consumes no repair attempt and does not block the round. Do not tell the reader about that+variance in advance. If a supposedly small difference instead changes the core look, role, structure+or behaviour, return to the vocabulary decision; do not copy or widen the installed package.+### Two ceilings, and they never share attempts-The first is over the *package*: something the package cannot express is a package defect, and fixing-it means changing the package's structure. The second is over the *values*: once the package can-express everything, tune the Recipe, the font, the placement and the motion.+The first is over a *project-local package*: something that new package cannot express is its defect,+and fixing it means changing that package's structure. Installed packages are immutable; a finding+outside their accepted fit is a component-selection conflict, not permission to modify them. The+second ceiling is over the values: tune the Recipe, font, placement and motion the selected component+actually declares.-**Write-and-remake the package: two attempts.** The first fixes what is obvious, the second fixes what+**Write-and-remake a project-local package: two attempts.** The first fixes what is obvious, the second fixes whatthe first revealed. If it is still something the package cannot express — a typeface mix it has noport for, a motion it cannot draw — the package is wrong rather than the values, and tuning valuesis thrashing. Widen the package instead, which starts a fresh write-and-remake for the widened shape.diff --git a/.agents/skills/hypit/references/original-authoring/conformance-round.md b/.agents/skills/hypit/references/original-authoring/conformance-round.mdindex e3ac90bc..9a70242d 100644--- a/.agents/skills/hypit/references/original-authoring/conformance-round.md+++ b/.agents/skills/hypit/references/original-authoring/conformance-round.md@@ -26,6 +26,10 @@ Write the element's own share of both into a file and pass it as `--intent-file`required for a reason: a conformance question with nothing to conform to asks whether the picturelooks acceptable, which it always does to whoever drew it.+Do not put the selected package, rejected candidates or component-fit rationale into the intent.+Details the author never specified and the brief never decided are not hidden requirements for the+reader to invent. Apply any named accepted variance only after the independent answer returns.+## The round```diff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.mdindex b41f0d85..54c04ec2 100644--- a/.agents/skills/hypit/references/original-authoring/route.md+++ b/.agents/skills/hypit/references/original-authoring/route.md@@ -46,7 +46,7 @@ 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>` |+| `vocabulary-checked` | Run-scoped vocabulary inspection and the frozen `.hypit/component-fit.json` are both persisted | `inspect_svml_vocabulary --run <run>` || `package-ready` | every project-owned package under `packages/` has a 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>` |@@ -127,7 +127,10 @@ about to invent, and this route is where that is easiest: there is no referenceFor a proven gap, read `../local-author-package.md` completely and build the package.Inspect the candidate packages now with `inspect_svml_vocabulary --package …` (without `--run`;-the Run is created in step 7). For a proven gap, build the package and keep it ready for the+the Run is created in step 7). Apply the shared fit judgement, write the concise canonical+`.hypit/component-fit.json`, and checkpoint `vocabulary-checked` as `in_progress` before package+development. User-unspecified icon, shadow, radius and other micro-details are the Agent's design+space, not automatic gaps. For a proven gap, build the package and keep it ready for theRun-scoped validation after all four source files exist. Do not treat an import or an empty packageas proof that the vocabulary gap is solved.@@ -164,6 +167,9 @@ hypit-reference-video-tools validate_local_author_packages --run build.svrunhypit-reference-video-tools validate_script_cues --run build.svrun```+The inspection completes `vocabulary-checked` only when the frozen component-fit file is still+valid.+`validate_local_author_packages` proves that every project-owned package under `packages/` has a realSurface/Producer/Fragment and is used by the compiled Source Graph. `validate_script_cues` rejectsany Cue over four visible words; split it with `||` before continuing.diff --git a/.agents/skills/hypit/references/reconstruction/comparison-round.md b/.agents/skills/hypit/references/reconstruction/comparison-round.mdindex 3a8b378a..c7378e1b 100644--- a/.agents/skills/hypit/references/reconstruction/comparison-round.md+++ b/.agents/skills/hypit/references/reconstruction/comparison-round.md@@ -144,6 +144,10 @@ The pair is always sent in one order: **one is the reference, two is the render.told that and must not be; you need it, because a difference reported "in one" is a difference in thereference and one "in two" is something to repair.+Only after the blind answer returns, read the frozen component fit. A reported difference that+exactly matches one of its accepted variances is documented rather than repaired. The observer never+receives the package name, fit rationale or variance list.+## Geometry is a first-class comparisonBefore comparing colour, typography, or motion, compare the layout hierarchy: Canvas → outerdiff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.mdindex 905c7b07..6053bf7a 100644--- a/.agents/skills/hypit/references/reconstruction/route.md+++ b/.agents/skills/hypit/references/reconstruction/route.md@@ -86,7 +86,7 @@ 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>` |+| `vocabulary-checked` | Run-scoped vocabulary inspection and the frozen `.hypit/component-fit.json` are both persisted | `inspect_svml_vocabulary --run <run>` || `package-ready` | every project-owned package under `packages/` has a 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>` |@@ -255,13 +255,14 @@ defaulted, and every conflict between observations is settled.### 13. Inspect candidate packages```bash-hypit-reference-video-tools inspect_svml_vocabulary --package @hypit/<name> [--package …] --run <build.svrun>+hypit-reference-video-tools inspect_svml_vocabulary --package @hypit/<name> [--package …]```Enumerate the systems from the observations, then inspect a candidate for each. A system you never-inspected 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.+inspected is a system you are about to invent. Apply `../vocabulary.md`'s shared fit judgement, write+the concise canonical `.hypit/component-fit.json`, and checkpoint `vocabulary-checked` as+`in_progress` before developing any gap. A small accepted variance belongs in that file; it is not a+reason to copy or modify an installed package.### 14. Develop a project-local package, only for a proven gap@@ -282,6 +283,14 @@ If no gap remains, remove unused project-owned package directories.deliverable even though this route runs nothing: without it the first thing the author meets is`RUNTIME_CAPABILITY_UNBOUND`.+Now persist the Run-scoped half of the frozen vocabulary decision. This completes+`vocabulary-checked` only when `.hypit/component-fit.json` remains valid:++```bash+hypit-reference-video-tools inspect_svml_vocabulary --package @hypit/<name> [--package …] \+ --run build.svrun+```+**Read now:**- `final-sources.md` — Segment boundaries, the forced seam, and take durations from `estimate:Speech`.diff --git a/.agents/skills/hypit/references/variant-expansion/route.md b/.agents/skills/hypit/references/variant-expansion/route.mdindex 1c2104bd..025c515e 100644--- a/.agents/skills/hypit/references/variant-expansion/route.md+++ b/.agents/skills/hypit/references/variant-expansion/route.md@@ -77,9 +77,9 @@ visuals, audio and text. README clone sets are useful evidence of the intended etheir Source, people, products, claims and assets are not templates.**Read now:** `../playbooks/index.md`. Select each variant's format from its intent. Read the matching-`formats/*.md` file completely and the craft files its footer names. Keep the base format by default.-A switch among ranking, street interview, podcast or another format is a high-change variant and must-be explicit in the plan.+format file named by that index completely and the craft files its footer names. Keep the base format+by default. A switch among ranking, street interview, podcast or another format is a high-change+variant and must be explicit in the plan.Persist `format-plan.json`. Each entry records the variant id, example basis and digest, playbook path,and frozen Format DNA: Hook, narrative progression, speaker/role grammar, layout system, timing model,@@ -123,6 +123,9 @@ Checkpoint `slate-drafted`, but do not freeze or dispatch it yet.**Read now:** `../vocabulary.md`.+Use its shared fit judgement and immutable-package boundary; `component-plan.json` records the batch+decision instead of creating a second copy of those rules.+Before any package or variant agent starts, the main agent runs:```bashdiff --git a/.agents/skills/hypit/references/vocabulary.md b/.agents/skills/hypit/references/vocabulary.mdindex aa7662cc..290f4178 100644--- a/.agents/skills/hypit/references/vocabulary.md+++ b/.agents/skills/hypit/references/vocabulary.md@@ -66,60 +66,79 @@ source is implementation, and the loader refuses a mistaken attribute against thagainst the source — so reading it neither teaches the contract nor matches how the element isvalidated.-## Reuse, compose, or declare a gap--Use this decision order:--1. Reuse one existing component when its declared vocabulary expresses the element exactly — every- property that changes what the viewer sees lands somewhere the package declares.-2. Compose multiple existing components when their declared outputs and timing express it to that- same standard, without changing what the element is.-3. Declare a real vocabulary gap when neither option works.--**Resemblance does not qualify a package.** A tag that draws the same kind of thing, or that carries-every property except one, leaves that element unexpressed, and an element the installed vocabulary-cannot express as stated is a gap. Steps 1 and 2 apply where the declared vocabulary already carries-the element as the evidence states it; step 3 is the ordinary outcome everywhere else, and-`local-author-package.md` is the route for it.--Step 2 is not a way around step 3. Composition may express one element with several components; it-may not move an element out of its role because some other tag happens to draw the same shape. What-an element **is** decides which vocabulary owns it — words spoken aloud are captions, a full-screen-designed field carrying content is one composition — and that answer does not change because the-element is styled beautifully or because the owning vocabulary is missing one property. A package-that owns the role but cannot express the required appearance is a gap, exactly as much as no package-at all: `playbooks/craft/captions.md` works one such case through.--**Do not force a similar-looking tag into a role it does not own, and never invent a component,-attribute, child, port, Recipe property or literal value** — not even with the intention of-implementing it later. A picture that `playbooks/craft/graphic-compositions.md` defines as one-self-contained graphic composition may never be split across unrelated tags to make installed-vocabulary fit.--## Resolve every declared appearance property--Declared vocabulary tells you which properties exist. It never tells you their values; only evidence-does.--Before accepting step 1 or step 2, name the appearance properties the element must have and say where-each one lands in the declared vocabulary. A property with nowhere to land is the finding, and it-makes the gap — there is no acceptable shortfall. The one thing that may not happen is quietly-authoring something else that resembles it.--The properties to account for are the drawn structure that-`playbooks/craft/graphic-compositions.md` enumerates — the type, the paint, the geometry, the stack-order and the reveal. Work from that list rather than a second copy of it.--**A default value is not a decision.** A value nobody established is not evidence, and there is no-state where a guessed value is acceptable. Where the value comes from differs by route: a-reconstruction measures it — `reconstruction/vocabulary.md` says how — and original authoring decides-it deliberately and writes it down.+## Judge component fit before writing Source++List the installed vocabulary, inspect the packages that plausibly own each visual system, and make a+short judgement. This is not a property-by-property score and it is not an exhaustive search through+unrelated packages. The Agent decides whether a candidate is close enough for the job, records why,+and chooses one of three outcomes:++- `reuse-existing`: the package owns the right role and is sufficiently close to what the program+ needs;+- `reuse-with-accepted-variance`: it is sufficiently close, but SVS cannot express a few named,+ unimportant appearance differences;+- `project-local-package`: the difference materially changes the component's core look, function,+ structure or behaviour.++Original authoring does not turn silence into a hidden specification. If the author asks for a+ranking board without defining every icon, shadow or radius, those details remain the Agent's design+space and an installed ranking component normally qualifies as `reuse-existing`. Reconstruction has+a picture to compare against, but a package that clearly represents the same visual system may still+qualify with a few low-impact skin differences recorded as accepted variance. A brand signature,+visual Hook, hierarchy, legibility, geometry or motion difference is not a small variance.+Original authoring records a variance only when the frozen brief or the author explicitly accepts+that difference; an unspecified detail is design freedom, not a variance.++Composition remains valid when several installed components genuinely express the requested system;+it may not move an element into the wrong semantic role merely because another tag draws a similar+shape. Never invent a component, attribute, child, port, Recipe property or literal value.++Installed packages are immutable dependencies. Do not modify them, copy or vendor their source into+the project, or read implementation source to discover undeclared syntax. When the fit is not good+enough, use the project-local package route and author it from the visible requirement, inspect+contract, README and `local-author-package.md`.++## Freeze the judgement++Before package development or Source authoring, write the decisions to the canonical+`.hypit/component-fit.json`. Keep it concise and record only what affected the choice:++```json+{+ "version": 1,+ "route": "description",+ "basis": ".hypit/brief.json and its frozen digest",+ "systems": [{+ "role": "ranking board",+ "inspected_candidates": ["@hypit/ranking"],+ "selected_package": "@hypit/ranking",+ "decision": "reuse-existing",+ "rationale": "same visual role and sufficiently similar presentation",+ "accepted_variances": []+ }]+}+```++`accepted_variances` contains short natural-language differences only for+`reuse-with-accepted-variance`; it is empty for the other decisions. Checkpoint the file before+developing a gap. For `project-local-package`, `selected_package` names the planned project specifier.++```bash+hypit-reference-video-tools route_state --action checkpoint --project-root <project> \+ --route description|reconstruction --state vocabulary-checked --status in_progress \+ --artifacts '{"component_fit":".hypit/component-fit.json"}'+```++The later Run-scoped `inspect_svml_vocabulary --run <run>` persists the vocabulary evidence and+completes `vocabulary-checked` only while this frozen file is valid. After compaction, read it before+resuming package work, Source authoring or visual repair.## A real gapFor a real gap, stop authoring sources and read `local-author-package.md` completely. Implement and-install the new project-local package, then run `hypit-reference-video-tools inspect_svml_vocabulary` against it before using its-tag. That call is not redundant with having just written the package: it proves the specifier+install the new project-local package, then run+`hypit-reference-video-tools inspect_svml_vocabulary` against it before using its tag. That call is+not redundant with having just written the package: it proves the specifierresolves, the activation contribution is wired, and the loader can decode the Surface. `pnpm check`proves none of those, because activation lookups fail at runtime rather than at compile time.@@ -131,7 +150,7 @@ without a project document is on the wrong side of it.After inspection, persist the result with `inspect_svml_vocabulary --run <build.svrun>`. Beforewriting or checking Source, run `validate_local_author_packages --run <build.svrun>`. Every-Every project-owned package directory under `packages/` must expose a real Surface, Producer and+project-owned package directory under `packages/` must expose a real Surface, Producer andFragment and must be imported and used by the compiled Graph; otherwise the route stops with amachine-readable diagnostic. Package directory names are descriptive slugs, not a required`local-` prefix.diff --git a/packages/reference-video-tools/src/index.ts b/packages/reference-video-tools/src/index.tsindex 9a2851da..dbbbf810 100644--- a/packages/reference-video-tools/src/index.ts+++ b/packages/reference-video-tools/src/index.ts@@ -15,6 +15,8 @@ export type {export type { MechanicalAuthoringCheckInput, ScriptCueCheckInput } from "./checks.js";export {checkpointRouteState,+ componentFitPath,+ componentFitSatisfied,readRouteState,reconcileRouteState,routeExecutionStatePath,@@ -22,6 +24,7 @@ export {startRouteState,ROUTE_STATE_STEPS,ROUTE_STATE_VERSION,+ COMPONENT_FIT_VERSION,} from "./route-state.js";export type { DescriptionRouteStep, ReconstructionRouteStep, RouteCheckpointInput, RouteKind, RouteState, RouteStateInput, RouteStep, VariantPackageRouteStep, VariantRouteStep } from "./route-state.js";export {diff --git a/packages/reference-video-tools/src/route-state.ts b/packages/reference-video-tools/src/route-state.tsindex 647d278f..c29f7cc0 100644--- a/packages/reference-video-tools/src/route-state.ts+++ b/packages/reference-video-tools/src/route-state.ts@@ -63,6 +63,13 @@ export type RouteCheckpointInput = RouteStateInput & {readonly error?: string;};+export const COMPONENT_FIT_VERSION = 1 as const;+const COMPONENT_FIT_DECISIONS = new Set([+ "reuse-existing",+ "reuse-with-accepted-variance",+ "project-local-package",+]);+export const ROUTE_STATE_VERSION = 3 as const;const PREVIOUS_ROUTE_STATE_VERSION = 2 as const;const LEGACY_ROUTE_STATE_VERSION = 1 as const;@@ -103,10 +110,72 @@ export function routeStatePath(projectRoot: string): string {return join(resolve(projectRoot), ".hypit", "route-state.json");}+export function componentFitPath(projectRoot: string): string {+ return join(resolve(projectRoot), ".hypit", "component-fit.json");+}+export function routeExecutionStatePath(projectRoot: string, routeId: string): string {return join(resolve(projectRoot), ".hypit", "routes", routeId, "state.json");}+function isCreationRoute(route: RouteKind): route is "description" | "reconstruction" {+ return route === "description" || route === "reconstruction";+}++function assertComponentFit(value: unknown, path: string, route: "description" | "reconstruction"): void {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ throw new Error(`component fit at ${path} is not an object`);+ }+ const fit = value as {+ version?: unknown;+ route?: unknown;+ basis?: unknown;+ systems?: unknown;+ };+ if (fit.version !== COMPONENT_FIT_VERSION) throw new Error(`component fit at ${path} has unsupported version`);+ if (fit.route !== route) throw new Error(`component fit at ${path} is for ${String(fit.route)}, not ${route}`);+ if (typeof fit.basis !== "string" || fit.basis.trim().length === 0) throw new Error(`component fit at ${path} has no basis`);+ if (!Array.isArray(fit.systems) || fit.systems.length === 0) throw new Error(`component fit at ${path} has no visual systems`);+ for (const [index, value] of fit.systems.entries()) {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ throw new Error(`component fit at ${path} has an invalid system at index ${index}`);+ }+ const system = value as {+ role?: unknown;+ inspected_candidates?: unknown;+ selected_package?: unknown;+ decision?: unknown;+ rationale?: unknown;+ accepted_variances?: unknown;+ };+ if (typeof system.role !== "string" || system.role.trim().length === 0) throw new Error(`component fit at ${path} system ${index} has no role`);+ if (!Array.isArray(system.inspected_candidates) || system.inspected_candidates.some((item) => typeof item !== "string")) {+ throw new Error(`component fit at ${path} system ${index} has invalid inspected_candidates`);+ }+ if (typeof system.selected_package !== "string" || system.selected_package.trim().length === 0) throw new Error(`component fit at ${path} system ${index} has no selected_package`);+ if (typeof system.decision !== "string" || !COMPONENT_FIT_DECISIONS.has(system.decision)) throw new Error(`component fit at ${path} system ${index} has an invalid decision`);+ if (typeof system.rationale !== "string" || system.rationale.trim().length === 0) throw new Error(`component fit at ${path} system ${index} has no rationale`);+ if (!Array.isArray(system.accepted_variances)) throw new Error(`component fit at ${path} system ${index} has invalid accepted_variances`);+ if (system.decision === "reuse-with-accepted-variance" && system.accepted_variances.length === 0) {+ throw new Error(`component fit at ${path} system ${index} accepts variance but names none`);+ }+ if (system.decision !== "reuse-with-accepted-variance" && system.accepted_variances.length > 0) {+ throw new Error(`component fit at ${path} system ${index} names variance for ${system.decision}`);+ }+ }+}++export async function componentFitSatisfied(projectRoot: string, route: RouteKind): Promise<boolean> {+ if (!isCreationRoute(route)) return false;+ const path = componentFitPath(projectRoot);+ try {+ assertComponentFit(JSON.parse(await readFile(path, "utf8")), path, route);+ return true;+ } catch {+ return false;+ }+}+function assertRouteState(value: unknown, path: string): asserts value is RouteState {if (value === null || typeof value !== "object") throw new Error(`route state at ${path} is not an object`);const state = value as Partial<RouteState>;@@ -311,8 +380,18 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promiseconst step = stepNumber(input.route, input.step);const completed = new Set(existing.completed_steps);const status = input.status ?? "complete";+ const artifacts = input.artifacts === undefined ? existing.artifacts : {+ ...existing.artifacts,+ ...Object.fromEntries(+ Object.entries(input.artifacts).map(([key, value]) => [key, normalizeArtifact(projectRoot, key, value)]),+ ),+ };+ if (input.artifacts?.component_fit !== undefined+ && (!isCreationRoute(input.route) || step !== stageNumber(input.route, "vocabulary-checked"))) {+ throw new Error("component_fit may be checkpointed only with vocabulary-checked on a creation route");+ }if (input.route === "description" && step === stageNumber("description", "brief-frozen") && status === "complete") {- const brief = input.artifacts?.brief ?? existing.artifacts.brief;+ const brief = artifacts.brief;const canonical = join(projectRoot, ".hypit", "brief.json");if (brief === undefined || resolve(projectRoot, brief) !== canonical) {throw new Error(`brief-frozen requires the canonical brief at ${canonical}`);@@ -327,6 +406,27 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promisethrow new Error(`the frozen base brief changed: expected ${frozenDigest}, found ${actualDigest ?? "missing"}; use Revision or a new project`);}}+ if (isCreationRoute(input.route) && step === stageNumber(input.route, "vocabulary-checked")) {+ const canonical = componentFitPath(projectRoot);+ const fit = artifacts.component_fit;+ if (fit !== undefined && fit !== canonical) throw new Error(`component fit must use the canonical path ${canonical}`);+ if (fit !== undefined && !(await componentFitSatisfied(projectRoot, input.route))) {+ throw new Error(`component fit at ${canonical} is missing or invalid`);+ }+ const frozenDigest = existing.artifact_digests.component_fit;+ const actualDigest = fit === undefined ? undefined : await digestPath(canonical);+ if (completed.has(step) && frozenDigest !== undefined && actualDigest !== frozenDigest) {+ throw new Error("component fit changed after it was frozen; run route_state reconcile before reclassifying it");+ }+ if (status === "complete") {+ if (!(await evidenceSatisfied("vocabulary", artifacts.vocabulary))) {+ throw new Error("vocabulary-checked requires valid Run-scoped vocabulary evidence");+ }+ if (fit !== canonical || !(await componentFitSatisfied(projectRoot, input.route))) {+ throw new Error(`vocabulary-checked requires the canonical component fit at ${canonical}`);+ }+ }+ }if (status === "complete") {// Named checkpoints are explicit user assertions and must not jump over earlier stages. Numeric// checkpoints remain compatible with route-aware automation, which may record a later durable@@ -341,16 +441,11 @@ export async function checkpointRouteState(input: RouteCheckpointInput): Promiseconst decisions = input.decision === undefined || input.decision.trim().length === 0 || existing.decisions.includes(input.decision)? existing.decisions: [...existing.decisions, input.decision.trim()];- const artifacts = input.artifacts === undefined ? existing.artifacts : {- ...existing.artifacts,- ...Object.fromEntries(- Object.entries(input.artifacts).map(([key, value]) => [key, normalizeArtifact(projectRoot, key, value)]),- ),- };const artifactDigests: Record<string, string> = { ...existing.artifact_digests };- const frozenKeys = new Set(["brief", "vocabulary", "baseline_manifest", "variant_brief", "allowed_changes", "guidance", "gap_plan", "types", "package_digest"]);+ const frozenKeys = new Set(["brief", "vocabulary", "component_fit", "baseline_manifest", "variant_brief", "allowed_changes", "guidance", "gap_plan", "types", "package_digest"]);for (const [key, value] of Object.entries(artifacts)) {if (!frozenKeys.has(key) && !value.includes(`${sep}.hypit${sep}evidence${sep}`)) continue;+ if (key === "component_fit" && input.artifacts?.component_fit === undefined) continue;const digest = await digestPath(value);if (digest !== undefined) artifactDigests[key] = digest;}@@ -484,6 +579,23 @@ export async function reconcileRouteState(projectRoot: string): Promise<RouteStafor (const [step, key] of Object.entries(evidenceByStep[existing.route])) {await reconcileStep(Number(step), key);}+ if (existing.status !== "complete" && isCreationRoute(existing.route)) {+ const vocabularyStep = stageNumber(existing.route, "vocabulary-checked");+ const canonical = componentFitPath(existing.project_root);+ const fitPath = artifact("component_fit");+ const expectedDigest = existing.artifact_digests.component_fit;+ const actualDigest = fitPath === undefined ? undefined : await digestPath(fitPath);+ const fitSatisfied = fitPath === canonical+ && await componentFitSatisfied(existing.project_root, existing.route)+ && expectedDigest !== undefined+ && actualDigest === expectedDigest;+ if (!fitSatisfied) {+ if (completed.has(vocabularyStep)) {+ conflicts.push(`step ${vocabularyStep} (vocabulary-checked) has no valid frozen component fit`);+ }+ for (let step = vocabularyStep; step <= ROUTE_STATE_STEPS[existing.route].length; step += 1) completed.delete(step);+ }+ }if (existing.route !== "variant-package") {const sourceName = existing.route === "variant" ? "source-updated" : "source-authored";const vocabularyName = existing.route === "variant" ? "vocabulary-verified" : "vocabulary-checked";diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.tsindex ea0d4ddf..617fb24f 100644--- a/packages/reference-video-tools/src/tools.ts+++ b/packages/reference-video-tools/src/tools.ts@@ -30,6 +30,8 @@ import { authoringCheck, mechanicalAuthoringCheck, previewCheck, reviewLogPath,import type { AuthoringCheckInput, PreviewCheckInput, ReconstructionCheckInput, ScriptCueCheckInput } from "./checks.js";import {checkpointRouteState,+ componentFitPath,+ componentFitSatisfied,readRouteState,reconcileRouteState,routeExecutionStatePath,@@ -1872,14 +1874,26 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV}const result = { packages: input.package_names, surfaces };let evidence: string | undefined;+ let componentFitRequired: string | undefined;if (input.run !== undefined) {const runPath = resolve(invokedFrom(), input.run);evidence = await persistRouteEvidence(runPath, "vocabulary.json", result);const route = await readRouteState(dirname(runPath));const step = routeStepFor(route?.route ?? "reconstruction", "vocabulary-checked");- await autoRouteCheckpoint(runPath, step, { vocabulary: evidence }, "validate_local_author_packages --run <build.svrun>");+ if (route?.route === "description" || route?.route === "reconstruction") {+ const fit = componentFitPath(dirname(runPath));+ if (await componentFitSatisfied(dirname(runPath), route.route)) {+ await autoRouteCheckpoint(runPath, step, { vocabulary: evidence, component_fit: fit }, "validate_local_author_packages --run <build.svrun>");+ } else componentFitRequired = fit;+ } else {+ await autoRouteCheckpoint(runPath, step, { vocabulary: evidence }, "validate_local_author_packages --run <build.svrun>");+ }}- return evidence === undefined ? result : { ...result, evidence };+ return evidence === undefined ? result : {+ ...result,+ evidence,+ ...(componentFitRequired === undefined ? {} : { component_fit_required: componentFitRequired }),+ };},async validate_local_author_packages(input): Promise<Record<string, unknown>> {diff --git a/packages/reference-video-tools/test/route-state.test.ts b/packages/reference-video-tools/test/route-state.test.tsindex 2dcade9e..b92fe785 100644--- a/packages/reference-video-tools/test/route-state.test.ts+++ b/packages/reference-video-tools/test/route-state.test.ts@@ -6,6 +6,7 @@ import { join } from "node:path";import {checkpointRouteState,+ componentFitPath,readRouteState,reconcileRouteState,routeStatePath,@@ -13,14 +14,34 @@ import {ROUTE_STATE_STEPS,} from "../src/route-state.js";+async function writeComponentFit(root: string, route: "description" | "reconstruction"): Promise<string> {+ const path = componentFitPath(root);+ await mkdir(join(root, ".hypit"), { recursive: true });+ await writeFile(path, JSON.stringify({+ version: 1,+ route,+ basis: route === "description" ? ".hypit/brief.json" : "reference-test",+ systems: [{+ role: "test system",+ inspected_candidates: ["@hypit/test"],+ selected_package: "@hypit/test",+ decision: "reuse-existing",+ rationale: "sufficiently similar for the test",+ accepted_variances: [],+ }],+ }), "utf8");+ return path;+}+async function completeDescriptionSourceGates(root: string): Promise<void> {const vocabulary = join(root, "vocabulary.json");+ const componentFit = await writeComponentFit(root, "description");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: 3, status: "complete", artifacts: { vocabulary, component_fit: componentFit } });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 } });}@@ -77,9 +98,18 @@ 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-"));+ const vocabulary = join(root, "vocabulary.json");+ const componentFit = await writeComponentFit(root, "reconstruction");+ await writeFile(vocabulary, JSON.stringify({ packages: [], surfaces: [] }), "utf8");await startRouteState({ projectRoot: root, route: "reconstruction" });for (let step = 1; step <= ROUTE_STATE_STEPS.reconstruction.length; step += 1) {- await checkpointRouteState({ projectRoot: root, route: "reconstruction", step, status: "complete" });+ await checkpointRouteState({+ projectRoot: root,+ route: "reconstruction",+ step,+ status: "complete",+ ...(step === 4 ? { artifacts: { vocabulary, component_fit: componentFit } } : {}),+ });}assert.equal((await readRouteState(root))?.status, "complete");const completed = await readRouteState(root);@@ -116,19 +146,24 @@ test("description reconciliation uses brief and vocabulary evidence rather thanconst root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));const brief = join(root, ".hypit", "brief.json");const vocabulary = join(root, "vocabulary.json");+ const componentFit = await writeComponentFit(root, "description");await mkdir(join(root, ".hypit"), { recursive: true });await writeFile(brief, JSON.stringify({ intent: "brief" }), "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: 3, status: "complete", artifacts: { vocabulary } });+ await checkpointRouteState({ projectRoot: root, route: "description", step: 3, status: "complete", artifacts: { vocabulary, component_fit: componentFit } });const state = await reconcileRouteState(root);assert.equal(state?.completed_steps.includes(2), true);assert.equal(state?.completed_steps.includes(3), true);assert.equal(state?.completed_steps.includes(6), false);await writeFile(brief, JSON.stringify({ intent: "changed after freeze" }), "utf8");+ await writeFile(componentFit, JSON.stringify({ changed: true }), "utf8");const conflicted = await reconcileRouteState(root);- assert.match(conflicted?.conflicts?.join("\n") ?? "", /brief digest changed/u);+ const conflicts = conflicted?.conflicts?.join("\n") ?? "";+ assert.match(conflicts, /brief digest changed/u);+ assert.match(conflicts, /component_fit digest changed/u);+ assert.equal(conflicted?.completed_steps.includes(3), false);});test("an interrupted in-progress step resumes at the first unmet step", async () => {