Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(cli): save check, snapshot and render artifacts per revision (#5522)
Xuanru Li23d1fe5b4272
diff --git a/docs/developers/harness-tool-context.mdx b/docs/developers/harness-tool-context.mdxindex 8107d29a91..84c2ab192b 100644--- a/docs/developers/harness-tool-context.mdx+++ b/docs/developers/harness-tool-context.mdx@@ -46,7 +46,7 @@ Each line is an event:"version": 1,"type": "artifact.created","command": "snapshot",- "artifact": { "role": "contact-sheet", "path": "/project/snapshots/contact-sheet.jpg", "mediaType": "image/jpeg" }+ "artifact": { "role": "contact-sheet", "path": "/project/.hyperframes/artifacts/snapshots/…/contact-sheet.jpg", "mediaType": "image/jpeg" }}```@@ -54,11 +54,12 @@ Each line is an event:| --- | --- | --- || `snapshot` | `frame` | Each captured frame (PNG) || `snapshot` | `contact-sheet` | Each page of the grid of frames made for review (JPEG) |+| `check` | `check-report` | The saved JSON report || `check` | `frame` | Each frame the browser check captured || `check` | `finding` | Each crop around a finding |Paths are absolute and stay where the command saved them. What to do with an artifact is the-harness's decision: attach the contact sheet to the tool result, or ignore it.+harness's decision: attach the contact sheet to the tool result, link the report, or ignore it.Ignore event types and roles you do not know; new ones are added without a version change.## `project-lock`: one browser command at a timediff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdxindex 6b4485257a..f9f5aa1c87 100644--- a/docs/packages/cli.mdx+++ b/docs/packages/cli.mdx@@ -737,7 +737,7 @@ cover every finding from the full check.| Flag | Description || -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- || `--json` | One aggregated envelope. Every finding carries a selector, `data-*` identity, source file, bbox, and sample time. |-| `--snapshots` | Save the five audited frames under `snapshots/`, plus a `finding-NN-<code>.png` crop per finding |+| `--snapshots` | Save the five audited frames under `.hyperframes/artifacts/snapshots/`, plus a `finding-NN-<code>.png` crop per finding || `--samples` | Midpoint samples across the duration (default 9) || `--at` | Explicit timestamps in seconds, comma-separated || `--at-transitions` | Also sample every tween start and end, to catch transient overlaps at transition seams |@@ -854,10 +854,10 @@ npx hyperframes snapshot my-project --at 1.5,4.3 --against ref.mp4```◆ Capturing 3 frames at [2.9s, 10.4s, 18.7s] from my-project-◇ 3 snapshots saved to snapshots/- snapshots/frame-00-at-2.9s.png- snapshots/frame-01-at-10.4s.png- snapshots/frame-02-at-18.7s.png+◇ 3 snapshots saved to <project>/.hyperframes/artifacts/snapshots/<id>+ .hyperframes/artifacts/snapshots/<id>/frame-00-at-2.9s.png+ .hyperframes/artifacts/snapshots/<id>/frame-01-at-10.4s.png+ .hyperframes/artifacts/snapshots/<id>/frame-02-at-18.7s.png```| Flag | Description |@@ -866,7 +866,7 @@ npx hyperframes snapshot my-project --at 1.5,4.3 --against ref.mp4| `--frames` | Evenly spaced frames instead (default 5) || `--range <start,end>` | Spread `--frames` across this interval only, in root-timeline seconds, with no end-of-timeline frame added || `--composition <id>` | Spread `--frames` across the visible interval of the element with this `data-composition-id`. Use one of `--at`, `--range` or `--composition`. |-| `--output, -o` | Where the PNGs go (default `<project>/snapshots`) |+| `--output, -o` | Where the PNGs go (default: a new `<project>/.hyperframes/artifacts/snapshots/<id>` per run) || `--end` / `--no-end` | Always add a readable end-of-timeline frame (default: on). `--no-end` captures only your `--at` times. || `--zoom` | Crop to a CSS selector or an exact `x,y,w,h` region, using a raised device scale factor. Layout is untouched — never CSS zoom or a resized viewport. A selector that matches nothing is an error. || `--against` | A reference video, such as footage you are rebuilding. For every captured time also saves its frame-exact frame (`ref-XX-…png`) and a labelled render / reference pair (`pair-XX-…jpg`). |@@ -1345,7 +1345,7 @@ Find and remove what HyperFrames left on disk.```bashnpx hyperframes clean --dry-run # list it, remove nothingnpx hyperframes clean-npx hyperframes clean --snapshots # also remove snapshots/ folders+npx hyperframes clean --snapshots # also remove snapshots and saved check reportsnpx hyperframes clean --json```@@ -1356,7 +1356,7 @@ It looks in the current project (not its subfolders) and every project the Studi- the history of projects that no longer exist;- extracted video frames and video proxies nobody has used for an hour (they rebuild on demand).-`snapshots/` folders are listed as also reclaimable and removed only with `--snapshots`. Rendered outputs, source+`snapshots/` folders and the saved snapshots and check reports under `.hyperframes/artifacts/` are listed as also reclaimable and removed only with `--snapshots`. Rendered outputs, sourcefiles, the browser download and models are never touched.### `info` and `compositions`diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.tsindex 7257fd762a..2b32f9cae0 100644--- a/packages/cli/src/commands/check.ts+++ b/packages/cli/src/commands/check.ts@@ -1,4 +1,14 @@-import { resolve } from "node:path";+import { captureArtifactRevision } from "../utils/artifactCapture.js";+import { pngDimensions } from "../utils/pngDimensions.js";+import { randomUUID } from "node:crypto";+import { mkdirSync, writeFileSync } from "node:fs";+import { join, resolve } from "node:path";+import {+ recordArtifacts,+ type ArtifactCapture,+ type ArtifactInput,+ type ArtifactRecord,+} from "@hyperframes/studio-server/history";import { formatFindingTimes } from "../utils/checkFindings.js";import { withProjectLock } from "../utils/projectLock.js";import { reportArtifacts } from "../utils/toolContext.js";@@ -17,6 +27,7 @@ import {DEFAULT_CHECK_OPTIONS,checkExitCode,runCheckPipeline,+ selectFindingCropRequests,type CheckFinding,type CheckOptions,type CheckReport,@@ -32,24 +43,108 @@ export const examples: Example[] = [["Also fail on warnings", "hyperframes check --strict"],];+type SavedCheck = Pick<ArtifactRecord, "id" | "revision" | "report" | "attribution">;+type SavedCheckReport = CheckReport & { saved?: SavedCheck };+export interface CheckCommandDependencies {resolveProject(dir: string | undefined): ProjectDir;- runPipeline(project: ProjectDir, options: CheckOptions): Promise<CheckReport>;+ runPipeline(project: ProjectDir, options: CheckOptions): Promise<SavedCheckReport>;withMeta(value: object): object;}const DEFAULT_COMMAND_DEPENDENCIES: CheckCommandDependencies = {resolveProject,async runPipeline(project, options) {+ const capture = await captureArtifactRevision(project.dir).catch(warnNotRecorded);const report = await runCheckPipeline(project, options);const images = (files: readonly string[]) => files.map((file) => resolve(project.dir, file));reportArtifacts("check", "frame", images(report.snapshots.files));reportArtifacts("check", "finding", images(report.snapshots.findingFiles));- return report;+ if (!capture) return report;+ try {+ return { ...report, saved: await saveCheckReport(project, options, report, capture) };+ } catch (error) {+ warnNotRecorded(error);+ return report;+ }},withMeta,};+function warnNotRecorded(error: unknown): undefined {+ console.warn(`${c.warn("⚠")} Check report was not recorded: ${normalizeErrorMessage(error)}`);+ return undefined;+}++async function saveCheckReport(+ project: ProjectDir,+ options: CheckOptions,+ report: CheckReport,+ capture: ArtifactCapture,+): Promise<SavedCheck> {+ const id = randomUUID();+ const directory = join(project.dir, ".hyperframes", "artifacts", "checks");+ mkdirSync(directory, { recursive: true });+ const path = join(directory, `${id}.json`);+ writeFileSync(path, JSON.stringify(report, null, 2) + "\n", { flag: "wx" });+ const reportScope =+ "scope" in report && typeof report.scope === "object" && report.scope !== null+ ? report.scope+ : undefined;+ const artifacts: ArtifactInput[] = [+ {+ kind: "check",+ id,+ scope: reportScope ? "scoped" : "project",+ report: resolve(path),+ metadata: {+ ok: report.ok,+ browserSkipped: report.browserSkipped,+ scope: reportScope,+ options,+ },+ },+ ];+ for (const [index, image] of report.snapshots.files.entries()) {+ artifacts.push({+ kind: "snapshot",+ id: `${id}-${index}`,+ scope: "full",+ image: resolve(project.dir, image),+ time: report.snapshots.times[index],+ metadata: {+ checkId: id,+ ...pngDimensions(resolve(project.dir, image)),+ },+ });+ }+ const crops = selectFindingCropRequests(report);+ for (const [index, image] of report.snapshots.findingFiles.entries()) {+ const crop = crops.find((request) => image.endsWith(request.filename));+ artifacts.push({+ kind: "snapshot",+ id: `${id}-crop-${index}`,+ scope: "finding",+ image: resolve(project.dir, image),+ time: crop?.time,+ metadata: {+ checkId: id,+ finding: crop,+ ...pngDimensions(resolve(project.dir, image)),+ },+ });+ }+ const [saved] = await recordArtifacts(project.dir, capture, artifacts);+ if (!saved) throw new Error("no history record was written");+ reportArtifacts("check", "check-report", [resolve(path)]);+ return {+ id: saved.id,+ revision: saved.revision,+ report: saved.report,+ attribution: saved.attribution,+ };+}+const CHECK_COMMAND_ARGS = {dir: { type: "positional", description: "Project directory", required: false },json: { type: "boolean", description: "Output agent-readable JSON", default: false },@@ -128,7 +223,7 @@ const CHECK_COMMAND_ARGS = {},snapshots: {type: "boolean",- description: "Save the five contrast-pass PNGs under snapshots/",+ description: "Save contrast-pass PNGs under .hyperframes/artifacts/snapshots/",default: false,},"caption-zone": {@@ -174,6 +269,12 @@ export function createCheckCommand(console.log(JSON.stringify(dependencies.withMeta(report), null, 2));} else {printHumanReport(report);+ if (report.saved) {+ console.log(`Report: ${report.saved.report}`);+ console.log(+ `Revision: ${report.saved.revision ?? "none"} (${report.saved.attribution})`,+ );+ }}setCommandExitCode(checkExitCode(report));} catch (error) {diff --git a/packages/cli/src/commands/checkArtifacts.test.ts b/packages/cli/src/commands/checkArtifacts.test.tsnew file mode 100644index 0000000000..5093395768--- /dev/null+++ b/packages/cli/src/commands/checkArtifacts.test.ts@@ -0,0 +1,106 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { openProjectHistory } from "@hyperframes/studio-server/history";+import { historyDeps } from "../utils/historyOwner.js";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { runCommand } from "citty";+import { expect, it, vi } from "vitest";+import check from "./check.js";+import { consumeCommandResult } from "../utils/commandResult.js";+import { checkExitCode, type CheckReport } from "../utils/checkPipeline.js";++it("persists real lint-blocked reports without overwriting earlier checks or inventing a revision", async () => {+ const project = mkdtempSync(join(tmpdir(), "hf-check-artifacts-"));+ const log = vi.spyOn(console, "log").mockImplementation(() => undefined);+ writeFileSync(+ join(project, "index.html"),+ "<html><body>Missing composition metadata</body></html>",+ );+ try {+ for (let i = 0; i < 2; i++) {+ await runCommand(check, { rawArgs: [project, "--json"] });+ consumeCommandResult();+ }+ const state = JSON.parse(readFileSync(join(project, ".hyperframes/video-state.json"), "utf8"));+ expect(state.checks.unversioned).toHaveLength(2);+ const [first, second] = state.checks.unversioned;+ expect(first.report).not.toBe(second.report);+ expect(first.report).toBe(+ join(project, ".hyperframes", "artifacts", "checks", `${first.id}.json`),+ );+ expect(JSON.parse(readFileSync(first.report, "utf8")).browserSkipped).toBe(true);+ expect(state.checks.latest).toEqual({ revision: null, id: second.id });+ expect(state.checks.revisions).toEqual({});+ const output = JSON.parse(String(log.mock.calls.at(-1)?.[0]));+ expect(output.saved).toEqual({+ id: second.id,+ revision: null,+ report: second.report,+ attribution: "unversioned",+ });+ expect(output.browserSkipped).toBe(true);+ } finally {+ log.mockRestore();+ consumeCommandResult();+ rmSync(project, { recursive: true, force: true });+ }+});++it("only warns when the report cannot be recorded; the exit status is the check's own", async () => {+ const project = mkdtempSync(join(tmpdir(), "hf-check-unrecorded-"));+ const log = vi.spyOn(console, "log").mockImplementation(() => undefined);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ writeFileSync(+ join(project, "index.html"),+ "<html><body>Missing composition metadata</body></html>",+ );+ mkdirSync(join(project, ".hyperframes", "artifacts"), { recursive: true });+ writeFileSync(join(project, ".hyperframes", "artifacts", "checks"), "not a directory");+ try {+ await runCommand(check, { rawArgs: [project, "--json"] });+ const output = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as CheckReport;+ expect(output).not.toHaveProperty("saved");+ expect(output.browserSkipped).toBe(true);+ expect(consumeCommandResult().exitCode).toBe(checkExitCode(output));+ expect(String(warn.mock.calls.at(-1)?.[0])).toContain("Check report was not recorded");+ } finally {+ log.mockRestore();+ warn.mockRestore();+ consumeCommandResult();+ rmSync(project, { recursive: true, force: true });+ }+});++it("still reports the check when another process holds history", async () => {+ const project = mkdtempSync(join(tmpdir(), "hf-check-history-held-"));+ const log = vi.spyOn(console, "log").mockImplementation(() => undefined);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ writeFileSync(+ join(project, "index.html"),+ "<html><body>Missing composition metadata</body></html>",+ );+ const previousWait = historyDeps.ownerWaitMs;+ historyDeps.ownerWaitMs = 0;+ const held = await openProjectHistory({+ projectDir: project,+ historyRoot: historyDeps.historyRoot,+ ownerWaitMs: 0,+ });+ try {+ await runCommand(check, { rawArgs: [project, "--json"] });+ const output = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as CheckReport;+ expect(output).not.toHaveProperty("saved");+ expect(output.browserSkipped).toBe(true);+ expect(consumeCommandResult().exitCode).toBe(checkExitCode(output));+ expect(+ warn.mock.calls.some((call) => String(call[0]).includes("Check report was not recorded")),+ ).toBe(true);+ } finally {+ historyDeps.ownerWaitMs = previousWait;+ await held.close();+ log.mockRestore();+ warn.mockRestore();+ consumeCommandResult();+ rmSync(project, { recursive: true, force: true });+ }+});diff --git a/packages/cli/src/commands/clean.test.ts b/packages/cli/src/commands/clean.test.tsindex af47354f0c..5111a10f7b 100644--- a/packages/cli/src/commands/clean.test.ts+++ b/packages/cli/src/commands/clean.test.ts@@ -203,4 +203,64 @@ describe("cleanLeftovers", () => {await run({ snapshots: true });expect(existsSync(snapshots)).toBe(false);});++ it("treats saved snapshot and check artifacts like snapshots/", async () => {+ const artifacts = join(project, ".hyperframes", "artifacts");+ const snapshots = plant(artifacts, "snapshots");+ const checks = plant(artifacts, "checks");+ const state = join(project, ".hyperframes", "video-state.json");+ writeFileSync(state, "{}");++ const plain = await run();+ expect(plain.alsoReclaimable).toEqual([+ { what: "Snapshots", path: snapshots, bytes: 1000 },+ { what: "Check reports", path: checks, bytes: 1000 },+ ]);+ expect(existsSync(snapshots) && existsSync(checks)).toBe(true);++ await run({ snapshots: true });+ expect(existsSync(snapshots) || existsSync(checks)).toBe(false);+ expect(existsSync(state)).toBe(true);+ });++ it.skipIf(process.platform === "win32")(+ "does not remove snapshots or checks through a symlinked artifacts folder",+ async () => {+ const outside = join(scratch, "outside");+ const snapshots = plant(outside, "snapshots");+ const checks = plant(outside, "checks");+ mkdirSync(join(project, ".hyperframes"));+ symlinkSync(outside, join(project, ".hyperframes", "artifacts"));++ await run({ snapshots: true });+ expect(existsSync(join(snapshots, "frame_000001.jpg"))).toBe(true);+ expect(existsSync(join(checks, "frame_000001.jpg"))).toBe(true);+ },+ );++ it.skipIf(process.platform === "win32")(+ "does not remove snapshots through an artifacts folder linked inside the project",+ async () => {+ const snapshots = plant(join(project, "src"), "snapshots");+ mkdirSync(join(project, ".hyperframes"));+ symlinkSync(join(project, "src"), join(project, ".hyperframes", "artifacts"));++ await run({ snapshots: true });+ expect(existsSync(join(snapshots, "frame_000001.jpg"))).toBe(true);+ },+ );++ it.skipIf(process.platform === "win32")(+ "does not remove snapshots or checks through a symlinked .hyperframes folder",+ async () => {+ const outside = join(scratch, "outside");+ const snapshots = plant(join(outside, "artifacts"), "snapshots");+ const checks = plant(join(outside, "artifacts"), "checks");+ symlinkSync(outside, join(project, ".hyperframes"));++ await run({ snapshots: true });+ expect(existsSync(join(snapshots, "frame_000001.jpg"))).toBe(true);+ expect(existsSync(join(checks, "frame_000001.jpg"))).toBe(true);+ },+ );});diff --git a/packages/cli/src/commands/clean.ts b/packages/cli/src/commands/clean.tsindex cd1e6e2e2c..bf7d1b9cb8 100644--- a/packages/cli/src/commands/clean.ts+++ b/packages/cli/src/commands/clean.ts@@ -1,6 +1,6 @@import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";+import { isAbsolute, join, relative, resolve } from "node:path";import { defineCommand } from "citty";import {EXTRACT_CACHE_MIN_AGE_MS,@@ -26,7 +26,7 @@ import { withMeta } from "../utils/updateCheck.js";export const examples: Example[] = [["See what HyperFrames left on disk, remove nothing", "hyperframes clean --dry-run"],["Remove it", "hyperframes clean"],- ["Also remove snapshot folders", "hyperframes clean --snapshots"],+ ["Also remove snapshots and saved check reports", "hyperframes clean --snapshots"],["For agents", "hyperframes clean --json"],];@@ -128,16 +128,35 @@ function sweepProxies(sweep: Sweep, project: string): void {});}+const SNAPSHOT_FOLDERS = [+ { what: "Snapshots", path: ["snapshots"] },+ { what: "Snapshots", path: [".hyperframes", "artifacts", "snapshots"] },+ { what: "Check reports", path: [".hyperframes", "artifacts", "checks"] },+];++function staysUnderArtifacts(project: string, path: string, folder: readonly string[]): boolean {+ try {+ const allowed = join(realpathSync(project), ...folder);+ const target = realpathSync(path);+ const fromAllowed = relative(allowed, target);+ return fromAllowed === "" || (!fromAllowed.startsWith("..") && !isAbsolute(fromAllowed));+ } catch {+ return false;+ }+}+function sweepSnapshots(sweep: Sweep, project: string, remove: boolean): void {- const snapshots = join(project, "snapshots");- if (!existsSync(snapshots)) return;- if (remove) drop(sweep, "Snapshots", snapshots);- else- sweep.result.alsoReclaimable.push({- what: "Snapshots",- path: snapshots,- bytes: directorySizeBytes(snapshots),- });+ for (const folder of SNAPSHOT_FOLDERS) {+ const path = join(project, ...folder.path);+ if (!existsSync(path) || !staysUnderArtifacts(project, path, folder.path)) continue;+ if (remove) drop(sweep, folder.what, path);+ else+ sweep.result.alsoReclaimable.push({+ what: folder.what,+ path,+ bytes: directorySizeBytes(path),+ });+ }}async function sweepHistories(sweep: Sweep, historyRoot: string, tempDir: string): Promise<void> {@@ -233,7 +252,11 @@ export default defineCommand({description: "List what would be removed, remove nothing",default: false,},- snapshots: { type: "boolean", description: "Also remove snapshots/ folders", default: false },+ snapshots: {+ type: "boolean",+ description: "Also remove snapshots/ and .hyperframes/artifacts/{snapshots,checks}/ folders",+ default: false,+ },json: { type: "boolean", description: "Output as JSON", default: false },},async run({ args }) {diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.tsindex ff2ca137b2..033cce32e9 100644--- a/packages/cli/src/commands/render.test.ts+++ b/packages/cli/src/commands/render.test.ts@@ -1,6 +1,6 @@// fallow-ignore-file code-duplicationimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { spawn } from "node:child_process";@@ -1207,6 +1207,32 @@ describe("renderLocal browser GPU config", () => {vi.advanceTimersByTime(100);expect(consumeCommandResult().exitCode).toBe(0);});++ it("still completes the render when the output registry cannot be written", async () => {+ const project = mkdtempSync(join(tmpdir(), "hf-render-unrecorded-"));+ mkdirSync(join(project, ".hyperframes"));+ writeFileSync(join(project, ".hyperframes", "render-outputs.json"), "{");+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ try {+ await renderLocal(project, join(project, "out.mp4"), {+ fps: { num: 30, den: 1 },+ quality: "standard",+ format: "mp4",+ gpu: false,+ browserGpuMode: "hardware",+ hdrMode: "auto",+ quiet: true,+ });+ expect(+ warn.mock.calls.some((call) =>+ String(call[0]).includes("Render output was not registered"),+ ),+ ).toBe(true);+ } finally {+ warn.mockRestore();+ rmSync(project, { recursive: true, force: true });+ }+ });});// Suite renamed with the breaker work: this is no longer an opt-in trial. Thediff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.tsindex 634a2f8eeb..36d508644d 100644--- a/packages/cli/src/commands/render.ts+++ b/packages/cli/src/commands/render.ts@@ -1,3 +1,5 @@+import { captureArtifactRevision } from "../utils/artifactCapture.js";+import { recordRenderSuccess, registerRenderOutput } from "@hyperframes/studio-server/history";import { failCommand, requestCliExit } from "../utils/commandResult.js";import { defineCommand } from "citty";import type { Example } from "./_examples.js";@@ -763,6 +765,12 @@ function resolveDockerHostPlatform(options: RenderOptions): string {return platform;}+async function registerRenderOutputOrWarn(projectDir: string, outputPath: string): Promise<void> {+ await registerRenderOutput(projectDir, outputPath).catch((error: unknown) =>+ console.warn(`Render output was not registered: ${normalizeErrorMessage(error)}`),+ );+}+// Inherited minor finding (CRAP 37.1, cyclomatic 11). This PR only added// `pageNavigationTimeoutMs` to the options forwarded to `buildDockerRunArgs`.// fallow-ignore-next-line complexity@@ -771,6 +779,8 @@ async function renderDocker(outputPath: string,options: RenderOptions,): Promise<SingleRenderResult> {+ await registerRenderOutputOrWarn(projectDir, outputPath);+ const capture = await captureArtifactRevision(projectDir).catch(() => undefined);const startTime = Date.now();// Dev mode (tsx/ts-node) uses "latest" since the local version isn't on npm@@ -860,6 +870,9 @@ async function renderDocker(// so any late throw here (telemetry flush, feedback prompt) cannot flip// the exit code.markRenderSucceeded();+ await runPostRenderStepAsync("recordRenderSuccess", () =>+ recordRenderSuccess(projectDir, outputPath, "completed", capture).then(() => {}),+ );// Track metrics (no job object available from Docker — use a minimal stub)runPostRenderStep("trackRenderComplete", () =>@@ -922,6 +935,8 @@ async function executeLocalRender(options: RenderOptions,cancellation: ReturnType<typeof createRenderCancellationScope>,): Promise<SingleRenderResult> {+ await registerRenderOutputOrWarn(projectDir, outputPath);+ const capture = await captureArtifactRevision(projectDir).catch(() => undefined);cancellation.checkAncestors();cancellation.signal.throwIfAborted();let recoveredOrphanTrees = 0;@@ -1130,6 +1145,14 @@ async function executeLocalRender(// the exit code. Field signal ts=1784169760 / ts=1784171150 / ts=1784172467// (win32/x64, CLI 0.7.58): valid MP4 on disk, exited 1 with no error print.markRenderSucceeded();+ await runPostRenderStepAsync("recordRenderSuccess", () =>+ recordRenderSuccess(+ projectDir,+ outputPath,+ job.outcome === "completed_with_warnings" ? "completed_with_warnings" : "completed",+ capture,+ ).then(() => {}),+ );maybeConsumeDeParallelRouterTrial(deParallelRouterActive, job, options.quiet);const elapsed = Date.now() - startTime;diff --git a/packages/cli/src/commands/snapshot-contactSheet.test.ts b/packages/cli/src/commands/snapshot-contactSheet.test.tsindex 10d4f211a8..f943c9804c 100644--- a/packages/cli/src/commands/snapshot-contactSheet.test.ts+++ b/packages/cli/src/commands/snapshot-contactSheet.test.ts@@ -40,6 +40,8 @@ vi.mock("@hyperframes/engine", () => ({}));import snapshotCommand from "./snapshot.js";+import { historyDeps } from "../utils/historyOwner.js";+import { openProjectHistory } from "@hyperframes/studio-server/history";describe("snapshot contact sheet failures", () => {let project: string;@@ -95,7 +97,11 @@ describe("snapshot contact sheet failures", () => {await expect(runCommand(snapshotCommand, {- rawArgs: [project, "--at", "0.5,1", "--no-end", "--describe", "false"],+ rawArgs: [+ project,+ ...["--at", "0.5,1", "--no-end", "--describe", "false"],+ ...["--output", join(project, "snapshots")],+ ],}),).resolves.toBeDefined();@@ -122,7 +128,11 @@ describe("snapshot contact sheet failures", () => {vi.doMock("../capture/contactSheet.js", () => ({ createSnapshotContactSheet: generate }));await runCommand(snapshotCommand, {- rawArgs: [project, "--at", "0.5,1", "--no-end", "--describe", "false"],+ rawArgs: [+ project,+ ...["--at", "0.5,1", "--no-end", "--describe", "false"],+ ...["--output", join(project, "snapshots")],+ ],});expect(generate).toHaveBeenCalledWith(join(project, "snapshots"), sheet);@@ -130,4 +140,57 @@ describe("snapshot contact sheet failures", () => {expect(console.warn).not.toHaveBeenCalled();expect(console.error).not.toHaveBeenCalled();});++ it("keeps the captured frames when another process holds history", async () => {+ const args = {+ rawArgs: [+ project,+ ...["--at", "0.5,1", "--no-end", "--describe", "false"],+ ...["--output", join(project, "snapshots")],+ ],+ };+ await runCommand(snapshotCommand, args);+ const statePath = join(project, ".hyperframes", "video-state.json");+ const recorded = JSON.parse(readFileSync(statePath, "utf8"));+ expect(recorded.snapshots.unversioned.length).toBeGreaterThan(0);++ const previousWait = historyDeps.ownerWaitMs;+ historyDeps.ownerWaitMs = 0;+ const held = await openProjectHistory({+ projectDir: project,+ historyRoot: historyDeps.historyRoot,+ ownerWaitMs: 0,+ });+ capture.screenshot.mockImplementation(async ({ path }: { path: string }) => {+ const bytes = Buffer.from("replaced PNG");+ writeFileSync(path, bytes);+ return bytes;+ });+ capture.evaluate+ .mockReset()+ .mockResolvedValueOnce({ loaded: [], errored: [], unused: [] })+ .mockResolvedValueOnce(2)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce(undefined);+ try {+ await runCommand(snapshotCommand, args);+ for (const [index, time] of ["0.5", "1"].entries()) {+ const frame = join(project, "snapshots", `frame-0${index}-at-${time}s.png`);+ expect(readFileSync(frame)).toEqual(Buffer.from("replaced PNG"));+ }+ const after = JSON.parse(readFileSync(statePath, "utf8"));+ expect(after.snapshots.unversioned).toEqual([]);+ expect(after.snapshots.latest).toBeNull();+ expect(console.error).not.toHaveBeenCalled();+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining("Snapshots were not recorded"),+ );+ } finally {+ historyDeps.ownerWaitMs = previousWait;+ await held.close();+ }+ });});diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.tsindex ad6d75093b..58d25def41 100644--- a/packages/cli/src/commands/snapshot.ts+++ b/packages/cli/src/commands/snapshot.ts@@ -6,6 +6,15 @@ import {resolveSnapshotCompositionRange,type SnapshotRange,} from "./snapshotSampling.js";+import { captureArtifactRevision } from "../utils/artifactCapture.js";+import { randomUUID } from "node:crypto";+import {+ artifactDirectory,+ forgetRecordedArtifacts,+ recordArtifacts,+ type ArtifactCapture,+} from "@hyperframes/studio-server/history";+import { pngDimensions } from "../utils/pngDimensions.js";import { failCommand } from "../utils/commandResult.js";// fallow-ignore-file complexityimport { defineCommand } from "citty";@@ -461,6 +470,17 @@ async function captureSnapshots(): Promise<string[]> {const { bundleWithLocalizedFonts } = await import("../utils/bundleWithLocalizedFonts.js");+ const capture = await captureArtifactRevision(projectDir).catch(warnSnapshotsNotRecorded);+ const invocation = randomUUID();+ const artifacts: Array<{+ id: string;+ image: string;+ time: number;+ metadata: Record<string, unknown>;+ }> = [];+ const replaced: string[] = [];+ const warnings: string[] = [];+ let completed = false;const numFrames = opts.frames ?? 5;// Localize fonts (embed remote @font-face as data URIs, matching the render@@ -471,13 +491,18 @@ async function captureSnapshots(const savedPaths: string[] = [];try {- const { browser: chromeBrowser, page } = await openSettledCompositionPage(html, server.url, {+ const {+ browser: chromeBrowser,+ page,+ renderReadyTimedOut,+ } = await openSettledCompositionPage(html, server.url, {renderReadyTimeoutMs: opts.timeout ?? 5000,renderReadyWarningSuffix: "snapshots may be inaccurate",browserGpuMode: opts.browserGpuMode,});try {+ if (renderReadyTimedOut) warnings.push("Render readiness timed out");// Font verification — split into loaded / errored / unused. Only status// "error" is a real failure; a face still "unloaded"/"loading" after// document.fonts.ready + the settle wait was simply never requested by any@@ -512,6 +537,9 @@ async function captureSnapshots(}}+ if (fontReport.errored.length)+ warnings.push(`Fonts failed: ${fontReport.errored.join(", ")}`);+const duration = await page.evaluate(() => {const win = window as any;if (typeof win.__player?.getDuration === "function") {@@ -572,13 +600,15 @@ async function captureSnapshots(? `(${orbitStageSource()})(${JSON.stringify(opts.angle)})`: null;- const snapshotDir = opts.outputDir ?? join(projectDir, "snapshots");+ const snapshotDir = opts.outputDir ?? artifactDirectory(projectDir, "snapshots");mkdirSync(snapshotDir, { recursive: true });try {const { readdirSync } = await import("node:fs");for (const file of readdirSync(snapshotDir)) {if (/\.(png|jpg|jpeg)$/i.test(file)) {- rmSync(join(snapshotDir, file), { force: true });+ const path = resolve(snapshotDir, file);+ replaced.push(path);+ rmSync(path, { force: true });}}} catch {@@ -618,6 +648,7 @@ async function captureSnapshots(// <video data-start> will screenshot black (chrome-headless ignores// programmatic currentTime writes). Say so instead of silently// shipping black frames (two wild Windows reports).+ warnings.push("Video frame extraction engine unavailable");console.warn(` ${c.warn("⚠")} @hyperframes/engine unavailable — <video> elements will appear black in snapshots. Verify media via a draft render's extracted frames instead.`,);@@ -762,6 +793,7 @@ async function captureSnapshots(if (active.length > 0 && updates.length < active.length) {const missed = active.length - updates.length;+ warnings.push(`${missed} video frames missing at ${time}s`);console.warn(` ${c.warn("⚠")} ${missed}/${active.length} active <video> frame(s) could not be extracted at ${time.toFixed(1)}s — those videos will appear black/stale in this snapshot`,);@@ -777,6 +809,7 @@ async function captureSnapshots(active.map((a) => a.id),);} catch {+ warnings.push(`Video injection failed at ${time}s`);console.warn(` ${c.warn("⚠")} video frame injection failed at ${time.toFixed(1)}s — <video> elements will appear black/stale in this snapshot`,);@@ -790,6 +823,7 @@ async function captureSnapshots(const filename = `frame-${index}-at-${timeLabel}.png`;const framePath = join(snapshotDir, filename);+ let crop: { x: number; y: number; width: number; height: number } | undefined;if (opts.zoom) {// Clip screenshot at a raised deviceScaleFactor — never CSS zoom or// viewport resizing — so the composition's own layout is untouched.@@ -799,11 +833,13 @@ async function captureSnapshots(}));const region = await resolveCropRegion(page, opts.zoom, canvas);if (!region) {+ warnings.push(`Crop target unavailable at ${time}s`);console.error(` ${c.warn("⚠")} --zoom target has no visible box at ${time.toFixed(1)}s — frame skipped`,);continue;}+ crop = region;const buffer = await captureRegionCrop(page,region,@@ -813,6 +849,19 @@ async function captureSnapshots(} else {await page.screenshot({ path: framePath, type: "png", omitBackground: true });}+ artifacts.push({+ id: `${invocation}-${i}`,+ image: resolve(framePath),+ time,+ metadata: {+ ...pngDimensions(framePath),+ crop,+ zoom: opts.zoom,+ zoomScale: opts.zoom ? (opts.zoomScale ?? DEFAULT_ZOOM_SCALE) : 1,+ angle: opts.angle,+ browserGpuMode: opts.browserGpuMode,+ },+ });if (opts.against) {// Frame-exact reference frame beside the render, so a rebuild can be// checked against its footage without hand-rolled ffmpeg + montage.@@ -841,16 +890,61 @@ async function captureSnapshots(const rel = relative(projectDir, framePath);savedPaths.push(rel.startsWith("..") || isAbsolute(rel) ? framePath : rel);}+ completed = true;} finally {await chromeBrowser.close();}} finally {await server.close();+ const recorded = capture+ ? await recordSnapshotArtifacts(+ projectDir,+ capture,+ artifacts,+ opts.zoom,+ warnings,+ completed,+ )+ : false;+ if (!recorded) {+ const paths = [...replaced, ...artifacts.map((artifact) => artifact.image)];+ if (paths.length > 0) await forgetRecordedArtifacts(projectDir, paths).catch(() => undefined);+ }}return savedPaths;}+function warnSnapshotsNotRecorded(error: unknown): undefined {+ console.warn(` ${c.warn("⚠")} Snapshots were not recorded: ${normalizeErrorMessage(error)}`);+ return undefined;+}++async function recordSnapshotArtifacts(+ projectDir: string,+ capture: ArtifactCapture,+ artifacts: Array<{ id: string; image: string; time: number; metadata: Record<string, unknown> }>,+ zoom: ZoomTarget | undefined,+ warnings: string[],+ completed: boolean,+): Promise<boolean> {+ const records = await recordArtifacts(+ projectDir,+ capture,+ artifacts.map((artifact) => ({+ kind: "snapshot",+ scope: zoom ? "crop" : "full",+ ...artifact,+ metadata: { ...artifact.metadata, warnings, partial: !completed || warnings.length > 0 },+ })),+ ).catch(warnSnapshotsNotRecorded);+ const record = records?.[0];+ if (!record) return false;+ console.log(` Revision: ${record.revision ?? "none"} (${record.attribution})`);+ console.log(` State: ${join(projectDir, ".hyperframes", "video-state.json")}`);+ return true;+}+export default defineCommand({meta: {name: "snapshot",@@ -865,7 +959,8 @@ export default defineCommand({output: {type: "string",alias: "o",- description: "Directory to write snapshots into (default: <project>/snapshots)",+ description:+ "Directory to write snapshots into (default: unique directory under <project>/.hyperframes/artifacts/snapshots)",},frames: {type: "string",@@ -1011,7 +1106,7 @@ export default defineCommand({try {const snapshotDir = args.output? resolve(String(args.output))- : join(project.dir, "snapshots");+ : artifactDirectory(project.dir, "snapshots");await withProjectLock(project.dir, "snapshot", async () => {const paths = await captureSnapshots(project.dir, {frames,@@ -1041,9 +1136,7 @@ export default defineCommand({failCommand();}- console.log(- `\n${c.success("◇")} ${paths.length} snapshots saved to ${args.output ? snapshotDir : "snapshots/"}`,- );+ console.log(`\n${c.success("◇")} ${paths.length} snapshots saved to ${snapshotDir}`);for (const p of paths) {console.log(` ${p}`);}diff --git a/packages/cli/src/utils/artifactCapture.test.ts b/packages/cli/src/utils/artifactCapture.test.tsnew file mode 100644index 0000000000..a55e479b31--- /dev/null+++ b/packages/cli/src/utils/artifactCapture.test.ts@@ -0,0 +1,130 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { createAdaptorServer } from "@hono/node-server";+import {+ createStudioApi,+ openProjectHistory,+ type StudioApiAdapter,+} from "@hyperframes/studio-server";+import { afterEach, expect, it } from "vitest";+import { runCommand } from "citty";+import { Hono } from "hono";+import { recordArtifact, type VideoState } from "@hyperframes/studio-server/history";+import { captureArtifactRevision } from "./artifactCapture.js";+import { historyDeps, withOwner, writeTurn } from "./historyOwner.js";+import { consumeCommandResult } from "./commandResult.js";+import check from "../commands/check.js";+const roots: string[] = [];+const originalRoot = historyDeps.historyRoot;+const originalFindServer = historyDeps.findServer;+afterEach(() => {+ historyDeps.historyRoot = originalRoot;+ historyDeps.findServer = originalFindServer;+ consumeCommandResult();+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});+async function fixture() {+ const dir = mkdtempSync(join(tmpdir(), "hf-artifact-revision-"));+ roots.push(dir);+ historyDeps.historyRoot = mkdtempSync(join(tmpdir(), "hf-artifact-history-"));+ roots.push(historyDeps.historyRoot);+ writeFileSync(join(dir, "index.html"), "<html>before</html>");+ const who = { kind: "agent", name: "test-agent" } as const;+ await withOwner(dir, async (owner) => {+ const turn = await owner.begin(who, "Edit video");+ writeTurn(dir, {+ ...turn,+ who,+ label: "Edit video",+ via: owner.via,+ lastWriteAt: Date.now(),+ parts: [],+ });+ });+ return {+ dir,+ state: (): VideoState =>+ JSON.parse(readFileSync(join(dir, ".hyperframes/video-state.json"), "utf8")),+ };+}+it("records edit-then-check before the next agent step, preserving the actor", async () => {+ const f = await fixture();+ for (const text of ["first", "second"]) {+ writeFileSync(join(f.dir, "index.html"), `<html>${text}</html>`);+ await runCommand(check, { rawArgs: [f.dir, "--json"] });+ consumeCommandResult();+ const state = f.state();+ const revision = state.currentRevision!;+ expect(state.checks.latest?.revision).toBe(revision);+ expect(state.checks.revisions[revision]).toHaveLength(1);+ expect(state.checks.unversioned).toHaveLength(0);+ expect(state.revisions[revision]?.actor).toEqual({ kind: "agent", name: "test-agent" });+ expect(readFileSync(state.files["index.html"]!.content, "utf8")).toBe(`<html>${text}</html>`);+ }+ const revision = f.state().currentRevision;+ await captureArtifactRevision(f.dir);+ expect(f.state().currentRevision).toBe(revision);+ expect(Object.keys(f.state().checks.revisions)).toHaveLength(2);+});+it("does not assign results when inputs change during capture", async () => {+ const f = await fixture();+ writeFileSync(join(f.dir, "index.html"), "<html>first</html>");+ const capture = await captureArtifactRevision(f.dir);+ expect(capture.revision).toBeTruthy();+ writeFileSync(join(f.dir, "index.html"), "<html>second</html>");+ const image = join(f.dir, ".hyperframes/frame.png");+ writeFileSync(image, "image");+ await recordArtifact(f.dir, capture, { kind: "snapshot", id: "frame", scope: "full", image });+ await captureArtifactRevision(f.dir);+ expect(f.state().snapshots.unversioned[0]?.attribution).toBe("inputs-changed");+ expect(f.state().snapshots.latest?.revision).toBeNull();+});++it("posts a preview checkpoint instead of sending GET", async () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-artifact-preview-"));+ roots.push(dir);+ historyDeps.historyRoot = mkdtempSync(join(tmpdir(), "hf-artifact-preview-history-"));+ roots.push(historyDeps.historyRoot);+ writeFileSync(join(dir, "index.html"), "<html>preview</html>");+ const history = await openProjectHistory({+ projectDir: dir,+ historyRoot: historyDeps.historyRoot,+ });+ let checkpoints = 0;+ const checkpoint = history.checkpoint.bind(history);+ history.checkpoint = () => {+ checkpoints += 1;+ return checkpoint();+ };+ const adapter = {+ listProjects: () => [],+ resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),+ history: () => history,+ } as unknown as StudioApiAdapter;+ const server = createAdaptorServer({+ fetch: new Hono().route("/api", createStudioApi(adapter)).fetch,+ });+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const { port } = server.address() as AddressInfo;+ historyDeps.findServer = async () =>+ ({+ port,+ host: "127.0.0.1",+ projectName: "demo",+ projectDir: dir,+ version: "test",+ pid: null,+ }) as never;+ try {+ await withOwner(dir, async (owner) => {+ expect(owner.via).toBe("preview");+ await owner.checkpoint();+ });+ expect(checkpoints).toBe(1);+ } finally {+ server.close();+ await history.close();+ }+});diff --git a/packages/cli/src/utils/artifactCapture.ts b/packages/cli/src/utils/artifactCapture.tsnew file mode 100644index 0000000000..87f730f05e--- /dev/null+++ b/packages/cli/src/utils/artifactCapture.ts@@ -0,0 +1,9 @@+import { beginArtifactCapture } from "@hyperframes/studio-server/history";+import { withOwner } from "./historyOwner.js";++export async function captureArtifactRevision(projectDir: string) {+ return withOwner(projectDir, async (owner) => {+ await owner.checkpoint();+ return beginArtifactCapture(projectDir);+ });+}diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.tsindex 59cce065ee..1a154c99f4 100644--- a/packages/cli/src/utils/checkBrowser.ts+++ b/packages/cli/src/utils/checkBrowser.ts@@ -1,3 +1,4 @@+import { checkSnapshotDirectory } from "./checkSnapshotDirectory.js";import { mkdirSync, writeFileSync } from "node:fs";import { join, resolve } from "node:path";import type { Page } from "puppeteer-core";@@ -289,7 +290,7 @@ export async function captureFindingCrops(const page = session.page;await waitForPreferredSeekTarget(page);- const snapshotDir = join(project.dir, "snapshots");+ const snapshotDir = checkSnapshotDirectory(project.dir);mkdirSync(snapshotDir, { recursive: true });for (const request of requests) {await seekCompositionTimeline(page, request.time, AUDIT_SEEK_OPTIONS);@@ -300,7 +301,7 @@ export async function captureFindingCrops(const region = padCropRegion(request.bbox, canvas, DEFAULT_ZOOM_PADDING_PX);const buffer = await captureRegionCrop(page, region, DEFAULT_ZOOM_SCALE);writeFileSync(join(snapshotDir, request.filename), buffer);- written.push(join("snapshots", request.filename));+ written.push(join(snapshotDir, request.filename));}return written;} finally {diff --git a/packages/cli/src/utils/checkPipeline.ts b/packages/cli/src/utils/checkPipeline.tsindex 5a6e1f0aa7..2ea601b752 100644--- a/packages/cli/src/utils/checkPipeline.ts+++ b/packages/cli/src/utils/checkPipeline.ts@@ -1,3 +1,4 @@+import { checkSnapshotDirectory } from "./checkSnapshotDirectory.js";import { findingElementKey, groupSampledFindings } from "./checkFindings.js";import { mkdirSync, writeFileSync } from "node:fs";import { join, relative } from "node:path";@@ -1749,12 +1750,12 @@ async function writeSnapshot(time: number,pngBase64: string,): Promise<string> {- const snapshotDir = join(projectDir, "snapshots");+ const snapshotDir = checkSnapshotDirectory(projectDir);mkdirSync(snapshotDir, { recursive: true });const filename = `frame-${String(index).padStart(2, "0")}-at-${time.toFixed(1)}s.png`;const path = join(snapshotDir, filename);writeFileSync(path, Buffer.from(pngBase64, "base64"));- return join("snapshots", filename);+ return relative(projectDir, path);}async function captureFindingCrops(diff --git a/packages/cli/src/utils/checkSnapshotDirectory.ts b/packages/cli/src/utils/checkSnapshotDirectory.tsnew file mode 100644index 0000000000..51365fa4d3--- /dev/null+++ b/packages/cli/src/utils/checkSnapshotDirectory.ts@@ -0,0 +1,14 @@+import { randomUUID } from "node:crypto";+import { join, resolve } from "node:path";++const runDirectories = new Map<string, string>();++export function checkSnapshotDirectory(projectDir: string): string {+ const project = resolve(projectDir);+ let directory = runDirectories.get(project);+ if (!directory) {+ directory = join(project, ".hyperframes", "artifacts", "snapshots", randomUUID());+ runDirectories.set(project, directory);+ }+ return directory;+}diff --git a/packages/cli/src/utils/historyOwner.ts b/packages/cli/src/utils/historyOwner.tsindex f012b6d6e9..34d1852a07 100644--- a/packages/cli/src/utils/historyOwner.ts+++ b/packages/cli/src/utils/historyOwner.ts@@ -46,6 +46,7 @@ export interface Owner {exclusive?: boolean,): Promise<{ id: string; startedAt: number }>;end(id: string): Promise<HistoryEntry | null>;+ checkpoint(): Promise<void>;close(): Promise<void>;}@@ -127,18 +128,22 @@ export async function endTurn(}function previewOwner(route: (path: string) => string): Owner {- const call = async (path: string, body?: object) => {- const init = body && {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(body),+ const call = async (path: string, body?: object, signal?: AbortSignal) => {+ const init = {+ ...(body && {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ }),+ ...(signal && { signal }),};const response = await fetch(route(path), init);if (response.ok) return response;const error = (await response.json().catch(() => null)) as { error?: string } | null;throw new Refusal(error?.error ?? `The preview answered ${response.status}.`);};- const json = async (path: string, body?: object) => (await call(path, body)).json();+ const json = async (path: string, body?: object, signal?: AbortSignal) =>+ (await call(path, body, signal)).json();const list = async () => (await json("")).entries as HistoryListItem[];return {via: "preview",@@ -162,6 +167,7 @@ function previewOwner(route: (path: string) => string): Owner {json(`/window/${id}/close`, {}).then((closed) => closed.entry as HistoryEntry | null).catch(async () => (await list()).find((entry) => entry.id === id) ?? null),+ checkpoint: async () => void (await json("/checkpoint", {}, AbortSignal.timeout(5_000))),close: async () => {},};}@@ -201,6 +207,7 @@ async function directOwner(projectDir: string): Promise<{ owner: Owner; turn: Tu// Opening filed every earlier write; the turn's own writes are filed to it when the next open passes it.begin: async () => ({ id: randomUUID(), startedAt: historyDeps.now() }),end: async (id) => history.list().find((entry) => entry.id === id) ?? null,+ checkpoint: () => history.checkpoint(),close: () => history.close(),},};diff --git a/packages/cli/src/utils/pngDimensions.ts b/packages/cli/src/utils/pngDimensions.tsnew file mode 100644index 0000000000..3f9f82beca--- /dev/null+++ b/packages/cli/src/utils/pngDimensions.ts@@ -0,0 +1,11 @@+import { readFileSync } from "node:fs";++export function pngDimensions(path: string): { width?: number; height?: number } {+ try {+ const png = readFileSync(path);+ if (png.length < 24) return {};+ return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };+ } catch {+ return {};+ }+}diff --git a/packages/cli/src/utils/toolContext.ts b/packages/cli/src/utils/toolContext.tsindex ae872773ca..67b44832f3 100644--- a/packages/cli/src/utils/toolContext.ts+++ b/packages/cli/src/utils/toolContext.ts@@ -8,7 +8,7 @@ export interface ToolContext {projectLock?: { waitMs: number };}-export type ArtifactRole = "contact-sheet" | "frame" | "finding";+export type ArtifactRole = "contact-sheet" | "frame" | "finding" | "check-report";interface ArtifactCreatedEvent {version: typeof TOOL_CONTEXT_VERSION;@@ -53,6 +53,7 @@ const MEDIA_TYPES: Record<string, string> = {".png": "image/png",".jpg": "image/jpeg",".jpeg": "image/jpeg",+ ".json": "application/json",};export function reportArtifacts(diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.tsindex 770779f93c..f751f02339 100644--- a/packages/cli/vitest.config.ts+++ b/packages/cli/vitest.config.ts@@ -25,6 +25,10 @@ if (process.platform === "win32") {export default defineConfig({resolve: {alias: [+ {+ find: /^@hyperframes\/studio-server\/history$/,+ replacement: resolve(__dirname, "../studio-server/src/history/index.ts"),+ },// Resolve the bare @hyperframes/core entry to TypeScript source, not built// dist. The published dist intentionally omits runtime/entry.ts, so the// dist build of loadHyperframeRuntimeSource() returns null — which makesdiff --git a/packages/studio-server/src/history/index.ts b/packages/studio-server/src/history/index.tsindex 93b6407510..f80aafa327 100644--- a/packages/studio-server/src/history/index.ts+++ b/packages/studio-server/src/history/index.ts@@ -34,6 +34,7 @@ export {export {beginArtifactCapture,+ forgetRecordedArtifacts,recordArtifact,recordArtifacts,artifactDirectory,diff --git a/packages/studio-server/src/history/videoState.test.ts b/packages/studio-server/src/history/videoState.test.tsindex bac83f7d97..47f3d8e4b0 100644--- a/packages/studio-server/src/history/videoState.test.ts+++ b/packages/studio-server/src/history/videoState.test.ts@@ -1,5 +1,6 @@import {mkdtempSync,+ mkdirSync,readFileSync,rmSync,writeFileSync,@@ -16,6 +17,7 @@ import {beginArtifactCapture,recordArtifact,recordArtifacts,+ forgetRecordedArtifacts,type VideoState,} from "./videoState.js";@@ -197,6 +199,23 @@ describe("video state", () => {expect(readdirSync(join(f.projectDir, ".hyperframes"))).not.toContain("blobs");});+ it("drops a record when a later run replaces the file without recording", async () => {+ const f = await fixture();+ const revision = await f.edit("first");+ const capture = await beginArtifactCapture(f.projectDir);+ const image = join(f.projectDir, "snapshots", "frame.png");+ mkdirSync(join(f.projectDir, "snapshots"));+ writeFileSync(image, "first image");+ await recordArtifacts(f.projectDir, capture, [+ { kind: "snapshot", id: "s1", time: 1, scope: "full", image },+ ]);+ writeFileSync(image, "replaced image");+ await forgetRecordedArtifacts(f.projectDir, [image]);+ const state = read(f.projectDir);+ expect(state.snapshots.revisions[revision] ?? []).toEqual([]);+ expect(state.snapshots.latest).toBeNull();+ });+it("repairs malformed derived state without losing committed history", async () => {const f = await fixture();const revision = await f.edit("first");diff --git a/packages/studio-server/src/history/videoState.ts b/packages/studio-server/src/history/videoState.tsindex 6b16f3c9b1..695d6c1f03 100644--- a/packages/studio-server/src/history/videoState.ts+++ b/packages/studio-server/src/history/videoState.ts@@ -294,6 +294,37 @@ function dropSupersededArtifacts(artifacts: ArtifactCollection, artifact: Artifa}}+function listsOf(artifacts: ArtifactCollection): ArtifactRecord[][] {+ return [...Object.values(artifacts.revisions), artifacts.unversioned];+}++export async function forgetRecordedArtifacts(+ projectDir: string,+ paths: readonly string[],+): Promise<void> {+ const gone = new Set(paths.map((path) => resolve(path)));+ if (gone.size === 0) return;+ await updateState(projectDir, (state) => {+ for (const artifacts of [state.checks, state.snapshots]) {+ for (const list of listsOf(artifacts)) {+ for (let i = list.length - 1; i >= 0; i--) {+ const record = list[i]!;+ const path = record.image ?? record.report;+ if (path && gone.has(resolve(path))) list.splice(i, 1);+ }+ }+ if (+ artifacts.latest &&+ !listsOf(artifacts).some((list) =>+ list.some((record) => record.id === artifacts.latest?.id),+ )+ ) {+ artifacts.latest = null;+ }+ }+ });+}+export function artifactDirectory(projectDir: string, kind: "checks" | "snapshots"): string {return join(resolve(projectDir), ".hyperframes", "artifacts", kind, randomUUID());}diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.jsonindex 7b0e4d556d..17426986f9 100644--- a/scripts/package-size-budgets.json+++ b/scripts/package-size-budgets.json@@ -12,5 +12,5 @@"@hyperframes/sdk": { "packed": 90662, "unpacked": 325069 },"@hyperframes/shader-transitions": { "packed": 212864, "unpacked": 825937 },"@hyperframes/studio": { "packed": 5998328, "unpacked": 24360208 },- "@hyperframes/studio-server": { "packed": 134964, "unpacked": 532277 }+ "@hyperframes/studio-server": { "packed": 141718, "unpacked": 559199 }}diff --git a/skills-manifest.json b/skills-manifest.jsonindex 558f0ab867..960e5a88ac 100644--- a/skills-manifest.json+++ b/skills-manifest.json@@ -6,7 +6,7 @@"files": 145},"faceless-explainer": {- "hash": "fe5ac45ac43dee42",+ "hash": "bb2225ebaf7f9622","files": 29},"figma": {@@ -30,7 +30,7 @@"files": 8},"hyperframes-cli": {- "hash": "5a0f95b33cc1e8ad",+ "hash": "56a46bc15c308d98","files": 11},"hyperframes-core": {@@ -58,7 +58,7 @@"files": 112},"motion-graphics": {- "hash": "6db77031ad839f6a",+ "hash": "7e4af0881390ac2e","files": 23},"music-to-video": {@@ -66,11 +66,11 @@"files": 169},"pr-to-video": {- "hash": "49dfd8081dfb3417",+ "hash": "d377b802ef54bc46","files": 35},"product-launch-video": {- "hash": "70d41a9836b6db41",+ "hash": "965b9b93bf19b173","files": 37},"remotion-to-hyperframes": {@@ -82,7 +82,7 @@"files": 2},"talking-head-recut": {- "hash": "9aac076ceddd2499",+ "hash": "4b2cf6d7b6e336b4","files": 28}}diff --git a/skills/faceless-explainer/SKILL.md b/skills/faceless-explainer/SKILL.mdindex 2697f22147..664e643263 100644--- a/skills/faceless-explainer/SKILL.md+++ b/skills/faceless-explainer/SKILL.md@@ -191,7 +191,7 @@ Inject transitions, run checks, pause for review, then render.`npx hyperframes snapshot --at <frame-midpoints>`-`snapshot` stitches the captured frames into one contact sheet (`snapshots/contact-sheet.jpg`). Glance at it; if nothing is obviously broken, move on — don't linger here.+`snapshot` stitches the captured frames into one contact sheet (`.hyperframes/artifacts/snapshots/<id>/contact-sheet.jpg`; the command prints the path). Glance at it; if nothing is obviously broken, move on — don't linger here.If a command fails, surface stderr and stop — don't pile on recovery commands. Fix it yourself: the cheapest safe edit to `compositions/frames/NN-*.html`, then rerun the failed check.diff --git a/skills/hyperframes-cli/SKILL.md b/skills/hyperframes-cli/SKILL.mdindex d920afac01..e9068bc9af 100644--- a/skills/hyperframes-cli/SKILL.md+++ b/skills/hyperframes-cli/SKILL.md@@ -79,6 +79,9 @@ Static audits cannot catch every mount failure. When the project uses sub-compos```bashnpx hyperframes snapshot --at <t1>,<t2>,<t3>+# For multiple samples within one scene or interval:+npx hyperframes snapshot --composition <data-composition-id> --frames 8+npx hyperframes snapshot --range 3:5 --frames 8```Treat tiny unstyled content, canvas-sized icons, missing hero elements, or timeline-registration timeouts as render-blocking mount defects. See `hyperframes-core/references/sub-compositions.md` for the corresponding fixes.diff --git a/skills/hyperframes-cli/references/lint-validate-inspect.md b/skills/hyperframes-cli/references/lint-validate-inspect.mdindex 55b54def91..58ce0915fe 100644--- a/skills/hyperframes-cli/references/lint-validate-inspect.md+++ b/skills/hyperframes-cli/references/lint-validate-inspect.md@@ -104,9 +104,13 @@ Drop a `*.motion.json` sidecar next to the composition (matching the html basenanpx hyperframes snapshot # 5 key frames as PNGnpx hyperframes snapshot ./my-project # specific projectnpx hyperframes snapshot --frames 10 # evenly-spaced N frames+npx hyperframes snapshot --range 3:5 --frames 8 # 8 frames within root-timeline seconds 3–5+npx hyperframes snapshot --composition intro --frames 8 # 8 frames within this data-composition-id```-Captures still PNGs from the composition for visual diffing, thumbnails, or attaching to a PR. Faster than rendering a video when you only need a few hero frames. Output lands in the project's snapshots directory. Not deprecated: it remains the standalone capture utility, while `check --snapshots` covers the gate's needs (overview frames annotated with labeled finding boxes, plus `finding-NN-<code>.png` crops for every error finding with a bbox).+Still PNGs. Each run writes `.hyperframes/artifacts/snapshots/<id>/` unless `--output` is set. `snapshot` is the standalone capture; `check --snapshots` is the gate.++One of `--at`, `--range START:END` (seconds), or `--composition <data-composition-id>` (not a CSS selector). `--frames` defaults to 5. Range and composition sample just before the end and add no extra end frame; `--at` adds one unless `--no-end`.### Zooming into a reported findingdiff --git a/skills/motion-graphics/SKILL.md b/skills/motion-graphics/SKILL.mdindex 3405c60009..06611a3e1a 100644--- a/skills/motion-graphics/SKILL.md+++ b/skills/motion-graphics/SKILL.md@@ -32,7 +32,7 @@ A short design-led motion graphic. **Asset-first**: decide the asset strategy an| source ◇ | Bash — media-use resolve (**skip if `asset_needs` is empty**) | `assets/` + `assets/index.md` | `phases/source/guide.md` || design | subagent — shot design around resolved assets | `shot-plan.json` (final: block(s) + layout + motion + positions) | `agents/director.md` (Part 2) || build | subagent — reuse-first composition | `compositions/index.html` | `agents/builder.md` |-| verify | Bash — `lint`, `check`, proof snapshots; repair on failure | `snapshots/contact-sheet.jpg` | Step 5 |+| verify | Bash — `lint`, `check`, proof snapshots; repair on failure | `.hyperframes/artifacts/snapshots/<id>/contact-sheet.jpg` | Step 5 || approve | Open the preview; ask render or changes; wait for the answer | explicit render approval | Step 6 || render | Bash — `hyperframes render` (MP4, or `--format webm/mov` for overlay) | `renders/video.mp4` or transparent overlay | Step 6 |diff --git a/skills/pr-to-video/SKILL.md b/skills/pr-to-video/SKILL.mdindex fe399ecb53..4a3d59a268 100644--- a/skills/pr-to-video/SKILL.md+++ b/skills/pr-to-video/SKILL.md@@ -221,7 +221,7 @@ Inject transitions, run checks, pause for review, then render.`npx hyperframes snapshot --at <frame-midpoints>`-`snapshot` stitches the captured frames into one contact sheet (`snapshots/contact-sheet.jpg`). Glance at it; if nothing is obviously broken, move on — don't linger here.+`snapshot` stitches the captured frames into one contact sheet (`.hyperframes/artifacts/snapshots/<id>/contact-sheet.jpg`; the command prints the path). Glance at it; if nothing is obviously broken, move on — don't linger here.If a command fails, surface stderr and stop — don't pile on recovery commands. Fix it yourself: the cheapest safe edit to `compositions/frames/NN-*.html`, then rerun the failed check.diff --git a/skills/product-launch-video/SKILL.md b/skills/product-launch-video/SKILL.mdindex 22ce3884f2..2d8af7c762 100644--- a/skills/product-launch-video/SKILL.md+++ b/skills/product-launch-video/SKILL.md@@ -230,7 +230,7 @@ The assembler emits separate narration clips without an audio group. Before carv`npx hyperframes snapshot --at <frame-midpoints-and-each-cut-minus-0.1s-and-plus-0.2s>`-`snapshot` stitches the captured frames into one contact sheet (`snapshots/contact-sheet.jpg`). Inspect the midpoint frames for layout failures, then compare the two images around every cut. A continuing element must keep the promised position, scale, opacity, and direction; fix any visible pop before rendering.+`snapshot` stitches the captured frames into one contact sheet (`.hyperframes/artifacts/snapshots/<id>/contact-sheet.jpg`; the command prints the path). Inspect the midpoint frames for layout failures, then compare the two images around every cut. A continuing element must keep the promised position, scale, opacity, and direction; fix any visible pop before rendering.If a command fails, surface stderr and stop — don't pile on recovery commands. Fix it yourself: the cheapest safe edit to `compositions/frames/NN-*.html`, then rerun the failed check.diff --git a/skills/talking-head-recut/SKILL.md b/skills/talking-head-recut/SKILL.mdindex 9af74497bd..e34ff0de6c 100644--- a/skills/talking-head-recut/SKILL.md+++ b/skills/talking-head-recut/SKILL.md@@ -1179,7 +1179,7 @@ For a sanity check before the full render, capture a single frame at aspecific timestamp:```bash-npx hyperframes snapshot public --at 5 # → public/snapshots/frame-00-at-5s.png (a single --at ignores --out)+npx hyperframes snapshot public --at 5 # → public/.hyperframes/artifacts/snapshots/<id>/frame-00-at-5s.png (a single --at ignores --out)```### 11. Report Results