Files
patriothacks/e2e/demoVideoFull.e2e.mjs

1567 lines
82 KiB
JavaScript

// Full-feature demo video (ad-hoc, user-requested - not tied to a plan
// todo number). Self-contained Playwright runner, same shape as every
// other e2e/*.e2e.mjs script in this project: starts a real local Vite
// dev server, drives the REAL shipped app through its REAL rendered UI
// (no bypass/internal-function calls for anything shown on camera), and
// records real video via Playwright's `recordVideo` context option.
//
// Two recording scenes:
// Scene 1 ("main"): one browser context, one continuous tour touching
// all 13 mini-apps plus the wallet, admin seed, and the upload-a-
// mini-app flow. `window.crypto.getRandomValues` is pinned (the same
// technique e2e/fairDrawWalletCredit.e2e.mjs already uses) so Fair
// Draw's real commit/reveal/verify cycle deterministically resolves to
// "You" winning, making the wallet-credit beat reliably demonstrable on
// camera without touching any other real logic. The raw capture is then
// run through `playwright-recast` (a real trace-based motion-graphics
// pipeline - see .omo/ulw-research/20261118-121942/ for the research
// that picked it over a from-scratch Remotion/Manim rebuild) to add a
// synthetic cursor, click ripples, and auto-zoom onto the exact element
// being interacted with, derived from the real Playwright trace - not
// hand-authored keyframes. It also gets a motion-graphics polish pass
// (see .omo/evidence/full-feature-demo/DEMO_VIDEO_NOTES.md for the
// research behind each choice): a kinetic-typography title card as a
// cold open/outro (crossfaded in via `.intro()`/`.outro()` - the same
// "bold statement before the product" hook used by Linear/Apple/Raycast
// launch films), real on-screen captions generated from this script's
// own beat-log narration (written into the trace via
// `context.tracing.group()` using the exact marker convention
// `subtitlesFromTrace()` already looks for, so no voiceover/TTS key is
// needed - captions carry the explanation instead), and a short
// self-synthesized ambient pad (`ffmpeg` sine-wave tones, not a
// copyrighted track) via `.backgroundMusic()` so the video isn't silent.
//
// Scene 2 ("assembly-sync"): TWO genuinely isolated browser contexts
// (separate storage origins - the same discipline
// e2e/assemblyScreenSync.e2e.mjs already proved out) open the real
// shipped Assembly screen and drive its real "Sync with nearby devices"
// toggle through connect -> partition -> heal -> converge, recorded as
// two side-by-side panes. Left as a plain capture (no recast pass): the
// point of this scene is the side-by-side proof of independent device
// state, which a zoom/cursor layer would only obscure.
//
// The two scenes are concatenated (scale/pad to one common canvas) into
// a single final video with a real ffmpeg binary.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { Recast } from "playwright-recast";
import { NARRATE_TITLE_PREFIX, ZOOM_TITLE_PREFIX } from "playwright-recast/helpers";
import ffmpegStatic from "ffmpeg-static";
import ffprobeStatic from "ffprobe-static";
// Todo 2 (promo-video-redesign plan): the landscape margin copy below
// cites these numbers directly from the real fixture module instead of
// hand-retyping them, so the margin text can never silently drift from
// what "Load Hollow demo" actually seeds (confirmed importable: Node's
// native TS type-stripping handles this file's type-only imports fine).
// This is read-only - no src/** file is modified by this plan todo.
import { HOLLOW_DEMO_FIXTURE } from "../src/admin/seedEvents.ts";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const EVIDENCE_DIR = resolve(ROOT, ".omo/evidence/full-feature-demo");
const VIDEO_TMP_DIR = resolve(ROOT, ".tmp/full-feature-demo");
const FINAL_VIDEO = resolve(ROOT, ".omo/evidence/full-feature-demo/the-commons-hollow-full-demo.mp4");
// The Playwright-bundled ffmpeg (~/.cache/ms-playwright/ffmpeg-*/ffmpeg-linux)
// is a `--disable-everything` build meant only for Playwright's own
// frame-to-webm screencast conversion: it has no `hstack`/`concat`/
// `setsar`/`fps` filters and no libx264 encoder at all, so it cannot do
// the compositing/concatenation this script needs, nor what
// `playwright-recast` needs (`zoompan`, `xfade`, `overlay`, `subtitles`/
// `ass` - confirmed present; `drawtext` confirmed ABSENT, so `.urlBar()`
// is not used anywhere in this script). `ffmpeg-static`/`ffprobe-static`
// are real devDependencies of this project (not a throwaway /tmp
// install) providing a full static build of both binaries; their
// directory is prepended to PATH so `playwright-recast`'s own internal
// `execFileSync('ffmpeg'|'ffprobe', ...)` calls find them too.
const FFMPEG_BIN = process.env.FFMPEG_BIN ?? ffmpegStatic;
const FFPROBE_BIN = process.env.FFPROBE_BIN ?? ffprobeStatic.path;
if (!existsSync(FFMPEG_BIN)) {
throw new Error(`ffmpeg binary not found at ${FFMPEG_BIN}. Set FFMPEG_BIN env var to override.`);
}
if (!existsSync(FFPROBE_BIN)) {
throw new Error(`ffprobe binary not found at ${FFPROBE_BIN}. Set FFPROBE_BIN env var to override.`);
}
process.env.PATH = `${dirname(FFMPEG_BIN)}:${dirname(FFPROBE_BIN)}:${process.env.PATH ?? ""}`;
const PANE = { width: 414, height: 896 };
// The main scene is recorded at 2x device-pixel density (recast's own
// documented fix for sharp zoomed/overlaid text - plain `deviceScaleFactor`
// never reaches a headless recording; it needs BOTH the
// `--force-device-scale-factor` launch arg AND a matching `recordVideo`
// `size`, confirmed by this project's own test render during the research
// pass, which otherwise warned of a 4.64x upscale and visibly soft text).
const RECAST_SCALE = 2;
const MAIN_VIDEO_SIZE = { width: PANE.width * RECAST_SCALE, height: PANE.height * RECAST_SCALE };
// Todo 2 (promo-video-redesign plan): the FINAL assembled canvas is now a
// true 16:9 landscape frame, not the portrait-ish 828x896 this used to be
// (`PANE.width * 2` x `PANE.height`). `compositeLandscapeWithMargins()`
// below already produces the main scene at exactly this resolution
// before `concatToFinal()` runs, so its existing
// scale+pad-to-`FINAL_W`x`FINAL_H` step is a no-op for that segment and
// only has real work left to do for the Assembly two-device composite
// (which stays its own untouched plain-capture treatment, just letterboxed
// into the same 16:9 frame like before).
const FINAL_W = 1920;
const FINAL_H = 1080;
const SIG_PORT = 44000 + Math.floor(Math.random() * 10000);
const VITE_PORT = 45000 + Math.floor(Math.random() * 10000);
const SIG = `ws://127.0.0.1:${SIG_PORT}`;
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, label, timeoutMs = 20000) {
const start = Date.now();
let lastErr;
while (Date.now() - start < timeoutMs) {
try {
const v = await fn();
if (v) return v;
} catch (e) {
lastErr = e;
}
await sleep(150);
}
throw new Error(`timeout waiting for: ${label}${lastErr ? ` (last error: ${lastErr})` : ""}`);
}
// `context` is optional (Scene 2's dualBeat has its own logger and never
// passes one): when present, each beat also opens a `context.tracing.group()`
// titled with recast's own `NARRATE_TITLE_PREFIX` marker - the exact
// convention its `subtitlesFromTrace()` stage already looks for (confirmed
// against `helpers.d.ts` and a standalone trace-parse probe), so this
// script's real beat narration becomes real on-screen captions without
// needing playwright-bdd or a TTS key. Each caption's window runs from its
// own beat to the next one's (or scene end), matching `narrate()`'s own
// documented span semantics.
function makeBeatLog(sceneName, sceneStartRef, context) {
const beats = [];
let captionOpen = false;
return {
beats,
async log(label, note, page) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
let screenshot;
if (page) {
screenshot = resolve(EVIDENCE_DIR, `${sceneName}-${String(beats.length).padStart(2, "0")}-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await page.screenshot({ path: screenshot }).catch(() => {});
}
beats.push({ scene: sceneName, label, note, sceneRelativeMs, screenshot });
console.log(`[${sceneName} +${(sceneRelativeMs / 1000).toFixed(1)}s] ${label}: ${note}`);
if (context) {
if (captionOpen) await context.tracing.groupEnd();
await context.tracing.group(`${NARRATE_TITLE_PREFIX}${note}`);
captionOpen = true;
}
},
// Writes a zero-duration `zoom()`-marker-shaped trace step (same
// `ZOOM_TITLE_PREFIX` convention `zoom()` itself writes - see
// helpers.js) nested inside the currently-open narrate group, at
// level 1.0 ("no zoom", per the helper's own JSDoc). The pipeline's
// `autoZoom()` stage only computes a zoom for a subtitle when
// `subtitle.zoom` is still unset (`executor.js`: "already set by
// enrichZoomFromReport" - the same guard also protects an explicit
// `zoom()` marker), so this pins the current beat's cue to an
// explicit no-zoom and excludes it from autoZoom's click-attribution
// window entirely, instead of inheriting the pan from whatever real
// click happened up to 2s before this beat opened.
async noZoom() {
if (context && captionOpen) {
await context.tracing.group(`${ZOOM_TITLE_PREFIX}${JSON.stringify({ x: 0.5, y: 0.5, level: 1 })}`);
await context.tracing.groupEnd();
}
},
async closeCaption() {
if (context && captionOpen) {
await context.tracing.groupEnd();
captionOpen = false;
}
},
};
}
// ---------------------------------------------------------------------
// Motion-graphics assets: a kinetic-typography title card (cold-open hook
// + outro, the same "bold statement before the product" pattern
// reverse-engineered from Linear/Apple/Raycast launch films - see
// DEMO_VIDEO_NOTES.md) and a short self-synthesized ambient pad (plain
// `ffmpeg` sine oscillators - no third-party/copyrighted audio file).
// Both are rendered with the same Chromium/ffmpeg this script already
// uses, at the exact resolution `addMotionGraphics()` needs so recast's
// internal `xfade`/`amix` compositing doesn't choke on a mismatch.
// ---------------------------------------------------------------------
const TITLE_CARD_CSS = `
* { margin:0; padding:0; box-sizing:border-box; }
html,body { width:100%; height:100%; background:#05070d; overflow:hidden; font-family: -apple-system, 'Helvetica Neue', Arial, sans-serif; }
.wrap { width:100%; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; position:relative; padding:0 60px; text-align:center; }
.glow { position:absolute; width:900px; height:900px; border-radius:50%; background:radial-gradient(circle, rgba(22,119,255,0.35) 0%, rgba(22,119,255,0) 70%); filter:blur(10px); }
.eyebrow { color:#4f9dff; letter-spacing:0.4em; font-size:20px; font-weight:600; text-transform:uppercase; opacity:0; transform:translateY(14px); animation: rise 0.6s ease forwards 0.15s; }
.title { color:#f5f7ff; font-size:72px; font-weight:800; letter-spacing:-0.02em; margin-top:18px; line-height:1.05; opacity:0; transform:translateY(20px); animation: rise 0.7s ease forwards 0.45s; }
.rule { width:110px; height:4px; background:#1677FF; margin-top:26px; transform:scaleX(0); transform-origin:center; animation: grow 0.6s ease forwards 0.95s; }
.tagline { color:#9fb3d9; font-size:26px; font-weight:400; margin-top:26px; max-width:620px; opacity:0; transform:translateY(14px); animation: rise 0.6s ease forwards 1.3s; }
@keyframes rise { to { opacity:1; transform:translateY(0); } }
@keyframes grow { to { transform:scaleX(1); } }
`;
function titleCardHtml({ eyebrow, title, tagline }) {
return `<!doctype html><html><head><style>${TITLE_CARD_CSS}</style></head>
<body><div class="wrap"><div class="glow"></div>
<div class="eyebrow">${eyebrow}</div>
<div class="title">${title}</div>
<div class="rule"></div>
<div class="tagline">${tagline}</div>
</div></body></html>`;
}
// Inter-act title cards for the problem-first 3-act restructure: the SAME
// titleCardHtml()/TITLE_CARD_CSS visual grammar as the intro/outro cards
// (reused verbatim via `srcdoc`, no parallel implementation), displayed on
// the SAME continuous Playwright recording/trace the main tour already
// produces, so the card still plays out as genuine composited video frames
// exactly like `renderTitleCard()`'s throwaway context does, with zero new
// compositing/splicing stage: addMotionGraphics()'s `.intro()`/`.outro()`
// calls stay exactly one each.
//
// PACING FIX: this used to `page.setContent(card)` (which DESTROYS the live
// React app) and then `page.goto('/')` to rebuild it - that full reload
// painted a run of pure-white blank frames between the dark card and the
// app on EVERY act boundary (measured on the pre-fix render: ~7 white
// frames / 0.28s at ~t23.3 (Act II->Farms) and again at ~t41.0
// (Act III->Assembly), plus a shorter bright blip at the Epilogue cut) -
// a jarring dead-frame flash in an otherwise dark-to-app cut. The card is
// now an isolated full-screen `<iframe srcdoc=...>` OVERLAY laid on top of
// the live app: the app is never unmounted, so there is no reload and no
// white flash. The overlay fades IN with an ease-out curve (landing motion
// decelerates), holds, navigates home UNDERNEATH via the app's own real
// client-side "Back to home" link (SPA routing, no reload - `pointer-events:
// none` lets the click pass through the still-opaque card), then fades OUT
// faster on an ease-in curve (leaving motion accelerates) to reveal the
// freshly-mounted grid. The card markup/CSS is byte-identical to the
// intro/outro cards because `srcdoc` renders the exact `titleCardHtml()`
// document in its own isolated browsing context.
async function showActTitleCard(page, beatLog, { label, eyebrow, title, tagline, holdMs = 2400 }) {
await page.evaluate((html) => {
const f = document.createElement("iframe");
f.id = "__act_card__";
f.setAttribute("srcdoc", html);
f.style.cssText =
"position:fixed;inset:0;width:100vw;height:100vh;border:0;margin:0;" +
// transparent to pointer events so the real "Back to home" link
// underneath stays clickable while the card is up; fade in quickly
// (ease-out) so the dark card bg lands before the internal
// kinetic-typography reveal starts, rather than fighting it.
"z-index:2147483647;pointer-events:none;opacity:0;" +
"transition:opacity 250ms cubic-bezier(0,0,0.2,1)";
document.body.appendChild(f);
requestAnimationFrame(() => {
f.style.opacity = "1";
});
}, titleCardHtml({ eyebrow, title, tagline }));
await beatLog.log(label, `${eyebrow} - "${title}": ${tagline}`, page);
// Pin this beat's cue to an explicit no-zoom (see `noZoom()`) - title
// cards are a full-screen kinetic-typography reveal, not an app
// interaction, and must never inherit autoZoom's pan from a preceding
// click (that was clipping Act II's longer title against the frame
// edge mid-hold).
await beatLog.noZoom();
await page.waitForTimeout(holdMs);
// Navigate back to a clean home grid UNDERNEATH the still-opaque card via
// the app's own client-side "Back to home" link (no full reload, no white
// flash). On "/" that link is hidden by ShellLayout, so this is a no-op
// there (e.g. Act I, which already starts from home).
const backLink = page.getByRole("link", { name: "Back to home" });
if ((await backLink.count()) > 0) {
await backLink.click();
}
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
// Fade the card out faster than it came in (leaving motion accelerates,
// ease-in) to reveal the freshly-mounted grid, then remove it.
await page.evaluate(() => {
const f = document.getElementById("__act_card__");
if (f) {
f.style.transition = "opacity 280ms cubic-bezier(0.4,0,1,1)";
f.style.opacity = "0";
}
});
await page.waitForTimeout(300);
await page.evaluate(() => document.getElementById("__act_card__")?.remove());
}
// Records the title card through a real throwaway Playwright context (same
// `recordVideo` mechanism as the real scenes) so the reveal animation plays
// out as genuine composited video frames, not a hand-assembled still.
async function renderTitleCard({ html, size, durationMs, outDir }) {
// Clean-and-recreate, not `.find()` over whatever is already there:
// this outDir accumulates one stale `.webm` per prior run (the intro/
// outro throwaway contexts never clean up after themselves), and
// `readdirSync().find()` has no ordering guarantee - it was silently
// picking an old recording instead of the one this call just made.
rmSync(outDir, { recursive: true, force: true });
mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: size, recordVideo: { dir: outDir, size } });
const page = await context.newPage();
await page.setContent(html, { waitUntil: "load" });
await page.waitForTimeout(durationMs);
await context.close();
await browser.close();
const file = readdirSync(outDir).find((f) => f.endsWith(".webm"));
if (!file) throw new Error(`title card recording produced no .webm in ${outDir}`);
return resolve(outDir, file);
}
// A soft three-note pad (C3/E3/G3) with slow tremolo, faded in and out -
// generated entirely by ffmpeg's `lavfi` sine-wave source, so there's no
// licensing question around the audio bed `.backgroundMusic()` needs.
// Deliberately NOT pre-attenuated here (no baked-in `volume=` cut below
// tremolo/fades) - `.backgroundMusic({ volume })` downstream is
// recast's own documented final-mix gain control (its own default is
// 0.3, implying it expects a near-unity source track). Stacking a quiet
// gain here on top of that gain was the F3-confirmed silent-audio
// regression: 0.14 (here) * 0.1 (backgroundMusic's volume) multiplied
// out to -69.5dB mean / -58.5dB max in the shipped video - deep in the
// noise floor, not an audible ambient track, even though a real AAC
// stream existed in the container. Verified by direct measurement
// (ffprobe volumedetect at each pipeline stage, then re-measured on a
// full re-render) that the unattenuated mix here plus `volume=0.55` on
// the `.backgroundMusic()` call below lands the final video audibly
// above the noise floor without clipping - see that call site's own
// note for the exact before/after numbers.
function generateAmbientTrack(outPath, durationSeconds = 26) {
mkdirSync(dirname(outPath), { recursive: true });
const fadeOutStart = Math.max(0, durationSeconds - 4);
execFileSync(
FFMPEG_BIN,
[
"-y",
"-f", "lavfi", "-i", `sine=frequency=130.81:duration=${durationSeconds}`,
"-f", "lavfi", "-i", `sine=frequency=164.81:duration=${durationSeconds}`,
"-f", "lavfi", "-i", `sine=frequency=196.00:duration=${durationSeconds}`,
"-filter_complex",
`[0][1][2]amix=inputs=3:duration=longest:weights=1 0.8 0.7[mix];` +
`[mix]tremolo=f=0.15:d=0.3,afade=t=in:st=0:d=3,afade=t=out:st=${fadeOutStart}:d=4[out]`,
"-map", "[out]",
"-c:a", "libmp3lame", "-b:a", "128k",
outPath,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
return outPath;
}
function startSignaling() {
return new Promise((resolvePromise, reject) => {
const child = spawn("node", ["node_modules/y-webrtc/bin/server.js"], {
cwd: ROOT,
env: { ...process.env, PORT: String(SIG_PORT) },
stdio: ["ignore", "pipe", "pipe"],
});
const to = setTimeout(() => reject(new Error("signaling start timeout")), 10000);
child.stdout.on("data", (b) => {
if (String(b).includes("Signaling server running")) {
clearTimeout(to);
resolvePromise(child);
}
});
child.stderr.on("data", (b) => process.stderr.write(`[sig] ${b}`));
child.on("exit", (code) => reject(new Error(`signaling exited early: ${code}`)));
});
}
async function startVite() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
return vite;
}
// ---------------------------------------------------------------------
// Generic shell navigation helpers
// ---------------------------------------------------------------------
async function backHome(page) {
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
}
async function openTile(page, label) {
await page.getByRole("button", { name: label }).click();
await page.locator(`[aria-label="${label}"]`).first().waitFor({ state: "visible", timeout: 10000 });
}
async function walletBalanceText(page) {
return (await page.getByTestId("wallet-balance").textContent())?.trim();
}
// ---------------------------------------------------------------------
// Fair Draw deterministic-winner override (mirrors
// e2e/fairDrawWalletCredit.e2e.mjs FILL_FOR_YOU_WINS exactly).
// ---------------------------------------------------------------------
async function forceLocalIdentityWinsFairDraw(context) {
await context.addInitScript(() => {
window.crypto.getRandomValues = function (arr) {
arr.fill(0x02);
return arr;
};
});
}
// =======================================================================
// SCENE 1: main single-context tour
// =======================================================================
async function recordMainScene() {
console.log("\n=== Scene 1: main feature tour ===");
const videoDir = resolve(VIDEO_TMP_DIR, "main");
// A prior crashed/aborted attempt leaves its own page@<guid>.webm behind
// in this same directory (mkdirSync({recursive:true}) never deletes
// existing files) - Recast.from(videoDir) has no way to tell that stale
// file apart from this run's real recording, so a leftover partial
// webm here silently corrupts the next render (confirmed: it produced a
// final video frozen on the intro card for nearly its whole length).
// Wiping the directory first guarantees exactly one real recording per
// render.
rmSync(videoDir, { recursive: true, force: true });
mkdirSync(videoDir, { recursive: true });
const browser = await chromium.launch({
headless: true,
args: ["--no-sandbox", `--force-device-scale-factor=${RECAST_SCALE}`],
});
const context = await browser.newContext({
viewport: PANE,
deviceScaleFactor: RECAST_SCALE,
recordVideo: { dir: videoDir, size: MAIN_VIDEO_SIZE },
});
// Real Playwright tracing (actions, screencast frames, cursor positions)
// is what playwright-recast's autoZoom()/cursorOverlay()/clickEffect()
// read to find click/fill coordinates - this is the one new line of
// capture this motion-graphics pass needed; the tour script below is
// completely unmodified.
await context.tracing.start({ screenshots: true, snapshots: true });
await forceLocalIdentityWinsFairDraw(context);
const page = await context.newPage();
const sceneStartRef = { value: Date.now() };
const beatLog = makeBeatLog("main", sceneStartRef, context);
try {
// --- Cold start: real non-custodial identity resolves, honest empty state ---
await page.goto(`${APP_URL}/`, { waitUntil: "load" });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await waitFor(async () => (await walletBalanceText(page)) !== "--", "identity resolves (wallet leaves '--')");
await beatLog.log("cold-start", "fresh local Ed25519 identity resolved, honest empty home grid + wallet", page);
await sleep(1200);
// --- Admin: Load Hollow demo seed ---
await page.goto(`${APP_URL}/admin`, { waitUntil: "load" });
await page.getByRole("button", { name: "Load Hollow demo" }).click();
await waitFor(
async () => ((await page.getByTestId("demo-load-status").textContent()) ?? "").includes("Demo data loaded"),
"demo seed load status",
);
await beatLog.log("admin-seed", "Load Hollow demo clicked - signed seed.* events appended (roster, proposal, housing, mentor, wallet balance)", page);
await sleep(1000);
await page.goto(`${APP_URL}/`, { waitUntil: "load" });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await sleep(800);
// =================================================================
// ACT I: "A crisis, verified twice" - a bad reading could be noise;
// it takes two independent sensors to be sure, one shelter of 4,200
// lives underground with no surface supply line to fall back on (one
// neighborhood of the Hollow's two billion, not the whole civilization).
// =================================================================
await showActTitleCard(page, beatLog, {
label: "act1-title",
eyebrow: "Act I",
title: "A Crisis, Verified Twice",
tagline: "This shelter: 4,200 residents, no surface supply line. A bad water reading could be noise - it takes two independent sensors before the shelter trusts it.",
});
// --- Water Watch: GAP-8 false-alert fix + genuine corroborated detection ---
// Sensor ids are real kiosk ids from DEFAULT_PIPE_NETWORK (not the
// arbitrary "sensor-A"/"sensor-B" placeholders this beat used before) so
// the real pipe-graph leak localization below actually resolves a
// suspected origin instead of silently staying "unmapped".
await openTile(page, "Water Watch");
async function reportReading(sensorId, value) {
await page.getByTestId("report-reading-sensor").fill(sensorId);
await page.getByTestId("report-reading-value").fill(String(value));
await page.getByTestId("report-reading-submit").click();
await waitFor(
async () => !((await page.getByTestId("report-reading-status").textContent()) ?? "").includes("Submitting..."),
`submit ${sensorId}=${value} settles`,
);
}
await reportReading("kiosk-1", 7);
await sleep(400);
await reportReading("kiosk-1", 7.05);
const stateAfterFlat = await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state");
if (stateAfterFlat === "alert") {
throw new Error("REGRESSION: a flat 2nd reading triggered a false alert (GAP-8 fix did not hold)");
}
await beatLog.log("waterwatch-no-false-alert", `flat 2nd reading (7.0 -> 7.05) did NOT fire a false alert - state is "${stateAfterFlat}", not "alert"`, page);
await sleep(1200);
await reportReading("kiosk-1", 50);
await waitFor(
async () => (await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state")) === "corroborating",
"pH channel reaches corroborating after a genuine spike",
);
await beatLog.log("waterwatch-corroborating", "genuine spike (7 -> 50) correctly flagged - awaiting a second independent sensor", page);
await sleep(1000);
await reportReading("kiosk-2", 7);
await reportReading("kiosk-2", 55);
await waitFor(
async () => (await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state")) === "alert",
"pH channel reaches alert once corroborated",
);
await beatLog.log("waterwatch-alert", "independent kiosk-2 corroborated the spike - real signed alert, Fair Share re-solve triggered", page);
await sleep(1200);
await page.getByTestId("device-monitor-my-tap").selectOption({ index: 1 });
await waitFor(
async () => (await page.getByTestId("device-monitor-origin-pH").count()) > 0,
"pipe-graph leak localization resolves a suspected origin",
);
await beatLog.log("waterwatch-localization", "real pipe-graph leak localization named a suspected origin node, with a live per-tap arrival countdown for the selected tap", page);
await sleep(1400);
// --- Fair Share: water allocation re-solved ---
await backHome(page);
await openTile(page, "Fair Share");
await waitFor(async () => {
const text = (await page.getByTestId("tile-water-allocation").textContent()) ?? "";
return text.trim().length > 0 && text !== "No allocation yet";
}, "Fair Share water tile shows a real re-solved allocation");
await beatLog.log("fairshare-water", "Fair Share's water tile reflects the honesty-anchor chain's re-solved CEEI allocation", page);
await sleep(1400);
// --- Tunnel Safety: real hazard report ---
await backHome(page);
await openTile(page, "Tunnel Safety");
await page.getByTestId("tunnel-safety-report-submit").click();
await waitFor(
async () => ((await page.getByTestId("tunnel-safety-report-status-text").textContent()) ?? "").includes("Hazard reported"),
"hazard report submitted",
);
await beatLog.log("tunnelsafety", "real hazard report appended for the selected corridor segment", page);
await sleep(1200);
// --- Find Family: on-device PSI search ---
await backHome(page);
await openTile(page, "Find Family");
await page.getByTestId("findfamily-search-input").fill("Ana Ramirez");
await page.getByTestId("findfamily-search-button").click();
await waitFor(
async () => (await page.getByTestId("findfamily-result-match").count()) > 0 || (await page.getByTestId("findfamily-result-nomatch").count()) > 0,
"PSI search resolves",
);
await beatLog.log("findfamily", "on-device private-set-intersection search resolved - the query never left the device", page);
await sleep(1200);
// =================================================================
// ACT II: "Keeping the Hollow alive" - the day-to-day engines of an
// underground shelter: grow-light farms, floor plans, mentorship, the
// clinic, a body clock with no sun, and the climb back to the surface.
// =================================================================
await showActTitleCard(page, beatLog, {
label: "act2-title",
eyebrow: "Act II",
title: "Keeping the Hollow Alive",
tagline: "Grow-light farms, floor plans, mentors, the clinic, a body clock with no sun - every decision for this 4,200-resident shelter replayable from one signed log, far below the surface.",
});
// --- Farms -> Fair Share food edge (2nd integration edge) ---
await openTile(page, "Farms");
await page.getByTestId("farms-temp-date").fill("2026-05-01");
await page.getByTestId("farms-temp-tmin").fill("10");
await page.getByTestId("farms-temp-tmax").fill("30");
await page.getByTestId("farms-temp-add").click();
await page.getByTestId("farms-plot-id").fill("plot-a");
await page.getByTestId("farms-plot-area").fill("100");
await page.getByTestId("farms-plot-add").click();
await page.getByTestId("farms-crop-id").fill("wheat");
await page.getByTestId("farms-crop-maturity-gdd").fill("10");
await page.getByTestId("farms-crop-yield").fill("2");
// The grow-light kWh field is a Wave-1 addition ("Add crop" is now
// gated on it too) - 0 keeps this crop energy-free so the LP's
// real 200.00 kg forecast is unaffected (no energy budget is set).
await page.getByTestId("farms-crop-kwh").fill("0");
await page.getByTestId("farms-crop-add").click();
await waitFor(
async () => ((await page.getByTestId("farms-forecast-total").textContent()) ?? "").includes("200.00 kg"),
"Farms LP optimizer reaches a real 200.00 kg forecast",
);
await beatLog.log("farms-forecast", "real GDD + LP optimizer forecast (1 temp reading, 1 plot, 1 crop) -> 200.00 kg", page);
await sleep(1200);
await backHome(page);
await openTile(page, "Fair Share");
await waitFor(async () => {
const text = (await page.getByTestId("tile-food-allocation").textContent()) ?? "";
return text.trim().length > 0 && text !== "No allocation yet" && text.trim() !== "0";
}, "Fair Share food tile reflects the Farms forecast");
await beatLog.log("fairshare-food", "Farms' real forecast fed Fair Share's second cross-mini-app integration edge - food tile re-solved", page);
await sleep(1400);
// --- Housing: real assigned slot from the demo seed + the resident-
// facing idle-space report + assignment-cycle trigger ---
await backHome(page);
await openTile(page, "Housing");
await page.getByTestId("housing-assigned-slot").waitFor({ state: "visible" });
await beatLog.log("housing", "Housing shows a real assigned room slot from the seeded assignment cycle, not a permanent empty state", page);
await sleep(1200);
await page.getByTestId("housing-report-space-id").fill("common-room-3");
await page.getByTestId("housing-report-location").fill("East wing, ground floor");
await page.getByTestId("housing-report-submit").click();
await waitFor(
async () => ((await page.getByTestId("housing-report-status-text").textContent()) ?? "").includes("Idle space reported"),
"idle space report submits",
);
await beatLog.log("housing-report-idle-space", "a resident reported a real idle space through the real form - available to the next assignment cycle", page);
await sleep(1000);
await page.getByTestId("housing-run-cycle").click();
await waitFor(
async () => ((await page.getByTestId("housing-run-cycle-status").textContent()) ?? "").length > 0,
"resident-triggered assignment cycle runs",
);
await beatLog.log("housing-run-cycle", "the resident-facing 'Run assignment cycle' button recorded a new real housing.assignment cycle against the current fairness-debt ledger", page);
await sleep(1200);
// --- Mentor: real at-risk skill + the apprentice-to-mentor matching engine ---
await backHome(page);
await openTile(page, "Mentor");
await page.getByTestId("mentor-card-well-repair").waitFor({ state: "visible" });
await beatLog.log("mentor", "Mentor shows a real at-risk skill card (deduped dependents count) from the seeded skill-holder data", page);
await sleep(1200);
await page.getByTestId("mentor-rate-again-well-repair").click();
await waitFor(
async () => (await page.getByTestId("mentor-matches").count()) > 0,
"the apprentice-match engine reacts to the new review",
);
await beatLog.log("mentor-apprentice-match", "rating yourself 'Again' on the at-risk skill created a real apprentice need; the real matching engine scores the mentor pool honestly rather than fabricating a match", page);
await sleep(1200);
// --- Health Post: WHO-IMCI triage classification + case-relay referral ---
await backHome(page);
await openTile(page, "Health Post");
await page.getByTestId("triage-age-input").fill("24");
await page.getByTestId("triage-hasCough-yes").click();
await page.getByTestId("triage-breathsPerMinute-input").fill("45");
await page.getByTestId("triage-chestIndrawing-no").click();
await page.getByTestId("triage-stridorWhenCalm-no").click();
await page.getByTestId("triage-hasDiarrhea-yes").click();
await page.getByTestId("triage-durationDays-input").fill("3");
await page.getByTestId("triage-bloodInStool-no").click();
await page.getByTestId("triage-restlessOrIrritable-no").click();
await page.getByTestId("triage-sunkenEyes-no").click();
await page.getByTestId("triage-ableToDrink-select").selectOption("normal");
await page.getByTestId("triage-skinPinch-select").selectOption("immediate");
await page.getByTestId("triage-hasFever-no").click();
await page.getByTestId("triage-submit").click();
await page.getByTestId("triage-result").waitFor({ state: "visible" });
const urgency = (await page.getByTestId("triage-urgency").textContent())?.trim();
await beatLog.log("healthpost-triage", `real WHO-IMCI classification from a full exam: "${urgency}"`, page);
await sleep(1200);
await page.getByTestId("triage-send-referral").click();
await page.getByTestId("triage-referral-sent").waitFor({ state: "visible" });
await beatLog.log("healthpost-send-to-clinician", "the referral-eligible result's real 'Send to clinician' button posted a signed healthpost.referral event to the clinician queue", page);
await sleep(1200);
// --- Light Clock: manual sleep/wake log ---
// This headless browser has no real motion-sensor hardware, but
// Chromium's DOM still defines a DeviceMotionEvent constructor, so
// requestMotionPermission() would otherwise resolve "granted" and the
// screen would land on its (sample-less) sensor-active panel instead
// of the manual-log fallback. Removing the constructor makes
// requestMotionPermission() honestly report "unavailable", which is
// what's actually true of this machine - it exercises the exact
// fallback contract startLightClockDataSource documents, through the
// real "Enable motion sensor" button, not a bypass.
await page.evaluate(() => {
delete window.DeviceMotionEvent;
});
await backHome(page);
await openTile(page, "Light Clock");
await page.getByTestId("lightclock-enable-sensor").click();
await page.getByTestId("lightclock-manual-hours").waitFor({ state: "visible" });
await beatLog.log("lightclock-manual-fallback", "no motion sensor available - the real sensor-first/manual-fallback contract switched to the manual log form", page);
await page.getByTestId("lightclock-manual-hours").fill("8");
await page.getByTestId("lightclock-manual-state").selectOption("asleep");
await page.getByTestId("lightclock-manual-add").click();
await page.getByTestId("lightclock-manual-entries").locator("li").first().waitFor({ state: "visible" });
await page.getByTestId("lightclock-manual-compute").click();
await beatLog.log("lightclock", "manual sleep/wake log entry added and circadian status computed", page);
await sleep(1200);
// --- The Climb: schedule inputs feeding the min-cost-flow engine ---
await backHome(page);
await openTile(page, "The Climb");
await page.getByTestId("theclimb-shaft-id").fill("shaft-1");
await page.getByTestId("theclimb-shaft-from").fill("D1");
await page.getByTestId("theclimb-shaft-to").fill("surface");
await page.getByTestId("theclimb-shaft-capacity").fill("20");
await page.getByTestId("theclimb-shaft-travel").fill("2");
await page.getByTestId("theclimb-shaft-add").click();
await page.getByTestId("theclimb-demand-id").fill("wave-1");
await page.getByTestId("theclimb-demand-sector").fill("D1");
await page.getByTestId("theclimb-demand-ready-period").fill("0");
await page.getByTestId("theclimb-demand-count").fill("15");
await page.getByTestId("theclimb-demand-add").click();
await page.getByTestId("theclimb-capacity-period").fill("0");
await page.getByTestId("theclimb-capacity-value").fill("20");
await page.getByTestId("theclimb-capacity-add").click();
await beatLog.log("theclimb", "real shaft/wave-demand/surface-capacity schedule fed to the min-cost-flow congestion engine", page);
await sleep(1200);
// =================================================================
// ACT III: "Who decides, underground" - quadratic votes and a
// commit-reveal lottery that still work when the network is cut, plus
// the shelter's own honest mood, decided in the open, not behind a
// severed server.
// =================================================================
await showActTitleCard(page, beatLog, {
label: "act3-title",
eyebrow: "Act III",
title: "Who Decides",
tagline: "Quadratic votes and a commit-reveal lottery that survive a severed network, the shelter's own honest mood - decided in the open, not behind a server.",
});
// --- Assembly (single-user half): seeded roster/proposal + create/vote + QV ballot ---
await openTile(page, "Assembly");
await page.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await beatLog.log("assembly-seeded", "demo-seeded roster (Aria, Kade) and an open proposal visible cold, no manual setup", page);
await sleep(1000);
await page.getByTestId("assembly-create-proposal-title-input").fill("Repave the common courtyard");
await page.getByTestId("assembly-create-proposal-description-input").fill("The paving stones have cracked and are a tripping hazard.");
await page.getByTestId("assembly-create-proposal-submit").click();
await page.getByText("Repave the common courtyard").waitFor({ state: "visible" });
const proposalArticle = page.locator("article", { hasText: "Repave the common courtyard" }).first();
const proposalId = (await proposalArticle.getAttribute("data-testid"))?.replace("assembly-proposal-", "");
await beatLog.log("assembly-create-proposal", "a new proposal was created through the real form", page);
await sleep(900);
await page.getByTestId("assembly-add-resident-name-input").fill("Nguyen");
await page.getByTestId("assembly-add-resident-submit").click();
await waitFor(
async () => (await page.locator('[data-testid^="assembly-roster-"]', { hasText: "Nguyen" }).count()) > 0,
"new resident appears on the roster",
);
await beatLog.log("assembly-add-resident", "a new resident was added to the roster through the real form", page);
await sleep(900);
if (proposalId) {
// GAP-A fix: the old direct-vote control (`assembly-vote-yes-<id>`) was
// removed from AssemblyScreen.tsx (dead CRDT path no tally ever read).
// The ONE real voting control left is the signed QV ballot
// (`assembly-qv-ballot-<choice>-<id>`), disabled unless the local
// account is enrolled on the roster. The "Nguyen" self-enrollment just
// above (`assembly-add-resident-submit`) enrolls THIS local account
// (addResident signs up the submitter, not an arbitrary third party),
// so the ballot button is now enabled and the still-current
// `assembly-vote-status-<id>` readout honestly reports "You voted Yes".
await page.getByTestId(`assembly-qv-ballot-yes-${proposalId}`).click();
await waitFor(
async () => ((await page.getByTestId(`assembly-vote-status-${proposalId}`).textContent()) ?? "").includes("You voted Yes"),
"QV ballot registers and the vote-status readout updates",
);
await beatLog.log("assembly-vote", "a real quadratic-vote ballot was cast on the new proposal by the newly self-enrolled resident - the live status readout confirms 'You voted Yes'", page);
await sleep(1000);
await waitFor(
async () => !((await page.getByTestId(`assembly-tally-yes-${proposalId}`).textContent()) ?? "").includes("Yes 0.00"),
"QV tally becomes non-zero after a real weighted ballot",
);
await beatLog.log("assembly-qv-tally", "the QV tally is no longer stuck at zero (Wave-1 fix: QV credit granted on the real roster/proposal lifecycle)", page);
await sleep(1200);
}
// --- Fair Draw: real commit-reveal-verify, commit published before any
// reveal, -> real wallet credit ---
await backHome(page);
await openTile(page, "Fair Draw");
await page.getByRole("button", { name: "Start Draw" }).click();
await page.getByTestId("reveal-draw-commit-hash").waitFor({ state: "visible" });
const commitHash = (await page.getByTestId("reveal-draw-commit-hash").textContent())?.trim();
await beatLog.log("fairdraw-commit", `a signed commit hash was published BEFORE any reveal - "${commitHash?.slice(0, 16)}..." - re-rolling after this point is auditable and rejected`, page);
await sleep(1400);
await page.getByRole("button", { name: "Reveal" }).click();
await page.getByTestId("reveal-draw-revealed").waitFor({ state: "visible" });
const winnerText = (await page.getByTestId("reveal-draw-winner").textContent())?.trim();
const badgeState = await page.getByTestId("reveal-draw-badge").getAttribute("data-state");
// Real audit-verdict badge (reveal-draw-integrity-badge): re-derived from
// validateReveal() over the whole signed Event Log - flips to "rejected"
// only for a duplicate/pre-commit reveal, never fabricated.
const integrityState = await page.getByTestId("reveal-draw-integrity-badge").getAttribute("data-state");
await beatLog.log("fairdraw-reveal", `real commit -> reveal -> verify cycle: "${winnerText}", badge state "${badgeState}", draw integrity "${integrityState}"`, page);
await sleep(1200);
await waitFor(async () => (await walletBalanceText(page)) !== undefined, "wallet balance chip present on fair-draw route");
await beatLog.log("fairdraw-wallet-live", "WalletCard balance updates live on the same route, no reload, from the real Fair Draw win", page);
await sleep(1000);
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByTestId("history-entry").first().waitFor({ state: "visible" });
await beatLog.log("fairdraw-history-row", "full transaction history now shows the real signed wallet.issue credit row", page);
await sleep(1000);
// --- Sky: memory-wall post + double-click double-post guard (GAP-20)
// + the real signed mood/morale pulse ---
// Already on the home route from the fairdraw-history-row step above -
// ShellLayout hides the "Back to home" link on "/" itself, so
// backHome() must NOT be called here.
await openTile(page, "Sky");
const skyMessage = "The sky over the Hollow turned amber tonight.";
await page.getByTestId("sky-memory-input").fill(skyMessage);
const countBefore = await page.getByTestId("sky-memory-list").locator("li").count().catch(() => 0);
await Promise.all([
page.getByTestId("sky-memory-submit").click(),
page.getByTestId("sky-memory-submit").click(),
]);
await waitFor(
async () => (await page.getByTestId("sky-memory-list").locator("li").count()) === countBefore + 1,
"exactly one memory-wall entry posted despite two synchronous clicks",
);
await beatLog.log("sky-post", "posted to the memory wall; a fast double-click produced exactly one entry, not two (GAP-20 fix)", page);
await sleep(1200);
await page.getByTestId("sky-mood-select").selectOption({ index: 1 });
await page.getByTestId("sky-mood-note").fill("Tense, but the water's clean again.");
await page.getByTestId("sky-mood-submit").click();
await waitFor(
async () => (await page.getByTestId("sky-mood-latest").count()) > 0,
"mood pulse posts and the latest-pulse readout updates",
);
await beatLog.log("sky-mood-pulse", "a real signed mood/morale pulse was posted - the shelter's honest mood is now visible, aggregated from real signed events", page);
await sleep(1200);
// =================================================================
// EPILOGUE: trust, made verifiable - with no server underground to
// keep anyone honest, every balance checks its own signature, and any
// resident can ship a new mini-app without a gatekeeper.
// =================================================================
await showActTitleCard(page, beatLog, {
label: "epilogue-title",
eyebrow: "Epilogue",
title: "Trust, Made Verifiable",
tagline: "No server underground to take on faith. Every balance checks its own signature - any resident can ship a new mini-app, no gatekeeper required.",
});
// --- Wallet signature verification (headline crypto feature) ---
await page.getByTestId("history-entry").first().waitFor({ state: "visible" });
const firstRow = page.getByTestId("history-entry").first();
const badge = firstRow.locator('[data-testid^="history-signature-badge-"]');
await waitFor(async () => ((await badge.textContent()) ?? "").trim() === "Verified", "signature badge resolves to Verified");
await beatLog.log("wallet-sig-verified", "independent verifyEntrySignature() re-check confirms the entry's Ed25519 signature is genuine", page);
await sleep(900);
const toggle = firstRow.locator('[data-testid^="history-expand-toggle-"]');
await toggle.click();
const detail = firstRow.locator('[data-testid^="history-signature-detail-"]');
await detail.waitFor({ state: "visible" });
await beatLog.log("wallet-sig-expanded", "raw Ed25519 signature + author public key bytes are directly inspectable, not just a claimed verification", page);
await sleep(1600);
await toggle.click();
// --- Upload a mini-app ---
// Already on the home route - showActTitleCard()'s post-card reset
// landed here, and no navigation has happened since. ShellLayout hides
// the "Back to home" link on "/" itself, so backHome() must NOT be
// called here.
await page.getByRole("button", { name: "+ Upload a mini-app" }).click();
await page.getByLabel("Mini-app name").fill("Counter Widget");
await page.getByLabel("Icon (emoji or data URI)").fill("\uD83D\uDD22");
await page.getByLabel("Entry point").fill("index.html");
await page.getByLabel("ledger.read").check();
await page.setInputFiles("#upload-html-file", {
name: "index.html",
mimeType: "text/html",
buffer: Buffer.from("<html><body><p>Counter Widget</p></body></html>"),
});
await beatLog.log("upload-form-filled", "real manifest form filled + a real HTML file attached via the real file input", page);
await sleep(900);
await page.getByRole("button", { name: "Upload mini-app" }).click();
await page.getByTestId("upload-success").waitFor({ state: "visible" });
await beatLog.log("upload-success", "the real uploadMiniapp() storage path accepted the package", page);
await sleep(900);
await page.getByRole("button", { name: "Go to home" }).click();
await page.getByRole("button", { name: "Counter Widget" }).waitFor({ state: "visible" });
await beatLog.log("upload-tile-appears", "the uploaded mini-app now appears as a real tile on the home grid", page);
await sleep(1400);
await beatLog.closeCaption();
} finally {
await context.tracing.stop({ path: resolve(videoDir, "trace.zip") });
await context.close();
await browser.close();
}
const videoPath = await page.video().path();
console.log(`Scene 1 recorded: ${videoPath} (${((Date.now() - sceneStartRef.value) / 1000).toFixed(1)}s wall-clock)`);
const enhancedPath = await addMotionGraphics(videoDir);
return { videoPath: enhancedPath, rawVideoPath: videoPath, beats: beatLog.beats };
}
// Runs the real Playwright trace this scene just recorded through
// playwright-recast: a synthetic cursor + click ripples at every real
// click/selectOption action, and an auto-zoom onto the exact element a
// fill/type/click action targeted, timed to that action's own real
// duration - all derived from the trace, never hand-authored keyframes.
// `.subtitlesFromTrace()` is required by `.autoZoom()` (confirmed by
// actually running this pipeline - it throws "autoZoom() requires
// subtitles() first" otherwise); it now also carries real captions, since
// `beatLog.log()` writes each beat's narration into the trace via
// `context.tracing.group()` using recast's own marker convention.
//
// Motion-graphics pass (see DEMO_VIDEO_NOTES.md for the research this is
// drawn from):
// 1. Kinetic-typography intro/outro title cards, crossfaded in/out -
// the "bold statement before the product" cold-open hook reverse-
// engineered from Linear/Apple/Raycast launch films.
// 2. Real captions (above) with a restyled, high-contrast caption box
// instead of the library default - legible on a 414px-wide pane and
// consistent with the app's own accent blue (#1677FF).
// 3. A short self-synthesized ambient pad via `.backgroundMusic()` - no
// voiceover (no TTS key in this environment), so sound design leans
// on music + pacing instead, at a volume low enough not to compete
// with the captions.
async function addMotionGraphics(videoDir) {
console.log("\nAdding motion graphics (cursor, click ripples, auto-zoom, intro/outro, captions, music) via playwright-recast...");
const outputPath = resolve(videoDir, "main-enhanced.mp4");
const assetsDir = resolve(VIDEO_TMP_DIR, "assets");
const introPath = await renderTitleCard({
html: titleCardHtml({
eyebrow: "One shelter in the Hollow, tonight",
title: "Who do you trust when the water turns bad?",
tagline: "4,200 residents in this shelter, cut off from the surface. No server. No central login.",
}),
size: MAIN_VIDEO_SIZE,
durationMs: 2600,
outDir: resolve(assetsDir, "intro"),
});
const outroPath = await renderTitleCard({
html: titleCardHtml({
eyebrow: "Built in 36 hours",
title: "The Commons",
tagline: "13 mini-apps for life underground. 1 wallet. Every balance a signed, replayable event - until the climb back to the surface.",
}),
size: MAIN_VIDEO_SIZE,
durationMs: 2600,
outDir: resolve(assetsDir, "outro"),
});
const musicPath = generateAmbientTrack(resolve(assetsDir, "ambient.mp3"), 26);
await Recast.from(videoDir)
.parse()
.speedUp({ duringIdle: 3.0, duringUserAction: 1.0, duringNetworkWait: 2.0, duringNavigation: 2.0, minSegmentDuration: 500 })
.subtitlesFromTrace()
// Todo 7 (promo-video-redesign plan): auto-zoom is pinned to level 1.0
// on every action type (no click/input zoom-in, idle already 1.0).
// `autoZoom()` renders through ffmpeg `zoompan`, whose visible region
// is `iw/z x ih/z` of the SOURCE frame panned toward the interaction
// point (see render/zoom-expression.js: `x=cx*iw-iw/z/2`), so any z>1
// HARD-CROPS the phone UI - at a click/input beat near an edge it cut
// the opposite edge of the 414px-wide app (confirmed by frame
// extraction: the home-grid's left+right columns and the `Upload a
// mini-app` button text were sliced off at ~t=39.8s and the 4th grid
// column + `View signature` labels at ~t=50s, both against uncropped
// reference screenshots in .omo/evidence/full-feature-demo/ proving
// the content was captured whole). The landscape composite below
// already fits the full phone into its frame region (scaled, never
// cropped - `overlay` centres a 444x960 phone in 1920x1080), so the
// ONLY crop source was this zoom; holding every level at 1.0 keeps the
// whole UI on screen at every beat. The stage stays (it owns the
// `subtitlesFromTrace()` -> zoom-marker contract and the `noZoom()`
// cues) but is now a non-cropping pass-through - `z=1.0` makes
// `buildZoomFilter()` emit a plain full-frame scale.
.autoZoom({ inputLevel: 1.0, clickLevel: 1.0, idleLevel: 1.0, centerBias: 0.3 })
// No `.cursorOverlay()` - this is a mobile touch-screen demo, not a
// desktop screencast, so there is no pointer to draw. `.clickEffect()`
// (tap ripple) is its own independent pipeline stage (confirmed in
// `dist/pipeline/pipeline.d.ts`) and survives untouched - the tap
// feedback stays even though the zoom-in is gone.
.clickEffect()
.intro({ path: introPath, fadeDuration: 600 })
.outro({ path: outroPath, fadeDuration: 600 })
// `volume: 0.55` is this pipeline's ONLY ambient-loudness knob (see
// the fix note on `generateAmbientTrack()` above) - raised from the
// old 0.1, which was stacking on top of that function's own (now
// removed) internal attenuation and rendering the track at
// noise-floor level (-69.5dB mean/-58.5dB max measured in the
// previously shipped video). A first re-render at 0.4 measured
// -40.3dB mean - audible but too close to the "not silent" floor for
// comfort - so this was raised once more to land with real margin
// above that threshold.
.backgroundMusic({ path: musicPath, volume: 0.55, ducking: false, fadeOutMs: 2500, loop: true })
.render({
format: "mp4",
resolution: MAIN_VIDEO_SIZE,
fps: 30,
// `burnSubtitles` defaults to false (confirmed in
// `dist/render/renderer.js`) - without it, `subtitlesFromTrace()`'s
// cues are parsed but never drawn, which is exactly what an earlier
// test render of this change showed (real captions in the trace,
// nothing burned into the frames).
burnSubtitles: true,
// `fontSize` is calibrated against the library's internal
// 1080p-widescreen reference canvas - on this project's narrow
// 828px-wide portrait canvas the library's own default ran text off
// the right edge uncut (confirmed by an earlier test render's
// extracted frames), so it's scaled down to roughly the 0.43x width
// ratio (828/1920) instead of reused verbatim. `chunkOptions` was
// tried and reverted: it splits one beat's full caption into many
// ~17-char fragments each on its own short timer, which flashed
// past before a viewer could read it (confirmed by frame extraction
// showing a single orphaned word per frame) - `wrapStyle: 'smart'`
// alone lets libass wrap the full line across 2-3 lines and hold it
// for the beat's whole on-screen window instead.
subtitleStyle: {
fontSize: 30,
primaryColor: "#F5F7FF",
backgroundColor: "#05070D",
backgroundOpacity: 0.82,
padding: 16,
position: "bottom",
marginVertical: 70,
marginHorizontal: 36,
bold: true,
wrapStyle: "smart",
},
})
.toFile(outputPath);
console.log(`Motion-graphics pass written: ${outputPath}`);
return outputPath;
}
// =======================================================================
// SCENE 2: Assembly real-screen WebRTC partition-and-heal, two devices
// =======================================================================
async function recordAssemblySyncScene() {
console.log("\n=== Scene 2: Assembly real-screen sync (two isolated devices) ===");
const videoDirA = resolve(VIDEO_TMP_DIR, "assembly-deviceA");
const videoDirB = resolve(VIDEO_TMP_DIR, "assembly-deviceB");
// Same stale-recording hazard as recordMainScene() above - wipe any
// leftover webm from a prior crashed attempt before recording.
rmSync(videoDirA, { recursive: true, force: true });
rmSync(videoDirB, { recursive: true, force: true });
mkdirSync(videoDirA, { recursive: true });
mkdirSync(videoDirB, { recursive: true });
const sig = await startSignaling();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const ctxA = await browser.newContext({ viewport: PANE, recordVideo: { dir: videoDirA, size: PANE } });
const ctxB = await browser.newContext({ viewport: PANE, recordVideo: { dir: videoDirB, size: PANE } });
const sigState = { blockSig: false };
for (const ctx of [ctxA, ctxB]) {
await ctx.routeWebSocket(new RegExp(`127\\.0\\.0\\.1:${SIG_PORT}`), (ws) => {
if (sigState.blockSig) {
ws.close();
return;
}
ws.connectToServer();
});
}
const pageA = await ctxA.newPage();
const pageB = await ctxB.newPage();
const sceneStartRef = { value: Date.now() };
const beatLog = makeBeatLog("assembly-sync", sceneStartRef);
const room = `full-demo-${Math.random().toString(36).slice(2)}`;
const ASSEMBLY_URL = `${APP_URL}/miniapp/assembly`;
const ENGINE_MODULE_URL = `${APP_URL}/src/miniapps/assembly/useAssemblyEngine.ts`;
const ASSEMBLY_LIB_URL = `${APP_URL}/src/lib/assembly.ts`;
async function dualBeat(label, note) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
const shotA = resolve(EVIDENCE_DIR, `assembly-sync-${String(beatLog.beats.length).padStart(2, "0")}-deviceA-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
const shotB = resolve(EVIDENCE_DIR, `assembly-sync-${String(beatLog.beats.length).padStart(2, "0")}-deviceB-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await pageA.screenshot({ path: shotA }).catch(() => {});
await pageB.screenshot({ path: shotB }).catch(() => {});
beatLog.beats.push({ scene: "assembly-sync", label, note, sceneRelativeMs, screenshot: shotA, screenshotDeviceB: shotB });
console.log(`[assembly-sync +${(sceneRelativeMs / 1000).toFixed(1)}s] ${label}: ${note}`);
}
async function setSyncTransportOverride(page) {
await page.evaluate(
async ({ moduleUrl, room, signaling }) => {
const mod = await import(/* @vite-ignore */ moduleUrl);
mod.setAssemblySyncTransportOverrideForTesting({
room,
signaling: [signaling],
peerOpts: { config: { iceServers: [] } },
});
},
{ moduleUrl: ENGINE_MODULE_URL, room, signaling: SIG },
);
}
async function readPeerCount(page) {
const el = page.getByTestId("assembly-peer-count");
if ((await el.count()) === 0) return 0;
const text = (await el.textContent()) ?? "";
const match = text.match(/Connected to (\d+)/);
return match ? Number(match[1]) : 0;
}
try {
await pageA.goto(ASSEMBLY_URL, { waitUntil: "load" });
await pageB.goto(ASSEMBLY_URL, { waitUntil: "load" });
await pageA.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await pageB.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await setSyncTransportOverride(pageA);
await setSyncTransportOverride(pageB);
await dualBeat("boot", "two genuinely isolated devices (separate storage origins) open the real Assembly screen; sync is honestly off by default");
// PACING: this scene carries NO captions (makeBeatLog here has no trace
// context), so each hold is a pure "glance at the UI state" beat, not a
// caption-reading window. The pre-fix holds (1000/1200/1400/1400/1500+
// 1500ms, all at 1x - this scene is never sped up) left the final ~10s
// of the video dragging, with freezedetect-confirmed near-static
// stretches of 3.1s (~t65.4) and 2.1s (~t68.6) and a frozen ~3s
// converged tail. Tightened so the connect->prove->partition->heal
// story keeps moving while each state stays on screen long enough to
// read at a glance.
await sleep(650);
// 1. Connect through the real UI toggle.
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await readPeerCount(pageA)) >= 1, "device A connects");
await waitFor(async () => (await readPeerCount(pageB)) >= 1, "device B connects");
await dualBeat("connected", "real WebRTC transport connected over a local signaling server - both devices see a live peer count");
await sleep(600);
// 2. Prove the transport genuinely carries data: a proposal seeded on
// A (via the real putProposal production function) arrives on B.
await pageA.evaluate(
async ({ engineUrl, libUrl, proposal }) => {
const engineMod = await import(/* @vite-ignore */ engineUrl);
const libMod = await import(/* @vite-ignore */ libUrl);
const { assembly } = engineMod.getAssemblyEngineForTesting(engineMod.DEFAULT_ASSEMBLY_DB_NAME);
libMod.putProposal(assembly, proposal);
},
{
engineUrl: ENGINE_MODULE_URL,
libUrl: ASSEMBLY_LIB_URL,
proposal: {
id: "sync-demo-prop",
title: "Install solar lanterns on the east path",
description: "Seeded on device A only - must arrive on device B purely over WebRTC.",
authorId: "seed",
createdAt: Date.now(),
status: "open",
},
},
);
await waitFor(
async () => (await pageB.getByTestId("assembly-proposal-sync-demo-prop").count()) > 0,
"device B receives device A's proposal over real WebRTC",
);
await dualBeat("transport-proven", "a proposal created on device A arrived on device B purely over the real WebRTC transport - B's own IndexedDB never had it");
await sleep(750);
// GAP-A fix: the old direct-vote control (`assembly-vote-yes-<id>`/
// `assembly-vote-no-<id>`) was removed from AssemblyScreen.tsx. The real
// QV ballot button stays disabled until the local account is enrolled on
// the roster, so each device enrolls itself through the real "Add me to
// roster" form before casting a ballot - this also exercises the same
// roster-entry CRDT replication the proposal-sync beat above just proved,
// now for each device's own identity while still connected.
await pageA.getByTestId("assembly-add-resident-name-input").fill("Device A resident");
await pageA.getByTestId("assembly-add-resident-submit").click();
await pageB.getByTestId("assembly-add-resident-name-input").fill("Device B resident");
await pageB.getByTestId("assembly-add-resident-submit").click();
await waitFor(
async () => !(await pageA.getByTestId("assembly-qv-ballot-yes-sync-demo-prop").isDisabled()),
"device A's QV ballot control becomes enabled after self-enrollment",
);
await waitFor(
async () => !(await pageB.getByTestId("assembly-qv-ballot-no-sync-demo-prop").isDisabled()),
"device B's QV ballot control becomes enabled after self-enrollment",
);
await dualBeat("enrolled", "each device enrolled its own identity on the roster through the real 'Add me to roster' form, enabling its own real QV ballot");
await sleep(600);
// 3. Partition: toggle sync OFF on both sides (real teardown) + block
// signaling + go offline, as defense in depth.
sigState.blockSig = true;
await ctxA.setOffline(true);
await ctxB.setOffline(true);
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await pageA.getByTestId("assembly-peer-count").count()) === 0, "device A's peer indicator disappears");
await waitFor(async () => (await pageB.getByTestId("assembly-peer-count").count()) === 0, "device B's peer indicator disappears");
await pageA.getByTestId(`assembly-qv-ballot-yes-sync-demo-prop`).click();
await pageB.getByTestId(`assembly-qv-ballot-no-sync-demo-prop`).click();
await sleep(500);
const aSeesB = await pageA.getByTestId("assembly-vote-status-sync-demo-prop").textContent();
const bSeesA = await pageB.getByTestId("assembly-vote-status-sync-demo-prop").textContent();
await dualBeat(
"partitioned",
`both devices genuinely isolated (peer count 0, network offline, signaling blocked) - independent votes cast (A sees "${aSeesB?.trim()}", B sees "${bSeesA?.trim()}")`,
);
await sleep(750);
// 4. Heal: restore network + signaling, toggle sync back on, converge.
sigState.blockSig = false;
await ctxA.setOffline(false);
await ctxB.setOffline(false);
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await readPeerCount(pageA)) >= 1, "device A reconnects");
await waitFor(async () => (await readPeerCount(pageB)) >= 1, "device B reconnects");
await sleep(600);
await dualBeat("healed-reconnected", "both devices reconnected after the partition - real WebrtcProvider re-established");
// Final converged state: held ~1.0s (within the 0.6-1.4s end-hold
// guideline) then the composite fades it to black (see
// compositeSideBySide) so the whole film closes on a graceful fade
// rather than a hard stop on a frozen frame.
await sleep(1000);
} finally {
await ctxA.close();
await ctxB.close();
await browser.close();
sig.kill("SIGKILL");
}
const videoPathA = await pageA.video().path();
const videoPathB = await pageB.video().path();
console.log(`Scene 2 recorded: deviceA=${videoPathA} deviceB=${videoPathB} (${((Date.now() - sceneStartRef.value) / 1000).toFixed(1)}s wall-clock)`);
return { videoPathA, videoPathB, beats: beatLog.beats };
}
// Composites the two real device panes side-by-side, THEN letterboxes
// that 828x896 (near-square) stack directly into the final 1920x1080
// canvas itself, rather than leaving that fit to `concatToFinal()`'s
// generic per-segment `scale+pad` step. F3's real manual QA (pixel-strip
// crops at y=0 and y=1080) found that generic step left ZERO top/bottom
// margin here - clipped BALANCE badge, clipped textarea resize-handle -
// while the main scene correctly got margins on all sides. Root cause:
// `concatToFinal()`'s `scale=...force_original_aspect_ratio=decrease`
// picks the limiting dimension by actual aspect ratio, and 828x896's
// ratio happens to fit 1920x1080's height almost exactly on the nose, so
// its own "decrease" fit landed on zero vertical pad - not a bug in that
// shared step (which is correct for an arbitrary aspect ratio), but a
// degenerate case for this specific one. Scaling the stack to
// `LANDSCAPE_PHONE_HEIGHT` (960, the same deliberate-margin height the
// main scene's own phone gets via `compositeLandscapeWithMargins()`) and
// padding to the full canvas here bakes in real margin on every side
// before `concatToFinal()` ever runs, making its generic fit a no-op for
// this segment too - exactly how it already behaves for the main scene.
function compositeSideBySide(videoPathA, videoPathB, outPath) {
mkdirSync(dirname(outPath), { recursive: true });
// PACING: this scene is concatenated straight after the dark "The Commons"
// outro card, and each device page boots white (a blank React mount) for
// ~0.4s - so the pre-fix hard concat cut dark-card -> pure-white-boot,
// a bright blank pop. A 0.5s fade-IN from black here lands the scene with
// decelerating motion out of the (near-black) outro and masks the white
// boot entirely. A 0.6s fade-OUT at the tail closes the whole film on a
// graceful dim-to-black instead of a hard stop on the frozen converged
// frame. The fade is baked into this 1920x1080 composite, so it survives
// `concatToFinal()`'s (now no-op) re-scale/pad of this segment.
const durA = ffmpegDurationSeconds(videoPathA);
const durB = ffmpegDurationSeconds(videoPathB);
const dur = Math.min(durA ?? 10, durB ?? 10); // hstack ends at the shorter input
const fadeOutStart = Math.max(0, dur - 0.6);
const filter =
`[0:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=25[v0];` +
`[1:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=25[v1];` +
"[v0][v1]hstack=inputs=2[stacked];" +
`[stacked]scale=-2:${LANDSCAPE_PHONE_HEIGHT},pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,` +
`fade=t=in:st=0:d=0.5,fade=t=out:st=${fadeOutStart.toFixed(2)}:d=0.6[v]`;
execFileSync(FFMPEG_BIN, [
"-y", "-i", videoPathA, "-i", videoPathB,
"-filter_complex", filter, "-map", "[v]",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
outPath,
], { stdio: ["ignore", "pipe", "pipe"] });
}
// ---------------------------------------------------------------------
// Todo 2 (promo-video-redesign plan): 16:9 landscape compositing with
// real-data margins. Matte's own documented guidance for a single-device
// capture is to center it with generous padding, or use the extra space
// for text callouts - this pads the mobile-styled portrait recording
// (828x1792, `MAIN_VIDEO_SIZE` - the already motion-graphics-enhanced
// output of `addMotionGraphics()`, todo 1's no-cursor-dot/ripple+zoom
// treatment fully baked in) onto a 1920x1080 canvas, phone centered with
// ~738px of padding either side, filled with real context instead of
// plain black bars:
// - LEFT margin: `HOLLOW_DEMO_FIXTURE`'s own starting-configuration
// numbers (imported above, never hand-retyped), the exact
// population/resource-pool/baseline-reading values the on-camera
// "Load Hollow demo" click actually seeds.
// - RIGHT margin: verbatim substrings of this same script's own
// `beatLog.log()` narration (`WAVE1_FIX_CALLOUTS` below cites the
// exact beat label each line came from) - the real Wave-1 fixes this
// tour demonstrates, copied, never paraphrased or invented.
// No `drawtext` filter is used (confirmed absent from the resolved
// ffmpeg-static build per the capability note above `FFMPEG_BIN`); both
// margins are instead rendered as real text by a throwaway Chromium page
// (same `page.screenshot()` mechanism `renderTitleCard()` already uses)
// into one background PNG, then the phone video is laid on top of it with
// the confirmed-present `overlay` filter.
// ---------------------------------------------------------------------
const LANDSCAPE_W = FINAL_W;
const LANDSCAPE_H = FINAL_H;
const LANDSCAPE_PHONE_HEIGHT = 960; // leaves 60px top/bottom padding on a 1080-tall canvas
const WAVE1_FIX_CALLOUTS = [
{ beat: "waterwatch-no-false-alert", text: "flat 2nd reading (7.0 -> 7.05) did NOT fire a false alert" },
{ beat: "waterwatch-localization", text: "real pipe-graph leak localization named a suspected origin node" },
{ beat: "farms-forecast", text: "real GDD + LP optimizer forecast (1 temp reading, 1 plot, 1 crop) -> 200.00 kg" },
{ beat: "housing-run-cycle", text: "the resident-facing 'Run assignment cycle' button recorded a new real housing.assignment cycle" },
{ beat: "assembly-qv-tally", text: "the QV tally is no longer stuck at zero (Wave-1 fix: QV credit granted on the real roster/proposal lifecycle)" },
{ beat: "sky-post", text: "a fast double-click produced exactly one entry, not two (GAP-20 fix)" },
];
function landscapeMarginBackgroundHtml() {
const f = HOLLOW_DEMO_FIXTURE;
const statLines = [
`Population: ${f.population.toLocaleString()}`,
`Power pool: ${f.resources.power}`,
`Water pool: ${f.resources.water}`,
`Food pool: ${f.resources.food}`,
`Cooling pool: ${f.resources.cooling}`,
...f.baselines.map((b) => `${b.channel}: ${b.value}`),
];
const fixLines = WAVE1_FIX_CALLOUTS.map((c) => c.text);
const css = `
* { margin:0; padding:0; box-sizing:border-box; }
html,body { width:100%; height:100%; background:#05070d; overflow:hidden; font-family: -apple-system, 'Helvetica Neue', Arial, sans-serif; }
.panel { position:absolute; top:0; bottom:0; width:700px; padding:56px 44px; }
.panel.left { left:0; }
.panel.right { right:0; text-align:right; }
.heading { color:#4f9dff; letter-spacing:0.16em; font-size:18px; font-weight:700; text-transform:uppercase; margin-bottom:24px; }
.line { font-size:21px; line-height:1.6; color:#c3cde3; margin-bottom:11px; }
`;
const leftItems = statLines.map((l) => `<div class="line">${l}</div>`).join("\n");
const rightItems = fixLines.map((l) => `<div class="line">${l}</div>`).join("\n");
return `<!doctype html><html><head><style>${css}</style></head>
<body>
<div class="panel left">
<div class="heading">The Hollow &middot; live seed data</div>
${leftItems}
</div>
<div class="panel right">
<div class="heading">Wave-1 fixes, shown live</div>
${rightItems}
</div>
</body></html>`;
}
async function renderLandscapeMarginBackground(outPath) {
mkdirSync(dirname(outPath), { recursive: true });
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: LANDSCAPE_W, height: LANDSCAPE_H } });
await page.setContent(landscapeMarginBackgroundHtml(), { waitUntil: "load" });
await page.screenshot({ path: outPath });
await browser.close();
return outPath;
}
// Pads the already motion-graphics-enhanced main scene video onto the
// 1920x1080 landscape canvas: phone scaled to `LANDSCAPE_PHONE_HEIGHT`
// (aspect-preserved - `scale=-2:...` keeps the real 414x896 ratio exactly,
// just at a lower pixel height) and centered over the real-data background
// via `overlay`'s own `(W-w)/2`/`(H-h)/2` expressions, so there is no
// manual padding arithmetic to get wrong and nothing of the phone UI is
// cropped. Runs after `addMotionGraphics()` (recast render, todo 1's
// treatment) and before `concatToFinal()`, per the plan's own ordering.
async function compositeLandscapeWithMargins(mainVideoPath) {
console.log("\nCompositing main scene into a 16:9 landscape frame with real-data margins...");
const assetsDir = resolve(VIDEO_TMP_DIR, "assets");
const backgroundPath = resolve(assetsDir, "landscape-margins.png");
await renderLandscapeMarginBackground(backgroundPath);
const outPath = resolve(VIDEO_TMP_DIR, "main-landscape.mp4");
const hasAudio = (() => {
try {
execFileSync(FFMPEG_BIN, ["-i", mainVideoPath, "-vn", "-c:a", "copy", "-f", "null", "-"], { stdio: ["ignore", "pipe", "pipe"] });
return true;
} catch {
return false;
}
})();
const vfilter = `[1:v]scale=-2:${LANDSCAPE_PHONE_HEIGHT}[phone];[0:v][phone]overlay=(W-w)/2:(H-h)/2:shortest=1[v]`;
const args = [
"-y",
"-loop", "1", "-framerate", "30", "-i", backgroundPath,
"-i", mainVideoPath,
"-filter_complex", vfilter,
"-map", "[v]",
];
if (hasAudio) args.push("-map", "1:a");
args.push("-c:v", "libx264", "-pix_fmt", "yuv420p", "-shortest");
if (hasAudio) args.push("-c:a", "aac", "-b:a", "128k");
args.push(outPath);
execFileSync(FFMPEG_BIN, args, { stdio: ["ignore", "pipe", "pipe"] });
console.log(`Landscape composite written: ${outPath}`);
return outPath;
}
function concatToFinal(mainVideoPath, assemblyCompositePath) {
mkdirSync(dirname(FINAL_VIDEO), { recursive: true });
// mainVideoPath may carry a real audio track (intro/outro/background
// music muxed in by addMotionGraphics()); assemblyCompositePath never
// does. concat requires matching stream counts per segment, so a
// silent pad stands in for segment 2's missing audio rather than
// dropping audio for both (which silently lost it before, and - the
// real bug this fixes - a `-map "[v]"`-only map with an unreferenced
// audio stream still present on input 0 was truncating the output's
// duration well short of its real video length).
// A single filter_complex mixing a real [0:a] stream with a
// filter-graph-generated anullsrc pad truncated this video's duration
// hard (confirmed by direct testing: per-stream ffprobe showed both
// main-enhanced streams genuinely ~43.5s, but that one-pass concat
// produced a ~26s output) - so this does it as three separately
// verifiable passes instead: video-only concat (the pattern already
// proven to work), a real silent file concatenated onto a real
// extracted copy of the main audio (not a filter-graph source node),
// then a final mux.
const assemblyDuration = ffmpegDurationSeconds(assemblyCompositePath) ?? 10;
const tmpVideo = resolve(VIDEO_TMP_DIR, "final-video-only.mp4");
const tmpSilence = resolve(VIDEO_TMP_DIR, "silence.m4a");
const tmpMainAudio = resolve(VIDEO_TMP_DIR, "main-audio.m4a");
const tmpAudio = resolve(VIDEO_TMP_DIR, "padded-audio.m4a");
const tmpAudioList = resolve(VIDEO_TMP_DIR, "audio-concat-list.txt");
const vfilter =
`[0:v]scale=${FINAL_W}:${FINAL_H}:force_original_aspect_ratio=decrease,pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=25[v0];` +
`[1:v]scale=${FINAL_W}:${FINAL_H}:force_original_aspect_ratio=decrease,pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=25[v1];` +
"[v0][v1]concat=n=2:v=1:a=0[v]";
execFileSync(FFMPEG_BIN, [
"-y", "-i", mainVideoPath, "-i", assemblyCompositePath,
"-filter_complex", vfilter, "-map", "[v]",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
tmpVideo,
], { stdio: ["ignore", "pipe", "pipe"] });
const hasAudio = (() => {
try {
execFileSync(FFMPEG_BIN, ["-i", mainVideoPath, "-vn", "-c:a", "copy", "-f", "null", "-"], { stdio: ["ignore", "pipe", "pipe"] });
return true;
} catch {
return false;
}
})();
if (hasAudio) {
execFileSync(FFMPEG_BIN, ["-y", "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", "-t", String(assemblyDuration), "-c:a", "aac", tmpSilence], { stdio: ["ignore", "pipe", "pipe"] });
execFileSync(FFMPEG_BIN, ["-y", "-i", mainVideoPath, "-vn", "-c:a", "aac", tmpMainAudio], { stdio: ["ignore", "pipe", "pipe"] });
writeFileSync(tmpAudioList, `file '${tmpMainAudio}'\nfile '${tmpSilence}'\n`);
execFileSync(FFMPEG_BIN, ["-y", "-f", "concat", "-safe", "0", "-i", tmpAudioList, "-c:a", "aac", tmpAudio], { stdio: ["ignore", "pipe", "pipe"] });
execFileSync(FFMPEG_BIN, [
"-y", "-i", tmpVideo, "-i", tmpAudio,
"-c:v", "copy", "-c:a", "aac", "-b:a", "128k", "-shortest", "-movflags", "+faststart",
FINAL_VIDEO,
], { stdio: ["ignore", "pipe", "pipe"] });
} else {
execFileSync(FFMPEG_BIN, ["-y", "-i", tmpVideo, "-c:v", "copy", "-movflags", "+faststart", FINAL_VIDEO], { stdio: ["ignore", "pipe", "pipe"] });
}
}
function ffmpegDurationSeconds(videoPath) {
try {
execFileSync(FFMPEG_BIN, ["-i", videoPath], { stdio: ["ignore", "pipe", "pipe"] });
return null;
} catch (e) {
const stderr = String(e.stderr ?? "");
const match = stderr.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (!match) return null;
const [, h, m, s] = match;
return Number(h) * 3600 + Number(m) * 60 + Number(s);
}
}
async function main() {
mkdirSync(EVIDENCE_DIR, { recursive: true });
const onlyScene = process.argv.includes("--main-only")
? "main"
: process.argv.includes("--assembly-only")
? "assembly"
: undefined;
const vite = await startVite();
let mainScene;
let assemblyScene;
try {
if (onlyScene !== "assembly") {
mainScene = await recordMainScene();
// Todo 2 (promo-video-redesign plan): pad the recast-enhanced
// portrait recording onto the final 16:9 landscape canvas with
// real-data margins, right after the recast render and before
// final concat.
mainScene.videoPath = await compositeLandscapeWithMargins(mainScene.videoPath);
}
if (onlyScene !== "main") assemblyScene = await recordAssemblySyncScene();
} finally {
await vite.close();
}
if (onlyScene) {
console.log(`\n===== DEBUG RUN (${onlyScene} only) DONE, skipping composite/concat =====`);
if (mainScene) console.log(`main video: ${mainScene.videoPath}, beats: ${mainScene.beats.length}`);
if (assemblyScene) console.log(`assembly videos: ${assemblyScene.videoPathA} / ${assemblyScene.videoPathB}, beats: ${assemblyScene.beats.length}`);
return;
}
console.log("\nCompositing Assembly two-device scene side-by-side...");
const assemblyComposite = resolve(VIDEO_TMP_DIR, "assembly-sync-composite.mp4");
compositeSideBySide(assemblyScene.videoPathA, assemblyScene.videoPathB, assemblyComposite);
console.log("Concatenating main scene + Assembly sync scene into the final video...");
concatToFinal(mainScene.videoPath, assemblyComposite);
const finalDuration = ffmpegDurationSeconds(FINAL_VIDEO);
const allBeats = [...mainScene.beats, ...assemblyScene.beats];
writeFileSync(
resolve(EVIDENCE_DIR, "beat-log.json"),
JSON.stringify(
{
recordedAt: new Date().toISOString(),
finalVideoPath: FINAL_VIDEO,
durationSeconds: finalDuration,
mainSceneBeatCount: mainScene.beats.length,
assemblySceneBeatCount: assemblyScene.beats.length,
beats: allBeats,
},
null,
2,
),
);
console.log(`\n===== DONE =====`);
console.log(`Final video: ${FINAL_VIDEO}`);
console.log(`Duration: ${finalDuration ? finalDuration.toFixed(1) + "s" : "unknown"}`);
console.log(`Total beats captured: ${allBeats.length}`);
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});