diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 518e222..8b63be6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -21,6 +21,8 @@ jobs:
- run: npx playwright install --with-deps chromium
- run: npm run test:beta
- run: npm run test:renderer
+ - run: npm run test:hybrid
+ - run: npm run test:prepared
- run: npm run test:browser
website:
name: Website validation
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3750737..8749da4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,26 @@
# Changelog
+## Unreleased
+
+Hybrid scenes: code-rendered elements composited with filmed or generated footage. See [hybrid scenes](docs/hybrid-scenes.md).
+
+- Add derived assets: a matte, depth map, normals, track, camera path or environment is pinned to the hash of the footage it was computed from. A replaced take, a second asset for one role, or a derived video with a different frame count is refused. `asset-add` gains `--role`, `--of` and depth-encoding flags; JSON `data` assets are accepted.
+- Add `editableframes/plate`: corner-pin homographies, track and camera-path sampling, frame-rate conform and cadence, depth encodings, plate measurements (levels, light direction, noise), seeded grain, object-id colours and shutter sampling.
+- Add `editableframes/three-plate`: depth occlusion by the footage, matte hold-out, lighting from the footage, camera-path replay, a shadow catcher and clay/depth/normal/id/matte passes.
+- Add optional `mediaInfo` and `derived` renderer services, declared control passes (`passes`, `clock.pass`) and `render --pass`.
+- Add shutter motion blur at export: `render --motion-blur ANGLE [--samples N]`.
+- Add `init --hybrid`, a starter with a synthetic plate, and `npm run test:hybrid`.
+- Document a trial of the hybrid helpers on generated footage, and how to conform mattes and depth maps made by other tools.
+- The hybrid starter lights its can from the footage at environment intensity 1 (was 1.5, set while half of the panorama was empty), with aluminium lids at aluminium's reflectance. Measured against real cans in generated plates.
+- Fix video frames looked up one frame early: media preparation read frame times as six-decimal seconds, so frame 1 of a 24 fps clip (0.041667) seemed to start after 1/24 s and a third of the frames of any 24 or 30 fps clip showed their predecessor. Frame times are now exact ticks in the stream's time base.
+- Fix MP4 and MOV exports coming out 10–13 levels darker than the frames drawn (128 became 115), footage included: the encoder converted sRGB to the BT.709 camera curve, which players do not undo. Exports now keep the drawn values (BT.709 matrix, limited range, transfer tagged as sRGB).
+- Fix footage tagged with BT.709 primaries and transfer (most camera footage) drawing darker than its values, and mattes and depth maps tagged the same way drawing changed data: decoded frames carried colour chunks the browser applied. Frames are now decoded without them.
+- Fix MOV export of a scene with no transparency, which failed extracting an alpha channel the frames did not have.
+- Document a trial of the hybrid helpers on filmed footage.
+- Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected.
+
+Runtime files changed, so existing projects need their normal `rebind`.
+
## 0.1.0-beta.1 — 2026-10-07
First beta for trusted local-code projects. No remote publication is implied.
diff --git a/README.md b/README.md
index e295ea8..e9b31cb 100644
--- a/README.md
+++ b/README.md
@@ -76,6 +76,7 @@ These are original code-built studies and previews, not copies of other creators
- **Give each clip the right controls.** Expose a camera for a 3D scene, colors for a title, or media timing for an embedded speaker. Panels support conditional fields, presets and numeric macros.
- **Let people and agents refine the same work.** Stable anchors, validated changes, saved history and undo/redo make targeted edits practical.
- **Bring video into the scene.** Import an MP4 as an editable media port, with timing, playback speed and audio controls. Export an opaque video or a transparent overlay.
+- **Put code inside footage.** Let a filmed or generated shot hide, light and carry code-rendered elements: a product behind a passing hand, a headline behind a presenter, a price pinned to a moving sign. Mattes, depth and tracks are pinned inputs from any tool; no model runs here. See [hybrid scenes](docs/hybrid-scenes.md).
- **Choose your model and host.** No Stitchable account, Remotion dependency or model API key is required by the framework. The shared skill and CLI are available for Claude Code, Codex and other tool-capable agents, including Grok; host-specific setup is documented separately.
## Try it
diff --git a/bin/editableframe.mjs b/bin/editableframe.mjs
index 2c8bf2a..74c8bd6 100755
--- a/bin/editableframe.mjs
+++ b/bin/editableframe.mjs
@@ -1,20 +1,23 @@
#!/usr/bin/env node
+import {chromiumOptions} from '../scripts/browser.mjs';
import fs from 'node:fs/promises';import path from 'node:path';
import {root,buildApps} from '../scripts/build.mjs';import {serve} from '../scripts/server.mjs';import {init,readProject,mutate,preview,rebind,importAsset} from '../scripts/project.mjs';
const [cmd,...args]=process.argv.slice(2),out=v=>console.log(JSON.stringify(v,null,2));
try{
- if(cmd==='init')out(await init(args[0]||'my-clip',{template:args.includes('--media')?'media':args.includes('--renderer')?'renderer':'canvas'}));
+ const flag=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};
+ if(cmd==='init')out(await init(args[0]||'my-clip',{template:args.includes('--media')?'media':args.includes('--renderer')?'renderer':args.includes('--hybrid')?'hybrid':'canvas'}));
else if(cmd==='inspect'){const d=await readProject(args[0]),cap=d.studio.capabilities(d.studio.doc.clips[0].id);out({...cap,baseRevision:d.revision,history:{length:d.studio.history.length,cursor:d.studio.cursor}})}
else if(cmd==='apply'){const p=JSON.parse(await fs.readFile(args[1],'utf8'));out(await mutate(args[0],d=>{if(p.baseRevision!==d.revision)throw Error('Stale revision: inspect again');d.studio.execute(p.command,d.studio.revision,'model')}))}
- else if(cmd==='asset-add')out(await importAsset(args[0],args[1],args[2]));
+ else if(cmd==='asset-add'){const depth=flag('--depth'),controller=new AbortController();let signalled;for(const [name,code]of [['SIGINT',130],['SIGTERM',143],['SIGHUP',129]])process.on(name,()=>{signalled??=code;controller.abort()});try{out(await importAsset(args[0],args[1],args[2],{signal:controller.signal,role:flag('--role'),of:flag('--of'),subject:flag('--subject'),encoding:depth?{kind:depth,near:Number(flag('--near')),far:Number(flag('--far')),packing:flag('--packing')??'gray8'}:undefined}))}catch(e){if(signalled)process.exitCode=signalled;throw e}}
else if(cmd==='rebind')out(await rebind(args[0],{reset:args.includes('--reset')}));
else if(cmd==='undo'||cmd==='redo')out(await mutate(args[0],d=>d.studio[cmd]()));
else if(cmd==='preview'){const h=await preview(args[0],{port:Number(args[1]||8791)});console.log(h.url);for(const signal of ['SIGINT','SIGTERM'])process.once(signal,async()=>{h.server.closeAllConnections?.();await h.close();process.exit(0)})}
else if(cmd==='studio'){await buildApps();const h=await serve(root,{port:Number(args[0]||8790)});console.log(h.url)}
- else if(cmd==='render'){const {render}=await import('../scripts/render.mjs');const option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};const controller=new AbortController();process.once('SIGINT',()=>controller.abort());out(await render(args[0],args[1],{frames:option('--frames')?Number(option('--frames')):args[2]&&!args[2].startsWith('--')?Number(args[2]):undefined,fps:option('--fps'),format:option('--format'),background:option('--background'),signal:controller.signal,onProgress:p=>{if(p.phase!=='frames'||p.frame%24===0)console.error(JSON.stringify(p))}}))}
+ else if(cmd==='render'){const {render}=await import('../scripts/render.mjs');const option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};for(const name of ['--expect-revision','--expect-binding'])if(args.includes(name)&&(!option(name)||option(name).startsWith('--')))throw Error('Missing value for '+name);const {beginJob,recoverJobs}=await import('../scripts/jobs.mjs');const controller=new AbortController();let signalled;for(const [name,code]of [['SIGINT',130],['SIGTERM',143],['SIGHUP',129]])process.on(name,()=>{signalled??=code;controller.abort()});if(!args.includes('--no-recover')){const found=await recoverJobs(args[0]).catch(e=>[{action:'recovery unavailable: '+e.message}]);if(found.length)console.error(JSON.stringify({phase:'recovery',jobs:found}))}const job=await beginJob(args[0],args[1]).catch(e=>{console.error('Render is not recoverable after a crash: '+e.message)});if(job)process.env.TMPDIR=process.env.TMP=process.env.TEMP=job.tmp;try{out(await render(args[0],args[1],{job,frames:option('--frames')?Number(option('--frames')):args[2]&&!args[2].startsWith('--')?Number(args[2]):undefined,fps:option('--fps'),format:option('--format'),background:option('--background'),pass:option('--pass'),motionBlur:option('--motion-blur')?{angle:Number(option('--motion-blur')),samples:option('--samples')?Number(option('--samples')):8}:undefined,expectRevision:option('--expect-revision'),expectBinding:option('--expect-binding'),signal:controller.signal,onProgress:p=>{if(p.phase!=='frames'||p.frame%24===0)console.error(JSON.stringify(p))}}))}catch(e){if(signalled)process.exitCode=signalled;throw e}finally{await job?.finish()}}
+ else if(cmd==='recover'){const {recoverJobs}=await import('../scripts/jobs.mjs');out(await recoverJobs(args[0],{dryRun:args.includes('--dry-run'),stopBrowsers:args.includes('--stop-browsers')}))}
else if(cmd==='assets'){const {run}=await import('../scripts/assets.mjs');await run(args)}
else if(cmd==='install-skill'){const {install}=await import('../scripts/install-skill.mjs');out(await install(args[0],args[1]))}
- else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{await fs.access(chromium.executablePath());checks.browser='installed'}catch{checks.browser='MISSING: run npx playwright install chromium'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})}
- else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer] Create an editable clip (media demo needs FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`);
+ else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{const options=chromiumOptions();await fs.access(options.executablePath??chromium.executablePath());checks.browser=options.executablePath?'configured executable exists (launch checked during render)':'Playwright Chromium exists (launch checked during render)'}catch(e){checks.browser='MISSING: '+e.message+'; install Playwright Chromium or set EDITABLEFRAMES_CHROMIUM_EXECUTABLE to an existing compatible browser'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})}
+ else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer|--hybrid] Create an editable clip (media and hybrid demos need FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n [--pass clay|depth|normal|id|matte] [--motion-blur ANGLE [--samples N]]\n [--expect-revision R] [--expect-binding B] [--no-recover]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n [--role alpha|matte|depth|normals|track|camera|environment|analysis|surface|coverage|foreground --of PLATE_ID [--subject ID]]\n [--depth inverse|linear --near N --far F] Data derived from a plate\n recover DIR [--dry-run] [--stop-browsers]\n Clean up after renders of DIR that were killed\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`);
else throw Error('Unknown command. Run editableframes help');
-}catch(e){console.error(e.message);process.exitCode=1}
+}catch(e){console.error(e.message);process.exitCode||=1}
diff --git a/docs/architecture.md b/docs/architecture.md
index c21c28f..8b4a3aa 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -38,13 +38,13 @@ not imply depth, layer, simulation, device or audio-automation services. See the
`AdapterRegistry` supports versioned adapters with `create(context)` returning `render(frame)`. An adapter can declare required host services. `createEffectHost` supplies only real implementations; missing services produce an explicit error. The initial demos include direct rendering paths as well as this optional registry. They do not yet all route through a single scheduler.
-The beta media host supplies `frameAt` and editable `portFrame`. General `layerAt`, `audioAt`, `maskAt`, `depthAt`, and `simulationAt` services remain extension work. Frame identity must include source revision, time, quality, color and effect order. Temporal effects must define whether they sample original source or upstream composition. Do not fake frame history by repeatedly drawing the same current frame.
+The beta media host supplies `frameAt` and editable `portFrame`. Mattes, depth maps, tracks and camera paths reach a renderer as ordinary pinned assets linked to the footage they were computed from (`mediaInfo`, `derived`; see [hybrid scenes](hybrid-scenes.md)). General `layerAt`, `audioAt` and `simulationAt` services, and depth ordering between separate clips, remain extension work. Frame identity must include source revision, time, quality, color and effect order. Temporal effects must define whether they sample original source or upstream composition. Do not fake frame history by repeatedly drawing the same current frame.
## Implemented and proposed
-Implemented: authoring core, disk-backed panel editor, revision-checked agent proposals, procedural Canvas/Three/WebGL2 studies, floating-point effects, device lighting, shared clip compositor, PTS-indexed local media frames, static audio-port mixing, rational frame exports and RGBA/ProRes transparency. See beta.md for the exact supported contract.
+Implemented: authoring core, disk-backed panel editor, revision-checked agent proposals, procedural Canvas/Three/WebGL2 studies, floating-point effects, device lighting, shared clip compositor, PTS-indexed local media frames, static audio-port mixing, rational frame exports and RGBA/ProRes transparency. See beta.md for the exact supported contract. Since beta 1: derived plate assets, depth occlusion, matte cut-outs, corner pins, lighting from a plate, declared control passes and shutter motion blur at export (hybrid-scenes.md).
-Proposed: streaming/hardware media decode, depth/ID sources, audio automation, untrusted-code sandboxing, distributed scheduling, EffectCraft/WASM bridge, broader DOM/media conformance, device-profile unification and explicit schema migration maps.
+Proposed: streaming/hardware media decode, depth ordering between clips, audio automation, untrusted-code sandboxing, distributed scheduling, EffectCraft/WASM bridge, broader DOM/media conformance, device-profile unification and explicit schema migration maps.
New custom code remains supported even when it exposes no editable controls. Unknown capabilities must not be discarded or converted to a smaller primitive vocabulary. In this beta, unknown template adapters prevent loading rather than mutating the saved document.
diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md
new file mode 100644
index 0000000..0aa76f4
--- /dev/null
+++ b/docs/avatar-lighting.md
@@ -0,0 +1,102 @@
+# Human foreground lighting
+
+**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested.
+
+Status: design and isolated still-image evaluation, not a shipped avatar relighting feature. Existing prepared-media primitives provide source-bound alpha and exact frame sampling; they do not recover a person's geometry or original illumination. Continuous speech, hands, multiple people, temporal stability and native preview/export parity still need video acceptance.
+
+## Route by the foreground's representation
+
+| Foreground | Default | Escalation |
+| --- | --- | --- |
+| Authored 3D geometry and materials | Editable lights, environment and physically based raster shading | Opt-in higher-quality transport where glass, indirect light or shadows justify it |
+| Filmed or generated human RGB + alpha | Preserve source pixels; bounded linear-light exposure/colour harmonisation | Prepared video-aware inverse-rendering passes or a reviewed video relight when light direction must change substantially |
+| Truly relightable 3D human asset | Use its authored geometry/material/skin transport model | Validate eyes, hair and subsurface scattering separately; an RGB avatar video is not such an asset |
+| Circular presenter inset | Treat as a screen-space UI layer; preserve the intentional frame | Relight only when explicitly intended to occupy the scene |
+
+Transparent output makes composition easier; it does not remove lighting baked into skin and clothing. A Three.js light cannot physically relight an ordinary video texture. A soft mask is not a normal map. Do not use subject depth as a substitute for facial normals or observed alpha.
+
+## Lighting is continuous, not a style enum
+
+Names such as office, daylight and neon are example recipes. The underlying editable description can contain arbitrary supported lights, directions, colours, intensity, source size, fill, environment, exposure and time tracks. A host may propose a new recipe from each background instead of choosing from a finite catalogue. Colour alone cannot identify incident illumination: a warm wall may be painted warm, and the brightest patch may be a surface rather than a light. Record observations, assumptions, confidence and user overrides separately. Keep scene estimates stable across a shot; freeze or interpolate authored tracks rather than re-estimating independently on every export frame.
+
+A common lighting description expresses intent across layers. Each renderer implements the subset its representation supports. RGB harmonisation must report that directional shadows/specular changes are unsupported; it must not silently present a colour ramp as a physical light solve.
+
+## Prepared human data contract (proposed extension)
+
+Retain current source identity, raster, rational rate, PTS, correspondence, validity/review and revision gates. Per subject, additionally identify foreground colour, alpha convention (straight/premultiplied), transfer function/primaries, any shading/gain map, normals/albedo/roughness/depth where actually provided, model/version/licence and source-to-output mapping. Missing passes are absent, never fabricated defaults. Map signed normal vectors and linear data explicitly; do not treat them as sRGB.
+
+Prefer native provider alpha and foreground colour over re-segmenting a flattened scene. Decontaminated edge colour matters when replacing the background. In an already-composited image, a masked colour delta can leave the old background unchanged, but cannot recover uncontaminated hair or unseen background. For multiple people, maintain subject IDs, separate adjustments and explicit overlap ordering; a union person mask cannot support independent lighting or depth relationships.
+
+Run models during preparation, outside the renderer clock. Cache reviewed outputs with hashes. Deterministic rendering samples those frozen artifacts at the exact source frame, including random/reverse seeks. A new background or lighting recipe invalidates lighting-dependent artifacts, not unrelated source audio or alpha. Generated outputs that change timing must be re-aligned or rejected; preserve the original speech track and verify lip sync.
+
+## Isolated evidence and rejected shortcuts
+
+Two high-resolution presenter screenshots and a separate small circular inset were evaluated locally. They are independent stills, not a continuous sequence. RVM MobileNetV3 separated the body but visibly damaged small headphone/cable features and left edge contamination. CPU execution is feasible on the tested Apple machine; that does not establish real-time video quality or cross-device throughput. RVM is GPL-3.0 and was evaluated separately, not bundled or selected for production distribution.
+
+Bounded linear-light gain preserved background pixels outside the supplied mask. It preserved source geometry by construction but did not create geometrically correct directional facial shadows. IC-Light SD1.5 FBC, run locally with the same seed on two stills, produced stronger light while changing facial and accessory detail. Raw generative replacement was rejected for faithful avatar rendering. A blurred, clamped luminance-ratio hint applied back to original pixels avoided substituting generated facial pixels, but remains experimental: incorrect inferred shapes can still imply incorrect shading, and temporal consistency was not tested.
+
+Do not interpret zero background change, equal frame counts or deterministic output as a likeness or photorealism score. Keep numerical integrity, boundary quality, identity/expression, illumination plausibility and temporal quality separate.
+
+## Next video acceptance
+
+Use a short alpha-capable talking clip with head turns, blink, open/closed mouth and a hand near the face. Compare unchanged source, conservative harmonisation and any stronger relighter against a fixed warm/cool background pair. Inspect every transition and alpha edge, speech timing, hair, headphones, teeth, skin texture, hands and clothing. Test a second person with overlaps independently. Export and native preview must agree on source mapping and approved revisions. A slideshow of supplied screenshots cannot pass this gate.
+
+## A presenter who handles a product (proposed)
+
+A generated presenter clip is one flattened picture. Imported as media it takes layer edits only: timing, crop, position, an overall grade, and code drawn over it. Her pose, the product in her hand, the grip, the room's light and the camera cannot be changed separately, because they are not separate in the file. Pilots on 2026-11-12 with hosted avatar and video models confirmed the useful half and the missing half:
+
+- **A model can perform the action.** From a supplied still of the presenter in a room, one take pointed and swept a hand toward the product, and another approached a table, gripped headphones by the headband, lifted them and stepped while holding them.
+- **Explicit first-frame composition helped in these takes.** Pose, framing and product orientation followed the supplied image. A take started from an explicitly composed standing frame gave the best result. Text instructions to lock the camera or stand were ignored in other takes.
+- **The product does not survive.** The generated headphones drifted toward generic ones. Exact code replacement is one fallback; it needs the additional inputs below. The default experiment now tests a richer reference set first, without claiming exact product preservation.
+- **Timing needs its own stage.** Speech meant to announce the lift started after it. Sliding audio against a face that is already speaking does not fix lip sync.
+
+To draw an exact product into such a shot, a scene needs inputs that do not exist yet:
+
+| Input | Why |
+|---|---|
+| Background, presenter colour + alpha, and hand holdout as separate source-bound layers | A product held in front of the torso but behind the fingers; a room that can change independently |
+| Product pose for every frame, with an anchor that changes | A pickup has phases: on the table (anchored to it, with contact shadow), grip, lift (anchor moves from table to hand with no jump), carry (follows the hand through changing light) |
+| A 3D or multi-view product asset | A lifted product shows sides a single photograph does not have |
+| Narration aligned before generation, or a tested lip-sync stage | Speech that names the action has to happen with it |
+
+Bad anatomy in a grip is repaired by another take or a reference performance, not by compositing. Without these inputs, a generated pickup supports edits to the footage layer and code overlays, not independent edits to the product or grip.
+
+## Provider and research notes
+
+- [HeyGen transparent output](https://developers.heygen.com/transparent-background-videos): the documented avatar route requests WebM using a matting-enabled avatar look. Verify eligibility and actual decoded alpha. This supplies a foreground, not relighting passes. Keep provider-specific requests in the host, outside the rendering library.
+- [Google Portrait Light](https://www.research.google/blog/portrait-light-enhancing-portrait-lighting-with-machine-learning/) predicts a low-frequency quotient applied to source pixels. This motivates detail-preserving gain control; it does not validate a handcrafted or diffusion-derived gain map.
+- [RVM](https://github.com/PeterL1n/RobustVideoMatting) provides recurrent foreground/matte inference, with GPL-3.0 licensing. Licence review and benchmark evidence are required before distribution.
+- [IC-Light](https://github.com/lllyasviel/IC-Light) is an image relighting candidate. Independent image inference is not a temporally validated video relighter.
+- [Beeble](https://developer.beeble.ai/) offers hosted transformation; account-gated product passes and a generative output are different contracts. No hosted pass/relight was tested in this evaluation. Assess output fidelity and current access before choosing it.
+
+## Reference-conditioned handling shots (2026-11-13)
+
+The next experiment generates presenter, product, hands and room together from multi-angle references, then prepares subject masks and suitable surface tracks for editable code. The shared visual context may improve contact, lighting and identity; those remain measured acceptance criteria. A whole-shot output is flattened footage. Code can expose timing, crop, transform, grade and overlay controls, but cannot independently change the generated grip, product pose, physical light or camera. Changing a generation reference means a new take and invalidates derived data.
+
+Use separate foreground generation when an exact or code-driven background is required. Compare native alpha where verified, neutral-background matting and suitable chroma-key acquisition; none automatically supplies shadows, uncontaminated hair or relightable geometry. Preserve separate subject IDs and corrections. Segmentation is not fractional alpha or surface depth.
+
+Product fidelity must be checked against references through the entire turn and grip. A tracked label can repair print only on a supported surface with valid visibility; a planar pin is not a solver for arbitrary curved products. Bad anatomy needs another take or reference performance. Audio references may influence speech or rhythm but do not guarantee lip sync, verbatim speech or action timing. Do not slide speech against an already-speaking face as a repair.
+
+Keep model jobs outside the rendering clock and provider-specific APIs outside the framework. Record actual decoded frame correspondence instead of requested duration, and retain the prior reviewed take until its replacement passes acceptance. The optional exact replacement contract above remains necessary when independent product geometry is required. See [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md). These experiments are not new renderer APIs or a production approval.
+
+## Interaction routing decision (2026-11-13)
+
+**All intended human–object interactions use reference-conditioned video generation by default.** This includes looking toward, pointing at, presenting, reaching for, touching, picking up, wearing and carrying an object. Generate the human, object, support surface and room together so gaze, gesture, orientation, scale, contact and lighting share one visual context. Treat the result as a candidate requiring review, not a promise that diffusion solves anatomy or preserves product details.
+
+The latest mask-composition exercise improved hair stability and removed measured hand/product overlap, but the presentation still failed: the person did not convincingly look toward the product, the gesture was unrelated to it, and the photographed headphones stood in an implausible pose. **Zero overlap is not a believable interaction. Do not manufacture a demonstration by moving an unrelated product cutout near a prerecorded gesture.** Do not keep iterating masks or placement on that route for this use case.
+
+Keep the existing composition framework around the generated shot: provider calls happen during preparation; retain references, prompts, job IDs, costs and original media; decode and bind masks/tracks to the accepted take; add editable typography, captions, prices, UI and suitable tracked screen content afterward. Screen-space cards stay outside subject holdouts. Independent product/portrait layouts, background swaps and code-rendered packshots remain valid when they do not imply interaction. A fully authored, synchronized 3D character/product scene is a separate explicit workflow, not a fallback inferred from a 2D avatar.
+
+Acceptance must inspect the whole gesture at normal and slow speed: eyes and head attend to the intended object, the open palm/index points toward its actual location, the product rests or is supported naturally, perspective and scale agree, contact does not slide or penetrate, and product identity remains faithful. Reject unnatural gaze, unsupported upright props, a gesture aimed elsewhere or a drifting product even when every frame decodes and every mask passes. Regenerate or change the shot; do not conceal the failure with a code overlay.
+
+Generated interaction is baked into the footage. Expose source selection, timing, crop, overall grade and code-overlay controls honestly. Changing gaze, pose, grip, product orientation or physical lighting requires a new take and invalidates dependent analysis. This is an authoring/host routing decision; it adds no implicit model service to the renderer.
+
+### Single-take result (2026-11-13): partial improvement, rejected for final use
+
+One [Kling 4.0 reference-image job on Replicate](https://replicate.com/kwaivgi/kling-v4.0) used a fictional presenter still, one official headphone view and an empty showroom reference. Requested five seconds at 720p; decoded output was 121 frames at 24 fps (5.0417 seconds), 1280×720. The published image-reference rate implies about $0.79 for the reported output duration; this is an estimate, not a verified billing-ledger charge. No second paid take was submitted in that initial exercise. A later authorized video-edit take is recorded in [the staging workflow](interaction-staging-workflow.md#retained-experiments-and-conclusions).
+
+Sampled frames show her head/eyes attending to the headphones and an open palm presenting toward them before she returns attention to the camera. This is better coordinated than the unrelated-avatar/product composite. However, the model kept the headphones upright, matching the product reference pose, despite explicit instructions to lay them on their side. **The take fails the requested support/orientation criterion and is not approved as a product advert.** The observation is consistent with reference-pose bias; one trial does not prove that cause or that this provider is the best choice. At that checkpoint pickup had not been tested. The later video edit demonstrates a plausible pickup-and-hold; identity through a turn, multi-person interaction and exact brand fidelity remain unproven.
+
+For the next separately authorized take, first obtain or approve a physically plausible scene/pose reference showing the intended product orientation and a coherent presenter eyeline. Prefer an actual product photograph in that resting pose or a reviewed scene keyframe, with detail references alongside it. Do not repeat an upright packshot and assume a negative prompt will fix the support geometry. If a provider accepts both scene keyframes and detail references, verify their combined endpoint contract and numbering. The raw take must pass gaze, gesture, support and product-fidelity review before final overlays are approved.
+
+The trial is also rendered through the existing code renderer with editable screen-space typography. Those controls change only the overlay; the human/product interaction remains the original generated footage. Preparing masks or importing the clip does not turn a failed raw take into an accepted one.
diff --git a/docs/beta.md b/docs/beta.md
index 8ab675b..880edf4 100644
--- a/docs/beta.md
+++ b/docs/beta.md
@@ -67,3 +67,7 @@ npm run check:public
## Opening an alpha project
Keep a copy of the complete project folder. Beta changes the runtime binding, so an alpha project can initially report an incompatible binding. Run `rebind DIR` to validate its existing schema/history against beta and record the new runtime. A compatible rebind preserves edits and archives the prior project. Do not use `--reset` just to dismiss an error: it deliberately starts from defaults and belongs only to an intentional incompatible schema replacement. Historic arbitrary-source restoration remains manual; property undo/redo is the supported persisted history contract.
+
+### Interrupted CLI work
+
+Imports cancel cleanly on SIGINT/SIGTERM/SIGHUP. Numbered edit locks can recover a provably dead local owner. CLI renders record owned temporary resources; subsequent renders attempt non-signalling recovery, also available through `recover DIR`. Use `--dry-run` to inspect, or explicitly `--stop-browsers` to request SIGTERM for a verified orphan browser. Unknown owners are left alone. These checks passed on one Mac/APFS; Windows takeover, network filesystems, power loss, preview and native-app integration are not covered. Existing projects need `rebind` after the runtime update. [Evidence](hybrid-concurrent-recovery-2026-11-14.md).
diff --git a/docs/code-generated-story-results-2026-11-13.md b/docs/code-generated-story-results-2026-11-13.md
new file mode 100644
index 0000000..edf1668
--- /dev/null
+++ b/docs/code-generated-story-results-2026-11-13.md
@@ -0,0 +1,58 @@
+# Interaction acceptance and code-generated story films — 2026-11-13
+
+> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact, native integration and style reuse remain open. See [current evidence](hybrid-gap-closure-2026-11-14.md).
+
+## Decisions from the latest outputs
+
+The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark.
+
+Keep two distinct production routes, selected by the required representation and editability:
+
+| Need | Selected route | What remains editable | Evidence / boundary |
+|---|---|---|---|
+| Realistic people handling a product or exchanging it | Stage the scene → approved start image plus identity/product references → jointly generate the interacting subjects and room → review → EditableFrames finishing | Staging before generation; accepted footage selection/timing/crop/grade and separate titles/captions afterward | Pickup and completed transfer now have user-accepted examples. Physical performance and product pixels are baked; repeatability and exact identity/branding remain open. |
+| Stylized characters acting in an authored world | Code builds the set, rigs, action, cameras, lights and renderer; export directly | Authored geometry, rigs, animation and look in source; selected parameters via controls | Two 48-second fantasy RPG films rendered. Fable's direction is preferred, but its draft fails one seek check and requires refinement. Not generic automatic character animation. |
+| Realistic interaction within an otherwise editable story | Use an approved authored shot/snapshot as generation input, then return the accepted clip to the edit | Code shots stay editable; generated sections have the same baked boundary as above | Proposed shot-level combination; this story exercise did not test such a round trip. Do not claim that model video preserves exact meshes or camera motion. |
+
+The earlier interaction rule applies to **independently assembled realistic plates**. It must not become a ban on code-authored character stories. A shared authored rig and choreography can represent an interaction; independent masks cannot invent it. Nor does stylization excuse intersecting hands, incoherent eyelines, or unsupported props.
+
+## What Fable actually used
+
+Both entries use **Three.js raster rendering in the current EditableFrames `defineRenderer` / `mountRenderer` contract**, exported locally through browser capture and FFmpeg. No diffusion-generated frames, external character asset pack, path tracer, NVIDIA-only runtime or paid generation call was used for these films. The difference is authored assets, staging and rendering choices, not a different foundational framework.
+
+| Area | Fable implementation observed in source | Why it fits the references better / remaining limitation |
+|---|---|---|
+| Character construction | Lofted heads and bodies, character-specific proportions, separate noses/ears/hair, articulated segmented limbs and five-finger hands. Canvas-painted face textures include lids, brows, pupils, mouth states and emissive eyes. | Narrower faces and controlled facial detail read closer to the reference game art. This is procedural geometry and a scene-specific rig, not a learned human reconstruction or a production facial rig. |
+| Materials | Seeded, low-resolution stone, wood, cloth, leather and skin texture functions; nearest-neighbor magnification with mipmapped minification. Humanoids use Lambert materials. | Local wear, varied stone courses, planks and painted features provide more surface detail. Physically based materials alone do not guarantee a better stylized image; Astra used standard materials yet its asset forms were more primitive. |
+| Acting | Two-bone arm IK, gaze targets, walk/sit/gesture poses, a deforming dragon spine and wings, speech-envelope-driven animation with limited facial states. | More purposeful action than small idle oscillations. IK positions joints; it does not verify grasp, reach, collisions or force. Speech-envelope animation is not phoneme-level lip sync. |
+| Camera and sets | Fifteen shots rather than Astra's eight; a medieval lane and a furnished tavern; approach, reaction, over-table, detail and ensemble shots. | Greater spatial context, shot variety and first-person framing. The doorway transition and handoff detail still need refinement. |
+| Lighting and finish | Local torches, ember, window/fill and chandelier lights; HDR beauty pass at twice the output dimensions, object-ID/depth contour pass, half-resolution bloom, tone mapping, grade, vignette and grain. | Local light and depth-aware contours make a coherent game-art look. The large bloom/highlights also obscure detail in parts of the draft; adding effects is not automatically a quality improvement. |
+| Framework | Explicit frame clock and editable light/look/camera/title/subtitle properties, with separate local TTS/audio preparation. | Source remains authorable and selected controls redraw the scene. This does not make every performance or audio edit automatically available in a panel. |
+
+These are source-backed mechanisms and plausible contributors to the user preference, **not isolated causal tests**. No ablation has established which individual technique explains how much of the difference. The preferred direction is a reusable authoring approach, not a requirement to reproduce Fable's bugs or every shader.
+
+## Actual result and acceptance
+
+- **Astra:** 48.000 seconds, 720×1280, 24 fps, 1,152 decoded frames, voiced/subtitled. Three sampled repeat seeks matched exactly in the tested browser; a light-control edit changed the scene. Faces/hands remain puppet-like, material and architectural variety are limited, and jaw movement is approximate.
+- **Fable 5.2:** authored the scene, soundtrack and 15-shot timeline, then hit its provider usage limit during visual refinement. The parent exported that saved source unchanged; hashes before/after confirm preservation. Both full video and original source are retained. The output is a **recovered unfinished draft**, not Fable's final approved delivery.
+- **Recovered Fable export:** 48.000 seconds, 720×1280, 24 fps, 1,152 frames decoded without video errors. Light-control edit changed the render. A generic browser resource 404 was retained; its URL was not established, so it is not silently dismissed as a confirmed favicon request.
+- **Seek defect:** frames 228 and 768 repeated exactly, but frame 960 changed 183,794 pixels; mean channel difference 7.128/255, maximum 238. The dragon's head direction visibly changes. The `better` shot reads the previous camera position for its gaze before setting the current camera, a likely cause from source inspection; a fix has not yet been verified. Successful sequential export does not pass random-access authoring.
+- **Audio recovery:** initial decoded AAC peak was 1.372. The parent applied gain 0.5 at output while copying video unchanged; delivered peak measured 0.737. The original audio export is retained. This avoids the measured output overshoot but cannot undo distortion already present in the mix.
+- **Visual limits:** rigid joints, sparse facial animation, awkward/oversized hand contact, strong light/bloom and the doorway transition. Fifteen shot stills and a 1 fps decoded sheet were inspected; there is no claim of normal-speed playback or exhaustive visual inspection of all 1,152 frames by the reviewer.
+
+The user prefers Fable's **visual direction**. Neither film reaches the reference's character finish; a general production-ready or deterministic story engine is not yet demonstrated. References supplied art direction; their screenshot pixels were not used as finished scene backgrounds. Preserve reference rights/provenance before redistributing any supplied images.
+
+## Story track: extend beyond the dungeon without constraining the core
+
+This is a new authored-story exercise, separate from **feature item 6 (camera solve)** and **feature item 13 (world reconstruction into splats/meshes)**. Code-generated geometry and known cameras do not validate either deferred feature. Also keep it distinct from the existing “many versions from one take” journey numbered 6.
+
+1. **ST1 — finish and stabilize this film.** Let Fable complete its own refinement when available. Correct the current-frame camera/gaze dependency and test random, repeated and reverse seeks across every shot and cut boundary; compare with sequential frames in the same renderer. Inspect normal/slow playback, all contact intervals, reach/support/release, camera-wall clipping and gaze. Repair highlight loss and audio gain; retain original versus corrected versions and explicit authorship. Verify each advertised control in both preview and export. No model call or wall-clock state inside frame rendering.
+2. **ST2 — extract optional reusable authoring modules.** Separate character shape/face/rig, props and set dressing, action targets/contacts, shot/camera track, light track, material/contour/post look and dialogue/subtitle timing. Give selected controls stable IDs and source bindings; keep arbitrary source code and replacement renderers possible. Do not embed a mandatory fantasy vocabulary, actor taxonomy or model provider into the core. Existing film scripts are prototypes, not a shipped animation package.
+3. **ST3 — test style transfer through code, not only palette changes.** Produce three additional short studies, for example a science-fiction repair shop, a sunny cel-shaded village and a clay/toy workshop. Use a common walk → dialogue → shared-prop action and camera brief while changing silhouettes, facial design, surface detail, set construction, light response and contour/post treatment. Retain the full editable sources and exact settings. Each style must pass its own whole-shot visual review; portability beyond the fantasy study is currently unproven. No new hosted spending is implied.
+4. **ST4 — test practical reuse and host delivery.** Reuse an approved actor across shots and changes in framing, light, costume and dialogue; check identity, silhouettes and contact after edits. Regenerate local speech/alignment when dialogue changes rather than retaining stale audio. Bind source, assets and audio to project revisions and test save/reload, undo/redo and export parity in the host before claiming an integrated story workflow. Measure preview, capture time and peak memory on actual additional desktop/laptop machines; this Mac run establishes no performance floor for ordinary computers.
+
+Style is an open combination of authorable geometry, textures, rigs, cameras and lights, not a fixed list of “dungeon / office / cool” presets. Presets may be convenient starting points. Cross-style reuse and a useful agent authoring workflow must be earned by ST3/ST4, not inferred from parameter exposure alone.
+
+## Interaction work that remains
+
+The accepted pickup/handoff samples validate the selected staged joint-generation direction sufficiently to proceed with host implementation. Prioritize frozen scene-set capture, ordered reference roles/hashes, durable submission receipts, failed/ambiguous-job handling, actual decoded timing and accepted-take import; keep provider work outside rendering. Repeat the tests with both people identity-referenced and with difficult contact/occlusion before claiming broader reliability. Exact product geometry/print, multi-angle consistency, object–object collisions and animal interactions remain separate acceptance gates. The detailed [staged-generation report](staged-generation-results-2026-11-13.md) retains the observed action beats, estimates and limits.
diff --git a/docs/hybrid-acceptance-round1-2026-11-13.md b/docs/hybrid-acceptance-round1-2026-11-13.md
new file mode 100644
index 0000000..8206208
--- /dev/null
+++ b/docs/hybrid-acceptance-round1-2026-11-13.md
@@ -0,0 +1,52 @@
+# Hybrid acceptance round 1 — 2026-11-13
+
+Status: local experiments, no new generated take, no independent reviewer approval, no native-host integration claim. Existing generated footage and cached local models were reused. Hosted generation spending in this round: $0.
+
+## Staged snapshot handoff
+
+A seller/product scene now renders through the current renderer-host with editable product horizontal/vertical position, scale, image-plane rotation and an approximate foreshortening control. The headphones lie camera-left on the table, within reach of the presenter's hand, against a detailed warm-lamp/cool-window background. Repeated frame-zero captures are byte-identical in the tested browser; changing horizontal placement changes the PNG. Source, assets, controls and captured PNG are hashed into a local manifest.
+
+This is a 2D reference composition, not solved 3D product orientation, contact or lighting. The snapshot plus separate product and presenter references has **not been submitted** to a model. The latest provider schema supports start-image plus references and explicitly numbers the start image before the references. The quoted 5-second 720p image-input trial is approximately $0.785 at $0.157/s; re-check pricing before submission. The previous video-edit pickup does not establish this round trip.
+
+The earlier local Scene Studio suite passed 19 checks, including clean capture during active drafts and identical capture-button/programmatic outputs. An offline packet prototype exercised eight integrity cases. These do not replace real provider receipts, ambiguous-job recovery or native integration tests.
+
+## Full-clip masking through a pickup
+
+The complete previously generated pickup was processed: 121 frames, 24 fps, 5.0417 seconds. Source SHA256: `3b9aaf790d8f639eda5005808e08977ae951b0de05f8418c6f73acf66512d6cf`. Analysis resolution was 640×360; this is not 1080p boundary acceptance.
+
+- SAM 2.1 Hiera Tiny on Apple Metal propagated separate person/product/gripping-hand prompts across every frame. Raw thresholded masks, no correction clicks or optional model postprocessing. Propagation plus saving took 136.67 s; steady-step median/p95 1.157/1.176 s; process peak RSS about 2.14 GB. These are preparation costs, not render FPS.
+- RVM MobileNetV3 FP32 on CPU processed all 121 frames with continuous recurrent state, at 640×360 and downsample ratio 1. Wall time including saved foreground/alpha was 24.27 s. Some local workloads overlapped, so this is not an isolated hardware/model benchmark. RVM and SAM solve different problems.
+- The comparison preserves the original table below y=277 and replaces the background above it with a bright yellow diagnostic field. Original contact and lighting remain baked. SAM binary edges visibly lose soft hair detail. RVM softens the hair but introduces background remnants below the arms; neither raw route is an automatic pass.
+- A second candidate constrains RVM alpha with each frame's SAM person support: alpha is unchanged up to 3 pixels outside support, tapers to zero by 6 pixels, and the product is separately restored from its SAM mask. This reduces the observed spill. It can still clip hair missed by SAM and retains boundary defects; it is a heuristic requiring review, not ground-truth matting or physical depth.
+
+Both comparisons export all 121 frames and repeat frame 48 with maximum RGB code difference zero in the tested browser. These are renderer checks. Sampled full-frame images and contact sheets were inspected; no annotated hair/hand error, full normal/slow playback approval, identity guarantee or production-quality badge is claimed. Whole-clip processing is broader evidence than the previous short interval, but not completion of the static/pan/handheld/multi-person stress matrix.
+
+**Plan change:** keep semantic masks, foreground colour/alpha and support correction as separate, versioned preparation artifacts. Add whole-shot bright/dark edge checks and correction ranges. A successful segmentation job is insufficient for background-swap acceptance.
+
+## Tracking: a negative forward/backward result
+
+A new diagnostic reuses the synthetic stationary panel with independently moving surrounding texture. It runs the current tracker on the 49-frame clip forwards and on a losslessly re-encoded reversed clip, then compares corresponding returned quads.
+
+Worst corner error against the known stationary panel: **6.861 px**. Maximum forward/backward disagreement: **0 px**. For 25 frames, actual error exceeds 4 px while correlation exceeds 0.95 and forward/backward disagreement is below 1 px. At the worst frame the score is 0.956. The motion is symmetric, making this a deliberately revealing case where both directions share the same wrong solution.
+
+**Plan change:** forward/backward agreement is a diagnostic, never sufficient acceptance. Independent intended-surface boundaries, visibility and distributed target evidence are required; ambiguous/blank surfaces need correction or rejection. No production rejection algorithm was implemented here. The original missing S1/orbit footage remains unretested; this experiment does not establish its exact cause.
+
+## Lighting: continuous controls and a representation boundary
+
+A new 120-frame, 24 fps clip holds camera, geometry, exposure and authored scene frame fixed while continuously changing a practical lamp from warm to cool. The scene uses a scanned pastry, procedural cup/plate/lamp, and a photographed HDR panorama. It is a renderer diagnostic, not a real moving room or final advertisement. Lamp source colour, bulb emission and shade emission change together.
+
+Matched warm/cool rectangular image regions show mean absolute RGB changes of 0.22/255 on the pastry, 5.74 on the cup and 24.96 on the table reflection. The tested upper-left photographed backdrop is byte-identical (0 change). These ROIs include some surrounding pixels and measure response, not material accuracy. Repeat-frame pixels match; no page errors were recorded.
+
+**Plan change:** continuous editable colour/intensity is supported; named presets are starting values, not a finite lighting catalogue. Accept per-object light response separately from the bulb looking brighter. Light placement must serve the intended hero object; the weak pastry response is a failed stress target. A baked panorama, product photo or human video does not acquire physically correct new illumination merely because a 3D light was added. Keep that distinction explicit and test separate relighting routes for those representations. Ordinary-computer performance and mixed human/product emitter scenes remain open.
+
+## Remaining order and numbering
+
+1. Submit and inspect the actual staged snapshot plus references once a fresh spending cap is settled; then test object–object contact and two-person handoff separately.
+2. Implement real handoff receipts, failure recovery, accepted-take import and source-bound analysis in the host. The local packet prototype is not that implementation.
+3. Annotated full-resolution mask/alpha acceptance, disappearance/re-entry, multiple people and actual-device comparison. SAM 3 remains an access/runtime and comparison gate.
+4. Independent-surface tracker rejection and repeatable real-footage visibility tests.
+5. Stronger hero-object light response, mixed human/product emitters and additional actual computers.
+
+**Feature item 6 (camera solve): not tested here. Feature item 13 (generated worlds): research only, not tested here.** Authored Three.js cameras, photographed HDR backdrops and homography tracking prove neither feature. The separate journey table also has an item 6, “many versions from one take”; that is a different, partially exercised editable-content journey. H5, feature 6 and feature 13 remain deferred under the prior scope decision, not silently completed.
+
+Primary references: [Kling input and pricing documentation](https://replicate.com/kwaivgi/kling-v4.0), [SAM 2](https://github.com/facebookresearch/sam2), [Robust Video Matting](https://github.com/PeterL1n/RobustVideoMatting). Measurements above come from local retained experiment receipts, not those references.
diff --git a/docs/hybrid-analysis-study-2026-11-13.md b/docs/hybrid-analysis-study-2026-11-13.md
new file mode 100644
index 0000000..7d4069c
--- /dev/null
+++ b/docs/hybrid-analysis-study-2026-11-13.md
@@ -0,0 +1,54 @@
+# Video segmentation and tracker study — 2026-11-13
+
+Status: isolated feasibility tests and one tracker correctness fix. No new hosted generation, no production segmentation integration, and no new independent Fable approval. Existing generated clips were reused. H4 preparation and H6 reference-conditioned shots are the next work; general camera solving, deformable surfaces and generated 3D worlds remain deferred.
+
+## SAM 2: actual Mac video tests
+
+Official SAM 2.1 Hiera Tiny, code revision `2b90b9f5ceec907a1c18123530e92e794ad901a4`, checkpoint SHA-256 `7402e0d864fa82708a20fbd15bc84245c2f26dff0eb43a4b5b93452deb34be69`. PyTorch 2.15.0, float32, four CPU threads, Apple Metal (MPS) on a 16 GiB Mac (`Mac18,5`); no NVIDIA GPU. Video/state storage offloaded to CPU. Optional model postprocessing disabled, so these are raw thresholded segmentation masks, not refined alpha.
+
+Two contiguous intervals, each starting 3.5 seconds into an existing generated clip:
+
+| Case | Frames / rate / decoded test size | Prompted instances | Propagation wall time | Steady-step median / p95 |
+|---|---|---|---|---|
+| Full-body pickup, Metal | 48 / 24 fps / 630 × 360 | Person, headphones, gripping hand | 50.78 s | 1.108 / 1.120 s |
+| Seated talking gesture, Metal | 48 / 25 fps / 640 × 360 | Person, image-left hand, image-right hand | 53.08 s | 1.180 / 1.195 s |
+| Pickup CPU fallback smoke test | First 8 / 24 fps / 630 × 360 | Same three prompts | 9.63 s | 1.350 / 1.739 s |
+
+The model internally uses 1024 × 1024 input. Manual positive/negative clicks were supplied only on interval frame 0; no correction clicks were added afterwards. All requested frames produced masks for all three IDs. CPU and Metal binary masks were identical over the eight shared frames; this is a narrow observation, not a cross-device determinism promise. The CPU timing sample is too short for a robust hardware ranking. Propagation wall time includes saved outputs; steady-step measurements exclude file saving, include output transfer, and omit the first yielded frame. Model load, decode/initialization and prompt time are recorded separately in the local receipts. This is not end-to-end app export throughput.
+
+Visual inspection of nine sampled overlays per clip found broad subject identity retained through lift/reach. The hand mask includes some wrist/sleeve and product boundaries need review. Binary masks cannot resolve fractional hair alpha, motion blur, edge colour contamination or the depth of individual fingers. Up to four pixels belonged to both product and hand masks in the pickup interval; this is an overlap diagnostic, not measured ground-truth error. No annotated boundary accuracy, real-time playback approval, complete original-clip review, multiple-person test or native preview/export parity is claimed. The historical failed phone-thumb sequence was not rerun.
+
+**Decision:** SAM 2 is a viable optional preparation adapter on this Mac. Cache reviewed masks before playback; do not infer on every render/seek. This performance is far from real-time 24/25 fps and says nothing about ordinary Windows/Linux hardware. Keep manual corrections and a separate alpha-refinement step. A model probability/logit is not physical alpha.
+
+## SAM 3: access and device gate, not a quality result
+
+The official repository supports text/visual prompting and temporal instance tracking, with SAM 3.1 multiplex checkpoints also available. This makes it a relevant candidate for finding and following several subjects, not a proven matting or contact-physics solution. Its documented installation requires CUDA; the inspected `Sam3VideoPredictorMultiGPU` selects a CUDA device and checks CUDA GPU IDs. No native MPS video route was validated. The official checkpoint request returned HTTP 401 without accepted/authenticated access. No credentials were requested or exposed and no paid endpoint was called.
+
+**Decision:** do not ship a SAM 3 default or claim a SAM 2-versus-SAM 3 accuracy winner. Next comparison requires an approved checkpoint and supported runtime, or an accessible hosted endpoint with a quoted capped test. Run the same retained source intervals, prompt identities and annotated boundary protocol. Check checkpoint-specific licensing before distribution; SAM 3 uses its own SAM license, not SAM 2's Apache assumption.
+
+Primary sources: [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3 installation and examples](https://github.com/facebookresearch/sam3), [SAM 3 video predictor](https://github.com/facebookresearch/sam3/blob/main/sam3/model/sam3_video_predictor.py).
+
+## Preparation architecture
+
+An image encoder/interactive decoder split is useful: cache heavy image features, then allow quick positive/negative point corrections. Video needs more than repeated image inference: memory propagation, stable instance IDs, cuts, disappearance/reappearance and correction-range invalidation. The model and checkpoint, preprocessing transform, source digest, frame mapping and correction revision must accompany cached data. Different models cannot share embeddings merely because tensor dimensions match.
+
+Produce separate subject/hand/product masks, optional refined foreground colour and alpha, and explicit review ranges. A union person mask is insufficient for independent hands or multiple presenters. Keep semantic segmentation, fractional alpha, surface registration and depth order distinct. Stale or incomplete required intervals must fail final composition; never stretch a short mask or hold a moving tail to fit a requested duration. Preparing a cropped test interval does not certify the full source.
+
+H6 can generate the whole shot and use these masks for editable titles, screen inserts and bounded colour adjustments. The masks do not separate baked light, recover hidden background or expose editable generated product geometry.
+
+## Tracker anomalies: what is known
+
+The original S1 board and filmed orbit source videos could not be found among the retained local assets after the earlier temporary-file loss. Their written measurements remain available; the following reproductions are deliberately new synthetic fixtures, not reruns of those shots.
+
+1. **S1: about 8 px error at confidence ≥0.976.** The exact cause is still unconfirmed. The tracker fits one homography to a low-resolution patch that normally includes a 25% margin. Texture or lighting outside the target can dominate; a blank interior supplies little constraint. A stationary synthetic panel with independently moving surrounding texture reproduced 6.86 px corner error, confidence 0.956 and zero lost frames. With the same surround fixed, error was 0 px and confidence 1.0. A weak-border variant reached 6.86 px at 0.959. These demonstrate the failure mechanism, not the historical shot's cause.
+2. **Orbit: switching to the next box face at confidence ≥0.703.** The original report says reducing the margin produced 43–124 lost frames because the selected panel was blank. This is consistent with competing planes entering the shared template. The code has no semantic face identity, visibility test or independent corner evidence: it accepts correlation ≥0.6 plus a broad finite-coordinate sanity check. The existing evidence supports a wrong-plane failure; it does not establish exactly which pixels drove the optimizer without the original source.
+
+Normalized correlation measures appearance agreement, not corner accuracy, subject identity, rigidity or visibility. Raising the threshold alone cannot solve this: the synthetic failure passes even 0.95. A segmentation mask may constrain the target but cannot provide texture or recover metric pose. Face changes, out-of-plane rotation and full occlusion need explicit rejection/reseeding or a more capable tracker, rather than silently inheriting the next surface.
+
+### Separate preparation-tracker correctness bug
+
+The external preparation tracker (not an EditableFrames runtime service) returned its updated homography with correlation measured before the last update. In a one-step diagnostic the returned warp had correlation 0.978855 while the reported score was 0.618937. Re-scoring the final warp fixes that mismatch; a regression independently samples the returned transform and compares the score. Its 13 plate-tools tests pass; no tracker implementation is added to this rendering library. The moving-surround fixture still fails by 6.86 px after this fix: it is not presented as a repair of S1 or the orbit.
+
+### Next acceptance gate
+
+Preserve source-level repeats and add annotated corner trajectories, surface masks and visibility intervals for static/pan/orbit footage. Record per-corner residuals, support distribution, local boundary agreement and forward/backward consistency alongside correlation; none alone certifies correctness. Inspect every crossing and face transition. Require correction or rejection when the intended surface disappears or independent evidence disagrees. Do not freeze a confidently wrong overlay and call the shot passed. Broader tracker redesign remains pending these measurements.
diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md
new file mode 100644
index 0000000..e05709b
--- /dev/null
+++ b/docs/hybrid-compositing-plan.md
@@ -0,0 +1,115 @@
+# Reliable hybrid compositing and motion design
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open.
+
+**Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API.
+
+Human foreground extension: [avatar lighting](avatar-lighting.md) records the representation-dependent routing, still-image findings and pending video acceptance. This is a design addition, not a claim of shipped portrait relighting.
+
+Status: implementation and acceptance plan, 2026-11-11. Implemented APIs are documented separately below; research gates remain explicit. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md).
+
+Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage and retained real-shot QA in progress for people, close-up hands, original-object reskin and clean-background code composition. Automatic geometry solving and production model selection remain research.
+
+## What the failed shots teach us
+
+| Observed failure | Diagnosis supported by the authored scenes | Required correction |
+|---|---|---|
+| A phone screen paints over a thumb, leaving a detached skin patch | The supplied matte loses the hand: foreground area drops from 12.44% at frame 59 to 0.18% at frame 60 and stays below 0.25% through frame 70. This is a missing foreground input, not just a rough edge. | Inspect plate, matte and composite together across the entire crossing; correct the subject track and correspondence, then refine its alpha edges. |
+| Menu text crosses a person's forehead | The menu scene has no subject matte. Its footer is clipped at the board's lower boundary in the inspected frames. Screen blending preserves board texture but cannot infer who is in front. | Fit the entire animated layout within the actual surface, then clip it; protect the person with a foreground holdout. |
+| An opaque price card erases the person's hair/head | There is no foreground holdout. Good planar tracking cannot fix layer order. | Treat all intersecting foreground subjects as required inputs. A plausible-looking board is not a passing result. |
+| A hand appears sliced through an added can | The example inserts a second can at an offset from the tracked original. Relative depth with hand-tuned near/far is being used as if it were registered scene geometry. | First distinguish insertion from reskinning. For a hand known to be in front, use its coherent alpha as the foreground constraint. |
+| A small labeled can sits over a larger generated can | Generating a world from a clay still did not preserve the product silhouette or proportions. | Reject the take for exact-object recomposition, or solve an explicit replacement workflow including removal of the original. Do not hide the mismatch with a smaller overlay. |
+
+These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. Those historical verdicts describe the original exports. Current implementation and repair evidence must name the new revisions separately.
+
+## Architecture decision: analyze, correct, cache, then render
+
+Keep the core model-neutral. A host or optional analysis package produces versioned masks, tracks, surface mappings and diagnostic reports. An author can correct them. Preview and export consume the same immutable artifacts. No model runs implicitly inside `render(clock)` and no model weights become a mandatory library dependency.
+
+Real-time compositing and real-time inference are different budgets. GPU/CPU acceleration can make preparation faster and enable interactive draft masks; it does not supply reliable geometry or physics by itself. Start with prepared per-frame data and GPU composition. Offer live draft inference only after profiling actual devices, with conspicuous provisional results and explicit promotion to a frozen render artifact.
+
+Bilibili provides a concrete live-inference precedent: its 2024 web.dev case study describes on-device MediaPipe Selfie Segmenter, worker/offscreen processing, reduced-resolution masks and CSS `mask-image` for comments behind people. Its older W3C presentation also describes mask-based rendering. These demonstrate a person-silhouette feature, not hair-level export alpha or collision simulation. Our choice to freeze reviewed masks for export is an architectural recommendation, not a claim that Bilibili precomputes everything. These are published primary sources; no authenticated production reverse engineering was performed. [Bilibili case study](https://web.dev/case-studies/bilibili-web-ai-improvements), [W3C presentation](https://www.w3.org/2019/03/23-chinese-web-zhaoxin-bilibili.pdf)
+
+### Proposed prepared-data contract
+
+Extend the existing derived-asset relationship with a versioned manifest. Names below are proposed fields, not accepted CLI flags:
+
+- Identity: source content digest, exact decoded dimensions/orientation/crop, frame count, rational time base and per-frame presentation timestamps; subject/surface IDs; model/checkpoint digest, preprocessing version and correction revision.
+- Semantics: `subject-alpha`, `foreground-color` where available, `surface-coverage`, `surface-map`, `depth`, `confidence` and `validity`. A binary segmentation probability is not silently relabeled as an alpha matte. Foreground alpha is white for foreground; linear alpha/data is not color-managed as display RGB.
+- Time: explicit source-frame correspondence and valid ranges. Plate, mask and track are fetched through one source-frame mapping, including trim, speed and reverse. Equal duration/FPS/count alone does not establish correspondence.
+- Storage: bounded, chunked cache; stream/prefetch under the existing decoded-memory budget. Use lossless data for final alpha and sufficiently precise depth/maps; lossy MP4 is diagnostic input, not the canonical final data format.
+- Failure: missing, stale, out-of-range, invalid or wrong-sized data fails final validation. Draft rendering can show the original plate plus a diagnostic. Never silently replace a missing holdout with an all-background mask, repeat a moving matte's last frame, or stretch a short matte to fit.
+
+Changing source bytes, orientation, crop or interpretation invalidates dependent analysis. Changing only the timeline edit map reuses analysis through an explicitly verified remap. Text edits reuse approved geometry/alpha, but invalidate content-dependent layout and occlusion review if the visible region changes.
+
+## Foreground preservation and layer order
+
+Start with explicit relationships such as `person in front of title` and `hand in front of screen`. Scope a holdout to the affected layer/group; a hand protecting the phone need not hide a separate foreground caption. Validate cycles and contradictory depth/ordering constraints. Occlusion state can change over a shot, but that change needs a tracked spatial relationship or an authored interval, not unrelated per-pixel guesses.
+
+For known foreground crossings, subject alpha owns the silhouette. Use temporally consistent, calibrated depth for ordering genuinely interleaved objects; raw per-frame normalized monocular depth must not slice fingers or faces. Depth confidence is separate from alpha confidence. One global foreground matte also cannot solve a hand that is simultaneously behind one object and in front of another.
+
+The preparation workflow is prompted video segmentation → tracked identity → positive/negative corrections at difficult frames → temporal propagation → alpha refinement around hair/fingers/motion blur → review. Track through disappearance/reappearance; reset temporal state at cuts. Sudden area collapse triggers a review/re-seeding candidate, not blind automatic acceptance: genuine occlusion or leaving the frame can also shrink a subject. Preserve legitimate holes between fingers and never assume every disconnected component is an error. Do not blur consecutive masks indiscriminately: that creates lag and ghost hands.
+
+Composite with explicit premultiplied-alpha and color-space conventions. Opaque protected interiors must preserve source pixels. At soft edges, copying `alpha × original plate` over a new background can retain the old background in hair and create a double edge. High-quality edge replacement requires decontaminated foreground color or a credible original-background estimate; document the approximation when those are absent. A soft mask alone does not prove a clean composite.
+
+Add diagnostic views for source, subject alpha, surface coverage, correspondence, confidence, final composite and difference inside protected regions. Provide brush/polygon corrections and an event-range view. Start with people in front of a title/board, then a separately gated close-up hand correction workflow; a portrait matting model is not proven on isolated fingers.
+
+## Four different placement operations
+
+1. **Planar insert:** board or phone. Render animated artwork in surface coordinates, project it with the track, clip to surface coverage, then apply foreground visibility. Explicitly exclude the bezel and check the full animated text bounds.
+2. **Reskin an existing rigid curved object:** select the original can, identify its body/silhouette and cap, estimate its pose/axis/radius and camera relationship, and fit a cylindrical UV or mesh mapping over time. Map the editable label into that surface; preserve lids, highlights, existing silhouette and contact shadow where appropriate. Reapply hand visibility. A featureless cylinder has ambiguous rotation; allow an authored seam/pose constraint and mark unobservable ranges.
+3. **Replace or insert a 3D object:** requires explicit camera/scale/contact placement and foreground ordering. If replacing an object whose silhouette changes, remove the old object's exposed pixels and recover newly revealed background. Clean-plate/inpainting work is separate, reviewed, and cannot be substituted by an extra mesh on top. Added objects need their own shadows/reflections; reskinning normally retains the original contact evidence.
+4. **Deforming surface:** cloth/skin needs a tracked mesh, dense UV correspondence or an atlas with visibility and disocclusion handling. A homography or cylinder is not sufficient. Start with a short cloth patch and a correction/import path; leave arbitrary bodies and loose folds experimental until tested.
+
+No mask fixes an impossible placement: if the recorded hand sweeps through the volume of an inserted can, making the whole hand foreground only changes the visible contradiction. Move the insert to a collision-free location, choose another take, or regenerate blocking. Reskinning the existing can avoids creating that new volume. Preserving shading during a reskin also needs an appearance model: a simple multiply blend retains the old albedo and cannot freely change a dark label into a light one. Begin with a blank neutral can, fit a shading/specular residual, and document where exact material recovery is ambiguous.
+
+Existing tools demonstrate the video surface-editing route. Mocha Pro documents PowerMesh-driven inserts, grid warps and tracked motion blur. Layered Neural Atlases learns per-shot mappings/alpha to propagate an atlas edit; CoDeF fits a canonical field and temporal deformation. These are evidence for feasibility, not drop-in real-time browser solutions or licenses to copy proprietary engines. [Mocha](https://borisfx.com/products/mocha-pro/), [Neural Atlases](https://layered-neural-atlases.github.io/), [CoDeF](https://qiuyu96.github.io/CoDeF/)
+
+Lovart advertises texture generation and image editing. Its public page does not establish which model implements an observed wrap effect or that exact artwork can be transferred through video with temporal geometry guarantees. Use it as a visual reference, not an inferred backend architecture. [Lovart texture feature](https://www.lovart.ai/features/ai-3d-texture)
+
+## Motion design is part of acceptance
+
+Every authored example declares its attachment space and timing: screen-space graphic, surface-attached artwork, or world-space object with a camera. Surface-attached text inherits the observed perspective; world text requires a real solve or an explicitly labeled authored approximation. Static printed labels should remain attached naturally; expressive animation belongs in a reveal, digital display or surrounding title when the brief calls for it.
+
+Deliver editable examples covering: staggered word/character reveals with readable holds; masked wipes and line draws; spring-like scale/rotation settles; text-on-path/orbits; tracked perspective titles; and a foreground-aware headline passing behind a person. Include at least one 3D/extruded or shader-treated title. Expose timing, stagger, easing, amplitude, path, typography, palette and attachment controls without restricting arbitrary renderer code.
+
+All code motion is a deterministic function of explicit clip animation time and seeded parameters, with any source/timeline mapping authored explicitly. Analytic curves or baked simulation caches make reverse/random seeks reproducible; never integrate a spring from the previous requested frame. Paused Web Animations can be driven through `currentTime` rather than wall-clock playback. Load fonts before measurement and verify script shaping, fallback and localized wrapping. [Web Animations clock](https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime)
+
+Compose the local animation before surface/camera projection, then visibility. Preserve the existing fixed `clock.mediaTime` for held footage/derived frames while code samples the shutter. Evaluate holdout against each code shutter sample so blurred letters cannot trail onto a protected face. This keeps correspondence; it does not reconstruct sub-frame subject motion absent from the plate. Label that physical limit and test moving masks rather than promising perfect motion-blurred edges.
+
+## Candidate analysis runtimes and evidence
+
+| Candidate | Intended role | Evidence and decision |
+|---|---|---|
+| SAM 2 / SAM 3.1 | Prompted object identity and temporal masks | SAM 2 code/checkpoints are Apache-2.0. SAM 3.1 is released, but uses SAM-specific terms and documented CUDA prerequisites; do not assume it runs in the target webview or inherits SAM 2's license. Neither automatically supplies hair alpha. [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3](https://github.com/facebookresearch/sam3), [SAM license](https://github.com/facebookresearch/sam3/blob/main/LICENSE) |
+| EdgeTAM | Optional lightweight tracked-mask candidate | Apache-2.0 code/checkpoints; upstream includes CoreML export and reports 16 FPS on iPhone 15 Pro Max. This is a segmentation benchmark, not a measured desktop export rate or alpha-quality guarantee. [Repository](https://github.com/facebookresearch/EdgeTAM) |
+| Robust Video Matting | Human-alpha benchmark and candidate adapter | Temporal recurrence; upstream provides ONNX, CoreML and TF.js variants. Reported RTX 3090 HD throughput is 172 FPS with FP16, downsample ratio .25, batch/chunk 1, excluding the video conversion pipeline. This is not a measured app speed. GPL-3.0 requires a deliberate distribution/compliance decision; it is not a permissive drop-in. [RVM](https://github.com/PeterL1n/RobustVideoMatting) |
+| MatAnyone family | Quality comparator for temporal matting | MatAnyone's S-Lab terms restrict ordinary use to non-commercial purposes; separately negotiate rights before commercial integration. Do not mistake a hosted listing for a redistribution grant. [License](https://github.com/pq-yang/MatAnyone/blob/main/LICENSE), [MatAnyone2 license](https://github.com/pq-yang/MatAnyone2/blob/main/LICENSE.txt) |
+| Video Depth Anything Small | Coarse temporally coherent depth | Upstream Small is Apache-2.0, Base/Large CC-BY-NC-4.0. Pin the exact checkpoint and verify its terms. Relative depth still needs registration/calibration and cannot be the sole skin-edge matte. [Repository](https://github.com/DepthAnything/Video-Depth-Anything) |
+| ONNX Runtime Web / native adapters | Optional execution backends | WebGPU where supported; WASM CPU fallback for validated small models. CoreML/native GPU candidates belong behind a host adapter. Probe operators, memory, webview support and seek/reset behavior; API support does not establish model portability. [ORT WebGPU](https://onnxruntime.ai/docs/tutorials/web/ep-webgpu.html) |
+
+No model is selected for distribution yet. Benchmark host-native and browser paths on actual Apple Silicon, Windows discrete/integrated GPU and CPU-only systems. Record decode + resize + inference + transfer + composition + encode, cold/warm latency, p50/p95, memory and energy, plus edge/temporal quality. Target cached 1080p playback at the project's 24/30 FPS; real-time inference is a measured optional tier, not a prerequisite for final export.
+
+## Ordered milestones and release gates
+
+| Phase | Deliverable | Exit evidence |
+|---|---|---|
+| H0 | Reclassify failed examples; retain originals; establish regression fixtures and source-frame annotations | Each reported failure has a reproducible source/mask/composite range; no production-ready badge on an unreviewed shot. |
+| H1a | Versioned correspondence/validity contract, shared frame access, explicit per-group holdout, correction import; human foreground first | Person crossing board/title passes every crossing frame in preview and export; missing/stale/short data fails safely. Include one kinetic headline now. |
+| H1b | Close-up hand segmentation, collapse detection and correction propagation | Thumb remains whole through entry, tap, lift and exit; all-frame correspondence, visibility and edge checks pass. Portrait-model success cannot waive this gate. |
+| H2 | Rigid-cylinder surface mapping and appearance-preserving label wrap | One original can, correct scale and placement, readable exact label, no exposed duplicate body, hand fully coherent through the crossing. |
+| H3 | Full kinetic typography examples and controls | At least three distinct treatments, random-seek/reverse/shutter checks, localization, readable holds and correct occlusion for every treatment. |
+| H4 | Optional accelerated analysis adapters | Actual device/end-to-end benchmark plus license/checkpoint receipts; cached fallback remains usable. |
+| H5 | Deformable meshes/atlases, calibrated 3D insertion and controlled generation | Separate experimental gates for cloth folds, camera/geometry consistency, clean background recovery and material fidelity. |
+
+Use generated and filmed examples; static, pan/push and handheld; fast finger entry, loose hair, motion blur, full occlusion/reappearance, crops, reverse/retime, and missing frames. For short clips, inspect every decoded output frame in contact sheets and full-resolution crossing crops, plus normal/slow playback. For longer clips, automated all-frame checks and reviewed event ranges supplement a complete playback; disclose unreviewed frames. Three-frame checks are smoke tests only.
+
+Proposed measurable gates: zero missing correspondence entries; no overlay pixels in annotated opaque foreground interiors before encoding; no detached/erased finger or head in any reviewed frame; measured boundary error on annotated events (target p95 ≤2 output pixels at 1080p, any >4 triggers correction); surface landmark drift and silhouette mismatch reported separately from tracker confidence; no unplanned subject-depth flips; layout bounds valid throughout animation. These are engineering targets to calibrate against annotations, not achieved benchmark results. Semi-transparent hair is evaluated with alpha/edge-color and temporal metrics, not a binary zero-overlap test. Flow-warp residuals, sudden area changes and components flag review, but cannot establish truth without annotations.
+
+The acceptance report records exact revisions, frame ranges, assets, model/correction provenance, annotated failures, best and worst frames, the full playable clip, and separate **render correctness**, **analysis correctness**, **art direction** and **final usability** verdicts. An export that completes can still fail the shot.
diff --git a/docs/hybrid-concurrent-recovery-2026-11-14.md b/docs/hybrid-concurrent-recovery-2026-11-14.md
new file mode 100644
index 0000000..ab82847
--- /dev/null
+++ b/docs/hybrid-concurrent-recovery-2026-11-14.md
@@ -0,0 +1,52 @@
+# Concurrent crash recovery: adopted with a bounded platform scope
+
+2026-11-14 · FLOW1 remains partial · three additional scoped checks resolved
+
+The SDK now uses numbered lock generations for edits/imports and a private job registry for CLI render recovery. This replaces the rejected stale-file deletion proposal. The coordinator applied Fable's replacement to the current SDK, fixed a mutating dry run, added cancellation regressions, and reran real-process fault tests before adoption. This does not close native-app or provider integration.
+
+## What changes for the user
+
+- Interrupting `asset-add` with Ctrl-C cancels its decoder, removes its staging files and leaves the project editable. SIGTERM and SIGHUP follow the same cleanup path.
+- After a killed edit/import, the next edit can take over a provably dead owner's numbered lock without deleting a successor's lock. An orphaned decoder is not signalled; its files remain until it exits and a later edit cleans them.
+- Each CLI render records its owned temporary locations before allocating them. The next render attempts recovery for that project. `recover DIR` performs the same recovery explicitly.
+- Automatic recovery sends no signals. A dead job with running children is left intact and reported. `recover DIR --stop-browsers` explicitly requests SIGTERM for that job's verified orphan browser; it never uses SIGKILL.
+- `recover DIR --dry-run` only reports. The coordinator found that the proposed version created registry/lock files; the adopted version does not create, acquire, reclaim or release anything.
+- Published output is preserved. A dead reservation is removed only when its receipt identifies that job and no output was published. Unknown owners and records are left alone.
+
+The job registry defaults to a private per-user run directory and can be isolated with `EDITABLEFRAMES_STATE_DIR`. Recovery instructions never come from a downloaded project's job file. This is still trusted local code, not protection against hostile code running as the same user.
+
+## Why the lock changed
+
+The rejected proposal read a dead lock, removed it, and created its replacement. A second contender could remove the first contender's live replacement. Fable reproduced simultaneous holders and also found false death detection across time zones/process renaming and receipt deletion by concurrent recoverers.
+
+The new protocol publishes a complete next-generation owner record using exclusive creation. Contenders never remove the current owner's record to acquire. A contender that resumes behind a newer generation withdraws. Owner identity uses host, PID namespace, PID and UTC start time; an inconclusive process query refuses takeover. Recovery of shared output reservations is serialized separately.
+
+This passed the recorded schedules and real processes; it is not a universal proof for every filesystem or operating system.
+
+## Verification on the adopted source
+
+| Fresh coordinator check | Result |
+|---|---|
+| SDK unit tests | 147 passed, zero failed |
+| Build | Passed |
+| Browser and beta integration | Passed using installed Chromium; no new browser download |
+| Real stale-lock contention | 30 rounds, six contenders, exactly one winner per round, zero overlapping holders |
+| Real CLI edit/import faults | 19/19 passed |
+| Real browser-render crash/recovery faults | 21/21 passed |
+| Sentinels | Files, unrelated browser and unrelated process survived |
+| Dry-run and graceful import cancellation regressions | Included in the 147 tests; SIGINT/SIGTERM/SIGHUP and no filesystem writes |
+
+The coordinator reran the worker's integration harness against the actual SDK checkout in separate disposable projects. These are independent executions of the same harness, not an independently designed fault model. Browser tests were serialized with other rendering work. No paid call, credential read, model download or native-app launch was needed.
+
+Fable's larger retained study additionally reports 30,650 exhaustive two-contender schedules, 80,000 sampled schedules with injected deaths, and 400 actual killed-holder rounds. Those are worker results, separate from the fresh coordinator runs. Four failed designs remain retained, including a recovery guard that wedged when its own recoverer died.
+
+## Still open
+
+- Evidence is one Mac on APFS. Linux was not run. Windows cannot verify owner identity and does not automatically take over or recover dead owners.
+- Caching/network filesystems and same-named machines sharing a project are unsupported by this evidence. Power-loss durability was not tested; lock records are not an fsync protocol.
+- PID/start-time rechecks narrow process-reuse risk but are not an atomic OS process handle. Explicit browser termination remains opt-in.
+- Old bare lock files from earlier SDK versions cannot be safely attributed and need deliberate manual recovery after confirming no owner is running.
+- Library `render()` callers and preview processes do not automatically gain the CLI's job ownership contract. Native app integration remains separate.
+- Asset removal, arbitrary live resources outside pinned assets, provider billing/reconciliation and audiovisual playback review remain open.
+
+Existing projects require explicit `rebind` after the runtime change. Code-generated scenes and accepted generated footage are unchanged: this work makes interruption/restart safer, not the picture more realistic. LIGHT1, MASK1, HUMAN1 and the story/interaction quality boundaries retain their previous limits.
diff --git a/docs/hybrid-experiment-map.html b/docs/hybrid-experiment-map.html
new file mode 100644
index 0000000..c30da1f
--- /dev/null
+++ b/docs/hybrid-experiment-map.html
@@ -0,0 +1,7 @@
+
Video experiment map
How should we make this movie?
Build the stage. Make the action together. Combine the pieces. Pick the right tool for each shot.
Build with code
Like a toy theatre: keep the actors, lights and moves editable.
Make action together
Like filming a play: hands and props must share the same action.
Combine the pieces
Like a scrapbook: add words, cut-outs and backgrounds.
Closing the gaps · 2026-11-14
38 tested subchecks resolved · 0/11 whole work items closed · $0 new hosted calls
Open a row to see what changed, what still fails, and the artifacts. A green subcheck only covers its stated test. This is an active checkpoint, not completion of the research programme.
Like a mirror: a shiny object should show the things beside it. The new test fixes that for a ball, box and floor. Real devices are the next test.
Before: 20.0
After: 2.4
Lower is better: average colour-code error on the test cylinder in held-out motion. This does not score the rest of the picture.
Fast code: move shapes, lights and cameras. More rendering time: clean tiny shiny highlights and calculate light bouncing around. Generated video: believable human performances when we lack the needed models and motion.
Still open: real-product proxy accuracy, grain, bounce light and production review. LIGHT1 stays partial.
ST1 · Make the preferred story dependableImproved; gap remainsCoordinator verification of resumed Fable result
Acceptance: Random/reverse seeks across every shot and cut match sequential reference in the same renderer; audio and all exposed controls checked; contact and framing improved.
Current limit: Painted faces, rigid joints, contact staging, local fonts and stock voices remain. No audio listening review or full native desktop source/audio/history acceptance.
What changed: All1152 sequential frames reproduced,228 new seeks and all12 controls passed. CLI samples now also pass revision-checked edits, stale rejection and byte-identical undo. These close runtime subchecks on this Mac; visual performance and native integration remain open.
Full film/audio/native app integration and other devices remain separate.
Completed Fable film — New 48-second export; visual and runtime acceptance are separate. Retained local evidence; not bundled.
Fable QA record — Worker-produced format, seek, control and audio measurements. Retained local evidence; not bundled.
Shot contact sheet — One frame per shot from the delivered MP4. Retained local evidence; not bundled.
Coordinator verification — 1152 sequential hashes, 228 repeat checks, all12 control edits. Retained local evidence; not bundled.
CLI edit/undo evidence — Three actual CLI-rendered frames; no full film/native acceptance claim. Retained local evidence; not bundled.
Exposure control: before — Original source and default lighting. Retained local evidence; not bundled.
Exposure control: after — Same frame after declared control edit. Retained local evidence; not bundled.
ST2-3 · Reuse the cast beyond the dungeonImproved; gap remainsFable 5.2 implementation · coordinator verification
Acceptance: At least two genuinely different short styles with reused rigs, a shared-prop action and evidence of editable changes.
Current limit: Two action briefs, not a general action library. The second requires a tray rim and finger clearance; the original rocket grasp remains unresolved. Film-scale contact, wrist/finger naturalness, gaze, audio listening, full-film CLI and native delivery remain open.
What changed: Three 12.5-second films reuse the original cast in sci-fi, cel-shaded village and toy/clay sets. Hands follow one shared prop trajectory. Coordinator reproduced 102 new frame samples, checked all 27 declared controls (one caption timing correction), decoded all 900 delivered video frames and verified CLI exposure edit/stale rejection/exact undo on three source frames per style. A second lift/turn/carry/set-down brief now runs in sci-fi and clay: cast/rig/look transfer, but action, grip and mesh probes required new source. Coordinator verified80 more frames,20 controls,672 decoded frames and six injected table-contact failures.
✓ Cast reused by reference — Cast/rig/look now transferred across two briefs. Second action needed23.7KB new choreography and a prop-specific grip; not a generic action library.
✓ Contrasting rendered styles — Sci-fi, cel-shaded village and toy/clay: three12.5-second films with distinct sets, proportions/materials and timing. Not visual-production approval.
✓ Independent seek reproduction — First brief102/102 and second brief80/80 fresh samples match saved sequential hashes, including cuts and contact transitions.
✓ Every declared control — First brief27 controls plus second brief20 change and restore individually. Caption timing correction retained for the first brief.
✓ CLI revision and undo specimens — Three source frames per style; exposure edit, stale rejection and exact undo pass.
◐ Natural contact and broader reuse — Second brief improves a tray grip, not the original rocket. Natural fingers/wrists, arbitrary props and per-action reuse remain partial.
◐ Sound and full native delivery — Five films decode:1,572 video frames total. Audio duration checked but not listened to. Full-film/native acceptance remains open.
✓ Second brief releases after table contact — Fresh672-frame geometry replay: touchdown215/216, both-hands hold through223/224; no unsupported frame under declared rules.
✓ Table checks detect deliberately bad poses — Both styles flag20mm floating,20mm sinking and missed-table placements. Bounded mesh-ray sensitivity, not full collision physics.
Attempts and artifacts (8 attempts · 23 artifacts)Fable worker launch
Read completed source and inspected APIs.
Result: Provider rate-limit termination; no new style source found.
Await provider availability; do not count this as a failed visual method.
Resumed cross-style implementation
Reuse original cast by reference; add shared world-space limb IK, foot-planted gait and prop-first handoff. Per-style proportions, materials, cameras, sets and motion timing.
Result: Three distinct rendered films, with the same walk → dialogue → transfer brief. Original baseline modules imported rather than rewritten.
This proves reuse for one brief; test a genuinely different action before proposing production modules.
Contact failures retained and revised
Worker inspected sampled digit clearance and limb reach through the whole action. Added lifted thumb approach, guarded finger closure and lower walking pelvis.
Result: Earlier reported penetrations of 21 mm and 19 mm and out-of-reach legs of 24 mm no longer appear in final worker probes. Clay grasp still reads poorly.
Sphere/capsule probes are not mesh collision checks; palms, bodies, set contact and natural grasp remain unverified.
Coordinator runtime and media checks
Fresh reverse-first and scattered frames including cuts/contact; individual edits; decode all three MP4s.
Result: 102/102 sampled hashes match, 27/27 controls change and restore at appropriate visible frames, 900 video frames decode. First sci-fi caption test chose a speech pause; preserved and corrected at frame120.
Same Mac/browser. Audio duration verified, not listened to; contact-sheet visual review is not normal-speed playback.
Actual CLI editing specimens
Import unmodified scene and style source; sample frames30,120,244, change exposure through revision-checked apply, repeat stale proposal, undo.
Result: All three styles pass: nine sampled frames change and restore exactly; stale proposals refused.
Only exposure through CLI; full film/audio, all CLI controls and native integration remain open.
Second brief: cast transfers, action rewritten
Reuse unchanged cast/rig/look in sci-fi and clay; author a two-handed carry, turn and set-down with dedicated rim clamp.
Result: Two14-second films delivered. New23.7KB choreography plus grip/probes; no general action reuse claim.
Keep per-shot action separate from reusable cast and visual style.
Tray and landing geometry revised
Worker mesh probes found clay runners sunk1.3mm and overhanging original stand4.7mm each end. Corrected rest height and widened stand; failed pass retained.
Result: Tray remains supported and hands release after contact. Prop has runners that provide finger space.
Not a same-prop fix to the rocket; arbitrary flat-bottom props remain unsupported by this grip.
Coordinator verification and deliberate faults
Fresh rendered samples, all controls, full decode and Node probe replay. Perturb settled tray up/down20mm and move it off table.
Result: 80/80 frames,20/20 controls,672 decoded/replayed frames pass. All six bad poses detected; both resting baselines valid.
Film-scale grip readability, natural motion and listening still need review.
Scifi — full12.5-second film — Rendered from the shared cast and action modules. Retained local evidence; not bundled.
Scifi — short handoff preview — Five-second excerpt for quick comparison; full-resolution film linked above. Retained local evidence; not bundled.
Village — full12.5-second film — Rendered from the shared cast and action modules. Retained local evidence; not bundled.
Village — short handoff preview — Five-second excerpt for quick comparison; full-resolution film linked above. Retained local evidence; not bundled.
Clay — full12.5-second film — Editable source retained. Clay grasp remains unresolved. Retained local evidence; not bundled.
Clay — short handoff preview — Five-second excerpt for quick comparison; full-resolution film linked above. Retained local evidence; not bundled.
Three styles compared — Same cast and action, three visual treatments. Retained local evidence; not bundled.
Clay remaining grasp problem — Flat hands and workbench overlap; passing integrity checks do not close this. Retained local evidence; not bundled.
Worker findings and retained attempts — Scope, limitations, failed contact attempts and reproduction commands. Retained local evidence; not bundled.
Coordinator sampled verification — 102 frame comparisons and27 control trials; one caption timing correction is separate. Retained local evidence; not bundled.
Caption timing correction — Frame120 has visible speech; change/restoration passes. Retained local evidence; not bundled.
CLI revision/undo evidence — Three independent CLI projects; nine source-frame samples total. Retained local evidence; not bundled.
Full media decode — 900 video frames, all three stereo tracks12.5seconds; no listening claim. Retained local evidence; not bundled.
Scifi second brief — full14-second film — Two-handed tray carry, turn, set down and release. Grip requires rim and underside clearance. Retained local evidence; not bundled.
Scifi second brief — set-down preview — Two-handed tray carry, turn, set down and release. Grip requires rim and underside clearance. Retained local evidence; not bundled.
Clay second brief — full14-second film — Two-handed tray carry, turn, set down and release. Grip requires rim and underside clearance. Retained local evidence; not bundled.
Clay second brief — set-down preview — Two-handed tray carry, turn, set down and release. Grip requires rim and underside clearance. Retained local evidence; not bundled.
Clay grasp comparison — Different prop: rocket before, rimmed tray after. Contact-zoom views are separate diagnostic renders. Retained local evidence; not bundled.
Second brief in both styles — Actual delivered-film moments. Retained local evidence; not bundled.
Second brief report — Reused modules, new action, failed attempts and limitations. Retained local evidence; not bundled.
Coordinator second-brief checks — 80 frame samples and20 individual controls. Retained local evidence; not bundled.
Geometry support replay — 672-frame replay; uses worker probe implementation. Retained local evidence; not bundled.
Deliberate geometry faults — Floating, sinking and missed table tests in both actual scenes. Retained local evidence; not bundled.
LIGHT1 · Make products respond properly to moving lightsImproved; gap remainsCoordinator verification of Fable motion and proxy study
Acceptance: Matched before/after clips, face/reflection gradients, shadow/decal checks, screen treatment and repeatability; inspect current v6 before repeating old fixes.
Current limit: Exact simple-shape proxies now work; approximate real-product proxies remain untested. Small polished highlights shimmer without supersampling; low-tap reflections are grainy. Matte bounce, multiple bounces, native integration, normal-speed review and other hardware remain open.
What changed: Depth-aware anisotropic planar lookup restores lid/display reflections on the deck. Geometry-placed cup/saucer probes reduce bounce-light bias. Geometry hit scores were insufficient: the clean screen partly omits valid reflections. No library default adopted. Opt-in direct-light repair verified from retained arrays; one GGX direct-light reference agrees with a CPU integral. Offline rendering remains the code route for difficult light transport. New independent one-bounce reference and exact plane/sphere/box reflection taps validate a narrower raster route; polished sampling limits remain explicit.
Queued next experiment: Approximate proxies on actual product geometry. Test mesh-based references, self-reflection and omitted thin parts under motion before adopting a product-lighting route.
Measured response, not a quality score. Each pair has its own scale.
Notebook glare peak — lower here is more readable mean screen luma; same material
Before129
After40.2
Notebook floor variation — remaining tradeoff luma range across directional sweep
Before3.02
After19.7
Cup warm/cool response — lamp moved mean absolute RGB codes; composition changed
Before1.15
After40.7
Palm-rest mean reflection energy / reference — tuned A reference=1; same-renderer one-bounce gather, not whole-image accuracy
Before2.04
After1.01
Cafe render cost at equal32 samples ms/frame on this Mac; excludes capture/encode
Before48.7
After70.6
I cup direct light / reference — ideal 1 regional mean, retained arrays; not whole-picture quality
Before1.35
After1
Glossy cylinder mean error — lower is better display codes versus Cycles; worker clip metric, substantial error remains
Before22.3
After18.5
Held-out cylinder reflection error — lower is better mean display codes on cylinder pixels; exact simple-shape proxies
Before20
After2.4
✓ Notebook light reaches reflections — Paired direction/colour controls now affect the metal and reference spheres; not a claim of fully physical light transport.
✓ Lamp reaches pastry — Warm/cool pastry-mask change rises from0 to3.04 codes. This is a narrow rim light; placement changed.
✓ Independent repeatability and controls — Earlier292 samples/26 edits plus refinement96 samples/21 edits restore on this Mac/browser. Integrity does not validate the choice of measurement region.
◐ Finished lighting and display readability — Fixed-pose glare avoidance remains demonstrated, but broad reflection tails are missing from the moving display; clean UI is not proof of correct coating.
◐ Native and wider product coverage — Only two local examples; no native delivery, additional hardware or all-product acceptance.
✓ Notebook glare avoided without material change — For this fixed pose/path: screen peak129.20→40.17; emission artwork unchanged; metal still responds.
✓ Finite-source café shadow transitions — Same composition: far plate transition23.92px, near contact4.79px; deterministic64-sample light.
✓ Cup front responds after lamp repositioning — Explicit composition change: warm/cool response1.15→40.72; not a repair of the old placement.
◐ Reflection content under moving camera and products — Independent pixel review improves flat deck and cup/saucer; broader light transport is not resolved. Coordinator recomputed retained point ratios and decoded 480 preview frames.
◐ Calibrated glossy and multi-bounce reference — Direct and one-bounce simple-scene references independently validated. Multi-bounce and broader materials remain open; exact proxies fix tested spatial reflections but not matte bounce.
✓ Direct café lamp calibration in arrangements A and I — Coordinator recomputed retained direct ratios: cup .998/1.000, saucer1.007/1.008. Scoped research repair, not whole-image accuracy or default adoption.
✓ Direct GGX reference agreement in three retained poses — Prior coordinator recomputation plus new independent worker derivation in five arrangements. No universal material or hardware claim.
✓ Independent one-bounce reference for five analytic arrangements — Separate numpy estimator agrees with Cycles at 0.9976–1.0017 energy ratio; white GGX plus matte neighbours only.
✓ Satin/polished temporal sampling boundary measured — Satin AA-off remains accurate in these tests; tiny polished highlights shimmer. Supersampling demonstrated; no global AA change.
✓ Exact-proxy spatial reflections on held-out simple scenes — Upper band 0.99–1.03× reference; sphere effect slope 0.96–0.98. Low-tap grain and actual product approximation remain open.
Attempts and artifacts (22 attempts · 39 artifacts)Current-source audit and baseline probes
Copied current laptop/cafe scenes, captured one reproduction frame and seven directional/colour key-light probes with reference spheres.
Result: Receipts report no capture errors. videos=[] and seek=null; no corrected-after output or completed result report. Provider usage limit terminated the run.
Resume the unfinished study when the requested provider is available; retain existing baseline. Do not count quota interruption as a failed lighting method.
Notebook A1 'livekey': the v6 key reflection card orbits with the key and takes key colour and strength; PMREM re-baked when key state changes
Notebook A1 'livekey': the v6 key reflection card orbits with the key and takes key colour and strength; PMREM re-baked when key state changes
Result: Chrome and clearcoat highlights now move with the key and warm/cool with it. Metal still reflects neutral studio cards while the real wall turns orange.
Coupled the reflection but not the room; continued with A2.
Notebook A2 'liveroom': environment = per-frame cube capture of the RENDERED set (lit floor + sweep, layer-filtered, product excluded) + studio cards. Capture uses environment=null to avoid frame-history dependence.
Notebook A2 'liveroom': environment = per-frame cube capture of the RENDERED set (lit floor + sweep, layer-filtered, product excluded) + studio cards. Capture uses environment=null to avoid frame-history dependence.
Result: Metal and chrome take the colour of the room the key lights (chrome coupling 0.035 to 0.49). Seek-deterministic. Side effect: more veiling reflection on the display. Later isolation corrects the veil cause: a static fill card, not the lit room.
Kept.
Notebook A3 'contact': footprint contact occlusion (depth-from-below ortho render, two blur passes) replaces the fixed ellipse
Notebook A3 'contact': footprint contact occlusion (depth-from-below ortho render, two blur passes) replaces the fixed ellipse
Result: Front edge grounding appeared improved. Original ratio0.84→0.79 was contaminated by diagnostic spheres; corrected refs-off ratio0.991→0.909. See later verification.
Kept.
Notebook A4/A5 'flags': black negative-fill flags behind/above camera (two placements) to cut display veiling
Notebook A4/A5 'flags': black negative-fill flags behind/above camera (two placements) to cut display veiling
Result: No measurable effect (screen luma 60.2 to 59.7). The veil does not come from the direction behind the camera.
Stopped after 2 placements; flags left out of the final. The source of the veil is not isolated; this needs a per-lobe environment debug view or a display-coating material decision.
Notebook clip attempt 1 (rendered, retained in pc/runs/after-attempt1-occluded)
Notebook clip attempt 1 (rendered, retained in pc/runs/after-attempt1-occluded)
Result: The moving key card was eclipsed by a static fill card inside the cube capture, giving an abrupt screen veil step at frames 42-43 (luma 68.6 to 62.3).
Fixed: the key card is drawn unoccluded by other emitter cards (depthTest off, renderOrder). The re-render shows the real mirror-direction glare instead (smooth sweep, peak 129).
Cafe C1 'physlamp' (no distance cutoff, inverse-square, stronger), C2 lamp nearer, C3 lower key/env ratio
Cafe C1 'physlamp' (no distance cutoff, inverse-square, stronger), C2 lamp nearer, C3 lower key/env ratio
Result: Pastry still dark in every variant.
Parameter changes did not address the cause; switched to isolation diagnosis.
Result: The croissant sits in the cup's shadow from the lamp in the original placement.
Root cause found.
Cafe C4/C5 clear line-of-sight placement behind cup; C6 bulb no longer self-occluding (bulb mesh surrounded the point light)
Cafe C4/C5 clear line-of-sight placement behind cup; C6 bulb no longer self-occluding (bulb mesh surrounded the point light)
Result: C4/C5: pastry only grazed (distance 3.2, near the shade cut-off). C6: no visible change; the bulb fix is kept as a correctness change but is not credited with the result.
Continued.
Cafe C10/C11 lamp between and behind pastry and cup (0.9,0,-1.7) + no cutoff + bulb fix + lower key/env ratio
Cafe C10/C11 lamp between and behind pastry and cup (0.9,0,-1.7) + no cutoff + bulb fix + lower key/env ratio
Result: The pastry takes a warm/cool rim light, the plate gets a lamp pool, and the croissant casts a shadow toward camera. Chosen as AFTER (C11).
Accepted as partial. The lamp is backlighting, so the cup front and grey sphere barely change.
Coordinator fresh validation
Reverse-first frame selection, comparison with worker sequential hashes, restoration after each control, independent ROI recomputation and media decode.
Result: 292 frame samples and26 individual edits/restorations pass with no page/request errors. Visual inspection confirms glare and limited café rim-light response. Correction: recomputation reused sphere-contaminated regions and therefore did not validate their product-only meaning.
Seek an independent critical review; keep whole LIGHT1 partial.
Independent critique corrects measurement regions
Compare hero renders with diagnostic spheres hidden against refs-on renders; isolate individual environment cards and lit room.
Result: About40–49% of three product/contact regions were affected by spheres. Left palm sweep1.58→20.46, contact ratio0.991→0.909 supersede previous figures. Resting veil comes mainly from a fill card.
Measure products with diagnostic objects hidden; keep reference-sphere response separate.
Aligned key, elevated path and black flag
Align reflection-card direction to light, move its path above mirror zone, place a flag in front of fill. Same product material.
Same Mac/browser; no full-motion visual or broader-device approval.
Moving camera plus turning products
Matched visible emitters, local per-object captures, planar reflections; tuned and held-out layouts.
Result: Worker reports less screen veil and restored bulb reflections. Coordinator decodes all five 120-frame previews; independent physical validation pending.
Repair self-reflection and cafe irradiance; do not count worker claims as new independently resolved checks.
Independent per-point reflection and bounce review
Surface-point cube gathers, direct/indirect term isolation, planar anisotropic sampling, geometry-placed probe rings and matte Cycles comparison.
Result: Deck mean reflection energy1.53–2.04x becomes0.91–1.01x; cup/saucer bias shrinks. Curved surfaces, lobe tails and penumbra calibration still fail.
Separate reference/calibration defects from raster approximations before adoption.
Coordinator retained-evidence verification
Strict decode of four previews; fresh arithmetic from raw notebook/cafe point receipts; inspect comparison sheets and shader diff.
Result: 480 frames decode; notebook energy ratios and cafe indirect ratios reproduce. No fresh render, playback approval or independent physical ground truth.
Keep LIGHT1 partial and the resolved count unchanged.
Opus direct calibration, GGX reference and remaining probe error
CPU occlusion/GGX reference, matched raster/Cycles, world-space bias and normal-offset repair; opt-in anti-aliasing and floor-plane variants.
Result: Direct lamp agreement repaired. Bias-only and two clipping attempts failed. Upper reflection band remains ~1.75x and neighbouring sphere missing; 48-frame comparison decoded by coordinator.
Review reference and temporal aliasing; test one bounded proxy-aware reflection integration before deciding on offline export.
Independent reference, moving highlights and exact spatial proxies
Separate analytic integration; 48-frame motion tests at two scales/roughnesses; held-out simple proxy arrangements and 24-frame motion.
Result: Upper-band ratio 1.70–2.47 → 0.99–1.03; held-out cylinder error 20.0 → 2.4 codes. Coordinator verified 86 hashes, 408 decoded preview frames and 45 regional ratios. Old freeze has three mismatches.
Test approximate real-product proxies. High sampling or offline rendering remains needed; no default adopted.
Notebook: before and after — 7-second comparison; watch the display glare during the key sweep. Retained local evidence; not bundled.
Café: before and after — 6-second comparison; lamp moved, photo background unchanged. Retained local evidence; not bundled.
Notebook still comparison — Default and changed key poses; finish remains partial. Retained local evidence; not bundled.
Café still comparison — Includes practical-only diagnosis showing occlusion of the original pastry. Retained local evidence; not bundled.
Remaining screen glare — Visible limitation retained rather than hidden. Retained local evidence; not bundled.
Worker report and failed attempts — Includes unsuccessful flags, lamp positions and the earlier reflection-card eclipse. Retained local evidence; not bundled.
Independent render checks — Fresh sampled rendering and individual control restoration. Retained local evidence; not bundled.
Independent measurements — Recomputed response and full media decode; recorded separately from worker results. Retained local evidence; not bundled.
Notebook glare before/after — Same display material; light path and flag changed. Retained local evidence; not bundled.
Café source-size before/after — Same composition, finite source; compare shadow edges. Retained local evidence; not bundled.
Café front-right lamp — Composition change; cup front lights up, reflection response still limited. Retained local evidence; not bundled.
Notebook full-frame comparison — Readable UI; floor and reflection tradeoffs visible. Retained local evidence; not bundled.
Café penumbra/contact comparison — Far shadows soften more than contact edges. Retained local evidence; not bundled.
Corrected veil diagnosis — Fill card drives resting veil; lit room removal barely changes it. Retained local evidence; not bundled.
Refinement attempts and limits — Failed material variants, approximations and benchmark scope. Retained local evidence; not bundled.
Coordinator verification.json — 96 new sample frames and21 individual edits. Retained local evidence; not bundled.
Coordinator measurements.json — Corrected refs-off measurements,936 decoded frames and independent shadow profiles. Retained local evidence; not bundled.
Notebook motion comparison — Old versus new; screen clearer, room darker. Retained local evidence; not bundled.
Cafe motion comparison — Old versus new; brighter cup is not yet calibrated. Retained local evidence; not bundled.
Glare limit — A real mirror-zone crossing must remain visible. Retained local evidence; not bundled.
Moving reflection evidence — Worker measurements and retained failure routes. Retained local evidence; not bundled.
Coordinator decode verification — All five previews decode; no new rendering or physical-accuracy claim. Retained local evidence; not bundled.
Notebook: old / Opus / Fable — Five seconds; deck self-reflection changes, screen unchanged. Retained local evidence; not bundled.
Cafe: old / Opus / Fable — Five seconds; cup and saucer probe placement changes. Retained local evidence; not bundled.
Notebook comparison sheets — Tuned and new arrangements, three moments each. Retained local evidence; not bundled.
Cafe comparison sheets — Targeted bounce corrections; still an authored product concept. Retained local evidence; not bundled.
Independent reflection study — Per-point reference, offline mismatch and retained failures. Retained local evidence; not bundled.
Coordinator verification — Decode and arithmetic only; no fresh rendering. Retained local evidence; not bundled.
Reflection routing checkpoint — Why difficult light transport belongs to offline code rendering before assuming diffusion. Retained local evidence; not bundled.
Glossy moving-light comparison — Frozen raster | experimental AA/plane variant | Cycles. 48 decoded frames; no visual approval. Retained local evidence; not bundled.
Café direct-light calibration — Retained, repaired and offline references; direct ratio maps. Retained local evidence; not bundled.
Current routing and verification — Raster versus offline rendering versus joint diffusion. Retained local evidence; not bundled.
Recomputed evidence — Four café means, 4784 glossy reference points, 14 hashes and clip decode. Retained local evidence; not bundled.
Moving reflection comparison — Centre probe | proxy taps | one-bounce Cycles; exact simple proxies, not actual products. Retained local evidence; not bundled.
Polished highlight sampling comparison — Clipped and unclipped exposure; AA-off shimmer is visible in the measured temporal signal. Retained local evidence; not bundled.
Held-out reflection still — Upper band and sphere restored; grain and dark matte neighbour remain. Retained local evidence; not bundled.
Highlight energy through motion — Small polished highlight pumps with AA off; satin stays stable. Retained local evidence; not bundled.
Motion and proxy study — Independent reference, scope, attempts and reproduction commands. Retained local evidence; not bundled.
Coordinator motion/proxy verification — 86 hashes, 408 decoded preview frames, 45 independently recomputed regional ratios; no fresh render. Retained local evidence; not bundled.
TRACK1 · Expose and contain tracking failuresImproved; gap remainsCoordinator
Acceptance: Retained wrong-face and false-confidence counterexamples reproduced; a useful quality/review mechanism rejects or flags failures without claiming correctness from round-trip agreement.
Current limit: Worst corner drift remains6.861px at correlation0.956. Diagnostics cannot identify a textured wrong plane or recover vanished targets; original filmed failure clips remain unavailable.
What changed: Implemented per-frame target-interior texture diagnostics and honest confidence semantics in the analysis tool. All49 frames of the retained wrong-track case are flagged for review. Existing alignment is deliberately unchanged.
◐ Correct the wrong alignment — Not fixed.6.861px worst drift remains; this safeguard is not a new tracker.
Attempts and artifacts (1 attempts · 3 artifacts)Target observability guard
Fixed-scale 4x4 two-axis gradient support inside the selected quad; exclude surrounding template margin.
Result: Blank, single-edge, localized and out-of-frame evidence flagged; distributed texture recognized without accuracy approval.13 existing and6 new tests pass.
Independent boundaries/identity and real-footage visibility acceptance remain open.
Same drift, explicit warning — Green is the known surface; magenta is the tracker. The warning improves detection, not alignment. Retained local evidence; not bundled.
Before/after warning diagnostic — The same wrong track, now explicitly flagged. No geometry-fix claim. Retained local evidence; not bundled.
Tracker measurements — 49-frame retained counterexample and diagnostic output. Retained local evidence; not bundled.
FLOW1 · Turn scene packets into a recoverable workflowImproved; gap remainsFable 5.2 protocol repair · coordinator verification and adoption
Acceptance: Local persisted job/receipt/import checks cover restart, failed/ambiguous work, reference order and actual decoded timing; no new paid submissions.
Current limit: Local Mac recovery checks pass; native/provider integration, other operating systems, network filesystems and power-loss durability remain unverified. Asset removal and live non-asset resources remain open.
What changed: Real CLI staging, frozen replay packet, generated take and live overlays demonstrated. Audio loss and unity-rate stretching fixed in SDK. Coordinator also repairs identity/reference mismatch in research ledger. Numbered edit locks and private CLI render-job recovery now adopted after fresh fault verification; automatic recovery sends no signals.
Experiment completed; limits remain: Concurrent recovery replacement adopted in SDK. 147 tests, 19 edit/import faults, 21 render faults and 30 six-contender rounds pass on the current Mac checkout. Native/provider and cross-platform gates remain.
✓ Crash and concurrent-submit safety — Killed after durable submission marker; restart becomes ambiguous; second owner and automatic retry refused.
✓ Ordered inputs and stale edits — Reference reordering, changed bytes, changed endpoint/action and stale revision refused. New replay loader descriptor/identity gap reproduced and fixed in coordinator research copy; four new adversarial cases refused.
✓ Keep accepted video when replacement fails — Bad output and failed replacement preserve prior accepted take across restart.
◐ Native/provider integration — Network-free prototype; no live provider timeout, billing or app integration acceptance.
✓ Full local CLI replay and editable final composition — 290-frame film and 266-frame crop; 48 fresh seek hashes, three restorations, dependent stale takes and undo verified on this Mac.
✓ Portable-renderer audio survives export at correct timing — Media declarations retained; 1x bypasses stretching. Real PCM test is exact and fails old chain; full and cropped MP4 audio align statistically.
✓ Validate imported bytes before manifest publication — Current SDK rejects corrupt/truncated media, invalid JSON/track data, mismatched matte frames and missing alpha. Source-copy race retains matching hash. Normal validation failures preserve project.
✓ Refuse exports whose expected snapshot is stale — Optional expected revision/binding checked before output allocation. Does not freeze arbitrary resources or integrate host ledger publication.
✓ Recover dead locks with concurrent contenders — Numbered generations replace stale unlink. Fresh 30 real-process rounds with six contenders: exactly one winner each. One Mac/APFS only; network filesystems unsupported.
✓ Graceful import cancellation leaves the project editable — SIGINT, SIGTERM and SIGHUP abort decoding and clean staging; real CLI fault suite 19/19. Older bare locks need manual attribution.
✓ Recover owned CLI render resources without harming live jobs — 21/21 fresh browser fault cases; sentinels survive. Automatic recovery sends no signals, explicit orphan-browser SIGTERM is opt-in; dry run writes nothing.
Attempts and artifacts (8 attempts · 19 artifacts)Persistent local generation receipt
SQLite WAL/FULL, frozen ordered scene packet, submission marker before transport, explicit job-ID reconciliation and reviewed take selection.
Result: 11/11 tests passed, including forced subprocess exit, two concurrent owners, corrupt replacement, modified source/output and variable cadence.
Move validated contract into native job/asset ownership; test actual provider reconciliation before shipping.
Opus: full CLI round trip with retained interaction takes
Freeze actual staging/reference identity; verify original provider records; import 121 + 169 frames; live titles, trim/crop and history.
Result: Worker reports 19 checks and 96 seeks, with exact overlay-free plate frames. Two audio defects found, fixed in scratch and retained.
Do not equate replay with provider reconciliation.
Coordinator: exporter fixes and fresh verification
SDK media declaration + 1x audio passthrough; 137 unit tests, real PCM regression, full 290/266-frame exports, 48 seeks and three restorations.
Result: Audio aligned statistically; CTA held and crop headroom corrected. Five record/crash checks and staging dependency/undo rerun.
Playback and native delivery remain open.
Coordinator: frozen reference descriptors were not identity-bound
Drop/reorder descriptors, alter role, substitute hash and path without changing packet identity.
Result: All four passed original loader; all four refused by coordinator research-copy fix.
Carry this contract into managed native import; no production integrity claim yet.
Initial crop used 60000 rather than exported HZ=120000.
Result: 133-frame result failed intended audio comparison. Kept as failed attempt; corrected script imports clock constant and passes at 266 frames.
Use exported clocks, never infer units.
Opus import and crash-recovery proposal
Real CLI faults on a scratch SDK: malformed media, SIGKILL, edit locks, source and export races.
Result: Worker reports 12/12 imports and 8/8 recovery scenarios; sequential recovery does not cover concurrent takeover.
Do not adopt process cleanup or removal unchanged.
Coordinator selective adoption and counterexample
Actual lock function with controlled filesystem scheduling; current SDK media/race/expected-gate regressions.
Result: Both stale-lock contenders acquired before release. Adopted private-copy validation and expected identity only; 140 tests and build pass.
Review concurrent recovery separately; no broad recovery claim.
Fable generation chain and coordinator dry-run correction
Four rejected lock designs; numbered owner records; private render job records; fresh actual SDK fault runs.
Result: 147 unit tests, build/browser/beta, 19 import/edit faults, 21 render faults, 30 six-contender rounds pass. Dry-run mutation found and fixed.
Keep FLOW1 partial until native/provider and platform integration are independently tested.
Fault-test results — Measured timing from both retained generated videos. Retained local evidence; not bundled.
Prototype source — No network, credentials or native UI. Retained local evidence; not bundled.
Reproduction tests — Retains real failure assertions; no paid submissions. Retained local evidence; not bundled.
Verified full film — Existing generated interaction plus live overlays, with audio; not a new generation. Retained local evidence; not bundled.
Corrected crop and trim — 266 frames, top-preserving 1.1x crop; whole baked image only. Retained local evidence; not bundled.
Overlay edit comparison — Worker before/after comparison; underlying take pixels retained. Retained local evidence; not bundled.
Round-trip findings — Editable versus baked ownership, exporter fixes and remaining native boundaries. Retained local evidence; not bundled.
Coordinator export evidence — Full export accepted; first crop attempt is failed and superseded by crop-corrected.json. Retained local evidence; not bundled.
Corrected crop evidence — Actual clock constant, frame count and audio checks. Retained local evidence; not bundled.
Packet integrity failure and repair — Four descriptor substitutions rejected after repair. Retained local evidence; not bundled.
Coordinator adoption review — Implemented subset versus rejected recovery proposal. Retained local evidence; not bundled.
Stale-lock race reproduction — Both contenders acquire before either releases; scratch project only. Retained local evidence; not bundled.
Recovery proposal and faults — Worker evidence, not the shipped implementation. Retained local evidence; not bundled.
Proposed recovery patch — Do not apply wholesale: known concurrent-lock defect. Retained local evidence; not bundled.
Real CLI validation receipt — Passed import, rebind, stale refusal and three-frame export with matching receipt. Retained local evidence; not bundled.
Adopted recovery report — Behavior, fresh results and limits. Retained local evidence; not bundled.
Fresh fault receipts — Current SDK, separate scratch projects, no paid calls. Retained local evidence; not bundled.
Rejected designs and broader worker study — Worker results distinguished from coordinator reruns. Retained local evidence; not bundled.
Recovery protocol diagram — Numbered locks, private job records and explicit browser shutdown. Retained local evidence; not bundled.
MASK1 · Finish the hair and contact evidenceImproved; gap remainsFable 5.2 model comparison; coordinator verification
Acceptance: Whole retained clips reviewed on difficult replacement backgrounds; retain failure frames and compare methods honestly.
Current limit: Neither ResNet50 nor ViTMatte earns hair adoption. Real alpha is unannotated; the body hybrid uses a fixed crop and unvalidated colour seam. Different hair, real footage and normal-speed acceptance remain open.
What changed: Keep MobileNet + room-aware repair as this-shot candidate. Larger models trade cleaner empty regions for fewer curls; ResNet body cleanup is experimental. Synthetic model ranking reverses with truth provenance.
Measured response, not a quality score. Each pair has its own scale.
Synthetic yellow composite error mean RGB codes; RVM-derived synthetic truth only
Before17.3
After17
✓ Reproduce scoped masking renderer — 36 fresh samples and nine edits/restores plus a fresh mount match; all12 comparison clips decode on this Mac. Stronger-model follow-up also reproduces 36 frames, 13 controls and a fresh mount; 12 new comparison videos decode.
✓ Recompute limited-reference measurements — Room proxies and synthetic error summaries independently recomputed within 0.0001, using worker reference data; no ground-truth generalization. Stronger-model synthetic ranking reversal independently reproduced; saved CPU/MPS arrays differ by at most one alpha code.
Attempts and artifacts (7 attempts · 15 artifacts)Fable audit unavailable
Requested independent Claude study.
Result: Provider quota reached before producing an audit artifact.
Result: Full repair residual 0.02198 → 0.01372; white shows 7.7× the RGB sensitivity of dark brown. Synthetic disappearance acquires 0.144 alpha with full repair.
Keep partial: quantify real hair detail and lag with annotations; do not optimize only stability.
Result: Real-room halo proxy 87.79 → 45.84; synthetic yellow error 17.32 → 16.96. Stronger model needed; no general accuracy score.
Compare stronger matting on identical inputs and independent footage; preserve failed holes, rings and wood-speckle attempts.
Coordinator verification and claim limits
Independent summary implementation over retained arrays; 36 fresh renderer samples, nine controls, remount and all12 MP4 decodes.
Result: All checks pass. Room likeness is not proof of absent hair; do not turn cross-metric percentages into a universal seven-fold correction.
No native integration or production approval from these checks.
Stronger local models: no hair replacement earned
ResNet50 r1.0/r0.5, narrow/wide ViTMatte and matching repair; CPU and Apple MPS, no NVIDIA.
Result: ResNet + repair lowers room-opacity proxy 45.8 to 28.8 but raises missing-opacity bound 0.15 to 0.45. ViTMatte loses low-contrast curl detail.
Retain failed variants. Independent real-hair alpha is needed before choosing a model.
Chair cleanup and fixed-region hybrid
Keep MobileNet + repair on the head and ResNet50 on the body; inspect brightened original.
Result: Much of the former hand-shadow smear is chair pixels. Cleaner body is plausible; fixed crop and hard RGB seam are not general routing.
Review motion and moving heads; do not promote based on stills.
Coordinator checks the model comparison
36 fresh frames, 13 controls, fresh mount, independent two-truth scoring, CPU/MPS saved-array comparison and 12 full decodes.
Result: Checks pass. Model ranking flips with synthetic truth source; maximum saved CPU/MPS alpha difference is one code.
Integrity verified, visual and production acceptance still open.
Hair audit report — Controlled method, measured tradeoff and remaining validation. Retained local evidence; not bundled.
Five-background still comparison — Same frame and RGB; four mask variants per background. Retained local evidence; not bundled.
White-background motion comparison — 96 frames; four variants, no new avatar generation. Retained local evidence; not bundled.
Dark-background motion comparison — Identical masks on dark brown. Retained local evidence; not bundled.
Reproduction and measurements — Per-pair residuals, decode checks and synthetic counterexample. Retained local evidence; not bundled.
Verified mask follow-up — Isolation findings, modest gain and explicit reference limits. Retained local evidence; not bundled.
Full-frame yellow comparison — Retained repair versus room-aware proposal; hand smear remains. Retained local evidence; not bundled.
Showroom comparison — Same presenter and staging on a detailed room. Retained local evidence; not bundled.
Room-reference evidence — Known-region proxy; purple regions have no room reference. Retained local evidence; not bundled.
Independent measurement record — Recomputed room/synthetic values and all clip decode records. Retained local evidence; not bundled.
Stronger-model decision — Neither model adopted for hair; body cleanup candidate and evidence limits. Retained local evidence; not bundled.
Hybrid in a showroom — Current candidate versus fixed-region head/body combination; silent. Retained local evidence; not bundled.
Hybrid against pale yellow — A revealing background; no general quality approval. Retained local evidence; not bundled.
Fine curls across candidates — Larger models visibly soften low-contrast curls. Retained local evidence; not bundled.
Independent stronger-model verification — Recomputed ranking reversal, saved CPU/MPS differences and 12 decodes. Retained local evidence; not bundled.
GLASS1 · Resolve or bound transparent materialsImproved; gap remainsOpus 5.5 study; coordinator verification
Acceptance: A matched scene comparison isolates nested transparency limits and gives a reproducible supported route.
Current limit: R2 is cylinder-only, omits submerged ice and responds weakly to practical light. Cycles is slow and approximated; no general native export route, other-device or production acceptance.
What changed: Resumed study reproduces missing transmission layers; clean topology alone fails. Two raster routes reveal liquid; matched Cycles retains the strongest nested detail with stated approximations.
Measured response, not a quality score. Each pair has its own scale.
Liquid visibility signal RGB codes; larger is not necessarily better (reference 50.30)
Before0.371
After72.1
✓ Reproduce missing nested layers — Installed renderer source and isolation images support the cause; geometry cleanup and closed DoubleSide shell do not fix this example.
Result: Provider rate limit before final evidence package; do not infer a supported route from partial artifacts.
Resume from retained files after quota recovery, or coordinator takeover after source/measurement audit.
Resumed study and independent verification
Layer isolation, matched display transform, two 72-frame shots, fresh raster sample renders and independent file measurements.
Result: 54 fresh frames identical; five edits restore; all 16 clip files decode. R2 restores cylinder inversion but omits submerged ice. Cycles shows nested contents with higher cost.
Retain partial; support a bounded offline quality candidate, not general raster transparency.
Retained glass diagnostics — Unverified worker diagnostics; interrupted study, not approval. Retained local evidence; not bundled.
Verified glass study — Route decision, calibration limits, independent checks and cost. Retained local evidence; not bundled.
Nested layer comparison — Stock, single-sheet, layered and Cycles routes. Retained local evidence; not bundled.
Orbit comparison — A0 | R2 | Cycles, three seconds. Retained local evidence; not bundled.
Moving practical comparison — Weak raster illumination through liquid remains visible. Retained local evidence; not bundled.
Independent verification record — Fresh frame matches, controls, all clip decodes and recomputed measurements. Retained local evidence; not bundled.
HUMAN1 · Light humans and products togetherImproved; gap remainsFable 5.2 shared-light study · coordinator range audit
Acceptance: Continuous changes preserve identity and agree across subjects/background; show limits of bounded colour matching.
Current limit: No target-light human reference; proxy normals, shadows, hair and highlight headroom limit correction. Only 3/7 front directions pass proposed synthetic half-house rule.
What changed: One editable track drives geometry and bounded footage correction; the photographed room remains baked. Broad human relighting is not established.
◐ Shared light track and editable history — Worker 284 seeks, 78 restorations and four CLI frames; coordinator verified delivery, not rerendered.
◐ Proposed operating range — Only 3/7 front directions pass synthetic half-house rule. The labelled supported human track peaks at 0.78, above proposed 0.5.
◐ Human shadows, hair and moved highlights — Not recovered by this correction; captured passes, relightable asset or regeneration required for this workflow.
Attempts and artifacts (1 attempts · 5 artifacts)Continuous practical on presenter and laptop
Unchanged matte; DPT proxy plus bounded additive image correction, with known-normal synthetic bust.
Result: More directional response, but real face has no reference; stronger light creates hard patches and baked-key conflicts.
Use paired-light references; test per-layer provenance and conservative review policy.
Human correction comparison — Untouched / prior / depth proxy. Edge case, not validated safe range. Retained local evidence; not bundled.
Strong-light failure — Hard patches, baked key and insufficient hair response. Retained local evidence; not bundled.
Pixel ownership — Shows geometry, footage correction and baked photograph separately. Retained local evidence; not bundled.
Shared-light findings — Worker methods, controls and limitations. Retained local evidence; not bundled.
Coordinator range and delivery audit — 13 decoded previews; saved grid rejects broad half-house/front acceptance. Retained local evidence; not bundled.
MACHINE1 · Check other ordinary computersNeeds a resourceExternal resource
Acceptance: Run the same reproducible benchmark on actual additional hardware.
Current limit: One Mac cannot prove Windows/Linux/modest-laptop performance.
Attempts and artifacts (0 attempts · 0 artifacts)
No new attempt has been completed in this round. Earlier evidence is retained in the original map.
SAM3 · Compare SAM 3 videoNeeds a resourceAccess/runtime resource
Acceptance: An actually runnable licensed model and accepted access, followed by matched-video comparison.
Current limit: Previous gated access/runtime constraints; no new download/spend assumed.
Attempts and artifacts (0 attempts · 0 artifacts)
No new attempt has been completed in this round. Earlier evidence is retained in the original map.
RECON · Camera solve and reconstructed worldsQueuedLater research
Acceptance: Real-camera and reconstructed-world acceptance separately; authored scenes do not count.
Current limit: Feature 6 and 13 still untested; initial round prioritizes existing failures.
Attempts and artifacts (0 attempts · 0 artifacts)
No new attempt has been completed in this round. Earlier evidence is retained in the original map.
41 grouped trials · 8 areas
Counts group related attempts—not individual renders, equal-sized studies or a success rate. These include HTML scenes and the models that supplied their inputs.
● 12 Worked in this test● 21 Needs more work● 8 Missed the goal
“Worked” means only the stated check or user judgment passed. It does not mean ready for every video.
▱ Keep pictures in the right place 5 trialsA sticker must stay on its sign.
Clean synthetic tracker Worked in this test
A clean moving test card tracked very accurately.
Limit: Known-answer synthetic proof; not real-scene reliability.
Generated café, poster and phone Needs more work
Cards followed short moving clips, with manual corners and some drift.
Limit: Up to about 8 px café error despite high confidence; curved paper is not planar.
Real filmed box orbit Missed the goal
The sticker slid onto the next face of the box.
Limit: Blank surfaces and changing faces defeat this tracker.
Tracker confidence + reverse check Missed the goal
Forward and backward trackers agreed on the same wrong answer.
Limit: 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed.
Frame timing and colour export Worked in this test
Fixed repeated source frames and unwanted darkening.
Limit: Integer timestamp and colour-tag corrections; retained export checks.
▤ Put people in front of the right things 5 trialsA hand should hide what is behind it.
Original phone thumb + café head Missed the goal
Old overlays erased a thumb and covered hair.
Limit: Original outputs failed even when the rest of the video looked fine.
Repaired phone + café + native card Worked in this test
Reviewed masks kept the thumb, head and hair visible.
Limit: Works with manual tuning on retained shots; native café preview/export exercised.
Depth map with an added can Missed the goal
A hand cut through the extra can.
Limit: Depth tuning did not establish common scene geometry.
Wrap the original left can Worked in this test
Put the artwork on the existing can instead of adding another one.
Limit: Manual rigid-cylinder fit; the hand did not cross that original can.
Kinetic words and exact screen cards Worked in this test
Words enter, move and stay on their intended surface.
Limit: Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified.
✂ Cut out hair, hands and products 5 trialsA cut-out edge needs more than scissors.
Avatar stills + bounded light matching Needs more work
Small colour changes preserve the original face.
Limit: Separate screenshots, not continuous speech; cannot create correct new directional shadows.
Local SAM 2 video + CPU fallback Needs more work
Followed people, hands and products through short clips.
Limit: Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha.
Full pickup: SAM / RVM / guided alpha Needs more work
Processed the whole pickup and reduced some background spill.
Limit: 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass.
Yellow-wall hair swap and repair Needs more work
Hair stopped disappearing as much after better preparation.
Limit: Improved source quality, prior-frame context and boundary repair; not all faults isolated.
Cut-out avatar pointing at headphones Missed the goal
The edges improved, but the person still did not convincingly present the object.
Limit: User rejected this route for interaction; zero overlap is not coherent gaze or contact.
☀ Make things belong in the light 7 trialsA lamp must light the object, not just glow.
Plate-based light guesses Needs more work
Sometimes found the useful side of the light; manual overrides mattered.
Limit: A bright surface or backlight can mislead the estimate.
Exact can on an empty generated stage Needs more work
Kept the product shape in code with an authored shadow.
Limit: Rendering worked; pasted-on lighting prompted the later lighting studies.
Local raster / WebGPU / Cycles Needs more work
All ran locally; corrected render tests were retained.
Limit: One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim.
DiffusionLight environment estimate Missed the goal
Invented lighting that did not fit the authored room.
Limit: Negative result for this scene, not a universal rejection of estimation.
IC-Light on exact artwork Missed the goal
Changed lettering and object detail.
Limit: Rejected for exact branded-object finishing; tests were stills, not a full relit video.
IC-Light on avatar stills / ratio hint Needs more work
A bounded hint kept original pixels; raw replacement changed facial detail.
Limit: Experimental still-image result; no temporal identity or light-direction acceptance.
One lamp changes warm → cool Needs more work
The cup and table responded, but the pastry barely did.
Limit: Baked photographed background stayed unchanged; per-object response must be checked.
◈ Try real and designed products 9 trialsCorrect shape matters as much as pretty light.
LUMA, SPRIG, CROWN & ROOT cans Needs more work
More detailed packaging helped; red design was preferred.
Limit: Lids, reflections, droplets, label seams and motion still needed refinement.
12 products × 6 lighting setups Needs more work
Expanded to PCs, phones, watches, cameras and lifestyle products.
Limit: 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults.
Oura / Garmin / Nothing photographs Needs more work
Recognisable products work as cut-outs and layouts.
Limit: Colour matching only: baked highlights and unseen sides cannot be relit or spun out.
Framework photo + grille repair Worked in this test
Improved small-detail downsampling for the layout.
Limit: Context photo only, not a relighting test or full temporal aliasing certification.
iPhone / Galaxy / MacBook 3D assets Needs more work
MacBook responded to moving lights after fixes.
Limit: iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier.
Two copies: spin, orbit and overlap Worked in this test
The nearer object drew in front in the tested crossing poses.
Limit: 35 poses; photo copies still have no real turn; mutual reflections/bounce untested.
Photos-to-3D product attempt Missed the goal
The generated model did not preserve the needed materials.
Limit: An importable mesh is not yet a faithful commercial product.
Glass, liquid and ice scenes Needs more work
Rendered scenes, but nested transparent parts could vanish.
Limit: Raster limitations; limited Cycles trials were not a matched-quality comparison.
Pastry, ceramic, plants, furniture, jewelry Needs more work
Broadened the material and scene tests.
Limit: Grounding, fabrics, jewelry detail and simple billboard steam remained weak.
↔ Make people show and hand over a product 5 trialsBodies must agree about the same action.
HeyGen Avatar IV + Atmee pointing Needs more work
Both made a presenter talk and gesture in a detailed room.
Limit: Requested gesture timing was not followed; these outputs were flattened video.
HeyGen walk, pickup and carry Needs more work
An explicit standing start gave the best framing.
Limit: Product detail drift and late speech remained.
Kling references + video-edit pickup Needs more work
Joint generation improved looking, gripping and holding.
Limit: The early upright position and camera-left instruction were not fully corrected.
Approved snapshot → full pickup Worked in this test
Camera-left placement and pickup looked good to the user.
Limit: One accepted example; heft is weak, exact geometry and lettering unproven.
Two-person handoff Worked in this test
Receiver supports it; giver lets go. The user likes the result.
Limit: One accepted example; second person lacked an identity reference.
♜ Build an animated story with code 2 trialsBuild the stage, actors and their moves.
Astra fantasy RPG film Needs more work
48 seconds of voiced, subtitled, editable 3D storytelling.
Limit: Three repeat seeks passed; faces and hands look more puppet-like than references.
Fable 5.2 fantasy RPG film Needs more work
User prefers its richer sets, proportions and cinematic direction.
Limit: 48-second recovered draft; usage limit interrupted refinement; one seek test fails.
↻ Keep the work editable and safe to repeat 3 trialsSave the recipe, not only the movie.
Clean staging snapshot + reference packet Worked in this test
Kept the chosen layout and reference order in a saved packet.
Limit: Local Scene Studio/packet checks; full native provider workflow still pending.
Generated clips → editable finishing Worked in this test
Titles, prices and other code layers remain changeable after generation.
Limit: Hands, product motion and room light inside the footage remain baked.
Clay/depth/normal/object-ID control passes Worked in this test
The authored scene can emit these inputs for another tool.
Limit: No successful hosted control-video restyling round trip established.
Your forecast is a strong direction—not yet a universal result.
Why it could go far
Code saves the world, cast and movements as a recipe. Better models can reuse and improve that recipe.
Game-like art fits 3D engines well. Fable’s richer characters, sets and shot direction already made a difference.
What still pushes back
Working code does not automatically create good acting, believable hands or an accurate product.
Assets, animation, sound, continuity and computer cost still matter. One draft is not proof of every future style or model.
The real dividing line
What must stay exact or changeable—and do we own the shapes and movement needed to change it?
A realistic product can be code. A fantasy action can be generated. A mask fixes the edge; it cannot teach a hand to hold something.
Future Fable versions and other providers catching up are forecasts. This exercise does not establish dates or permanent vendor leadership.
Can lighting have more than a few presets?
Yes. Light position, direction, size, colour and brightness can change continuously. Presets are starting points.
But a light only changes what the scene represents. A photographed background has baked light. A new lamp needs its glow, shadows, reflections and nearby surfaces to agree.
Our lamp trial changed the table strongly and the pastry weakly; the photographed room stayed unchanged. Mixed avatar/product relighting still needs testing.
Where the route can go
Potential categories are not the same as completed tests.
Fantasy / RPG / game-like stories Build with code
Two 48-second fantasy drafts; user prefers Fable.
New styles, longer acting and reliable seeking remain unproven.
Sci-fi, cartoons, toy/clay and mascot stories Build with code
Plausible next studies, not demonstrated styles.
Need new silhouettes, rigs, sets and movement—not only new colours.
Lessons, diagrams and animated explainers Build + combine
Exact text, graphics and moving cards exercised.
A complete educational film and factual review are separate tests.
Product ads, assembly and digital showrooms Build + combine
Product rendering, moving copies and layouts exercised.
Faithful CAD/materials and approved artwork matter; a photo has no hidden back.
Game trailers / architectural walkthroughs Build or use captured footage
The scene/camera machinery is relevant; no dedicated acceptance.
A generated reenactment is not evidence of real gameplay or a real building.
People talking, demonstrating or handing over Make the action together
Pickup and handoff accepted; standalone avatar tests have limits.
Film it or jointly generate it. Do not glue an unrelated gesture onto a product.
Hair, cloth, fluids, crowds and destruction Choose per shot
Hair cut-out and simple glass/liquid studies only.
May need authored simulation, specialist assets or generated footage; cost matters.
News, interviews, testimonials and real events Use genuine footage + code
This is an authenticity requirement, not an experiment result.
Preserve recorded evidence; a convincing synthetic performance cannot replace it.
One advert can use several tools
Illustrative 60-second edit—not a video we have already tested.
CODE · Headline
Exact words and animation.
CODE + APPROVED 3D · Product turn
Correct shape, material and specifications.
JOINT ACTION · Pickup and handoff
Film or generate people, hands and product together. Review accuracy.
CODE + UI · Explain the feature
Editable callouts over correct screen content.
GENUINE FOOTAGE · Testimonial
A real customer’s real words.
CODE · Price and call to action
Make versions without regenerating the performance.
Keep an interaction group together.
The giver, receiver, hands and product share one performance. The price card can be separate code.
Generated footage keeps its internal action baked. You can trim, crop or replace the clip; changing a grip or moving the product usually means another generation or a validated rig.
Next: prove reuse, not just one good shot
Finish Fable’s draft: seeking, contact, cuts, audio and controls.
Separate reusable actors, actions, sets and looks.
Try sci-fi, cel village and toy/clay scenes with the same action brief.
Test persistent actors, host editing/export and more computers.
Still not established
SAM 3 video: Access/runtime gate; no accuracy comparison with SAM 2.
Camera solve · feature 6: No accepted real 3D camera reconstruction.
Reconstructed worlds · feature 13: No splat/mesh reconstruction test; a code-authored world is different.
Cloth/skin reskin + automatic contact: No general deforming-surface or physical interaction solver.
More story styles: Sci-fi, cel village and clay/toy styles are proposed, not tested.
Longer episodes and persistent cast: No multi-episode identity/performance acceptance.
Ordinary-computer coverage: No robust Windows/Linux/modest-laptop benchmark.
Native generation handoff: Local packets exist; full capture/job/recovery/import flow remains to be delivered.
Stronger human video relighting: No complete mixed human/product emitter and temporal-identity pass.
Checkpoint: 13 Nov 2026. Based on retained tests, user judgments and earlier Fable reviews. No fresh Fable endorsement: that checkpoint preceded this research round. Current work is recorded in Gap closure. Full inventory, evidence and debate.
\ No newline at end of file
diff --git a/docs/hybrid-experiment-map.md b/docs/hybrid-experiment-map.md
new file mode 100644
index 0000000..6c048c5
--- /dev/null
+++ b/docs/hybrid-experiment-map.md
@@ -0,0 +1,169 @@
+# What we tried, and where code-generated video fits
+
+> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact and native integration remain open. Cross-style cast reuse now spans two briefs; see [second-brief findings](hybrid-story-second-brief-2026-11-14.md). Actions still require new choreography. See [current evidence](hybrid-gap-closure-2026-11-14.md).
+
+Checkpoint: 2026-11-13. [Interactive experiment map](hybrid-experiment-map.html) · [Static infographic](media/hybrid-experiment-map.svg).
+
+**41 grouped trial entries across 8 areas.** These are an inventory of related attempts, not 41 independent jobs, equal-sized experiments or a success-rate benchmark. They include the local browser/HTML scene studies and the model/preparation steps used by those compositions. Superseded failures stay visible beside later repairs. This is not a claim to enumerate every frame or revision.
+
+**Legend:** “Worked in this test” means the specifically stated check or user judgment succeeded; it does not mean production-ready. “Needs more work” has a useful partial result. “Missed the goal” records a failed use case, not a universal ban on a technology. Proposed work appears separately.
+
+## The debate: a strong direction, not an unlimited promise
+
+**The user’s forecast:** future LLMs may eventually author almost any game-look or fantasy video. We adopt this as a direction to explore, not a verified promise about Fable 5.5, Fable 6, release dates or permanent vendor leadership. One preferred film does not rank providers in general.
+
+**The strongest case for it.** Code can retain the world, cast, actions, cameras and lights as a reusable recipe. Once a rig or set works, the next scene can reuse it. Stylized art often tolerates simplified surfaces, and a game aesthetic fits real-time renderers naturally. Better authoring, better assets and better rendering tools can compound. Our two complete 48-second exports establish that this route already makes coherent short, voiced scenes; Fable’s richer assets and direction were preferred.
+
+**The strongest objection.** Writing valid code is not the same as directing believable acting. Anatomy, facial performance, contact, eyelines, cloth, sound, camera cuts, continuity and taste need work even when the program runs. Rendering time, memory and source-asset quality do not disappear with a smarter LLM. Fable’s unfinished draft still fails one random-seek check. We have neither a multi-episode test nor a benchmark on ordinary laptops. The initial cross-style hypothesis now has two-brief evidence for cast, rig and look. The second action required new choreography and grip code, so general action portability remains unproven.
+
+**The line is not cartoon versus real.** Code can render a realistic product if it has faithful geometry and materials. A fantasy battle can still be cheaper or better as a simulated or generated shot. The useful question is: *what must remain changeable or exact, and do we own the representation needed to change it?*
+
+## Choose a route for each shot—and sometimes each layer
+
+1. **Build with code** when we can author the shapes, rigs and motion and need repeatable edits: price, UI, product layout, a known camera, stylized characters, diagrams or an approved CAD model. Geometry being editable does not make an invented mesh accurate. Exact labels require correct artwork and a validated render.
+2. **Make the action together** when independently composited people/objects cannot convincingly share gaze, grip, weight or support. Use a single choreographed rig/simulation, filmed performance, or jointly generated shot. Our chosen realistic-avatar route is approved staging → snapshot + references → joint generation → review. This is a workflow default from our trials, not a claim that realistic CG interaction is impossible.
+3. **Combine independent pieces** when their relationship is mostly placement, visibility and colour: captions, titles, background swaps, a presenter beside a diagram, a pinned screen. Masks solve who hides whom; they do not create acting, contact, reflections or lighting geometry.
+4. **Use genuine footage** when the shot claims a real event, testimony, actual gameplay or measured product behaviour. Code can clarify and annotate it. Synthetic footage may be a labelled illustration, not proof.
+
+An interaction group should share one performance. For example, the two people, their hands and the transferred product belong together. A separate price card can remain code outside that group. A generated clip is editable as a clip—trim, crop, grade, replace—but its internal fingers, product motion and room lighting are baked. Moving a product afterward without its hand requires regeneration or a separately validated reconstruction/rig.
+
+### Example: one 60-second advert can use several routes
+
+Illustrative edit, **not a tested deliverable**:
+
+| Time | Section | Route | Why |
+|---|---|---|---|
+| 0–5 s | Animated headline | Code | Exact words and motion. |
+| 5–15 s | Product turns with specifications | Code + approved 3D asset | Repeatable angle and exact information; asset fidelity gate. |
+| 15–30 s | Seller picks up and hands over product | Filmed or jointly generated action | Shared support, gaze and contact. Generated product accuracy must be reviewed. |
+| 30–40 s | Interface / feature explanation | Code, with captured UI where necessary | Changeable callouts and correct screen content. |
+| 40–55 s | Customer testimonial | Genuine authorised recording | Real testimony must remain real. |
+| 55–60 s | Price and call to action | Code | Versions without regenerating the performance. |
+
+A fantasy episode can likewise mix authored dialogue with a difficult simulated/generated insert. That mixed story round trip has not been tested here.
+
+## What “unlimited lighting options” means
+
+The warm/cool/office labels are starting settings, not a closed menu. Direction, position, size, colour, intensity, environment, material and time can vary continuously. But a control only changes representations it reaches: a 3D light can light a mesh; it cannot recover the back of a photograph or remove baked shadows from footage. A new visible lamp needs illumination on nearby surfaces, appropriate shadows/reflections and consistent changes over time. Our lamp sweep exposed weak pastry response and an unchanged photographed background. Mixed human/product relighting is still an open gate.
+
+## Decisions and next experiments
+
+- Keep code-authored storytelling as a first-class, open authoring route. Build optional rig/action/set/look modules rather than a mandatory dungeon template or fixed genre list.
+- Finish **ST1** before calling the Fable draft dependable: fix seek state, inspect acting/contact/cut boundaries, check audio and exposed controls in preview/export. Then extract reusable parts (**ST2**).
+- For **ST3**, use the same walk → dialogue → shared-prop brief in a sci-fi workshop, cel-shaded village and toy/clay scene. Change shapes, faces, motion, sets and lighting as well as palette. A style counts only after whole-shot review and seek checks.
+- For **ST4**, keep the same actor through scene/light/dialogue edits, test save/reload and host export, and measure additional real computers. Do not extrapolate one Mac into a minimum supported laptop specification.
+- Keep the accepted realistic pickup/handoff route; implement durable scene-set capture, ordered references, job recovery and accepted-take import. Repeat with both people identity-referenced and difficult contact before claiming reliability.
+- Keep feature **6 (camera solve)** and **13 (world reconstruction)** explicitly untested. Authored fantasy worlds establish neither.
+
+**Evidence and review status:** this synthesis uses retained renders, source inspection, measurements, user judgments and earlier Fable reviews. Those are different kinds of evidence. No new render, paid model call or fresh Fable review was performed for this map. Fable’s recorded provider limit prevented a new consultation at this checkpoint. Its earlier findings challenge rendering/material/interaction claims; they are not approval of this new debate or the unfinished story draft.
+
+## Video categories and the present evidence
+
+| Category | Likely route | What we know | Boundary |
+|---|---|---|---|
+| Fantasy / RPG / game-like stories | Build with code | Two 48-second fantasy drafts; user prefers Fable. | New styles, longer acting and reliable seeking remain unproven. |
+| Sci-fi, cartoons, toy/clay and mascot stories | Build with code | Plausible next studies, not demonstrated styles. | Need new silhouettes, rigs, sets and movement—not only new colours. |
+| Lessons, diagrams and animated explainers | Build + combine | Exact text, graphics and moving cards exercised. | A complete educational film and factual review are separate tests. |
+| Product ads, assembly and digital showrooms | Build + combine | Product rendering, moving copies and layouts exercised. | Faithful CAD/materials and approved artwork matter; a photo has no hidden back. |
+| Game trailers / architectural walkthroughs | Build or use captured footage | The scene/camera machinery is relevant; no dedicated acceptance. | A generated reenactment is not evidence of real gameplay or a real building. |
+| People talking, demonstrating or handing over | Make the action together | Pickup and handoff accepted; standalone avatar tests have limits. | Film it or jointly generate it. Do not glue an unrelated gesture onto a product. |
+| Hair, cloth, fluids, crowds and destruction | Choose per shot | Hair cut-out and simple glass/liquid studies only. | May need authored simulation, specialist assets or generated footage; cost matters. |
+| News, interviews, testimonials and real events | Use genuine footage + code | This is an authenticity requirement, not an experiment result. | Preserve recorded evidence; a convincing synthetic performance cannot replace it. |
+
+## Inventory of studies already tried
+
+### Keep pictures in the right place
+
+A sticker must stay on its sign.
+
+- **Clean synthetic tracker — Worked in this test.** A clean moving test card tracked very accurately. **Limit:** Known-answer synthetic proof; not real-scene reliability. Evidence: [hybrid-scenes.md](hybrid-scenes.md).
+- **Generated café, poster and phone — Needs more work.** Cards followed short moving clips, with manual corners and some drift. **Limit:** Up to about 8 px café error despite high confidence; curved paper is not planar. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records.
+- **Real filmed box orbit — Missed the goal.** The sticker slid onto the next face of the box. **Limit:** Blank surfaces and changing faces defeat this tracker. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records.
+- **Tracker confidence + reverse check — Missed the goal.** Forward and backward trackers agreed on the same wrong answer. **Limit:** 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed. Evidence: [hybrid-analysis-study-2026-11-13.md](hybrid-analysis-study-2026-11-13.md).
+- **Frame timing and colour export — Worked in this test.** Fixed repeated source frames and unwanted darkening. **Limit:** Integer timestamp and colour-tag corrections; retained export checks. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records.
+
+### Put people in front of the right things
+
+A hand should hide what is behind it.
+
+- **Original phone thumb + café head — Missed the goal.** Old overlays erased a thumb and covered hair. **Limit:** Original outputs failed even when the rest of the video looked fine. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+- **Repaired phone + café + native card — Worked in this test.** Reviewed masks kept the thumb, head and hair visible. **Limit:** Works with manual tuning on retained shots; native café preview/export exercised. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+- **Depth map with an added can — Missed the goal.** A hand cut through the extra can. **Limit:** Depth tuning did not establish common scene geometry. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records.
+- **Wrap the original left can — Worked in this test.** Put the artwork on the existing can instead of adding another one. **Limit:** Manual rigid-cylinder fit; the hand did not cross that original can. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+- **Kinetic words and exact screen cards — Worked in this test.** Words enter, move and stay on their intended surface. **Limit:** Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+
+### Cut out hair, hands and products
+
+A cut-out edge needs more than scissors.
+
+- **Avatar stills + bounded light matching — Needs more work.** Small colour changes preserve the original face. **Limit:** Separate screenshots, not continuous speech; cannot create correct new directional shadows. Evidence: [avatar-lighting.md](avatar-lighting.md).
+- **Local SAM 2 video + CPU fallback — Needs more work.** Followed people, hands and products through short clips. **Limit:** Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha. Evidence: [hybrid-analysis-study-2026-11-13.md](hybrid-analysis-study-2026-11-13.md).
+- **Full pickup: SAM / RVM / guided alpha — Needs more work.** Processed the whole pickup and reduced some background spill. **Limit:** 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md).
+- **Yellow-wall hair swap and repair — Needs more work.** Hair stopped disappearing as much after better preparation. **Limit:** Improved source quality, prior-frame context and boundary repair; not all faults isolated. Evidence: Retained local study: `mask-composition/retry/README.md` (not bundled here).
+- **Cut-out avatar pointing at headphones — Missed the goal.** The edges improved, but the person still did not convincingly present the object. **Limit:** User rejected this route for interaction; zero overlap is not coherent gaze or contact. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+
+### Make things belong in the light
+
+A lamp must light the object, not just glow.
+
+- **Plate-based light guesses — Needs more work.** Sometimes found the useful side of the light; manual overrides mattered. **Limit:** A bright surface or backlight can mislead the estimate. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records.
+- **Exact can on an empty generated stage — Needs more work.** Kept the product shape in code with an authored shadow. **Limit:** Rendering worked; pasted-on lighting prompted the later lighting studies. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+- **Local raster / WebGPU / Cycles — Needs more work.** All ran locally; corrected render tests were retained. **Limit:** One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim. Evidence: Retained local study: `review-resolution.txt` (not bundled here).
+- **DiffusionLight environment estimate — Missed the goal.** Invented lighting that did not fit the authored room. **Limit:** Negative result for this scene, not a universal rejection of estimation. Evidence: Retained local study: `fable-review.txt` (not bundled here).
+- **IC-Light on exact artwork — Missed the goal.** Changed lettering and object detail. **Limit:** Rejected for exact branded-object finishing; tests were stills, not a full relit video. Evidence: Retained local study: `fable-review.txt` (not bundled here).
+- **IC-Light on avatar stills / ratio hint — Needs more work.** A bounded hint kept original pixels; raw replacement changed facial detail. **Limit:** Experimental still-image result; no temporal identity or light-direction acceptance. Evidence: [avatar-lighting.md](avatar-lighting.md).
+- **One lamp changes warm → cool — Needs more work.** The cup and table responded, but the pastry barely did. **Limit:** Baked photographed background stayed unchanged; per-object response must be checked. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md).
+
+### Try real and designed products
+
+Correct shape matters as much as pretty light.
+
+- **LUMA, SPRIG, CROWN & ROOT cans — Needs more work.** More detailed packaging helped; red design was preferred. **Limit:** Lids, reflections, droplets, label seams and motion still needed refinement. Evidence: Retained local study: `beverage-design/fable-design-review.txt` (not bundled here).
+- **12 products × 6 lighting setups — Needs more work.** Expanded to PCs, phones, watches, cameras and lifestyle products. **Limit:** 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults. Evidence: Retained local study: `product-lab/fable-expanded-review.txt` (not bundled here).
+- **Oura / Garmin / Nothing photographs — Needs more work.** Recognisable products work as cut-outs and layouts. **Limit:** Colour matching only: baked highlights and unseen sides cannot be relit or spun out. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **Framework photo + grille repair — Worked in this test.** Improved small-detail downsampling for the layout. **Limit:** Context photo only, not a relighting test or full temporal aliasing certification. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **iPhone / Galaxy / MacBook 3D assets — Needs more work.** MacBook responded to moving lights after fixes. **Limit:** iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **Two copies: spin, orbit and overlap — Worked in this test.** The nearer object drew in front in the tested crossing poses. **Limit:** 35 poses; photo copies still have no real turn; mutual reflections/bounce untested. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **Photos-to-3D product attempt — Missed the goal.** The generated model did not preserve the needed materials. **Limit:** An importable mesh is not yet a faithful commercial product. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records.
+- **Glass, liquid and ice scenes — Needs more work.** Rendered scenes, but nested transparent parts could vanish. **Limit:** Raster limitations; limited Cycles trials were not a matched-quality comparison. Evidence: Retained local study: `scene-lab/README.txt` (not bundled here).
+- **Pastry, ceramic, plants, furniture, jewelry — Needs more work.** Broadened the material and scene tests. **Limit:** Grounding, fabrics, jewelry detail and simple billboard steam remained weak. Evidence: Retained local study: `scene-lab/README.txt` (not bundled here).
+
+### Make people show and hand over a product
+
+Bodies must agree about the same action.
+
+- **HeyGen Avatar IV + Atmee pointing — Needs more work.** Both made a presenter talk and gesture in a detailed room. **Limit:** Requested gesture timing was not followed; these outputs were flattened video. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **HeyGen walk, pickup and carry — Needs more work.** An explicit standing start gave the best framing. **Limit:** Product detail drift and late speech remained. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records.
+- **Kling references + video-edit pickup — Needs more work.** Joint generation improved looking, gripping and holding. **Limit:** The early upright position and camera-left instruction were not fully corrected. Evidence: [interaction-staging-workflow.md](interaction-staging-workflow.md).
+- **Approved snapshot → full pickup — Worked in this test.** Camera-left placement and pickup looked good to the user. **Limit:** One accepted example; heft is weak, exact geometry and lettering unproven. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md).
+- **Two-person handoff — Worked in this test.** Receiver supports it; giver lets go. The user likes the result. **Limit:** One accepted example; second person lacked an identity reference. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md).
+
+### Build an animated story with code
+
+Build the stage, actors and their moves.
+
+- **Astra fantasy RPG film — Needs more work.** 48 seconds of voiced, subtitled, editable 3D storytelling. **Limit:** Three repeat seeks passed; faces and hands look more puppet-like than references. Evidence: [code-generated-story-results-2026-11-13.md](code-generated-story-results-2026-11-13.md).
+- **Fable 5.2 fantasy RPG film — Needs more work.** User prefers its richer sets, proportions and cinematic direction. **Limit:** 48-second recovered draft; usage limit interrupted refinement; one seek test fails. Evidence: [code-generated-story-results-2026-11-13.md](code-generated-story-results-2026-11-13.md).
+
+### Keep the work editable and safe to repeat
+
+Save the recipe, not only the movie.
+
+- **Clean staging snapshot + reference packet — Worked in this test.** Kept the chosen layout and reference order in a saved packet. **Limit:** Local Scene Studio/packet checks; full native provider workflow still pending. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md).
+- **Generated clips → editable finishing — Worked in this test.** Titles, prices and other code layers remain changeable after generation. **Limit:** Hands, product motion and room light inside the footage remain baked. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md).
+- **Clay/depth/normal/object-ID control passes — Worked in this test.** The authored scene can emit these inputs for another tool. **Limit:** No successful hosted control-video restyling round trip established. Evidence: [hybrid-scenes.md](hybrid-scenes.md).
+
+## Not yet established
+
+- **SAM 3 video:** Access/runtime gate; no accuracy comparison with SAM 2.
+- **Camera solve · feature 6:** No accepted real 3D camera reconstruction.
+- **Reconstructed worlds · feature 13:** No splat/mesh reconstruction test; a code-authored world is different.
+- **Cloth/skin reskin + automatic contact:** No general deforming-surface or physical interaction solver.
+- **More story styles:** Sci-fi, cel village and clay/toy styles are proposed, not tested.
+- **Longer episodes and persistent cast:** No multi-episode identity/performance acceptance.
+- **Ordinary-computer coverage:** No robust Windows/Linux/modest-laptop benchmark.
+- **Native generation handoff:** Local packets exist; full capture/job/recovery/import flow remains to be delivered.
+- **Complex interaction breadth:** Object collisions, animals, crowds and repeated two-person identity tests remain open.
+- **Stronger human video relighting:** No complete mixed human/product emitter and temporal-identity pass.
+
+For the source-level Fable/Astra comparison and ST1–ST4 acceptance, see [the story report](code-generated-story-results-2026-11-13.md). For the accepted interaction takes and costs, see [the staged-generation report](staged-generation-results-2026-11-13.md).
diff --git a/docs/hybrid-gap-closure-2026-11-14.md b/docs/hybrid-gap-closure-2026-11-14.md
new file mode 100644
index 0000000..67652c4
--- /dev/null
+++ b/docs/hybrid-gap-closure-2026-11-14.md
@@ -0,0 +1,88 @@
+# Hybrid gap closure — 2026-11-14 checkpoint
+
+This is an active research checkpoint. The [experiment dashboard](hybrid-experiment-map.html) now has a Gap closure tab with scoped subchecks, attempts and retained artifact descriptions. No whole work item is declared finished. No new hosted-model calls were made in this round.
+
+| Work item | New measured evidence | What remains |
+|---|---|---|
+| ST1: dependable authored story | Resumed original Fable film completed. Coordinator reproduced all 1,152 sequential frame hashes, 228 new shuffled/reverse/cut-adjacent checks and all 12 exposed control changes/restorations. | Acting, physical contact, face finish, soundtrack listening, native app integration and other hardware. |
+| ST1: CLI delivery specimen | Three source frames (228, 696, 960) exported through the current CLI. Exposure edit changes all three; stale proposal rejected; undo restores pixels exactly. | This is three sampled frames, not full-film audio export or desktop acceptance. |
+| TRACK1: misleading confidence | Target-interior texture diagnostic flags all 49 frames of the retained synthetic wrong-track case. Six new regressions and 13 existing plate tests pass. | Geometry is unchanged: worst error 6.861 px at correlation 0.956. Wrong textured planes can evade this warning. Original real-footage failures remain unavailable. |
+| FLOW1: recoverable generation | Network-free local prototype passes 11 crash/concurrency/input/output fault tests using retained real pickup and handoff media. | Native transport/UI, actual provider reconciliation and atomic managed-asset import. No claim of provider idempotency or prevented real charges. |
+| ST2–3: reusable cast / contrasting styles | First brief: three styles. Second carry/set-down brief: two styles,80 additional frame samples,20 control checks,672 decoded/replayed frames and six deliberate contact faults detected. [Second-brief evidence](hybrid-story-second-brief-2026-11-14.md). | Cast/rig/look reuse is demonstrated; action required new code. Tray-specific grip, natural movement, listening and full native delivery remain open. |
+| LIGHT1: moving product illumination | Independent refinement avoids observed notebook glare, produces finite-source café penumbrae and lights cup front after an explicit lamp move. Coordinator verifies96 new samples,21 edits and936 decoded/recomputed frames. [Corrected measurements](hybrid-lighting-refinement-2026-11-14.md). | Diagnostic-sphere contamination corrected; fixed poses only. Floor/screen tradeoffs, negligible practical-light reflections and composition/quality limits remain. |
+
+## Story: the earlier failed draft is historical
+
+The original Fable worker resumed and fixed two shot routines that read camera position before setting the current frame's camera. Its final film remains 48 seconds, 720×1280, 24 fps. The earlier recovered draft and failed seek result are retained; they are superseded for current runtime acceptance, not erased.
+
+The coordinator performed a fresh full sequential pass, additional seek samples, and one change/restoration per declared control. No page or resource errors appeared in that pass. These are same-machine, same-browser comparisons. They do not prove pixel identity on another GPU/browser or high-quality acting. The source still uses painted facial detail, rigid body segments, approximate lip-sync, stock speech and system fonts. Audio level/timing measurements are not a listening review.
+
+The CLI specimen exposed a missing managed Chromium installation even though another compatible Chromium existed. An explicit `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` option now selects an existing absolute executable path, with no automatic download or silent fallback. Rendering verifies launch and records the browser version plus whether an override was configured. `doctor` checks file presence; it does not claim launch compatibility. A runtime-source change intentionally requires project rebind under the existing binding contract. The CLI specimen passed after explicit rebind. All 136 SDK unit tests pass, including configuration validation and distribution documentation consistency.
+
+## Tracking: a useful warning is not a repaired track
+
+The diagnostic samples the selected quad's interior, excluding its surrounding template margin, and checks spatially distributed two-axis texture. It identifies blank targets, a single edge, concentrated detail and out-of-frame support. Its thresholds are heuristic, not calibrated accuracy probabilities. The result reports `accuracy_verified: false`; even distributed texture does not approve identity or visibility.
+
+The comparison video shows the same wrong geometry before and after, with an added review warning. Do not interpret the warning as a correct replacement surface, an automatic hide/reject decision, a new tracker, or a visual-native-UI feature. Independent surface identity, occlusion recovery and boundary accuracy remain research gates.
+
+## Generation workflow: tested contract before host integration
+
+The local prototype freezes scene revision, action, provider/model and ordered reference hashes. It persists an attempt marker before any external transport would begin. A forced process exit at that point reopens as ambiguous; automatic retry is refused. Explicit provider-ID reconciliation can resume the record. Two concurrent owners cannot both start the same row.
+
+Changed reference order/bytes, changed endpoint/action and stale revisions are rejected. Decoding is separate from visual acceptance. Corrupt or failed replacements preserve the last accepted take across restart; a modified output cannot be accepted. Variable-rate media requires an explicit conform step.
+
+The retained pickup decodes to **121 frames / 5.041667 s**, and the handoff to **169 frames / 7.041667 s**, both 1280×720 at 24 fps. Requested five/seven-second durations must not replace measured timing.
+
+Limits: this local SQLite prototype assumes one transport owner has stopped before recovery. Its local approval field is not an authorization boundary. Mutable file paths need atomic managed-asset import. No actual provider timeout, credit reconciliation, authenticated desktop integration or new paid request was exercised.
+
+## Remaining gates
+
+Hair/contact whole-clip evidence, mixed human/product directional lighting, nested transparent materials, real additional computers, SAM 3 access/runtime, camera solve (feature 6), and reconstructed worlds (feature 13) remain open. Authored fantasy scenes do not complete camera solve or world reconstruction. Neither a completed worker nor passing integrity tests establishes visual production readiness.
+
+## Mask audit and provider interruption
+
+[Controlled five-background hair audit](hybrid-mask-audit-2026-11-14.md): same foreground RGB,96 frames and four alpha variants. Repair reduces measured temporal residual by37.6%, but an analytic visibility counterexample demonstrates why smoothing is not accuracy. MASK1 remains partial. Fable reached its provider limit before this review; Opus reached the same limit while diagnosing dark submerged ice. Glass stills/sources are retained but unverified; GLASS1 now needs resumption and verification, rather than remaining shown as actively running. No new hosted calls.
+
+## Resumed glass study
+
+The earlier interruption is historical. [Verified nested-transparency follow-up](hybrid-glass-study-2026-11-14.md) changes GLASS1 to partial: 54 fresh frame comparisons and five control restorations pass; sixteen clip files decode. Source and isolated layers explain why stock capture hides contents. R2 restores cylinder inversion but omits submerged ice; the matched Cycles candidate preserves stronger nested detail at substantial cost. General transparent-material support remains open.
+
+## Resumed hair isolation study
+
+The provider interruption is historical. [Completed mask follow-up](hybrid-mask-followup-2026-11-14.md) keeps MASK1 partial: source preparation, context and resolution are separated; the room-aware repair reduces a partial halo proxy by48% but synthetic yellow composite error by only2%. Coordinator checks reproduce36 frames, nine control restorations, a fresh mount and all12 video decodes. Reference data remains model-assisted; no general hair-accuracy or production approval follows.
+
+## Stronger models tested; MASK1 remains partial
+
+[Verified local model comparison](hybrid-stronger-matting-2026-11-14.md): ResNet50 reduces a room-opacity proxy but loses more hair; ViTMatte softens low-contrast curls. Coordinator reproduces the synthetic ranking reversal, 36 fresh renderer samples, 13 controls, a fresh mount, saved CPU/MPS alpha agreement within one code and all 12 comparison-video decodes. A fixed-region head/body combination is experimental. No whole work item closes; 26 scoped subchecks remain resolved.
+
+## Local CLI round trip and audio repair
+
+[Verified replay workflow](hybrid-roundtrip-workflow-2026-11-14.md) adds two scoped subchecks, bringing the checkpoint to 28 resolved subchecks and zero whole items closed. The coordinator fixes portable-renderer audio loss and unity-rate stretching in the SDK, verifies full film/trim exports and repairs a separate reference-descriptor mismatch in the research ledger. Native import, provider reconciliation, audio listening and normal-speed visual acceptance remain open.
+
+## Moving reflections checkpoint
+
+LIGHT1 stays partial. New worker evidence is under independent review; the total remains 28 scoped checks resolved and 0 whole work items closed. [Results and remaining defects](hybrid-moving-reflections-2026-11-14.md).
+
+## Shared human/product light checkpoint
+
+HUMAN1 moves from working to partial. No new independently resolved subcheck: 28 remain. Broad relighting and the proposed simple guard are not validated. [Evidence](hybrid-shared-human-light-2026-11-14.md). Follow-up reflection repair and import recovery hit the Claude API rate limit; no completed result is claimed.
+
+## Import and recovery checkpoint
+
+Validated imports and expected export identity add two scoped checks: 30 resolved, 0 whole items closed. The worker recovery proposal remains unadopted after the coordinator reproduced concurrent stale-lock takeover. [Evidence](hybrid-import-recovery-2026-11-14.md).
+
+## Independent moving-reflection review
+
+LIGHT1 remains partial; 30 scoped checks remain resolved and 0 whole items are closed. Pixel-based review improves flat self-reflection and local irradiance but corrects earlier geometry-only accuracy claims. A matte offline comparison fails in one penumbra arrangement; glossy calibration remains untested. [Evidence and next experiment](hybrid-reflection-review-2026-11-14.md).
+
+## Concurrent recovery adoption checkpoint
+
+33 scoped checks are resolved, with 0 whole work items closed. Fresh verification passes 147 unit tests, build/browser/beta, 19 import/edit faults, 21 render faults and 30 rounds of six contenders. Numbered locks and private CLI render records replace the rejected stale-unlink design. Automatic recovery sends no signals; explicit browser termination is opt-in. The coordinator also repaired mutating dry-run behavior. Native/provider integration, other platforms, network filesystems and power-loss durability remain open. [Implementation, evidence and limits](hybrid-concurrent-recovery-2026-11-14.md).
+
+## Direct-light calibration checkpoint
+
+35 scoped research subchecks are resolved, with 0 whole work items closed. The café point-shadow bias mismatch is explained and direct light repaired in A/I. A single-scatter GGX direct reference agrees with separate CPU integration across three retained poses. Coordinator recomputation and 48-frame decode confirm the recorded evidence, not fresh-render or motion approval. No default shader changes are adopted. Mixed bounces, nearby reflections and a bright horizon band remain; offline rendering remains a code-based route, not a reason to regenerate known geometry with diffusion. [Evidence and next motion/proxy test](hybrid-light-calibration-2026-11-14.md).
+
+## Motion and spatial-reflection checkpoint
+
+38 scoped research subchecks are resolved; 0 whole work items are closed. One-bounce reference validation, the satin/polished sampling boundary, and exact-proxy reflections are now evidenced. Held-out cylinder error falls from 20.0 to 2.4 display codes, but proxies exactly match the simple test shapes. Tiny polished highlights shimmer without supersampling; matte bounce and real-product proxy errors remain open. Three old frozen-method hashes are stale and are not valid protocol evidence. Coordinator checked 86 hashes, decoded 408 preview frames and recomputed 45 ratios. [Results, corrections and next real-product test](hybrid-motion-proxy-2026-11-14.md).
diff --git a/docs/hybrid-glass-study-2026-11-14.md b/docs/hybrid-glass-study-2026-11-14.md
new file mode 100644
index 0000000..afd7ab3
--- /dev/null
+++ b/docs/hybrid-glass-study-2026-11-14.md
@@ -0,0 +1,41 @@
+# Nested glass, liquid and ice: verified limits
+
+2026-11-14. **GLASS1: partial. No production approval or integration patch.** The previously interrupted study resumed and completed. Its original failures and coordinator verification are retained. New hosted-model spend: $0.
+
+## What changed
+
+The stock three.js r180 transmission capture samples opaque objects and, on this tested GPU path, back faces of double-sided transmissive objects. Transmissive front faces do not generally see each other. This explains why the glass can conceal the liquid and ice. The coordinator inspected this path in the installed renderer source. Clean geometry fails too; removing overlaps alone does not solve the capture limitation. The double-sided back-face path is skipped when WEBGL_multisampled_render_to_texture is present, so the single-sheet workaround is not a portable default.
+
+| Route | Adding liquid: mean RGB code change in the same region | Main limit |
+|---|---:|---|
+| Original stock approach | 0.37 | Contents almost invisible |
+| Clean geometry, stock approach | 0.74 | Geometry cleanup alone does not fix capture |
+| Closed double-sided shell | 0.68 | Inner shell wins the capture |
+| Single-sheet workaround (R1) | 43.96 | Flat tint, milky ice; abandons closed shell |
+| Layered cylinder refraction (R2) | 72.10 | Over-bright liquid, dark upper ice, submerged ice omitted |
+| Cycles reference | 50.30 | Slow, authored interface setup and physical approximations |
+
+These are visibility signals, not quality scores. A larger signal is not necessarily better. R2 restores cylinder lens inversion, but has a bright base band and only supports a vertical liquid cylinder with a flat top. Its omission of submerged ice is explicit, not a solved feature.
+
+## Independent coordinator verification
+
+- 54 new out-of-order raster frames across three routes and two shots match the saved lossless video pixels exactly.
+- Five independent control edits change pixels and restore identical PNGs; no page errors.
+- Eight full lossless clips and eight full MP4s decode: 72 frames each, 1280×720, 24 fps. There are eight unique sequences, not sixteen independent scenes.
+- Recomputed the six liquid-visibility values above from retained geometry masks and stills.
+- Recomputed liquid-region brightness range under the moving practical: R1 4.73, R2 2.78, Cycles 12.56 luma codes. The fast routes respond weakly through the liquid.
+- Rechecked all five emissive calibration swatches: maximum difference at most one code in the sampled patches.
+
+The coordinator inspected still comparisons and renderer source. No fresh Cycles rendering, normal-speed perceptual review, or independent performance benchmark was performed. Geometry masks are worker-generated, not human ground truth. An initial measurement invocation ran before queued capture finished and failed for a missing receipt; the subsequent complete verification passed.
+
+## Reference boundaries
+
+The reference shares geometry export, camera path, HDR and the three.js Neutral+sRGB display transform. It is a much better controlled comparison than the earlier mismatched tone maps. It is still not physical ground truth: caustics are off, glass casts an opaque shadow, nested interfaces use small insets and relative IOR changes, and pixel filters differ. Raster omits scene reflections and indirect bounce, while the reference includes them; raster uses a point highlight versus an 8 mm source in Cycles. The worker measured a 4.2-code grey-sphere difference and a 20.6-code chrome-sphere difference, with chrome-only environment alignment correlation 0.92. Do not attribute every pixel difference solely to transmission.
+
+## Route decision
+
+Keep editable raster as the default for the already-supported opaque scenes. For hero shots whose nested transparent contents matter, offer a separately validated offline quality route; the tested Cycles setup is the strongest candidate for this particular drink, not a general certified export path. Keep R2 experimental and opt-in for authored cylindrical drinks with its omitted ice and lighting limitations disclosed. Do not silently replace closed geometry or omit nested objects in a quality export.
+
+Worker timings on one Apple M6 / 16 GB Mac: R2 about 11.5 ms per frame for synchronized rendering, about 96 ms including capture; Cycles 7.2–8.4 seconds per frame at 64 samples plus denoising, approximately 9–10 minutes per 72-frame clip, with peak RSS 4.3–5.1 GB. These measure different pipeline scopes and are not ordinary-computer guarantees. No NVIDIA hardware was used.
+
+Still open: arbitrary liquid shapes, glass/base refraction, submerged and above-surface ice, scene reflections, calibrated brightness, moving practical-light response, other hardware, native integration, and visual approval. No whole research item is closed by the passing integrity checks.
diff --git a/docs/hybrid-import-recovery-2026-11-14.md b/docs/hybrid-import-recovery-2026-11-14.md
new file mode 100644
index 0000000..aa5fbcd
--- /dev/null
+++ b/docs/hybrid-import-recovery-2026-11-14.md
@@ -0,0 +1,40 @@
+# Validated imports and gated exports; crash recovery still open
+
+> Superseded recovery status: numbered locks and bounded CLI job recovery are now adopted after fresh fault tests. The rejected proposal below remains historical evidence. [Current implementation and limits](hybrid-concurrent-recovery-2026-11-14.md).
+
+2026-11-14 · FLOW1 remains partial
+
+The worker reproduced corrupt imports, orphaned render resources, stale edit locks and export races on one Mac. Its full scratch patch is retained as a proposal. Coordinator review adopted only private-copy import validation and expected export identity checks. Automatic job recovery, stale-lock breaking, asset removal, runtime rehashing and the self-SIGKILL test hook are not adopted.
+
+## Implemented subset
+
+`asset-add` now copies into a private staging directory, hashes the copy, validates its declaration and JSON data, strictly decodes media with FFmpeg, and runs the existing preparation checks before publishing the manifest. Prepared-analysis receipts also validate referenced alpha media rather than taking the early data-only return in the worker proposal. A candidate whose source changes during copy is pinned under the copied bytes' hash. Existing immutable content is never overwritten. Normal validation failure cleans the staging directory and leaves project and manifest unchanged.
+
+The final content file is installed before the manifest. A crash between those steps may leave unreferenced bytes. SIGKILL may also leave staging/decode directories and the old edit lock. No automatic sweep or lock breaking is enabled by this change.
+
+`render --expect-revision R --expect-binding B` refuses a mismatched project snapshot before allocating output or launching a browser. Missing flag values are refused. These optional flags bind a caller's gate to the snapshot the renderer reads; they do not freeze arbitrary project files or external network resources. Hosts must compare output receipts with their own accepted take/ledger state before publication.
+
+Imports now pay the validation/decode cost earlier. The worker measured a retained seven-second 720p import at approximately four seconds rather than 61 ms. This is worker evidence on one Mac, not a general performance guarantee.
+
+## New finding: concurrent stale-lock recovery is unsafe
+
+The coordinator reproduced a race in the worker's proposed lock recovery. Two contenders read the same dead owner. The first removes the stale lock and installs its live successor. The second then writes its stale-owner record over that new lock, archives it and acquires another lock. Both calls return success before either releases.
+
+The reproduction deliberately controls filesystem scheduling in a scratch project, using the proposal's actual `acquireLock` function. It is not a timing-only suspicion and signals no processes. This blocks adoption of automatic lock breaking despite the worker's passing sequential recovery tests.
+
+Additional proposal limits remain: process identity uses `ps` with second-resolution start time; imported job records are trusted to name same-user processes; Playwright artifact routing uses an undocumented launch option; Windows identity and preview recovery are untested. These are outside the adopted subset.
+
+## Coordinator verification
+
+Three regression tests cover valid video/audio/image imports, corrupt/truncated media and invalid JSON refusal, immutable IDs, invalid track data, derived frame-count mismatch, missing prepared-alpha references, copied-byte identity during a source change, and stale export rejection before output allocation. The full suite passes 140 tests and the required build passes. The stale-lock race above is retained separately as a failing proposal experiment. A fresh real-CLI smoke run also passed: media init, validated import, explicit rebind, stale-revision refusal, and three PNG frames whose receipt matches the expected revision and binding. This is a short CLI check, not a full native-app export.
+
+The full worker suite reported 12/12 importer cases, 8/8 cancel/kill scenarios and 3/3 removal recoveries in its scratch patch. Those numbers are not tests of the adopted subset and are not carried forward as production coverage. Its partial-checkout regression baseline lacked website files; the coordinator used the full current SDK checkout instead.
+
+## Still open
+
+- Recovering SIGKILL leftovers without competing recoverers breaking a live successor's lock.
+- Safe asset removal with useful history recovery and clear missing-asset errors.
+- Runtime/source changes during bundling and live static paths outside pinned assets.
+- Native desktop import/export integration, provider reconciliation, billing/idempotency and other hardware/platforms.
+
+Existing projects require explicit rebind because the renderer implementation is part of runtime identity. All generated footage remains unchanged; these fixes protect the path that imports and exports it.
diff --git a/docs/hybrid-learning-checkpoint-2026-11-15.md b/docs/hybrid-learning-checkpoint-2026-11-15.md
new file mode 100644
index 0000000..2a30201
--- /dev/null
+++ b/docs/hybrid-learning-checkpoint-2026-11-15.md
@@ -0,0 +1,31 @@
+# Illustrated stories and real-mesh reflections: 15 November 2026
+
+Research evidence, not a runtime release or production approval. The shared private learning notebook holds the films, comparisons and retained failures. These conclusions are scoped to two delivered studies on one Mac.
+
+## Illustrated 2D stories now have a concrete example
+
+A 34-second original office/shop/city cartoon was drawn entirely with Canvas 2D code through `defineRenderer` and `mountRenderer`. The recurring cast, illustrated sets, exact signage and charts demonstrate another code-authored video family beyond the earlier 3D fantasy examples.
+
+Labels, captions, palette, framing and selected acting choices remain editable in preview. Changed dialogue requires rebuilding the recorded voices; cut-time edits require soundtrack alignment; a new MP4 always requires export. The full film used a custom harness and FFmpeg audio muxing. The real CLI was checked on four edited frames and a 48-frame silent specimen, not the whole film with sound.
+
+The worker reports deterministic seeks and five edit/restores. The coordinator verified deliverable hashes, full decode and duration, and inspected the contact sheet. Neither watched normal-speed playback or listened to the soundtrack. Acting is pose-based, mouth motion follows volume, the night palette misses signs and the facepalm obscures an eye. Reuse across a second story remains untested. A watchable example does not close the broader story-production track.
+
+Next: viewing feedback first; then a second script using the same cast if the visual direction is useful.
+
+## Real meshes narrow the fast-reflection route
+
+The next experiment used a third-party laptop mesh and a procedural cup. Simple per-part reflection proxies improved the laptop deck reflecting its own lid and screen. The same rule represented a ring handle as a solid box, incorrectly darkening the cup wall beside it. One proxy per entire product also lost the laptop's self-reflection.
+
+Keep proxy rendering as a bounded preview/export candidate for slab-like parts. Use offline rendering of the same code scene for complex hollow shapes, highlights reflected between glossy surfaces and diffuse bounce light. This is a renderer choice; it does not require diffusion.
+
+The measured comparison uses diagnostic materials, not the asset's final coatings. Hero-material previews are stills only and uncalibrated. Display reflections, edge quality, other devices and normal-speed review remain open. LIGHT1 stays partial and no default shader or integration patch is adopted.
+
+The worker retained failed tuning passes and rendered a full 84-frame offline comparison. The coordinator decoded the comparison clips and inspected the handle failure crop; the numerical transport results were not independently recomputed in this handoff.
+
+## Routing remains per shot
+
+- Code scene: exact graphics, illustrated characters, controllable objects and authored motion.
+- Slower rendering of that scene: complex light transport where the geometry and materials are available.
+- Joint generated performance: photoreal people and products interacting when suitable rigs, captured motion or assets are unavailable.
+
+The last route is supported by earlier interaction trials, not newly tested by these lighting experiments. These are current practical choices, not a proof that a video category is impossible with code.
diff --git a/docs/hybrid-light-calibration-2026-11-14.md b/docs/hybrid-light-calibration-2026-11-14.md
new file mode 100644
index 0000000..e35e3a6
--- /dev/null
+++ b/docs/hybrid-light-calibration-2026-11-14.md
@@ -0,0 +1,48 @@
+# Direct-light calibration and the remaining reflection boundary
+
+> Follow-up: [motion and spatial-proxy testing](hybrid-motion-proxy-2026-11-14.md) independently validates the one-bounce reference, demonstrates a polished-highlight shimmer limit, and corrects the old freeze/emitter/horizon claims. This page records the earlier checkpoint.
+
+2026-11-14 · LIGHT1 remains partial · research options only
+
+The unexplained café penumbra comparison is now explained and repaired for direct light in the retained research scenes. The remaining indirect-light discrepancy is explained but not repaired. A glossy direct-light reference has also been checked against a separate CPU integration method. None of the shader changes is adopted as a library default.
+
+## What changed
+
+The retained point-shadow bias was normalized against a roughly 500-unit depth range. A bias of -0.002 therefore allowed approximately one world unit of shadow leakage. That hid nearby cup, handle and saucer occlusion. The earlier arrangement-A agreement was partly cancellation between this leak and lamp-stem occlusion of the emitter samples, not a sound calibration.
+
+The opt-in repair uses a 3 mm world-space bias, directs the normal offset toward each light, excludes the lamp stem inside the bulb from that bulb's shadow maps, and uses a symmetric emitter sample distribution. Fixing only the bias exposed lampshade-interior self-shadowing; the second correction matters. Two failed clipping implementations are retained.
+
+| Direct lamp energy / Cycles reference; ideal = 1 | Retained | Repaired |
+|---|---:|---:|
+| A cup | 0.980 | 0.998 |
+| A saucer | 1.060 | 1.007 |
+| I cup | 1.351 | 1.000 |
+| I saucer | 1.115 | 1.008 |
+
+These are regional means, not per-pixel correctness. The coordinator independently recomputed them from the retained linear arrays and object masks. Absolute mean linear errors remain 0.00095–0.00520. The change in the retained styled café frames is subtle overall: worker measurements report 0.33–0.38 display codes mean frame change, with stronger differences at contacts. This is not a new finished advert.
+
+## One glossy reference, with a narrow material contract
+
+The worker matched geometry and matte lighting before comparing a white, single-scatter GGX metal cylinder. Cycles direct light agrees with the separate CPU GGX integral at approximately 1.000 mean ratio and 0.3–0.5% relative RMS over three tested poses. The coordinator recomputed the comparison on 1,486 / 1,649 / 1,649 retained sample points. This checks consistency of retained evidence, not an independent derivation or fresh render of the reference integrator.
+
+The raster's specular anti-aliasing widens the highlight. Removing that term brings its tail energy ratio from 1.10–1.12 to 0.995–1.008, including the worker's held-out light pose. Regional mean improvement does not eliminate residual pixel error: relative RMS remains 4.7–6.9%. Disabling anti-aliasing could introduce shimmer; that has not been tested. Clearcoat, Principled materials, textured roughness and arbitrary metal finishes are not covered.
+
+## Why the whole picture still differs
+
+The reflection probe has the wrong spatial view of the floor and misses the neighbouring sphere. A floor-plane correction improves the lower cylinder, but the upper bright band remains around 1.75× the reference. The modified clip still has about 18.5 display codes mean cylinder error, versus about 22.3 for the frozen method. A brighter result is not automatically a better result.
+
+The café probe captures mix bounce orders. After direct-light fixes, their indirect result matches neither a universal one-bounce nor a complete multi-bounce solution: it reaches 43–72% of the eight-bounce cup reference in these arrangements. The worker did not independently validate Cycles indirect light, and the eight-bounce still is noisy.
+
+## Routing decision
+
+1. **Editable raster:** useful for responsive staging and bounded direct-light/shadow work. Keep world-scale bias and emitter geometry explicit. Do not disable specular anti-aliasing globally from this study.
+2. **Offline rendering of the same scene:** the demonstrated route when nearby reflections, nested transparent materials or multiple light bounces matter. This remains code-generated video; it is not outside code generation's capabilities. A production adapter must preserve geometry, camera, material and light identity, expose unsupported features, and test export parity.
+3. **Joint diffusion take:** retain for photoreal human/object performance when usable geometry or controllable motion is missing. No diffusion was needed or tested here. A generated take keeps its internal lighting/action baked; overlays and whole-frame trim/crop remain editable under the earlier workflow.
+
+The boundary is assets, physical requirements and compute budget—not “all hard lighting needs diffusion.” The worker's CPU timings are about 1.5 seconds per 480×270 glossy frame and 20 seconds per 1280×720 matte café frame. They do not establish performance on typical computers.
+
+## Verification and next experiment
+
+The coordinator read the relevant installed shader code, recomputed four café ratios and three glossy reference comparisons, verified all 14 delivered-file hashes, decoded all 48 frames of the 2-second 1440×270 comparison, and inspected the café and glossy comparison stills. No fresh rendering, normal-speed viewing, sound review or cross-hardware test was performed. No runtime source changes or paid model calls were made in this checkpoint.
+
+Two scoped research subchecks are now resolved: direct café calibration for A/I, and retained direct-GGX reference agreement for three poses. LIGHT1 remains partial. Next: independently review the reference and test the anti-aliasing change under motion; try one bounded importance-sampled reflection lookup with explicit scene proxies against the same reference. Preserve failures and reject it if shimmer, cost or remaining errors make offline rendering the better route.
diff --git a/docs/hybrid-lighting-followup-2026-11-14.md b/docs/hybrid-lighting-followup-2026-11-14.md
new file mode 100644
index 0000000..06b5f26
--- /dev/null
+++ b/docs/hybrid-lighting-followup-2026-11-14.md
@@ -0,0 +1,46 @@
+# Moving product lights — resumed study, 2026-11-14
+
+**Verdict: partial improvement in two local examples.** The resumed Opus study delivered eight before/after, hero/diagnostic clips. The coordinator independently reproduced sampled frames, individual control reversions and the principal region measurements. This does not approve either shot as a finished advert or establish a new native lighting feature.
+
+> **Correction and follow-up:** [Independent refinement and corrected measurements](hybrid-lighting-refinement-2026-11-14.md). Diagnostic spheres contaminated three earlier regions; the coordinator reproduced those contaminated pixels too. The corrected figures below use refs-off hero renders. The screen-veil and palm-gradient explanations below are also revised. New path/flag and finite-source results supersede the pending-follow-up status, without establishing general production readiness.
+
+## What changed
+
+The current notebook's direct key light moved, but its environment reflection card stayed fixed. The experiment now couples card direction, colour and intensity to the key controls and captures the lit floor/backdrop into the reflection environment. A product-footprint contact term replaces the earlier ellipse, which faded before the front edge.
+
+The café pastry received no light from the original practical lamp. Isolation renders show it behind the cup's shadow from that lamp. Removing the distance cutoff alone did not solve this. Moving the lamp between/behind the objects and reducing competing fill produces a visible pastry rim light. The revised set therefore differs from the original placement.
+
+These are explicit source changes in retained experimental scenes. They are not automatic scene understanding or a generic learned relighting model. The photographed café backdrop is unchanged.
+
+## Independently recomputed observations
+
+Values are image-code measurements, not perceptual scores or calibrated physical illumination. The notebook rows use projected surface regions and the café rows use the documented object-support masks. Camera and product pose are held fixed while lighting varies; moving-object interaction is not tested by these clips.
+
+| Measurement | Before | After | Interpretation |
+|---|---:|---:|---|
+| Left palm-rest luma range, refs-off full direction sweep | 1.58 | 20.46 | Corrected product-only response; earlier sphere-contaminated2.28→15.56 withdrawn |
+| Right palm-rest luma range | 0.69 | 18.41 | More response to key direction |
+| Chrome colour shift relative to wall shift | 0.035 | 0.493 | Reflection now follows changing light colour |
+| Screen warm/cool colour shift | 0.19 | 0.23 | Emissive content is not simply tinted with the room |
+| Resting screen luma | 46.63 | 60.24 | Unwanted veiling reflection raises the black level |
+| Front contact strip / open floor luma, refs off | 0.991 | 0.909 | Corrected heuristic; earlier0.841→0.787 measured sphere/shadow contamination |
+| Pastry warm/cool mean absolute RGB change | 0.000 | 3.042 | Mostly a narrow rim/back light |
+| Cup warm/cool mean absolute RGB change | 0.873 | 1.150 | Front-face response is still weak |
+| Photographed background maximum pixel change | 0 | 0 | No photographic relighting; both full 144-frame diagnostic sequences checked |
+
+The coordinator decoded all eight MP4s: four notebook clips of 168 frames and four café clips of 144 frames, all 1280×720 at 24 fps. Fresh reverse-first samples, including the screen-glare interval, matched all **292** saved sequential hashes. All **26** individual control edits changed pixels and restored exactly immediately after each edit. No page/request errors occurred. These checks use one Mac/browser; no cross-device guarantee follows.
+
+## Failures retained, and limits that remain
+
+- A first notebook export had a reflection step when its moving key card passed behind a fixed emitter card. The first experiment forced the key card to draw over other emitter cards. The follow-up reproduces this with a nearby depth-tested emitter and then aligns its direction to the key. Single-probe parallax and uncalibrated emitter energy remain approximations.
+- The display catches a broad glare during frames 28–46. The worker measured a peak mean screen luma around 129; coordinator still inspection confirms the visible contrast loss. Two black-flag placements did not materially reduce it. The completed follow-up avoids the observed glare with an elevated key path and a flag, keeping the display material unchanged. Its floor/reflection tradeoffs remain documented separately.
+- **Withdrawn interpretation:** the earlier palm-gradient reduction was the diagnostic sphere. Refs-off gradient increases; the separate left-to-right deck contrast falls, largely due to the rim card according to the refinement study. Resting display veil comes primarily from a fill card, not the lit room.
+- Contact darkening is a key-independent approximation. This does not establish area-light shadows, general indirect bounce, or mutual reflections among arbitrary products.
+- The first café experiment has zero source size, so its pool and shadows are hard. The completed finite-source follow-up softens distant shadows while preserving tighter contact. The pastry receives a rim light and the cup front remains weak. Several strength/cutoff/placement attempts failed before the isolation diagnosis. The first placement cannot be called repaired merely because a later placement works better.
+- The procedural notebook concept, scanned pastry and procedural cup are the only cases covered. Actual product-material fidelity, the desktop and other product classes remain unverified here.
+
+## Current decision after independent refinement
+
+Keep the coupled-light/reflection approach as an explicit authoring option. The [completed follow-up](hybrid-lighting-refinement-2026-11-14.md) tests an unchanged-material glare-avoiding path, labelled finish alternatives, finite-source shadows and a separate front-side lamp placement. Keep LIGHT1 partial: reflective practical lights, floor/display tradeoffs, moving objects, native integration and broader hardware remain open.
+
+The original quota interruption and failed attempts remain retained. No new hosted-model calls or paid assets were used.
diff --git a/docs/hybrid-lighting-refinement-2026-11-14.md b/docs/hybrid-lighting-refinement-2026-11-14.md
new file mode 100644
index 0000000..d42b015
--- /dev/null
+++ b/docs/hybrid-lighting-refinement-2026-11-14.md
@@ -0,0 +1,64 @@
+# Notebook glare and finite café lighting — corrected evidence, 2026-11-14
+
+**LIGHT1 remains partial.** A second implementation removes the notebook's glare with the display material unchanged, gives the café lamp a finite size, and tests a separate composition that lights the cup front. These are opt-in authored scenes, not automatic lighting or a new framework default. No paid calls were made.
+
+## Correction to the earlier report
+
+The coordinator's earlier independent recomputation used the same diagnostic images as the first worker. Reference spheres and their shadows cover roughly **40% of the left palm region, 48% of the front lip and 49% of the contact strip**. Recomputing those pixels did not independently validate that the regions measured the intended surfaces. Retain the original evidence, but supersede the affected interpretation and values.
+
+With reference spheres hidden, the 0–95-frame direction sweep gives left palm response **1.58 → 20.46** codes, front lip **23.43 → 39.45**, and resting contact/open-floor ratio **0.991 → 0.909**. The prior 2.28 → 15.56 palm result and 0.841 → 0.787 contact result are not valid product-only measurements. The corrected sweep also uses the full declared direction interval rather than sparse still samples. A projected contact-region ratio remains a heuristic, not a physical contact measurement.
+
+The earlier claim that the lit floor reduced the palm's spatial gradient is withdrawn. The reference sphere caused that observation. The second worker finds that the separate left-to-right deck contrast decreases, largely because of the rim card; that limitation remains.
+
+Saved isolation renders also correct the resting screen-veil diagnosis: removing the lit room changes mean screen luma by only **−0.02**, while hiding one static fill card changes it by **−15.12**. The coordinator reproduced those values. The earlier flags were behind the fill card from the reflection probe's viewpoint.
+
+## Notebook: fix the light path before changing the product
+
+The key's reflection card was below the direction of its direct light. The new scene aligns their azimuth and elevation, uses a depth-tested nearby card, raises the key as it crosses the screen's mirror direction, and places a black flag in front of the offending fill card. Camera, product pose and display material remain fixed in the comparison.
+
+| Delivered hero-clip measurement | Previous experiment | Path plus flag |
+|---|---:|---:|
+| Peak screen luma, all 168 frames | 129.20 | 40.17 |
+| Resting screen luma | 59.24 | 39.98 |
+| Largest adjacent-frame screen RGB change | 11.76 | 0.037 |
+| Left palm direction-sweep range | 20.46 | 19.87 |
+| Right palm direction-sweep range | 18.45 | 17.76 |
+| Floor direction-sweep range | 3.02 | 19.71 |
+
+These are coordinator recomputations from lossless exports, with reference spheres hidden. Values are 8-bit image codes, not calibrated radiometry or perceptual scores. The emission-only display pixels match exactly, so this result does not recolour the UI artwork.
+
+The improvement has costs: the elevated light brightens the floor, and the very low remaining screen reflection can make the display look pasted on. A path-only alternative retains more glass reflection but also retains the resting veil. The worker also rendered explicitly labelled anti-reflective and matte finish variants: anti-reflective reduces but does not eliminate glare; matte retains glare and takes the key's tint. Neither is evidence about a real manufacturer's coating.
+
+The worker's near-card comparison supports a narrower explanation of the old forced overdraw: it approximates a key emitter nearer than the other cards. That does not make the rig physically complete. Single-probe parallax, independently scaled direct-light/card energy, camera-invisible cards and flags that cast no shadows remain limitations. A convincing view at one fixed pose is not general light transport.
+
+## Café: source size and placement solve different problems
+
+The finite source averages 64 deterministic light-position renders in linear light before tone mapping. Each sample has its own shadow visibility. This produces wider shadows far from the caster while keeping contact tighter; it is not a uniform post-render blur.
+
+| Shadow transition, fixed scanline | Point source | Finite source |
+|---|---:|---:|
+| Cup shadow on plate | 0.84 px | 23.92 px |
+| Cup shadow on cloth | 0.82 px | 27.89 px |
+| Pastry contact shadow | 0.86 px | 4.79 px |
+
+Softening the source in the same composition does **not** solve weak front illumination. Moving the lamp to camera-side right is a separate, declared composition change.
+
+| Warm/cool mean absolute RGB response | Previous lamp | Finite source, same position | Finite source, front-right |
+|---|---:|---:|---:|
+| Cup | 1.15 | 1.46 | 40.72 |
+| Pastry | 3.04 | 2.60 | 8.69 |
+| Chrome reference | 0.00 | 0.00 | 0.10 |
+
+The chrome result exposes an unresolved problem: the lamp is effectively absent from reflections. The photographed background is unchanged in the checked region across all three full 144-frame clips. It has not been relit. The foreground lamp is visually large, the cup becomes a flat saturated orange under warm light, and the pastry still sits partly in the shade's penumbra.
+
+## Verification and measured limits
+
+The coordinator reproduced **96 fresh frame samples across six refined hero/diagnostic clips**, and **21 individual edits/restorations**, with no page/request errors. Independent recomputation decoded all frames of three notebook and three café lossless clips: **936 frames**. The worker separately reports 1,065 repeat samples, 61 control checks, and successful decoding of all 11 full clips and 14 delivery files. Those wider counts are worker evidence, not a second coordinator rerun.
+
+Worker capture receipts report about 13.3 seconds for a 168-frame notebook hero and 40.9–41.8 seconds for the 144-frame finite-source café heroes on this Mac. These are end-to-end capture observations for these scenes, not interactive frame-rate or ordinary-computer guarantees. The finite-source method performs 64 renders per output frame.
+
+Visual review used before/after images and contact sheets; no normal-speed viewing or listening claim is made. Product fidelity, moving camera/product interaction, other materials and other hardware remain untested here.
+
+## Updated acceptance
+
+Close only these scoped subchecks: avoid the observed notebook glare on this fixed-pose light path without changing its display material; produce source-size-dependent café penumbrae; demonstrate useful cup-front response after an explicit lamp move. Keep overall LIGHT1 partial. Next work must address reflective practical lights, floor/display tradeoffs, moving products and hardware cost before making this a general default.
diff --git a/docs/hybrid-mask-audit-2026-11-14.md b/docs/hybrid-mask-audit-2026-11-14.md
new file mode 100644
index 0000000..5d6918f
--- /dev/null
+++ b/docs/hybrid-mask-audit-2026-11-14.md
@@ -0,0 +1,36 @@
+# Hair-mask audit across replacement backgrounds
+
+Status: **partial**. Coordinator audit; the requested Fable review hit its provider rate limit before producing an artifact. No Fable approval is claimed. No paid calls.
+
+## Controlled evidence
+
+96 retained frames at 25 fps, cropped to the same head region, are composited over pale yellow, white, dark brown, magenta and a checker. Four columns compare old support alpha, full-resolution/context alpha, repaired alpha and a half-strength repair. All columns use **identical raw RVM foreground RGB** and linear-light straight-alpha composition. This isolates the mask; it deliberately does not reproduce the earlier full repair's RGB averaging.
+
+PNG inputs and stills add no intermediate loss. The underlying inference used retained JPEG source frames; this audit does not undo that compression or rerun inference. Backgrounds are diagnostic swatches, not new realistic room scenes. All five MP4s decode successfully (96 frames each, 3.84 seconds; no audio). The saved contact sheet shows frame 47 on every background; selected frames were visually inspected, not every frame in real-time playback.
+
+| Mask | Adjacent motion-compensated alpha residual |
+|---|---:|
+| Old support | 0.03500 |
+| Full-resolution/context | 0.02198 |
+| Temporal repair | 0.01372 |
+| Half repair trial | 0.01720 |
+
+The same shared nine-pixel boundary band and forward/backward flow check are used for all methods. The full repair reduces this residual by 37.6% against raw; half repair by 21.8%. **These are temporal stability measurements, not annotated hair accuracy.** Small differences from the earlier 0.01366 follow recomputation from quantized saved masks rather than pre-save float arrays.
+
+With foreground RGB held fixed, repair-versus-raw boundary RGB differences average 1.55 codes on white versus 0.20 on dark brown (7.7×), 1.15 on yellow, 0.73 on magenta and 0.78 on checker. This measures sensitivity to the same alpha edit, not error against ground truth. Dark backgrounds conceal much of the difference. At frame 47 the old support produces conspicuous missing/contaminated curl regions; all newer masks improve that still, but faint edge haze remains visible on white.
+
+## The remaining risk
+
+The full repair changes alpha by up to 0.145 after quantization; half repair caps this at about 0.073. Both preserve the raw alpha of pixels >=0.99 exactly. Boundary opacity can be added or removed: the full repair changes net alpha mass by up to about 117 pixel equivalents in either direction. That is not a count of correctly recovered hairs.
+
+An analytic counterexample tests the exact temporal correction formula with perfect correspondence: a true one-frame disappearance (center alpha 0; four neighbors 0.55) becomes alpha 0.144 with full repair and 0.072 with half repair. This is a synthetic test of the correction stage, **not an observed 0.144 ghost in the real clip**; optical-flow validity may reject such samples. It establishes why improving stability alone cannot approve the filter. The half-strength trial trades less change for less smoothing; it is not selected as a superior default.
+
+## Decision and next gate
+
+Keep soft mattes independent of hard SAM support at fine hair. Validate each replacement on light and dark backgrounds. Keep repair strength editable and retain the unfiltered matte. Do not silently choose aggressive temporal smoothing from its own stability score. Before closing MASK1, use annotated fast curls/disocclusions and compare detail, lag and false opacity separately; isolate inference context/resolution/source preparation, and review normal-speed clips. No new general grasp/pointing claim follows from this work.
+
+The glass worker also reached its rate limit. Its raster and Cycles stills and diagnostic sources were retained, but it stopped while diagnosing dark submerged ice. There is no completed calibrated comparison, motion clip acceptance or approved transparency route from that interrupted study.
+
+**Subsequent glass update:** the interrupted study resumed and was independently checked. See [nested-transparency follow-up](hybrid-glass-study-2026-11-14.md); its status is now partial, not awaiting a first result. The mask findings above are unchanged.
+
+**Subsequent hair update:** Fable completed the isolation study after resumption. [Verified follow-up](hybrid-mask-followup-2026-11-14.md) adds limited reference tests and a conservative repair. This earlier fixed-RGB, linear-light comparison remains a separate measurement, not a ground-truth score.
diff --git a/docs/hybrid-mask-followup-2026-11-14.md b/docs/hybrid-mask-followup-2026-11-14.md
new file mode 100644
index 0000000..a962da5
--- /dev/null
+++ b/docs/hybrid-mask-followup-2026-11-14.md
@@ -0,0 +1,61 @@
+# Hair audit follow-up: isolate the model from the repair
+
+2026-11-14. **MASK1 remains partial.** Fable's resumed audit is complete and the coordinator checked its delivered data and standalone renderer. This supersedes the earlier statement that the independent audit was unavailable. No paid calls, downloads or production approval.
+
+## Better evidence changes the interpretation
+
+The earlier coordinator audit held foreground RGB constant and compared alpha variants. It established background sensitivity and stability, not accurate hair extraction. The new study decodes the retained source without an additional lossy intermediate, isolates source compression, recurrent warm-up, resolution and support clipping, and adds two limited references that do not depend on optical flow.
+
+Worker isolation findings on this one 96-frame excerpt:
+
+- Replacing the original JPEG intermediates with lossless decoded frames reduces the flicker score by 39.5% at the same model settings. This was the largest measured single preparation change.
+- At full resolution, 88 preceding frames of context improve the estimated missing-opacity proxy from 1.86 to 0.49, while average flicker barely changes.
+- Warm full-resolution inference improves that proxy from 3.39 at half resolution to 0.49, but softens edges. Higher thin-structure energy can include texture/noise, not just hairs.
+- Hard SAM support removes soft alpha in the hair region. Keep support masks distinct from fine-edge mattes.
+- The five-frame repair reduces real-clip flow-compensated fluctuation by 32.5%, but also reduces thin-structure energy by 8.9%.
+
+Inference was run by the worker, not rerun independently by the coordinator. Its port of the prior repair matched the retained outputs exactly according to its saved receipt. These isolation results improve the evidence, but do not generalize beyond this clip/model.
+
+## What the references do and do not establish
+
+The partial room plate is estimated from other frames of the same locked camera. An RVM-based exclusion mask chooses candidate empty-room samples. Similarity to that plate is useful evidence of a halo, but is **not proof that no low-contrast hair is present**. Coverage is only about one fifth of the hair boundary. The missing-opacity bound assumes the compositing/noise model and reliable plate estimates; avoid calling it an unconditional physical ground truth.
+
+The known-alpha benchmark re-composites a presenter using an RVM-derived, sharpened matte, then compresses the result and processes it again. Alpha is known for this synthetic test, but the test is easier than natural fine curls and uses the same source. It is neither a manual annotation nor an independent footage benchmark.
+
+On that synthetic test, the five-frame repair reduces temporal alpha error by only 4.5%, while yellow-background composite error gets slightly worse: 17.32 → 17.45 RGB codes. Do not describe 32.5% divided by 4.5% as a universal seven-fold correction: these are different metrics on real and constructed clips. The supported conclusion is that lower fluctuation alone cannot establish better compositing.
+
+## Proposed repair and independently reproduced measurements
+
+The proposed `clear_gated3` uses conservative room evidence to clear some opacity, applies a lower-bound correction, then a limited three-frame filter. It requires a fixed camera and background revealed elsewhere in the footage. It is not an automatic solution for arbitrary moving cameras.
+
+| Measurement | Unfiltered full-resolution matte | Proposed repair |
+|---|---:|---:|
+| Real-room halo proxy, mean opacity-equivalent pixels | 87.79 | 45.84 |
+| Same proxy during frames 24–53 | 116.22 | 45.33 |
+| Real-room missing-opacity proxy | 0.495 | 0.148 |
+| Synthetic false-opacity mass | 340.77 | 309.30 |
+| Synthetic composite error on yellow, RGB codes | 17.32 | 16.96 |
+
+The 48% real-room proxy reduction is **not** 48% overall hair accuracy. On the synthetic composite, the improvement is about 2%. All recomputed summary values agree with the worker's numbers within 0.0001. They reuse its plate, inference arrays and synthetic truth; the measurement code is independent, the reference data is not.
+
+The synthetic matte resembles past truth more than future truth under the worker's lag indicator, including before filtering. This supports a model-origin lag problem in that benchmark. It does not establish exact lag in milliseconds or prove that no particular strand gains delay under filtering.
+
+## Renderer and media checks
+
+The coordinator freshly rendered 36 out-of-order samples across three cases: every PNG matches the saved sequential pass. Nine control edits change and restore the result, and a fresh mount reproduces it exactly. No page/resource errors. All 12 delivered MP4s decode and have their frame counts/rates recorded; two intentionally slowed diagnostic intervals are not full-length sequences. These are standalone EditableFrames renderer-host checks on one Mac, not app/exporter integration.
+
+Selected stills were inspected. The concrete-side smoke is reduced, but faint wood-aligned fringes and ragged edges remain. A smear under the moving hand is visible and unaddressed. No normal-speed playback or audio listening acceptance is claimed; clips are silent.
+
+## Revised route
+
+1. Preserve losslessly decoded source frames before matting; do not introduce JPEG intermediates.
+2. Keep recurrent context, inference scale and support-mask clipping explicit and test them separately.
+3. Retain raw mattes and adjustable post-processing. Do not choose repair strength using flicker alone.
+4. Offer the room-aware repair only for its fixed-camera, revealed-background case; uncertain room evidence must not erase plausible hair.
+5. Test a stronger video-matting model against the same source and references, plus genuinely independent footage and annotated edges. The installed MobileNet model remains the main limitation in this study; stronger weights/runtime were not tested here.
+
+The previous coordinator used linear-light compositing with fixed foreground RGB. This study uses encoded-sRGB canvas compositing and model foreground colours. Its 5.3× white/dark error ratio and the prior 7.7× alpha-edit sensitivity measure different quantities; neither replaces the other. Colour-space convention must be declared in comparisons. Keep both evidence sets and all failed repairs.
+
+## Subsequent model comparison
+
+The earlier stronger-model resource gap has now been exercised: [ResNet50 and ViTMatte comparison](hybrid-stronger-matting-2026-11-14.md). Neither earns adoption as a hair matte. The remaining acceptance gap is independent real-hair evidence and motion review, not merely access to larger weights.
diff --git a/docs/hybrid-motion-proxy-2026-11-14.md b/docs/hybrid-motion-proxy-2026-11-14.md
new file mode 100644
index 0000000..7d5ed37
--- /dev/null
+++ b/docs/hybrid-motion-proxy-2026-11-14.md
@@ -0,0 +1,62 @@
+# Moving highlights and spatial reflections: measured boundaries
+
+2026-11-14 · LIGHT1 remains partial · no default shader adoption
+
+A scene-aware reflection method now reproduces the tested nearby sphere and corrects the bright upper band. This extends the useful raster envelope, but its proxies are exact for the simple test geometry. It does not establish accuracy for real products. Offline rendering remains code-generated video, and these lighting errors do not require diffusion.
+
+## What the new reference establishes
+
+A separately written numpy integrator with analytic geometry and two estimators confirms the direct single-scatter GGX reference. It also independently checks one bounce from matte neighbours in five arrangements: Cycles/integrator energy ratios are 0.9976–1.0017. Per-pixel RMS remains 2.9–6.1% with Monte Carlo noise on both sides. Multiple bounces, arbitrary materials and real-product geometry are outside this validation.
+
+The worker freshly reproduced eight retained raster arrays and one Cycles pose byte-identically. The coordinator checked retained evidence and delivery integrity; the coordinator did not repeat the rendering or derive a third integrator.
+
+## Moving highlights: do not switch anti-aliasing off globally
+
+The study moved the light, camera and product for 48 frames, at two resolutions and two roughness values. A 4×4 supersampled reference separates actual highlight movement from sampling error.
+
+| Tested case | AA off | Default specular AA | Decision |
+|---|---|---|---|
+| Satin cylinder, roughness 0.35 | Under 0.2 display codes mean error in the tested cases | Broadens the highlight; error changes with output size | Bounded opt-in, not a new default |
+| Polished cylinder, roughness 0.10, roughly 2-pixel highlight | 2.7% energy pumping; 17.6-code temporal reversal | 1.0% pumping, 5.7 codes, but tails about 3× too bright | Supersample final output |
+
+Clipping the highlight to white hides shimmer; evaluate an unclipped exposure too. The alternative normal-derivative AA formula also widens the polished highlight excessively. Supersampling costs about 27 vs 9 ms for the satin case and 105 vs 34 ms for polished on this Mac. These are research render timings, not export or general-computer performance.
+
+## Spatial reflections: a real improvement with a geometry condition
+
+The new shader samples reflection directions from the material lobe and traces them against a floor plane, sphere and box. It uses a captured view at the hit, handles disoccluded hits explicitly, and returns the background when a ray misses the scene. Tuning used one pose; two arrangements and the motion path were frozen before method development.
+
+| Measurement | Centre probe | Proxy taps |
+|---|---:|---:|
+| Upper-band reflected energy / one-bounce reference, five arrangements | 1.70–2.47 | 0.99–1.03 |
+| Neighbour sphere effect, regression slope | −0.05 to 0.79 | 0.96–0.98 |
+| Whole-picture error on cylinder pixels, five arrangements | 17.7–22.8 codes | 1.3–1.9 codes |
+| Held-out motion, same cylinder metric | 20.0 codes | 2.4 codes |
+
+The coordinator recomputed 45 whole/lower/upper energy ratios from packed linear arrays and independently constructed eroded object masks. All agree with the recorded rounded ratios. These are cylinder-region results, not whole-scene quality scores: matte neighbours remain 21–47 codes too dark.
+
+At 64 taps, grain remains about 4.3 codes RMS against the 1024-tap version and changes over time. About 1024 taps reduces error against Cycles to 1.3 codes, without separating reference noise. Omitting the sphere proxy loses its reflection and increases error to as much as 7 codes. Approximate proxies for real devices, thin geometry, textured/coloured surfaces and broader materials remain untested.
+
+The proxy pass takes 2.3–3.1 ms at 960×540 when the cylinder occupies about 10% of the frame. At 1080p and 75% occupancy it takes 12.9 ms at 64 taps or 47.1 ms at 256 taps. These exclude the separate direct-light pass and capture/encoding. One-bounce Cycles takes about 12 seconds per 960×540 frame on this Mac.
+
+## Corrections to the preceding study
+
+- The older frozen-method manifest no longer matches three retained source/bundle/capture files. Fresh baseline rendering still reproduces the evidence; the old manifest must not be cited as proof of a frozen protocol.
+- The prior held-out light pose includes the highlight peak, not only its tail.
+- Most residual AA-off direct-light error comes from different emitter models: uniform points inside a ball versus a Lambertian sphere. An alternative distribution was checked in the CPU model, not rendered as a new raster result.
+- The upper-band error is not mainly prefiltering. Rays that miss scene geometry were incorrectly answered with nearby floor. A floor-plane-only correction fails one held-out arrangement at 1.78× lower-band energy.
+
+## Routing and next gate
+
+1. **Editable raster:** direct lights and shadows; tested satin highlights; spatial reflections with explicit, adequate proxies. Use more samples for polished or grain-sensitive delivery. Keep these options experimental.
+2. **Offline rendering of the same scene:** complex nearby geometry, matte bounce, multiple reflections and nested glass/liquid. Preserve asset, camera and light identity. This is a compute/renderer choice within code generation.
+3. **Generated joint performance:** use when photoreal interacting people or objects lack suitable assets, rigs or motion. Generated lighting and contact are baked; captions, branding overlays and whole-frame edits can stay live. Diffusion was not used in this lighting study.
+
+Next test: approximate proxies for retained real-product meshes, compared with the actual mesh reference under camera/product/light motion. Include deliberate proxy omissions, self-reflection, an unseen arrangement, quality/cost at final resolution, and an explicit failure threshold. Stop at a measured route boundary rather than calling every partial result solved.
+
+## Verification and retained failures
+
+Coordinator: all 44 delivery hashes and 42 sibling input hashes match; all nine previews decode (408 frames); 45 regional ratios recomputed; three stale old-freeze hashes confirmed; comparison stills and the energy chart inspected. No coordinator fresh render, normal-speed playback, audio or second-device acceptance.
+
+Worker: 352 out-of-order rerenders match, 13 controls change and restore exactly, no page errors. Retained failures include a tail-only motion test, the first proxy method, omitted disocclusion, omitted sphere proxy and over-soft polished AA. No paid calls, downloads or default runtime changes.
+
+Three additional research subchecks are resolved only in scope: one-bounce reference validation; the measured satin/polished motion boundary; and exact-proxy reflection accuracy in the held-out simple scenes. LIGHT1 remains partial and is not approved for production.
diff --git a/docs/hybrid-moving-reflections-2026-11-14.md b/docs/hybrid-moving-reflections-2026-11-14.md
new file mode 100644
index 0000000..abd6623
--- /dev/null
+++ b/docs/hybrid-moving-reflections-2026-11-14.md
@@ -0,0 +1,41 @@
+# Moving-camera and moving-product reflections
+
+> Superseded interpretations: [the independent reflection review](hybrid-reflection-review-2026-11-14.md) corrects the self-reflection, neighbour-effect and screen-cleanliness claims, adds a bounded matte offline comparison, and measures equal-sample timing. The text below records the earlier checkpoint.
+
+
+2026-11-14 · LIGHT1 remains partial · two scenes on one Mac
+
+The new raster method uses colocated visible emitters and direct/specular light, per-object reflection captures, and planar mirrors for flat surfaces. It improves reflection placement under camera orbit and product rotation. It does not establish calibrated product realism or general self-reflection support.
+
+## What the worker measured
+
+| Observation | Earlier method | New method |
+|---|---|---|
+| Notebook screen veil, tuned / held-out | 24.1 / 28.8 image codes | Below 1 in both |
+| Notebook light-source reflection samples reproduced, tuned | 147/180, with 138 false positives | 180/180, with 8 false positives |
+| Cup bulb-reflection samples reproduced | 0/43 | 43/43 |
+
+These are worker-reported image-code and geometric-content measurements, not physical radiometry or independent image-quality scores. The mirror audit shares the rendering geometry, so perfect planar agreement validates plumbing rather than physical accuracy. Held-out layouts were adjusted using ID passes before their first beauty renders; this was a constrained arrangement test, not a blind external benchmark.
+
+The clean screen depends on what it reflects. A lower key crosses the mirror zone and produces visible glare; raising the key avoids it without changing the display material. The emission-only UI differs by a mean 0.0095 codes rather than being byte-identical. The photographed café backdrop remains baked; changes there are confined to the existing steam overlay.
+
+## Remaining defects and failed approaches
+
+- Hiding each object during its reflection capture removes self-reflections. About 52–56% of notebook chassis mirror rays hit the notebook itself. Including it naively shifts the palm rests by about 60 codes.
+- A planar deck experiment improves geometric content agreement but loses the brushed streak; it was added after the held-out run and is not held-out evidence.
+- Nearby-product reflections remain weak or missing on the notebook body. Reflections between the cup and saucer change by several codes on a second bounce.
+- The new café cup is about 30 codes brighter, with no independent energy calibration. The saucer diffuse probe sits inside the cup. These are open defects, not an approved look.
+- The new studio background and neighbouring desktop are darker; held-out contact contrast is weaker.
+- Emitter-only cube captures missed the nearby bulb. A single room probe turned the café table orange. Both failures are retained.
+
+## Verification and limits
+
+The worker reports exact shuffled/reverse seeks and control restoration, plus a three-frame real-CLI edit/stale-edit/undo specimen. The coordinator independently decoded all five comparison previews (120 frames each, 24 fps), checked the CLI receipt's internal consistency, and inspected notebook/café comparison stills. The coordinator has not rerun the reflection measurements. Neither review watched normal-speed playback. There is no offline reference, other hardware, measured GPU utilisation, or finished-advert approval.
+
+Notebook steady rendering is reported at 19–21 ms/frame versus 11–12 previously. Café timing is not a fair speed comparison because the sample count changed from 64 to 32. Capture/encoding costs are separate.
+
+## Next experiment and routing consequence
+
+Independently verify self-reflection, nearby-object visibility and local irradiance before adopting the method. Use fixed geometry and material settings, isolate direct/specular/diffuse terms, retain failures, and freeze the method before a genuinely new arrangement. Recover the saucer probe placement and test whether extra bounces conserve a plausible brightness range.
+
+Code can keep geometry, lights, camera and material edits live. These failures bound this raster implementation; they do not prove that code cannot solve the shot. Offline rendering remains a candidate for complex reflection/refraction. Joint diffusion generation remains the tested route for difficult photorealistic interaction, with baked internals and live code overlays afterward.
diff --git a/docs/hybrid-reflection-review-2026-11-14.md b/docs/hybrid-reflection-review-2026-11-14.md
new file mode 100644
index 0000000..9ceb300
--- /dev/null
+++ b/docs/hybrid-reflection-review-2026-11-14.md
@@ -0,0 +1,49 @@
+# Reflection review: better flat surfaces, incomplete light transport
+
+> Follow-up: the penumbra mismatch is now explained and repaired for direct light, and a narrow glossy direct reference is checked. Indirect transport remains incomplete. [Current calibration](hybrid-light-calibration-2026-11-14.md).
+
+2026-11-14 · LIGHT1 remains partial · research implementation, not a library default
+
+The independent review corrects three earlier interpretations: hiding the notebook from its own reflection capture caused the larger palm-rest error; the brighter café cup was partly justified bounce light and partly a sampling error; and nearby-product reflections were not negligible merely because the approximation failed to draw them. No finished-advert or general hardware approval follows.
+
+## What changed
+
+| Case | Earlier moving-reflection method | Review method | Remaining limit |
+|---|---|---|---|
+| Notebook palm-rest reflection energy / one-bounce reference, A / I / I0 | 2.04 / 1.57 / 1.53 | 1.01 / 0.94 / 0.91 | Flat up-facing deck only; mean energy agreement is not per-pixel agreement |
+| Cup signed brightness bias, three arrangements | +5.9 to +13.0 image codes | −1.8 to −4.4 | Mean absolute error still 5.2–9.0 codes; glossy offline match untested |
+| Saucer signed brightness bias | −3.0 to −10.3 codes | −0.2 to +3.7 | More than one bounce still missing |
+| Nearby object on tuned notebook deck | About 1% of reference change | About 42% | Side-facing and curved surfaces remain weak |
+
+The deck method samples a planar reflection with depth-aware, directionally stretched highlight taps. It recovers the lid/display in the deck without hiding the whole object. The café method places six probes around the cup, one in its bowl, and six above the exposed saucer, preserving the cup and its shadows in those captures. These are explicit scene-specific implementations, not a universal relighting model.
+
+The reference gathers light at each tested surface point and integrates the material response. It is a useful one-bounce reference inside the same raster renderer, **not physical ground truth**. It excludes textured metal and points within 2 cm of other geometry; comparisons disable bump. Its anisotropic reference also removes a clamp found in the renderer's direct-light formula. Therefore its ratios cannot certify the entire product or a manufacturer's finish.
+
+## Corrections to the earlier report
+
+- A ray hitting the right object is a geometry check, not proof that the reflection's pixels have the right brightness or spread. The earlier 43/43 bulb-hit result and near-perfect planar scores must not be described as reflection accuracy.
+- The notebook's clean display is partly a missing-reflection effect. Its reflected energy is 0.21, 0.68 and 0.97 of the per-point reference across three arrangements. Broad highlight tails outside the mirror image are missing. Avoiding a mirror-zone crossing remains useful art direction, but is not a material calibration.
+- The old “at most 0.07 codes” neighbour effect was measured in a renderer that largely omitted it. The new reference sees up to 5 codes on the deck and 39 at a sampled base-side point. New rule-drawn arrangements barely show the neighbour, so they do not establish general neighbour handling. A separate designed stress case still over-responds.
+- The café's roughly 30-code increase was not all an error. Roughly 20–25 codes are supported by the one-bounce gather; the remaining 6–13 mostly comes from probe placement. Lowering exposure would conceal rather than repair that distribution.
+
+## Offline comparison and new bottleneck
+
+In the directly lit café arrangement, matched matte, lamp-only Cycles gives direct light within 2%. The ring improves cup indirect light from 0.73 to 0.91 of the one-bounce reference and saucer light from 0.18 to 1.02. Eight bounces produce roughly twice the indirect light of one bounce.
+
+However, the second arrangement sits in the lampshade penumbra: raster direct light is 1.35 times Cycles and indirect is about 1.9 times. That discrepancy is unexplained. The offline comparison is matte and lamp-only; **there is no matched glossy reference**. The next experiment must isolate this calibration discrepancy before using Cycles as an authority for these glossy shots.
+
+Other remaining issues: side/bevel/lid self-reflections; per-pixel light occlusion; weak anisotropic effect despite improved direction; about 0.7–0.8 codes of fixed deck dither that may shimmer in motion; brass lamp reflections; and missing multi-bounce light.
+
+## Cost and verification
+
+On this Mac only, notebook rendering rose from 18.8 to 21.8 ms/frame. Café rendering at equal 32 samples rose from 48.7 to 70.6 ms/frame; at 64 samples, 75.6 to 95.9. These exclude capture/encoding and are not a claim of interactive performance on ordinary computers.
+
+Worker receipts report 57 reverse/shuffled/edge seeks per clip across six clips (342 checks), 78 control edits/restorations, and no browser errors. Options-off regression matches the earlier build within one code on at most 11 pixels. The coordinator independently decoded all four previews (480 frames), recomputed notebook energy ratios from 360 retained point records and café indirect ratios from the raw point receipts, and inspected the notebook/café comparison sheets. This is arithmetic and delivery verification, **not a fresh render or independent validation of the reference integrator**. Neither review watched normal-speed playback. No new resolved dashboard count is added; the existing integrity checks already cover this kind of evidence.
+
+## Routing decision
+
+1. **Editable raster:** use for stylized scenes and bounded product shots with tested reflection paths. Keep exposure, camera, materials and lights editable; show limitations of the selected method.
+2. **Offline rendering:** retain code-authored geometry and controls, but render expensive reflection/refraction and repeated bounces offline where the shot requires them. This remains code-driven, not diffusion. Match units, materials and tone mapping before comparing results.
+3. **Joint diffusion:** keep for the previously demonstrated photorealistic contact/performance workflow when editable geometry and motion assets are unavailable or inadequate. It bakes interaction, camera and lighting into a take; live captions and graphics are composited afterward. This study made no diffusion calls and provides no new diffusion accuracy claim.
+
+Do not promote the scene-specific shader patches into the library default yet. Preserve them as reproducible research assets while the penumbra discrepancy and glossy reference are investigated.
diff --git a/docs/hybrid-roundtrip-workflow-2026-11-14.md b/docs/hybrid-roundtrip-workflow-2026-11-14.md
new file mode 100644
index 0000000..d4cb2ee
--- /dev/null
+++ b/docs/hybrid-roundtrip-workflow-2026-11-14.md
@@ -0,0 +1,61 @@
+# Scene staging → generated interaction → editable final composition
+
+2026-11-14 · FLOW1 remains partial · local replay, no new provider request
+
+The local round trip now has a concrete example: an editable staging scene produces a frozen reference packet, two retained interaction takes return as baked media, and live code overlays remain editable in the final film. This is a useful interoperability slice, not an integrated provider or native-app workflow.
+
+## Ownership determines what an edit can do
+
+| Requested edit | Local operation | Consequence |
+|---|---|---|
+| Headline, caption, accent, CTA or cue timing | Edit live overlay controls and export | Generated takes and their input packets stay unchanged. |
+| Crop or trim the shot | Resample/cut the whole baked frame | Cannot reveal hidden content or independently move the product. |
+| Change staged product position, grip or contact | Freeze a revised scene packet | Existing take becomes stale; a dependent handoff becomes stale too. Keep old accepted output available. |
+| Change only the handoff action prompt | Freeze a new handoff packet | Pickup can stay fresh; handoff needs replacement and review. |
+| Change a filmed face, light direction or physical interaction | New capture/generation or separately validated VFX work | The current importer has no recovered geometry or independent controls for these baked pixels. |
+
+The tested preference is joint generation for difficult photorealistic interaction, not a claim that code or traditional animation cannot ever produce it. Exact text/UI remain code-controlled. Opaque products with usable geometry can remain rendered. Nested transparent materials may need an offline renderer. A generated shot can be combined with these routes while retaining an explicit record of which layers are editable and which are baked.
+
+## Replay provenance and timing
+
+Both takes are retained outputs from the earlier successful pickup and handoff tests. The replay importer verifies original request/receipt/status/download records, model, prompt, ordered references, job identity and downloaded bytes. It labels each import `retained-replay`, `newlyGenerated: false`, with no transport. It handles the observed status output field as either a string or list.
+
+The staging CLI reproduces the submitted start-image bytes. The handoff start image derives from pickup frame 120, creating an explicit dependency. The resulting film has 121 + 169 = 290 frames at 24 fps, or 12.0833 seconds. A half-second trim at each end produces 266 frames. Requested generation duration is not substituted for actual decoded timing.
+
+Packet identity covers provider inputs, while source revision and binding remain provenance. An undo that restores the exact start-image pixels can restore freshness despite a changed editor revision. This is intentional; a renderer revision alone does not imply the provider saw different pixels.
+
+## Exporter fixes found by the exercise
+
+1. The portable renderer adapter dropped `scene.media`. Audio ports therefore never reached the existing scheduler, producing silent exports. The adapter now preserves explicit media declarations.
+2. Unity-speed audio passed through `atempo=1`. That unnecessary time-stretch shifted the retained soundtrack locally. Unity rate now uses `anull`; non-unity rates retain the existing tempo chain.
+
+Regression coverage schedules portable-renderer audio through offsets, trim, mute and speed, and runs real PCM through the mixer to check sample alignment after trim and delay. Explicit static media declarations are supported; arbitrary DOM audio, animated audio automation and automatic renderer-prop-to-audio binding are not implied. Existing projects need an explicit rebind after this runtime change.
+
+## Evidence and limits
+
+The worker reports full CLI render/edit/undo/redo checks, 290 exact source-frame comparisons with overlays disabled, overlay edits confined to their masks, 96 seek comparisons, and 19 fault/interoperability tests. These worker results remain distinguishable from the coordinator's new checks listed below. Original failed exports and proposed patches are retained.
+
+Coordinator source review found and reproduced an additional packet bug: deleting or reordering reference descriptors, changing their role, or substituting both hash and storage path could pass `load_packet`. It checked each descriptor against itself but not against the identity-hashed ordered list. The coordinator copy now compares the entire ordered descriptor list (excluding storage paths) with packet identity; all four mutations are rejected. The original worker result is therefore not general tamper coverage. This patch is research-only, pending native integration.
+
+The coordinator also reran five retained-record/restart/crash checks successfully. The public library passes all 137 unit tests and its required build. A new real-PCM mixer regression compares 36,000 sample frames with zero code error after trim and delay. The fresh preview path matches 48 shuffled/reverse frames to retained hashes and restores all three control changes exactly.
+
+Coordinator verification is recorded beside the research artifacts. Its corrected example holds the CTA through the final frame and uses a smaller, top-preserving crop to avoid the original headroom error. Both changes are local edits to the composition, not new generation.
+
+Neither reviewer listened to audio or watched normal-speed playback. Audio alignment is statistical; decoded frames and deterministic seeks do not certify perceptual acting or product fidelity. The take-to-take texture change still needs playback review. The full-film audio has zero measured lag in every audible one-second window (minimum correlation 0.999), including across the cut. AAC decoding includes a small padded tail; its decoded sample count is not treated as a changed picture duration.
+
+## Remaining gaps
+
+- The wrapper is research code: provider reconciliation, billing/idempotency, native UI/import and atomic managed-asset ownership are not implemented by this study.
+- CLI `asset-add` can accept undecodable media. This wrapper probes first, but it does not repair the general importer. Removal/recovery still needs a supported transaction.
+- A SIGKILL can leave decoded frames and orphan browsers. No partially published movie was observed; crash cleanup remains open. Graceful cancellation and uncatchable process death are separate cases.
+- Frozen local references do not constitute a complete host authorization system; races and multi-owner durable import need separate work.
+- The wrapper checks freshness before acquiring the render lock; it is not an atomic staging/ledger/export snapshot across concurrent editors. The recorded gate must not be presented as such.
+- No additional hardware was exercised. No proof that a new provider request would reproduce these retained outputs follows from a successful replay.
+
+## Coordinator failure retained
+
+The first coordinator crop test assumed 60,000 timeline ticks per second rather than reading the actual exported `HZ = 120000`. It produced 133 frames and failed audio alignment against the intended trim. The failed file and script are retained. The corrective script reads the library constant and asserts the requested 266-frame result before accepting it. This was a harness error, not a media-timing defect in the library.
+
+## Final coordinator acceptance in this scope
+
+Both full public-CLI exports passed: 290-frame full film and corrected 266-frame crop/trim, each with two audio tracks mixed. Both have zero measured audio lag; the full film has 0.99938 overall waveform correlation and 0.99985 around the cut. The corrected crop has correlation above 0.99. A fresh product move marks both pickup and dependent handoff stale; undo restores freshness. All four reference-descriptor adversarial cases are rejected after the research-copy fix. The unity-speed PCM regression also fails against the old filter chain, so it detects the original defect.
diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md
new file mode 100644
index 0000000..225f85e
--- /dev/null
+++ b/docs/hybrid-scenes.md
@@ -0,0 +1,307 @@
+# Hybrid scenes: code inside footage
+
+> Latest examples (15 November): a 34-second illustrated 2D story broadens the code-animation route. Real-mesh reflection tests help the laptop deck but fail beside a hollow handle; retain offline rendering for complex transport. No default adopted. [Examples, editability and remaining limits](hybrid-learning-checkpoint-2026-11-15.md).
+
+
+> Import/export reliability: private-copy validation and expected-revision export gates are implemented in the library. Numbered locks and bounded CLI render recovery now pass fresh crash/concurrency tests on this Mac. Automatic recovery sends no signals; native and cross-platform integration remain open. [Evidence and remaining work](hybrid-concurrent-recovery-2026-11-14.md).
+
+
+> Shared human/product light: one continuous track works, but footage correction is experimental. Half-house light plus front direction is not a sufficient acceptance rule. [Evidence and routing boundaries](hybrid-shared-human-light-2026-11-14.md).
+
+
+> Moving-reflection checkpoint: camera/product motion improves screen and emitter placement, but self-reflection and café brightness remain open. [Evidence and limits](hybrid-moving-reflections-2026-11-14.md).
+
+
+## Start here: what we tried, and which tool fits the shot
+
+[](hybrid-experiment-map.html)
+
+**[Open the interactive HTML map](hybrid-experiment-map.html)** · **[Read the full inventory and debate](hybrid-experiment-map.md)**. The HTML file opens locally in a browser; GitHub shows this static infographic and the Markdown evidence. No server or model call is needed.
+
+The map records **41 grouped trial entries in eight areas**, including failed attempts and later repairs. “Worked” means only the stated check or user judgment succeeded. It is not a production-readiness score. Ten remaining research/integration areas are listed separately.
+
+**Current position:** code-authored game-like storytelling is a promising, expandable route. Future LLM capability is a forecast; the preferred Fable fantasy draft is evidence of one short style, not every genre or a general provider ranking. Choose by the shot’s required accuracy, editability and shared action—not simply cartoon versus realistic. Exact graphics and authored worlds favour code; realistic handling trials favour staged joint generation; genuine testimony requires recorded evidence. Independent masks cannot create a shared performance.
+
+The HTML includes simple route illustrations, searchable trial cards, the strongest arguments on both sides, a category map and an illustrative mixed-route advert. This synthesis draws on existing Fable reviews; no fresh Fable endorsement was obtained during its recorded provider-limit window.
+
+---
+
+**Glass follow-up (2026-11-14):** [Verified nested-transparency limits](hybrid-glass-study-2026-11-14.md). The resumed study supports an experimental cylinder-only raster route and a slower Cycles quality candidate for this drink. Submerged ice, general shapes, moving-light response and native integration remain open.
+
+**CLI round trip (2026-11-14):** [Verified replay composition and audio fixes](hybrid-roundtrip-workflow-2026-11-14.md). Live overlays remain editable over retained generated interaction; staging/action changes invalidate dependent takes. Local CLI slice works, native/provider integration remains open.
+
+**Stronger-model follow-up (2026-11-14):** [Matched local model comparison](hybrid-stronger-matting-2026-11-14.md). Neither ResNet50 nor ViTMatte earns hair adoption. Body cleanup is a separate fixed-region experiment; independent alpha and motion acceptance remain open.
+
+**Mask isolation follow-up (2026-11-14):** [Completed independent study and coordinator verification](hybrid-mask-followup-2026-11-14.md). Lossless preparation matters; smoothing is not accurate extraction. A conservative room-aware repair helps this locked shot, but model limits and hand smears remain.
+
+**Mask audit (2026-11-14):** [Same foreground on five backgrounds](hybrid-mask-audit-2026-11-14.md). Dark backgrounds conceal alpha errors; temporal repair trades stability against real edge changes. Keep raw mattes and adjustable repair strength. Both studies subsequently resumed; see the follow-ups above. Neither is production-approved.
+
+**Gap closure checkpoint (2026-11-14):** [Verified subchecks, retained failures and remaining gates](hybrid-gap-closure-2026-11-14.md). The completed Fable film now passes independent seeking/control checks and a three-frame CLI edit/undo specimen. Target-texture warnings and a local recovery prototype add safeguards; tracking geometry, native integration and visual acting remain open.
+
+**Lighting correction (2026-11-14):** [Verified glare/shadow refinement and corrected measurement regions](hybrid-lighting-refinement-2026-11-14.md). Fixed-pose improvements are real; whole-scene realism and moving-product acceptance remain open.
+
+**Cross-style follow-up (2026-11-14):** [Three rendered styles and independent checks](hybrid-story-reuse-2026-11-14.md). The same cast now performs one shared-prop brief in sci-fi, cel-shaded village and toy/clay settings. A [second carry/set-down brief](hybrid-story-second-brief-2026-11-14.md) now demonstrates cast/rig/look reuse in two styles, but requires new choreography and a tray-specific grip. General action reuse remains partial.
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). At that checkpoint the Fable draft was unfinished and failed a random-seek check. The resumed film now passes the scoped runtime checks above; cross-style cast reuse now spans two action briefs, while action generalization and natural contact remain partial. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open.
+
+**Interaction policy (2026-11-13):** realistic avatar/product looking, pointing and physical handling use a reference-conditioned whole-shot generation route. Explicitly authored stylized rigs are a separate route, with their own contact and seek acceptance. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact.
+
+Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services.
+
+**Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented.
+
+A hybrid scene combines two kinds of picture in one shot:
+
+- **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light.
+- **Code**: it supplies what has to be exactly right: the product's shape and label, a price, an interface, a chart, a logo, a caption.
+
+Stacking one on top of the other is easy and already worked. This document covers the harder case, where the two must agree with each other: a hand passes in front of a code-rendered product, a headline sits behind a presenter, a price stays stuck to a moving sign, the product is lit by the room it stands in.
+
+
+
+*The hybrid starter, frames 7 and 34. The plate is a synthetic diagnostic pattern, not footage. The can, its label, the price screen and the headline are code.*
+
+See [prepared foreground and surface artwork](prepared-plates.md) for the implemented receipt, correction, holdout and motion APIs, and their verification limits.
+
+## Goal
+
+Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched.
+
+EditableFrames does not run any model. Mattes, depth maps, tracks and camera paths are **inputs**. You make them with whatever tool you trust and license, and EditableFrames pins them, checks them and draws with them. This keeps the framework model-neutral and keeps export deterministic: the same inputs give the same frames.
+
+## Video creation journeys
+
+Each journey says what the author does, what EditableFrames does, and how far it is proven.
+
+| # | Journey | The author supplies | EditableFrames does | Proven by |
+|---|---|---|---|---|
+| 1 | **A product in a generated place.** A hard-surface product sits in a scene made by a video model and takes on its light. | The plate. | Wraps the plate into an environment, estimates which side the light is on, and lights the product with both. Lighting from the plate is an editable, undoable control. | Integration test: the lit side follows the bright area, the colour follows the plate, toggling it changes only the product. |
+| 2 | **Something in the footage passes in front of the product.** A hand, a person, a pillar. | The plate and a depth map of it. | Writes the plate's depth into the depth buffer, so every mesh is hidden exactly where the footage is nearer. | Integration test: the product is covered by the plate foreground and visible beside it. |
+| 3 | **A headline behind the presenter.** Text or graphics sit between the subject and the background. | The plate and a matte of the subject. | Redraws the matted subject over the DOM layers. | Integration test: no headline pixel survives in front of the subject, and the text continues on both sides. |
+| 4 | **Screen or label replacement.** An exact interface, price or label sits on a surface that moves in the footage. | The plate and a planar track of the surface. | Pins a DOM element to the tracked quad on every frame, including between frames. | Integration test: the element covers the tracked surface edge to edge as it moves. |
+| 5 | **Code first, footage second.** The code scene sets the camera and blocking; a video model paints a world around it; the exact product goes back on top. | A scene that declares control passes. | Exports the scene as clay, depth, normal, object-id and matte passes from the same camera and timing. | Integration test for the passes. Sending them to a video model and compositing the result is outside this repository and unproven here. |
+| 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. |
+| 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. |
+| 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. |
+| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred; resumed film passes same-machine sequential/seek/control checks and a three-frame CLI specimen. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. |
+
+The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found.
+
+## Try it
+
+```sh
+node bin/editableframes.mjs init ./my-hybrid --hybrid
+node bin/editableframes.mjs preview ./my-hybrid
+node bin/editableframes.mjs render ./my-hybrid ./hybrid.mp4
+node bin/editableframes.mjs render ./my-hybrid ./hybrid-blur.mp4 --motion-blur 180
+node bin/editableframes.mjs render ./my-hybrid ./clay --format png --pass clay
+```
+
+The starter generates its own plate, matte, depth map and track with FFmpeg from one set of formulas, so tests can state where every pixel must land. Replace them with your own:
+
+```sh
+node bin/editableframes.mjs asset-add ./my-hybrid shot ./shot.mp4
+node bin/editableframes.mjs asset-add ./my-hybrid shot-matte ./shot-matte.mp4 --role matte --of shot
+node bin/editableframes.mjs asset-add ./my-hybrid shot-depth ./shot-depth.mp4 --role depth --of shot --depth inverse --near 1 --far 20
+node bin/editableframes.mjs asset-add ./my-hybrid shot-track ./shot-track.json --role track --of shot
+node bin/editableframes.mjs rebind ./my-hybrid
+```
+
+## Layers
+
+Back to front, this order is right for most shots:
+
+1. **Plate.**
+2. **Far DOM**: screens pinned to surfaces in the background; text that passes behind the subject.
+3. **Cut-out**: the plate's subject again (plate × matte), which restores it over layer 2.
+4. **3D canvas**, depth-tested against the plate's depth. Depth decides per pixel whether the subject or the object is in front, so the canvas can sit above the cut-out.
+5. **Near DOM**: captions, calls to action, logos.
+
+A scene can draw all five itself, as the starter does. That keeps one clock and one set of inputs. Depth ordering between separate clips is not available: clips stack with a transform and opacity only.
+
+## Plate data
+
+Data computed from a plate is declared in `assets.json` as a **derived** asset. It records the hash of the plate it was computed from:
+
+```json
+"shot-matte": {"src": "assets/…mp4", "type": "video", "sha256": "…",
+ "derived": {"of": "shot", "role": "matte", "sourceSha256": ""}}
+```
+
+`asset-add --role … --of …` writes this for you.
+
+| Role | Type | Meaning |
+|---|---|---|
+| `matte` | video or image | White keeps the subject, black drops it. Luminance is coverage. |
+| `depth` | video or image | Distance from the camera. White is near. Needs an `encoding` (below). |
+| `normals` | video or image | Camera-space normals, `(n + 1) / 2` in RGB. Accepted and pinned; no helper consumes it yet. |
+| `track` | data (JSON) | A planar or point track. See `packages/plate/track.mjs`. |
+| `camera` | data (JSON) | A camera path. See `packages/plate/camera.mjs`. |
+| `environment` | image | An equirectangular picture of the plate's surroundings. Accepted and pinned; the starter does not use one. |
+
+Rules, each refused with a message that says what to do:
+
+- The plate's hash must equal `sourceSha256`. A regenerated take invalidates its derived data.
+- A plate has at most one asset per role.
+- A derived asset cannot derive from another derived asset.
+- A derived video must have exactly as many frames as its plate.
+- A depth asset must carry an encoding. Tracks and camera paths are validated when loaded.
+
+**Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that.
+
+- *Fewer frames at the plate's own rate* means correspondence is incomplete; do not assume the missing frames are all at the end. Verify which source frame each output describes, then recompute/correct missing data or trim the shot to a verified range. Do not hold the tail of a moving matte/depth map to satisfy the frame-count check. Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early.
+- *Another frame rate* has to be resampled onto the plate's frame times.
+- *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing.
+- Check the result against moving edges throughout each crossing. Inspect every decoded frame of short final clips, including full-resolution crossing crops and normal/slow playback. A few matching frames are only a smoke test.
+
+**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale: tuning `near` and `far` can create a plausible ordering in some frames, but does not establish shared geometry or correct hand/face edges. They are not measurements. Prefer an explicit subject holdout for a known foreground crossing.
+
+**Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so.
+
+**Camera path** files are `{version: 1, frameRate, frames: [{frame, position, quaternion, fovY}]}`: camera-to-world, +Y up, looking down −Z, `fovY` in degrees.
+
+## Renderer contract additions
+
+Two optional services join `asset` and `mediaFrame`. Check that they exist before using them.
+
+- `context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, derived}` for a declared asset.
+- `context.derived(id, role)` returns the id of the asset derived from `id` with that role, or `undefined`.
+
+`mediaFrame(id, seconds)` serves matte and depth frames like any other video. `asset(id)` returns a URL for a data asset; fetch it and parse the JSON.
+
+A scene may declare **control passes**:
+
+```js
+defineRenderer({ …, passes: ['clay', 'depth', 'normal', 'id', 'matte'], … })
+```
+
+
+
+*Clay, depth, normal and object-id passes of the starter, exported with `render --pass`.*
+
+The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A host never asks for a pass the scene did not declare, and the CLI refuses one. Pass names are open, like renderer names. `beauty` is implied and cannot be declared.
+
+## Helpers
+
+`editableframes/plate` is pure and renderer-independent:
+
+| Area | Functions |
+|---|---|
+| Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` |
+| Tracks | `validateTrack`, `sampleTrack`, `sampleTrackFrame`, `scalePoints` |
+| Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` |
+| Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` |
+| Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` |
+| Measuring a plate | `plateStats`, `matchLevels`, `applyLevels`, `estimateKeyLight`, `estimateNoise`, `grainAt`, `expandHighlights` |
+| Passes | `idColor`, `idFromColor`, `validatePasses` |
+| Canvas | `drawCutout`, `drawGrain`, `createFrameLoader` |
+| Shutter | `shutterSamples`, `validateShutter` |
+
+`editableframes/three-plate` is an optional Three.js adapter:
+
+| Function | Purpose |
+|---|---|
+| `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. |
+| `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. |
+| `createPlateEnvironment(renderer)` | Lights the scene with the plate. |
+| `paintPlatePanorama(context, source, width)` | The panorama `createPlateEnvironment` builds: the plate in front of the camera, mirrored behind it. |
+| `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. |
+| `applyCameraSample(camera, sample)` | Replays a camera path. |
+| `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. |
+| `renderPass(renderer, scene, camera, pass, options)` | Draws the scene as clay, depth, normal, id or matte. |
+| `dataTexture(image)` | A texture for plate data with no colour management. |
+
+None of this narrows what a renderer may draw. A scene that uses other libraries can read the same assets and implement its own passes.
+
+## What is estimated, and how far to trust it
+
+Three helpers guess from a single view. Expose their results as controls.
+
+- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. Its colour is the brightest area's colour, which can be an object's (blue components read as a blue light) rather than the light's.
+- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`).
+- **Depth `near` and `far`** are yours to tune, as above.
+
+## Frame rate
+
+Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow.
+
+- Anything locked to the footage should move on the footage's frame grid. Use `seconds = clock.mediaTime ?? clock.frame / clock.fps` for footage and its derived data: this clock stays at the output frame during shutter sampling. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames.
+- A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it.
+
+## Export
+
+- `render DIR OUT --pass NAME` renders a declared pass. The receipt records it.
+- `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur.
+- MP4 and MOV keep the values the browser drew: BT.709 matrix, limited range, transfer tagged as sRGB. Footage in a hybrid shot comes out at the levels it went in.
+- An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility.
+
+## Compared with a full compositing checklist
+
+Professional compositing uses more steps than this. Stated plainly:
+
+| Step | Status |
+|---|---|
+| Occlusion by plate geometry | Done, from a depth map. |
+| Subject in front of graphics | Done, from a matte. |
+| Planar tracking and corner pin | Drawing done, for flat surfaces. The track comes from another tool. A surface that bends (curled paper, cloth) needs a mesh warp, which is not provided. |
+| Edge clean-up of the cut-out | Not provided. A matte edge keeps some of the plate's background colour, which shows as a thin fringe over contrasting graphics. |
+| Reflections of the plate in the object | Approximated by `createPlateEnvironment`. |
+| Light direction | Estimated; editable. |
+| Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. |
+| Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. |
+| Motion blur | Done at export, for code layers. |
+| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. The catcher is a plane with no depth: a shadow it catches is also drawn over a real object standing on that plane. |
+| Camera match | Replay only. No solver. |
+| Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. |
+| Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. |
+| Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. |
+
+## On generated footage
+
+The helpers were tried on twelve 5–6 second plates from four video models (Seedance 1 Pro Fast, Kling 2.5 Turbo Pro, Veo 3.1 Fast, Wan 2.2), with mattes and depth maps from hosted models and tracks from a classical planar tracker. Each scene was a renderer scene of the kind the starter shows. This is one trial, not a benchmark.
+
+
+
+*Historical samples, not passing clips. The phone matte collapses during the tap/lift, and the added can has inconsistent hand ordering and does not reskin the original can. Retained to document the experiment; see the corrected verdicts below.*
+
+| Journey | What was found |
+|---|---|
+| Screen or label on a surface | Tracking held the phone within 3 px at 1088 × 1920 while it moved 24 px, but the composite fails: its thumb matte collapses at frames 60–70 of 121. The café menu also fails because no foreground matte protects the person and the footer overflows. A curled sheet missed the planar pin by up to 15 px. |
+| Headline behind a subject | Sampled frames demonstrate the layer effect, with a 1–2 px light fringe at hair. Whole-shot acceptance was not established by those samples. |
+| Footage in front of a 3D object | Fails final quality in the can example: the hand is split across the inserted object. Hand-tuned relative depth does not share its scale/camera, and no mask resolves a hand moving through the volume chosen for the new object. |
+| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. |
+| Placing a 3D object without a camera solve | A tracked stand-in provides an approximate screen anchor, not a metric camera/pose solve. The example adds a second can; it fails the intended original-can reskin. A separate code-first take also exposes a larger generated can beneath the code object: one conditioning still did not preserve geometry. |
+
+Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project.
+
+## On filmed footage
+
+Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-control dolly, one on a tripod) were tried the same way, with a hosted matte and depth map for the third. It is a smaller trial than the one on generated plates.
+
+| Journey | What was found |
+|---|---|
+| Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. |
+| Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. |
+| Headline behind a subject | Fails whole-shot acceptance: while a fast arm enters (up to 460 px per frame), the matte lags by 1–2 frames and the headline shows through it. Its forearm edge is about 10 px wide from 10% to 90%. Other frames demonstrate the layer effect. |
+| Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. |
+
+The same trial found three export defects, all fixed:
+
+- MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included.
+- A scene with no transparency could not be exported to MOV.
+- Footage tagged with BT.709 primaries and transfer, as most camera footage is, was drawn darker than its values before it ever reached the encoder. A board pixel stored as (142, 117, 73) drew as (136, 109, 63).
+
+## Limits
+
+- The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast.
+- A renderer scene has no audio port. Sound from footage inside a scene is not mixed; keep speech on a media-port clip.
+- `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units.
+- Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes.
+- Results differ slightly across GPUs and browsers, as elsewhere in this framework.
+- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. The trials and subsequent failure audit above establish current limitations; all-frame quality gates remain proposed work.
diff --git a/docs/hybrid-shared-human-light-2026-11-14.md b/docs/hybrid-shared-human-light-2026-11-14.md
new file mode 100644
index 0000000..a75277c
--- /dev/null
+++ b/docs/hybrid-shared-human-light-2026-11-14.md
@@ -0,0 +1,50 @@
+# One light track, different kinds of foreground
+
+2026-11-14 · HUMAN1 remains partial · research renderer, no native relighter
+
+A continuous editable light track can coordinate a rendered product, a footage presenter, and an authored counter plane. That does not give these layers equal relighting capability. The 3D product uses geometry and materials; the presenter receives a bounded image correction using estimated depth; the photographed room retains its baked illumination.
+
+## What was actually tested
+
+One retained generated presenter, one 96-frame excerpt at 25 fps, one laptop GLB, and one photographed room on one Mac. No new media generation, downloads or paid calls. The presenter matte is reused unchanged. DPT depth supplies approximate normals; camera, subject depth, ambient share and white balance are authored assumptions. The baked-light fit uses face rows, despite its metadata saying face/neck.
+
+The worker compares untouched footage, a prior colour/exposure match, and a bounded additive correction using the depth proxy. A synthetic bust with known normals supplies a reference for the algorithm. It is not a human-face reference.
+
+| Synthetic bust, front hemisphere | Prior match error | Depth-proxy error |
+|---|---:|---:|
+| Lamp at half house light | 12.9 codes | 6.5 codes |
+| Lamp equal to house light | 24.9 codes | 11.0 codes |
+| Lamp becomes key, house at 30% | 53.1 codes | 20.3 codes |
+
+These worker-reported averages are 8-bit image-code errors on the synthetic control. The reported “share” is error reduction relative to leaving the source unchanged, not the fraction of physically correct illumination or a human realism score. Estimated normals are roughly 19–23 degrees off on synthetic skin and 40 degrees off on curls.
+
+## The operating range is not validated
+
+The worker proposes half-house light in the front hemisphere as a starting range. Coordinator inspection of the saved nonideal-bust grid finds only **3 of 7 front directions** pass the worker's combined criterion (error at most 8 codes and error reduction at least 0.6). Passing angles are -60, +60 and +90 degrees in that experiment. They must not become a universal whitelist.
+
+The human clip named “supported” peaks at approximately 0.78 times the dimmed house light, above the proposed 0.5 starting bound. It is an edge-case demonstration. It is not a validated safe preset. A native guard cannot approve arbitrary footage solely from lamp ratio and direction.
+
+## Visible gains and failures
+
+The milder example warms the lamp-side cheek, neck and hand while dimming the far side. The coordinator inspected the comparison at frame 62. The stronger example at frame 95 has a hard lit patch and an unnatural grey region beside the nose; its baked key remains visible. The worker reports about 9% loss of fine facial contrast in the milder example.
+
+The first track lacked highlight headroom and pushed about 51% of measured head/neck skin pixels above 250. Dimming the room in the final track is an art-direction change, not recovered source detail. No algorithm here restores clipped source information. Hair response remains inadequate; small proxy improvements in some numeric cells do not establish useful hair relighting.
+
+No new presenter shadows, product-to-presenter shadows, hair transmission, or relocated highlights are created. The lamp globe itself is absent from product reflections; only its analytic highlight is present. The counter is a proxy-plane correction over baked pixels. The room photograph responds only to uniform house exposure unless an explicitly authored wash is enabled.
+
+## Verification
+
+The worker reports 284 repeat-seek comparisons, 78 edit/restores, five fresh mounts and a four-frame real CLI history test. A first fresh-mount failure caused by GLB draw order was fixed and retained. The coordinator independently decoded all 13 preview files (96 frames, 25 fps, silent), audited the saved operating-range grid, and checked the CLI success receipt. The coordinator has not rerendered the shader or independently measured the human accuracy. Neither review watched normal-speed playback; there is no target-light reference for this presenter.
+
+## Routing rule for the plan
+
+- Geometry with materials: use an editable renderer and shared light track; validate reflections, shadows and exposure for the shot.
+- Footage with mild lighting changes: retain bounded correction as experimental, with source/proxy provenance, explicit limitations and visual review. Do not advertise general relighting.
+- New key direction, cast shadows, hair glow, moving highlights or lost headroom: use a suitably captured/relightable asset, validated VFX, or a regenerated take. Merely having normals would not solve every material and visibility problem.
+- Performance involving mutual contact or shadows: joint generation is a candidate from the earlier interaction tests, not a result tested in this light experiment. Preserve identity/product review and keep typography/UI live afterward.
+
+The light controls are continuous values, not a finite list of presets. The limitation is how much information each layer contains. Code is not inherently unable to depict the effect; ordinary RGB footage does not identify the geometry, material and lighting uniquely.
+
+## Next resources and work
+
+A real paired-light capture or a relightable subject with independently known passes is needed to score human accuracy. Another presenter and exposure range would test generality. A prepared-pass contract should record pixel ownership, source hashes, frame clock, proxy confidence and baked-light assumptions. Its acceptance policy must distinguish unsupported from unmeasured; a deterministic render is not a quality certificate.
diff --git a/docs/hybrid-story-reuse-2026-11-14.md b/docs/hybrid-story-reuse-2026-11-14.md
new file mode 100644
index 0000000..6f66d58
--- /dev/null
+++ b/docs/hybrid-story-reuse-2026-11-14.md
@@ -0,0 +1,44 @@
+# Reusable cast across three styles — 2026-11-14
+
+> **Second-brief follow-up:** [Carry, turn, set down and release](hybrid-story-second-brief-2026-11-14.md) now tests the cast in two styles on a different action. Cast/rig/look transfer; action, grip and probes needed new code. This first-brief report is retained as the earlier result.
+
+ST2–ST3 advances from quota-blocked to **partial, with rendered evidence**. Three 12.5-second films reuse the original fantasy cast in a sci-fi repair bay, a cel-shaded village and a toy/clay workshop. Each is 1280×720 at 24 fps, with 300 frames, captions and local synthesized voices. No hosted-model calls were made.
+
+## What actually transfers
+
+The baseline character modules are imported by reference. New shared modules provide limb inverse kinematics, foot-planted walking, restyling and an explicit action clock. Each style supplies its own set, camera direction, materials, proportions, prop, light and motion treatment. These are authored source modules, not a new SDK style-generation feature.
+
+The important contact decision is **prop first, hands second**: author one world-space prop trajectory, then solve both characters' hands onto its grip sites. This avoids independent hand/prop animations disagreeing about where the object is. It does not infer arbitrary interactions from a prompt or guarantee collision-free bodies.
+
+| Film | Distinct treatment | Visual limit seen in contact sheets |
+|---|---|---|
+| Sci-fi | Reflective suits, emissive trim, repair bay, smooth motion, side grip on a power cell | Wrist bend and rigid fingers remain obvious; heads tilt steeply toward the prop. |
+| Village | Banded toon shading, ink contours, outdoor sun, stepped poses, overhand basket grip | Table overlaps the exchange in projection; faces are cropped during the contact close-up. |
+| Toy/clay | Shorter legs, larger heads/hands, textured matte surfaces, poses on threes, depth of field, underhand toy cradle | Flat hands read as paddles; workbench overlaps the prop; release is low in frame. **Not accepted as a convincing grasp.** |
+
+The coordinator agrees that sci-fi and village communicate the handoff more clearly. This is contact-sheet inspection, not a normal-speed playback or soundtrack listening review. The three films demonstrate a range of looks on **one action brief**, not general character portability or a production-ready animation system.
+
+## Independently checked delivery
+
+| Check | Coordinator result | Scope |
+|---|---|---|
+| Fresh frame reproduction | 102/102 sampled hashes match the saved sequential renders | Reverse-first and scattered samples, including both cuts and contact transitions; same Mac/browser. |
+| Individual controls | 27/27 declared controls visibly change and restore the sampled frame | One caption test initially selected a speech pause at frame 150. That observation is retained; the corrected sci-fi test at frame 120 passes during visible speech. |
+| Media decode | All 900 frames decode without errors | Three 12.5-second 1280×720/24 fps files; stereo audio duration also 12.5 seconds. No listening claim. |
+| Actual CLI edits | All three style specimens pass | Source frames 30, 120 and 244 per style; exposure edit changes all nine samples, stale proposals are refused, undo restores exact PNG bytes. |
+
+The CLI result extends the worker's renderer-host-only evidence. It does not cover full-film audio export, every control through the CLI, revision migration after source changes, native desktop delivery or another GPU.
+
+## Contact evidence: useful but not independent ground truth
+
+The worker reports no unsupported prop frames, no unreachable limb targets and minimum sampled digit clearances of +0.01, +0.03 and +0.02 mm for sci-fi, village and clay. Reported shared holds last roughly 0.75–0.79 seconds. Earlier retained attempts reported thumb penetration of 21 mm, finger penetration of 19 mm and unreachable walking legs by 24 mm; revised approach paths, closure and pelvis motion remove those reported failures.
+
+These values come from the authored scene and simplified probes. Digit spheres are checked against approximate prop capsules; palms, body intersections and prop-to-set contact are not tested. Zero grip error reads back the solver's own target, so it is not independent proof of contact. The coordinator verified pixels, controls and delivery, not a separate mesh-collision simulation.
+
+The clay film passes the automated checks and still looks wrong. Keep numerical integrity, visible grasp quality and reuse breadth as separate acceptance gates.
+
+## Next decision
+
+Keep ST2–ST3 partial. Before moving these modules into a supported library, exercise a second brief that changes the action structure: turn, carry with two hands, set down, release and look toward the recipient. Require object-to-set and palm contact checks, dedicated grip shapes and wider framing. Preserve failed trials. Continue to treat realistic human/product interactions as a jointly generated shot where appropriate; authored stylized contact is a distinct route with different quality limits.
+
+Audio listening, facial performance, skinning, cloth, large turns, sitting, third actors, broader hardware and full native integration remain open. Camera solve and reconstructed worlds are unchanged by this study.
diff --git a/docs/hybrid-story-second-brief-2026-11-14.md b/docs/hybrid-story-second-brief-2026-11-14.md
new file mode 100644
index 0000000..be86ace
--- /dev/null
+++ b/docs/hybrid-story-second-brief-2026-11-14.md
@@ -0,0 +1,45 @@
+# Second action brief: carry and set down — 2026-11-14
+
+**ST2–ST3 remains partial, with a clearer reuse boundary.** Two new 14-second films use the same cast in sci-fi and toy/clay settings. The character lifts a tray with both hands, turns 90 degrees, walks to a table, lowers the tray, releases it and looks toward the other actor. Both films are 1280×720, 24 fps, with 336 frames and local synthesized dialogue. No paid model calls were used.
+
+## What this changes in the plan
+
+The characters, limb solver, restyling, proportions, gaze tools, render pipelines and typography transferred without changes. **The action did not.** The second brief required a new 23.7 KB choreography module, a tray-specific grip and new contact probes; each style also needed roughly 10 KB of prop/set/camera source. A copied walking module needed a change to start from rest.
+
+This supports reusable **cast, rig and look modules**, plus authored per-shot action code. It does not establish a general action library that accepts arbitrary “pick up” or “set down” instructions. Do not report source imports as proof that the first brief's action machinery was reused: the old story module appears in the import graph but does not execute here.
+
+The new clay grip is clearer in close-up, but this is **not a same-prop repair**. The earlier rocket is replaced by a tray with a rim and runners that leave space for the fingers. The new hand clamps the end wall, hooks fingers underneath and puts its thumb over the rim. The tray rests before the thumb lifts and fingers slide out. A plain box flush on a table cannot be released with this geometry.
+
+## Evidence and independent checks
+
+| Check | Sci-fi | Clay | Meaning |
+|---|---:|---:|---|
+| Coordinator fresh frame samples | 40/40 | 40/40 | Saved sequential hashes reproduced across cuts and contact transitions. |
+| Individual controls, changed then restored | 10/10 | 10/10 | Same Mac/browser; visible-frame tests. |
+| Fully decoded video | 336 frames / 14 s | 336 frames / 14 s | Stereo audio also spans 14 s; no listening review. |
+| Fresh geometry-probe replay | 336 match | 336 match | Node recomputation matches browser probe records; uses the worker's scene/probe implementation. |
+| First table contact / last both-hands hold | 215 / 223 | 216 / 224 | The authored release follows measured table contact. |
+| Unsupported frames under declared mesh rules | 0 | 0 | Geometric support classification, not forces or balance. |
+| Minimum sampled hand/table clearance | 5.34 mm | 6.81 mm | Fingers have room under the tray ends. |
+
+The coordinator also deliberately perturbed the actual settled tray in each scene. Lifting it 20 mm produces a roughly +20 mm runner gap; sinking it 20 mm produces −20 mm; moving it off the table produces zero supporting ray hits. The original poses have full runner-vertex support. These six fault cases and two resting baselines show that the table check can detect these errors; they do not validate all contact configurations.
+
+The worker separately exercised real CLI exposure and contact-zoom edits on four sampled frames per style, stale revision refusal, two undos and two redos. Its receipts report exact pixel restoration. That CLI run was inspected, not rerun by the coordinator. It covers two controls on sampled frames, not full-film/audio export or the native app.
+
+## Better probes, still bounded
+
+The earlier grip check read the solver's own targets. The new contact checks use actual geometry: rays from runner underside vertices to table triangles, and sampled hand surfaces against bounding boxes derived from tray vertices. The coordinator verified that the tray-part transforms in the delivered poses are unit scale, so the reported local-distance units are applicable there.
+
+Sampling can miss crossings between samples. Clay's lumpy meshes lie inside their boxes; its runner surface varies by about 1.83 mm. The tests do not model friction, force, character balance, hand-to-hand contact or hand-to-body contact. The worker's zero target-readback error remains explicitly excluded from contact acceptance.
+
+The retained failed pass matters: the first clay stand was too narrow, leaving runner vertices unsupported by about 4.7 mm at each end, despite passing seek tests. A separate geometry check caught it. Another correction raised the tray about 1.3 mm to avoid sinking into the lumpy table. Failed output and records remain retained.
+
+## Visual decision
+
+Close inspection shows a thumb over the rim and fingers under the edge, with no workbench visually behind the airborne tray. Those contact-zoom views are new camera renders of the same state, **not frames from the delivered film**. In the film each hand is only about 40–50 pixels high, so finger contact is harder to judge. Wrist bends, uniformly hooked fingers, rigid limbs, painted faces and limited downward gaze remain visible limitations.
+
+The coordinator inspected comparison sheets and source, not normal-speed motion or audio. The new action is more explicit, but keep natural performance and film-scale grip readability partial. The second actor does not share the load; two-person contact is not tested by this brief. Village, sitting, arbitrary props and additional hardware remain untested.
+
+## Next engineering boundary
+
+Separate reusable cast/rig/look from per-shot choreography, grip-specific geometry and validation. Require both a geometric contact check that responds to deliberately bad placements and an actual-film visual check. Avoid making props convenient for the solver without disclosing that constraint. Keep realistic interaction generation and authored stylized animation as separate production routes; this study does not replace either with a universal interaction solver.
diff --git a/docs/hybrid-stronger-matting-2026-11-14.md b/docs/hybrid-stronger-matting-2026-11-14.md
new file mode 100644
index 0000000..0dedeab
--- /dev/null
+++ b/docs/hybrid-stronger-matting-2026-11-14.md
@@ -0,0 +1,57 @@
+# Stronger local matting: no replacement earned
+
+2026-11-14 · MASK1 remains partial · no paid calls · research only
+
+RVM ResNet50 and ViTMatte-S were tested on the retained generated presenter. Neither earns adoption as the hair matte. MobileNetV3 plus the conservative room-aware `clear_gated3` repair remains the preferred candidate for this shot, not a production-approved general solution. Larger models can remove unwanted background while also removing real-looking curls.
+
+## What was tested
+
+One 96-frame, 3.84-second excerpt at 1280×720, with lossless decoding and 88 frames of recurrent warm-up. ResNet50 used resolution ratios 1.0 and 0.5; ViTMatte-S used narrow and wide trimaps derived from MobileNet. The same room-aware repair was applied to new candidates. A second generation of the same fictional presenter is a distinct clip, not independent real-camera or different-hair evidence. No real hair alpha is annotated.
+
+| Head-region proxy | MobileNet + repair | ResNet50 r1.0 + repair |
+|---|---:|---:|
+| Room-like opacity (lower preferred) | 45.8 | 28.8 |
+| Missing-opacity bound (lower preferred) | 0.15 | 0.45 |
+| Thin-structure energy (descriptor, not accuracy) | 336 | 191 |
+
+These are model-assisted proxies. A pixel resembling the room does not prove hair is absent. The alternative reference built where neither network sees a subject is a useful sensitivity check, not an unbiased reference. ViTMatte cleans the concrete-side haze but softens the low-contrast curls against wood. No candidate improves both principal proxies over the current candidate.
+
+## Why the synthetic ranking cannot select a model
+
+The coordinator independently recomputed the white-background RGB error over all 96 frames using the saved alpha and foreground arrays, without the worker's scoring function:
+
+| Constructed alpha source | MobileNet error | ResNet50 error |
+|---|---:|---:|
+| MobileNet-derived truth | 23.7510 | 24.6416 |
+| ResNet-derived truth | 19.6987 | 18.9538 |
+
+The ranking reverses. Both synthetic clips have sharper, easier boundaries derived from this same source footage. Use them to expose tradeoffs, not to claim which model extracts real curls best. Numbers use the experiment's encoded-sRGB composite convention and are not interchangeable with the earlier linear-light audit.
+
+## Body cleanup is a separate candidate
+
+Brightened source frames reveal a chair in much of the previously described hand-shadow smear. ResNet50 removes more of those chair fragments. The delivered hybrid keeps MobileNet + repair around the head and ResNet50 on the body. It is an inspectable experiment, not an adopted model setting.
+
+The head region is fixed at pixels (440, 0)–(850, 330), with a 12 px alpha blend at its sides and lower boundary. Foreground RGB switches at the blend midpoint rather than blending continuously. Moving heads, colour seams, hair outside the region, and normal-speed playback remain unvalidated. Do not generalize this crop into automatic subject routing or claim it solves contact/interaction masking.
+
+## Coordinator verification
+
+- 36 fresh renderer samples across four cases match the worker's saved frame hashes exactly.
+- All 13 control changes alter the picture and restore it exactly; a fresh mount matches, with no browser errors.
+- Independent synthetic error recomputation matches all four reported values exactly.
+- Saved CPU/MPS alpha comparisons were independently rechecked: maximum difference is one alpha code for MobileNet, ResNet50 and narrow ViTMatte. These are comparisons of saved inference outputs, not new inference runs.
+- All 12 comparison MP4s fully decode with no errors.
+- Selected full-frame and hair-crop stills were inspected. Neither reviewer watched normal-speed playback or listened to audio; the delivered comparisons are silent. This is standalone renderer verification on one Mac, not native-app/exporter verification.
+
+## Performance and distribution boundary
+
+Worker single-run inference measurements on this Mac: MobileNet 0.46 s/frame CPU and 0.050 s/frame MPS; ResNet50 0.69 and 0.129; ViTMatte including its guide 1.15 and 0.27. These exclude the complete compositing/export pipeline and do not establish performance on ordinary PCs.
+
+The retained provenance records identify RVM as GPL-3.0, and ViTMatte's model card as Apache-2.0 with MIT code; training-data terms still need review before distribution. RVM's published runtime instructions do not document MPS; it was experimentally exercised here. No weights or model runtime are added to the library by this update.
+
+The worker downloaded about 227 MB and retained about 3,008 MiB of evidence. One initial library call wrote a one-byte Hugging Face cache version marker outside the study directory; later calls confined caches to the study. Nothing was deleted.
+
+## Next acceptance gate
+
+Obtain consented real footage with a known backing or annotated alpha on representative frames, including different hair and a moving camera/background. Compare lost detail, false opacity, temporal lag and normal-speed replacement-room playback together. The present bottleneck is independent evidence, not inference speed. A subject-memory video matting model is an untested future candidate requiring runtime and distribution review; downloading another model alone would not close MASK1.
+
+The dashboard retains the larger-model failures, fine-curl and haze crops, chair cleanup, fixed-region hybrid, full-frame comparisons, source, model provenance and both verification records. No whole research item is closed by this study.
diff --git a/docs/interaction-staging-workflow.md b/docs/interaction-staging-workflow.md
new file mode 100644
index 0000000..5b0e8f1
--- /dev/null
+++ b/docs/interaction-staging-workflow.md
@@ -0,0 +1,48 @@
+# Stage the scene, then generate the interaction
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration.
+
+## The boundary
+
+Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion.
+
+For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; a two-person transfer now has one local demonstration, while animal and object-collision shots remain untested and broader multi-person reliability remains unvalidated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction.
+
+## Author and agent workflow
+
+1. **Stage:** place subjects, products, support surfaces and background; set scale, orientation, camera, eyelines and initial lighting. Humans and agents edit the same saved scene. Use plausible resting poses and reachable objects. Blocking proxies describe placement, not final appearance or solved anatomy.
+2. **Approve and freeze:** choose the source frame and shot camera, commit the intended scene revision, and capture a clean snapshot without selection outlines, gizmos or editor chrome. Save the editable scene alongside it. Re-check support, reach and framing before spending on generation.
+3. **Package the scene set:** include that snapshot plus separate subject identity, product detail/multi-angle and background references as available. Label each reference's purpose and preserve their order. Record scene/source revision, frame/time base, camera, output dimensions, assets and hashes, reference rights/provenance, desired action beats and acceptance criteria. Retain the actual submitted bytes and prompt, not merely expiring URLs.
+4. **Generate during preparation:** select a model such as Kling using the chosen endpoint's actual capabilities. Prefer a start-frame/keyframe input for composition and separate reference inputs for appearance when the endpoint supports both together. An ordinary reference image is a softer hint; do not label it a locked first frame. Verify combinations, reference numbering, duration and cost before submitting. If the endpoint cannot accept the scene set, choose a compatible route or disclose the limitation rather than silently dropping a reference. An accepted video can instead be the base for a video-edit request.
+5. **Review the whole interaction:** inspect normal/slow playback and every contact transition for gaze, reachable grip, support/release, hand/limb anatomy, collisions, identity, product geometry/branding, shadows and reflections. Judge positional instruction following separately from overall appearance. A snapshot conditions the result; it does not constrain a solver or guarantee exact placement.
+6. **Return to composition:** import an accepted take as a versioned footage asset, probe actual decoded frames/timestamps, then derive masks/tracks from those exact bytes where needed. Keep typography, prices, captions and suitable surface inserts independently editable. Screen-space UI does not inherit physical subject holdouts. Keep the staged scene so another layout can produce another snapshot/take.
+
+Generate the interacting subjects and shared support/room as one shot by default: it gives the model a common lighting and contact context. Foreground-only generation is a separately tested option when alpha, edge colors, contact shadows and background correspondence are actually available. It is not a general solution for changing a room after a pickup.
+
+## What exists and what remains
+
+The standalone Scene Studio example already exposes placement, camera/light controls, saved scene state and **Save reference PNG** from a frozen committed shot. It is an opt-in example, not proof of a universal editor/agent capture API or a native host integration. The scene-set manifest, automatic provider packaging, generation handoff, receipt binding and accepted-take import still need host integration and end-to-end tests. No implicit model call belongs in `render(clock)` and no mandatory vendor dependency is added to the core.
+
+Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags.
+
+## Earlier experiments and conclusions (before the staged trial)
+
+The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support.
+
+The first reference-conditioned Kling take used separate presenter, product and room images. Attention improved, but the headphones stayed upright despite a side-resting instruction. The follow-up used **that accepted-looking video as the base plus the official single-view product photo**, not a newly staged scene snapshot. It produced a clearer headband grip, lift and supported two-hand hold; the user preferred it. The requested camera-left shift was not meaningfully achieved, and the weighing motion read mainly as pickup-and-hold. The upright start remained. Thus the pickup result supports joint generation; it does **not** complete the snapshot-plus-references test, establish exact product fidelity or validate other interaction categories.
+
+The follow-up decoded to 1280×720, 121 frames at 24 fps (5.0417 s). Its EditableFrames round trip retained the frame count, repeated a randomly sought frame identically in the tested browser, and preserved source pixels outside the title before encoding. Title/eyebrow/accent/visibility remained editable. Those are renderer-integrity checks, not proof of physical realism. Contact crops covered all frames and full-scene samples were inspected; no fresh independent reviewer approval is claimed.
+
+At the recorded provider rate, the successful video edit was estimated at about $0.95; the account ledger charge was not retrieved. One earlier upload-URL attempt failed validation and is retained separately. A direct original MP4 output URL, verified against the local source hash, resolved the transport issue. The provider returned a 10.084-second duration metric for a 5.0417-second file, consistent with input-plus-output billing; decoded timestamps must own the timeline.
+
+## Editability and evidence retention
+
+After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects.
+
+Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category, repeat the snapshot handoff and validate native host integration before broad quality claims.
diff --git a/docs/lighting.md b/docs/lighting.md
index 97f5f0d..4d9f694 100644
--- a/docs/lighting.md
+++ b/docs/lighting.md
@@ -27,3 +27,19 @@ For generated geometry, use `createDeviceMaterial` on every chassis, and use sep
The website exposes **Body finish** and **Reflection angle** through its normal editable schema and undo/redo. The library viewer's **Satin aluminium bodies** toggle is saved with its existing appearance history. Screen content uses a separate unlit material so exposure does not alter interface colors. Look profiles record device, camera, HDR identity and material policy.
Lighting cannot recover missing geometry or separate parts merged in the source model. These are fan-made models with varying fidelity, not calibrated scans. New renderers may use other lighting and materials without changing the core document.
+
+## Photographs versus models
+
+A real product can enter a scene two ways, and they light differently. A trial on 2026-11-12 used official photographs of four products and third-party models of three.
+
+| Route | Can | Cannot |
+|---|---|---|
+| Product photograph on an alpha plane | Keep the exact logo, controls and proportions; take restrained colour and exposure matching from the scene | Respond to a moving light. Its highlights and shadows are baked in and turn with the image, and it has no unseen sides. |
+| 3D model | Respond to moving lights and environment: at a fixed pose, moving the lights changed a neutral patch from about 106 to 193 RGB | Look better than its materials. Two phone models read flat beside product photography and were unsuitable for close-ups. |
+
+Name the operation the scene performs: on a photograph it is colour matching, not relighting. Keep a device's display out of the grade applied to its case. Downsample a large photograph explicitly before drawing it small; a fine grille aliased until it was downsampled in steps, which cut its error against a Lanczos reference by 58%. When a metal model washes out, check the environment before the lights: in the trial the pale plateau came from environment strength, and 0.8 → 0.2 restored the surface. Moving, correct highlights on a product only available as photographs need CAD with material maps, a photogrammetry capture, or photographs taken under several lights.
+
+## Checking overlap between moving products
+
+Two copies of each product in one scene, one turning and one orbiting behind and in front of it, were checked with separate object-id passes (A only, B only, both) at 35 crossing poses: no wrong foreground assignment over 353,771 interior pixels, antialiased edges excluded. Axis-aligned bounding boxes flagged 36 collisions between the two laptops that a rotation-invariant footprint showed were at least 0.44 scene units apart. Use a tight bound before reporting a collision. The photographed products rotated only in the image plane, with their baked highlights turning too; draw order cannot repair that. Reflections of one copy in the other, bounce light and area-light shadows were not simulated.
+
diff --git a/docs/media/README.md b/docs/media/README.md
index fbb3a30..9a3b0b6 100644
--- a/docs/media/README.md
+++ b/docs/media/README.md
@@ -7,3 +7,7 @@ Actions are actual UI interactions: raise Tower height from 1 to 1.4, set Trees
The recording uses the standalone film study, whose edits can be saved by downloading a project snapshot. Disk-backed project previews additionally persist edits immediately. This GIF does not demonstrate a hosted account, a remote agent session or an export.
Gallery thumbnails elsewhere in the README are existing renders from `apps/films/previews`, `apps/effects/previews` and `assets/devices/previews`. No private posts or third-party screenshots are included. Device credits are in `assets/devices/ATTRIBUTIONS.txt`.
+
+`hybrid-starter.png` and `hybrid-passes.png` are frames of the `init --hybrid` starter rendered by the CLI: frames 7 and 34 of the picture, and the clay, depth, normal and object-id passes of frame 1 over a dark backdrop. The plate in them is a synthetic diagnostic pattern generated by FFmpeg, not footage.
+
+`hybrid-generated-plates.jpg` shows four frames of two hybrid scenes rendered by the CLI over generated footage. The plates were made for this repository with Seedance 1 Pro Fast (the hand and phone) and Kling 2.5 Turbo Pro (the desk, the plain can and the arm) from start images made with Seedream 4. The app screen, its text, the labelled can and the price tag are code. The people in them are generated; no real person is shown.
diff --git a/docs/media/hybrid-experiment-map.svg b/docs/media/hybrid-experiment-map.svg
new file mode 100644
index 0000000..7a99973
--- /dev/null
+++ b/docs/media/hybrid-experiment-map.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/media/hybrid-generated-plates.jpg b/docs/media/hybrid-generated-plates.jpg
new file mode 100644
index 0000000..7f06f0c
Binary files /dev/null and b/docs/media/hybrid-generated-plates.jpg differ
diff --git a/docs/media/hybrid-passes.png b/docs/media/hybrid-passes.png
new file mode 100644
index 0000000..f386319
Binary files /dev/null and b/docs/media/hybrid-passes.png differ
diff --git a/docs/media/hybrid-starter.png b/docs/media/hybrid-starter.png
new file mode 100644
index 0000000..fd59ccc
Binary files /dev/null and b/docs/media/hybrid-starter.png differ
diff --git a/docs/prepared-plates.md b/docs/prepared-plates.md
new file mode 100644
index 0000000..4ea0ab2
--- /dev/null
+++ b/docs/prepared-plates.md
@@ -0,0 +1,51 @@
+# Prepared foreground and surface artwork
+
+The plate utilities now include versioned analysis receipts, explicit source-frame sampling, foreground holdouts, source-space corrections, cylinder/mesh artwork mapping and deterministic kinetic text. These are rendering and authoring primitives. Real footage still requires a reviewed subject mask and surface track; model success does not certify either.
+
+## Frozen analysis
+
+`validatePreparedAnalysis(receipt, sourceInfo)` checks source content identity, decoded raster, rational frame rate, presentation times, correspondence, mask identity, correction revision and preparation provenance. A receipt has `version:1`, `kind:"prepared-plate"`, `source`, `alpha`, `subject`, `revision`, `provenance` and one entry per source frame in `frames`. Each entry contains `sourceFrame`, `maskFrame`, `valid`, `reviewed` and optional diagnostic `issues`.
+
+`preparedFrame(receipt, seconds, {start, startFrame, speed})` maps explicit clip time to a source frame, including trim and reverse. `start` is a time in seconds; an optional integer `startFrame` instead anchors the trim to that frame's actual presentation time. Use `sampleTrackFrame(track, sample.sourceFrame)` to sample matching geometry without converting quantized timestamps back through nominal fps. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame.
+
+Import a receipt as a data asset with `--role analysis --of plate`, and its explicit-alpha media with `--role alpha --of plate`. `--subject ID` distinguishes derived assets for multiple subjects. `derived(plate, role, subject)` resolves that subject; the original two-argument form still resolves an unqualified role. The CLI verifies content hashes, while media preparation checks the receipt against the actual decoded plate and mask.
+
+The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index. A derived still mask retains its own single frame throughout the video.
+
+## Foreground and corrections
+
+`createForegroundHoldout({root,width,height})` creates a child `root` for the affected code layers. Call `update(decodedMask,{channel,frame,...})` before capturing. `channel` is `alpha` or `luminance`; missing or wrong-sized masks throw. An uncorrected explicit-alpha image uses CSS GPU masking where supported. Luminance masks and live corrections use the CPU fallback. No model runs inside the renderer.
+
+Correction books bind `sourceSha256`, `subject` and increasing frame keys. Each key has polygons with `operation:"add"|"subtract"|"replace"` and source-raster `points`. `interpolation:"linear"` propagates only between matching polygon keys; it never extrapolates beyond them. `createMaskCorrectionSession` turns renderer gestures into immutable book proposals. The host applies revision checks and Undo. Re-prepare and review the corrected result before final export.
+
+`analyzeMask` reports coverage, bounds and collapse flags without deleting components. `foregroundLeakage` measures changed pixels inside an annotated opaque foreground. `diagnosticMask()` exposes the current subject coverage as a green overlay for a source/mask review view. These diagnostics flag work to review; they do not infer ground truth.
+
+## Surface mapping and motion
+
+`cylinderMesh` maps a label to an authored/tracked projected body quad. It preserves that body's screen bounds; the seam is an author control when a blank cylinder makes rotation unobservable. `sampleSurface` accepts externally tracked deforming UV meshes. `drawSurfaceArtwork` rasterizes UV triangles without translucent clip seams. `relightArtwork` preserves observed shading under a specified neutral-albedo assumption. Arbitrary old printing requires a separate clean albedo/shading estimate.
+
+The [surface example](../examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background.
+
+`createKineticText` and `typeMotion` provide staggered rise, wipe, spring-like settle, orbit and CSS extrusion treatments. Timing, text, stagger, easing treatment and displacement are explicit inputs; random/reverse seeks reproduce the same state. Character splitting uses grapheme clusters where available. Font readiness and surface safe-area checks remain part of layout acceptance.
+
+## Verification and limits
+
+`npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage.
+
+The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement.
+
+## Exact geometry with a generated environment
+
+The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact foreground cylinder or optional imported GLB in code, over a clean background asset named `world`. A native host can bind `world` and supply verified `worldInfo` (width, height, frames, rational frameRate). The scene adds an authored contact shadow, plate-derived reflection approximation, control passes and an analytic orbit title. The background must have no original foreground object; this avoids a mismatched generated silhouette behind the exact object. It does not solve a camera or prove that a video model consumed 3D control passes. Imported photo geometry/material fidelity is a separate acceptance task.
+
+`surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface.
+
+The code-first scene applies `label` and `model` changes on each render. Live edits and Undo produce the same product as a fresh capture instance; switching models releases the previous geometry, materials and textures.
+
+## Retained generated-footage QA (2026-11-11)
+
+The new primitives were exercised on complete short clips, keeping the original failed renders separately. Reviewed source/mask contact sheets and every output event crop covered 121 frames each for a café board, close-up phone, opaque board card and original-can reskin; the exact-geometry scene covered 81 frames. The board footer was moved inside its safe area, the phone subject mask was replaced after collapse, and the label was fit to the original neutral can body. These shots work with reviewed inputs and manual surface/material tuning. They do not establish automatic segmentation or camera solving.
+
+Before video encoding, each of the four foreground composites preserved every tested opaque interior pixel: alpha at least 254/255, eroded by two source pixels, with at most one RGB code-value tolerance. This is a scoped leakage check against the supplied reviewed mask, not annotated boundary accuracy or fractional-hair color validation. All 81 exact-geometry control mattes were byte-identical; the generated background contained no product to mismatch. The label stayed on the original can and retained its rims/contact shadow. That shot's hand did not cross the original left can, so it is not a can-crossing stress test.
+
+The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 133 unit tests plus real-pixel prepared alpha/luminance capture, rejection of missing foregrounds, live label/GLB edit parity and quantized final-frame reskin rendering. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work.
diff --git a/docs/renderer-contract.md b/docs/renderer-contract.md
index c463e9a..343a4bf 100644
--- a/docs/renderer-contract.md
+++ b/docs/renderer-contract.md
@@ -72,6 +72,13 @@ SVG and WebGL descendants. PNG and ProRes preserve alpha; MP4 flattens over the
requested background. `window.editableframes.captureTarget` describes the capture
selector for browser harnesses. `png()` remains the legacy Canvas-only shortcut.
This is trusted local browser execution, not isolation from malicious authored code.
+The CLI normally uses Playwright's managed Chromium. To use an already installed,
+compatible Chromium explicitly, set `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` to its
+absolute executable path. `doctor` checks that configured file; `render` verifies
+it can actually launch. This opt-in does not download a browser or silently fall
+back. Record the browser version with visual evidence; cross-version pixel
+identity is not promised.
+
For WebGL, retain the rendered drawing buffer for capture (for example,
`preserveDrawingBuffer: true`) and await required GPU work.
Cross-browser/GPU/font pixel identity is not promised.
@@ -125,10 +132,26 @@ returns a URL for a pinned manifest ID. `context.mediaFrame(id, sourceSeconds)`
available with prepared media and returns a PTS-selected frame URL or undefined.
Load/decode that image before finishing the render; this API does not return a
borrowed Canvas. The CLI supports image/video/audio manifests; its default renderer
-path does not mix arbitrary DOM audio automatically. Legacy media-port audio keeps
-its existing mixing path. `captureSurface` is absent in this host. Feature-check
+path does not mix arbitrary DOM audio automatically. Explicit static `scene.media` ports use
+the same mixing path as legacy media ports. `captureSurface` is absent in this host. Feature-check
optional services; do not invent layer, depth, simulation or screen services.
+`context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate,
+derived}` for a declared asset. `context.derived(id, role)` returns the ID of the
+asset computed from `id` with that role (`matte`, `depth`, `normals`, `track`,
+`camera`, `environment`), or undefined. Both exist only when the project declares
+media. A `data` asset is JSON: fetch `asset(id)` and parse it. See
+[hybrid scenes](hybrid-scenes.md) for compositing code with footage.
+
+## Optional control passes
+
+A scene may declare `passes: ['clay', 'depth', …]`: other ways it can draw
+itself, for conditioning a video model or compositing elsewhere. Names are open
+lowercase identifiers; `beauty` is implied and cannot be declared. The host
+supplies `clock.pass`, which is `'beauty'` unless a pass was requested, and never
+requests a pass the scene did not declare. `render DIR OUT --pass NAME` exports
+one. Draw nothing but the pass: hide footage and DOM layers.
+
When exposing controls for separate components, use distinct stable semantic
anchors and matching properties. Connect controlled DOM nodes to those IDs, or
implement Canvas/WebGL picking against the current rendered geometry and props.
@@ -161,3 +184,34 @@ These tests do not establish a native application's integration or agent reliabi
For optional object parents, locked/hidden policy and bounded direct-manipulation
proposals, read [the interaction contract](interaction-contract.md). The renderer
hook returns sparse control values; a host owns one atomic commit and cancellation.
+
+### Footage during shutter sampling
+
+`clock.mediaTime` is source seconds at the output frame's time, after the clip's
+trim and playback rate. Without a shutter it equals `clock.frame / clock.fps`.
+During motion blur, `clock.frame` advances through the shutter samples while
+`clock.mediaTime` stays fixed. Use `clock.mediaTime ?? clock.frame / clock.fps`
+for footage, mattes, depth and tracks attached to it; use `clock.frame` for code
+animation. `mediaFrame(id, seconds)` still honors the exact time requested, so
+custom scenes must choose the appropriate clock. Legacy renderers receive
+`mediaTime` alongside `time`; pass `mediaTime` to `host.portFrame` for footage.
+The media starter uses this clock too; authored media offsets remain explicit.
+
+### Static audio on portable renderer scenes
+
+A `defineRenderer` descriptor may declare `media` ports just like a template:
+
+```js
+media: {
+ firstTake: {asset: 'pickup', offset: 0, end: 'transparent'},
+ secondTake: {asset: 'handoff', offset: 121 / 24, end: 'transparent'},
+}
+```
+
+The editing adapter preserves this declaration for the existing audio scheduler.
+Audio follows clip trim, playback rate and port offsets; pictures must still sample
+those sources explicitly. At unchanged speed, the mixer uses a passthrough filter
+instead of time-stretching. This does not imply dynamic audio automation, arbitrary
+renderer-prop bindings, or sample-identical AAC encoding. Source/runtime changes
+still require an explicit project rebind. `npm run test:audio` exercises PCM trim,
+delay and 1× sample alignment through the real mixer and requires FFmpeg.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 6184942..4b6dd4b 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -6,7 +6,7 @@ The implemented beta contract and verification commands are in [beta.md](beta.md
2. Streaming demux/decode with bounded on-disk caches, hardware backends, performance benchmarks and native webview parity.
3. Audio automation, exact browser audio scheduling, mastering/loudness and additional export containers/deliverables.
4. Explicit source/schema migration maps, restoring historic dependency graphs, incremental timeline state and large-project benchmarks.
-5. DOM capture and additional output adapters, general depth/layer/mask/simulation services, measured EffectCraft/WASM bridges.
+5. DOM capture and additional output adapters, depth ordering between clips and general layer/simulation services, measured EffectCraft/WASM bridges. For [hybrid scenes](hybrid-scenes.md): depth of field and lens matching, light wrap, linear-light compositing, shadows and reflections cast onto footage, and a real-footage acceptance set.
6. Unify device looks and more film/effect studies as generic project adapters; finish per-model screen calibration.
7. Promote research labs for maps, fashion, avatars and other genres using the same media/adapter/credit contracts.
8. Validate live agent-host installation and evaluate MCP packaging; publish an actual repository/release and asset-pack URLs when requested.
diff --git a/docs/staged-generation-results-2026-11-13.md b/docs/staged-generation-results-2026-11-13.md
new file mode 100644
index 0000000..a93e190
--- /dev/null
+++ b/docs/staged-generation-results-2026-11-13.md
@@ -0,0 +1,46 @@
+# Staged generation tests — 2026-11-13
+
+**User visual acceptance (2026-11-13):** the user says the full-pickup and two-person handoff outputs look good. Treat these takes as accepted demonstrations of the staged joint-generation direction and proceed with the planned host workflow. This does not certify exact product fidelity, requested heft, repeatability, all-frame anatomy or native delivery, and is not a new independent Fable review. The original measurements below remain unchanged. [Combined conclusions and the separate authored-story experiment](code-generated-story-results-2026-11-13.md).
+
+Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval.
+
+## Test A: authored snapshot → pickup
+
+The editable reference scene places the real product photograph on the camera-left table using exposed position, scale, image-plane rotation and approximate foreshortening controls. Its background and fictional presenter come from a retained image. This is a 2D blocking composition: it does not establish physical resting geometry, a camera solve or measured lighting.
+
+The captured 1280×720 snapshot was submitted as `start_image`; separate product-detail and presenter images followed in that order as `@image_2` and `@image_3`. Thus this trial really exercises first-frame plus separate references, unlike the previous video-edit trial. The exact prompt asks for look → grip → lift → supporting palm → gentle heft/hold in five seconds, with a fixed camera and the original starting position.
+
+Prediction `nj6k9wyeenrmt0d1tjwr4cqc8m`, `kwaivgi/kling-v4.0`, image-input route. Processing took 111.34 s. Decoded output: 1280×720, 121 frames, 24 fps, 5.041667 s; audio present. SHA256: `10276551f3efb9d2dfbc4831baf054173475c271ffb575f0d667366ffc056afb`.
+
+**Observed:** the camera-left resting start is retained. A product-and-table image patch matches at zero whole-pixel translation, normalized correlation 0.99398; mean absolute RGB differences are 3.91/255 over the frame and 3.85/255 over the product region. This measures opening-frame placement, not exact product shape or a physically constrained trajectory. The woman looks down, reaches, closes on the headband, rotates/lifts the single pair, brings the other hand below it, then shifts to a supported display. The requested heft reads mainly as pickup and hold. All 121 contact crops and 15 full-scene samples were inspected. No conspicuous duplicate product or gross hand-through-earcup event was found in that inspection; fine anatomy, text fidelity, exact geometry and normal/slow playback acceptance are not certified.
+
+The accepted-for-inspection take was imported into an EditableFrames renderer with separate title/eyebrow/accent/visibility controls. Export retains 121 frames at 24 fps. Repeat frame 48 has zero maximum RGB difference; source pixels outside typography are unchanged before encoding; a title-control edit changes 15,118 pixels; no page errors. Generated hands, product motion, physical light and room pixels remain baked.
+
+**Verdict: works with manual staging for this pickup.** This advances the local snapshot handoff from untested to one demonstrated case. It is not exact-object advertising approval, universal first-frame compliance, multi-angle validation or native host delivery.
+
+## Test B: two-person handoff
+
+The final decoded frame of Test A is the start image; product and presenter references remain separate. The second adult is specified in text, not supplied as an identity reference or pre-staged actor. The seven-second prompt requires entry → receiver grip/support → giver releases both hands → receiver alone holds. This is a living-thing–living-thing–object test, not an object–object collision test.
+
+Prediction `7dz5cxr6mdrmt0d1tjz9eahxg0`, same image-input route. Processing took 100.33 s. Output: 1280×720, 169 frames, 24 fps, 7.041667 s; audio present. SHA256: `99f2bd0be73114fbc4d92d3cbd20b8f2a7533efbbf8c869ab3574fe951c69423`.
+
+**Observed:** the man enters from camera-right and lowers himself beside the woman. She turns toward him and extends the single pair. Their hands share support around 3.5–4.7 s. At about 4.8–5.0 s she releases and withdraws her hands; by about 5.25 s her empty hands are on the table. The receiver alone holds and inspects the headphones through the end. All 169 contact crops and first/middle/last full-scene images were inspected. No gross duplication or disconnected limb was found in that inspection. Fine fingers, exact product surfaces/lettering and photometric consistency are not certified. Recipient identity consistency across other shots is untested.
+
+The opening-frame product-region patch has zero whole-pixel translation and correlation 0.9970; whole-frame RGB difference averages 3.32/255. These are opening-frame comparisons, not interaction fidelity scores. Editable typography is placed over the empty lower-left tabletop to avoid the second actor. Physical interaction remains baked in the generated footage. Export retains all 169 frames at 24 fps; repeat frame 48 and source pixels outside the lower-left typography region have zero maximum RGB difference before encoding. A control edit changes 15,803 pixels; no page errors.
+
+**Verdict: works with manual review for this transfer.** Completed release is now demonstrated once; it is not proof of repeatable multi-person choreography. The seven-second duration and different starting pose prevent treating this as a controlled comparison against the five-second pickup.
+
+## Budget and durable evidence
+
+Published image-input pricing was rechecked at $0.157/s for 720p. Five plus seven requested seconds estimated $1.884. Actual decoded durations total 12.083333 s, estimating **$1.8971** at the published rate (provider-rounded durations estimate $1.8972). Actual account billing was not retrieved. The round is closed to further submissions; the remaining estimate is below the minimum three-second image-input job. Each submission is guarded against retry after an ambiguous POST and linked to ordered input hashes and a job receipt. No third job is permitted in this round. Provider cost estimates are not a verified account ledger charge.
+
+## Plan implications
+
+- Preserve the distinction between `start_image` and an ordinary appearance reference. The observed placement benefit supports using an approved starting frame, without claiming an exact constraint or a controlled A/B model study.
+- Freeze source/render binding, scene controls, frame/camera, snapshot and reference bytes/order before submission. Preserve the editable scene for another layout, and regenerate action when that layout changes.
+- Acceptance must include the actual action beats. A good-looking pickup without heft, or two people holding without release, is not full instruction compliance.
+- Source-bound masks/tracks must be regenerated for new take bytes. Existing masks from the earlier pickup cannot be attached to these new videos.
+- Remaining: object–object contact, repeatability across seeds/takes, two identity-referenced subjects, multi-angle product fidelity, full-resolution edge annotations, native receipt/import/failure handling, stronger mixed human/product relighting and actual additional-computer benchmarks.
+- Feature item 6 (camera solve) and feature item 13 (generated worlds) remain untested/deferred. Authored cameras, captured stills and generated videos are not evidence for either.
+
+Primary provider reference: [Kling inputs and pricing](https://replicate.com/kwaivgi/kling-v4.0). Visual findings and timings above are local experiment observations.
diff --git a/examples/hybrid-code-first/clip.mjs b/examples/hybrid-code-first/clip.mjs
new file mode 100644
index 0000000..79325bb
--- /dev/null
+++ b/examples/hybrid-code-first/clip.mjs
@@ -0,0 +1,51 @@
+// Keep exact foreground geometry out of unconstrained background generation.
+// Supply a clean background asset named world, or world/worldInfo props in a host.
+import * as T from 'three';
+import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
+import {defineRenderer} from 'editableframes/renderer';
+import {createKineticText,createFrameLoader,conformSeconds} from 'editableframes/plate';
+import {renderPass,createPlateEnvironment} from 'editableframes/three-plate';
+export default defineRenderer({id:'code-first-product',renderer:'three+html',width:832,height:480,fps:16,durationInFrames:81,
+ passes:['clay','depth','normal','id','matte'],defaultProps:{label:'LUMA',model:'',world:'world',worldInfo:null,backplate:true,spin:false},
+ controls:{version:1,fields:[{key:'world',anchor:'background',type:'media',mediaKind:'video',default:'world',label:'Empty background'},{key:'worldInfo',anchor:'background',type:'json',default:null,label:'Background frame metadata'},{key:'model',anchor:'product',type:'model',default:'',label:'Optional photo model'},{key:'label',type:'string',label:'Exact label'},{key:'spin',type:'bool',label:'Rotate model'}]},
+ async create({root,props,asset,mediaInfo,mediaFrame,sourceFrame}){
+ root.style.background='#d6dcd6';
+ const canvas=document.createElement('canvas');root.append(canvas);
+ const r=new T.WebGLRenderer({canvas,alpha:true,antialias:true,preserveDrawingBuffer:true});r.setSize(832,480);r.shadowMap.enabled=true;r.shadowMap.type=T.PCFSoftShadowMap;r.setClearColor(0,0);r.outputColorSpace=T.SRGBColorSpace;r.toneMapping=T.NeutralToneMapping;
+ const scene=new T.Scene(),camera=new T.PerspectiveCamera(35,832/480,.1,30);camera.position.set(0,.1,4.5);camera.lookAt(0,0,0);
+ scene.add(new T.HemisphereLight(0xf4fff8,0x646b71,2));const key=new T.DirectionalLight(0xffffff,3);key.position.set(-3,5,4);key.castShadow=true;key.shadow.mapSize.set(1024,1024);key.shadow.camera.left=-3;key.shadow.camera.right=3;key.shadow.camera.top=3;key.shadow.camera.bottom=-3;key.shadow.bias=-.0002;scene.add(key);
+ const product=new T.Group();product.userData.passId='product';product.position.set(.55,-.13,0);scene.add(product);
+ let modelKey,labelKey,labelCanvas,labelTexture;
+ const release=object=>{const resources=new Set();object.traverse(o=>{if(o.geometry)resources.add(o.geometry);for(const m of o.material?(Array.isArray(o.material)?o.material:[o.material]):[]){resources.add(m);for(const value of Object.values(m))if(value?.isTexture)resources.add(value);}});for(const resource of resources)resource.dispose();};
+ async function updateProduct(){
+ const next=String(props.model??'');
+ if(next!==modelKey){
+ const replacement=new T.Group();let canvas,texture;
+ if(next){
+ const gltf=await new GLTFLoader().loadAsync(asset(next)),model=gltf.scene;
+ const box=new T.Box3().setFromObject(model),size=box.getSize(new T.Vector3()),centre=box.getCenter(new T.Vector3());
+ if(!Number.isFinite(size.y)||size.y<=0){release(model);throw Error('Product model has no finite height');}
+ model.position.sub(centre);const fit=new T.Group();fit.add(model);fit.scale.setScalar(1.25/size.y);replacement.add(fit);
+ }else{
+ canvas=document.createElement('canvas');canvas.width=1024;canvas.height=512;texture=new T.CanvasTexture(canvas);texture.colorSpace=T.SRGBColorSpace;
+ replacement.add(new T.Mesh(new T.CylinderGeometry(.31,.31,1.18,64),new T.MeshStandardMaterial({map:texture,metalness:.2,roughness:.36})));
+ for(const y of [-.61,.61]){const lid=new T.Mesh(new T.CylinderGeometry(.30,.31,.04,64),new T.MeshStandardMaterial({color:0xb9bfc0,metalness:.9,roughness:.22}));lid.position.y=y;replacement.add(lid);}
+ }
+ replacement.traverse(o=>{if(o.isMesh)o.castShadow=true;});release(product);product.clear();product.add(replacement);
+ modelKey=next;labelCanvas=canvas;labelTexture=texture;labelKey=undefined;
+ }
+ const label=String(props.label??'');
+ if(labelCanvas&&label!==labelKey){const ctx=labelCanvas.getContext('2d');ctx.fillStyle='#ef633f';ctx.fillRect(0,0,1024,512);ctx.fillStyle='white';ctx.textAlign='center';ctx.font='900 95px Arial';for(const x of [256,768])ctx.fillText(label,x,280);labelTexture.needsUpdate=true;labelKey=label;}
+ }
+ const floor=new T.Mesh(new T.PlaneGeometry(20,20),new T.ShadowMaterial({opacity:.32}));floor.receiveShadow=true;floor.userData.passExclude=true;floor.rotation.x=-Math.PI/2;floor.position.y=-.76;scene.add(floor);
+ const title=document.createElement('div');title.style.cssText='position:absolute;left:46px;top:42px;color:#17251e;font:800 32px/1.05 Arial;letter-spacing:-1px;max-width:310px';root.append(title);
+ const sub=document.createElement('div');sub.style.cssText='position:absolute;left:46px;bottom:42px;color:#17251e;font:600 13px Arial;letter-spacing:2px';root.append(sub);
+ const kinetic=createKineticText({root:title});let bg,bgctx;const loader=createFrameLoader(),env=createPlateEnvironment(r);if(props.backplate){bg=document.createElement('canvas');bg.width=832;bg.height=480;root.prepend(bg);bg.style.cssText='position:absolute;inset:0';canvas.style.cssText='position:absolute;inset:0';bgctx=bg.getContext('2d');}
+ return {async render(clock){
+ await updateProduct();
+ const time=clock.frame/clock.fps;product.rotation.y=props.spin?time*.65:-1.3;kinetic.render(time,{text:'BUILT IN CODE. SET IN MOTION.',effect:'orbit',stagger:.09,duration:.8,hold:3600,pathRadius:30});sub.textContent=props.model?'PHOTO → GLB → EDITABLE HTML':String(props.label)+' / BLOOD ORANGE';
+ if(props.backplate){const info=props.worldInfo??mediaInfo?.(String(props.world));if(!info?.frameRate||!info.frames)throw Error('Supply verified empty-background metadata');const at=conformSeconds(clock.mediaTime??time,info.frameRate),index=Math.floor(at*info.frameRate.num/info.frameRate.den+1e-6);if(index<0||index>=info.frames)throw Error('Empty background frame outside source range');const image=await loader.load(sourceFrame?sourceFrame(String(props.world),index,{width:info.width,height:info.height,seconds:at}):mediaFrame(String(props.world),at));bgctx.drawImage(image,0,0,832,480);scene.environment=env.update(image);scene.environmentIntensity=1;floor.visible=true;title.style.color=sub.style.color='white';}
+ const pass=clock.pass??'beauty';title.style.visibility=sub.style.visibility=pass==='beauty'?'visible':'hidden';if(bg)bg.style.visibility=pass==='beauty'?'visible':'hidden';
+ if(pass!=='beauty'){root.style.background='transparent';renderPass(r,scene,camera,pass,{ids:['product']});}else{root.style.background=props.backplate?'#202620':'#d6dcd6';r.render(scene,camera);}
+ },dispose(){kinetic.dispose();loader.dispose();env.dispose();release(product);release(floor);r.dispose();r.forceContextLoss();root.replaceChildren();}};
+ }});
diff --git a/examples/hybrid-surfaces/clip.mjs b/examples/hybrid-surfaces/clip.mjs
new file mode 100644
index 0000000..b2eca0b
--- /dev/null
+++ b/examples/hybrid-surfaces/clip.mjs
@@ -0,0 +1,67 @@
+import {defineRenderer} from 'editableframes/renderer';
+import {createFrameLoader,createForegroundHoldout,validatePreparedAnalysis,preparedFrame,sampleTrackFrame,scalePoints,cylinderMesh,sampleSurface,drawSurfaceArtwork,relightArtwork,createKineticText,loadPreparedAnalysis,pendingMaskCorrections} from 'editableframes/plate';
+
+export const controls={version:1,fields:[
+ {key:'foregroundSource',anchor:'surface',path:'/foregroundSource',type:'media',mediaKind:'video',default:'plate',label:'Original object footage'},
+ {key:'foregroundMask',anchor:'foreground',path:'/foregroundMask',type:'media',mediaKind:'video',default:'foreground',label:'Prepared foreground'},
+ {key:'prepared',anchor:'foreground',path:'/prepared',type:'json',default:null,label:'Prepared analysis'},
+ {key:'corrections',anchor:'foreground',path:'/corrections',type:'json',default:null,label:'Subject corrections'},
+ {key:'track',anchor:'surface',path:'/track',type:'json',default:null,label:'Original body track'},
+ {key:'meshTrack',anchor:'surface',path:'/meshTrack',type:'json',default:null,label:'Optional deforming UV mesh'},
+ {key:'label',anchor:'label',path:'/label',type:'string',default:'LUMA',label:'Exact label'},
+ {key:'detail',anchor:'label',path:'/detail',type:'string',default:'BLOOD ORANGE',label:'Small print'},
+ {key:'color',anchor:'label',path:'/color',type:'color',default:'#ed5426',label:'Body colour'},
+ {key:'seam',anchor:'surface',path:'/seam',type:'number',min:-1,max:1,default:0,animatable:true,label:'Authored label rotation'},
+ {key:'bodyInset',anchor:'surface',path:'/bodyInset',type:'number',min:0,max:.1,default:.02,label:'Body edge inset'},
+ {key:'rimCurve',anchor:'surface',path:'/rimCurve',type:'number',min:0,max:.1,default:.03,label:'Lower body curvature'},
+ {key:'reference',anchor:'lighting',path:'/reference',type:'number',min:1,max:255,default:180,label:'Neutral body reference'},
+ {key:'shading',anchor:'lighting',path:'/shading',type:'number',min:0,max:1,default:1,label:'Preserve observed shading'},
+ {key:'headline',anchor:'headline',path:'/headline',type:'string',default:'MADE TO MOVE.',label:'Motion title'},
+ {key:'motion',anchor:'headline',path:'/motion',type:'string',default:'rise',label:'Text treatment'},
+ {key:'plateStartFrame',anchor:'surface',path:'/plateStartFrame',type:'number',min:0,max:18000,default:0,label:'Source frame at start'},
+ {key:'plateSpeed',anchor:'surface',path:'/plateSpeed',type:'number',min:-8,max:8,default:1,label:'Source speed'},
+]};
+const defaults=Object.fromEntries(controls.fields.map(f=>[f.key,f.default]));
+export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1920,height:1080,fps:24,durationInFrames:108000,controls,defaultProps:{...defaults,foregroundRequired:true},
+ async create({root,props,sourceFrame,asset,mediaInfo}){
+ if(!sourceFrame)throw Error('Surface reskin needs the host exact source-frame service');
+ const initialPrepared=props.prepared??(mediaInfo?await loadPreparedAnalysis({asset,mediaInfo},'analysis'):null);
+ const initialTrack=props.track??(mediaInfo?await (await fetch(asset('track'))).json():null);
+ const doc=root.ownerDocument,stage=doc.createElement('div');stage.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(stage);
+ const canvas=()=>{const c=doc.createElement('canvas');c.style.cssText='position:absolute;inset:0;width:100%;height:100%';return c;};
+ const plate=canvas(),ink=canvas(),art=canvas();art.width=2048;art.height=1024;stage.append(plate);
+ const title=doc.createElement('div');title.style.cssText='position:absolute;left:5%;top:8%;width:88%;font:900 72px/1.05 system-ui;color:white';
+ const kinetic=createKineticText({root:title}),frames=createFrameLoader({document:doc,max:6});let holdout=null,identity='',labelKey='';
+ return {
+ async render(clock){
+ if(props.preparedError)throw Error(props.preparedError);
+ const receipt=validatePreparedAnalysis(props.prepared??initialPrepared),s=receipt.source,track=props.track??initialTrack;
+ const pending=pendingMaskCorrections(props.corrections,receipt.provenance.appliedCorrections);
+ if(pending)throw Error('Corrections changed; prepare and review a new mask revision before rendering');
+ if(!props.foregroundSource||!props.foregroundMask||!track)throw Error('Reskin needs the original source, foreground and original-body track');
+ if(track.sourceSha256&&track.sourceSha256!==s.sha256)throw Error('Surface track belongs to a different take');
+ const at=preparedFrame(receipt,clock.mediaTime??clock.frame/clock.fps,{startFrame:Number(props.plateStartFrame),speed:Number(props.plateSpeed)});
+ const w=root.clientWidth||clock.width,h=root.clientHeight||clock.height;
+ for(const c of [plate,ink])if(c.width!==w||c.height!==h){c.width=w;c.height=h;}
+ if(identity!==s.sha256){identity=s.sha256;holdout?.dispose();holdout=createForegroundHoldout({root:stage,width:s.width,height:s.height});holdout.root.append(ink,title);}
+ const info={width:s.width,height:s.height,seconds:at.seconds};
+ const [image,mask]=await Promise.all([frames.load(sourceFrame(String(props.foregroundSource),at.sourceFrame,info)),frames.load(sourceFrame(String(props.foregroundMask),at.maskFrame,{...info,seconds:at.maskSeconds}))]);
+ const pc=plate.getContext('2d',{willReadFrequently:true});pc.drawImage(image,0,0,w,h);
+ const key=JSON.stringify([props.label,props.detail,props.color]);
+ if(key!==labelKey){labelKey=key;const c=art.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,2048,1024);c.fillStyle='white';c.textAlign='center';c.textBaseline='middle';c.font='900 190px system-ui';c.fillText(String(props.label),1024,470,900);c.font='700 38px system-ui';c.fillText(String(props.detail),1024,650,900);}
+ const pin=sampleTrackFrame(track,at.sourceFrame);if(pin.held||pin.confidence<=0)throw Error('Original body track is missing at source frame '+at.sourceFrame);
+ const fitted=props.meshTrack?sampleSurface(props.meshTrack,at.sourceFrame):null;
+ const quad=scalePoints(pin.quad,track,w,h),inset=Number(props.bodyInset),curve=Number(props.rimCurve);
+ if(!Number.isFinite(inset)||inset<0||inset>.1||!Number.isFinite(curve)||curve<0||curve>.1)throw Error('Invalid body inset/curvature');
+ const fittedQuad=[quad[0].map((v,i)=>v+(quad[1][i]-v)*inset),quad[1].map((v,i)=>v+(quad[0][i]-v)*inset),quad[2].map((v,i)=>v+(quad[3][i]-v)*inset),quad[3].map((v,i)=>v+(quad[2][i]-v)*inset)];
+ const mesh=fitted?{...fitted,vertices:scalePoints(fitted.vertices,track,w,h)}:cylinderMesh(fittedQuad,{seam:Number(props.seam)});
+ if(!fitted){const bodyHeight=(Math.hypot(quad[3][0]-quad[0][0],quad[3][1]-quad[0][1])+Math.hypot(quad[2][0]-quad[1][0],quad[2][1]-quad[1][1]))/2;mesh.vertices=mesh.vertices.map(([x,y],i)=>{const u=i%65/64,v=Math.floor(i/65)/8;return [x,y-bodyHeight*curve*(2*u-1)**2*v**6];});}
+ const ic=ink.getContext('2d',{willReadFrequently:true});ic.clearRect(0,0,w,h);drawSurfaceArtwork(ic,art,mesh,{wrap:true});
+ const pixels=ic.getImageData(0,0,w,h);pixels.data.set(relightArtwork(pixels.data,pc.getImageData(0,0,w,h).data,{reference:Number(props.reference),strength:Number(props.shading)}));ic.putImageData(pixels,0,0);
+ holdout.update(mask,{channel:receipt.alpha.channel,corrections:pending,frame:at.sourceFrame,sourceSha256:s.sha256,subject:receipt.subject});
+ kinetic.render(clock.frame/clock.fps,{text:String(props.headline),effect:String(props.motion),hold:3600,stagger:.08});
+ },
+ dispose(){frames.dispose();kinetic.dispose();holdout?.dispose();stage.remove();},
+ };
+ }
+});
diff --git a/package.json b/package.json
index 3f258d4..4abdaff 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,8 @@
"./manipulation": "./packages/core/manipulation.mjs",
"./three-manipulation": "./packages/three/manipulation.mjs",
"./key-timing": "./packages/core/key-timing.mjs",
+ "./plate": "./packages/plate/index.mjs",
+ "./three-plate": "./packages/three/plate.mjs",
"./rotation": "./packages/core/rotation.mjs",
"./spatial-session": "./packages/core/spatial-session.mjs",
"./three-editor": "./packages/three/spatial-editor.mjs"
@@ -46,7 +48,10 @@
"test:renderer": "node tests/renderer-integration.mjs",
"build:scene": "node examples/scene-editor/build.mjs",
"dev:scene": "node examples/scene-editor/serve.mjs",
- "test:scene": "node tests/scene-editor-browser.mjs"
+ "test:scene": "node tests/scene-editor-browser.mjs",
+ "test:hybrid": "node tests/hybrid-integration.mjs",
+ "test:prepared": "node tests/prepared-integration.mjs && node tests/hybrid-editing.mjs",
+ "test:audio": "node tests/audio-integration.mjs"
},
"dependencies": {
"esbuild": "0.25.10",
diff --git a/packages/core/definition.mjs b/packages/core/definition.mjs
index ec13839..233fff3 100644
--- a/packages/core/definition.mjs
+++ b/packages/core/definition.mjs
@@ -31,7 +31,7 @@ export function rendererTemplate(scene) {
{title:'Presets',fields:controls.presets.map(p=>({id:`preset:${p.id}`,kind:'preset',label:p.label??p.id,operations:Object.entries(p.values).map(([key,value])=>{const f=controls.fields.find(f=>f.key===key);return {anchor:f.anchor,property:f.property,value};})}))},
]} : null;
return {id:scene.id,title:scene.title??scene.id,width:scene.width,height:scene.height,duration:scene.durationInFrames/scene.fps,
- frameRate:rendererFrameRate(scene),nodes,schemas,panel,payload:{rendererProtocol:1,controlsIdentity:identity,props:{}},
+ frameRate:rendererFrameRate(scene),nodes,schemas,panel,...(scene.media?{media:scene.media}:{}),payload:{rendererProtocol:1,controlsIdentity:identity,props:{}},
validatePayload(payload){if(!payload || payload.rendererProtocol!==1 || payload.controlsIdentity!==identity || !payload.props || typeof payload.props!=='object' || Array.isArray(payload.props))throw Error('Renderer controls changed incompatibly; rebind with an explicit reset or migration');
if(payload.resetControls!==undefined&&(!Array.isArray(payload.resetControls)||payload.resetControls.length>controls.fields.length||new Set(payload.resetControls).size!==payload.resetControls.length||payload.resetControls.some(key=>!controls.fields.some(field=>field.key===key))))throw Error('Invalid reset control identity');},
controls,
diff --git a/packages/core/renderer.mjs b/packages/core/renderer.mjs
index 37eccc8..7d0787b 100644
--- a/packages/core/renderer.mjs
+++ b/packages/core/renderer.mjs
@@ -20,6 +20,9 @@ export function defineRenderer(scene) {
if(!Number.isFinite(scene.fps)||scene.fps<=0)throw Error('Invalid renderer fps');
if(scene.frameRate&&(!Number.isSafeInteger(scene.frameRate.num)||scene.frameRate.num<1||!Number.isSafeInteger(scene.frameRate.den)||scene.frameRate.den<1||Math.abs(scene.frameRate.num/scene.frameRate.den-scene.fps)>1e-7))throw Error('Renderer frameRate disagrees with fps');
if(scene.animationPolicy!==undefined&&!['clock','authored'].includes(scene.animationPolicy))throw Error('Invalid animation policy');
+ // Optional control passes (clay, depth, id...) the scene can draw besides its picture.
+ // A host passes clock.pass and never asks for one that is not declared here.
+ if(scene.passes!==undefined&&(!Array.isArray(scene.passes)||scene.passes.length>16||new Set(scene.passes).size!==scene.passes.length||scene.passes.some(p=>typeof p!=='string'||!/^[a-z][a-z0-9-]{0,31}$/.test(p)||p==='beauty')))throw Error('Invalid renderer passes');
return Object.freeze({...scene,protocol:RENDERER_PROTOCOL});
}
/** Optional picking result; not a grammar for scene objects. Coordinates are
diff --git a/packages/media/frames.mjs b/packages/media/frames.mjs
new file mode 100644
index 0000000..4a0f195
--- /dev/null
+++ b/packages/media/frames.mjs
@@ -0,0 +1,11 @@
+import {ptsIndex} from './ports.mjs';
+
+/** Derived videos share the plate's frame correspondence. A derived still
+ * supplies one raster for every source frame, regardless of the plate clock. */
+export function mediaFrameUrl(catalog,id,time){
+ const asset=catalog[id];
+ if(!asset||asset.type==='audio'||asset.type==='data')throw Error('Missing visual asset: '+id);
+ const parent=asset.derived&&catalog[asset.derived.of];
+ const index=ptsIndex(asset.type==='video'&&parent?.type==='video'?parent.pts:asset.pts,time);
+ return index<0?undefined:asset.url+String(index+1).padStart(6,'0')+'.png';
+}
diff --git a/packages/plate/camera.mjs b/packages/plate/camera.mjs
new file mode 100644
index 0000000..41c8118
--- /dev/null
+++ b/packages/plate/camera.mjs
@@ -0,0 +1,47 @@
+/** A solved or authored camera path for a plate.
+ *
+ * {version:1, width, height, frameRate:{num,den},
+ * frames:[{frame, position:[x,y,z], quaternion:[x,y,z,w], fovY}]}
+ *
+ * Convention: camera-to-world, right-handed, +Y up, looking down -Z (the
+ * Three.js camera convention). fovY is the vertical field of view in degrees.
+ * A solve of generated footage is approximate; EditableFrames only replays it. */
+const finite = v => typeof v === 'number' && Number.isFinite(v);
+export function validateCameraPath(path) {
+ if (!path || path.version !== 1) throw Error('Camera path needs version 1');
+ const r = path.frameRate;
+ if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Camera path needs frameRate {num,den}');
+ if (!Array.isArray(path.frames) || !path.frames.length || path.frames.length > 100_000) throw Error('Camera path needs 1..100000 frames');
+ let previous = -1;
+ for (const f of path.frames) {
+ if (!Number.isSafeInteger(f.frame) || f.frame <= previous) throw Error('Camera frames must be strictly increasing integers');
+ previous = f.frame;
+ if (!Array.isArray(f.position) || f.position.length !== 3 || !f.position.every(finite)) throw Error(`Camera frame ${f.frame} needs position [x,y,z]`);
+ if (!Array.isArray(f.quaternion) || f.quaternion.length !== 4 || !f.quaternion.every(finite) || Math.abs(Math.hypot(...f.quaternion) - 1) > 1e-3) throw Error(`Camera frame ${f.frame} needs a unit quaternion [x,y,z,w]`);
+ if (!(f.fovY > 0 && f.fovY < 180)) throw Error(`Camera frame ${f.frame} needs fovY in degrees`);
+ }
+ return path;
+}
+export function slerp(a, b, t) {
+ let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
+ const sign = dot < 0 ? -1 : 1; dot = Math.min(1, Math.abs(dot));
+ let wa = 1 - t, wb = t;
+ if (dot < 0.9995) { const theta = Math.acos(dot), s = Math.sin(theta); wa = Math.sin((1 - t) * theta) / s; wb = Math.sin(t * theta) / s; }
+ const out = a.map((v, i) => v * wa + sign * b[i] * wb), length = Math.hypot(...out);
+ return out.map(v => v / length);
+}
+/** Sample at plate seconds; ends are held. */
+export function sampleCameraPath(path, seconds) {
+ if (!finite(seconds)) throw Error('Camera sample needs finite seconds');
+ const frames = path.frames, position = seconds * path.frameRate.num / path.frameRate.den;
+ let lo = 0, hi = frames.length - 1;
+ if (position <= frames[0].frame) hi = 0;
+ else if (position >= frames[hi].frame) lo = hi;
+ else { while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (frames[mid].frame <= position) lo = mid; else hi = mid; } }
+ const a = frames[lo], b = frames[hi], t = a === b ? 0 : (position - a.frame) / (b.frame - a.frame);
+ return {
+ position: a.position.map((v, i) => v + (b.position[i] - v) * t),
+ quaternion: slerp(a.quaternion, b.quaternion, t),
+ fovY: a.fovY + (b.fovY - a.fovY) * t,
+ };
+}
diff --git a/packages/plate/canvas.mjs b/packages/plate/canvas.mjs
new file mode 100644
index 0000000..3969d90
--- /dev/null
+++ b/packages/plate/canvas.mjs
@@ -0,0 +1,47 @@
+/** 2D-canvas helpers for layering DOM and Canvas content with a plate. */
+/** Draw `plate` keeping only what `matte` marks white, onto `context`'s canvas.
+ * Layer the result above anything that should pass BEHIND the plate's subject
+ * (a headline behind a presenter). `scratch` is a second canvas this function
+ * may resize and overwrite; pass the same one every frame. */
+export function drawCutout(context, plate, matte, scratch) {
+ const {width, height} = context.canvas;
+ if (scratch.width !== width) scratch.width = width;
+ if (scratch.height !== height) scratch.height = height;
+ const s = scratch.getContext('2d', {willReadFrequently: true});
+ s.globalCompositeOperation = 'copy'; s.drawImage(matte, 0, 0, width, height);
+ const alpha = s.getImageData(0, 0, width, height), a = alpha.data;
+ // Luminance becomes coverage. The matte's own colour is discarded.
+ for (let i = 0; i < a.length; i += 4) { a[i + 3] = (a[i] * 54 + a[i + 1] * 183 + a[i + 2] * 19) >> 8; a[i] = a[i + 1] = a[i + 2] = 0; }
+ s.putImageData(alpha, 0, 0);
+ s.globalCompositeOperation = 'source-in'; s.drawImage(plate, 0, 0, width, height);
+ s.globalCompositeOperation = 'source-over';
+ context.clearRect(0, 0, width, height); context.drawImage(scratch, 0, 0);
+}
+/** Deterministic film grain over `context`'s canvas, sized by `sigma` (0..1,
+ * for example from `estimateNoise`). */
+export function drawGrain(context, grainAt, {sigma, frame, seed = 1}) {
+ const {width, height} = context.canvas, image = context.createImageData(width, height), d = image.data, amplitude = Math.min(1, sigma * 3) * 255;
+ for (let y = 0, i = 0; y < height; y++) for (let x = 0; x < width; x++, i += 4) {
+ const g = grainAt(x, y, frame, seed);
+ d[i] = d[i + 1] = d[i + 2] = g > 0 ? 255 : 0; d[i + 3] = Math.abs(g) * amplitude;
+ }
+ context.putImageData(image, 0, 0);
+}
+/** Decode plate frames by URL, keeping the most recent few. Await the image
+ * inside `render` so the host captures only finished frames. */
+export function createFrameLoader({max = 12, document: doc = globalThis.document} = {}) {
+ const cache = new Map();
+ return {
+ load(url) {
+ if (!url) return Promise.resolve(null);
+ let hit = cache.get(url);
+ if (hit) { cache.delete(url); cache.set(url, hit); return hit; }
+ hit = (async () => { const image = doc.createElement('img'); image.src = url; await image.decode(); return image; })();
+ hit.catch(() => cache.delete(url));
+ cache.set(url, hit);
+ while (cache.size > max) cache.delete(cache.keys().next().value);
+ return hit;
+ },
+ dispose() { cache.clear(); },
+ };
+}
diff --git a/packages/plate/color.mjs b/packages/plate/color.mjs
new file mode 100644
index 0000000..ef61fe0
--- /dev/null
+++ b/packages/plate/color.mjs
@@ -0,0 +1,106 @@
+/** Measuring a plate so code-rendered pixels can be matched to it.
+ * Every function takes 8-bit RGBA (`Uint8ClampedArray`, as ImageData gives) and
+ * is deterministic. They are estimates from one view of the scene: expose the
+ * results as editable controls instead of trusting them blindly. */
+export const srgbToLinear = v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
+export const linearToSrgb = v => v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
+const LUT = Float64Array.from({length: 256}, (_, i) => srgbToLinear(i / 255));
+const luminance = (r, g, b) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
+function check(rgba, width, height) {
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || rgba?.length !== width * height * 4) throw Error('Expected RGBA pixels matching width x height');
+}
+function percentile(histogram, total, fraction) {
+ let seen = 0; const target = total * fraction;
+ for (let i = 0; i < 256; i++) { seen += histogram[i]; if (seen >= target) return i; }
+ return 255;
+}
+/** Black point, white point and mean per channel, in linear light. The points
+ * are the 1st and 99th percentiles, so a few stray pixels do not set them. */
+export function plateStats(rgba, width, height) {
+ check(rgba, width, height);
+ const h = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], sum = [0, 0, 0], total = width * height;
+ for (let i = 0; i < rgba.length; i += 4) for (let c = 0; c < 3; c++) { h[c][rgba[i + c]]++; sum[c] += LUT[rgba[i + c]]; }
+ return {
+ black: h.map(x => LUT[percentile(x, total, 0.01)]),
+ white: h.map(x => LUT[percentile(x, total, 0.99)]),
+ mean: sum.map(v => v / total),
+ };
+}
+/** Levels that sit a full-range (0..1 linear) render inside the plate's own
+ * range, so its blacks are no blacker and its whites no whiter than the plate's. */
+export function matchLevels(stats) {
+ return {offset: [...stats.black], gain: stats.white.map((w, c) => Math.max(0, w - stats.black[c]))};
+}
+export const applyLevels = (rgb, levels) => rgb.map((v, c) => levels.offset[c] + v * levels.gain[c]);
+
+/** Where the light seems to come from, judged from the brightest 5% of the
+ * frame. Returns a unit vector in camera space pointing FROM the subject TOWARD
+ * the light (Three.js convention: +X right, +Y up, +Z toward the camera), its
+ * colour, how concentrated it is (0 = flat overcast, 1 = one small source) and
+ * the colour of everything else as ambient fill.
+ *
+ * A picture says which SIDE the light is on, not how far in front of or behind
+ * the subject it sits, and nothing about what is behind the camera. So the
+ * side-to-side and up-down parts come from where the bright area is in frame,
+ * and the front-to-back part is a stated assumption: a small source is placed
+ * level with the subject (side light), a broad one in front of it (frontal).
+ * Treat the result as a starting value for an editable control. */
+export function estimateKeyLight(rgba, width, height) {
+ check(rgba, width, height);
+ const histogram = new Uint32Array(256), total = width * height, lum = new Float32Array(total);
+ for (let i = 0, p = 0; i < rgba.length; i += 4, p++) {
+ lum[p] = luminance(LUT[rgba[i]], LUT[rgba[i + 1]], LUT[rgba[i + 2]]);
+ histogram[Math.min(255, Math.round(linearToSrgb(lum[p]) * 255))]++;
+ }
+ // The histogram bin is a rounded value; the margin keeps a flat frame from
+ // reading as a faint light source through that rounding.
+ const threshold = srgbToLinear(percentile(histogram, total, 0.95) / 255) + 2e-3;
+ let weight = 0, cx = 0, cy = 0, spread = 0; const key = [0, 0, 0], ambient = [0, 0, 0]; let ambientCount = 0;
+ for (let y = 0, p = 0; y < height; y++) for (let x = 0; x < width; x++, p++) {
+ const i = p * 4, w = lum[p] - threshold;
+ if (w > 0) { weight += w; cx += w * (x + 0.5); cy += w * (y + 0.5); for (let c = 0; c < 3; c++) key[c] += w * LUT[rgba[i + c]]; }
+ else { ambientCount++; for (let c = 0; c < 3; c++) ambient[c] += LUT[rgba[i + c]]; }
+ }
+ const fill = ambient.map(v => ambientCount ? v / ambientCount : 0);
+ if (!(weight > 1e-9)) return {toward: [0, 0.7071, 0.7071], color: [1, 1, 1], concentration: 0, ambient: fill};
+ cx /= weight; cy /= weight;
+ for (let y = 0, p = 0; y < height; y++) for (let x = 0; x < width; x++, p++) { const w = lum[p] - threshold; if (w > 0) spread += w * (((x + 0.5 - cx) / width) ** 2 + ((y + 0.5 - cy) / height) ** 2); }
+ // A uniform frame has spread 1/6 across both axes; a point source has 0.
+ const concentration = Math.min(1, Math.max(0, 1 - Math.sqrt(spread / weight) / Math.sqrt(1 / 6)));
+ const toward = [cx / width * 2 - 1, 1 - cy / height * 2, 0.25 + 0.75 * (1 - concentration)];
+ const length = Math.hypot(...toward), peak = Math.max(...key, 1e-9);
+ return {toward: toward.map(v => v / length), color: key.map(v => v / peak), concentration, ambient: fill};
+}
+/** Noise standard deviation in 0..1 code values (Immerkaer's fast estimator,
+ * on luma). Use it to size the grain added over code-rendered layers. */
+export function estimateNoise(rgba, width, height) {
+ check(rgba, width, height);
+ if (width < 3 || height < 3) return 0;
+ const y = new Float32Array(width * height);
+ for (let i = 0, p = 0; i < rgba.length; i += 4, p++) y[p] = (0.2126 * rgba[i] + 0.7152 * rgba[i + 1] + 0.0722 * rgba[i + 2]) / 255;
+ let sum = 0;
+ for (let r = 1; r < height - 1; r++) for (let c = 1; c < width - 1; c++) {
+ const p = r * width + c;
+ sum += Math.abs(y[p - width - 1] - 2 * y[p - width] + y[p - width + 1] - 2 * y[p - 1] + 4 * y[p] - 2 * y[p + 1] + y[p + width - 1] - 2 * y[p + width] + y[p + width + 1]);
+ }
+ return Math.sqrt(Math.PI / 2) * sum / (6 * (width - 2) * (height - 2));
+}
+/** Seeded grain in -1..1 for one pixel of one frame: no Math.random, so a
+ * repeated or backward seek draws the same grain. */
+export function grainAt(x, y, frame, seed = 1) {
+ let h = Math.imul(x | 0, 374761393) ^ Math.imul(y | 0, 668265263) ^ Math.imul(frame | 0, 2147483647) ^ Math.imul(seed | 0, 1274126177);
+ h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16;
+ return (h >>> 0) / 2147483647.5 - 1;
+}
+/** Lift an 8-bit frame into linear float RGBA and push its clipped highlights
+ * above 1, so a display-referred plate can stand in for a light source. The
+ * boost is a guess at what the tone curve threw away; it is not recovered data. */
+export function expandHighlights(rgba, {knee = 0.8, boost = 6} = {}) {
+ const out = new Float32Array(rgba.length);
+ for (let i = 0; i < rgba.length; i += 4) {
+ const r = LUT[rgba[i]], g = LUT[rgba[i + 1]], b = LUT[rgba[i + 2]], l = luminance(r, g, b);
+ const over = l > knee ? (l - knee) / (1 - knee) : 0, k = 1 + boost * over * over;
+ out[i] = r * k; out[i + 1] = g * k; out[i + 2] = b * k; out[i + 3] = 1;
+ }
+ return out;
+}
diff --git a/packages/plate/conform.mjs b/packages/plate/conform.mjs
new file mode 100644
index 0000000..dc0eac7
--- /dev/null
+++ b/packages/plate/conform.mjs
@@ -0,0 +1,33 @@
+/** Keeping code and plate on the same instants.
+ * Video generators emit a fixed rate (commonly 24 fps; some 16 or 30). A code
+ * layer that is locked to something in the plate must move on the plate's frame
+ * grid, or it slides against the picture between plate frames. */
+const rate = r => { if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Frame rate needs positive integers {num,den}'); return r; };
+const gcd = (a, b) => b ? gcd(b, a % b) : a;
+/** Index of the plate frame on screen at `seconds`. */
+export function plateFrameIndex(seconds, frameRate) {
+ rate(frameRate);
+ if (!(seconds >= 0)) throw Error('Plate time must be non-negative seconds');
+ return Math.floor(seconds * frameRate.num / frameRate.den + 1e-9);
+}
+/** `seconds` snapped back to the start of the plate frame that is showing. */
+export function conformSeconds(seconds, frameRate) {
+ return plateFrameIndex(seconds, frameRate) * frameRate.den / frameRate.num;
+}
+/** How a plate plays inside a timeline of another rate: how many timeline
+ * frames each plate frame is held for, over one repeating cycle. An uneven
+ * pattern (24 in 30 -> 1,1,1,2) is visible judder on any camera or subject move. */
+export function cadence(plateRate, timelineRate) {
+ rate(plateRate); rate(timelineRate);
+ // timeline frames per plate frame = (t.num/t.den) / (p.num/p.den)
+ const num = timelineRate.num * plateRate.den, den = timelineRate.den * plateRate.num, g = gcd(num, den);
+ const cycleTimeline = num / g, cyclePlate = den / g;
+ if (cyclePlate > 10_000) return {pattern: null, even: false, dropsFrames: num < den, advice: 'Rates share no short cycle; render the timeline at the plate rate or interpolate the plate.'};
+ const pattern = new Array(cyclePlate).fill(0);
+ for (let i = 0; i < cycleTimeline; i++) pattern[Math.floor((i * cyclePlate + 1e-9) / cycleTimeline)]++;
+ const even = pattern.every(v => v === pattern[0]), dropsFrames = pattern.some(v => v === 0);
+ const advice = even && !dropsFrames ? 'Even cadence; no conform needed.'
+ : dropsFrames ? 'The timeline is slower than the plate and drops plate frames; render at the plate rate.'
+ : `Uneven cadence ${pattern.join(',')}; render the timeline at ${plateRate.num}/${plateRate.den} fps or interpolate the plate first.`;
+ return {pattern, even, dropsFrames, advice};
+}
diff --git a/packages/plate/correction-session.mjs b/packages/plate/correction-session.mjs
new file mode 100644
index 0000000..c78d4ba
--- /dev/null
+++ b/packages/plate/correction-session.mjs
@@ -0,0 +1,29 @@
+/** A renderer gesture proposes an immutable correction book; the embedding
+ * editor owns commit/revision checks and Undo. No disk or model side effects. */
+export function createMaskCorrectionSession(){
+ let active=null;
+ return {
+ gesture(event,{book,sourceSha256,subject,sourceFrame,sourceWidth,sourceHeight,width,height,operation='add',radius=12}={}){
+ if(!['add','subtract','replace'].includes(operation)||![sourceWidth,sourceHeight,width,height,radius].every(n=>Number.isFinite(n)&&n>0)||!Number.isSafeInteger(sourceFrame)||sourceFrame<0)throw Error('Invalid correction gesture context');
+ const point=p=>[Math.max(0,Math.min(sourceWidth,p.x/width*sourceWidth)),Math.max(0,Math.min(sourceHeight,p.y/height*sourceHeight))];
+ if(event.phase==='cancel'){active=null;return null;}
+ if(event.phase==='begin'){
+ if(book&&(book.sourceSha256!==sourceSha256||book.subject!==subject))throw Error('Correction source/subject changed');
+ active={id:event.id,frame:sourceFrame,points:[point(event.start)],book:structuredClone(book??{version:1,sourceSha256,subject,keys:[]})};return null;
+ }
+ if(!active||active.id!==event.id)return null;
+ if(active.frame!==sourceFrame){active=null;throw Error('Source frame changed during correction');}
+ const p=point(event.point),last=active.points.at(-1);
+ if(Math.hypot(p[0]-last[0],p[1]-last[1])>1 && active.points.length<4096)active.points.push(p);
+ if(event.phase!=='commit')return null;
+ const pending=active;active=null;
+ const points=pending.points.length<3?Array.from({length:20},(_,i)=>{const a=i/20*Math.PI*2;return[p[0]+Math.cos(a)*radius,p[1]+Math.sin(a)*radius];}):pending.points;
+ const next=pending.book,existing=next.keys.find(k=>k.frame===sourceFrame);
+ const polygon={operation,points};
+ if(existing)existing.polygons.push(polygon);else next.keys.push({frame:sourceFrame,polygons:[polygon]});
+ next.keys.sort((a,b)=>a.frame-b.frame);
+ return {values:{corrections:next}};
+ },
+ cancel(){active=null;},
+ };
+}
diff --git a/packages/plate/depth.mjs b/packages/plate/depth.mjs
new file mode 100644
index 0000000..3535597
--- /dev/null
+++ b/packages/plate/depth.mjs
@@ -0,0 +1,62 @@
+/** Depth plates. A depth asset is an ordinary image or video whose pixels
+ * encode distance from the camera; the manifest says how.
+ *
+ * encoding = {kind:'inverse'|'linear', near, far, packing:'gray8'|'rg16'}
+ *
+ * White is NEAR in both kinds. `inverse` (disparity-like, what monocular depth
+ * models emit) spends its precision close to the camera; `linear` spreads it
+ * evenly. `near` and `far` are the distances that white and black stand for, in
+ * scene units along the view axis. Relative depth has no true scale: near/far
+ * are a choice the author tunes until occlusion lands, not a measurement. */
+export function validateDepthEncoding(encoding) {
+ if (!encoding || !['inverse', 'linear'].includes(encoding.kind)) throw Error('Depth encoding needs kind inverse or linear');
+ if (!(encoding.near > 0) || !(encoding.far > encoding.near) || !Number.isFinite(encoding.far)) throw Error('Depth encoding needs 0 < near < far');
+ if (!['gray8', 'rg16'].includes(encoding.packing ?? 'gray8')) throw Error('Depth packing must be gray8 or rg16');
+ return {kind: encoding.kind, near: encoding.near, far: encoding.far, packing: encoding.packing ?? 'gray8'};
+}
+/** Channel bytes to a 0..1 code value. rg16 keeps 16 bits in red (high) and green (low). */
+export const unpackDepth = (r, g, packing = 'gray8') => packing === 'rg16' ? (r * 256 + g) / 65535 : r / 255;
+export function packDepth(value, packing = 'gray8') {
+ const v = Math.min(1, Math.max(0, value));
+ if (packing !== 'rg16') { const byte = Math.round(v * 255); return [byte, byte, byte]; }
+ const code = Math.round(v * 65535); return [code >> 8, code & 255, 0];
+}
+/** Code value (white = near) to view-axis distance. */
+export function decodeDepth(value, encoding) {
+ const {kind, near, far} = encoding, v = Math.min(1, Math.max(0, value));
+ return kind === 'inverse' ? 1 / (1 / far + v * (1 / near - 1 / far)) : far - v * (far - near);
+}
+export function encodeDepth(distance, encoding) {
+ const {kind, near, far} = encoding, d = Math.min(far, Math.max(near, distance));
+ return kind === 'inverse' ? (1 / d - 1 / far) / (1 / near - 1 / far) : (far - d) / (far - near);
+}
+/** GLSL for the same decode: `float plateDistance(vec4 texel)`. */
+export function depthGlsl(encoding) {
+ const {kind, near, far, packing} = validateDepthEncoding(encoding), f = v => Number(v).toPrecision(9).replace(/^(-?\d+)$/, '$1.0');
+ const code = packing === 'rg16' ? '(texel.r * 65280.0 + texel.g * 255.0) / 65535.0' : 'texel.r';
+ const distance = kind === 'inverse' ? `1.0 / (${f(1 / far)} + v * ${f(1 / near - 1 / far)})` : `${f(far)} - v * ${f(far - near)}`;
+ return `float plateDistance(vec4 texel){float v=clamp(${code},0.0,1.0);return ${distance};}`;
+}
+/** Pixel + distance to a camera-space point (Three.js convention: -Z forward). */
+export function unprojectDepth(u, v, distance, fovY, aspect) {
+ const tan = Math.tan(fovY * Math.PI / 360);
+ return [(u * 2 - 1) * tan * aspect * distance, (1 - v * 2) * tan * distance, -distance];
+}
+/** Least-squares plane y = a*x + b*z + c through camera-space points: enough
+ * to lay a shadow catcher on a floor or table read from a depth plate. */
+export function fitGroundPlane(points) {
+ if (!Array.isArray(points) || points.length < 3) throw Error('A plane needs at least three points');
+ let sxx = 0, sxz = 0, szz = 0, sx = 0, sz = 0, sxy = 0, szy = 0, sy = 0; const n = points.length;
+ for (const [x, y, z] of points) { sxx += x * x; sxz += x * z; szz += z * z; sx += x; sz += z; sxy += x * y; szy += z * y; sy += y; }
+ const m = [[sxx, sxz, sx, sxy], [sxz, szz, sz, szy], [sx, sz, n, sy]];
+ for (let col = 0; col < 3; col++) {
+ let pivot = col;
+ for (let r = col + 1; r < 3; r++) if (Math.abs(m[r][col]) > Math.abs(m[pivot][col])) pivot = r;
+ if (Math.abs(m[pivot][col]) < 1e-12) throw Error('Points do not span a ground plane');
+ [m[col], m[pivot]] = [m[pivot], m[col]];
+ for (let r = 0; r < 3; r++) if (r !== col) { const k = m[r][col] / m[col][col]; for (let c = col; c < 4; c++) m[r][c] -= k * m[col][c]; }
+ }
+ const a = m[0][3] / m[0][0], b = m[1][3] / m[1][1], c = m[2][3] / m[2][2], length = Math.hypot(a, 1, b);
+ let rms = 0; for (const [x, y, z] of points) rms += (a * x + b * z + c - y) ** 2;
+ return {normal: [-a / length, 1 / length, -b / length], point: [0, c, 0], rms: Math.sqrt(rms / n)};
+}
diff --git a/packages/plate/foreground.mjs b/packages/plate/foreground.mjs
new file mode 100644
index 0000000..8926de4
--- /dev/null
+++ b/packages/plate/foreground.mjs
@@ -0,0 +1,64 @@
+import {sampleMaskCorrections} from './prepared.mjs';
+
+/** A holdout protects one authored DOM/Canvas/WebGL group. It clips the code
+ * layer itself, so no screenshot/readback of arbitrary code content is needed.
+ * Alpha is treated as linear coverage. Soft edges retain the source plate's
+ * observed colors; foreground color decontamination is a separate input. */
+export function createForegroundHoldout({root,width,height,document:doc=root.ownerDocument}) {
+ if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1)throw Error('Holdout needs positive raster dimensions');
+ const content=doc.createElement('div');
+ content.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(content);
+ const canvas=doc.createElement('canvas');canvas.width=width;canvas.height=height;
+ const c=canvas.getContext('2d',{willReadFrequently:true});
+ let disposed=false,directMask=null;
+ return {
+ root:content,
+ diagnosticMask(){
+ if(directMask){c.globalCompositeOperation='copy';c.drawImage(directMask,0,0,width,height);}
+ const image=c.getImageData(0,0,width,height);
+ for(let i=0;i>8;d[i]=d[i+1]=d[i+2]=255;d[i+3]=a;}
+ c.putImageData(image,0,0);
+ if(corrections){
+ if(corrections.sourceSha256!==sourceSha256||corrections.subject!==subject)throw Error('Corrections belong to a different source or subject');
+ for(const p of sampleMaskCorrections(corrections,frame)){
+ if(p.operation==='replace'){c.clearRect(0,0,width,height);c.globalCompositeOperation='source-over';}
+ else c.globalCompositeOperation=p.operation==='subtract'?'destination-out':'source-over';
+ c.fillStyle='#fff';c.beginPath();p.points.forEach(([x,y],i)=>i?c.lineTo(x,y):c.moveTo(x,y));c.closePath();c.fill();
+ }
+ }
+ // Invert foreground coverage to visibility for the affected code group.
+ const corrected=c.getImageData(0,0,width,height);
+ for(let i=3;i=opaque){protectedPixels++;const e=Math.max(...[0,1,2].map(c=>Math.abs(source[i+c]-composite[i+c])));maxError=Math.max(maxError,e);if(e>tolerance)leakedPixels++;}
+ return {protectedPixels,leakedPixels,maxError};
+}
diff --git a/packages/plate/homography.mjs b/packages/plate/homography.mjs
new file mode 100644
index 0000000..4ed6fde
--- /dev/null
+++ b/packages/plate/homography.mjs
@@ -0,0 +1,66 @@
+/** Planar projective maps for corner pins and screen/label replacement.
+ * A homography is a row-major 3x3 array [a,b,c, d,e,f, g,h,1]. Quads are four
+ * [x,y] corners in the order top-left, top-right, bottom-right, bottom-left. */
+const finite = v => typeof v === 'number' && Number.isFinite(v);
+export function validateQuad(quad, what = 'Quad') {
+ if (!Array.isArray(quad) || quad.length !== 4 || quad.some(p => !Array.isArray(p) || p.length !== 2 || !p.every(finite))) throw Error(`${what} needs four finite [x,y] corners`);
+ return quad;
+}
+export const rectQuad = (width, height) => [[0, 0], [width, 0], [width, height], [0, height]];
+
+/** The homography carrying each `from` corner onto the matching `to` corner. */
+export function solveHomography(from, to) {
+ validateQuad(from, 'Source quad'); validateQuad(to, 'Target quad');
+ const rows = [];
+ for (let i = 0; i < 4; i++) {
+ const [x, y] = from[i], [u, v] = to[i];
+ rows.push([x, y, 1, 0, 0, 0, -u * x, -u * y, u]);
+ rows.push([0, 0, 0, x, y, 1, -v * x, -v * y, v]);
+ }
+ // Gaussian elimination with partial pivoting on the 8x8 system.
+ for (let col = 0; col < 8; col++) {
+ let pivot = col;
+ for (let r = col + 1; r < 8; r++) if (Math.abs(rows[r][col]) > Math.abs(rows[pivot][col])) pivot = r;
+ if (Math.abs(rows[pivot][col]) < 1e-12) throw Error('Degenerate quad: three corners are collinear or two coincide');
+ [rows[col], rows[pivot]] = [rows[pivot], rows[col]];
+ for (let r = 0; r < 8; r++) {
+ if (r === col) continue;
+ const factor = rows[r][col] / rows[col][col];
+ if (factor) for (let c = col; c < 9; c++) rows[r][c] -= factor * rows[col][c];
+ }
+ }
+ return [...rows.map((row, i) => row[8] / row[i]), 1];
+}
+export function applyHomography(h, [x, y]) {
+ const w = h[6] * x + h[7] * y + h[8];
+ return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w];
+}
+export function multiplyHomography(a, b) {
+ const out = new Array(9);
+ for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) out[r * 3 + c] = a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c];
+ return out.map(v => v / out[8]);
+}
+export function invertHomography(h) {
+ const [a, b, c, d, e, f, g, i, j] = h;
+ const det = a * (e * j - f * i) - b * (d * j - f * g) + c * (d * i - e * g);
+ if (Math.abs(det) < 1e-15) throw Error('Homography is not invertible');
+ const inv = [e * j - f * i, c * i - b * j, b * f - c * e, f * g - d * j, a * j - c * g, c * d - a * f, d * i - e * g, b * g - a * i, a * e - b * d];
+ return inv.map(v => v / inv[8]);
+}
+/** CSS matrix3d for an element whose transform-origin is its top-left corner. */
+export function cssMatrix3d(h) {
+ const n = v => { const r = Math.abs(v) < 1e-12 ? 0 : v; return Number(r.toFixed(10)); };
+ return `matrix3d(${[h[0], h[3], 0, h[6], h[1], h[4], 0, h[7], 0, 0, 1, 0, h[2], h[5], 0, h[8]].map(n).join(',')})`;
+}
+/** Transform that lays a `width`x`height` element onto `quad` (same units as
+ * the element's offset parent). Set `transform-origin: 0 0` on the element. */
+export function cornerPinTransform(width, height, quad) {
+ if (!(width > 0) || !(height > 0)) throw Error('Corner pin needs a positive element size');
+ return cssMatrix3d(solveHomography(rectQuad(width, height), quad));
+}
+/** Signed area; negative means the quad is mirrored (seen from behind). */
+export function quadArea(quad) {
+ let area = 0;
+ for (let i = 0; i < 4; i++) { const [x1, y1] = quad[i], [x2, y2] = quad[(i + 1) % 4]; area += x1 * y2 - x2 * y1; }
+ return area / 2;
+}
diff --git a/packages/plate/index.mjs b/packages/plate/index.mjs
new file mode 100644
index 0000000..8aed7ca
--- /dev/null
+++ b/packages/plate/index.mjs
@@ -0,0 +1,19 @@
+/** Hybrid scenes: code-rendered elements composited with footage ("plates"),
+ * generated or filmed. Pure, renderer-independent helpers; nothing here runs a
+ * model. See docs/hybrid-scenes.md. */
+export * from './homography.mjs';
+export * from './track.mjs';
+export * from './camera.mjs';
+export * from './conform.mjs';
+export * from './motion-blur.mjs';
+export * from './depth.mjs';
+export * from './color.mjs';
+export * from './passes.mjs';
+export * from './manifest.mjs';
+export * from './canvas.mjs';
+export * from './prepared.mjs';
+export * from './foreground.mjs';
+export * from './surface.mjs';
+export * from './typography.mjs';
+export * from './correction-session.mjs';
+export * from './raster-surface.mjs';
diff --git a/packages/plate/manifest.mjs b/packages/plate/manifest.mjs
new file mode 100644
index 0000000..9c4689f
--- /dev/null
+++ b/packages/plate/manifest.mjs
@@ -0,0 +1,44 @@
+/** Derived assets: data computed FROM another asset, pinned to the exact bytes
+ * it was computed from.
+ *
+ * "presenter-matte": {src, type:"video", sha256,
+ * derived:{of:"presenter", role:"matte", sourceSha256:""}}
+ *
+ * A matte, depth map, track or camera solve describes one particular take.
+ * Regenerate the take and they describe something that no longer exists, so a
+ * mismatch is refused instead of being composited a few pixels off. */
+import {validateDepthEncoding} from './depth.mjs';
+export const DERIVED_ROLES = Object.freeze({
+ alpha: ['video','image'], // explicit fractional alpha channel
+ analysis: ['data'], // prepared source correspondence/review receipt
+ surface: ['data'], // UV mesh/pose correspondence
+ coverage: ['video', 'image'], // visible target surface, not subject alpha
+ foreground: ['video', 'image'], // decontaminated foreground color, when available
+ matte: ['video', 'image'], // white = keep (subject), black = drop
+ depth: ['video', 'image'], // see depth.mjs; needs `encoding`
+ normals: ['video', 'image'], // camera-space normals, (n+1)/2 in RGB
+ track: ['data'], // track.mjs
+ camera: ['data'], // camera.mjs
+ environment: ['image'], // an equirectangular picture of the plate's surroundings
+});
+export function validateDerived(assets) {
+ const index = {};
+ for (const [id, asset] of Object.entries(assets)) {
+ const d = asset.derived;
+ if (d === undefined) continue;
+ if (!d || typeof d.of !== 'string' || !Object.hasOwn(assets, d.of) || d.of === id) throw Error(`Derived asset ${id} must name another declared asset in derived.of`);
+ if (assets[d.of].derived) throw Error(`Derived asset ${id} cannot derive from ${d.of}, which is itself derived`);
+ if (!Object.hasOwn(DERIVED_ROLES, d.role)) throw Error(`Derived asset ${id} has unknown role ${d.role}`);
+ if (!DERIVED_ROLES[d.role].includes(asset.type)) throw Error(`A ${d.role} must be ${DERIVED_ROLES[d.role].join(' or ')}, not ${asset.type}: ${id}`);
+ if (!/^[a-f0-9]{64}$/.test(d.sourceSha256 ?? '')) throw Error(`Derived asset ${id} needs derived.sourceSha256`);
+ if (d.sourceSha256 !== assets[d.of].sha256) throw Error(`${id} was made from different bytes than the current ${d.of}; regenerate the ${d.role} for this take`);
+ if (d.role === 'depth') validateDepthEncoding(d.encoding);
+ else if (d.encoding !== undefined) throw Error(`Only depth assets carry an encoding: ${id}`);
+ if(d.subject!==undefined && (typeof d.subject!=='string'||!/^[a-zA-Z0-9_.-]{1,80}$/.test(d.subject)))throw Error('Invalid derived subject: '+id);
+ const slot=d.subject===undefined?d.role:d.role+':'+d.subject;
+ index[d.of] ??= {};
+ if (index[d.of][slot]) throw Error(`${d.of} has two ${d.role} assets (${index[d.of][slot]}, ${id}); keep one`);
+ index[d.of][slot] = id;
+ }
+ return index;
+}
diff --git a/packages/plate/motion-blur.mjs b/packages/plate/motion-blur.mjs
new file mode 100644
index 0000000..2d125c8
--- /dev/null
+++ b/packages/plate/motion-blur.mjs
@@ -0,0 +1,16 @@
+/** Sub-frame sample times for an offline shutter. Frames are explicit, so a
+ * host can afford N renders per output frame and average them. */
+export function validateShutter({samples = 8, angle = 180, phase = 'centered'} = {}) {
+ if (!Number.isSafeInteger(samples) || samples < 2 || samples > 64) throw Error('Motion blur samples must be an integer 2..64');
+ if (!(angle > 0 && angle <= 360)) throw Error('Shutter angle must be in (0, 360] degrees');
+ if (!['centered', 'forward'].includes(phase)) throw Error('Shutter phase must be centered or forward');
+ return {samples, angle, phase};
+}
+/** Fractional frames to render for output `frame`. `centered` straddles the
+ * frame instant; `forward` opens at it. Times before frame 0 are clamped. */
+export function shutterSamples(frame, options) {
+ const {samples, angle, phase} = validateShutter(options);
+ if (!(frame >= 0)) throw Error('Shutter needs a non-negative frame');
+ const open = angle / 360, start = phase === 'centered' ? frame - open / 2 : frame;
+ return Array.from({length: samples}, (_, k) => Math.max(0, start + (k + 0.5) / samples * open));
+}
diff --git a/packages/plate/passes.mjs b/packages/plate/passes.mjs
new file mode 100644
index 0000000..e501b31
--- /dev/null
+++ b/packages/plate/passes.mjs
@@ -0,0 +1,24 @@
+/** Control passes: the same scene drawn as structure instead of as a picture,
+ * to condition a video model or to composite elsewhere. A scene declares the
+ * passes it implements; a host never invents one it was not given. */
+export const PASS = /^[a-z][a-z0-9-]{0,31}$/;
+export const COMMON_PASSES = Object.freeze(['beauty', 'clay', 'depth', 'normal', 'id', 'matte']);
+export function validatePasses(passes) {
+ if (passes === undefined) return [];
+ if (!Array.isArray(passes) || passes.length > 16 || new Set(passes).size !== passes.length || passes.some(p => typeof p !== 'string' || !PASS.test(p))) throw Error('passes must be up to 16 unique lowercase names');
+ return passes.filter(p => p !== 'beauty');
+}
+// An odd multiplier is a bijection on 24-bit integers, so neighbouring ids get
+// far-apart colours and every colour still decodes to exactly one id.
+const SPREAD = 0x9E3779, MASK = 0xFFFFFF;
+let inverse = 1; for (let i = 0; i < 5; i++) inverse = Math.imul(inverse, 2 - Math.imul(SPREAD, inverse)) & MASK;
+/** Byte colour for object `index` (0-based). Colour [0,0,0] means "no object". */
+export function idColor(index) {
+ if (!Number.isSafeInteger(index) || index < 0 || index >= MASK) throw Error('Object index out of range');
+ const code = Math.imul(index + 1, SPREAD) & MASK;
+ return [code >> 16, (code >> 8) & 255, code & 255];
+}
+/** Object index for a byte colour, or -1 for the empty colour. */
+export function idFromColor([r, g, b]) {
+ return (Math.imul((r << 16) | (g << 8) | b, inverse) & MASK) - 1;
+}
diff --git a/packages/plate/prepared.mjs b/packages/plate/prepared.mjs
new file mode 100644
index 0000000..f00d04f
--- /dev/null
+++ b/packages/plate/prepared.mjs
@@ -0,0 +1,129 @@
+/** Model-neutral, immutable analysis receipts. Frame numbers are source frames,
+ * never timeline frames. A receipt records correspondence, not pixel truth. */
+const hash = x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x);
+const integer = x => Number.isSafeInteger(x) && x >= 0;
+const finite = x => typeof x === 'number' && Number.isFinite(x);
+export function validatePreparedAnalysis(data, source) {
+ if (!data || data.version !== 1 || data.kind !== 'prepared-plate') throw Error('Prepared analysis needs version 1, kind prepared-plate');
+ const s = data.source;
+ if (!s || typeof s.asset!=='string' || !s.asset || !hash(s.sha256) || !integer(s.width) || !s.width || !integer(s.height) || !s.height || !integer(s.frames) || !s.frames || s.frames > 100000) throw Error('Prepared analysis needs a bounded source digest, dimensions and frame count');
+ const rate = s.frameRate;
+ if (!rate || !integer(rate.num) || !rate.num || !integer(rate.den) || !rate.den) throw Error('Prepared analysis needs a rational source frame rate');
+ if (s.orientation !== 0 || !Array.isArray(s.crop) || s.crop.length !== 4 || !s.crop.every(integer) || s.crop.join() !== [0,0,s.width,s.height].join()) throw Error('Prepare analysis from the decoded, oriented full source raster');
+ if (!Array.isArray(s.pts) || s.pts.length !== s.frames || s.pts.some((t,i) => !finite(t) || t < 0 || (i && t <= s.pts[i-1])) || s.pts[0] !== 0) throw Error('Prepared analysis needs strictly increasing source presentation times starting at zero');
+ if (source) {
+ for (const key of ['sha256','width','height','frames']) if (source[key] !== s[key]) throw Error(`Prepared analysis source ${key} changed; prepare this take again`);
+ if (source.frameRate && source.frameRate.num * rate.den !== rate.num * source.frameRate.den) throw Error('Prepared source frame rate changed');
+ if (source.pts && (source.pts.length !== s.frames || source.pts.some((t,i) => Math.abs(t-s.pts[i]) > 1e-7))) throw Error('Prepared source presentation times changed');
+ }
+ if (typeof data.subject !== 'string' || !/^[\w.-]{1,80}$/.test(data.subject) || !hash(data.revision)) throw Error('Prepared analysis needs a subject and correction revision digest');
+ if (!data.provenance || typeof data.provenance.method !== 'string' || !data.provenance.method || typeof data.provenance.preprocess !== 'string' || !data.provenance.preprocess) throw Error('Prepared analysis needs method and preprocessing provenance');
+ if (data.provenance.checkpoint !== undefined && !hash(data.provenance.checkpoint)) throw Error('Checkpoint identity must be a content digest');
+ if (!data.alpha || typeof data.alpha.asset !== 'string' || !hash(data.alpha.sha256) || !['luminance','alpha'].includes(data.alpha.channel) || !['segmentation','alpha'].includes(data.alpha.semantics)) throw Error('Prepared analysis needs a pinned alpha/segmentation asset and channel');
+ if (!Array.isArray(data.frames) || data.frames.length !== s.frames) throw Error('Prepared analysis is missing source-frame correspondence');
+ data.frames.forEach((f,i) => {
+ if (f.sourceFrame !== i || !integer(f.maskFrame) || f.maskFrame >= s.frames || typeof f.valid !== 'boolean' || typeof f.reviewed !== 'boolean') throw Error(`Invalid prepared correspondence at source frame ${i}`);
+ if (f.issues !== undefined && (!Array.isArray(f.issues) || f.issues.some(x => typeof x !== 'string'))) throw Error(`Invalid issues at source frame ${i}`);
+ });
+ return data;
+}
+
+/** Explicit source mapping handles trim/reverse; out-of-range never holds a tail. */
+export function preparedFrame(data, seconds, {start = 0, startFrame, speed = 1, requireReviewed = true, allowInvalid = false} = {}) {
+ if (![seconds,start,speed].every(finite)) throw Error('Prepared sampling needs finite time, trim and speed');
+ const pts = data.source.pts;
+ if (startFrame !== undefined && (!integer(startFrame) || startFrame >= pts.length)) throw Error('Prepared trim needs a source frame inside the plate');
+ const time = (startFrame === undefined ? start : pts[startFrame]) + seconds * speed;
+ const end = pts.at(-1) + data.source.frameRate.den / data.source.frameRate.num;
+ if (time < -1e-9 || time >= end - 1e-9) throw Error(`Prepared source time ${time} is outside 0..${end}`);
+ let lo=0, hi=pts.length;
+ while (lo+1>1; if(pts[mid]<=time+1e-9)lo=mid;else hi=mid; }
+ const f=data.frames[lo];
+ if ((!f.valid && !allowInvalid) || (requireReviewed && !f.reviewed)) throw Error(`Prepared subject ${data.subject} needs correction/review at source frame ${lo}${f.issues?.length ? ': '+f.issues.join(', ') : ''}`);
+ return {...f, seconds:pts[lo], maskSeconds:pts[f.maskFrame]};
+}
+
+/** Bounded diagnostics. Area collapse flags review, not automatic deletion or
+ * identity reassignment: a real subject can leave the shot. */
+export function analyzeMask(rgba, width, height, {channel='luminance', previousCoverage, collapseRatio=.2,expected=true} = {}) {
+ if (!integer(width) || !width || !integer(height) || !height || rgba.length !== width*height*4) throw Error('Mask raster dimensions do not match');
+ if (!['luminance','alpha'].includes(channel)) throw Error('Mask channel must be luminance or alpha');
+ let area=0, opaque=0, left=width,top=height,right=-1,bottom=-1;
+ for(let p=0;p127){opaque++;const x=p%width,y=Math.floor(p/width);left=Math.min(left,x);right=Math.max(right,x);top=Math.min(top,y);bottom=Math.max(bottom,y);}
+ }
+ const coverage=opaque/(width*height), issues=[];
+ if(expected&&opaque===0)issues.push('foreground-absent');
+ if(expected && finite(previousCoverage) && previousCoverage>.001 && coverage10000)throw Error('Invalid subject correction book');
+ let last=-1;
+ for(const k of book.keys){
+ if(!integer(k.frame)||k.frame<=last||!Array.isArray(k.polygons)||k.polygons.length>128)throw Error('Correction keys must have increasing whole frames and bounded polygons');last=k.frame;
+ for(const p of k.polygons){
+ if(!['add','subtract','replace'].includes(p.operation)||!Array.isArray(p.points)||p.points.length<3||p.points.length>4096||p.points.some(v=>!Array.isArray(v)||v.length!==2||!v.every(finite)))throw Error('Correction polygon needs finite source-raster points and an operation');
+ }
+ }
+ return book;
+}
+
+/** Propagation is explicit and bounded between matching authored polygon keys.
+ * No extrapolation beyond them, and no blind optical-flow identity guess. */
+export function sampleMaskCorrections(book, frame) {
+ validateMaskCorrections(book);
+ if(!integer(frame))throw Error('Correction sample needs a whole source frame');
+ const exact=book.keys.find(k=>k.frame===frame);if(exact)return structuredClone(exact.polygons);
+ const next=book.keys.findIndex(k=>k.frame>frame);if(next<=0)return [];
+ const a=book.keys[next-1],b=book.keys[next];if(a.interpolation!=='linear')return [];
+ if(a.polygons.length!==b.polygons.length||a.polygons.some((p,i)=>p.operation!==b.polygons[i].operation||p.points.length!==b.polygons[i].points.length))throw Error(`Correction topology changes across ${a.frame}..${b.frame}`);
+ const t=(frame-a.frame)/(b.frame-a.frame);
+ return a.polygons.map((p,i)=>({...p,points:p.points.map((v,j)=>v.map((n,c)=>n+(b.polygons[i].points[j][c]-n)*t))}));
+}
+
+/** Layout is tested in surface coordinates before projective mapping. */
+export function assertSurfaceLayout(boxes, {width,height,padding=0}) {
+ for(const b of boxes)if(![b.x,b.y,b.width,b.height].every(finite)||b.width<0||b.height<0||b.xwidth-padding||b.y+b.height>height-padding)throw Error(`Artwork ${b.id??''} exceeds the surface safe area`);
+ return true;
+}
+
+export async function loadPreparedAnalysis({asset,mediaInfo}, id) {
+ if(!asset||!mediaInfo)throw Error('Prepared media requires asset and mediaInfo host services');
+ const response=await fetch(asset(id));if(!response.ok)throw Error(`Cannot load prepared analysis ${id}`);
+ const data=await response.json(), source=mediaInfo(data.source.asset);
+ validatePreparedAnalysis(data,source);
+ const mask=mediaInfo(data.alpha.asset);
+ if(mask.sha256!==data.alpha.sha256 || mask.frames!==data.source.frames || mask.width!==data.source.width || mask.height!==data.source.height)throw Error('Prepared mask bytes, dimensions or frame count changed');
+ return data;
+}
+
+const ordered=value=>Array.isArray(value)?value.map(ordered):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,ordered(value[k])])):value;
+/** Canonical masks already contain approved corrections. Live strokes are
+ * provisional; only an append-only delta can be previewed without raw input. */
+export function pendingMaskCorrections(book,applied){
+ if(!book)return null;
+ validateMaskCorrections(book);
+ const equal=(a,b)=>JSON.stringify(ordered(a))===JSON.stringify(ordered(b));
+ if(equal(book,applied))return null;
+ if(!applied)return book.keys.some(k=>k.polygons.length)?structuredClone(book):null;
+ validateMaskCorrections(applied);
+ if(book.sourceSha256!==applied.sourceSha256||book.subject!==applied.subject)throw Error('Correction identity changed');
+ // Editing either endpoint or inserting inside a baked interpolation interval
+ // changes its whole span, which cannot be represented as a live delta.
+ for(let i=0;ik.frame>a.frame&&k.frame!equal(book.keys.find(k=>k.frame===old.frame),old)))throw Error('Re-prepare from the original mask to change a baked interpolation interval');
+ }
+ const pending=structuredClone(book);pending.keys=[];
+ for(const old of applied.keys)if(!book.keys.some(k=>k.frame===old.frame))throw Error('Re-prepare from the original mask to remove baked corrections');
+ for(const key of book.keys){const old=applied.keys.find(k=>k.frame===key.frame);const count=old?.polygons.length??0;
+ if(old&&(!equal(key.polygons.slice(0,count),old.polygons)||key.interpolation!==old.interpolation))throw Error('Re-prepare from the original mask to change baked corrections');
+ if(key.polygons.length>count)pending.keys.push({...structuredClone(key),polygons:structuredClone(key.polygons.slice(count))});
+ }
+ return pending.keys.length?pending:null;
+}
diff --git a/packages/plate/raster-surface.mjs b/packages/plate/raster-surface.mjs
new file mode 100644
index 0000000..0cbe0a9
--- /dev/null
+++ b/packages/plate/raster-surface.mjs
@@ -0,0 +1,25 @@
+/** Rasterize a UV mesh once per output pixel without Canvas clip seams.
+ * The inverse barycentric map keeps adjacent triangles from double-blending
+ * antialiased clip edges. Output is straight RGBA; interpolation is premultiplied. */
+export function rasterizeSurface(pixels,sourceWidth,sourceHeight,mesh,width,height,{wrap=false}={}){
+ if(pixels.length!==sourceWidth*sourceHeight*4||![sourceWidth,sourceHeight,width,height].every(n=>Number.isSafeInteger(n)&&n>0)||width*height>4096*4096)throw Error('Invalid surface raster dimensions');
+ const out=new Uint8ClampedArray(width*height*4);
+ for(const t of mesh.triangles){
+ const [a,b,c]=t.map(i=>mesh.vertices[i]),[ua,ub,uc]=t.map(i=>mesh.uv[i]);
+ const det=(b[1]-c[1])*(a[0]-c[0])+(c[0]-b[0])*(a[1]-c[1]);if(Math.abs(det)<1e-9)continue;
+ const x0=Math.max(0,Math.floor(Math.min(a[0],b[0],c[0]))),x1=Math.min(width,Math.ceil(Math.max(a[0],b[0],c[0]))),y0=Math.max(0,Math.floor(Math.min(a[1],b[1],c[1]))),y1=Math.min(height,Math.ceil(Math.max(a[1],b[1],c[1])));
+ for(let y=y0;y1)continue;
+ if(v<0||v>1)continue;
+ const sx=u*(sourceWidth-1),sy=v*(sourceHeight-1),ix=Math.floor(sx),iy=Math.floor(sy),fx=sx-ix,fy=sy-iy;
+ const indices=[iy*sourceWidth+ix,iy*sourceWidth+Math.min(ix+1,sourceWidth-1),Math.min(iy+1,sourceHeight-1)*sourceWidth+ix,Math.min(iy+1,sourceHeight-1)*sourceWidth+Math.min(ix+1,sourceWidth-1)],weights=[(1-fx)*(1-fy),fx*(1-fy),(1-fx)*fy,fx*fy];
+ let alpha=0;const rgb=[0,0,0];
+ for(let i=0;i<4;i++){const j=indices[i]*4,aw=pixels[j+3]/255*weights[i];alpha+=aw;for(let k=0;k<3;k++)rgb[k]+=pixels[j+k]*aw;}
+ const dest=(y*width+x)*4;if(alpha>0){for(let k=0;k<3;k++)out[dest+k]=rgb[k]/alpha;out[dest+3]=alpha*255;}
+ }
+ }
+ return out;
+}
diff --git a/packages/plate/surface.mjs b/packages/plate/surface.mjs
new file mode 100644
index 0000000..3914d6d
--- /dev/null
+++ b/packages/plate/surface.mjs
@@ -0,0 +1,73 @@
+import {rasterizeSurface} from './raster-surface.mjs';
+import {solveHomography,applyHomography,rectQuad,quadArea} from './homography.mjs';
+const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite);
+
+/** A rigid cylindrical body in an authored/tracked projected quad. This is an
+ * image-space surface fit, not an inferred metric camera or hidden geometry.
+ * The axis/seam is authored when a blank cylinder makes rotation unobservable. */
+export function cylinderMesh(quad,{columns=64,rows=8,seam=0,arc=Math.PI*2}={}) {
+ if(!Number.isSafeInteger(columns)||columns<2||columns>256||!Number.isSafeInteger(rows)||rows<1||rows>128||!Number.isFinite(seam)||!(arc>0&&arc<=Math.PI*2))throw Error('Invalid cylinder tessellation or seam');
+ if(quadArea(quad)<=0)throw Error('Cylinder body quad is mirrored or degenerate');
+ const h=solveHomography(rectQuad(1,1),quad),vertices=[],uv=[],triangles=[];
+ for(let y=0;y<=rows;y++)for(let x=0;x<=columns;x++){
+ const nx=x/columns*2-1;
+ vertices.push(applyHomography(h,[(nx+1)/2,y/rows]));
+ uv.push([.5+Math.asin(Math.max(-1,Math.min(1,nx)))/arc+seam,y/rows]);
+ }
+ for(let y=0;y40000||!mesh.vertices.every(point)||!Array.isArray(mesh.uv)||mesh.uv.length!==mesh.vertices.length||!mesh.uv.every(point)||!Array.isArray(mesh.triangles)||mesh.triangles.length>80000)throw Error('Surface needs bounded vertices, UVs and triangles');
+ for(const t of mesh.triangles)if(!Array.isArray(t)||t.length!==3||t.some(i=>!Number.isSafeInteger(i)||i<0||i>=mesh.vertices.length)||new Set(t).size!==3)throw Error('Invalid surface triangle');
+ return mesh;
+}
+
+/** Tracked cloth/mesh import path: each key supplies corresponding vertices.
+ * Visibility and tracking quality remain prepared inputs. No extrapolation. */
+export function sampleSurface(track,frame) {
+ if(!track||track.version!==1||!Array.isArray(track.frames)||!track.frames.length||!Number.isFinite(frame))throw Error('Invalid surface track');
+ let previous=-1;
+ for(const f of track.frames){if(!Number.isSafeInteger(f.frame)||f.frame<=previous)throw Error('Surface frames must increase');previous=f.frame;validateSurfaceMesh(f);}
+ const exact=track.frames.find(f=>f.frame===frame);if(exact){if(exact.valid===false)throw Error(`Invalid surface at ${frame}`);return exact;}
+ const next=track.frames.findIndex(f=>f.frame>frame);if(next<=0)throw Error(`Surface frame ${frame} outside tracked range`);
+ const a=track.frames[next-1],b=track.frames[next];
+ if(a.valid===false||b.valid===false||JSON.stringify(a.triangles)!==JSON.stringify(b.triangles)||a.vertices.length!==b.vertices.length||JSON.stringify(a.uv)!==JSON.stringify(b.uv))throw Error('Surface visibility/topology changes require an explicit key');
+ const t=(frame-a.frame)/(b.frame-a.frame);
+ return {...a,frame,vertices:a.vertices.map((p,i)=>p.map((v,j)=>v+(b.vertices[i][j]-v)*t))};
+}
+
+/** Triangulated UV artwork warp. The caller supplies surface coverage and
+ * foreground holdouts. Lids/contact shadows remain in the unmodified plate. */
+const scratchCanvases=new WeakMap();
+export function drawSurfaceArtwork(context,artwork,mesh,{wrap=false}={}) {
+ validateSurfaceMesh(mesh);
+ const w=artwork.naturalWidth??artwork.width,h=artwork.naturalHeight??artwork.height;
+ if(!(w>0&&h>0))throw Error('Artwork has no decoded dimensions');
+ let scratch=scratchCanvases.get(context);
+ if(!scratch){const doc=context.canvas.ownerDocument;scratch={source:doc.createElement('canvas'),target:doc.createElement('canvas')};scratchCanvases.set(context,scratch);}
+ scratch.source.width=w;scratch.source.height=h;
+ const input=scratch.source.getContext('2d',{willReadFrequently:true});input.drawImage(artwork,0,0);
+ const width=context.canvas.width,height=context.canvas.height;
+ scratch.target.width=width;scratch.target.height=height;
+ const target=scratch.target.getContext('2d'),image=target.createImageData(width,height);
+ image.data.set(rasterizeSurface(input.getImageData(0,0,w,h).data,w,h,mesh,width,height,{wrap}));target.putImageData(image,0,0);context.drawImage(scratch.target,0,0);
+}
+
+/** Preserve observed shading on a neutral original body. `reference` is the
+ * original albedo (0..255); arbitrary old printing needs an independent clean
+ * albedo/shading estimate, rather than pretending multiplication removes it. */
+export function relightArtwork(artwork,plate,{reference=180,strength=1}={}) {
+ if(artwork.length!==plate.length||artwork.length%4||!(reference>0&&reference<=255)||!(strength>=0&&strength<=1))throw Error('Invalid reskin rasters or neutral reference');
+ const out=new Uint8ClampedArray(artwork);
+ for(let i=0;iMath.hypot(p[0]-actual[i][0],p[1]-actual[i][1])).sort((a,b)=>a-b);
+ return {max:errors.at(-1),p95:errors[Math.ceil(errors.length*.95)-1],mean:errors.reduce((a,b)=>a+b,0)/errors.length};
+}
diff --git a/packages/plate/track.mjs b/packages/plate/track.mjs
new file mode 100644
index 0000000..0725cbd
--- /dev/null
+++ b/packages/plate/track.mjs
@@ -0,0 +1,54 @@
+/** Tracking data a host or any external tool produced for a plate.
+ *
+ * {version:1, kind:'planar'|'point', width, height, frameRate:{num,den},
+ * frames:[{frame, quad:[[x,y]*4] | point:[x,y], confidence?}]}
+ *
+ * Coordinates are plate pixels, origin top-left. Frames are plate frame
+ * numbers; they may be sparse. EditableFrames never runs a tracker itself. */
+import {validateQuad} from './homography.mjs';
+const finite = v => typeof v === 'number' && Number.isFinite(v);
+export function validateTrack(track) {
+ if (!track || track.version !== 1 || !['planar', 'point'].includes(track.kind)) throw Error('Track needs version 1 and kind planar or point');
+ if (!Number.isSafeInteger(track.width) || !Number.isSafeInteger(track.height) || track.width < 1 || track.height < 1) throw Error('Track needs the plate width and height');
+ const r = track.frameRate;
+ if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Track needs the plate frameRate {num,den}');
+ if (!Array.isArray(track.frames) || !track.frames.length || track.frames.length > 100_000) throw Error('Track needs 1..100000 frames');
+ let previous = -1;
+ for (const f of track.frames) {
+ if (!Number.isSafeInteger(f.frame) || f.frame <= previous) throw Error('Track frames must be strictly increasing integers');
+ previous = f.frame;
+ if (track.kind === 'planar') validateQuad(f.quad, `Track frame ${f.frame}`);
+ else if (!Array.isArray(f.point) || f.point.length !== 2 || !f.point.every(finite)) throw Error(`Track frame ${f.frame} needs a finite [x,y] point`);
+ if (f.confidence !== undefined && !(f.confidence >= 0 && f.confidence <= 1)) throw Error('Track confidence must be 0..1');
+ }
+ return track;
+}
+const mix = (a, b, t) => a + (b - a) * t;
+/** Sample at plate seconds. Between tracked frames the shape is interpolated
+ * (sub-frame samples are what motion blur needs); outside the tracked range the
+ * nearest tracked frame is held and `held` says so. */
+export function sampleTrack(track, seconds) {
+ if (!finite(seconds)) throw Error('Track sample needs finite seconds');
+ return sampleTrackFrame(track, seconds * track.frameRate.num / track.frameRate.den);
+}
+/** Sample a known decoded source frame without converting its quantized PTS
+ * back through nominal fps. Fractional positions remain available to authors. */
+export function sampleTrackFrame(track, position) {
+ if (!finite(position)) throw Error('Track sample needs a finite frame');
+ const frames = track.frames;
+ let lo = 0, hi = frames.length - 1;
+ if (position <= frames[0].frame) hi = 0;
+ else if (position >= frames[hi].frame) lo = hi;
+ else { while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (frames[mid].frame <= position) lo = mid; else hi = mid; } }
+ const a = frames[lo], b = frames[hi], t = a === b ? 0 : (position - a.frame) / (b.frame - a.frame);
+ // Exactly on a tracked frame, that frame's own confidence stands; between two, the worse one.
+ const confidence = t === 0 ? a.confidence ?? 1 : Math.min(a.confidence ?? 1, b.confidence ?? 1);
+ const held = position < frames[0].frame || position > frames.at(-1).frame;
+ if (track.kind === 'point') return {point: [mix(a.point[0], b.point[0], t), mix(a.point[1], b.point[1], t)], confidence, held};
+ return {quad: a.quad.map((p, i) => [mix(p[0], b.quad[i][0], t), mix(p[1], b.quad[i][1], t)]), confidence, held};
+}
+/** Plate pixels to another raster of the same aspect (for example the scene). */
+export function scalePoints(points, track, width, height) {
+ const sx = width / track.width, sy = height / track.height;
+ return points.map(([x, y]) => [x * sx, y * sy]);
+}
diff --git a/packages/plate/typography.mjs b/packages/plate/typography.mjs
new file mode 100644
index 0000000..f84259a
--- /dev/null
+++ b/packages/plate/typography.mjs
@@ -0,0 +1,28 @@
+/** Seekable motion design. Curves are analytic functions of explicit seconds;
+ * no animation depends on the previously requested frame. */
+const clamp=x=>Math.max(0,Math.min(1,x));
+export function typeMotion(seconds,{start=0,duration=.65,hold=2,exit=.35,index=0,stagger=.06,effect='rise',distance=60,turn=0,pathRadius=80}={}) {
+ if(![seconds,start,duration,hold,exit,index,stagger,distance,turn,pathRadius].every(Number.isFinite)||duration<=0||hold<0||exit<0||index<0||stagger<0)throw Error('Invalid typography timing');
+ if(!['rise','wipe','spring','orbit','extrude'].includes(effect))throw Error('Unknown typography treatment');
+ const t=seconds-start-index*stagger,p=clamp(t/duration),q=exit===0?(t>duration+hold?1:0):clamp((t-duration-hold)/exit),ease=1-(1-p)**3;
+ let x=0,y=(1-ease)*distance,scale=1,rotate=(1-ease)*turn;
+ if(effect==='spring'){scale=p===1?1:1-Math.exp(-7*p)*Math.cos(11*p);y=(1-p)*distance*Math.exp(-3*p);}
+ if(effect==='orbit'){const angle=(1-ease)*Math.PI; x=Math.sin(angle)*pathRadius;y=(1-Math.cos(angle))*pathRadius;rotate+=(1-ease)*90;}
+ if(effect==='wipe')y=0;
+ return {opacity:t<0?0:(effect==='wipe'?1:ease)*(1-q),x,y:y-q*distance,scale,rotate,clip:effect==='wipe'?`inset(0 ${(1-ease)*100}% 0 0)`:undefined,extrusion:effect==='extrude'?8*(1-q):0};
+}
+
+export function createKineticText({root,text='',effect='rise',split='words',document:doc=root.ownerDocument}) {
+ const group=doc.createElement('span');group.style.cssText='display:inline;white-space:pre-wrap';root.append(group);
+ let signature='',nodes=[];
+ return {
+ render(seconds,{text:next=text,effect:treatment=effect,split:mode=split,...options}={}){
+ const key=JSON.stringify([next,mode]);
+ if(key!==signature){signature=key;group.replaceChildren();const units=mode==='characters'?(typeof Intl.Segmenter==='function'?[...new Intl.Segmenter(undefined,{granularity:'grapheme'}).segment(String(next))].map(s=>s.segment):Array.from(String(next))):String(next).split(/(\s+)/);nodes=units.map(unit=>{const node=doc.createElement('span');node.textContent=unit;node.style.cssText='display:inline-block;white-space:pre;transform-origin:50% 70%';group.append(node);return node;});}
+ let index=0;
+ for(const node of nodes){const blank=/^\s*$/.test(node.textContent),m=typeMotion(seconds,{...options,effect:treatment,index:blank?Math.max(0,index-1):index++});Object.assign(node.style,{opacity:String(m.opacity),transform:`translate(${m.x}px,${m.y}px) rotate(${m.rotate}deg) scale(${m.scale})`,clipPath:m.clip??'none',textShadow:m.extrusion?Array.from({length:Math.round(m.extrusion)},(_,i)=>`${i+1}px ${i+1}px 0 rgba(0,0,0,.32)`).join(','):'none'});}
+ },
+ bounds(){return nodes.filter(n=>n.textContent.trim()).map((n,i)=>({id:String(i),x:n.offsetLeft,y:n.offsetTop,width:n.offsetWidth,height:n.offsetHeight}));},
+ dispose(){group.remove();},
+ };
+}
diff --git a/packages/runtime/compositor.mjs b/packages/runtime/compositor.mjs
index 208b35a..3777a08 100644
--- a/packages/runtime/compositor.mjs
+++ b/packages/runtime/compositor.mjs
@@ -7,15 +7,16 @@ export function evaluateClip(studio,clip,time){
}
export function createCompositor(canvas,{templates,createRenderer,host}){
const ctx=canvas.getContext('2d',{alpha:true}),renderers=new Map();let chain=Promise.resolve(),generation=0;
- const draw=async(studio,time,{selected,timeline=false}={})=>{
- if(!Number.isFinite(time)||time<0)throw Error('Invalid render time');
+ const draw=async(studio,time,{selected,timeline=false,mediaTime=time}={})=>{
+ if(!Number.isFinite(time)||time<0||!Number.isFinite(mediaTime)||mediaTime<0)throw Error('Invalid render time');
const clips=timeline?studio.doc.clips.filter(c=>time>=c.start/HZ&&time<(c.start+c.duration)/HZ):[studio.clip(selected)];
const active=new Set(clips.map(c=>c.id));for(const [id,r]of renderers)if(!active.has(id)){await r.instance.dispose?.();renderers.delete(id)}
const first=clips[0],t=first&&templates[first.template];canvas.width=timeline?studio.doc.width:(t?.width??1280);canvas.height=timeline?studio.doc.height:(t?.height??720);ctx.clearRect(0,0,canvas.width,canvas.height);
for(const clip of clips){
const spec=templates[clip.template];let r=renderers.get(clip.id);if(!r){const surface=document.createElement('canvas');surface.width=spec.width??1280;surface.height=spec.height??720;const instance=await createRenderer(surface,{host,template:spec});if(typeof instance?.render!=='function')throw Error('Renderer must implement render(frame)');r={surface,instance};renderers.set(clip.id,r)}
const evaluated=evaluateClip(studio,clip,timeline?time:clip.start/HZ+time);
- const output=await r.instance.render({template:spec,time:evaluated.sourceTime,projectTime:time,nodes:evaluated.nodes,ports:evaluated.ports,host,clip});
+ const mediaSourceTime=evaluateClip(studio,clip,timeline?mediaTime:clip.start/HZ+mediaTime).sourceTime;
+ const output=await r.instance.render({template:spec,time:evaluated.sourceTime,mediaTime:mediaSourceTime,projectTime:time,nodes:evaluated.nodes,ports:evaluated.ports,host,clip});
const image=await r.instance.capture?.()??output??r.surface;
if(typeof image?.width!=='number'||typeof image?.height!=='number')throw Error('Renderer needs an image surface or capture() adapter');
ctx.save();const tr=clip.transform;ctx.globalAlpha=tr.opacity;ctx.translate(tr.x,tr.y);ctx.scale(tr.scale,tr.scale);ctx.drawImage(image,0,0,canvas.width,canvas.height);
diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs
index ae89fe9..9dbf7f0 100644
--- a/packages/runtime/editor.mjs
+++ b/packages/runtime/editor.mjs
@@ -1,15 +1,23 @@
import {normalizeObjectHierarchy,selectableObject,parentObjectId} from '../core/objects.mjs';
-import {createRendererCompositor} from './renderer-compositor.mjs';import {ptsIndex} from '../media/ports.mjs';
+import {createRendererCompositor} from './renderer-compositor.mjs';import {mediaFrameUrl} from '../media/frames.mjs';
import {Studio,clone,HZ} from '../core/index.mjs';import {createMediaHost} from '../media/browser.mjs';import {createAudioPlayback} from '../media/playback.mjs';import {createCompositor} from './compositor.mjs';
export async function mount({templates,createRenderer,scene,binding,initial,mediaCatalog={},assetIds=[],persistence=null,capture=false}){
const $=s=>document.querySelector(s);let canvas=$('#screen');
- if(scene){const stage=document.createElement('div');stage.id='screen';canvas.replaceWith(stage);canvas=stage;if(capture){stage.style.background='transparent';stage.style.borderRadius='0';document.documentElement.style.background='transparent';document.body.style.background='transparent';}}
+ if(scene){const stage=document.createElement('div');stage.id='screen';canvas.replaceWith(stage);canvas=stage;if(capture){stage.style.background='transparent';stage.style.borderRadius='0';document.documentElement.style.background='transparent';document.body.style.background='transparent';
+ // The stage is transparent where the scene draws nothing, so the editor's own chrome would be captured through it.
+ document.body.style.visibility='hidden';stage.style.visibility='visible';}}
let studio;
if(initial)studio=Studio.restore(initial,templates,binding);else{studio=new Studio(templates,{binding});studio.doc.clips=Object.keys(templates).map(id=>studio.make(id));studio.check(studio.doc);studio.base=clone(studio.doc)}
- let selected=studio.doc.clips[0]?.id,time=0,playing=false,last=0,timeline=false,revision=persistence?.revision,operations=Promise.resolve(),disposed=false;
+ let selected=studio.doc.clips[0]?.id,time=0,playing=false,last=0,timeline=false,pass='beauty',revision=persistence?.revision,operations=Promise.resolve(),disposed=false;
const host=createMediaHost(mediaCatalog),services={};
if(assetIds.length)services.asset=id=>{if(!assetIds.includes(id))throw Error('Undeclared asset: '+id);return '/__ef/source/'+encodeURIComponent(id);};
- if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';};
+ if(Object.keys(mediaCatalog).length){
+ // Facts about a declared asset, and the data derived from it (matte, depth, track, camera).
+ services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {sha256:a.sha256,pts:[...(a.pts??[])],type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};};
+ services.derived=(id,role,subject)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role&&mediaCatalog[key].derived.subject===subject);};
+ }
+ if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>mediaFrameUrl(mediaCatalog,id,time);
+ services.sourceFrame=(id,index)=>{const a=mediaCatalog[id];if(!a||!Number.isSafeInteger(index)||index<0||index>=a.pts.length)throw Error('Invalid declared source frame: '+id+':'+index);return a.url+String(index+1).padStart(6,'0')+'.png';};
const renderer=scene?createRendererCompositor(canvas,{scene,templates,services,capture}):createCompositor(canvas,{templates,createRenderer,host}),audio=createAudioPlayback(mediaCatalog);let selection=null,selectionVersion=0;
if(scene)canvas.addEventListener('pointerdown',async event=>{
const ticket=++selectionVersion;
@@ -26,7 +34,7 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi
const keySelection=event=>{if(scene&&selection&&(event.key==='Escape'||event.altKey&&event.key==='ArrowUp')){event.preventDefault();selectParent();}};
if(scene)document.addEventListener('keydown',keySelection);
const fail=e=>{$('#status').textContent=e.message;playing=false;audio.stop();$('#play').textContent='Play'};
- function draw(){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing})}
+ function draw({mediaTime}={}){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing,mediaTime,...(scene?{pass}:{})})}
function context(){return {...studio.capabilities(selected),baseRevision:persistence?revision:studio.revision,...(scene?{selection,objects:objectRows(),capture:{kind:'dom',selector:'#screen'}}:{})}}
function refresh(){
if(!studio.doc.clips.some(c=>c.id===selected))selected=studio.doc.clips[0]?.id;
@@ -66,5 +74,5 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi
$('#open').onchange=async e=>{try{studio=Studio.restore(await e.target.files[0].text(),templates,binding);refresh();await draw()}catch(e){fail(e)}};
$('#apply').onclick=()=>{try{const p=JSON.parse($('#proposal').value);edit(p.command,p.baseRevision,'model').catch(fail)}catch(e){fail(e)}};
async function loop(now){if(disposed)return;if(playing){try{time=(time+Math.max(0,Math.min(.1,(now-last)/1000)))%duration();$('#seek').value=time;await draw();let s=studio,t=time;if(!timeline){s=Object.create(studio);s.doc={...studio.doc,clips:[{...clip(),start:0}]}}if(playing)await audio.update(s,t,true);else audio.stop()}catch(e){fail(e)}}last=now;requestAnimationFrame(loop)}requestAnimationFrame(loop);
- refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;await draw()},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}};
+ refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;if(options.pass!==undefined){if(!scene&&options.pass!=='beauty')throw Error('Only renderer scenes draw control passes');pass=options.pass;}await draw({mediaTime:options.mediaTime})},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}};
}
diff --git a/packages/runtime/renderer-compositor.mjs b/packages/runtime/renderer-compositor.mjs
index b271465..40ee079 100644
--- a/packages/runtime/renderer-compositor.mjs
+++ b/packages/runtime/renderer-compositor.mjs
@@ -8,9 +8,10 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt
const residents=new Map();let chain=Promise.resolve(),disposed=false,lastRequest,renderVersion=0,pickVersion=0,activeJob,pendingJob,disposal;
stage.style.position=capture?'fixed':'relative';stage.style.overflow='hidden';
if(capture){stage.style.left='0';stage.style.top='0';stage.style.zIndex='2147483647';}
- async function draw(studio,time,{selected,timeline=false,playing=false}={}) {
+ async function draw(studio,time,{selected,timeline=false,playing=false,pass='beauty',mediaTime=time}={}) {
if(disposed)throw Error('Compositor disposed');
- if(!Number.isFinite(time)||time<0)throw Error('Invalid source time');
+ if(pass!=='beauty'&&!(scene.passes??[]).includes(pass))throw Error(`This scene does not declare a ${pass} pass`);
+ if(!Number.isFinite(time)||time<0||!Number.isFinite(mediaTime)||mediaTime<0)throw Error('Invalid source time');
const clips=timeline?studio.doc.clips.filter(c=>time>=c.start/HZ&&time<(c.start+c.duration)/HZ):[studio.clip(selected)];
const active=new Set(clips.map(c=>c.id));
for(const [id,r] of residents)if(!active.has(id)){await r.instance.dispose();r.layer.remove();residents.delete(id);}
@@ -31,12 +32,13 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt
const tr=clip.transform;resident.layer.style.opacity=String(tr.opacity);resident.layer.style.transform=`translate(${tr.x/width*100}%,${tr.y/height*100}%) scale(${tr.scale})`;
resident.root.style.transform=`scale(${stage.clientWidth/scene.width},${stage.clientHeight/scene.height})`;
const evaluated=evaluateClip(studio,clip,timeline?time:clip.start/HZ+time);
- const clock={frame:evaluated.sourceTime*scene.fps,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing};
+ const mediaSourceTime=evaluateClip(studio,clip,timeline?mediaTime:clip.start/HZ+mediaTime).sourceTime;
+ const clock={frame:evaluated.sourceTime*scene.fps,mediaTime:mediaSourceTime,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing,pass};
resident.clock=clock;
try {await resident.instance.render(clock,sampledRendererProps(scene,templates[clip.template],clip,evaluated.nodes));}
catch(error){residents.delete(clip.id);resident.layer.remove();await resident.instance.dispose().catch(()=>{});throw error;}
resident.overlays.style.transform=`scale(${stage.clientWidth/1920},${stage.clientHeight/1080})`;resident.overlays.replaceChildren();
- for(const node of evaluated.nodes.filter(n=>n.overlay)){
+ for(const node of pass==='beauty'?evaluated.nodes.filter(n=>n.overlay):[]){
const p=node.props;if(!p.visible||evaluated.sourceTimep.end)continue;
const label=document.createElement('div');label.textContent=p.text;
Object.assign(label.style,{position:'absolute',left:`${p.x-14}px`,top:`${p.y-10}px`,padding:'10px 14px',font:`600 ${p.size}px sans-serif`,color:p.color,opacity:p.opacity,whiteSpace:'pre',background:p.style==='plain'?'transparent':p.background,borderRadius:p.style==='pill'?`${p.size}px`:'10px'});
diff --git a/packages/runtime/renderer-host.mjs b/packages/runtime/renderer-host.mjs
index a2a142b..779d12e 100644
--- a/packages/runtime/renderer-host.mjs
+++ b/packages/runtime/renderer-host.mjs
@@ -11,7 +11,7 @@ export async function mountRenderer(scene,{root,props={},services={},timeoutMs=3
if (!root?.ownerDocument?.createElement || !root.append || !Number.isFinite(timeoutMs) || timeoutMs<=0) throw Error('Renderer host needs a DOM root and positive deadline');
const current=mergeProps(scene.defaultProps??{},props),readiness=new Readiness(),controller=new AbortController();
const supplied={};
- for (const key of ['asset','mediaFrame','captureSurface']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];}
+ for (const key of ['asset','mediaFrame','captureSurface','mediaInfo','derived','sourceFrame']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];}
// Each mount owns a replaceable surface. A late async frame can only write
// into its detached surface, never a retry's DOM. This is not a code sandbox.
const surface=root.ownerDocument.createElement('div');
diff --git a/packages/three/plate.mjs b/packages/three/plate.mjs
new file mode 100644
index 0000000..21285c3
--- /dev/null
+++ b/packages/three/plate.mjs
@@ -0,0 +1,189 @@
+/** Optional Three.js adapter for hybrid scenes: a code-rendered 3D object that
+ * has to sit INSIDE footage (a "plate") instead of on top of it.
+ *
+ * Not a restriction on renderers. Nothing here runs a model; mattes, depth,
+ * tracks and camera paths are inputs the host or the author supplies.
+ * See docs/hybrid-scenes.md. */
+import * as T from 'three';
+import {depthGlsl, validateDepthEncoding} from '../plate/depth.mjs';
+import {expandHighlights} from '../plate/color.mjs';
+import {idColor} from '../plate/passes.mjs';
+export const revision = 'editableframes.three-plate/1';
+const QUAD_VERTEX = 'varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,0.0,1.0);}';
+function fullscreen(material, renderOrder) {
+ const mesh = new T.Mesh(new T.PlaneGeometry(2, 2), material);
+ mesh.frustumCulled = false; mesh.renderOrder = renderOrder; mesh.userData.plateHelper = true;
+ return mesh;
+}
+/** A texture for plate data (matte, depth, normals): no colour management, no
+ * mipmaps. `image` is anything WebGL can upload. */
+export function dataTexture(image, {filter = T.LinearFilter} = {}) {
+ const texture = new T.Texture(image);
+ texture.colorSpace = T.NoColorSpace; texture.minFilter = texture.magFilter = filter; texture.generateMipmaps = false; texture.needsUpdate = true;
+ return texture;
+}
+/** Let the plate's own geometry hide the scene. Draws nothing visible; it
+ * writes the plate's depth into the depth buffer first, so every mesh is then
+ * depth-tested against the footage: a hand in front of the product covers it,
+ * a wall behind it does not.
+ *
+ * Needs WebGL2 and a perspective camera with the standard depth buffer (not
+ * logarithmic or reversed). Add the returned `mesh` to the scene; call
+ * `update(texture, camera)` whenever the plate frame or the camera changes. */
+export function createDepthOccluder(encoding) {
+ const material = new T.ShaderMaterial({
+ colorWrite: false, depthWrite: true, depthTest: true, depthFunc: T.AlwaysDepth,
+ uniforms: {map: {value: null}, near: {value: 0.1}, far: {value: 100}},
+ vertexShader: QUAD_VERTEX,
+ fragmentShader: `uniform sampler2D map;uniform float near;uniform float far;varying vec2 vUv;${depthGlsl(encoding)}
+void main(){float d=clamp(plateDistance(texture2D(map,vUv)),near,far);float ndc=(far+near)/(far-near)-(2.0*far*near)/((far-near)*d);gl_FragDepth=ndc*0.5+0.5;gl_FragColor=vec4(0.0);}`,
+ });
+ const mesh = fullscreen(material, -1e9);
+ return {
+ mesh,
+ update(texture, camera) {
+ if (!camera?.isPerspectiveCamera) throw Error('Depth occlusion needs a perspective camera');
+ material.uniforms.map.value = texture; material.uniforms.near.value = camera.near; material.uniforms.far.value = camera.far;
+ },
+ dispose() { mesh.geometry.dispose(); material.dispose(); },
+ };
+}
+/** Punch the plate's subject out of everything drawn so far. Where the matte
+ * is white the canvas becomes transparent, so the footage underneath shows
+ * through: the cheap way to put a 3D object BEHIND a matted subject when no
+ * depth is available. Coverage is all-or-nothing per pixel; it cannot place
+ * the object in front of one part of the subject and behind another. */
+export function createMatteHoldout() {
+ const material = new T.ShaderMaterial({
+ transparent: true, depthTest: false, depthWrite: false, blending: T.CustomBlending, blendEquation: T.AddEquation,
+ blendSrc: T.ZeroFactor, blendDst: T.OneMinusSrcAlphaFactor, blendSrcAlpha: T.ZeroFactor, blendDstAlpha: T.OneMinusSrcAlphaFactor,
+ uniforms: {map: {value: null}},
+ vertexShader: QUAD_VERTEX,
+ fragmentShader: 'uniform sampler2D map;varying vec2 vUv;void main(){vec3 m=texture2D(map,vUv).rgb;gl_FragColor=vec4(0.0,0.0,0.0,dot(m,vec3(0.2126,0.7152,0.0722)));}',
+ });
+ const mesh = fullscreen(material, 1e9);
+ return {mesh, update(texture) { material.uniforms.map.value = texture; }, dispose() { mesh.geometry.dispose(); material.dispose(); }};
+}
+/** Paint `source` into an equirectangular canvas `width` wide and `width / 2`
+ * high: as shot in front of the camera (u 0 to 0.5; Three's lookup puts -Z, into
+ * the picture, at u = 0.25) and mirrored behind it (u 0.5 to 1, centred on +Z).
+ * The mirror maps x to width - x, so the copy lands on the back half. A surface
+ * facing the camera reflects that back half, so leaving it empty turns a
+ * mirror-like product black. */
+export function paintPlatePanorama(context, source, width) {
+ const half = width / 2, height = width / 2;
+ context.setTransform(1, 0, 0, 1, 0, 0); context.drawImage(source, 0, 0, half, height);
+ context.setTransform(-1, 0, 0, 1, width, 0); context.drawImage(source, 0, 0, half, height);
+ context.setTransform(1, 0, 0, 1, 0, 0);
+}
+/** Light the scene with the plate itself. The frame is wrapped into a
+ * panorama (in front of the camera as shot, mirrored behind it), its clipped
+ * highlights are pushed above 1, and the result is prefiltered for physically
+ * based reflections. A metal object then reflects the footage it stands in.
+ *
+ * This is the standard stand-in when no real environment capture exists. It is
+ * plausible, not measured: what is behind the camera is invented by mirroring.
+ * Prefer a real `environment` asset for the plate when one exists.
+ *
+ * `update(source)` accepts anything a 2D canvas can draw and returns the
+ * environment texture; assign it to `scene.environment`. */
+export function createPlateEnvironment(renderer, {width = 256, knee = 0.8, boost = 6, document: doc = globalThis.document} = {}) {
+ const height = width / 2, canvas = doc.createElement('canvas'); canvas.width = width; canvas.height = height;
+ const context = canvas.getContext('2d', {willReadFrequently: true}), generator = new T.PMREMGenerator(renderer);
+ generator.compileEquirectangularShader();
+ let target;
+ return {
+ update(source) {
+ paintPlatePanorama(context, source, width);
+ const linear = expandHighlights(context.getImageData(0, 0, width, height).data, {knee, boost}), pixels = new Uint16Array(linear.length);
+ for (let i = 0; i < linear.length; i++) pixels[i] = T.DataUtils.toHalfFloat(Math.min(65000, linear[i]));
+ const texture = new T.DataTexture(pixels, width, height, T.RGBAFormat, T.HalfFloatType);
+ texture.flipY = true; texture.minFilter = texture.magFilter = T.LinearFilter; texture.generateMipmaps = false;
+ texture.colorSpace = T.LinearSRGBColorSpace; texture.mapping = T.EquirectangularReflectionMapping; texture.needsUpdate = true;
+ const next = generator.fromEquirectangular(texture); texture.dispose(); target?.dispose(); target = next;
+ return target.texture;
+ },
+ dispose() { target?.dispose(); generator.dispose(); },
+ };
+}
+/** Aim a directional light using `estimateKeyLight`'s result. `target` is the
+ * point the light should fall on; `strength` scales the final intensity. */
+export function applyKeyLight(light, estimate, {target = new T.Vector3(), distance = 6, strength = 2} = {}) {
+ light.position.set(...estimate.toward).multiplyScalar(distance).add(target);
+ light.target.position.copy(target); light.target.updateMatrixWorld();
+ light.color.setRGB(...estimate.color, T.LinearSRGBColorSpace);
+ // A flat, overcast plate has no key to speak of; a single hot source has a strong one.
+ light.intensity = strength * (0.25 + 0.75 * estimate.concentration);
+ return light;
+}
+/** Replay a sampled camera path (`sampleCameraPath`) on a perspective camera. */
+export function applyCameraSample(camera, sample) {
+ camera.position.set(...sample.position); camera.quaternion.set(...sample.quaternion);
+ if (camera.fov !== sample.fovY) { camera.fov = sample.fovY; camera.updateProjectionMatrix(); }
+ camera.updateMatrixWorld();
+}
+/** An invisible plane that only shows the shadows cast onto it, laid on a
+ * floor or table found in the plate (`fitGroundPlane`), in camera space. */
+export function createShadowCatcher(plane, {size = 40, opacity = 0.35} = {}) {
+ const mesh = new T.Mesh(new T.PlaneGeometry(size, size), new T.ShadowMaterial({opacity}));
+ mesh.quaternion.setFromUnitVectors(new T.Vector3(0, 0, 1), new T.Vector3(...plane.normal).normalize());
+ mesh.position.set(...plane.point); mesh.receiveShadow = true; mesh.userData.plateHelper = true;
+ return mesh;
+}
+const RAW_VERTEX = 'varying vec3 vView;void main(){vec4 mv=modelViewMatrix*vec4(position,1.0);vView=mv.xyz;gl_Position=projectionMatrix*mv;}';
+// ShaderMaterial bypasses tone mapping and output colour conversion, so these
+// passes write the exact bytes a decoder expects.
+const rawColor = rgb => new T.ShaderMaterial({uniforms: {color: {value: new T.Vector3(...rgb)}}, vertexShader: RAW_VERTEX, fragmentShader: 'uniform vec3 color;void main(){gl_FragColor=vec4(color,1.0);}'});
+/** Draw the scene as one control pass instead of as a picture.
+ *
+ * clay matte grey under the scene's own lights: shape, camera and shading
+ * depth distance as grey, white = near, in `encoding` (default inverse)
+ * normal camera-space normals
+ * id one flat colour per object in `ids` (decode with `idFromColor`)
+ * matte white silhouette on a transparent background
+ *
+ * Objects are named by `userData.passId` on a mesh or the nearest ancestor, else
+ * the mesh's own `name`. Helper meshes this module creates, and anything with
+ * `userData.passExclude`, are left out. Edges are antialiased, so id and depth
+ * values are exact only away from silhouettes. Scene state is restored. */
+export function renderPass(renderer, scene, camera, pass, {ids = [], encoding} = {}) {
+ if (pass === 'beauty') { renderer.render(scene, camera); return; }
+ if (!['clay', 'depth', 'normal', 'id', 'matte'].includes(pass)) throw Error('Unknown pass: ' + pass);
+ const depth = validateDepthEncoding(encoding ?? {kind: 'inverse', near: camera.near, far: camera.far});
+ const saved = {background: scene.background, override: scene.overrideMaterial, clear: renderer.getClearColor(new T.Color()), alpha: renderer.getClearAlpha(), tone: renderer.toneMapping}, swapped = [], hidden = [], made = [];
+ const passId = object => { for (let o = object; o; o = o.parent) if (typeof o.userData?.passId === 'string') return o.userData.passId; return object.name; };
+ const use = (mesh, material) => { swapped.push([mesh, mesh.material]); mesh.material = material; };
+ try {
+ scene.background = null; scene.overrideMaterial = null; renderer.setClearColor(0x000000, 0);
+ const shared = pass === 'clay' ? new T.MeshStandardMaterial({color: 0xb8b8b8, roughness: 0.85, metalness: 0})
+ : pass === 'normal' ? new T.MeshNormalMaterial()
+ : pass === 'matte' ? rawColor([1, 1, 1])
+ : pass === 'depth' ? new T.ShaderMaterial({vertexShader: RAW_VERTEX, fragmentShader: `varying vec3 vView;${depthEncodeGlsl(depth)}void main(){gl_FragColor=vec4(vec3(plateCode(-vView.z)),1.0);}`})
+ : null;
+ if (shared) made.push(shared);
+ if (pass !== 'clay') renderer.toneMapping = T.NoToneMapping;
+ const byId = new Map();
+ scene.traverse(object => {
+ if (!object.isMesh && !object.isLine && !object.isPoints && !object.isSprite) return;
+ if (object.userData.plateHelper || object.userData.passExclude || !object.isMesh) { if (object.visible) { hidden.push(object); object.visible = false; } return; }
+ if (shared) { use(object, shared); return; }
+ const index = ids.indexOf(passId(object));
+ if (index < 0) { if (object.visible) { hidden.push(object); object.visible = false; } return; }
+ if (!byId.has(index)) { const material = rawColor(idColor(index).map(v => v / 255)); byId.set(index, material); made.push(material); }
+ use(object, byId.get(index));
+ });
+ renderer.render(scene, camera);
+ } finally {
+ for (const [mesh, material] of swapped) mesh.material = material;
+ for (const object of hidden) object.visible = true;
+ for (const material of made) material.dispose();
+ scene.background = saved.background; scene.overrideMaterial = saved.override; renderer.setClearColor(saved.clear, saved.alpha); renderer.toneMapping = saved.tone;
+ }
+}
+function depthEncodeGlsl(encoding) {
+ // Mirrors encodeDepth() in ../plate/depth.mjs, so a depth pass and a depth plate share one convention.
+ const {kind, near, far} = encoding, f = v => Number(v).toPrecision(9).replace(/^(-?\d+)$/, '$1.0');
+ return kind === 'inverse'
+ ? `float plateCode(float d){d=clamp(d,${f(near)},${f(far)});return (1.0/d-${f(1 / far)})/${f(1 / near - 1 / far)};}`
+ : `float plateCode(float d){d=clamp(d,${f(near)},${f(far)});return (${f(far)}-d)/${f(far - near)};}`;
+}
diff --git a/scripts/audio.mjs b/scripts/audio.mjs
index 225f8c8..f9adb00 100644
--- a/scripts/audio.mjs
+++ b/scripts/audio.mjs
@@ -1,5 +1,5 @@
import {run,ffmpeg} from './process.mjs';import {audioPlan} from '../packages/media/audio-plan.mjs';
-export function tempoFilters(rate){const f=[];while(rate>2){f.push('atempo=2');rate/=2}while(rate<.5){f.push('atempo=0.5');rate*=2}f.push('atempo='+rate);return f.join(',')}
+export function tempoFilters(rate){if(rate===1)return 'anull';const f=[];while(rate>2){f.push('atempo=2');rate/=2}while(rate<.5){f.push('atempo=0.5');rate*=2}f.push('atempo='+rate);return f.join(',')}
export async function mixAudio(d,catalog,output,duration,{signal}={}){
const tracks=audioPlan(d.studio,catalog);if(!tracks.length)return {tracks:0};
const args=['-v','error','-n','-f','lavfi','-i','anullsrc=r=48000:cl=stereo'];
diff --git a/scripts/browser.mjs b/scripts/browser.mjs
new file mode 100644
index 0000000..ce08b0c
--- /dev/null
+++ b/scripts/browser.mjs
@@ -0,0 +1,14 @@
+import path from 'node:path';
+import {statSync} from 'node:fs';
+
+// Explicit opt-in to a locally managed Chromium; never download or silently
+// substitute a different browser when the Playwright-managed one is missing.
+export function chromiumOptions(env = process.env) {
+ const executablePath = env.EDITABLEFRAMES_CHROMIUM_EXECUTABLE;
+ if (!executablePath) return {};
+ if (!path.isAbsolute(executablePath)) throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE must be an absolute path');
+ let file;
+ try { file = statSync(executablePath); } catch { throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE does not name an existing file'); }
+ if (!file.isFile()) throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE must name a browser executable file');
+ return {executablePath};
+}
diff --git a/scripts/demo-hybrid.mjs b/scripts/demo-hybrid.mjs
new file mode 100644
index 0000000..36feb57
--- /dev/null
+++ b/scripts/demo-hybrid.mjs
@@ -0,0 +1,29 @@
+import fs from 'node:fs/promises';import path from 'node:path';import {run,ffmpeg} from './process.mjs';import {fileHash} from './media.mjs';
+// A diagnostic plate with a known answer, not footage: a warm wall with a bright
+// window (the light), a slate board drifting right (a surface to pin a screen
+// to) and a dark bar sweeping across in front of everything (the occluder).
+// Its matte, depth and track are generated from the same formulas, so tests can
+// state where every pixel must land. Real plates get these from other tools.
+export const HYBRID_DEMO={width:640,height:360,fps:24,seconds:3,board:{y:50,width:160,height:90,x:frame=>Math.floor(430+frame/2)},bar:{width:70,x:frame=>Math.floor(60+150*frame/24)},depth:{kind:'inverse',near:1.2,far:12,packing:'gray8'},codes:{wall:38,board:51,bar:230},colors:{wall:'0x9a5a32',window:'0xfff2d0',board:'0x3a3f4a',bar:'0x12324a'}};
+export async function createHybridDemo(dir){
+ const d=HYBRID_DEMO,size=`${d.width}x${d.height}`,common=`r=${d.fps}:d=${d.seconds}`,gray=v=>'0x'+v.toString(16).padStart(2,'0').repeat(3);
+ await fs.mkdir(path.join(dir,'assets'),{recursive:true});
+ const source=(color,s)=>`color=c=${color}:s=${s}:${common},format=gbrp`;
+ // overlay truncates x to whole pixels in a planar RGB format, matching Math.floor above.
+ const boardX=`x='430+t*${d.fps}/2'`,barX=`x='60+150*t'`;
+ const graphs={
+ 'plate.mp4':`${source(d.colors.wall,size)}[w];${source(d.colors.window,'120x90')}[n];${source(d.colors.board,`${d.board.width}x${d.board.height}`)}[b];${source(d.colors.bar,`${d.bar.width}x${d.height}`)}[r];[w][n]overlay=x=40:y=30:format=gbrp[a];[a][b]overlay=${boardX}:y=${d.board.y}:format=gbrp[c];[c][r]overlay=${barX}:y=0:format=gbrp[v]`,
+ 'plate-matte.mp4':`${source('black',size)}[w];${source('white',`${d.bar.width}x${d.height}`)}[r];[w][r]overlay=${barX}:y=0:format=gbrp[v]`,
+ 'plate-depth.mp4':`${source(gray(d.codes.wall),size)}[w];${source(gray(d.codes.board),`${d.board.width}x${d.board.height}`)}[b];${source(gray(d.codes.bar),`${d.bar.width}x${d.height}`)}[r];[w][b]overlay=${boardX}:y=${d.board.y}:format=gbrp[c];[c][r]overlay=${barX}:y=0:format=gbrp[v]`,
+ };
+ for(const [name,graph]of Object.entries(graphs))await run(ffmpeg(),['-v','error','-n','-filter_complex',graph,'-map','[v]','-frames:v',String(d.fps*d.seconds),'-c:v','libx264','-qp','0','-pix_fmt','yuv444p',path.join(dir,'assets',name)]);
+ const frames=Array.from({length:d.fps*d.seconds},(_,frame)=>{const x=d.board.x(frame),{y,width,height}=d.board;return {frame,quad:[[x,y],[x+width,y],[x+width,y+height],[x,y+height]],confidence:1}});
+ await fs.writeFile(path.join(dir,'assets','board-track.json'),JSON.stringify({version:1,kind:'planar',width:d.width,height:d.height,frameRate:{num:d.fps,den:1},frames}));
+ const sha=name=>fileHash(path.join(dir,'assets',name)),plate=await sha('plate.mp4'),derived=(role,extra={})=>({derived:{of:'plate',role,sourceSha256:plate,...extra}});
+ await fs.writeFile(path.join(dir,'assets.json'),JSON.stringify({version:1,assets:{
+ plate:{src:'assets/plate.mp4',type:'video',sha256:plate},
+ 'plate-matte':{src:'assets/plate-matte.mp4',type:'video',sha256:await sha('plate-matte.mp4'),...derived('matte')},
+ 'plate-depth':{src:'assets/plate-depth.mp4',type:'video',sha256:await sha('plate-depth.mp4'),...derived('depth',{encoding:d.depth})},
+ 'board-track':{src:'assets/board-track.json',type:'data',sha256:await sha('board-track.json'),...derived('track')},
+ }},null,2));
+}
diff --git a/scripts/jobs.mjs b/scripts/jobs.mjs
new file mode 100644
index 0000000..340d3e6
--- /dev/null
+++ b/scripts/jobs.mjs
@@ -0,0 +1,89 @@
+// Render job records, and recovery after a death that ran no cleanup (SIGKILL, power loss, a crash).
+//
+// What a job owns is decided when it starts, not guessed afterwards:
+// - one record, written before anything it names exists, in a directory only this user can write. Project
+// folders are copied, downloaded and shared; nothing inside a project can direct a deletion or a signal.
+// - one temporary root named after the job's random id. The CLI points TMPDIR at it, so the decoded media,
+// the browser profile and every other temporary file of the job and its children are inside it.
+// - one frame directory next to the output, also named after the id.
+// A browser started by the job therefore carries the job's id in its own command line (--user-data-dir).
+// That, not a pid, is the evidence of ownership: no other process is started with that path.
+import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {randomUUID,createHash} from 'node:crypto';
+import {acquireLock,probe,processTable} from './lock.mjs';
+
+const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+export async function registry({create=true}={}){
+ const dir=process.env.EDITABLEFRAMES_STATE_DIR||path.join(os.homedir(),'.editableframes','run');
+ if(create)await fs.mkdir(dir,{recursive:true,mode:0o700});const st=await fs.lstat(dir).catch(e=>{if(!create&&e.code==='ENOENT')return null;throw e});if(!st)return null;
+ if(!st.isDirectory()||process.getuid&&(st.uid!==process.getuid()||st.mode&0o022))throw Error('Job records need a directory owned and writable only by this user: '+dir);
+ return fs.realpath(dir);
+}
+export async function beginJob(projectDir,output){
+ const state=await registry(),id=randomUUID(),file=path.join(state,'jobs',id+'.json');output=path.resolve(output);
+ const record={version:1,id,owner:await probe.self().catch(()=>null),project:await fs.realpath(projectDir),output,tmp:path.join(await fs.realpath(os.tmpdir()),'ef-job-'+id),temp:path.join(path.dirname(output),'.editableframe-render-'+id),created:new Date().toISOString()};
+ // The record is complete when it appears, and it appears before anything it names.
+ await fs.mkdir(path.dirname(file),{recursive:true});await fs.writeFile(file+'.tmp',JSON.stringify(record,null,1));await fs.rename(file+'.tmp',file);await fs.mkdir(record.tmp);
+ return {id,tmp:record.tmp,temp:record.temp,record,
+ // Normal end, success or failure. The record is dropped only when nothing it names is left.
+ async finish(){
+ const gone=await fs.rm(record.tmp,{recursive:true,force:true,maxRetries:5,retryDelay:100}).then(()=>true,()=>false);
+ if(gone&&!await exists(record.temp))await fs.rm(file,{force:true});
+ }};
+}
+const exists=p=>fs.lstat(p).then(()=>true,()=>false);
+const isBrowser=(row,job)=>row.command.includes('--user-data-dir='+job.tmp+path.sep)&&!row.command.includes('--type=');
+const sleep=ms=>new Promise(r=>setTimeout(r,ms));
+
+// SIGTERM one process, only if it is still exactly the process that was just examined. Never SIGKILL.
+async function stop(row){
+ const now=(await processTable([row.pid])).find(r=>r.pid===row.pid);
+ if(!now||now.lstart!==row.lstart||now.command!==row.command)return 'gone';
+ process.kill(row.pid,'SIGTERM');
+ for(let i=0;i<50;i++){await sleep(100);if(!(await processTable([row.pid])).some(r=>r.pid===row.pid&&r.lstart===row.lstart))return 'terminated'}
+ return 'still running after SIGTERM';
+}
+async function removeDir(p){
+ const st=await fs.lstat(p).catch(()=>null);if(!st)return 'absent';
+ if(!st.isDirectory())return 'left: not a directory';
+ await fs.rm(p,{recursive:true,force:true,maxRetries:5,retryDelay:100});return 'removed';
+}
+// Recover the dead jobs of ONE project. Jobs whose owner is alive, or cannot be verified, are not touched.
+// Without `stopBrowsers` nothing is signalled: a job whose processes are still running is left whole and
+// reported. With it, the job's own orphaned browser is asked to exit (SIGTERM).
+export async function recoverJobs(projectDir,{stopBrowsers=false,dryRun=false}={}){
+ const state=await registry({create:!dryRun});if(!state)return [];const project=await fs.realpath(projectDir),jobs=path.join(state,'jobs'),report=[];
+ const names=(await fs.readdir(jobs).catch(()=>[])).filter(n=>n.endsWith('.json')&&UUID.test(n.slice(0,-5))).sort();
+ if(!names.length)return report;
+ // One recoverer per project. The receipt is the only shared NAME recovery removes: with recoverers
+ // serialized, and a new render unable to create a receipt that exists, check-then-remove cannot hit a newcomer's.
+ let lock;if(!dryRun)try{lock=await acquireLock(path.join(state,'locks',createHash('sha256').update(project).digest('hex').slice(0,32)),{what:'recovery'})}catch(e){if(e.code==='ELOCKED')return [{action:'skipped: '+e.message}];throw e}
+ try{
+ await lock?.reclaim();
+ for(const name of names){
+ const file=path.join(jobs,name),id=name.slice(0,-5);let job;try{job=JSON.parse(await fs.readFile(file,'utf8'))}catch{continue}
+ if(job.project!==project)continue;
+ const r={job:id,owner:job.owner?.pid??null};report.push(r);
+ const s=await probe.state(job.owner);
+ if(s!=='dead'){r.action=s==='alive'?'skipped: owner is running':'skipped: owner cannot be verified from this machine';continue}
+ if(job.id!==id||path.basename(String(job.tmp))!=='ef-job-'+id||path.basename(String(job.temp))!=='.editableframe-render-'+id||!path.isAbsolute(String(job.output))){r.action='left: record does not describe this job';continue}
+ let rows;try{rows=await processTable()}catch{r.action='left: cannot list processes';continue}
+ const using=()=>rows.filter(p=>p.command.includes(id)&&p.pid!==process.pid);
+ if(dryRun){r.action='would recover';r.processes=using().map(p=>p.pid);r.dirs=[job.tmp,job.temp];continue}
+ if(stopBrowsers&&using().length){
+ r.stopped=[];for(const p of using().filter(p=>isBrowser(p,job)))r.stopped.push({pid:p.pid,result:await stop(p)});
+ for(let i=0;i<30;i++){rows=await processTable();if(!using().length)break;await sleep(100)}
+ }
+ // The owner is dead, so nothing new can start. Whatever still names the job may be writing into its directories.
+ if(using().length){r.action='left: still used by running processes';r.processes=using().map(p=>({pid:p.pid,browser:isBrowser(p,job)}));r.dirs=[job.tmp,job.temp];continue}
+ // A receipt this job reserved for an output it never published is a dead reservation.
+ const receiptFile=job.output+'.json',receipt=await fs.readFile(receiptFile,'utf8').then(JSON.parse).catch(()=>null);
+ if(!receipt)r.receipt='absent';else if(receipt.job!==id)r.receipt='left: belongs to another render';
+ else if(!await exists(job.output)){await lock.assertHeld();await fs.rm(receiptFile);r.receipt='removed: reserved, never published'}
+ else{const [a,b]=await Promise.all([fs.stat(job.output),fs.stat(path.join(job.temp,'output'+path.extname(job.output))).catch(()=>null)]);r.receipt=b&&a.ino!==b.ino?'left: the output is not the file this render made':'kept: output was published'}
+ r.dirs={[job.tmp]:await removeDir(job.tmp),[job.temp]:await removeDir(job.temp)};
+ r.action='recovered';
+ await fs.mkdir(path.join(state,'recovered'),{recursive:true});await fs.writeFile(path.join(state,'recovered',name),JSON.stringify({...job,recovery:{at:new Date().toISOString(),...r}},null,1));await fs.rm(file);
+ }
+ }finally{await lock?.release()}
+ return report;
+}
diff --git a/scripts/lock.mjs b/scripts/lock.mjs
new file mode 100644
index 0000000..ba02192
--- /dev/null
+++ b/scripts/lock.mjs
@@ -0,0 +1,110 @@
+// A crash-safe exclusive lock whose stale state is taken over without deleting or rewriting anything.
+//
+// A lock that is a single file has to be REMOVED before a dead owner's successor can create it, and every
+// way of removing it races: the contender decides from what it read, and by the time it unlinks or renames
+// the name, the name may belong to a live successor. Re-reading first only narrows that window.
+//
+// Here the lock is a chain of generations in one directory:
+// 000000000007.json owner record, created complete by hard link (fails if the name exists), never rewritten
+// 000000000007.released the owner's release marker
+// 000000000007.recovered a later holder finished cleaning up after this dead owner
+// Only the HIGHEST generation matters. It is free when released, held when its owner is alive, and stale
+// when its owner is provably dead. Acquiring is always the exclusive creation of highest+1, so taking over
+// a stale lock is the same single atomic step as taking a free one, and exactly one contender can win it.
+// Nothing a contender does can damage a live holder, because no step removes or replaces a holder's record.
+import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {execFile} from 'node:child_process';import {randomUUID} from 'node:crypto';
+
+// ---- process identity -------------------------------------------------------------------------------
+// (host, pid, start time) names a process; argv is kept for the stricter match signalling needs. Start time
+// is read with TZ=UTC and LC_ALL=C: `ps` prints it in local time and language, so two processes with
+// different environments would otherwise disagree about the same live process.
+const ROW=/^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+(.*)$/;
+export function processTable(pids){
+ if(process.platform==='win32')return Promise.reject(Error('Process identity is not available on win32'));
+ return new Promise((resolve,reject)=>execFile('ps',[...(pids?['-p',pids.join(',')]:['-A']),'-ww','-o','pid=,ppid=,lstart=,command='],{timeout:10000,maxBuffer:64*1024*1024,env:{...process.env,TZ:'UTC',LC_ALL:'C'}},(e,out)=>{
+ if(e&&!(pids&&e.code===1))return reject(e); // with -p, exit 1 means none of them is running
+ resolve(String(out).split('\n').map(l=>ROW.exec(l)).filter(Boolean).map(m=>({pid:Number(m[1]),ppid:Number(m[2]),lstart:m[3].replace(/\s+/g,' '),command:m[4]})));
+ }));
+}
+let self;
+export const selfIdentity=()=>self??=(async()=>{
+ const row=(await processTable([process.pid])).find(r=>r.pid===process.pid);if(!row)throw Error('ps cannot see this process');
+ return {host:os.hostname(),ns:await fs.readlink('/proc/self/ns/pid').catch(()=>null),pid:row.pid,lstart:row.lstart,command:row.command};
+})();
+// 'alive' | 'dead' | 'unknown'. 'dead' needs positive proof: same host and pid namespace, and a `ps` that
+// demonstrably sees this process reports no process with that pid and start time. Everything else,
+// including another machine sharing the folder, a sandboxed `ps` and Windows, is 'unknown'.
+export async function ownerState(owner){
+ try{
+ const me=await selfIdentity();
+ if(!owner||owner.host!==me.host||(owner.ns??null)!==me.ns||!Number.isSafeInteger(owner.pid)||owner.pid<2||typeof owner.lstart!=='string')return 'unknown';
+ const rows=await processTable([owner.pid,process.pid]);
+ if(!rows.some(r=>r.pid===me.pid&&r.lstart===me.lstart))return 'unknown';
+ return rows.some(r=>r.pid===owner.pid&&r.lstart===owner.lstart)?'alive':'dead';
+ }catch{return 'unknown'}
+}
+// Indirection so tests can simulate several owners, and their deaths, inside one process.
+export const probe={self:selfIdentity,state:ownerState};
+
+// ---- generation chain -------------------------------------------------------------------------------
+const NAME=/^(\d{12})\.(json|released|recovered)$/,name=g=>String(g).padStart(12,'0');
+async function scan(dir){
+ const names=new Set(await fs.readdir(dir)),owned=[];
+ for(const n of names){const m=NAME.exec(n);if(m&&m[2]==='json')owned.push(Number(m[1]))}
+ return {names,gens:owned.sort((a,b)=>a-b),top:owned.length?Math.max(...owned):0};
+}
+// The name a holder gives its own leftovers; null for a record that is not a well-formed one.
+export const recordId=r=>Number.isSafeInteger(r?.gen)&&/^[0-9a-f-]{36}$/.test(r?.token)?name(r.gen)+'-'+r.token:null;
+export class LockedError extends Error{constructor(message,holder){super(message);this.code='ELOCKED';this.holder=holder}}
+
+export async function acquireLock(dir,{what='edit'}={}){
+ await fs.mkdir(dir,{recursive:true});
+ const owner=await probe.self().catch(()=>null),token=randomUUID();
+ for(let attempt=0;attempt<16;attempt++){
+ const seen=await scan(dir),top=seen.top;
+ if(top&&!seen.names.has(name(top)+'.released')){
+ let held;try{held=JSON.parse(await fs.readFile(path.join(dir,name(top)+'.json'),'utf8'))}catch(e){if(e.code==='ENOENT')continue;held=null}
+ const s=await probe.state(held?.owner);
+ if(s==='alive')throw new LockedError(`Another ${what} is active; retry after it finishes`,held);
+ if(s!=='dead')throw new LockedError(`Another ${what} may be active: its owner cannot be verified from this machine. If none is running anywhere, create the empty file ${path.join(dir,name(top)+'.released')}`,held);
+ }
+ const gen=top+1,file=path.join(dir,name(gen)+'.json'),temp=path.join(dir,'.new-'+token+'-'+attempt);
+ await fs.writeFile(temp,JSON.stringify({version:1,gen,token,owner,what,acquired:new Date().toISOString()}),{flag:'wx'});
+ // The whole acquisition: an exclusive create of the next generation, already complete when it appears.
+ try{await fs.link(temp,file)}catch(e){if(e.code==='EEXIST'||e.code==='ENOENT')continue;throw e}finally{await fs.rm(temp,{force:true})}
+ // A holder may delete generations below its own. A contender that stalled across that cleanup can create
+ // a number that is no longer the highest; it then holds nothing, and withdraws.
+ if((await scan(dir)).top!==gen){await fs.rm(file,{force:true});continue}
+ return handle(dir,gen,token,owner);
+ }
+ throw new LockedError(`Could not acquire the ${what} lock: too much contention`);
+}
+function handle(dir,gen,token,owner){
+ const base=g=>path.join(dir,name(g));let released=false;
+ return {dir,gen,token,owner,id:recordId({gen,token}),
+ // Before publishing, a holder checks that nobody superseded it. That can only happen if this live
+ // process was judged dead, which `ownerState` is built not to do; the check bounds the damage if it does.
+ async assertHeld(){if(released||(await scan(dir)).top!==gen)throw Error('This process no longer holds the lock')},
+ async release(){if(released)return;released=true;await fs.writeFile(base(gen)+'.released','')},
+ // Run by the holder only. Calls clean(record) for each earlier generation whose owner died without
+ // releasing; `clean` returns {complete,...}. A generation is forgotten only once released or completely
+ // cleaned, so a crash at any point here is repeated by the next holder.
+ async reclaim(clean=async()=>({complete:true})){
+ const seen=await scan(dir),report=[],earlier=new Set();
+ for(const n of seen.names){const m=NAME.exec(n);if(m&&Number(m[1])a-b)){
+ if(seen.names.has(name(g)+'.json')&&!seen.names.has(name(g)+'.released')&&!seen.names.has(name(g)+'.recovered')){
+ let record;try{record=JSON.parse(await fs.readFile(base(g)+'.json','utf8'))}catch{record=null}
+ const s=await probe.state(record?.owner);
+ if(s!=='dead'){report.push({gen:g,action:'left: owner '+(s==='alive'?'is alive':'cannot be verified')});continue}
+ const result=await clean(record);report.push({gen:g,owner:record.owner.pid,...result});
+ if(!result.complete)continue;
+ await fs.writeFile(base(g)+'.recovered',JSON.stringify(result));
+ }
+ for(const suffix of ['.json','.released','.recovered'])await fs.rm(base(g)+suffix,{force:true});
+ }
+ // Half-made records of contenders that died. Removing a live contender's only makes it retry.
+ for(const n of seen.names)if(n.startsWith('.new-')&&!n.startsWith('.new-'+token))await fs.rm(path.join(dir,n),{force:true});
+ return report;
+ }};
+}
diff --git a/scripts/media.mjs b/scripts/media.mjs
index 21e7764..8d353d8 100644
--- a/scripts/media.mjs
+++ b/scripts/media.mjs
@@ -1,40 +1,80 @@
import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {createHash} from 'node:crypto';import {createReadStream} from 'node:fs';
-import {run,ffmpeg,ffprobe} from './process.mjs';
+import {run,ffmpeg,ffprobe} from './process.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validatePreparedAnalysis} from '../packages/plate/prepared.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs';
export async function fileHash(file){const h=createHash('sha256');for await(const chunk of createReadStream(file))h.update(chunk);return h.digest('hex')}
+export function checkDeclaration(id,a){
+ if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id)||!['video','audio','image','data'].includes(a.type)||typeof a.src!=='string'||path.isAbsolute(a.src)||a.src.split(/[\\/]/).some(p=>p==='..'||p.startsWith('.'))||!/^[a-f0-9]{64}$/.test(a.sha256))throw Error('Invalid asset declaration: '+id);
+}
+// The byte-level checks every reader applies. The importer runs them on the staged copy BEFORE publishing it.
+export async function checkBytes(id,a,file){
+ if(await fileHash(file)!==a.sha256)throw Error('Asset content changed: '+id+'; import it as a new immutable asset');
+ // `data` is small JSON a renderer reads (a track, a camera path); it is never decoded as media.
+ if(a.type==='data'){if((await fs.stat(file)).size>8*1024**2)throw Error('Data asset exceeds 8 MiB: '+id);let json;try{json=JSON.parse(await fs.readFile(file,'utf8'))}catch{throw Error('Data asset is not JSON: '+id)}if(a.derived?.role==='analysis')validatePreparedAnalysis(json);if(a.derived?.role==='track')validateTrack(json);if(a.derived?.role==='camera')validateCameraPath(json);}
+}
+// Import preflight for media: (1) a strict decode of every stream, which refuses a file the decoder reports
+// errors in even where it would still produce some frames (a truncated faststart MP4 decodes 13 of 24);
+// (2) the exact preparation a render performs, on this asset and the assets it is derived from.
+export async function preflightMedia(id,asset,related={},{signal,root}={}){
+ if(asset.type==='data'&&asset.derived?.role!=='analysis')return {type:'data'};
+ try{if(asset.type!=='data')await run(ffmpeg(),['-nostdin','-v','error','-xerror','-i',asset.file,'-map','0:v?','-map','0:a?','-f','null','-'],{signal,timeout:600000})}
+ catch(e){throw Error('Asset failed a strict decode: '+id+': '+String(e.message).split('\n').filter(Boolean).slice(0,2).join(' '))}
+ const media=await prepareMedia({...related,[id]:asset},{signal,root});
+ try{const c=media.catalog[id];return {type:c.type,frames:c.pts.length,duration:c.duration,audio:c.audio,width:c.width,height:c.height}}finally{await media.close()}
+}
export async function readAssets(dir){
let manifest;try{manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'))}catch(e){if(e.code==='ENOENT')return {};throw e}
if(manifest.version!==1 || !manifest.assets || Array.isArray(manifest.assets))throw Error('Invalid assets manifest');
const assets={};for(const [id,a]of Object.entries(manifest.assets)){
- if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id)||!['video','audio','image'].includes(a.type)||typeof a.src!=='string'||path.isAbsolute(a.src)||a.src.split(/[\\/]/).some(p=>p==='..'||p.startsWith('.'))||!/^[a-f0-9]{64}$/.test(a.sha256))throw Error('Invalid asset declaration: '+id);
+ checkDeclaration(id,a);
const file=await fs.realpath(path.join(dir,a.src));if(!file.startsWith(dir+path.sep))throw Error('Asset escapes project: '+id);
- if(await fileHash(file)!==a.sha256)throw Error('Asset content changed: '+id+'; import it as a new immutable asset');
+ await checkBytes(id,a,file);
assets[id]={...a,file};
- }return assets;
+ }
+ // Mattes, depth, tracks and camera paths are pinned to the exact bytes they were computed from.
+ validateDerived(assets);return assets;
}
-export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxFrames=18000}={}){
- const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-media-')),catalog={},frozenAssets={};let budget=0;
+export async function prepareMedia(assets,{signal,root,maxDecodedBytes=8*1024**3,maxFrames=18000}={}){
+ const dir=await fs.mkdtemp(path.join(root??os.tmpdir(),'ef-media-')),catalog={},frozenAssets={};let budget=0;
try{await fs.mkdir(path.join(dir,'sources'));for(const [id,original]of Object.entries(assets)){
const file=path.join(dir,'sources',id+path.extname(original.file));await fs.copyFile(original.file,file);if(await fileHash(file)!==original.sha256)throw Error('Asset changed while preparing: '+id);const a={...original,file};frozenAssets[id]=a;
+ if(a.type==='data'){catalog[id]={type:'data',sha256:a.sha256,derived:a.derived,audio:false,pts:[],url:'/__ef/source/'+id};continue}
const info=JSON.parse((await run(ffprobe(),['-v','error','-show_streams','-show_format','-of','json',a.file],{signal})).toString());
const v=info.streams.find(s=>s.codec_type==='video'),astream=info.streams.find(s=>s.codec_type==='audio'),audio=!!astream;
let pts=[],duration=Number(info.format.duration??v?.duration??0);
if(a.type!=='audio'){
if(!v)throw Error('Asset has no video/image stream: '+id);
if(v.width>4096||v.height>4096)throw Error('Media exceeds 4096-pixel decode limit');
- const data=JSON.parse((await run(ffprobe(),['-v','error','-select_streams','v:0','-show_frames','-show_entries','frame=best_effort_timestamp_time,pkt_duration_time','-of','json',a.file],{signal})).toString());
+ // Integer ticks in the stream's time base, not `*_time` seconds: ffprobe prints those to six
+ // decimals, so 1/24 s reads 0.041667, later than the frame really is, and a third of the
+ // frames of a 24 or 30 fps clip were looked up as their predecessor.
+ const [tn,td]=String(v.time_base??'').split('/').map(Number);
+ if(!(Number.isSafeInteger(tn)&&Number.isSafeInteger(td)&&tn>0&&td>0))throw Error('Media has no stream time base: '+id);
+ const data=JSON.parse((await run(ffprobe(),['-v','error','-select_streams','v:0','-show_frames','-show_entries','frame=best_effort_timestamp,duration,pkt_duration','-of','json',a.file],{signal})).toString());
const frames=data.frames??[];if(!frames.length||frames.length>maxFrames)throw Error('Media frame budget exceeded: '+id);
- const first=Number(frames[0].best_effort_timestamp_time??0);
- pts=frames.map(f=>Number(f.best_effort_timestamp_time??0)-first);
+ const first=Number(frames[0].best_effort_timestamp??0);
+ pts=frames.map(f=>(Number(f.best_effort_timestamp??0)-first)*tn/td);
if(pts.some((t,i)=>!Number.isFinite(t)||(i&&t0?lastTicks*tn/td:1/30));
budget+=v.width*v.height*4*frames.length;if(budget>maxDecodedBytes)throw Error('Decoded media budget exceeded; trim/proxy sources or raise maxDecodedBytes');
const dest=path.join(dir,id);await fs.mkdir(dest);
- await run(ffmpeg(),['-v','error','-i',a.file,'-map','0:v:0','-fps_mode','passthrough','-frames:v',String(frames.length),path.join(dest,'%06d.png')],{signal,timeout:300000});
+ // A PNG from a clip tagged with BT.709 primaries and transfer (most camera footage) carries cICP, cHRM and gAMA
+ // chunks, and the browser then draws it through that curve: footage drew darker, and a matte or depth map's data
+ // changed. The tags do not change the decoded values; clearing them keeps the chunks out.
+ await run(ffmpeg(),['-v','error','-i',a.file,'-map','0:v:0','-vf','setparams=color_primaries=unknown:color_trc=unknown','-fps_mode','passthrough','-frames:v',String(frames.length),path.join(dest,'%06d.png')],{signal,timeout:300000});
const files=await fs.readdir(dest);if(files.length!==pts.length)throw Error('Decoded frame count differs from PTS index: '+id);
}
if(a.type==='audio'&&!audio)throw Error('Asset has no audio: '+id);
if(audio){budget+=duration*48000*4;if(!Number.isFinite(duration)||duration<=0||budget>maxDecodedBytes)throw Error('Audio decode budget exceeded');a.previewAudio=path.join(dir,'sources',id+'-audio.wav');await run(ffmpeg(),['-v','error','-n','-i',a.file,'-map','0:a:0','-vn','-af',`apad=whole_dur=${duration},atrim=duration=${duration}`,'-ar','48000','-ac','2','-c:a','pcm_s16le',a.previewAudio],{signal,timeout:300000});}
- catalog[id]={type:a.type,sha256:a.sha256,duration,pts,audio,width:v?.width,height:v?.height,audioOffset:Number(astream?.start_time??0)-Number(v?.start_time??0),sourceUrl:audio?'/__ef/audio/'+id:null,url:'/__ef/media/'+id+'/'};
+ const [rn,rd]=String(v?.avg_frame_rate??'').split('/').map(Number),frameRate=a.type==='video'&&Number.isSafeInteger(rn)&&Number.isSafeInteger(rd)&&rn>0&&rd>0?{num:rn,den:rd}:undefined;
+ catalog[id]={type:a.type,sha256:a.sha256,derived:a.derived,frameRate,duration,pts,audio,width:v?.width,height:v?.height,audioOffset:Number(astream?.start_time??0)-Number(v?.start_time??0),sourceUrl:audio?'/__ef/audio/'+id:null,url:'/__ef/media/'+id+'/'};
+ }
+ // A per-frame matte or depth map only lines up when it has exactly the plate's frames.
+ for(const [id,entry]of Object.entries(catalog)){const d=entry.derived;if(!d||entry.type!=='video')continue;const parent=catalog[d.of];if(parent.type==='video'&&parent.pts.length!==entry.pts.length)throw Error(`${id} has ${entry.pts.length} frames but ${d.of} has ${parent.pts.length}; a ${d.role} must match its plate frame for frame`)}
+ for(const [id,a]of Object.entries(frozenAssets))if(a.derived?.role==='analysis'){
+ const receipt=JSON.parse(await fs.readFile(a.file,'utf8')),parent=catalog[a.derived.of];
+ validatePreparedAnalysis(receipt,{...parent,frames:parent.pts.length});
+ const mask=catalog[receipt.alpha.asset];
+ if(!mask||mask.sha256!==receipt.alpha.sha256||mask.pts.length!==parent.pts.length||mask.width!==parent.width||mask.height!==parent.height)throw Error('Prepared alpha identity/raster differs: '+id);
}
return {dir,catalog,assets:frozenAssets,close:()=>fs.rm(dir,{recursive:true,force:true})};
}catch(e){await fs.rm(dir,{recursive:true,force:true});throw e}
diff --git a/scripts/project.mjs b/scripts/project.mjs
index 7a32ac4..699aed0 100644
--- a/scripts/project.mjs
+++ b/scripts/project.mjs
@@ -1,6 +1,7 @@
+import {validatePreparedAnalysis} from '../packages/plate/prepared.mjs';
import fs from 'node:fs/promises';import path from 'node:path';import {pathToFileURL} from 'node:url';import {createHash,randomUUID} from 'node:crypto';import {build} from 'esbuild';
-import {root} from './build.mjs';import {Studio,clone} from '../packages/core/index.mjs';import {serve,sendFile} from './server.mjs';import {readAssets,prepareMedia,fileHash} from './media.mjs';
-import {normalizeClipModule} from '../packages/core/definition.mjs';
+import {root} from './build.mjs';import {acquireLock,recordId,processTable} from './lock.mjs';import {Studio,clone} from '../packages/core/index.mjs';import {serve,sendFile} from './server.mjs';import {readAssets,prepareMedia,fileHash,checkDeclaration,checkBytes,preflightMedia} from './media.mjs';
+import {normalizeClipModule} from '../packages/core/definition.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs';
const publicExports=JSON.parse(await fs.readFile(path.join(root,'package.json'),'utf8')).exports;
function publicPackagePlugin(){return {name:'editableframes-public-exports',setup(b){b.onResolve({filter:/^editableframes(?:\/.*)?$/},args=>{const key=args.path==='editableframes'?'.':'./'+args.path.slice('editableframes/'.length),file=publicExports[key];return file?{path:path.join(root,file)}:{errors:[{text:'Unknown EditableFrames export: '+args.path}]};});}};}
export const hash=s=>createHash('sha256').update(s).digest('hex');
@@ -8,7 +9,7 @@ export async function definition(dir){
dir=await fs.realpath(dir);const file=path.join(dir,'clip.mjs');
const bundled=await build({entryPoints:[file],bundle:true,format:'esm',platform:'browser',write:false,minify:true,nodePaths:[path.join(root,'node_modules')],plugins:[publicPackagePlugin()]});
const assets=await readAssets(dir);const assetIdentity=Object.fromEntries(Object.entries(assets).map(([id,{file,...rest}])=>[id,rest]));
- const runtimeFiles=['packages/core/rotation.mjs','packages/core/spatial-session.mjs','packages/three/spatial-math.mjs','packages/three/spatial-editor.mjs','packages/core/key-timing.mjs','packages/core/manipulation.mjs','packages/three/manipulation.mjs','packages/core/index.mjs','packages/core/animation.mjs','packages/core/host.mjs','packages/core/renderer.mjs','packages/core/controls.mjs','packages/core/objects.mjs','packages/core/interaction.mjs','packages/core/definition.mjs','packages/runtime/renderer-host.mjs','packages/runtime/renderer-compositor.mjs','packages/runtime/editor.mjs','packages/runtime/compositor.mjs','packages/media/ports.mjs','packages/media/browser.mjs','packages/media/audio-plan.mjs','packages/media/playback.mjs','scripts/render.mjs','scripts/audio.mjs','package-lock.json'];
+ const runtimeFiles=['packages/core/rotation.mjs','packages/core/spatial-session.mjs','packages/three/spatial-math.mjs','packages/three/spatial-editor.mjs','packages/core/key-timing.mjs','packages/core/manipulation.mjs','packages/three/manipulation.mjs','packages/core/index.mjs','packages/core/animation.mjs','packages/core/host.mjs','packages/core/renderer.mjs','packages/core/controls.mjs','packages/core/objects.mjs','packages/core/interaction.mjs','packages/core/definition.mjs','packages/runtime/renderer-host.mjs','packages/runtime/renderer-compositor.mjs','packages/runtime/editor.mjs','packages/runtime/compositor.mjs','packages/media/ports.mjs','packages/media/browser.mjs','packages/media/audio-plan.mjs','packages/media/playback.mjs','scripts/render.mjs','scripts/browser.mjs','scripts/audio.mjs','package-lock.json'];
const runtimeIdentity=Object.fromEntries(await Promise.all(runtimeFiles.map(async file=>[file,hash(await fs.readFile(path.join(root,file)))])));
const binding=hash(Buffer.concat([Buffer.from(bundled.outputFiles[0].contents),Buffer.from(JSON.stringify(runtimeIdentity)),Buffer.from(JSON.stringify(assetIdentity))]));
const normalized=normalizeClipModule(await import('data:text/javascript;base64,'+Buffer.from(bundled.outputFiles[0].contents).toString('base64')));
@@ -16,16 +17,50 @@ export async function definition(dir){
}
export async function init(dir,{template='canvas'}={}){
await fs.mkdir(dir,{recursive:true});if((await fs.readdir(dir)).length)throw Error('init needs an empty directory');
- if(!['canvas','media','renderer'].includes(template))throw Error('Unknown starter');
+ if(!['canvas','media','renderer','hybrid'].includes(template))throw Error('Unknown starter');
await fs.copyFile(path.join(root,'templates',template,'clip.mjs'),path.join(dir,'clip.mjs'));
if(template==='media'){const {createDemoMedia}=await import('./demo-media.mjs');await createDemoMedia(dir);}
+ if(template==='hybrid'){const {createHybridDemo}=await import('./demo-hybrid.mjs');await createHybridDemo(dir);}
const d=await definition(dir),s=new Studio(d.templates,{binding:d.binding});s.doc.clips=[s.make(d.template.id)];s.doc.width=d.template.width??1280;s.doc.height=d.template.height??720;s.doc.fps=d.frameRate;s.check(s.doc);s.base=clone(s.doc);
await snapshotSource(d);await fs.writeFile(path.join(dir,'project.json'),s.serialize());return {directory:path.resolve(dir),template:d.template.id};
}
export async function readProject(dir){const d=await definition(dir),raw=await fs.readFile(path.join(d.dir,'project.json'),'utf8');return {...d,raw,revision:hash(raw),studio:Studio.restore(raw,d.templates,d.binding)};}
+// One edit per project. The lock records its owner, so an edit that was killed no longer blocks the project
+// for ever: the next edit takes over in one atomic step (lock.mjs) and removes what the dead one left.
+// `.editableframe-edit.lock` is still created while the lock is held, so an older CLI is kept out as well.
+export async function editLock(dir){
+ dir=await fs.realpath(dir);const legacy=path.join(dir,'.editableframe-edit.lock'),lock=await acquireLock(path.join(dir,'.editableframe','locks','edit')),release=lock.release;let mine=false;
+ lock.release=async()=>{if(mine)await fs.rm(legacy,{force:true});await release()};
+ try{
+ // Holding the lock, a legacy file that names an earlier generation belongs to a holder that is gone.
+ const old=await fs.readFile(legacy,'utf8').then(JSON.parse).catch(e=>e.code==='ENOENT'?undefined:null);
+ if(old===null||old&&!(old.gen{throw e.code==='EEXIST'?Error('Another edit is active; retry after it finishes'):e});mine=true;
+ lock.recovered=await lock.reclaim(record=>sweepEdit(dir,record));
+ }catch(e){await lock.release();throw e}
+ return lock;
+}
+// What a killed edit left behind. Each name carries that edit's own lock generation and token, so nothing is
+// found by pattern. A decoder it started may still be writing; it is never signalled, it ends by itself,
+// and its directory is left for the next edit to remove.
+async function sweepEdit(dir,record){
+ const id=recordId(record),removed=[],left=[];if(!id)return {complete:true};
+ const stage=path.join(dir,'assets','.import-'+id),st=await fs.lstat(stage).catch(()=>null);
+ if(st&&!st.isDirectory()){await fs.rm(stage,{force:true});removed.push(stage)}
+ else if(st){
+ const users=await processTable().then(rows=>rows.filter(r=>r.command.includes('.import-'+id)).map(r=>r.pid),()=>null);
+ if(users===null||users.length)left.push({path:stage,why:users?'still used by process '+users.join(', '):'cannot list processes'});
+ else{await fs.rm(stage,{recursive:true,force:true});removed.push(stage)}
+ }
+ for(const f of ['assets.json','project.json']){const t=path.join(dir,f+'.'+id+'.tmp');if(await fs.lstat(t).then(s=>s.isFile(),()=>false)){await fs.rm(t,{force:true});removed.push(t)}}
+ const result={complete:!left.length,removed,left};
+ if(removed.length||left.length){const log=path.join(dir,'.editableframe','recovered');await fs.mkdir(log,{recursive:true});await fs.writeFile(path.join(log,'edit-'+id+'.json'),JSON.stringify({at:new Date().toISOString(),owner:record.owner,...result},null,1))}
+ return result;
+}
export async function mutate(dir,operation){
- const lock=path.join(dir,'.editableframe-edit.lock');const fd=await fs.open(lock,'wx').catch(error=>{if(error.code==='EEXIST')throw Error('Another edit is active; retry after it finishes');throw error;});
- try{const d=await readProject(dir);await operation(d);const raw=d.studio.serialize(),dest=path.join(d.dir,'project.json'),temp=dest+'.'+randomUUID()+'.tmp';try{await fs.writeFile(temp,raw);await fs.rename(temp,dest)}finally{await fs.rm(temp,{force:true})}return {revision:hash(raw),history:d.studio.history.length,cursor:d.studio.cursor};}finally{await fd.close();await fs.rm(lock,{force:true})}
+ const lock=await editLock(dir);
+ try{const d=await readProject(dir);await operation(d);const raw=d.studio.serialize(),dest=path.join(d.dir,'project.json'),temp=dest+'.'+lock.id+'.tmp';try{await fs.writeFile(temp,raw);await lock.assertHeld();await fs.rename(temp,dest)}finally{await fs.rm(temp,{force:true})}return {revision:hash(raw),history:d.studio.history.length,cursor:d.studio.cursor};}finally{await lock.release()}
}
export async function preview(dir,{port=8791,editable=true,signal,snapshot}={}){
const d=snapshot??await readProject(dir),media=await prepareMedia(d.assets,{signal});
@@ -72,26 +107,43 @@ export async function snapshotSource(d){
const dest=path.join(d.dir,'.editableframe','sources',d.binding);await fs.mkdir(dest,{recursive:true});await fs.writeFile(path.join(dest,'clip.bundle.mjs'),d.bundledSource);await fs.copyFile(d.file,path.join(dest,'clip.mjs'));await fs.copyFile(path.join(root,'packages/core/index.mjs'),path.join(dest,'core.mjs'));await fs.copyFile(path.join(root,'packages/core/animation.mjs'),path.join(dest,'animation.mjs'));for(const file of ['rotation.mjs','spatial-session.mjs','key-timing.mjs','manipulation.mjs','renderer.mjs','controls.mjs','objects.mjs','interaction.mjs','definition.mjs'])await fs.copyFile(path.join(root,'packages/core',file),path.join(dest,file));await fs.writeFile(path.join(dest,'runtime.json'),JSON.stringify(d.runtimeIdentity,null,2));await fs.writeFile(path.join(dest,'assets.json'),JSON.stringify({version:1,assets:d.assetIdentity},null,2));
}
export async function rebind(dir,{reset=false}={}){
- const lock=path.join(dir,'.editableframe-edit.lock'),fd=await fs.open(lock,'wx');
+ const lock=await editLock(dir);
try{const d=await definition(dir),file=path.join(d.dir,'project.json'),raw=await fs.readFile(file,'utf8'),p=JSON.parse(raw);
let s;if(reset){s=new Studio(d.templates,{binding:d.binding});s.doc.clips=[s.make(d.template.id)];s.doc.width=d.template.width??1280;s.doc.height=d.template.height??720;s.doc.fps=d.frameRate;s.check(s.doc);s.base=clone(s.doc);}else{s=Studio.restore(raw,d.templates,p.binding);s.binding=d.binding;}
const archive=path.join(d.dir,'.editableframe','revisions');await fs.mkdir(archive,{recursive:true});const backup=path.join(archive,hash(raw)+'.json');await fs.writeFile(backup,raw);await snapshotSource(d);
- const temp=file+'.'+randomUUID()+'.tmp';try{await fs.writeFile(temp,s.serialize());await fs.rename(temp,file)}finally{await fs.rm(temp,{force:true})}
+ const temp=file+'.'+lock.id+'.tmp';try{await fs.writeFile(temp,s.serialize());await lock.assertHeld();await fs.rename(temp,file)}finally{await fs.rm(temp,{force:true})}
return {binding:d.binding,backup,reset};
- }finally{await fd.close();await fs.rm(lock,{force:true})}
+ }finally{await lock.release()}
}
-export async function importAsset(dir,id,source,{type}={}){
+export async function importAsset(dir,id,source,{type,role,of,encoding,subject,signal}={}){
if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id))throw Error('Invalid asset ID');
- dir=await fs.realpath(dir);const lock=path.join(dir,'.editableframe-edit.lock'),fd=await fs.open(lock,'wx');
+ dir=await fs.realpath(dir);const lock=await editLock(dir);let stage;
try{
- const d=await readProject(dir);if(Object.hasOwn(d.assets,id))throw Error('Asset IDs are immutable; use a new ID and swap the port');
- const ext=path.extname(source).toLowerCase();type??=(['.png','.jpg','.jpeg','.webp'].includes(ext)?'image':['.wav','.mp3','.flac','.m4a'].includes(ext)?'audio':'video');
- if(!['image','audio','video'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension');
- const sha256=await fileHash(source),src='assets/'+sha256+ext;await fs.mkdir(path.join(dir,'assets'),{recursive:true});await fs.copyFile(source,path.join(dir,src));
- const manifest={version:1,assets:{...d.assetIdentity,[id]:{src,type,sha256}}};
- const file=path.join(dir,'assets.json'),tmp=file+'.'+randomUUID()+'.tmp';await fs.writeFile(tmp,JSON.stringify(manifest,null,2));await fs.rename(tmp,file);
- // Rebinding is separate and explicit; the old project/source snapshot is retained.
- return {id,sha256,next:'Run rebind to accept the added asset; set a media port to its ID.'};
- }finally{await fd.close();await fs.rm(lock,{force:true})}
+ // Only the asset manifest is needed. Reading the whole project would refuse the
+ // binding the previous import changed, so a second import before rebind failed.
+ const d=await definition(dir);if(Object.hasOwn(d.assets,id))throw Error('Asset IDs are immutable; use a new ID and swap the port');
+ const ext=path.extname(source).toLowerCase();type??=(['.png','.jpg','.jpeg','.webp'].includes(ext)?'image':['.wav','.mp3','.flac','.m4a'].includes(ext)?'audio':ext==='.json'?'data':'video');
+ if(!['image','audio','video','data'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension');
+ // A derived asset records the hash of the take it describes, so a regenerated take cannot reuse it.
+ if((role===undefined)!==(of===undefined))throw Error('Use --role and --of together');
+ let derived;if(role){if(!Object.hasOwn(d.assets,of))throw Error('Unknown --of asset: '+of);derived={of,role,sourceSha256:d.assets[of].sha256,...(subject?{subject}:{}),...(encoding?{encoding}:{})};}
+ // Validate a private copy. Hashing the source before copying can pin different bytes under that hash.
+ signal?.throwIfAborted();const assetsDir=path.join(dir,'assets');await fs.mkdir(assetsDir,{recursive:true});
+ // Named after this edit's lock, so a later edit can tell exactly whose it was. The decode goes inside it.
+ stage=path.join(assetsDir,'.import-'+lock.id);await fs.mkdir(stage);const candidate=path.join(stage,'candidate'+ext);
+ await fs.copyFile(source,candidate,fs.constants.COPYFILE_EXCL);
+ const sha256=await fileHash(candidate),src='assets/'+sha256+ext,declaration={src,type,sha256,...(derived?{derived}:{})};
+ checkDeclaration(id,declaration);await checkBytes(id,declaration,candidate);
+ const manifest={version:1,assets:{...d.assetIdentity,[id]:declaration}};validateDerived(manifest.assets);
+ const related={},relate=k=>{if(!k||related[k]||!d.assets[k])return;related[k]=d.assets[k];relate(d.assets[k].derived?.of)};relate(of);
+ if(type==='data'&&role==='analysis'){const receipt=JSON.parse(await fs.readFile(candidate,'utf8'));relate(receipt?.alpha?.asset);}
+ const probe=await preflightMedia(id,{...declaration,file:candidate},related,{signal,root:stage});signal?.throwIfAborted();
+ if(await fileHash(candidate)!==sha256)throw Error('Import candidate changed during validation');
+ // Content is installed without overwriting an existing immutable file. Publish the manifest last.
+ await lock.assertHeld();const final=path.join(dir,src);try{await fs.link(candidate,final)}catch(e){if(e.code!=='EEXIST')throw e;if(await fileHash(final)!==sha256)throw Error('Stored file does not match its content address: '+src)}
+ const file=path.join(dir,'assets.json'),tmp=file+'.'+lock.id+'.tmp';
+ try{await fs.writeFile(tmp,JSON.stringify(manifest,null,2));await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}
+ return {id,sha256,probe,next:'Run rebind to accept the added asset; set a media port to its ID.'};
+ }finally{try{if(stage)await fs.rm(stage,{recursive:true,force:true})}finally{await lock.release()}}
}
diff --git a/scripts/render.mjs b/scripts/render.mjs
index 1ca6db0..254d8df 100644
--- a/scripts/render.mjs
+++ b/scripts/render.mjs
@@ -1,52 +1,78 @@
+import {chromiumOptions} from './browser.mjs';
import fs from 'node:fs/promises';import path from 'node:path';import {randomUUID} from 'node:crypto';import {chromium} from 'playwright';
-import {preview,readProject} from './project.mjs';import {mixAudio} from './audio.mjs';import {run,ffmpeg,ffprobe} from './process.mjs';import {HZ} from '../packages/core/index.mjs';
+import {preview,readProject} from './project.mjs';import {mixAudio} from './audio.mjs';import {run,ffmpeg,ffprobe} from './process.mjs';import {HZ} from '../packages/core/index.mjs';import {shutterSamples,validateShutter} from '../packages/plate/motion-blur.mjs';
export function frameRate(value={num:24,den:1}){
if(typeof value==='string'){const [num,den=1]=value.split('/').map(Number);value={num,den}}
if(typeof value==='number')value={num:value,den:1};
if(!Number.isSafeInteger(value.num)||!Number.isSafeInteger(value.den)||value.num<1||value.den<1||value.num/value.den>120||value.num/value.den<1||value.num>1000000||value.den>1000000)throw Error('Invalid rational frame rate');return value;
}
async function absent(file){try{await fs.lstat(file);throw Error('Output already exists: '+file)}catch(e){if(e.code!=='ENOENT')throw e}}
-export async function render(dir,output,{fps,frames,format,background='#101922',signal,onProgress=()=>{}}={}){
+export async function render(dir,output,{fps,frames,format,background='#101922',pass='beauty',motionBlur,signal,onProgress=()=>{},expectRevision,expectBinding,job}={}){
if(!output)throw Error('Output path is required');signal?.throwIfAborted();
- const d=await readProject(dir),rate=frameRate(fps??d.studio.doc.fps),duration=Math.max(0,...d.studio.doc.clips.map(c=>(c.start+c.duration)/HZ));
+ const d=await readProject(dir);
+ if(expectRevision!==undefined&&expectRevision!==d.revision)throw Error('Stale export revision: inspect again');
+ if(expectBinding!==undefined&&expectBinding!==d.binding)throw Error('Stale export binding: rebind and inspect again');
+ const rate=frameRate(fps??d.studio.doc.fps),duration=Math.max(0,...d.studio.doc.clips.map(c=>(c.start+c.duration)/HZ));
const count=frames??Math.ceil(duration*rate.num/rate.den);if(!Number.isSafeInteger(count)||count<1||count>36000)throw Error('Invalid export frame budget');
+ // A control pass exists only where the scene's own code draws it.
+ if(pass!=='beauty'&&(d.kind!=='renderer'||!(d.scene.passes??[]).includes(pass)))throw Error(`This scene does not declare a ${pass} pass`+(d.kind==='renderer'&&d.scene.passes?.length?`; it declares: ${d.scene.passes.join(', ')}`:''));
+ const shutter=motionBlur?validateShutter(motionBlur):null;if(shutter&&count*shutter.samples>144000)throw Error('Motion blur sample budget exceeded; lower --samples or the frame count');
format??=path.extname(output)==='.mov'?'mov':path.extname(output)==='.mp4'?'mp4':null;
if(!['mp4','mov','png'].includes(format))throw Error('Use .mp4, .mov (alpha), or --format png');
if(!/^#[0-9a-f]{6}$/i.test(background))throw Error('Background must be a six-digit color');
output=path.resolve(output);await absent(output);await absent(output+'.json');await fs.mkdir(path.dirname(output),{recursive:true});
- const temp=path.join(path.dirname(output),'.editableframe-render-'+randomUUID());await fs.mkdir(temp);
+ const temp=job?.temp??path.join(path.dirname(output),'.editableframe-render-'+randomUUID());await fs.mkdir(temp);
let host,browser;const errors=[];
const abort=()=>browser?.close().catch(()=>{});signal?.addEventListener('abort',abort,{once:true});
try{
onProgress({phase:'media',progress:0});host=await preview(dir,{port:0,editable:false,signal,snapshot:d});
- browser=await chromium.launch({headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']});
+ // With a job the caller owns cancellation; Playwright's own handlers would exit the process before cleanup.
+ browser=await chromium.launch({...chromiumOptions(),...(job?{handleSIGINT:false,handleSIGTERM:false,handleSIGHUP:false}:{}),headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']});
const page=await browser.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(host.url);await page.waitForFunction(()=>window.editableframe?.ready,{},{timeout:30000});
- const frameDir=path.join(temp,'frames');await fs.mkdir(frameDir);
+ const frameDir=path.join(temp,'frames'),sampleDir=path.join(temp,'samples');await fs.mkdir(frameDir);if(shutter)await fs.mkdir(sampleDir);
for(let frame=0;framewindow.editableframe.seek(t,{timeline:true}),frame*rate.den/rate.num);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});}
- else{const png=await page.evaluate(async t=>{await window.editableframe.seek(t,{timeline:true});return window.editableframe.png()},frame*rate.den/rate.num);bytes=Buffer.from(png.split(',')[1],'base64');}
- await fs.writeFile(path.join(frameDir,String(frame+1).padStart(6,'0')+'.png'),bytes);
+ // One capture per output frame, or one per shutter sample when motion blur is on.
+ const times=shutter?shutterSamples(frame,shutter):[frame];
+ for(let sample=0;samplewindow.editableframe.seek(t,{timeline:true,pass,mediaTime}),[seconds,pass,mediaTime]);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});}
+ else{const png=await page.evaluate(async ([t,mediaTime])=>{await window.editableframe.seek(t,{timeline:true,mediaTime});return window.editableframe.png()},[seconds,mediaTime]);bytes=Buffer.from(png.split(',')[1],'base64');}
+ await fs.writeFile(shutter?path.join(sampleDir,String(frame*shutter.samples+sample+1).padStart(8,'0')+'.png'):path.join(frameDir,String(frame+1).padStart(6,'0')+'.png'),bytes);
+ }
onProgress({phase:'frames',frame:frame+1,total:count,progress:(frame+1)/count});
}
+ if(shutter){
+ // Average each frame's samples as premultiplied colour, so a half-covered pixel keeps its hue instead of darkening.
+ // Float intermediates avoid losing a code value even when every sample is identical.
+ // The mean is taken on encoded (display) values, not linear light.
+ onProgress({phase:'shutter',progress:0});
+ await run(ffmpeg(),['-v','error','-n','-framerate','1','-i',path.join(sampleDir,'%08d.png'),'-vf',`format=gbrapf32le,premultiply=inplace=1,tmix=frames=${shutter.samples},select='not(mod(n+1\\,${shutter.samples}))',unpremultiply=inplace=1,format=rgba`,'-fps_mode','passthrough','-frames:v',String(count),path.join(frameDir,'%06d.png')],{signal,timeout:600000});
+ if((await fs.readdir(frameDir)).length!==count)throw Error('Motion blur produced the wrong number of frames');
+ await fs.rm(sampleDir,{recursive:true,force:true});
+ }
const actualDuration=count*rate.den/rate.num,audioPath=path.join(temp,'audio.wav');const audio=await mixAudio({...d,assets:host.media.assets},host.media.catalog,audioPath,actualDuration,{signal});
let result;
if(format==='png'){
if(audio.tracks)await fs.copyFile(audioPath,path.join(frameDir,'audio.wav'));result=frameDir;
}else{
result=path.join(temp,'output.'+format);const args=['-v','error','-n','-framerate',`${rate.num}/${rate.den}`,'-i',path.join(frameDir,'%06d.png')];if(audio.tracks)args.push('-i',audioPath);
- const convert='scale=in_range=pc:out_range=pc:out_color_matrix=bt709,format=yuv444p,colorspace=ispace=bt709:itrc=srgb:iprimaries=bt709:irange=pc:all=bt709:range=tv:format=yuv444p';
+ // RGB to BT.709 YUV in limited range, with the transfer left as drawn and tagged as sRGB. Converting it to the BT.709
+ // camera curve made every export 10-13 levels darker (128 -> 115), footage included, and no player undoes it.
+ const convert='scale=in_range=pc:out_range=tv:out_color_matrix=bt709,format=yuv444p';
if(format==='mp4')args.push('-f','lavfi','-i',`color=c=${background.replace('#','0x')}:s=${d.studio.doc.width}x${d.studio.doc.height}:r=${rate.num}/${rate.den}`,'-filter_complex',`[${audio.tracks?2:1}:v]format=rgba[bg];[bg][0:v]overlay=shortest=1:format=rgb,${convert},format=yuv420p[v]`,'-map','[v]','-c:v','libx264','-crf','18','-pix_fmt','yuv420p','-movflags','+faststart');
- else args.push('-filter_complex',`[0:v]split[rgb][alpha];[alpha]alphaextract[a];[rgb]${convert}[color];[color][a]alphamerge,format=yuva444p10le[v]`,'-map','[v]','-c:v','prores_ks','-profile:v','4','-pix_fmt','yuva444p10le','-alpha_bits','16');
+ else args.push('-filter_complex',`[0:v]format=rgba,split[rgb][alpha];[alpha]alphaextract[a];[rgb]${convert}[color];[color][a]alphamerge,format=yuva444p10le[v]`,'-map','[v]','-c:v','prores_ks','-profile:v','4','-pix_fmt','yuva444p10le','-alpha_bits','16');
if(audio.tracks)args.push('-map','1:a:0','-c:a',format==='mov'?'pcm_s16le':'aac');
- args.push('-frames:v',String(count),'-t',String(actualDuration),'-color_primaries','bt709','-color_trc','bt709','-colorspace','bt709',result);
+ args.push('-frames:v',String(count),'-t',String(actualDuration),'-color_range','tv','-color_primaries','bt709','-color_trc','iec61966-2-1','-colorspace','bt709',result);
onProgress({phase:'encode',progress:0});await run(ffmpeg(),args,{signal,timeout:600000});
const info=JSON.parse((await run(ffprobe(),['-v','error','-show_streams','-show_format','-of','json',result],{signal})).toString());
if(!info.streams.some(s=>s.codec_type==='video')||audio.tracks&&!info.streams.some(s=>s.codec_type==='audio'))throw Error('Encoded media failed stream validation');
}
signal?.throwIfAborted();
- const receipt={version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))};
+ const receipt={...(job?{job:job.id}:{}),configuredBrowser:Boolean(process.env.EDITABLEFRAMES_CHROMIUM_EXECUTABLE),version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',pass,motionBlur:shutter,runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))};
// Reserve the receipt path, and publish a complete file without overwriting another writer.
const receiptFile=output+'.json',fd=await fs.open(receiptFile,'wx');let published=false;
try{await fd.writeFile(JSON.stringify(receipt,null,2));await fd.sync();if(format==='png'){await absent(output);await fs.rename(result,output)}else await fs.link(result,output);published=true}finally{await fd.close();if(!published)await fs.rm(receiptFile,{force:true})}
diff --git a/skills/editableframes/SKILL.md b/skills/editableframes/SKILL.md
index d9edd07..d15034c 100644
--- a/skills/editableframes/SKILL.md
+++ b/skills/editableframes/SKILL.md
@@ -23,6 +23,18 @@ Use `preview ` and inspect more than one meaningful frame. For an M
The bundled `studio` has effect and creative studies plus the device library. Study their code when useful, while keeping new renderers free to use other libraries. EffectCraft's 306-entry map is research; only 24 scoped visual prototypes are demonstrated. Device assets keep their individual licenses and credits.
+## Code inside footage
+
+When a shot mixes code with filmed or generated video, let footage supply what only has to look real (people, places, light) and code supply what must be exactly right (the product, labels, prices, interfaces, captions). Read [references/hybrid.md](references/hybrid.md) before authoring. `init --hybrid` creates a working example. A matte, depth map, track or camera path is an input made by another tool: import it with `asset-add --role --of `, never invent one, and say so when a shot needs one that is missing. Replacing the footage invalidates data derived from it. Sample anything locked to the footage at `conformSeconds(clock.mediaTime ?? clock.frame / clock.fps, plate.frameRate)`, and render the project at the footage's frame rate. `render --pass ` exports a declared control pass; `render --motion-blur 180` adds a shutter. Light and depth scale are estimates: expose them as controls and check real frames.
+
+For final short clips, inspect every decoded frame, crossing crops and playback; tracking confidence and three sampled frames do not certify quality. A missing or collapsed hand/person mask is a failed shot, not merely an edge to soften. Recompute/correct missing derived frames or trim to verified ranges; never stretch or hold a moving matte’s tail. Distinguish planar insertion, original-object reskin, 3D insertion/replacement and deforming cloth before authoring. Plan readable motion and attachment space for typography using explicit animation time. Read the [quality and motion-design roadmap](references/hybrid-compositing-plan.md) for proposed improvements; its new contracts and features are not implemented APIs.
+
## Spatial objects
For separately editable spatial objects expose one animatable vec3 with role position and explicit coordinateSpace/unit, plus one positive number with role scale. Use editableframes/manipulation (or editableframes/three-manipulation) and consume the same props in rendering. Publish working per-object manipulationCapabilities and measurement; roles alone cannot make a renderer draggable. Nonspatial lighting parameters need no invented transforms. Keep the 200-control budget; arbitrary renderer code and future libraries remain supported. Read docs/object-manipulation.md for source tick identity, first-key holding and gesture write policy. Preserve existing split-number tracks; migrate them explicitly rather than relabeling their type.
+
+For explicitly authored stylized character stories, read the [code-generated story findings and acceptance track](references/code-generated-story-results-2026-11-13.md). Rigs, choreography and looks remain replaceable source, not a fixed core scene grammar. The preferred fantasy draft is not production-ready: contact, current-frame gaze/camera evaluation, reverse/random seeks, audio timing and cross-style reuse still need acceptance. Realistic interactions assembled from independent plates retain the staged joint-generation route.
+
+Asset imports now validate a private copy before publication; invalid media is refused and valid media takes longer to import. After adding assets, rebind explicitly. For a previously approved export snapshot, pass `render DIR OUTPUT --expect-revision R --expect-binding B` using the revision/binding from inspect; compare the receipt before publishing. These flags do not freeze arbitrary static/network resources. CLI render recovery is scoped to verified dead owners: `recover DIR --dry-run` reports without writing; `recover DIR` cleans unused owned resources without signalling; `recover DIR --stop-browsers` explicitly requests SIGTERM for verified orphan browsers. Never manually release an unknown lock without confirming no owner runs anywhere. Asset removal and native integration remain open. See [the recovery checkpoint](references/hybrid-concurrent-recovery-2026-11-14.md).
+
+For known-geometry lighting, distinguish editable raster preview from offline code rendering and from joint diffusion performance. Calibrate point-shadow bias in world units; reference agreement on one pose can hide cancelling errors. Do not globally disable specular anti-aliasing: AA-off was accurate for the tested satin cylinder but shimmers for tiny polished highlights; supersample those outputs. Exact-proxy reflections now pass simple held-out scenes; actual product approximations remain untested. Nearby reflections and multi-bounce transport remain offline-route candidates. See [the motion and proxy study](references/hybrid-motion-proxy-2026-11-14.md).
diff --git a/skills/editableframes/references/code-generated-story-results-2026-11-13.md b/skills/editableframes/references/code-generated-story-results-2026-11-13.md
new file mode 100644
index 0000000..edf1668
--- /dev/null
+++ b/skills/editableframes/references/code-generated-story-results-2026-11-13.md
@@ -0,0 +1,58 @@
+# Interaction acceptance and code-generated story films — 2026-11-13
+
+> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact, native integration and style reuse remain open. See [current evidence](hybrid-gap-closure-2026-11-14.md).
+
+## Decisions from the latest outputs
+
+The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark.
+
+Keep two distinct production routes, selected by the required representation and editability:
+
+| Need | Selected route | What remains editable | Evidence / boundary |
+|---|---|---|---|
+| Realistic people handling a product or exchanging it | Stage the scene → approved start image plus identity/product references → jointly generate the interacting subjects and room → review → EditableFrames finishing | Staging before generation; accepted footage selection/timing/crop/grade and separate titles/captions afterward | Pickup and completed transfer now have user-accepted examples. Physical performance and product pixels are baked; repeatability and exact identity/branding remain open. |
+| Stylized characters acting in an authored world | Code builds the set, rigs, action, cameras, lights and renderer; export directly | Authored geometry, rigs, animation and look in source; selected parameters via controls | Two 48-second fantasy RPG films rendered. Fable's direction is preferred, but its draft fails one seek check and requires refinement. Not generic automatic character animation. |
+| Realistic interaction within an otherwise editable story | Use an approved authored shot/snapshot as generation input, then return the accepted clip to the edit | Code shots stay editable; generated sections have the same baked boundary as above | Proposed shot-level combination; this story exercise did not test such a round trip. Do not claim that model video preserves exact meshes or camera motion. |
+
+The earlier interaction rule applies to **independently assembled realistic plates**. It must not become a ban on code-authored character stories. A shared authored rig and choreography can represent an interaction; independent masks cannot invent it. Nor does stylization excuse intersecting hands, incoherent eyelines, or unsupported props.
+
+## What Fable actually used
+
+Both entries use **Three.js raster rendering in the current EditableFrames `defineRenderer` / `mountRenderer` contract**, exported locally through browser capture and FFmpeg. No diffusion-generated frames, external character asset pack, path tracer, NVIDIA-only runtime or paid generation call was used for these films. The difference is authored assets, staging and rendering choices, not a different foundational framework.
+
+| Area | Fable implementation observed in source | Why it fits the references better / remaining limitation |
+|---|---|---|
+| Character construction | Lofted heads and bodies, character-specific proportions, separate noses/ears/hair, articulated segmented limbs and five-finger hands. Canvas-painted face textures include lids, brows, pupils, mouth states and emissive eyes. | Narrower faces and controlled facial detail read closer to the reference game art. This is procedural geometry and a scene-specific rig, not a learned human reconstruction or a production facial rig. |
+| Materials | Seeded, low-resolution stone, wood, cloth, leather and skin texture functions; nearest-neighbor magnification with mipmapped minification. Humanoids use Lambert materials. | Local wear, varied stone courses, planks and painted features provide more surface detail. Physically based materials alone do not guarantee a better stylized image; Astra used standard materials yet its asset forms were more primitive. |
+| Acting | Two-bone arm IK, gaze targets, walk/sit/gesture poses, a deforming dragon spine and wings, speech-envelope-driven animation with limited facial states. | More purposeful action than small idle oscillations. IK positions joints; it does not verify grasp, reach, collisions or force. Speech-envelope animation is not phoneme-level lip sync. |
+| Camera and sets | Fifteen shots rather than Astra's eight; a medieval lane and a furnished tavern; approach, reaction, over-table, detail and ensemble shots. | Greater spatial context, shot variety and first-person framing. The doorway transition and handoff detail still need refinement. |
+| Lighting and finish | Local torches, ember, window/fill and chandelier lights; HDR beauty pass at twice the output dimensions, object-ID/depth contour pass, half-resolution bloom, tone mapping, grade, vignette and grain. | Local light and depth-aware contours make a coherent game-art look. The large bloom/highlights also obscure detail in parts of the draft; adding effects is not automatically a quality improvement. |
+| Framework | Explicit frame clock and editable light/look/camera/title/subtitle properties, with separate local TTS/audio preparation. | Source remains authorable and selected controls redraw the scene. This does not make every performance or audio edit automatically available in a panel. |
+
+These are source-backed mechanisms and plausible contributors to the user preference, **not isolated causal tests**. No ablation has established which individual technique explains how much of the difference. The preferred direction is a reusable authoring approach, not a requirement to reproduce Fable's bugs or every shader.
+
+## Actual result and acceptance
+
+- **Astra:** 48.000 seconds, 720×1280, 24 fps, 1,152 decoded frames, voiced/subtitled. Three sampled repeat seeks matched exactly in the tested browser; a light-control edit changed the scene. Faces/hands remain puppet-like, material and architectural variety are limited, and jaw movement is approximate.
+- **Fable 5.2:** authored the scene, soundtrack and 15-shot timeline, then hit its provider usage limit during visual refinement. The parent exported that saved source unchanged; hashes before/after confirm preservation. Both full video and original source are retained. The output is a **recovered unfinished draft**, not Fable's final approved delivery.
+- **Recovered Fable export:** 48.000 seconds, 720×1280, 24 fps, 1,152 frames decoded without video errors. Light-control edit changed the render. A generic browser resource 404 was retained; its URL was not established, so it is not silently dismissed as a confirmed favicon request.
+- **Seek defect:** frames 228 and 768 repeated exactly, but frame 960 changed 183,794 pixels; mean channel difference 7.128/255, maximum 238. The dragon's head direction visibly changes. The `better` shot reads the previous camera position for its gaze before setting the current camera, a likely cause from source inspection; a fix has not yet been verified. Successful sequential export does not pass random-access authoring.
+- **Audio recovery:** initial decoded AAC peak was 1.372. The parent applied gain 0.5 at output while copying video unchanged; delivered peak measured 0.737. The original audio export is retained. This avoids the measured output overshoot but cannot undo distortion already present in the mix.
+- **Visual limits:** rigid joints, sparse facial animation, awkward/oversized hand contact, strong light/bloom and the doorway transition. Fifteen shot stills and a 1 fps decoded sheet were inspected; there is no claim of normal-speed playback or exhaustive visual inspection of all 1,152 frames by the reviewer.
+
+The user prefers Fable's **visual direction**. Neither film reaches the reference's character finish; a general production-ready or deterministic story engine is not yet demonstrated. References supplied art direction; their screenshot pixels were not used as finished scene backgrounds. Preserve reference rights/provenance before redistributing any supplied images.
+
+## Story track: extend beyond the dungeon without constraining the core
+
+This is a new authored-story exercise, separate from **feature item 6 (camera solve)** and **feature item 13 (world reconstruction into splats/meshes)**. Code-generated geometry and known cameras do not validate either deferred feature. Also keep it distinct from the existing “many versions from one take” journey numbered 6.
+
+1. **ST1 — finish and stabilize this film.** Let Fable complete its own refinement when available. Correct the current-frame camera/gaze dependency and test random, repeated and reverse seeks across every shot and cut boundary; compare with sequential frames in the same renderer. Inspect normal/slow playback, all contact intervals, reach/support/release, camera-wall clipping and gaze. Repair highlight loss and audio gain; retain original versus corrected versions and explicit authorship. Verify each advertised control in both preview and export. No model call or wall-clock state inside frame rendering.
+2. **ST2 — extract optional reusable authoring modules.** Separate character shape/face/rig, props and set dressing, action targets/contacts, shot/camera track, light track, material/contour/post look and dialogue/subtitle timing. Give selected controls stable IDs and source bindings; keep arbitrary source code and replacement renderers possible. Do not embed a mandatory fantasy vocabulary, actor taxonomy or model provider into the core. Existing film scripts are prototypes, not a shipped animation package.
+3. **ST3 — test style transfer through code, not only palette changes.** Produce three additional short studies, for example a science-fiction repair shop, a sunny cel-shaded village and a clay/toy workshop. Use a common walk → dialogue → shared-prop action and camera brief while changing silhouettes, facial design, surface detail, set construction, light response and contour/post treatment. Retain the full editable sources and exact settings. Each style must pass its own whole-shot visual review; portability beyond the fantasy study is currently unproven. No new hosted spending is implied.
+4. **ST4 — test practical reuse and host delivery.** Reuse an approved actor across shots and changes in framing, light, costume and dialogue; check identity, silhouettes and contact after edits. Regenerate local speech/alignment when dialogue changes rather than retaining stale audio. Bind source, assets and audio to project revisions and test save/reload, undo/redo and export parity in the host before claiming an integrated story workflow. Measure preview, capture time and peak memory on actual additional desktop/laptop machines; this Mac run establishes no performance floor for ordinary computers.
+
+Style is an open combination of authorable geometry, textures, rigs, cameras and lights, not a fixed list of “dungeon / office / cool” presets. Presets may be convenient starting points. Cross-style reuse and a useful agent authoring workflow must be earned by ST3/ST4, not inferred from parameter exposure alone.
+
+## Interaction work that remains
+
+The accepted pickup/handoff samples validate the selected staged joint-generation direction sufficiently to proceed with host implementation. Prioritize frozen scene-set capture, ordered reference roles/hashes, durable submission receipts, failed/ambiguous-job handling, actual decoded timing and accepted-take import; keep provider work outside rendering. Repeat the tests with both people identity-referenced and with difficult contact/occlusion before claiming broader reliability. Exact product geometry/print, multi-angle consistency, object–object collisions and animal interactions remain separate acceptance gates. The detailed [staged-generation report](staged-generation-results-2026-11-13.md) retains the observed action beats, estimates and limits.
diff --git a/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md b/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md
new file mode 100644
index 0000000..8206208
--- /dev/null
+++ b/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md
@@ -0,0 +1,52 @@
+# Hybrid acceptance round 1 — 2026-11-13
+
+Status: local experiments, no new generated take, no independent reviewer approval, no native-host integration claim. Existing generated footage and cached local models were reused. Hosted generation spending in this round: $0.
+
+## Staged snapshot handoff
+
+A seller/product scene now renders through the current renderer-host with editable product horizontal/vertical position, scale, image-plane rotation and an approximate foreshortening control. The headphones lie camera-left on the table, within reach of the presenter's hand, against a detailed warm-lamp/cool-window background. Repeated frame-zero captures are byte-identical in the tested browser; changing horizontal placement changes the PNG. Source, assets, controls and captured PNG are hashed into a local manifest.
+
+This is a 2D reference composition, not solved 3D product orientation, contact or lighting. The snapshot plus separate product and presenter references has **not been submitted** to a model. The latest provider schema supports start-image plus references and explicitly numbers the start image before the references. The quoted 5-second 720p image-input trial is approximately $0.785 at $0.157/s; re-check pricing before submission. The previous video-edit pickup does not establish this round trip.
+
+The earlier local Scene Studio suite passed 19 checks, including clean capture during active drafts and identical capture-button/programmatic outputs. An offline packet prototype exercised eight integrity cases. These do not replace real provider receipts, ambiguous-job recovery or native integration tests.
+
+## Full-clip masking through a pickup
+
+The complete previously generated pickup was processed: 121 frames, 24 fps, 5.0417 seconds. Source SHA256: `3b9aaf790d8f639eda5005808e08977ae951b0de05f8418c6f73acf66512d6cf`. Analysis resolution was 640×360; this is not 1080p boundary acceptance.
+
+- SAM 2.1 Hiera Tiny on Apple Metal propagated separate person/product/gripping-hand prompts across every frame. Raw thresholded masks, no correction clicks or optional model postprocessing. Propagation plus saving took 136.67 s; steady-step median/p95 1.157/1.176 s; process peak RSS about 2.14 GB. These are preparation costs, not render FPS.
+- RVM MobileNetV3 FP32 on CPU processed all 121 frames with continuous recurrent state, at 640×360 and downsample ratio 1. Wall time including saved foreground/alpha was 24.27 s. Some local workloads overlapped, so this is not an isolated hardware/model benchmark. RVM and SAM solve different problems.
+- The comparison preserves the original table below y=277 and replaces the background above it with a bright yellow diagnostic field. Original contact and lighting remain baked. SAM binary edges visibly lose soft hair detail. RVM softens the hair but introduces background remnants below the arms; neither raw route is an automatic pass.
+- A second candidate constrains RVM alpha with each frame's SAM person support: alpha is unchanged up to 3 pixels outside support, tapers to zero by 6 pixels, and the product is separately restored from its SAM mask. This reduces the observed spill. It can still clip hair missed by SAM and retains boundary defects; it is a heuristic requiring review, not ground-truth matting or physical depth.
+
+Both comparisons export all 121 frames and repeat frame 48 with maximum RGB code difference zero in the tested browser. These are renderer checks. Sampled full-frame images and contact sheets were inspected; no annotated hair/hand error, full normal/slow playback approval, identity guarantee or production-quality badge is claimed. Whole-clip processing is broader evidence than the previous short interval, but not completion of the static/pan/handheld/multi-person stress matrix.
+
+**Plan change:** keep semantic masks, foreground colour/alpha and support correction as separate, versioned preparation artifacts. Add whole-shot bright/dark edge checks and correction ranges. A successful segmentation job is insufficient for background-swap acceptance.
+
+## Tracking: a negative forward/backward result
+
+A new diagnostic reuses the synthetic stationary panel with independently moving surrounding texture. It runs the current tracker on the 49-frame clip forwards and on a losslessly re-encoded reversed clip, then compares corresponding returned quads.
+
+Worst corner error against the known stationary panel: **6.861 px**. Maximum forward/backward disagreement: **0 px**. For 25 frames, actual error exceeds 4 px while correlation exceeds 0.95 and forward/backward disagreement is below 1 px. At the worst frame the score is 0.956. The motion is symmetric, making this a deliberately revealing case where both directions share the same wrong solution.
+
+**Plan change:** forward/backward agreement is a diagnostic, never sufficient acceptance. Independent intended-surface boundaries, visibility and distributed target evidence are required; ambiguous/blank surfaces need correction or rejection. No production rejection algorithm was implemented here. The original missing S1/orbit footage remains unretested; this experiment does not establish its exact cause.
+
+## Lighting: continuous controls and a representation boundary
+
+A new 120-frame, 24 fps clip holds camera, geometry, exposure and authored scene frame fixed while continuously changing a practical lamp from warm to cool. The scene uses a scanned pastry, procedural cup/plate/lamp, and a photographed HDR panorama. It is a renderer diagnostic, not a real moving room or final advertisement. Lamp source colour, bulb emission and shade emission change together.
+
+Matched warm/cool rectangular image regions show mean absolute RGB changes of 0.22/255 on the pastry, 5.74 on the cup and 24.96 on the table reflection. The tested upper-left photographed backdrop is byte-identical (0 change). These ROIs include some surrounding pixels and measure response, not material accuracy. Repeat-frame pixels match; no page errors were recorded.
+
+**Plan change:** continuous editable colour/intensity is supported; named presets are starting values, not a finite lighting catalogue. Accept per-object light response separately from the bulb looking brighter. Light placement must serve the intended hero object; the weak pastry response is a failed stress target. A baked panorama, product photo or human video does not acquire physically correct new illumination merely because a 3D light was added. Keep that distinction explicit and test separate relighting routes for those representations. Ordinary-computer performance and mixed human/product emitter scenes remain open.
+
+## Remaining order and numbering
+
+1. Submit and inspect the actual staged snapshot plus references once a fresh spending cap is settled; then test object–object contact and two-person handoff separately.
+2. Implement real handoff receipts, failure recovery, accepted-take import and source-bound analysis in the host. The local packet prototype is not that implementation.
+3. Annotated full-resolution mask/alpha acceptance, disappearance/re-entry, multiple people and actual-device comparison. SAM 3 remains an access/runtime and comparison gate.
+4. Independent-surface tracker rejection and repeatable real-footage visibility tests.
+5. Stronger hero-object light response, mixed human/product emitters and additional actual computers.
+
+**Feature item 6 (camera solve): not tested here. Feature item 13 (generated worlds): research only, not tested here.** Authored Three.js cameras, photographed HDR backdrops and homography tracking prove neither feature. The separate journey table also has an item 6, “many versions from one take”; that is a different, partially exercised editable-content journey. H5, feature 6 and feature 13 remain deferred under the prior scope decision, not silently completed.
+
+Primary references: [Kling input and pricing documentation](https://replicate.com/kwaivgi/kling-v4.0), [SAM 2](https://github.com/facebookresearch/sam2), [Robust Video Matting](https://github.com/PeterL1n/RobustVideoMatting). Measurements above come from local retained experiment receipts, not those references.
diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md
new file mode 100644
index 0000000..952f674
--- /dev/null
+++ b/skills/editableframes/references/hybrid-compositing-plan.md
@@ -0,0 +1,113 @@
+# Reliable hybrid compositing and motion design
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open.
+
+**Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API.
+
+Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid guide](hybrid.md).
+
+Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage; the real-shot acceptance gates below still require full visual QA. Automatic geometry solving and production model selection remain research.
+
+## What the failed shots teach us
+
+| Observed failure | Diagnosis supported by the authored scenes | Required correction |
+|---|---|---|
+| A phone screen paints over a thumb, leaving a detached skin patch | The supplied matte loses the hand: foreground area drops from 12.44% at frame 59 to 0.18% at frame 60 and stays below 0.25% through frame 70. This is a missing foreground input, not just a rough edge. | Inspect plate, matte and composite together across the entire crossing; correct the subject track and correspondence, then refine its alpha edges. |
+| Menu text crosses a person's forehead | The menu scene has no subject matte. Its footer is clipped at the board's lower boundary in the inspected frames. Screen blending preserves board texture but cannot infer who is in front. | Fit the entire animated layout within the actual surface, then clip it; protect the person with a foreground holdout. |
+| An opaque price card erases the person's hair/head | There is no foreground holdout. Good planar tracking cannot fix layer order. | Treat all intersecting foreground subjects as required inputs. A plausible-looking board is not a passing result. |
+| A hand appears sliced through an added can | The example inserts a second can at an offset from the tracked original. Relative depth with hand-tuned near/far is being used as if it were registered scene geometry. | First distinguish insertion from reskinning. For a hand known to be in front, use its coherent alpha as the foreground constraint. |
+| A small labeled can sits over a larger generated can | Generating a world from a clay still did not preserve the product silhouette or proportions. | Reject the take for exact-object recomposition, or solve an explicit replacement workflow including removal of the original. Do not hide the mismatch with a smaller overlay. |
+
+These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. No new implementation or corrected full-length video is claimed by this plan.
+
+## Architecture decision: analyze, correct, cache, then render
+
+Keep the core model-neutral. A host or optional analysis package produces versioned masks, tracks, surface mappings and diagnostic reports. An author can correct them. Preview and export consume the same immutable artifacts. No model runs implicitly inside `render(clock)` and no model weights become a mandatory library dependency.
+
+Real-time compositing and real-time inference are different budgets. GPU/CPU acceleration can make preparation faster and enable interactive draft masks; it does not supply reliable geometry or physics by itself. Start with prepared per-frame data and GPU composition. Offer live draft inference only after profiling actual devices, with conspicuous provisional results and explicit promotion to a frozen render artifact.
+
+Bilibili provides a concrete live-inference precedent: its 2024 web.dev case study describes on-device MediaPipe Selfie Segmenter, worker/offscreen processing, reduced-resolution masks and CSS `mask-image` for comments behind people. Its older W3C presentation also describes mask-based rendering. These demonstrate a person-silhouette feature, not hair-level export alpha or collision simulation. Our choice to freeze reviewed masks for export is an architectural recommendation, not a claim that Bilibili precomputes everything. These are published primary sources; no authenticated production reverse engineering was performed. [Bilibili case study](https://web.dev/case-studies/bilibili-web-ai-improvements), [W3C presentation](https://www.w3.org/2019/03/23-chinese-web-zhaoxin-bilibili.pdf)
+
+### Proposed prepared-data contract
+
+Extend the existing derived-asset relationship with a versioned manifest. Names below are proposed fields, not accepted CLI flags:
+
+- Identity: source content digest, exact decoded dimensions/orientation/crop, frame count, rational time base and per-frame presentation timestamps; subject/surface IDs; model/checkpoint digest, preprocessing version and correction revision.
+- Semantics: `subject-alpha`, `foreground-color` where available, `surface-coverage`, `surface-map`, `depth`, `confidence` and `validity`. A binary segmentation probability is not silently relabeled as an alpha matte. Foreground alpha is white for foreground; linear alpha/data is not color-managed as display RGB.
+- Time: explicit source-frame correspondence and valid ranges. Plate, mask and track are fetched through one source-frame mapping, including trim, speed and reverse. Equal duration/FPS/count alone does not establish correspondence.
+- Storage: bounded, chunked cache; stream/prefetch under the existing decoded-memory budget. Use lossless data for final alpha and sufficiently precise depth/maps; lossy MP4 is diagnostic input, not the canonical final data format.
+- Failure: missing, stale, out-of-range, invalid or wrong-sized data fails final validation. Draft rendering can show the original plate plus a diagnostic. Never silently replace a missing holdout with an all-background mask, repeat a moving matte's last frame, or stretch a short matte to fit.
+
+Changing source bytes, orientation, crop or interpretation invalidates dependent analysis. Changing only the timeline edit map reuses analysis through an explicitly verified remap. Text edits reuse approved geometry/alpha, but invalidate content-dependent layout and occlusion review if the visible region changes.
+
+## Foreground preservation and layer order
+
+Start with explicit relationships such as `person in front of title` and `hand in front of screen`. Scope a holdout to the affected layer/group; a hand protecting the phone need not hide a separate foreground caption. Validate cycles and contradictory depth/ordering constraints. Occlusion state can change over a shot, but that change needs a tracked spatial relationship or an authored interval, not unrelated per-pixel guesses.
+
+For known foreground crossings, subject alpha owns the silhouette. Use temporally consistent, calibrated depth for ordering genuinely interleaved objects; raw per-frame normalized monocular depth must not slice fingers or faces. Depth confidence is separate from alpha confidence. One global foreground matte also cannot solve a hand that is simultaneously behind one object and in front of another.
+
+The preparation workflow is prompted video segmentation → tracked identity → positive/negative corrections at difficult frames → temporal propagation → alpha refinement around hair/fingers/motion blur → review. Track through disappearance/reappearance; reset temporal state at cuts. Sudden area collapse triggers a review/re-seeding candidate, not blind automatic acceptance: genuine occlusion or leaving the frame can also shrink a subject. Preserve legitimate holes between fingers and never assume every disconnected component is an error. Do not blur consecutive masks indiscriminately: that creates lag and ghost hands.
+
+Composite with explicit premultiplied-alpha and color-space conventions. Opaque protected interiors must preserve source pixels. At soft edges, copying `alpha × original plate` over a new background can retain the old background in hair and create a double edge. High-quality edge replacement requires decontaminated foreground color or a credible original-background estimate; document the approximation when those are absent. A soft mask alone does not prove a clean composite.
+
+Add diagnostic views for source, subject alpha, surface coverage, correspondence, confidence, final composite and difference inside protected regions. Provide brush/polygon corrections and an event-range view. Start with people in front of a title/board, then a separately gated close-up hand correction workflow; a portrait matting model is not proven on isolated fingers.
+
+## Four different placement operations
+
+1. **Planar insert:** board or phone. Render animated artwork in surface coordinates, project it with the track, clip to surface coverage, then apply foreground visibility. Explicitly exclude the bezel and check the full animated text bounds.
+2. **Reskin an existing rigid curved object:** select the original can, identify its body/silhouette and cap, estimate its pose/axis/radius and camera relationship, and fit a cylindrical UV or mesh mapping over time. Map the editable label into that surface; preserve lids, highlights, existing silhouette and contact shadow where appropriate. Reapply hand visibility. A featureless cylinder has ambiguous rotation; allow an authored seam/pose constraint and mark unobservable ranges.
+3. **Replace or insert a 3D object:** requires explicit camera/scale/contact placement and foreground ordering. If replacing an object whose silhouette changes, remove the old object's exposed pixels and recover newly revealed background. Clean-plate/inpainting work is separate, reviewed, and cannot be substituted by an extra mesh on top. Added objects need their own shadows/reflections; reskinning normally retains the original contact evidence.
+4. **Deforming surface:** cloth/skin needs a tracked mesh, dense UV correspondence or an atlas with visibility and disocclusion handling. A homography or cylinder is not sufficient. Start with a short cloth patch and a correction/import path; leave arbitrary bodies and loose folds experimental until tested.
+
+No mask fixes an impossible placement: if the recorded hand sweeps through the volume of an inserted can, making the whole hand foreground only changes the visible contradiction. Move the insert to a collision-free location, choose another take, or regenerate blocking. Reskinning the existing can avoids creating that new volume. Preserving shading during a reskin also needs an appearance model: a simple multiply blend retains the old albedo and cannot freely change a dark label into a light one. Begin with a blank neutral can, fit a shading/specular residual, and document where exact material recovery is ambiguous.
+
+Existing tools demonstrate the video surface-editing route. Mocha Pro documents PowerMesh-driven inserts, grid warps and tracked motion blur. Layered Neural Atlases learns per-shot mappings/alpha to propagate an atlas edit; CoDeF fits a canonical field and temporal deformation. These are evidence for feasibility, not drop-in real-time browser solutions or licenses to copy proprietary engines. [Mocha](https://borisfx.com/products/mocha-pro/), [Neural Atlases](https://layered-neural-atlases.github.io/), [CoDeF](https://qiuyu96.github.io/CoDeF/)
+
+Lovart advertises texture generation and image editing. Its public page does not establish which model implements an observed wrap effect or that exact artwork can be transferred through video with temporal geometry guarantees. Use it as a visual reference, not an inferred backend architecture. [Lovart texture feature](https://www.lovart.ai/features/ai-3d-texture)
+
+## Motion design is part of acceptance
+
+Every authored example declares its attachment space and timing: screen-space graphic, surface-attached artwork, or world-space object with a camera. Surface-attached text inherits the observed perspective; world text requires a real solve or an explicitly labeled authored approximation. Static printed labels should remain attached naturally; expressive animation belongs in a reveal, digital display or surrounding title when the brief calls for it.
+
+Deliver editable examples covering: staggered word/character reveals with readable holds; masked wipes and line draws; spring-like scale/rotation settles; text-on-path/orbits; tracked perspective titles; and a foreground-aware headline passing behind a person. Include at least one 3D/extruded or shader-treated title. Expose timing, stagger, easing, amplitude, path, typography, palette and attachment controls without restricting arbitrary renderer code.
+
+All code motion is a deterministic function of explicit clip animation time and seeded parameters, with any source/timeline mapping authored explicitly. Analytic curves or baked simulation caches make reverse/random seeks reproducible; never integrate a spring from the previous requested frame. Paused Web Animations can be driven through `currentTime` rather than wall-clock playback. Load fonts before measurement and verify script shaping, fallback and localized wrapping. [Web Animations clock](https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime)
+
+Compose the local animation before surface/camera projection, then visibility. Preserve the existing fixed `clock.mediaTime` for held footage/derived frames while code samples the shutter. Evaluate holdout against each code shutter sample so blurred letters cannot trail onto a protected face. This keeps correspondence; it does not reconstruct sub-frame subject motion absent from the plate. Label that physical limit and test moving masks rather than promising perfect motion-blurred edges.
+
+## Candidate analysis runtimes and evidence
+
+| Candidate | Intended role | Evidence and decision |
+|---|---|---|
+| SAM 2 / SAM 3.1 | Prompted object identity and temporal masks | SAM 2 code/checkpoints are Apache-2.0. SAM 3.1 is released, but uses SAM-specific terms and documented CUDA prerequisites; do not assume it runs in the target webview or inherits SAM 2's license. Neither automatically supplies hair alpha. [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3](https://github.com/facebookresearch/sam3), [SAM license](https://github.com/facebookresearch/sam3/blob/main/LICENSE) |
+| EdgeTAM | Optional lightweight tracked-mask candidate | Apache-2.0 code/checkpoints; upstream includes CoreML export and reports 16 FPS on iPhone 15 Pro Max. This is a segmentation benchmark, not a measured desktop export rate or alpha-quality guarantee. [Repository](https://github.com/facebookresearch/EdgeTAM) |
+| Robust Video Matting | Human-alpha benchmark and candidate adapter | Temporal recurrence; upstream provides ONNX, CoreML and TF.js variants. Reported RTX 3090 HD throughput is 172 FPS with FP16, downsample ratio .25, batch/chunk 1, excluding the video conversion pipeline. This is not a measured app speed. GPL-3.0 requires a deliberate distribution/compliance decision; it is not a permissive drop-in. [RVM](https://github.com/PeterL1n/RobustVideoMatting) |
+| MatAnyone family | Quality comparator for temporal matting | MatAnyone's S-Lab terms restrict ordinary use to non-commercial purposes; separately negotiate rights before commercial integration. Do not mistake a hosted listing for a redistribution grant. [License](https://github.com/pq-yang/MatAnyone/blob/main/LICENSE), [MatAnyone2 license](https://github.com/pq-yang/MatAnyone2/blob/main/LICENSE.txt) |
+| Video Depth Anything Small | Coarse temporally coherent depth | Upstream Small is Apache-2.0, Base/Large CC-BY-NC-4.0. Pin the exact checkpoint and verify its terms. Relative depth still needs registration/calibration and cannot be the sole skin-edge matte. [Repository](https://github.com/DepthAnything/Video-Depth-Anything) |
+| ONNX Runtime Web / native adapters | Optional execution backends | WebGPU where supported; WASM CPU fallback for validated small models. CoreML/native GPU candidates belong behind a host adapter. Probe operators, memory, webview support and seek/reset behavior; API support does not establish model portability. [ORT WebGPU](https://onnxruntime.ai/docs/tutorials/web/ep-webgpu.html) |
+
+No model is selected for distribution yet. Benchmark host-native and browser paths on actual Apple Silicon, Windows discrete/integrated GPU and CPU-only systems. Record decode + resize + inference + transfer + composition + encode, cold/warm latency, p50/p95, memory and energy, plus edge/temporal quality. Target cached 1080p playback at the project's 24/30 FPS; real-time inference is a measured optional tier, not a prerequisite for final export.
+
+## Ordered milestones and release gates
+
+| Phase | Deliverable | Exit evidence |
+|---|---|---|
+| H0 | Reclassify failed examples; retain originals; establish regression fixtures and source-frame annotations | Each reported failure has a reproducible source/mask/composite range; no production-ready badge on an unreviewed shot. |
+| H1a | Versioned correspondence/validity contract, shared frame access, explicit per-group holdout, correction import; human foreground first | Person crossing board/title passes every crossing frame in preview and export; missing/stale/short data fails safely. Include one kinetic headline now. |
+| H1b | Close-up hand segmentation, collapse detection and correction propagation | Thumb remains whole through entry, tap, lift and exit; all-frame correspondence, visibility and edge checks pass. Portrait-model success cannot waive this gate. |
+| H2 | Rigid-cylinder surface mapping and appearance-preserving label wrap | One original can, correct scale and placement, readable exact label, no exposed duplicate body, hand fully coherent through the crossing. |
+| H3 | Full kinetic typography examples and controls | At least three distinct treatments, random-seek/reverse/shutter checks, localization, readable holds and correct occlusion for every treatment. |
+| H4 | Optional accelerated analysis adapters | Actual device/end-to-end benchmark plus license/checkpoint receipts; cached fallback remains usable. |
+| H5 | Deformable meshes/atlases, calibrated 3D insertion and controlled generation | Separate experimental gates for cloth folds, camera/geometry consistency, clean background recovery and material fidelity. |
+
+Use generated and filmed examples; static, pan/push and handheld; fast finger entry, loose hair, motion blur, full occlusion/reappearance, crops, reverse/retime, and missing frames. For short clips, inspect every decoded output frame in contact sheets and full-resolution crossing crops, plus normal/slow playback. For longer clips, automated all-frame checks and reviewed event ranges supplement a complete playback; disclose unreviewed frames. Three-frame checks are smoke tests only.
+
+Proposed measurable gates: zero missing correspondence entries; no overlay pixels in annotated opaque foreground interiors before encoding; no detached/erased finger or head in any reviewed frame; measured boundary error on annotated events (target p95 ≤2 output pixels at 1080p, any >4 triggers correction); surface landmark drift and silhouette mismatch reported separately from tracker confidence; no unplanned subject-depth flips; layout bounds valid throughout animation. These are engineering targets to calibrate against annotations, not achieved benchmark results. Semi-transparent hair is evaluated with alpha/edge-color and temporal metrics, not a binary zero-overlap test. Flow-warp residuals, sudden area changes and components flag review, but cannot establish truth without annotations.
+
+The acceptance report records exact revisions, frame ranges, assets, model/correction provenance, annotated failures, best and worst frames, the full playable clip, and separate **render correctness**, **analysis correctness**, **art direction** and **final usability** verdicts. An export that completes can still fail the shot.
diff --git a/skills/editableframes/references/hybrid-concurrent-recovery-2026-11-14.md b/skills/editableframes/references/hybrid-concurrent-recovery-2026-11-14.md
new file mode 100644
index 0000000..ab82847
--- /dev/null
+++ b/skills/editableframes/references/hybrid-concurrent-recovery-2026-11-14.md
@@ -0,0 +1,52 @@
+# Concurrent crash recovery: adopted with a bounded platform scope
+
+2026-11-14 · FLOW1 remains partial · three additional scoped checks resolved
+
+The SDK now uses numbered lock generations for edits/imports and a private job registry for CLI render recovery. This replaces the rejected stale-file deletion proposal. The coordinator applied Fable's replacement to the current SDK, fixed a mutating dry run, added cancellation regressions, and reran real-process fault tests before adoption. This does not close native-app or provider integration.
+
+## What changes for the user
+
+- Interrupting `asset-add` with Ctrl-C cancels its decoder, removes its staging files and leaves the project editable. SIGTERM and SIGHUP follow the same cleanup path.
+- After a killed edit/import, the next edit can take over a provably dead owner's numbered lock without deleting a successor's lock. An orphaned decoder is not signalled; its files remain until it exits and a later edit cleans them.
+- Each CLI render records its owned temporary locations before allocating them. The next render attempts recovery for that project. `recover DIR` performs the same recovery explicitly.
+- Automatic recovery sends no signals. A dead job with running children is left intact and reported. `recover DIR --stop-browsers` explicitly requests SIGTERM for that job's verified orphan browser; it never uses SIGKILL.
+- `recover DIR --dry-run` only reports. The coordinator found that the proposed version created registry/lock files; the adopted version does not create, acquire, reclaim or release anything.
+- Published output is preserved. A dead reservation is removed only when its receipt identifies that job and no output was published. Unknown owners and records are left alone.
+
+The job registry defaults to a private per-user run directory and can be isolated with `EDITABLEFRAMES_STATE_DIR`. Recovery instructions never come from a downloaded project's job file. This is still trusted local code, not protection against hostile code running as the same user.
+
+## Why the lock changed
+
+The rejected proposal read a dead lock, removed it, and created its replacement. A second contender could remove the first contender's live replacement. Fable reproduced simultaneous holders and also found false death detection across time zones/process renaming and receipt deletion by concurrent recoverers.
+
+The new protocol publishes a complete next-generation owner record using exclusive creation. Contenders never remove the current owner's record to acquire. A contender that resumes behind a newer generation withdraws. Owner identity uses host, PID namespace, PID and UTC start time; an inconclusive process query refuses takeover. Recovery of shared output reservations is serialized separately.
+
+This passed the recorded schedules and real processes; it is not a universal proof for every filesystem or operating system.
+
+## Verification on the adopted source
+
+| Fresh coordinator check | Result |
+|---|---|
+| SDK unit tests | 147 passed, zero failed |
+| Build | Passed |
+| Browser and beta integration | Passed using installed Chromium; no new browser download |
+| Real stale-lock contention | 30 rounds, six contenders, exactly one winner per round, zero overlapping holders |
+| Real CLI edit/import faults | 19/19 passed |
+| Real browser-render crash/recovery faults | 21/21 passed |
+| Sentinels | Files, unrelated browser and unrelated process survived |
+| Dry-run and graceful import cancellation regressions | Included in the 147 tests; SIGINT/SIGTERM/SIGHUP and no filesystem writes |
+
+The coordinator reran the worker's integration harness against the actual SDK checkout in separate disposable projects. These are independent executions of the same harness, not an independently designed fault model. Browser tests were serialized with other rendering work. No paid call, credential read, model download or native-app launch was needed.
+
+Fable's larger retained study additionally reports 30,650 exhaustive two-contender schedules, 80,000 sampled schedules with injected deaths, and 400 actual killed-holder rounds. Those are worker results, separate from the fresh coordinator runs. Four failed designs remain retained, including a recovery guard that wedged when its own recoverer died.
+
+## Still open
+
+- Evidence is one Mac on APFS. Linux was not run. Windows cannot verify owner identity and does not automatically take over or recover dead owners.
+- Caching/network filesystems and same-named machines sharing a project are unsupported by this evidence. Power-loss durability was not tested; lock records are not an fsync protocol.
+- PID/start-time rechecks narrow process-reuse risk but are not an atomic OS process handle. Explicit browser termination remains opt-in.
+- Old bare lock files from earlier SDK versions cannot be safely attributed and need deliberate manual recovery after confirming no owner is running.
+- Library `render()` callers and preview processes do not automatically gain the CLI's job ownership contract. Native app integration remains separate.
+- Asset removal, arbitrary live resources outside pinned assets, provider billing/reconciliation and audiovisual playback review remain open.
+
+Existing projects require explicit `rebind` after the runtime change. Code-generated scenes and accepted generated footage are unchanged: this work makes interruption/restart safer, not the picture more realistic. LIGHT1, MASK1, HUMAN1 and the story/interaction quality boundaries retain their previous limits.
diff --git a/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md b/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md
new file mode 100644
index 0000000..f3c65d0
--- /dev/null
+++ b/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md
@@ -0,0 +1,84 @@
+# Hybrid gap closure — 2026-11-14 checkpoint
+
+This is an active research checkpoint. The [experiment dashboard](hybrid-experiment-map.html) now has a Gap closure tab with scoped subchecks, attempts and retained artifact descriptions. No whole work item is declared finished. No new hosted-model calls were made in this round.
+
+| Work item | New measured evidence | What remains |
+|---|---|---|
+| ST1: dependable authored story | Resumed original Fable film completed. Coordinator reproduced all 1,152 sequential frame hashes, 228 new shuffled/reverse/cut-adjacent checks and all 12 exposed control changes/restorations. | Acting, physical contact, face finish, soundtrack listening, native app integration and other hardware. |
+| ST1: CLI delivery specimen | Three source frames (228, 696, 960) exported through the current CLI. Exposure edit changes all three; stale proposal rejected; undo restores pixels exactly. | This is three sampled frames, not full-film audio export or desktop acceptance. |
+| TRACK1: misleading confidence | Target-interior texture diagnostic flags all 49 frames of the retained synthetic wrong-track case. Six new regressions and 13 existing plate tests pass. | Geometry is unchanged: worst error 6.861 px at correlation 0.956. Wrong textured planes can evade this warning. Original real-footage failures remain unavailable. |
+| FLOW1: recoverable generation | Network-free local prototype passes 11 crash/concurrency/input/output fault tests using retained real pickup and handoff media. | Native transport/UI, actual provider reconciliation and atomic managed-asset import. No claim of provider idempotency or prevented real charges. |
+| ST2–3: reusable cast / contrasting styles | First brief: three styles. Second carry/set-down brief: two styles,80 additional frame samples,20 control checks,672 decoded/replayed frames and six deliberate contact faults detected. [Second-brief evidence](hybrid-story-second-brief-2026-11-14.md). | Cast/rig/look reuse is demonstrated; action required new code. Tray-specific grip, natural movement, listening and full native delivery remain open. |
+| LIGHT1: moving product illumination | Independent refinement avoids observed notebook glare, produces finite-source café penumbrae and lights cup front after an explicit lamp move. Coordinator verifies96 new samples,21 edits and936 decoded/recomputed frames. [Corrected measurements](hybrid-lighting-refinement-2026-11-14.md). | Diagnostic-sphere contamination corrected; fixed poses only. Floor/screen tradeoffs, negligible practical-light reflections and composition/quality limits remain. |
+
+## Story: the earlier failed draft is historical
+
+The original Fable worker resumed and fixed two shot routines that read camera position before setting the current frame's camera. Its final film remains 48 seconds, 720×1280, 24 fps. The earlier recovered draft and failed seek result are retained; they are superseded for current runtime acceptance, not erased.
+
+The coordinator performed a fresh full sequential pass, additional seek samples, and one change/restoration per declared control. No page or resource errors appeared in that pass. These are same-machine, same-browser comparisons. They do not prove pixel identity on another GPU/browser or high-quality acting. The source still uses painted facial detail, rigid body segments, approximate lip-sync, stock speech and system fonts. Audio level/timing measurements are not a listening review.
+
+The CLI specimen exposed a missing managed Chromium installation even though another compatible Chromium existed. An explicit `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` option now selects an existing absolute executable path, with no automatic download or silent fallback. Rendering verifies launch and records the browser version plus whether an override was configured. `doctor` checks file presence; it does not claim launch compatibility. A runtime-source change intentionally requires project rebind under the existing binding contract. The CLI specimen passed after explicit rebind. All 136 SDK unit tests pass, including configuration validation and distribution documentation consistency.
+
+## Tracking: a useful warning is not a repaired track
+
+The diagnostic samples the selected quad's interior, excluding its surrounding template margin, and checks spatially distributed two-axis texture. It identifies blank targets, a single edge, concentrated detail and out-of-frame support. Its thresholds are heuristic, not calibrated accuracy probabilities. The result reports `accuracy_verified: false`; even distributed texture does not approve identity or visibility.
+
+The comparison video shows the same wrong geometry before and after, with an added review warning. Do not interpret the warning as a correct replacement surface, an automatic hide/reject decision, a new tracker, or a visual-native-UI feature. Independent surface identity, occlusion recovery and boundary accuracy remain research gates.
+
+## Generation workflow: tested contract before host integration
+
+The local prototype freezes scene revision, action, provider/model and ordered reference hashes. It persists an attempt marker before any external transport would begin. A forced process exit at that point reopens as ambiguous; automatic retry is refused. Explicit provider-ID reconciliation can resume the record. Two concurrent owners cannot both start the same row.
+
+Changed reference order/bytes, changed endpoint/action and stale revisions are rejected. Decoding is separate from visual acceptance. Corrupt or failed replacements preserve the last accepted take across restart; a modified output cannot be accepted. Variable-rate media requires an explicit conform step.
+
+The retained pickup decodes to **121 frames / 5.041667 s**, and the handoff to **169 frames / 7.041667 s**, both 1280×720 at 24 fps. Requested five/seven-second durations must not replace measured timing.
+
+Limits: this local SQLite prototype assumes one transport owner has stopped before recovery. Its local approval field is not an authorization boundary. Mutable file paths need atomic managed-asset import. No actual provider timeout, credit reconciliation, authenticated desktop integration or new paid request was exercised.
+
+## Remaining gates
+
+Hair/contact whole-clip evidence, mixed human/product directional lighting, nested transparent materials, real additional computers, SAM 3 access/runtime, camera solve (feature 6), and reconstructed worlds (feature 13) remain open. Authored fantasy scenes do not complete camera solve or world reconstruction. Neither a completed worker nor passing integrity tests establishes visual production readiness.
+
+## Mask audit and provider interruption
+
+[Controlled five-background hair audit](hybrid-mask-audit-2026-11-14.md): same foreground RGB,96 frames and four alpha variants. Repair reduces measured temporal residual by37.6%, but an analytic visibility counterexample demonstrates why smoothing is not accuracy. MASK1 remains partial. Fable reached its provider limit before this review; Opus reached the same limit while diagnosing dark submerged ice. Glass stills/sources are retained but unverified; GLASS1 now needs resumption and verification, rather than remaining shown as actively running. No new hosted calls.
+
+## Resumed glass study
+
+The earlier interruption is historical. [Verified nested-transparency follow-up](hybrid-glass-study-2026-11-14.md) changes GLASS1 to partial: 54 fresh frame comparisons and five control restorations pass; sixteen clip files decode. Source and isolated layers explain why stock capture hides contents. R2 restores cylinder inversion but omits submerged ice; the matched Cycles candidate preserves stronger nested detail at substantial cost. General transparent-material support remains open.
+
+## Resumed hair isolation study
+
+The provider interruption is historical. [Completed mask follow-up](hybrid-mask-followup-2026-11-14.md) keeps MASK1 partial: source preparation, context and resolution are separated; the room-aware repair reduces a partial halo proxy by48% but synthetic yellow composite error by only2%. Coordinator checks reproduce36 frames, nine control restorations, a fresh mount and all12 video decodes. Reference data remains model-assisted; no general hair-accuracy or production approval follows.
+
+## Stronger models tested; MASK1 remains partial
+
+[Verified local model comparison](hybrid-stronger-matting-2026-11-14.md): ResNet50 reduces a room-opacity proxy but loses more hair; ViTMatte softens low-contrast curls. Coordinator reproduces the synthetic ranking reversal, 36 fresh renderer samples, 13 controls, a fresh mount, saved CPU/MPS alpha agreement within one code and all 12 comparison-video decodes. A fixed-region head/body combination is experimental. No whole work item closes; 26 scoped subchecks remain resolved.
+
+## Local CLI round trip and audio repair
+
+[Verified replay workflow](hybrid-roundtrip-workflow-2026-11-14.md) adds two scoped subchecks, bringing the checkpoint to 28 resolved subchecks and zero whole items closed. The coordinator fixes portable-renderer audio loss and unity-rate stretching in the SDK, verifies full film/trim exports and repairs a separate reference-descriptor mismatch in the research ledger. Native import, provider reconciliation, audio listening and normal-speed visual acceptance remain open.
+
+## Moving reflections checkpoint
+
+LIGHT1 stays partial. New worker evidence is under independent review; the total remains 28 scoped checks resolved and 0 whole work items closed. [Results and remaining defects](hybrid-moving-reflections-2026-11-14.md).
+
+## Shared human/product light checkpoint
+
+HUMAN1 moves from working to partial. No new independently resolved subcheck: 28 remain. Broad relighting and the proposed simple guard are not validated. [Evidence](hybrid-shared-human-light-2026-11-14.md). Follow-up reflection repair and import recovery hit the Claude API rate limit; no completed result is claimed.
+
+## Import and recovery checkpoint
+
+Validated imports and expected export identity add two scoped checks: 30 resolved, 0 whole items closed. The worker recovery proposal remains unadopted after the coordinator reproduced concurrent stale-lock takeover. [Evidence](hybrid-import-recovery-2026-11-14.md).
+
+## Independent moving-reflection review
+
+LIGHT1 remains partial; 30 scoped checks remain resolved and 0 whole items are closed. Pixel-based review improves flat self-reflection and local irradiance but corrects earlier geometry-only accuracy claims. A matte offline comparison fails in one penumbra arrangement; glossy calibration remains untested. [Evidence and next experiment](hybrid-reflection-review-2026-11-14.md).
+
+## Concurrent recovery adoption checkpoint
+
+33 scoped checks are resolved, with 0 whole work items closed. Fresh verification passes 147 unit tests, build/browser/beta, 19 import/edit faults, 21 render faults and 30 rounds of six contenders. Numbered locks and private CLI render records replace the rejected stale-unlink design. Automatic recovery sends no signals; explicit browser termination is opt-in. The coordinator also repaired mutating dry-run behavior. Native/provider integration, other platforms, network filesystems and power-loss durability remain open. [Implementation, evidence and limits](hybrid-concurrent-recovery-2026-11-14.md).
+
+## Direct-light calibration checkpoint
+
+35 scoped research subchecks are resolved, with 0 whole work items closed. The café point-shadow bias mismatch is explained and direct light repaired in A/I. A single-scatter GGX direct reference agrees with separate CPU integration across three retained poses. Coordinator recomputation and 48-frame decode confirm the recorded evidence, not fresh-render or motion approval. No default shader changes are adopted. Mixed bounces, nearby reflections and a bright horizon band remain; offline rendering remains a code-based route, not a reason to regenerate known geometry with diffusion. [Evidence and next motion/proxy test](hybrid-light-calibration-2026-11-14.md).
diff --git a/skills/editableframes/references/hybrid-glass-study-2026-11-14.md b/skills/editableframes/references/hybrid-glass-study-2026-11-14.md
new file mode 100644
index 0000000..afd7ab3
--- /dev/null
+++ b/skills/editableframes/references/hybrid-glass-study-2026-11-14.md
@@ -0,0 +1,41 @@
+# Nested glass, liquid and ice: verified limits
+
+2026-11-14. **GLASS1: partial. No production approval or integration patch.** The previously interrupted study resumed and completed. Its original failures and coordinator verification are retained. New hosted-model spend: $0.
+
+## What changed
+
+The stock three.js r180 transmission capture samples opaque objects and, on this tested GPU path, back faces of double-sided transmissive objects. Transmissive front faces do not generally see each other. This explains why the glass can conceal the liquid and ice. The coordinator inspected this path in the installed renderer source. Clean geometry fails too; removing overlaps alone does not solve the capture limitation. The double-sided back-face path is skipped when WEBGL_multisampled_render_to_texture is present, so the single-sheet workaround is not a portable default.
+
+| Route | Adding liquid: mean RGB code change in the same region | Main limit |
+|---|---:|---|
+| Original stock approach | 0.37 | Contents almost invisible |
+| Clean geometry, stock approach | 0.74 | Geometry cleanup alone does not fix capture |
+| Closed double-sided shell | 0.68 | Inner shell wins the capture |
+| Single-sheet workaround (R1) | 43.96 | Flat tint, milky ice; abandons closed shell |
+| Layered cylinder refraction (R2) | 72.10 | Over-bright liquid, dark upper ice, submerged ice omitted |
+| Cycles reference | 50.30 | Slow, authored interface setup and physical approximations |
+
+These are visibility signals, not quality scores. A larger signal is not necessarily better. R2 restores cylinder lens inversion, but has a bright base band and only supports a vertical liquid cylinder with a flat top. Its omission of submerged ice is explicit, not a solved feature.
+
+## Independent coordinator verification
+
+- 54 new out-of-order raster frames across three routes and two shots match the saved lossless video pixels exactly.
+- Five independent control edits change pixels and restore identical PNGs; no page errors.
+- Eight full lossless clips and eight full MP4s decode: 72 frames each, 1280×720, 24 fps. There are eight unique sequences, not sixteen independent scenes.
+- Recomputed the six liquid-visibility values above from retained geometry masks and stills.
+- Recomputed liquid-region brightness range under the moving practical: R1 4.73, R2 2.78, Cycles 12.56 luma codes. The fast routes respond weakly through the liquid.
+- Rechecked all five emissive calibration swatches: maximum difference at most one code in the sampled patches.
+
+The coordinator inspected still comparisons and renderer source. No fresh Cycles rendering, normal-speed perceptual review, or independent performance benchmark was performed. Geometry masks are worker-generated, not human ground truth. An initial measurement invocation ran before queued capture finished and failed for a missing receipt; the subsequent complete verification passed.
+
+## Reference boundaries
+
+The reference shares geometry export, camera path, HDR and the three.js Neutral+sRGB display transform. It is a much better controlled comparison than the earlier mismatched tone maps. It is still not physical ground truth: caustics are off, glass casts an opaque shadow, nested interfaces use small insets and relative IOR changes, and pixel filters differ. Raster omits scene reflections and indirect bounce, while the reference includes them; raster uses a point highlight versus an 8 mm source in Cycles. The worker measured a 4.2-code grey-sphere difference and a 20.6-code chrome-sphere difference, with chrome-only environment alignment correlation 0.92. Do not attribute every pixel difference solely to transmission.
+
+## Route decision
+
+Keep editable raster as the default for the already-supported opaque scenes. For hero shots whose nested transparent contents matter, offer a separately validated offline quality route; the tested Cycles setup is the strongest candidate for this particular drink, not a general certified export path. Keep R2 experimental and opt-in for authored cylindrical drinks with its omitted ice and lighting limitations disclosed. Do not silently replace closed geometry or omit nested objects in a quality export.
+
+Worker timings on one Apple M6 / 16 GB Mac: R2 about 11.5 ms per frame for synchronized rendering, about 96 ms including capture; Cycles 7.2–8.4 seconds per frame at 64 samples plus denoising, approximately 9–10 minutes per 72-frame clip, with peak RSS 4.3–5.1 GB. These measure different pipeline scopes and are not ordinary-computer guarantees. No NVIDIA hardware was used.
+
+Still open: arbitrary liquid shapes, glass/base refraction, submerged and above-surface ice, scene reflections, calibrated brightness, moving practical-light response, other hardware, native integration, and visual approval. No whole research item is closed by the passing integrity checks.
diff --git a/skills/editableframes/references/hybrid-import-recovery-2026-11-14.md b/skills/editableframes/references/hybrid-import-recovery-2026-11-14.md
new file mode 100644
index 0000000..aa5fbcd
--- /dev/null
+++ b/skills/editableframes/references/hybrid-import-recovery-2026-11-14.md
@@ -0,0 +1,40 @@
+# Validated imports and gated exports; crash recovery still open
+
+> Superseded recovery status: numbered locks and bounded CLI job recovery are now adopted after fresh fault tests. The rejected proposal below remains historical evidence. [Current implementation and limits](hybrid-concurrent-recovery-2026-11-14.md).
+
+2026-11-14 · FLOW1 remains partial
+
+The worker reproduced corrupt imports, orphaned render resources, stale edit locks and export races on one Mac. Its full scratch patch is retained as a proposal. Coordinator review adopted only private-copy import validation and expected export identity checks. Automatic job recovery, stale-lock breaking, asset removal, runtime rehashing and the self-SIGKILL test hook are not adopted.
+
+## Implemented subset
+
+`asset-add` now copies into a private staging directory, hashes the copy, validates its declaration and JSON data, strictly decodes media with FFmpeg, and runs the existing preparation checks before publishing the manifest. Prepared-analysis receipts also validate referenced alpha media rather than taking the early data-only return in the worker proposal. A candidate whose source changes during copy is pinned under the copied bytes' hash. Existing immutable content is never overwritten. Normal validation failure cleans the staging directory and leaves project and manifest unchanged.
+
+The final content file is installed before the manifest. A crash between those steps may leave unreferenced bytes. SIGKILL may also leave staging/decode directories and the old edit lock. No automatic sweep or lock breaking is enabled by this change.
+
+`render --expect-revision R --expect-binding B` refuses a mismatched project snapshot before allocating output or launching a browser. Missing flag values are refused. These optional flags bind a caller's gate to the snapshot the renderer reads; they do not freeze arbitrary project files or external network resources. Hosts must compare output receipts with their own accepted take/ledger state before publication.
+
+Imports now pay the validation/decode cost earlier. The worker measured a retained seven-second 720p import at approximately four seconds rather than 61 ms. This is worker evidence on one Mac, not a general performance guarantee.
+
+## New finding: concurrent stale-lock recovery is unsafe
+
+The coordinator reproduced a race in the worker's proposed lock recovery. Two contenders read the same dead owner. The first removes the stale lock and installs its live successor. The second then writes its stale-owner record over that new lock, archives it and acquires another lock. Both calls return success before either releases.
+
+The reproduction deliberately controls filesystem scheduling in a scratch project, using the proposal's actual `acquireLock` function. It is not a timing-only suspicion and signals no processes. This blocks adoption of automatic lock breaking despite the worker's passing sequential recovery tests.
+
+Additional proposal limits remain: process identity uses `ps` with second-resolution start time; imported job records are trusted to name same-user processes; Playwright artifact routing uses an undocumented launch option; Windows identity and preview recovery are untested. These are outside the adopted subset.
+
+## Coordinator verification
+
+Three regression tests cover valid video/audio/image imports, corrupt/truncated media and invalid JSON refusal, immutable IDs, invalid track data, derived frame-count mismatch, missing prepared-alpha references, copied-byte identity during a source change, and stale export rejection before output allocation. The full suite passes 140 tests and the required build passes. The stale-lock race above is retained separately as a failing proposal experiment. A fresh real-CLI smoke run also passed: media init, validated import, explicit rebind, stale-revision refusal, and three PNG frames whose receipt matches the expected revision and binding. This is a short CLI check, not a full native-app export.
+
+The full worker suite reported 12/12 importer cases, 8/8 cancel/kill scenarios and 3/3 removal recoveries in its scratch patch. Those numbers are not tests of the adopted subset and are not carried forward as production coverage. Its partial-checkout regression baseline lacked website files; the coordinator used the full current SDK checkout instead.
+
+## Still open
+
+- Recovering SIGKILL leftovers without competing recoverers breaking a live successor's lock.
+- Safe asset removal with useful history recovery and clear missing-asset errors.
+- Runtime/source changes during bundling and live static paths outside pinned assets.
+- Native desktop import/export integration, provider reconciliation, billing/idempotency and other hardware/platforms.
+
+Existing projects require explicit rebind because the renderer implementation is part of runtime identity. All generated footage remains unchanged; these fixes protect the path that imports and exports it.
diff --git a/skills/editableframes/references/hybrid-learning-checkpoint-2026-11-15.md b/skills/editableframes/references/hybrid-learning-checkpoint-2026-11-15.md
new file mode 100644
index 0000000..2a30201
--- /dev/null
+++ b/skills/editableframes/references/hybrid-learning-checkpoint-2026-11-15.md
@@ -0,0 +1,31 @@
+# Illustrated stories and real-mesh reflections: 15 November 2026
+
+Research evidence, not a runtime release or production approval. The shared private learning notebook holds the films, comparisons and retained failures. These conclusions are scoped to two delivered studies on one Mac.
+
+## Illustrated 2D stories now have a concrete example
+
+A 34-second original office/shop/city cartoon was drawn entirely with Canvas 2D code through `defineRenderer` and `mountRenderer`. The recurring cast, illustrated sets, exact signage and charts demonstrate another code-authored video family beyond the earlier 3D fantasy examples.
+
+Labels, captions, palette, framing and selected acting choices remain editable in preview. Changed dialogue requires rebuilding the recorded voices; cut-time edits require soundtrack alignment; a new MP4 always requires export. The full film used a custom harness and FFmpeg audio muxing. The real CLI was checked on four edited frames and a 48-frame silent specimen, not the whole film with sound.
+
+The worker reports deterministic seeks and five edit/restores. The coordinator verified deliverable hashes, full decode and duration, and inspected the contact sheet. Neither watched normal-speed playback or listened to the soundtrack. Acting is pose-based, mouth motion follows volume, the night palette misses signs and the facepalm obscures an eye. Reuse across a second story remains untested. A watchable example does not close the broader story-production track.
+
+Next: viewing feedback first; then a second script using the same cast if the visual direction is useful.
+
+## Real meshes narrow the fast-reflection route
+
+The next experiment used a third-party laptop mesh and a procedural cup. Simple per-part reflection proxies improved the laptop deck reflecting its own lid and screen. The same rule represented a ring handle as a solid box, incorrectly darkening the cup wall beside it. One proxy per entire product also lost the laptop's self-reflection.
+
+Keep proxy rendering as a bounded preview/export candidate for slab-like parts. Use offline rendering of the same code scene for complex hollow shapes, highlights reflected between glossy surfaces and diffuse bounce light. This is a renderer choice; it does not require diffusion.
+
+The measured comparison uses diagnostic materials, not the asset's final coatings. Hero-material previews are stills only and uncalibrated. Display reflections, edge quality, other devices and normal-speed review remain open. LIGHT1 stays partial and no default shader or integration patch is adopted.
+
+The worker retained failed tuning passes and rendered a full 84-frame offline comparison. The coordinator decoded the comparison clips and inspected the handle failure crop; the numerical transport results were not independently recomputed in this handoff.
+
+## Routing remains per shot
+
+- Code scene: exact graphics, illustrated characters, controllable objects and authored motion.
+- Slower rendering of that scene: complex light transport where the geometry and materials are available.
+- Joint generated performance: photoreal people and products interacting when suitable rigs, captured motion or assets are unavailable.
+
+The last route is supported by earlier interaction trials, not newly tested by these lighting experiments. These are current practical choices, not a proof that a video category is impossible with code.
diff --git a/skills/editableframes/references/hybrid-light-calibration-2026-11-14.md b/skills/editableframes/references/hybrid-light-calibration-2026-11-14.md
new file mode 100644
index 0000000..e35e3a6
--- /dev/null
+++ b/skills/editableframes/references/hybrid-light-calibration-2026-11-14.md
@@ -0,0 +1,48 @@
+# Direct-light calibration and the remaining reflection boundary
+
+> Follow-up: [motion and spatial-proxy testing](hybrid-motion-proxy-2026-11-14.md) independently validates the one-bounce reference, demonstrates a polished-highlight shimmer limit, and corrects the old freeze/emitter/horizon claims. This page records the earlier checkpoint.
+
+2026-11-14 · LIGHT1 remains partial · research options only
+
+The unexplained café penumbra comparison is now explained and repaired for direct light in the retained research scenes. The remaining indirect-light discrepancy is explained but not repaired. A glossy direct-light reference has also been checked against a separate CPU integration method. None of the shader changes is adopted as a library default.
+
+## What changed
+
+The retained point-shadow bias was normalized against a roughly 500-unit depth range. A bias of -0.002 therefore allowed approximately one world unit of shadow leakage. That hid nearby cup, handle and saucer occlusion. The earlier arrangement-A agreement was partly cancellation between this leak and lamp-stem occlusion of the emitter samples, not a sound calibration.
+
+The opt-in repair uses a 3 mm world-space bias, directs the normal offset toward each light, excludes the lamp stem inside the bulb from that bulb's shadow maps, and uses a symmetric emitter sample distribution. Fixing only the bias exposed lampshade-interior self-shadowing; the second correction matters. Two failed clipping implementations are retained.
+
+| Direct lamp energy / Cycles reference; ideal = 1 | Retained | Repaired |
+|---|---:|---:|
+| A cup | 0.980 | 0.998 |
+| A saucer | 1.060 | 1.007 |
+| I cup | 1.351 | 1.000 |
+| I saucer | 1.115 | 1.008 |
+
+These are regional means, not per-pixel correctness. The coordinator independently recomputed them from the retained linear arrays and object masks. Absolute mean linear errors remain 0.00095–0.00520. The change in the retained styled café frames is subtle overall: worker measurements report 0.33–0.38 display codes mean frame change, with stronger differences at contacts. This is not a new finished advert.
+
+## One glossy reference, with a narrow material contract
+
+The worker matched geometry and matte lighting before comparing a white, single-scatter GGX metal cylinder. Cycles direct light agrees with the separate CPU GGX integral at approximately 1.000 mean ratio and 0.3–0.5% relative RMS over three tested poses. The coordinator recomputed the comparison on 1,486 / 1,649 / 1,649 retained sample points. This checks consistency of retained evidence, not an independent derivation or fresh render of the reference integrator.
+
+The raster's specular anti-aliasing widens the highlight. Removing that term brings its tail energy ratio from 1.10–1.12 to 0.995–1.008, including the worker's held-out light pose. Regional mean improvement does not eliminate residual pixel error: relative RMS remains 4.7–6.9%. Disabling anti-aliasing could introduce shimmer; that has not been tested. Clearcoat, Principled materials, textured roughness and arbitrary metal finishes are not covered.
+
+## Why the whole picture still differs
+
+The reflection probe has the wrong spatial view of the floor and misses the neighbouring sphere. A floor-plane correction improves the lower cylinder, but the upper bright band remains around 1.75× the reference. The modified clip still has about 18.5 display codes mean cylinder error, versus about 22.3 for the frozen method. A brighter result is not automatically a better result.
+
+The café probe captures mix bounce orders. After direct-light fixes, their indirect result matches neither a universal one-bounce nor a complete multi-bounce solution: it reaches 43–72% of the eight-bounce cup reference in these arrangements. The worker did not independently validate Cycles indirect light, and the eight-bounce still is noisy.
+
+## Routing decision
+
+1. **Editable raster:** useful for responsive staging and bounded direct-light/shadow work. Keep world-scale bias and emitter geometry explicit. Do not disable specular anti-aliasing globally from this study.
+2. **Offline rendering of the same scene:** the demonstrated route when nearby reflections, nested transparent materials or multiple light bounces matter. This remains code-generated video; it is not outside code generation's capabilities. A production adapter must preserve geometry, camera, material and light identity, expose unsupported features, and test export parity.
+3. **Joint diffusion take:** retain for photoreal human/object performance when usable geometry or controllable motion is missing. No diffusion was needed or tested here. A generated take keeps its internal lighting/action baked; overlays and whole-frame trim/crop remain editable under the earlier workflow.
+
+The boundary is assets, physical requirements and compute budget—not “all hard lighting needs diffusion.” The worker's CPU timings are about 1.5 seconds per 480×270 glossy frame and 20 seconds per 1280×720 matte café frame. They do not establish performance on typical computers.
+
+## Verification and next experiment
+
+The coordinator read the relevant installed shader code, recomputed four café ratios and three glossy reference comparisons, verified all 14 delivered-file hashes, decoded all 48 frames of the 2-second 1440×270 comparison, and inspected the café and glossy comparison stills. No fresh rendering, normal-speed viewing, sound review or cross-hardware test was performed. No runtime source changes or paid model calls were made in this checkpoint.
+
+Two scoped research subchecks are now resolved: direct café calibration for A/I, and retained direct-GGX reference agreement for three poses. LIGHT1 remains partial. Next: independently review the reference and test the anti-aliasing change under motion; try one bounded importance-sampled reflection lookup with explicit scene proxies against the same reference. Preserve failures and reject it if shimmer, cost or remaining errors make offline rendering the better route.
diff --git a/skills/editableframes/references/hybrid-lighting-followup-2026-11-14.md b/skills/editableframes/references/hybrid-lighting-followup-2026-11-14.md
new file mode 100644
index 0000000..06b5f26
--- /dev/null
+++ b/skills/editableframes/references/hybrid-lighting-followup-2026-11-14.md
@@ -0,0 +1,46 @@
+# Moving product lights — resumed study, 2026-11-14
+
+**Verdict: partial improvement in two local examples.** The resumed Opus study delivered eight before/after, hero/diagnostic clips. The coordinator independently reproduced sampled frames, individual control reversions and the principal region measurements. This does not approve either shot as a finished advert or establish a new native lighting feature.
+
+> **Correction and follow-up:** [Independent refinement and corrected measurements](hybrid-lighting-refinement-2026-11-14.md). Diagnostic spheres contaminated three earlier regions; the coordinator reproduced those contaminated pixels too. The corrected figures below use refs-off hero renders. The screen-veil and palm-gradient explanations below are also revised. New path/flag and finite-source results supersede the pending-follow-up status, without establishing general production readiness.
+
+## What changed
+
+The current notebook's direct key light moved, but its environment reflection card stayed fixed. The experiment now couples card direction, colour and intensity to the key controls and captures the lit floor/backdrop into the reflection environment. A product-footprint contact term replaces the earlier ellipse, which faded before the front edge.
+
+The café pastry received no light from the original practical lamp. Isolation renders show it behind the cup's shadow from that lamp. Removing the distance cutoff alone did not solve this. Moving the lamp between/behind the objects and reducing competing fill produces a visible pastry rim light. The revised set therefore differs from the original placement.
+
+These are explicit source changes in retained experimental scenes. They are not automatic scene understanding or a generic learned relighting model. The photographed café backdrop is unchanged.
+
+## Independently recomputed observations
+
+Values are image-code measurements, not perceptual scores or calibrated physical illumination. The notebook rows use projected surface regions and the café rows use the documented object-support masks. Camera and product pose are held fixed while lighting varies; moving-object interaction is not tested by these clips.
+
+| Measurement | Before | After | Interpretation |
+|---|---:|---:|---|
+| Left palm-rest luma range, refs-off full direction sweep | 1.58 | 20.46 | Corrected product-only response; earlier sphere-contaminated2.28→15.56 withdrawn |
+| Right palm-rest luma range | 0.69 | 18.41 | More response to key direction |
+| Chrome colour shift relative to wall shift | 0.035 | 0.493 | Reflection now follows changing light colour |
+| Screen warm/cool colour shift | 0.19 | 0.23 | Emissive content is not simply tinted with the room |
+| Resting screen luma | 46.63 | 60.24 | Unwanted veiling reflection raises the black level |
+| Front contact strip / open floor luma, refs off | 0.991 | 0.909 | Corrected heuristic; earlier0.841→0.787 measured sphere/shadow contamination |
+| Pastry warm/cool mean absolute RGB change | 0.000 | 3.042 | Mostly a narrow rim/back light |
+| Cup warm/cool mean absolute RGB change | 0.873 | 1.150 | Front-face response is still weak |
+| Photographed background maximum pixel change | 0 | 0 | No photographic relighting; both full 144-frame diagnostic sequences checked |
+
+The coordinator decoded all eight MP4s: four notebook clips of 168 frames and four café clips of 144 frames, all 1280×720 at 24 fps. Fresh reverse-first samples, including the screen-glare interval, matched all **292** saved sequential hashes. All **26** individual control edits changed pixels and restored exactly immediately after each edit. No page/request errors occurred. These checks use one Mac/browser; no cross-device guarantee follows.
+
+## Failures retained, and limits that remain
+
+- A first notebook export had a reflection step when its moving key card passed behind a fixed emitter card. The first experiment forced the key card to draw over other emitter cards. The follow-up reproduces this with a nearby depth-tested emitter and then aligns its direction to the key. Single-probe parallax and uncalibrated emitter energy remain approximations.
+- The display catches a broad glare during frames 28–46. The worker measured a peak mean screen luma around 129; coordinator still inspection confirms the visible contrast loss. Two black-flag placements did not materially reduce it. The completed follow-up avoids the observed glare with an elevated key path and a flag, keeping the display material unchanged. Its floor/reflection tradeoffs remain documented separately.
+- **Withdrawn interpretation:** the earlier palm-gradient reduction was the diagnostic sphere. Refs-off gradient increases; the separate left-to-right deck contrast falls, largely due to the rim card according to the refinement study. Resting display veil comes primarily from a fill card, not the lit room.
+- Contact darkening is a key-independent approximation. This does not establish area-light shadows, general indirect bounce, or mutual reflections among arbitrary products.
+- The first café experiment has zero source size, so its pool and shadows are hard. The completed finite-source follow-up softens distant shadows while preserving tighter contact. The pastry receives a rim light and the cup front remains weak. Several strength/cutoff/placement attempts failed before the isolation diagnosis. The first placement cannot be called repaired merely because a later placement works better.
+- The procedural notebook concept, scanned pastry and procedural cup are the only cases covered. Actual product-material fidelity, the desktop and other product classes remain unverified here.
+
+## Current decision after independent refinement
+
+Keep the coupled-light/reflection approach as an explicit authoring option. The [completed follow-up](hybrid-lighting-refinement-2026-11-14.md) tests an unchanged-material glare-avoiding path, labelled finish alternatives, finite-source shadows and a separate front-side lamp placement. Keep LIGHT1 partial: reflective practical lights, floor/display tradeoffs, moving objects, native integration and broader hardware remain open.
+
+The original quota interruption and failed attempts remain retained. No new hosted-model calls or paid assets were used.
diff --git a/skills/editableframes/references/hybrid-lighting-refinement-2026-11-14.md b/skills/editableframes/references/hybrid-lighting-refinement-2026-11-14.md
new file mode 100644
index 0000000..d42b015
--- /dev/null
+++ b/skills/editableframes/references/hybrid-lighting-refinement-2026-11-14.md
@@ -0,0 +1,64 @@
+# Notebook glare and finite café lighting — corrected evidence, 2026-11-14
+
+**LIGHT1 remains partial.** A second implementation removes the notebook's glare with the display material unchanged, gives the café lamp a finite size, and tests a separate composition that lights the cup front. These are opt-in authored scenes, not automatic lighting or a new framework default. No paid calls were made.
+
+## Correction to the earlier report
+
+The coordinator's earlier independent recomputation used the same diagnostic images as the first worker. Reference spheres and their shadows cover roughly **40% of the left palm region, 48% of the front lip and 49% of the contact strip**. Recomputing those pixels did not independently validate that the regions measured the intended surfaces. Retain the original evidence, but supersede the affected interpretation and values.
+
+With reference spheres hidden, the 0–95-frame direction sweep gives left palm response **1.58 → 20.46** codes, front lip **23.43 → 39.45**, and resting contact/open-floor ratio **0.991 → 0.909**. The prior 2.28 → 15.56 palm result and 0.841 → 0.787 contact result are not valid product-only measurements. The corrected sweep also uses the full declared direction interval rather than sparse still samples. A projected contact-region ratio remains a heuristic, not a physical contact measurement.
+
+The earlier claim that the lit floor reduced the palm's spatial gradient is withdrawn. The reference sphere caused that observation. The second worker finds that the separate left-to-right deck contrast decreases, largely because of the rim card; that limitation remains.
+
+Saved isolation renders also correct the resting screen-veil diagnosis: removing the lit room changes mean screen luma by only **−0.02**, while hiding one static fill card changes it by **−15.12**. The coordinator reproduced those values. The earlier flags were behind the fill card from the reflection probe's viewpoint.
+
+## Notebook: fix the light path before changing the product
+
+The key's reflection card was below the direction of its direct light. The new scene aligns their azimuth and elevation, uses a depth-tested nearby card, raises the key as it crosses the screen's mirror direction, and places a black flag in front of the offending fill card. Camera, product pose and display material remain fixed in the comparison.
+
+| Delivered hero-clip measurement | Previous experiment | Path plus flag |
+|---|---:|---:|
+| Peak screen luma, all 168 frames | 129.20 | 40.17 |
+| Resting screen luma | 59.24 | 39.98 |
+| Largest adjacent-frame screen RGB change | 11.76 | 0.037 |
+| Left palm direction-sweep range | 20.46 | 19.87 |
+| Right palm direction-sweep range | 18.45 | 17.76 |
+| Floor direction-sweep range | 3.02 | 19.71 |
+
+These are coordinator recomputations from lossless exports, with reference spheres hidden. Values are 8-bit image codes, not calibrated radiometry or perceptual scores. The emission-only display pixels match exactly, so this result does not recolour the UI artwork.
+
+The improvement has costs: the elevated light brightens the floor, and the very low remaining screen reflection can make the display look pasted on. A path-only alternative retains more glass reflection but also retains the resting veil. The worker also rendered explicitly labelled anti-reflective and matte finish variants: anti-reflective reduces but does not eliminate glare; matte retains glare and takes the key's tint. Neither is evidence about a real manufacturer's coating.
+
+The worker's near-card comparison supports a narrower explanation of the old forced overdraw: it approximates a key emitter nearer than the other cards. That does not make the rig physically complete. Single-probe parallax, independently scaled direct-light/card energy, camera-invisible cards and flags that cast no shadows remain limitations. A convincing view at one fixed pose is not general light transport.
+
+## Café: source size and placement solve different problems
+
+The finite source averages 64 deterministic light-position renders in linear light before tone mapping. Each sample has its own shadow visibility. This produces wider shadows far from the caster while keeping contact tighter; it is not a uniform post-render blur.
+
+| Shadow transition, fixed scanline | Point source | Finite source |
+|---|---:|---:|
+| Cup shadow on plate | 0.84 px | 23.92 px |
+| Cup shadow on cloth | 0.82 px | 27.89 px |
+| Pastry contact shadow | 0.86 px | 4.79 px |
+
+Softening the source in the same composition does **not** solve weak front illumination. Moving the lamp to camera-side right is a separate, declared composition change.
+
+| Warm/cool mean absolute RGB response | Previous lamp | Finite source, same position | Finite source, front-right |
+|---|---:|---:|---:|
+| Cup | 1.15 | 1.46 | 40.72 |
+| Pastry | 3.04 | 2.60 | 8.69 |
+| Chrome reference | 0.00 | 0.00 | 0.10 |
+
+The chrome result exposes an unresolved problem: the lamp is effectively absent from reflections. The photographed background is unchanged in the checked region across all three full 144-frame clips. It has not been relit. The foreground lamp is visually large, the cup becomes a flat saturated orange under warm light, and the pastry still sits partly in the shade's penumbra.
+
+## Verification and measured limits
+
+The coordinator reproduced **96 fresh frame samples across six refined hero/diagnostic clips**, and **21 individual edits/restorations**, with no page/request errors. Independent recomputation decoded all frames of three notebook and three café lossless clips: **936 frames**. The worker separately reports 1,065 repeat samples, 61 control checks, and successful decoding of all 11 full clips and 14 delivery files. Those wider counts are worker evidence, not a second coordinator rerun.
+
+Worker capture receipts report about 13.3 seconds for a 168-frame notebook hero and 40.9–41.8 seconds for the 144-frame finite-source café heroes on this Mac. These are end-to-end capture observations for these scenes, not interactive frame-rate or ordinary-computer guarantees. The finite-source method performs 64 renders per output frame.
+
+Visual review used before/after images and contact sheets; no normal-speed viewing or listening claim is made. Product fidelity, moving camera/product interaction, other materials and other hardware remain untested here.
+
+## Updated acceptance
+
+Close only these scoped subchecks: avoid the observed notebook glare on this fixed-pose light path without changing its display material; produce source-size-dependent café penumbrae; demonstrate useful cup-front response after an explicit lamp move. Keep overall LIGHT1 partial. Next work must address reflective practical lights, floor/display tradeoffs, moving products and hardware cost before making this a general default.
diff --git a/skills/editableframes/references/hybrid-mask-audit-2026-11-14.md b/skills/editableframes/references/hybrid-mask-audit-2026-11-14.md
new file mode 100644
index 0000000..5d6918f
--- /dev/null
+++ b/skills/editableframes/references/hybrid-mask-audit-2026-11-14.md
@@ -0,0 +1,36 @@
+# Hair-mask audit across replacement backgrounds
+
+Status: **partial**. Coordinator audit; the requested Fable review hit its provider rate limit before producing an artifact. No Fable approval is claimed. No paid calls.
+
+## Controlled evidence
+
+96 retained frames at 25 fps, cropped to the same head region, are composited over pale yellow, white, dark brown, magenta and a checker. Four columns compare old support alpha, full-resolution/context alpha, repaired alpha and a half-strength repair. All columns use **identical raw RVM foreground RGB** and linear-light straight-alpha composition. This isolates the mask; it deliberately does not reproduce the earlier full repair's RGB averaging.
+
+PNG inputs and stills add no intermediate loss. The underlying inference used retained JPEG source frames; this audit does not undo that compression or rerun inference. Backgrounds are diagnostic swatches, not new realistic room scenes. All five MP4s decode successfully (96 frames each, 3.84 seconds; no audio). The saved contact sheet shows frame 47 on every background; selected frames were visually inspected, not every frame in real-time playback.
+
+| Mask | Adjacent motion-compensated alpha residual |
+|---|---:|
+| Old support | 0.03500 |
+| Full-resolution/context | 0.02198 |
+| Temporal repair | 0.01372 |
+| Half repair trial | 0.01720 |
+
+The same shared nine-pixel boundary band and forward/backward flow check are used for all methods. The full repair reduces this residual by 37.6% against raw; half repair by 21.8%. **These are temporal stability measurements, not annotated hair accuracy.** Small differences from the earlier 0.01366 follow recomputation from quantized saved masks rather than pre-save float arrays.
+
+With foreground RGB held fixed, repair-versus-raw boundary RGB differences average 1.55 codes on white versus 0.20 on dark brown (7.7×), 1.15 on yellow, 0.73 on magenta and 0.78 on checker. This measures sensitivity to the same alpha edit, not error against ground truth. Dark backgrounds conceal much of the difference. At frame 47 the old support produces conspicuous missing/contaminated curl regions; all newer masks improve that still, but faint edge haze remains visible on white.
+
+## The remaining risk
+
+The full repair changes alpha by up to 0.145 after quantization; half repair caps this at about 0.073. Both preserve the raw alpha of pixels >=0.99 exactly. Boundary opacity can be added or removed: the full repair changes net alpha mass by up to about 117 pixel equivalents in either direction. That is not a count of correctly recovered hairs.
+
+An analytic counterexample tests the exact temporal correction formula with perfect correspondence: a true one-frame disappearance (center alpha 0; four neighbors 0.55) becomes alpha 0.144 with full repair and 0.072 with half repair. This is a synthetic test of the correction stage, **not an observed 0.144 ghost in the real clip**; optical-flow validity may reject such samples. It establishes why improving stability alone cannot approve the filter. The half-strength trial trades less change for less smoothing; it is not selected as a superior default.
+
+## Decision and next gate
+
+Keep soft mattes independent of hard SAM support at fine hair. Validate each replacement on light and dark backgrounds. Keep repair strength editable and retain the unfiltered matte. Do not silently choose aggressive temporal smoothing from its own stability score. Before closing MASK1, use annotated fast curls/disocclusions and compare detail, lag and false opacity separately; isolate inference context/resolution/source preparation, and review normal-speed clips. No new general grasp/pointing claim follows from this work.
+
+The glass worker also reached its rate limit. Its raster and Cycles stills and diagnostic sources were retained, but it stopped while diagnosing dark submerged ice. There is no completed calibrated comparison, motion clip acceptance or approved transparency route from that interrupted study.
+
+**Subsequent glass update:** the interrupted study resumed and was independently checked. See [nested-transparency follow-up](hybrid-glass-study-2026-11-14.md); its status is now partial, not awaiting a first result. The mask findings above are unchanged.
+
+**Subsequent hair update:** Fable completed the isolation study after resumption. [Verified follow-up](hybrid-mask-followup-2026-11-14.md) adds limited reference tests and a conservative repair. This earlier fixed-RGB, linear-light comparison remains a separate measurement, not a ground-truth score.
diff --git a/skills/editableframes/references/hybrid-mask-followup-2026-11-14.md b/skills/editableframes/references/hybrid-mask-followup-2026-11-14.md
new file mode 100644
index 0000000..a962da5
--- /dev/null
+++ b/skills/editableframes/references/hybrid-mask-followup-2026-11-14.md
@@ -0,0 +1,61 @@
+# Hair audit follow-up: isolate the model from the repair
+
+2026-11-14. **MASK1 remains partial.** Fable's resumed audit is complete and the coordinator checked its delivered data and standalone renderer. This supersedes the earlier statement that the independent audit was unavailable. No paid calls, downloads or production approval.
+
+## Better evidence changes the interpretation
+
+The earlier coordinator audit held foreground RGB constant and compared alpha variants. It established background sensitivity and stability, not accurate hair extraction. The new study decodes the retained source without an additional lossy intermediate, isolates source compression, recurrent warm-up, resolution and support clipping, and adds two limited references that do not depend on optical flow.
+
+Worker isolation findings on this one 96-frame excerpt:
+
+- Replacing the original JPEG intermediates with lossless decoded frames reduces the flicker score by 39.5% at the same model settings. This was the largest measured single preparation change.
+- At full resolution, 88 preceding frames of context improve the estimated missing-opacity proxy from 1.86 to 0.49, while average flicker barely changes.
+- Warm full-resolution inference improves that proxy from 3.39 at half resolution to 0.49, but softens edges. Higher thin-structure energy can include texture/noise, not just hairs.
+- Hard SAM support removes soft alpha in the hair region. Keep support masks distinct from fine-edge mattes.
+- The five-frame repair reduces real-clip flow-compensated fluctuation by 32.5%, but also reduces thin-structure energy by 8.9%.
+
+Inference was run by the worker, not rerun independently by the coordinator. Its port of the prior repair matched the retained outputs exactly according to its saved receipt. These isolation results improve the evidence, but do not generalize beyond this clip/model.
+
+## What the references do and do not establish
+
+The partial room plate is estimated from other frames of the same locked camera. An RVM-based exclusion mask chooses candidate empty-room samples. Similarity to that plate is useful evidence of a halo, but is **not proof that no low-contrast hair is present**. Coverage is only about one fifth of the hair boundary. The missing-opacity bound assumes the compositing/noise model and reliable plate estimates; avoid calling it an unconditional physical ground truth.
+
+The known-alpha benchmark re-composites a presenter using an RVM-derived, sharpened matte, then compresses the result and processes it again. Alpha is known for this synthetic test, but the test is easier than natural fine curls and uses the same source. It is neither a manual annotation nor an independent footage benchmark.
+
+On that synthetic test, the five-frame repair reduces temporal alpha error by only 4.5%, while yellow-background composite error gets slightly worse: 17.32 → 17.45 RGB codes. Do not describe 32.5% divided by 4.5% as a universal seven-fold correction: these are different metrics on real and constructed clips. The supported conclusion is that lower fluctuation alone cannot establish better compositing.
+
+## Proposed repair and independently reproduced measurements
+
+The proposed `clear_gated3` uses conservative room evidence to clear some opacity, applies a lower-bound correction, then a limited three-frame filter. It requires a fixed camera and background revealed elsewhere in the footage. It is not an automatic solution for arbitrary moving cameras.
+
+| Measurement | Unfiltered full-resolution matte | Proposed repair |
+|---|---:|---:|
+| Real-room halo proxy, mean opacity-equivalent pixels | 87.79 | 45.84 |
+| Same proxy during frames 24–53 | 116.22 | 45.33 |
+| Real-room missing-opacity proxy | 0.495 | 0.148 |
+| Synthetic false-opacity mass | 340.77 | 309.30 |
+| Synthetic composite error on yellow, RGB codes | 17.32 | 16.96 |
+
+The 48% real-room proxy reduction is **not** 48% overall hair accuracy. On the synthetic composite, the improvement is about 2%. All recomputed summary values agree with the worker's numbers within 0.0001. They reuse its plate, inference arrays and synthetic truth; the measurement code is independent, the reference data is not.
+
+The synthetic matte resembles past truth more than future truth under the worker's lag indicator, including before filtering. This supports a model-origin lag problem in that benchmark. It does not establish exact lag in milliseconds or prove that no particular strand gains delay under filtering.
+
+## Renderer and media checks
+
+The coordinator freshly rendered 36 out-of-order samples across three cases: every PNG matches the saved sequential pass. Nine control edits change and restore the result, and a fresh mount reproduces it exactly. No page/resource errors. All 12 delivered MP4s decode and have their frame counts/rates recorded; two intentionally slowed diagnostic intervals are not full-length sequences. These are standalone EditableFrames renderer-host checks on one Mac, not app/exporter integration.
+
+Selected stills were inspected. The concrete-side smoke is reduced, but faint wood-aligned fringes and ragged edges remain. A smear under the moving hand is visible and unaddressed. No normal-speed playback or audio listening acceptance is claimed; clips are silent.
+
+## Revised route
+
+1. Preserve losslessly decoded source frames before matting; do not introduce JPEG intermediates.
+2. Keep recurrent context, inference scale and support-mask clipping explicit and test them separately.
+3. Retain raw mattes and adjustable post-processing. Do not choose repair strength using flicker alone.
+4. Offer the room-aware repair only for its fixed-camera, revealed-background case; uncertain room evidence must not erase plausible hair.
+5. Test a stronger video-matting model against the same source and references, plus genuinely independent footage and annotated edges. The installed MobileNet model remains the main limitation in this study; stronger weights/runtime were not tested here.
+
+The previous coordinator used linear-light compositing with fixed foreground RGB. This study uses encoded-sRGB canvas compositing and model foreground colours. Its 5.3× white/dark error ratio and the prior 7.7× alpha-edit sensitivity measure different quantities; neither replaces the other. Colour-space convention must be declared in comparisons. Keep both evidence sets and all failed repairs.
+
+## Subsequent model comparison
+
+The earlier stronger-model resource gap has now been exercised: [ResNet50 and ViTMatte comparison](hybrid-stronger-matting-2026-11-14.md). Neither earns adoption as a hair matte. The remaining acceptance gap is independent real-hair evidence and motion review, not merely access to larger weights.
diff --git a/skills/editableframes/references/hybrid-motion-proxy-2026-11-14.md b/skills/editableframes/references/hybrid-motion-proxy-2026-11-14.md
new file mode 100644
index 0000000..7d5ed37
--- /dev/null
+++ b/skills/editableframes/references/hybrid-motion-proxy-2026-11-14.md
@@ -0,0 +1,62 @@
+# Moving highlights and spatial reflections: measured boundaries
+
+2026-11-14 · LIGHT1 remains partial · no default shader adoption
+
+A scene-aware reflection method now reproduces the tested nearby sphere and corrects the bright upper band. This extends the useful raster envelope, but its proxies are exact for the simple test geometry. It does not establish accuracy for real products. Offline rendering remains code-generated video, and these lighting errors do not require diffusion.
+
+## What the new reference establishes
+
+A separately written numpy integrator with analytic geometry and two estimators confirms the direct single-scatter GGX reference. It also independently checks one bounce from matte neighbours in five arrangements: Cycles/integrator energy ratios are 0.9976–1.0017. Per-pixel RMS remains 2.9–6.1% with Monte Carlo noise on both sides. Multiple bounces, arbitrary materials and real-product geometry are outside this validation.
+
+The worker freshly reproduced eight retained raster arrays and one Cycles pose byte-identically. The coordinator checked retained evidence and delivery integrity; the coordinator did not repeat the rendering or derive a third integrator.
+
+## Moving highlights: do not switch anti-aliasing off globally
+
+The study moved the light, camera and product for 48 frames, at two resolutions and two roughness values. A 4×4 supersampled reference separates actual highlight movement from sampling error.
+
+| Tested case | AA off | Default specular AA | Decision |
+|---|---|---|---|
+| Satin cylinder, roughness 0.35 | Under 0.2 display codes mean error in the tested cases | Broadens the highlight; error changes with output size | Bounded opt-in, not a new default |
+| Polished cylinder, roughness 0.10, roughly 2-pixel highlight | 2.7% energy pumping; 17.6-code temporal reversal | 1.0% pumping, 5.7 codes, but tails about 3× too bright | Supersample final output |
+
+Clipping the highlight to white hides shimmer; evaluate an unclipped exposure too. The alternative normal-derivative AA formula also widens the polished highlight excessively. Supersampling costs about 27 vs 9 ms for the satin case and 105 vs 34 ms for polished on this Mac. These are research render timings, not export or general-computer performance.
+
+## Spatial reflections: a real improvement with a geometry condition
+
+The new shader samples reflection directions from the material lobe and traces them against a floor plane, sphere and box. It uses a captured view at the hit, handles disoccluded hits explicitly, and returns the background when a ray misses the scene. Tuning used one pose; two arrangements and the motion path were frozen before method development.
+
+| Measurement | Centre probe | Proxy taps |
+|---|---:|---:|
+| Upper-band reflected energy / one-bounce reference, five arrangements | 1.70–2.47 | 0.99–1.03 |
+| Neighbour sphere effect, regression slope | −0.05 to 0.79 | 0.96–0.98 |
+| Whole-picture error on cylinder pixels, five arrangements | 17.7–22.8 codes | 1.3–1.9 codes |
+| Held-out motion, same cylinder metric | 20.0 codes | 2.4 codes |
+
+The coordinator recomputed 45 whole/lower/upper energy ratios from packed linear arrays and independently constructed eroded object masks. All agree with the recorded rounded ratios. These are cylinder-region results, not whole-scene quality scores: matte neighbours remain 21–47 codes too dark.
+
+At 64 taps, grain remains about 4.3 codes RMS against the 1024-tap version and changes over time. About 1024 taps reduces error against Cycles to 1.3 codes, without separating reference noise. Omitting the sphere proxy loses its reflection and increases error to as much as 7 codes. Approximate proxies for real devices, thin geometry, textured/coloured surfaces and broader materials remain untested.
+
+The proxy pass takes 2.3–3.1 ms at 960×540 when the cylinder occupies about 10% of the frame. At 1080p and 75% occupancy it takes 12.9 ms at 64 taps or 47.1 ms at 256 taps. These exclude the separate direct-light pass and capture/encoding. One-bounce Cycles takes about 12 seconds per 960×540 frame on this Mac.
+
+## Corrections to the preceding study
+
+- The older frozen-method manifest no longer matches three retained source/bundle/capture files. Fresh baseline rendering still reproduces the evidence; the old manifest must not be cited as proof of a frozen protocol.
+- The prior held-out light pose includes the highlight peak, not only its tail.
+- Most residual AA-off direct-light error comes from different emitter models: uniform points inside a ball versus a Lambertian sphere. An alternative distribution was checked in the CPU model, not rendered as a new raster result.
+- The upper-band error is not mainly prefiltering. Rays that miss scene geometry were incorrectly answered with nearby floor. A floor-plane-only correction fails one held-out arrangement at 1.78× lower-band energy.
+
+## Routing and next gate
+
+1. **Editable raster:** direct lights and shadows; tested satin highlights; spatial reflections with explicit, adequate proxies. Use more samples for polished or grain-sensitive delivery. Keep these options experimental.
+2. **Offline rendering of the same scene:** complex nearby geometry, matte bounce, multiple reflections and nested glass/liquid. Preserve asset, camera and light identity. This is a compute/renderer choice within code generation.
+3. **Generated joint performance:** use when photoreal interacting people or objects lack suitable assets, rigs or motion. Generated lighting and contact are baked; captions, branding overlays and whole-frame edits can stay live. Diffusion was not used in this lighting study.
+
+Next test: approximate proxies for retained real-product meshes, compared with the actual mesh reference under camera/product/light motion. Include deliberate proxy omissions, self-reflection, an unseen arrangement, quality/cost at final resolution, and an explicit failure threshold. Stop at a measured route boundary rather than calling every partial result solved.
+
+## Verification and retained failures
+
+Coordinator: all 44 delivery hashes and 42 sibling input hashes match; all nine previews decode (408 frames); 45 regional ratios recomputed; three stale old-freeze hashes confirmed; comparison stills and the energy chart inspected. No coordinator fresh render, normal-speed playback, audio or second-device acceptance.
+
+Worker: 352 out-of-order rerenders match, 13 controls change and restore exactly, no page errors. Retained failures include a tail-only motion test, the first proxy method, omitted disocclusion, omitted sphere proxy and over-soft polished AA. No paid calls, downloads or default runtime changes.
+
+Three additional research subchecks are resolved only in scope: one-bounce reference validation; the measured satin/polished motion boundary; and exact-proxy reflection accuracy in the held-out simple scenes. LIGHT1 remains partial and is not approved for production.
diff --git a/skills/editableframes/references/hybrid-moving-reflections-2026-11-14.md b/skills/editableframes/references/hybrid-moving-reflections-2026-11-14.md
new file mode 100644
index 0000000..abd6623
--- /dev/null
+++ b/skills/editableframes/references/hybrid-moving-reflections-2026-11-14.md
@@ -0,0 +1,41 @@
+# Moving-camera and moving-product reflections
+
+> Superseded interpretations: [the independent reflection review](hybrid-reflection-review-2026-11-14.md) corrects the self-reflection, neighbour-effect and screen-cleanliness claims, adds a bounded matte offline comparison, and measures equal-sample timing. The text below records the earlier checkpoint.
+
+
+2026-11-14 · LIGHT1 remains partial · two scenes on one Mac
+
+The new raster method uses colocated visible emitters and direct/specular light, per-object reflection captures, and planar mirrors for flat surfaces. It improves reflection placement under camera orbit and product rotation. It does not establish calibrated product realism or general self-reflection support.
+
+## What the worker measured
+
+| Observation | Earlier method | New method |
+|---|---|---|
+| Notebook screen veil, tuned / held-out | 24.1 / 28.8 image codes | Below 1 in both |
+| Notebook light-source reflection samples reproduced, tuned | 147/180, with 138 false positives | 180/180, with 8 false positives |
+| Cup bulb-reflection samples reproduced | 0/43 | 43/43 |
+
+These are worker-reported image-code and geometric-content measurements, not physical radiometry or independent image-quality scores. The mirror audit shares the rendering geometry, so perfect planar agreement validates plumbing rather than physical accuracy. Held-out layouts were adjusted using ID passes before their first beauty renders; this was a constrained arrangement test, not a blind external benchmark.
+
+The clean screen depends on what it reflects. A lower key crosses the mirror zone and produces visible glare; raising the key avoids it without changing the display material. The emission-only UI differs by a mean 0.0095 codes rather than being byte-identical. The photographed café backdrop remains baked; changes there are confined to the existing steam overlay.
+
+## Remaining defects and failed approaches
+
+- Hiding each object during its reflection capture removes self-reflections. About 52–56% of notebook chassis mirror rays hit the notebook itself. Including it naively shifts the palm rests by about 60 codes.
+- A planar deck experiment improves geometric content agreement but loses the brushed streak; it was added after the held-out run and is not held-out evidence.
+- Nearby-product reflections remain weak or missing on the notebook body. Reflections between the cup and saucer change by several codes on a second bounce.
+- The new café cup is about 30 codes brighter, with no independent energy calibration. The saucer diffuse probe sits inside the cup. These are open defects, not an approved look.
+- The new studio background and neighbouring desktop are darker; held-out contact contrast is weaker.
+- Emitter-only cube captures missed the nearby bulb. A single room probe turned the café table orange. Both failures are retained.
+
+## Verification and limits
+
+The worker reports exact shuffled/reverse seeks and control restoration, plus a three-frame real-CLI edit/stale-edit/undo specimen. The coordinator independently decoded all five comparison previews (120 frames each, 24 fps), checked the CLI receipt's internal consistency, and inspected notebook/café comparison stills. The coordinator has not rerun the reflection measurements. Neither review watched normal-speed playback. There is no offline reference, other hardware, measured GPU utilisation, or finished-advert approval.
+
+Notebook steady rendering is reported at 19–21 ms/frame versus 11–12 previously. Café timing is not a fair speed comparison because the sample count changed from 64 to 32. Capture/encoding costs are separate.
+
+## Next experiment and routing consequence
+
+Independently verify self-reflection, nearby-object visibility and local irradiance before adopting the method. Use fixed geometry and material settings, isolate direct/specular/diffuse terms, retain failures, and freeze the method before a genuinely new arrangement. Recover the saucer probe placement and test whether extra bounces conserve a plausible brightness range.
+
+Code can keep geometry, lights, camera and material edits live. These failures bound this raster implementation; they do not prove that code cannot solve the shot. Offline rendering remains a candidate for complex reflection/refraction. Joint diffusion generation remains the tested route for difficult photorealistic interaction, with baked internals and live code overlays afterward.
diff --git a/skills/editableframes/references/hybrid-reflection-review-2026-11-14.md b/skills/editableframes/references/hybrid-reflection-review-2026-11-14.md
new file mode 100644
index 0000000..9ceb300
--- /dev/null
+++ b/skills/editableframes/references/hybrid-reflection-review-2026-11-14.md
@@ -0,0 +1,49 @@
+# Reflection review: better flat surfaces, incomplete light transport
+
+> Follow-up: the penumbra mismatch is now explained and repaired for direct light, and a narrow glossy direct reference is checked. Indirect transport remains incomplete. [Current calibration](hybrid-light-calibration-2026-11-14.md).
+
+2026-11-14 · LIGHT1 remains partial · research implementation, not a library default
+
+The independent review corrects three earlier interpretations: hiding the notebook from its own reflection capture caused the larger palm-rest error; the brighter café cup was partly justified bounce light and partly a sampling error; and nearby-product reflections were not negligible merely because the approximation failed to draw them. No finished-advert or general hardware approval follows.
+
+## What changed
+
+| Case | Earlier moving-reflection method | Review method | Remaining limit |
+|---|---|---|---|
+| Notebook palm-rest reflection energy / one-bounce reference, A / I / I0 | 2.04 / 1.57 / 1.53 | 1.01 / 0.94 / 0.91 | Flat up-facing deck only; mean energy agreement is not per-pixel agreement |
+| Cup signed brightness bias, three arrangements | +5.9 to +13.0 image codes | −1.8 to −4.4 | Mean absolute error still 5.2–9.0 codes; glossy offline match untested |
+| Saucer signed brightness bias | −3.0 to −10.3 codes | −0.2 to +3.7 | More than one bounce still missing |
+| Nearby object on tuned notebook deck | About 1% of reference change | About 42% | Side-facing and curved surfaces remain weak |
+
+The deck method samples a planar reflection with depth-aware, directionally stretched highlight taps. It recovers the lid/display in the deck without hiding the whole object. The café method places six probes around the cup, one in its bowl, and six above the exposed saucer, preserving the cup and its shadows in those captures. These are explicit scene-specific implementations, not a universal relighting model.
+
+The reference gathers light at each tested surface point and integrates the material response. It is a useful one-bounce reference inside the same raster renderer, **not physical ground truth**. It excludes textured metal and points within 2 cm of other geometry; comparisons disable bump. Its anisotropic reference also removes a clamp found in the renderer's direct-light formula. Therefore its ratios cannot certify the entire product or a manufacturer's finish.
+
+## Corrections to the earlier report
+
+- A ray hitting the right object is a geometry check, not proof that the reflection's pixels have the right brightness or spread. The earlier 43/43 bulb-hit result and near-perfect planar scores must not be described as reflection accuracy.
+- The notebook's clean display is partly a missing-reflection effect. Its reflected energy is 0.21, 0.68 and 0.97 of the per-point reference across three arrangements. Broad highlight tails outside the mirror image are missing. Avoiding a mirror-zone crossing remains useful art direction, but is not a material calibration.
+- The old “at most 0.07 codes” neighbour effect was measured in a renderer that largely omitted it. The new reference sees up to 5 codes on the deck and 39 at a sampled base-side point. New rule-drawn arrangements barely show the neighbour, so they do not establish general neighbour handling. A separate designed stress case still over-responds.
+- The café's roughly 30-code increase was not all an error. Roughly 20–25 codes are supported by the one-bounce gather; the remaining 6–13 mostly comes from probe placement. Lowering exposure would conceal rather than repair that distribution.
+
+## Offline comparison and new bottleneck
+
+In the directly lit café arrangement, matched matte, lamp-only Cycles gives direct light within 2%. The ring improves cup indirect light from 0.73 to 0.91 of the one-bounce reference and saucer light from 0.18 to 1.02. Eight bounces produce roughly twice the indirect light of one bounce.
+
+However, the second arrangement sits in the lampshade penumbra: raster direct light is 1.35 times Cycles and indirect is about 1.9 times. That discrepancy is unexplained. The offline comparison is matte and lamp-only; **there is no matched glossy reference**. The next experiment must isolate this calibration discrepancy before using Cycles as an authority for these glossy shots.
+
+Other remaining issues: side/bevel/lid self-reflections; per-pixel light occlusion; weak anisotropic effect despite improved direction; about 0.7–0.8 codes of fixed deck dither that may shimmer in motion; brass lamp reflections; and missing multi-bounce light.
+
+## Cost and verification
+
+On this Mac only, notebook rendering rose from 18.8 to 21.8 ms/frame. Café rendering at equal 32 samples rose from 48.7 to 70.6 ms/frame; at 64 samples, 75.6 to 95.9. These exclude capture/encoding and are not a claim of interactive performance on ordinary computers.
+
+Worker receipts report 57 reverse/shuffled/edge seeks per clip across six clips (342 checks), 78 control edits/restorations, and no browser errors. Options-off regression matches the earlier build within one code on at most 11 pixels. The coordinator independently decoded all four previews (480 frames), recomputed notebook energy ratios from 360 retained point records and café indirect ratios from the raw point receipts, and inspected the notebook/café comparison sheets. This is arithmetic and delivery verification, **not a fresh render or independent validation of the reference integrator**. Neither review watched normal-speed playback. No new resolved dashboard count is added; the existing integrity checks already cover this kind of evidence.
+
+## Routing decision
+
+1. **Editable raster:** use for stylized scenes and bounded product shots with tested reflection paths. Keep exposure, camera, materials and lights editable; show limitations of the selected method.
+2. **Offline rendering:** retain code-authored geometry and controls, but render expensive reflection/refraction and repeated bounces offline where the shot requires them. This remains code-driven, not diffusion. Match units, materials and tone mapping before comparing results.
+3. **Joint diffusion:** keep for the previously demonstrated photorealistic contact/performance workflow when editable geometry and motion assets are unavailable or inadequate. It bakes interaction, camera and lighting into a take; live captions and graphics are composited afterward. This study made no diffusion calls and provides no new diffusion accuracy claim.
+
+Do not promote the scene-specific shader patches into the library default yet. Preserve them as reproducible research assets while the penumbra discrepancy and glossy reference are investigated.
diff --git a/skills/editableframes/references/hybrid-roundtrip-workflow-2026-11-14.md b/skills/editableframes/references/hybrid-roundtrip-workflow-2026-11-14.md
new file mode 100644
index 0000000..d4cb2ee
--- /dev/null
+++ b/skills/editableframes/references/hybrid-roundtrip-workflow-2026-11-14.md
@@ -0,0 +1,61 @@
+# Scene staging → generated interaction → editable final composition
+
+2026-11-14 · FLOW1 remains partial · local replay, no new provider request
+
+The local round trip now has a concrete example: an editable staging scene produces a frozen reference packet, two retained interaction takes return as baked media, and live code overlays remain editable in the final film. This is a useful interoperability slice, not an integrated provider or native-app workflow.
+
+## Ownership determines what an edit can do
+
+| Requested edit | Local operation | Consequence |
+|---|---|---|
+| Headline, caption, accent, CTA or cue timing | Edit live overlay controls and export | Generated takes and their input packets stay unchanged. |
+| Crop or trim the shot | Resample/cut the whole baked frame | Cannot reveal hidden content or independently move the product. |
+| Change staged product position, grip or contact | Freeze a revised scene packet | Existing take becomes stale; a dependent handoff becomes stale too. Keep old accepted output available. |
+| Change only the handoff action prompt | Freeze a new handoff packet | Pickup can stay fresh; handoff needs replacement and review. |
+| Change a filmed face, light direction or physical interaction | New capture/generation or separately validated VFX work | The current importer has no recovered geometry or independent controls for these baked pixels. |
+
+The tested preference is joint generation for difficult photorealistic interaction, not a claim that code or traditional animation cannot ever produce it. Exact text/UI remain code-controlled. Opaque products with usable geometry can remain rendered. Nested transparent materials may need an offline renderer. A generated shot can be combined with these routes while retaining an explicit record of which layers are editable and which are baked.
+
+## Replay provenance and timing
+
+Both takes are retained outputs from the earlier successful pickup and handoff tests. The replay importer verifies original request/receipt/status/download records, model, prompt, ordered references, job identity and downloaded bytes. It labels each import `retained-replay`, `newlyGenerated: false`, with no transport. It handles the observed status output field as either a string or list.
+
+The staging CLI reproduces the submitted start-image bytes. The handoff start image derives from pickup frame 120, creating an explicit dependency. The resulting film has 121 + 169 = 290 frames at 24 fps, or 12.0833 seconds. A half-second trim at each end produces 266 frames. Requested generation duration is not substituted for actual decoded timing.
+
+Packet identity covers provider inputs, while source revision and binding remain provenance. An undo that restores the exact start-image pixels can restore freshness despite a changed editor revision. This is intentional; a renderer revision alone does not imply the provider saw different pixels.
+
+## Exporter fixes found by the exercise
+
+1. The portable renderer adapter dropped `scene.media`. Audio ports therefore never reached the existing scheduler, producing silent exports. The adapter now preserves explicit media declarations.
+2. Unity-speed audio passed through `atempo=1`. That unnecessary time-stretch shifted the retained soundtrack locally. Unity rate now uses `anull`; non-unity rates retain the existing tempo chain.
+
+Regression coverage schedules portable-renderer audio through offsets, trim, mute and speed, and runs real PCM through the mixer to check sample alignment after trim and delay. Explicit static media declarations are supported; arbitrary DOM audio, animated audio automation and automatic renderer-prop-to-audio binding are not implied. Existing projects need an explicit rebind after this runtime change.
+
+## Evidence and limits
+
+The worker reports full CLI render/edit/undo/redo checks, 290 exact source-frame comparisons with overlays disabled, overlay edits confined to their masks, 96 seek comparisons, and 19 fault/interoperability tests. These worker results remain distinguishable from the coordinator's new checks listed below. Original failed exports and proposed patches are retained.
+
+Coordinator source review found and reproduced an additional packet bug: deleting or reordering reference descriptors, changing their role, or substituting both hash and storage path could pass `load_packet`. It checked each descriptor against itself but not against the identity-hashed ordered list. The coordinator copy now compares the entire ordered descriptor list (excluding storage paths) with packet identity; all four mutations are rejected. The original worker result is therefore not general tamper coverage. This patch is research-only, pending native integration.
+
+The coordinator also reran five retained-record/restart/crash checks successfully. The public library passes all 137 unit tests and its required build. A new real-PCM mixer regression compares 36,000 sample frames with zero code error after trim and delay. The fresh preview path matches 48 shuffled/reverse frames to retained hashes and restores all three control changes exactly.
+
+Coordinator verification is recorded beside the research artifacts. Its corrected example holds the CTA through the final frame and uses a smaller, top-preserving crop to avoid the original headroom error. Both changes are local edits to the composition, not new generation.
+
+Neither reviewer listened to audio or watched normal-speed playback. Audio alignment is statistical; decoded frames and deterministic seeks do not certify perceptual acting or product fidelity. The take-to-take texture change still needs playback review. The full-film audio has zero measured lag in every audible one-second window (minimum correlation 0.999), including across the cut. AAC decoding includes a small padded tail; its decoded sample count is not treated as a changed picture duration.
+
+## Remaining gaps
+
+- The wrapper is research code: provider reconciliation, billing/idempotency, native UI/import and atomic managed-asset ownership are not implemented by this study.
+- CLI `asset-add` can accept undecodable media. This wrapper probes first, but it does not repair the general importer. Removal/recovery still needs a supported transaction.
+- A SIGKILL can leave decoded frames and orphan browsers. No partially published movie was observed; crash cleanup remains open. Graceful cancellation and uncatchable process death are separate cases.
+- Frozen local references do not constitute a complete host authorization system; races and multi-owner durable import need separate work.
+- The wrapper checks freshness before acquiring the render lock; it is not an atomic staging/ledger/export snapshot across concurrent editors. The recorded gate must not be presented as such.
+- No additional hardware was exercised. No proof that a new provider request would reproduce these retained outputs follows from a successful replay.
+
+## Coordinator failure retained
+
+The first coordinator crop test assumed 60,000 timeline ticks per second rather than reading the actual exported `HZ = 120000`. It produced 133 frames and failed audio alignment against the intended trim. The failed file and script are retained. The corrective script reads the library constant and asserts the requested 266-frame result before accepting it. This was a harness error, not a media-timing defect in the library.
+
+## Final coordinator acceptance in this scope
+
+Both full public-CLI exports passed: 290-frame full film and corrected 266-frame crop/trim, each with two audio tracks mixed. Both have zero measured audio lag; the full film has 0.99938 overall waveform correlation and 0.99985 around the cut. The corrected crop has correlation above 0.99. A fresh product move marks both pickup and dependent handoff stale; undo restores freshness. All four reference-descriptor adversarial cases are rejected after the research-copy fix. The unity-speed PCM regression also fails against the old filter chain, so it detects the original defect.
diff --git a/skills/editableframes/references/hybrid-shared-human-light-2026-11-14.md b/skills/editableframes/references/hybrid-shared-human-light-2026-11-14.md
new file mode 100644
index 0000000..a75277c
--- /dev/null
+++ b/skills/editableframes/references/hybrid-shared-human-light-2026-11-14.md
@@ -0,0 +1,50 @@
+# One light track, different kinds of foreground
+
+2026-11-14 · HUMAN1 remains partial · research renderer, no native relighter
+
+A continuous editable light track can coordinate a rendered product, a footage presenter, and an authored counter plane. That does not give these layers equal relighting capability. The 3D product uses geometry and materials; the presenter receives a bounded image correction using estimated depth; the photographed room retains its baked illumination.
+
+## What was actually tested
+
+One retained generated presenter, one 96-frame excerpt at 25 fps, one laptop GLB, and one photographed room on one Mac. No new media generation, downloads or paid calls. The presenter matte is reused unchanged. DPT depth supplies approximate normals; camera, subject depth, ambient share and white balance are authored assumptions. The baked-light fit uses face rows, despite its metadata saying face/neck.
+
+The worker compares untouched footage, a prior colour/exposure match, and a bounded additive correction using the depth proxy. A synthetic bust with known normals supplies a reference for the algorithm. It is not a human-face reference.
+
+| Synthetic bust, front hemisphere | Prior match error | Depth-proxy error |
+|---|---:|---:|
+| Lamp at half house light | 12.9 codes | 6.5 codes |
+| Lamp equal to house light | 24.9 codes | 11.0 codes |
+| Lamp becomes key, house at 30% | 53.1 codes | 20.3 codes |
+
+These worker-reported averages are 8-bit image-code errors on the synthetic control. The reported “share” is error reduction relative to leaving the source unchanged, not the fraction of physically correct illumination or a human realism score. Estimated normals are roughly 19–23 degrees off on synthetic skin and 40 degrees off on curls.
+
+## The operating range is not validated
+
+The worker proposes half-house light in the front hemisphere as a starting range. Coordinator inspection of the saved nonideal-bust grid finds only **3 of 7 front directions** pass the worker's combined criterion (error at most 8 codes and error reduction at least 0.6). Passing angles are -60, +60 and +90 degrees in that experiment. They must not become a universal whitelist.
+
+The human clip named “supported” peaks at approximately 0.78 times the dimmed house light, above the proposed 0.5 starting bound. It is an edge-case demonstration. It is not a validated safe preset. A native guard cannot approve arbitrary footage solely from lamp ratio and direction.
+
+## Visible gains and failures
+
+The milder example warms the lamp-side cheek, neck and hand while dimming the far side. The coordinator inspected the comparison at frame 62. The stronger example at frame 95 has a hard lit patch and an unnatural grey region beside the nose; its baked key remains visible. The worker reports about 9% loss of fine facial contrast in the milder example.
+
+The first track lacked highlight headroom and pushed about 51% of measured head/neck skin pixels above 250. Dimming the room in the final track is an art-direction change, not recovered source detail. No algorithm here restores clipped source information. Hair response remains inadequate; small proxy improvements in some numeric cells do not establish useful hair relighting.
+
+No new presenter shadows, product-to-presenter shadows, hair transmission, or relocated highlights are created. The lamp globe itself is absent from product reflections; only its analytic highlight is present. The counter is a proxy-plane correction over baked pixels. The room photograph responds only to uniform house exposure unless an explicitly authored wash is enabled.
+
+## Verification
+
+The worker reports 284 repeat-seek comparisons, 78 edit/restores, five fresh mounts and a four-frame real CLI history test. A first fresh-mount failure caused by GLB draw order was fixed and retained. The coordinator independently decoded all 13 preview files (96 frames, 25 fps, silent), audited the saved operating-range grid, and checked the CLI success receipt. The coordinator has not rerendered the shader or independently measured the human accuracy. Neither review watched normal-speed playback; there is no target-light reference for this presenter.
+
+## Routing rule for the plan
+
+- Geometry with materials: use an editable renderer and shared light track; validate reflections, shadows and exposure for the shot.
+- Footage with mild lighting changes: retain bounded correction as experimental, with source/proxy provenance, explicit limitations and visual review. Do not advertise general relighting.
+- New key direction, cast shadows, hair glow, moving highlights or lost headroom: use a suitably captured/relightable asset, validated VFX, or a regenerated take. Merely having normals would not solve every material and visibility problem.
+- Performance involving mutual contact or shadows: joint generation is a candidate from the earlier interaction tests, not a result tested in this light experiment. Preserve identity/product review and keep typography/UI live afterward.
+
+The light controls are continuous values, not a finite list of presets. The limitation is how much information each layer contains. Code is not inherently unable to depict the effect; ordinary RGB footage does not identify the geometry, material and lighting uniquely.
+
+## Next resources and work
+
+A real paired-light capture or a relightable subject with independently known passes is needed to score human accuracy. Another presenter and exposure range would test generality. A prepared-pass contract should record pixel ownership, source hashes, frame clock, proxy confidence and baked-light assumptions. Its acceptance policy must distinguish unsupported from unmeasured; a deterministic render is not a quality certificate.
diff --git a/skills/editableframes/references/hybrid-story-reuse-2026-11-14.md b/skills/editableframes/references/hybrid-story-reuse-2026-11-14.md
new file mode 100644
index 0000000..6f66d58
--- /dev/null
+++ b/skills/editableframes/references/hybrid-story-reuse-2026-11-14.md
@@ -0,0 +1,44 @@
+# Reusable cast across three styles — 2026-11-14
+
+> **Second-brief follow-up:** [Carry, turn, set down and release](hybrid-story-second-brief-2026-11-14.md) now tests the cast in two styles on a different action. Cast/rig/look transfer; action, grip and probes needed new code. This first-brief report is retained as the earlier result.
+
+ST2–ST3 advances from quota-blocked to **partial, with rendered evidence**. Three 12.5-second films reuse the original fantasy cast in a sci-fi repair bay, a cel-shaded village and a toy/clay workshop. Each is 1280×720 at 24 fps, with 300 frames, captions and local synthesized voices. No hosted-model calls were made.
+
+## What actually transfers
+
+The baseline character modules are imported by reference. New shared modules provide limb inverse kinematics, foot-planted walking, restyling and an explicit action clock. Each style supplies its own set, camera direction, materials, proportions, prop, light and motion treatment. These are authored source modules, not a new SDK style-generation feature.
+
+The important contact decision is **prop first, hands second**: author one world-space prop trajectory, then solve both characters' hands onto its grip sites. This avoids independent hand/prop animations disagreeing about where the object is. It does not infer arbitrary interactions from a prompt or guarantee collision-free bodies.
+
+| Film | Distinct treatment | Visual limit seen in contact sheets |
+|---|---|---|
+| Sci-fi | Reflective suits, emissive trim, repair bay, smooth motion, side grip on a power cell | Wrist bend and rigid fingers remain obvious; heads tilt steeply toward the prop. |
+| Village | Banded toon shading, ink contours, outdoor sun, stepped poses, overhand basket grip | Table overlaps the exchange in projection; faces are cropped during the contact close-up. |
+| Toy/clay | Shorter legs, larger heads/hands, textured matte surfaces, poses on threes, depth of field, underhand toy cradle | Flat hands read as paddles; workbench overlaps the prop; release is low in frame. **Not accepted as a convincing grasp.** |
+
+The coordinator agrees that sci-fi and village communicate the handoff more clearly. This is contact-sheet inspection, not a normal-speed playback or soundtrack listening review. The three films demonstrate a range of looks on **one action brief**, not general character portability or a production-ready animation system.
+
+## Independently checked delivery
+
+| Check | Coordinator result | Scope |
+|---|---|---|
+| Fresh frame reproduction | 102/102 sampled hashes match the saved sequential renders | Reverse-first and scattered samples, including both cuts and contact transitions; same Mac/browser. |
+| Individual controls | 27/27 declared controls visibly change and restore the sampled frame | One caption test initially selected a speech pause at frame 150. That observation is retained; the corrected sci-fi test at frame 120 passes during visible speech. |
+| Media decode | All 900 frames decode without errors | Three 12.5-second 1280×720/24 fps files; stereo audio duration also 12.5 seconds. No listening claim. |
+| Actual CLI edits | All three style specimens pass | Source frames 30, 120 and 244 per style; exposure edit changes all nine samples, stale proposals are refused, undo restores exact PNG bytes. |
+
+The CLI result extends the worker's renderer-host-only evidence. It does not cover full-film audio export, every control through the CLI, revision migration after source changes, native desktop delivery or another GPU.
+
+## Contact evidence: useful but not independent ground truth
+
+The worker reports no unsupported prop frames, no unreachable limb targets and minimum sampled digit clearances of +0.01, +0.03 and +0.02 mm for sci-fi, village and clay. Reported shared holds last roughly 0.75–0.79 seconds. Earlier retained attempts reported thumb penetration of 21 mm, finger penetration of 19 mm and unreachable walking legs by 24 mm; revised approach paths, closure and pelvis motion remove those reported failures.
+
+These values come from the authored scene and simplified probes. Digit spheres are checked against approximate prop capsules; palms, body intersections and prop-to-set contact are not tested. Zero grip error reads back the solver's own target, so it is not independent proof of contact. The coordinator verified pixels, controls and delivery, not a separate mesh-collision simulation.
+
+The clay film passes the automated checks and still looks wrong. Keep numerical integrity, visible grasp quality and reuse breadth as separate acceptance gates.
+
+## Next decision
+
+Keep ST2–ST3 partial. Before moving these modules into a supported library, exercise a second brief that changes the action structure: turn, carry with two hands, set down, release and look toward the recipient. Require object-to-set and palm contact checks, dedicated grip shapes and wider framing. Preserve failed trials. Continue to treat realistic human/product interactions as a jointly generated shot where appropriate; authored stylized contact is a distinct route with different quality limits.
+
+Audio listening, facial performance, skinning, cloth, large turns, sitting, third actors, broader hardware and full native integration remain open. Camera solve and reconstructed worlds are unchanged by this study.
diff --git a/skills/editableframes/references/hybrid-story-second-brief-2026-11-14.md b/skills/editableframes/references/hybrid-story-second-brief-2026-11-14.md
new file mode 100644
index 0000000..be86ace
--- /dev/null
+++ b/skills/editableframes/references/hybrid-story-second-brief-2026-11-14.md
@@ -0,0 +1,45 @@
+# Second action brief: carry and set down — 2026-11-14
+
+**ST2–ST3 remains partial, with a clearer reuse boundary.** Two new 14-second films use the same cast in sci-fi and toy/clay settings. The character lifts a tray with both hands, turns 90 degrees, walks to a table, lowers the tray, releases it and looks toward the other actor. Both films are 1280×720, 24 fps, with 336 frames and local synthesized dialogue. No paid model calls were used.
+
+## What this changes in the plan
+
+The characters, limb solver, restyling, proportions, gaze tools, render pipelines and typography transferred without changes. **The action did not.** The second brief required a new 23.7 KB choreography module, a tray-specific grip and new contact probes; each style also needed roughly 10 KB of prop/set/camera source. A copied walking module needed a change to start from rest.
+
+This supports reusable **cast, rig and look modules**, plus authored per-shot action code. It does not establish a general action library that accepts arbitrary “pick up” or “set down” instructions. Do not report source imports as proof that the first brief's action machinery was reused: the old story module appears in the import graph but does not execute here.
+
+The new clay grip is clearer in close-up, but this is **not a same-prop repair**. The earlier rocket is replaced by a tray with a rim and runners that leave space for the fingers. The new hand clamps the end wall, hooks fingers underneath and puts its thumb over the rim. The tray rests before the thumb lifts and fingers slide out. A plain box flush on a table cannot be released with this geometry.
+
+## Evidence and independent checks
+
+| Check | Sci-fi | Clay | Meaning |
+|---|---:|---:|---|
+| Coordinator fresh frame samples | 40/40 | 40/40 | Saved sequential hashes reproduced across cuts and contact transitions. |
+| Individual controls, changed then restored | 10/10 | 10/10 | Same Mac/browser; visible-frame tests. |
+| Fully decoded video | 336 frames / 14 s | 336 frames / 14 s | Stereo audio also spans 14 s; no listening review. |
+| Fresh geometry-probe replay | 336 match | 336 match | Node recomputation matches browser probe records; uses the worker's scene/probe implementation. |
+| First table contact / last both-hands hold | 215 / 223 | 216 / 224 | The authored release follows measured table contact. |
+| Unsupported frames under declared mesh rules | 0 | 0 | Geometric support classification, not forces or balance. |
+| Minimum sampled hand/table clearance | 5.34 mm | 6.81 mm | Fingers have room under the tray ends. |
+
+The coordinator also deliberately perturbed the actual settled tray in each scene. Lifting it 20 mm produces a roughly +20 mm runner gap; sinking it 20 mm produces −20 mm; moving it off the table produces zero supporting ray hits. The original poses have full runner-vertex support. These six fault cases and two resting baselines show that the table check can detect these errors; they do not validate all contact configurations.
+
+The worker separately exercised real CLI exposure and contact-zoom edits on four sampled frames per style, stale revision refusal, two undos and two redos. Its receipts report exact pixel restoration. That CLI run was inspected, not rerun by the coordinator. It covers two controls on sampled frames, not full-film/audio export or the native app.
+
+## Better probes, still bounded
+
+The earlier grip check read the solver's own targets. The new contact checks use actual geometry: rays from runner underside vertices to table triangles, and sampled hand surfaces against bounding boxes derived from tray vertices. The coordinator verified that the tray-part transforms in the delivered poses are unit scale, so the reported local-distance units are applicable there.
+
+Sampling can miss crossings between samples. Clay's lumpy meshes lie inside their boxes; its runner surface varies by about 1.83 mm. The tests do not model friction, force, character balance, hand-to-hand contact or hand-to-body contact. The worker's zero target-readback error remains explicitly excluded from contact acceptance.
+
+The retained failed pass matters: the first clay stand was too narrow, leaving runner vertices unsupported by about 4.7 mm at each end, despite passing seek tests. A separate geometry check caught it. Another correction raised the tray about 1.3 mm to avoid sinking into the lumpy table. Failed output and records remain retained.
+
+## Visual decision
+
+Close inspection shows a thumb over the rim and fingers under the edge, with no workbench visually behind the airborne tray. Those contact-zoom views are new camera renders of the same state, **not frames from the delivered film**. In the film each hand is only about 40–50 pixels high, so finger contact is harder to judge. Wrist bends, uniformly hooked fingers, rigid limbs, painted faces and limited downward gaze remain visible limitations.
+
+The coordinator inspected comparison sheets and source, not normal-speed motion or audio. The new action is more explicit, but keep natural performance and film-scale grip readability partial. The second actor does not share the load; two-person contact is not tested by this brief. Village, sitting, arbitrary props and additional hardware remain untested.
+
+## Next engineering boundary
+
+Separate reusable cast/rig/look from per-shot choreography, grip-specific geometry and validation. Require both a geometric contact check that responds to deliberately bad placements and an actual-film visual check. Avoid making props convenient for the solver without disclosing that constraint. Keep realistic interaction generation and authored stylized animation as separate production routes; this study does not replace either with a universal interaction solver.
diff --git a/skills/editableframes/references/hybrid-stronger-matting-2026-11-14.md b/skills/editableframes/references/hybrid-stronger-matting-2026-11-14.md
new file mode 100644
index 0000000..0dedeab
--- /dev/null
+++ b/skills/editableframes/references/hybrid-stronger-matting-2026-11-14.md
@@ -0,0 +1,57 @@
+# Stronger local matting: no replacement earned
+
+2026-11-14 · MASK1 remains partial · no paid calls · research only
+
+RVM ResNet50 and ViTMatte-S were tested on the retained generated presenter. Neither earns adoption as the hair matte. MobileNetV3 plus the conservative room-aware `clear_gated3` repair remains the preferred candidate for this shot, not a production-approved general solution. Larger models can remove unwanted background while also removing real-looking curls.
+
+## What was tested
+
+One 96-frame, 3.84-second excerpt at 1280×720, with lossless decoding and 88 frames of recurrent warm-up. ResNet50 used resolution ratios 1.0 and 0.5; ViTMatte-S used narrow and wide trimaps derived from MobileNet. The same room-aware repair was applied to new candidates. A second generation of the same fictional presenter is a distinct clip, not independent real-camera or different-hair evidence. No real hair alpha is annotated.
+
+| Head-region proxy | MobileNet + repair | ResNet50 r1.0 + repair |
+|---|---:|---:|
+| Room-like opacity (lower preferred) | 45.8 | 28.8 |
+| Missing-opacity bound (lower preferred) | 0.15 | 0.45 |
+| Thin-structure energy (descriptor, not accuracy) | 336 | 191 |
+
+These are model-assisted proxies. A pixel resembling the room does not prove hair is absent. The alternative reference built where neither network sees a subject is a useful sensitivity check, not an unbiased reference. ViTMatte cleans the concrete-side haze but softens the low-contrast curls against wood. No candidate improves both principal proxies over the current candidate.
+
+## Why the synthetic ranking cannot select a model
+
+The coordinator independently recomputed the white-background RGB error over all 96 frames using the saved alpha and foreground arrays, without the worker's scoring function:
+
+| Constructed alpha source | MobileNet error | ResNet50 error |
+|---|---:|---:|
+| MobileNet-derived truth | 23.7510 | 24.6416 |
+| ResNet-derived truth | 19.6987 | 18.9538 |
+
+The ranking reverses. Both synthetic clips have sharper, easier boundaries derived from this same source footage. Use them to expose tradeoffs, not to claim which model extracts real curls best. Numbers use the experiment's encoded-sRGB composite convention and are not interchangeable with the earlier linear-light audit.
+
+## Body cleanup is a separate candidate
+
+Brightened source frames reveal a chair in much of the previously described hand-shadow smear. ResNet50 removes more of those chair fragments. The delivered hybrid keeps MobileNet + repair around the head and ResNet50 on the body. It is an inspectable experiment, not an adopted model setting.
+
+The head region is fixed at pixels (440, 0)–(850, 330), with a 12 px alpha blend at its sides and lower boundary. Foreground RGB switches at the blend midpoint rather than blending continuously. Moving heads, colour seams, hair outside the region, and normal-speed playback remain unvalidated. Do not generalize this crop into automatic subject routing or claim it solves contact/interaction masking.
+
+## Coordinator verification
+
+- 36 fresh renderer samples across four cases match the worker's saved frame hashes exactly.
+- All 13 control changes alter the picture and restore it exactly; a fresh mount matches, with no browser errors.
+- Independent synthetic error recomputation matches all four reported values exactly.
+- Saved CPU/MPS alpha comparisons were independently rechecked: maximum difference is one alpha code for MobileNet, ResNet50 and narrow ViTMatte. These are comparisons of saved inference outputs, not new inference runs.
+- All 12 comparison MP4s fully decode with no errors.
+- Selected full-frame and hair-crop stills were inspected. Neither reviewer watched normal-speed playback or listened to audio; the delivered comparisons are silent. This is standalone renderer verification on one Mac, not native-app/exporter verification.
+
+## Performance and distribution boundary
+
+Worker single-run inference measurements on this Mac: MobileNet 0.46 s/frame CPU and 0.050 s/frame MPS; ResNet50 0.69 and 0.129; ViTMatte including its guide 1.15 and 0.27. These exclude the complete compositing/export pipeline and do not establish performance on ordinary PCs.
+
+The retained provenance records identify RVM as GPL-3.0, and ViTMatte's model card as Apache-2.0 with MIT code; training-data terms still need review before distribution. RVM's published runtime instructions do not document MPS; it was experimentally exercised here. No weights or model runtime are added to the library by this update.
+
+The worker downloaded about 227 MB and retained about 3,008 MiB of evidence. One initial library call wrote a one-byte Hugging Face cache version marker outside the study directory; later calls confined caches to the study. Nothing was deleted.
+
+## Next acceptance gate
+
+Obtain consented real footage with a known backing or annotated alpha on representative frames, including different hair and a moving camera/background. Compare lost detail, false opacity, temporal lag and normal-speed replacement-room playback together. The present bottleneck is independent evidence, not inference speed. A subject-memory video matting model is an untested future candidate requiring runtime and distribution review; downloading another model alone would not close MASK1.
+
+The dashboard retains the larger-model failures, fine-curl and haze crops, chair cleanup, fixed-region hybrid, full-frame comparisons, source, model provenance and both verification records. No whole research item is closed by this study.
diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md
new file mode 100644
index 0000000..25f0cb7
--- /dev/null
+++ b/skills/editableframes/references/hybrid.md
@@ -0,0 +1,295 @@
+# Hybrid scenes: code inside footage
+
+> Reflection review: flat-deck self-reflection and local bounce improve, but broad highlights, curved surfaces and a cross-renderer penumbra mismatch remain open. [Corrections, measured limits and routing](hybrid-reflection-review-2026-11-14.md).
+
+
+> Import/export reliability: private-copy validation and expected-revision export gates are implemented in the library. Automatic crash recovery remains proposed after a reproduced stale-lock race. [Evidence and remaining work](hybrid-import-recovery-2026-11-14.md).
+
+
+> Shared human/product light: one continuous track works, but footage correction is experimental. Half-house light plus front direction is not a sufficient acceptance rule. [Evidence and routing boundaries](hybrid-shared-human-light-2026-11-14.md).
+
+
+> Moving-reflection checkpoint: camera/product motion improves screen and emitter placement, but self-reflection and café brightness remain open. [Evidence and limits](hybrid-moving-reflections-2026-11-14.md).
+
+
+## Start here: what we tried, and which tool fits the shot
+
+[](hybrid-experiment-map.html)
+
+**[Open the interactive HTML map](hybrid-experiment-map.html)** · **[Read the full inventory and debate](hybrid-experiment-map.md)**. The HTML file opens locally in a browser; GitHub shows this static infographic and the Markdown evidence. No server or model call is needed.
+
+The map records **41 grouped trial entries in eight areas**, including failed attempts and later repairs. “Worked” means only the stated check or user judgment succeeded. It is not a production-readiness score. Ten remaining research/integration areas are listed separately.
+
+**Current position:** code-authored game-like storytelling is a promising, expandable route. Future LLM capability is a forecast; the preferred Fable fantasy draft is evidence of one short style, not every genre or a general provider ranking. Choose by the shot’s required accuracy, editability and shared action—not simply cartoon versus realistic. Exact graphics and authored worlds favour code; realistic handling trials favour staged joint generation; genuine testimony requires recorded evidence. Independent masks cannot create a shared performance.
+
+The HTML includes simple route illustrations, searchable trial cards, the strongest arguments on both sides, a category map and an illustrative mixed-route advert. This synthesis draws on existing Fable reviews; no fresh Fable endorsement was obtained during its recorded provider-limit window.
+
+---
+
+**Glass follow-up (2026-11-14):** [Verified nested-transparency limits](hybrid-glass-study-2026-11-14.md). The resumed study supports an experimental cylinder-only raster route and a slower Cycles quality candidate for this drink. Submerged ice, general shapes, moving-light response and native integration remain open.
+
+**CLI round trip (2026-11-14):** [Verified replay composition and audio fixes](hybrid-roundtrip-workflow-2026-11-14.md). Live overlays remain editable over retained generated interaction; staging/action changes invalidate dependent takes. Local CLI slice works, native/provider integration remains open.
+
+**Stronger-model follow-up (2026-11-14):** [Matched local model comparison](hybrid-stronger-matting-2026-11-14.md). Neither ResNet50 nor ViTMatte earns hair adoption. Body cleanup is a separate fixed-region experiment; independent alpha and motion acceptance remain open.
+
+**Mask isolation follow-up (2026-11-14):** [Completed independent study and coordinator verification](hybrid-mask-followup-2026-11-14.md). Lossless preparation matters; smoothing is not accurate extraction. A conservative room-aware repair helps this locked shot, but model limits and hand smears remain.
+
+**Mask audit (2026-11-14):** [Same foreground on five backgrounds](hybrid-mask-audit-2026-11-14.md). Dark backgrounds conceal alpha errors; temporal repair trades stability against real edge changes. Keep raw mattes and adjustable repair strength. Both studies subsequently resumed; see the follow-ups above. Neither is production-approved.
+
+**Gap closure checkpoint (2026-11-14):** [Verified subchecks, retained failures and remaining gates](hybrid-gap-closure-2026-11-14.md). The completed Fable film now passes independent seeking/control checks and a three-frame CLI edit/undo specimen. Target-texture warnings and a local recovery prototype add safeguards; tracking geometry, native integration and visual acting remain open.
+
+**Lighting correction (2026-11-14):** [Verified glare/shadow refinement and corrected measurement regions](hybrid-lighting-refinement-2026-11-14.md). Fixed-pose improvements are real; whole-scene realism and moving-product acceptance remain open.
+
+**Cross-style follow-up (2026-11-14):** [Three rendered styles and independent checks](hybrid-story-reuse-2026-11-14.md). The same cast now performs one shared-prop brief in sci-fi, cel-shaded village and toy/clay settings. A [second carry/set-down brief](hybrid-story-second-brief-2026-11-14.md) now demonstrates cast/rig/look reuse in two styles, but requires new choreography and a tray-specific grip. General action reuse remains partial.
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). At that checkpoint the Fable draft was unfinished and failed a random-seek check. The resumed film now passes the scoped runtime checks above; cross-style cast reuse now spans two action briefs, while action generalization and natural contact remain partial. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open.
+
+**Interaction policy (2026-11-13):** realistic avatar/product looking, pointing and physical handling use a reference-conditioned whole-shot generation route. Explicitly authored stylized rigs are a separate route, with their own contact and seek acceptance. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact.
+
+Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services.
+
+**Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented.
+
+A hybrid scene combines two kinds of picture in one shot:
+
+- **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light.
+- **Code**: it supplies what has to be exactly right: the product's shape and label, a price, an interface, a chart, a logo, a caption.
+
+Stacking one on top of the other is easy and already worked. This document covers the harder case, where the two must agree with each other: a hand passes in front of a code-rendered product, a headline sits behind a presenter, a price stays stuck to a moving sign, the product is lit by the room it stands in.
+
+See [prepared foreground and surface artwork](prepared-plates.md) for the implemented receipt, correction, holdout and motion APIs, and their verification limits.
+
+## Goal
+
+Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched.
+
+EditableFrames does not run any model. Mattes, depth maps, tracks and camera paths are **inputs**. You make them with whatever tool you trust and license, and EditableFrames pins them, checks them and draws with them. This keeps the framework model-neutral and keeps export deterministic: the same inputs give the same frames.
+
+## Video creation journeys
+
+Each journey says what the author does, what EditableFrames does, and how far it is proven.
+
+| # | Journey | The author supplies | EditableFrames does | Proven by |
+|---|---|---|---|---|
+| 1 | **A product in a generated place.** A hard-surface product sits in a scene made by a video model and takes on its light. | The plate. | Wraps the plate into an environment, estimates which side the light is on, and lights the product with both. Lighting from the plate is an editable, undoable control. | Integration test: the lit side follows the bright area, the colour follows the plate, toggling it changes only the product. |
+| 2 | **Something in the footage passes in front of the product.** A hand, a person, a pillar. | The plate and a depth map of it. | Writes the plate's depth into the depth buffer, so every mesh is hidden exactly where the footage is nearer. | Integration test: the product is covered by the plate foreground and visible beside it. |
+| 3 | **A headline behind the presenter.** Text or graphics sit between the subject and the background. | The plate and a matte of the subject. | Redraws the matted subject over the DOM layers. | Integration test: no headline pixel survives in front of the subject, and the text continues on both sides. |
+| 4 | **Screen or label replacement.** An exact interface, price or label sits on a surface that moves in the footage. | The plate and a planar track of the surface. | Pins a DOM element to the tracked quad on every frame, including between frames. | Integration test: the element covers the tracked surface edge to edge as it moves. |
+| 5 | **Code first, footage second.** The code scene sets the camera and blocking; a video model paints a world around it; the exact product goes back on top. | A scene that declares control passes. | Exports the scene as clay, depth, normal, object-id and matte passes from the same camera and timing. | Integration test for the passes. Sending them to a video model and compositing the result is outside this repository and unproven here. |
+| 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. |
+| 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. |
+| 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. |
+| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred; resumed film passes same-machine sequential/seek/control checks and a three-frame CLI specimen. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. |
+
+The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found.
+
+## Try it
+
+```sh
+node bin/editableframes.mjs init ./my-hybrid --hybrid
+node bin/editableframes.mjs preview ./my-hybrid
+node bin/editableframes.mjs render ./my-hybrid ./hybrid.mp4
+node bin/editableframes.mjs render ./my-hybrid ./hybrid-blur.mp4 --motion-blur 180
+node bin/editableframes.mjs render ./my-hybrid ./clay --format png --pass clay
+```
+
+The starter generates its own plate, matte, depth map and track with FFmpeg from one set of formulas, so tests can state where every pixel must land. Replace them with your own:
+
+```sh
+node bin/editableframes.mjs asset-add ./my-hybrid shot ./shot.mp4
+node bin/editableframes.mjs asset-add ./my-hybrid shot-matte ./shot-matte.mp4 --role matte --of shot
+node bin/editableframes.mjs asset-add ./my-hybrid shot-depth ./shot-depth.mp4 --role depth --of shot --depth inverse --near 1 --far 20
+node bin/editableframes.mjs asset-add ./my-hybrid shot-track ./shot-track.json --role track --of shot
+node bin/editableframes.mjs rebind ./my-hybrid
+```
+
+## Layers
+
+Back to front, this order is right for most shots:
+
+1. **Plate.**
+2. **Far DOM**: screens pinned to surfaces in the background; text that passes behind the subject.
+3. **Cut-out**: the plate's subject again (plate × matte), which restores it over layer 2.
+4. **3D canvas**, depth-tested against the plate's depth. Depth decides per pixel whether the subject or the object is in front, so the canvas can sit above the cut-out.
+5. **Near DOM**: captions, calls to action, logos.
+
+A scene can draw all five itself, as the starter does. That keeps one clock and one set of inputs. Depth ordering between separate clips is not available: clips stack with a transform and opacity only.
+
+## Plate data
+
+Data computed from a plate is declared in `assets.json` as a **derived** asset. It records the hash of the plate it was computed from:
+
+```json
+"shot-matte": {"src": "assets/…mp4", "type": "video", "sha256": "…",
+ "derived": {"of": "shot", "role": "matte", "sourceSha256": ""}}
+```
+
+`asset-add --role … --of …` writes this for you.
+
+| Role | Type | Meaning |
+|---|---|---|
+| `matte` | video or image | White keeps the subject, black drops it. Luminance is coverage. |
+| `depth` | video or image | Distance from the camera. White is near. Needs an `encoding` (below). |
+| `normals` | video or image | Camera-space normals, `(n + 1) / 2` in RGB. Accepted and pinned; no helper consumes it yet. |
+| `track` | data (JSON) | A planar or point track. See `packages/plate/track.mjs`. |
+| `camera` | data (JSON) | A camera path. See `packages/plate/camera.mjs`. |
+| `environment` | image | An equirectangular picture of the plate's surroundings. Accepted and pinned; the starter does not use one. |
+
+Rules, each refused with a message that says what to do:
+
+- The plate's hash must equal `sourceSha256`. A regenerated take invalidates its derived data.
+- A plate has at most one asset per role.
+- A derived asset cannot derive from another derived asset.
+- A derived video must have exactly as many frames as its plate.
+- A depth asset must carry an encoding. Tracks and camera paths are validated when loaded.
+
+**Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that.
+
+- *Fewer frames at the plate's own rate* means correspondence is incomplete; do not assume the missing frames are all at the end. Verify which source frame each output describes, then recompute/correct missing data or trim the shot to a verified range. Do not hold the tail of a moving matte/depth map to satisfy the frame-count check. Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early.
+- *Another frame rate* has to be resampled onto the plate's frame times.
+- *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing.
+- Check the result against moving edges throughout each crossing. Inspect every decoded frame of short final clips, including full-resolution crossing crops and normal/slow playback. A few matching frames are only a smoke test.
+
+**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale: tuning `near` and `far` can create a plausible ordering in some frames, but does not establish shared geometry or correct hand/face edges. They are not measurements. Prefer an explicit subject holdout for a known foreground crossing.
+
+**Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so.
+
+**Camera path** files are `{version: 1, frameRate, frames: [{frame, position, quaternion, fovY}]}`: camera-to-world, +Y up, looking down −Z, `fovY` in degrees.
+
+## Renderer contract additions
+
+Two optional services join `asset` and `mediaFrame`. Check that they exist before using them.
+
+- `context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, derived}` for a declared asset.
+- `context.derived(id, role)` returns the id of the asset derived from `id` with that role, or `undefined`.
+
+`mediaFrame(id, seconds)` serves matte and depth frames like any other video. `asset(id)` returns a URL for a data asset; fetch it and parse the JSON.
+
+A scene may declare **control passes**:
+
+```js
+defineRenderer({ …, passes: ['clay', 'depth', 'normal', 'id', 'matte'], … })
+```
+
+The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A host never asks for a pass the scene did not declare, and the CLI refuses one. Pass names are open, like renderer names. `beauty` is implied and cannot be declared.
+
+## Helpers
+
+`editableframes/plate` is pure and renderer-independent:
+
+| Area | Functions |
+|---|---|
+| Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` |
+| Tracks | `validateTrack`, `sampleTrack`, `sampleTrackFrame`, `scalePoints` |
+| Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` |
+| Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` |
+| Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` |
+| Measuring a plate | `plateStats`, `matchLevels`, `applyLevels`, `estimateKeyLight`, `estimateNoise`, `grainAt`, `expandHighlights` |
+| Passes | `idColor`, `idFromColor`, `validatePasses` |
+| Canvas | `drawCutout`, `drawGrain`, `createFrameLoader` |
+| Shutter | `shutterSamples`, `validateShutter` |
+
+`editableframes/three-plate` is an optional Three.js adapter:
+
+| Function | Purpose |
+|---|---|
+| `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. |
+| `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. |
+| `createPlateEnvironment(renderer)` | Lights the scene with the plate. |
+| `paintPlatePanorama(context, source, width)` | The panorama `createPlateEnvironment` builds: the plate in front of the camera, mirrored behind it. |
+| `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. |
+| `applyCameraSample(camera, sample)` | Replays a camera path. |
+| `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. |
+| `renderPass(renderer, scene, camera, pass, options)` | Draws the scene as clay, depth, normal, id or matte. |
+| `dataTexture(image)` | A texture for plate data with no colour management. |
+
+None of this narrows what a renderer may draw. A scene that uses other libraries can read the same assets and implement its own passes.
+
+## What is estimated, and how far to trust it
+
+Three helpers guess from a single view. Expose their results as controls.
+
+- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. Its colour is the brightest area's colour, which can be an object's (blue components read as a blue light) rather than the light's.
+- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`).
+- **Depth `near` and `far`** are yours to tune, as above.
+
+## Frame rate
+
+Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow.
+
+- Anything locked to the footage should move on the footage's frame grid. Use `seconds = clock.mediaTime ?? clock.frame / clock.fps` for footage and its derived data: this clock stays at the output frame during shutter sampling. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames.
+- A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it.
+
+## Export
+
+- `render DIR OUT --pass NAME` renders a declared pass. The receipt records it.
+- `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur.
+- MP4 and MOV keep the values the browser drew: BT.709 matrix, limited range, transfer tagged as sRGB. Footage in a hybrid shot comes out at the levels it went in.
+- An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility.
+
+## Compared with a full compositing checklist
+
+Professional compositing uses more steps than this. Stated plainly:
+
+| Step | Status |
+|---|---|
+| Occlusion by plate geometry | Done, from a depth map. |
+| Subject in front of graphics | Done, from a matte. |
+| Planar tracking and corner pin | Drawing done, for flat surfaces. The track comes from another tool. A surface that bends (curled paper, cloth) needs a mesh warp, which is not provided. |
+| Edge clean-up of the cut-out | Not provided. A matte edge keeps some of the plate's background colour, which shows as a thin fringe over contrasting graphics. |
+| Reflections of the plate in the object | Approximated by `createPlateEnvironment`. |
+| Light direction | Estimated; editable. |
+| Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. |
+| Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. |
+| Motion blur | Done at export, for code layers. |
+| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. The catcher is a plane with no depth: a shadow it catches is also drawn over a real object standing on that plane. |
+| Camera match | Replay only. No solver. |
+| Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. |
+| Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. |
+| Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. |
+
+## On generated footage
+
+The helpers were tried on twelve 5–6 second plates from four video models (Seedance 1 Pro Fast, Kling 2.5 Turbo Pro, Veo 3.1 Fast, Wan 2.2), with mattes and depth maps from hosted models and tracks from a classical planar tracker. Each scene was a renderer scene of the kind the starter shows. This is one trial, not a benchmark.
+
+| Journey | What was found |
+|---|---|
+| Screen or label on a surface | Tracking held the phone within 3 px at 1088 × 1920 while it moved 24 px, but the composite fails: its thumb matte collapses at frames 60–70 of 121. The café menu also fails because no foreground matte protects the person and the footer overflows. A curled sheet missed the planar pin by up to 15 px. |
+| Headline behind a subject | Sampled frames demonstrate the layer effect, with a 1–2 px light fringe at hair. Whole-shot acceptance was not established by those samples. |
+| Footage in front of a 3D object | Fails final quality in the can example: the hand is split across the inserted object. Hand-tuned relative depth does not share its scale/camera, and no mask resolves a hand moving through the volume chosen for the new object. |
+| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. |
+| Placing a 3D object without a camera solve | A tracked stand-in provides an approximate screen anchor, not a metric camera/pose solve. The example adds a second can; it fails the intended original-can reskin. A separate code-first take also exposes a larger generated can beneath the code object: one conditioning still did not preserve geometry. |
+
+Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project.
+
+## On filmed footage
+
+Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-control dolly, one on a tripod) were tried the same way, with a hosted matte and depth map for the third. It is a smaller trial than the one on generated plates.
+
+| Journey | What was found |
+|---|---|
+| Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. |
+| Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. |
+| Headline behind a subject | Fails whole-shot acceptance: while a fast arm enters (up to 460 px per frame), the matte lags by 1–2 frames and the headline shows through it. Its forearm edge is about 10 px wide from 10% to 90%. Other frames demonstrate the layer effect. |
+| Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. |
+
+The same trial found three export defects, all fixed:
+
+- MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included.
+- A scene with no transparency could not be exported to MOV.
+- Footage tagged with BT.709 primaries and transfer, as most camera footage is, was drawn darker than its values before it ever reached the encoder. A board pixel stored as (142, 117, 73) drew as (136, 109, 63).
+
+## Limits
+
+- The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast.
+- A renderer scene has no audio port. Sound from footage inside a scene is not mixed; keep speech on a media-port clip.
+- `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units.
+- Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes.
+- Results differ slightly across GPUs and browsers, as elsewhere in this framework.
+- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. The trials and subsequent failure audit above establish current limitations; all-frame quality gates remain proposed work.
diff --git a/skills/editableframes/references/interaction-staging-workflow.md b/skills/editableframes/references/interaction-staging-workflow.md
new file mode 100644
index 0000000..5b0e8f1
--- /dev/null
+++ b/skills/editableframes/references/interaction-staging-workflow.md
@@ -0,0 +1,48 @@
+# Stage the scene, then generate the interaction
+
+**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes.
+
+**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified.
+
+**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested.
+
+Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration.
+
+## The boundary
+
+Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion.
+
+For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; a two-person transfer now has one local demonstration, while animal and object-collision shots remain untested and broader multi-person reliability remains unvalidated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction.
+
+## Author and agent workflow
+
+1. **Stage:** place subjects, products, support surfaces and background; set scale, orientation, camera, eyelines and initial lighting. Humans and agents edit the same saved scene. Use plausible resting poses and reachable objects. Blocking proxies describe placement, not final appearance or solved anatomy.
+2. **Approve and freeze:** choose the source frame and shot camera, commit the intended scene revision, and capture a clean snapshot without selection outlines, gizmos or editor chrome. Save the editable scene alongside it. Re-check support, reach and framing before spending on generation.
+3. **Package the scene set:** include that snapshot plus separate subject identity, product detail/multi-angle and background references as available. Label each reference's purpose and preserve their order. Record scene/source revision, frame/time base, camera, output dimensions, assets and hashes, reference rights/provenance, desired action beats and acceptance criteria. Retain the actual submitted bytes and prompt, not merely expiring URLs.
+4. **Generate during preparation:** select a model such as Kling using the chosen endpoint's actual capabilities. Prefer a start-frame/keyframe input for composition and separate reference inputs for appearance when the endpoint supports both together. An ordinary reference image is a softer hint; do not label it a locked first frame. Verify combinations, reference numbering, duration and cost before submitting. If the endpoint cannot accept the scene set, choose a compatible route or disclose the limitation rather than silently dropping a reference. An accepted video can instead be the base for a video-edit request.
+5. **Review the whole interaction:** inspect normal/slow playback and every contact transition for gaze, reachable grip, support/release, hand/limb anatomy, collisions, identity, product geometry/branding, shadows and reflections. Judge positional instruction following separately from overall appearance. A snapshot conditions the result; it does not constrain a solver or guarantee exact placement.
+6. **Return to composition:** import an accepted take as a versioned footage asset, probe actual decoded frames/timestamps, then derive masks/tracks from those exact bytes where needed. Keep typography, prices, captions and suitable surface inserts independently editable. Screen-space UI does not inherit physical subject holdouts. Keep the staged scene so another layout can produce another snapshot/take.
+
+Generate the interacting subjects and shared support/room as one shot by default: it gives the model a common lighting and contact context. Foreground-only generation is a separately tested option when alpha, edge colors, contact shadows and background correspondence are actually available. It is not a general solution for changing a room after a pickup.
+
+## What exists and what remains
+
+The standalone Scene Studio example already exposes placement, camera/light controls, saved scene state and **Save reference PNG** from a frozen committed shot. It is an opt-in example, not proof of a universal editor/agent capture API or a native host integration. The scene-set manifest, automatic provider packaging, generation handoff, receipt binding and accepted-take import still need host integration and end-to-end tests. No implicit model call belongs in `render(clock)` and no mandatory vendor dependency is added to the core.
+
+Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags.
+
+## Earlier experiments and conclusions (before the staged trial)
+
+The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support.
+
+The first reference-conditioned Kling take used separate presenter, product and room images. Attention improved, but the headphones stayed upright despite a side-resting instruction. The follow-up used **that accepted-looking video as the base plus the official single-view product photo**, not a newly staged scene snapshot. It produced a clearer headband grip, lift and supported two-hand hold; the user preferred it. The requested camera-left shift was not meaningfully achieved, and the weighing motion read mainly as pickup-and-hold. The upright start remained. Thus the pickup result supports joint generation; it does **not** complete the snapshot-plus-references test, establish exact product fidelity or validate other interaction categories.
+
+The follow-up decoded to 1280×720, 121 frames at 24 fps (5.0417 s). Its EditableFrames round trip retained the frame count, repeated a randomly sought frame identically in the tested browser, and preserved source pixels outside the title before encoding. Title/eyebrow/accent/visibility remained editable. Those are renderer-integrity checks, not proof of physical realism. Contact crops covered all frames and full-scene samples were inspected; no fresh independent reviewer approval is claimed.
+
+At the recorded provider rate, the successful video edit was estimated at about $0.95; the account ledger charge was not retrieved. One earlier upload-URL attempt failed validation and is retained separately. A direct original MP4 output URL, verified against the local source hash, resolved the transport issue. The provider returned a 10.084-second duration metric for a 5.0417-second file, consistent with input-plus-output billing; decoded timestamps must own the timeline.
+
+## Editability and evidence retention
+
+After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects.
+
+Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category, repeat the snapshot handoff and validate native host integration before broad quality claims.
diff --git a/skills/editableframes/references/prepared-plates.md b/skills/editableframes/references/prepared-plates.md
new file mode 100644
index 0000000..2f75890
--- /dev/null
+++ b/skills/editableframes/references/prepared-plates.md
@@ -0,0 +1,49 @@
+# Prepared foreground and surface artwork
+
+The plate utilities now include versioned analysis receipts, explicit source-frame sampling, foreground holdouts, source-space corrections, cylinder/mesh artwork mapping and deterministic kinetic text. These are rendering and authoring primitives. Real footage still requires a reviewed subject mask and surface track; model success does not certify either.
+
+## Frozen analysis
+
+`validatePreparedAnalysis(receipt, sourceInfo)` checks source content identity, decoded raster, rational frame rate, presentation times, correspondence, mask identity, correction revision and preparation provenance. A receipt has `version:1`, `kind:"prepared-plate"`, `source`, `alpha`, `subject`, `revision`, `provenance` and one entry per source frame in `frames`. Each entry contains `sourceFrame`, `maskFrame`, `valid`, `reviewed` and optional diagnostic `issues`.
+
+`preparedFrame(receipt, seconds, {start, speed})` maps explicit clip time to a source frame, including trim and reverse. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame.
+
+Import a receipt as a data asset with `--role analysis --of plate`, and its explicit-alpha media with `--role alpha --of plate`. `--subject ID` distinguishes derived assets for multiple subjects. `derived(plate, role, subject)` resolves that subject; the original two-argument form still resolves an unqualified role. The CLI verifies content hashes, while media preparation checks the receipt against the actual decoded plate and mask.
+
+The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index.
+
+## Foreground and corrections
+
+`createForegroundHoldout({root,width,height})` creates a child `root` for the affected code layers. Call `update(decodedMask,{channel,frame,...})` before capturing. `channel` is `alpha` or `luminance`; missing or wrong-sized masks throw. An uncorrected explicit-alpha image uses CSS GPU masking where supported. Luminance masks and live corrections use the CPU fallback. No model runs inside the renderer.
+
+Correction books bind `sourceSha256`, `subject` and increasing frame keys. Each key has polygons with `operation:"add"|"subtract"|"replace"` and source-raster `points`. `interpolation:"linear"` propagates only between matching polygon keys; it never extrapolates beyond them. `createMaskCorrectionSession` turns renderer gestures into immutable book proposals. The host applies revision checks and Undo. Re-prepare and review the corrected result before final export.
+
+`analyzeMask` reports coverage, bounds and collapse flags without deleting components. `foregroundLeakage` measures changed pixels inside an annotated opaque foreground. `diagnosticMask()` exposes the current subject coverage as a green overlay for a source/mask review view. These diagnostics flag work to review; they do not infer ground truth.
+
+## Surface mapping and motion
+
+`cylinderMesh` maps a label to an authored/tracked projected body quad. It preserves that body's screen bounds; the seam is an author control when a blank cylinder makes rotation unobservable. `sampleSurface` accepts externally tracked deforming UV meshes. `drawSurfaceArtwork` rasterizes UV triangles without translucent clip seams. `relightArtwork` preserves observed shading under a specified neutral-albedo assumption. Arbitrary old printing requires a separate clean albedo/shading estimate.
+
+The [surface example](../examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background.
+
+`createKineticText` and `typeMotion` provide staggered rise, wipe, spring-like settle, orbit and CSS extrusion treatments. Timing, text, stagger, easing treatment and displacement are explicit inputs; random/reverse seeks reproduce the same state. Character splitting uses grapheme clusters where available. Font readiness and surface safe-area checks remain part of layout acceptance.
+
+## Verification and limits
+
+`npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage.
+
+The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement.
+
+## Exact geometry with a generated environment
+
+The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact foreground cylinder or optional imported GLB in code, over a clean background asset named `world`. A native host can bind `world` and supply verified `worldInfo` (width, height, frames, rational frameRate). The scene adds an authored contact shadow, plate-derived reflection approximation, control passes and an analytic orbit title. The background must have no original foreground object; this avoids a mismatched generated silhouette behind the exact object. It does not solve a camera or prove that a video model consumed 3D control passes. Imported photo geometry/material fidelity is a separate acceptance task.
+
+`surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface.
+
+## Retained generated-footage QA (2026-11-11)
+
+The new primitives were exercised on complete short clips, keeping the original failed renders separately. Reviewed source/mask contact sheets and every output event crop covered 121 frames each for a café board, close-up phone, opaque board card and original-can reskin; the exact-geometry scene covered 81 frames. The board footer was moved inside its safe area, the phone subject mask was replaced after collapse, and the label was fit to the original neutral can body. These shots work with reviewed inputs and manual surface/material tuning. They do not establish automatic segmentation or camera solving.
+
+Before video encoding, each of the four foreground composites preserved every tested opaque interior pixel: alpha at least 254/255, eroded by two source pixels, with at most one RGB code-value tolerance. This is a scoped leakage check against the supplied reviewed mask, not annotated boundary accuracy or fractional-hair color validation. All 81 exact-geometry control mattes were byte-identical; the generated background contained no product to mismatch. The label stayed on the original can and retained its rims/contact shadow. That shot's hand did not cross the original left can, so it is not a can-crossing stress test.
+
+The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 131 unit tests plus real-pixel prepared alpha/luminance capture and rejection of missing foregrounds. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work.
diff --git a/skills/editableframes/references/renderer.md b/skills/editableframes/references/renderer.md
index c463e9a..343a4bf 100644
--- a/skills/editableframes/references/renderer.md
+++ b/skills/editableframes/references/renderer.md
@@ -72,6 +72,13 @@ SVG and WebGL descendants. PNG and ProRes preserve alpha; MP4 flattens over the
requested background. `window.editableframes.captureTarget` describes the capture
selector for browser harnesses. `png()` remains the legacy Canvas-only shortcut.
This is trusted local browser execution, not isolation from malicious authored code.
+The CLI normally uses Playwright's managed Chromium. To use an already installed,
+compatible Chromium explicitly, set `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` to its
+absolute executable path. `doctor` checks that configured file; `render` verifies
+it can actually launch. This opt-in does not download a browser or silently fall
+back. Record the browser version with visual evidence; cross-version pixel
+identity is not promised.
+
For WebGL, retain the rendered drawing buffer for capture (for example,
`preserveDrawingBuffer: true`) and await required GPU work.
Cross-browser/GPU/font pixel identity is not promised.
@@ -125,10 +132,26 @@ returns a URL for a pinned manifest ID. `context.mediaFrame(id, sourceSeconds)`
available with prepared media and returns a PTS-selected frame URL or undefined.
Load/decode that image before finishing the render; this API does not return a
borrowed Canvas. The CLI supports image/video/audio manifests; its default renderer
-path does not mix arbitrary DOM audio automatically. Legacy media-port audio keeps
-its existing mixing path. `captureSurface` is absent in this host. Feature-check
+path does not mix arbitrary DOM audio automatically. Explicit static `scene.media` ports use
+the same mixing path as legacy media ports. `captureSurface` is absent in this host. Feature-check
optional services; do not invent layer, depth, simulation or screen services.
+`context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate,
+derived}` for a declared asset. `context.derived(id, role)` returns the ID of the
+asset computed from `id` with that role (`matte`, `depth`, `normals`, `track`,
+`camera`, `environment`), or undefined. Both exist only when the project declares
+media. A `data` asset is JSON: fetch `asset(id)` and parse it. See
+[hybrid scenes](hybrid-scenes.md) for compositing code with footage.
+
+## Optional control passes
+
+A scene may declare `passes: ['clay', 'depth', …]`: other ways it can draw
+itself, for conditioning a video model or compositing elsewhere. Names are open
+lowercase identifiers; `beauty` is implied and cannot be declared. The host
+supplies `clock.pass`, which is `'beauty'` unless a pass was requested, and never
+requests a pass the scene did not declare. `render DIR OUT --pass NAME` exports
+one. Draw nothing but the pass: hide footage and DOM layers.
+
When exposing controls for separate components, use distinct stable semantic
anchors and matching properties. Connect controlled DOM nodes to those IDs, or
implement Canvas/WebGL picking against the current rendered geometry and props.
@@ -161,3 +184,34 @@ These tests do not establish a native application's integration or agent reliabi
For optional object parents, locked/hidden policy and bounded direct-manipulation
proposals, read [the interaction contract](interaction-contract.md). The renderer
hook returns sparse control values; a host owns one atomic commit and cancellation.
+
+### Footage during shutter sampling
+
+`clock.mediaTime` is source seconds at the output frame's time, after the clip's
+trim and playback rate. Without a shutter it equals `clock.frame / clock.fps`.
+During motion blur, `clock.frame` advances through the shutter samples while
+`clock.mediaTime` stays fixed. Use `clock.mediaTime ?? clock.frame / clock.fps`
+for footage, mattes, depth and tracks attached to it; use `clock.frame` for code
+animation. `mediaFrame(id, seconds)` still honors the exact time requested, so
+custom scenes must choose the appropriate clock. Legacy renderers receive
+`mediaTime` alongside `time`; pass `mediaTime` to `host.portFrame` for footage.
+The media starter uses this clock too; authored media offsets remain explicit.
+
+### Static audio on portable renderer scenes
+
+A `defineRenderer` descriptor may declare `media` ports just like a template:
+
+```js
+media: {
+ firstTake: {asset: 'pickup', offset: 0, end: 'transparent'},
+ secondTake: {asset: 'handoff', offset: 121 / 24, end: 'transparent'},
+}
+```
+
+The editing adapter preserves this declaration for the existing audio scheduler.
+Audio follows clip trim, playback rate and port offsets; pictures must still sample
+those sources explicitly. At unchanged speed, the mixer uses a passthrough filter
+instead of time-stretching. This does not imply dynamic audio automation, arbitrary
+renderer-prop bindings, or sample-identical AAC encoding. Source/runtime changes
+still require an explicit project rebind. `npm run test:audio` exercises PCM trim,
+delay and 1× sample alignment through the real mixer and requires FFmpeg.
diff --git a/skills/editableframes/references/staged-generation-results-2026-11-13.md b/skills/editableframes/references/staged-generation-results-2026-11-13.md
new file mode 100644
index 0000000..a93e190
--- /dev/null
+++ b/skills/editableframes/references/staged-generation-results-2026-11-13.md
@@ -0,0 +1,46 @@
+# Staged generation tests — 2026-11-13
+
+**User visual acceptance (2026-11-13):** the user says the full-pickup and two-person handoff outputs look good. Treat these takes as accepted demonstrations of the staged joint-generation direction and proceed with the planned host workflow. This does not certify exact product fidelity, requested heft, repeatability, all-frame anatomy or native delivery, and is not a new independent Fable review. The original measurements below remain unchanged. [Combined conclusions and the separate authored-story experiment](code-generated-story-results-2026-11-13.md).
+
+Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval.
+
+## Test A: authored snapshot → pickup
+
+The editable reference scene places the real product photograph on the camera-left table using exposed position, scale, image-plane rotation and approximate foreshortening controls. Its background and fictional presenter come from a retained image. This is a 2D blocking composition: it does not establish physical resting geometry, a camera solve or measured lighting.
+
+The captured 1280×720 snapshot was submitted as `start_image`; separate product-detail and presenter images followed in that order as `@image_2` and `@image_3`. Thus this trial really exercises first-frame plus separate references, unlike the previous video-edit trial. The exact prompt asks for look → grip → lift → supporting palm → gentle heft/hold in five seconds, with a fixed camera and the original starting position.
+
+Prediction `nj6k9wyeenrmt0d1tjwr4cqc8m`, `kwaivgi/kling-v4.0`, image-input route. Processing took 111.34 s. Decoded output: 1280×720, 121 frames, 24 fps, 5.041667 s; audio present. SHA256: `10276551f3efb9d2dfbc4831baf054173475c271ffb575f0d667366ffc056afb`.
+
+**Observed:** the camera-left resting start is retained. A product-and-table image patch matches at zero whole-pixel translation, normalized correlation 0.99398; mean absolute RGB differences are 3.91/255 over the frame and 3.85/255 over the product region. This measures opening-frame placement, not exact product shape or a physically constrained trajectory. The woman looks down, reaches, closes on the headband, rotates/lifts the single pair, brings the other hand below it, then shifts to a supported display. The requested heft reads mainly as pickup and hold. All 121 contact crops and 15 full-scene samples were inspected. No conspicuous duplicate product or gross hand-through-earcup event was found in that inspection; fine anatomy, text fidelity, exact geometry and normal/slow playback acceptance are not certified.
+
+The accepted-for-inspection take was imported into an EditableFrames renderer with separate title/eyebrow/accent/visibility controls. Export retains 121 frames at 24 fps. Repeat frame 48 has zero maximum RGB difference; source pixels outside typography are unchanged before encoding; a title-control edit changes 15,118 pixels; no page errors. Generated hands, product motion, physical light and room pixels remain baked.
+
+**Verdict: works with manual staging for this pickup.** This advances the local snapshot handoff from untested to one demonstrated case. It is not exact-object advertising approval, universal first-frame compliance, multi-angle validation or native host delivery.
+
+## Test B: two-person handoff
+
+The final decoded frame of Test A is the start image; product and presenter references remain separate. The second adult is specified in text, not supplied as an identity reference or pre-staged actor. The seven-second prompt requires entry → receiver grip/support → giver releases both hands → receiver alone holds. This is a living-thing–living-thing–object test, not an object–object collision test.
+
+Prediction `7dz5cxr6mdrmt0d1tjz9eahxg0`, same image-input route. Processing took 100.33 s. Output: 1280×720, 169 frames, 24 fps, 7.041667 s; audio present. SHA256: `99f2bd0be73114fbc4d92d3cbd20b8f2a7533efbbf8c869ab3574fe951c69423`.
+
+**Observed:** the man enters from camera-right and lowers himself beside the woman. She turns toward him and extends the single pair. Their hands share support around 3.5–4.7 s. At about 4.8–5.0 s she releases and withdraws her hands; by about 5.25 s her empty hands are on the table. The receiver alone holds and inspects the headphones through the end. All 169 contact crops and first/middle/last full-scene images were inspected. No gross duplication or disconnected limb was found in that inspection. Fine fingers, exact product surfaces/lettering and photometric consistency are not certified. Recipient identity consistency across other shots is untested.
+
+The opening-frame product-region patch has zero whole-pixel translation and correlation 0.9970; whole-frame RGB difference averages 3.32/255. These are opening-frame comparisons, not interaction fidelity scores. Editable typography is placed over the empty lower-left tabletop to avoid the second actor. Physical interaction remains baked in the generated footage. Export retains all 169 frames at 24 fps; repeat frame 48 and source pixels outside the lower-left typography region have zero maximum RGB difference before encoding. A control edit changes 15,803 pixels; no page errors.
+
+**Verdict: works with manual review for this transfer.** Completed release is now demonstrated once; it is not proof of repeatable multi-person choreography. The seven-second duration and different starting pose prevent treating this as a controlled comparison against the five-second pickup.
+
+## Budget and durable evidence
+
+Published image-input pricing was rechecked at $0.157/s for 720p. Five plus seven requested seconds estimated $1.884. Actual decoded durations total 12.083333 s, estimating **$1.8971** at the published rate (provider-rounded durations estimate $1.8972). Actual account billing was not retrieved. The round is closed to further submissions; the remaining estimate is below the minimum three-second image-input job. Each submission is guarded against retry after an ambiguous POST and linked to ordered input hashes and a job receipt. No third job is permitted in this round. Provider cost estimates are not a verified account ledger charge.
+
+## Plan implications
+
+- Preserve the distinction between `start_image` and an ordinary appearance reference. The observed placement benefit supports using an approved starting frame, without claiming an exact constraint or a controlled A/B model study.
+- Freeze source/render binding, scene controls, frame/camera, snapshot and reference bytes/order before submission. Preserve the editable scene for another layout, and regenerate action when that layout changes.
+- Acceptance must include the actual action beats. A good-looking pickup without heft, or two people holding without release, is not full instruction compliance.
+- Source-bound masks/tracks must be regenerated for new take bytes. Existing masks from the earlier pickup cannot be attached to these new videos.
+- Remaining: object–object contact, repeatability across seeds/takes, two identity-referenced subjects, multi-angle product fidelity, full-resolution edge annotations, native receipt/import/failure handling, stronger mixed human/product relighting and actual additional-computer benchmarks.
+- Feature item 6 (camera solve) and feature item 13 (generated worlds) remain untested/deferred. Authored cameras, captured stills and generated videos are not evidence for either.
+
+Primary provider reference: [Kling inputs and pricing](https://replicate.com/kwaivgi/kling-v4.0). Visual findings and timings above are local experiment observations.
diff --git a/templates/hybrid/clip.mjs b/templates/hybrid/clip.mjs
new file mode 100644
index 0000000..2e8a967
--- /dev/null
+++ b/templates/hybrid/clip.mjs
@@ -0,0 +1,101 @@
+// Hybrid starter: a code-rendered product inside footage.
+//
+// Footage ("plate") supplies what should merely look real. Code supplies what
+// must be exactly right: the product, its label, the screen and the headline.
+// The plate here is a synthetic diagnostic pattern; swap in your own with
+// `asset-add`, together with the matte, depth and track made from it.
+//
+// Layers, back to front:
+// plate the footage
+// screen DOM, corner-pinned to a tracked surface in the plate
+// headline DOM, passes BEHIND the plate's subject
+// cut-out the plate's subject again (plate x matte), restoring it over the DOM layers
+// product WebGL, depth-tested against the plate's own depth
+import * as THREE from 'three';
+import {RoomEnvironment} from 'three/examples/jsm/environments/RoomEnvironment.js';
+import {defineRenderer} from 'editableframes/renderer';
+import {sampleTrack,scalePoints,cornerPinTransform,conformSeconds,drawCutout,createFrameLoader,estimateKeyLight} from 'editableframes/plate';
+import {createDepthOccluder,createPlateEnvironment,applyKeyLight,dataTexture,renderPass} from 'editableframes/three-plate';
+
+const WIDTH=640,HEIGHT=360,IDS=['can.body','can.lid'];
+export default defineRenderer({
+ id:'hybrid-product',title:'Product in footage',renderer:'three+dom',width:WIDTH,height:HEIGHT,fps:24,durationInFrames:72,
+ passes:['clay','depth','normal','id','matte'],
+ defaultProps:{label:'ORBIT',detail:'330 ml · 0 kcal',color:'#d8263c',headline:'Cold. Always.',price:'$2.49',distance:3,offset:0,plateLight:true},
+ controls:{version:1,objects:[{id:'scene',label:'Scene'},{id:'can',label:'Can',parentId:'scene'},{id:'headline',label:'Headline',parentId:'scene'},{id:'screen',label:'Screen',parentId:'scene'},{id:'light',label:'Lighting',parentId:'scene'}],fields:[
+ {key:'label',anchor:'can',property:'label',path:'/label',type:'string',label:'Label'},
+ {key:'detail',anchor:'can',property:'detail',path:'/detail',type:'string',label:'Small print'},
+ {key:'color',anchor:'can',property:'color',path:'/color',type:'color',label:'Can colour'},
+ {key:'distance',anchor:'can',property:'distance',path:'/distance',type:'number',min:1.5,max:8,label:'Distance from camera',animatable:true},
+ {key:'offset',anchor:'can',property:'offset',path:'/offset',type:'number',min:-2,max:2,label:'Left / right',animatable:true},
+ {key:'headline',anchor:'headline',property:'text',path:'/headline',type:'string',label:'Headline'},
+ {key:'price',anchor:'screen',property:'text',path:'/price',type:'string',label:'Screen text'},
+ {key:'plateLight',anchor:'light',property:'fromPlate',path:'/plateLight',type:'bool',label:'Light from the footage'},
+ ]},
+ async create({root,props,asset,mediaFrame,mediaInfo,derived}){
+ if(!asset||!mediaFrame||!mediaInfo||!derived)throw Error('This scene needs a host that serves plate media (asset, mediaFrame, mediaInfo, derived)');
+ const plate=mediaInfo('plate'),matteId=derived('plate','matte'),depthId=derived('plate','depth'),trackId=derived('plate','track');
+ if(!matteId||!depthId||!trackId)throw Error('The plate needs a matte, a depth map and a track; add them with asset-add --role … --of plate');
+ const encoding=mediaInfo(depthId).derived.encoding,track=await (await fetch(asset(trackId))).json();
+ const doc=root.ownerDocument,layer=(tag,css)=>{const node=doc.createElement(tag);node.style.cssText='position:absolute;left:0;top:0;'+css;stage.append(node);return node;};
+ const stage=doc.createElement('div');stage.style.cssText=`position:relative;width:${WIDTH}px;height:${HEIGHT}px;overflow:hidden`;root.append(stage);
+ const sized=canvas=>{canvas.width=WIDTH;canvas.height=HEIGHT;return canvas;};
+ const plateCanvas=sized(layer('canvas','')),plateContext=plateCanvas.getContext('2d',{willReadFrequently:true});
+ const screen=layer('div','width:160px;height:90px;transform-origin:0 0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#0b1220;color:#fff;font:700 34px/1 system-ui,sans-serif');
+ screen.dataset.efAnchor='screen';const priceText=doc.createElement('div'),priceNote=doc.createElement('div');priceNote.textContent='per can';priceNote.style.cssText='font:500 11px/1.6 system-ui,sans-serif;opacity:.75';screen.append(priceText,priceNote);
+ const headline=layer('div',`width:${WIDTH}px;top:296px;text-align:center;color:#fff;font:800 40px/1 system-ui,sans-serif;letter-spacing:-.01em`);headline.dataset.efAnchor='headline';
+ const cutCanvas=sized(layer('canvas','')),cutContext=cutCanvas.getContext('2d'),scratch=doc.createElement('canvas');
+ const glCanvas=layer('canvas',`width:${WIDTH}px;height:${HEIGHT}px`);
+
+ const renderer=new THREE.WebGLRenderer({canvas:glCanvas,alpha:true,antialias:true,preserveDrawingBuffer:true});
+ renderer.setPixelRatio(1);renderer.setSize(WIDTH,HEIGHT,false);renderer.setClearColor(0x000000,0);renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.NeutralToneMapping;
+ const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(35,WIDTH/HEIGHT,0.1,50);
+ const key=new THREE.DirectionalLight(0xffffff,2);scene.add(key,key.target);
+ const can=new THREE.Group();can.userData.passId='can.body';scene.add(can);
+ const labelCanvas=doc.createElement('canvas');labelCanvas.width=1024;labelCanvas.height=512;
+ const labelMap=new THREE.CanvasTexture(labelCanvas);labelMap.colorSpace=THREE.SRGBColorSpace;labelMap.anisotropy=8;
+ const body=new THREE.Mesh(new THREE.CylinderGeometry(.33,.33,1,96,1,true),new THREE.MeshStandardMaterial({map:labelMap,metalness:.25,roughness:.36}));
+ // Aluminium reflects about 91% of the light that reaches it; a darker base colour reads as grey metal.
+ const lidMaterial=new THREE.MeshStandardMaterial({color:0xf5f6f6,metalness:1,roughness:.22});
+ const lids=[.52,-.52].map(y=>{const lid=new THREE.Mesh(new THREE.CylinderGeometry(.3,.33,.04,96),lidMaterial);lid.position.y=y;lid.rotation.x=y<0?Math.PI:0;lid.userData.passId='can.lid';return lid;});
+ can.add(body,...lids);
+ const occluder=createDepthOccluder(encoding),depthMap=dataTexture(doc.createElement('canvas'));scene.add(occluder.mesh);
+ const plateEnvironment=createPlateEnvironment(renderer),pmrem=new THREE.PMREMGenerator(renderer),room=new RoomEnvironment(),neutral=pmrem.fromScene(room,.04);room.dispose();pmrem.dispose();
+ const frames=createFrameLoader(),probe=doc.createElement('canvas');probe.width=64;probe.height=36;const probeContext=probe.getContext('2d',{willReadFrequently:true});
+ let labelKey,litFrom;
+
+ function paintLabel(){
+ const next=[props.label,props.detail,props.color].join('\n');if(next===labelKey)return;labelKey=next;
+ const c=labelCanvas.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,1024,512);c.fillStyle='rgba(255,255,255,.14)';c.fillRect(0,96,1024,8);c.fillRect(0,408,1024,8);
+ // The label is text laid out by the browser, so it is the same crisp string in every frame and every variant.
+ c.fillStyle='#fff';c.textAlign='center';c.textBaseline='middle';
+ for(const x of [256,768]){c.font='900 150px system-ui,sans-serif';c.fillText(String(props.label),x,236);c.font='600 34px system-ui,sans-serif';c.fillText(String(props.detail),x,356);}
+ labelMap.needsUpdate=true;
+ }
+ return {
+ async render(clock){
+ const pass=clock.pass??'beauty',seconds=clock.frame/clock.fps;
+ // Anything locked to the footage moves on the footage's own frame grid.
+ const plateTime=conformSeconds(Math.min(clock.mediaTime??seconds,plate.duration-1e-6),plate.frameRate);
+ const [plateImage,matteImage,depthImage]=await Promise.all([plateTime,plateTime,plateTime].map((t,i)=>frames.load(mediaFrame(['plate',matteId,depthId][i],t))));
+ paintLabel();
+ can.position.set(props.offset,-.12,-props.distance);can.rotation.y=seconds*.9+.6;
+ if(pass!=='beauty'){stage.style.background='transparent';for(const node of [plateCanvas,screen,headline,cutCanvas])node.style.visibility='hidden';renderPass(renderer,scene,camera,pass,{ids:IDS,encoding});return;}
+ for(const node of [plateCanvas,screen,headline,cutCanvas])node.style.visibility='visible';
+ plateContext.drawImage(plateImage,0,0,WIDTH,HEIGHT);
+ const pin=sampleTrack(track,plateTime);screen.style.transform=cornerPinTransform(160,90,scalePoints(pin.quad,track,WIDTH,HEIGHT));priceText.textContent=String(props.price);
+ headline.textContent=String(props.headline);
+ drawCutout(cutContext,plateImage,matteImage,scratch);
+ depthMap.image=depthImage;depthMap.needsUpdate=true;occluder.update(depthMap,camera);
+ // Intensity 1: the environment's light is the plate's own pixel values, with no extra gain. On generated plates,
+ // aluminium lit this way was 5-6% brighter than a real can standing beside it, except where the light came from behind it.
+ if(props.plateLight){
+ if(litFrom!==plateImage){litFrom=plateImage;scene.environment=plateEnvironment.update(plateImage);scene.environmentIntensity=1;probeContext.drawImage(plateImage,0,0,64,36);applyKeyLight(key,estimateKeyLight(probeContext.getImageData(0,0,64,36).data,64,36),{target:can.position});}
+ }else{litFrom=null;scene.environment=neutral.texture;scene.environmentIntensity=1;key.position.set(2,4,3);key.target.position.copy(can.position);key.target.updateMatrixWorld();key.color.set(0xffffff);key.intensity=1.2;}
+ renderer.render(scene,camera);
+ },
+ pick({x,y}){const p=new THREE.Vector3().copy(can.position).project(camera);return Math.hypot(x-(p.x+1)/2*WIDTH,y-(1-p.y)/2*HEIGHT)<70?{anchor:'can',property:'label'}:null;},
+ dispose(){frames.dispose();occluder.dispose();depthMap.dispose();plateEnvironment.dispose();neutral.dispose();labelMap.dispose();body.geometry.dispose();body.material.dispose();for(const lid of lids)lid.geometry.dispose();lidMaterial.dispose();renderer.dispose();renderer.forceContextLoss?.();stage.remove();},
+ };
+ }
+});
diff --git a/templates/media/clip.mjs b/templates/media/clip.mjs
index 8172d45..7fb3e53 100644
--- a/templates/media/clip.mjs
+++ b/templates/media/clip.mjs
@@ -2,12 +2,12 @@ export const template={id:'media-explainer',title:'Signals / editable media stud
nodes:[{id:'design',type:'design',label:'Art direction',props:{headline:'THE SIGNAL IS MOVING',accent:'#9ceaac',transparent:true},keys:{}},{id:'presenter',type:'media',label:'Embedded video + audio',props:{asset:'demo',gain:.3,muted:false,sourceIn:0,rate:1,offset:0,end:'hold',size:150},keys:{}}],
schemas:{design:{headline:{type:'text',maxLength:50,label:'Headline'},accent:{type:'color',label:'Accent'},transparent:{type:'boolean',label:'Transparent background'}},media:{asset:{type:'text',maxLength:80,label:'Asset ID'},gain:{type:'number',min:0,max:1,label:'Voice volume',keyframe:false},muted:{type:'boolean',label:'Mute voice'},sourceIn:{type:'number',min:0,max:3,label:'Video in point',keyframe:false},rate:{type:'number',min:.5,max:2,label:'Video speed',keyframe:false},offset:{type:'number',min:0,max:3,label:'Start delay',keyframe:false},end:{type:'enum',values:['hold','loop','transparent'],label:'After video ends'},size:{type:'number',min:80,max:190,label:'Video size'}}},
media:{presenter:{anchor:'presenter',bindings:{asset:'asset',gain:'gain',muted:'muted',sourceIn:'sourceIn',rate:'rate',offset:'offset',end:'end'}}}};
-export function createRenderer(canvas){canvas.width=960;canvas.height=540;const c=canvas.getContext('2d',{alpha:true});return {async render({time,nodes,ports,host}){
+export function createRenderer(canvas){canvas.width=960;canvas.height=540;const c=canvas.getContext('2d',{alpha:true});return {async render({time,mediaTime=time,nodes,ports,host}){
const p=nodes.find(n=>n.id==='design').props,m=nodes.find(n=>n.id==='presenter').props;c.clearRect(0,0,960,540);
if(!p.transparent){c.fillStyle='#12252d';c.fillRect(0,0,960,540)}
c.fillStyle='#18333fe6';c.beginPath();c.roundRect(32,32,896,476,28);c.fill();c.fillStyle=p.accent;c.font='12px sans-serif';c.fillText('EDITABLEFRAMES / VIDEO + AUDIO + ALPHA',64, 70);c.fillStyle='#f3f7ee';c.font='bold 32px sans-serif';c.fillText(p.headline,64,124);
c.strokeStyle='#365461';c.lineWidth=1;for(let i=0;i<4;i++){c.beginPath();c.moveTo(64,210+i*65);c.lineTo(570,210+i*65);c.stroke()}
c.strokeStyle=p.accent;c.lineWidth=4;c.beginPath();for(let i=0;i<110;i++){const x=64+i*4.6,y=385-i*1.6-Math.sin(i*.16-time*1.7)*28;i?c.lineTo(x,y):c.moveTo(x,y)}c.stroke();
- const frame=await host.portFrame(ports.presenter,time);if(frame){c.save();c.beginPath();c.arc(744,296,m.size,0,Math.PI*2);c.clip();c.drawImage(frame,744-m.size,296-m.size,m.size*2,m.size*2);c.restore()}
+ const frame=await host.portFrame(ports.presenter,mediaTime);if(frame){c.save();c.beginPath();c.arc(744,296,m.size,0,Math.PI*2);c.clip();c.drawImage(frame,744-m.size,296-m.size,m.size*2,m.size*2);c.restore()}
c.fillStyle='#d1dfde';c.font='14px sans-serif';c.fillText('Original test footage • replace Asset ID with your presenter',64,471);c.fillStyle=p.accent;c.fillText(time.toFixed(2)+' s',828,471);return canvas;
},dispose(){}}}
diff --git a/tests/audio-integration.mjs b/tests/audio-integration.mjs
new file mode 100644
index 0000000..b7cd471
--- /dev/null
+++ b/tests/audio-integration.mjs
@@ -0,0 +1,23 @@
+// Real PCM regression: a 1x take must not pass through a time-stretch algorithm.
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';
+import {mixAudio} from '../scripts/audio.mjs';import {run,ffmpeg} from '../scripts/process.mjs';
+import {normalizeClipModule} from '../packages/core/definition.mjs';import {defineRenderer} from '../packages/core/renderer.mjs';
+import {Studio,clone,ticks} from '../packages/core/index.mjs';
+const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-audio-test-'));
+try{
+ const rate=48000,n=rate,pcm=Buffer.alloc(n*4);let seed=123456;
+ for(let i=0;i>>0;const v=Math.round((seed/2**32-.5)*12000);pcm.writeInt16LE(v,i*4);pcm.writeInt16LE(-v,i*4+2);}
+ const raw=path.join(tmp,'input.pcm'),wav=path.join(tmp,'input.wav');await fs.writeFile(raw,pcm);
+ await run(ffmpeg(),['-v','error','-n','-f','s16le','-ar',String(rate),'-ac','2','-i',raw,'-c:a','pcm_s16le',wav]);
+ const {template}=normalizeClipModule({default:defineRenderer({id:'audio-regression',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,media:{take:{asset:'source',offset:.25,sourceIn:.125}},create(){return {render(){}}}})});
+ const studio=new Studio({[template.id]:template},{binding:'test'});studio.doc.clips=[studio.make(template.id)];studio.base=clone(studio.doc);
+ // Clip trim moves the port from .25 to .125 seconds; source still begins at .125.
+ studio.execute({type:'timing',clip:studio.doc.clips[0].id,sourceIn:ticks(.125),duration:ticks(.75)});
+ const output=path.join(tmp,'mix.wav');const receipt=await mixAudio({studio,assets:{source:{file:wav}}},{source:{audio:true,duration:1}},output,.75);assert.equal(receipt.tracks,1);
+ const actual=await run(ffmpeg(),['-v','error','-i',output,'-f','s16le','-ac','2','-ar',String(rate),'-']);assert.equal(actual.length,.75*rate*4);
+ const delay=.125*rate,source=.125*rate;let maxError=0;
+ for(let i=0;i{
+ assert.deepEqual(chromiumOptions({}),{});
+ assert.deepEqual(chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:''}),{});
+});
+test('configured browser preserves an existing absolute path including spaces',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'ef-browser-'));
+ try {const file=path.join(dir,'Browser With Spaces');fs.writeFileSync(file,'fixture only');assert.deepEqual(chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:file}),{executablePath:file});}
+ finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('bad explicit configuration is rejected rather than silently falling back',()=>{
+ assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:'relative/chrome'}),/absolute/);
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'ef-browser-'));
+ try {assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:dir}),/file/);assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:path.join(dir,'missing')}),/existing/);}
+ finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
diff --git a/tests/cancellation.test.mjs b/tests/cancellation.test.mjs
new file mode 100644
index 0000000..2625e4c
--- /dev/null
+++ b/tests/cancellation.test.mjs
@@ -0,0 +1,48 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import {spawn} from 'node:child_process';
+import {init,mutate} from '../scripts/project.mjs';
+import {recoverJobs} from '../scripts/jobs.mjs';
+const cli=path.resolve(import.meta.dirname,'../bin/editableframes.mjs');
+const exists=p=>fs.lstat(p).then(()=>true,()=>false);
+const sleep=ms=>new Promise(r=>setTimeout(r,ms));
+
+// A decoder stand-in deliberately waits at the strict-decode boundary. No production fault hook.
+// The real CLI must abort its child, wait for its exit, remove staging and release the edit lock.
+for(const [signal,exitCode] of [['SIGINT',130],['SIGTERM',143],['SIGHUP',129]]){
+ test(`asset-add ${signal} cancels decode and leaves the project editable`,{skip:process.platform==='win32',timeout:20000},async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-cancel-')),dir=path.join(tmp,'project'),marker=path.join(tmp,'decoder.json');let child,done;
+ try{
+ await init(dir);const before=await fs.readFile(path.join(dir,'project.json'),'utf8');
+ const decoder=path.join(tmp,'decoder');await fs.writeFile(decoder,"#!/usr/bin/env node\nimport('node:fs').then(fs=>{fs.writeFileSync(process.env.EF_TEST_MARKER,JSON.stringify({pid:process.pid,args:process.argv.slice(2)}));setInterval(()=>{},1000)});\n",{mode:0o700});
+ const input=path.join(tmp,'candidate.mp4');await fs.writeFile(input,'fixture bytes; decoder deliberately waits');
+ child=spawn(process.execPath,[cli,'asset-add',dir,'cancelled',input],{env:{...process.env,PATH:path.dirname(process.execPath)+path.delimiter+process.env.PATH,FFMPEG_PATH:decoder,EF_TEST_MARKER:marker},stdio:['ignore','pipe','pipe']});
+ let stderr='';child.stderr.on('data',b=>stderr+=b);done=new Promise(resolve=>child.once('close',(code,signal)=>resolve({code,signal})));
+ const deadline=Date.now()+10000;while(!await exists(marker)&&Date.now()n.startsWith('.import-')),[]);
+ assert.equal(await fs.readFile(path.join(dir,'project.json'),'utf8'),before);
+ assert.equal(await exists(path.join(dir,'assets.json')),false);
+ assert.throws(()=>process.kill(decoderInfo.pid,0),e=>e.code==='ESRCH');
+ await mutate(dir,()=>{});
+ }finally{if(child&&child.exitCode===null&&child.signalCode===null){child.kill('SIGTERM');await done}await fs.rm(tmp,{recursive:true,force:true})}
+ });
+}
+
+test('recover dry run does not create or mutate the registry',{timeout:10000},async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-dry-run-')),state=path.join(tmp,'state'),saved=process.env.EDITABLEFRAMES_STATE_DIR;
+ try{
+ process.env.EDITABLEFRAMES_STATE_DIR=state;
+ assert.deepEqual(await recoverJobs(tmp,{dryRun:true}),[]);assert.equal(await exists(state),false);
+ await fs.mkdir(path.join(state,'jobs'),{recursive:true,mode:0o700});
+ const id='00000000-0000-0000-0000-000000000001',record=JSON.stringify({id,project:await fs.realpath(tmp),owner:null});
+ await fs.writeFile(path.join(state,'jobs',id+'.json'),record);
+ const report=await recoverJobs(tmp,{dryRun:true});assert.equal(report.length,1);assert.equal(await exists(path.join(state,'locks')),false);
+ assert.equal(await fs.readFile(path.join(state,'jobs',id+'.json'),'utf8'),record);
+ }finally{if(saved===undefined)delete process.env.EDITABLEFRAMES_STATE_DIR;else process.env.EDITABLEFRAMES_STATE_DIR=saved;await fs.rm(tmp,{recursive:true,force:true})}
+});
diff --git a/tests/cli.test.mjs b/tests/cli.test.mjs
index 33156b2..b841842 100644
--- a/tests/cli.test.mjs
+++ b/tests/cli.test.mjs
@@ -12,7 +12,7 @@ test('portable CLI starter and exact public documentation compile outside the ch
const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-portable-cli-')),dir=path.join(tmp,'scene');
try{
cli('init',dir,'--renderer');const c=cli('inspect',dir);assert.equal(c.anchors[0].id,'orb');assert.equal(c.anchors[0].values.color,'#38bdf8');
- const guide=await fs.readFile(path.join(root,'docs/renderer-contract.md'),'utf8');assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/renderer.md'),'utf8'),guide);
+ const guide=await fs.readFile(path.join(root,'docs/renderer-contract.md'),'utf8');assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/renderer.md'),'utf8'),guide);/* The skill copy drops the pictures, whose relative links would not resolve from the skill folder. */assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/hybrid.md'),'utf8'),(await fs.readFile(path.join(root,'docs/hybrid-scenes.md'),'utf8')).replace(/\n!\[[^\n]*\]\(media\/[^\n]*\)\n\n\*[^\n]*\*\n/g,''));
const code=guide.match(/```js\n([\s\S]*?)```/)[1];await fs.writeFile(path.join(dir,'clip.mjs'),code);cli('rebind',dir,'--reset');assert.deepEqual(cli('inspect',dir).anchors,[]);
const {readProject}=await import('../scripts/project.mjs');const d=await readProject(dir);assert.equal(d.kind,'renderer');assert.deepEqual(d.studio.doc.fps,{num:30,den:1});assert.equal(d.studio.doc.width,640);
}finally{await fs.rm(tmp,{recursive:true,force:true})}
diff --git a/tests/hybrid-editing.mjs b/tests/hybrid-editing.mjs
new file mode 100644
index 0000000..313a7b2
--- /dev/null
+++ b/tests/hybrid-editing.mjs
@@ -0,0 +1,40 @@
+// Live instances must render edits exactly as newly mounted capture instances.
+import assert from 'node:assert/strict';
+import {build} from 'esbuild';
+import {chromium} from 'playwright';
+const {outputFiles}=await build({stdin:{contents:`
+ import product from './examples/hybrid-code-first/clip.mjs';
+ import surface from './examples/hybrid-surfaces/clip.mjs';
+ import {mountRenderer} from './packages/runtime/renderer-host.mjs';
+ import * as T from 'three';
+ import {GLTFExporter} from 'three/examples/jsm/exporters/GLTFExporter.js';
+ window.proof={product,surface,mountRenderer,T,GLTFExporter};`,resolveDir:new URL('..',import.meta.url).pathname},bundle:true,write:false,format:'iife'});
+const browser=await chromium.launch({headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']});
+try{
+ const page=await browser.newPage();await page.setContent('');await page.addScriptTag({content:outputFiles[0].text});
+ const result=await page.evaluate(async()=>{
+ const {product,surface,mountRenderer,T,GLTFExporter}=window.proof,clock={frame:16,fps:16,width:832,height:480,pass:'beauty'};
+ const urls=[];
+ for(const color of [0x2255ff,0xffcc22]){const mesh=new T.Mesh(new T.BoxGeometry(.7,1,.5),new T.MeshStandardMaterial({color}));const bytes=await new GLTFExporter().parseAsync(mesh,{binary:true});urls.push(URL.createObjectURL(new Blob([bytes])));mesh.geometry.dispose();mesh.material.dispose();}
+ const root=document.querySelector('#live'),services={asset:id=>urls[Number(id)]};
+ const live=await mountRenderer(product,{root,props:{backplate:false},services});
+ const pixels=node=>node.querySelector('canvas').toDataURL();const states=[];
+ for(const values of [{label:'FIRST',model:''},{label:'SECOND',model:''},{label:'SECOND',model:'0'},{label:'SECOND',model:'1'},{label:'FIRST',model:''}]){
+ const props={...values,backplate:false};await live.render(clock,props);const shown=pixels(root);
+ const freshRoot=document.querySelector('#fresh'),fresh=await mountRenderer(product,{root:freshRoot,props,services});await fresh.render(clock);
+ states.push({same:shown===pixels(freshRoot),pixels:shown});await fresh.dispose();
+ }
+ await live.dispose();urls.forEach(url=>URL.revokeObjectURL(url));
+ const source={asset:'plate',sha256:'a'.repeat(64),width:100,height:80,frames:8,frameRate:{num:24,den:1},pts:[0,.042,.083,.125,.167,.208,.25,.292],orientation:0,crop:[0,0,100,80]};
+ const prepared={version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source,alpha:{asset:'mask',sha256:'b'.repeat(64),channel:'alpha',semantics:'alpha'},provenance:{method:'test',preprocess:'test/1'},frames:source.pts.map((_,i)=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))};
+ const track={version:1,kind:'planar',sourceSha256:source.sha256,width:100,height:80,frameRate:source.frameRate,frames:source.pts.map((_,frame)=>({frame,quad:[[10,10],[30,10],[30,70],[10,70]],confidence:1}))};
+ const canvas=document.createElement('canvas');canvas.width=100;canvas.height=80;const empty=canvas.toDataURL(),ctx=canvas.getContext('2d');ctx.fillStyle='#aaa';ctx.fillRect(0,0,100,80);const original=canvas.toDataURL();
+ root.style.cssText='position:relative;width:100px;height:80px';
+ const props={...surface.defaultProps,prepared,track,foregroundSource:'plate',foregroundMask:'mask',headline:''};
+ const instance=await surface.create({root,props,sourceFrame:id=>id==='plate'?original:empty});
+ for(const frame of [0,9,1,9])await instance.render({frame,fps:30,width:100,height:80});await instance.dispose();
+ return {freshParity:states.every(s=>s.same),labelChanged:states[0].pixels!==states[1].pixels,modelChanged:states[2].pixels!==states[3].pixels,undoRestored:states[0].pixels===states[4].pixels,reskinLastFrame:true};
+ });
+ assert.deepEqual(result,{freshParity:true,labelChanged:true,modelChanged:true,undoRestored:true,reskinLastFrame:true});
+ console.log('PASS: live label/model edits and Undo match fresh renders; quantized final-frame reskin renders after reverse seeks.');
+}finally{await browser.close();}
diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs
new file mode 100644
index 0000000..76b2a22
--- /dev/null
+++ b/tests/hybrid-integration.mjs
@@ -0,0 +1,168 @@
+// Real pixels through the real CLI: a code-rendered product inside footage.
+// The plate is synthetic so every assertion below has a known answer.
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';
+import {init,readProject,mutate,rebind,importAsset} from '../scripts/project.mjs';
+import {render} from '../scripts/render.mjs';import {run,ffmpeg} from '../scripts/process.mjs';
+import {HYBRID_DEMO as demo} from '../scripts/demo-hybrid.mjs';
+import {idFromColor,encodeDepth} from '../packages/plate/index.mjs';
+
+const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-hybrid-')),dir=path.join(tmp,'film'),checks=[];
+const W=demo.width,H=demo.height,hex=value=>[1,3,5].map(i=>parseInt(value.replace('0x','#').slice(i,i+2),16));
+const WALL=hex(demo.colors.wall),BAR=hex(demo.colors.bar),BOARD=hex(demo.colors.board),SCREEN=[11,18,32];
+async function pixels(file){const data=await run(ffmpeg(),['-v','error','-i',file,'-pix_fmt','rgba','-f','rawvideo','-'],{maxOutput:64*1024**2});assert.equal(data.length,W*H*4);return {at:(x,y)=>[...data.subarray((y*W+x)*4,(y*W+x)*4+4)],data};}
+const close=(actual,expected,tolerance=8)=>expected.every((v,i)=>Math.abs(actual[i]-v)<=tolerance);
+const frameFile=(folder,frame)=>path.join(folder,String(frame+1).padStart(6,'0')+'.png');
+const mean=(image,x0,y0,x1,y1)=>{const sum=[0,0,0];let n=0;for(let y=y0;yv/n)};
+try{
+ await init(dir,{template:'hybrid'});
+ const project=await readProject(dir);assert.deepEqual(project.scene.passes,['clay','depth','normal','id','matte']);assert.deepEqual(project.studio.doc.fps,{num:24,den:1});
+
+ // --- Beauty: occlusion, layering and tracking --------------------------------
+ const beauty=path.join(tmp,'beauty');await render(dir,beauty,{format:'png',frames:40});
+ const early=6,late=35,barAt=frame=>demo.bar.x(frame),boardAt=frame=>demo.board.x(frame);
+ const a=await pixels(frameFile(beauty,early)),b=await pixels(frameFile(beauty,late));
+ // --- An MP4 keeps the levels the browser drew ---------------------------------
+ // Decoded with the matrix and range it declares, an MP4 of the starter must give the PNG frame's values: the
+ // footage in a hybrid shot is not re-graded on the way out. Converting to the BT.709 camera curve made it
+ // 10-13 levels darker (128 -> 115), which no player undoes.
+ const movie=path.join(tmp,'movie.mp4');await render(dir,movie,{format:'mp4',frames:early+1});
+ const decoded=await run(ffmpeg(),['-v','error','-i',movie,'-vf',`select=eq(n\\,${early}),scale=in_range=tv:out_range=pc:in_color_matrix=bt709,format=rgba`,'-frames:v','1','-f','rawvideo','-'],{maxOutput:64*1024**2});
+ assert.equal(decoded.length,W*H*4);
+ const shown={at:(x,y)=>[...decoded.subarray((y*W+x)*4,(y*W+x)*4+4)]};
+ const drawn=mean(a,0,0,W,H),encoded=mean(shown,0,0,W,H);
+ assert.ok(drawn.every((v,i)=>Math.abs(encoded[i]-v)<=2),`MP4 levels ${encoded.map(Math.round)} differ from the drawn frame's ${drawn.map(Math.round)}`);
+ checks.push('An MP4 export keeps the levels of the drawn frames');
+ // An opaque scene's frames have no alpha channel; the MOV (ProRes 4444) path extracted alpha from them and failed.
+ const prores=path.join(tmp,'movie.mov');await render(dir,prores,{format:'mov',frames:early+1});
+ const proresFrame=await run(ffmpeg(),['-v','error','-i',prores,'-vf',`select=eq(n\\,${early}),scale=in_range=tv:out_range=pc:in_color_matrix=bt709,format=rgba`,'-frames:v','1','-f','rawvideo','-'],{maxOutput:64*1024**2});
+ assert.equal(proresFrame.length,W*H*4);
+ const proresShown={at:(x,y)=>[...proresFrame.subarray((y*W+x)*4,(y*W+x)*4+4)]},proresLevels=mean(proresShown,0,0,W,H);
+ assert.ok(drawn.every((v,i)=>Math.abs(proresLevels[i]-v)<=2),`MOV levels ${proresLevels.map(Math.round)} differ from the drawn frame's ${drawn.map(Math.round)}`);
+ assert.equal(proresShown.at(W>>1,H>>1)[3],255,'an opaque scene stays opaque');
+ checks.push('An opaque scene exports to MOV, at the levels of the drawn frames');
+ // Frame 6: the bar is far left; the product is in the clear.
+ assert.ok(barAt(early)+demo.bar.width<250);
+ // Label samples sit on rows 112-140: plain label above its text. The text is laid out with the platform's font, and
+ // white text lit by a warm plate has the plate's own colour, so a sample that lands on a letter proves nothing.
+ const can=a.at(300,125);assert.ok(!close(can,WALL,30)&&!close(can,BAR,30),'the product is drawn over the wall');assert.ok(can[0]>can[2]*2,'and it is the red can');
+ // Frame 35: the bar stands in front of the product's centre, and ONLY the plate's depth says so.
+ assert.ok(barAt(late)<320&&barAt(late)+demo.bar.width>320);
+ assert.ok(close(b.at(320,170),BAR),'the plate foreground hides the product where it is nearer');
+ const beside=b.at(barAt(late)+demo.bar.width+12,125);assert.ok(!close(beside,WALL,30)&&!close(beside,BAR,30),'the product is still visible beside the foreground');
+ checks.push('A 3D object is hidden by plate foreground and shown over plate background, from the depth map alone');
+
+ // The headline is DOM text; the cut-out layer puts the plate subject back over it.
+ const white=(image,x0,x1)=>{let n=0;for(let y=296;y<340;y++)for(let x=x0;x235&&p[1]>235&&p[2]>235)n++}return n};
+ assert.ok(white(a,200,440)>400,'the headline is drawn');
+ assert.equal(white(b,barAt(late)+2,barAt(late)+demo.bar.width-2),0,'no headline pixel survives in front of the bar');
+ assert.ok(white(b,200,barAt(late))>50&&white(b,barAt(late)+demo.bar.width,440)>50,'and it continues on both sides');
+ checks.push('DOM text passes behind the matted plate subject');
+
+ // The screen is a DOM element pinned to the tracked board, which moves 14px between these frames.
+ assert.equal(boardAt(late)-boardAt(early),14);
+ for(const [image,frame]of [[a,early],[b,late]]){const x=boardAt(frame);
+ assert.ok(close(image.at(x+4,demo.board.y+4),SCREEN),'screen covers the board corner');assert.ok(close(image.at(x+demo.board.width-4,demo.board.y+demo.board.height-4),SCREEN),'and its far corner');
+ assert.ok(close(image.at(x-4,demo.board.y+4),WALL),'and stops at the board edge');assert.ok(!close(image.at(x+4,demo.board.y+4),BOARD,6));}
+ checks.push('A DOM screen stays corner-pinned to a tracked surface as it moves');
+
+ // --- Lighting from the plate --------------------------------------------------
+ // The plate's only bright area is a window on the left, so the can's left side is the lit one.
+ const lit=mean(a,262,112,300,140),shade=mean(a,345,112,380,140);assert.ok(lit[0]>shade[0]*1.2,'the side facing the bright window is brighter');
+ // The panorama's back half is the plate mirrored, so the side turned away still sees footage, not black.
+ assert.ok(shade[0]>90,`the shaded side reflects the footage behind the camera, not an empty half (${Math.round(shade[0])})`);
+ await mutate(dir,d=>d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model'));
+ const neutralDir=path.join(tmp,'neutral');await render(dir,neutralDir,{format:'png',frames:early+1});const n=await pixels(frameFile(neutralDir,early));
+ const warm=rgb=>rgb[0]/(rgb[2]+1),plateLit=mean(a,262,112,380,140),studioLit=mean(n,262,112,380,140);
+ assert.ok(Math.abs(plateLit[0]-studioLit[0])+Math.abs(plateLit[1]-studioLit[1])+Math.abs(plateLit[2]-studioLit[2])>12,'turning plate lighting off changes the product');
+ assert.ok(warm(plateLit)>warm(studioLit),'under the warm plate the product reads warmer than under neutral studio light');
+ assert.ok(close(n.at(20,340),a.at(20,340),2),'the footage itself is untouched by the lighting control');
+ await mutate(dir,d=>d.studio.undo());
+ checks.push('The product is lit by the footage: direction follows the bright area, colour follows the plate, and it is an undoable control');
+
+ // --- Control passes ------------------------------------------------------------
+ const pass=async(name,folder=name)=>{const out=path.join(tmp,folder);const receipt=await render(dir,out,{format:'png',frames:1,pass:name});assert.equal(receipt.pass,name);return pixels(frameFile(out,0));};
+ const id=await pass('id');assert.equal(id.at(5,5)[3],0,'no plate, no DOM: the pass is transparent outside the object');
+ assert.equal(idFromColor(id.at(320,200)),0,'the body decodes to the first declared id');
+ let lid=false;for(let y=80;y<140&&!lid;y++)lid=id.at(320,y)[3]===255&&idFromColor(id.at(320,y))===1;assert.ok(lid,'the lid decodes to the second');
+ const depth=await pass('depth'),front=3-.33,expected=Math.round(encodeDepth(front,demo.depth)*255);
+ assert.ok(Math.abs(depth.at(320,200)[0]-expected)<=3,`depth pass encodes the nearest surface (${depth.at(320,200)[0]} vs ${expected})`);assert.ok(depth.at(320,200)[0]>depth.at(262,200)[0],'and falls off toward the silhouette');
+ const matte=await pass('matte');assert.deepEqual(matte.at(320,200),[255,255,255,255]);assert.equal(matte.at(5,5)[3],0);
+ // Nothing but the object: the capture page's own chrome must not show through a transparent frame.
+ let stray=0;for(let y=0;y410||y<70))stray++;assert.equal(stray,0,'a transparent pass contains only the scene');
+ const normal=await pass('normal');assert.ok(normal.at(320,200)[2]>200&&Math.abs(normal.at(320,200)[0]-128)<25,'the surface facing the camera has a camera-facing normal');
+ const clay=await pass('clay'),grey=clay.at(300,200),spread=p=>Math.max(...p.slice(0,3))-Math.min(...p.slice(0,3));assert.equal(grey[3],255);assert.ok(!close(grey,can,25)&&spread(grey)d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model'));
+ const studioClay=(await pass('clay','clay-neutral')).at(300,200);await mutate(dir,d=>d.studio.undo());
+ assert.ok(spread(studioClay)<16,`under neutral light clay is neutral grey (${studioClay.slice(0,3)})`);
+ await assert.rejects(render(dir,path.join(tmp,'albedo'),{format:'png',frames:1,pass:'albedo'}),/does not declare a albedo pass; it declares: clay/);
+ checks.push('clay, depth, normal, id and matte passes export from the same scene; an undeclared pass is refused');
+
+ // --- Derived data is pinned to its take ---------------------------------------
+ const short=path.join(tmp,'short.mp4');await run(ffmpeg(),['-v','error','-f','lavfi','-i',`color=c=gray:s=${W}x${H}:r=24:d=1`,'-c:v','libx264','-qp','0','-pix_fmt','yuv444p',short]);
+ await importAsset(dir,'plate-normals',short,{role:'normals',of:'plate'});await rebind(dir);
+ await assert.rejects(render(dir,path.join(tmp,'mismatch'),{format:'png',frames:1}),/plate-normals has 24 frames but plate has 72/);
+ await assert.rejects(importAsset(dir,'second-matte',short,{role:'matte',of:'plate'}),/two matte/);
+ const manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'));manifest.assets['plate-matte'].derived.sourceSha256='0'.repeat(64);await fs.writeFile(path.join(dir,'assets.json'),JSON.stringify(manifest));
+ await assert.rejects(readProject(dir),/regenerate the matte/);
+ checks.push('A matte from another take, a second matte, and a derived video with the wrong frame count are refused');
+ // The documented import sequence: several asset-add calls, then one rebind.
+ const seqDir=path.join(tmp,'sequence');await init(seqDir,{template:'hybrid'});const demoAsset=name=>path.join(seqDir,'assets',name);
+ await importAsset(seqDir,'shot',demoAsset('plate.mp4'));
+ await importAsset(seqDir,'shot-matte',demoAsset('plate-matte.mp4'),{role:'matte',of:'shot'});
+ await importAsset(seqDir,'shot-depth',demoAsset('plate-depth.mp4'),{role:'depth',of:'shot',encoding:demo.depth});
+ await importAsset(seqDir,'shot-track',demoAsset('board-track.json'),{role:'track',of:'shot'});
+ await rebind(seqDir);const seq=await readProject(seqDir);
+ assert.deepEqual(['shot-matte','shot-depth','shot-track'].map(id=>seq.assets[id].derived.of),['shot','shot','shot']);
+ checks.push('Several derived assets can be added before one rebind, as docs/hybrid-scenes.md shows');
+
+ // --- Motion blur ------------------------------------------------------------------
+ // The bundled hybrid scene must freeze its footage and attached pin too.
+ const hybridSoft=path.join(tmp,'hybrid-shutter');
+ await render(seqDir,hybridSoft,{format:'png',frames:3,motionBlur:{angle:180,samples:8}});
+ const hybridSharp=await pixels(frameFile(beauty,2)),hybridBlurred=await pixels(frameFile(hybridSoft,2));
+ assert.ok(hybridSharp.data.subarray(10*W*4,11*W*4).equals(hybridBlurred.data.subarray(10*W*4,11*W*4)),'the moving foreground stays on one footage frame');
+ for(let y=50;y<140;y++)assert.ok(hybridSharp.data.subarray((y*W+430)*4,(y*W+620)*4).equals(hybridBlurred.data.subarray((y*W+430)*4,(y*W+620)*4)),'the screen pin stays locked to the fixed plate');
+ checks.push('The hybrid starter keeps footage and its tracked card fixed during shutter sampling');
+ const blurDir=path.join(tmp,'blur-clip');await init(blurDir,{template:'renderer'});
+ await fs.writeFile(path.join(blurDir,'clip.mjs'),`import {defineRenderer} from 'editableframes/renderer';export default defineRenderer({id:'mover',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,async create({root}){const box=document.createElement('div');box.style.cssText='position:absolute;top:30px;width:30px;height:30px;background:#00ff00';root.append(box);return {render(clock){box.style.left=(clock.frame*20)+'px';},dispose(){box.remove();}};}});`);
+ await rebind(blurDir,{reset:true});
+ const sharpDir=path.join(tmp,'sharp'),softDir=path.join(tmp,'soft');await render(blurDir,sharpDir,{format:'png',frames:4});
+ const receipt=await render(blurDir,softDir,{format:'png',frames:4,motionBlur:{angle:180,samples:8}});assert.deepEqual(receipt.motionBlur,{samples:8,angle:180,phase:'centered'});assert.equal((await fs.readdir(softDir)).length,4);
+ const row=async file=>{const data=await run(ffmpeg(),['-v','error','-i',file,'-pix_fmt','rgba','-f','rawvideo','-']);return Array.from({length:160},(_,x)=>[...data.subarray((45*160+x)*4,(45*160+x)*4+4)]);};
+ const sharp=await row(frameFile(sharpDir,2)),soft=await row(frameFile(softDir,2));
+ assert.ok(sharp.every(p=>p[3]===0||p[3]===255),'without a shutter every pixel is fully on or off');
+ const partial=soft.filter(p=>p[3]>8&&p[3]<247);assert.ok(partial.length>=8,'the shutter leaves partly covered pixels along the direction of travel');
+ // The shutter is open over 1.75..2.25 frames at 20px per frame. Eight samples sit at the middle of
+ // eight equal slices, so the first and last are 8.75px apart: 4px of smear on each side of the square.
+ assert.equal(soft.filter(p=>p[3]>0).length-sharp.filter(p=>p[3]>0).length,8);
+ assert.ok(partial.every(p=>p[1]>=245&&p[0]<=10&&p[2]<=10),'a half-covered pixel keeps the pure colour: samples are averaged premultiplied');
+ checks.push('Shutter motion blur averages sub-frame samples with correct edge colour');
+
+ // A real moving plate stays on its output frame, while code still smears.
+ // Use the same fixture at a tiny angle too: previously any positive angle
+ // mixed the previous/current plate 50/50, regardless of the shutter width.
+ const plateFile=path.join(tmp,'moving-plate.mp4');
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=160x90:rate=24:duration=1','-c:v','libx264','-qp','0',plateFile]);
+ await importAsset(blurDir,'moving-plate',plateFile);
+ await fs.writeFile(path.join(blurDir,'clip.mjs'),`import {defineRenderer} from 'editableframes/renderer';
+ import {createFrameLoader} from 'editableframes/plate';
+ export default defineRenderer({id:'mover',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,async create({root,mediaFrame}){
+ const canvas=document.createElement('canvas');canvas.width=160;canvas.height=90;root.append(canvas);const ctx=canvas.getContext('2d'),loader=createFrameLoader();
+ const box=document.createElement('div');box.style.cssText='position:absolute;top:30px;width:30px;height:30px;background:#00ff00';root.append(box);
+ return {async render(clock){ctx.drawImage(await loader.load(mediaFrame('moving-plate',clock.mediaTime)),0,0);box.style.left=(clock.frame*20)+'px';},dispose(){loader.dispose();canvas.remove();box.remove();}};}});`);
+ await rebind(blurDir,{reset:true});
+ const footageSharp=path.join(tmp,'footage-sharp');await render(blurDir,footageSharp,{format:'png',frames:4});
+ const decode=folder=>run(ffmpeg(),['-v','error','-i',frameFile(folder,2),'-pix_fmt','rgba','-f','rawvideo','-']);
+ const sharpPixels=await decode(footageSharp);
+ for(const angle of [180,1]){
+ const folder=path.join(tmp,'footage-blur-'+angle);await render(blurDir,folder,{format:'png',frames:4,motionBlur:{angle,samples:8}});
+ const blurred=await decode(folder);
+ // Every pixel outside the code's rows must be byte-identical to the sharp export.
+ for(let y=0;y<90;y++)if(y<30||y>=60)assert.ok(blurred.subarray(y*160*4,(y+1)*160*4).equals(sharpPixels.subarray(y*160*4,(y+1)*160*4)),`footage changed at row ${y}, shutter ${angle}`);
+ if(angle===180)assert.ok(!blurred.subarray(40*160*4,50*160*4).equals(sharpPixels.subarray(40*160*4,50*160*4)),'code still blurs over the fixed plate');
+ }
+ checks.push('Shutter samples hold actual footage fixed while code blurs');
+ console.log(JSON.stringify({checks},null,2));
+}finally{await fs.rm(tmp,{recursive:true,force:true});}
diff --git a/tests/hybrid-prepared.test.mjs b/tests/hybrid-prepared.test.mjs
new file mode 100644
index 0000000..d185485
--- /dev/null
+++ b/tests/hybrid-prepared.test.mjs
@@ -0,0 +1,88 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {validatePreparedAnalysis,preparedFrame,sampleTrackFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion,createMaskCorrectionSession,rasterizeSurface,validateDerived,pendingMaskCorrections} from '../packages/plate/index.mjs';
+const hash='a'.repeat(64),maskHash='b'.repeat(64);
+const receipt=()=>({version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source:{asset:'plate',sha256:hash,width:100,height:80,frames:3,frameRate:{num:24,den:1},pts:[0,1/24,2/24],orientation:0,crop:[0,0,100,80]},alpha:{asset:'mask',sha256:maskHash,channel:'luminance',semantics:'segmentation'},provenance:{method:'manual','preprocess':'test/1'},frames:[0,1,2].map(i=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))});
+test('quantized container times retain exact tracked corners through trim and reverse',()=>{
+ const r=receipt();r.source.pts=[0,.042,.083];
+ const track={kind:'planar',frameRate:r.source.frameRate,frames:[0,1,2].map(frame=>({frame,quad:[[frame,0],[frame+5,0],[frame+5,5],[frame,5]],confidence:1}))};
+ for(const [time,options,expected] of [[1/24,{},0],[.042,{},1],[.1,{},2],[0,{startFrame:1},1],[.042,{startFrame:1,speed:-1},0],[1,{startFrame:2,speed:0},2]]){
+ const selected=preparedFrame(r,time,options),pin=sampleTrackFrame(track,selected.sourceFrame);
+ assert.equal(selected.sourceFrame,expected);assert.equal(pin.quad[0][0],expected);assert.equal(pin.held,false);
+ }
+ assert.throws(()=>preparedFrame(r,0,{startFrame:3}),/trim/);
+});
+test('prepared source identity, correspondence and review survive trims/reverse/random seeks',()=>{
+ const r=validatePreparedAnalysis(receipt());
+ assert.equal(preparedFrame(r,1/24).sourceFrame,1);
+ assert.equal(preparedFrame(r,1/24,{start:2/24,speed:-1}).sourceFrame,1);
+ assert.equal(preparedFrame(r,0).sourceFrame,0);
+ assert.throws(()=>preparedFrame(r,3/24),/outside/);
+ const stale=receipt();assert.throws(()=>validatePreparedAnalysis(stale,{...stale.source,sha256:maskHash}),/changed/);
+ const missing=receipt();missing.frames.pop();assert.throws(()=>validatePreparedAnalysis(missing),/correspondence/);
+ const bad=receipt();bad.frames[1].valid=false;assert.throws(()=>preparedFrame(bad,1/24),/frame 1/);
+ bad.frames[1].valid=true;bad.frames[1].reviewed=false;assert.throws(()=>preparedFrame(bad,1/24),/review/);
+});
+test('mask collapse is flagged without erasing disconnected finger components',()=>{
+ const pixels=new Uint8ClampedArray(4*100);for(const p of [1,3,10,99])pixels.fill(255,p*4,p*4+4);
+ const a=analyzeMask(pixels,10,10,{previousCoverage:.5});
+ assert.equal(a.coverage,.04);assert.deepEqual(a.bounds,[0,0,10,10]);assert.deepEqual(a.issues,['foreground-area-collapse']);
+});
+test('corrections propagate only inside authored matching intervals',()=>{
+ const polygon=x=>({operation:'add',points:[[x,0],[x+4,0],[x+4,4],[x,4]]});
+ const b={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:10,interpolation:'linear',polygons:[polygon(0)]},{frame:20,polygons:[polygon(10)]}]};
+ assert.equal(sampleMaskCorrections(b,15)[0].points[0][0],5);assert.deepEqual(sampleMaskCorrections(b,21),[]);
+ b.keys[1].polygons[0].operation='subtract';assert.throws(()=>sampleMaskCorrections(b,15),/topology/);
+});
+test('surface layout rejects overflowing footer rather than silently clipping it',()=>{
+ assertSurfaceLayout([{x:10,y:10,width:80,height:30}],{width:100,height:60});
+ assert.throws(()=>assertSurfaceLayout([{id:'footer',x:0,y:58,width:100,height:10}],{width:100,height:60}),/footer/);
+});
+test('cylindrical mapping keeps the original body bounds and non-linear UV spacing',()=>{
+ const m=cylinderMesh([[10,20],[110,20],[110,220],[10,220]],{columns:4,rows:1});
+ assert.deepEqual(m.vertices[0],[10,20]);assert.deepEqual(m.vertices[4],[110,20]);assert.equal(m.vertices.at(-1)[1],220);
+ assert.equal(m.uv[2][0],.5);assert.ok(m.uv[1][0]>.25,'surface curvature compresses the edge texture');
+ assert.equal(surfaceError(m.vertices,m.vertices).max,0);
+ const a={frame:0,...m},b={frame:10,...m,vertices:m.vertices.map(([x,y])=>[x+20,y])};
+ assert.equal(sampleSurface({version:1,frames:[a,b]},5).vertices[0][0],20);
+ assert.throws(()=>sampleSurface({version:1,frames:[a,b]},11),/outside/);
+});
+test('all text treatments reproduce after reverse/random seeks and retain readable holds',()=>{
+ for(const effect of ['rise','wipe','spring','orbit','extrude']){
+ const first=typeMotion(.3,{effect});typeMotion(2,{effect});typeMotion(0,{effect});assert.deepEqual(typeMotion(.3,{effect}),first);
+ assert.equal(typeMotion(-1,{effect}).opacity,0);assert.equal(typeMotion(1.5,{effect}).opacity,1);assert.equal(typeMotion(4,{effect}).opacity,0);
+ }
+});
+
+test('correction gestures propose reversible books without mutating an existing revision',()=>{
+ const session=createMaskCorrectionSession(),book={version:1,sourceSha256:hash,subject:'hand',keys:[]};
+ const options={book,sourceSha256:hash,subject:'hand',sourceFrame:1,sourceWidth:100,sourceHeight:80,width:200,height:160};
+ session.gesture({phase:'begin',id:'stroke',start:{x:50,y:50}},options);
+ const proposal=session.gesture({phase:'commit',id:'stroke',point:{x:50,y:50}},options);
+ assert.equal(book.keys.length,0);assert.equal(proposal.values.corrections.keys[0].frame,1);assert.equal(proposal.values.corrections.keys[0].polygons[0].points.length,20);
+});
+test('adjacent surface triangles cover every interior pixel without transparency seams',()=>{
+ const art=new Uint8ClampedArray(4*16);for(let i=0;i{
+ const asset={type:'video',sha256:hash},derived=subject=>({type:'video',sha256:maskHash,derived:{of:'plate',role:'matte',sourceSha256:hash,subject}});
+ validateDerived({plate:asset,hand:derived('hand'),person:derived('person')});
+ assert.throws(()=>validateDerived({plate:asset,hand:derived('hand'),another:derived('hand')}),/two matte/);
+});
+
+test('baked corrections are applied once and subsequent edits remain provisional',()=>{
+ const p={operation:'add',points:[[0,0],[5,0],[5,5]]},book={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:0,polygons:[p]}]};
+ assert.equal(pendingMaskCorrections(book,structuredClone(book)),null);
+ const edited=structuredClone(book);edited.keys[0].polygons.push({...p,operation:'subtract'});
+ assert.equal(pendingMaskCorrections(edited,book).keys[0].polygons.length,1);
+ assert.throws(()=>pendingMaskCorrections({...book,keys:[]},book),/original mask/);
+});
+
+test('changing a baked interpolated span requires preparation from the raw mask',()=>{
+ const p={operation:'add',points:[[0,0],[5,0],[5,5]]},a={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:0,interpolation:'linear',polygons:[p]},{frame:10,polygons:[p]}]};
+ const edited=structuredClone(a);edited.keys.splice(1,0,{frame:5,polygons:[p]});assert.throws(()=>pendingMaskCorrections(edited,a),/interpolation interval/);
+ const appended=structuredClone(a);appended.keys[0].polygons.push(p);assert.throws(()=>pendingMaskCorrections(appended,a),/interpolation interval/);
+});
diff --git a/tests/import.test.mjs b/tests/import.test.mjs
new file mode 100644
index 0000000..f45f1fd
--- /dev/null
+++ b/tests/import.test.mjs
@@ -0,0 +1,35 @@
+import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';
+import {init,importAsset,readProject} from '../scripts/project.mjs';import {fileHash} from '../scripts/media.mjs';import {run,ffmpeg} from '../scripts/process.mjs';import {render} from '../scripts/render.mjs';
+
+test('import validates copied media and JSON before publishing; failed candidates preserve project',async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-import-')),dir=path.join(tmp,'project');
+ try{
+ await init(dir);const video=path.join(tmp,'valid.mp4'),image=path.join(tmp,'valid.png'),audio=path.join(tmp,'valid.wav');
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=128x96:rate=24','-t','1','-c:v','libx264','-movflags','+faststart',video]);
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','color=red:s=32x32','-frames:v','1',image]);
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','sine=frequency=440:duration=0.1',audio]);
+ const raw=await fs.readFile(path.join(dir,'project.json')),before=await readProject(dir);
+ const snapshot=async()=>({manifest:await fs.readFile(path.join(dir,'assets.json'),'utf8').catch(e=>{if(e.code==='ENOENT')return null;throw e}),assets:await fs.readdir(path.join(dir,'assets')).catch(e=>{if(e.code==='ENOENT')return [];throw e})});
+ const bytes=await fs.readFile(video),invalid=[['bad.mp4',Buffer.from('not a movie')],['bad.png',Buffer.from('not an image')],['bad.wav',Buffer.from('RIFF')],['bad.json',Buffer.from('{')],['truncated.mp4',bytes.subarray(0,Math.floor(bytes.length*.65))]];
+ for(const [name,body]of invalid){const f=path.join(tmp,name);await fs.writeFile(f,body);const old=await snapshot();await assert.rejects(importAsset(dir,'candidate',f));assert.deepEqual(await snapshot(),old,name);assert.deepEqual(await fs.readFile(path.join(dir,'project.json')),raw);assert.equal((await readProject(dir)).revision,before.revision);}
+ for(const [id,file]of [['movie',video],['picture',image],['sound',audio]]){const r=await importAsset(dir,id,file);assert.equal(r.sha256,await fileHash(file));assert.ok(r.probe);}
+ const old=await snapshot();await assert.rejects(importAsset(dir,'movie',video),/immutable/);assert.deepEqual(await snapshot(),old);
+ const badTrack=path.join(tmp,'track.json');await fs.writeFile(badTrack,'{}');await assert.rejects(importAsset(dir,'badtrack',badTrack,{role:'track',of:'movie'}));assert.deepEqual(await snapshot(),old);
+ const analysis=path.join(tmp,'analysis.json'),digest=await fileHash(video);
+ await fs.writeFile(analysis,JSON.stringify({version:1,kind:'prepared-plate',source:{asset:'movie',sha256:digest,width:128,height:96,frames:24,frameRate:{num:24,den:1},orientation:0,crop:[0,0,128,96],pts:Array.from({length:24},(_,i)=>i/24)},subject:'person',revision:'0'.repeat(64),provenance:{method:'fixture',preprocess:'none'},alpha:{asset:'missing',sha256:digest,channel:'luminance',semantics:'alpha'},frames:Array.from({length:24},(_,i)=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:false}))}));
+ await assert.rejects(importAsset(dir,'analysis',analysis,{role:'analysis',of:'movie'}),/Prepared alpha identity/);assert.deepEqual(await snapshot(),old);
+ const short=path.join(tmp,'short.mp4');await run(ffmpeg(),['-v','error','-f','lavfi','-i','color=white:s=128x96:r=24','-frames:v','4',short]);await assert.rejects(importAsset(dir,'mask',short,{role:'matte',of:'movie'}),/match its plate/);assert.deepEqual(await snapshot(),old);
+ }finally{await fs.rm(tmp,{recursive:true,force:true})}
+});
+
+test('import pins the copied bytes when the source changes at copy time',async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-import-race-')),dir=path.join(tmp,'project'),source=path.join(tmp,'values.json');const copy=fs.copyFile;
+ try{await init(dir);await fs.writeFile(source,'{"value":1}');fs.copyFile=async(src,...args)=>{if(src===source)await fs.writeFile(source,'{"value":2}');return copy(src,...args)};
+ const result=await importAsset(dir,'data',source);assert.equal(result.sha256,await fileHash(source));const d=await (await import('../scripts/project.mjs')).definition(dir);assert.equal(d.assets.data.sha256,result.sha256);assert.equal(await fs.readFile(d.assets.data.file,'utf8'),'{"value":2}');
+ }finally{fs.copyFile=copy;await fs.rm(tmp,{recursive:true,force:true})}
+});
+
+test('expected export identity refuses a stale gate before allocating output',async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-export-gate-')),dir=path.join(tmp,'project'),output=path.join(tmp,'absent','clip.mp4');
+ try{await init(dir);const d=await readProject(dir);await assert.rejects(render(dir,output,{expectRevision:'old'}),/Stale export revision/);await assert.rejects(render(dir,output,{expectRevision:d.revision,expectBinding:'old'}),/Stale export binding/);await assert.rejects(fs.stat(path.dirname(output)),{code:'ENOENT'});}finally{await fs.rm(tmp,{recursive:true,force:true})}
+});
diff --git a/tests/media-pts.test.mjs b/tests/media-pts.test.mjs
new file mode 100644
index 0000000..a7c8850
--- /dev/null
+++ b/tests/media-pts.test.mjs
@@ -0,0 +1,53 @@
+import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {createHash} from 'node:crypto';
+import {prepareMedia} from '../scripts/media.mjs';import {run,ffmpeg,ffprobe} from '../scripts/process.mjs';import {ptsIndex} from '../packages/media/ports.mjs';
+import {mediaFrameUrl} from '../packages/media/frames.mjs';
+test('a static derived matte stays available throughout its moving parent',async()=>{
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-static-matte-'));let media;
+ try{
+ const plate=path.join(dir,'plate.mp4'),mask=path.join(dir,'mask.png');
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=64x48:rate=24:duration=1','-c:v','libx264',plate]);
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','color=c=white:s=64x48','-frames:v','1',mask]);
+ const sha=async file=>createHash('sha256').update(await fs.readFile(file)).digest('hex'),source=await sha(plate);
+ media=await prepareMedia({plate:{file:plate,type:'video',sha256:source},mask:{file:mask,type:'image',sha256:await sha(mask),derived:{of:'plate',role:'matte',sourceSha256:source}}});
+ assert.equal(mediaFrameUrl(media.catalog,'mask',-1),undefined,'a still retains its own presentation clock');
+ for(const frame of [0,1,12,23]){
+ const url=mediaFrameUrl(media.catalog,'mask',frame/24);
+ assert.ok(url.endsWith('/000001.png'));await fs.access(path.join(media.dir,'mask',path.basename(url)));
+ assert.ok(mediaFrameUrl(media.catalog,'plate',frame/24).endsWith(String(frame+1).padStart(6,'0')+'.png'));
+ }
+ }finally{await media?.close();await fs.rm(dir,{recursive:true,force:true});}
+});
+// ffprobe prints `*_time` values to six decimals, so frame 1 of a 24 fps clip reads 0.041667: later than
+// 1/24 s. Looked up at the frame's own time, a third of the frames of a 24 or 30 fps clip resolved to
+// their predecessor, so a plate showed frame n-1 while a track sampled on the plate's grid used frame n.
+for(const rate of [24,30])test(`every frame of a ${rate} fps clip is found at its own frame time`,async()=>{
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-pts-'));let media;
+ try{
+ const file=path.join(dir,'clip.mp4');
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i',`testsrc2=size=64x48:rate=${rate}:duration=1`,'-c:v','libx264','-g',String(rate),file]);
+ const sha256=createHash('sha256').update(await fs.readFile(file)).digest('hex');
+ media=await prepareMedia({clip:{file,type:'video',sha256}});
+ const {pts}=media.catalog.clip;assert.equal(pts.length,rate);
+ const wrong=[];for(let n=0;n{const found=[];for(let i=8;i+8<=png.length;){const length=png.readUInt32BE(i),type=png.toString('latin1',i+4,i+8);if(['cICP','cHRM','gAMA','iCCP','sRGB'].includes(type))found.push(type);i+=12+length;}return found;};
+test('frames of a colour-tagged clip hold their values with no colour chunks for the browser to apply',async()=>{
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-tagged-'));let media;
+ try{
+ const file=path.join(dir,'tagged.mp4');
+ await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=64x48:rate=25:duration=1','-vf','setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709','-c:v','libx264','-pix_fmt','yuv420p',file]);
+ const tags=(await run(ffprobe(),['-v','error','-select_streams','v:0','-show_entries','stream=color_transfer,color_primaries','-of','csv=p=0',file])).toString().trim();
+ assert.equal(tags,'bt709,bt709','the fixture must carry the tags real footage does');
+ const sha256=createHash('sha256').update(await fs.readFile(file)).digest('hex');
+ media=await prepareMedia({clip:{file,type:'video',sha256}});
+ const frame=path.join(media.dir,'clip','000011.png');
+ assert.deepEqual(colourChunks(await fs.readFile(frame)),[]);
+ const raw=args=>run(ffmpeg(),['-v','error',...args,'-f','rawvideo','-pix_fmt','rgb24','-']);
+ assert.ok((await raw(['-i',frame])).equals(await raw(['-i',file,'-vf','select=eq(n\\,10)','-frames:v','1'])),'the frame keeps the values a plain decode gives');
+ }finally{await media?.close();await fs.rm(dir,{recursive:true,force:true})}
+});
diff --git a/tests/media.test.mjs b/tests/media.test.mjs
index 2be3300..c289a93 100644
--- a/tests/media.test.mjs
+++ b/tests/media.test.mjs
@@ -4,3 +4,17 @@ test('PTS lookup follows variable source timestamps and explicit end policies',(
test('audio mapping respects split, trim, delay, speed, mute and one track per port',()=>{const s=make(),c=s.doc.clips[0];s.execute({type:'split',clip:c.id,at:ticks(2)});const plan=audioPlan(s,{demo:{audio:true}});assert.equal(plan.length,2);assert.equal(plan[1].start,2);assert.equal(plan[1].sourceIn,2);assert.equal(plan[1].duration,2);s.execute({type:'set',clip:c.id,anchor:'presenter',property:'muted',value:true});assert.equal(audioPlan(s,{demo:{audio:true}}).length,1)});
test('rational output clock is preserved; invalid ports fail closed',()=>{assert.deepEqual(frameRate('30000/1001'),{num:30000,den:1001});assert.throws(()=>frameRate('30/0'));assert.throws(()=>resolvePorts({...template,media:{bad:{asset:'demo',rate:NaN}}},template.nodes))});
test('invalid cache sizes cannot enter an eviction loop',()=>{const c=new FrameCache(10);assert.throws(()=>c.set('a',{},-1));assert.throws(()=>c.set('a',{},NaN));assert.throws(()=>new FrameCache(-1))});
+
+// A portable renderer's audio declaration must survive the editing adapter.
+// Exercise the resulting audio schedule, not just the adapted object's shape.
+test('renderer media declaration preserves clip trim, offsets, mute and speed in audio schedule',async()=>{
+ const {normalizeClipModule}=await import('../packages/core/definition.mjs');
+ const {defineRenderer}=await import('../packages/core/renderer.mjs');
+ const {template:t}=normalizeClipModule({default:defineRenderer({id:'audio-renderer',renderer:'dom',width:160,height:90,fps:24,durationInFrames:96,
+ media:{first:{asset:'a'},second:{asset:'b',offset:2},muted:{asset:'a',muted:true}},create(){return {render(){}}}})});
+ const s=new Studio({[t.id]:t},{binding:'test'});s.doc.clips=[s.make(t.id)];s.base=clone(s.doc);
+ const c=s.doc.clips[0],catalog={a:{audio:true,duration:2},b:{audio:true,duration:2}};
+ let p=audioPlan(s,catalog);assert.equal(p.length,2);assert.deepEqual(p.map(x=>[x.asset,x.start,x.sourceIn,x.duration]),[['a',0,0,2],['b',2,0,2]]);
+ s.execute({type:'timing',clip:c.id,sourceIn:ticks(.5),duration:ticks(1.5),rate:2});
+ p=audioPlan(s,catalog);assert.deepEqual(p.map(x=>[x.asset,x.start,x.sourceIn,x.duration,x.rate]),[['a',0,.5,.75,2],['b',.75,0,.75,2]]);
+});
diff --git a/tests/plate.test.mjs b/tests/plate.test.mjs
new file mode 100644
index 0000000..7427607
--- /dev/null
+++ b/tests/plate.test.mjs
@@ -0,0 +1,218 @@
+import {test} from 'node:test';
+import assert from 'node:assert/strict';
+import * as plate from '../packages/plate/index.mjs';
+import {defineRenderer} from '../packages/core/renderer.mjs';
+import {mountRenderer} from '../packages/runtime/renderer-host.mjs';
+
+const near = (a, b, tolerance = 1e-6) => assert.ok(Math.abs(a - b) <= tolerance, `${a} is not within ${tolerance} of ${b}`);
+const image = (width, height, paint) => { const data = new Uint8ClampedArray(width * height * 4); for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) { const [r, g, b] = paint(x, y); data.set([r, g, b, 255], (y * width + x) * 4); } return data; };
+
+test('a corner pin carries every corner onto its target and inverts', () => {
+ const quad = [[10, 12], [130, 24], [118, 96], [4, 70]], h = plate.solveHomography(plate.rectQuad(160, 90), quad);
+ plate.rectQuad(160, 90).forEach((corner, i) => plate.applyHomography(h, corner).forEach((v, axis) => near(v, quad[i][axis], 1e-9)));
+ plate.applyHomography(plate.invertHomography(h), quad[2]).forEach((v, axis) => near(v, [160, 90][axis], 1e-8));
+ const identity = plate.multiplyHomography(h, plate.invertHomography(h));
+ [1, 0, 0, 0, 1, 0, 0, 0, 1].forEach((v, i) => near(identity[i], v, 1e-9));
+ // A pure translation is the simplest case to read off the CSS matrix.
+ assert.equal(plate.cornerPinTransform(10, 10, [[5, 7], [15, 7], [15, 17], [5, 17]]), 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,5,7,0,1)');
+ assert.throws(() => plate.solveHomography(plate.rectQuad(10, 10), [[0, 0], [5, 5], [10, 10], [20, 20]]), /Degenerate/);
+ assert.throws(() => plate.cornerPinTransform(0, 10, quad), /positive/);
+ assert.ok(plate.quadArea(quad) > 0); assert.ok(plate.quadArea([...quad].reverse()) < 0);
+});
+
+test('tracks interpolate between frames, hold outside them and refuse bad data', () => {
+ const track = {version: 1, kind: 'planar', width: 640, height: 360, frameRate: {num: 24, den: 1}, frames: [
+ {frame: 2, quad: [[0, 0], [10, 0], [10, 10], [0, 10]], confidence: 1},
+ {frame: 6, quad: [[40, 0], [50, 0], [50, 10], [40, 10]], confidence: .5},
+ ]};
+ plate.validateTrack(track);
+ const mid = plate.sampleTrack(track, 4 / 24);
+ assert.deepEqual(mid.quad[0], [20, 0]); assert.equal(mid.confidence, .5); assert.equal(mid.held, false);
+ // The last good frame before a weaker one is still fully trusted.
+ assert.equal(plate.sampleTrack(track, 2 / 24).confidence, 1); assert.equal(plate.sampleTrack(track, 6 / 24).confidence, .5);
+ // Sub-frame times are what a motion-blur sample asks for.
+ near(plate.sampleTrack(track, 2.5 / 24).quad[0][0], 5);
+ assert.deepEqual(plate.sampleTrack(track, 0).quad[0], [0, 0]); assert.equal(plate.sampleTrack(track, 0).held, true);
+ assert.deepEqual(plate.sampleTrack(track, 9).quad[0], [40, 0]); assert.equal(plate.sampleTrack(track, 9).held, true);
+ assert.deepEqual(plate.scalePoints([[320, 180]], track, 1280, 720), [[640, 360]]);
+ const point = {...track, kind: 'point', frames: [{frame: 0, point: [0, 0]}, {frame: 10, point: [10, 20]}]};
+ assert.deepEqual(plate.sampleTrack(plate.validateTrack(point), 5 / 24).point, [5, 10]);
+ assert.throws(() => plate.validateTrack({...track, frames: [track.frames[1], track.frames[0]]}), /increasing/);
+ assert.throws(() => plate.validateTrack({...track, frames: [{frame: 0, quad: [[0, 0]]}]}), /four finite/);
+ assert.throws(() => plate.validateTrack({...track, frameRate: {num: 24, den: 0}}), /frameRate/);
+});
+
+test('camera paths slerp rotation and hold their ends', () => {
+ const half = Math.SQRT1_2, path = plate.validateCameraPath({version: 1, frameRate: {num: 24, den: 1}, frames: [
+ {frame: 0, position: [0, 0, 0], quaternion: [0, 0, 0, 1], fovY: 30},
+ {frame: 24, position: [2, 0, -4], quaternion: [0, half, 0, half], fovY: 50},
+ ]});
+ const mid = plate.sampleCameraPath(path, .5);
+ assert.deepEqual(mid.position, [1, 0, -2]); near(mid.fovY, 40);
+ // Halfway to a 90-degree yaw is a 45-degree yaw, still a unit quaternion.
+ near(mid.quaternion[1], Math.sin(Math.PI / 8)); near(mid.quaternion[3], Math.cos(Math.PI / 8)); near(Math.hypot(...mid.quaternion), 1);
+ assert.deepEqual(plate.sampleCameraPath(path, 99).position, [2, 0, -4]);
+ // q and -q are the same rotation; the short way round is taken.
+ near(plate.slerp([0, 0, 0, 1], [0, 0, 0, -1], .5)[3], 1);
+ assert.throws(() => plate.validateCameraPath({...path, frames: [{...path.frames[0], quaternion: [0, 0, 0, 2]}]}), /unit quaternion/);
+});
+
+test('conform snaps code to the plate frame grid and names uneven cadence', () => {
+ const film = {num: 24, den: 1};
+ assert.equal(plate.plateFrameIndex(.5, film), 12); assert.equal(plate.plateFrameIndex(1 / 24, film), 1);
+ near(plate.conformSeconds(.51, film), .5); near(plate.conformSeconds(1, {num: 30000, den: 1001}), 29 * 1001 / 30000);
+ assert.deepEqual(plate.cadence(film, {num: 30, den: 1}).pattern, [2, 1, 1, 1]); assert.equal(plate.cadence(film, {num: 30, den: 1}).even, false);
+ assert.deepEqual(plate.cadence(film, {num: 60, den: 1}).pattern, [3, 2]);
+ assert.equal(plate.cadence(film, film).even, true); assert.equal(plate.cadence({num: 30, den: 1}, {num: 60, den: 1}).even, true);
+ assert.equal(plate.cadence({num: 30, den: 1}, film).dropsFrames, true);
+ assert.throws(() => plate.plateFrameIndex(-1, film));
+});
+
+test('shutter samples stay inside the open interval', () => {
+ assert.deepEqual(plate.shutterSamples(10, {samples: 4, angle: 180}), [9.8125, 9.9375, 10.0625, 10.1875]);
+ assert.deepEqual(plate.shutterSamples(0, {samples: 2, angle: 360, phase: 'forward'}), [.25, .75]);
+ assert.ok(plate.shutterSamples(0, {samples: 8, angle: 360}).every(t => t >= 0));
+ for (const bad of [{samples: 1}, {samples: 65}, {angle: 0}, {angle: 361}, {phase: 'late'}]) assert.throws(() => plate.validateShutter(bad));
+});
+
+test('depth encodings round-trip, white is near, and the shader carries the same constants', () => {
+ for (const kind of ['inverse', 'linear']) {
+ const encoding = plate.validateDepthEncoding({kind, near: 1.2, far: 12});
+ near(plate.decodeDepth(1, encoding), 1.2); near(plate.decodeDepth(0, encoding), 12);
+ for (const distance of [1.2, 2, 3.3, 7, 12]) near(plate.decodeDepth(plate.encodeDepth(distance, encoding), encoding), distance, 1e-9);
+ assert.ok(plate.encodeDepth(2, encoding) > plate.encodeDepth(5, encoding));
+ }
+ const [high, low] = plate.packDepth(.123456, 'rg16'); near(plate.unpackDepth(high, low, 'rg16'), .123456, 1 / 65535);
+ assert.deepEqual(plate.packDepth(1), [255, 255, 255]);
+ assert.match(plate.depthGlsl({kind: 'linear', near: 1, far: 9, packing: 'rg16'}), /texel\.r \* 65280\.0.*9\.00000000 - v \* 8\.00000000/);
+ assert.throws(() => plate.validateDepthEncoding({kind: 'inverse', near: 0, far: 5})); assert.throws(() => plate.validateDepthEncoding({kind: 'metric', near: 1, far: 5}));
+ assert.deepEqual(plate.unprojectDepth(.5, .5, 3, 35, 16 / 9), [0, 0, -3]);
+ // A floor one unit below the camera, sampled at four depths.
+ const floor = plate.fitGroundPlane([[0, -1, -2], [1, -1, -3], [-1, -1, -5], [2, -1, -4]]);
+ near(floor.normal[1], 1); near(floor.point[1], -1); near(floor.rms, 0);
+ assert.throws(() => plate.fitGroundPlane([[0, 0, 0], [1, 1, 0], [2, 2, 0]]), /ground plane/);
+});
+
+test('plate measurements: levels, light direction, noise and grain', () => {
+ const stats = plate.plateStats(image(40, 20, x => x < 20 ? [30, 30, 30] : [220, 200, 180]), 40, 20);
+ near(stats.black[0], plate.srgbToLinear(30 / 255)); near(stats.white[2], plate.srgbToLinear(180 / 255));
+ const levels = plate.matchLevels(stats);
+ // A full-range render lands exactly on the plate's own black and white.
+ plate.applyLevels([0, 0, 0], levels).forEach((v, c) => near(v, stats.black[c]));
+ plate.applyLevels([1, 1, 1], levels).forEach((v, c) => near(v, stats.white[c]));
+
+ const window = (x0, y0) => image(64, 36, (x, y) => x >= x0 && x < x0 + 8 && y >= y0 && y < y0 + 6 ? [255, 240, 200] : [90, 60, 40]);
+ const left = plate.estimateKeyLight(window(4, 3), 64, 36), right = plate.estimateKeyLight(window(52, 26), 64, 36);
+ assert.ok(left.toward[0] < -.4 && left.toward[1] > .3, 'a bright patch upper-left lights from upper-left');
+ assert.ok(right.toward[0] > .4 && right.toward[1] < -.2, 'a bright patch lower-right lights from lower-right');
+ near(Math.hypot(...left.toward), 1); assert.ok(left.concentration > .7); assert.ok(left.color[0] >= left.color[2]);
+ assert.ok(left.ambient[0] > left.ambient[2], 'the fill keeps the wall colour');
+ assert.equal(plate.estimateKeyLight(image(64, 36, () => [128, 128, 128]), 64, 36).concentration, 0);
+
+ assert.equal(plate.estimateNoise(image(64, 64, () => [128, 128, 128]), 64, 64), 0);
+ // Known Gaussian noise (seeded Box-Muller), sigma 8/255.
+ let seed = 7; const random = () => (seed = Math.imul(seed, 1664525) + 1013904223 >>> 0) / 4294967296;
+ const noisy = image(128, 128, () => { const g = Math.sqrt(-2 * Math.log(random() + 1e-12)) * Math.cos(2 * Math.PI * random()), v = Math.round(128 + 8 * g); return [v, v, v]; });
+ near(plate.estimateNoise(noisy, 128, 128), 8 / 255, 4 / 255 / 4);
+
+ assert.equal(plate.grainAt(3, 9, 12, 5), plate.grainAt(3, 9, 12, 5)); assert.notEqual(plate.grainAt(3, 9, 12, 5), plate.grainAt(3, 9, 13, 5));
+ let sum = 0; for (let i = 0; i < 4000; i++) { const g = plate.grainAt(i % 80, i >> 4, 1); assert.ok(g >= -1 && g <= 1); sum += g; }
+ assert.ok(Math.abs(sum / 4000) < .08, 'grain is centred on zero');
+
+ const expanded = plate.expandHighlights(new Uint8ClampedArray([255, 255, 255, 255, 100, 100, 100, 255]));
+ assert.ok(expanded[0] > 6, 'a clipped white is pushed well above 1'); near(expanded[4], plate.srgbToLinear(100 / 255), 1e-6);
+ assert.throws(() => plate.plateStats(new Uint8ClampedArray(8), 4, 4));
+});
+
+test('object ids survive a round trip through colour', () => {
+ const seen = new Set();
+ for (const index of [0, 1, 2, 3, 255, 256, 65535, 1_000_000, 16_777_213]) { const color = plate.idColor(index); assert.equal(plate.idFromColor(color), index); seen.add(color.join()); }
+ assert.equal(seen.size, 9); assert.equal(plate.idFromColor([0, 0, 0]), -1);
+ // Neighbouring ids are far apart, so two adjacent objects stay distinguishable by eye.
+ const [a, b] = [plate.idColor(0), plate.idColor(1)]; assert.ok(Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]) > 100);
+ assert.throws(() => plate.idColor(-1));
+ assert.deepEqual(plate.validatePasses(['beauty', 'clay', 'id']), ['clay', 'id']);
+ assert.throws(() => plate.validatePasses(['clay', 'clay'])); assert.throws(() => plate.validatePasses(['Depth']));
+});
+
+test('a scene declares its passes; invalid declarations are refused', () => {
+ const base = {id: 'x', renderer: 'any', width: 16, height: 16, fps: 24, durationInFrames: 1, create: async () => ({render() {}, dispose() {}})};
+ assert.deepEqual(defineRenderer({...base, passes: ['clay', 'depth']}).passes, ['clay', 'depth']);
+ assert.equal(defineRenderer(base).passes, undefined);
+ for (const passes of [['beauty'], ['clay', 'clay'], ['Bad Name'], 'clay']) assert.throws(() => defineRenderer({...base, passes}), /passes/);
+});
+
+test('derived assets are pinned to the take they were made from', () => {
+ const sha = c => c.repeat(64), ok = () => ({
+ plate: {type: 'video', sha256: sha('a')},
+ matte: {type: 'video', sha256: sha('b'), derived: {of: 'plate', role: 'matte', sourceSha256: sha('a')}},
+ depth: {type: 'video', sha256: sha('c'), derived: {of: 'plate', role: 'depth', sourceSha256: sha('a'), encoding: {kind: 'inverse', near: 1, far: 10}}},
+ track: {type: 'data', sha256: sha('d'), derived: {of: 'plate', role: 'track', sourceSha256: sha('a')}},
+ });
+ assert.deepEqual(plate.validateDerived(ok()), {plate: {matte: 'matte', depth: 'depth', track: 'track'}});
+ const broken = edit => { const assets = ok(); edit(assets); return () => plate.validateDerived(assets); };
+ // The plate was regenerated: its matte now describes a different picture.
+ assert.throws(broken(a => { a.plate.sha256 = sha('e'); }), /regenerate the matte/);
+ assert.throws(broken(a => { a.matte.derived.of = 'missing'; }), /another declared asset/);
+ assert.throws(broken(a => { a.matte.derived.of = 'matte'; }), /another declared asset/);
+ assert.throws(broken(a => { a.track.type = 'video'; }), /A track must be data/);
+ assert.throws(broken(a => { delete a.depth.derived.encoding; }), /encoding/);
+ assert.throws(broken(a => { a.matte.derived.encoding = {kind: 'inverse', near: 1, far: 2}; }), /Only depth/);
+ assert.throws(broken(a => { a.matte.derived.role = 'roto'; }), /unknown role/);
+ assert.throws(broken(a => { a.second = structuredClone(a.matte); }), /two matte/);
+ assert.throws(broken(a => { a.chain = {type: 'video', sha256: sha('f'), derived: {of: 'matte', role: 'matte', sourceSha256: sha('b')}}; }), /itself derived/);
+});
+
+test('the host hands plate services to a scene and nothing it was not given', async () => {
+ const element = () => ({style: {}, append() {}, remove() {}});
+ const root = {ownerDocument: {createElement: element, fonts: {ready: Promise.resolve()}}, append() {}};
+ let context;
+ const scene = defineRenderer({id: 'x', renderer: 'any', width: 16, height: 16, fps: 24, durationInFrames: 1, create: async c => { context = c; return {render() {}, dispose() {}}; }});
+ const instance = await mountRenderer(scene, {root, services: {mediaInfo: id => ({id}), derived: (id, role) => `${id}-${role}`}});
+ assert.deepEqual(context.mediaInfo('plate'), {id: 'plate'}); assert.equal(context.derived('plate', 'matte'), 'plate-matte');
+ assert.equal(context.mediaFrame, undefined); assert.equal(context.asset, undefined);
+ await instance.dispose();
+ await assert.rejects(mountRenderer(scene, {root, services: {derived: 'nope'}}), /Invalid derived service/);
+});
+
+test('the plate panorama fills both halves: as shot in front, mirrored behind', async () => {
+ const {paintPlatePanorama} = await import('../packages/three/plate.mjs');
+ const draws = [];let m = [1, 0, 0, 1, 0, 0];
+ const context = {setTransform: (...a) => {m = a;}, drawImage: (_s, x, y, w) => {const xs = [x, x + w].map(v => m[0] * v + m[4]);draws.push([Math.min(...xs), Math.max(...xs), m[0]]);}};
+ paintPlatePanorama(context, {}, 256);
+ assert.deepEqual(draws, [[0, 128, 1], [128, 256, -1]]);
+});
+
+test('control passes restore visibility and override materials, even when rendering throws', async () => {
+ const T = await import('three');
+ const {renderPass} = await import('../packages/three/plate.mjs');
+ for (const fail of [false, true]) for (const pass of ['id', 'matte', 'depth', 'normal', 'clay']) {
+ const scene = new T.Scene(), camera = new T.PerspectiveCamera();
+ const original = new T.MeshBasicMaterial(), override = new T.MeshBasicMaterial({color: 0xff0000});
+ scene.overrideMaterial = override;
+ const visible = new T.Mesh(new T.BoxGeometry(), original); visible.name = 'included';
+ const hidden = new T.Mesh(new T.BoxGeometry(), original); hidden.visible = false;
+ const excluded = new T.Mesh(new T.BoxGeometry(), original);
+ scene.add(visible, hidden, excluded);
+ let calls = 0;
+ const renderer = {toneMapping: T.NeutralToneMapping, getClearColor: c => c.set(0x123456), getClearAlpha: () => .5, setClearColor() {},
+ render(s) {
+ calls++;
+ assert.equal(s.overrideMaterial, null, 'the pass material must reach Three.js');
+ assert.notEqual(visible.material, original);
+ assert.equal(hidden.visible, false);
+ if (pass === 'id') assert.equal(excluded.visible, false);
+ if (fail) throw Error('GPU failure');
+ }};
+ const draw = () => renderPass(renderer, scene, camera, pass, {ids: ['included']});
+ if (fail) assert.throws(draw, /GPU failure/); else draw();
+ assert.equal(calls, 1);
+ assert.equal(hidden.visible, false, 'an invisible mesh stays invisible after the pass');
+ assert.equal(excluded.visible, true);
+ assert.equal(scene.overrideMaterial, override);
+ assert.equal(visible.material, original);
+ assert.equal(renderer.toneMapping, T.NeutralToneMapping);
+ for (const mesh of [visible, hidden, excluded]) mesh.geometry.dispose();
+ original.dispose(); override.dispose();
+ }
+});
diff --git a/tests/prepared-integration.mjs b/tests/prepared-integration.mjs
new file mode 100644
index 0000000..b3c4d2e
--- /dev/null
+++ b/tests/prepared-integration.mjs
@@ -0,0 +1,32 @@
+// Real pixels: foreground preservation over animated DOM, through the CLI.
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {init,rebind} from '../scripts/project.mjs';
+import {render} from '../scripts/render.mjs';
+import {run,ffmpeg} from '../scripts/process.mjs';
+const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-prepared-')),dir=path.join(tmp,'scene');
+const source=`import {defineRenderer} from 'editableframes/renderer';
+import {createForegroundHoldout,createKineticText} from 'editableframes/plate';
+export default defineRenderer({id:'foreground-regression',renderer:'dom',width:160,height:90,fps:12,durationInFrames:12,defaultProps:{badFrame:-1},
+ create({root,props}){
+ root.style.background='#162432';
+ const hold=createForegroundHoldout({root,width:160,height:90}),box=document.createElement('div');
+ box.style.cssText='position:absolute;inset:0;background:#ff0000;color:white;font:900 20px system-ui;overflow:hidden';hold.root.append(box);
+ const title=createKineticText({root:box,text:'EXACT WORDS'}),mask=document.createElement('canvas');mask.width=160;mask.height=90;
+ return {async render(clock){const c=mask.getContext('2d');c.fillStyle='black';c.fillRect(0,0,160,90);c.fillStyle='white';c.fillRect(clock.frame*6,20,35,55);title.render(clock.frame/clock.fps,{effect:'spring',hold:10});let sample=mask,channel='luminance';if(clock.frame%2){const d=c.getImageData(0,0,160,90);for(let i=0;irender(dir,path.join(tmp,'bad'),{format:'png',frames:6}),/Required foreground mask missing/);
+ console.log('PASS: every protected interior pixel stays unchanged across all 12 animated frames; missing required data rejects capture.');
+}finally{await fs.rm(tmp,{recursive:true,force:true});}
diff --git a/tests/recovery.test.mjs b/tests/recovery.test.mjs
new file mode 100644
index 0000000..1a65a2c
--- /dev/null
+++ b/tests/recovery.test.mjs
@@ -0,0 +1,57 @@
+import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {spawn} from 'node:child_process';import {pathToFileURL} from 'node:url';import {randomUUID} from 'node:crypto';
+import {init,mutate,editLock} from '../scripts/project.mjs';import {acquireLock,processTable} from '../scripts/lock.mjs';import {recoverJobs} from '../scripts/jobs.mjs';
+const skip=process.platform==='win32'&&'process identity is not available on Windows; nothing is recovered there';
+const url=file=>JSON.stringify(pathToFileURL(path.resolve(import.meta.dirname,file)).href);
+// A real second process that runs `body`, prints one line, then waits to be killed.
+function holder(body,env={}){const child=spawn(process.execPath,['--input-type=module','-e',`${body};console.log('ready');setInterval(()=>{},1<<30)`],{stdio:['ignore','pipe','inherit'],env:{...process.env,...env}});return new Promise(resolve=>child.stdout.once('data',()=>resolve({child,kill:()=>new Promise(done=>{child.once('close',done);child.kill('SIGKILL')})})))}
+const exists=p=>fs.lstat(p).then(()=>true,()=>false);
+
+test('an edit that was killed is taken over once, and its staging directory removed; a live edit is not',{skip},async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-recovery-')),dir=path.join(tmp,'project');
+ try{
+ await init(dir);const assets=path.join(dir,'assets');await fs.mkdir(path.join(assets,'.import-unrelated'),{recursive:true});
+ const h=await holder(`import fs from 'node:fs/promises';import {editLock} from ${url('../scripts/project.mjs')};const lock=await editLock(${JSON.stringify(dir)});await fs.mkdir(${JSON.stringify(assets)}+'/.import-'+lock.id)`);
+ const staged=(await fs.readdir(assets)).filter(n=>/^\.import-\d{12}-/.test(n));assert.equal(staged.length,1);
+ await assert.rejects(mutate(dir,()=>{}),/Another edit is active; retry after it finishes/);
+ await h.kill();
+ // Eight contenders for the dead lock: exactly one takes it; the rest see a live holder.
+ const results=await Promise.allSettled(Array.from({length:8},()=>editLock(dir)));const won=results.filter(r=>r.status==='fulfilled');
+ assert.equal(won.length,1);for(const r of results)if(r.status==='rejected')assert.match(r.reason.message,/Another edit is active/);
+ assert.deepEqual((await fs.readdir(assets)).filter(n=>n.startsWith('.import-')),['.import-unrelated']);
+ await won[0].value.release();assert.equal(await exists(path.join(dir,'.editableframe-edit.lock')),false);
+ await mutate(dir,()=>{});
+ // A lock left by a CLI without owned locks cannot be verified, so it is refused, not broken.
+ await fs.writeFile(path.join(dir,'.editableframe-edit.lock'),'');await assert.rejects(mutate(dir,()=>{}),/without a verifiable owner/);
+ }finally{await fs.rm(tmp,{recursive:true,force:true})}
+});
+
+test('a lock whose owner cannot be proven dead is never taken over',{skip},async()=>{
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-recovery-'));
+ try{
+ const me=(await processTable([process.pid]))[0],record=owner=>fs.writeFile(path.join(dir,'000000000001.json'),JSON.stringify({version:1,gen:1,token:randomUUID(),owner}));
+ for(const owner of [null,{host:'another-machine',ns:null,pid:me.pid,lstart:me.lstart},{host:os.hostname(),ns:null,pid:99999999,lstart:me.lstart},{host:os.hostname(),ns:'pid:[1]',pid:me.pid,lstart:'Thu Jan 1 00:00:00 1970'}]){await record(owner);await assert.rejects(acquireLock(dir),e=>e.code==='ELOCKED'&&/cannot be verified/.test(e.message))}
+ await fs.writeFile(path.join(dir,'000000000001.json'),'not json');await assert.rejects(acquireLock(dir),/cannot be verified/);
+ await fs.writeFile(path.join(dir,'000000000001.released'),'');const lock=await acquireLock(dir);assert.equal(lock.gen,2);await lock.release();
+ }finally{await fs.rm(dir,{recursive:true,force:true})}
+});
+
+test('recovery removes a dead render\'s own directories and unpublished receipt, and nothing else',{skip},async()=>{
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-recovery-')),dir=path.join(tmp,'project'),state=path.join(tmp,'state'),output=path.join(tmp,'out','film.mp4'),saved=process.env.EDITABLEFRAMES_STATE_DIR;
+ process.env.EDITABLEFRAMES_STATE_DIR=state;
+ try{
+ await init(dir);
+ const begin=`import fs from 'node:fs/promises';import {beginJob} from ${url('../scripts/jobs.mjs')};const job=await beginJob(${JSON.stringify(dir)},${JSON.stringify(output)});await fs.mkdir(job.temp,{recursive:true});await fs.writeFile(${JSON.stringify(output)}+'.json',JSON.stringify({job:job.id}))`;
+ const h=await holder(begin,{EDITABLEFRAMES_STATE_DIR:state,TMPDIR:tmp}),[name]=await fs.readdir(path.join(state,'jobs')),job=JSON.parse(await fs.readFile(path.join(state,'jobs',name),'utf8'));
+ assert.equal((await recoverJobs(dir))[0].action,'skipped: owner is running');assert.ok(await exists(job.tmp));
+ await h.kill();
+ // A record whose paths are not this job's own names, and a record planted inside the project, direct nothing.
+ const foreign=path.join(tmp,'keep');await fs.mkdir(foreign);const forged=randomUUID();
+ await fs.writeFile(path.join(state,'jobs',forged+'.json'),JSON.stringify({...job,id:forged,tmp:foreign,output:path.join(tmp,'other.mp4')}));
+ await fs.mkdir(path.join(dir,'.editableframe','jobs'),{recursive:true});await fs.writeFile(path.join(dir,'.editableframe','jobs',randomUUID()+'.json'),JSON.stringify({...job,tmp:foreign}));
+ const [a,b]=await Promise.all([recoverJobs(dir),recoverJobs(dir)]),all=[...a,...b];
+ assert.equal(all.filter(r=>r.action==='recovered').length,1);assert.equal(all.find(r=>r.action==='recovered').receipt,'removed: reserved, never published');
+ assert.ok(all.some(r=>r.job===forged&&r.action==='left: record does not describe this job'));
+ assert.equal(await exists(job.tmp),false);assert.equal(await exists(job.temp),false);assert.equal(await exists(output+'.json'),false);assert.ok(await exists(foreign));
+ assert.deepEqual((await recoverJobs(dir)).map(r=>r.action),['left: record does not describe this job']);
+ }finally{if(saved===undefined)delete process.env.EDITABLEFRAMES_STATE_DIR;else process.env.EDITABLEFRAMES_STATE_DIR=saved;await fs.rm(tmp,{recursive:true,force:true})}
+});
diff --git a/tests/renderer-scheduling.test.mjs b/tests/renderer-scheduling.test.mjs
index 76c18ee..fe53f50 100644
--- a/tests/renderer-scheduling.test.mjs
+++ b/tests/renderer-scheduling.test.mjs
@@ -43,3 +43,38 @@ test('a failed resident is removed and retries create a new instance',async()=>{
await compositor.render(studio,0,options);await assert.rejects(compositor.render(studio,1/30,options),/frame failed/);
assert.equal(stage.children.length,0);assert.equal(disposed,1);await compositor.render(studio,2/30,options);assert.equal(created,2);assert.equal(stage.children.length,1);await compositor.dispose();assert.equal(disposed,2);
});
+
+test('shutter samples carry a fixed media clock through trims, retiming and backward seeks', async () => {
+ const clocks=[];
+ const {compositor,studio,options}=setup({capture:true,render:clock=>clocks.push(clock)});
+ const clip=studio.doc.clips[0];
+ // Clip offsets use document ticks; evaluate both clocks through the same clip mapping.
+ const {HZ}=await import('../packages/core/index.mjs');
+ clip.start=HZ;clip.sourceIn=HZ/2;clip.rate=2;
+ for(const time of [1.49,1.51,1.49])await compositor.render(studio,time,{...options,timeline:true,mediaTime:1.5});
+ assert.deepEqual(clocks.map(c=>c.mediaTime),[1.5,1.5,1.5]);
+ assert.ok(clocks[0].frame {
+ const {createCompositor}=await import('../packages/runtime/compositor.mjs');
+ const {HZ}=await import('../packages/core/index.mjs');
+ const scene=defineRenderer({id:'legacy-clock',renderer:'dom',width:320,height:180,fps:30,durationInFrames:90,create(){}});
+ const d=normalizeClipModule({default:scene}),studio=new Studio(d.templates);
+ const clip=studio.make(scene.id);studio.doc.clips=[clip];clip.start=HZ;clip.sourceIn=HZ/2;clip.rate=2;
+ const context={clearRect(){},save(){},restore(){},translate(){},scale(){},drawImage(){}};
+ const canvas={getContext:()=>context},calls=[],clocks=[],host={portFrame:(port,time)=>calls.push(time)};
+ const compositor=createCompositor(canvas,{templates:d.templates,host,createRenderer(surface,{host:initialHost}){
+ return {render(frame){assert.equal(frame.host,initialHost);clocks.push(frame);
+ frame.host.portFrame(null,frame.mediaTime+.25);return surface;}};
+ }});
+ for(const time of [1.49,1.51,1.49])await compositor.render(studio,time,{timeline:true,mediaTime:1.5});
+ assert.deepEqual(calls,[1.75,1.75,1.75]);assert.ok(clocks[0].time