import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, it } from 'node:test' import { pathToFileURL } from 'node:url' import retime from '../src/retime.ts' import musicAlign, { verifyMarkedAlignment } from '../src/music-align.ts' import musicAttribution from '../src/music-attribution.ts' import verifyVideo from '../src/verify-video.ts' const root = new URL('..', import.meta.url).pathname describe('retime', () => { it('snaps scene bounds from rounded scaled starts and regenerates durations', () => { const result = retime({ config: { fps: 30, pace: 1.3, baseEnd: 90, scenes: [ { id: 'intro', start: 0, end: 8 }, { id: 'build', start: 8, end: 20 }, { id: 'payoff', start: 72, end: 84 }, { id: 'outro', start: 84 }, ], }, }) assert.equal(result.frames, Math.round((90 * 30) / 1.3)) assert.equal(result.scenes[0].startFrame, 0) assert.equal( result.scenes[0].durationFrames, Math.round((8 * 30) / 1.3) - 0, ) assert.equal( result.scenes[1].startFrame, Math.round((8 * 30) / 1.3), ) const sum = result.scenes.reduce((n, s) => n + s.durationFrames, 0) assert.equal(sum, result.frames) assert.equal(result.durationSeconds, Number((result.frames / 30).toFixed(5))) }) it('rewrites host HTML data-start/duration, root, and music safely by id', () => { const html = [ '
', '
', '
', '', '
', ].join('') const result = retime({ config: { fps: 30, pace: 2, baseEnd: 16, scenes: [ { id: 'intro', start: 0, end: 8 }, { id: 'payoff', start: 8, end: 16 }, ], html, }, }) assert.match(result.html!, /id="intro"[^>]*data-start="0" data-duration="4"/) assert.match(result.html!, /id="payoff"[^>]*data-start="4" data-duration="4"/) assert.match(result.html!, /id="root" data-duration="8"/) assert.match(result.html!, /id="music" data-duration="8"/) assert.match(result.html!, /id="intro-extra" data-start="9" data-duration="1"/) }) it('rejects duplicate ids, non-zero first start, and unknown keys', () => { assert.throws(() => retime({ config: { fps: 30, pace: 1, baseEnd: 4, scenes: [ { id: 'a', start: 0, end: 2 }, { id: 'a', start: 2, end: 4 }, ], }, }), ) assert.throws(() => retime({ config: { fps: 30, pace: 1, baseEnd: 4, scenes: [{ id: 'a', start: 1, end: 4 }], }, }), ) assert.throws(() => // @ts-expect-error intentional unknown key retime({ config: { fps: 30, pace: 1, baseEnd: 2, scenes: [{ id: 'a', start: 0, end: 2 }] }, extra: 1 }), ) }) it('requires matching host elements when html is provided', () => { assert.throws(() => retime({ config: { fps: 30, pace: 1, baseEnd: 2, scenes: [{ id: 'missing', start: 0, end: 2 }], html: '
', }, }), ) }) }) describe('productPromoPace GSAP driver', () => { it('scales wall duration by 1/pace without rewriting authored eases', () => { const paceSource = readFileSync( join(root, 'skills/product-promo-video/assets/pace.js'), 'utf8', ) const calls: Array> = [] const authored = { duration: () => 90, _ease: 'power2.inOut', } const fakeTimeline = { fromTo( target: unknown, from: unknown, to: Record, position: unknown, ) { calls.push({ target, from, to, position }) return fakeTimeline }, } const gsap = { timeline: ({ paused }: { paused: boolean }) => { assert.equal(paused, true) return fakeTimeline } } const window: Record = {} const fn = new Function('gsap', 'window', `${paceSource}\nreturn window;`) const win = fn(gsap, window) as { PRODUCT_PROMO_PACE: number productPromoPace: (authored: { duration: () => number }) => unknown } assert.equal(win.PRODUCT_PROMO_PACE, 1.3) win.productPromoPace(authored) assert.equal(calls.length, 1) assert.equal(calls[0].target, authored) assert.deepEqual(calls[0].from, { time: 0 }) assert.equal((calls[0].to as { time: number }).time, 90) assert.equal((calls[0].to as { duration: number }).duration, 90 / 1.3) assert.equal((calls[0].to as { ease: string }).ease, 'none') assert.equal(calls[0].position, 0) assert.equal(authored._ease, 'power2.inOut') }) it('respects a runtime PRODUCT_PROMO_PACE override', () => { const paceSource = readFileSync( join(root, 'skills/product-promo-video/assets/pace.js'), 'utf8', ) let durationArg = 0 const fakeTimeline = { fromTo( _t: unknown, _f: unknown, to: { duration: number }, ) { durationArg = to.duration return fakeTimeline }, } const gsap = { timeline: () => fakeTimeline } const window: Record = {} const fn = new Function('gsap', 'window', `${paceSource}\nreturn window;`) const win = fn(gsap, window) as { PRODUCT_PROMO_PACE: number productPromoPace: (authored: { duration: () => number }) => unknown } win.PRODUCT_PROMO_PACE = 2 win.productPromoPace({ duration: () => 10 }) assert.equal(durationArg, 5) }) }) describe('musicAlign', () => { it('frame-snaps offset for generic onset 5.86 and reveal 3.2/1.3', () => { const brandRevealSeconds = 3.2 / 1.3 const plan = musicAlign({ sourceOnsetSeconds: 5.86, brandRevealSeconds, fps: 30, durationSeconds: 20, }) const revealFrame = Math.round(brandRevealSeconds * 30) assert.equal(plan.revealFrame, revealFrame) assert.equal(plan.actualRevealSeconds, Number((revealFrame / 30).toFixed(5))) const rawOffset = 5.86 - revealFrame / 30 const expectedOffset = Math.round(rawOffset * 30) / 30 assert.equal(plan.mediaOffsetSeconds, Number(expectedOffset.toFixed(5))) assert.equal(plan.withinOneFrame, true) assert.equal(plan.fadeInSeconds, 0.6) assert.equal(plan.fadeOutSeconds, 3.5) assert.equal(plan.silentFallback.hasAudio, false) assert.match(plan.ffmpegFilter, /atrim=start=/) assert.match(plan.ffmpegFilter, /afade=t=in/) assert.match(plan.ffmpegFilter, /afade=t=out/) }) it('rejects negative media offsets and short sources', () => { assert.throws(() => musicAlign({ sourceOnsetSeconds: 0.1, brandRevealSeconds: 2, fps: 30, durationSeconds: 10, }), ) assert.throws(() => musicAlign({ sourceOnsetSeconds: 5, brandRevealSeconds: 1, fps: 30, durationSeconds: 10, sourceDurationSeconds: 12, }), ) }) it('verifyMarkedAlignment stays within one frame and never claims listening', () => { const result = verifyMarkedAlignment({ outputOnsetSeconds: 2 + 1 / 60, expectedFrame: 60, fps: 30, }) assert.equal(result.withinOneFrame, true) assert.equal(result.listeningVerified, false) assert.ok(result.checklist.some((line) => /listening/i.test(line))) }) }) describe('musicAttribution', () => { it('emits markdown without asserting clearance', () => { const note = musicAttribution({ title: 'Example Cue', creator: 'Example Artist', sourceUrl: 'https://example.com/track', licenseName: 'Example License', licenseUrl: 'https://example.com/license', }) assert.match(note.markdown, /Example Cue/) assert.match(note.markdown, /not a copyright/) assert.equal(note.rightsVerified, false) assert.equal(note.recommendFreshRightsCheck, true) assert.doesNotMatch(note.markdown, /cleared for commercial use without review/i) }) it('records optional flags without inventing rights', () => { const note = musicAttribution({ title: 'Cue', creator: 'Artist', sourceUrl: 'https://example.com/a', licenseName: 'Lic', licenseUrl: 'https://example.com/l', contentId: 'cid-1', commercialUseAllowed: true, verifiedAt: '2026-01-01T00:00:00Z', notes: 're-check before upload', }) assert.match(note.markdown, /cid-1/) assert.match(note.markdown, /reported allowed/) assert.match(note.markdown, /2026-01-01/) assert.equal(note.rightsVerified, false) }) }) describe('verifyVideo', () => { it('parses rational fps and keeps review pending', () => { const summary = verifyVideo({ probe: { streams: [ { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, avg_frame_rate: '30/1', duration: '1.0', nb_frames: '30', }, { codec_type: 'audio', codec_name: 'aac', duration: '1.0' }, ], format: { format_name: 'mov,mp4', duration: '1.0', size: '1234' }, }, expect: { fps: 30, width: 1920, height: 1080, requireAudio: true }, reviewFrames: ['frames/open.png'], }) assert.equal(summary.video?.fps, 30) assert.equal(summary.hasAudio, true) assert.equal(summary.frameCount, 30) assert.equal(summary.frameCountApproximate, false) assert.equal(summary.approved, false) assert.equal(summary.reviewStatus, 'pending_human_inspection') assert.equal(summary.listeningVerified, false) assert.ok(summary.checks.every((c) => c.ok)) assert.ok(summary.checklist.some((l) => /open\.png/.test(l))) }) it('flags approximate frame counts when nb_frames is absent', () => { const summary = verifyVideo({ probe: { streams: [ { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, avg_frame_rate: '25/1', duration: '2', }, ], format: { duration: '2' }, }, }) assert.equal(summary.frameCountApproximate, true) assert.equal(summary.frameCount, 50) assert.ok(summary.checklist[0].includes('approximate')) }) it('fails conflicting audio expectations', () => { assert.throws(() => verifyVideo({ probe: { streams: [], format: {} }, expect: { requireAudio: true, requireSilent: true }, }), ) }) }) describe('local synthetic mp4 + CLI', () => { it('probes a generated testsrc mp4 through verify-video helper and script', () => { const dir = mkdtempSync(join(tmpdir(), 'promo-video-')) const mp4 = join(dir, 'sample.mp4') const gen = spawnSync( 'ffmpeg', [ '-y', '-f', 'lavfi', '-i', 'testsrc2=size=320x240:rate=30', '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=44100', '-t', '0.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', mp4, ], { encoding: 'utf8' }, ) if (gen.status !== 0) { rmSync(dir, { recursive: true, force: true }) assert.fail(`ffmpeg unavailable or failed: ${gen.stderr}`) } const probe = spawnSync( 'ffprobe', ['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', mp4], { encoding: 'utf8' }, ) assert.equal(probe.status, 0) const summary = verifyVideo({ probe: JSON.parse(probe.stdout), expect: { requireAudio: true, minDurationSeconds: 0.4 }, }) assert.equal(summary.hasAudio, true) assert.ok((summary.format.durationSeconds ?? 0) >= 0.4) assert.equal(summary.approved, false) const script = join(root, 'skills/product-promo-video/scripts/verify-video.mjs') const cli = spawnSync( process.execPath, [script, '--file', mp4, '--expect', JSON.stringify({ requireAudio: true })], { encoding: 'utf8' }, ) assert.equal(cli.status, 0, cli.stderr) const parsed = JSON.parse(cli.stdout) assert.equal(parsed.summary.hasAudio, true) assert.equal(parsed.summary.approved, false) rmSync(dir, { recursive: true, force: true }) }) it('retime CLI stays dry by default and writes only with --write', async () => { const dir = mkdtempSync(join(tmpdir(), 'promo-retime-')) const htmlPath = join(dir, 'index.html') const configPath = join(dir, 'promo.json') writeFileSync( htmlPath, '
', ) writeFileSync( configPath, JSON.stringify({ fps: 30, pace: 2, baseEnd: 8, scenes: [{ id: 'intro', start: 0, end: 8 }], htmlPath: './index.html', }), ) const script = join(root, 'skills/product-promo-video/scripts/retime.mjs') const dry = spawnSync(process.execPath, [script, '--config', configPath], { encoding: 'utf8', }) assert.equal(dry.status, 0, dry.stderr) assert.match(dry.stdout, /dry-run/) assert.match(readFileSync(htmlPath, 'utf8'), /data-duration="8"/) const write = spawnSync( process.execPath, [script, '--config', configPath, '--write'], { encoding: 'utf8' }, ) assert.equal(write.status, 0, write.stderr) assert.match(readFileSync(htmlPath, 'utf8'), /data-duration="4"/) rmSync(dir, { recursive: true, force: true }) }) }) describe('package surface', () => { it('skill frontmatter name matches directory', () => { const skill = readFileSync( join(root, 'skills/product-promo-video/SKILL.md'), 'utf8', ) assert.match(skill, /^---\nname: product-promo-video\n/m) assert.match(skill, /kody:@kody\/skills\/retime/) assert.match(skill, /kody:@kody\/skills\/music-align/) assert.match(skill, /kody:@kody\/skills\/verify-video/) assert.match(skill, /kody:@kody\/skills\/music-attribution/) const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) for (const name of ['narration-align', 'voice-pauses', 'voice-timing', 'final-qa']) { assert.match(skill, new RegExp(`kody:@kody/skills/${name}`)) assert.ok(pkg.exports[`./${name}`], `package export ./${name}`) } assert.doesNotMatch(skill, /KODY_PACE|kodyPace|kody-launch/i) }) it('ships beatmap.py as a pinned uv script', () => { const py = readFileSync(join(root, 'skills/product-promo-video/scripts/beatmap.py'), 'utf8') assert.match(py, /^#!\/usr\/bin\/env -S uv run --script/) assert.match(py, /dependencies = \["librosa==[\d.]+", "numpy==[\d.]+"\]/) }) it('keeps SKILL.md short and every referenced file present', () => { const dir = join(root, 'skills/product-promo-video') const skill = readFileSync(join(dir, 'SKILL.md'), 'utf8') assert.ok(skill.split('\n').length <= 60, 'SKILL.md stays an index; detail belongs in references/') for (const ref of skill.matchAll(/`(references\/[a-z-]+\.md)`/g)) { assert.ok(readFileSync(join(dir, ref[1]), 'utf8').length > 0, ref[1]) } }) it('pace asset uses generic PRODUCT_PROMO_PACE names only', () => { const pace = readFileSync( join(root, 'skills/product-promo-video/assets/pace.js'), 'utf8', ) assert.match(pace, /PRODUCT_PROMO_PACE/) assert.match(pace, /productPromoPace/) assert.doesNotMatch(pace, /KODY_PACE|kodyPace/) }) })