@lalalic/markcut 3.2.34 → 3.2.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -1,311 +1,26 @@
1
- # markcut — AGENT.md
1
+ # Markcut — repository agent rules
2
2
 
3
- > Markdown-to-video engine. Describe scenes in markdown, get a rendered video with TTS narration.
3
+ Markcut parses a Markdown video document into a validated stream tree and renders videos with Remotion. For **video authoring and viewing**, load [skills/markcut/SKILL.md](skills/markcut/SKILL.md); load its DSL, map, component, review and troubleshooting references only when the task needs them. For **implementation internals**, consult [docs/developer-reference.md](docs/developer-reference.md), not the video Skill startup prompt.
4
4
 
5
- ## Quick Start
5
+ ## Work on the requested layer
6
6
 
7
- ```bash
8
- npm run render storyboard.md # render markdown → MP4 (9x16 default)
9
- npm run preview storyboard.md --edit # live preview with auto-reload
10
- npm run preview storyboard.md --storyboard # fast structure preview (skips TTI/TTV, shows prompts as placeholders)
11
- npm test # unit + integration tests
12
- npm run typecheck # TypeScript type check
13
- ```
14
-
15
- ## Input formats
16
-
17
- | Format | CLI | Description |
18
- |---|---|---|
19
- | Markdown | `markcut render storyboard.md` | `## Scene` headings, `- image src:...` bullets, `script:"narration"` |
20
- | Descriptive JSON | `markcut render video.json` | Same schema as markdown, JSON syntax |
21
- | Compiled JSON | `markcut render tree.json` | Pre-compiled stream tree (no pipeline needed) |
22
-
23
- See [docs/markdown-strict-descriptive.md](docs/markdown-strict-descriptive.md) for the complete markdown syntax reference.
24
-
25
- ## Key concepts
26
-
27
- - **Scene** — narrative unit with `name`, `script` (TTS), `instruction` (visual intent), `children`
28
- - **Layout** — `parallel` (simultaneous), `series` (sequential), `transitionSeries` (sequential with transitions)
29
- - **Script → TTS → STT** — `script` field generates edge-tts audio, whisper transcribes to VTT subtitles
30
- - **Theme** — preset colors/fonts/effects: `cinematic`, `neon`, `minimal`, `corporate`
31
- - **TTL config** — root-level `tts.cli`, `tts.voice`, `tts.rate` with per-scene `tts` overrides
32
- - **Subtitle** — root-level VTT overlay from merged per-clip STT. Not a tree node. Supports animated caption types (`typewriter`, `fade`, `bounce`, `glowing`, etc.) via `remotion-subtitle`, HTML in cue text, and per-cue `<Sequence>` rendering for zero CPU when inactive.
33
-
34
- ## Stream types
35
-
36
- | Type | Purpose |
37
- |---|---|
38
- | `root` | Canvas config: width, height, fps, theme, subtitle, stylesheet |
39
- | `scene` | Storyboard container: name, layout, script, children |
40
- | `folder` | Internal container (series/parallel) |
41
- | `image` | Still photo with fit mode |
42
- | `video` | Video clip with startFrom/endAt trimming, playbackRate |
43
- | `audio` | Soundtrack/SFX with foreground ducking |
44
- | `component` | External React component by componentName + props |
45
- | `effect` | CSS keyframe animation wrapper (fadeIn, zoomIn, bounceIn, etc.) |
46
- | `include` | Embed external video JSON (file, URL, or data URI) |
47
-
48
- ## CLI
49
-
50
- ```bash
51
- markcut render <file.json|.md> [--output path]
52
- markcut preview <file.json|.md> [--edit] [--label] [--port 3001]
53
- ```
54
-
55
- ## Project structure
56
-
57
- ```
58
- src/
59
- ├── entry.tsx → MarkCut + DescriptiveComposition
60
- ├── descriptive/ → Compiler, markdown parser, resolve pipeline
61
- ├── types/ → React renderers (one per stream type)
62
- ├── schema/ → Zod stream tree schemas
63
- ├── themes/ → Theme presets + ThemeProvider
64
- ├── render/cli.mjs → CLI entry
65
- ├── render/tts.ts → TTS via CLI template + variable substitution
66
- ├── player/pipeline.mjs → Bundled pipeline (server imports this)
67
- ├── player/server.mjs → Unified server (--edit, --label, preview)
68
- ├── player/components/ → React control components (edit, label, variant bar)
69
- │ ├── index.ts
70
- │ ├── EditControls.tsx
71
- │ ├── LabelControls.tsx
72
- │ └── VariantBar.tsx
73
- └── tests/ → Vitest integration tests
74
- ```
75
-
76
- ## External component contract
77
-
78
- Register components at render time:
79
-
80
- ```tsx
81
- <MarkCut
82
- root={descriptiveJson}
83
- compose={{ components: { AnimatedHeadline, StatCounter } }}
84
- />
85
- ```
86
-
87
- In descriptive markdown:
88
-
89
- ```md
90
- - component componentName:StatCounter duration:3 props:{value:42}
91
- ```
92
-
93
- Components receive props as defined in the descriptive JSON. No eval, no JSX parsing — just `React.createElement(registry[name], props)`.
94
- ```
95
-
96
- ## Stream Tree Architecture
97
-
98
- ### Core Concept
99
-
100
- Everything is a **stream tree** — nested JSON nodes keyed by `type`.
101
- The tree is validated by Zod and rendered by Remotion via recursive React components.
102
-
103
- ```json
104
- { "id":"root", "type":"root", "width":1080, "height":1920, "fps":30,
105
- "isSeries":true, "transition":"fade", "children":[...] }
106
- ```
107
-
108
- ### Composition Rules
109
-
110
- | Concept | Rule |
111
- |---------|------|
112
- | **Series** (`isSeries:true`) | Children play sequentially. Optional `transition` (fade/slide/wipe/flip/clockWipe) + `transitionTime` (default 0.5s). |
113
- | **Parallel** (`isSeries:false`) | Children play simultaneously. Duration = max child duration. |
114
- | **Background** (`isBackground:true`) | Loops for parent duration. Excluded from duration calculation. |
115
- | **Timing** | Every leaf carries base fields `start`/`end` (seconds, relative to parent) + optional `startFrom`/`endAt` (source trim) + `duration` (convenience). `end` is the source of truth; `duration` normalizes to `end = start + duration` when `end` is absent. Inside series parents `start` is 0 (positioning is implicit). |
116
- | **Scene** (`type:"scene"`) | UI storyboard card; engine treats as folder. Has `name` + `description` + `script`. |
117
-
118
- ### Duration Calculation
119
-
120
- Computed by `getDurationInSeconds()` in `src/utils/index.ts`:
121
- - **Leaf nodes**: duration = `leafEnd(stream)` = `end ?? (start + duration)` (single deterministic read; `start`/`end`/`duration` live on the base node)
122
- - **Series**: sum of children durations minus transition overlaps
123
- - **Parallel**: max of children durations
124
- - **Background children**: excluded from calculation
125
- - **Include with `src`**: treated as leaf (duration from base `end`)
126
- - Sets `durationInSeconds` on every node as a side effect
127
-
128
- ### 12 Stream Types
129
-
130
- All types share base fields from `BaseShape`: `id`, `name`, `title`, `description`, `script`, `src`, `style`, `visible`, `isBackground`, `start`, `end`, `duration`, `startFrom`, `endAt`, `durationInSeconds`.
131
-
132
- | Type | Purpose | Key Fields |
133
- |------|---------|------------|
134
- | `root` | Canvas container | `width`, `height`, `fps`, `isSeries`, `transition`, `stylesheet` |
135
- | `folder` | Group children | `isSeries`, `transition`, `children[]` |
136
- | `scene` | Storyboard node (alias for folder) | `name`, `description`, `script`, `children[]` |
137
- | `image` | Still photo | `src`, `fit` (contain/cover/fill) |
138
- | `video` | Video clip | `src`, `volume`, `playbackRate` |
139
- | `audio` | Soundtrack/SFX | `src`, `volume`, `foreground` (ducks parent) |
140
- | `subtitle` | Text overlay | `src` (text/VTT) or `cues[]`, `fontSize`, `style` |
141
- | `component` | Built-in `<Markdown>` | Renders markdown with GFM. Props: `source`/`children`, `plugins`, `components` |
142
- | `component` | Built-in `<Mermaid>` | Renders Mermaid diagrams as inline SVG. Props: `source`/`children`, `theme` |
143
- | `component` | React component | `componentName`, `props`, `src` (remote ESM) |
144
- | `effect` | CSS animation wrapper | `animation`, `customKeyframes`, `children[]` |
145
- | `rhythm` | Beat-synced loop | `src`, `spots[]`, `children[]` |
146
- | `map` | Route visualization | `waypoints[{lat,lng,label}]`, `routeColor` |
147
- | `include` | Embed sub-tree | `src` (path/URL/data URI), `children[]` |
148
-
149
- ## Key Implementation Details
150
-
151
- ### Folder.tsx — Series/Parallel Engine
152
-
153
- - `FolderLeaf` is the recursive workhorse that renders all stream types
154
- - For `isSeries:true`: uses Remotion `<Series>` or `<TransitionSeries>` (if transition set)
155
- - For `isSeries:false`: renders children as parallel `<Sequence>` elements
156
- - Each child's duration comes from `child.durationInSeconds` (set by `getDurationInSeconds`)
157
- - Transition elements are interleaved between series children
158
- - Background children are wrapped in `<Loop>`
159
- - Scene nodes delegate to `SceneLeaf` → `FolderLeaf` (identity)
160
- - Effect nodes delegate to `EffectWrapper` → `FolderLeaf`
7
+ - Preserve the user's source video Markdown, selected template and manual `assets/`; never manually wipe generated `.markcut/` cache as a shortcut. Generated output is not a replacement for source Markdown.
8
+ - `src/descriptive/` owns Markdown parsing/compilation; `src/schema/` owns stream schema; `src/types/` renders streams; `src/player/` owns native preview; `src/mcp/` owns hosted ChatGPT preview; `src/vision/` owns media processing. Follow these boundaries instead of adding rules to the Skill to compensate for code defects.
9
+ - For a video authoring task, check `markcut verify` before preview/render, then confirm **real playback**. Parsing, compilation, rendered MP4 and hosted MCP iframe are separate checks.
10
+ - Never assume an image or map HTTP success means a visible frame; never assume a compiled audio stream means audible sound. Distinguish inferred routes from recorded GPS data.
161
11
 
162
- ### Video.tsx — startFrom/endAt Trimming
12
+ ## Commands and evidence
163
13
 
164
- - Uses Remotion `<OffthreadVideo>` for CPU-efficient video decoding
165
- - `startFrom` / `endAt` on the base node trim the source video (in seconds)
166
- - `playbackRate` is capped at 1 (`Math.min(1, ...)`) so source longer than timeline plays at normal speed and is truncated by the Sequence
167
- - **Critical formula**: `OffthreadVideo endAt = startFrom_frames + ((endAt_source - startFrom_source) * fps / playbackRate)`
168
- This sets `endAt` beyond the actual source end when `playbackRate < 1`, which prevents Remotion from rendering blank frames before the Sequence ends.
169
- - `endAt` without explicit value falls back to `stream.durationInSeconds ?? end - start`
170
-
171
- ### Rendering Pipeline
172
-
173
- 1. `Root.tsx` reads `getInputProps()` → parses via Zod `rootSchema`
174
- 2. `getDurationInSeconds()` stamps `durationInSeconds` on every node
175
- 3. `Composition.durationInFrames` is set to total duration
176
- 4. `MarkCut` wraps everything in `ComposeContext` + `ThemeProvider` + `AbsoluteFill`
177
- 5. `FolderLeaf` recursively renders the tree
178
-
179
- ### CLI Usage
180
-
181
- ```bash
182
- node src/render/cli.mjs render <file.json> [--output path]
183
- node src/render/cli.mjs render --template <id> --data <data.json>
184
- node src/render/cli.mjs preview <file.json> [--edit] [--label] [--port 3001]
185
- node src/render/cli.mjs templates
186
- ```
187
-
188
- ### Player Server (Edit Mode)
189
-
190
- - `--edit` flag starts a live-reload loop: edit JSON → player auto-refreshes
191
- - `--label` flag starts a labeling UI for selecting and annotating media
192
- - `--port` flag sets the server port (default 3001)
193
- - Unified server: `server.mjs` serves all modes (preview, edit, label). React control components in `components/`.
194
- - **Persistent AI agent via `pi --mode rpc`** (one cold start, many edits): at boot, `startAgentProcess()` spawns the configured agent CLI (`DEFAULT_AGENT_CLI`) with `--mode rpc` appended (the `-p/--prompt` flag is stripped — prompts arrive over stdin). Each `/api/edit` POST writes `{"id","type":"prompt","message"}` to stdin and resolves on the streamed `agent_settled` event (NOT idle-timeout guessing — pi's default interactive mode is a TUI, not a stdin REPL, so text/stdin mode does not work). Assistant text is collected from `message_end` events (`message.role==="assistant"`, text content blocks). `--session-id` (derived from the file path) resumes conversation history from disk across restarts. Do not revert to one-shot `spawn` per edit — that re-incurs the full cold-start every request.
195
-
196
- ## Testing
197
-
198
- ### Test Framework
199
- - **Vitest** with custom config in `tests/vitest.config.ts`
200
- - Non-parallel (`pool: "forks", fileParallelism: false`)
201
- - 600s timeout per test (integration tests render real MP4s)
202
-
203
- ### Key Test Utilities (`tests/utils.ts`)
204
-
205
- | Function | Purpose |
206
- |----------|---------|
207
- | `renderFixture(path, opts)` | Render a stream tree JSON → MP4 using `npx remotion render` |
208
- | `renderScenes(path, opts)` | Render scene-based video.json using `Main16x9` composition |
209
- | `getVideoInfo(path)` | Extract metadata via ffprobe (duration, dimensions, FPS, audio) |
210
- | `extractFrame(video, time, out)` | Extract PNG frame at timestamp via ffmpeg |
211
- | `isFrameNonBlank(path)` | Check center pixel isn't black (>10 in any RGB channel) |
212
- | `getFrameFileSize(path)` | Get PNG file size (proxy for visual content) |
213
- | `extractAudio(video, out)` | Extract audio track to WAV |
214
- | `transcribeAudio(path)` | Run whisper STT on audio |
215
-
216
- ### Test Categories (30 tests)
217
-
218
- 1. Basic Rendering — empty composition, dimension verification
219
- 2. Image + Subtitle — image rendering, inline/VTT/karaoke subtitles
220
- 3. Effects — fadeIn, bounceIn, custom keyframes
221
- 4. Map Rendering — canvas route visualization
222
- 5. Audio Rendering — audio track, non-silent verification
223
- 6. Include — nested composition via include
224
- 7. Full Feature Combination — multiple features
225
- 8. Scene Node — scene-based rendering
226
- 9. Audio STT — speech-to-text verification via whisper
227
- 10. Multiple Aspect Ratios — 16x9, 9x16, 1x1
228
- 11. Cross-Stream Types — parallel rendering, effect-wrapped children
229
- 12. Frame-Accurate — timeline consistency, frame count
230
- 13. Description Field — schema validation, render preservation
231
- 14. Scene as Folder Alias — scene/folder interchangeability
232
- 15. **Video startFrom/endAt Trimming** — video trimming + photo in series
233
-
234
- ### Running Tests
235
-
236
- ```bash
237
- npm test # all tests
238
- npm run test:integration # render integration tests only
239
- npx vitest run tests/render.test.ts -t "Test Name" # single test
14
+ ```sh
15
+ npm run typecheck
16
+ npm test
17
+ npm run verify -- <video.md>
18
+ npm run preview -- <video.md> --storyboard
19
+ npm run render -- <video.md> --output <path.mp4>
240
20
  ```
241
21
 
22
+ Use focused tests first, then regression tests relevant to changed code. Avoid running costly media generation when checking Markdown-only changes; create separate real-player E2E evidence when playback behavior was changed.
242
23
 
243
- ## Adding a new built-in component
244
-
245
- Built-in components are always available in `jsx:"..."` fields without imports. To add one:
246
-
247
- 1. **Create the component** in `src/components/<Name>.tsx` — a standard React component.
248
- 2. **Export from barrel** — add the re-export in `src/components/index.ts` and add the name to `BUILTIN_COMPONENT_NAMES` in `src/components/builtin-registry.ts`.
249
-
250
- ## 3-Level Authoring Workflow (see SKILL.md)
251
-
252
- | Level | Format | Purpose |
253
- |-------|--------|---------|
254
- | **Label** | `labels.json` | Browse media, label clips, add descriptions |
255
- | **Storyboard** | `storyboard.json` | `scene` nodes with high-level structure + script |
256
- | **Assemble** | `video.json` | Full stream tree with all types, render to MP4 |
257
-
258
- ### Script → TTS → STT → VTT Pipeline
259
-
260
- Every node carries an optional `script` field for narration/dialogue text. The pipeline:
261
- 1. **Storyboard** — agent writes `script` on any node (scene, folder, leaf) as narrative text
262
- 2. **TTS** — walk the tree, collect all `script` values with node id + timing, generate WAV audio per segment via `edge-tts`
263
- 3. **STT** — transcribe each TTS audio or concatenated audio to VTT via whisper
264
- 4. **Subtitle** — attach resulting VTT as a `subtitle` child node for final rendering
265
-
266
- This separates concerns: `script` = authoring text (human/agent-friendly), `subtitle` = rendered output (timed VTT cues).
267
-
268
- ### Multi-turn Dialogue
269
-
270
- When `script` text contains multiple `SpeakerName: text` lines (2+), the pipeline auto-expands it into a multi-turn dialogue. Each line becomes a separate audio node with `speaker` field, wrapped in a `series` container for sequential playback.
271
-
272
- ```md
273
- - script "Ray: Hello everyone
274
- Alice: Good day to you
275
- Ray: Let's begin"
276
- ```
277
-
278
- Per-speaker voices are configured via `voices` on root. Each value is extra CLI flags appended to the TTS template:
279
-
280
- ```md
281
- voices:{"Ray":"--voice en-US-GuyNeural","Alice":"--voice en-US-JennyNeural"}
282
- ```
283
-
284
- The speaker name is matched against `voices` map and the extra flags are appended to the TTS CLI template, naturally supporting voice cloning or edge-tts features (rate, pitch, etc.). Subtitles include the speaker prefix (`Ray: Hello everyone`).
285
-
286
- ## Dependencies
287
-
288
- - **Remotion 4.0.469** — core rendering engine
289
- - **React 19** — component model
290
- - **Zod 4** — schema validation
291
- - **@remotion/transitions** — scene transitions (fade, slide, wipe, flip, clockWipe)
292
- - **@vis.gl/react-google-maps** — map visualization
293
- - **immer** — state management (player app)
294
- - **vitest** — test runner
295
- - **TypeScript 5.6** — strict mode with `noUncheckedIndexedAccess`
296
-
297
- ## MCP Review UI Verification
298
-
299
- For comment-editor or timeline-dot changes, verify the built MCP player in a real browser: multiline input and overlay controls, then add/select/edit/remove Overall, Scene and Spot markers on the Remotion seek bar. Unit tests alone do not prove the hosted iframe is updated.
300
-
301
- ## MCP Provider Reload After Changes
302
-
303
- Whenever Markcut MCP server, preview UI, bridge, or bundled player code changes, rebuild the MCP bundle and reload **only the Markcut MCP provider** through Neo's provider control interface before testing or declaring the change live. Verify the running provider serves the new resource URI, then open a fresh ChatGPT iframe and check its displayed version and affected behavior. A Git push or ChatGPT tool-list refresh alone is not a provider reload. Never restart the whole Neo MCP app as a workaround; if scoped reload fails, report the live version and blocker explicitly.
304
-
305
- ## MCP background-audio regression guard
306
-
307
- When extracting HTTPS BGM from a preview tree, traverse the tree **before** returning the captured audio variable. JavaScript evaluates object properties left-to-right: returning `{audio, playbackRoot: strip(root)}` silently loses the BGM handle while removing the native audio node. Keep the pure extraction in `src/mcp/audio-preview-tree.ts` and run `tests/mcp-web-audio-preview.test.ts`. For user-style playback verification, check network HTTP 200, decoded duration, a running AudioContext, advancing Remotion frames, and nonzero Web Audio analyser RMS; a decoded source alone does not establish audible playback. Browser TTS must retain BGM and environmental audio, and only generated narration can be removed; listen for speech start/end to duck and restore Web Audio music gain.
308
-
309
- ## Route map framing
24
+ For MCP provider/player/bridge changes: rebuild the relevant bundle, reload **only the Markcut provider** through Neo's supported provider controls, verify the published resource/version, and open a fresh ChatGPT iframe. Do not restart the entire Neo MCP app. Verify scene/timed comments in the real hosted player, not just unit tests. For browser automation follow the separately discovered WebHelm Skill and stop task-owned sessions.
310
25
 
311
- For `map view:route`, omit `zoom` to auto-fit geotagged stops to the Remotion composition dimensions, including 9:16 vertical output; auto-fit reserves 14% padding. The route schema and both descriptive compiler paths must leave omitted zoom undefined, or their old `zoom:10` defaults silently override the runtime fit. Explicit `zoom` and camera tweens still override fit. Verify the real browser map's zoom/center and rendered tiles, not just a successful Markdown compile or Google API HTTP response. A calculated Directions line is not proof of a recorded GPS track.
26
+ Preserve unrelated worktrees, services, sessions, user media and credentials. Keep private coordinates and media links out of logs/public artifacts. For implementation-specific known regressions and tests, see [docs/developer-reference.md](docs/developer-reference.md).
package/README.md CHANGED
@@ -381,3 +381,12 @@ markcut queue list
381
381
  ```
382
382
 
383
383
  The template must use an executable reachable from the process environment. To avoid ambiguity with shell quoting of `$HOME`, use a literal absolute path in production. If unset, execution is unchanged. Rendering cache continues to be managed by Markcut, not the queue. No service restart or Markcut-specific queue daemon is required.
384
+
385
+ ## Vision inference adapters
386
+
387
+ Markcut's video and image understanding works through generic CLI templates.
388
+ Choose a project-specific inference adapter in the calling Agent/configuration,
389
+ then supply `--itt`, `--vtt` and `--agent` (or `MARKCUT_ITT_CLI`,
390
+ `MARKCUT_VTT_CLI` and `MARKCUT_AGENT_CLI`). See `markcut vision --help`
391
+ and `markcut --show-clis` for the supported placeholders. Markcut does not
392
+ choose or manage a browser/model provider.
@@ -0,0 +1,311 @@
1
+ # Markcut Developer Reference
2
+
3
+ > Markdown-to-video engine. Describe scenes in markdown, get a rendered video with TTS narration.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ npm run render storyboard.md # render markdown → MP4 (9x16 default)
9
+ npm run preview storyboard.md --edit # live preview with auto-reload
10
+ npm run preview storyboard.md --storyboard # fast structure preview (skips TTI/TTV, shows prompts as placeholders)
11
+ npm test # unit + integration tests
12
+ npm run typecheck # TypeScript type check
13
+ ```
14
+
15
+ ## Input formats
16
+
17
+ | Format | CLI | Description |
18
+ |---|---|---|
19
+ | Markdown | `markcut render storyboard.md` | `## Scene` headings, `- image src:...` bullets, `script:"narration"` |
20
+ | Descriptive JSON | `markcut render video.json` | Same schema as markdown, JSON syntax |
21
+ | Compiled JSON | `markcut render tree.json` | Pre-compiled stream tree (no pipeline needed) |
22
+
23
+ See [docs/markdown-strict-descriptive.md](docs/markdown-strict-descriptive.md) for the complete markdown syntax reference.
24
+
25
+ ## Key concepts
26
+
27
+ - **Scene** — narrative unit with `name`, `script` (TTS), `instruction` (visual intent), `children`
28
+ - **Layout** — `parallel` (simultaneous), `series` (sequential), `transitionSeries` (sequential with transitions)
29
+ - **Script → TTS → STT** — `script` field generates edge-tts audio, whisper transcribes to VTT subtitles
30
+ - **Theme** — preset colors/fonts/effects: `cinematic`, `neon`, `minimal`, `corporate`
31
+ - **TTL config** — root-level `tts.cli`, `tts.voice`, `tts.rate` with per-scene `tts` overrides
32
+ - **Subtitle** — root-level VTT overlay from merged per-clip STT. Not a tree node. Supports animated caption types (`typewriter`, `fade`, `bounce`, `glowing`, etc.) via `remotion-subtitle`, HTML in cue text, and per-cue `<Sequence>` rendering for zero CPU when inactive.
33
+
34
+ ## Stream types
35
+
36
+ | Type | Purpose |
37
+ |---|---|
38
+ | `root` | Canvas config: width, height, fps, theme, subtitle, stylesheet |
39
+ | `scene` | Storyboard container: name, layout, script, children |
40
+ | `folder` | Internal container (series/parallel) |
41
+ | `image` | Still photo with fit mode |
42
+ | `video` | Video clip with startFrom/endAt trimming, playbackRate |
43
+ | `audio` | Soundtrack/SFX with foreground ducking |
44
+ | `component` | External React component by componentName + props |
45
+ | `effect` | CSS keyframe animation wrapper (fadeIn, zoomIn, bounceIn, etc.) |
46
+ | `include` | Embed external video JSON (file, URL, or data URI) |
47
+
48
+ ## CLI
49
+
50
+ ```bash
51
+ markcut render <file.json|.md> [--output path]
52
+ markcut preview <file.json|.md> [--edit] [--label] [--port 3001]
53
+ ```
54
+
55
+ ## Project structure
56
+
57
+ ```
58
+ src/
59
+ ├── entry.tsx → MarkCut + DescriptiveComposition
60
+ ├── descriptive/ → Compiler, markdown parser, resolve pipeline
61
+ ├── types/ → React renderers (one per stream type)
62
+ ├── schema/ → Zod stream tree schemas
63
+ ├── themes/ → Theme presets + ThemeProvider
64
+ ├── render/cli.mjs → CLI entry
65
+ ├── render/tts.ts → TTS via CLI template + variable substitution
66
+ ├── player/pipeline.mjs → Bundled pipeline (server imports this)
67
+ ├── player/server.mjs → Unified server (--edit, --label, preview)
68
+ ├── player/components/ → React control components (edit, label, variant bar)
69
+ │ ├── index.ts
70
+ │ ├── EditControls.tsx
71
+ │ ├── LabelControls.tsx
72
+ │ └── VariantBar.tsx
73
+ └── tests/ → Vitest integration tests
74
+ ```
75
+
76
+ ## External component contract
77
+
78
+ Register components at render time:
79
+
80
+ ```tsx
81
+ <MarkCut
82
+ root={descriptiveJson}
83
+ compose={{ components: { AnimatedHeadline, StatCounter } }}
84
+ />
85
+ ```
86
+
87
+ In descriptive markdown:
88
+
89
+ ```md
90
+ - component componentName:StatCounter duration:3 props:{value:42}
91
+ ```
92
+
93
+ Components receive props as defined in the descriptive JSON. No eval, no JSX parsing — just `React.createElement(registry[name], props)`.
94
+ ```
95
+
96
+ ## Stream Tree Architecture
97
+
98
+ ### Core Concept
99
+
100
+ Everything is a **stream tree** — nested JSON nodes keyed by `type`.
101
+ The tree is validated by Zod and rendered by Remotion via recursive React components.
102
+
103
+ ```json
104
+ { "id":"root", "type":"root", "width":1080, "height":1920, "fps":30,
105
+ "isSeries":true, "transition":"fade", "children":[...] }
106
+ ```
107
+
108
+ ### Composition Rules
109
+
110
+ | Concept | Rule |
111
+ |---------|------|
112
+ | **Series** (`isSeries:true`) | Children play sequentially. Optional `transition` (fade/slide/wipe/flip/clockWipe) + `transitionTime` (default 0.5s). |
113
+ | **Parallel** (`isSeries:false`) | Children play simultaneously. Duration = max child duration. |
114
+ | **Background** (`isBackground:true`) | Loops for parent duration. Excluded from duration calculation. |
115
+ | **Timing** | Every leaf carries base fields `start`/`end` (seconds, relative to parent) + optional `startFrom`/`endAt` (source trim) + `duration` (convenience). `end` is the source of truth; `duration` normalizes to `end = start + duration` when `end` is absent. Inside series parents `start` is 0 (positioning is implicit). |
116
+ | **Scene** (`type:"scene"`) | UI storyboard card; engine treats as folder. Has `name` + `description` + `script`. |
117
+
118
+ ### Duration Calculation
119
+
120
+ Computed by `getDurationInSeconds()` in `src/utils/index.ts`:
121
+ - **Leaf nodes**: duration = `leafEnd(stream)` = `end ?? (start + duration)` (single deterministic read; `start`/`end`/`duration` live on the base node)
122
+ - **Series**: sum of children durations minus transition overlaps
123
+ - **Parallel**: max of children durations
124
+ - **Background children**: excluded from calculation
125
+ - **Include with `src`**: treated as leaf (duration from base `end`)
126
+ - Sets `durationInSeconds` on every node as a side effect
127
+
128
+ ### 12 Stream Types
129
+
130
+ All types share base fields from `BaseShape`: `id`, `name`, `title`, `description`, `script`, `src`, `style`, `visible`, `isBackground`, `start`, `end`, `duration`, `startFrom`, `endAt`, `durationInSeconds`.
131
+
132
+ | Type | Purpose | Key Fields |
133
+ |------|---------|------------|
134
+ | `root` | Canvas container | `width`, `height`, `fps`, `isSeries`, `transition`, `stylesheet` |
135
+ | `folder` | Group children | `isSeries`, `transition`, `children[]` |
136
+ | `scene` | Storyboard node (alias for folder) | `name`, `description`, `script`, `children[]` |
137
+ | `image` | Still photo | `src`, `fit` (contain/cover/fill) |
138
+ | `video` | Video clip | `src`, `volume`, `playbackRate` |
139
+ | `audio` | Soundtrack/SFX | `src`, `volume`, `foreground` (ducks parent) |
140
+ | `subtitle` | Text overlay | `src` (text/VTT) or `cues[]`, `fontSize`, `style` |
141
+ | `component` | Built-in `<Markdown>` | Renders markdown with GFM. Props: `source`/`children`, `plugins`, `components` |
142
+ | `component` | Built-in `<Mermaid>` | Renders Mermaid diagrams as inline SVG. Props: `source`/`children`, `theme` |
143
+ | `component` | React component | `componentName`, `props`, `src` (remote ESM) |
144
+ | `effect` | CSS animation wrapper | `animation`, `customKeyframes`, `children[]` |
145
+ | `rhythm` | Beat-synced loop | `src`, `spots[]`, `children[]` |
146
+ | `map` | Route visualization | `waypoints[{lat,lng,label}]`, `routeColor` |
147
+ | `include` | Embed sub-tree | `src` (path/URL/data URI), `children[]` |
148
+
149
+ ## Key Implementation Details
150
+
151
+ ### Folder.tsx — Series/Parallel Engine
152
+
153
+ - `FolderLeaf` is the recursive workhorse that renders all stream types
154
+ - For `isSeries:true`: uses Remotion `<Series>` or `<TransitionSeries>` (if transition set)
155
+ - For `isSeries:false`: renders children as parallel `<Sequence>` elements
156
+ - Each child's duration comes from `child.durationInSeconds` (set by `getDurationInSeconds`)
157
+ - Transition elements are interleaved between series children
158
+ - Background children are wrapped in `<Loop>`
159
+ - Scene nodes delegate to `SceneLeaf` → `FolderLeaf` (identity)
160
+ - Effect nodes delegate to `EffectWrapper` → `FolderLeaf`
161
+
162
+ ### Video.tsx — startFrom/endAt Trimming
163
+
164
+ - Uses Remotion `<OffthreadVideo>` for CPU-efficient video decoding
165
+ - `startFrom` / `endAt` on the base node trim the source video (in seconds)
166
+ - `playbackRate` is capped at 1 (`Math.min(1, ...)`) so source longer than timeline plays at normal speed and is truncated by the Sequence
167
+ - **Critical formula**: `OffthreadVideo endAt = startFrom_frames + ((endAt_source - startFrom_source) * fps / playbackRate)`
168
+ This sets `endAt` beyond the actual source end when `playbackRate < 1`, which prevents Remotion from rendering blank frames before the Sequence ends.
169
+ - `endAt` without explicit value falls back to `stream.durationInSeconds ?? end - start`
170
+
171
+ ### Rendering Pipeline
172
+
173
+ 1. `Root.tsx` reads `getInputProps()` → parses via Zod `rootSchema`
174
+ 2. `getDurationInSeconds()` stamps `durationInSeconds` on every node
175
+ 3. `Composition.durationInFrames` is set to total duration
176
+ 4. `MarkCut` wraps everything in `ComposeContext` + `ThemeProvider` + `AbsoluteFill`
177
+ 5. `FolderLeaf` recursively renders the tree
178
+
179
+ ### CLI Usage
180
+
181
+ ```bash
182
+ node src/render/cli.mjs render <file.json> [--output path]
183
+ node src/render/cli.mjs render --template <id> --data <data.json>
184
+ node src/render/cli.mjs preview <file.json> [--edit] [--label] [--port 3001]
185
+ node src/render/cli.mjs templates
186
+ ```
187
+
188
+ ### Player Server (Edit Mode)
189
+
190
+ - `--edit` flag starts a live-reload loop: edit JSON → player auto-refreshes
191
+ - `--label` flag starts a labeling UI for selecting and annotating media
192
+ - `--port` flag sets the server port (default 3001)
193
+ - Unified server: `server.mjs` serves all modes (preview, edit, label). React control components in `components/`.
194
+ - **Persistent AI agent via `pi --mode rpc`** (one cold start, many edits): at boot, `startAgentProcess()` spawns the configured agent CLI (`DEFAULT_AGENT_CLI`) with `--mode rpc` appended (the `-p/--prompt` flag is stripped — prompts arrive over stdin). Each `/api/edit` POST writes `{"id","type":"prompt","message"}` to stdin and resolves on the streamed `agent_settled` event (NOT idle-timeout guessing — pi's default interactive mode is a TUI, not a stdin REPL, so text/stdin mode does not work). Assistant text is collected from `message_end` events (`message.role==="assistant"`, text content blocks). `--session-id` (derived from the file path) resumes conversation history from disk across restarts. Do not revert to one-shot `spawn` per edit — that re-incurs the full cold-start every request.
195
+
196
+ ## Testing
197
+
198
+ ### Test Framework
199
+ - **Vitest** with custom config in `tests/vitest.config.ts`
200
+ - Non-parallel (`pool: "forks", fileParallelism: false`)
201
+ - 600s timeout per test (integration tests render real MP4s)
202
+
203
+ ### Key Test Utilities (`tests/utils.ts`)
204
+
205
+ | Function | Purpose |
206
+ |----------|---------|
207
+ | `renderFixture(path, opts)` | Render a stream tree JSON → MP4 using `npx remotion render` |
208
+ | `renderScenes(path, opts)` | Render scene-based video.json using `Main16x9` composition |
209
+ | `getVideoInfo(path)` | Extract metadata via ffprobe (duration, dimensions, FPS, audio) |
210
+ | `extractFrame(video, time, out)` | Extract PNG frame at timestamp via ffmpeg |
211
+ | `isFrameNonBlank(path)` | Check center pixel isn't black (>10 in any RGB channel) |
212
+ | `getFrameFileSize(path)` | Get PNG file size (proxy for visual content) |
213
+ | `extractAudio(video, out)` | Extract audio track to WAV |
214
+ | `transcribeAudio(path)` | Run whisper STT on audio |
215
+
216
+ ### Test Categories (30 tests)
217
+
218
+ 1. Basic Rendering — empty composition, dimension verification
219
+ 2. Image + Subtitle — image rendering, inline/VTT/karaoke subtitles
220
+ 3. Effects — fadeIn, bounceIn, custom keyframes
221
+ 4. Map Rendering — canvas route visualization
222
+ 5. Audio Rendering — audio track, non-silent verification
223
+ 6. Include — nested composition via include
224
+ 7. Full Feature Combination — multiple features
225
+ 8. Scene Node — scene-based rendering
226
+ 9. Audio STT — speech-to-text verification via whisper
227
+ 10. Multiple Aspect Ratios — 16x9, 9x16, 1x1
228
+ 11. Cross-Stream Types — parallel rendering, effect-wrapped children
229
+ 12. Frame-Accurate — timeline consistency, frame count
230
+ 13. Description Field — schema validation, render preservation
231
+ 14. Scene as Folder Alias — scene/folder interchangeability
232
+ 15. **Video startFrom/endAt Trimming** — video trimming + photo in series
233
+
234
+ ### Running Tests
235
+
236
+ ```bash
237
+ npm test # all tests
238
+ npm run test:integration # render integration tests only
239
+ npx vitest run tests/render.test.ts -t "Test Name" # single test
240
+ ```
241
+
242
+
243
+ ## Adding a new built-in component
244
+
245
+ Built-in components are always available in `jsx:"..."` fields without imports. To add one:
246
+
247
+ 1. **Create the component** in `src/components/<Name>.tsx` — a standard React component.
248
+ 2. **Export from barrel** — add the re-export in `src/components/index.ts` and add the name to `BUILTIN_COMPONENT_NAMES` in `src/components/builtin-registry.ts`.
249
+
250
+ ## 3-Level Authoring Workflow (historical implementation)
251
+
252
+ | Level | Format | Purpose |
253
+ |-------|--------|---------|
254
+ | **Label** | `labels.json` | Browse media, label clips, add descriptions |
255
+ | **Storyboard** | `storyboard.json` | `scene` nodes with high-level structure + script |
256
+ | **Assemble** | `video.json` | Full stream tree with all types, render to MP4 |
257
+
258
+ ### Script → TTS → STT → VTT Pipeline
259
+
260
+ Every node carries an optional `script` field for narration/dialogue text. The pipeline:
261
+ 1. **Storyboard** — agent writes `script` on any node (scene, folder, leaf) as narrative text
262
+ 2. **TTS** — walk the tree, collect all `script` values with node id + timing, generate WAV audio per segment via `edge-tts`
263
+ 3. **STT** — transcribe each TTS audio or concatenated audio to VTT via whisper
264
+ 4. **Subtitle** — attach resulting VTT as a `subtitle` child node for final rendering
265
+
266
+ This separates concerns: `script` = authoring text (human/agent-friendly), `subtitle` = rendered output (timed VTT cues).
267
+
268
+ ### Multi-turn Dialogue
269
+
270
+ When `script` text contains multiple `SpeakerName: text` lines (2+), the pipeline auto-expands it into a multi-turn dialogue. Each line becomes a separate audio node with `speaker` field, wrapped in a `series` container for sequential playback.
271
+
272
+ ```md
273
+ - script "Ray: Hello everyone
274
+ Alice: Good day to you
275
+ Ray: Let's begin"
276
+ ```
277
+
278
+ Per-speaker voices are configured via `voices` on root. Each value is extra CLI flags appended to the TTS template:
279
+
280
+ ```md
281
+ voices:{"Ray":"--voice en-US-GuyNeural","Alice":"--voice en-US-JennyNeural"}
282
+ ```
283
+
284
+ The speaker name is matched against `voices` map and the extra flags are appended to the TTS CLI template, naturally supporting voice cloning or edge-tts features (rate, pitch, etc.). Subtitles include the speaker prefix (`Ray: Hello everyone`).
285
+
286
+ ## Dependencies
287
+
288
+ - **Remotion 4.0.469** — core rendering engine
289
+ - **React 19** — component model
290
+ - **Zod 4** — schema validation
291
+ - **@remotion/transitions** — scene transitions (fade, slide, wipe, flip, clockWipe)
292
+ - **@vis.gl/react-google-maps** — map visualization
293
+ - **immer** — state management (player app)
294
+ - **vitest** — test runner
295
+ - **TypeScript 5.6** — strict mode with `noUncheckedIndexedAccess`
296
+
297
+ ## MCP Review UI Verification
298
+
299
+ For comment-editor or timeline-dot changes, verify the built MCP player in a real browser: multiline input and overlay controls, then add/select/edit/remove Overall, Scene and Spot markers on the Remotion seek bar. Unit tests alone do not prove the hosted iframe is updated.
300
+
301
+ ## MCP Provider Reload After Changes
302
+
303
+ Whenever Markcut MCP server, preview UI, bridge, or bundled player code changes, rebuild the MCP bundle and reload **only the Markcut MCP provider** through Neo's provider control interface before testing or declaring the change live. Verify the running provider serves the new resource URI, then open a fresh ChatGPT iframe and check its displayed version and affected behavior. A Git push or ChatGPT tool-list refresh alone is not a provider reload. Never restart the whole Neo MCP app as a workaround; if scoped reload fails, report the live version and blocker explicitly.
304
+
305
+ ## MCP background-audio regression guard
306
+
307
+ When extracting HTTPS BGM from a preview tree, traverse the tree **before** returning the captured audio variable. JavaScript evaluates object properties left-to-right: returning `{audio, playbackRoot: strip(root)}` silently loses the BGM handle while removing the native audio node. Keep the pure extraction in `src/mcp/audio-preview-tree.ts` and run `tests/mcp-web-audio-preview.test.ts`. For user-style playback verification, check network HTTP 200, decoded duration, a running AudioContext, advancing Remotion frames, and nonzero Web Audio analyser RMS; a decoded source alone does not establish audible playback. Browser TTS must retain BGM and environmental audio, and only generated narration can be removed; listen for speech start/end to duck and restore Web Audio music gain.
308
+
309
+ ## Route map framing
310
+
311
+ For `map view:route`, omit `zoom` to auto-fit geotagged stops to the Remotion composition dimensions, including 9:16 vertical output; auto-fit reserves 14% padding. The route schema and both descriptive compiler paths must leave omitted zoom undefined, or their old `zoom:10` defaults silently override the runtime fit. Explicit `zoom` and camera tweens still override fit. Verify the real browser map's zoom/center and rendered tiles, not just a successful Markdown compile or Google API HTTP response. A calculated Directions line is not proof of a recorded GPS track.