refactor(skills): move product-launch / pr-to-video / faceless-explainer onto the script-driven architecture (#1635)

* refactor(product-launch-video): restructure onto script-driven architecture

Move product-launch-video onto the shared script-driven authoring flow:
build-frame remixes a hyperframes-creative preset onto brand tokens, audio
routes through the shared hyperframes-media engine, per-preset caption skins,
and every frame is authored as a directed shot. Removes the old bespoke
scripts (captions/validate/prep/hoist/…) in favour of the shared lib.

assemble-index.mjs keeps upstream #1629's blank/partial scene-file guard
(reject an empty or markup-less scene file at assembly, before emitting
data-composition-src, and re-dispatch) carried onto the restructured reader.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(pr-to-video): restructure onto script-driven architecture

Move pr-to-video onto the shared script-driven authoring flow: ingest.mjs
folds the gh PR artifacts into the synthetic capture package the shared
backend (build-frame / captions / assemble-index) reads, add the mechanism
beat, route audio through hyperframes-media, and remix a hyperframes-creative
preset onto brand tokens via the shared lib.

- Fix skill name: pr-to-video-refactor -> pr-to-video (match directory).
- Drop a stale faceless-explainer-refactor reference in an ingest.mjs comment.
- assemble-index.mjs keeps upstream #1629's blank/partial scene-file guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(faceless-explainer): restructure onto script-driven architecture

Move faceless-explainer onto the shared script-driven authoring flow:
every visual is invented (typography / abstract graphics / diagram / data-viz)
and authored through the shared backend (build-frame remixes a
hyperframes-creative preset onto tokens, audio via hyperframes-media,
assemble-index builds the standalone index.html) using the shared lib.

- Fix skill name: faceless-explainer-refactor -> faceless-explainer (match directory).
- assemble-index.mjs keeps upstream #1629's blank/partial scene-file guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(skills): refresh test-skills-fresh.sh workflow roster

Update the install-and-verify harness to the current surface: 10 workflows
(adds website-to-video, embedded-captions, graphic-overlays, slideshow;
drops the removed footage-recut) and refreshed example prompts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style(product-launch-video): oxfmt storyboard.mjs

Run oxfmt over lib/storyboard.mjs — formatting only, no logic change.
Fixes the Format / Preflight CI check.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(studio): import commitGsapPositionFromDrag from its actual module

The function was split out into gsapDragPositionCommit.ts in #1605, but the
test kept importing it from ./gsapDragCommit, which no longer exports it —
yielding 'is not a function' at runtime. Import from the correct module.

Inherited main breakage (same fix as #1631); fixes the Test CI check on this
branch independently of merge order.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(hyperframes): refine router skill metadata tags

Update the entry router's metadata tags (video / animation / router focus);
oxfmt collapses the now-shorter metadata to a single line.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): tighten caption comment-strip + document audio --only merge

Review follow-ups (#1635):

- captions.mjs (x3): the HTML-comment strip used a single global replace, which
  CodeQL flags as incomplete multi-character sanitization (a nested/partial pair
  can re-form a marker the single pass misses). Strip in a fixpoint loop instead.
  Input is preset-library content, not user-controlled, so this is lint-
  cleanliness, not XSS defense.
- audio.mjs (x3): document that fetch-sfx (--only sfx) MERGES into the neutral
  audio_engine_meta.json sidecar — the engine reads prev and recomputes only the
  sfx section, so voices/bgm from the generate pass are preserved (review Q).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): remove existsSync->write TOCTOU in workflow scripts

Clears the 9 js/file-system-race CodeQL alerts (captions/audio/transitions x3).
Each was an existsSync precheck followed by a later write of the same path:

- captions.mjs: caption-overrides shim -> atomic writeFileSync({ flag: 'wx' }).
- audio.mjs (sync-durations) + transitions.mjs (inject): drop the existsSync
  precheck and read directly, surfacing the same friendly error from a try/catch
  on readFileSync — no check->write gap.

Behavior is unchanged (same error messages); these are local single-process
deterministic scripts so the race was never a real risk, but this clears the gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): paint root composition ground color in assemble-index

Per-frame roots carry data-start/data-duration and get clip-gated against the
global timeline at render, so only the first frame's window overlaps global 0 —
a frame's own full-bleed background can't serve as the video ground, and every
frame after the first renders on the bare body color (black). Paint the ground
on the always-present root composition using the project's frame.md canvas color
(the same role the caption skin maps to --cap-canvas); fall back to the body
letterbox color when frame.md is absent or has no resolvable ground.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(hyperframes): drop router-tag edit (moved to the foundation PR)

The entry SKILL.md is rewritten wholesale by the frame-presets/media foundation
PR (#1632); editing it here too guaranteed a merge conflict. Restore this file
to main and let the router-tag tweak live with the rewrite in #1632, so the two
PRs no longer both touch it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
WaterrrForever
2026-06-22 22:49:42 +08:00
committed by GitHub
co-authored by Claude Opus 4.8
parent d0f0ec29e7
commit 1967901b57
630 changed files with 8846 additions and 87665 deletions
@@ -0,0 +1,55 @@
// assets.mjs — stage frame-named capture assets into assets/.
// Shared by stage-assets.mjs (Step 4 close, BEFORE the frame workers run) and
// assemble-index.mjs (Step 5, idempotent backstop). Only assets a frame names
// in `asset_candidates` are staged; unnamed assets never reach the project.
// asset_candidates value form: "assets/<basename> — desc; assets/… — …".
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { basename, join } from "node:path";
export function basenamesFromCandidates(value) {
if (typeof value !== "string") return [];
return value
.split(";")
.map((seg) => seg.split(/\s+[—–-]\s+/)[0].trim()) // strip the " — description"
.filter(Boolean)
.map((p) => basename(p.replace(/^assets\//, "")));
}
// Copy each frame's asset_candidates from capture/{assets,assets/videos,
// screenshots} into assets/. Already-staged files are left as is (first-wins),
// so calling this twice is safe. Returns { staged, wanted, anomalies }.
export function stageAssets({ hyperframesDir, frames }) {
const wanted = new Set();
for (const f of frames) {
for (const b of basenamesFromCandidates(f.extra?.asset_candidates)) wanted.add(b);
}
const captureDirs = [
join(hyperframesDir, "capture/assets"),
join(hyperframesDir, "capture/assets/videos"), // videos download into a subdir
join(hyperframesDir, "capture/screenshots"),
];
const assetsDir = join(hyperframesDir, "assets");
const anomalies = [];
let staged = 0;
if (wanted.size > 0) {
mkdirSync(assetsDir, { recursive: true });
for (const b of wanted) {
const dest = join(assetsDir, b);
if (existsSync(dest)) {
staged++;
continue;
} // first-wins / already staged
const src = captureDirs.map((d) => join(d, b)).find((p) => existsSync(p));
if (src) {
copyFileSync(src, dest);
staged++;
} else {
anomalies.push(
`asset "${b}" named by a frame but not found under capture/ — frame will 404 it`,
);
}
}
}
return { staged, wanted, anomalies };
}
@@ -1,39 +0,0 @@
// capture-meta.mjs — shared capture-ingest helpers.
//
// Both derive-context-pack.mjs (Phase 1 post-processor) and build-design.mjs
// (Phase 1b) read the same `hyperframes capture` output. This module holds the
// parsing they would otherwise each re-implement, so the algorithms stay in
// lockstep (previously the source-URL discovery was duplicated byte-for-byte in
// both files and could drift).
import fs from "node:fs";
import path from "node:path";
/**
* Discover the captured page's source URL.
*
* `hyperframes capture` writes the URL into its agent-scaffolding files
* (CLAUDE.md / AGENTS.md / .cursorrules); we grep those for the first URL.
* Fallback: reconstruct from meta.id (a host slug like "heygen.com-video").
*
* @param {string} captureDir capture output dir (contains the scaffold files + meta.json)
* @param {{id?: string}|null} meta parsed capture/meta.json (for the fallback)
* @returns {string} the source URL, or "" if none could be discovered
*/
export function discoverSourceUrl(captureDir, meta) {
for (const f of ["CLAUDE.md", "AGENTS.md", ".cursorrules"]) {
let txt = "";
try {
txt = fs.readFileSync(path.join(captureDir, f), "utf8");
} catch {
// scaffold file absent — try the next one
}
const m = txt.match(/https?:\/\/[\w.-]+(?:\/[^\s)"'`]*)?/);
if (m) return m[0];
}
if (meta?.id) {
const host = String(meta.id).replace(/-[a-z]+$/, "");
return `https://${host}/`;
}
return "";
}
@@ -1,30 +1,10 @@
// dimensions.mjs — single source of truth for the video canvas size.
//
// ============================================================================
// THE A/B ↔ C SEAM (read this before wiring orientation in upstream)
// ============================================================================
// The whole faceless-explainer pipeline used to be hard-locked to landscape
// 1920×1080. It is now dimension-parametric: every deterministic script
// (assemble-index, transitions, captions, hoist-videos) and every
// scene worker reads the canvas size from ONE place — `group_spec.json`
// `width`/`height` — which prep.mjs stamps in.
//
// prep.mjs resolves the size with this precedence (see resolveDimensions):
// 1. explicit `--width N --height N` flags on prep (testing / override)
// 2. `narrator_scripts.json` → `dimensions: { width, height }` (explicit px)
// 3. `narrator_scripts.json` → `orientation: "landscape|portrait|square"`
// 4. default → landscape 1920×1080 (back-compat)
//
// >>> For whoever wires the intent→orientation entry (Step 0 / scriptwriting):
// do NOT thread pixels through every script. Just write ONE field into
// `narrator_scripts.json` — `orientation` (friendly) or `dimensions`
// (explicit px) — exactly the way `stylePreset` already lives there. prep
// picks it up and the rest of the pipeline follows automatically. If you
// write nothing, the video stays landscape (no behavior change).
// ============================================================================
// dimensions.mjs — canvas size + caption-band geometry for the product-launch
// pipeline. Single source of truth = the STORYBOARD frontmatter `format` global
// ("1920x1080" / "1080x1920" / "1080x1080", or a named orientation). Every
// script and the index assembler reads the size from here; none hardcodes it.
// Named orientation presets. Square/portrait are 1080-based so they share the
// long-edge pixel budget with landscape (same render cost ballpark).
// long-edge pixel budget with landscape (same render-cost ballpark).
export const ORIENTATION_PRESETS = {
landscape: { width: 1920, height: 1080 }, // 16:9 — default
portrait: { width: 1080, height: 1920 }, // 9:16 — reels / shorts / TikTok
@@ -37,47 +17,25 @@ function sane(w, h) {
return Number.isFinite(w) && Number.isFinite(h) && w >= 240 && h >= 240 && w <= 8192 && h <= 8192;
}
// Resolve canvas dims from (in priority order) explicit flags, an explicit
// `dimensions` object, a named `orientation`, else the landscape default.
// `flags` = { width, height } (strings or numbers, may be undefined).
// `narratorScripts` = the parsed narrator_scripts.json (may be null).
// Returns { width, height, source } — `source` is for logging/anomalies.
export function resolveDimensions(flags = {}, narratorScripts = null) {
const fw = flags.width != null ? parseInt(flags.width, 10) : NaN;
const fh = flags.height != null ? parseInt(flags.height, 10) : NaN;
if (sane(fw, fh)) return { width: fw, height: fh, source: "flags" };
const dim = narratorScripts && narratorScripts.dimensions;
if (dim) {
const w = parseInt(dim.width, 10);
const h = parseInt(dim.height, 10);
if (sane(w, h)) return { width: w, height: h, source: "narrator_scripts.dimensions" };
// Parse a STORYBOARD `format` global into { width, height, source }. Accepts
// "WxH" (e.g. "1920x1080"; `x` or `×`, any inner spacing) or a named orientation;
// falls back to landscape so a storyboard with a missing/garbled format still
// renders (no behavior change vs the old landscape lock).
export function parseFormat(format) {
const s = typeof format === "string" ? format.trim().toLowerCase() : "";
if (ORIENTATION_PRESETS[s]) return { ...ORIENTATION_PRESETS[s], source: `orientation=${s}` };
const m = s.match(/^(\d+)\s*[x×]\s*(\d+)$/);
if (m) {
const w = parseInt(m[1] ?? "", 10);
const h = parseInt(m[2] ?? "", 10);
if (sane(w, h)) return { width: w, height: h, source: "format" };
}
const orient =
narratorScripts && typeof narratorScripts.orientation === "string"
? narratorScripts.orientation.trim().toLowerCase()
: "";
if (orient && ORIENTATION_PRESETS[orient]) {
return { ...ORIENTATION_PRESETS[orient], source: `orientation=${orient}` };
}
return { ...DEFAULT_DIMENSIONS, source: "default(landscape)" };
}
// Read dims back out of a group_spec (downstream consumers). Falls back to the
// landscape default so a group_spec produced before this change still works.
export function readDims(groupSpec) {
const w = parseInt(groupSpec?.width, 10);
const h = parseInt(groupSpec?.height, 10);
if (sane(w, h)) return { width: w, height: h };
return { ...DEFAULT_DIMENSIONS };
}
// Caption band geometry, derived from canvas height. The band is the bottom
// ~16.67% of the canvas (matches the original landscape 180px band at h=1080:
// 1080 round(1080 × 0.1667) = 900). Foreground content must end `safetyPx`
// above the band top.
// Caption band geometry, derived from canvas height: the bottom ~16.67% (180px
// at h=1080). Frame content must end `safetyPx` above the band top. Holds even
// when captions are disabled (bottom-edge consistency).
export const CAPTION_BAND_FRACTION = 0.1667;
export function captionBand(height, safetyPx = 20) {
const h = Number.isFinite(height) ? height : DEFAULT_DIMENSIONS.height;
@@ -1,124 +0,0 @@
// Scene visual-hierarchy gate for validate-section.mjs.
//
// A scene is "risky" when it stacks competing focal claims — a multi-act scene,
// or an action/payoff (CTA) co-existing with proof (logos / stats). Risky scenes
// must declare a **PrimarySubjectTimeline:** and a **Handoff:** so one subject
// owns the frame at a time. This module decides risk; the enforcement (which
// anchors a risky scene must carry) stays in validate-section.mjs.
//
// Two sources, in priority order:
// 1. AUTHORITATIVE — a structured `**Hierarchy:**` anchor the planner declares.
// This is a pure schema read (no prose scanning), so it never costs review
// to reason about regex alternations. Prefer it.
// 2. FALLBACK — the prose classifier below, kept for plans that don't declare
// the anchor yet. Once an E2E replay confirms the planner reliably emits
// `**Hierarchy:**`, this fallback (classifyHierarchy + its regexes) can be
// deleted and the gate becomes a pure schema check.
// Fixed vocabulary for the **Hierarchy:** anchor. `simple` is the explicit
// "no competing focal claims" declaration (risky=false). The others map 1:1 to
// the prose classifier's signals so both sources produce the same shape.
export const HIERARCHY_TAGS = ["simple", "multi-act", "action", "social-proof", "data-proof"];
// Read the authoritative `**Hierarchy:** <tags>` anchor. Returns null when the
// anchor is absent (→ caller falls back to the prose classifier). When present,
// returns the risk shape plus any `unknown` tags (caller turns those into a
// validation error so a typo can't silently disable the gate).
export function declaredHierarchy(body) {
const m = body.match(/^\*\*Hierarchy:\*\*\s*(.*)$/m);
if (!m) return null;
const tags = m[1]
.toLowerCase()
.split(/[,\s]+/)
.filter(Boolean);
const allowed = new Set(HIERARCHY_TAGS);
const unknown = tags.filter((t) => !allowed.has(t));
const multiAct = tags.includes("multi-act");
const hasAction = tags.includes("action");
const hasSocialProof = tags.includes("social-proof");
const hasDataProof = tags.includes("data-proof");
return {
source: "declared",
unknown,
multiAct,
hasAction,
hasSocialProof,
hasDataProof,
risky: multiAct || (hasAction && (hasSocialProof || hasDataProof)),
};
}
const hasAny = (text, patterns) => patterns.some((pattern) => pattern.test(text));
// Strip negated clauses so a scene that only mentions proof to DENY it (e.g. a
// pure CTA: "there is no logo strip / customer logo / stat counter / chart")
// doesn't read as a proof scene. Each negation eats to the next sentence stop.
// This is what lets a CTA stop writing anti-regex defensive prose.
function stripNegations(text) {
return text.replace(
/\b(no|not|never|without|isn'?t|aren'?t|don'?t|doesn'?t|won'?t|cannot|can'?t)\b[^.;:]*/gi,
" ",
);
}
// FALLBACK prose classifier — the historical hierarchyRisk(). Same return shape
// as declaredHierarchy() so callers don't branch on the source.
export function classifyHierarchy(body) {
const text = body.toLowerCase();
// Proof signals are read from (1) cited component ids — an unambiguous,
// structured signal preferred over fuzzy prose scans — and (2) the prose with
// negated clauses removed, using PHRASE patterns (not bare "logo"/"customer",
// which over-trigger on brand wordmarks and incidental mentions).
const proofText = stripNegations(text);
const compM = body.match(/^\*\*Components:\*\*\s*(.*)$/m);
const compIds = compM ? [...compM[1].matchAll(/`([^`]+)`/g)].map((m) => m[1]) : [];
const compProof = compIds.some((id) => /logo|proof|testimonial|customer/i.test(id));
const compData = compIds.some((id) => /stat|chart|metric|kpi|counter/i.test(id));
const multiAct = /\b(multi[- ]?act|three[- ]?act|act\s+[abc]|\bfocal points?)\b/i.test(text);
const hasAction =
/\b(cta|get started|call[- ]?to[- ]?action|button|sign up|book demo|start trial|download|subscribe|contact sales|action headline|payoff frame|payoff close|closing action)\b/i.test(
text,
);
const hasSocialProof =
compProof ||
hasAny(proofText, [
/logo[- ]?(strip|grid|wall|cloud|chain|row|rail|lockup)/i,
/\btrusted by\b/i,
/social[- ]proof/i,
/\btestimonials?\b/i,
/customer logos?/i,
/enterprise logos?/i,
/\bbrands? you (know|trust)\b/i,
]);
const hasDataProof =
compData ||
hasAny(proofText, [
/\bstats?\b/i,
/\bstat[- ]?counter\b/i,
/\bmetrics?\b/i,
/\bkpis?\b/i,
/\bproof cluster\b/i,
/\bproof rail\b/i,
/\bchart\b/i,
/\bcount[- ]?up\b/i,
/\bpolicy compliance\b/i,
/\bhours saved\b/i,
/\byield\b/i,
]);
return {
source: "prose",
unknown: [],
multiAct,
hasAction,
hasSocialProof,
hasDataProof,
risky: multiAct || (hasAction && (hasSocialProof || hasDataProof)),
};
}
// Resolve a scene's hierarchy profile: prefer the declared anchor (schema check),
// else classify the prose (fallback).
export function hierarchyProfile(body) {
return declaredHierarchy(body) || classifyHierarchy(body);
}
@@ -1,101 +0,0 @@
// prep.mjs concern module — capture media + brand fonts → the HyperFrames
// project's public/ tree, plus the @font-face block extraction. Pure file I/O;
// no section_plan / group_spec knowledge. Split out of prep.mjs (Steps 2/2b/2c)
// to keep the orchestrator lean.
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { extname, join } from "node:path";
// `.bin` is the capture-stage fallback name for images with unrecognized MIME
// (typically image/* with a missing or CDN-rewritten Content-Type). Downstream
// Phase 4b workers reference them as <img src>; browsers render by magic bytes
// and almost all display correctly. Include it in the allowlist to avoid orphaning files.
const ASSET_EXTS = new Set([
".png",
".jpg",
".jpeg",
".webp",
".svg",
".bin",
// Video extensions — Phase 3 frequently quotes hero/demo .mp4 from the
// capture. Forgetting these forces Phase 4b workers to substitute poster
// .webp, losing motion fidelity. Keep in sync with the playable formats
// hyperframes-core accepts in <video>/clip sub-comps.
".mp4",
".mov",
".webm",
]);
const FONT_EXTS = new Set([".woff2", ".woff", ".ttf", ".otf"]);
// Step 2: copy capture image/video media → public/. hyperframes capture writes
// assets/ + screenshots/ + extracted/ under captureDir; we want only the media
// (assets/ + screenshots/), not the JSON manifests under extracted/. First-wins
// on basename collisions (the skipped path is reported, never silently lost).
export function copyCaptureAssets(captureDir, publicDir) {
mkdirSync(publicDir, { recursive: true });
const collisions = [];
let copied = 0;
function walk(dir) {
if (!existsSync(dir)) return;
for (const ent of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, ent.name);
if (ent.isDirectory()) walk(p);
else if (ent.isFile() && ASSET_EXTS.has(extname(ent.name).toLowerCase())) {
const target = join(publicDir, ent.name);
if (existsSync(target)) {
collisions.push({ kept: target, skipped: p });
} else {
copyFileSync(p, target);
copied++;
}
}
}
}
walk(join(captureDir, "assets"));
walk(join(captureDir, "screenshots"));
return { copied, collisions };
}
// Step 2b: copy self-hosted brand fonts (Phase 1b's download-fonts.mjs writes
// them into design-system/fonts/) → public/fonts/ so the renderer resolves the
// @font-face url()s that index.html declares.
export function copyBrandFonts(designSystemDir, publicDir) {
const fontsSrcDir = join(designSystemDir, "fonts");
let fontsCopied = 0;
if (existsSync(fontsSrcDir)) {
const fontsDestDir = join(publicDir, "fonts");
mkdirSync(fontsDestDir, { recursive: true });
for (const ent of readdirSync(fontsSrcDir, { withFileTypes: true })) {
if (!ent.isFile()) continue;
if (!FONT_EXTS.has(extname(ent.name).toLowerCase())) continue;
const src = join(fontsSrcDir, ent.name);
const dest = join(fontsDestDir, ent.name);
if (!existsSync(dest)) {
copyFileSync(src, dest);
fontsCopied++;
}
}
}
return fontsCopied;
}
// Step 2c: pull the @font-face block out of design.html (download-fonts.mjs wraps
// its injection with two comment anchors), rewrite url('fonts/<file>') →
// url('public/fonts/<file>') so paths resolve against the project root, and return
// it for group_spec.font_face_css. @font-face is global by spec and cannot be
// class-scoped — Phase 4c declares it once at the document root.
export function extractFontFaceCss(designSystemDir) {
let fontFaceCss = "";
const designHtmlPath = join(designSystemDir, "design.html");
if (existsSync(designHtmlPath)) {
const designHtml = readFileSync(designHtmlPath, "utf8");
const m = designHtml.match(
/\/\*\s*===\s*auto-injected by download-fonts\.mjs\s*===\s*\*\/([\s\S]*?)\/\*\s*===\s*end download-fonts\.mjs block\s*===\s*\*\//,
);
if (m) {
fontFaceCss = m[1].trim().replace(/url\(\s*(['"]?)fonts\//g, "url($1public/fonts/");
}
}
return fontFaceCss;
}
@@ -1,113 +0,0 @@
// prep.mjs concern module — resolve the design-system chunk library (Phase 1b's
// emit-chunks.mjs output) onto each scene, and extract the :root brand-tokens
// block. Split out of prep.mjs (Step 4b). Mutates scenes[].design_chunks in place
// and appends to the shared anomalies array; returns chunksIndex for the summary.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { die } from "./prep-log.mjs";
// Phase 1b's emit-chunks.mjs writes design-system/chunks/{tokens.css, easings.js,
// components/<id>.html, index.json}. Downstream Phase 4b workers read only the
// chunks listed in their dispatch — never design.html — cutting per-worker
// must-read load by ~4× (12 KB design.html → 1-3 KB per chunk file).
//
// Resolution policy:
// - chunks/index.json missing → degrade gracefully: design_chunks = null
// for every scene, log an anomaly, and let
// the worker fall back to reading design.html.
// - index.json present → every scene gets tokens_file + easings_file
// + the FULL component library (worker picks).
export function resolveDesignChunks({ designSystemDir, scenes, anomalies }) {
const chunksDir = join(designSystemDir, "chunks");
const chunksIndexPath = join(chunksDir, "index.json");
let chunksIndex = null;
if (existsSync(chunksIndexPath)) {
try {
chunksIndex = JSON.parse(readFileSync(chunksIndexPath, "utf8"));
} catch (e) {
anomalies.push(
`design-system/chunks/index.json present but unreadable (${e.message}) — workers will fall back to design.html`,
);
}
} else {
anomalies.push(
`design-system/chunks/ missing — Phase 1b's emit-chunks.mjs was not run. Workers will fall back to reading design.html (slower).`,
);
}
let availableComponents = null;
if (chunksIndex) {
availableComponents = new Map(
(chunksIndex.components || []).map((c) => [c.id, join(designSystemDir, c.file)]),
);
}
for (const s of scenes) {
if (!chunksIndex) {
s.design_chunks = null;
continue;
}
const tokensAbs = join(designSystemDir, chunksIndex.tokens_file || "chunks/tokens.css");
const easingsAbs = join(designSystemDir, chunksIndex.easings_file || "chunks/easings.js");
const voiceAbs = join(designSystemDir, chunksIndex.voice_file || "chunks/voice.md");
if (!existsSync(tokensAbs))
die(`design_chunks: tokens_file "${tokensAbs}" referenced by index.json but missing on disk`);
if (!existsSync(easingsAbs))
die(
`design_chunks: easings_file "${easingsAbs}" referenced by index.json but missing on disk`,
);
if (!existsSync(voiceAbs))
die(`design_chunks: voice_file "${voiceAbs}" referenced by index.json but missing on disk`);
// Optional chunks (null when preset declared no §H / §T). Worker reads
// these on demand — paths are passed through dispatch verbatim. We only check
// file existence when index.json references one (consistency guard); the
// worker then opens it lazily without re-checking.
const hintsAbs = chunksIndex.hints_file ? join(designSystemDir, chunksIndex.hints_file) : null;
if (hintsAbs && !existsSync(hintsAbs))
die(`design_chunks: hints_file "${hintsAbs}" referenced by index.json but missing on disk`);
const typeRolesAbs = chunksIndex.type_roles_file
? join(designSystemDir, chunksIndex.type_roles_file)
: null;
if (typeRolesAbs && !existsSync(typeRolesAbs))
die(
`design_chunks: type_roles_file "${typeRolesAbs}" referenced by index.json but missing on disk`,
);
// Components are a style REFERENCE library, not a plan-time citation. Forward
// EVERY available component to every worker; the worker picks which to use by
// visual judgment (see agents/hyperframes-scene.md). Existence is guaranteed by
// emit-chunks; filter defensively so a stale index entry never ships a missing path.
const componentPaths = availableComponents
? [...availableComponents.values()].filter((abs) => existsSync(abs))
: [];
s.design_chunks = {
tokens_file: tokensAbs,
easings_file: easingsAbs,
voice_file: voiceAbs,
hints_file: hintsAbs,
type_roles_file: typeRolesAbs,
components: componentPaths,
};
}
return { chunksIndex };
}
// Extract the :root token block from tokens.css. tokens.css is a single global
// :root {…} block (brand colors, font roles, spacing/radius). Emit it into
// group_spec.brand_tokens_css so assemble-index.mjs can declare it ONCE in
// index.html's <head>; CSS custom properties inherit through the light DOM into
// every mounted sub-composition, so scenes reference var(--*) without re-declaring.
export function extractBrandTokensCss(chunksIndex, designSystemDir) {
let brandTokensCss = "";
if (chunksIndex) {
const tokensAbs = join(designSystemDir, chunksIndex.tokens_file || "chunks/tokens.css");
if (existsSync(tokensAbs)) {
const tokensRaw = readFileSync(tokensAbs, "utf8");
const m = tokensRaw.match(/:root\s*\{[\s\S]*\}/);
brandTokensCss = (m ? m[0] : tokensRaw).trim();
}
}
return brandTokensCss;
}
@@ -1,8 +0,0 @@
// Shared failure helper for prep.mjs and its concern modules (prep-assets,
// prep-design, prep-section, prep-sfx). Keeps the "✗ prep.mjs:" prefix stable
// across the split so error output is identical regardless of which module
// raised it — the whole pipeline is still "prep" from the caller's point of view.
export function die(msg) {
console.error(`✗ prep.mjs: ${msg}`);
process.exit(1);
}
@@ -1,187 +0,0 @@
// prep.mjs concern module — parse section_plan.md (Phase 3) into the film-level
// header + per-scene base records. Pure string→data; no disk access, no timing
// merge (prep.mjs adds rule_paths / design_chunks / the duration ladder after).
// Split out of prep.mjs (Step 3) — the densest single block in the file.
//
// section_plan.md anchors recognised:
// **Effects:** — required, 2-5 backtick-wrapped rule ids
// **Duration:** — required, positive float seconds
// **Blueprint:** — optional (soft), "based-on <id>" | "extended <id>" |
// "composed" | absent (→ "composed").
// **Transition:** — optional, how THIS scene is entered.
// **SFX:** — optional (soft), bullet list of cue lines (scene-local t).
// PrimarySubjectTimeline / Handoff are NOT recognised anchors here, so (per the
// guide) they must appear after SFX to fall into creative_brief.
import { die } from "./prep-log.mjs";
const ANCHORS = ["Effects", "Duration"];
// Components/Surface anchors removed — the design system is a style REFERENCE,
// not a plan-time contract (workers self-pick components from the forwarded
// library; no scene-level surface commitment). Blueprint/Transition stay.
// `Hierarchy` is a validator-only signal (validate-section.mjs reads it for the
// risk gate); recognise it here so it advances lastAnchorEnd and never leaks into
// the worker's creative_brief.
const OPTIONAL_ANCHORS = ["Blueprint", "Transition", "Hierarchy"];
function anchorRe(name) {
return new RegExp(`^\\*\\*${name}:\\*\\*\\s*(.*)$`, "m");
}
function parseSceneBlock(body, sceneId) {
const raw = {};
let lastAnchorEnd = 0;
for (const a of ANCHORS) {
const m = body.match(anchorRe(a));
if (!m) die(`${sceneId}: missing **${a}:** anchor in section_plan.md`);
raw[a] = m[1].trim();
const end = m.index + m[0].length;
if (end > lastAnchorEnd) lastAnchorEnd = end;
}
// Optional anchors — include them in lastAnchorEnd when present to avoid leaking
// into creative_brief; missing optional anchors are fine.
for (const a of OPTIONAL_ANCHORS) {
const m = body.match(anchorRe(a));
if (m) {
raw[a] = m[1].trim();
const end = m.index + m[0].length;
if (end > lastAnchorEnd) lastAnchorEnd = end;
}
}
// Effects: ordered backtick-wrapped ids inside [...]
const effects = [...raw.Effects.matchAll(/`([^`]+)`/g)].map((m) => m[1]);
if (effects.length === 0) die(`${sceneId}: **Effects:** has no backtick-wrapped ids`);
// Duration: leading float
const durM = raw.Duration.match(/[\d.]+/);
if (!durM) die(`${sceneId}: **Duration:** could not parse float from "${raw.Duration}"`);
const estimatedDuration_s = parseFloat(durM[0]);
if (!isFinite(estimatedDuration_s) || estimatedDuration_s <= 0)
die(`${sceneId}: **Duration:** ${estimatedDuration_s} is not a positive float`);
// Blueprint (soft): "based-on <id>" | "extended <id>" | "composed" | (absent → "composed")
// Do not validate shape here: the validator can add that later; id references are
// loosely bound and the build agent handles them.
const blueprint = raw.Blueprint || "composed";
// Transition (OPTIONAL): how THIS scene is entered.
// **Transition:** <type> [DIRECTION] [<dur>s]
// Parsed loosely here (validator already shape-checked); null when absent so
// Step 6.5 can default-fill. Scene 1's transition is the open (no between-
// scene transition precedes it) — parsed but ignored at injection time.
let transition = null;
if (raw.Transition) {
const tokens = raw.Transition.trim().split(/\s+/);
const type = tokens[0].toLowerCase();
let direction = null;
let durationOverride = null;
for (const tok of tokens.slice(1)) {
if (/^[\d.]+s$/i.test(tok)) durationOverride = parseFloat(tok);
else direction = tok.toUpperCase();
}
if (type) transition = { type, direction, duration_s: durationOverride };
}
// SFX (optional / soft anchor; omitted entirely = no SFX for this scene):
// **SFX:**
// - `impact-bass-1.mp3` at 0.2s, volume 0.35 — hero snap
// - `whoosh-short.mp3` at 4.1s — exit
// (or `**SFX:** none`, or no anchor at all). The validator
// (validate-section.mjs) no longer requires the anchor; when present it
// checks each cited file against the manifest. This parser accepts either
// form. "none" / any non-empty trailer skips the bullet scan (no cues).
// sfx_cues[].t is SCENE-LOCAL seconds (this function knows nothing about
// global timing; we add s.start_s offset in Step 6).
const sfxCues = [];
const sfxHeaderRe = /^\*\*SFX:\*\*[ \t]*(.*)$/m;
const sfxHeaderM = body.match(sfxHeaderRe);
if (sfxHeaderM) {
const sfxHeaderEnd = sfxHeaderM.index + sfxHeaderM[0].length;
if (sfxHeaderEnd > lastAnchorEnd) lastAnchorEnd = sfxHeaderEnd;
}
if (sfxHeaderM && sfxHeaderM[1].trim() === "") {
const sfxHeaderEnd = sfxHeaderM.index + sfxHeaderM[0].length;
const afterHeader = body.slice(sfxHeaderEnd);
const lines = afterHeader.split("\n");
let consumed = 0; // chars consumed past the header
for (let li = 0; li < lines.length; li++) {
const line = lines[li];
const trimmed = line.trim();
if (trimmed === "") {
consumed += line.length + 1;
continue;
}
if (!trimmed.startsWith("-")) break; // next anchor / prose / scene heading
// Parse: `<file>.mp3` at <T>s[, volume <V>][, — <note>]
const cueRe =
/^[\s\-*]+`([^`]+\.mp3)`\s+at\s+([\d.]+)\s*s(?:[,\s]+volume\s+([\d.]+))?(?:\s*[—–-]\s*(.*))?$/;
const m = trimmed.match(cueRe);
if (m) {
const file = m[1];
const tLocal = parseFloat(m[2]);
const volume = m[3] != null ? parseFloat(m[3]) : null;
const note = m[4] ? m[4].trim() : "";
if (!isFinite(tLocal) || tLocal < 0) {
die(`${sceneId}: **SFX:** invalid t for "${file}": "${m[2]}"`);
}
sfxCues.push({ file, t_local: tLocal, volume, note });
} else {
die(`${sceneId}: **SFX:** unparseable cue line: "${trimmed}"`);
}
consumed += line.length + 1;
}
const sfxBlockEnd = sfxHeaderEnd + consumed;
if (sfxBlockEnd > lastAnchorEnd) lastAnchorEnd = sfxBlockEnd;
}
// creative_brief = everything after the LAST anchor line, verbatim
const brief = body.slice(lastAnchorEnd).replace(/^\s*\n+/, "");
return {
effects,
estimatedDuration_s,
blueprint,
transition,
sfxCues,
creative_brief: brief,
};
}
// Parse the whole plan: the "## Film Direction" header (film-level invariants the
// orchestrator forwards to every worker) + each "## Scene N:" block. Dies on a
// missing required anchor / unparseable value; tolerant when Film Direction is
// absent (legacy plans). Returns base scene records — prep.mjs layers rule_paths,
// design_chunks and the audio-truth duration ladder on top.
export function parseSectionPlan(planText) {
const sceneHeadRe = /^## Scene\s+(\d+)\s*:\s*(.+?)\s*$/gm;
const heads = [...planText.matchAll(sceneHeadRe)];
if (heads.length === 0) die("no '## Scene N: <name>' headings found in section_plan.md");
// Film Direction: the film-level header (`## Film Direction` ... up to the first
// `## Scene`). Written once by visual-design; the orchestrator prepends it to
// every scene worker's shared packet header and to the finalize dispatch, so
// per-scene creative_brief can stay deltas-only. validate-section.mjs enforces
// presence and size; prep just extracts what is there (tolerant when absent).
let film_direction = "";
{
const fdHead = planText.match(/^## Film Direction[ \t]*$/m);
if (fdHead && fdHead.index < heads[0].index) {
film_direction = planText.slice(fdHead.index + fdHead[0].length, heads[0].index).trim();
}
}
const scenes = [];
for (let i = 0; i < heads.length; i++) {
const m = heads[i];
const sceneNumber = parseInt(m[1], 10);
const sceneName = m[2].trim();
const start = m.index + m[0].length;
const end = i + 1 < heads.length ? heads[i + 1].index : planText.length;
const body = planText.slice(start, end);
const sceneId = `scene_${sceneNumber}`;
const parsed = parseSceneBlock(body, sceneId);
scenes.push({ sceneNumber, sceneId, sceneName, ...parsed });
}
return { film_direction, scenes };
}
@@ -1,91 +0,0 @@
// prep.mjs concern module — resolve the SFX library and scene cues into globally
// timed sfx records. Split out of prep.mjs (Step 6.5). Copies the opt-in library
// into the project, validates each cue against manifest.json, and offsets each
// cue's scene-local t by its scene start_s. Appends to the shared anomalies array
// and returns the sorted sfx[] for group_spec.
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { die } from "./prep-log.mjs";
// SFX library is OPT-IN: when the orchestrator passes --sfx-lib the directory is
// copied into <PROJECT_DIR>/assets/sfx/ and section_plan **SFX:** cues are
// validated against manifest.json. Without --sfx-lib, scene cues are silently
// dropped (warning only). Voice/bgm live under assets/; SFX matches.
export function resolveSfx({ sfxLibDir, hyperframesDir, scenes, groups, anomalies }) {
const sfx = [];
if (sfxLibDir) {
const sfxManifestPath = join(sfxLibDir, "manifest.json");
if (!existsSync(sfxManifestPath)) {
die(`--sfx-lib points to ${sfxLibDir} but manifest.json is missing`);
}
let sfxManifest;
try {
sfxManifest = JSON.parse(readFileSync(sfxManifestPath, "utf8"));
} catch (e) {
die(`sfx manifest.json parse: ${e.message}`);
}
// Build filename → { duration, key } lookup so cues can reference by filename
// (matching v1 storyboard syntax: `impact-bass-1.mp3` not the manifest key).
const sfxByFile = new Map();
for (const [key, entry] of Object.entries(sfxManifest)) {
if (entry?.file && isFinite(entry.duration)) {
sfxByFile.set(entry.file, { key, duration: entry.duration });
}
}
// Copy entire SFX directory into <PROJECT_DIR>/assets/sfx/ (mp3 + manifest +
// CREDITS). Idempotent: skip files that already exist (e.g. re-runs).
const sfxDestDir = join(hyperframesDir, "assets", "sfx");
mkdirSync(sfxDestDir, { recursive: true });
let sfxCopied = 0;
for (const ent of readdirSync(sfxLibDir, { withFileTypes: true })) {
if (!ent.isFile()) continue;
const src = join(sfxLibDir, ent.name);
const dest = join(sfxDestDir, ent.name);
if (!existsSync(dest)) {
copyFileSync(src, dest);
sfxCopied++;
}
}
// Resolve each scene's cues against manifest + add scene.start_s offset.
for (const g of groups) {
for (const sid of g.scene_ids) {
const sceneEntry = g.scenes[sid];
const sceneCues = scenes.find((x) => x.sceneId === sid)?.sfxCues || [];
for (const cue of sceneCues) {
const hit = sfxByFile.get(cue.file);
if (!hit) {
anomalies.push(
`${sid}: SFX cue file "${cue.file}" not in manifest — dropping (known files: ${[...sfxByFile.keys()].slice(0, 5).join(", ")}${sfxByFile.size > 5 ? ", …" : ""})`,
);
continue;
}
const tGlobal = Number((sceneEntry.start_s + cue.t_local).toFixed(3));
sfx.push({
file: cue.file,
t: tGlobal,
duration: hit.duration,
volume: cue.volume != null ? cue.volume : 0.35,
scene_id: sid,
t_local: cue.t_local,
note: cue.note || "",
});
}
}
}
// Sort by global t for predictable index.html emission order.
sfx.sort((a, b) => a.t - b.t);
console.log(` sfx lib copied: ${sfxCopied} file(s) → assets/sfx/`);
} else {
// Surface plan cues that won't make it to the timeline because no lib was provided.
let droppedCueCount = 0;
for (const s of scenes) droppedCueCount += s.sfxCues?.length || 0;
if (droppedCueCount > 0) {
anomalies.push(
`section_plan declares ${droppedCueCount} SFX cue(s) but --sfx-lib not passed — all cues dropped`,
);
}
}
return sfx;
}
@@ -1,20 +0,0 @@
// scratch-dir.mjs — private per-process scratch dir for audio.mjs intermediates
// (narration .txt handoffs, detached-BGM logs).
//
// Bare `/tmp/<predictable-name>` writes are symlink-race exploitable on shared
// hosts (CodeQL js/insecure-temporary-file): a co-located process can
// pre-create the path as a symlink and redirect the write. mkdtempSync yields
// an unpredictable, owner-only (0700) directory, so file names inside it can
// stay deterministic. Deliberately never cleaned up here: the detached BGM
// process keeps writing its log after audio.mjs exits; the OS tmp cleaner
// reaps the directory like any other tmpdir() entry.
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
let scratchDir = null;
export function scratchPath(name) {
if (!scratchDir) scratchDir = mkdtempSync(join(tmpdir(), "hf-audio-"));
return join(scratchDir, name);
}
@@ -0,0 +1,249 @@
// storyboard.mjs — vendored lenient parser for STORYBOARD.md.
//
// Faithful plain-JS port of @hyperframes/core/storyboard
// (packages/core/src/storyboard/parseStoryboard.ts). Vendored because skills
// ship standalone: installed via `npx skills add`, a skill's scripts can't reach
// the monorepo's core package, and the core export points at .ts source that
// `node` (which runs these scripts) can't load. CANONICAL contract = the core
// parser + skills/hyperframes-core/references/storyboard-format.md; keep this in
// lockstep. Behavior: never throws, accepts freeform narrative, recognizes
// Frame/Beat/Scene headings at H2/H3, preserves unknown keys verbatim under
// `extra` (keys lowercased). Pure node — no deps.
export const FRAME_STATUSES = ["outline", "built", "animated"];
export const DEFAULT_FRAME_STATUS = "outline";
// Detection-only frame heading (ends at the keyword); ReDoS-hardened — keep as-is.
const FRAME_HEADING_RE = /^(#{2,3})[ \t]+(?:frame|beat|scene)\b/i;
const FRAME_TITLE_SEP_RE = /^[\s.:—-]+/;
const HEADING_LEVEL_RE = /^(#{1,6})\s+/;
const META_RE = /^\s*[-*]\s+([A-Za-z_][\w-]*)\s*:\s*(.+?)\s*$/;
const LEADING_INT_RE = /^(\d+)/;
const DURATION_NUM_RE = /(\d+(?:\.\d+)?)/;
const TRANSITION_KEYS = new Set(["transition_in", "transitionin", "transition"]);
const SCENE_KEYS = new Set(["scene", "description", "summary", "caption"]);
export const VOICEOVER_ALIASES = ["voiceover", "vo", "voice_over", "narration"];
const VOICEOVER_KEYS = new Set(VOICEOVER_ALIASES);
export function parseStoryboard(source) {
const warnings = [];
const { globals, bodyStartLine, body } = parseFrontmatter(source, warnings);
const frames = parseFrames(body, bodyStartLine, warnings);
return { globals, frames, warnings };
}
function emptyGlobals() {
return { extra: {} };
}
function isFrameStatus(value) {
return FRAME_STATUSES.includes(value);
}
// ── Frontmatter ─────────────────────────────────────────────────────────────
function findFrontmatterRange(lines, warnings) {
let start = 0;
while (start < lines.length && (lines[start] ?? "").trim() === "") start++;
if ((lines[start] ?? "").trim() !== "---") return null;
for (let i = start + 1; i < lines.length; i++) {
if ((lines[i] ?? "").trim() === "---") return { start, end: i };
}
warnings.push({
message: "Frontmatter opening '---' has no closing '---'; treating whole file as body.",
line: start + 1,
});
return null;
}
function parseFrontmatterEntries(lines, start, end, warnings) {
const globals = emptyGlobals();
for (let i = start + 1; i < end; i++) {
const raw = lines[i] ?? "";
if (raw.trim() === "") continue;
const colon = raw.indexOf(":");
if (colon === -1) {
warnings.push({
message: `Ignored non key:value frontmatter line: "${raw.trim()}"`,
line: i + 1,
});
continue;
}
const key = raw.slice(0, colon).trim().toLowerCase();
assignGlobal(globals, key, stripQuotes(raw.slice(colon + 1).trim()));
}
return globals;
}
function parseFrontmatter(source, warnings) {
const lines = source.split(/\r?\n/);
const range = findFrontmatterRange(lines, warnings);
if (!range) return { globals: emptyGlobals(), bodyStartLine: 1, body: source };
const globals = parseFrontmatterEntries(lines, range.start, range.end, warnings);
const body = lines.slice(range.end + 1).join("\n");
return { globals, bodyStartLine: range.end + 2, body };
}
function assignGlobal(globals, key, value) {
switch (key) {
case "format":
globals.format = value;
break;
case "message":
globals.message = value;
break;
case "arc":
globals.arc = value;
break;
case "audience":
globals.audience = value;
break;
default:
globals.extra[key] = value;
}
}
// ── Frames ──────────────────────────────────────────────────────────────────
function openFrameSection(line, headingLine) {
const match = FRAME_HEADING_RE.exec(line);
if (!match) return null;
const headingText = line.slice(match[0].length).replace(FRAME_TITLE_SEP_RE, "").trim();
return { headingText, headingLine, level: (match[1] ?? "##").length, lines: [] };
}
function endsFrameSection(line, current) {
if (!current) return false;
const heading = HEADING_LEVEL_RE.exec(line);
return heading !== null && (heading[1] ?? "").length <= current.level;
}
function parseFrames(body, bodyStartLine, warnings) {
const lines = body.split(/\r?\n/);
const sections = [];
let current = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? "";
const opened = openFrameSection(line, bodyStartLine + i);
if (opened) {
sections.push(opened);
current = opened;
} else if (endsFrameSection(line, current)) {
current = null;
} else if (current) {
current.lines.push(line);
}
}
return sections.map((section, idx) => buildFrame(section, idx + 1, warnings));
}
function buildFrame(section, index, warnings) {
const frame = { index, status: DEFAULT_FRAME_STATUS, narrative: "", extra: {} };
const { number, title } = parseHeading(section.headingText);
if (number !== undefined) frame.number = number;
if (title) frame.title = title;
const narrativeLines = [];
for (const line of section.lines) {
const meta = META_RE.exec(line);
if (meta) {
applyMeta(
frame,
(meta[1] ?? "").toLowerCase(),
(meta[2] ?? "").trim(),
section.headingLine,
warnings,
);
} else {
narrativeLines.push(line);
}
}
frame.narrative = narrativeLines.join("\n").trim();
return frame;
}
function parseHeading(text) {
if (!text) return {};
const intMatch = LEADING_INT_RE.exec(text);
if (!intMatch) return { title: text };
const number = Number.parseInt(intMatch[1] ?? "", 10);
const rest = text
.slice((intMatch[0] ?? "").length)
.replace(/^[\s.:—-]+/, "")
.trim();
return { number, title: rest || undefined };
}
// Dispatch a recognized metadata key to its field, else stash under `extra`.
// Mirrors core's META_SETTERS map exactly (direct keys + alias sets).
function applyMeta(frame, key, value, headingLine, warnings) {
switch (key) {
case "duration":
applyDuration(frame, value, headingLine, warnings);
return;
case "status":
applyStatus(frame, value, headingLine, warnings);
return;
case "poster":
applyPoster(frame, value);
return;
case "src":
frame.src = value;
return;
}
if (TRANSITION_KEYS.has(key)) {
frame.transitionIn = value;
return;
}
if (SCENE_KEYS.has(key)) {
frame.scene = value;
return;
}
if (VOICEOVER_KEYS.has(key)) {
frame.voiceover = stripQuotes(value);
return;
}
frame.extra[key] = value;
}
function applyPoster(frame, value) {
const num = DURATION_NUM_RE.exec(value);
if (num) frame.poster = Number.parseFloat(num[1] ?? "");
}
function applyDuration(frame, value, headingLine, warnings) {
frame.duration = value;
const num = DURATION_NUM_RE.exec(value);
if (num) {
frame.durationSeconds = Number.parseFloat(num[1] ?? "");
return;
}
warnings.push({
message: `Frame ${frame.index}: could not parse duration "${value}".`,
line: headingLine,
frameIndex: frame.index,
});
}
function applyStatus(frame, value, headingLine, warnings) {
const normalized = value.toLowerCase();
if (isFrameStatus(normalized)) {
frame.status = normalized;
return;
}
frame.extra.status = value;
warnings.push({
message: `Frame ${frame.index}: unknown status "${value}"; defaulting to "${DEFAULT_FRAME_STATUS}".`,
line: headingLine,
frameIndex: frame.index,
});
}
function stripQuotes(value) {
if (value.length >= 2) {
const first = value[0];
const last = value[value.length - 1];
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
return value.slice(1, -1);
}
}
return value;
}
@@ -0,0 +1,170 @@
// tokens.mjs — shared brand-token parsing + semantic role mapping for frame.md /
// FRAME.md. Used by build-frame.mjs (remix a preset onto brand tokens) and
// captions.mjs (derive caption colors from frame.md). One mapping → frames and
// captions stay consistent. Pure node.
// Collect `key: value` pairs under the top-level `colors:` block (until dedent).
export function parseColors(md) {
const out = [];
let inBlock = false;
for (const line of md.split(/\r?\n/)) {
if (/^colors:\s*$/.test(line)) {
inBlock = true;
continue;
}
if (!inBlock) continue;
if (/^\S/.test(line)) break; // dedent to a top-level key → end of block
const m = line.match(
/^\s+([\w-]+):\s*["']?(#[0-9a-fA-F]{3,8}|rgba?\([^)]*\)|[^"'#\s][^"'\n]*?)["']?\s*$/,
);
if (m) out.push([m[1], m[2].trim()]);
}
return out;
}
// relative luminance of a #rrggbb (null for non-hex like rgba()).
export function lum(v) {
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
if (!m) return null;
const n = parseInt(m[1], 16);
return 0.2126 * ((n >> 16) & 255) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255);
}
// chroma (maxmin channel) of a #rrggbb — a cheap "how colorful" proxy; 1 for non-hex.
export function chroma(v) {
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
if (!m) return -1;
const n = parseInt(m[1], 16);
const r = (n >> 16) & 255,
g = (n >> 8) & 255,
b = n & 255;
return Math.max(r, g, b) - Math.min(r, g, b);
}
// Browser user-agent default colors for links / visited links. These leak into a
// capture from any UNSTYLED <a> and are NOT brand colors — but being pure & saturated
// they beat a real accent on chroma alone. Never let one become the accent.
export const UA_DEFAULT_COLORS = new Set(
["#0000EE", "#0000FF", "#0000CC", "#1A0DAB", "#551A8B", "#EE0000"].map((c) => c.toUpperCase()),
);
// Pick the brand ACCENT — never by raw chroma alone, never a UA-default link color.
// Priority:
// 1) with capture colorStats → the colorful color used MOST as an interactive
// background (buttons / pills). That is, by definition, the brand action color.
// 2) no stats → most chromatic color AFTER removing UA defaults + `exclude`.
// A stray default link color (e.g. #0000EE) can win under neither path.
export function pickAccent(stats, colors, exclude = []) {
const ban = new Set([...exclude, ...UA_DEFAULT_COLORS].map((c) => String(c).toUpperCase()));
const ok = (h) => /^#[0-9a-fA-F]{6}$/.test(String(h)) && !ban.has(String(h).toUpperCase());
if (Array.isArray(stats) && stats.length) {
const a = stats
.filter((s) => ok(s?.hex) && (s.interactiveBg || 0) > 0 && chroma(s.hex) > 40)
.sort(
(x, y) => (y.interactiveBg || 0) - (x.interactiveBg || 0) || chroma(y.hex) - chroma(x.hex),
);
if (a.length) return a[0].hex;
}
const c = (colors ?? [])
.map(String)
.filter(ok)
.sort((x, y) => chroma(y) - chroma(x));
return c[0];
}
// Derive brand roles from rich capture colorStats (areaBg / interactiveBg / textCount /
// maxArea) — by semantic FUNCTION, not luminance/chroma proxies. Returns null when stats
// are unusable, so the caller can fall back. canvas = the color painting the most real
// background area (the page ground, dark or light); ink = the dominant text color that
// actually contrasts with the canvas; accent via pickAccent.
export function brandRolesFromStats(stats) {
if (!Array.isArray(stats) || !stats.length) return null;
const v = stats.filter((s) => /^#[0-9a-fA-F]{6}$/.test(s?.hex || ""));
if (!v.length) return null;
const canvas = [...v].sort(
(a, b) =>
(b.areaBg || 0) - (a.areaBg || 0) ||
(b.maxArea || 0) - (a.maxArea || 0) ||
(b.bgCount || 0) - (a.bgCount || 0),
)[0]?.hex;
const accent = pickAccent(
v,
v.map((s) => s.hex),
[canvas],
);
if (!canvas || !accent) return null;
const cl = lum(canvas) ?? 0;
const ink =
[...v]
.filter((s) => s.hex !== canvas && s.hex !== accent)
.sort((a, b) => (b.textCount || 0) - (a.textCount || 0))
.find((s) => Math.abs((lum(s.hex) ?? 0) - cl) > 64)?.hex ??
(cl > 128 ? "#000000" : "#FFFFFF");
const accent2 =
v
.filter(
(s) =>
![canvas, ink, accent].includes(s.hex) &&
(s.interactiveBg || 0) > 0 &&
chroma(s.hex) > 40 &&
!UA_DEFAULT_COLORS.has(s.hex.toUpperCase()),
)
.sort((a, b) => (b.interactiveBg || 0) - (a.interactiveBg || 0))[0]?.hex ?? accent;
return { ink, canvas, accent, accent2 };
}
// Map a list of [key, value] colors to semantic roles. ink = a dark/ink-named
// color (else darkest); canvas = a paper/cream/white-named color (else lightest);
// accents = whatever's left, ranked by chroma (the loudest color is almost always
// the brand accent) — UA-default link colors excluded so a stray <a> color never wins.
// For an unkeyed brand list, pass synthetic keys — name matching simply no-ops and it
// falls back to luminance/chroma, which is what we want. NOTE: when capture colorStats
// exist, prefer brandRolesFromStats() — it picks by function, not these proxies.
export function semanticColors(colors) {
if (!colors.length) return {};
const named = (re) => colors.find(([k]) => re.test(k));
const hexes = colors.filter(([, v]) => lum(v) != null);
const byLum = [...hexes].sort((a, b) => (lum(a[1]) ?? 1e9) - (lum(b[1]) ?? 1e9));
const pick = (m, fallback) => (m ? m[1] : fallback ? fallback[1] : undefined);
// "ink" must be a whole word-segment so "soft-pink"/"pink" don't match it.
const ink = pick(
named(/(?:^|[-_])ink(?:[-_]|$)|black|charcoal|^text(?:-dark)?$|outline|noir/i),
byLum[0] ?? colors[0],
);
const canvas = pick(
named(/cream|paper|canvas|white|bg|ground|surface|base|sand|parchment|off-?white|bone/i),
byLum[byLum.length - 1] ?? colors[colors.length - 1],
);
const accents = colors
.filter(([, v]) => v !== ink && v !== canvas && !UA_DEFAULT_COLORS.has(String(v).toUpperCase()))
.sort((a, b) => chroma(b[1]) - chroma(a[1]))
.map(([, v]) => v);
return { ink, canvas, accent: accents[0] ?? ink, accent2: accents[1] ?? accents[0] ?? ink };
}
// Collect role→fontFamily under the top-level `typography:` block; pick a display
// + body family from the usual role names. Returns quoted families (or null).
export function parseFonts(md) {
const roles = {};
let inBlock = false;
for (const line of md.split(/\r?\n/)) {
if (/^typography:\s*$/.test(line)) {
inBlock = true;
continue;
}
if (!inBlock) continue;
if (/^\S/.test(line)) break;
const m = line.match(/^\s+([\w-]+):\s*\{[^}]*fontFamily:\s*"([^"]+)"/);
if (m) roles[m[1]] = m[2];
}
const q = (s) => (s ? `"${s}"` : null);
const body = roles.body ?? roles.subtitle ?? Object.values(roles)[0];
const display =
roles.display ??
roles.headline ??
roles["card-headline"] ??
roles["section-headline"] ??
roles["quote-display"] ??
body;
return { display: q(display), body: q(body) };
}
@@ -1,42 +1,29 @@
// Shared loader for the transition registry — the single source of truth for
// PLV scene-to-scene transitions. Parses the ```json fenced block in
// skills/hyperframes-animation/transitions/TRANSITION-REGISTRY.md so the
// validator, prep, injector, and verifier all read the SAME vocabulary +
// GSAP templates. No duplicated allow-lists.
// transition-registry.mjs — loader for this skill's vendored transition registry
// (./transitions.json). The registry is the curated Tier-B subset (transform /
// opacity / filter on the two frame clip wrappers `#el-<id>`, no overlay DOM) +
// each type's GSAP template. Vendored into the skill so it ships standalone; the
// recipes originate from the shared catalog skills/hyperframes-animation/
// transitions/ (css-*.md) — keep them in step if those shared recipes change.
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
// scripts/lib/ -> ../../.. -> skills/ then into hyperframes-animation/transitions
export const DEFAULT_REGISTRY_PATH = resolve(
here,
"../../../hyperframes-animation/transitions/TRANSITION-REGISTRY.md",
);
export const DEFAULT_REGISTRY_PATH = resolve(here, "./transitions.json");
let _cache = null;
// Parse the first ```json … ``` fenced block out of the registry markdown.
export function loadTransitionRegistry(registryPath = DEFAULT_REGISTRY_PATH) {
if (_cache && _cache.path === registryPath) return _cache.data;
let md;
try {
md = readFileSync(registryPath, "utf8");
} catch (e) {
throw new Error(`transition registry not found at ${registryPath}: ${e.message}`);
}
const m = md.match(/```json\s*\n([\s\S]*?)\n```/);
if (!m) throw new Error(`transition registry ${registryPath} has no \`\`\`json block`);
let data;
try {
data = JSON.parse(m[1]);
data = JSON.parse(readFileSync(registryPath, "utf8"));
} catch (e) {
throw new Error(`transition registry json parse failed: ${e.message}`);
throw new Error(`transition registry not loadable at ${registryPath}: ${e.message}`);
}
if (!Array.isArray(data.transitions) || data.transitions.length === 0) {
throw new Error(`transition registry json has no transitions[]`);
throw new Error(`transition registry ${registryPath} has no transitions[]`);
}
_cache = { path: registryPath, data };
return data;
@@ -0,0 +1,71 @@
{
"_comment": "Vendored transition registry for the product-launch workflow — the curated Tier-B subset (transform/opacity/filter on the two frame clip wrappers #el-<id>, no overlay DOM, no per-frame cooperation). Each type carries its GSAP template; the transitions.mjs injector stamps it onto window.__timelines[\"main\"]. Recipes originate from the shared catalog skills/hyperframes-animation/transitions/ (css-*.md) — keep in step if those change. Token placeholders the injector substitutes: __OLD__ (#el-<from>), __NEW__ (#el-<to>), __T__ (overlap-start s), __DUR__ (this boundary's duration), __DX__/__DXIN__ (horizontal travel + incoming offset), __DY__/__DYIN__ (vertical).",
"transitions": [
{
"name": "crossfade",
"energy": "any",
"default_duration_s": 0.5,
"directions": [],
"source": "css-dissolve.md",
"gsap_template": [
"tl.to(__OLD__, { opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { opacity: 0 }, { opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
]
},
{
"name": "blur-crossfade",
"energy": "calm",
"default_duration_s": 0.6,
"directions": [],
"source": "css-dissolve.md",
"note": "Default when the two frames' #root backgrounds differ a lot — the blur masks the background-color clash a plain crossfade would expose.",
"gsap_template": [
"tl.to(__OLD__, { filter: \"blur(10px)\", scale: 1.03, opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { filter: \"blur(10px)\", scale: 0.97, opacity: 0 }, { filter: \"blur(0px)\", scale: 1, opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
]
},
{
"name": "push-slide",
"energy": "medium",
"default_duration_s": 0.5,
"directions": ["LEFT", "RIGHT", "UP", "DOWN"],
"default_direction": "LEFT",
"source": "css-push.md",
"note": "Directional. The injector picks __DX__/__DY__ from the direction and emits the horizontal OR vertical pair (not both).",
"gsap_template_horizontal": [
"tl.to(__OLD__, { x: __DX__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { x: __DXIN__, opacity: 1 }, { x: 0, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
],
"gsap_template_vertical": [
"tl.to(__OLD__, { y: __DY__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { y: __DYIN__, opacity: 1 }, { y: 0, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
]
},
{
"name": "zoom-through",
"energy": "high",
"default_duration_s": 0.4,
"directions": [],
"source": "css-scale.md",
"gsap_template": [
"tl.to(__OLD__, { scale: 2.5, opacity: 0, filter: \"blur(8px)\", duration: __DUR__, ease: \"power3.in\" }, __T__);",
"tl.fromTo(__NEW__, { scale: 0.5, opacity: 0, filter: \"blur(8px)\" }, { scale: 1, opacity: 1, filter: \"blur(0px)\", duration: __DUR__, ease: \"power3.out\" }, __T__);"
]
},
{
"name": "squeeze",
"energy": "medium",
"default_duration_s": 0.4,
"directions": [],
"source": "css-push.md",
"note": "Old compresses to a vertical line on the left edge; new expands from the right edge. Incoming starts off (scaleX 0) so its higher-track stacking is harmless.",
"gsap_template": [
"tl.to(__OLD__, { scaleX: 0, transformOrigin: \"left center\", duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { scaleX: 0, transformOrigin: \"right center\", opacity: 1 }, { scaleX: 1, transformOrigin: \"right center\", duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
]
}
],
"default_high_energy": "zoom-through",
"default_calm": "blur-crossfade",
"max_duration_s": 2.0
}