Skip to content

Write HTML. Render video. Built for agents.

fix(cli): detect a missing or stale studio build before it crashes (#4076)

Miguel Ángelde9206e0f851
diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts
index c1edb4c6d7..9f4469f780 100644
--- a/packages/cli/src/cli.lifecycle.test.ts
+++ b/packages/cli/src/cli.lifecycle.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import { mockTelemetry } from "./cliDispatchTestUtils.js";
const originalArgv = [...process.argv];
const originalExitCode = process.exitCode;
@@ -244,22 +245,6 @@ function mockInitCommand(run: () => void): void {
}));
}
-function mockTelemetry(overrides: {
- flushSync?: ReturnType<typeof vi.fn>;
- trackCommandResult?: ReturnType<typeof vi.fn>;
-}): void {
- vi.doMock("./telemetry/index.js", () => ({
- flush: vi.fn(async () => {}),
- flushSync: overrides.flushSync ?? vi.fn(),
- incrementCommandCount: vi.fn(),
- showTelemetryNotice: vi.fn(),
- shouldTrack: () => false,
- trackCliError: vi.fn(),
- trackCommand: vi.fn(),
- trackCommandResult: overrides.trackCommandResult ?? vi.fn(),
- }));
-}
-
function emitStreamEpipe(): void {
process.stdout.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
}
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 66c67ccdb8..9aca6e8464 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -31,7 +31,7 @@ for (const stream of [process.stdout, process.stderr]) {
// probe lands in a directory that does not contain the bundled worker.
// We emit the worker entry next to cli.js (see tsup.config.ts) and tell
// the pool where to find it via the published env-var override.
-import { dirname, join } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { existsSync } from "node:fs";
@@ -106,6 +106,7 @@ import { getRunId } from "./telemetry/runId.js";
import { reportCommandFailure, trackCommandFailures } from "./utils/command-failure-tracking.js";
import { isRenderSucceeded } from "./utils/render-success-state.js";
import { resolveCommandUsage } from "./utils/commandUsageResolution.js";
+import { isDevMode } from "./utils/env.js";
import {
CliResultSignal,
CliRuntimeError,
@@ -118,6 +119,22 @@ import {
const isHelp = process.argv.includes("--help") || process.argv.includes("-h");
+// Runs before commands/preview.js is imported, so a missing or stale
+// package is named here instead of crashing deep inside that import.
+async function assertStudioWorkspaceBuilt(): Promise<void> {
+ if (!isDevMode()) return;
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+ const { checkStudioWorkspaceBuild, formatWorkspaceBuildProblems } =
+ await import("./utils/workspaceBuildCheck.js");
+ const problems = checkStudioWorkspaceBuild(repoRoot);
+ if (problems.length === 0) return;
+ console.error(formatWorkspaceBuildProblems(problems));
+ throw new CliRuntimeError("Studio workspace build check failed", {
+ exitCode: 1,
+ presented: true,
+ });
+}
+
// ---------------------------------------------------------------------------
// CLI definition — all commands are lazy-loaded via dynamic import()
// ---------------------------------------------------------------------------
@@ -128,7 +145,8 @@ const commandLoaders = {
catalog: () => import("./commands/catalog.js").then((m) => m.default),
play: () => import("./commands/play.js").then((m) => m.default),
present: () => import("./commands/present.js").then((m) => m.default),
- preview: () => import("./commands/preview.js").then((m) => m.default),
+ preview: () =>
+ assertStudioWorkspaceBuilt().then(() => import("./commands/preview.js").then((m) => m.default)),
publish: () => import("./commands/publish.js").then((m) => m.default),
render: () => import("./commands/render.js").then((m) => m.default),
lint: () => import("./commands/lint.js").then((m) => m.default),
diff --git a/packages/cli/src/cli.workspaceBuildGate.test.ts b/packages/cli/src/cli.workspaceBuildGate.test.ts
new file mode 100644
index 0000000000..7ff0ea107e
--- /dev/null
+++ b/packages/cli/src/cli.workspaceBuildGate.test.ts
@@ -0,0 +1,64 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mockTelemetry } from "./cliDispatchTestUtils.js";
+
+const originalArgv = [...process.argv];
+const originalExitCode = process.exitCode;
+
+afterEach(() => {
+ process.argv = [...originalArgv];
+ process.exitCode = originalExitCode;
+ vi.doUnmock("./commands/preview.js");
+ vi.doUnmock("./utils/env.js");
+ vi.doUnmock("./utils/workspaceBuildCheck.js");
+ vi.doUnmock("./telemetry/index.js");
+ vi.doUnmock("./telemetry/events.js");
+ vi.resetModules();
+});
+
+function mockPreviewGate(problems: Array<Record<string, string>>): () => boolean {
+ let previewImported = false;
+ vi.doMock("./commands/preview.js", () => {
+ previewImported = true;
+ return { default: { meta: { name: "preview" }, args: {}, run: vi.fn() } };
+ });
+ vi.doMock("./utils/env.js", () => ({ isDevMode: () => true }));
+ vi.doMock("./utils/workspaceBuildCheck.js", () => ({
+ checkStudioWorkspaceBuild: () => problems,
+ formatWorkspaceBuildProblems: () =>
+ problems.map((p) => ` - ${p.package}: ${p.detail}`).join("\n"),
+ }));
+ mockTelemetry();
+ return () => previewImported;
+}
+
+describe("CLI preview workspace build gate", () => {
+ it("blocks the preview command before its module loads, without printing the raw error twice", async () => {
+ const wasPreviewImported = mockPreviewGate([
+ {
+ package: "core",
+ kind: "missing",
+ detail: "dist/ is missing or empty",
+ fix: "bun run build",
+ },
+ ]);
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
+
+ process.argv = ["node", "cli.ts", "preview", "--json"];
+ await import("./cli.js");
+
+ expect(wasPreviewImported()).toBe(false);
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("dist/ is missing or empty"));
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ expect(process.exitCode).toBe(1);
+ errorSpy.mockRestore();
+ });
+
+ it("imports the preview module once the workspace build check reports no problems", async () => {
+ const wasPreviewImported = mockPreviewGate([]);
+
+ process.argv = ["node", "cli.ts", "preview", "--json"];
+ await import("./cli.js");
+
+ expect(wasPreviewImported()).toBe(true);
+ });
+});
diff --git a/packages/cli/src/cliDispatchTestUtils.ts b/packages/cli/src/cliDispatchTestUtils.ts
new file mode 100644
index 0000000000..fbfe43d05d
--- /dev/null
+++ b/packages/cli/src/cliDispatchTestUtils.ts
@@ -0,0 +1,26 @@
+import { vi } from "vitest";
+
+// Shared by every test that drives the real `cli.js` dispatch path
+// (dynamic import + process.argv) instead of source-text matching.
+
+export function mockTelemetry(
+ overrides: {
+ flushSync?: ReturnType<typeof vi.fn>;
+ trackCommandResult?: ReturnType<typeof vi.fn>;
+ trackCommandFailure?: ReturnType<typeof vi.fn>;
+ } = {},
+): void {
+ vi.doMock("./telemetry/index.js", () => ({
+ flush: vi.fn(async () => {}),
+ flushSync: overrides.flushSync ?? vi.fn(),
+ incrementCommandCount: vi.fn(),
+ showTelemetryNotice: vi.fn(),
+ shouldTrack: () => false,
+ trackCliError: vi.fn(),
+ trackCommand: vi.fn(),
+ trackCommandResult: overrides.trackCommandResult ?? vi.fn(),
+ }));
+ vi.doMock("./telemetry/events.js", () => ({
+ trackCommandFailure: overrides.trackCommandFailure ?? vi.fn(),
+ }));
+}
diff --git a/packages/cli/src/utils/workspaceBuildCheck.test.ts b/packages/cli/src/utils/workspaceBuildCheck.test.ts
new file mode 100644
index 0000000000..03d778acf8
--- /dev/null
+++ b/packages/cli/src/utils/workspaceBuildCheck.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import {
+ checkStudioWorkspaceBuild,
+ SKIP_STALE_CHECK_ENV,
+ STUDIO_WORKSPACE_BUILD_ORDER,
+} from "./workspaceBuildCheck.js";
+
+let dirs: string[] = [];
+
+function tmpRepoRoot(): string {
+ const dir = mkdtempSync(join(tmpdir(), "hf-workspace-build-check-"));
+ dirs.push(dir);
+ return dir;
+}
+
+/** A fully built package: dist/index.js exists, no exports gap, dist newer than src. */
+function writeBuiltPackage(
+ repoRoot: string,
+ pkg: string,
+ exportsMap: Record<string, unknown> = {
+ ".": { node: "./dist/index.js", import: "./src/index.ts" },
+ },
+): void {
+ const pkgDir = join(repoRoot, "packages", pkg);
+ mkdirSync(join(pkgDir, "src"), { recursive: true });
+ mkdirSync(join(pkgDir, "dist"), { recursive: true });
+ writeFileSync(join(pkgDir, "package.json"), JSON.stringify({ name: pkg, exports: exportsMap }));
+ writeFileSync(join(pkgDir, "src", "index.ts"), "export {};");
+ writeFileSync(join(pkgDir, "dist", "index.js"), "export {};");
+ const srcFiles = [join(pkgDir, "src", "index.ts")];
+ if (pkg === "core") {
+ mkdirSync(join(pkgDir, "src", "generated"), { recursive: true });
+ writeFileSync(join(pkgDir, "src", "generated", "runtime-inline.ts"), "export {};");
+ writeFileSync(join(pkgDir, "src", "generated", "audio-fx-runtime-inline.ts"), "export {};");
+ srcFiles.push(
+ join(pkgDir, "src", "generated", "runtime-inline.ts"),
+ join(pkgDir, "src", "generated", "audio-fx-runtime-inline.ts"),
+ );
+ }
+ // dist strictly newer than every src file so a fresh build never reads as
+ // stale — explicit timestamps, not write order, since two writeFileSync
+ // calls can land within the same JS Date.now() tick.
+ const past = new Date(Date.now() - 10_000);
+ const now = new Date();
+ for (const file of srcFiles) utimesSync(file, past, past);
+ utimesSync(join(pkgDir, "dist", "index.js"), now, now);
+}
+
+function writeAllBuilt(repoRoot: string): void {
+ for (const pkg of STUDIO_WORKSPACE_BUILD_ORDER) writeBuiltPackage(repoRoot, pkg);
+}
+
+afterEach(() => {
+ delete process.env[SKIP_STALE_CHECK_ENV];
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
+ dirs = [];
+});
+
+describe("checkStudioWorkspaceBuild", () => {
+ it("reports every package as missing on a fresh clone with nothing built", () => {
+ const repoRoot = tmpRepoRoot();
+ mkdirSync(join(repoRoot, "packages"), { recursive: true });
+
+ const problems = checkStudioWorkspaceBuild(repoRoot);
+
+ expect(problems.map((p) => p.package)).toEqual([...STUDIO_WORKSPACE_BUILD_ORDER]);
+ expect(problems.every((p) => p.kind === "missing")).toBe(true);
+ });
+
+ it("reports only the one package whose src changed after its last build", () => {
+ const repoRoot = tmpRepoRoot();
+ writeAllBuilt(repoRoot);
+ const parsersSrc = join(repoRoot, "packages", "parsers", "src", "index.ts");
+ utimesSync(parsersSrc, new Date(), new Date());
+
+ const problems = checkStudioWorkspaceBuild(repoRoot);
+
+ expect(problems).toEqual([expect.objectContaining({ package: "parsers", kind: "stale" })]);
+ });
+
+ it("skips the stale-src check under the escape hatch env var", () => {
+ const repoRoot = tmpRepoRoot();
+ writeAllBuilt(repoRoot);
+ const parsersSrc = join(repoRoot, "packages", "parsers", "src", "index.ts");
+ utimesSync(parsersSrc, new Date(), new Date());
+ process.env[SKIP_STALE_CHECK_ENV] = "1";
+
+ expect(checkStudioWorkspaceBuild(repoRoot)).toEqual([]);
+ });
+
+ it("reports a new export subpath missing from an otherwise fresh dist", () => {
+ const repoRoot = tmpRepoRoot();
+ writeAllBuilt(repoRoot);
+ // Simulates a merge that added a subpath to package.json and its src file,
+ // without anyone rebuilding this already-checked-out worktree's dist.
+ writeBuiltPackage(repoRoot, "core", {
+ ".": { node: "./dist/index.js", import: "./src/index.ts" },
+ "./new-thing": { node: "./dist/newThing.js", import: "./src/newThing.ts" },
+ });
+
+ const problems = checkStudioWorkspaceBuild(repoRoot);
+
+ expect(problems).toEqual([expect.objectContaining({ package: "core", kind: "missing" })]);
+ expect(problems[0]?.detail).toContain("newThing.js");
+ });
+
+ it("reports nothing for a fully built, fresh workspace", () => {
+ const repoRoot = tmpRepoRoot();
+ writeAllBuilt(repoRoot);
+
+ expect(checkStudioWorkspaceBuild(repoRoot)).toEqual([]);
+ });
+
+ it("reports a broken package.json instead of throwing", () => {
+ const repoRoot = tmpRepoRoot();
+ writeAllBuilt(repoRoot);
+ writeFileSync(join(repoRoot, "packages", "parsers", "package.json"), "{not json");
+
+ const problems = checkStudioWorkspaceBuild(repoRoot);
+
+ expect(problems).toEqual([expect.objectContaining({ package: "parsers", kind: "missing" })]);
+ expect(problems[0]?.detail).toContain("package.json is invalid");
+ });
+});
diff --git a/packages/cli/src/utils/workspaceBuildCheck.ts b/packages/cli/src/utils/workspaceBuildCheck.ts
new file mode 100644
index 0000000000..6ada3e0c6c
--- /dev/null
+++ b/packages/cli/src/utils/workspaceBuildCheck.ts
@@ -0,0 +1,166 @@
+// Detects a missing or stale workspace build before anything else imports it.
+// Zero `@hyperframes/*` imports: must stay importable when nothing is built.
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+/** Build-dependency order: each package only depends on ones before it. */
+export const STUDIO_WORKSPACE_BUILD_ORDER = [
+ "parsers",
+ "lint",
+ "studio-server",
+ "core",
+ "player",
+] as const;
+
+// Gitignored, produced only by `core`'s own build script. `runtime-inline.ts`
+// is imported by `core/src/index.ts` directly; `audio-fx-runtime-inline.ts` is
+// only reached via core's own `./audio-fx-runtime` subpath, which engine imports.
+const CORE_REQUIRED_GENERATED_FILES = [
+ "src/generated/runtime-inline.ts",
+ "src/generated/audio-fx-runtime-inline.ts",
+];
+
+export const SKIP_STALE_CHECK_ENV = "HYPERFRAMES_SKIP_BUILD_STALE_CHECK";
+
+export interface WorkspaceBuildProblem {
+ package: string;
+ kind: "missing" | "stale";
+ detail: string;
+ fix: string;
+}
+
+function buildCommand(pkg: string): string {
+ return `bun run --filter @hyperframes/${pkg} build`;
+}
+
+function isTestFile(name: string): boolean {
+ return /\.test\.[tj]sx?$/.test(name);
+}
+
+/** Newest mtime among files under `dir` (recursive; skips node_modules). */
+function newestMtimeMs(dir: string, { skipTests }: { skipTests: boolean }): number {
+ if (!existsSync(dir)) return 0;
+ const mtimes = readdirSync(dir, { recursive: true, withFileTypes: true })
+ .filter((entry) => entry.isFile() && !entry.parentPath.includes("node_modules"))
+ .filter((entry) => !skipTests || !isTestFile(entry.name))
+ .map((entry) => statSync(join(entry.parentPath, entry.name)).mtimeMs);
+ return mtimes.length > 0 ? Math.max(...mtimes) : 0;
+}
+
+/** The `./dist/...` targets named in every condition of a package's own `exports`
+ * map (not `publishConfig.exports`, which describes the published tarball). */
+function distExportEntries(packageDir: string): Array<{ subpath: string; target: string }> {
+ const pkgJsonPath = join(packageDir, "package.json");
+ if (!existsSync(pkgJsonPath)) return [];
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8")) as {
+ exports?: Record<string, unknown>;
+ };
+ return Object.entries(pkg.exports ?? {}).flatMap(([subpath, conditions]) =>
+ distTargetsOf(conditions).map((target) => ({ subpath, target })),
+ );
+}
+
+function distTargetsOf(conditions: unknown): string[] {
+ if (typeof conditions !== "object" || conditions === null) return [];
+ return Object.values(conditions as Record<string, unknown>).filter(
+ (value): value is string => typeof value === "string" && value.startsWith("./dist/"),
+ );
+}
+
+// Declared exports whose target file is missing — the gap a merge that adds
+// a subpath without a rebuild leaves, which a stale-mtime check alone misses.
+function missingDistExportTargets(packageDir: string): string[] {
+ return distExportEntries(packageDir)
+ .filter((entry) => !existsSync(join(packageDir, entry.target)))
+ .map((entry) => `${entry.subpath} (${entry.target})`);
+}
+
+// A malformed package.json must produce the same friendly message as any
+// other build problem, not an uncaught SyntaxError.
+function exportProblemsFor(packageDir: string, pkg: string, fix: string): WorkspaceBuildProblem[] {
+ let missingExports: string[];
+ try {
+ missingExports = missingDistExportTargets(packageDir);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return [{ package: pkg, kind: "missing", detail: `package.json is invalid: ${message}`, fix }];
+ }
+ if (missingExports.length === 0) return [];
+ return [
+ {
+ package: pkg,
+ kind: "missing",
+ detail: `dist is missing exported file(s): ${missingExports.join(", ")}`,
+ fix,
+ },
+ ];
+}
+
+// Checks parsers/lint/studio-server/core/player in build order. Missing
+// files always report; a stale src skips via HYPERFRAMES_SKIP_BUILD_STALE_CHECK=1.
+export function checkStudioWorkspaceBuild(repoRoot: string): WorkspaceBuildProblem[] {
+ const problems: WorkspaceBuildProblem[] = [];
+
+ for (const pkg of STUDIO_WORKSPACE_BUILD_ORDER) {
+ const packageDir = join(repoRoot, "packages", pkg);
+ const distDir = join(packageDir, "dist");
+ const fix = buildCommand(pkg);
+
+ if (!existsSync(distDir) || readdirSync(distDir).length === 0) {
+ problems.push({ package: pkg, kind: "missing", detail: "dist/ is missing or empty", fix });
+ continue;
+ }
+
+ if (pkg === "core") {
+ const missingGenerated = CORE_REQUIRED_GENERATED_FILES.filter(
+ (rel) => !existsSync(join(packageDir, rel)),
+ );
+ if (missingGenerated.length > 0) {
+ problems.push({
+ package: pkg,
+ kind: "missing",
+ detail: `generated file(s) missing: ${missingGenerated.join(", ")}`,
+ fix,
+ });
+ continue;
+ }
+ }
+
+ const exportProblems = exportProblemsFor(packageDir, pkg, fix);
+ if (exportProblems.length > 0) {
+ problems.push(...exportProblems);
+ continue;
+ }
+
+ if (process.env[SKIP_STALE_CHECK_ENV]) continue;
+
+ const newestSrc = newestMtimeMs(join(packageDir, "src"), { skipTests: true });
+ const newestDist = newestMtimeMs(distDir, { skipTests: false });
+ if (newestSrc > newestDist) {
+ problems.push({
+ package: pkg,
+ kind: "stale",
+ detail: `src changed after the last build (set ${SKIP_STALE_CHECK_ENV}=1 to skip this check)`,
+ fix,
+ });
+ }
+ }
+
+ return problems;
+}
+
+export function formatWorkspaceBuildProblems(problems: WorkspaceBuildProblem[]): string {
+ const lines = ["Studio workspace build check failed", ""];
+ for (const problem of problems) {
+ lines.push(` - ${problem.package}: ${problem.detail}`);
+ lines.push(` fix: ${problem.fix}`);
+ }
+ lines.push("");
+ lines.push(
+ " Or build every package in order (core depends on the first three, player on core):",
+ );
+ lines.push(" bun run --filter '@hyperframes/{parsers,lint,studio-server}' build \\");
+ lines.push(" && bun run --filter @hyperframes/core build \\");
+ lines.push(" && bun run --filter @hyperframes/player build");
+ return lines.join("\n");
+}