Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: add resumable route state recovery (#100)

rponeawa9d4f00c25f69
diff --git a/.agents/skills/hypit/SKILL.md b/.agents/skills/hypit/SKILL.md
index b67f211f..22ce0e4d 100644
--- a/.agents/skills/hypit/SKILL.md
+++ b/.agents/skills/hypit/SKILL.md
@@ -28,6 +28,12 @@ names the files it needs; read those when you reach that step rather than all of
Keep `.svml` Author Source, `.svs` Recipe Source, `.svrun` Run Source, and
`hypit.runtime.json` Runtime Profile as separate languages and responsibilities.
+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 checks
+before continuing. Never resume from chat memory alone, and never repeat a completed or paid step
+without verifying its durable evidence.
+
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.
@@ -66,6 +72,8 @@ the boundary and launcher selection. Read it before the first command of any rou
at the step that proves a vocabulary gap.
- Seeing what the sources produce, or proving the graph traces before any Build → read
`references/preview.md`.
+- Recovering after interruption or context compaction → read `references/recovery.md` before any
+ other route step.
- Preview-only media realization, temporary preview Runs, mock Artifact caching, or estimated
SemanticTake timing → read `references/preview-mock.md`.
- Runtime setup, plan/build/status/inspect/get/reuse → read `references/runtime.md`.
diff --git a/.agents/skills/hypit/references/authoring.md b/.agents/skills/hypit/references/authoring.md
index 1a3b772e..4247c423 100644
--- a/.agents/skills/hypit/references/authoring.md
+++ b/.agents/skills/hypit/references/authoring.md
@@ -27,6 +27,9 @@ syntax, its references, its graph structure — and proves nothing about whether
can actually be built, nor that an uncertain requirement was understood correctly. `preview.md`
proves the Run traces, before any Provider is reached.
+Route commands write durable evidence to `.hypit/route-state.json`. If context is compressed, read
+`recovery.md`, reconcile the project, and resume from the reported `next_action`.
+
## Reuse an accepted Record
Hypit holds no implicit cache. Connect a Record an earlier Build accepted to a later Build by naming
diff --git a/.agents/skills/hypit/references/original-authoring/conformance-round.md b/.agents/skills/hypit/references/original-authoring/conformance-round.md
index 6343e57f..9db50a0f 100644
--- a/.agents/skills/hypit/references/original-authoring/conformance-round.md
+++ b/.agents/skills/hypit/references/original-authoring/conformance-round.md
@@ -1,5 +1,9 @@
# Reading each element against what it was asked to be
+Completed reviews are durable evidence in the project review log and route snapshot. After a context
+boundary, reconcile `.hypit/route-state.json` and continue from its `next_action`; do not repeat an
+already completed local review.
+
**Read `../element-review.md` first.** It owns the round this file sits inside, and everything below
is what having no reference changes.
diff --git a/.agents/skills/hypit/references/original-authoring/route.md b/.agents/skills/hypit/references/original-authoring/route.md
index 483d6f7c..d60af57d 100644
--- a/.agents/skills/hypit/references/original-authoring/route.md
+++ b/.agents/skills/hypit/references/original-authoring/route.md
@@ -16,6 +16,39 @@ a reconstruction gets for free have to be decided deliberately: what the program
every appearance value *is*. Neither has an evidence file to consult. Write them down rather than
discovering them at render time.
+## Checkpoint and recovery
+
+Start the project snapshot after creating the project directory:
+
+```bash
+hypit-reference-video-tools route_state --action start --project-root <project> \
+ --route description
+```
+
+Route tools update machine-owned stages after successful checks, renders, and reviews. Record an
+explicit checkpoint after brief decisions, Source edits, repairs, and Build actions. After any
+interruption or context compaction, read `../recovery.md`, run `route_state --action reconcile
+--project-root <project>`, and continue only from its `next_action`.
+
+### Durable stage map
+
+| state | update / completion predicate | recovery entry |
+| --- | --- | --- |
+| `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 |
+| `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>` |
+| `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` |
+| `repairs-complete` | explicit checkpoint after applying review findings | edit Source, then rerun the checks |
+| `final-checked` | final `authoring_check` returns `passed: true` | `authoring_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
+infers a creative brief, conformance judgement or repair from file presence alone.
+
## A description is the whole request
The author gives what the video should be — its subject, its length, its audience, who is in it, what
diff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.md
index 2ac14e53..52a4e6d9 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
+`preview_check` and `render_element` advance the project's `.hypit/route-state.json` only after their
+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.
+
Three ways to look at a Source before a Provider is ever reached: prove the graph traces, render one
element to a still, and open the whole Run for a person. They answer different questions, and none of
them costs a generation.
diff --git a/.agents/skills/hypit/references/quickstart.md b/.agents/skills/hypit/references/quickstart.md
index 3f845c82..44fd68dc 100644
--- a/.agents/skills/hypit/references/quickstart.md
+++ b/.agents/skills/hypit/references/quickstart.md
@@ -36,3 +36,6 @@ the SemanticTrack is the frame domain every `start`/`end` window resolves into
For execution, preserve the full lifecycle: select the Profile, inspect the frozen plan, run
`runtime up` when preflight is not ready, submit a fresh automatically identified Build, inspect its
accepted 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.
diff --git a/.agents/skills/hypit/references/reconstruction/comparison-round.md b/.agents/skills/hypit/references/reconstruction/comparison-round.md
index 7be8402a..64a44c64 100644
--- a/.agents/skills/hypit/references/reconstruction/comparison-round.md
+++ b/.agents/skills/hypit/references/reconstruction/comparison-round.md
@@ -1,5 +1,9 @@
# Comparing what was built against the reference
+Completed comparisons are durable evidence in `comparisons.jsonl` and the route snapshot. After a
+context boundary, run `route_state --action reconcile` before comparing again; answered pairs are
+reused and are not sent to the observer twice.
+
**Read `../element-review.md` first.** It owns the round this file sits inside: one element at a time,
render what the Source configures, realize preview mocks for what a Build has not made, one round, two attempt ceilings,
measure rather than guess, and the rule that the reader is not the builder. Everything below is what a
diff --git a/.agents/skills/hypit/references/reconstruction/route.md b/.agents/skills/hypit/references/reconstruction/route.md
index 4a60b477..91b44900 100644
--- a/.agents/skills/hypit/references/reconstruction/route.md
+++ b/.agents/skills/hypit/references/reconstruction/route.md
@@ -53,6 +53,40 @@ observations describe the reference and are cached, and `compare_reconstruction`
element against it. Author the change in early and the evidence describes one video while the sources
describe another.
+## Checkpoint and recovery
+
+Start the project snapshot before the first route decision:
+
+```bash
+hypit-reference-video-tools route_state --action start --project-root <project> \
+ --route reconstruction
+```
+
+The route tools update machine-owned stages after successful checks, renders, and comparisons. After
+reference/observer decisions, Source edits, repairs, or Build actions, write an explicit checkpoint.
+After any interruption or context compaction, read `../recovery.md`, run `route_state --action
+reconcile --project-root <project>`, and resume only from its `next_action`. The snapshot is evidence
+of intent; files and check results remain the authority.
+
+### Durable stage map
+
+| state | update / completion predicate | recovery entry |
+| --- | --- | --- |
+| `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` |
+| `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>` |
+| `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>` |
+| `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
+infers the observer's creative judgement or a repair from file presence alone.
+
---
## Phase 0 — Before any command
diff --git a/.agents/skills/hypit/references/recovery.md b/.agents/skills/hypit/references/recovery.md
new file mode 100644
index 00000000..23a1642f
--- /dev/null
+++ b/.agents/skills/hypit/references/recovery.md
@@ -0,0 +1,54 @@
+# Recovering a Hypit route after interruption or context compaction
+
+Treat every new turn as a possible context boundary. Do not continue from the chat transcript alone.
+The durable source of progress is the project's `.hypit/route-state.json`; the durable source of truth
+is the artifacts and checks it points to.
+
+## Recovery sequence
+
+1. Read `../SKILL.md`.
+2. Read the route file that matches the project.
+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`.
+7. Continue only after the state reports the next step explicitly.
+
+If the snapshot is missing, start one before continuing:
+
+```bash
+hypit-reference-video-tools route_state --action start \
+ --project-root <project> --route reconstruction|description --run <run>
+```
+
+Use `--route description` for original-authoring and `--route reconstruction` for reference-video
+work. A project has one active route; a route mismatch is an error rather than an invitation to merge
+two histories.
+
+## What the state means
+
+The state is a small snapshot, not a transcript. It records the current route step, completed steps,
+manual decisions, a short next action, and pointers to files such as `state.json`, `round.json`, render
+outputs, comparison/review logs, and the final check result. Full prompts and observer prose remain in
+their existing logs and are never copied into the snapshot.
+
+Machine-owned commands update the snapshot only after their success predicate is true. Source writing,
+repair, observer judgement, and Build submission are manual boundaries and require an explicit
+checkpoint:
+
+```bash
+hypit-reference-video-tools route_state --action checkpoint \
+ --project-root <project> --route reconstruction --step 9 \
+ --status complete --next-action 'run final reconstruction_check' \
+ --decision 'caption box is intentionally centred'
+```
+
+`reconcile` never guesses a creative decision. It can advance from durable files and passing checks,
+but leaves an unrecorded manual step as the next action. If a recorded artifact disappeared, the next
+reconciliation moves the route back to the first step whose evidence is missing.
+
+## Idempotency and paid work
+
+Repeated `prepare`, preview-mock, render, comparison, and check commands must reuse their existing
+caches and logs. Never submit a paid Build merely because the context was compacted: inspect the state,
+verify the Build/Record evidence, and resume observation with the existing command instead.
diff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.ts
index e58c1900..f8fa94fb 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, RenderElementInput, ReviewElementInput } from "./tools.js";
+import type { CompareReconstructionInput, ObserveReferenceInput, RecordObservationInput, RenderElementInput, ReviewElementInput, RouteStateCommandInput } from "./tools.js";
/**
* A word range written on the command line as `from:to`, half-open.
@@ -26,12 +26,16 @@ function usage(): string {
return [
"Usage:",
" hypit-reference-video-tools list_svml_packages",
+ " hypit-reference-video-tools route_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>",
" hypit-reference-video-tools prepare_reference --video-path <path or link> [--observer gemini|agent] [--redo media|transcript|people|voices|systems|places|all]",
" hypit-reference-video-tools observe_reference --reference-id <id> [--shot-id <id> ...] [--reobserve]",
" hypit-reference-video-tools observe_reference --reference-id <id> --shot-id <id> [--shot-id <id> ...] --question <text>",
" hypit-reference-video-tools observe_reference --reference-id <id> --batch <questions.json>",
- " hypit-reference-video-tools record_observation --reference-id <id> --key <key> --text <text>|--text-file <path>",
- " hypit-reference-video-tools record_observation --reference-id <id> --batch <answers.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_visual_contract [--shape visual-track|text-flow|text-typography|text-paint|text-document|path-command] [--producers-of <package> ...]",
" hypit-reference-video-tools paths",
@@ -268,6 +272,45 @@ async function main(): Promise<void> {
let result: unknown;
if (command === "list_svml_packages") {
result = await tools.list_svml_packages();
+ } else if (command === "route_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.route_state(supplied as RouteStateCommandInput);
+ } else if (action === "start") {
+ const route = one(flags, "route");
+ if (route !== "reconstruction" && route !== "description") throw new Error("--route must be reconstruction or description");
+ result = await tools.route_state({ action, project_root: projectRoot, route,
+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),
+ ...(one(flags, "reference-id") === undefined ? {} : { reference_id: one(flags, "reference-id") }) } as RouteStateCommandInput);
+ } else if (action === "read" || action === "reconcile") {
+ result = await tools.route_state({ action, project_root: projectRoot });
+ } else {
+ const route = one(flags, "route");
+ if (route !== "reconstruction" && route !== "description") throw new Error("--route must be reconstruction or description");
+ const step = Number(required(flags, "step"));
+ if (!Number.isSafeInteger(step) || step < 1) throw new Error("--step must be a positive integer");
+ 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");
+ const artifacts = one(flags, "artifacts");
+ let parsedArtifacts: Readonly<Record<string, string>> | undefined;
+ if (artifacts !== undefined) {
+ try { parsedArtifacts = JSON.parse(artifacts) 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.route_state({ action, project_root: projectRoot, route, step,
+ ...(status === undefined ? {} : { status }),
+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),
+ ...(one(flags, "reference-id") === undefined ? {} : { reference_id: one(flags, "reference-id") }),
+ ...(one(flags, "next-action") === undefined ? {} : { next_action: one(flags, "next-action") }),
+ ...(parsedArtifacts === undefined ? {} : { artifacts: parsedArtifacts }),
+ ...(one(flags, "decision") === undefined ? {} : { decision: one(flags, "decision") }),
+ ...(one(flags, "command") === undefined ? {} : { command: one(flags, "command") }),
+ ...(one(flags, "error") === undefined ? {} : { error: one(flags, "error") }),
+ } as RouteStateCommandInput);
+ }
} 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");
@@ -314,17 +357,18 @@ async function main(): Promise<void> {
if (typeof entry.text !== "string") throw new Error(`answer ${entry.key} needs a "text" or a "text_file"`);
return { key: entry.key, text: entry.text };
}));
- result = await tools.record_observation({ reference_id: required(flags, "reference-id"), answers });
+ result = await tools.record_observation({ reference_id: required(flags, "reference-id"), ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }), answers } as RecordObservationInput);
} else {
// An observation is paragraphs of prose. --text keeps a short one on the command line; --text-file
// is how a long one arrives without the shell deciding where it ends.
const textFile = one(flags, "text-file");
const input = supplied ?? {
reference_id: required(flags, "reference-id"),
+ ...(one(flags, "run") === undefined ? {} : { run: one(flags, "run") }),
key: required(flags, "key"),
text: textFile === undefined ? required(flags, "text") : await readFile(textFile, "utf8"),
};
- result = await tools.record_observation(input as { reference_id: string; key: string; text: string });
+ result = await tools.record_observation(input as { reference_id: string; run?: string; key: string; text: string });
}
} else if (command === "review_element") {
const reviewFile = one(flags, "batch");
diff --git a/packages/reference-video-tools/src/index.ts b/packages/reference-video-tools/src/index.ts
index 17576bd7..0a37400d 100644
--- a/packages/reference-video-tools/src/index.ts
+++ b/packages/reference-video-tools/src/index.ts
@@ -3,5 +3,17 @@ export type {
ReferenceVideoTools,
PrepareReferenceInput,
ObserveReferenceInput,
+ RecordObservationInput,
InspectVocabularyInput,
+ RouteStateCommandInput,
} from "./tools.js";
+export {
+ checkpointRouteState,
+ readRouteState,
+ reconcileRouteState,
+ routeStatePath,
+ startRouteState,
+ ROUTE_STATE_STEPS,
+ ROUTE_STATE_VERSION,
+} from "./route-state.js";
+export type { RouteCheckpointInput, RouteKind, RouteState, RouteStateInput } from "./route-state.js";
diff --git a/packages/reference-video-tools/src/route-state.ts b/packages/reference-video-tools/src/route-state.ts
new file mode 100644
index 00000000..9f511d9e
--- /dev/null
+++ b/packages/reference-video-tools/src/route-state.ts
@@ -0,0 +1,270 @@
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+
+export type RouteKind = "reconstruction" | "description";
+export type RouteStatus = "active" | "complete" | "blocked";
+
+export type RouteState = {
+ readonly version: 1;
+ readonly route: RouteKind;
+ readonly project_root: string;
+ readonly run?: string;
+ readonly reference_id?: string;
+ readonly status: RouteStatus;
+ readonly current_step: number;
+ readonly completed_steps: readonly number[];
+ readonly in_progress: { readonly step: number; readonly started_at: string } | null;
+ 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 RouteStateInput = {
+ readonly projectRoot: string;
+ readonly route: RouteKind;
+ readonly run?: string;
+ readonly referenceId?: string;
+};
+
+export type RouteCheckpointInput = RouteStateInput & {
+ readonly step: number;
+ readonly status?: "in_progress" | "complete" | "blocked";
+ readonly nextAction?: string;
+ readonly artifacts?: Readonly<Record<string, string>>;
+ readonly decision?: string;
+ readonly command?: string;
+ readonly error?: string;
+};
+
+export const ROUTE_STATE_VERSION = 1 as const;
+
+export const 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",
+ ],
+ description: [
+ "environment", "brief-frozen", "source-authored", "vocabulary-checked", "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");
+}
+
+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>;
+ if (state.version !== ROUTE_STATE_VERSION) throw new Error(`route state at ${path} has unsupported version`);
+ if (state.route !== "reconstruction" && state.route !== "description") throw new Error(`route state at ${path} has an invalid route`);
+ if (typeof state.project_root !== "string" || state.project_root.length === 0) throw new Error(`route state at ${path} has no project_root`);
+ if (typeof state.status !== "string" || !["active", "complete", "blocked"].includes(state.status)) throw new Error(`route state at ${path} has an invalid status`);
+ const currentStep = state.current_step;
+ if (typeof currentStep !== "number" || !Number.isSafeInteger(currentStep) || currentStep < 1 || currentStep > ROUTE_STATE_STEPS[state.route].length + 1) throw new Error(`route state at ${path} has an invalid current_step`);
+ if (!Array.isArray(state.completed_steps) || state.completed_steps.some((step) => !Number.isSafeInteger(step) || step < 1)) throw new Error(`route 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(`route state at ${path} has invalid in_progress`);
+ if (state.artifacts === null || typeof state.artifacts !== "object" || Array.isArray(state.artifacts)) throw new Error(`route state at ${path} has invalid artifacts`);
+ if (!Array.isArray(state.decisions) || state.decisions.some((item) => typeof item !== "string")) throw new Error(`route state at ${path} has invalid decisions`);
+ if (state.conflicts !== undefined && (!Array.isArray(state.conflicts) || state.conflicts.some((item) => typeof item !== "string"))) throw new Error(`route state at ${path} has invalid conflicts`);
+ if (typeof state.next_action !== "string" || typeof state.updated_at !== "string") throw new Error(`route state at ${path} is missing recovery fields`);
+}
+
+export async function readRouteState(projectRoot: string): Promise<RouteState | undefined> {
+ const path = routeStatePath(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(`route state at ${path} is invalid JSON; original file was preserved: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ assertRouteState(parsed, path);
+ return parsed;
+}
+
+async function writeRouteState(state: RouteState): Promise<RouteState> {
+ const path = routeStatePath(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;
+}
+
+function nextUncompleted(route: RouteKind, completed: readonly number[]): number {
+ const done = new Set(completed);
+ const steps = ROUTE_STATE_STEPS[route];
+ for (let step = 1; step <= steps.length; step += 1) if (!done.has(step)) return step;
+ return steps.length + 1;
+}
+
+export async function startRouteState(input: RouteStateInput): Promise<RouteState> {
+ const projectRoot = resolve(input.projectRoot);
+ const existing = await readRouteState(projectRoot);
+ if (existing !== undefined && existing.status !== "complete" && (existing.route !== input.route || existing.project_root !== projectRoot)) {
+ throw new Error(`project already has an active ${existing.route} route at ${routeStatePath(projectRoot)}`);
+ }
+ if (existing !== undefined && existing.route === input.route) return existing;
+ const now = new Date().toISOString();
+ return await writeRouteState({
+ version: ROUTE_STATE_VERSION,
+ route: input.route,
+ project_root: projectRoot,
+ ...(input.run === undefined ? {} : { run: resolve(projectRoot, input.run) }),
+ ...(input.referenceId === undefined ? {} : { reference_id: input.referenceId }),
+ status: "active",
+ current_step: 1,
+ completed_steps: [],
+ in_progress: { step: 1, started_at: now },
+ artifacts: {},
+ decisions: [],
+ next_action: `complete ${ROUTE_STATE_STEPS[input.route][0]}`,
+ updated_at: now,
+ });
+}
+
+export async function checkpointRouteState(input: RouteCheckpointInput): Promise<RouteState> {
+ const projectRoot = resolve(input.projectRoot);
+ const existing = await readRouteState(projectRoot);
+ if (existing === undefined) throw new Error(`no route state at ${routeStatePath(projectRoot)}; run route_state start first`);
+ if (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);
+ const completedSteps = [...completed].sort((a, b) => a - b);
+ const next = input.status === "complete" ? nextUncompleted(input.route, completedSteps) : input.step;
+ const now = new Date().toISOString();
+ const 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, resolve(projectRoot, value)]),
+ ),
+ };
+ const state: RouteState = {
+ ...existing,
+ ...(input.run === undefined ? {} : { run: resolve(projectRoot, input.run) }),
+ ...(input.referenceId === undefined ? {} : { reference_id: input.referenceId }),
+ status: input.status === "blocked" ? "blocked" : next > ROUTE_STATE_STEPS[input.route].length ? "complete" : "active",
+ current_step: next,
+ completed_steps: completedSteps,
+ in_progress: input.status === "in_progress"
+ ? { step: input.step, started_at: now }
+ : input.status === "complete"
+ ? (next > ROUTE_STATE_STEPS[input.route].length ? null : { step: next, started_at: now })
+ : existing.in_progress,
+ artifacts,
+ decisions,
+ next_action: input.nextAction?.trim()
+ || (next > ROUTE_STATE_STEPS[input.route].length ? "route complete" : `complete ${ROUTE_STATE_STEPS[input.route][next - 1]}`),
+ ...(input.command === undefined ? {} : { last_command: input.command }),
+ ...(input.error === undefined ? {} : { last_error: input.error }),
+ updated_at: now,
+ };
+ return await writeRouteState(state);
+}
+
+async function exists(path: string | undefined): Promise<boolean> {
+ if (path === undefined) return false;
+ return await stat(path).then(() => true, () => false);
+}
+
+async function evidenceSatisfied(key: string, path: string | undefined): Promise<boolean> {
+ if (!(await exists(path)) || path === undefined) return false;
+ // Check artifacts are written as JSON by the route-aware commands. Reconcile deliberately
+ // verifies their success predicate instead of treating a stale/failing report as completion.
+ if (key === "preview_check") {
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as { sound?: unknown };
+ return value.sound === true;
+ } catch { return false; }
+ }
+ if (key === "final_check") {
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as { passed?: unknown };
+ return value.passed === true;
+ } catch { return false; }
+ }
+ if (key === "comparison_log" || key === "review_log") {
+ try {
+ const lines = (await readFile(path, "utf8")).split("\n").filter((line) => line.trim().length > 0);
+ return lines.some((line) => {
+ try {
+ const value = JSON.parse(line) as { status?: unknown };
+ return value.status === "complete";
+ } catch { return false; }
+ });
+ } catch { return false; }
+ }
+ if (key === "reference_state") {
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as { shots?: unknown; video?: unknown };
+ return Array.isArray(value.shots) && value.video !== undefined;
+ } catch { return false; }
+ }
+ if (key === "reference_observations") {
+ try {
+ const value = JSON.parse(await readFile(path, "utf8")) as Record<string, { status?: unknown }>;
+ const entries = Object.values(value);
+ return entries.length > 0 && entries.every((item) => item?.status === "complete");
+ } catch { return false; }
+ }
+ return true;
+}
+
+/** Reconcile a snapshot with the small, durable evidence pointers it records. */
+export async function reconcileRouteState(projectRoot: string): Promise<RouteState | undefined> {
+ const existing = await readRouteState(projectRoot);
+ if (existing === undefined) return undefined;
+ const completed = new Set(existing.completed_steps);
+ const conflicts: string[] = [];
+ const artifact = (name: string): string | undefined => existing.artifacts[name];
+ const reconcileStep = async (step: number, key: string): Promise<void> => {
+ const renderComplete = key === "preview_render"
+ ? await evidenceSatisfied("render_sidecar", artifact("render_sidecar"))
+ : true;
+ const satisfied = renderComplete && await evidenceSatisfied(key, artifact(key));
+ if (satisfied) completed.add(step);
+ else {
+ if (completed.has(step)) conflicts.push(`step ${step} (${key}) was marked complete but its evidence is missing or failed`);
+ completed.delete(step);
+ }
+ };
+ 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",
+ },
+ 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",
+ },
+ };
+ for (const [step, key] of Object.entries(evidenceByStep[existing.route])) {
+ await reconcileStep(Number(step), key);
+ }
+ const completedSteps = [...completed].sort((a, b) => a - b);
+ const next = nextUncompleted(existing.route, completedSteps);
+ const now = new Date().toISOString();
+ const { conflicts: _oldConflicts, ...withoutConflicts } = existing;
+ const state: RouteState = {
+ ...withoutConflicts,
+ status: next > ROUTE_STATE_STEPS[existing.route].length ? "complete" : existing.status === "blocked" ? "blocked" : "active",
+ current_step: next,
+ completed_steps: completedSteps,
+ in_progress: next > ROUTE_STATE_STEPS[existing.route].length ? null : { step: next, started_at: now },
+ next_action: next > ROUTE_STATE_STEPS[existing.route].length ? "route complete" : `complete ${ROUTE_STATE_STEPS[existing.route][next - 1]}`,
+ ...(conflicts.length === 0 ? {} : { conflicts }),
+ updated_at: now,
+ };
+ return await writeRouteState(state);
+}
diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.ts
index 680bd096..cb5cf7d5 100644
--- a/packages/reference-video-tools/src/tools.ts
+++ b/packages/reference-video-tools/src/tools.ts
@@ -23,6 +23,15 @@ import type { RenderElementInput, RenderPreviewsInput, SpokenRange, StandInFocus
import { downloadReferenceVideo, isReferenceUrl } from "@hypit/yt-dlp";
import { authoringCheck, previewCheck, reviewLogPath } from "./checks.js";
import type { AuthoringCheckInput, PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";
+import {
+ checkpointRouteState,
+ readRouteState,
+ reconcileRouteState,
+ routeStatePath,
+ startRouteState,
+ ROUTE_STATE_STEPS,
+} from "./route-state.js";
+import type { RouteKind, RouteState } from "./route-state.js";
import {
assert,
completelyStill,
@@ -60,6 +69,8 @@ export type ObserveReferenceInput = {
};
export type RecordObservationInput = {
readonly reference_id: string;
+ /** Optional Run used to persist reconstruction route progress after an out-of-band answer. */
+ readonly run?: string;
readonly key?: string;
readonly text?: string;
/**
@@ -163,6 +174,11 @@ export type RecordReviewInput = {
readonly text: string;
};
+export type RouteStateCommandInput =
+ | ({ readonly action: "start"; readonly project_root: string; readonly route: RouteKind; readonly run?: string; readonly reference_id?: string })
+ | ({ 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 { RenderElementInput, RenderPreviewsInput } from "./authoring.js";
export type { PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";
@@ -188,6 +204,7 @@ export type ReferenceVideoTools = {
* were unreachable to this route while the check began by demanding a reference.
*/
authoring_check(input: Omit<AuthoringCheckInput, "mode" | "reference_id">): Promise<Record<string, unknown>>;
+ route_state(input: RouteStateCommandInput): Promise<Record<string, unknown>>;
};
type ToolOptions = {
@@ -201,6 +218,117 @@ type ToolOptions = {
export type GenerateText = (input: { readonly parts: readonly Part[]; readonly instruction: string }) => Promise<string>;
type ObservationTask = { readonly key: string; readonly request: Request };
+function routeStateResult(state: RouteState | undefined): Record<string, unknown> {
+ return state === undefined ? { state: null } : { state, path: routeStatePath(state.project_root) };
+}
+
+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 }) });
+ return routeStateResult(state);
+ }
+ if (input.action === "read") return routeStateResult(await readRouteState(input.project_root));
+ if (input.action === "reconcile") return routeStateResult(await reconcileRouteState(input.project_root));
+ if (input.action !== "checkpoint") throw new Error(`unsupported route state action ${input.action}`);
+ const state = await checkpointRouteState({
+ projectRoot: input.project_root,
+ route: input.route,
+ step: input.step,
+ ...(input.status === undefined ? {} : { status: input.status }),
+ ...(input.run === undefined ? {} : { run: input.run }),
+ ...(input.reference_id === undefined ? {} : { referenceId: input.reference_id }),
+ ...(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 }),
+ });
+ return routeStateResult(state);
+}
+
+async function autoRouteCheckpoint(
+ runPath: string | undefined,
+ step: number,
+ artifacts: Readonly<Record<string, string>> = {},
+ nextAction?: string,
+ command?: string,
+): Promise<void> {
+ if (runPath === undefined) return;
+ const projectRoot = dirname(resolve(runPath));
+ const state = await readRouteState(projectRoot);
+ if (state === undefined || state.status === "complete") return;
+ await checkpointRouteState({
+ projectRoot,
+ route: state.route,
+ step,
+ status: "complete",
+ run: runPath,
+ artifacts,
+ command: command ?? `route step ${step}`,
+ ...(nextAction === undefined ? {} : { nextAction }),
+ });
+}
+
+async function persistRouteEvidence(runPath: string, name: string, result: Record<string, unknown>): Promise<string> {
+ const path = join(dirname(resolve(runPath)), ".hypit", name);
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, `${JSON.stringify(result, null, 2)}\n`, "utf8");
+ return path;
+}
+
+async function autoRouteError(runPath: string | undefined, command: string, error: unknown): Promise<void> {
+ if (runPath === undefined) return;
+ const resolved = resolve(invokedFrom(), runPath);
+ const projectRoot = dirname(resolved);
+ const state = await readRouteState(projectRoot);
+ if (state === undefined || state.status === "complete") return;
+ await checkpointRouteState({
+ projectRoot,
+ route: state.route,
+ step: state.current_step <= ROUTE_STATE_STEPS[state.route].length ? state.current_step : ROUTE_STATE_STEPS[state.route].length,
+ status: "in_progress",
+ run: resolved,
+ command,
+ error: error instanceof Error ? error.message : String(error),
+ });
+}
+
+async function renderEvidence(output: unknown): Promise<Readonly<Record<string, string>>> {
+ if (typeof output !== "string") return {};
+ const rendered = resolve(invokedFrom(), output);
+ const sidecar = standInSidecarPath(rendered);
+ const [renderFile, sidecarFile] = await Promise.all([
+ stat(rendered).then((value) => value.isFile(), () => false),
+ stat(sidecar).then((value) => value.isFile(), () => false),
+ ]);
+ return renderFile && sidecarFile ? { preview_render: rendered, render_sidecar: sidecar } : {};
+}
+
+async function referenceObservationComplete(referenceId: string): Promise<boolean> {
+ const state = await readJson<ReferenceState>(join(stateRoot(referenceId), "state.json")).catch(() => undefined);
+ if (state === undefined || !prepared(state)) return false;
+ const observations = await readJson<Record<string, Observation>>(join(state.root, "observations.json")) ?? {};
+ const required = state.shots.flatMap((shot, index) => [
+ `visual:${shot.shot_id}`, `type:${shot.shot_id}`, `audio:${shot.shot_id}`,
+ ...(index === 0 ? [] : [`boundary:${shot.shot_id}`]),
+ ]);
+ return required.every((key) => observations[key]?.status === "complete")
+ && Object.values(observations).every((value) => value?.status === "complete");
+}
+
+async 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");
+}
+
+async function persistRoutePlan(runPath: string, result: Record<string, unknown>): Promise<string> {
+ const path = join(dirname(resolve(runPath)), ".hypit", "route-plan.json");
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, `${JSON.stringify({ plan: result.plan ?? [], generated_at: new Date().toISOString() }, null, 2)}\n`, "utf8");
+ return path;
+}
+
function observation(status: Observation["status"], text: string): Observation { return { status, text }; }
function unavailable(reason: string): Transcript { return { status: "unavailable", transcript_ref: null, word_count: 0, reason }; }
@@ -254,6 +382,8 @@ export type ComparisonRecord = {
* crediting none of them.
*/
readonly id: string;
+ /** The project Run, when this comparison was made over a word range. */
+ readonly run?: string;
/** Which stretch was compared. A comparison names its shot or its word range, never both. */
readonly shot_id?: string;
readonly range?: ComparedRange;
@@ -1670,6 +1800,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
scope,
});
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");
return {
reference_id: state.reference_id,
observer,
@@ -1700,6 +1831,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
await appendLooked(comparisonLog(root), {
at: startedAt,
id: comparisonId,
+ ...(input.run === undefined ? {} : { run: resolve(invokedFrom(), input.run) }),
...(shot === undefined ? {} : { shot_id: shot.shot_id }),
...(cut === undefined ? {} : { range: cut.record }),
...(input.element === undefined ? {} : { element: input.element.trim() }),
@@ -1713,6 +1845,9 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
...(standIn === undefined ? {} : { stand_in: standIn }),
...(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");
+ }
return {
reference_id: state.reference_id,
observer,
@@ -1754,7 +1889,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
// a lock, for writes that take no time. Running them in the order they were written keeps the
// failures in that order too.
const { done, failures } = await runBatch(round, { concurrency: 1, gapMs: 0 }, async (one) =>
- await tools.record_observation({ reference_id: input.reference_id, key: one.key, text: one.text }));
+ await tools.record_observation({ reference_id: input.reference_id, ...(input.run === undefined ? {} : { run: input.run }), key: one.key, text: one.text }));
return {
recorded: done.length,
failed: failures.length,
@@ -1777,14 +1912,22 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
const current = await readJson<ReferenceState>(join(root, "state.json")) ?? state;
await writeJson(join(root, "state.json"), { ...current, [field]: observation("complete", text) });
});
+ await maybeCheckpointReferenceObservation(input);
return { reference_id: state.reference_id, key, stored_in: "state" };
}
// A comparison is answered against the entry it opened in the log rather than against the
// observation cache: the log is what a gate reads to tell an element that was looked at from one
// that never was, and until this existed an agent-observer comparison could never leave `pending`.
if (key.startsWith("comparison:")) {
- const closed = await closeLooked(comparisonLog(root), key.slice("comparison:".length), text);
+ const comparisonId = key.slice("comparison:".length);
+ const closed = await closeLooked(comparisonLog(root), comparisonId, text);
assert(closed, `${key} names no open comparison of reference ${input.reference_id}`);
+ const comparison = (await readFile(join(root, "comparisons.jsonl"), "utf8"))
+ .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");
+ await maybeCheckpointReferenceObservation(input);
return { reference_id: state.reference_id, key, stored_in: "comparisons" };
}
const shotKeys = new Set(state.shots.flatMap((shot) => [`visual:${shot.shot_id}`, `type:${shot.shot_id}`, `audio:${shot.shot_id}`, `boundary:${shot.shot_id}`, `window:${shot.shot_id}`]));
@@ -1806,6 +1949,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
cache[key] = observation("complete", text);
await writeJson(path, cache);
});
+ await maybeCheckpointReferenceObservation(input);
return { reference_id: state.reference_id, key, stored_in: "observations" };
},
@@ -1956,6 +2100,7 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
assert(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");
return { run: runPath, review_id: id, stored_in: reviewLogPath(runPath) };
},
@@ -1970,6 +2115,18 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
...one, run: one.run ?? input.run,
...(one.reference_id ?? input.reference_id === undefined ? {} : { reference_id: input.reference_id }),
} as RenderElementInput));
+ if (failures.length === 0 && done.length > 0) {
+ const run = round[0]?.run ?? input.run;
+ const 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,
+ evidence, "compare_reconstruction or review_element");
+ }
+ } else if (failures.length > 0) {
+ const failedRun = round[0]?.run ?? input.run;
+ await autoRouteError(failedRun, "render_element", failures[0]?.error ?? "render failed");
+ }
return {
rendered: done.length,
failed: failures.length,
@@ -1977,7 +2134,18 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
...(failures.length === 0 ? {} : { failures }),
};
}
- return await renderElement(input);
+ try {
+ const 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,
+ evidence, "compare_reconstruction or review_element");
+ }
+ return result;
+ } catch (error) {
+ await autoRouteError(input.run, "render_element", error);
+ throw error;
+ }
},
async render_previews(input): Promise<Record<string, unknown>> {
@@ -1985,15 +2153,62 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
},
async preview_check(input): Promise<Record<string, unknown>> {
- return await previewCheck(input, { packageRoot });
+ const runPath = resolve(invokedFrom(), input.run);
+ try {
+ 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;
+ 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");
+ } else await autoRouteError(runPath, "preview_check", result.refused ?? result.problems ?? "preview check failed");
+ return result;
+ } catch (error) {
+ await autoRouteError(runPath, "preview_check", error);
+ throw error;
+ }
},
async reconstruction_check(input): Promise<Record<string, unknown>> {
- return await authoringCheck({ ...input, mode: "reconstruction" }, { packageRoot });
+ const runPath = resolve(invokedFrom(), input.run);
+ try {
+ 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>");
+ }
+ if (result.passed === true) await autoRouteCheckpoint(runPath, 10, { final_check: evidence }, "submit the approved Build");
+ else await autoRouteError(runPath, "reconstruction_check", result.issues ?? result.unresolved ?? "reconstruction check failed");
+ return result;
+ } catch (error) {
+ await autoRouteError(runPath, "reconstruction_check", error);
+ throw error;
+ }
},
async authoring_check(input): Promise<Record<string, unknown>> {
- return await authoringCheck({ ...input, mode: "description" }, { packageRoot });
+ const runPath = resolve(invokedFrom(), input.run);
+ try {
+ 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>");
+ }
+ if (result.passed === true) await autoRouteCheckpoint(runPath, 10, { final_check: evidence }, "submit the approved Build");
+ else await autoRouteError(runPath, "authoring_check", result.issues ?? result.unresolved ?? "authoring check failed");
+ return result;
+ } catch (error) {
+ await autoRouteError(runPath, "authoring_check", error);
+ throw error;
+ }
+ },
+
+ async route_state(input): Promise<Record<string, unknown>> {
+ return await runRouteStateCommand(input);
},
};
return tools;
diff --git a/packages/reference-video-tools/test/route-state.test.ts b/packages/reference-video-tools/test/route-state.test.ts
new file mode 100644
index 00000000..83809694
--- /dev/null
+++ b/packages/reference-video-tools/test/route-state.test.ts
@@ -0,0 +1,109 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ checkpointRouteState,
+ readRouteState,
+ reconcileRouteState,
+ routeStatePath,
+ startRouteState,
+} from "../src/route-state.js";
+
+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" });
+ assert.equal(started.current_step, 1);
+ assert.equal(started.run, join(root, "build.svrun"));
+ const completed = await checkpointRouteState({ projectRoot: root, route: "reconstruction", step: 1, status: "complete", nextAction: "prepare reference" });
+ assert.deepEqual(completed.completed_steps, [1]);
+ assert.equal(completed.current_step, 2);
+ const repeated = await checkpointRouteState({ projectRoot: root, route: "reconstruction", step: 1, status: "complete" });
+ assert.deepEqual(repeated.completed_steps, [1]);
+ assert.equal((await readRouteState(root))?.current_step, 2);
+});
+
+test("reconcile uses durable artifact pointers and preserves manual gaps", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ const 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 } });
+ const reconciled = await reconcileRouteState(root);
+ assert.equal(reconciled?.completed_steps.includes(3), true);
+ assert.equal(reconciled?.current_step, 1, "manual earlier steps remain owed instead of being guessed from a later file");
+});
+
+test("corrupt route state fails without replacing the original file", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ await mkdir(join(root, ".hypit"), { recursive: true });
+ await writeFile(routeStatePath(root), "{broken", "utf8");
+ await assert.rejects(readRouteState(root), /invalid JSON.*original file was preserved/u);
+ assert.equal(await readFile(routeStatePath(root), "utf8"), "{broken");
+});
+
+test("a project cannot switch an active route", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ await startRouteState({ projectRoot: root, route: "reconstruction" });
+ await assert.rejects(startRouteState({ projectRoot: root, route: "description" }), /already has an active reconstruction route/u);
+});
+
+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) {
+ await checkpointRouteState({ projectRoot: root, route: "reconstruction", step, status: "complete" });
+ }
+ assert.equal((await readRouteState(root))?.status, "complete");
+ const restarted = await startRouteState({ projectRoot: root, route: "description" });
+ assert.equal(restarted.route, "description");
+ assert.deepEqual(restarted.completed_steps, []);
+});
+
+test("checkpoint artifacts are merged and stale machine evidence is rolled back", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ const source = join(root, "main.svml");
+ const check = join(root, "preview-check.json");
+ 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 reconcileRouteState(root);
+ assert.equal((await readRouteState(root))?.completed_steps.includes(5), 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?.current_step, 1);
+ assert.match(rolledBack?.conflicts?.[0] ?? "", /step 5.*preview_check/u);
+});
+
+test("description reconciliation uses brief and vocabulary evidence rather than reference artifacts", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ const brief = join(root, "brief.md");
+ const vocabulary = join(root, "vocabulary.json");
+ await writeFile(brief, "brief", "utf8");
+ await writeFile(vocabulary, "{}", "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 } });
+ 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);
+});
+
+test("an interrupted in-progress step resumes at the first unmet step", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-route-state-"));
+ await startRouteState({ projectRoot: root, route: "reconstruction" });
+ await checkpointRouteState({ projectRoot: root, route: "reconstruction", step: 1, status: "complete" });
+ const interrupted = await checkpointRouteState({ projectRoot: root, route: "reconstruction", step: 2, status: "in_progress", nextAction: "finish reference preparation" });
+ assert.equal(interrupted.in_progress?.step, 2);
+ const resumed = await reconcileRouteState(root);
+ assert.equal(resumed?.current_step, 2);
+ assert.equal(resumed?.in_progress?.step, 2);
+ assert.equal(resumed?.next_action, "complete reference-prepared");
+});