Skip to content

Agent Skill for 15–90 s motion graphics, promo and character videos: reference analysis, seven stage gates, Remotion and HyperFrames engines.

feat: timeline editor (picture, text, voice, music) on one edit.json (#7)

Unclejobs9c3a2a8c23b1
diff --git a/README.ko.md b/README.ko.md
index 1c4ef18..856e1e3 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -16,7 +16,7 @@ Codex, Claude Code와 다른 스킬 지원 런타임에서 같은 스킬 폴더
![carry: 첫 줄이 아이리스 전환을 지나 다음 장면의 라벨로 이어지는 세 프레임](docs/assets/carry.ko.png)
-**바로 가기** · [왜 게이트인가](#왜-게이트인가) · [빠른 시작](#빠른-시작) · [설치](#설치) · [들어 있는 것](#들어-있는-것) · [레퍼런스 분석](#레퍼런스-분석) · [사용 흐름](#사용-흐름) · [하네스](#하네스) · [캐릭터 일관성 7가지](#캐릭터-일관성-7가지) · [자주 겪는 함정](#자주-겪는-함정) · [참고 문서](#참고-문서) · [필요한 도구](#필요한-도구) · [알려진 한계](#알려진-한계) · [검증 범위](#검증-범위)
+**바로 가기** · [왜 게이트인가](#왜-게이트인가) · [빠른 시작](#빠른-시작) · [설치](#설치) · [들어 있는 것](#들어-있는-것) · [타임라인 편집기](#타임라인-편집기) · [레퍼런스 분석](#레퍼런스-분석) · [사용 흐름](#사용-흐름) · [하네스](#하네스) · [캐릭터 일관성 7가지](#캐릭터-일관성-7가지) · [자주 겪는 함정](#자주-겪는-함정) · [참고 문서](#참고-문서) · [필요한 도구](#필요한-도구) · [알려진 한계](#알려진-한계) · [검증 범위](#검증-범위)
## 왜 게이트인가
@@ -106,9 +106,26 @@ cp -r motion-video-skill/skills/motion-video-production ~/.claude/skills/
| 목소리와 음악 | composio CLI로 ElevenLabs·Fish Audio 목소리, 타이밍에 맞춘 절차적 스코어 | `vo.mjs`, `score.mjs` |
| HyperFrames 엔진 | HTML/CSS 페이지를 GSAP으로 움직여 mp4로 렌더해요 | `engines/hyperframes/` |
| 레퍼런스 분석 | 레퍼런스 영상을 OpenCV로 분해해 목표값을 만들어요 | `scripts/ref-analyze.py` |
+| 타임라인 편집기 | 영상·텍스트·목소리·음악 트랙을 브라우저에서 고치고 `edit.json`에 저장, mp4 다시 빌드 | `timeline/` |
엔진은 바꿔 끼울 수 있어요. carry와 wordcut이 필요하면 Remotion, 재료가 웹페이지라면 HyperFrames가 맞아요. 비교는 [`references/engines.md`](skills/motion-video-production/references/engines.md)에 있어요.
+## 타임라인 편집기
+
+완성된 편집을 영상·텍스트·목소리·음악 네 트랙으로 열어요. 컷 지점을 옮기고, 자막을 고치거나 위치를 바꾸고, 대사를 밀고, 게인과 페이드를 정한 뒤 mp4를 다시 만들어요. Node.js와 ffmpeg 말고는 설치할 게 없어요.
+
+```bash
+node "$SKILL_ROOT/timeline/serve.mjs" "$PROJECT_ROOT" # 브라우저에서 편집기가 열려요
+```
+
+![타임라인 편집기: 미리보기, 속성 패널, 박 격자 위의 영상·텍스트·목소리·음악 트랙](docs/assets/timeline.png)
+
+- **파일 하나, 편집자 둘.** 브라우저와 에이전트가 같은 코어로 같은 `edit.json`을 고쳐요(에이전트는 `timeline/apply.mjs`). 서로 고친 내용이 2초 안에 보이고, 되돌리기도 돼요.
+- **게이트가 실시간이에요.** 위쪽 알약이 고칠 때마다 편집 게이트의 타이밍 검사를 돌려요. 컷이 박자 위에 있는지, 빈틈이 없는지, 대사가 컷 안에 있는지. 문제가 있는 항목은 주황색 테두리가 생겨요.
+- **빌드는 에이전트와 같아요.** `timeline/build.mjs`가 소스를 프레임 단위로 자르고, 소리마다 게인·페이드를 적용해 섞고(음악은 목소리 아래로 낮춰요), 자막을 미리보기와 같은 모양으로 화면에 새겨요(libass가 있는 ffmpeg 필요, macOS는 `brew install ffmpeg-full`).
+
+형식, op, 한계는 [`timeline/README.md`](skills/motion-video-production/timeline/README.md)에 있어요.
+
## 레퍼런스 분석
![레퍼런스 분석: 레퍼런스를 목표값으로 바꾸고, 렌더 결과를 같은 분석기로 재서 gate.py ref가 비교](docs/assets/reference.ko.png)
@@ -235,6 +252,7 @@ skills/motion-video-production/ 설치하는 스킬 폴더 (아래 전체
templates/ ANALYSIS.md, STORY.md, BEATSHEET.md, MUSIC_BRIEF.md 외
engines/remotion/ carry 데모, wordcut 템플릿, 렌더·목소리·스코어 파이프라인
engines/hyperframes/ HTML/GSAP carry 데모
+ timeline/ 타임라인 편집기(브라우저), apply.mjs(에이전트 편집), build.mjs(edit.json -> mp4)
```
## 검증 범위
diff --git a/README.md b/README.md
index a7244d0..6709507 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
An **Agent Skill** for making 15–90 second motion graphics, promo and character videos with music and voice, where **every stage is checked before the next one starts**. It ships a reference-video analyzer, seven stage gates and two render engines (Remotion, HyperFrames). Codex, Claude Code and other skill-capable runtimes use the same skill folder.
-**Jump to** · [Why gates](#why-gates) · [Quick start](#quick-start) · [Installation](#installation) · [What's inside](#whats-inside) · [Reference analysis](#reference-analysis) · [Workflow](#workflow) · [Harness](#harness) · [Seven consistency criteria](#seven-consistency-criteria) · [Gotchas](#gotchas) · [Reference docs](#reference-docs) · [Required tools](#required-tools) · [Known limitations](#known-limitations) · [Verification scope](#verification-scope)
+**Jump to** · [Why gates](#why-gates) · [Quick start](#quick-start) · [Installation](#installation) · [What's inside](#whats-inside) · [Timeline editor](#timeline-editor) · [Reference analysis](#reference-analysis) · [Workflow](#workflow) · [Harness](#harness) · [Seven consistency criteria](#seven-consistency-criteria) · [Gotchas](#gotchas) · [Reference docs](#reference-docs) · [Required tools](#required-tools) · [Known limitations](#known-limitations) · [Verification scope](#verification-scope)
## Why gates
@@ -108,9 +108,26 @@ The agent answers in your language. Gate output and most reference docs are writ
| Voice and music | ElevenLabs and Fish Audio voices via the composio CLI, a procedural score on the timing | `vo.mjs`, `score.mjs` |
| HyperFrames engine | Animates plain HTML/CSS pages with GSAP and renders them to mp4 | `engines/hyperframes/` |
| Reference analysis | Takes a reference video apart with OpenCV into target numbers | `scripts/ref-analyze.py` |
+| Timeline editor | Picture, text, voice and music tracks in the browser; edits `edit.json`, rebuilds the mp4 | `timeline/` |
The engine is swappable. Use Remotion when you need carry and wordcut, HyperFrames when the source material is web pages. The comparison is in [`references/engines.md`](skills/motion-video-production/references/engines.md).
+## Timeline editor
+
+The finished edit opens as four tracks: picture, text, voice and music. Move a cut point, retime or rewrite a caption, slide a line of dialogue, set gain and fades, then rebuild the mp4. No install beyond Node.js and ffmpeg.
+
+```bash
+node "$SKILL_ROOT/timeline/serve.mjs" "$PROJECT_ROOT" # opens the editor in your browser
+```
+
+![Timeline editor: preview, inspector, and picture, text, voice and music tracks on a beat grid](docs/assets/timeline.png)
+
+- **One file, two editors.** The browser and the agent change the same `edit.json` through the same core (`timeline/apply.mjs` for the agent). Each sees the other's edit within two seconds; undo works on both.
+- **The gate is live.** The pill in the top bar runs the edit gate's timing checks on every change: cuts on the beat, no gaps, each line inside its cut. The item at fault turns orange.
+- **Build is the same as the agent's.** `timeline/build.mjs` cuts the sources frame-exact, mixes every sound with its gain and fades (music ducks under voice) and burns the captions into the picture as they look in the preview (needs ffmpeg with libass; on macOS `brew install ffmpeg-full`).
+
+Format, ops and limits: [`timeline/README.md`](skills/motion-video-production/timeline/README.md).
+
## Reference analysis
![Reference analysis: the reference becomes targets, the render is measured by the same analyzer, gate.py ref compares them](docs/assets/reference.png)
@@ -237,6 +254,7 @@ skills/motion-video-production/ Skill folder to install (everything below
templates/ ANALYSIS.md, STORY.md, BEATSHEET.md, MUSIC_BRIEF.md and more
engines/remotion/ carry demo, wordcut template, render, voice and score pipeline
engines/hyperframes/ HTML/GSAP carry demo
+ timeline/ timeline editor (browser), apply.mjs (agent edits), build.mjs (edit.json -> mp4)
```
## Verification scope
diff --git a/docs/assets/timeline.png b/docs/assets/timeline.png
new file mode 100644
index 0000000..0406c6e
Binary files /dev/null and b/docs/assets/timeline.png differ
diff --git a/skills/motion-video-production/SKILL.md b/skills/motion-video-production/SKILL.md
index dcd0398..1721a38 100644
--- a/skills/motion-video-production/SKILL.md
+++ b/skills/motion-video-production/SKILL.md
@@ -142,6 +142,13 @@ python3 "$SKILL_ROOT/harness/gate.py" <단계> "$PROJECT_ROOT"
- 믹스와 mux는 `bash "$SKILL_ROOT/scripts/mix-mux.sh" <picture.mp4> <fps> <초> <music.wav> <vo.wav|-> <out.mp4>`로 합니다. 프레임 수가 맞을 때만 mux하고, 대사가 나올 때 음악을 낮춥니다.
- 최종 확인은 `bash "$SKILL_ROOT/scripts/verify.sh" <mp4>`(`PRODUCTION=productions/<id>`를 주면 carry 검사도 함께)로 하고, 생성된 컨택트 시트를 직접 봅니다. 레퍼런스가 있으면 `gate.py ref`로 비교합니다.
+### 타임라인 편집기 (조립 뒤 사람이 직접 고칠 때)
+- 만든 영상을 사용자가 타임라인으로 보고 고치게 하려면 `node "$SKILL_ROOT/timeline/serve.mjs" "$PROJECT_ROOT"`를 실행합니다. 브라우저에 영상·텍스트·목소리·음악 네 트랙이 뜹니다. Node 표준 라이브러리와 ffmpeg만 씁니다(설치 없음).
+- 기준 파일은 `edit.json` 하나입니다. 게이트가 읽는 `cuts`에 선택 트랙 `text`(자막)와 `audio`(목소리·음악: `file`, `t`, `in`, `d`, `gain` dB, `fadeIn`, `fadeOut`, 음악의 `duck`)를 더합니다. 형식은 `timeline/README.md`에 있습니다. 목소리 항목의 `id`는 `voices.json`의 대사 id와 같게 씁니다.
+- 에이전트도 같은 코어로 고칩니다: `node "$SKILL_ROOT/timeline/apply.mjs" "$PROJECT_ROOT" ops.json`(인자 없이 실행하면 타임라인과 문제 목록 출력). 열린 편집기는 2초 안에 바뀐 내용을 받습니다. 사용자가 편집기에서 고친 뒤에는 `apply.mjs`로 다시 읽고 이어갑니다.
+- 결과물은 `node "$SKILL_ROOT/timeline/build.mjs" "$PROJECT_ROOT"`(편집기의 Build 버튼과 같음)로 `out/final.mp4`를 만듭니다. 컷은 소스에서 프레임 단위로 자르고, 오디오는 항목마다 위치·게인·페이드를 적용해 섞고(음악은 목소리 아래로 낮춤), 텍스트는 화면에 새기고(libass 필요. macOS는 `brew install ffmpeg-full`, 빌드가 자동으로 찾음) `out/captions.srt`도 씁니다. libass가 없거나 `--no-burn`이면 자막 트랙으로만 넣습니다. 그다음 `gate.py edit`, `gate.py final`을 돌립니다.
+- 첫 저장 때 원래 `edit.json`을 `qa/timeline/`에 복사해 둡니다.
+
### 브랜드 소개 영상과 홈페이지 (레시피)
"우리 가게 소개 영상을 홈페이지에 넣고 싶다"는 요청은 이 순서로 만듭니다. 새 엔진 없이 wordcut 템플릿과 `templates/homepage-intro.html`을 씁니다. 자세한 순서와 예시는 `references/brand-intro.md`에 있습니다.
1. 레퍼런스를 읽고(있으면 0단계) 장면 목록을 4줄 이하로 씁니다. 한 줄 = 프레임 범위, 화면, 빌려 오는 레퍼런스.
@@ -179,5 +186,6 @@ python3 "$SKILL_ROOT/harness/gate.py" <단계> "$PROJECT_ROOT"
| `verify.sh` | 영상 측정, 반복 프레임, 가장자리 색, 컨택트 시트, 받아쓰기, 선택적 carry 검사 |
| `beat-grid.py` | BPM 기준 박 길이·스냅 계산 |
| `../harness/gate.py` | 단계별 통과 여부를 종료 코드로 판정 |
+| `../timeline/serve.mjs`, `apply.mjs`, `build.mjs` | 타임라인 편집기, 에이전트용 편집 CLI, edit.json → mp4 빌드 |
엔진 폴더의 스크립트(`pipeline/render.mjs`, `probe.mjs`, `score.mjs`, `vo.mjs`, `vo-assemble.mjs`, `productions/wordcut/*.mjs`)는 `references/engines.md`에 정리돼 있습니다.
diff --git a/skills/motion-video-production/harness/selftest.sh b/skills/motion-video-production/harness/selftest.sh
index 9b5beae..b397440 100644
--- a/skills/motion-video-production/harness/selftest.sh
+++ b/skills/motion-video-production/harness/selftest.sh
@@ -147,5 +147,12 @@ else
echo "skip ICC 회귀 사례 (PIL 없음)"
fi
+# 타임라인 코어(편집기·에이전트 CLI·빌드가 같이 쓰는 순수 함수)
+if command -v node >/dev/null; then
+ if node --test "$HERE/../timeline/core.test.mjs" >/dev/null 2>&1; then echo "ok 타임라인 코어 테스트"; else echo "FAIL 타임라인 코어 테스트 (node --test timeline/core.test.mjs)"; fails=$((fails+1)); fi
+else
+ echo "skip 타임라인 코어 테스트 (node 없음)"
+fi
+
echo "-- 셀프테스트 실패 $fails 건"
(( fails == 0 ))
diff --git a/skills/motion-video-production/timeline/README.md b/skills/motion-video-production/timeline/README.md
new file mode 100644
index 0000000..2b0dc3d
--- /dev/null
+++ b/skills/motion-video-production/timeline/README.md
@@ -0,0 +1,78 @@
+# Timeline editor
+
+See the finished edit as four tracks (picture, text, voice, music), change it in the browser, and build the mp4 again. The agent edits the same file through the same core, so the person and the agent never work on two copies.
+
+```bash
+node "$SKILL_ROOT/timeline/serve.mjs" "$PROJECT_ROOT" # opens http://127.0.0.1:4321/
+node "$SKILL_ROOT/timeline/apply.mjs" "$PROJECT_ROOT" # print the timeline and its problems
+node "$SKILL_ROOT/timeline/apply.mjs" "$PROJECT_ROOT" ops.json # agent edit (or - for stdin)
+node "$SKILL_ROOT/timeline/build.mjs" "$PROJECT_ROOT" [--no-burn] # edit.json -> out/final.mp4
+```
+
+Needs Node.js 24+ and ffmpeg. No `npm install`. The page loads Pretendard and JetBrains Mono from jsDelivr and falls back to system fonts offline.
+
+## In the editor
+
+| Do | How |
+|---|---|
+| Play, scrub | Space, click or drag the ruler |
+| Move the cut point between two shots | Drag the line between them. Cuts stay back to back; the right shot keeps showing the same moment of its source |
+| Move or trim text and sound | Drag the body; drag an edge |
+| Edit a caption | Double-click it, or type in the inspector |
+| Add a caption | T (at the playhead) |
+| Gain, fades, ducking | Inspector, with a sound selected |
+| Nudge | ← → by a frame, Shift by a beat |
+| Snap | On by default: item edges and the playhead within 8 px, otherwise the beat. S toggles, Alt bypasses |
+| Undo, redo | ⌘Z, ⇧⌘Z |
+| Zoom | ⌘ or Ctrl + wheel |
+
+Every change is saved to `edit.json` at once; the first save of a session copies the original to `qa/timeline/`. The pill in the top bar runs the same timing checks as the edit gate (beat grid, contiguous cuts, a line inside its cut) plus file-length checks, and the item at fault gets an orange outline. **Run gate** runs `gate.py edit`; **Build mp4** runs `build.mjs`.
+
+If someone else changes `edit.json` while the editor is open (the agent, a text editor), the editor reloads within two seconds. If both change it at once, the editor's change is refused (revision conflict) and the editor shows the current file.
+
+## edit.json
+
+The gates read `bpm`, `fps`, `width`, `height` and `cuts`. The editor adds two optional tracks the gates ignore.
+
+```json
+{
+ "bpm": 96, "fps": 30, "width": 1280, "height": 720,
+ "cuts": [
+ { "t": 0, "d": 5, "src": "clip:01@0" },
+ { "t": 5, "d": 5, "src": "clip:[email protected]", "line": "n1" }
+ ],
+ "text": [
+ { "t": 5.625, "d": 2.5, "text": "Gather it, and it fits on one page." }
+ ],
+ "audio": [
+ { "id": "music", "kind": "music", "file": "audio/score.wav", "t": 0, "d": 10, "gain": -6, "fadeOut": 1.875 },
+ { "id": "n1", "kind": "voice", "file": "vo/n1.wav", "t": 5.625, "d": 2.4 }
+ ]
+}
+```
+
+- `cuts[].src` is `clip:<name>@<second>` (`clip/<name>.mp4`) or `file:<path>@<second>` for any video in the project, such as an engine render.
+- `audio[]`: `t` where it starts on the timeline, `in` where it starts in the file, `d` how long, `gain` in dB (−60 to 12), `fadeIn` and `fadeOut` in seconds, `duck: false` to keep music at full level under voice. A voice item's `id` matches its line id in `voices.json`, and a cut's `line` names it.
+- Items get ids (`c1`, `t1`, `a1`) the first time they are saved. Times are seconds.
+
+## Ops (agents)
+
+`apply.mjs` takes a JSON array. The batch is applied all or nothing, and the editor's undo uses the inverse ops the core returns.
+
+```json
+[
+ { "op": "update", "track": "text", "id": "t1", "patch": { "text": "New line", "t": 6.25 } },
+ { "op": "update", "track": "audio", "id": "music", "patch": { "gain": -9 } },
+ { "op": "create", "track": "text", "item": { "t": 10.625, "d": 2.5, "text": "Second line" } },
+ { "op": "delete", "track": "text", "id": "t3" }
+]
+```
+
+A patch field set to `null` removes it. Shape errors (a missing file name, gain out of range) refuse the batch; timing problems come back as BLOCK and WARN lines so a half-finished edit can be saved.
+
+## Limits
+
+- Preview plays the clips and sounds as they are, with the same gains and fades; it does not apply the build's loudness normalization, and ducking is approximated.
+- Text is plain captions. Styled on-screen type belongs in the engine (Remotion or HyperFrames); render it, then place the render as a `file:` cut.
+- Captions are burned into the picture, matching the preview, when ffmpeg has libass. The build uses `$FFMPEG`, else `ffmpeg` on PATH, else Homebrew's keg-only `ffmpeg-full` (`brew install ffmpeg-full`; the plain `ffmpeg` formula has no libass). Without libass, or with `--no-burn`, the text goes in as a subtitle track. `out/captions.srt` is always written.
+- Cuts can be re-timed but not reordered or added in the editor yet; ask the agent (one `create` or `update` op).
diff --git a/skills/motion-video-production/timeline/apply.mjs b/skills/motion-video-production/timeline/apply.mjs
new file mode 100644
index 0000000..1fe9241
--- /dev/null
+++ b/skills/motion-video-production/timeline/apply.mjs
@@ -0,0 +1,37 @@
+#!/usr/bin/env node
+// The agent's entry to the timeline: the same core the editor uses.
+// node apply.mjs <project> print the timeline and its diagnostics
+// node apply.mjs <project> ops.json apply ops (a JSON array) and write edit.json
+// node apply.mjs <project> - read the ops from stdin
+// An open editor picks the change up within two seconds. Exit 0 = applied (or printed) with no errors, 1 = errors.
+import { readFileSync } from 'node:fs';
+import { apply, length, validate } from './core.mjs';
+import { media, open, read, write } from './project.mjs';
+
+const [, , root, opsArg] = process.argv;
+if (!root) { console.error('usage: node apply.mjs <project> [ops.json|-]'); process.exit(2); }
+const p = open(root);
+let doc = read(p);
+let diagnostics;
+if (opsArg) {
+ const ops = JSON.parse(readFileSync(opsArg === '-' ? 0 : opsArg, 'utf8'));
+ const r = apply(doc, ops, media(p, doc));
+ if (!r.ok) { print(r.diagnostics); process.exit(1); }
+ write(p, r.doc);
+ doc = r.doc;
+ diagnostics = r.diagnostics;
+ console.log(`applied ${ops.length} op(s) to ${p.file}`);
+} else diagnostics = validate(doc, media(p, doc));
+
+const f = (x) => x.toFixed(2).padStart(6);
+console.log(`${doc.bpm} BPM · ${doc.fps} fps · ${length(doc).toFixed(2)} s`);
+for (const c of doc.cuts) console.log(`cut ${c.id.padEnd(5)} ${f(c.t)} +${f(c.d)} ${c.src}${c.line ? ` line ${c.line}` : ''}`);
+for (const x of doc.text) console.log(`text ${x.id.padEnd(5)} ${f(x.t)} +${f(x.d)} ${JSON.stringify(x.text)}`);
+for (const a of doc.audio) console.log(`${a.kind.padEnd(5)} ${a.id.padEnd(5)} ${f(a.t)} +${f(a.d)} ${a.file}@${a.in} ${a.gain} dB`);
+print(diagnostics);
+process.exit(diagnostics.some((d) => d.severity === 'error') ? 1 : 0);
+
+function print(ds) {
+ if (!ds.length) return console.log('no problems');
+ for (const d of ds) console.log(`${d.severity === 'error' ? 'BLOCK' : 'WARN '} ${d.code} ${d.message}`);
+}
diff --git a/skills/motion-video-production/timeline/build.mjs b/skills/motion-video-production/timeline/build.mjs
new file mode 100644
index 0000000..90b2ba4
--- /dev/null
+++ b/skills/motion-video-production/timeline/build.mjs
@@ -0,0 +1,101 @@
+#!/usr/bin/env node
+// Build out/final.mp4 from edit.json: cuts from their sources, every audio item at its place with its gain and fades
+// (music ducks under voice unless duck is false), text as out/captions.srt plus a subtitle track.
+// node build.mjs <project> [--no-burn] text is drawn into the picture (libass); --no-burn keeps it as a subtitle track only
+// ffmpeg: $FFMPEG, else the first of `ffmpeg` on PATH and Homebrew's keg-only ffmpeg-full that has the subtitles filter.
+// Frame starts are rounded once from cumulative time (G12), so the frame count matches gate.py final.
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { length, validate } from './core.mjs';
+import { inside, media, open, read, srcPath } from './project.mjs';
+
+const [, , root, ...flags] = process.argv;
+if (!root) { console.error('usage: node build.mjs <project> [--burn]'); process.exit(2); }
+const p = open(root);
+const hasSubs = (bin) => { try { return execFileSync(bin, ['-hide_banner', '-filters'], { encoding: 'utf8' }).includes(' subtitles '); } catch { return false; } };
+const FFMPEG = process.env.FFMPEG
+ || ['ffmpeg', '/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg', '/usr/local/opt/ffmpeg-full/bin/ffmpeg'].find((b) => (b === 'ffmpeg' || existsSync(b)) && hasSubs(b))
+ || 'ffmpeg';
+const doc = read(p);
+const errors = validate(doc, media(p, doc)).filter((d) => d.severity === 'error');
+if (errors.length) {
+ for (const d of errors) console.error(`BLOCK ${d.code} ${d.message}`);
+ process.exit(1);
+}
+
+const F = doc.fps, total = length(doc), frames = Math.round(total * F);
+const cuts = [...doc.cuts].sort((a, b) => a.t - b.t);
+const abs = (rel) => {
+ const a = inside(p, rel);
+ if (!a || !existsSync(a)) { console.error(`missing file: ${rel}`); process.exit(1); }
+ return a;
+};
+let [W, H] = [doc.width, doc.height];
+if (!W || !H) {
+ const s = execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0', abs(srcPath(cuts[0].src).path)], { encoding: 'utf8' }).trim().split(',');
+ [W, H] = s.map(Number);
+}
+
+const inputs = [], graph = [];
+cuts.forEach((c, i) => {
+ const s = srcPath(c.src), rate = c.rate ?? 1;
+ inputs.push('-ss', String(s.at), '-t', String(c.d * rate + 1), '-i', abs(s.path));
+ const n = Math.round((c.t + c.d) * F) - Math.round(c.t * F);
+ graph.push(`[${i}:v]setpts=(PTS-STARTPTS)/${rate},fps=${F},scale=${W}:${H}:force_original_aspect_ratio=decrease,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,tpad=stop_mode=clone:stop_duration=${c.d},trim=end_frame=${n},setpts=PTS-STARTPTS[v${i}]`);
+});
+graph.push(`${cuts.map((_, i) => `[v${i}]`).join('')}concat=n=${cuts.length}:v=1:a=0[vout]`);
+
+const voices = [], music = [];
+doc.audio.forEach((a, k) => {
+ const i = cuts.length + k, ms = Math.round(a.t * 1000);
+ inputs.push('-ss', String(a.in), '-t', String(a.d), '-i', abs(a.file));
+ const fades = [a.fadeIn > 0 && `afade=t=in:d=${a.fadeIn}`, a.fadeOut > 0 && `afade=t=out:st=${Math.max(0, a.d - a.fadeOut)}:d=${a.fadeOut}`].filter(Boolean);
+ graph.push(`[${i}:a]aformat=sample_rates=48000:channel_layouts=stereo,volume=${a.gain}dB${fades.map((f) => `,${f}`).join('')},adelay=${ms}:all=1[a${k}]`);
+ (a.kind === 'voice' ? voices : music).push({ label: `a${k}`, duck: a.duck !== false });
+});
+const mix = (list, out) => graph.push(list.length === 1 ? `[${list[0].label}]anull[${out}]` : `${list.map((x) => `[${x.label}]`).join('')}amix=inputs=${list.length}:normalize=0[${out}]`);
+let audio;
+if (!voices.length && !music.length) {
+ graph.push(`anullsrc=r=48000:cl=stereo,atrim=duration=${total}[aout]`);
+ audio = 'aout';
+} else {
+ const parts = [];
+ if (voices.length) mix(voices, 'vo');
+ if (music.length) mix(music, 'mu');
+ if (voices.length && music.length && music.some((m) => m.duck)) {
+ // same ducking as scripts/mix-mux.sh: the voice keys a compressor on the music
+ graph.push('[vo]asplit=2[vo1][key]', '[mu][key]sidechaincompress=threshold=0.03:ratio=5:attack=15:release=250:makeup=1[mud]');
+ parts.push('vo1', 'mud');
+ } else parts.push(...(voices.length ? ['vo'] : []), ...(music.length ? ['mu'] : []));
+ graph.push(`${parts.map((x) => `[${x}]`).join('')}amix=inputs=${parts.length}:normalize=0,apad,atrim=duration=${total},loudnorm=I=-14:TP=-1.5:LRA=9,aresample=48000[aout]`);
+ audio = 'aout';
+}
+
+mkdirSync(join(p.root, 'out'), { recursive: true });
+const srt = join(p.root, 'out', 'captions.srt');
+const tc = (s) => { const ms = Math.round(s * 1000); return `${String(Math.floor(ms / 3600000)).padStart(2, '0')}:${String(Math.floor(ms / 60000) % 60).padStart(2, '0')}:${String(Math.floor(ms / 1000) % 60).padStart(2, '0')},${String(ms % 1000).padStart(3, '0')}`; };
+const texts = [...doc.text].sort((a, b) => a.t - b.t);
+writeFileSync(srt, texts.map((x, i) => `${i + 1}\n${tc(x.t)} --> ${tc(Math.min(total, x.t + x.d))}\n${x.text}\n`).join('\n'));
+
+const canBurn = hasSubs(FFMPEG);
+const burn = !flags.includes('--no-burn') && texts.length > 0;
+if (burn && !canBurn) console.warn(`${FFMPEG} has no subtitles filter (libass), so the text goes in as a subtitle track only. macOS: brew install ffmpeg-full; elsewhere: an ffmpeg built with libass, or set FFMPEG=<path>`);
+let vout = 'vout';
+if (burn && canBurn) {
+ // same look as the editor preview: bold paper text with an ink outline, 7% above the bottom (sizes on libass's 288-line canvas)
+ graph.push(`[vout]subtitles=captions.srt:force_style='FontName=Pretendard,Bold=1,FontSize=23,PrimaryColour=&H00F7FAFA,OutlineColour=&H00090A0A,BorderStyle=1,Outline=2,Shadow=0,MarginV=20,MarginL=24,MarginR=24'[vsub]`);
+ vout = 'vsub';
+}
+const subIn = texts.length && !(burn && canBurn) ? ['-i', srt] : [];
+const subIndex = cuts.length + doc.audio.length;
+const out = join(p.root, 'out', 'final.mp4');
+execFileSync(FFMPEG, [
+ '-v', 'error', '-y', ...inputs, ...subIn,
+ '-filter_complex', graph.join(';'),
+ '-map', `[${vout}]`, '-map', `[${audio}]`, ...(subIn.length ? ['-map', `${subIndex}:s`, '-c:s', 'mov_text', '-metadata:s:s:0', 'language=und'] : []),
+ '-frames:v', String(frames), '-r', String(F), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18',
+ '-c:a', 'aac', '-b:a', '256k', '-movflags', '+faststart', out,
+], { stdio: 'inherit', cwd: join(p.root, 'out') }); // cwd so the subtitles filter gets a plain file name
+console.log(`built ${out}: ${frames} frames at ${F} fps, ${cuts.length} cuts, ${doc.audio.length} audio items, ${texts.length} text items${burn && canBurn ? ' (burned in, also out/captions.srt)' : texts.length ? ' (subtitle track + out/captions.srt)' : ''} with ${FFMPEG}`);
+console.log(`next: python3 "$SKILL_ROOT/harness/gate.py" final "${p.root}"`);
diff --git a/skills/motion-video-production/timeline/core.mjs b/skills/motion-video-production/timeline/core.mjs
new file mode 100644
index 0000000..2512165
--- /dev/null
+++ b/skills/motion-video-production/timeline/core.mjs
@@ -0,0 +1,229 @@
+// Timeline core: inspect · apply · validate over the project's edit.json.
+// Pure functions, no DOM and no Node APIs, so the editor (browser), the server and the agent CLI share one file.
+// The shape follows the stage contract the gates already read (bpm, fps, cuts[t, d, src, line?, rate?]) and adds
+// two optional tracks the gates ignore: text[] and audio[].
+//
+// cuts [{ id, t, d, src: "clip:<name>@<s>" | "file:<path>@<s>", line?, rate? }] contiguous from 0
+// text [{ id, t, d, text }] captions / on-screen lines
+// audio [{ id, kind: "voice" | "music", file, t, in, d, gain, fadeIn, fadeOut, duck? }] gain in dB, times in s
+//
+// apply() takes atomic ops and is all-or-nothing. It returns the new doc and the inverse ops (undo), never mutates.
+
+export const TRACKS = ['cuts', 'text', 'audio'];
+const PREFIX = { cuts: 'c', text: 't', audio: 'a' };
+const EPS = 1e-6;
+
+const num = (x) => typeof x === 'number' && Number.isFinite(x);
+const round = (x, p = 1e4) => Math.round(x * p) / p;
+const clone = (x) => (x === undefined ? x : JSON.parse(JSON.stringify(x)));
+
+export const beat = (doc) => 60 / doc.bpm;
+export const length = (doc) => Math.max(0, ...doc.cuts.map((c) => c.t + c.d));
+export const frame = (doc) => 1 / (doc.fps || 30);
+
+/** Fill defaults and ids so every item can be addressed. Returns a new doc. */
+export function normalize(raw) {
+ const doc = clone(raw) || {};
+ doc.fps ??= 30;
+ for (const track of TRACKS) doc[track] = Array.isArray(doc[track]) ? doc[track] : [];
+ for (const track of TRACKS) {
+ const used = new Set(doc[track].map((x) => x.id).filter(Boolean));
+ let n = 1;
+ for (const x of doc[track]) {
+ if (x.id) continue;
+ while (used.has(PREFIX[track] + n)) n++;
+ x.id = PREFIX[track] + n;
+ used.add(x.id);
+ }
+ }
+ for (const a of doc.audio) {
+ a.kind ??= 'music';
+ a.in ??= 0;
+ a.gain ??= 0;
+ a.fadeIn ??= 0;
+ a.fadeOut ??= 0;
+ }
+ doc.cuts.sort((a, b) => a.t - b.t);
+ return doc;
+}
+
+/** Schema problems that make a doc unusable. Empty array means the shape is fine. */
+function shapeErrors(doc) {
+ const e = [];
+ if (!num(doc.bpm) || doc.bpm <= 0) e.push('bpm must be a positive number');
+ if (!num(doc.fps) || doc.fps <= 0) e.push('fps must be a positive number');
+ for (const track of TRACKS) {
+ const ids = new Set();
+ for (const x of doc[track]) {
+ if (typeof x.id !== 'string' || !x.id) e.push(`${track}: item without id`);
+ else if (ids.has(x.id)) e.push(`${track}: duplicate id ${x.id}`);
+ ids.add(x.id);
+ if (!num(x.t) || x.t < -EPS) e.push(`${track} ${x.id}: t must be >= 0`);
+ if (!num(x.d) || x.d <= 0) e.push(`${track} ${x.id}: d must be > 0`);
+ }
+ }
+ for (const c of doc.cuts) if (typeof c.src !== 'string' || !/^(clip|file):[^@]+@[0-9.]+$/.test(c.src)) e.push(`cuts ${c.id}: src must be clip:<name>@<s> or file:<path>@<s>`);
+ for (const x of doc.text) if (typeof x.text !== 'string') e.push(`text ${x.id}: text must be a string`);
+ for (const a of doc.audio) {
+ if (typeof a.file !== 'string' || !a.file) e.push(`audio ${a.id}: file is required`);
+ if (a.kind !== 'voice' && a.kind !== 'music') e.push(`audio ${a.id}: kind must be voice or music`);
+ if (!num(a.in) || a.in < 0) e.push(`audio ${a.id}: in must be >= 0`);
+ if (!num(a.gain) || a.gain < -60 || a.gain > 12) e.push(`audio ${a.id}: gain must be -60..12 dB`);
+ if (!num(a.fadeIn) || !num(a.fadeOut) || a.fadeIn < 0 || a.fadeOut < 0 || a.fadeIn + a.fadeOut > a.d + EPS) e.push(`audio ${a.id}: fades must be >= 0 and fit in d`);
+ }
+ return e;
+}
+
+/**
+ * Timing checks, the same ones the gates make (B02 beat grid, B03 contiguous cuts, B05 line inside its cut)
+ * plus editor checks. media: { [path]: seconds } for files whose length is known.
+ * Returns [{ code, severity: "error" | "warn", ids, message }].
+ */
+export function validate(doc, media = {}) {
+ const out = shapeErrors(doc).map((message) => ({ code: 'S01', severity: 'error', ids: [], message }));
+ if (out.length) return out;
+ const add = (code, severity, ids, message) => out.push({ code, severity, ids, message });
+ const b = beat(doc), half = frame(doc) / 2, end = length(doc);
+ const cuts = [...doc.cuts].sort((x, y) => x.t - y.t);
+ if (!cuts.length) add('B01', 'error', [], 'no cuts yet');
+ for (const c of cuts) {
+ for (const [what, v] of [['start', c.t], ['end', c.t + c.d]]) {
+ const off = Math.abs(v / b - Math.round(v / b)) * b;
+ if (off > half + EPS) add('B02', 'warn', [c.id], `cut ${what} ${v.toFixed(3)} s is ${(off * 1000).toFixed(0)} ms off the beat`);
+ }
+ }
+ if (cuts.length && Math.abs(cuts[0].t) > frame(doc) + EPS) add('B03', 'error', [cuts[0].id], 'the first cut must start at 0');
+ for (let i = 0; i + 1 < cuts.length; i++) {
+ const gap = cuts[i + 1].t - (cuts[i].t + cuts[i].d);
+ if (Math.abs(gap) > frame(doc) + EPS) add('B03', 'error', [cuts[i].id, cuts[i + 1].id], `${gap > 0 ? 'gap' : 'overlap'} of ${Math.abs(gap).toFixed(3)} s between cuts`);
+ }
+ const voice = new Map(doc.audio.filter((a) => a.kind === 'voice').map((a) => [a.id, a]));
+ for (const c of cuts) {
+ const v = c.line && voice.get(c.line);
+ if (v && (v.t < c.t - EPS || v.t + v.d > c.t + c.d + EPS)) add('B05', 'error', [c.id, v.id], `line ${v.id} runs outside its cut ${c.id}; the mouth gets cut`);
+ }
+ const texts = [...doc.text].sort((x, y) => x.t - y.t);
+ for (let i = 0; i + 1 < texts.length; i++) {
+ if (texts[i].t + texts[i].d > texts[i + 1].t + EPS) add('T01', 'warn', [texts[i].id, texts[i + 1].id], 'two text items overlap');
+ }
+ for (const x of [...doc.text, ...doc.audio]) {
+ if (end && x.t + x.d > end + EPS) add('X01', 'warn', [x.id], `${x.id} runs ${(x.t + x.d - end).toFixed(2)} s past the last cut`);
+ }
+ for (const a of doc.audio) {
+ const len = media[a.file];
+ if (num(len) && a.in + a.d > len + 0.05) add('A10', 'error', [a.id], `${a.id} uses ${(a.in + a.d).toFixed(2)} s of a ${len.toFixed(2)} s file`);
+ }
+ for (const c of cuts) {
+ const m = /^(clip|file):([^@]+)@([0-9.]+)$/.exec(c.src);
+ const path = m && (m[1] === 'clip' ? `clip/${m[2]}.mp4` : m[2]);
+ const len = path && media[path];
+ if (num(len) && Number(m[3]) + c.d * (c.rate ?? 1) > len + 0.05) add('B06', 'error', [c.id], `${c.id} needs ${(Number(m[3]) + c.d * (c.rate ?? 1)).toFixed(2)} s of a ${len.toFixed(2)} s clip`);
+ }
+ return out;
+}
+
+/** Nearest beat (or frame when beats are off) to t. */
+export function snap(doc, t, { beats = true } = {}) {
+ const step = beats ? beat(doc) : frame(doc);
+ return round(Math.max(0, Math.round(t / step) * step));
+}
+
+/**
+ * Apply ops atomically.
+ * { op: "update", track, id, patch } patch fields; a field set to null is removed
+ * { op: "create", track, item, index? }
+ * { op: "delete", track, id }
+ * Returns { ok: true, doc, inverse, diagnostics } or { ok: false, diagnostics }.
+ * Shape errors refuse the whole batch; timing problems come back as diagnostics so a half-finished edit can be saved.
+ */
+export function apply(doc, ops, media = {}) {
+ if (!Array.isArray(ops) || !ops.length) return refuse('ops must be a non-empty array');
+ let next = clone(doc);
+ const inverse = [];
+ for (const op of ops) {
+ if (!op || !TRACKS.includes(op.track)) return refuse(`unknown track ${op?.track}`);
+ const list = next[op.track];
+ if (op.op === 'update') {
+ const i = list.findIndex((x) => x.id === op.id);
+ if (i < 0) return refuse(`${op.track} ${op.id} not found`);
+ if (!op.patch || typeof op.patch !== 'object' || 'id' in op.patch) return refuse('update needs a patch without id');
+ const prev = list[i];
+ const undo = {};
+ for (const k of Object.keys(op.patch)) undo[k] = k in prev ? clone(prev[k]) : null;
+ const item = { ...prev };
+ for (const [k, v] of Object.entries(op.patch)) {
+ if (v === null) delete item[k];
+ else item[k] = typeof v === 'number' ? round(v) : clone(v);
+ }
+ list[i] = item;
+ inverse.unshift({ op: 'update', track: op.track, id: op.id, patch: undo });
+ } else if (op.op === 'create') {
+ const item = clone(op.item);
+ if (!item || typeof item !== 'object') return refuse('create needs an item');
+ if (!item.id) item.id = freshId(next, op.track);
+ if (list.some((x) => x.id === item.id)) return refuse(`${op.track} ${item.id} already exists`);
+ const at = Number.isInteger(op.index) ? Math.max(0, Math.min(list.length, op.index)) : list.length;
+ list.splice(at, 0, item);
+ inverse.unshift({ op: 'delete', track: op.track, id: item.id });
+ } else if (op.op === 'delete') {
+ const i = list.findIndex((x) => x.id === op.id);
+ if (i < 0) return refuse(`${op.track} ${op.id} not found`);
+ const [gone] = list.splice(i, 1);
+ inverse.unshift({ op: 'create', track: op.track, item: gone, index: i });
+ } else return refuse(`unknown op ${op.op}`);
+ }
+ next = normalize(next);
+ const diagnostics = validate(next, media);
+ if (diagnostics.some((d) => d.code === 'S01')) return { ok: false, diagnostics };
+ return { ok: true, doc: next, inverse, diagnostics };
+}
+
+export function freshId(doc, track) {
+ const used = new Set(doc[track].map((x) => x.id));
+ let n = 1;
+ while (used.has(PREFIX[track] + n)) n++;
+ return PREFIX[track] + n;
+}
+
+/** Where the boundary after cut leftId may go: [earliest, latest], so neither side vanishes or runs out of source. */
+export function rollRange(doc, leftId) {
+ const cuts = [...doc.cuts].sort((a, b) => a.t - b.t);
+ const i = cuts.findIndex((c) => c.id === leftId);
+ const a = cuts[i], b = cuts[i + 1], f = frame(doc);
+ if (!a) return null;
+ if (!b) return [a.t + f, Infinity];
+ const m = /^(clip|file):([^@]+)@([0-9.]+)$/.exec(b.src);
+ // the right cut keeps showing the same moment of its source, so its in-point moves with the boundary
+ const earliest = m ? b.t - Number(m[3]) / (b.rate ?? 1) : -Infinity;
+ return [Math.max(a.t + f, earliest), b.t + b.d - f];
+}
+
+/** Ops that move the boundary between cut leftId and the next cut to time t (a roll edit), clamped to rollRange. */
+export function rollOps(doc, leftId, t) {
+ const range = rollRange(doc, leftId);
+ if (!range) return [];
+ const cuts = [...doc.cuts].sort((a, b) => a.t - b.t);
+ const i = cuts.findIndex((c) => c.id === leftId);
+ const a = cuts[i], b = cuts[i + 1];
+ t = Math.min(range[1], Math.max(range[0], t));
+ if (!b) return [{ op: 'update', track: 'cuts', id: a.id, patch: { d: t - a.t } }];
+ const m = /^(clip|file):([^@]+)@([0-9.]+)$/.exec(b.src);
+ const src = m ? `${m[1]}:${m[2]}@${round(Math.max(0, Number(m[3]) + (t - b.t) * (b.rate ?? 1)))}` : b.src;
+ return [
+ { op: 'update', track: 'cuts', id: a.id, patch: { d: t - a.t } },
+ { op: 'update', track: 'cuts', id: b.id, patch: { t, d: b.t + b.d - t, src } },
+ ];
+}
+
+/** Clean JSON for edit.json: stable key order, defaults dropped where they equal the default. */
+export function serialize(doc) {
+ const { bpm, fps, width, height, cuts, text, audio, ...rest } = doc;
+ const out = { bpm, fps, ...(width ? { width } : {}), ...(height ? { height } : {}), ...rest, cuts };
+ if (text.length) out.text = text;
+ if (audio.length) out.audio = audio;
+ return JSON.stringify(out, null, 2) + '\n';
+}
+
+function refuse(message) {
+ return { ok: false, diagnostics: [{ code: 'S01', severity: 'error', ids: [], message }] };
+}
diff --git a/skills/motion-video-production/timeline/core.test.mjs b/skills/motion-video-production/timeline/core.test.mjs
new file mode 100644
index 0000000..cc567b6
--- /dev/null
+++ b/skills/motion-video-production/timeline/core.test.mjs
@@ -0,0 +1,82 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { apply, normalize, rollOps, serialize, snap, validate } from './core.mjs';
+
+const base = () => normalize({
+ bpm: 120, fps: 30,
+ cuts: [{ t: 0, d: 2, src: 'clip:01@0', line: 'n1' }, { t: 2, d: 2, src: 'clip:[email protected]' }],
+ text: [{ t: 0.5, d: 1, text: 'hello' }],
+ audio: [{ id: 'n1', kind: 'voice', file: 'vo/n1.wav', t: 0.5, d: 1 }, { id: 'm', file: 'audio/score.wav', t: 0, d: 4 }],
+});
+const codes = (ds) => ds.map((d) => d.code).sort();
+
+test('normalize gives ids and audio defaults without touching the input', () => {
+ const raw = { bpm: 120, cuts: [{ t: 0, d: 1, src: 'clip:01@0' }] };
+ const doc = normalize(raw);
+ assert.equal(doc.cuts[0].id, 'c1');
+ assert.equal(raw.cuts[0].id, undefined);
+ assert.deepEqual(base().audio[1], { id: 'm', kind: 'music', file: 'audio/score.wav', t: 0, d: 4, in: 0, gain: 0, fadeIn: 0, fadeOut: 0 });
+});
+
+test('a clean doc has no diagnostics', () => {
+ assert.deepEqual(validate(base()), []);
+});
+
+test('timing checks mirror the gates', () => {
+ const doc = base();
+ doc.cuts[1].t = 2.2; // gap and off-beat start
+ doc.audio[0].d = 2; // line runs past its cut
+ doc.text.push({ id: 't2', t: 1, d: 1, text: 'x' }); // overlaps t1
+ assert.deepEqual(codes(validate(doc, { 'vo/n1.wav': 1.5 })), ['A10', 'B02', 'B02', 'B03', 'B05', 'T01']);
+});
+
+test('apply is atomic and its inverse restores the doc', () => {
+ const doc = base();
+ const r = apply(doc, [
+ { op: 'update', track: 'text', id: 't1', patch: { text: 'bye', t: 1 } },
+ { op: 'create', track: 'text', item: { t: 3, d: 0.5, text: 'new' } },
+ { op: 'delete', track: 'audio', id: 'm' },
+ ]);
+ assert.ok(r.ok);
+ assert.equal(r.doc.text.find((x) => x.id === 't2').text, 'new');
+ assert.equal(doc.text.length, 1, 'input untouched');
+ const back = apply(r.doc, r.inverse);
+ assert.ok(back.ok);
+ assert.deepEqual(back.doc, doc);
+});
+
+test('a bad op refuses the whole batch', () => {
+ const r = apply(base(), [{ op: 'update', track: 'text', id: 't1', patch: { text: 'ok' } }, { op: 'update', track: 'text', id: 'nope', patch: {} }]);
+ assert.equal(r.ok, false);
+ assert.equal(apply(base(), [{ op: 'update', track: 'audio', id: 'm', patch: { gain: 40 } }]).ok, false);
+});
+
+test('update with null removes a field and undo brings it back', () => {
+ const r = apply(base(), [{ op: 'update', track: 'cuts', id: 'c1', patch: { line: null } }]);
+ assert.equal('line' in r.doc.cuts[0], false);
+ assert.equal(apply(r.doc, r.inverse).doc.cuts[0].line, 'n1');
+});
+
+test('roll edit keeps cuts contiguous and moves the right in-point', () => {
+ const doc = base();
+ const r = apply(doc, rollOps(doc, 'c1', 2.5));
+ assert.ok(r.ok);
+ assert.deepEqual(r.doc.cuts.map((c) => [c.t, c.d, c.src]), [[0, 2.5, 'clip:01@0'], [2.5, 1.5, 'clip:02@1']]);
+ assert.ok(!codes(r.diagnostics).includes('B03'));
+});
+
+test('roll edit stops where the right cut would run out of source', () => {
+ const doc = base();
+ const r = apply(doc, rollOps(doc, 'c1', 1));
+ assert.deepEqual(r.doc.cuts.map((c) => [c.t, c.src]), [[0, 'clip:01@0'], [1.5, 'clip:02@0']]);
+});
+
+test('snap goes to the nearest beat', () => {
+ assert.equal(snap(base(), 1.26), 1.5);
+ assert.equal(snap(base(), 1.26, { beats: false }), 1.2667);
+});
+
+test('serialize keeps the gate fields first and drops empty tracks', () => {
+ const doc = normalize({ bpm: 96, cuts: [{ t: 0, d: 1, src: 'clip:01@0' }] });
+ assert.deepEqual(Object.keys(JSON.parse(serialize(doc))), ['bpm', 'fps', 'cuts']);
+});
diff --git a/skills/motion-video-production/timeline/editor.html b/skills/motion-video-production/timeline/editor.html
new file mode 100644
index 0000000..a2eb388
--- /dev/null
+++ b/skills/motion-video-production/timeline/editor.html
@@ -0,0 +1,581 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Timeline</title>
+<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/[email protected]/dist/web/variable/pretendardvariable.min.css">
+<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/500.css">
+<style>
+/* Uncle Jobs, night: ink ground, paper text, one orange accent (the playhead and what needs fixing).
+ Structure from hairlines, hierarchy from size and weight. No shadows, no gradients. */
+:root {
+ --ink-900: #0a0a09; --ink-800: #141413; --ink-700: #232220; --ink-600: #3a3934; --ink-500: #5c5a52; --ink-400: #8e8b7e;
+ --ink-300: #c9c5b6; --paper: #fafaf7; --line: #2a2926; --accent: #ff5a14; --accent-300: #ff9c5c;
+ --sans: "Pretendard Variable", Pretendard, "Apple SD Gothic Neo", system-ui, sans-serif;
+ --mono: "JetBrains Mono", ui-monospace, SFMono-Regular, monospace;
+ --label: 112px; --row: 64px;
+}
+* { box-sizing: border-box; margin: 0; }
+html, body { height: 100%; background: var(--ink-900); color: var(--paper); font: 500 13px/1.4 var(--sans); -webkit-font-smoothing: antialiased; overflow: hidden; }
+button, input, textarea, select { font: inherit; color: inherit; }
+.mono { font-family: var(--mono); font-variant-ligatures: none; font-variant-numeric: tabular-nums; }
+.muted { color: var(--ink-400); }
+.app { display: grid; grid-template-rows: 52px minmax(0, 1fr) auto 26px; height: 100vh; }
+
+/* top bar */
+.bar { display: flex; align-items: center; gap: 20px; padding: 0 20px; border-bottom: 1px solid var(--line); }
+.bar .name { font-weight: 800; font-size: 14px; letter-spacing: -0.01em; }
+.bar .spacer { flex: 1; }
+.btn { background: none; border: 1px solid var(--ink-600); border-radius: 8px; height: 30px; padding: 0 12px; cursor: pointer; white-space: nowrap; }
+.btn:hover { border-color: var(--ink-400); }
+.btn:disabled { opacity: .35; cursor: default; }
+.btn.primary { background: var(--paper); color: var(--ink-900); border-color: var(--paper); font-weight: 700; }
+.icon { width: 30px; padding: 0; display: inline-grid; place-items: center; }
+.toggle { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--ink-400); user-select: none; }
+.toggle input { accent-color: var(--paper); }
+.pill { font: 700 11px/1 var(--mono); letter-spacing: .06em; padding: 7px 10px 6px; border-radius: 999px; white-space: nowrap; border: 1px solid var(--ink-500); cursor: pointer; background: none; }
+.pill.block { background: var(--accent); border-color: var(--accent); color: var(--ink-900); }
+.pill.warn { border-color: var(--accent-300); color: var(--accent-300); }
+.saved { min-width: 120px; text-align: right; }
+
+/* stage: preview + inspector */
+.stage { display: grid; grid-template-columns: minmax(0, 1fr) 320px; min-height: 0; border-bottom: 1px solid var(--line); }
+.viewer { display: flex; flex-direction: column; min-height: 0; padding: 20px 24px 14px; gap: 12px; }
+.screen { position: relative; flex: 1; min-height: 0; display: grid; place-items: center; }
+.frame { position: relative; background: #000; aspect-ratio: var(--ar, 16 / 9); max-width: 100%; max-height: 100%; height: 100%; border-radius: 6px; overflow: hidden; box-shadow: 0 0 0 1px var(--line); }
+.frame video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
+.caption { position: absolute; left: 8%; right: 8%; bottom: 7%; text-align: center; font-weight: 700; font-size: clamp(14px, 5.2cqh, 40px); line-height: 1.35; text-wrap: balance; word-break: keep-all;
+ color: var(--paper); -webkit-text-stroke: 4px var(--ink-900); paint-order: stroke fill; }
+.frame { container-type: size; }
+.transport { display: flex; align-items: center; gap: 14px; justify-content: center; }
+.tc { font-size: 22px; letter-spacing: -0.01em; }
+.tc small { font-size: 13px; color: var(--ink-400); }
+.clock { display: flex; flex-direction: column; gap: 3px; min-width: 210px; margin-left: 6px; }
+.tc { line-height: 1; }
+.beatpos { font-size: 11px; line-height: 1; letter-spacing: .02em; }
+
+.inspector { border-left: 1px solid var(--line); padding: 20px; overflow: auto; }
+.inspector h2 { font-size: 15px; font-weight: 800; letter-spacing: -0.01em; }
+.inspector .kind { font: 500 11px/1 var(--mono); color: var(--ink-400); letter-spacing: .04em; margin-bottom: 8px; }
+.field { display: grid; gap: 6px; margin-top: 16px; }
+.field > span { color: var(--ink-400); font-size: 12px; }
+.field input, .field textarea { background: var(--ink-800); border: 1px solid var(--ink-700); border-radius: 8px; padding: 8px 10px; width: 100%; }
+.field input:focus, .field textarea:focus { outline: none; border-color: var(--ink-400); }
+.field textarea { min-height: 76px; resize: vertical; line-height: 1.5; word-break: keep-all; }
+.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.range { display: flex; align-items: center; gap: 10px; }
+.range input[type=range] { flex: 1; accent-color: var(--paper); padding: 0; background: none; border: 0; }
+.range output { width: 56px; text-align: right; }
+.diag { margin-top: 22px; border-top: 1px solid var(--line); padding-top: 14px; display: grid; gap: 10px; }
+.diag div { display: grid; grid-template-columns: 42px 1fr; gap: 8px; cursor: pointer; }
+.diag b { font: 700 11px/1.5 var(--mono); }
+.diag .error b { color: var(--accent); }
+.diag .warn b { color: var(--accent-300); }
+.empty { color: var(--ink-400); line-height: 1.6; }
+.empty kbd { font: 500 11px var(--mono); border: 1px solid var(--ink-600); border-radius: 4px; padding: 1px 5px; color: var(--ink-300); }
+.actions { display: flex; gap: 8px; margin-top: 20px; }
+
+/* timeline */
+.timeline { position: relative; height: calc(30px + 4 * var(--row) + 1px); overflow-x: auto; overflow-y: hidden; user-select: none; }
+.timeline::-webkit-scrollbar { height: 8px; } .timeline::-webkit-scrollbar-thumb { background: var(--ink-600); border-radius: 4px; }
+.labels { position: absolute; left: 0; top: 0; width: var(--label); z-index: 4; background: var(--ink-900); border-right: 1px solid var(--line); position: sticky; float: left; height: 100%; }
+.labels div { height: var(--row); display: flex; flex-direction: column; justify-content: center; padding: 0 16px; border-top: 1px solid var(--line); font-weight: 700; }
+.labels div:first-child { height: 30px; border-top: 0; }
+.labels small { font: 500 10px/1 var(--mono); color: var(--ink-500); margin-top: 5px; font-weight: 500; }
+.lane-wrap { position: relative; margin-left: var(--label); height: 100%; }
+.ruler { position: relative; height: 30px; cursor: text; }
+.ruler canvas, .grid { position: absolute; left: 0; top: 0; pointer-events: none; }
+.lane { position: relative; height: var(--row); border-top: 1px solid var(--line); }
+.item { position: absolute; top: 7px; bottom: 7px; border-radius: 6px; overflow: hidden; cursor: grab; background: var(--ink-800); box-shadow: inset 0 0 0 1px var(--ink-700); }
+.item.sel { box-shadow: inset 0 0 0 2px var(--paper); z-index: 2; }
+.item.bad { box-shadow: inset 0 0 0 2px var(--accent); }
+.item.sel.bad { box-shadow: inset 0 0 0 2px var(--paper), 0 0 0 2px var(--accent); }
+.item .h { position: absolute; top: 0; bottom: 0; width: 8px; cursor: ew-resize; z-index: 3; }
+.item .h.l { left: 0; } .item .h.r { right: 0; }
+.item .h:hover { background: rgba(250, 250, 247, .18); }
+.item .lab { position: absolute; left: 8px; right: 8px; top: 6px; font-size: 12px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; z-index: 1; }
+.item .sub { position: absolute; left: 8px; bottom: 5px; font: 500 10px/1 var(--mono); color: var(--ink-400); pointer-events: none; z-index: 1; }
+.cut { background-size: auto 100%; background-repeat: repeat-x; }
+.cut .lab, .cut .sub { right: auto; max-width: calc(100% - 16px); background: rgba(10, 10, 9, .78); padding: 3px 6px; border-radius: 4px; }
+.cut .lab { top: 5px; } .cut .sub { bottom: 5px; color: var(--ink-300); }
+.text-item { background: var(--ink-700); }
+.text-item .lab { top: 50%; transform: translateY(-50%); font-weight: 600; }
+.audio-item canvas { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
+.audio-item .lab { color: var(--paper); top: 5px; font-size: 11px; }
+.boundary { position: absolute; top: 4px; bottom: 4px; width: 12px; margin-left: -6px; cursor: col-resize; z-index: 3; }
+.boundary::after { content: ""; position: absolute; left: 5px; top: 0; bottom: 0; width: 2px; border-radius: 1px; background: var(--ink-900); }
+.boundary:hover::after { background: var(--paper); }
+.playhead { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: var(--accent); z-index: 5; pointer-events: none; }
+.playhead::before { content: ""; position: absolute; top: 0; left: -5px; border: 6px solid transparent; border-top: 8px solid var(--accent); }
+.snapline { position: absolute; top: 30px; bottom: 0; width: 1px; background: var(--paper); opacity: .5; z-index: 4; pointer-events: none; display: none; }
+
+.status { display: flex; align-items: center; gap: 18px; padding: 0 20px; border-top: 1px solid var(--line); color: var(--ink-500); font: 500 11px/1 var(--mono); }
+.status .spacer { flex: 1; }
+dialog { background: var(--ink-800); color: var(--paper); border: 1px solid var(--ink-600); border-radius: 12px; padding: 20px; width: min(760px, 90vw); }
+dialog::backdrop { background: rgba(10, 10, 9, .7); }
+dialog pre { font: 500 12px/1.55 var(--mono); max-height: 60vh; overflow: auto; white-space: pre-wrap; margin-top: 12px; color: var(--ink-300); }
+dialog h3 { font-size: 15px; font-weight: 800; }
+.toast { position: fixed; left: 50%; bottom: 44px; transform: translateX(-50%); background: var(--paper); color: var(--ink-900); padding: 9px 14px; border-radius: 8px; font-weight: 700; opacity: 0; transition: opacity .2s; pointer-events: none; z-index: 10; }
+.toast.on { opacity: 1; }
+</style>
+<body>
+<div class="app">
+ <header class="bar">
+ <span class="name" id="name">timeline</span>
+ <span class="mono muted" id="meta"></span>
+ <span class="spacer"></span>
+ <button class="btn icon" id="undo" title="Undo (⌘Z)" disabled><svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 3.5 2.5 6.5l3 3"/><path d="M2.5 6.5h7a4 4 0 0 1 0 8h-2"/></svg></button>
+ <button class="btn icon" id="redo" title="Redo (⇧⌘Z)" disabled><svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="m10.5 3.5 3 3-3 3"/><path d="M13.5 6.5h-7a4 4 0 0 0 0 8h2"/></svg></button>
+ <label class="toggle"><input type="checkbox" id="snap" checked> Snap to beat <span class="mono">S</span></label>
+ <button class="pill" id="health">…</button>
+ <span class="mono muted saved" id="saved"></span>
+ <button class="btn" id="gate">Run gate</button>
+ <button class="btn primary" id="build">Build mp4</button>
+ </header>
+
+ <section class="stage">
+ <div class="viewer">
+ <div class="screen"><div class="frame" id="frame"><video id="video" muted playsinline preload="auto"></video><div class="caption" id="caption"></div></div></div>
+ <div class="transport">
+ <button class="btn icon" id="back" title="Previous beat (←)"><svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="2" y="2.5" width="1.6" height="9" rx=".5"/><path d="M12 2.8v8.4a.5.5 0 0 1-.8.4L5 7.4a.5.5 0 0 1 0-.8l6.2-4.2a.5.5 0 0 1 .8.4z"/></svg></button>
+ <button class="btn icon primary" id="play" title="Play (Space)"><svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><path d="M3.5 2.2v9.6a.6.6 0 0 0 .9.5l7.6-4.8a.6.6 0 0 0 0-1L4.4 1.7a.6.6 0 0 0-.9.5z"/></svg></button>
+ <button class="btn icon" id="fwd" title="Next beat (→)"><svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="10.4" y="2.5" width="1.6" height="9" rx=".5"/><path d="M2 2.8v8.4a.5.5 0 0 0 .8.4L9 7.4a.5.5 0 0 0 0-.8L2.8 2.4a.5.5 0 0 0-.8.4z"/></svg></button>
+ <div class="clock"><span class="tc mono" id="tc">00:00.00 <small>/ 00:00.00</small></span><span class="mono muted beatpos" id="beatpos"></span></div>
+ </div>
+ </div>
+ <aside class="inspector" id="inspector"></aside>
+ </section>
+
+ <section class="timeline" id="timeline">
+ <div class="labels">
+ <div></div>
+ <div>Picture<small>cuts</small></div>
+ <div>Text<small>captions</small></div>
+ <div>Voice<small>lines</small></div>
+ <div>Music<small>score</small></div>
+ </div>
+ <div class="lane-wrap" id="lanes">
+ <div class="ruler" id="ruler"><canvas id="rulerc"></canvas></div>
+ <canvas class="grid" id="grid"></canvas>
+ <div class="lane" id="lane-cuts"></div>
+ <div class="lane" id="lane-text"></div>
+ <div class="lane" id="lane-voice"></div>
+ <div class="lane" id="lane-music"></div>
+ <div class="snapline" id="snapline"></div>
+ <div class="playhead" id="playhead"></div>
+ </div>
+ </section>
+
+ <footer class="status"><span id="hint">Drag to move · edges trim · double-click text to edit · T adds text at the playhead · ⌘/Ctrl + wheel zooms · Alt disables snapping</span><span class="spacer"></span><span id="rev"></span></footer>
+</div>
+<dialog id="dlg"><h3 id="dlgTitle"></h3><pre id="dlgBody"></pre><div class="actions"><button class="btn" onclick="dlg.close()">Close</button></div></dialog>
+<div class="toast" id="toast"></div>
+
+<script type="module">
+import { apply, beat, freshId, length, rollOps, rollRange, snap as snapTo } from '/core.mjs';
+
+const $ = (id) => document.getElementById(id);
+const ICON_PLAY = '<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><path d="M3.5 2.2v9.6a.6.6 0 0 0 .9.5l7.6-4.8a.6.6 0 0 0 0-1L4.4 1.7a.6.6 0 0 0-.9.5z"/></svg>', ICON_PAUSE = '<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="3" y="2" width="3" height="10" rx=".8"/><rect x="8" y="2" width="3" height="10" rx=".8"/></svg>';
+const S = { doc: null, rev: 0, media: {}, diags: [], sel: null, pxs: 80, t: 0, playing: false, undo: [], redo: [], peaks: {}, buffers: {}, busy: false };
+const fmt = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${(s % 60).toFixed(2).padStart(5, '0')}`;
+const toast = (msg) => { $('toast').textContent = msg; $('toast').classList.add('on'); clearTimeout(toast.h); toast.h = setTimeout(() => $('toast').classList.remove('on'), 1600); };
+const parseSrc = (src) => { const m = /^(clip|file):([^@]+)@([0-9.]+)$/.exec(src); return m && { path: m[1] === 'clip' ? `clip/${m[2]}.mp4` : m[2], at: Number(m[3]), name: m[2] }; };
+const total = () => Math.max(length(S.doc), ...S.doc.audio.map((a) => a.t + a.d), ...S.doc.text.map((x) => x.t + x.d), 1);
+const track = (kind) => (kind === 'cut' ? 'cuts' : kind === 'text' ? 'text' : 'audio');
+const find = (sel) => sel && S.doc[track(sel.kind)].find((x) => x.id === sel.id);
+
+// ---------- server ----------
+async function load(first) {
+ const r = await fetch(`/api/doc${first ? '' : `?since=${S.rev}`}`);
+ if (r.status === 204) return false;
+ take(await r.json());
+ if (!first) toast('edit.json changed outside the editor, reloaded');
+ return true;
+}
+function take(s) {
+ const firstTime = !S.doc;
+ Object.assign(S, { doc: s.doc, rev: s.revision, media: s.media, diags: s.diagnostics });
+ if (firstTime) { $('name').textContent = s.name; document.title = `${s.name} · timeline`; }
+ if (S.sel && !find(S.sel)) S.sel = null;
+ render();
+}
+let queue = Promise.resolve();
+function commit(ops, opts) { return (queue = queue.then(() => send(ops, opts)).catch(() => {})); }
+async function send(ops, { label, history = true } = {}) {
+ if (!ops.length) return;
+ const local = apply(S.doc, ops, S.media); // instant feedback and refusal before the round trip
+ if (!local.ok) { toast(local.diagnostics[0].message); return render(); }
+ S.doc = local.doc; S.diags = local.diagnostics; render();
+ const r = await fetch('/api/apply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ops, revision: S.rev }) });
+ const body = await r.json();
+ if (r.status === 409) { take(body); toast('Someone else changed the timeline. Reloaded; redo your last change.'); return; }
+ if (!r.ok) { toast(body.diagnostics?.[0]?.message || 'Not saved'); await load(true); return; }
+ take(body);
+ if (history) { S.undo.push({ ops, inverse: body.inverse, label }); S.redo = []; }
+ $('saved').textContent = 'saved';
+ setTimeout(() => ($('saved').textContent = ''), 1200);
+ updateHistory();
+}
+async function undo() {
+ const h = S.undo.pop(); if (!h) return;
+ await commit(h.inverse, { history: false, label: h.label }); S.redo.push(h); updateHistory(); toast(`Undid ${h.label || 'change'}`);
+}
+async function redo() {
+ const h = S.redo.pop(); if (!h) return;
+ await commit(h.ops, { history: false }); S.undo.push(h); updateHistory();
+}
+function updateHistory() { $('undo').disabled = !S.undo.length; $('redo').disabled = !S.redo.length; }
+setInterval(() => { if (!S.drag && !S.busy) load(false).catch(() => {}); }, 1500);
+
+// ---------- rendering ----------
+const X = (t) => t * S.pxs;
+function render() {
+ if (!S.doc) return;
+ const T = total(), W = Math.max(X(T) + 240, $('timeline').clientWidth - 112);
+ $('lanes').style.width = `${W}px`;
+ const d = S.doc;
+ $('meta').textContent = `${d.bpm} BPM · ${d.fps} fps · ${length(d).toFixed(2)} s`;
+ if (d.width && d.height) $('frame').style.setProperty('--ar', `${d.width} / ${d.height}`);
+ $('rev').textContent = `edit.json · revision ${S.rev}`;
+ drawGrid(W);
+ const bad = new Set(S.diags.filter((x) => x.severity === 'error').flatMap((x) => x.ids));
+ const isSel = (kind, id) => S.sel && S.sel.kind === kind && S.sel.id === id;
+
+ const cuts = [...d.cuts].sort((a, b) => a.t - b.t);
+ $('lane-cuts').innerHTML = cuts.map((c, i) => {
+ const s = parseSrc(c.src);
+ const thumbs = s ? `background-image:${thumbStrip(c, s)}` : '';
+ return `<div class="item cut ${isSel('cut', c.id) ? 'sel' : ''} ${bad.has(c.id) ? 'bad' : ''}" data-kind="cut" data-id="${c.id}" style="left:${X(c.t)}px;width:${X(c.d)}px;${thumbs}">
+ <span class="lab">${s ? esc(s.name) : esc(c.src)}</span><span class="sub">${c.d.toFixed(2)} s${c.line ? ` · ${esc(c.line)}` : ''}</span></div>`;
+ }).join('') + cuts.map((c) => `<div class="boundary" data-roll="${c.id}" style="left:${X(c.t + c.d)}px"></div>`).join('');
+
+ $('lane-text').innerHTML = d.text.map((x) => `<div class="item text-item ${isSel('text', x.id) ? 'sel' : ''} ${bad.has(x.id) ? 'bad' : ''}" data-kind="text" data-id="${x.id}" style="left:${X(x.t)}px;width:${X(x.d)}px">
+ <span class="h l"></span><span class="lab">${esc(x.text) || '<span class="muted">empty</span>'}</span><span class="h r"></span></div>`).join('');
+
+ for (const kind of ['voice', 'music']) {
+ $(`lane-${kind}`).innerHTML = d.audio.filter((a) => a.kind === kind).map((a) => `<div class="item audio-item ${isSel(kind, a.id) ? 'sel' : ''} ${bad.has(a.id) ? 'bad' : ''}" data-kind="${kind}" data-id="${a.id}" style="left:${X(a.t)}px;width:${X(a.d)}px">
+ <canvas></canvas><span class="h l"></span><span class="lab">${esc(a.id)} <span class="mono muted" style="font-weight:500">${a.gain > 0 ? '+' : ''}${a.gain} dB</span></span><span class="h r"></span></div>`).join('');
+ }
+ document.querySelectorAll('.audio-item').forEach(drawWave);
+ renderInspector();
+ renderHealth();
+ seek(S.t, { keepScroll: true });
+}
+const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
+
+function thumbStrip(c, s) {
+ const h = 50, w = Math.round(h * 16 / 9), n = Math.max(1, Math.ceil(X(c.d) / w));
+ const urls = [];
+ for (let i = 0; i < Math.min(n, 12); i++) urls.push(`url('/api/thumb?src=${encodeURIComponent(c.src).replace(/'/g, '%27')}&t=${(s.at + (c.d * (c.rate ?? 1) * i) / n).toFixed(2)}')`);
+ return urls.join(',') + `;background-size:${w}px 100%;background-position:${urls.map((_, i) => `${i * w}px 0`).join(',')}`;
+}
+
+function drawGrid(W) {
+ const H = $('lanes').clientHeight, dpr = devicePixelRatio || 1;
+ for (const [cv, h] of [[$('grid'), H], [$('rulerc'), 30]]) {
+ cv.width = W * dpr; cv.height = h * dpr; cv.style.width = `${W}px`; cv.style.height = `${h}px`;
+ }
+ const g = $('grid').getContext('2d'), r = $('rulerc').getContext('2d');
+ g.scale(dpr, dpr); r.scale(dpr, dpr);
+ const b = beat(S.doc), T = total() + 4;
+ r.font = `500 10px ${getComputedStyle(document.body).getPropertyValue('--mono')}`;
+ for (let i = 0, t = 0; t <= T; i++, t = i * b) {
+ const x = Math.round(X(t)) + 0.5, bar = i % 4 === 0;
+ g.fillStyle = bar ? 'rgba(250,250,247,.07)' : 'rgba(250,250,247,.03)';
+ g.fillRect(x, 30, 1, H);
+ r.fillStyle = bar ? '#5c5a52' : '#3a3934';
+ r.fillRect(x, bar ? 16 : 22, 1, bar ? 14 : 8);
+ }
+ const step = S.pxs > 120 ? 1 : S.pxs > 40 ? 2 : 5;
+ r.fillStyle = '#8e8b7e';
+ for (let t = 0; t <= T; t += step) r.fillText(fmt(t).replace(/\.00$/, ''), X(t) + 4, 12);
+}
+
+async function drawWave(el) {
+ const a = S.doc.audio.find((x) => x.id === el.dataset.id);
+ if (!a) return;
+ if (!S.peaks[a.file]) S.peaks[a.file] = fetch(`/api/peaks?file=${encodeURIComponent(a.file)}`).then((r) => (r.ok ? r.json() : []));
+ const peaks = await S.peaks[a.file];
+ const cv = el.querySelector('canvas'); if (!cv) return;
+ const w = el.clientWidth, h = el.clientHeight, dpr = devicePixelRatio || 1;
+ cv.width = w * dpr; cv.height = h * dpr;
+ const g = cv.getContext('2d'); g.scale(dpr, dpr);
+ // drawn relative to the loudest moment of the file, so quiet files stay readable and gain still shows
+ const gain = 10 ** (a.gain / 20), top = Math.max(0.05, ...peaks);
+ g.fillStyle = a.kind === 'voice' ? 'rgba(250,250,247,.62)' : 'rgba(142,139,126,.55)';
+ const mid = h / 2 + 7, amp = h / 2 - 12;
+ for (let x = 0; x < w; x += 2) {
+ const s = (x / w) * a.d, k = Math.floor((a.in + s) * 100);
+ let v = peaks[k] ?? 0;
+ const fade = Math.min(1, a.fadeIn ? s / a.fadeIn : 1, a.fadeOut ? (a.d - s) / a.fadeOut : 1);
+ v = Math.min(1, (v / top) * gain * Math.max(0, fade));
+ const y = Math.max(0.75, Math.sqrt(v) * amp);
+ g.fillRect(x, mid - y, 1.5, y * 2);
+ }
+ if (a.fadeIn || a.fadeOut) {
+ g.strokeStyle = 'rgba(250,250,247,.5)'; g.lineWidth = 1; g.beginPath();
+ g.moveTo(0, h - 4); g.lineTo(X(a.fadeIn), 4); g.lineTo(w - X(a.fadeOut), 4); g.lineTo(w, h - 4); g.stroke();
+ }
+}
+
+function renderHealth() {
+ const e = S.diags.filter((x) => x.severity === 'error').length, w = S.diags.length - e;
+ const h = $('health');
+ h.className = `pill ${e ? 'block' : w ? 'warn' : ''}`;
+ h.textContent = e ? `BLOCK · ${e}` : w ? `WARN · ${w}` : 'PASS';
+}
+
+// ---------- inspector ----------
+function renderInspector() {
+ const el = $('inspector'), x = find(S.sel);
+ const diag = S.diags.map((d) => `<div class="${d.severity}" data-ids="${d.ids.join(',')}"><b>${d.code}</b><span>${esc(d.message)}</span></div>`).join('');
+ const diagBlock = diag ? `<div class="diag">${diag}</div>` : '';
+ if (!x) {
+ el.innerHTML = `<div class="kind">PROJECT</div><h2>${esc($('name').textContent)}</h2>
+ <p class="empty" style="margin-top:12px">Select a cut, a line of text or a sound to edit it.<br><kbd>Space</kbd> play · <kbd>T</kbd> add text · <kbd>⌫</kbd> delete · <kbd>⌘Z</kbd> undo</p>
+ <div class="actions"><button class="btn" id="addText">Add text at playhead</button></div>${diagBlock}`;
+ $('addText').onclick = addText;
+ } else if (S.sel.kind === 'text') {
+ el.innerHTML = `<div class="kind">TEXT · ${x.id}</div><h2>Caption</h2>
+ <label class="field"><span>Text</span><textarea id="f-text">${esc(x.text)}</textarea></label>
+ <div class="pair"><label class="field"><span>Start (s)</span><input class="mono" id="f-t" type="number" step="0.01" value="${x.t}"></label>
+ <label class="field"><span>Length (s)</span><input class="mono" id="f-d" type="number" step="0.01" value="${x.d}"></label></div>
+ <div class="actions"><button class="btn" id="del">Delete</button></div>${diagBlock}`;
+ bind('f-text', (v) => ({ text: v }), 'change');
+ } else if (S.sel.kind === 'cut') {
+ const s = parseSrc(x.src);
+ el.innerHTML = `<div class="kind">CUT · ${x.id}</div><h2>${esc(s?.name || x.src)}</h2>
+ <label class="field"><span>Source</span><input class="mono" id="f-src" value="${esc(x.src)}"></label>
+ <div class="pair"><label class="field"><span>Start (s)</span><input class="mono" value="${x.t}" disabled></label>
+ <label class="field"><span>Length (s)</span><input class="mono" value="${x.d}" disabled></label></div>
+ <label class="field"><span>Voice line in this cut</span><input class="mono" id="f-line" value="${esc(x.line || '')}" placeholder="none"></label>
+ <p class="empty" style="margin-top:14px">Drag the line between two cuts to move the cut point. Cuts stay back to back, as the edit gate requires.</p>${diagBlock}`;
+ bind('f-src', (v) => ({ src: v }), 'change');
+ bind('f-line', (v) => ({ line: v || null }), 'change');
+ } else {
+ el.innerHTML = `<div class="kind">${S.sel.kind.toUpperCase()} · ${x.id}</div><h2>${esc(x.file.split('/').pop())}</h2>
+ <div class="pair"><label class="field"><span>Start (s)</span><input class="mono" id="f-t" type="number" step="0.01" value="${x.t}"></label>
+ <label class="field"><span>Length (s)</span><input class="mono" id="f-d" type="number" step="0.01" value="${x.d}"></label></div>
+ <label class="field"><span>From second of the file</span><input class="mono" id="f-in" type="number" step="0.01" min="0" value="${x.in}"></label>
+ <label class="field"><span>Gain</span><div class="range"><input type="range" id="f-gain" min="-30" max="12" step="0.5" value="${x.gain}"><output class="mono" id="o-gain">${x.gain} dB</output></div></label>
+ <div class="pair"><label class="field"><span>Fade in (s)</span><input class="mono" id="f-fi" type="number" step="0.05" min="0" value="${x.fadeIn}"></label>
+ <label class="field"><span>Fade out (s)</span><input class="mono" id="f-fo" type="number" step="0.05" min="0" value="${x.fadeOut}"></label></div>
+ ${x.kind === 'music' ? `<label class="toggle" style="margin-top:16px"><input type="checkbox" id="f-duck" ${x.duck !== false ? 'checked' : ''}> Duck under voice</label>` : ''}
+ <div class="actions"><button class="btn" id="del">Delete</button></div>${diagBlock}`;
+ bind('f-in', (v) => ({ in: Number(v) }));
+ bind('f-fi', (v) => ({ fadeIn: Number(v) }));
+ bind('f-fo', (v) => ({ fadeOut: Number(v) }));
+ $('f-gain').oninput = (e) => { $('o-gain').textContent = `${e.target.value} dB`; };
+ bind('f-gain', (v) => ({ gain: Number(v) }), 'change');
+ if ($('f-duck')) $('f-duck').onchange = (e) => commit([{ op: 'update', track: 'audio', id: x.id, patch: { duck: e.target.checked ? null : false } }], { label: 'ducking' });
+ }
+ if ($('f-t')) { bind('f-t', (v) => ({ t: Number(v) })); bind('f-d', (v) => ({ d: Number(v) })); }
+ if ($('del')) $('del').onclick = remove;
+ el.querySelectorAll('.diag div').forEach((row) => (row.onclick = () => {
+ const id = row.dataset.ids.split(',')[0]; if (!id) return;
+ const kind = S.doc.cuts.some((c) => c.id === id) ? 'cut' : S.doc.text.some((c) => c.id === id) ? 'text' : S.doc.audio.find((a) => a.id === id)?.kind;
+ if (kind) { S.sel = { kind, id }; const it = find(S.sel); seek(it.t); render(); }
+ }));
+}
+function bind(id, patch, ev = 'change') {
+ $(id)[`on${ev}`] = (e) => commit([{ op: 'update', track: track(S.sel.kind), id: S.sel.id, patch: patch(e.target.value) }], { label: id.slice(2) });
+}
+function addText() {
+ const t = S.snapOn !== false ? snapTo(S.doc, S.t) : S.t;
+ const id = freshId(S.doc, 'text');
+ commit([{ op: 'create', track: 'text', item: { id, t, d: beat(S.doc) * 4, text: '' } }], { label: 'new text' }).then(() => {
+ S.sel = { kind: 'text', id }; render(); $('f-text')?.focus();
+ });
+}
+function remove() {
+ if (!S.sel || S.sel.kind === 'cut') return;
+ const sel = S.sel; S.sel = null;
+ commit([{ op: 'delete', track: track(sel.kind), id: sel.id }], { label: 'delete' });
+}
+
+// ---------- dragging ----------
+const lanes = $('lanes');
+const snapOn = (e) => $('snap').checked && !e.altKey;
+function snapT(t, e, self) {
+ if (!snapOn(e)) return { t: Math.round(t * S.doc.fps) / S.doc.fps };
+ // beats, plus the edges of other items, within 8 px
+ const cands = [S.t];
+ for (const tr of ['cuts', 'text', 'audio']) for (const x of S.doc[tr]) if (x.id !== self) cands.push(x.t, x.t + x.d);
+ let best = null;
+ for (const c of cands) if (Math.abs(X(c - t)) <= 8 && (best === null || Math.abs(c - t) < Math.abs(best - t))) best = c;
+ return best === null ? { t: snapTo(S.doc, t) } : { t: best, line: true };
+}
+function showSnap(t, on) { const s = $('snapline'); s.style.display = on ? 'block' : 'none'; if (on) s.style.left = `${X(t)}px`; }
+
+lanes.addEventListener('pointerdown', (e) => {
+ const at = (e.clientX - lanes.getBoundingClientRect().left) / S.pxs;
+ if (e.target.closest('.ruler')) { scrub(e); return; }
+ const roll = e.target.closest('[data-roll]');
+ const item = e.target.closest('.item');
+ if (!roll && !item) { S.sel = null; seek(at); render(); return; }
+ e.preventDefault();
+ lanes.setPointerCapture(e.pointerId);
+ if (roll) { S.drag = { mode: 'roll', id: roll.dataset.roll, el: roll }; return; }
+ const kind = item.dataset.kind, id = item.dataset.id;
+ S.sel = { kind, id };
+ const x = find(S.sel);
+ const mode = e.target.classList.contains('l') ? 'trimL' : e.target.classList.contains('r') ? 'trimR' : kind === 'cut' ? 'select' : 'move';
+ S.drag = { mode, kind, id, x0: e.clientX, orig: { ...x }, el: item, moved: false };
+ render(); S.drag.el = lanes.querySelector(`.item[data-id="${CSS.escape(id)}"][data-kind="${kind}"]`);
+});
+lanes.addEventListener('pointermove', (e) => {
+ const D = S.drag; if (!D) return;
+ const at = (e.clientX - lanes.getBoundingClientRect().left) / S.pxs;
+ if (D.mode === 'roll') {
+ const s = snapT(at, e, D.id), [lo, hi] = rollRange(S.doc, D.id), b = beat(S.doc);
+ // when snapping, the clamp lands on a beat inside the range too
+ const [l, h] = snapOn(e) ? [Math.ceil(lo / b - 1e-6) * b, Math.floor(hi / b + 1e-6) * b] : [lo, hi];
+ D.t = l <= h ? Math.min(h, Math.max(l, s.t)) : Math.min(hi, Math.max(lo, s.t));
+ D.el.style.left = `${X(D.t)}px`; showSnap(D.t, s.line || D.t !== s.t); return;
+ }
+ if (D.mode === 'select') return;
+ const dt = (e.clientX - D.x0) / S.pxs, o = D.orig, min = 1 / S.doc.fps;
+ if (Math.abs(e.clientX - D.x0) > 2) D.moved = true;
+ let t = o.t, d = o.d, inp = o.in, s;
+ if (D.mode === 'move') { s = snapT(o.t + dt, e, D.id); const s2 = snapT(o.t + o.d + dt, e, D.id); if (!s.line && s2.line) s = { t: s2.t - o.d, line: true, at: s2.t }; t = Math.max(0, s.t); }
+ if (D.mode === 'trimL') { s = snapT(o.t + dt, e, D.id); t = Math.min(o.t + o.d - min, Math.max(0, s.t, D.kind === 'text' ? 0 : o.t - o.in)); d = o.t + o.d - t; if (D.kind !== 'text') inp = o.in + (t - o.t); }
+ if (D.mode === 'trimR') { s = snapT(o.t + o.d + dt, e, D.id); d = Math.max(min, s.t - o.t); const len = S.media[o.file]; if (D.kind !== 'text' && len) d = Math.min(d, len - o.in); }
+ D.patch = { t, d, ...(D.kind === 'text' ? {} : { in: inp }) };
+ D.el.style.left = `${X(t)}px`; D.el.style.width = `${X(d)}px`;
+ showSnap(s.at ?? (D.mode === 'trimR' ? t + d : t), s.line);
+});
+lanes.addEventListener('pointerup', () => {
+ const D = S.drag; S.drag = null; showSnap(0, false);
+ if (!D) return;
+ if (D.mode === 'roll' && D.t != null) return commit(rollOps(S.doc, D.id, D.t), { label: 'cut point' });
+ if (D.mode === 'select' || !D.moved || !D.patch) { const x = find({ kind: D.kind, id: D.id }); if (x && !D.moved) seek(Math.max(S.t, 0)); return; }
+ const changed = Object.fromEntries(Object.entries(D.patch).filter(([k, v]) => Math.abs(v - D.orig[k]) > 1e-4));
+ if (Object.keys(changed).length) commit([{ op: 'update', track: track(D.kind), id: D.id, patch: changed }], { label: D.mode === 'move' ? 'move' : 'trim' });
+});
+lanes.addEventListener('dblclick', (e) => {
+ const item = e.target.closest('.text-item');
+ if (item) { S.sel = { kind: 'text', id: item.dataset.id }; render(); $('f-text')?.focus(); $('f-text')?.select(); }
+});
+function scrub(e) {
+ const move = (ev) => { if (S.playing) stop(); seek((ev.clientX - lanes.getBoundingClientRect().left) / S.pxs); };
+ move(e);
+ const up = () => { removeEventListener('pointermove', move); removeEventListener('pointerup', up); };
+ addEventListener('pointermove', move); addEventListener('pointerup', up);
+}
+$('timeline').addEventListener('wheel', (e) => {
+ if (!(e.metaKey || e.ctrlKey)) return;
+ e.preventDefault();
+ const tl = $('timeline'), at = (e.clientX - lanes.getBoundingClientRect().left) / S.pxs;
+ S.pxs = Math.min(600, Math.max(12, S.pxs * Math.exp(-e.deltaY * 0.002)));
+ render(); tl.scrollLeft = X(at) - (e.clientX - tl.getBoundingClientRect().left - 112);
+}, { passive: false });
+
+// ---------- playback: picture from <video>, sound from Web Audio with the same gain and fades the build uses ----------
+let ctx, nodes = [], t0 = 0, start = 0, raf;
+const video = $('video');
+function cutAt(t) { return [...S.doc.cuts].sort((a, b) => a.t - b.t).find((c) => t >= c.t - 1e-6 && t < c.t + c.d) || null; }
+function showFrame(t, playing) {
+ const c = cutAt(t);
+ if (!c) { video.removeAttribute('src'); video.load(); return; }
+ const s = parseSrc(c.src); if (!s) return;
+ const url = `/media/${s.path.split('/').map(encodeURIComponent).join('/')}`;
+ const want = s.at + (t - c.t) * (c.rate ?? 1);
+ if (video.dataset.src !== url) { video.dataset.src = url; video.src = url; video.currentTime = want; video.playbackRate = c.rate ?? 1; if (playing) video.play().catch(() => {}); return; }
+ if (!playing || Math.abs(video.currentTime - want) > 0.12) video.currentTime = want;
+ if (playing && video.paused) video.play().catch(() => {});
+}
+function showCaption(t) { const x = S.doc.text.find((x) => t >= x.t && t < x.t + x.d); $('caption').textContent = x ? x.text : ''; }
+function seek(t, { keepScroll } = {}) {
+ S.t = Math.max(0, Math.min(t, total()));
+ $('playhead').style.left = `${X(S.t)}px`;
+ $('tc').innerHTML = `${fmt(S.t)} <small>/ ${fmt(length(S.doc))}</small>`;
+ const b = beat(S.doc), n = Math.floor(S.t / b + 1e-6);
+ $('beatpos').textContent = `bar ${Math.floor(n / 4) + 1} · beat ${(n % 4) + 1}`;
+ if (!S.playing) { showFrame(S.t, false); showCaption(S.t); }
+ if (!keepScroll) follow();
+}
+function follow() {
+ const tl = $('timeline'), x = X(S.t), view = tl.clientWidth - 112;
+ if (x < tl.scrollLeft || x > tl.scrollLeft + view - 40) tl.scrollLeft = Math.max(0, x - 80);
+}
+async function buffer(file) {
+ if (!S.buffers[file]) S.buffers[file] = fetch(`/media/${file.split('/').map(encodeURIComponent).join('/')}`).then((r) => r.arrayBuffer()).then((b) => ctx.decodeAudioData(b));
+ return S.buffers[file];
+}
+async function play() {
+ ctx ??= new AudioContext();
+ await ctx.resume();
+ if (S.t >= length(S.doc) - 0.01) S.t = 0;
+ const from = S.t;
+ const bufs = await Promise.all(S.doc.audio.map((a) => buffer(a.file).catch(() => null)));
+ S.playing = true; $('play').innerHTML = ICON_PAUSE;
+ t0 = ctx.currentTime + 0.05; start = from;
+ const voiceOn = (t) => S.doc.audio.some((a) => a.kind === 'voice' && t >= a.t && t < a.t + a.d);
+ S.doc.audio.forEach((a, i) => {
+ const buf = bufs[i]; if (!buf || a.t + a.d <= from) return;
+ const src = ctx.createBufferSource(), g = ctx.createGain();
+ src.buffer = buf; src.connect(g).connect(ctx.destination);
+ const lin = 10 ** (a.gain / 20), skip = Math.max(0, from - a.t), when = t0 + Math.max(0, a.t - from);
+ // fades and a simple duck preview, as automation on the gain
+ const g0 = (s) => lin * Math.max(0, Math.min(1, a.fadeIn ? s / a.fadeIn : 1, a.fadeOut ? (a.d - s) / a.fadeOut : 1)) * (a.kind === 'music' && a.duck !== false && voiceOn(a.t + s) ? 0.45 : 1);
+ for (let s = skip; s <= a.d; s += 0.05) g.gain.setValueAtTime(g0(s), when + (s - skip));
+ src.start(when, a.in + skip, a.d - skip);
+ nodes.push(src);
+ });
+ showFrame(from, true);
+ tick();
+}
+function tick() {
+ if (!S.playing) return;
+ const t = start + (ctx.currentTime - t0);
+ if (t >= length(S.doc)) { stop(); seek(length(S.doc)); return; }
+ S.t = Math.max(start, t);
+ $('playhead').style.left = `${X(S.t)}px`;
+ $('tc').innerHTML = `${fmt(S.t)} <small>/ ${fmt(length(S.doc))}</small>`;
+ showFrame(S.t, true); showCaption(S.t); follow();
+ raf = requestAnimationFrame(tick);
+}
+function stop() {
+ S.playing = false; $('play').innerHTML = ICON_PLAY;
+ cancelAnimationFrame(raf); nodes.forEach((n) => { try { n.stop(); } catch {} }); nodes = []; video.pause();
+}
+$('play').onclick = () => (S.playing ? stop() : play());
+$('back').onclick = () => { stop(); seek(Math.ceil(S.t / beat(S.doc) - 1.001) * beat(S.doc)); };
+$('fwd').onclick = () => { stop(); seek(Math.floor(S.t / beat(S.doc) + 1.001) * beat(S.doc)); };
+$('undo').onclick = undo; $('redo').onclick = redo;
+
+addEventListener('keydown', (e) => {
+ if (e.target.matches('input, textarea')) { if (e.key === 'Escape') e.target.blur(); return; }
+ const mod = e.metaKey || e.ctrlKey;
+ if (e.code === 'Space') { e.preventDefault(); S.playing ? stop() : play(); }
+ else if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
+ else if (e.key === 'Backspace' || e.key === 'Delete') remove();
+ else if (e.key.toLowerCase() === 't' && !mod) { e.preventDefault(); addText(); }
+ else if (e.key.toLowerCase() === 's' && !mod) $('snap').checked = !$('snap').checked;
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
+ e.preventDefault();
+ const x = find(S.sel), step = e.shiftKey ? beat(S.doc) : 1 / S.doc.fps, dir = e.key === 'ArrowLeft' ? -1 : 1;
+ if (x && S.sel.kind !== 'cut') commit([{ op: 'update', track: track(S.sel.kind), id: x.id, patch: { t: Math.max(0, x.t + dir * step) } }], { label: 'nudge' });
+ else { stop(); seek(S.t + dir * step); }
+ } else if (e.key === 'Escape') { S.sel = null; render(); }
+});
+
+// ---------- gate and build ----------
+async function run(path, title) {
+ S.busy = true; $('gate').disabled = $('build').disabled = true;
+ $('dlgTitle').textContent = `${title} …`; $('dlgBody').textContent = ''; $('dlg').showModal();
+ try {
+ const r = await (await fetch(path, { method: 'POST' })).json();
+ $('dlgTitle').textContent = `${title} · ${r.code === 0 ? 'exit 0' : `exit ${r.code}`}`;
+ $('dlgBody').textContent = r.text || '(no output)';
+ } finally { S.busy = false; $('gate').disabled = $('build').disabled = false; }
+}
+$('gate').onclick = () => run('/api/gate', 'gate.py edit');
+$('build').onclick = () => run('/api/build', 'Build out/final.mp4');
+$('health').onclick = () => { S.sel = null; render(); };
+addEventListener('resize', render);
+
+load(true).then(() => { $('timeline').scrollLeft = 0; seek(0); });
+</script>
+</body>
+</html>
diff --git a/skills/motion-video-production/timeline/project.mjs b/skills/motion-video-production/timeline/project.mjs
new file mode 100644
index 0000000..ad3a72a
--- /dev/null
+++ b/skills/motion-video-production/timeline/project.mjs
@@ -0,0 +1,61 @@
+// Project I/O shared by the server and the CLI: read and write edit.json, measure media with ffprobe.
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
+import { join, resolve, sep } from 'node:path';
+import { normalize, serialize } from './core.mjs';
+
+export function open(root) {
+ root = resolve(root);
+ const file = join(root, 'edit.json');
+ if (!existsSync(file)) throw new Error(`no edit.json in ${root}. Write one first (see timeline/README.md).`);
+ return { root, file };
+}
+
+export function read(p) {
+ return normalize(JSON.parse(readFileSync(p.file, 'utf8')));
+}
+
+/** Atomic write. The first write of a session keeps a copy of the original under qa/timeline/. */
+export function write(p, doc) {
+ if (!p.backedUp) {
+ const dir = join(p.root, 'qa', 'timeline');
+ mkdirSync(dir, { recursive: true });
+ copyFileSync(p.file, join(dir, `edit-${new Date().toISOString().replace(/[:.]/g, '-')}.json`));
+ p.backedUp = true;
+ }
+ const tmp = `${p.file}.tmp-${process.pid}`;
+ writeFileSync(tmp, serialize(doc));
+ renameSync(tmp, p.file);
+ return statSync(p.file).mtimeMs;
+}
+
+/** Absolute path for a project-relative path, or null when it escapes the project. */
+export function inside(p, rel) {
+ const abs = resolve(p.root, rel);
+ return abs === p.root || abs.startsWith(p.root + sep) ? abs : null;
+}
+
+export function srcPath(src) {
+ const m = /^(clip|file):([^@]+)@([0-9.]+)$/.exec(src || '');
+ return m ? { path: m[1] === 'clip' ? `clip/${m[2]}.mp4` : m[2], at: Number(m[3]) } : null;
+}
+
+const lengths = new Map();
+/** { path: seconds } for every file the doc points at (cached by mtime). Missing files are left out. */
+export function media(p, doc) {
+ const out = {};
+ const paths = new Set([...doc.audio.map((a) => a.file), ...doc.cuts.map((c) => srcPath(c.src)?.path).filter(Boolean)]);
+ for (const rel of paths) {
+ const abs = inside(p, rel);
+ if (!abs || !existsSync(abs)) continue;
+ const key = `${abs}:${statSync(abs).mtimeMs}`;
+ if (!lengths.has(key)) {
+ try {
+ lengths.set(key, Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', abs], { encoding: 'utf8' }).trim()));
+ } catch { lengths.set(key, NaN); }
+ }
+ const len = lengths.get(key);
+ if (Number.isFinite(len)) out[rel] = len;
+ }
+ return out;
+}
diff --git a/skills/motion-video-production/timeline/serve.mjs b/skills/motion-video-production/timeline/serve.mjs
new file mode 100644
index 0000000..6811fa1
--- /dev/null
+++ b/skills/motion-video-production/timeline/serve.mjs
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+// Local timeline editor for a project folder. Node standard library and ffmpeg only.
+// node serve.mjs <project> [--port 4321] [--no-open]
+// The browser and the agent edit the same edit.json: the editor writes through /api/apply,
+// the agent through apply.mjs, and each side sees the other's change (revision + file mtime).
+import { execFile, execFileSync, spawn } from 'node:child_process';
+import { createReadStream, existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs';
+import { createServer } from 'node:http';
+import { createHash } from 'node:crypto';
+import { basename, dirname, extname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { apply, validate } from './core.mjs';
+import { inside, media, open, read, srcPath, write } from './project.mjs';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SKILL = dirname(HERE);
+const args = process.argv.slice(2);
+const root = args.find((a) => !a.startsWith('--') && args[args.indexOf(a) - 1] !== '--port');
+if (!root) { console.error('usage: node serve.mjs <project> [--port 4321] [--no-open]'); process.exit(2); }
+const port = Number(args[args.indexOf('--port') + 1]) || 4321;
+const p = open(root);
+const cache = join(p.root, 'qa', 'timeline', 'cache');
+mkdirSync(cache, { recursive: true });
+
+let doc = read(p);
+let revision = 1;
+let mtime = statSync(p.file).mtimeMs;
+
+/** Pick up edits made outside the editor (the agent, a text editor). */
+function sync() {
+ const now = statSync(p.file).mtimeMs;
+ if (now === mtime) return;
+ try { doc = read(p); revision++; } catch { /* half-written file: try again on the next poll */ return; }
+ mtime = now;
+}
+
+const state = () => {
+ const m = media(p, doc);
+ return { name: basename(p.root), revision, doc, media: m, diagnostics: validate(doc, m), hasSkillGate: existsSync(join(SKILL, 'harness', 'gate.py')) };
+};
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.mjs': 'text/javascript', '.js': 'text/javascript', '.json': 'application/json', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.png': 'image/png', '.jpg': 'image/jpeg' };
+
+const server = createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://x');
+ try {
+ if (req.method === 'GET' && url.pathname === '/') return file(res, join(HERE, 'editor.html'));
+ if (url.pathname === '/favicon.ico') return send(res, 204);
+ if (req.method === 'GET' && url.pathname === '/core.mjs') return file(res, join(HERE, 'core.mjs'));
+ if (req.method === 'GET' && url.pathname === '/api/doc') {
+ sync();
+ if (Number(url.searchParams.get('since')) === revision) return send(res, 204);
+ return json(res, 200, state());
+ }
+ if (req.method === 'POST' && url.pathname === '/api/apply') {
+ sync();
+ const body = JSON.parse(await text(req));
+ if (body.revision !== revision) return json(res, 409, state());
+ const r = apply(doc, body.ops, media(p, doc));
+ if (!r.ok) return json(res, 422, { diagnostics: r.diagnostics });
+ doc = r.doc;
+ mtime = write(p, doc);
+ revision++;
+ return json(res, 200, { ...state(), inverse: r.inverse });
+ }
+ if (req.method === 'POST' && (url.pathname === '/api/gate' || url.pathname === '/api/build')) {
+ const cmd = url.pathname === '/api/gate'
+ ? ['python3', [join(SKILL, 'harness', 'gate.py'), 'edit', p.root]]
+ : [process.execPath, [join(HERE, 'build.mjs'), p.root]];
+ execFile(cmd[0], cmd[1], { maxBuffer: 1 << 24 }, (err, stdout, stderr) =>
+ json(res, 200, { code: err ? (err.code ?? 1) : 0, text: `${stdout}${stderr}`.trim() }));
+ return;
+ }
+ if (req.method === 'GET' && url.pathname === '/api/peaks') return peaks(res, url.searchParams.get('file'));
+ if (req.method === 'GET' && url.pathname === '/api/thumb') return thumb(res, url.searchParams.get('src'), Number(url.searchParams.get('t')) || 0);
+ if (req.method === 'GET' && url.pathname.startsWith('/media/')) {
+ const abs = inside(p, decodeURIComponent(url.pathname.slice(7)));
+ if (!abs || !existsSync(abs)) return send(res, 404);
+ return file(res, abs, req.headers.range);
+ }
+ send(res, 404);
+ } catch (e) {
+ json(res, 500, { diagnostics: [{ code: 'S00', severity: 'error', ids: [], message: String(e.message || e) }] });
+ }
+});
+
+/** Waveform peaks, 100 per second, from mono 4 kHz PCM. Cached by path and mtime. */
+function peaks(res, rel) {
+ const abs = rel && inside(p, rel);
+ if (!abs || !existsSync(abs)) return send(res, 404);
+ const out = join(cache, `${hash(abs)}.peaks.json`);
+ if (!existsSync(out)) {
+ const pcm = execFileSync('ffmpeg', ['-v', 'error', '-i', abs, '-ac', '1', '-ar', '4000', '-f', 's16le', '-'], { maxBuffer: 1 << 28 });
+ const n = Math.floor(pcm.length / 2), step = 40, list = [];
+ for (let i = 0; i < n; i += step) {
+ let m = 0;
+ for (let j = i; j < Math.min(n, i + step); j++) m = Math.max(m, Math.abs(pcm.readInt16LE(j * 2)));
+ list.push(Math.round((m / 32768) * 1000) / 1000);
+ }
+ writeFileSync(out, JSON.stringify(list));
+ }
+ file(res, out);
+}
+
+/** One JPEG frame of a cut's source at t seconds into the source. */
+function thumb(res, src, t) {
+ const s = srcPath(src);
+ const abs = s && inside(p, s.path);
+ if (!abs || !existsSync(abs)) return send(res, 404);
+ const out = join(cache, `${hash(abs, t.toFixed(2))}.jpg`);
+ if (!existsSync(out)) execFileSync('ffmpeg', ['-v', 'error', '-y', '-ss', String(t), '-i', abs, '-frames:v', '1', '-vf', 'scale=-2:144', '-q:v', '4', out]);
+ file(res, out);
+}
+
+/** Cache key: the file, its mtime (so a regenerated clip gets new thumbnails) and an optional extra. */
+function hash(abs, extra = '') {
+ return createHash('sha1').update(`${abs}:${statSync(abs).mtimeMs}:${extra}`).digest('hex').slice(0, 16);
+}
+
+function file(res, abs, range) {
+ const size = statSync(abs).size;
+ const type = TYPES[extname(abs).toLowerCase()] || 'application/octet-stream';
+ const m = range && /bytes=(\d*)-(\d*)/.exec(range);
+ if (m) {
+ const start = m[1] ? Number(m[1]) : size - Number(m[2]);
+ const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
+ res.writeHead(206, { 'Content-Type': type, 'Content-Range': `bytes ${start}-${end}/${size}`, 'Accept-Ranges': 'bytes', 'Content-Length': end - start + 1, 'Cache-Control': 'no-cache' });
+ return createReadStream(abs, { start, end }).pipe(res);
+ }
+ res.writeHead(200, { 'Content-Type': type, 'Content-Length': size, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache' });
+ createReadStream(abs).pipe(res);
+}
+const send = (res, code) => { res.writeHead(code); res.end(); };
+const json = (res, code, body) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); };
+const text = (req) => new Promise((ok, no) => { let s = ''; req.on('data', (c) => (s += c)); req.on('end', () => ok(s)); req.on('error', no); });
+
+server.listen(port, '127.0.0.1', () => {
+ const at = `http://127.0.0.1:${port}/`;
+ console.log(`timeline editor for ${p.root}\n${at}`);
+ if (!args.includes('--no-open') && process.platform === 'darwin') spawn('open', [at], { stdio: 'ignore', detached: true }).unref();
+});