03:00:0050% OFFClaim

Assemble video shots on an exact integer-frame timeline

Map decoded CFR/VFR sources to per-shot integer-frame budgets, then inspect an actual 22-frame example at 24 fps, its cut images and terminal duration.

Use this offline recipe when several already prepared video shots must occupy an exact number of output frames. It distinguishes source timestamps from the output frame grid and checks the images on both sides of every cut.

The example uses original geometric scenes and a real 22-frame MP4. On 17 October 2026, it was encoded, decoded and checked with Node v24.18.0, FFmpeg 6.0 and ffprobe n4.4.1, alongside three controlled negative artifacts. These are local technical results, not MiniMax H3 outputs; no model generation or provider call was made. Human playback and perceptual review have not been performed.

01. Define the delivery in frames

Write the output frame rate as a rational number, for example 24/1, and assign an integer outputFrames to every shot. The sum must equal expectedTotalFrames. At 24 fps, the recorded 22-frame fixture lasts exactly 11/12 seconds; player rounding is not the acceptance rule. Its three shot budgets are 7, 7 and 8 frames. The two cut boundaries fall between output frames 6/7 and 13/14, using zero-based frame numbers.

For a longer delivery example, 3:24 at 24 fps means 204 seconds and 4,896 output frames. Twenty-five complete eight-second segments consume 4,800 frames, leaving a 96-frame final segment. This is a planning calculation: the inline test encodes only 22 frames, not 204 seconds, and does not show that the longer source clips exist or that a model can generate the full duration in one request.

02. Inspect actual source timestamps

The preparation command creates 25 original PNG inputs and three SVG design sketches. Each raster contains a source-and-frame marker plus a moving geometric element. These original inputs are 8 frames for shot A, 10 for B and 7 for C. Their actual PNG hashes matched before and after the recorded media run.

Encoding and decoding produced inventories of 8, 10 and 8 frames. The variable-rate C source includes the final image repeated by the concat input, so its eighth decoded frame is not a newly drawn 26th input. A was observed at 24000/1001 fps with time base 1/48000; B has 40 ms spacing with time base 1/51200. C starts at 2 seconds and its observed PTS are 2.00, 2.04, 2.12, 2.24, 2.28, 2.36, 2.40, 2.44 seconds.

Keep the raw measurement separate from the presentation rule. In C, ffprobe reported pkt_duration=2048 at time base 1/51200, or 40 ms, for every frame. Some adjacent PTS are 80 or 120 ms apart. The runner preserves those raw packet durations; it does not rewrite them to pretend ffprobe reported the longer intervals. The recorded shot-a.probe.raw.json, shot-b.probe.raw.json and shot-c.probe.raw.json retain the actual stdout bytes and are hash-bound in the decoded inventory.

03. Bind each shot to the source

Each EDL row names a shot ID, source ID, exact source-file SHA-256, a source-relative starting offset and an output-frame budget. The source's first decoded timestamp supplies its origin, so a source starting at two seconds does not add two seconds of blank output.

The declared policy is active-at-or-before-no-interpolation: at each target time, choose the latest source frame whose PTS is no later than that time. For a nonterminal source frame, the effective presentation window is explicitly derived as next observed PTS - current observed PTS. This is a protocol-derived hold window, not an observed packet duration. The terminal frame has no next PTS, so its duration must come from a real, positive duration or pkt_duration observation. Missing or zero duration, non-increasing PTS, an out-of-range interval or a sampled coverage gap fails; average FPS is not a substitute.

Intervals include their start and exclude their end. The rule may repeat or drop images; it does not synthesize motion. Do not silently change speed to make a shot fit. Revise its source interval or output budget deliberately, record the decision, then rebuild the map. Use shot identity and file binding when a file is attached to the wrong shot.

04. Prepare inputs without encoding video

Save all nine complete .mjs files shown below, with their displayed filenames, in one empty local folder. Run these commands from that folder:

node --test frame-budget.test.mjs encoded-negative-cases.test.mjs
node run-recipe.mjs --out ./new-original-inputs

The output directory must not already exist. The preparation command draws the original raster inputs and writes a status with mediaExecuted:false. That remains the correct default behavior even though the separately recorded run below executed media. It makes no network request, submits no model task and creates no encoded video. The inline logic and preparation tests are useful checks, but a passing pure test is not itself an encoder receipt.

05. Read the recorded run or execute a fresh one

The historical run of 17 October 2026 had the following recorded observations. Its media-execution-receipt.json is dated 2026-10-17T01:33:47.353Z. Its command-log.json records 48 successful tool events. The run produced a 22-frame positive output, checked both cuts and all 22 source/frame markers, and exercised the three actual negative cases below. The output is assembled-review.mp4, with SHA-256:

3b624e031f6a082e2ac2ae89b8c36cb91873bd67c5d64f8c5fa1427059db96f1

After the fresh execution command below completes, inspect the raw source probes, decoded inventory, EDL, frame map, marker proof and output probe in new-media-run/ beside its MP4. Its command log records the new tool calls, while runtime-source-binding.json identifies the executed source files. Keep these newly created records with the result; the historical hash above identifies only the older example output.

For a fresh run, use a different, nonexistent output directory and existing local tools:

ALLOW_LOCAL_MEDIA_EXECUTION=1 node run-recipe.mjs --out ./new-media-run --execute-media --ffmpeg /absolute/path/to/ffmpeg --ffprobe /absolute/path/to/ffprobe

The explicit switch enables local media execution. The script uses 96×64 inputs, serial tool calls, single-thread settings, process timeouts and bounded buffers. It encodes the sources, reads their decoded timestamps and real hashes, checks selected markers against the original input definition, then assembles the 22-frame MP4 and tests three small negative artifacts. The observed tool versions are one tested configuration, not a promise that every FFmpeg build supports it. Missing filters or FFV1/libx264 capabilities fail; the command does not install tools or call an external service.

This command never encodes a 204-second fixture. A full-length benchmark needs a separate actual run and receipt.

06. Check the decoded artifact and its negative controls

Acceptance of this small technical fixture requires the decoded frame count to equal the budget, all PTS to lie on the declared CFR grid, and every source/frame marker to match its planned output position. The recorded positive output met those checks at 24 fps with duration 11/12 seconds. A correct duration alone would not establish that a cut uses the correct image.

Keep the source hashes, raw probes, decoded inventory, EDL, full frame map, original-marker proof and complete encoder/probe commands alongside the output. Raw probes and the inventory/EDL are saved before planning, so a failed plan can retain diagnostic facts without receiving a success receipt. Positive and negative observations use the same validator, including actual packet PTS, DTS and duration.

Frame indices are zero-based: index 7 is the eighth image and index 21 is the last. All three negative artifacts were actually encoded or mutated, decoded and probed in the recorded run. Each produced exactly its expected issue and no second validator defect:

Recorded artifact Controlled difference Observed sole rejection
negative-media/short-21-of-22.mp4 21 decoded images, frame observations and packets instead of 22 OUTPUT_FRAME_COUNT
negative-media/wrong-cut-image.mp4 Still 22 frames on the same grid; image at zero-based frame 7 is wrong OUTPUT_FRAME_ID_MISMATCH at frame 7
negative-media/bad-terminal-duration.mp4 Same 22 images, PTS and encoded sample bytes; terminal duration halves OUTPUT_TERMINAL_DURATION at frame 21

For the last case, the code changes actual MP4 sample timing bytes rather than probe JSON. It accepts only the fixture's one-video-track, nonfragmented, no-edit-list layout, with final moov after mdat, no composition reordering, a 24,000 media time scale and 1,000 ticks per normal frame. It keeps 21 normal samples and changes the terminal duration to 500 ticks, updates container durations and preserves media data. The recorded observations contain 22 frames and packets on each side. All positive durations and the first 21 negative durations are 1,000 ticks; the negative terminal frame and packet each report 500 ticks. Packet locations, all PTS/DTS and all 22 encoded sample payload hashes remain equal. Missing, invalid or zero durations would fail observation rather than pass the negative.

Encoder failure, failed probing, an unsupported container or an unexpected validator issue cannot count as a successful negative. The default preparation-only command lists these cases as planned; the separate recorded media run contains their executed results. Timing and marker checks do not establish whether a creative cut looks right: inspect your own footage for motion, lighting and narrative continuity.

If a source has an abrupt pose or lighting jump, exact frame assembly preserves that jump. To inspect a particular frame, use frame selection by timestamp. For still-image inputs, use the existing PNG sequence recipe.

07. Keep the task boundary clear

Use this recipe for timing and cut identity after clips exist. For planning separate shots, browse the workflow library. Record creative decisions and accepted clip versions in a shot manifest before assembling the frame timeline. Correct frame assembly preserves the images you supply, including any unwanted visual jump.

The original code license is reproduced below. Use existing local FFmpeg and ffprobe executables. Technical references: FFmpeg concat, fps and setpts. Compare the stated historical observations with the measurements produced by your run; a command documented by FFmpeg is not proof of your own export.

Complete source and input construction

Save every file below with its exact filename in the same folder. The source includes the input definitions and construction logic; code blocks are complete, including all companion modules.

LICENSE.txt

MIT License

Copyright (c) 2026 MiniMax H3 Studio

Permission is hereby granted, free of charge, to any person obtaining a copy
of this original fixture code, input definitions and generated synthetic media
(the "Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies, and to permit persons to whom the Materials
are furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Materials.

THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
MATERIALS.

This notice covers only the newly authored local source files and synthetic
fixtures. No FFmpeg binary, third-party library, font, model output or creator
media is included or relicensed. Documentation links retain their own terms.

decoded-output-validator.mjs

/** Shared positive/negative checks over supplied actual decoded observations. */
import {rat,compare,frameTime} from './frame-budget.mjs';
import {WIDTH,HEIGHT,readMarker} from './original-inputs.mjs';
export class DecodedOutputValidationError extends Error {
  constructor(issues){super(issues.map(x=>x.code).join(','));this.name='DecodedOutputValidationError';this.code=issues[0]?.code;this.issues=issues;}
}
export function validateDecodedOutput({plan,probe,rgb,expectedMarkers}){
  const issues=[],add=(code,detail={})=>issues.push({code,...detail});
  if(plan?.totalFrames!==22||plan.targetFps!=='24/1'||!Array.isArray(expectedMarkers)||expectedMarkers.length!==22||expectedMarkers.some(x=>!Number.isInteger(x)||x<0||x>255))throw new Error('FIXED_22_FRAME_CONTRACT_REQUIRED');
  const stream=probe?.streams?.[0],frames=probe?.frames,packets=probe?.packets;
  if(!stream||!Array.isArray(frames)||!Array.isArray(packets)||!Buffer.isBuffer(rgb))throw new DecodedOutputValidationError([{code:'OUTPUT_PROBE_SCHEMA'}]);
  if(stream.width!==WIDTH||stream.height!==HEIGHT)add('OUTPUT_DIMENSIONS');
  const stride=WIDTH*HEIGHT*3,pixelFrames=rgb.length/stride;
  if(!Number.isInteger(pixelFrames)||pixelFrames!==22||frames.length!==22||packets.length!==22)add('OUTPUT_FRAME_COUNT',{expected:22,pixelFrames,probeFrames:frames.length,packetFrames:packets.length});
  let timebase;try{timebase=rat(stream.time_base);if(timebase[0]<=0n)throw new Error('TIMEBASE');}catch{add('OUTPUT_TIMEBASE');}
  const present=Math.min(Math.floor(pixelFrames),frames.length,packets.length,22);
  for(let i=0;i<present;i++){
    const f=frames[i],packet=packets[i];
    if(!/^-?\d{1,20}$/.test(String(f.best_effort_timestamp)))add('OUTPUT_PTS_MISSING',{frame:i});
    else if(timebase&&compare([BigInt(f.best_effort_timestamp)*timebase[0],timebase[1]],frameTime(i,rat('24/1')))!==0)add('OUTPUT_CFR_GRID',{frame:i});
    if(!/^-?\d{1,20}$/.test(String(packet.pts))||! /^-?\d{1,20}$/.test(String(packet.dts)))add('OUTPUT_PACKET_TIMESTAMPS',{frame:i});
    else{if(packet.pts.toString()!==packet.dts.toString())add('OUTPUT_PTS_DTS_REORDER',{frame:i});if(timebase&&compare([BigInt(packet.pts)*timebase[0],timebase[1]],frameTime(i,rat('24/1')))!==0)add('OUTPUT_PACKET_CFR_GRID',{frame:i});}
    const frame=rgb.subarray(i*stride,(i+1)*stride);let readable=true;
    for(let bit=0;bit<8;bit++){const p=(8*WIDTH+8+bit*8)*3,v=(frame[p]+frame[p+1]+frame[p+2])/3;if(v>56&&v<200)readable=false;}
    if(!readable)add('OUTPUT_MARKER_NOT_READABLE',{frame:i});
    const marker=readMarker(frame);if(marker!==expectedMarkers[i])add('OUTPUT_FRAME_ID_MISMATCH',{frame:i,expected:expectedMarkers[i],actual:marker});
    const duration=f.duration??f.pkt_duration;
    if(!/^\d{1,20}$/.test(String(duration))||!/^\d{1,20}$/.test(String(packet.duration))||!timebase||compare([BigInt(duration)*timebase[0],timebase[1]],frameTime(1,rat('24/1')))!==0||compare([BigInt(packet.duration)*timebase[0],timebase[1]],frameTime(1,rat('24/1')))!==0)add(i===21?'OUTPUT_TERMINAL_DURATION':'OUTPUT_FRAME_DURATION',{frame:i,expectedDuration:'1/24',frameDuration:duration===undefined?null:String(duration),packetDuration:packet.duration===undefined?null:String(packet.duration),timeBase:stream.time_base});
  }
  if(issues.length)throw new DecodedOutputValidationError(issues);
  return {valid:true,framesChecked:22,cutsChecked:plan.cuts.length,duration:'11/12',evidenceScope:'supplied decoded bytes and probe metadata; caller binds actual tool execution and artifact hashes',markers:expectedMarkers};
}

encoded-negative-cases.mjs

/** Actual small encoded negatives; only shared-validator rejections can pass. */
import {mkdir,copyFile,readFile,writeFile} from 'node:fs/promises';
import {join} from 'node:path';
import {hashBytes,rat,compare} from './frame-budget.mjs';
import {DecodedOutputValidationError,validateDecodedOutput} from './decoded-output-validator.mjs';
import {patchTerminalSampleDuration} from './mp4-terminal-duration.mjs';
const ensure=(ok,code)=>{if(!ok)throw new Error(code);};
export function negativeCaseSchedule(){return [{id:'short-21-of-22',expectedCode:'OUTPUT_FRAME_COUNT',expectedDecodedFrames:21},{id:'wrong-cut-image',expectedCode:'OUTPUT_FRAME_ID_MISMATCH',expectedFrame:7},{id:'bad-terminal-duration',expectedCode:'OUTPUT_TERMINAL_DURATION',expectedFrame:21,expectedTerminalTicks:'500',expectedTimeBase:'1/24000'}];}
function terminalTimingObservations(positiveObservation,negativeObservation){
  const observed={};
  for(const [label,o] of [['positive',positiveObservation],['negative',negativeObservation]]){
    const probe=o?.probe,frames=probe?.frames,packets=probe?.packets;
    ensure(frames?.length===22&&packets?.length===22,'NEGATIVE_TERMINAL_OBSERVATION_INVALID:'+label+':count');
    let validTimeBase=false;try{validTimeBase=compare(rat(probe.streams[0].time_base),rat('1/24000'))===0;}catch{}
    ensure(validTimeBase,'NEGATIVE_TERMINAL_OBSERVATION_INVALID:'+label+':timebase');
    const durations=[];
    for(let i=0;i<22;i++){
      const frameDuration=frames[i].duration??frames[i].pkt_duration,packetDuration=packets[i].duration,expected=label==='negative'&&i===21?'500':'1000';
      // Missing/invalid/zero durations describe an incomplete observation, not the intended encoded defect.
      ensure(/^\d{1,20}$/.test(String(frameDuration))&&/^\d{1,20}$/.test(String(packetDuration))&&BigInt(frameDuration)===BigInt(expected)&&BigInt(packetDuration)===BigInt(expected),'NEGATIVE_TERMINAL_OBSERVATION_INVALID:'+label+':duration:'+i);
      durations.push({frame:i,frameDuration:String(frameDuration),packetDuration:String(packetDuration)});
    }
    observed[label]={timeBase:probe.streams[0].time_base,durations};
  }
  return observed;
}
export function evaluateNegativeObservation(spec,observation,{positiveObservation}={}){
  const timingObservations=spec.expectedTerminalTicks!==undefined?terminalTimingObservations(positiveObservation,observation):null;
  try{validateDecodedOutput(observation);}catch(error){
    if(!(error instanceof DecodedOutputValidationError))throw error;
    const issue=error.issues[0];
    const exactCount=spec.expectedDecodedFrames===undefined||(issue.pixelFrames===spec.expectedDecodedFrames&&issue.probeFrames===spec.expectedDecodedFrames&&issue.packetFrames===spec.expectedDecodedFrames);
    let exactTerminal=true;if(spec.expectedTerminalTicks!==undefined){try{exactTerminal=String(observation.probe.packets[21].duration)===spec.expectedTerminalTicks&&compare(rat(observation.probe.streams[0].time_base),rat(spec.expectedTimeBase))===0;}catch{exactTerminal=false;}}
    const exact=error.issues.length===1&&issue.code===spec.expectedCode&&(spec.expectedFrame===undefined||issue.frame===spec.expectedFrame)&&exactCount&&exactTerminal;
    ensure(exact,'WRONG_NEGATIVE_REJECTION_REASON:'+spec.id+':'+error.issues.map(x=>x.code).join(','));
    return {id:spec.id,validatorIssues:error.issues,expectedRejectionObserved:true,...(timingObservations?{timingObservations}:{}),evidenceScope:'supplied decoded observation only; does not authenticate media/tool execution'};
  }
  throw new Error('NEGATIVE_CASE_NOT_REJECTED:'+spec.id);
}
export async function executeEncodedNegativeCases({executeMedia=false,out,framesDir,positiveOutput,plan,expectedMarkers,positiveObservation,encode,observe}){
  if(!executeMedia)return {executed:false,certified:false,cases:negativeCaseSchedule().map(s=>({...s,status:'planned'}))};
  ensure(process.env.ALLOW_LOCAL_MEDIA_EXECUTION==='1','MEDIA_EXECUTION_REQUIRES_RESOURCE_APPROVAL');
  ensure(plan?.totalFrames===22&&plan.targetFps==='24/1'&&expectedMarkers?.length===22,'FIXED_22_FRAME_CONTRACT_REQUIRED');
  const root=join(out,'negative-media');await mkdir(root);const results=[];
  for(const spec of negativeCaseSchedule()){
    let artifact,mutation=null;
    try{
      if(spec.id==='short-21-of-22'){artifact=join(root,'short-21-of-22.mp4');await encode(framesDir,21,artifact);}
      else if(spec.id==='wrong-cut-image'){
        const dir=join(root,'wrong-cut-frames');await mkdir(dir);
        for(let i=0;i<22;i++)await copyFile(join(framesDir,`frame-${String(i===7?6:i).padStart(4,'0')}.png`),join(dir,`frame-${String(i).padStart(4,'0')}.png`));
        artifact=join(root,'wrong-cut-image.mp4');await encode(dir,22,artifact);
      }else{artifact=join(root,'bad-terminal-duration.mp4');const patched=patchTerminalSampleDuration(await readFile(positiveOutput));await writeFile(artifact,patched.bytes,{flag:'wx'});mutation=patched.mutation;}
      const decoded=await observe(artifact);
      if(spec.id==='bad-terminal-duration'){
        const before=await readFile(positiveOutput),after=await readFile(artifact),a=positiveObservation?.probe?.packets,b=decoded.probe?.packets;
        ensure(a?.length===22&&b?.length===22,'TERMINAL_PACKET_COUNT');const payloadHashes=[];
        for(let i=0;i<22;i++){
          const pos=Number(a[i].pos),size=Number(a[i].size);ensure(Number.isSafeInteger(pos)&&Number.isSafeInteger(size)&&pos>=0&&size>0&&pos+size<=before.length&&pos+size<=after.length,'TERMINAL_PACKET_BOUNDS');
          ensure(String(a[i].pos)===String(b[i].pos)&&String(a[i].size)===String(b[i].size),'TERMINAL_PACKET_LOCATION_CHANGED');
          const hash=hashBytes(before.subarray(pos,pos+size));ensure(hash===hashBytes(after.subarray(pos,pos+size)),'TERMINAL_SAMPLE_PAYLOAD_CHANGED');payloadHashes.push(hash);
        }
        mutation.unchangedEncodedSamplePayloadSha256=payloadHashes;
      }
      const checked=evaluateNegativeObservation(spec,{plan,expectedMarkers,...decoded},{positiveObservation});
      results.push({...checked,artifact:artifact.split('/').at(-1),artifactSha256:hashBytes(await readFile(artifact)),mutation});
      await writeFile(join(root,spec.id+'.probe.json'),JSON.stringify(decoded.probe,null,2)+'\n',{flag:'wx'});
    }catch(error){
      // A failed encoder/probe or unsupported MP4 layout is not an accepted negative.
      if(error.message.startsWith('WRONG_NEGATIVE_REJECTION_REASON:')||error.message.startsWith('NEGATIVE_CASE_NOT_REJECTED:'))throw error;
      throw new Error('NEGATIVE_MEDIA_TOOL_OR_LAYOUT_FAILURE:'+spec.id+':'+error.message,{cause:error});
    }
  }
  const receipt={schemaVersion:1,executed:true,certified:false,executedAt:new Date().toISOString(),cases:results,scope:'three actual bounded encoded artifacts rejected by the same decoded-output validator; independent QA remains pending'};
  await writeFile(join(root,'negative-media-receipt.json'),JSON.stringify(receipt,null,2)+'\n',{flag:'wx'});return receipt;
}

encoded-negative-cases.test.mjs

import test from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp,rm,access} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
import {markerRgb,WIDTH,HEIGHT} from './original-inputs.mjs';
import {DecodedOutputValidationError,validateDecodedOutput} from './decoded-output-validator.mjs';
import {negativeCaseSchedule,evaluateNegativeObservation,executeEncodedNegativeCases} from './encoded-negative-cases.mjs';
import {patchTerminalSampleDuration} from './mp4-terminal-duration.mjs';
const stride=WIDTH*HEIGHT*3;
function observation(){
 const rgbs=Array.from({length:22},(_,i)=>markerRgb(i<7?0:i<14?1:2,i<7?i:i<14?i-7:Math.floor((i-14)/2)));
 const expectedMarkers=Array.from({length:22},(_,i)=>(i<7?32:i<14?64:96)+(i<7?i:i<14?i-7:Math.floor((i-14)/2)));
 return{plan:{totalFrames:22,targetFps:'24/1',cuts:[{before:6,after:7},{before:13,after:14}]},expectedMarkers,rgb:Buffer.concat(rgbs),probe:{streams:[{time_base:'1/24000',width:96,height:64}],frames:Array.from({length:22},(_,i)=>({best_effort_timestamp:String(i*1000),pkt_duration:'1000'})),packets:Array.from({length:22},(_,i)=>({pts:String(i*1000),dts:String(i*1000),duration:'1000',pos:String(16+i*2),size:'2'}))}};
}
function expectCode(fn,code){assert.throws(fn,error=>error instanceof DecodedOutputValidationError&&error.issues.length===1&&error.issues[0].code===code);}
test('one shared validator accepts the complete 22-frame decoded-data contract without certifying execution',()=>{const checked=validateDecodedOutput(observation());assert.equal(checked.framesChecked,22);assert.match(checked.evidenceScope,/supplied decoded/);assert.equal(checked.executed,undefined);});
test('a complete 21-frame decode yields only frame-count rejection, not a decoder failure',()=>{const o=observation();o.rgb=o.rgb.subarray(0,21*stride);o.probe.frames.pop();o.probe.packets.pop();const checked=evaluateNegativeObservation(negativeCaseSchedule()[0],o);assert.equal(checked.validatorIssues[0].code,'OUTPUT_FRAME_COUNT');assert.match(checked.evidenceScope,/does not authenticate/);});
test('wrong image at the first cut is rejected despite identical count and PTS',()=>{const o=observation();o.rgb.copy(o.rgb,7*stride,6*stride,7*stride);const x=evaluateNegativeObservation(negativeCaseSchedule()[1],o);assert.deepEqual(x.validatorIssues.map(v=>[v.code,v.frame]),[['OUTPUT_FRAME_ID_MISMATCH',7]]);});
test('short terminal duration is distinct from a wrong PTS or wrong image',()=>{const o=observation();o.probe.frames[21].pkt_duration='500';o.probe.packets[21].duration='500';assert.equal(evaluateNegativeObservation(negativeCaseSchedule()[2],o,{positiveObservation:observation()}).validatorIssues[0].frame,21);});
test('actual packet duration alone can expose the container terminal defect',()=>{const o=observation();o.probe.packets[21].duration='500';expectCode(()=>validateDecodedOutput(o),'OUTPUT_TERMINAL_DURATION');});
test('a second defect prevents acceptance as the intended negative',()=>{const o=observation();o.rgb.copy(o.rgb,7*stride,6*stride,7*stride);o.probe.frames[21].pkt_duration='500';assert.throws(()=>evaluateNegativeObservation(negativeCaseSchedule()[1],o),/WRONG_NEGATIVE_REJECTION_REASON/);const short=observation();short.rgb=short.rgb.subarray(0,20*stride);short.probe.frames.length=20;short.probe.packets.length=20;assert.throws(()=>evaluateNegativeObservation(negativeCaseSchedule()[0],short),/WRONG_NEGATIVE_REJECTION_REASON/);const terminal=observation();terminal.probe.frames[21].pkt_duration='499';terminal.probe.packets[21].duration='499';assert.throws(()=>evaluateNegativeObservation(negativeCaseSchedule()[2],terminal,{positiveObservation:observation()}),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/);});
test('nonzero PTS/DTS reordering is rejected independently',()=>{const o=observation();o.probe.packets[5].dts='4000';expectCode(()=>validateDecodedOutput(o),'OUTPUT_PTS_DTS_REORDER');});
test('unknown last duration and missing packet observations cannot become a successful negative',()=>{const o=observation();delete o.probe.frames[21].pkt_duration;expectCode(()=>validateDecodedOutput(o),'OUTPUT_TERMINAL_DURATION');const p=observation();delete p.probe.packets;expectCode(()=>validateDecodedOutput(p),'OUTPUT_PROBE_SCHEMA');});
test('no-execute scheduling invokes neither encoder nor probe and is not certified',async()=>{let calls=0;const x=await executeEncodedNegativeCases({encode:()=>calls++,observe:()=>calls++});assert.equal(calls,0);assert.equal(x.executed,false);assert.equal(x.certified,false);assert.equal(x.cases.length,3);assert(x.cases.every(c=>c.status==='planned'));});
test('a validator-accepted candidate is never counted as a successful negative',()=>{assert.throws(()=>evaluateNegativeObservation(negativeCaseSchedule()[0],observation()),/NEGATIVE_CASE_NOT_REJECTED/);});
test('an encoder/tool error is not converted to expected rejection',async()=>{const dir=await mkdtemp(join(tmpdir(),'pseo-negative-tool-failure-')),before=process.env.ALLOW_LOCAL_MEDIA_EXECUTION;try{process.env.ALLOW_LOCAL_MEDIA_EXECUTION='1';const o=observation();await assert.rejects(executeEncodedNegativeCases({executeMedia:true,out:dir,plan:o.plan,expectedMarkers:o.expectedMarkers,encode:()=>{throw new Error('SIMULATED_ENOENT');}}),/NEGATIVE_MEDIA_TOOL_OR_LAYOUT_FAILURE:short-21-of-22:SIMULATED_ENOENT/);await assert.rejects(access(join(dir,'negative-media/negative-media-receipt.json')));}finally{if(before===undefined)delete process.env.ALLOW_LOCAL_MEDIA_EXECUTION;else process.env.ALLOW_LOCAL_MEDIA_EXECUTION=before;await rm(dir,{recursive:true,force:true});}});
function box(type,data=Buffer.alloc(0)){const h=Buffer.alloc(8);h.writeUInt32BE(data.length+8);h.write(type,4,4,'ascii');return Buffer.concat([h,data]);}
function containerFixture({edits=false,cttsOffset=null,moovFirst=false,afterMoov=false,fragment=false}={}){
 const stts=Buffer.alloc(16);stts.writeUInt32BE(1,4);stts.writeUInt32BE(22,8);stts.writeUInt32BE(1000,12);
 const stsz=Buffer.alloc(12+22*4);stsz.writeUInt32BE(22,8);for(let i=0;i<22;i++)stsz.writeUInt32BE(2,12+i*4);
 const co=Buffer.alloc(12);co.writeUInt32BE(1,4);co.writeUInt32BE(16,8);
 const ctts=Buffer.alloc(16);ctts.writeUInt32BE(1,4);ctts.writeUInt32BE(22,8);if(cttsOffset!==null)ctts.writeUInt32BE(cttsOffset,12);
 const mdhd=Buffer.alloc(24);mdhd.writeUInt32BE(24000,12);mdhd.writeUInt32BE(22000,16);
 const mvhd=Buffer.alloc(20);mvhd.writeUInt32BE(1000,12);mvhd.writeUInt32BE(917,16);
 const tkhd=Buffer.alloc(24);tkhd.writeUInt32BE(917,20);const hdlr=Buffer.alloc(12);hdlr.write('vide',8,4,'ascii');
 const stbl=box('stbl',Buffer.concat([box('stts',stts),box('stsz',stsz),box('stsc',Buffer.alloc(8)),box('stco',co),...(cttsOffset===null?[]:[box('ctts',ctts)])]));
 const track=box('trak',Buffer.concat([box('tkhd',tkhd),...(edits?[box('edts')]:[]),box('mdia',Buffer.concat([box('mdhd',mdhd),box('hdlr',hdlr),box('minf',stbl)]))]));
 const moov=box('moov',Buffer.concat([box('mvhd',mvhd),track])),mdat=box('mdat',Buffer.from(Array.from({length:44},(_,i)=>i)));
 return Buffer.concat([box('ftyp'),...(fragment?[box('moof')]:[]),...(moovFirst?[moov,mdat]:[mdat,moov]),...(afterMoov?[box('free')]:[])]);
}
test('bounded container mutation preserves mdat and shifts only the final sample duration table',()=>{const input=containerFixture(),x=patchTerminalSampleDuration(input),b=x.bytes,tag=b.indexOf(Buffer.from('stts'));assert.equal(b.length,input.length+8);assert.equal(b.readUInt32BE(tag+8),2);assert.deepEqual([b.readUInt32BE(tag+12),b.readUInt32BE(tag+16),b.readUInt32BE(tag+20),b.readUInt32BE(tag+24)],[21,1000,1,500]);assert.equal(b.readUInt32BE(b.indexOf(Buffer.from('mdhd'))+20),21500);assert.equal(b.readUInt32BE(b.indexOf(Buffer.from('mvhd'))+20),896);assert.deepEqual(input.subarray(input.indexOf(Buffer.from('mdat'))+4,input.indexOf(Buffer.from('mdat'))+48),b.subarray(b.indexOf(Buffer.from('mdat'))+4,b.indexOf(Buffer.from('mdat'))+48));assert.match(x.mutation.evidenceScope,/decoded rejection still requires/);});
for(const[name,options,code]of[['edit lists',{edits:true},/MP4_UNSUPPORTED_EDIT_OR_FRAGMENT/],['fragment',{fragment:true},/MP4_UNSUPPORTED_EDIT_OR_FRAGMENT/],['faststart',{moovFirst:true},/MP4_REQUIRES_FINAL_MOOV_AFTER_MDAT/],['trailing boxes',{afterMoov:true},/MP4_REQUIRES_FINAL_MOOV_AFTER_MDAT/],['composition reorder',{cttsOffset:1000},/MP4_COMPOSITION_REORDER/]])test('unsupported '+name+' is a failure, not a generic repair',()=>{assert.throws(()=>patchTerminalSampleDuration(containerFixture(options)),code);});
test('a nonfragmented explicit zero composition offset is supported',()=>{assert.equal(patchTerminalSampleDuration(containerFixture({cttsOffset:0})).mutation.samples,22);});
test('truncated atom and unsupported extended box size are rejected',()=>{assert.throws(()=>patchTerminalSampleDuration(containerFixture().subarray(0,-1)),/MP4_BOX_SIZE/);const b=containerFixture();b.writeUInt32BE(1);assert.throws(()=>patchTerminalSampleDuration(b),/MP4_BOX_SIZE/);});
test('the default CLI prepares originals and plans all three cases without media execution',async()=>{const dir=await mkdtemp(join(tmpdir(),'pseo-default-preparation-'));try{const raw=execFileSync(process.execPath,[fileURLToPath(new URL('./run-recipe.mjs',import.meta.url)),'--out',join(dir,'prepared')],{timeout:10000,maxBuffer:64*1024});const x=JSON.parse(raw);assert.equal(x.mediaExecuted,false);assert.equal(x.negativeMedia.executed,false);assert.equal(x.negativeMedia.certified,false);await assert.rejects(access(join(dir,'prepared','command-log.json')));await assert.rejects(access(join(dir,'prepared','media-execution-receipt.json')));}finally{await rm(dir,{recursive:true,force:true});}});

test('terminal negative requires complete actual positive and negative frame/packet durations, not just a shared issue code',()=>{
 const spec=negativeCaseSchedule()[2],negative=()=>{const o=observation();o.probe.frames[21].pkt_duration='500';o.probe.packets[21].duration='500';return o;};
 for(const label of ['positive','negative'])for(const field of ['frame','packet'])for(const invalid of [undefined,'not-an-integer','0','499']){
   const positive=observation(),bad=negative(),target=(label==='positive'?positive:bad).probe;
   if(field==='frame'){delete target.frames[21].pkt_duration;if(invalid!==undefined)target.frames[21].pkt_duration=invalid;}
   else{delete target.packets[21].duration;if(invalid!==undefined)target.packets[21].duration=invalid;}
   assert.throws(()=>evaluateNegativeObservation(spec,bad,{positiveObservation:positive}),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/,label+' '+field+' '+String(invalid));
 }
 const bad=negative();delete bad.probe.frames[21].pkt_duration;expectCode(()=>validateDecodedOutput(bad),'OUTPUT_TERMINAL_DURATION');
 assert.throws(()=>evaluateNegativeObservation(spec,bad,{positiveObservation:observation()}),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/);
 assert.throws(()=>evaluateNegativeObservation(spec,negative()),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/);
 const positive=observation();positive.probe.packets.pop();assert.throws(()=>evaluateNegativeObservation(spec,negative(),{positiveObservation:positive}),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/);
 const earlier=negative();earlier.probe.packets[0].duration='500';assert.throws(()=>evaluateNegativeObservation(spec,earlier,{positiveObservation:observation()}),/NEGATIVE_TERMINAL_OBSERVATION_INVALID/);
 const checked=evaluateNegativeObservation(spec,negative(),{positiveObservation:observation()});
 assert.equal(checked.timingObservations.positive.durations[21].packetDuration,'1000');assert.equal(checked.timingObservations.negative.durations[21].frameDuration,'500');
 assert.equal(checked.validatorIssues[0].packetDuration,'500');assert.equal(checked.validatorIssues[0].expectedDuration,'1/24');
});

frame-budget.mjs

/** Exact planning over already decoded timestamps; never infers model capability. */
import { createHash } from 'node:crypto';
const ensure = (condition, code) => { if (!condition) throw new Error(code); };
const gcd = (a,b) => b === 0n ? (a < 0n ? -a : a) : gcd(b,a%b);
const bounded = (n) => { ensure(n >= -(1n<<100n) && n <= (1n<<100n), 'RATIONAL_RANGE'); return n; };
export function rat(value) {
  ensure(typeof value === 'string' && /^-?\d{1,20}\/[1-9]\d{0,19}$/.test(value), 'RATIONAL_SYNTAX');
  let [n,d] = value.split('/').map(BigInt); const g = gcd(n,d); n/=g;d/=g;return [bounded(n),bounded(d)];
}
const simplify = (n,d) => { ensure(d>0n,'RATIONAL_DENOMINATOR'); const g=gcd(n,d);return [bounded(n/g),bounded(d/g)]; };
export const add = (a,b) => simplify(a[0]*b[1]+b[0]*a[1],a[1]*b[1]);
export const sub = (a,b) => simplify(a[0]*b[1]-b[0]*a[1],a[1]*b[1]);
export const compare = (a,b) => a[0]*b[1] < b[0]*a[1] ? -1 : a[0]*b[1] > b[0]*a[1] ? 1 : 0;
export const str = (a) => `${a[0]}/${a[1]}`;
export const frameTime = (index,fps) => simplify(BigInt(index)*fps[1],fps[0]);
export const hashBytes = (b) => createHash('sha256').update(b).digest('hex');
export const safeName = (s) => typeof s === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(s) && !s.includes('..');
const hex = (s) => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s);
const id = (s) => typeof s === 'string' && /^[a-z][a-z0-9-]{0,59}$/.test(s);
const integer = (n,min,max) => Number.isSafeInteger(n)&&n>=min&&n<=max;
export function planFrameBudget(edl, inventory, {allowSyntheticTiming=false}={}) {
  ensure(edl?.schemaVersion===1 && edl.sampling==='active-at-or-before-no-interpolation','EDL_SCHEMA');
  ensure(inventory?.schemaVersion===1 && Array.isArray(inventory.sources)&&inventory.sources.length>=1&&inventory.sources.length<=8,'INVENTORY_SCHEMA');
  const actual = inventory.evidenceKind==='decoded-media-inventory';
  ensure(actual || (allowSyntheticTiming && inventory.evidenceKind==='synthetic-timing-definition'),'DECODED_INVENTORY_REQUIRED');
  const fps=rat(edl.targetFps);ensure(compare(fps,rat('1/1'))>=0&&compare(fps,rat('60/1'))<=0,'FPS_RANGE');
  ensure(integer(edl.expectedTotalFrames,1,12000),'TOTAL_FRAME_LIMIT');
  ensure(Array.isArray(edl.shots)&&edl.shots.length>=1&&edl.shots.length<=64,'SHOT_LIMIT');
  const sources=new Map();
  for(const s of inventory.sources){
    ensure(id(s.id)&&!sources.has(s.id)&&safeName(s.file)&&hex(s.sha256),'SOURCE_BINDING');
    ensure(integer(s.width,16,1920)&&integer(s.height,16,1080)&&s.width*s.height<=2073600,'SOURCE_DIMENSIONS');
    ensure(Array.isArray(s.frames)&&s.frames.length>=1&&s.frames.length<=12000,'SOURCE_FRAME_LIMIT');
    let last=null;const frames=[];
    for(const [i,f] of s.frames.entries()){
      ensure(f.index===i&&safeName(f.file)&&hex(f.sha256),'FRAME_BINDING');const pts=rat(f.pts),duration=rat(f.duration);
      ensure(compare(duration,rat('0/1'))>0 && (!last||compare(pts,last)>0),'NON_MONOTONIC_PTS');
      frames.push({...f,p:pts,d:duration});last=pts;
    }
    sources.set(s.id,{...s,frames,origin:frames[0].p,end:add(frames.at(-1).p,frames.at(-1).d)});
  }
  const seen=new Set(),mapping=[],shots=[];let out=0;
  for(const shot of edl.shots){
    ensure(id(shot.id)&&!seen.has(shot.id),'DUPLICATE_SHOT_ID');seen.add(shot.id);
    ensure(integer(shot.outputFrames,1,12000)&&sources.has(shot.sourceId),'SHOT_SOURCE_OR_BUDGET');
    const s=sources.get(shot.sourceId);ensure(shot.sourceSha256===s.sha256,'SOURCE_HASH_MISMATCH');
    const offset=rat(shot.sourceIn);ensure(compare(offset,rat('0/1'))>=0,'SOURCE_IN_NEGATIVE');
    const start=add(s.origin,offset),end=add(start,frameTime(shot.outputFrames,fps));
    ensure(compare(start,s.origin)>=0&&compare(end,s.end)<=0,'SOURCE_RANGE_OUT_OF_BOUNDS');
    ensure(out+shot.outputFrames<=12000,'TOTAL_FRAME_LIMIT');let cursor=0;
    for(let j=0;j<shot.outputFrames;j++){
      const wanted=add(start,frameTime(j,fps));
      while(cursor+1<s.frames.length&&compare(s.frames[cursor+1].p,wanted)<=0)cursor++;
      const f=s.frames[cursor];ensure(compare(f.p,wanted)<=0&&compare(wanted,add(f.p,f.d))<0,'SOURCE_PTS_GAP');
      mapping.push({outputFrame:out+j,outputPts:str(frameTime(out+j,fps)),shotId:shot.id,sourceId:s.id,sourceFrame:f.index,sourcePts:f.pts,sourceFrameFile:f.file,sourceFrameSha256:f.sha256});
    }
    shots.push({id:shot.id,sourceId:s.id,outputStart:out,outputEndExclusive:out+shot.outputFrames,sourceStart:str(start),sourceEndExclusive:str(end)});out+=shot.outputFrames;
  }
  ensure(out===edl.expectedTotalFrames,'FRAME_BUDGET_SUM');
  return {schemaVersion:1,evidenceKind:actual?'planned-from-decoded-media':'synthetic-planning-only',mediaEncoded:false,targetFps:str(fps),totalFrames:out,duration:str(frameTime(out,fps)),sampling:edl.sampling,shots,mapping,cuts:shots.slice(1).map(s=>({before:s.outputStart-1,after:s.outputStart}))};
}
export function verifyMarkerFrames(plan, actual, expected) {
  ensure(Array.isArray(actual)&&Array.isArray(expected)&&actual.length===plan.totalFrames&&expected.length===plan.totalFrames,'DECODED_FRAME_COUNT');
  for(let i=0;i<actual.length;i++)ensure(actual[i]===expected[i],`FRAME_ID_MISMATCH:${i}`);
  return {framesChecked:actual.length,cutsChecked:plan.cuts.length,scope:'supplied decoded marker values only; caller must bind actual bytes/timestamps'};
}

frame-budget.test.mjs

import test from 'node:test';import assert from 'node:assert/strict';
import {planFrameBudget,verifyMarkerFrames,rat,str,add,compare}from './frame-budget.mjs';
const H='a'.repeat(64),F='b'.repeat(64);
function fixture(){const sources=[{id:'a',file:'a.nut',sha256:H,width:96,height:64,frames:Array.from({length:6},(_,i)=>({index:i,file:`f-${i}.png`,sha256:F,pts:`${i}/24`,duration:'1/24'}))},{id:'b',file:'b.nut',sha256:F,width:96,height:64,frames:[{index:0,file:'b0.png',sha256:H,pts:'2/1',duration:'1/12'},{index:1,file:'b1.png',sha256:F,pts:'25/12',duration:'1/6'},{index:2,file:'b2.png',sha256:H,pts:'9/4',duration:'1/12'}]}];const inventory={schemaVersion:1,evidenceKind:'synthetic-timing-definition',sources};const edl={schemaVersion:1,targetFps:'24/1',expectedTotalFrames:10,sampling:'active-at-or-before-no-interpolation',shots:[{id:'open',sourceId:'a',sourceSha256:H,sourceIn:'0/1',outputFrames:4},{id:'close',sourceId:'b',sourceSha256:F,sourceIn:'0/1',outputFrames:6}]};return{edl,inventory};}
const plan=(f)=>planFrameBudget(f.edl,f.inventory,{allowSyntheticTiming:true});
test('rational arithmetic preserves exact thirds and fractional FPS',()=>{assert.equal(str(add(rat('1/3'),rat('1/6'))),'1/2');assert.equal(compare(rat('24000/1001'),rat('24/1')),-1);});
test('two-shot budget uses nonzero source origin, active VFR frame and exact cuts',()=>{const p=plan(fixture());assert.equal(p.totalFrames,10);assert.equal(p.duration,'5/12');assert.equal(p.evidenceKind,'synthetic-planning-only');assert.equal(p.mediaEncoded,false);assert.deepEqual(p.cuts,[{before:3,after:4}]);assert.deepEqual(p.mapping.slice(4).map(x=>x.sourceFrame),[0,0,1,1,1,1]);assert.equal(p.mapping[4].sourcePts,'2/1');});
test('synthetic timing cannot pass default decoded-media requirement',()=>{const f=fixture();assert.throws(()=>planFrameBudget(f.edl,f.inventory),/DECODED_INVENTORY_REQUIRED/);});
for(const [name,mutate,error]of[
 ['wrong total',f=>f.edl.expectedTotalFrames=11,/FRAME_BUDGET_SUM/],
 ['duplicate shot',f=>f.edl.shots[1].id='open',/DUPLICATE_SHOT_ID/],
 ['changed input hash',f=>f.edl.shots[0].sourceSha256=F,/SOURCE_HASH_MISMATCH/],
 ['out-of-range interval',f=>f.edl.shots[0].sourceIn='1/1',/SOURCE_RANGE_OUT_OF_BOUNDS/],
 ['negative source offset',f=>f.edl.shots[0].sourceIn='-1/24',/SOURCE_IN_NEGATIVE/],
 ['nonmonotonic PTS',f=>f.inventory.sources[0].frames[1].pts='0/1',/NON_MONOTONIC_PTS/],
 ['timing gap',f=>{f.inventory.sources[0].frames[0].duration='1/100';f.edl.targetFps='48/1';},/SOURCE_PTS_GAP/],
 ['traversal basename',f=>f.inventory.sources[0].file='../a.nut',/SOURCE_BINDING/],
 ['missing source hash',f=>delete f.inventory.sources[0].sha256,/SOURCE_BINDING/],
 ['fractional output frame count',f=>f.edl.shots[0].outputFrames=2.5,/SHOT_SOURCE_OR_BUDGET/],
 ['zero FPS denominator',f=>f.edl.targetFps='24/0',/RATIONAL_SYNTAX/],
 ['unbounded total',f=>f.edl.expectedTotalFrames=12001,/TOTAL_FRAME_LIMIT/],
 ['source frame identity gap',f=>f.inventory.sources[0].frames[2].index=9,/FRAME_BINDING/],
 ['missing final frame duration',f=>delete f.inventory.sources[0].frames[5].duration,/RATIONAL_SYNTAX/],
])test(name,()=>{const f=fixture();mutate(f);assert.throws(()=>plan(f),error);});
test('wrong cut marker is rejected even when output count matches',()=>{const p=plan(fixture());assert.throws(()=>verifyMarkerFrames(p,[1,2,3,4,9,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]),/FRAME_ID_MISMATCH:4/);});
test('decoded count is distinct from rounded duration metadata',()=>{const p=plan(fixture());assert.throws(()=>verifyMarkerFrames(p,Array(9).fill(1),Array(10).fill(1)),/DECODED_FRAME_COUNT/);});

media-execution.mjs

/** Deferred, explicit offline FFmpeg execution. No network or generation provider. */
import { execFileSync } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { readFile,writeFile,copyFile,mkdir,lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { rat,str,sub,compare,hashBytes,planFrameBudget } from './frame-budget.mjs';
import { WIDTH,HEIGHT,readMarker,verifyOriginalInputs } from './original-inputs.mjs';
import {validateDecodedOutput} from './decoded-output-validator.mjs';
import {executeEncodedNegativeCases} from './encoded-negative-cases.mjs';
const ensure=(condition,code)=>{if(!condition)throw new Error(code);};
export function buildFfmpegArgv(args){
  ensure(Array.isArray(args)&&args.length>=1&&args.every(v=>typeof v==='string'),'FFMPEG_ARGV');
  const destination=args.at(-1);ensure(destination.length>0&&!destination.startsWith('-'),'FFMPEG_OUTPUT_DESTINATION');
  return ['-hide_banner','-nostdin','-loglevel','error','-filter_threads','1','-filter_complex_threads','1','-threads','1',...args.slice(0,-1),'-threads:v','1',destination];
}
const fractionDecimal=s=>{const [n,d]=rat(s);return (Number(n)/Number(d)).toFixed(9);};
export async function captureRuntimeSourceHashes(){
  const hashes={};for(const name of ['frame-budget.mjs','original-inputs.mjs','media-execution.mjs','run-recipe.mjs','decoded-output-validator.mjs','encoded-negative-cases.mjs','mp4-terminal-duration.mjs']){
    const url=new URL(name,import.meta.url),info=await lstat(url);ensure(info.isFile()&&!info.isSymbolicLink()&&info.size<=256*1024,'RUNTIME_SOURCE_NOT_BOUNDED_REGULAR_FILE');
    const bytes=await readFile(url);ensure(bytes.length===info.size,'RUNTIME_SOURCE_CHANGED_WHILE_READING');hashes[name]=hashBytes(bytes);
  }return hashes;
}
/** Presentation windows are a protocol derivation, not observed packet durations. */
export function sourcePresentationTiming(probe,sampling){
  ensure(sampling==='active-at-or-before-no-interpolation','PROBE_SAMPLING_PROTOCOL');
  const stream=probe.streams?.[0];ensure(stream&&stream.width===WIDTH&&stream.height===HEIGHT,'PROBE_DIMENSIONS');
  const tb=rat(stream.time_base);ensure(compare(tb,rat('0/1'))>0,'PROBE_TIME_BASE');
  ensure(Array.isArray(probe.frames)&&probe.frames.length>0&&probe.frames.length<=64,'PROBE_FRAME_LIMIT');
  const ticks=(value,code)=>{ensure((typeof value==='string'||Number.isSafeInteger(value))&&/^-?\d{1,20}$/.test(String(value)),code);return BigInt(value);};
  const observed=probe.frames.map(f=>{
    const pts=str(sub([ticks(f.best_effort_timestamp,'PROBE_PTS_MISSING')*tb[0],tb[1]],rat('0/1')));
    const field=f.duration!==undefined&&f.duration!==null?'duration':'pkt_duration';
    const durationTicks=ticks(f[field],'PROBE_FRAME_DURATION_MISSING');ensure(durationTicks>0n,'PROBE_FRAME_DURATION_MISSING');
    return {pts,observedDuration:{field,ticks:String(f[field]),timeBase:stream.time_base,value:str(sub([durationTicks*tb[0],tb[1]],rat('0/1')))}};
  });
  return observed.map((f,index)=>{
    const next=observed[index+1];if(next)ensure(compare(rat(next.pts),rat(f.pts))>0,'PROBE_NON_MONOTONIC_PTS');
    return {index,...f,duration:next?str(sub(rat(next.pts),rat(f.pts))):f.observedDuration.value,durationBasis:next?'derived-next-observed-pts-active-at-or-before':'observed-terminal-frame-duration'};
  });
}
async function probeSource(runProbe,file,decodedDir,id,out){
  const raw=runProbe(['-v','error','-select_streams','v:0','-show_frames','-show_entries','stream=time_base,width,height:frame=best_effort_timestamp,pkt_duration,duration','-of','json',file]);
  const probeRawFile=`${id}.probe.raw.json`;await writeFile(join(out,probeRawFile),raw,{flag:'wx'});
  const p=JSON.parse(raw),timing=sourcePresentationTiming(p,'active-at-or-before-no-interpolation'),frames=[];
  for(const frame of timing){
    const name=`frame-${String(frame.index).padStart(4,'0')}.png`,b=await readFile(join(decodedDir,name));frames.push({...frame,file:name,sha256:hashBytes(b)});
  }
  return {id,file:file.split('/').at(-1),sha256:hashBytes(await readFile(file)),width:WIDTH,height:HEIGHT,timeBase:p.streams[0].time_base,sampling:'active-at-or-before-no-interpolation',frames,probe:p,probeRawFile,probeRawSha256:hashBytes(raw)};
}
export async function executeMedia({out,manifest,ffmpeg,ffprobe}){
  ensure(process.env.ALLOW_LOCAL_MEDIA_EXECUTION==='1','MEDIA_EXECUTION_REQUIRES_RESOURCE_APPROVAL');
  ensure(typeof ffmpeg==='string'&&typeof ffprobe==='string','EXPLICIT_ENCODER_PATHS_REQUIRED');
  const runtimeSourceHashes=await captureRuntimeSourceHashes();
  const originalInputBefore=await verifyOriginalInputs(out,manifest);
  await writeFile(join(out,'runtime-source-binding.json'),JSON.stringify({observedAt:new Date().toISOString(),sourceHashes:runtimeSourceHashes},null,2)+'\n',{flag:'wx'});
  const commandLog=[],logPath=join(out,'command-log.json');writeFileSync(logPath,'[]\n',{flag:'wx'});
  const runTool=(binary,argv,{timeout=45000,maxBuffer=4*1024*1024}={})=>{
    const event={binary,argv:[...argv],startedAt:new Date().toISOString(),timeoutMilliseconds:timeout,maxBufferBytes:maxBuffer};commandLog.push(event);
    try{const bytes=execFileSync(binary,argv,{timeout,maxBuffer});event.exitCode=0;event.stdoutSha256=hashBytes(bytes);return bytes;}
    catch(error){event.exitCode=Number.isInteger(error.status)?error.status:null;event.signal=error.signal??null;throw error;}
    finally{event.completedAt=new Date().toISOString();writeFileSync(logPath,JSON.stringify(commandLog,null,2)+'\n');}
  };
  const run=args=>runTool(ffmpeg,buildFfmpegArgv(args));
  const probe=args=>runTool(ffprobe,['-threads','1',...args],{timeout:15000,maxBuffer:2*1024*1024});
  const versionsStartedAt=new Date().toISOString(),ffmpegVersion=runTool(ffmpeg,['-version'],{timeout:5000,maxBuffer:512*1024}).toString('utf8'),ffprobeVersion=runTool(ffprobe,['-version'],{timeout:5000,maxBuffer:512*1024}).toString('utf8');
  const toolVersions={startedAt:versionsStartedAt,observedAt:new Date().toISOString(),node:process.version,ffmpeg:ffmpegVersion,ffprobe:ffprobeVersion};
  await writeFile(join(out,'tool-versions.json'),JSON.stringify(toolVersions,null,2)+'\n',{flag:'wx'});
  const sources=[];
  for(const def of manifest.sources){
    const source=join(out,`${def.id}.nut`),dir=join(out,def.id);
    if(def.fps){run(['-framerate',def.fps,'-start_number','0','-i',join(dir,'frame-%04d.png'),'-frames:v',String(def.frames.length),'-an','-c:v','ffv1','-pix_fmt','bgr0',source]);}
    else{
      const concat=["ffconcat version 1.0",...def.frames.flatMap((f,i)=>[`file '${f.file}'`,`duration ${fractionDecimal(def.durations[i])}`]),`file '${def.frames.at(-1).file}'`].join('\n')+'\n';await writeFile(join(dir,'timing.ffconcat'),concat,{flag:'wx'});
      run(['-f','concat','-safe','1','-i',join(dir,'timing.ffconcat'),'-vf',`setpts=PTS+${fractionDecimal(def.requestedPtsOffset)}/TB`,'-vsync','vfr','-an','-c:v','ffv1','-pix_fmt','bgr0',source]);
    }
    const decoded=join(out,`${def.id}-decoded`);await mkdir(decoded);run(['-i',source,'-vsync','0','-start_number','0',join(decoded,'frame-%04d.png')]);
    sources.push(await probeSource(probe,source,decoded,def.id,out));
  }
  const inventory={schemaVersion:1,evidenceKind:'decoded-media-inventory',sources};
  const edl={schemaVersion:1,targetFps:'24/1',sampling:'active-at-or-before-no-interpolation',expectedTotalFrames:22,shots:[{id:'opening',sourceId:'shot-a',outputFrames:7,sourceIn:'0/1'},{id:'detail',sourceId:'shot-b',outputFrames:7,sourceIn:'0/1'},{id:'hold',sourceId:'shot-c',outputFrames:8,sourceIn:'0/1'}].map(s=>({...s,sourceSha256:sources.find(v=>v.id===s.sourceId).sha256}))};
  for(const [name,data]of Object.entries({'decoded-inventory.json':inventory,'edl.actual.json':edl}))await writeFile(join(out,name),JSON.stringify(data,null,2)+'\n',{flag:'wx'});
  const plan=planFrameBudget(edl,inventory);const framesDir=join(out,'assembled-frames');await mkdir(framesDir);
  const expected=[],expectedMarkerProof=[];
  for(const m of plan.mapping){const file=join(out,`${m.sourceId}-decoded`,m.sourceFrameFile);const bytes=await readFile(file);ensure(hashBytes(bytes)===m.sourceFrameSha256,'DECODED_SOURCE_DRIFT');await copyFile(file,join(framesDir,`frame-${String(m.outputFrame).padStart(4,'0')}.png`));const rgb=run(['-i',file,'-frames:v','1','-pix_fmt','rgb24','-f','rawvideo','pipe:1']);ensure(rgb.length===WIDTH*HEIGHT*3,'SOURCE_FRAME_PIXELS');
    const original=manifest.sources.find(s=>s.id===m.sourceId),definition=original.frames[m.sourceFrame]??(!original.fps&&m.sourceFrame===original.frames.length?original.frames.at(-1):null);
    ensure(definition&&readMarker(rgb)===definition.expectedMarker,'DECODED_SOURCE_MARKER_NOT_ORIGINAL');
    const actualMarker=readMarker(rgb);expected.push(actualMarker);expectedMarkerProof.push({outputFrame:m.outputFrame,sourceId:m.sourceId,sourceFrame:m.sourceFrame,decodedPngSha256:m.sourceFrameSha256,decodedRgbSha256:hashBytes(rgb),expectedOriginalMarker:definition.expectedMarker,actualDecodedMarker:actualMarker});
  }
  const encode=(directory,count,destination)=>{ensure(count===21||count===22,'FIXED_ENCODE_FRAME_LIMIT');return run(['-framerate','24','-start_number','0','-i',join(directory,'frame-%04d.png'),'-frames:v',String(count),'-an','-c:v','libx264','-crf','0','-bf','0','-pix_fmt','yuv444p','-video_track_timescale','24000','-use_editlist','0',destination]);};
  const observe=async file=>{
    const rgb=run(['-i',file,'-vsync','0','-pix_fmt','rgb24','-f','rawvideo','pipe:1']);
    const p=JSON.parse(probe(['-v','error','-select_streams','v:0','-show_frames','-show_entries','stream=time_base,width,height:frame=best_effort_timestamp,pkt_duration,duration','-of','json',file]));
    const packets=JSON.parse(probe(['-v','error','-select_streams','v:0','-show_packets','-show_entries','packet=pts,dts,duration,pos,size','-of','json',file]));p.packets=packets.packets;return{rgb,probe:p};
  };
  const output=join(out,'assembled-review.mp4');encode(framesDir,22,output);
  const positiveObservation=await observe(output),outputProbe=positiveObservation.probe;
  const outputChecks=validateDecodedOutput({plan,expectedMarkers:expected,...positiveObservation});
  const negativeMedia=await executeEncodedNegativeCases({executeMedia:true,out,framesDir,positiveOutput:output,positiveObservation,plan,expectedMarkers:expected,encode,observe});
  const originalInputAfter=await verifyOriginalInputs(out,manifest);ensure(JSON.stringify(originalInputBefore)===JSON.stringify(originalInputAfter),'ORIGINAL_INPUT_BINDING_CHANGED_DURING_RUN');
  const afterSourceHashes=await captureRuntimeSourceHashes();ensure(Object.keys(runtimeSourceHashes).every(name=>runtimeSourceHashes[name]===afterSourceHashes[name]),'EXECUTION_CODE_CHANGED_DURING_RUN');
  const receipt={schemaVersion:1,evidenceKind:'local-synthetic-media-fixture',executedAt:new Date().toISOString(),providerRequests:0,paidSpend:0,modelGeneration:false,runtimeSourceHashes,originalInputBinding:{before:originalInputBefore,after:originalInputAfter},codeHashRecheckedAt:new Date().toISOString(),toolVersions:{node:toolVersions.node,ffmpeg:toolVersions.ffmpeg.split('\n')[0],ffprobe:toolVersions.ffprobe.split('\n')[0]},sourceHashes:sources.map(s=>({id:s.id,sha256:s.sha256})),outputSha256:hashBytes(await readFile(output)),outputFrames:plan.totalFrames,duration:plan.duration,outputChecks,negativeMedia,expectedMarkerProof,scope:'22-frame small offline original fixture; not 204-second execution, semantic continuity or MiniMax generation'};
  for(const [name,data]of Object.entries({'frame-map.json':plan,'expected-marker-proof.json':expectedMarkerProof,'output-probe.json':outputProbe,'media-execution-receipt.json':receipt}))await writeFile(join(out,name),JSON.stringify(data,null,2)+'\n',{flag:'wx'});
  return receipt;
}

mp4-terminal-duration.mjs

/** Narrow mutation of our own nonfragmented, one-track, no-edit-list MP4. */
import {hashBytes} from './frame-budget.mjs';
const ensure=(ok,code)=>{if(!ok)throw new Error(code);};
const CONTAINERS=new Set(['moov','trak','mdia','minf','stbl']);
function boxes(bytes,start=0,end=bytes.length,depth=0,state={count:0}){ensure(depth<=8,'MP4_BOX_DEPTH_LIMIT');const result=[];let p=start;while(p<end){ensure(p+8<=end,'MP4_BOX_TRUNCATED');ensure(++state.count<=256,'MP4_BOX_COUNT_LIMIT');const size=bytes.readUInt32BE(p),type=bytes.toString('ascii',p+4,p+8);ensure(size>=8&&p+size<=end,'MP4_BOX_SIZE');const data=bytes.subarray(p+8,p+size);result.push({type,start:p,end:p+size,data,children:CONTAINERS.has(type)?boxes(bytes,p+8,p+size,depth+1,state):null});p+=size;}ensure(p===end,'MP4_BOX_BOUNDARY');return result;}
const descendants=(xs)=>xs.flatMap(x=>[x,...(x.children?descendants(x.children):[])]);
const only=(xs,type)=>{const list=xs.filter(x=>x.type===type);ensure(list.length===1,'MP4_UNSUPPORTED_'+type);return list[0];};
function encode(node){const data=node.children?Buffer.concat(node.children.map(encode)):node.data,b=Buffer.alloc(8);b.writeUInt32BE(data.length+8);b.write(node.type,4,4,'ascii');return Buffer.concat([b,data]);}
export function patchTerminalSampleDuration(input){
  ensure(Buffer.isBuffer(input)&&input.length>0&&input.length<=4*1024*1024,'MP4_BYTE_LIMIT');
  const top=boxes(input),all=descendants(top);ensure(!all.some(x=>['edts','elst','mvex','moof'].includes(x.type)),'MP4_UNSUPPORTED_EDIT_OR_FRAGMENT');
  const moov=only(top,'moov'),mdat=only(top,'mdat');ensure(mdat.end<=moov.start&&top.at(-1)===moov,'MP4_REQUIRES_FINAL_MOOV_AFTER_MDAT');
  const tracks=moov.children.filter(x=>x.type==='trak');ensure(tracks.length===1,'MP4_REQUIRES_SINGLE_TRACK');const track=tracks[0],inside=descendants([track]);
  const hdlr=only(inside,'hdlr');ensure(hdlr.data.length>=12&&hdlr.data.toString('ascii',8,12)==='vide','MP4_REQUIRES_VIDEO_ONLY');
  const stsz=only(inside,'stsz');ensure(stsz.data.length>=12&&stsz.data.readUInt32BE(8)===22,'MP4_EXPECTS_22_SAMPLE_SIZES');
  const ctts=inside.filter(x=>x.type==='ctts');ensure(ctts.length<=1,'MP4_UNSUPPORTED_ctts');
  if(ctts.length){const d=ctts[0].data;ensure(d.length>=8&&d[0]===0&&d.readUInt32BE(4)<=22&&d.length===8+8*d.readUInt32BE(4),'MP4_UNSUPPORTED_CTTS');let samples=0;for(let p=8;p<d.length;p+=8){samples+=d.readUInt32BE(p);ensure(d.readUInt32BE(p+4)===0,'MP4_COMPOSITION_REORDER');}ensure(samples===22,'MP4_CTTS_SAMPLE_COUNT');}
  const chunkTables=inside.filter(x=>x.type==='stco'||x.type==='co64');ensure(chunkTables.length===1,'MP4_CHUNK_TABLE_REQUIRED');
  const stts=only(inside,'stts'),mdhd=only(inside,'mdhd'),tkhd=only(inside,'tkhd'),mvhd=only(moov.children,'mvhd');
  for(const box of [stts,mdhd,tkhd,mvhd]){ensure(box.data[0]===0,'MP4_UNSUPPORTED_FULLBOX_VERSION');box.data=Buffer.from(box.data);}
  ensure(stts.data.length===16&&stts.data.readUInt32BE(4)===1&&stts.data.readUInt32BE(8)===22&&stts.data.readUInt32BE(12)===1000,'MP4_EXPECTS_22_CFR_SAMPLES');
  ensure(mdhd.data.length>=20&&mdhd.data.readUInt32BE(12)===24000&&mdhd.data.readUInt32BE(16)===22000,'MP4_EXPECTS_FIXED_MEDIA_TIMESCALE');
  ensure(mvhd.data.length>=20&&tkhd.data.length>=24,'MP4_HEADER_TRUNCATED');const movieScale=mvhd.data.readUInt32BE(12);ensure(movieScale>0&&movieScale<=1000000,'MP4_MOVIE_TIMESCALE');
  const beforeMovie=Math.ceil(22000*movieScale/24000),afterMovie=Math.ceil(21500*movieScale/24000);ensure(mvhd.data.readUInt32BE(16)===beforeMovie&&tkhd.data.readUInt32BE(20)===beforeMovie,'MP4_INCONSISTENT_MOVIE_DURATION');
  const table=Buffer.alloc(24);stts.data.copy(table,0,0,4);table.writeUInt32BE(2,4);table.writeUInt32BE(21,8);table.writeUInt32BE(1000,12);table.writeUInt32BE(1,16);table.writeUInt32BE(500,20);stts.data=table;
  mdhd.data.writeUInt32BE(21500,16);mvhd.data.writeUInt32BE(afterMovie,16);tkhd.data.writeUInt32BE(afterMovie,20);
  const output=Buffer.concat(top.map(encode)),again=boxes(output),afterMdat=only(again,'mdat');ensure(hashBytes(mdat.data)===hashBytes(afterMdat.data),'MP4_MDAT_CHANGED');
  return {bytes:output,mutation:{kind:'actual-mp4-stts-terminal-duration',samples:22,timescale:24000,oldTerminalDuration:1000,newTerminalDuration:500,mdatSha256:hashBytes(mdat.data),unchangedSampleTableHashes:Object.fromEntries(inside.filter(x=>['stsz','stsc','stss','stco','co64','ctts'].includes(x.type)).map(x=>[x.type,hashBytes(x.data)])),sourceSha256:hashBytes(input),mutatedSha256:hashBytes(output),expectedUnchanged:'all encoded sample bytes and first 22 PTS; verify by actual ffprobe/decode',evidenceScope:'actual container bytes mutated; decoded rejection still requires tool execution'}};
}

original-inputs.mjs

/** Original 96x64 raster sources; no fonts, external media or AI calls. */
import { deflateSync } from 'node:zlib';
import { mkdir,writeFile,lstat,readdir,open } from 'node:fs/promises';
import { constants } from 'node:fs';
import { join,resolve,parse,sep } from 'node:path';
import { hashBytes } from './frame-budget.mjs';
export const WIDTH=96, HEIGHT=64;
const ensure=(ok,code)=>{if(!ok)throw new Error(code);};
const definitions=()=>[{id:'shot-a',fps:'24000/1001',frames:8},{id:'shot-b',fps:'25/1',frames:10},{id:'shot-c',fps:null,frames:7,durations:['1/25','2/25','3/25','1/25','2/25','1/25','1/25'],requestedPtsOffset:'2/1'}];
const manifestFor=sources=>({schemaVersion:1,evidenceKind:'original-raster-definitions-not-encoded-video',width:WIDTH,height:HEIGHT,sources,mediaExecution:false,disclosure:'PNG frames are actual local original assets. Intended source timing is not an observation of encoded media.'});
const crc = (b) => { let c=0xffffffff;for(const x of b){c^=x;for(let i=0;i<8;i++)c=(c>>>1)^((c&1)?0xedb88320:0);}return(c^0xffffffff)>>>0; };
const chunk=(name,data)=>{const n=Buffer.alloc(4);n.writeUInt32BE(data.length);const t=Buffer.from(name),c=Buffer.alloc(4);c.writeUInt32BE(crc(Buffer.concat([t,data])));return Buffer.concat([n,t,data,c]);};
export function markerRgb(sourceIndex,frameIndex){
  const b=Buffer.alloc(WIDTH*HEIGHT*3);const colours=[[35,95,165],[155,75,115],[65,140,90]],base=colours[sourceIndex];
  for(let y=0;y<HEIGHT;y++)for(let x=0;x<WIDTH;x++){
    let colour=(x-20-frameIndex*3)**2+(y-36)**2<90?[225,180,60]:base;
    if(y>=4&&y<12&&x>=4&&x<68){const bit=Math.floor((x-4)/8);const v=(((sourceIndex+1)*32+frameIndex)>>bit)&1;colour=v?[240,240,240]:[16,16,16];}
    if(x<3||x>=WIDTH-3||y<2||y>=HEIGHT-2)colour=[25,25,25];
    const p=(y*WIDTH+x)*3;b[p]=colour[0];b[p+1]=colour[1];b[p+2]=colour[2];
  }return b;
}
export function readMarker(rgb){let code=0;for(let bit=0;bit<8;bit++){const p=(8*WIDTH+8+bit*8)*3;const v=(rgb[p]+rgb[p+1]+rgb[p+2])/3;if(v>128)code|=1<<bit;}return code;}
export function encodePng(rgb){const header=Buffer.alloc(13);header.writeUInt32BE(WIDTH,0);header.writeUInt32BE(HEIGHT,4);header[8]=8;header[9]=2;const raw=Buffer.alloc((WIDTH*3+1)*HEIGHT);for(let y=0;y<HEIGHT;y++)rgb.copy(raw,y*(WIDTH*3+1)+1,y*WIDTH*3,(y+1)*WIDTH*3);return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',header),chunk('IDAT',deflateSync(raw)),chunk('IEND',Buffer.alloc(0))]);}
function expectedManifest(){
  return manifestFor(definitions().map((d,si)=>({...d,sourceDesign:'source-design.svg',frames:Array.from({length:d.frames},(_,index)=>({index,file:`frame-${String(index).padStart(4,'0')}.png`,sha256:hashBytes(encodePng(markerRgb(si,index))),expectedMarker:(si+1)*32+index}))})));
}
async function regularBytes(path,maximum){
  const before=await lstat(path);ensure(before.isFile()&&!before.isSymbolicLink()&&before.size<=maximum,'ORIGINAL_INPUT_NOT_BOUNDED_REGULAR_FILE');
  const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);
  try{
    const opened=await handle.stat();ensure(opened.isFile()&&opened.dev===before.dev&&opened.ino===before.ino&&opened.size===before.size&&opened.mtimeMs===before.mtimeMs,'ORIGINAL_INPUT_CHANGED_BEFORE_OPEN');
    const chunks=[];let total=0;
    for(;;){const buffer=Buffer.alloc(Math.min(16*1024,maximum+1-total));const {bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;total+=bytesRead;ensure(total<=maximum,'ORIGINAL_INPUT_READ_BOUND');chunks.push(buffer.subarray(0,bytesRead));}
    const after=await handle.stat(),current=await lstat(path);
    ensure(current.isFile()&&!current.isSymbolicLink()&&[after,current].every(st=>st.dev===opened.dev&&st.ino===opened.ino&&st.size===total&&st.mtimeMs===opened.mtimeMs)&&opened.size===total,'ORIGINAL_INPUT_CHANGED_WHILE_READING');
    return Buffer.concat(chunks,total);
  }finally{await handle.close();}
}
/** File-only identity proof for this fixed fixture; never runs a media tool. */
export async function verifyOriginalInputs(out,manifest){
  ensure(typeof out==='string'&&out.length>0,'ORIGINAL_INPUT_ROOT');
  const root=resolve(out),expected=expectedManifest(),directories=[];
  ensure(JSON.stringify(manifest)===JSON.stringify(expected),'ORIGINAL_INPUT_MANIFEST_NOT_DETERMINISTIC');
  // Reject symlinked ancestors as well as symlinked input files/directories.
  let current=parse(root).root;
  for(const part of root.slice(current.length).split(sep).filter(Boolean)){
    current=join(current,part);const info=await lstat(current);ensure(info.isDirectory()&&!info.isSymbolicLink(),'ORIGINAL_INPUT_ROOT_NOT_REAL_DIRECTORY');directories.push({path:current,dev:info.dev,ino:info.ino});
  }
  const manifestExpected=Buffer.from(JSON.stringify(expected,null,2)+'\n'),manifestBytes=await regularBytes(join(root,'original-input-manifest.json'),64*1024);
  ensure(manifestBytes.equals(manifestExpected),'ORIGINAL_INPUT_MANIFEST_BYTES_CHANGED');
  const frames=[];
  for(const source of expected.sources){
    const directory=join(root,source.id),info=await lstat(directory);ensure(info.isDirectory()&&!info.isSymbolicLink(),'ORIGINAL_INPUT_SOURCE_NOT_REAL_DIRECTORY');directories.push({path:directory,dev:info.dev,ino:info.ino});
    const names=await readdir(directory,{withFileTypes:true}),pngs=names.filter(x=>x.name.toLowerCase().endsWith('.png'));
    ensure(names.every(x=>!x.isSymbolicLink())&&pngs.length===source.frames.length&&pngs.every(x=>x.isFile()&&source.frames.some(f=>f.file===x.name)),'ORIGINAL_INPUT_PNG_SET_CHANGED');
    for(const frame of source.frames){
      const path=source.id+'/'+frame.file,bytes=await regularBytes(join(root,source.id,frame.file),256*1024),sha256=hashBytes(bytes);
      ensure(sha256===frame.sha256,'ORIGINAL_INPUT_PNG_HASH_CHANGED:'+path);frames.push({sourceId:source.id,index:frame.index,path,bytes:bytes.length,sha256});
    }
  }
  ensure(frames.length===25&&new Set(frames.map(f=>f.path)).size===25,'ORIGINAL_INPUT_EXPECTED_25_UNIQUE_PNGS');
  for(const d of directories){const st=await lstat(d.path);ensure(st.isDirectory()&&!st.isSymbolicLink()&&st.dev===d.dev&&st.ino===d.ino,'ORIGINAL_INPUT_ANCESTOR_CHANGED');}
  return {schemaVersion:1,manifestSha256:hashBytes(manifestBytes),manifestBytes:manifestBytes.length,frameCount:25,frames};
}
export async function writeOriginalInputs(out){
  const defs=definitions();
  const written=[];
  for(const [si,d] of defs.entries()){
    const dir=join(out,d.id);await mkdir(dir);const frameFiles=[];
    for(let i=0;i<d.frames;i++){
      const rgb=markerRgb(si,i),png=encodePng(rgb),file=`frame-${String(i).padStart(4,'0')}.png`;await writeFile(join(dir,file),png,{flag:'wx'});frameFiles.push({index:i,file,sha256:hashBytes(png),expectedMarker:(si+1)*32+i});
    }
    const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="96" height="64"><rect width="96" height="64" fill="${['#235fa5','#9b4b73','#418c5a'][si]}"/><circle cx="20" cy="36" r="9" fill="#e1b43c"/><path d="M4 8H68" stroke="#f0f0f0" stroke-width="8"/></svg>\n`;
    await writeFile(join(dir,'source-design.svg'),svg,{flag:'wx'});written.push({...d,sourceDesign:'source-design.svg',frames:frameFiles});
  }
  const result=manifestFor(written);
  await writeFile(join(out,'original-input-manifest.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx'});return result;
}

run-recipe.mjs

import {mkdir,writeFile} from 'node:fs/promises';
import {resolve,join} from 'node:path';
import {writeOriginalInputs} from './original-inputs.mjs';
import {executeEncodedNegativeCases} from './encoded-negative-cases.mjs';
const args=process.argv.slice(2),value=(name)=>{const i=args.indexOf(name);return i<0?null:args[i+1];};
const out=value('--out');if(!out||out.startsWith('--'))throw new Error('Use --out NEW_DIRECTORY');
const dest=resolve(out);await mkdir(dest,{recursive:false});
const manifest=await writeOriginalInputs(dest);
const status={schemaVersion:1,preparedAt:new Date().toISOString(),originalRasterInputsWritten:true,mediaExecuted:false,notModelGeneration:true,qualified:false,publicationReady:false,negativeMedia:await executeEncodedNegativeCases({executeMedia:false})};
if(args.includes('--execute-media')){
 const {executeMedia}=await import('./media-execution.mjs');status.mediaReceipt=await executeMedia({out:dest,manifest,ffmpeg:value('--ffmpeg'),ffprobe:value('--ffprobe')});status.mediaExecuted=true;status.negativeMedia=status.mediaReceipt.negativeMedia;
}
await writeFile(join(dest,'run-status.json'),JSON.stringify(status,null,2)+'\n',{flag:'wx'});console.log(JSON.stringify(status));
Original source design diagram
Original source design diagram
Original 22-frame local execution from 17 October 2026; no model generation
Assemble video shots on an exact integer-frame timeline