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: scaffold a component package, and let one live where the guide says

rpone820484c55b4a
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 88767f6a..b9977000 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -34,6 +34,7 @@ import type {
import { writeCliHelp, writeCliOutput } from "./output.js";
import type { CliColorMode, CliIo } from "./output.js";
import { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";
+import { scaffoldComponentPackage } from "./scaffold.js";
import { loadDiscoveredSourcePackages } from "./source-packages.js";
import {
clearRuntimeProfile,
@@ -67,6 +68,8 @@ type ParsedArgs = {
readonly model: string | undefined;
readonly aspectRatio: string | undefined;
readonly resolution: string | undefined;
+ /** Scaffold a component package that draws nothing, so it needs no preview and no still. */
+ readonly noVisual: boolean;
/** Leave the declared external programs alone; build against what is running. */
readonly noPrograms: boolean;
readonly json: boolean;
@@ -132,6 +135,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
let model: string | undefined;
let aspectRatio: string | undefined;
let resolution: string | undefined;
+ let noVisual = false;
let noPrograms = false;
let json = false;
let color: CliColorMode = "auto";
@@ -280,6 +284,10 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
index += 1;
continue;
}
+ if (item === "--no-visual") {
+ noVisual = true;
+ continue;
+ }
if (item === "--follow") {
follow = true;
continue;
@@ -359,6 +367,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
model,
aspectRatio,
resolution,
+ noVisual,
noPrograms,
json,
color,
@@ -405,6 +414,10 @@ function assertCommandOptions(args: ParsedArgs): void {
// A package asset needs credentials and nothing else; no Runtime Profile applies.
add("--prompt", "--to", "--model", "--aspect-ratio", "--resolution");
break;
+ case "new-package":
+ // Writing files from string templates reads no Source and opens no Runtime.
+ add("--to", "--no-visual");
+ break;
case "cancel":
add("--runtime", "--reason");
break;
@@ -460,6 +473,7 @@ function usage(): string {
" hypit cancel <build-id> [--runtime profile.json] [--reason text]",
" hypit auth status|login|logout <endpoint-instance> [--runtime profile.json] [--slot name] [--from secret-file]",
" hypit image --prompt <text|text-file> --to <path.png> [--model package] [--aspect-ratio r] [--resolution r]",
+ " hypit new-package <package-name> [--to directory] [--no-visual]",
"",
"output:",
" --json --verbose --color auto|always|never --no-color --debug",
@@ -905,7 +919,7 @@ export async function runCli(
|| args.command === "inspect" || args.command === "get" || args.command === "cancel"
|| args.command === "doctor" || args.command === "programs"
|| args.command === "runtime" || args.command === "queue" || args.command === "paths"
- || args.command === "image";
+ || args.command === "image" || args.command === "new-package";
const operational = known || args.command === "auth";
const fileOptional = args.command === "builds" || args.command === "history" || args.command === "queue"
|| args.command === "paths" || args.command === "image"
@@ -938,6 +952,41 @@ export async function runCli(
packageRoot,
});
};
+ if (args.command === "new-package") {
+ if (args.file === undefined) throw new Error("new-package requires a package name such as @hypit/local-notepad-list");
+ const scaffolded = await scaffoldComponentPackage({
+ name: args.file,
+ visual: !args.noVisual,
+ cwd: process.cwd(),
+ ...(args.to === undefined ? {} : { to: args.to }),
+ });
+ // A path outside the working directory reads better absolute than as a run of `..`.
+ const nested = relative(process.cwd(), scaffolded.root);
+ const shown = nested === "" ? "."
+ : nested.startsWith("..") || isAbsolute(nested) ? scaffolded.root
+ : nested;
+ writeOperational({
+ format: "hypit.cli-new-package@1",
+ name: scaffolded.name,
+ path: scaffolded.root,
+ tag: scaffolded.tag,
+ surface: scaffolded.surface,
+ visual: scaffolded.visual,
+ files: scaffolded.files,
+ }, "Package scaffolded", "success", [
+ ["Package", scaffolded.name],
+ ["Path", shown],
+ ["Element", `<${scaffolded.surface}:${scaffolded.tag}>`],
+ ["Files", String(scaffolded.files.length)],
+ ], [
+ "Run pnpm install so the workspace links it, then pnpm check.",
+ "The Manifest declares no Type and no Producer yet; the Surface validates and publishes nothing.",
+ ...(scaffolded.visual
+ ? [`Write preview/${scaffolded.tag}.png with node --import tsx ${shown}/test/render-still.ts`]
+ : []),
+ ]);
+ return;
+ }
if (args.command === "image") {
if (args.prompt === undefined) throw new Error("image requires --prompt with text or a text file path");
if (args.to === undefined) throw new Error("image requires --to with the file to write");
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 0219e4dd..4e93a0ac 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -521,6 +521,23 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
"the credentials the selected Provider declares.",
"Unset options take the model's own first declared value.",
],
+ "new-package": [
+ colors.accent(colors.strong("hypit new-package")),
+ colors.dim("Scaffold one component package: a Markup element and the code behind it."),
+ "",
+ " hypit new-package <package-name> [--to <directory>] [--no-visual]",
+ "",
+ " <package-name> the full name, such as @hypit/local-notepad-list",
+ " --to <directory> where to write it; defaults to packages/<name-after-the-scope>",
+ " --no-visual the component draws nothing, so skip the still render and preview",
+ "",
+ "It writes the Manifest, Types, Surface, Producers, Activation and README, plus a",
+ "still-render entry that draws one frame into preview/<Tag>.png through the local",
+ "HyperFrames Runtime. Nothing is generated it cannot decide: the nominal Types, the",
+ "Producers and the renderer are left with the comment saying where they go.",
+ "The directory must be empty, and only a package under a workspace glob is linked",
+ "by pnpm install and typechecked by pnpm check.",
+ ],
auth: [
colors.accent(colors.strong("hypit auth")),
colors.dim("Manage credentials required by one declared Endpoint instance."),
@@ -561,6 +578,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {
row("plan <run-source>", "freeze and inspect a Build plan"),
row("build <run-source>", "submit a durable Build; --follow only observes"),
row("image --prompt … --to <path>", "generate one picture file for a package asset"),
+ row("new-package <package-name>", "scaffold one component package"),
"",
colors.strong("Archive"),
row("builds", "list known Builds"),
diff --git a/packages/cli/src/reachability.ts b/packages/cli/src/reachability.ts
new file mode 100644
index 00000000..65b1f64f
--- /dev/null
+++ b/packages/cli/src/reachability.ts
@@ -0,0 +1,43 @@
+import type { BuildState, CompiledGraph } from "@hypit/protocol";
+
+export type UnreachedGeneration = {
+ /** The Producer that would have run, as the Source named it. */
+ readonly name: string;
+ readonly producer: string;
+};
+
+/**
+ * Generations a Source declares that this Run will not perform.
+ *
+ * Whether anything *consumes* a declaration cannot answer this. An Author Source has no targets, so
+ * "nothing needs this" has no meaning there, and a package's own expansion consumes its own
+ * intermediate steps — a generated picture is read by the step that picks the primary image, which
+ * makes the generation look used even when the picture it produces is read by nobody.
+ *
+ * A Run Source does have targets, and planning already prunes to what they reach. So the question
+ * that can be answered is the one that matters: this Run declares the generation and will not run
+ * it. Either nothing needs it, or a target is missing, or an accepted Record should have been
+ * pinned and was not.
+ */
+export function unreachedGenerations(
+ graph: CompiledGraph,
+ state: BuildState,
+ names: Readonly<Record<string, string>> = {},
+): readonly UnreachedGeneration[] {
+ const built = new Set<string>();
+ for (const step of state.plan.steps) {
+ for (const record of Object.values(step.outputs)) built.add(record);
+ }
+ // A satisfied output is deliberately not produced again; that is reuse working, not a leftover.
+ for (const selection of state.plan.selections) built.add(selection.record);
+ const found: UnreachedGeneration[] = [];
+ for (const operation of graph.operations) {
+ if (operation.result.kind !== "need") continue;
+ if (built.has(operation.result.record)) continue;
+ found.push({
+ name: names[operation.id] ?? names[operation.result.record] ?? operation.result.name,
+ producer: `${operation.producer.module.name}@${operation.producer.module.version}/${operation.producer.name}`,
+ });
+ }
+ return found;
+}
diff --git a/packages/cli/src/scaffold.ts b/packages/cli/src/scaffold.ts
new file mode 100644
index 00000000..e91743e2
--- /dev/null
+++ b/packages/cli/src/scaffold.ts
@@ -0,0 +1,566 @@
+import { mkdir, readdir, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+
+/**
+ * The files a new component package starts life with.
+ *
+ * These are pure string templates over one package name, so they need nothing the generic
+ * command engine does not already have: no compiler, no Host, no Provider and no new
+ * dependency. Anything a template cannot decide — the nominal Types, the Producers, the
+ * renderer — is left to the author with the comment that says where it goes, rather than
+ * guessed here.
+ */
+
+export type ScaffoldRequest = {
+ /** Full package name, such as `@hypit/local-notepad-list`. */
+ readonly name: string;
+ /** Directory the package is written into; defaults to `packages/<slug>` under `cwd`. */
+ readonly to?: string;
+ /** A package that draws nothing skips the still-render entry and the preview picture. */
+ readonly visual?: boolean;
+ readonly cwd: string;
+};
+
+export type ScaffoldedPackage = {
+ readonly name: string;
+ /** Absolute directory the package was written into. */
+ readonly root: string;
+ /** The Markup tag its one Surface declaration answers to. */
+ readonly tag: string;
+ /** The Surface's declared name inside the Module. */
+ readonly surface: string;
+ readonly visual: boolean;
+ /** Package-relative paths, in the order they were written. */
+ readonly files: readonly string[];
+};
+
+const NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
+
+/** `@hypit/local-notepad-list` → `local-notepad-list`; an unscoped name is its own slug. */
+function slugOf(name: string): string {
+ const separator = name.indexOf("/");
+ return separator === -1 ? name : name.slice(separator + 1);
+}
+
+function words(slug: string): readonly string[] {
+ return slug.split(/[^a-z0-9]+/u).filter((word) => word.length > 0);
+}
+
+function pascal(parts: readonly string[]): string {
+ return parts.map((word) => word[0]!.toUpperCase() + word.slice(1)).join("");
+}
+
+function camel(parts: readonly string[]): string {
+ const value = pascal(parts);
+ return value[0]!.toLowerCase() + value.slice(1);
+}
+
+/**
+ * A package installed only by one project is conventionally named `local-…`; that prefix
+ * says where the package lives, not what its element is, so it is not part of the tag.
+ */
+function tagWords(slug: string): readonly string[] {
+ const parts = words(slug);
+ const stripped = parts[0] === "local" ? parts.slice(1) : parts;
+ return stripped.length > 0 ? stripped : parts;
+}
+
+export type ScaffoldNames = {
+ readonly slug: string;
+ readonly tag: string;
+ readonly surface: string;
+ /** Identifier prefix every exported binding carries. */
+ readonly symbol: string;
+};
+
+export function scaffoldNames(name: string): ScaffoldNames {
+ if (!NAME.test(name)) {
+ throw new Error(`${name} is not a package name; write it as @scope/kebab-case-name`);
+ }
+ const slug = slugOf(name);
+ const parts = tagWords(slug);
+ return {
+ slug,
+ tag: pascal(parts),
+ surface: parts.join("-"),
+ symbol: camel(parts),
+ };
+}
+
+function packageJson(name: string, visual: boolean): string {
+ const value = {
+ name,
+ version: "0.0.0-dev",
+ license: "SEE LICENSE IN LICENSE",
+ private: true,
+ type: "module",
+ exports: { ".": "./src/index.ts" },
+ hypit: { activation: "./src/activation.ts" },
+ dependencies: {
+ "@hypit/component-kit": "workspace:*",
+ "@hypit/markup": "workspace:*",
+ "@hypit/protocol": "workspace:*",
+ },
+ ...(visual
+ ? {
+ devDependencies: {
+ "@hypit/composition": "workspace:*",
+ "@hypit/hyperframes": "workspace:*",
+ "@hypit/program-space": "workspace:*",
+ "@hypit/provider-hyperframes-local": "workspace:*",
+ },
+ }
+ : {}),
+ };
+ return `${JSON.stringify(value, undefined, 2)}\n`;
+}
+
+function manifest(name: string, names: ScaffoldNames, visual: boolean): string {
+ const { tag, surface, symbol } = names;
+ const preview = visual
+ ? ` preview: previewImage("${tag}.png"),\n`
+ : "";
+ const previewHelper = visual
+ ? [
+ `import { readFile } from "node:fs/promises";`,
+ ``,
+ ``,
+ ].join("\n")
+ : "";
+ const previewFunction = visual
+ ? [
+ `/** The picture this package ships for its own Surface, read from its own preview/ directory. */`,
+ `const previewImage = (file: string) => ({`,
+ ` mediaType: "image/png",`,
+ ` path: \`preview/\${file}\`,`,
+ ` open: async () => Uint8Array.from(await readFile(new URL(\`../preview/\${file}\`, import.meta.url))),`,
+ `});`,
+ ``,
+ ``,
+ ].join("\n")
+ : "";
+ const appearance = visual
+ ? ` appearance: "Describe exactly what a viewer sees: the shapes, where they sit, how they enter, hold and leave. Replace this sentence before the package ships — a reader who cannot picture the element cannot choose it.",\n`
+ : "";
+ return `${previewHelper}import type { MarkupSurfaceDeclaration } from "@hypit/markup";
+import type { ModuleManifest, ProducerRef, TypeRef } from "@hypit/protocol";
+
+${previewFunction}export const ${symbol}ModuleRef = { name: "${name}", version: "1" } as const;
+
+/**
+ * Nominal Types this Module owns. Add one entry per authored value, declare the same name
+ * in the Manifest below, and give it a TypeScript shape in types.ts.
+ */
+export const ${symbol}Types = {} satisfies Record<string, TypeRef>;
+
+/**
+ * Producers this Module declares. Add one entry per deterministic step, declare its inputs
+ * and outputs in the Manifest below, and implement it in component.ts.
+ */
+export const ${symbol}Producers = {} satisfies Record<string, ProducerRef>;
+
+export const ${symbol}MarkupSurfaces = [{
+ name: "${surface}", tag: "${tag}", mode: "structured",
+ // One entry per Type this element publishes, once the Manifest declares one.
+ outputs: [],
+ vocabulary: {
+ summary: "One ${tag}. Say what the element is for in one sentence, in the author's terms.",
+${appearance}${preview} attributes: [
+ { name: "id", kind: "identifier", required: true,
+ summary: "Names this ${tag} and prefixes every binding it publishes." },
+ ],
+ example: \`<${surface}:${tag} id="example"/>\`,
+ notes: [
+ "The element is empty; it accepts no children and no text.",
+ "This Surface publishes nothing yet: its Module declares no Type for it to carry.",
+ ],
+ },
+}] as const satisfies readonly MarkupSurfaceDeclaration[];
+
+export const ${symbol}Manifest: ModuleManifest = {
+ format: "hypit.module@1",
+ name: ${symbol}ModuleRef.name,
+ version: ${symbol}ModuleRef.version,
+ // One entry per Module whose Types this one references.
+ dependencies: [],
+ types: [],
+ capabilities: [],
+ producers: [],
+};
+
+export const ${symbol}Dependency = { module: ${symbol}ModuleRef } as const;
+`;
+}
+
+function types(names: ScaffoldNames): string {
+ const { tag } = names;
+ return `/**
+ * The TypeScript shapes the Manifest's nominal Types carry. Every value that crosses a
+ * boundary belongs here, and gets an \`assert…\` and a \`seal…\` beside the code that builds it.
+ */
+
+/** Identity every ${tag} value is prefixed by. */
+export type ${tag}Header = {
+ readonly id: string;
+};
+`;
+}
+
+function surface(names: ScaffoldNames): string {
+ const { tag, symbol } = names;
+ return `import type { StructuredElement, StructuredSurfaceHandler } from "@hypit/markup";
+
+import type { ${tag}Header } from "./types.js";
+
+/** Exactly the attributes the vocabulary declares; add each new one here and there together. */
+const ATTRIBUTES: readonly string[] = ["id"];
+
+function requiredText(element: StructuredElement, name: string): string {
+ const value = element.attributes[name];
+ if (typeof value !== "string" || value.trim().length === 0) {
+ throw new Error(\`\${element.name}.\${name} must be text.\`);
+ }
+ return value.trim();
+}
+
+/** Reads what the vocabulary promises, and refuses anything else in the author's terms. */
+export function read${tag}Header(element: StructuredElement): ${tag}Header {
+ const unknown = Object.keys(element.attributes).find((name) => !ATTRIBUTES.includes(name));
+ if (unknown !== undefined) throw new Error(\`\${element.name} does not accept \${unknown}.\`);
+ if (element.children.length > 0) throw new Error(\`\${element.name} accepts no children.\`);
+ return { id: requiredText(element, "id") };
+}
+
+/**
+ * Decodes one <${tag}> element.
+ *
+ * It validates the element today and publishes nothing, because the Module declares no
+ * Type yet. To publish: add the Type to \`${symbol}Types\`, list it in the Manifest and in
+ * this Surface's \`outputs\`, then push a SurfaceRecordDraft here —
+ *
+ * records.push({
+ * id: header.id,
+ * type: ${symbol}Types.program,
+ * value: { kind: "inline", value: seal${tag}Program(header) },
+ * range: element.range,
+ * });
+ *
+ * Operations the element needs run as Producers, wired by a GraphFragment in \`fragments\`.
+ */
+export const decode${tag}Surface: StructuredSurfaceHandler = ({ element }) => {
+ read${tag}Header(element);
+ return { records: [], components: [], fragments: [] };
+};
+`;
+}
+
+function component(names: ScaffoldNames): string {
+ const { symbol } = names;
+ return `import type { ComponentPackage } from "@hypit/component-kit";
+
+/**
+ * The deterministic handlers this package's Manifest declared, plus the Validators that
+ * guard its nominal Types. Both lists stay in step with the Manifest: a Producer declared
+ * there and missing here fails at load, not at Build.
+ */
+export const ${symbol}Component = {
+ producers: [],
+ validators: [],
+} satisfies ComponentPackage;
+`;
+}
+
+function activation(names: ScaffoldNames): string {
+ const { tag, symbol } = names;
+ return `import { createMarkupSurfaceHostFacet } from "@hypit/markup";
+
+import {
+ decode${tag}Surface,
+ ${symbol}Component,
+ ${symbol}Manifest,
+ ${symbol}MarkupSurfaces,
+ ${symbol}ModuleRef,
+} from "./index.js";
+
+/** Everything a Host installs from this package, and nothing a Host has to know by name. */
+export const hypitPackage = {
+ format: "hypit.node-package@1" as const,
+ modules: [{ manifest: ${symbol}Manifest }],
+ components: [${symbol}Component],
+ hostFacets: [
+ createMarkupSurfaceHostFacet({
+ module: ${symbol}ModuleRef,
+ declaration: ${symbol}MarkupSurfaces[0],
+ handler: decode${tag}Surface,
+ }),
+ ],
+};
+
+export default hypitPackage;
+`;
+}
+
+function index(names: ScaffoldNames): string {
+ const { tag, symbol } = names;
+ return `export { ${symbol}Component } from "./component.js";
+export {
+ ${symbol}Dependency,
+ ${symbol}Manifest,
+ ${symbol}MarkupSurfaces,
+ ${symbol}ModuleRef,
+ ${symbol}Producers,
+ ${symbol}Types,
+} from "./manifest.js";
+export { decode${tag}Surface, read${tag}Header } from "./surface.js";
+export type { ${tag}Header } from "./types.js";
+`;
+}
+
+function renderStill(names: ScaffoldNames): string {
+ const { tag, slug } = names;
+ return `/**
+ * Renders one frame of this package through the local HyperFrames Runtime and writes it to
+ * preview/${tag}.png — the picture this package's Surface declaration points at.
+ *
+ * node --import tsx test/render-still.ts [frame]
+ *
+ * No Provider, no Build and no Runtime Profile take part: the preview is authoring input
+ * that ships inside the package, so it is never anybody's Output.
+ */
+import { spawnSync } from "node:child_process";
+import { copyFile, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import os from "node:os";
+import path from "node:path";
+
+import { sealComposition, sealVisualTrack } from "@hypit/composition";
+import type { VisualTrack } from "@hypit/composition";
+import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";
+import { sealProgramSpace } from "@hypit/program-space";
+import type { ProgramSpace } from "@hypit/program-space";
+
+const CANVAS = { width: 1080, height: 1920, clearColor: "#101014" } as const;
+const FPS = 10;
+const TOTAL_FRAMES = 10;
+
+/** The repository that owns the local HyperFrames Provider, whatever depth this package sits at. */
+async function repositoryRoot(): Promise<string> {
+ let directory = import.meta.dirname;
+ while (true) {
+ const marker = path.join(directory, "packages/provider-hyperframes-local/package.json");
+ if (await stat(marker).then((entry) => entry.isFile(), () => false)) return directory;
+ const parent = path.dirname(directory);
+ if (parent === directory) throw new Error("run this inside the repository that owns @hypit/provider-hyperframes-local");
+ directory = parent;
+ }
+}
+
+/**
+ * Replace this with your renderer.
+ *
+ * Build the Program your Surface publishes and lower it to one VisualTrack, exactly as the
+ * Producer will. Until then it draws one placeholder card, so the render path can be run
+ * and looked at from the first minute.
+ */
+function render(space: ProgramSpace): VisualTrack {
+ void space;
+ return sealVisualTrack({
+ visualIr: "hypit.visual-ir@1",
+ id: "${slug}-preview",
+ presents: [{
+ id: "placeholder",
+ span: { startFrame: 0, endFrameExclusive: TOTAL_FRAMES },
+ stacking: { order: 0, tieBreak: "${slug}-preview" },
+ elements: [{
+ id: "card",
+ order: 0,
+ kind: "box",
+ style: [
+ { name: "background-color", value: "#f5f2e8" },
+ { name: "border-radius", value: "48px" },
+ { name: "height", value: "640px" },
+ { name: "left", value: "120px" },
+ { name: "position", value: "absolute" },
+ { name: "top", value: "640px" },
+ { name: "width", value: "840px" },
+ ],
+ }],
+ }],
+ });
+}
+
+async function main(): Promise<void> {
+ const wanted = Number(process.argv[2] ?? "0");
+ if (!Number.isSafeInteger(wanted) || wanted < 0) throw new Error("frame must be a whole number");
+ const space = sealProgramSpace({
+ durationSec: TOTAL_FRAMES / FPS,
+ frameRate: { numerator: FPS, denominator: 1 },
+ });
+ const document = compileHyperframesDocument(sealComposition({
+ id: "${slug}-preview",
+ canvas: CANVAS,
+ tracks: [render(space)],
+ }), space);
+ const hyperframesCli = createRequire(path.join(await repositoryRoot(), "packages/provider-hyperframes-local/package.json"))
+ .resolve("hyperframes/bin/hyperframes.mjs");
+ const temporary = await mkdtemp(path.join(os.tmpdir(), "${slug}-still-"));
+ try {
+ if (document.artifacts.length > 0) {
+ // Write each Artifact's bytes into \`temporary\` and return its file name below.
+ throw new Error(\`this still does not carry Artifacts yet; \${document.artifacts.length} were required\`);
+ }
+ await writeFile(path.join(temporary, "index.html"), materializeHyperframesHtml(document, (artifact) => {
+ throw new Error(\`unmapped Artifact \${artifact.digest}\`);
+ }));
+ const frames = path.join(temporary, "frames");
+ await mkdir(frames);
+ const rendered = spawnSync(process.execPath, [
+ hyperframesCli, "render", temporary,
+ "--format", "png-sequence", "--output", frames,
+ "--fps", String(FPS), "--workers", "1",
+ "--no-browser-gpu", "--no-best-effort", "--quiet",
+ ], { encoding: "utf8", timeout: 600_000 });
+ if (rendered.status !== 0) throw new Error(\`\${rendered.stdout}\\n\${rendered.stderr}\`);
+ const produced = (await readdir(frames)).filter((name) => name.endsWith(".png")).sort();
+ const chosen = produced[wanted];
+ if (chosen === undefined) throw new Error(\`frame \${wanted} is out of range; \${produced.length} rendered\`);
+ const output = path.join(import.meta.dirname, "../preview/${tag}.png");
+ await mkdir(path.dirname(output), { recursive: true });
+ await copyFile(path.join(frames, chosen), output);
+ process.stdout.write(\`\${output} (\${produced.length} frames rendered)\\n\`);
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
+
+await main();
+`;
+}
+
+function readme(name: string, names: ScaffoldNames, visual: boolean): string {
+ const { tag, surface: surfaceName, symbol, slug } = names;
+ const visualSection = visual
+ ? `
+## The preview picture
+
+\`src/manifest.ts\` declares \`preview/${tag}.png\`. Write it with the still-render entry, which
+renders one frame through the local HyperFrames Runtime and needs no Provider:
+
+\`\`\`
+node --import tsx test/render-still.ts
+\`\`\`
+
+It draws a placeholder card until \`render\` in \`test/render-still.ts\` calls your renderer.
+
+Other pictures a component draws itself with — paper, a board, a panel — go in \`assets/\` and
+are read with \`readFile(new URL("../assets/…", import.meta.url))\`. Generate one with
+\`hypit image --prompt … --to assets/….png\` and commit the result: neither the preview nor an
+asset is an input the installing project supplies, and neither is produced by a Build.
+`
+ : "";
+ return `# ${name}
+
+One component package: a Markup element authors write, and the deterministic code behind it.
+
+## What is here
+
+| File | Role |
+|---|---|
+| \`src/manifest.ts\` | Module identity, nominal Types, Producers and the Surface declaration with its vocabulary |
+| \`src/types.ts\` | The TypeScript shapes those nominal Types carry |
+| \`src/surface.ts\` | \`<${surfaceName}:${tag}>\` into typed Records and graph inputs |
+| \`src/component.ts\` | The Producer handlers the Manifest declared, and the Type Validators |
+| \`src/activation.ts\` | The Host facets a Host installs |
+| \`src/index.ts\` | The package's public surface |
+${visual ? `| \`test/render-still.ts\` | One frame rendered locally into \`preview/${tag}.png\` |\n` : ""}| \`assets/\` | Pictures this component draws itself with |
+| \`preview/\` | The picture the Surface declaration points at |
+
+\`docs/guide/component-anatomy.md\` describes every role, including the ones this package does
+not have a file for yet: the value layer (\`assert…\`, \`seal…\`), the Style decoder, the renderer
+and the Fragment.
+
+## What is still yours to write
+
+1. **The Types.** Add each nominal Type to \`${symbol}Types\` in \`src/manifest.ts\`, declare the
+ same name under \`types\`, and give it a shape in \`src/types.ts\`. Write these first and stop
+ changing them: everything else agrees with them.
+2. **The value layer.** One \`assert…\` stating what is wrong in the author's terms and one
+ \`seal…\` canonicalising it, for every value that crosses a boundary.
+3. **The Producers.** Declare inputs and outputs under \`producers\` in the Manifest, then
+ implement each one in \`src/component.ts\`.
+4. **The Surface's real output.** \`decode${tag}Surface\` validates and publishes nothing today.
+ Add the Records it pushes and the GraphFragment that wires the Producers.
+5. **The vocabulary.** \`summary\`${visual ? ", `appearance`" : ""}, every attribute and every note in \`src/manifest.ts\` are what a
+ reader chooses this element by. The scaffolded text is placeholder; replace it.
+${visualSection}
+## Installing it
+
+The package is a workspace member. From the repository root:
+
+\`\`\`
+pnpm install
+pnpm check
+\`\`\`
+
+Then a Source reaches it by Module name, and \`as\` chooses the prefix its element is written under:
+
+\`\`\`
+<?svml using="@hypit/markup@1"?>
+
+<svml>
+ <import as="${surfaceName}" from="${name}@1"/>
+
+ <${surfaceName}:${tag} id="${slug}-one"/>
+</svml>
+\`\`\`
+
+\`hypit check\` on that Source is the shortest proof the package loads.
+`;
+}
+
+/**
+ * Writes one component package and returns what it wrote.
+ *
+ * The directory must not already hold files: a scaffold that merges into existing work has
+ * no way to tell an intentional edit from something it is about to lose.
+ */
+export async function scaffoldComponentPackage(request: ScaffoldRequest): Promise<ScaffoldedPackage> {
+ const names = scaffoldNames(request.name);
+ const visual = request.visual ?? true;
+ const root = resolve(request.cwd, request.to ?? join("packages", names.slug));
+ const existing = await readdir(root).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return [];
+ throw error;
+ });
+ if (existing.length > 0) {
+ throw new Error(`${root} is not empty; scaffold into a new directory`);
+ }
+ const files: (readonly [string, string])[] = [
+ ["package.json", packageJson(request.name, visual)],
+ ["README.md", readme(request.name, names, visual)],
+ ["src/manifest.ts", manifest(request.name, names, visual)],
+ ["src/types.ts", types(names)],
+ ["src/surface.ts", surface(names)],
+ ["src/component.ts", component(names)],
+ ["src/activation.ts", activation(names)],
+ ["src/index.ts", index(names)],
+ ...(visual ? [["test/render-still.ts", renderStill(names)] as const] : []),
+ ];
+ for (const [file, contents] of files) {
+ const target = join(root, file);
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(target, contents);
+ }
+ // Both directories are part of the package's shape even before anything is put in them.
+ for (const directory of ["assets", "preview"]) {
+ await mkdir(join(root, directory), { recursive: true });
+ }
+ return {
+ name: request.name,
+ root,
+ tag: names.tag,
+ surface: names.surface,
+ visual,
+ files: [...files.map(([file]) => file), "assets/", "preview/"],
+ };
+}
diff --git a/packages/cli/test/new-package.test.ts b/packages/cli/test/new-package.test.ts
new file mode 100644
index 00000000..baa13447
--- /dev/null
+++ b/packages/cli/test/new-package.test.ts
@@ -0,0 +1,172 @@
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import type { CliDistribution } from "../src/distribution.js";
+import { runCli } from "../src/main.js";
+import { scaffoldNames } from "../src/scaffold.js";
+
+/** new-package writes files and nothing else, so no Distribution capability is reachable. */
+const distribution = {
+ openRuntimeHost: () => { throw new Error("new-package must open no Runtime"); },
+ generatePicture: () => { throw new Error("new-package must call no Provider"); },
+} as unknown as CliDistribution;
+
+async function scaffold(argv: readonly string[]): Promise<{ readonly output: string; readonly root: string }> {
+ const temporary = await mkdtemp(path.join(os.tmpdir(), "hypit-new-package-"));
+ let output = "";
+ await runCli(argv.map((item) => (item === "<to>" ? temporary : item)),
+ { write: (text) => { output += text; } }, distribution);
+ return { output, root: temporary };
+}
+
+type Machine = {
+ readonly format: string;
+ readonly name: string;
+ readonly path: string;
+ readonly tag: string;
+ readonly surface: string;
+ readonly visual: boolean;
+ readonly files: readonly string[];
+};
+
+test("a scaffolded package carries every role a component package fills", async () => {
+ const { output, root } = await scaffold([
+ "new-package", "@hypit/local-notepad-list", "--to", "<to>", "--json",
+ ]);
+ try {
+ const machine = JSON.parse(output) as Machine;
+ assert.equal(machine.format, "hypit.cli-new-package@1");
+ assert.equal(machine.name, "@hypit/local-notepad-list");
+ assert.equal(machine.path, root);
+ assert.equal(machine.tag, "NotepadList");
+ assert.equal(machine.surface, "notepad-list");
+ assert.equal(machine.visual, true);
+ assert.deepEqual(machine.files, [
+ "package.json", "README.md",
+ "src/manifest.ts", "src/types.ts", "src/surface.ts", "src/component.ts",
+ "src/activation.ts", "src/index.ts",
+ "test/render-still.ts",
+ "assets/", "preview/",
+ ]);
+
+ const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")) as {
+ readonly name: string;
+ readonly version: string;
+ readonly private: boolean;
+ readonly type: string;
+ readonly exports: Readonly<Record<string, string>>;
+ readonly hypit: Readonly<Record<string, string>>;
+ readonly dependencies: Readonly<Record<string, string>>;
+ };
+ assert.equal(manifest.name, "@hypit/local-notepad-list");
+ assert.equal(manifest.version, "0.0.0-dev");
+ assert.equal(manifest.private, true);
+ assert.equal(manifest.type, "module");
+ assert.equal(manifest.exports["."], "./src/index.ts");
+ assert.equal(manifest.hypit["activation"], "./src/activation.ts");
+ assert.equal(manifest.dependencies["@hypit/markup"], "workspace:*");
+
+ const module = await readFile(path.join(root, "src/manifest.ts"), "utf8");
+ assert.match(module, /name: "@hypit\/local-notepad-list", version: "1"/u);
+ assert.match(module, /types: \[\],/u);
+ assert.match(module, /producers: \[\],/u);
+ // The vocabulary is what a reader chooses the element by, so every part of it is written.
+ for (const part of ["summary:", "appearance:", "preview: previewImage(\"NotepadList.png\")", "attributes:", "example:", "notes:"]) {
+ assert.ok(module.includes(part), `manifest is missing ${part}`);
+ }
+ assert.match(module, /\{ name: "id", kind: "identifier", required: true,/u);
+
+ // Both directories exist even before anything is put in them.
+ assert.deepEqual(await readdir(path.join(root, "assets")), []);
+ assert.deepEqual(await readdir(path.join(root, "preview")), []);
+
+ const still = await readFile(path.join(root, "test/render-still.ts"), "utf8");
+ assert.match(still, /preview\/NotepadList\.png/u);
+ assert.match(still, /hyperframes\/bin\/hyperframes\.mjs/u);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("--no-visual drops the still render and the preview the Surface would declare", async () => {
+ const { output, root } = await scaffold([
+ "new-package", "@hypit/local-quiet-thing", "--to", "<to>", "--no-visual", "--json",
+ ]);
+ try {
+ const machine = JSON.parse(output) as Machine;
+ assert.equal(machine.visual, false);
+ assert.ok(!machine.files.includes("test/render-still.ts"));
+ const module = await readFile(path.join(root, "src/manifest.ts"), "utf8");
+ assert.ok(!module.includes("previewImage"));
+ assert.ok(!module.includes("appearance:"));
+ const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")) as {
+ readonly devDependencies?: unknown;
+ };
+ assert.equal(manifest.devDependencies, undefined);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the element tag drops the local- prefix, which says where a package lives", () => {
+ assert.deepEqual(scaffoldNames("@hypit/local-notepad-list"),
+ { slug: "local-notepad-list", tag: "NotepadList", surface: "notepad-list", symbol: "notepadList" });
+ assert.deepEqual(scaffoldNames("@hypit/ranking"),
+ { slug: "ranking", tag: "Ranking", surface: "ranking", symbol: "ranking" });
+ assert.deepEqual(scaffoldNames("comment-sticker"),
+ { slug: "comment-sticker", tag: "CommentSticker", surface: "comment-sticker", symbol: "commentSticker" });
+});
+
+test("a name that is not a package name is refused before anything is written", async () => {
+ await assert.rejects(
+ async () => await scaffold(["new-package", "@hypit/Notepad List", "--to", "<to>"]),
+ /is not a package name/u,
+ );
+});
+
+test("new-package refuses to write into a directory that already holds files", async () => {
+ const temporary = await mkdtemp(path.join(os.tmpdir(), "hypit-new-package-"));
+ try {
+ await writeFile(path.join(temporary, "package.json"), "{}\n");
+ await assert.rejects(
+ async () => await runCli(
+ ["new-package", "@hypit/local-notepad-list", "--to", temporary],
+ { write: () => {} }, distribution,
+ ),
+ /is not empty/u,
+ );
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+});
+
+test("new-package takes its name positionally and refuses options that do not apply", async () => {
+ await assert.rejects(
+ async () => await runCli(["new-package"], { write: () => {} }, distribution),
+ /hypit new-package <package-name>/u,
+ );
+ await assert.rejects(
+ async () => await runCli(
+ ["new-package", "@hypit/local-notepad-list", "--runtime", "/tmp/profile.json"],
+ { write: () => {} }, distribution,
+ ),
+ /--runtime does not apply to new-package/u,
+ );
+ await assert.rejects(
+ async () => await runCli(["build", "run.svrun", "--no-visual"], { write: () => {} }, distribution),
+ /--no-visual does not apply to build/u,
+ );
+});
+
+test("help lists new-package and describes it under its own topic", async () => {
+ let listing = "";
+ await runCli(["--help"], { write: (text) => { listing += text; } }, distribution);
+ assert.match(listing, /new-package <package-name>/u);
+ let topic = "";
+ await runCli(["help", "new-package"], { write: (text) => { topic += text; } }, distribution);
+ assert.match(topic, /--no-visual/u);
+ assert.match(topic, /packages\/<name-after-the-scope>/u);
+});
diff --git a/packages/cli/test/reachability.test.ts b/packages/cli/test/reachability.test.ts
new file mode 100644
index 00000000..eaad5c63
--- /dev/null
+++ b/packages/cli/test/reachability.test.ts
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { BuildState, CompiledGraph } from "@hypit/protocol";
+
+import { unreachedGenerations } from "../src/reachability.js";
+
+const producer = { module: { name: "@hypit/nano-banana", version: "1" }, name: "request-nano-banana-2" };
+
+const graph = {
+ format: "hypit.graph@1",
+ outputs: [],
+ candidates: [],
+ operations: [
+ {
+ id: "operation:used", producer, inputs: {},
+ result: { kind: "need", name: "used.image", id: "need:used", record: "record:used" },
+ },
+ {
+ id: "operation:orphan", producer, inputs: {},
+ result: { kind: "need", name: "orphan.image", id: "need:orphan", record: "record:orphan" },
+ },
+ {
+ id: "operation:reused", producer, inputs: {},
+ result: { kind: "need", name: "reused.image", id: "need:reused", record: "record:reused" },
+ },
+ {
+ id: "operation:computed", producer, inputs: {},
+ result: { kind: "output", name: "board.program", record: "record:computed" },
+ },
+ ],
+} as unknown as CompiledGraph;
+
+const state = {
+ plan: {
+ format: "hypit.plan@1",
+ steps: [{ id: "step:used", producer, inputs: {}, outputs: { image: "record:used" }, needs: {} }],
+ goals: [],
+ selections: [{ output: "output:reused", candidate: "candidate:reused", record: "record:reused" }],
+ },
+} as unknown as BuildState;
+
+test("a generation this Run will not perform is named, and reuse is not mistaken for one", () => {
+ const found = unreachedGenerations(graph, state, { "operation:orphan": "paper.image" });
+ assert.deepEqual(found.map((item) => item.name), ["paper.image"],
+ "the planned generation is performed, and the satisfied one is deliberately reused");
+ assert.equal(found[0]!.producer, "@hypit/nano-banana@1/request-nano-banana-2");
+});
+
+test("a computed value nothing builds is not reported, because leaving one costs nothing", () => {
+ const onlyComputed = {
+ ...graph,
+ operations: (graph as unknown as { operations: readonly unknown[] }).operations.slice(3),
+ } as unknown as CompiledGraph;
+ assert.deepEqual(unreachedGenerations(onlyComputed, state), [],
+ "components publish Programs beside the Tracks that carry them; only an external request wastes anything");
+});
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index b935844d..3dbeebb5 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,3 +1,7 @@
packages:
- packages/*
- services/media-lambda
+ # A project-local author package lives at <project>/packages/local-<slug>, which for a project
+ # kept in this checkout means examples/<project>/packages/. Without this the convention the
+ # authoring guide documents produces a package pnpm never links.
+ - examples/*/packages/*
diff --git a/tsconfig.json b/tsconfig.json
index fc9fa4e8..c95290a0 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -19,6 +19,8 @@
},
"include": [
"packages/**/*.ts",
+ "examples/*/packages/*/src/**/*.ts",
+ "examples/*/packages/*/test/**/*.ts",
"services/media-lambda/src/**/*.ts"
],
"exclude": [