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: add dynamic brief intake and revision route
rpone60ad4f65cf9f
diff --git a/.agents/skills/hypit/SKILL.md b/.agents/skills/hypit/SKILL.mdindex 0b1dc772..0bef3b41 100644--- a/.agents/skills/hypit/SKILL.md+++ b/.agents/skills/hypit/SKILL.md@@ -76,6 +76,14 @@ the boundary and launcher selection. Read it before the first command of any rougiven at all. What it is for, who is in it and what it says are the author's; the workingdirectory, the project location, the packages and the generators are yours to decide rather than toask for.+- A sparse or ambiguous original request → read `references/brief-intake.md`. Discover complete+ projects under the checkout's `examples/` directory and analyze their author intent when relevant;+ otherwise use the document's general, open-ended fallback. Do not hard-code video types or skip+ the brief-sufficiency gate.+- A completed project followed by a natural-language change → read `references/revision.md` and use+ the independent `revision_state` route. Restore the element's role in the frozen brief, edit only+ Source/Recipe/Run, invalidate the affected graph closure, and rerun deterministic gates. Revision+ never invokes VLM/observer visual inspection; leave visual inspection for a later Studio session.- A syntax question about one element, or a source that already exists → read`references/authoring.md`, then `references/quickstart.md` and the linked authoritativedocs/package READMEs. A whole video is `references/original-authoring/route.md`, not this file.diff --git a/.agents/skills/hypit/references/authoring.md b/.agents/skills/hypit/references/authoring.mdindex eb6c9d0f..fe829988 100644--- a/.agents/skills/hypit/references/authoring.md+++ b/.agents/skills/hypit/references/authoring.md@@ -1,5 +1,9 @@# Hypit source authoring+For a post-completion natural-language change, use `revision.md`. That route edits Source/Recipe/Run+and reruns deterministic gates only; this authoring page's visual review guidance does not apply to a+revision.+Read `quickstart.md`, then the authoritative published page it selects.Keep Author Source, Recipe Source and Run Source complete and internally consistent rather thanassembling independent per-shot source fragments.diff --git a/.agents/skills/hypit/references/brief-intake.md b/.agents/skills/hypit/references/brief-intake.mdnew file mode 100644index 00000000..a3f7c5fa--- /dev/null+++ b/.agents/skills/hypit/references/brief-intake.md@@ -0,0 +1,63 @@+# Dynamic brief intake for original authoring++An original-authoring request is not ready for Source merely because it contains a format name or a+single sentence. First freeze a brief that is sufficient to choose the narrative, Script, visual+semantics, timing, facts and paid generation inputs.++## Discover examples, never classify by filename++From the Hypit checkout root, inspect `examples/` when it exists. Enumerate complete projects and+read each candidate's `main.svml`, `recipes.svs`, `build.svrun`, and relevant package README. A+read-only `hypit check` is allowed. Do not copy its Source, facts, people, assets, prompts or source+closure into the new project. Directory names, file names and component counts are only search clues.++For each candidate, read in this order:++```text+Script / Narrative+→ what the author wants the viewer to understand, believe, feel or do+→ opening attention strategy and Hook+→ narrative expansion, proof, reversal and payoff+→ visual, audio and text relationships+→ Recipe / Surface expression+→ Graph / Run implementation+```++Write an intent summary in your own words. It must distinguish what the Source explicitly says from+what you infer, and identify decisions that affect Graph structure, Script cuts, visual meaning,+timing, factual claims or paid generation. Compare the user's request with that summary. Ask only+for the high-impact decisions the request leaves unresolved. Never turn an example into a template or+a hard-coded type-specific questionnaire; an opening provocation is evidence of that author's Hook,+not a rule for a purported format.++## General fallback when no example matches++If `examples/` is absent, empty, or semantically unlike the request, do not start Source and do not+skip intake. Use the user's words, installed vocabulary, craft references and the compilable SVML/SVS+/SVRun structure to derive an open-ended intent hypothesis:++- the promised viewer result and the central claim or tension;+- a plausible attention strategy and what expectation it creates;+- how the idea should develop and resolve;+- which visual, audio and text changes carry that meaning;+- which decisions are already made, which low-risk implementation details you may choose, and which+ core facts, claims, Hook, audience promise, timing or paid inputs require confirmation.++This is an analysis method, not a list of ranking, interview, podcast or other type questions. Keep+the brief unfrozen while any unresolved answer could change the program's intent or graph.++## Durable brief++Persist a concise `.hypit/brief` file (JSON or Markdown; do not put it in Author Source) containing:++- user goal and audience;+- intent, Hook/attention strategy and narrative progression;+- visual/audio/text relationships;+- example project path and digest, or the general-analysis basis;+- confirmed decisions and unresolved questions;+- the expected SVML/SVS/SVRun structural consequences.++Checkpoint `brief-frozen` only after unresolved questions no longer affect those consequences. An+agent may select fonts, package details and model tier when they are genuinely low risk; it may not+invent core facts, ranking criteria, claims, Hook or audience promises. The brief is the reference for+later review and revision, not a copy of an example.diff --git a/.agents/skills/hypit/references/element-review.md b/.agents/skills/hypit/references/element-review.mdindex 61729539..f01bcad0 100644--- a/.agents/skills/hypit/references/element-review.md+++ b/.agents/skills/hypit/references/element-review.md@@ -1,5 +1,9 @@# Looking at what was built, before a Build runs+This visual-review page is for the initial reconstruction/description routes. A post-completion+revision does not use it, does not call a VLM/observer, and stops after deterministic gates; see+`revision.md`.+Structural checks prove that a source is legal. They prove nothing about whether it looks like whatwas wanted. A newly written package can resolve, activate, decode and pass every check while drawingsomething nobody asked for. Close that gap deliberately.diff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.mdindex d8253312..d52b7990 100644--- a/.agents/skills/hypit/references/original-authoring/route.md+++ b/.agents/skills/hypit/references/original-authoring/route.md@@ -13,8 +13,12 @@ between the two — what a picture is, what one generation owes another, which p**This route spends.** One Build generates the pictures, the takes, the speech and the render, andstep 13 is where the author says yes to it. There is no reference to check against, so the two thingsa reconstruction gets for free have to be decided deliberately: what the program is *for*, and what-every appearance value *is*. Neither has an evidence file to consult. Write them down rather than-discovering them at render time.+ every appearance value *is*. Neither has an evidence file to consult. Write them down rather than+ discovering them at render time.++If a completed project receives a natural-language change, use `../revision.md` instead of restarting+this route. Revision is Source/Recipe/Run-only and deterministic; it does not invoke a VLM or visual+observer.## Checkpoint and recovery@@ -75,13 +79,19 @@ set -a && source .env && set +a**Read now:** `../credentials.md` — which variables each Provider needs.-### 3. Ask what the description leaves out+### 3. Make the brief sufficient before writing Source-What is missing from a description is usually the duration, the aspect ratio and the language. Ask-those together, once. Ask about the video and nothing else.+**Read now:** `../brief-intake.md`. If this is a sparse or ambiguous request, inspect complete+projects under the checkout root's `examples/` directory and compare their recovered author intent,+Hook and narrative to the request. If no example is semantically relevant, use the document's+general fallback; absence of an example is not permission to guess or skip intake.-Freeze the answers along with the Script's meaning, the format, the supplied assets and the factual-claims before any prompt is written. Everything downstream is measured against them.+Ask only for unresolved, high-impact creative decisions. Freeze a concise `.hypit/brief` recording+the user's goal, audience, intent, Hook, narrative progression, visual/audio/text relationships,+claims, confirmed decisions, unresolved questions, and expected SVML/SVS/SVRun consequences. Low-risk+implementation details are yours; core facts, claims, Hook and audience promise require confirmation.+Do not enter `brief-frozen` or write paid-generation prompts until no unresolved answer can change the+Graph, Script, visual semantics, timing or generation inputs.### 4. Read the craft this program needsdiff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.mdindex a5d145bf..87071767 100644--- a/.agents/skills/hypit/references/preview.md+++ b/.agents/skills/hypit/references/preview.md@@ -1,5 +1,9 @@# See what you authored, without paying+Revision work does not invoke the visual-review workflow described below. It may run deterministic+preview checks (and optionally render for artifact integrity), but never calls a VLM/observer; read+`revision.md` for that route.+`preview_check` and `render_element` advance the project's `.hypit/route-state.json` only after theirsuccess 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.diff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.mdindex 6a2cd201..c7b88e94 100644--- a/.agents/skills/hypit/references/reconstruction/route.md+++ b/.agents/skills/hypit/references/reconstruction/route.md@@ -13,6 +13,10 @@ Those belong to the Build the author starts deliberately, after reading what wasSeeing the reconstruction is what that Build is for. What is settled here is that the graph traces,which is the part a Build cannot repair.+If the project is already complete and the author asks for a natural-language change, stop following+this creation route and read `../revision.md`. Revision edits Source/Recipe/Run and reruns deterministic+gates; it does not invoke a VLM or visual observer.+One exception, because it is not a generation of the video: a component's own surface — the field itselements are drawn on — is produced while the package is authored, with `hypit image`, and committedinside the package. `../playbooks/craft/generated-dependencies.md` draws that line.diff --git a/.agents/skills/hypit/references/recovery.md b/.agents/skills/hypit/references/recovery.mdindex e841515f..39f03232 100644--- a/.agents/skills/hypit/references/recovery.md+++ b/.agents/skills/hypit/references/recovery.md@@ -26,6 +26,11 @@ Use `--route description` for original-authoring and `--route reconstruction` fowork. A project has one active route; a route mismatch is an error rather than an invitation to mergetwo histories.+For a completed project with a new natural-language change, use `.hypit/revision-state.json` and the+`revision_state` commands described in `revision.md`. Reconcile both the parent route snapshot and+the revision snapshot before editing. Revision does not call VLM/observer, render, or perform visual+review; it stops after the requested deterministic gates and leaves Studio untouched.+## What the state meansThe state is a small snapshot, not a transcript. It records the current route step, completed steps,diff --git a/.agents/skills/hypit/references/revision.md b/.agents/skills/hypit/references/revision.mdnew file mode 100644index 00000000..986755a9--- /dev/null+++ b/.agents/skills/hypit/references/revision.md@@ -0,0 +1,57 @@+# Post-completion natural-language revision route++When a completed reconstruction or description project receives a request such as “move this element+right” or “raise the captions”, start a separate revision route. Do not edit the rendered MP4, PNG,+WAV, preview mock or Artifact directly. The source remains authoritative.++## Recovery and state++Read `SKILL.md`, `recovery.md`, the parent `.hypit/route-state.json`, the project's+`.hypit/revision-state.json`, and `git status`. Start the state once:++```bash+hypit-reference-video-tools revision_state --action start \+ --project-root <project> --run build.svrun --parent-route description \+ --request 'raise the captions slightly'+```++The snapshot is atomic and small. It records the parent route/state digest, request summary, impact+and affected Source, durable artifact references, decisions, current stage and `next_action`.+Use `revision_state read` and `revision_state reconcile` after interruption or context compaction;+never resume from chat memory. Manual intent mapping and Source edits require an explicit checkpoint.+Machine evidence may advance only when its file/check predicate is true.++Stages are:++```text+request-captured → impact-assessed → intent-mapped → source-updated+→ gates-checked → preview-rendered → review-complete → final-checked+→ revision-complete → build-complete (only if paid generation changed)+```++`preview-rendered` and `review-complete` are not required work in this route. `review-complete` is+deliberately not a VLM/observer step. Revision does not call+`review_element`, `compare_reconstruction`, Vertex, WhisperX or any other visual observer. Mark that+stage only as an explicit mechanical checkpoint when the requested source change has been covered by+the deterministic checks. No visual acceptance work is implied here; leave Studio untouched unless+the user later asks to open it.++## Work sequence++1. Read the current `main.svml`, `recipes.svs`, `build.svrun`, runtime profile, brief and the target+ package README/vocabulary. Recover the target element's role in the author's intent.+2. Classify the request's impact: geometry/style, Script/semantic timing, graph structure, or paid+ generation. Record the affected Source files and the smallest invalidated graph closure.+3. Map natural language to the authoritative field before editing. “字幕往上一点” is a+ Frame/Placement/Recipe/Style change; a changed line is a Cue/SemanticTake/timing change; a new+ component is a vocabulary-gap and package change. A Hook or opening change also requires checking+ that later beats still fulfil its promise.+4. Edit only Source, Recipe or Run. Re-run package/Cue gates, `hypit check`, `preview_check`, and the+ route-specific final check. Do not render, compare, review or inspect any frame during revision;+ existing unchanged artifacts may be reused by digest.+5. Check the final gate. Confirm cost again only when an image/video/voice generation input changed;+ geometry and layout revisions do not trigger a paid Build. Build only after explicit approval.++Revision never edits or regenerates mock media. If a later, explicit Studio session previews the+updated Run, that session must continue using the existing SVRun-native preview-mock path; never+revive `make_placeholder`, hand-written SemanticTracks, or absolute-path mock Candidates.diff --git a/packages/reference-video-tools/README.md b/packages/reference-video-tools/README.mdindex cb0ec45a..26bd9c49 100644--- a/packages/reference-video-tools/README.md+++ b/packages/reference-video-tools/README.md@@ -2,11 +2,16 @@CLI tools for reconstructing a reference video with Hypit.-The package exposes six CLI subcommands: `list_svml_packages`, `prepare_reference`,+The package exposes reference-observation, vocabulary/gate, rendering, review, route-state and+revision-state CLI subcommands, including `list_svml_packages`, `prepare_reference`,`observe_reference`, `record_observation`, `inspect_svml_vocabulary`, and `compare_reconstruction`.Each command prints one JSON result to stdout. The final source files are authored by the callingagent and checked with the installed `hypit check` command.+For a completed project change, `revision_state --action start|read|checkpoint|reconcile` stores a+small atomic `.hypit/revision-state.json` snapshot. Revision edits Source/Recipe/Run and reruns+deterministic gates; it does not invoke a VLM/observer or perform visual review.+`--observer` on `prepare_reference` chooses who reads the reference, once per reference:- `gemini` uploads the shot clips and the whole video to Vertex at a fixed temperature of `1.0`. Itdiff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.tsindex fbdd39fe..237ca33f 100644--- a/packages/reference-video-tools/src/cli.ts+++ b/packages/reference-video-tools/src/cli.ts@@ -2,7 +2,7 @@import { readFile } from "node:fs/promises";import { createReferenceVideoTools } from "./tools.js";-import type { CompareReconstructionInput, ObserveReferenceInput, RecordObservationInput, RenderElementInput, ReviewElementInput, RouteStateCommandInput } from "./tools.js";+import type { CompareReconstructionInput, ObserveReferenceInput, RecordObservationInput, RenderElementInput, ReviewElementInput, RouteStateCommandInput, RevisionStateCommandInput } from "./tools.js";/*** A word range written on the command line as `from:to`, half-open.@@ -27,6 +27,7 @@ function usage(): string {"Usage:"," hypit-reference-video-tools list_svml_packages"," hypit-reference-video-tools route_state --action start|read|checkpoint|reconcile --project-root <dir> [options]",+ " hypit-reference-video-tools revision_state --action start|read|checkpoint|reconcile --project-root <dir> [options]"," start: --route reconstruction|description [--run <run>] [--reference-id <id>]"," checkpoint: --route <route> --step <n> [--status in_progress|complete|blocked] [--next-action <text>] [--artifacts <json>]"," read/reconcile: --project-root <dir>",@@ -313,6 +314,51 @@ async function main(): Promise<void> {...(one(flags, "error") === undefined ? {} : { error: one(flags, "error") }),} as RouteStateCommandInput);}+ } else if (command === "revision_state") {+ const action = typeof supplied?.action === "string" ? supplied.action : one(flags, "action");+ if (action !== "start" && action !== "read" && action !== "checkpoint" && action !== "reconcile") {+ throw new Error("--action must be start, read, checkpoint or reconcile");+ }+ const projectRoot = typeof supplied?.project_root === "string" ? supplied.project_root : required(flags, "project-root");+ if (supplied !== undefined) {+ result = await tools.revision_state(supplied as RevisionStateCommandInput);+ } else if (action === "start") {+ const parentRoute = one(flags, "parent-route");+ if (parentRoute !== undefined && parentRoute !== "reconstruction" && parentRoute !== "description") throw new Error("--parent-route must be reconstruction or description");+ result = await tools.revision_state({ action, project_root: projectRoot,+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),+ ...(parentRoute === undefined ? {} : { parent_route: parentRoute }),+ ...(one(flags, "parent-state-digest") === undefined ? {} : { parent_state_digest: one(flags, "parent-state-digest") }),+ ...(one(flags, "request") === undefined ? {} : { request: one(flags, "request") }),+ } as RevisionStateCommandInput);+ } else if (action === "read" || action === "reconcile") {+ result = await tools.revision_state({ action, project_root: projectRoot });+ } else {+ const stepRaw = required(flags, "step");+ const numericStep = Number(stepRaw);+ const step: number | string = Number.isSafeInteger(numericStep) && numericStep >= 1 ? numericStep : stepRaw;+ const status = one(flags, "status");+ if (status !== undefined && status !== "in_progress" && status !== "complete" && status !== "blocked") throw new Error("--status must be in_progress, complete or blocked");+ let artifacts: Readonly<Record<string, string>> | undefined;+ const artifactRaw = one(flags, "artifacts");+ if (artifactRaw !== undefined) {+ try { artifacts = JSON.parse(artifactRaw) as Readonly<Record<string, string>>; } catch (error) { throw new Error(`--artifacts is not valid JSON: ${error instanceof Error ? error.message : String(error)}`); }+ }+ result = await tools.revision_state({ action, project_root: projectRoot, step,+ ...(status === undefined ? {} : { status }),+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),+ ...(one(flags, "parent-route") === undefined ? {} : { parent_route: one(flags, "parent-route") as "reconstruction" | "description" }),+ ...(one(flags, "parent-state-digest") === undefined ? {} : { parent_state_digest: one(flags, "parent-state-digest") }),+ ...(one(flags, "request") === undefined ? {} : { request: one(flags, "request") }),+ ...(one(flags, "next-action") === undefined ? {} : { next_action: one(flags, "next-action") }),+ ...(artifacts === undefined ? {} : { artifacts }),+ ...(one(flags, "decision") === undefined ? {} : { decision: one(flags, "decision") }),+ ...(one(flags, "command") === undefined ? {} : { command: one(flags, "command") }),+ ...(one(flags, "error") === undefined ? {} : { error: one(flags, "error") }),+ ...(many(flags, "impact").length === 0 ? {} : { impact: many(flags, "impact") }),+ ...(many(flags, "affected-source").length === 0 ? {} : { affected_source: many(flags, "affected-source") }),+ } as RevisionStateCommandInput);+ }} else if (command === "prepare_reference") {const observer = one(flags, "observer");if (observer !== undefined && observer !== "gemini" && observer !== "agent") throw new Error("--observer must be gemini or agent");diff --git a/packages/reference-video-tools/src/index.ts b/packages/reference-video-tools/src/index.tsindex cfb9d41b..04bdcdec 100644--- a/packages/reference-video-tools/src/index.ts+++ b/packages/reference-video-tools/src/index.ts@@ -7,6 +7,7 @@ export type {InspectVocabularyInput,ValidateLocalAuthorPackagesInput,RouteStateCommandInput,+ RevisionStateCommandInput,} from "./tools.js";export type { ScriptCueCheckInput } from "./checks.js";export {@@ -19,3 +20,13 @@ export {ROUTE_STATE_VERSION,} from "./route-state.js";export type { RouteCheckpointInput, RouteKind, RouteState, RouteStateInput } from "./route-state.js";+export {+ checkpointRevisionState,+ readRevisionState,+ reconcileRevisionState,+ revisionStatePath,+ startRevisionState,+ REVISION_STATE_VERSION,+ REVISION_STEPS,+} from "./revision-state.js";+export type { RevisionCheckpointInput, RevisionState, RevisionStateInput, RevisionStatus, RevisionStep } from "./revision-state.js";diff --git a/packages/reference-video-tools/src/revision-state.ts b/packages/reference-video-tools/src/revision-state.tsnew file mode 100644index 00000000..ca727e34--- /dev/null+++ b/packages/reference-video-tools/src/revision-state.ts@@ -0,0 +1,226 @@+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";+import { createHash } from "node:crypto";+import { dirname, join, resolve } from "node:path";++/** A durable, small snapshot for a post-completion natural-language revision. */+export type RevisionStatus = "active" | "complete" | "blocked";+export type RevisionStep =+ | "request-captured"+ | "impact-assessed"+ | "intent-mapped"+ | "source-updated"+ | "gates-checked"+ | "preview-rendered"+ | "review-complete"+ | "final-checked"+ | "revision-complete"+ | "build-complete";++export const REVISION_STATE_VERSION = 1 as const;+export const REVISION_STEPS: readonly RevisionStep[] = [+ "request-captured", "impact-assessed", "intent-mapped", "source-updated", "gates-checked",+ "preview-rendered", "review-complete", "final-checked", "revision-complete", "build-complete",+];++export type RevisionState = {+ readonly version: 1;+ readonly project_root: string;+ readonly run?: string;+ readonly parent_route?: "reconstruction" | "description";+ readonly parent_state_digest?: string;+ readonly status: RevisionStatus;+ readonly current_step: number;+ readonly completed_steps: readonly number[];+ readonly in_progress: { readonly step: number; readonly started_at: string } | null;+ readonly request?: string;+ readonly impact?: readonly string[];+ readonly affected_source?: readonly string[];+ readonly artifacts: Readonly<Record<string, string>>;+ readonly decisions: readonly string[];+ readonly next_action: string;+ readonly last_command?: string;+ readonly last_error?: string;+ readonly conflicts?: readonly string[];+ readonly updated_at: string;+};++export type RevisionStateInput = {+ readonly projectRoot: string;+ readonly run?: string;+ readonly parentRoute?: "reconstruction" | "description";+ readonly parentStateDigest?: string;+ readonly request?: string;+};++export type RevisionCheckpointInput = RevisionStateInput & {+ readonly step: number | RevisionStep;+ readonly status?: "in_progress" | "complete" | "blocked";+ readonly nextAction?: string;+ readonly artifacts?: Readonly<Record<string, string>>;+ readonly decision?: string;+ readonly command?: string;+ readonly error?: string;+ readonly impact?: readonly string[];+ readonly affectedSource?: readonly string[];+};++export function revisionStatePath(projectRoot: string): string {+ return join(resolve(projectRoot), ".hypit", "revision-state.json");+}++function nextUncompleted(completed: readonly number[]): number {+ const done = new Set(completed);+ for (let step = 1; step <= REVISION_STEPS.length; step += 1) if (!done.has(step)) return step;+ return REVISION_STEPS.length + 1;+}++function stepNumber(step: RevisionStep | number): number {+ if (typeof step === "number") {+ if (!Number.isSafeInteger(step) || step < 1 || step > REVISION_STEPS.length) throw new Error(`revision step ${step} is outside the revision route`);+ return step;+ }+ const index = REVISION_STEPS.indexOf(step);+ if (index < 0) throw new Error(`unknown revision step ${step}`);+ return index + 1;+}++function assertState(value: unknown, path: string): asserts value is RevisionState {+ if (value === null || typeof value !== "object") throw new Error(`revision state at ${path} is not an object`);+ const state = value as Partial<RevisionState>;+ if (state.version !== REVISION_STATE_VERSION) throw new Error(`revision state at ${path} has unsupported version`);+ if (typeof state.project_root !== "string" || state.project_root.length === 0) throw new Error(`revision state at ${path} has no project_root`);+ if (state.parent_route !== undefined && state.parent_route !== "reconstruction" && state.parent_route !== "description") throw new Error(`revision state at ${path} has invalid parent_route`);+ if (state.run !== undefined && typeof state.run !== "string") throw new Error(`revision state at ${path} has invalid run`);+ if (state.request !== undefined && typeof state.request !== "string") throw new Error(`revision state at ${path} has invalid request`);+ if (!REVISION_STEPS.length || typeof state.status !== "string" || !["active", "complete", "blocked"].includes(state.status)) throw new Error(`revision state at ${path} has invalid status`);+ if (typeof state.current_step !== "number" || !Number.isSafeInteger(state.current_step) || state.current_step < 1 || state.current_step > REVISION_STEPS.length + 1) throw new Error(`revision state at ${path} has invalid current_step`);+ if (!Array.isArray(state.completed_steps) || state.completed_steps.some((step) => !Number.isSafeInteger(step) || step < 1 || step > REVISION_STEPS.length)) throw new Error(`revision state at ${path} has invalid completed_steps`);+ if (state.in_progress !== null && (state.in_progress === undefined || typeof state.in_progress !== "object" || !Number.isSafeInteger(state.in_progress.step))) throw new Error(`revision state at ${path} has invalid in_progress`);+ if (state.artifacts === null || typeof state.artifacts !== "object" || Array.isArray(state.artifacts)) throw new Error(`revision state at ${path} has invalid artifacts`);+ if (!Array.isArray(state.decisions) || state.decisions.some((item) => typeof item !== "string")) throw new Error(`revision state at ${path} has invalid decisions`);+ if (state.impact !== undefined && (!Array.isArray(state.impact) || state.impact.some((item) => typeof item !== "string"))) throw new Error(`revision state at ${path} has invalid impact`);+ if (state.affected_source !== undefined && (!Array.isArray(state.affected_source) || state.affected_source.some((item) => typeof item !== "string"))) throw new Error(`revision state at ${path} has invalid affected_source`);+ if (typeof state.next_action !== "string" || typeof state.updated_at !== "string") throw new Error(`revision state at ${path} is missing recovery fields`);+}++async function writeRevisionState(state: RevisionState): Promise<RevisionState> {+ const path = revisionStatePath(state.project_root);+ await mkdir(dirname(path), { recursive: true });+ const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, "utf8");+ await rename(temporary, path);+ return state;+}++export async function readRevisionState(projectRoot: string): Promise<RevisionState | undefined> {+ const path = revisionStatePath(projectRoot);+ const text = await readFile(path, "utf8").catch((error: unknown) => {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ });+ if (text === undefined) return undefined;+ let parsed: unknown;+ try { parsed = JSON.parse(text); } catch (error) {+ throw new Error(`revision state at ${path} is invalid JSON; original file was preserved: ${error instanceof Error ? error.message : String(error)}`);+ }+ assertState(parsed, path);+ return parsed;+}++export async function startRevisionState(input: RevisionStateInput): Promise<RevisionState> {+ const projectRoot = resolve(input.projectRoot);+ const existing = await readRevisionState(projectRoot);+ if (existing !== undefined && existing.status !== "complete") throw new Error(`project already has an active revision at ${revisionStatePath(projectRoot)}`);+ const parentPath = join(projectRoot, ".hypit", "route-state.json");+ const parentBytes = await readFile(parentPath).catch(() => undefined);+ const parentStateDigest = input.parentStateDigest ?? (parentBytes === undefined ? undefined : `sha256:${createHash("sha256").update(parentBytes).digest("hex")}`);+ let parentRoute = input.parentRoute;+ if (parentRoute === undefined && parentBytes !== undefined) {+ try {+ const parsed = JSON.parse(parentBytes.toString()) as { route?: unknown };+ if (parsed.route === "reconstruction" || parsed.route === "description") parentRoute = parsed.route;+ } catch { /* parent route remains explicit/unknown; recovery can still inspect the file */ }+ }+ const now = new Date().toISOString();+ return writeRevisionState({+ version: 1, project_root: projectRoot, status: "active", current_step: 1, completed_steps: [],+ in_progress: { step: 1, started_at: now }, artifacts: {}, decisions: [],+ ...(input.run === undefined ? {} : { run: resolve(projectRoot, input.run) }),+ ...(parentRoute === undefined ? {} : { parent_route: parentRoute }),+ ...(parentStateDigest === undefined ? {} : { parent_state_digest: parentStateDigest }),+ ...(input.request === undefined ? {} : { request: input.request }),+ next_action: `complete ${REVISION_STEPS[0]}`,+ updated_at: now,+ });+}++export async function checkpointRevisionState(input: RevisionCheckpointInput): Promise<RevisionState> {+ const projectRoot = resolve(input.projectRoot);+ const existing = await readRevisionState(projectRoot);+ if (existing === undefined) throw new Error(`no revision state at ${revisionStatePath(projectRoot)}; run revision_state start first`);+ const step = stepNumber(input.step);+ const completed = new Set(existing.completed_steps);+ if (input.status === "complete") completed.add(step);+ const completedSteps = [...completed].sort((a, b) => a - b);+ const next = input.status === "complete" ? nextUncompleted(completedSteps) : step;+ const now = new Date().toISOString();+ const artifacts = input.artifacts === undefined ? existing.artifacts : {+ ...existing.artifacts,+ ...Object.fromEntries(Object.entries(input.artifacts).map(([key, value]) => [key, resolve(projectRoot, value)])),+ };+ const decisions = input.decision === undefined || input.decision.trim().length === 0 || existing.decisions.includes(input.decision)+ ? existing.decisions : [...existing.decisions, input.decision.trim()];+ return writeRevisionState({+ ...existing,+ ...(input.run === undefined ? {} : { run: resolve(projectRoot, input.run) }),+ ...(input.parentRoute === undefined ? {} : { parent_route: input.parentRoute }),+ ...(input.parentStateDigest === undefined ? {} : { parent_state_digest: input.parentStateDigest }),+ ...(input.request === undefined ? {} : { request: input.request }),+ ...(input.impact === undefined ? {} : { impact: [...input.impact] }),+ ...(input.affectedSource === undefined ? {} : { affected_source: [...input.affectedSource] }),+ status: input.status === "blocked" ? "blocked" : next > REVISION_STEPS.length ? "complete" : "active",+ current_step: next,+ completed_steps: completedSteps,+ in_progress: input.status === "in_progress" ? { step, started_at: now } : input.status === "complete" ? (next > REVISION_STEPS.length ? null : { step: next, started_at: now }) : existing.in_progress,+ artifacts, decisions,+ next_action: input.nextAction?.trim() || (next > REVISION_STEPS.length ? "revision complete" : `complete ${REVISION_STEPS[next - 1]}`),+ ...(input.command === undefined ? {} : { last_command: input.command }),+ ...(input.error === undefined ? {} : { last_error: input.error }),+ updated_at: now,+ });+}++async function fileExists(path: string | undefined): Promise<boolean> {+ return path !== undefined && await stat(path).then((value) => value.isFile(), () => false);+}++/** Reconcile only machine-verifiable revision stages; creative mapping and review stay explicit. */+export async function reconcileRevisionState(projectRoot: string): Promise<RevisionState | undefined> {+ const existing = await readRevisionState(projectRoot);+ if (existing === undefined) return undefined;+ const completed = new Set(existing.completed_steps);+ const conflicts: string[] = [];+ const checks: Readonly<Record<number, string>> = {+ 5: "gates_check", 6: "preview_render", 8: "final_check", 10: "build",+ };+ for (const [rawStep, key] of Object.entries(checks)) {+ const step = Number(rawStep);+ const present = await fileExists(existing.artifacts[key]);+ if (present) completed.add(step);+ else if (completed.has(step)) { completed.delete(step); conflicts.push(`step ${step} (${key}) was marked complete but its evidence is missing`); }+ }+ // A later machine artifact cannot silently credit the manual intent/source stages.+ const next = nextUncompleted([...completed]);+ const now = new Date().toISOString();+ const { conflicts: _old, ...base } = existing;+ return writeRevisionState({+ ...base,+ status: next > REVISION_STEPS.length ? "complete" : existing.status === "blocked" ? "blocked" : "active",+ current_step: next,+ completed_steps: [...completed].sort((a, b) => a - b),+ in_progress: next > REVISION_STEPS.length ? null : { step: next, started_at: now },+ next_action: next > REVISION_STEPS.length ? "revision complete" : `complete ${REVISION_STEPS[next - 1]}`,+ ...(conflicts.length === 0 ? {} : { conflicts }),+ updated_at: now,+ });+}diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.tsindex cf68f8c3..6d5aedaf 100644--- a/packages/reference-video-tools/src/tools.ts+++ b/packages/reference-video-tools/src/tools.ts@@ -36,6 +36,14 @@ import {ROUTE_STATE_STEPS,} from "./route-state.js";import type { RouteKind, RouteState } from "./route-state.js";+import {+ checkpointRevisionState,+ readRevisionState,+ reconcileRevisionState,+ revisionStatePath,+ startRevisionState,+} from "./revision-state.js";+import type { RevisionState, RevisionStep } from "./revision-state.js";import {assert,completelyStill,@@ -188,6 +196,11 @@ export type RouteStateCommandInput =| ({ readonly action: "read" | "reconcile"; readonly project_root: string })| ({ readonly action: "checkpoint"; readonly project_root: string; readonly route: RouteKind; readonly step: number; readonly status?: "in_progress" | "complete" | "blocked"; readonly run?: string; readonly reference_id?: string; readonly next_action?: string; readonly artifacts?: Readonly<Record<string, string>>; readonly decision?: string; readonly command?: string; readonly error?: string });+export type RevisionStateCommandInput =+ | ({ readonly action: "start"; readonly project_root: string; readonly run?: string; readonly parent_route?: "reconstruction" | "description"; readonly parent_state_digest?: string; readonly request?: string })+ | ({ readonly action: "read" | "reconcile"; readonly project_root: string })+ | ({ readonly action: "checkpoint"; readonly project_root: string; readonly step: number | RevisionStep; readonly status?: "in_progress" | "complete" | "blocked"; readonly run?: string; readonly parent_route?: "reconstruction" | "description"; readonly parent_state_digest?: string; readonly request?: string; readonly next_action?: string; readonly artifacts?: Readonly<Record<string, string>>; readonly decision?: string; readonly command?: string; readonly error?: string; readonly impact?: readonly string[]; readonly affected_source?: readonly string[] });+export type { RenderElementInput, RenderPreviewsInput } from "./authoring.js";export type { PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";@@ -216,6 +229,7 @@ export type ReferenceVideoTools = {*/authoring_check(input: Omit<AuthoringCheckInput, "mode" | "reference_id">): Promise<Record<string, unknown>>;route_state(input: RouteStateCommandInput): Promise<Record<string, unknown>>;+ revision_state(input: RevisionStateCommandInput): Promise<Record<string, unknown>>;};type ToolOptions = {@@ -233,6 +247,10 @@ function routeStateResult(state: RouteState | undefined): Record<string, unknownreturn state === undefined ? { state: null } : { state, path: routeStatePath(state.project_root) };}+function revisionStateResult(state: RevisionState | undefined): Record<string, unknown> {+ return state === undefined ? { state: null } : { state, path: revisionStatePath(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`);@@ -263,6 +281,37 @@ async function runRouteStateCommand(input: RouteStateCommandInput): Promise<Recoreturn routeStateResult(state);}+async function runRevisionStateCommand(input: RevisionStateCommandInput): Promise<Record<string, unknown>> {+ if (input.action === "start") {+ return revisionStateResult(await startRevisionState({+ projectRoot: input.project_root,+ ...(input.run === undefined ? {} : { run: input.run }),+ ...(input.parent_route === undefined ? {} : { parentRoute: input.parent_route }),+ ...(input.parent_state_digest === undefined ? {} : { parentStateDigest: input.parent_state_digest }),+ ...(input.request === undefined ? {} : { request: input.request }),+ }));+ }+ if (input.action === "read") return revisionStateResult(await readRevisionState(input.project_root));+ if (input.action === "reconcile") return revisionStateResult(await reconcileRevisionState(input.project_root));+ if (input.action !== "checkpoint") throw new Error(`unsupported revision state action ${input.action}`);+ return revisionStateResult(await checkpointRevisionState({+ projectRoot: input.project_root,+ step: input.step,+ ...(input.status === undefined ? {} : { status: input.status }),+ ...(input.run === undefined ? {} : { run: input.run }),+ ...(input.parent_route === undefined ? {} : { parentRoute: input.parent_route }),+ ...(input.parent_state_digest === undefined ? {} : { parentStateDigest: input.parent_state_digest }),+ ...(input.request === undefined ? {} : { request: input.request }),+ ...(input.next_action === undefined ? {} : { nextAction: input.next_action }),+ ...(input.artifacts === undefined ? {} : { artifacts: input.artifacts }),+ ...(input.decision === undefined ? {} : { decision: input.decision }),+ ...(input.command === undefined ? {} : { command: input.command }),+ ...(input.error === undefined ? {} : { error: input.error }),+ ...(input.impact === undefined ? {} : { impact: input.impact }),+ ...(input.affected_source === undefined ? {} : { affectedSource: input.affected_source }),+ }));+}+async function autoRouteCheckpoint(runPath: string | undefined,step: number,@@ -2379,6 +2428,10 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVasync route_state(input): Promise<Record<string, unknown>> {return await runRouteStateCommand(input);},++ async revision_state(input): Promise<Record<string, unknown>> {+ return await runRevisionStateCommand(input);+ },};return tools;}