From cf5adb0172c72b49b27283dcaa2d0bc0fe28a2f2 Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:54:59 +0530 Subject: [PATCH 1/6] Workflows: save a routine and have an agent follow it again A workflow is a name, what it is for, and steps in plain words, each with the tool call that did it last time. Saved as library/workflows/.json, shared by every project. - workflows.js validates them (steps, limits, calls to real FableCut tools) and writes the text an agent follows - fablecut_workflows: list / show / save / delete, run in the MCP server itself, so it works without the editor server - GET/POST /api/workflows and /api/workflows/delete - CLAUDE.md "Workflows" section and docs page, README, llms.txt, site --- CHANGELOG.md | 8 ++ CLAUDE.md | 58 +++++++++++- README.md | 1 + docs/docs/audio/index.html | 4 +- docs/docs/build.js | 5 + docs/docs/captions/index.html | 4 +- docs/docs/color/index.html | 4 +- docs/docs/compositing/index.html | 4 +- docs/docs/compositions/index.html | 4 +- docs/docs/editing/index.html | 4 +- docs/docs/export/index.html | 4 +- docs/docs/frames/index.html | 4 +- docs/docs/index.html | 6 +- docs/docs/library/index.html | 6 +- docs/docs/masks/index.html | 4 +- docs/docs/mcp/index.html | 4 +- docs/docs/media/index.html | 4 +- docs/docs/motion-paths/index.html | 4 +- docs/docs/motion/index.html | 4 +- docs/docs/presets-templates/index.html | 4 +- docs/docs/project-json/index.html | 4 +- docs/docs/projects/index.html | 4 +- docs/docs/props/index.html | 4 +- docs/docs/recipes/index.html | 4 +- docs/docs/remake/index.html | 4 +- docs/docs/rest-api/index.html | 6 +- docs/docs/sequences/index.html | 6 +- docs/docs/studio/index.html | 2 +- docs/docs/tracking/index.html | 4 +- docs/docs/transcripts/index.html | 4 +- docs/docs/versions/index.html | 6 +- docs/docs/workflows/index.html | 126 +++++++++++++++++++++++++ docs/index.html | 1 + docs/llms.txt | 3 + docs/sitemap.xml | 6 ++ manifest.json | 1 + mcp-server.js | 52 ++++++++++ paths.js | 7 +- server.js | 42 ++++++++- test/workflows.test.js | 98 +++++++++++++++++++ workflows.js | 95 +++++++++++++++++++ 41 files changed, 556 insertions(+), 63 deletions(-) create mode 100644 docs/docs/workflows/index.html create mode 100644 test/workflows.test.js create mode 100644 workflows.js diff --git a/CHANGELOG.md b/CHANGELOG.md index ca5d1f719..a7f747ee8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Workflows.** Save a routine you want repeated, such as a podcast clean-up + or the weekly reel, as steps in plain words plus the tool calls that did + them. An agent lists your workflows and follows one on the next project, + fitting each step to the new footage instead of replaying it blindly. Saved + in `library/workflows/` and shared by every project; agents use + `fablecut_workflows`, and `/api/workflows` serves them over REST. + ### Changed - **Dropdowns match the editor.** The editor's dropdowns open a list in its dark theme instead of the browser's own popup, with optgroup headings, the diff --git a/CLAUDE.md b/CLAUDE.md index e066e35f0..a254a76b8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -74,6 +74,9 @@ Every Claude Code session then has these tools: always the open one. See "Projects" below. - `fablecut_versions` — a project's saved versions: save one before big edits, compare a version with now, restore one (never destructive), mark the final cut. See "Versions" below. +- `fablecut_workflows` — saved workflows: recipes of steps (and the tool calls that did + them) the user wants repeated on other projects. Save one, list them, show one and follow + it. See "Workflows" below. ### Token-efficient editing (important for agents) @@ -219,8 +222,9 @@ Reusable assets, visible in the editor's left-panel tabs and never copied: | `library/fonts/` | font editor | `.ttf/.otf/.woff/.woff2`, auto-registered, family name = file name; a variable font draws every `weight` | | `library/presets/` | Inspector → Motion → Presets | saved animation presets, one `.json` each (see "Presets and templates") | | `library/templates/`| **Templates** | saved templates, one `.json` each, listed after the built-in ones | +| `library/workflows/`| — | saved workflows, one `.json` each (see "Workflows") | -- List via `GET /api/library?dir=sfx|elements|svg|fonts|presets|templates` (recursive; subfolders OK). +- List via `GET /api/library?dir=sfx|elements|svg|fonts|presets|templates|workflows` (recursive; subfolders OK). - To use one in the timeline, add a media entry whose `src` is its library path, e.g. `{ "id":"m_x", "name":"whoosh.mp3", "kind":"audio", "src":"/library/sfx/whoosh.mp3" }` — then reference it from clips like any other media. @@ -1892,6 +1896,55 @@ and restore if the user prefers the old one; **client rounds** — save "Round 1 "Round 2", … with the feedback in the note, mark the approved one final; **what did the agent do?** — `diff` against the "Before agent edits" version. +### Workflows + +A **workflow** is a recipe the user wants repeated on other projects: "my podcast +clean-up", "the weekly reel", "client delivery". It is a name, what it is for, and +its steps in order. Each step says in plain words what to do, and may carry the +tool call that did it last time. Workflows are shared by every project, one JSON +file each in `library/workflows/.json`: + +```jsonc +{ "id": "podcast-clean-up", "name": "Podcast clean-up", + "description": "Voice level, no dead air, captions, a Shorts cut.", "tags": ["podcast"], + "steps": [ + { "text": "Reduce the room noise on the voice clips.", + "call": { "tool": "fablecut_denoise", "args": { "clipIds": ["c_vo"], "amount": "medium" } } }, + { "text": "Normalize the voice to -16 LUFS.", + "call": { "tool": "fablecut_normalize_audio", "args": { "clipIds": ["c_vo"], "target": -16 } } }, + { "text": "Cut the pauses longer than half a second, keeping the music bed running." }, + { "text": "Export for YouTube Shorts.", "call": { "tool": "fablecut_export", "args": { "preset": "youtube-shorts" } } } ], + "created": "…", "updated": "…" } +``` + +| key | does | +|---|---| +| `name` · `id` | up to 80 characters; the id is made from the name, and saving the same name again updates that workflow (it keeps its `created`) | +| `description` · `tags` | what it is for (up to 600 characters) · up to 12 labels | +| `steps` | 1–50, each `{text, call?}` (a plain string is a step with only text); `text` up to 1000 characters | +| `call` | `{tool, args}`: a FableCut tool (not `fablecut_workflows`) and the arguments it was given, up to 20 000 characters | + +**Following one is a job for judgement, not a replay.** The new project has other +clips, ids and times, so a step's call is a worked example: read what the step says, +look at the project (`fablecut_get_project {compact:true}`, `fablecut_frame`), and +make the call that does that here. A step with no call is one only the agent's +judgement can do ("pick the three strongest shots"). + +**Agents** use `fablecut_workflows` (or the REST endpoints below): + +- `{}` lists them (id, name, steps, tags, description); `{action:"show", id}` gives + the steps to follow (id or name). +- `{action:"save", workflow:{name, description?, tags?, steps}}` keeps one. Save when + the user asks to keep or repeat what was just done: write each step the way you would + explain it to another editor, and attach the calls that worked. A call to a tool that + doesn't exist refuses the save. +- `{action:"delete", id}` removes one: only when the user asks. + +Recipes: **"do what you did last week"** — `{}`, then `show` the one that matches and do +its steps; **a house style for every episode** — after the first episode is right, save +its loudness, captions, grade and export steps as one workflow; **hand a routine to another +agent** — the file in `library/workflows/` is plain JSON any agent can read. + ### Sequences A project can hold several **sequences**: timelines of their own that share @@ -2261,6 +2314,9 @@ obvious cuts were missed, raise it if motion is being misread as cuts. - `GET /api/presets` · `GET /api/templates` — the saved presets / templates, validated (bad files skipped); `POST /api/presets {preset}` · `POST /api/templates {template}` — validate one and save it as `library/presets/.json` / `library/templates/.json`, returning `{id, name, file}` +- `GET /api/workflows[?id=]` — the saved workflows, validated (bad files skipped), or one by id or name (404 if none) · + `POST /api/workflows {workflow}` — validate and save it as `library/workflows/.json`, returning it with + `created` / `updated` · `POST /api/workflows/delete {id}` → `{deleted}`. See "Workflows". - `POST /api/upload?name=foo.mp4` — raw body saved into ./media, returns `{src}`. MP4/MOV/M4V uploads are auto-remuxed with `+faststart` (needs ffmpeg on PATH). Files copied straight into ./media by external tools skip this — remux big ones diff --git a/README.md b/README.md index fa6f54eb2..0598f1fad 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ big operation (cutting silences, snapping to the beat, reframing), and every - **Projects** — a dashboard of every project with pictures, notes and tags: open, create from a canvas or a saved project template, duplicate, rename, archive and delete, import an old project file; media is shared, so copies cost no footage - **Sequences** — several timelines in one project (a 16:9 and a 9:16 cut, cut-downs, alternatives) sharing its media and compositions, each with its own canvas, frame rate, mix and delivery settings; switch from the menu at the left of the timeline toolbar - **Versions** — non-destructive history: save a version (Ctrl/Cmd+S), automatic versions every 10 minutes and before an agent edits, compare a version with now, restore (the current state is kept as a version first), mark the final cut; backups carry every version, and an unreadable `project.json` is recovered at startup +- **Workflows** — save a routine you want repeated (a podcast clean-up, the weekly reel) as plain-language steps plus the tool calls that did them, in `library/workflows/`; an agent lists them and follows one on the next project, fitting each step to the new footage (`fablecut_workflows`) - **Proxies** — light, frame-accurate H.264 copies of 4K / HEVC / ProRes footage made in the background (ffmpeg); edit on the proxy with the monitor's **Proxy** button, export always renders the originals - **Import from URL** — **+ URL** downloads an HTTPS video/audio/image into `./media/` (same-origin after import). Remote SVG is refused. Agents use diff --git a/docs/docs/audio/index.html b/docs/docs/audio/index.html index 182658955..6a98aab63 100644 --- a/docs/docs/audio/index.html +++ b/docs/docs/audio/index.html @@ -75,14 +75,14 @@

Audio mix

How clips reach the speakers and the export: clip gain, channels, track faders, the master, and loudness normalize.

Every clip runs through the same chain in preview and export: source → channels (audioChannel / channelMode) → gain (dB) → clip fx → volume (keyframes, fades, duck) → pan → its A-track, then track fx → track fader → track pan → (submix bus fx → fader → pan) → master sum → master fx → master fader. A track has a fader (tracks[].gain, dB), a pan (tracks[].pan) and effects (tracks[].fx); the master has a fader (master.gain) and effects (master.fx). Submix buses (buses[], B1…B8) group tracks: a track with out:"B1" feeds that bus instead of the master, and the bus has its own effects, fader, pan and mute - e.g. every dialogue lane into one bus with one compressor and one fader. Audio on a video lane (a clip with volume > 0 on V1…) goes straight to the master. In the UI these are the strips in the Mixer tab beside the Inspector (its FX button edits that track's or the master's effects); mute / solo are the existing track switches (disabledTracks).

Effects (fx - an array processed in order; every parameter optional, out-of-range values are clamped; on:false bypasses one without losing its settings):

typeparameters (default)
eqlowFreq 120 Hz, lowGain 0 dB (low shelf) · midFreq 1000, midGain 0, midQ 1 (peak) · highFreq 8000, highGain 0 (high shelf); gains −18…+18
highpass / lowpassfreq (80 / 8000 Hz), q 0.71
compressorthreshold −20 dB, ratio 4, attack 10 ms, release 200 ms, knee 6 dB, makeup 0 dB
limiterceiling −1 dB, release 80 ms - brickwall, 5 ms lookahead; nothing passes the ceiling
gatethreshold −50 dB, range −40 dB (how far it closes), attack 2, hold 80, release 150 ms
delaytime 0.3 s, feedback 0.35, mix 0.25
reverbdecay 2 s, predelay 20 ms, mix 0.25
distortiondrive 0.3, mix 1
widenerwidth 1.5 (0 = mono, 1 = as is, 2 = extra wide)
pitchsemitones 0 (−12…+12; changes pitch, not speed - about 30 ms of delay), mix 1

Presets fill the chain with tweakable effects: Voice - clean-voice, podcast, radio, deep-voice (pitch down 4 semitones + a warmer EQ), telephone; Music - cinematic, wide, muffled (next room). Agents apply them (or any chain) with the patch op setFx: {op:"setFx", target:"clip", id:"c_vo", preset:"podcast"} · {op:"setFx", target:"track", id:"A3", fx:[{type:"eq", highGain:-3}]} · {op:"setFx", target:"master", fx:[{type:"limiter", ceiling:-1}], append:true} · {op:"setFx", target:"bus", id:"B1", preset:"podcast"} · fx:null clears. On a clip it applies to its linked stems too; chains are validated (unknown effect or preset → the whole patch is refused). The compact project view shows chains as fx:highpass·eq·… (lowpass~freq = automated).

Effect automation - any effect parameter except reverb decay can follow keyframes: keys on the effect, {param: [{t, v, ease?}]}. t is seconds from the clip's start for a clip's effects, and timeline seconds for a track's, a bus's or the master's; ease (linear · ease-in · ease-out · ease-in-out, default ease-in-out) shapes the segment arriving at that key, as with clip keyframes. While a parameter has keys they set it. Preview and export follow them the same way (export steps every 20 ms with a short glide). In the effects panel each parameter has a ◆: set or remove a key at the playhead; with keys, the slider edits the key under the playhead. Agents: {op:"setFxKeys", target:"bus", id:"B1", type:"lowpass", param:"freq", keys:[{t:0, v:18000}, {t:8, v:500, ease:"ease-in"}]} (index picks the effect when the type repeats; keys:null clears) - or write keys inside a setFx chain. Example - a filter sweep into the drop: a lowpass on the music clip keyed from 400 Hz up to 20000 Hz over the build.

  • Set a track fader / pan: {op:"setTrack", id:"A2", set:{gain:-8, pan:0}} (null or 0 resets). Master: {op:"setProject", set:{master:{gain:-1}}}.
  • Buses: {op:"setBus", id:"B1", set:{name:"Dialogue", gain:-2, pan?, mute?}} creates or updates one; route a track in with {op:"setTrack", id:"A1", set:{out:"B1"}} (out:"master" or null routes it back); {op:"removeBus", id:"B1"} sends its tracks back to the master. In the Mixer: + Bus, the → menu under a track's name, double-click a bus name to rename it.
  • Noise reduction - fablecut_denoise {clipIds, amount?:"light"|"medium"|"strong"|"off"} (default medium; the inspector's Noise control does the same). The file's noise floor is measured (its quietest 50 ms windows), then ffmpeg's FFT denoiser pulls everything near it down (10 / 18 / 30 dB) into a FLAC copy of the whole source file in media/, registered with derivedFrom (the original) and denoise (the amount). The clip and its linked audio stems switch to that copy; the picture keeps its own file, so links, in points and timing stay as they were. off switches back; a level already rendered is reused. Works on audio clips (a video's sound is on its linked stems). Needs ffmpeg. Use it before normalizing - the measured loudness changes.
  • Normalize - fablecut_normalize_audio {clipIds, mode?:"lufs"|"peak", target?} measures each clip's source window after its channel routing (ITU-R BS.1770 integrated loudness with EBU R128 gating, or sample peak) and sets props.gain to hit the target. Linked stems are measured together and share one gain; passing a video clip normalizes its stems. Targets: −14 LUFS streaming / social, −16 LUFS podcast / dialogue, −23 LUFS broadcast, or mode:"peak", target:-1. Locked clips are skipped unless force:true. The inspector's Normalize in the editor does the same measurement.
  • Fade curves - a fade transition on an audio clip may carry curve: "power" (constant power - the crossfade default, no dip in the middle), "linear" (constant gain - for crossfading the same material, e.g. a split of one take) or "exp" (slow start, natural fade to silence). No curve keeps the original eased shape. Only the volume follows the curve; picture fades are unchanged. {transitionOut:{type:"fade", duration:3, curve:"exp"}}.
  • Crossfades - overlap A and B on one track and give A transitionOut:{type:"fade", duration:d, curve:"power"} and B transitionIn the same, with d = the overlap. Shift+D in the editor does it for you: it borrows the overlap from spare media on both sides of the cut (half each, or more from the side that has it), so nothing after the cut moves; for a linked shot the stems crossfade and B's picture dissolves in.
  • Auto-duck - fablecut_auto_duck {clipIds:[music…], under?:["A1"], amount?:-12, threshold?:-40, attack?:0.3, release?:0.6} finds where the voice tracks (default: every other audio track) are above threshold dBFS - short gaps are bridged so the music doesn't pump between words - and writes keyframes.duck on the music: ramp down attack s before speech, hold, back up over release s. It replaces earlier ducking; amount:0 clears it. Same as the inspector's Auto-duck section or the clip menu's Auto-duck under other tracks.
  • Silence - fablecut_silence {clipIds, threshold?:-40, minSilence?:0.5, padding?:0.15, cut?, tracks?, force?} listens to the speech clips (a video brings its linked stems; each measured after its channel routing, gain and volume) and finds every stretch where none of them is above threshold dBFS for at least minSilence seconds. It keeps padding seconds of quiet after the phrase before and before the phrase after, so words aren't clipped; a clip's own start and end are cut to the first and last word. Cuts land on whole frames, and the gaps between clips are left alone. Without cut it only reports the spans (timeline seconds). With cut:true each one is removed with an extract on the targeted tracks (tracks picks others), last first, in one revision: later material moves up, linked stems stay in step, and locked tracks and clips stay where they are - lock the music bed first if it should keep running under the tightened edit. force:true cuts through locked material too, so pass it only when the user asked. Only time that was actually heard is cut: a clip with no audio stream (or disabled) is left alone, and so is one with a speed ramp (keyframes.speed) - its sound doesn't sit on the timeline at one speed. A version of the project as it was is kept before the cut; if that fails the reply says so in a warning, and then there is no version to go back to. Raise threshold toward −30 in a noisy room; lower minSilence for a tighter, jump-cut feel. In the editor: the Inspector's Silence section on an audio or video clip (or right-click → Find silences) - Find marks the silences on the timeline as amber bands, Cut N extracts them (one undo step), Clear removes the marks. The marks drop when the timeline, a clip's file, speed or level, or the frame rate changes.
  • Beats - fablecut_beats {clipId, markers?, snap?, retime?, every?, force?} listens to a music clip (an audio clip, or a video's sound) and finds its tempo (BPM), a steady beat grid - the tempo's period, phased and fitted to the hits, so it doesn't drift over a song - and the drop, all in timeline seconds through the clip's in point and speed. On its own it only reports. Then, in one revision: markers:true puts a cyan marker on every beat (other markers stay, and a beat that already has one keeps it); snap:true (or {tracks, maxShift}) rolls each cut on the targeted video tracks to the nearest beat within half a beat - a roll, so nothing else moves and linked stems follow; a cut whose clips have no spare footage to reach the beat stays where it is, and the reply says how many; retime:{track?, every?, from?} lays a track's clips (default the lowest video track with clips) back to back on the beat, every beats each (1, 2, 4, 8 or 16; default 2), from the first beat at or after from (default the music's start), in their order - a clip whose footage runs out gets fewer beats, clips past the music keep their length, and one with less than a beat of footage refuses the whole re-cut. Locked clips are left alone by snap and refuse retime, unless force:true (only when the user asked). A version is kept before snap or retime; if saving it fails, the edit still goes ahead and the reply says so in a warning. A re-cut clip that gets shorter loses the keyframes past its new end, and its transitions are kept no longer than the clip, as with a trim. The music clip itself (and its linked stems) is never re-cut, even when it sits on the track being re-cut. Cuts land on whole frames. A clip with a speed ramp is refused: its music doesn't keep time on the timeline. In the editor: the Inspector's Beats section on an audio or video clip - Find beats shows the beat as ticks across the timeline and the BPM and drop below; then Mark, Snap cuts, and Re-cut a track every N beats (each one undo step).
  • In the editor, each audio clip shows its volume line (yellow; dashed = after ducking): drag it to change the level, Ctrl/Cmd-click to add a keyframe, drag a point to move it, Alt-click or double-click to remove one. The corner fade grips drag a constant-power fade in or out. Both edit linked stems together.
  • Use gain for "this clip is too quiet / loud", volume keyframes for shaping, duck for dipping under dialogue, the track fader to balance whole lanes (dialogue against the music bed), and a bus when several lanes need the same processing or one fader.
diff --git a/docs/docs/build.js b/docs/docs/build.js index ffaac5966..e469cbc8d 100644 --- a/docs/docs/build.js +++ b/docs/docs/build.js @@ -118,6 +118,11 @@ const PAGES = [ lede: "Saved copies of a project you can compare and go back to, made by you, every few minutes, and before an agent edits; restoring is never destructive, and a backup carries them all.", parts: [["project.json schema", "Versions"]], }, + { + slug: "workflows", nav: "Workflows", title: "Workflows", group: "The timeline", + lede: "Save a routine you want repeated — steps in plain words plus the tool calls that did them — and have an agent follow it on the next project.", + parts: [["project.json schema", "Workflows"]], + }, { slug: "sequences", nav: "Sequences", title: "Sequences", group: "The timeline", lede: "Several timelines in one project — a 16:9 and a 9:16 cut, cut-downs, alternatives — sharing its media and compositions, each with its own canvas, mix and delivery settings.", diff --git a/docs/docs/captions/index.html b/docs/docs/captions/index.html index 551223975..6fc5ffa77 100644 --- a/docs/docs/captions/index.html +++ b/docs/docs/captions/index.html @@ -75,14 +75,14 @@

Captions

Captions timed word by word from the transcript, in four styles, burned into the picture; SRT and WebVTT out and in.

Captions are made from a transcript (see Transcripts and text-based editing): the timeline's words are grouped into captions, and each caption is an ordinary text clip with wordTimes (each word's start and end), so its animation follows the speech word by word, and caption: true, so captions can be found, replaced and exported as a group. Because they are text clips they render the same way in preview and export (burned into the picture), and the Inspector restyles them like any title.

stylelook
subtitle (default)plain text on a dark bar, low on the frame, up to two lines
karaokebold outlined text; each word lights up as it is said
highlightbig uppercase outlined words, the one being said in a colour (highlightColor) - the short-video look; up to five words
popone to three big words at a time, each popping in as it is said

A new caption starts at a pause of 0.6 s or more, after a sentence, after a comma once it has three words, or when it would run too long (lines, words or seconds). Lines are as long as fit the canvas at the style's size: sizes follow the canvas's shorter side, so a 9:16 reel gets narrower captions than a 16:9 video. Each caption stays about a quarter of a second after its last word, never into the next one, and starts and ends on whole frames.

They go on the video lane captions are already on; otherwise on the top video lane when nothing is there while they run, else on a new lane above it. Making captions again replaces the ones there. Make them after the cutting is done: a cut through a caption shortens it but doesn't re-time its words, so make them again after you change the edit. The editor says so for a moment whenever an edit shortens a caption.

In the editor, the Captions row of the Transcript tab: pick a style, then Add captions (one undo step). SRT and VTT download the timeline's captions as a subtitle file; Import… places the captions of an SRT or WebVTT file instead, re-broken to the style's line length, with their words spread over each caption. Select a caption to restyle it in the Inspector: the Highlight colour sits under Animation, and a note says its words follow the speech.

Agents use fablecut_captions:

  • {} or {style:"highlight"} makes captions from every clip with sound (transcribing what has no transcript yet, as fablecut_transcribe does), and answers with where they went and the first few. clipIds, from / to limit it; lines, words and size (a scale on the style's size) adjust it; track picks the lane; replace:false keeps the captions already there.
  • {export:"srt"} or {export:"vtt"} writes the captions that show (not disabled, not on a disabled track) to exports/<project name>.srt or .vtt, adding a number when that name is taken (<project name> 2.srt), and returns the path: use that one.
  • {import:"<path to .srt or .vtt>"} places a file's captions (the file's text works too).
  • {remove:true} deletes every caption clip. Locked captions are left alone and refuse the call unless force:true.
  • Check one with fablecut_frame {time} while a word is being said. Restyle them all with updateClip (e.g. props:{highlightColor:"#22d3ee", y:500}) on each caption id from the compact view, which lists a caption as [5 words timed to speech] instead of its times.
diff --git a/docs/docs/color/index.html b/docs/docs/color/index.html index 2912578ce..01a380698 100644 --- a/docs/docs/color/index.html +++ b/docs/docs/color/index.html @@ -75,7 +75,7 @@
keydoes
name · ona label; on:false turns the layer off
qualifier.hue[centre°, width°, soft°] - hues within ±width/2 of the centre, easing out over soft; wraps through red. Greys carry no hue, so a hue range leaves them out
qualifier.sat · qualifier.luma[low, high, soft] on 0…1 - saturation (HSV) / Rec.709 luma between low and high
qualifier.invertselect everything else
mask.shapeellipse · rect · poly · bezier (or freehand with a stroke, fitted into a bezier - see Masks)
mask.x · mask.ycentre, as fractions of the clip's picture (0…1, y down)
mask.w · mask.hsize, fractions of the picture's width / height (ellipse, rect)
mask.rotationdegrees, clockwise
mask.feathersoft edge, a fraction of the picture's height (0…0.5), centred on the outline
mask.pointspoly: 3–16 [dx, dy] corners around x, y (fractions of width / height); bezier: 3–24 anchors [dx, dy] or [dx, dy, inX, inY, outX, outY] with curve handles
mask.invertgrade outside the shape
mask.keysanimate it: [{t, x?, y?, w?, h?, rotation?, feather?, ease?}], t in seconds from the clip's start; each param eases between the keys that set it (ease on the arriving key, as for clip keyframes)

Masks live in the clip's own picture, so they follow the clip when it is moved, scaled, rotated, cropped or flipped. On an adjustment layer they are fractions of the canvas.

In the editor the strip under Copy / Paste lists Primary and the layers; + Layer adds one. With a layer picked, the wheels, sliders and curves edit that layer, and three more sections appear: the layer's name, On, Matte (the monitor shows what it selects, white = graded), ↑ ↓ to reorder, Delete; Qualifier - Pick then click a colour in the monitor to select its hue, saturation and luma, then tune the ranges; and Mask - pick a shape and drag it on the monitor (inside moves it, the handles resize it, the knob rotates it, Shift snaps to 15°; on a poly or bezier, Ctrl-click adds a point and double-click removes one), or Draw a free-hand outline on the monitor (it becomes a bezier). ◆ Key keys the shape at the playhead; once it has keys, every change to the shape keys.

Wheel colours. A wheel's r, g, b normally carry no brightness: they are a point on the vectorscope's Cb / Cr plane, so pushing a wheel toward a colour moves the picture's trace toward that colour's target. To tint shadows teal by about 0.03: lift: [-0.034, 0.008, 0.012, 0] (r = 1.5748·Cr, g = −0.1873·Cb − 0.4681·Cr, b = 1.8556·Cb, with Cb = 0.0065, Cr = −0.0216 here). Small values go a long way - ±0.02…0.05 on lift and offset, ±0.05…0.15 on gamma and gain.

Agents set a grade with the patch op setGrade and check it with fablecut_scopes:

  • {op:"setGrade", id:"c_a", grade:{exposure:0.3, temp:-15, contrast:1.15}} - merges into the clip's grade key by key; null on a key resets it; replace:true starts from neutral; grade:null clears it; ids:[…] grades several clips at once. curves merges per channel: grade:{curves:{r:[[0.5, 0.55]]}} keeps the other channels, curves:{y:null} removes the luma curve. layers replaces the whole layer list. Unknown keys or bad values refuse the whole patch. Locks apply (force:true as elsewhere).
  • {op:"setGradeLayer", id, layer, set:{…}} edits one layer: layer is an index (0 = first) or a name. A name that isn't there yet - or the index one past the end - adds a layer. set takes any layer key and merges like setGrade; qualifier and mask also merge key by key (mask:{x:0.6} moves it, qualifier:{luma:null} drops the luma range). replace:true starts the layer from scratch (keeping its name), remove:true deletes it. ids:[…] works too.
  • fablecut_scopes {time} renders the graded frame at time (default: the playhead) exactly as export would - an open editor tab, else headless - and returns numbers: luma min / 1st percentile / median / mean / 99th percentile / max (0–1), the % of pixels at pure black and pure white, mean R/G/B, average saturation, and the midtones' colour cast (hue name, hue angle, strength; "neutral" below 0.01), plus the clips on screen and their grades. With an exportFrame it measures the delivered crop.
  • fablecut_scopes {time, matte:{clip, layer}} also measures what one layer selects: the matte's coverage (% of that clip's own picture, measured alone - other clips and adjustment layers don't count) and the levels, mean RGB, saturation and cast of the selected pixels after grading. A coverage near 0 means the qualifier or mask misses; check it before trusting a secondary.

Reading the numbers: a normally exposed shot has its median near 0.35–0.5; whitePct above ~1 means clipped highlights (lower highlights / whites, or add highSoft); blackPct above ~2 means crushed shadows. A cast strength above ~0.03 on a scene that should be neutral wants white balance: move temp against the cast (orange / yellow → lower temp; blue / cyan → raise it) and tint against green / magenta, then measure again.

Secondary workflow: grade the whole shot first (primary), then add a layer for the one thing that needs its own correction - e.g. skin: {op:"setGradeLayer", id, layer:"Skin", set:{qualifier:{hue:[25, 40, 20], sat:[0.12, 0.7, 0.1]}, saturation:92}}, then fablecut_scopes {matte:{clip:id, layer:0}} - expect a coverage that matches how much of the frame is skin and a cast near orange (hue ~25–35°). A sky: qualifier:{hue:[210, 50, 25], luma:[0.45, 1, 0.1]} with hueSat:[[210, 1.25]]. A vignette or a relight: a feathered ellipse mask with invert:true and exposure:-0.5, or without invert and exposure:+0.3 on a face; give it keys to follow a move.

Workflow for matching shots: grade the hero shot, measure it, then grade every other shot of the scene until its median and cast land near the hero's. In the editor, Copy / Paste on the Color tab pastes one clip's grade onto every selected clip.

diff --git a/docs/docs/compositing/index.html b/docs/docs/compositing/index.html index eb19f9c8c..a3404401a 100644 --- a/docs/docs/compositing/index.html +++ b/docs/docs/compositing/index.html @@ -75,14 +75,14 @@

Track mattes and blending

Cut a clip with the picture on another track by its alpha or its brightness, and lay clips over each other with blend modes, from the Inspector or from an agent with setMatte.

A track matte cuts a clip with the picture on another track: where that picture is opaque (alpha) or bright (luma), the clip shows. Set it on the clip being cut, the fill:

propdoes
mattealpha · alpha-inverted · luma · luma-inverted. Alpha keeps the clip where the matte's pixels are opaque, luma where they are bright (white = shows, black = gone, Rec. 709 weights). The inverted modes keep the opposite
matteTrackthe video track the matte comes from. Default: the video track directly above the clip (V2 for a clip on V1)

The matte track does not draw into the frame while a clip on screen uses it; it only cuts. Its clips keep their own transform, keyframes, opacity, masks and effects, so the matte can move, scale and animate on its own. When the matte track has nothing at that moment, alpha / luma show nothing of the clip and the inverted modes show all of it. Track mattes and masks combine: the matte cuts the clip, then its masks cut what is left, then opacity and blend composite it. A clip used as a matte is drawn without its own track matte. Audio clips take neither.

blend is how a clip lays over what is under it: normal · multiply · screen · overlay · darken · lighten · color-dodge · color-burn · hard-light · soft-light · difference · exclusion · hue · saturation · color · luminosity · lighter (add). Blending happens after masks and mattes, so a masked clip only blends where it is kept.

In the editor, Track matte and Matte track sit under Blend in the Inspector's Transform section (the Adjustment layer section for an adjustment layer). The timeline marks a clip with a track matte ◐ and shows the clips that serve as its matte hatched, labelled Matte.

Agents: {op:"setMatte", id, matte:"luma"} (or ids:[…]; track:"V3" picks the matte track, track:null goes back to the one above; matte:null removes it). blend, matte and matteTrack written through addClip / updateClip are validated too. fablecut_scopes lists each clip on screen with its matte (e.g. luma from V2), blend, and whether it is a matte itself.

Recipes: text filled with video - the text on V2, the video on V1 with matte:"alpha"; a shape reveal - an svg or a masked solid on V2 whose scale keys up, the shot on V1 with matte:"alpha"; light leaks / film burn on V2 with blend:"screen"; a grade only in the bright areas - an adjustment layer with matte:"luma" over a copy of the shot; a cut-out through a texture - luma-inverted against a black-and-white texture.

diff --git a/docs/docs/compositions/index.html b/docs/docs/compositions/index.html index 973af3654..8b4bddcba 100644 --- a/docs/docs/compositions/index.html +++ b/docs/docs/compositions/index.html @@ -75,7 +75,7 @@
keydefaultdoes
id · name- · the idhow clips and agents refer to it · the label shown on its clips and in the bin
width · heightthe project'sthe comp's frame, px (16…8192)
duration-seconds; what the comp shows past its clips is transparent (or its background)
backgroundnonea colour behind the comp's clips; leave it out for transparent
tracksV3…V1, A1, A2the comp's own lanes, like the project's tracks
clips[]ordinary clips of any kind (comp clips too), with times inside the comp
template-set on a placed template: {id, hold, fields} (see Presets and templates)

A comp clip (kind:"comp", compId, no mediaId) shows the comp from its in (comp seconds) for its duration, at speed 1. It draws like a picture of the comp's size: fit defaults to none (the comp's own pixels), and its transform, keyframes, opacity, transitions, masks, track matte, blend, grade and filters all apply to the comp's frame as a whole. Trims and splits move its in like a video clip's; the window can't run past the comp's length.

The media inside a comp plays and exports as if it were on the timeline: its video frames, and its audio, which goes through the main timeline's audio track of the same name (its fader, effects and bus). A comp clip that is disabled, or sits on a disabled track, silences the comp's audio too. Comps nest up to 4 deep, and a comp can never contain itself.

In the editor: the bin's Project tab lists the comps; drag one onto the timeline to place it, and double-click it (or a comp clip, or Open in the Inspector's Composition section) to open it. An open comp takes over the timeline: every tool, shortcut and inspector works on its clips, and the breadcrumb above the timeline (or Esc, once nothing is selected) goes back out. Right-click clips → Precompose moves them into a new comp and puts a comp clip in their place; right-click the Project tab → New composition starts an empty one. The Composition section also sets the comp's name, size, length and background.

Agents:

  • {op:"addComp", comp:{id?, name, duration, width?, height?, background?, tracks?, clips?:[…]}} adds one (its clips go through the same checks as addClip). {op:"updateComp", id, set:{name?, width?, height?, duration?, background?, tracks?}} changes it; {op:"removeComp", id} is refused while a clip still uses it.
  • Place it with addClip {kind:"comp", compId, track, start, duration, in?}.
  • {op:"inComp", comp, ops:[…]} runs clip and timeline ops on the comp's own clips: addClip, updateClip, removeClip, split, rippleDelete, the trims, setShape, setMask, setGrade, setParent, setMotionPath, setTextPath, clip setFx, precompose, and inComp for a comp inside it.
  • {op:"precompose", ids:[…], name?, id?} moves those clips (here, or in the comp an inComp is running in) into a new comp that starts at the earliest of them; a comp clip of the same length takes their place.
  • The compact view shows a comp clip as comp(lt in:1.5) and lists every comp under COMPS with its clips.

Recipes: reusable lower third - a template (next section) gives every speaker their own copy with their own name; a plain comp suits a graphic that is the same every time; logo sting - a draw-on logo comp at the head and tail of the edit; picture in picture of a whole scene - precompose the scene's clips, then scale the comp clip down and move it into a corner; one grade for a sequence - precompose it and grade the comp clip once.

diff --git a/docs/docs/editing/index.html b/docs/docs/editing/index.html index 2013a695b..7f05ed2fd 100644 --- a/docs/docs/editing/index.html +++ b/docs/docs/editing/index.html @@ -75,14 +75,14 @@

Editing rules

How tracks, links, locks, targeting and the trim tools behave, for people and agents alike.

  • Rendering order: V1 is drawn first, then V2, V3, … on top. SVG/image/text clips go on any V track (higher V lanes are handy overlay lanes). Add lanes with the timeline +V / +A buttons (or by listing them in tracks); up to 16 per kind. Right-click an empty track header → Remove track (disabled if the lane has clips or is the last video/audio track).
  • Audio tracks A1–An hold both standalone audio files and linked companions for imported video. Dropping a video creates the picture on a V track (props.volume: 0 so it isn't doubled) plus one kind:"audio" clip per source channel on consecutive A-tracks that share a linkGroup (and the same mediaId / timing). Each stem is mono-isolated then placed with pan (defaults preserve stereo: L −1, R +1). Standalone music/SFX also live on A-tracks. Linked partners move/trim/split together - edit timing on any member of the group; do not treat A-tracks as music-only.
  • Three track switches (Premiere-style), all in the track header and all persisted on project.json:
    • Enable (eye / speaker) → disabledTracks. Output only: a disabled lane is left out of preview, audio and export. It does not affect editing.
    • Target (click the track name - lit = targeted) → untargetedTracks. Decides which lanes an edit touches when nothing is selected: split at playhead (S), insert ripple (,), replace punches (.), ripple-delete shifting (⇧Del), close gap (⇧G), next gap (G), split / trim at IN/OUT (T / ⇧T) and jump to cut (↑ / ↓). Source placement follows targeting too: the picture lands on V1 if it is targeted, else the lowest targeted video lane (none → the edit lands audio-only); stems land on the first two targeted audio lanes. A selection is always edited wherever it sits.
    • Lock (padlock) → lockedTracks. Nothing on a locked lane can be moved, trimmed, split, deleted or edited in the inspector, and ripples leave it where it is while the other lanes shift. A locked lane is never an edit target. Typical use: lock the music bed, then ripple the picture freely.
  • Clip lock / enable - right-click a clip, or use the toggles at the top of the inspector. locked: true pins one clip the same way a locked lane does. disabled: true (⇧E) keeps the clip on the timeline but drops it from preview, audio and export - like a disabled lane, for a single clip. Both apply to the clip's whole linked group.
  • Locks and linked groups - a linked A/V group with any locked member (its own flag or its lane) counts as locked as a whole, so sync is never broken by a partial move.
  • Sync lock - edits that shift clips move the targeted lanes; linked AV partners always ride along, even on an untargeted lane, and locked groups stay put. On reload relinkClips rebuilds linkGroup from matching mediaId / start / in / duration.
  • Unlink / link (Ctrl/Cmd+L) - unlinking a group removes its linkGroup and stamps unlinked: true on each member, so the reload-time relink leaves them apart; picture and audio then move, trim and delete separately. Link (select one video clip plus its audio, Ctrl/Cmd+L) only joins clips of the same file that line up exactly - same start, in and duration - because a link here means identical timing.
  • Agents and locks - fablecut_patch_project refuses updateClip / removeClip on locked material (own flag, locked lane, or a linked partner of one) and addClip onto a locked lane. Treat locked clips as the user's finished work: leave them alone. Only when the user asks you to change one, pass force: true on that op, or unlock first with updateClip set:{locked:null} (always allowed). fablecut_set_project, REST PUT and direct file edits are not guarded - respect locks there too.
  • Media is fit-ted to the canvas (default "contain"), then crop → scale/x/y/ rotation → flips apply.
  • props keys are all optional - missing keys get the defaults above.
  • Video/audio clips must satisfy in + duration×speed ≤ media.duration.
  • Keyframes fully override the static prop value while present; they are clip-local and are re-based automatically when clips are split or trimmed.
  • Transitions modulate the evaluated props (fade also fades audio); they render on top of keyframes, so both can coexist.
  • Same-track overlap IS the crossfade idiom: overlap A and B by ~1 s and give B transitionIn: {type:"fade"} (for audio also A transitionOut, both with curve:"power" - see Audio mix).
  • A cut/split is just two clips: first with duration: t, second with start: +t, in: +t×speed, duration: rest.
  • Edit tools (timeline toolbar picker, or V / B / R / Y / U) change what a clip drag does. Agents run the same edits with the patch ops rippleTrim, roll, slip and slide (see Timeline edit ops).
    • Selection (V) - move and trim, as always.
    • Ripple edit (B) - drag a clip edge; everything after it on the targeted tracks (and the clip's own lanes) moves with it, so no gap opens or closes. Dragging a head keeps the clip's start and trims its source In.
    • Rolling edit (R) - drag a cut; the clip on one side lengthens by what the other loses, nothing else moves.
    • Slip (Y) - drag a clip to change its source In only (dragging left shows later source); position and length stay. Video / audio clips only.
    • Slide (U) - drag a clip along its track; the clip before it trims its tail and the clip after it its head, so the sequence length stays. All four are clamped to the available source media, MIN_DUR and the free room on the track, take linked partners with them, and refuse on locked clips; a readout by the pointer shows the offset while dragging.
  • Lift (;) / Extract (') - remove IN→OUT on the targeted tracks. Lift leaves the gap; Extract closes it. Linked partners are cut too, locked clips stay whole, and IN / OUT clear afterwards.
  • Jump to cut - ↑ / ↓ move the playhead to the previous / next clip In or Out. Selection first (that clip’s start then end); no selection walks targeted-track cuts. Source monitor: 0 / In / Out / duration. Does not change project.json.
  • bgRemove and chromaKey can combine with all filters; heavy pixel work is automatic (only runs when those props are set).
diff --git a/docs/docs/export/index.html b/docs/docs/export/index.html index b7536c508..80adb3a3f 100644 --- a/docs/docs/export/index.html +++ b/docs/docs/export/index.html @@ -75,7 +75,7 @@

Export is one ffmpeg pass. The server owns the input side and the output path; args is everything in between (plus JPEG color conversion derived from color):

ffmpeg -y -f image2pipe -framerate <fps> -i - [-i audio.wav] <jpeg-color> <args…> exports/<name><extension>
  • There is no allow-list. Any codec, filter, container or flag your local ffmpeg supports works - ProRes, DNxHD, NVENC/QSV/VideoToolbox, VP9/AV1, 10-bit, HDR tags. See the shipped prores422, broadcast1080i50, nvenc-h264, nvenc-hevc, videotoolbox-h264 and videotoolbox-hevc profiles (the NVENC ones need an NVIDIA GPU; VideoToolbox requires macOS / Apple Silicon).
  • Args are validated by ffmpeg itself, not by a schema: when an export starts the server dry-runs the profile against a 0.1 s synthetic input (lavfi). A typo or an encoder your build lacks is rejected up front with ffmpeg's own message, instead of failing after every frame has been rendered.
  • Use the array form - each element is passed to spawn untouched, so no quoting is needed (["-vf", "drawtext=text='hi there'"] just works). A plain string is accepted and split on whitespace.
  • color controls JPEG→YUV conversion and stream tags (-colorspace / -color_primaries / -color_trc / -color_range). Default is BT.709 limited (range: "tv"). Use "range": "pc" for full-range masters. Do not put those flags in args - the engine strips them and applies color so vf and tags stay aligned. -pix_fmt stays in args (sampling / bit depth only).
  • Nothing else is injected for you: +faststart, -shortest, -strict -2 for Opus in MP4 and pixel-format choices are all yours to write.
  • Frames arrive as JPEG (4:2:0), so yuv422p/yuv444p cannot recover chroma the source never had; raise jpegQuality before reaching for a wider pixel format. Optional pixelFormat:"rgba" on /api/export/begin pipes uncompressed canvas frames instead (-f rawvideo) when a caller wants full chroma.
  • The audio mix is only present when the timeline has audio; with no audio there is a single input, so avoid hardcoded -map 1:a.

Note: Fast export pipes composited JPEG frames from the browser (-f image2pipe), not -i source.mp4. Filters and codec settings apply to that frame stream. To transcode an existing file verbatim, run ffmpeg directly - that is outside the compositor path.

Encoding profiles are listed at the bottom of the Export dialog's Preset list.

What the Export dialog opens on (priority):

  1. project.delivery, then project.encodeProfile - set with setProject
  2. The last preset or profile used in this browser
  3. The master delivery preset

MCP: fablecut_encode_profiles lists profiles; {detail:true} includes each args array; {profile:"hq"} returns one profile. fablecut_status shows the effective profile.

diff --git a/docs/docs/frames/index.html b/docs/docs/frames/index.html index 6494a2bf9..4d0248830 100644 --- a/docs/docs/frames/index.html +++ b/docs/docs/frames/index.html @@ -75,14 +75,14 @@

Look at the footage

Show an agent what the footage holds: one frame, a contact sheet across a clip, or the composed timeline - as an image, or as text-only measurements for models without vision.

fablecut_analyze_reference gives you the ears - where the cuts are, how hard each shot hits. fablecut_frame gives you the eyes. It answers with a real image (an MCP image content block), so you can judge a shot instead of inferring it from an energy value.

callreturns
{path:"/media/x.mp4", t:3.2}that exact frame
{path:"/media/x.mp4", frames:12}a 4×3 contact sheet across the whole clip
{path:"/media/x.mp4", frames:12, from:30, to:90}a contact sheet across part of it
{time:8.5} (no path)the composed timeline at 8.5 s, graded, all tracks
{path} with an absolute paththe file is read in place without copying into media/
{path, text:true}text-only statistics (luma, colors, texture, saturation, motion) for non-vision agents

Each answer leads with a text line naming the source, the timestamp(s) and (in timeline mode) the clips on screen, so you always know what you are looking at. width sets the pixel width (default 768 for one frame, 320 per contact-sheet cell); text:true returns descriptive statistics instead of an image block, for agents without vision capability - luma levels (min, p1, median, mean, p99, max, all 0–1 like fablecut_scopes), dominant colors, texture, saturation and per-cell motion; where/timeout apply to timeline mode only.

The REST endpoint /api/frame accepts src, t, frames, from, to, w, q (JPEG quality 1–31) and text=1 (statistics mode) as query parameters.

When it pays. Before choosing a clip's in point, sample a few candidate moments - the blueprint tells you a shot spans 2.1 s–4.9 s and reads energy: 88, but only a frame tells you whether that is a car jump or a pan across a landscape. Contact sheets are the cheap survey: one call shows you what a whole 3-minute clip holds, then you grab single frames where it matters. Timeline mode answers "what did I actually build?" - the same picture the user sees and export renders, grades and transitions included.

Needs ffmpeg on PATH for the source modes. Timeline mode runs in the open editor tab, else a headless browser, like fablecut_export.

diff --git a/docs/docs/index.html b/docs/docs/index.html index 326a6db6f..52c96af65 100644 --- a/docs/docs/index.html +++ b/docs/docs/index.html @@ -75,14 +75,14 @@

FableCut docs

The manual for FableCut, built from CLAUDE.md in the repo: the same text your agent reads through the fablecut_docs tool, so what you read here is what it knows.

-
Studio (no install)The same editor at studio.fablecut.space, with nothing to install. It edits a folder on your own disk, and Claude Code, claude.ai, ChatGPT or any MCP client can drive it by link.MCP toolsConnect an agent, and the calls it uses to read and change your timeline without burning tokens.project.jsonThe whole edit in one file: canvas, markers, tracks, media and clips.Clip propsEvery property a clip can carry and its default. A key a clip leaves out falls back to these.CompositionsBuild a lower third, a logo sting or a whole scene once as a composition, then place it anywhere as one clip that moves, masks and grades like a picture, from the bin or by an agent with addComp, inComp and precompose.Media managementFile details, search, filters, sorting, tags and collections, where each file is used, relinking missing files, and proxies for heavy footage.ProjectsKeep many projects in one FableCut: a dashboard to open, create from a canvas or template, duplicate, rename, take notes on, tag, archive and delete them, and fablecut_projects for agents.VersionsSaved copies of a project you can compare and go back to, made by you, every few minutes, and before an agent edits; restoring is never destructive, and a backup carries them all.SequencesSeveral timelines in one project - a 16:9 and a 9:16 cut, cut-downs, alternatives - sharing its media and compositions, each with its own canvas, mix and delivery settings.Editing rulesHow tracks, links, locks, targeting and the trim tools behave, for people and agents alike.Asset librarySound effects, overlays, fonts and animated SVGs that ship with the editor, and how to make your own.Audio mixHow clips reach the speakers and the export: clip gain, channels, track faders, the master, and loudness normalize.TranscriptsTurn speech into words with times, in the browser, then read, search and cut the edit like text: in the Transcript tab, or from an agent with fablecut_transcribe.CaptionsCaptions timed word by word from the transcript, in four styles, burned into the picture; SRT and WebVTT out and in.ColorGrade a clip with wheels, exposure, white balance and tone, and check it with scopes: in the Color workspace, or from an agent with setGrade and fablecut_scopes.MasksCut what a clip shows with rectangles, ellipses, bezier and free-hand shapes: feathered, expanded, inverted, combined and keyframed, from the monitor or from an agent with setMask.Track mattes and blendingCut a clip with the picture on another track by its alpha or its brightness, and lay clips over each other with blend modes, from the Inspector or from an agent with setMatte.TrackingFollow a point or a region through a video clip, then make a mask follow it or pin a title, sticker or another clip to it, from the Inspector or from an agent with fablecut_track.Shapes and parentingMotion graphics: vector shape layers with fills, strokes, groups and trim paths, null objects, parenting and the anchor point, keyframed on the monitor or by an agent with setShape and setParent.Motion pathsBend a clip's travel into a curve, turn it along the way, blur fast moves with a shutter angle, and set titles along lines, arcs, circles and drawn paths, on the monitor or by an agent with setMotionPath and setTextPath.Presets & templatesPut a ready-made entrance, exit, emphasis or loop on any clip, and place lower thirds, logo animations and social layouts whose text, colours and logo you fill in, from the bin and the Inspector or by an agent with applyPreset and addTemplate.RecipesShort answers for common edits: grades, captions, speed ramps, transitions and more, each one a few props away.Remake a referenceTurn a video you like into a blueprint of shots, beats and energy, then rebuild it with your own footage.Look at the footageShow an agent what the footage holds: one frame, a contact sheet across a clip, or the composed timeline - as an image, or as text-only measurements for models without vision.REST APIThe HTTP endpoints behind the editor, for scripts and tools that don't speak MCP.ExportThe three export engines, which range gets exported, and the ffmpeg encoding profiles.

Run#

node server.js        # → http://localhost:7777   (from npm: npx -y fablecut)

Files: index.html + style.css + app.js (editor UI), server.js (API + hosting), project.json (the timeline - THE file to edit), media/ (project footage), library/ (default asset library, see below).

How Claude Code edits a video#

  1. Ensure the server is running (background: node server.js, or fablecut_status).
  2. Put source files in ./media/ (copy them in, import via the UI / + URL, or fablecut_import_media with a local path or HTTPS URL).
  3. Read project.json, modify media / clips, increment revision, write it back.
  4. The browser UI (if open) reloads instantly. The user previews/exports from the UI.

Rules:

  • Prefer fablecut_set_project over direct file writes - it detects conflicts automatically (see the MCP section above). If you do write project.json directly, read it immediately before writing (never write from a stale read: if the user tweaked something in the UI between your read and write, that write destroys their changes). The UI detects external changes by revision comparison, so a write that does not bump revision is invisible to it.
  • Make each edit a single atomic write (read → modify → write once), and bump revision (integer). Partial multi-step edits can be picked up half-finished.
  • New media entries may omit duration - the browser probes it and writes it back. If you need the duration yourself, re-read project.json after a second or two, or probe with ffprobe.
  • Don't edit project.json while the UI may be mid-drag - the UI defers external reloads during gestures, then picks up the next change.
+
Studio (no install)The same editor at studio.fablecut.space, with nothing to install. It edits a folder on your own disk, and Claude Code, claude.ai, ChatGPT or any MCP client can drive it by link.MCP toolsConnect an agent, and the calls it uses to read and change your timeline without burning tokens.project.jsonThe whole edit in one file: canvas, markers, tracks, media and clips.Clip propsEvery property a clip can carry and its default. A key a clip leaves out falls back to these.CompositionsBuild a lower third, a logo sting or a whole scene once as a composition, then place it anywhere as one clip that moves, masks and grades like a picture, from the bin or by an agent with addComp, inComp and precompose.Media managementFile details, search, filters, sorting, tags and collections, where each file is used, relinking missing files, and proxies for heavy footage.ProjectsKeep many projects in one FableCut: a dashboard to open, create from a canvas or template, duplicate, rename, take notes on, tag, archive and delete them, and fablecut_projects for agents.VersionsSaved copies of a project you can compare and go back to, made by you, every few minutes, and before an agent edits; restoring is never destructive, and a backup carries them all.WorkflowsSave a routine you want repeated - steps in plain words plus the tool calls that did them - and have an agent follow it on the next project.SequencesSeveral timelines in one project - a 16:9 and a 9:16 cut, cut-downs, alternatives - sharing its media and compositions, each with its own canvas, mix and delivery settings.Editing rulesHow tracks, links, locks, targeting and the trim tools behave, for people and agents alike.Asset librarySound effects, overlays, fonts and animated SVGs that ship with the editor, and how to make your own.Audio mixHow clips reach the speakers and the export: clip gain, channels, track faders, the master, and loudness normalize.TranscriptsTurn speech into words with times, in the browser, then read, search and cut the edit like text: in the Transcript tab, or from an agent with fablecut_transcribe.CaptionsCaptions timed word by word from the transcript, in four styles, burned into the picture; SRT and WebVTT out and in.ColorGrade a clip with wheels, exposure, white balance and tone, and check it with scopes: in the Color workspace, or from an agent with setGrade and fablecut_scopes.MasksCut what a clip shows with rectangles, ellipses, bezier and free-hand shapes: feathered, expanded, inverted, combined and keyframed, from the monitor or from an agent with setMask.Track mattes and blendingCut a clip with the picture on another track by its alpha or its brightness, and lay clips over each other with blend modes, from the Inspector or from an agent with setMatte.TrackingFollow a point or a region through a video clip, then make a mask follow it or pin a title, sticker or another clip to it, from the Inspector or from an agent with fablecut_track.Shapes and parentingMotion graphics: vector shape layers with fills, strokes, groups and trim paths, null objects, parenting and the anchor point, keyframed on the monitor or by an agent with setShape and setParent.Motion pathsBend a clip's travel into a curve, turn it along the way, blur fast moves with a shutter angle, and set titles along lines, arcs, circles and drawn paths, on the monitor or by an agent with setMotionPath and setTextPath.Presets & templatesPut a ready-made entrance, exit, emphasis or loop on any clip, and place lower thirds, logo animations and social layouts whose text, colours and logo you fill in, from the bin and the Inspector or by an agent with applyPreset and addTemplate.RecipesShort answers for common edits: grades, captions, speed ramps, transitions and more, each one a few props away.Remake a referenceTurn a video you like into a blueprint of shots, beats and energy, then rebuild it with your own footage.Look at the footageShow an agent what the footage holds: one frame, a contact sheet across a clip, or the composed timeline - as an image, or as text-only measurements for models without vision.REST APIThe HTTP endpoints behind the editor, for scripts and tools that don't speak MCP.ExportThe three export engines, which range gets exported, and the ffmpeg encoding profiles.

Run#

node server.js        # → http://localhost:7777   (from npm: npx -y fablecut)

Files: index.html + style.css + app.js (editor UI), server.js (API + hosting), project.json (the timeline - THE file to edit), media/ (project footage), library/ (default asset library, see below).

How Claude Code edits a video#

  1. Ensure the server is running (background: node server.js, or fablecut_status).
  2. Put source files in ./media/ (copy them in, import via the UI / + URL, or fablecut_import_media with a local path or HTTPS URL).
  3. Read project.json, modify media / clips, increment revision, write it back.
  4. The browser UI (if open) reloads instantly. The user previews/exports from the UI.

Rules:

  • Prefer fablecut_set_project over direct file writes - it detects conflicts automatically (see the MCP section above). If you do write project.json directly, read it immediately before writing (never write from a stale read: if the user tweaked something in the UI between your read and write, that write destroys their changes). The UI detects external changes by revision comparison, so a write that does not bump revision is invisible to it.
  • Make each edit a single atomic write (read → modify → write once), and bump revision (integer). Partial multi-step edits can be picked up half-finished.
  • New media entries may omit duration - the browser probes it and writes it back. If you need the duration yourself, re-read project.json after a second or two, or probe with ffprobe.
  • Don't edit project.json while the UI may be mid-drag - the UI defers external reloads during gestures, then picks up the next change.
diff --git a/docs/docs/library/index.html b/docs/docs/library/index.html index deb6db7ec..ac56467eb 100644 --- a/docs/docs/library/index.html +++ b/docs/docs/library/index.html @@ -75,12 +75,12 @@

Asset library

Sound effects, overlays, fonts and animated SVGs that ship with the editor, and how to make your own.

-

The asset library#

Reusable assets, visible in the editor's left-panel tabs and never copied:

FolderEditor tabPurpose
library/sfx/Sound FXwhooshes, impacts, risers, UI clicks
library/elements/Elementsoverlay art: alpha PNGs, light leaks, textures, stickers
library/svg/SVGanimated vector graphics you author (convention below)
library/fonts/font editor.ttf/.otf/.woff/.woff2, auto-registered, family name = file name; a variable font draws every weight
library/presets/Inspector → Motion → Presetssaved animation presets, one .json each (see Presets and templates)
library/templates/Templatessaved templates, one .json each, listed after the built-in ones
  • List via GET /api/library?dir=sfx|elements|svg|fonts|presets|templates (recursive; subfolders OK).
  • To use one in the timeline, add a media entry whose src is its library path, e.g. { "id":"m_x", "name":"whoosh.mp3", "kind":"audio", "src":"/library/sfx/whoosh.mp3" } - then reference it from clips like any other media.
  • Dropping files into these folders live-refreshes the open UI.

Authoring animated SVGs#

You can create your own vector animations/overlays: write an .svg file into library/svg/ (or media/), register it as media with "kind": "svg", and place it on a video track. The compositor renders it frame-accurately, driven by the clip's local time (preview and export).

Conventions (required for time-driven animation):

  1. Root <svg> must carry width and height attributes (or a viewBox).
  2. Animate with CSS @keyframes inside a <style> block - SMIL (<animate>) is NOT time-controlled.
  3. Never write a literal animation-delay. For staggered starts set the custom property --d on the element instead: style="--d:0.4s". (The engine drives time by overriding animation-delay to calc(var(--d,0s) - t) with animations paused.)
  4. animation-fill-mode: both (or the both keyword in the shorthand) for one-shot intros; infinite for loops - both work.
  5. For rotations/scales around an element's own center add transform-box: fill-box; transform-origin: center;.
  6. Keep files self-contained (no external hrefs).

Skeleton:

<svg xmlns="http://www.w3.org/2000/svg" width="800" height="450" viewBox="0 0 800 450">
+    

The asset library#

Reusable assets, visible in the editor's left-panel tabs and never copied:

FolderEditor tabPurpose
library/sfx/Sound FXwhooshes, impacts, risers, UI clicks
library/elements/Elementsoverlay art: alpha PNGs, light leaks, textures, stickers
library/svg/SVGanimated vector graphics you author (convention below)
library/fonts/font editor.ttf/.otf/.woff/.woff2, auto-registered, family name = file name; a variable font draws every weight
library/presets/Inspector → Motion → Presetssaved animation presets, one .json each (see Presets and templates)
library/templates/Templatessaved templates, one .json each, listed after the built-in ones
library/workflows/-saved workflows, one .json each (see Workflows)
  • List via GET /api/library?dir=sfx|elements|svg|fonts|presets|templates|workflows (recursive; subfolders OK).
  • To use one in the timeline, add a media entry whose src is its library path, e.g. { "id":"m_x", "name":"whoosh.mp3", "kind":"audio", "src":"/library/sfx/whoosh.mp3" } - then reference it from clips like any other media.
  • Dropping files into these folders live-refreshes the open UI.

Authoring animated SVGs#

You can create your own vector animations/overlays: write an .svg file into library/svg/ (or media/), register it as media with "kind": "svg", and place it on a video track. The compositor renders it frame-accurately, driven by the clip's local time (preview and export).

Conventions (required for time-driven animation):

  1. Root <svg> must carry width and height attributes (or a viewBox).
  2. Animate with CSS @keyframes inside a <style> block - SMIL (<animate>) is NOT time-controlled.
  3. Never write a literal animation-delay. For staggered starts set the custom property --d on the element instead: style="--d:0.4s". (The engine drives time by overriding animation-delay to calc(var(--d,0s) - t) with animations paused.)
  4. animation-fill-mode: both (or the both keyword in the shorthand) for one-shot intros; infinite for loops - both work.
  5. For rotations/scales around an element's own center add transform-box: fill-box; transform-origin: center;.
  6. Keep files self-contained (no external hrefs).

Skeleton:

<svg xmlns="http://www.w3.org/2000/svg" width="800" height="450" viewBox="0 0 800 450">
   <style>
     .a { transform-box: fill-box; transform-origin: center;
          animation: pop 0.5s cubic-bezier(.34,1.56,.64,1) both; }
@@ -90,7 +90,7 @@ 

The asset library<circle class="a" style="--d:0.2s" cx="400" cy="225" r="60" fill="#ffd166"/> </svg>

Examples in library/svg/: sparkles.svg (loop), lower-third.svg, confetti-burst.svg, underline-swoosh.svg (draw-on via stroke-dashoffset).

diff --git a/docs/docs/masks/index.html b/docs/docs/masks/index.html index 946463238..fe8911d6d 100644 --- a/docs/docs/masks/index.html +++ b/docs/docs/masks/index.html @@ -75,7 +75,7 @@
keydefaultdoes
shape-rect · ellipse · bezier (write freehand with a stroke to have one drawn for you)
x · y0.5centre, as fractions of the clip's picture (0…1, y down)
w · h0.5size, fractions of the picture's width / height (rect, ellipse)
points-bezier: 3–64 anchors around x, y, each [dx, dy] (a corner) or [dx, dy, inX, inY, outX, outY] (with curve handles relative to the anchor), all fractions of the picture's width / height
stroke-freehand only: [[u, v], …] picture fractions along an outline; it is simplified and stored as an editable bezier
scale · rotation1 · 0about the centre; degrees clockwise
modeaddhow this mask combines with the ones before it: add · subtract · intersect · difference
invertfalseuse everything outside the shape
opacity10…1, how strongly this mask counts
feather0soft edge, project pixels, centred on the outline
expand0grow (+) or shrink (−) the outline, project pixels
name · on-a label; on:false turns the mask off
keys-animate it: [{t, x?, y?, w?, h?, scale?, rotation?, feather?, expand?, opacity?, points?, ease?}], t in seconds from the clip's start; each param eases between the keys that set it (ease on the arriving key, as for clip keyframes). points keys morph the outline and need the shape's point count

Masks combine bottom-up (first in the list first). The first one starts from nothing when it adds and from the whole picture otherwise, so a lone subtract cuts a hole in a full picture. At most 8 masks per clip.

The picture a mask lives in is the clip's drawn rectangle for video, image and svg (after fit and crop), the text block for text, and the whole canvas for an adjustment layer. Masks follow the clip when it is moved, scaled, rotated or flipped, and keep the clip's keyframes.

In the editor, the Masks section of the Inspector has + Rect, + Ellipse, Pen (click points on the monitor, drag while placing one to pull curve handles, click the first point or press Enter to close) and Draw (drag a free-hand outline). Matte shows the clip's matte in the monitor (white = visible). Pick a mask's chip to edit it: mode, Invert, the sliders, ↑ ↓ to reorder, Copy, Delete, and on the monitor, drag inside to move it, the edge handles to resize it and the knob to rotate it (Shift snaps to 15°). On a bezier, drag a point to move it, drag its handles to curve it (Alt breaks the pair), Alt-drag a point to pull fresh handles, Ctrl-click the outline to add a point, and double-click a point to remove it. ◆ Key keys the whole mask at the playhead; once it has keys, every change keys. Esc steps back (point, then mask).

Agents edit masks with patch ops:

  • {op:"setMask", id, set:{shape:"ellipse", x:0.5, y:0.45, w:0.4, h:0.7, feather:40}} adds a mask (no mask, an index one past the end or a new name adds one; a new mask needs shape). {op:"setMask", id, mask:"Subject", set:{x:0.6}} edits one, by index (0 = first) or name, merging key by key (null resets a key). replace:true starts it over, keeping its name. ids:[…] edits several clips.
  • A drawn outline: set:{shape:"freehand", stroke:[[0.4, 0.3], [0.6, 0.32], …]}. It is stored as an editable bezier.
  • {op:"setMaskKeys", id, mask, keys:[{t:0, x:0.3}, {t:2, x:0.7}]} animates one (keys:null stops it); {op:"removeMask", id, mask} deletes one.
  • props.masks written through addClip / updateClip is validated the same way. Bad keys, shapes or values refuse the whole patch. Locks apply (force:true as elsewhere).
  • fablecut_scopes {time, mask:{clip}} measures them: the % of the clip's picture its masks keep (the feathered matte, measured alone) and the % of the frame the masked clip covers. The compact project view lists each clip's masks as [2 masks: ellipse feather 40, rect subtract].

Recipes: spotlight - a feathered ellipse on the clip; split screen - two clips on V1 / V2, a rect on the top one covering its half; cut a logo out of the background - a bezier around it, feather 2–4; reveal - a rect whose w (or x) keys from 0 to full; effects only on the face - an adjustment layer with a feathered ellipse, keyed to follow it; vignette through an adjustment layer - an inverted ellipse with feather:200 and the layer's brightness down.

diff --git a/docs/docs/mcp/index.html b/docs/docs/mcp/index.html index 2f7bdf096..e418d87a7 100644 --- a/docs/docs/mcp/index.html +++ b/docs/docs/mcp/index.html @@ -75,12 +75,12 @@

MCP tools

Connect an agent, and the calls it uses to read and change your timeline without burning tokens.

-

Register the MCP server once at user scope as fablecut: claude mcp add -s user fablecut -- npx -y fablecut mcp (from npm, no path needed), or from a clone claude mcp add -s user fablecut -- node "<path-to>/fablecut/mcp-server.js". Every Claude Code session then has these tools:

  • fablecut_status - auto-starts the editor server, returns URL + project summary. Call first.
  • fablecut_docs - returns this document (section: "…" returns only matching ## sections).
  • fablecut_get_project / fablecut_set_project - read / replace the timeline JSON. fablecut_get_project {compact:true} returns a one-line-per-clip summary instead.
  • fablecut_patch_project - apply targeted ops (add/update/remove clip/media, set project fields, add and open sequences) without round-tripping the document. Prefer this for edits.
  • fablecut_import_media - copy a local file (or download an https:// URL) into ./media/ and register it. The stored src is always /media/….
  • fablecut_files - the real folders in ./media/: list one, make folders, move or rename files and folders, trash and restore (nothing is deleted). See Media management below.
  • fablecut_analyze_reference - turn a reference video into an edit blueprint (shots, beats, BPM, energy, drop) + extract its music. See Remake a reference video.
  • fablecut_frame - look at a moment and get back an actual image. {path, t} returns one frame of a source clip; {path, frames} returns a contact sheet across it; with no path, {time} renders the composed timeline. See Look at the footage below.
  • fablecut_encode_profiles - list the delivery presets (YouTube, Shorts, Reels, TikTok, X, LinkedIn, Master, Broadcast, Web, Archive, saved ones) and the raw ffmpeg encoding profiles from encoding-profiles.json. {preset:"youtube"} returns one preset's spec. See Export below.
  • fablecut_normalize_audio - measure clips (BS.1770 LUFS or sample peak, via ffmpeg) and set their clip gain to a loudness target. See Audio mix below.
  • fablecut_auto_duck - find where the voice tracks speak and write duck keyframes that dip the music under it. See Audio mix below.
  • fablecut_frame - see a moment. {path, t} → one JPEG frame of a source clip; {path, frames:12} → a contact sheet across it; {time} → the composed timeline, graded, as export renders it. Returns a real image, not numbers. See Look at the footage below.
  • fablecut_denoise - reduce background noise on audio clips (renders a cleaned copy of the file and switches the clip's stems to it). See Audio mix below.
  • fablecut_silence - find the pauses in speech and, with cut:true, cut them out (extract on the targeted tracks, stems in step). See Audio mix below.
  • fablecut_beats - find a music clip's tempo, beat and drop; mark the beats, snap the cuts to them, or re-cut a track's clips on the beat. See Audio mix below.
  • fablecut_reframe - reframe for another shape (9:16, 1:1, 4:5): a copy of the sequence on that canvas whose shots follow the subject. See Sequences below.
  • fablecut_highlights - the best moments of long footage cut into a short edit, in a new sequence. See Sequences below.
  • fablecut_transcribe - turn speech into words with times (Whisper, in the browser), read them on the timeline, find a phrase and cut it out. See Transcripts and text-based editing below.
  • fablecut_captions - caption clips from the transcript, timed word by word (subtitle, karaoke, highlight, word pop); export or import SRT / WebVTT. See Captions below.
  • fablecut_export - render the timeline to a file in exports/ with the editor's own Fast export (open tab, or headless Chrome / Edge). See Export below.
  • fablecut_scopes - measure the graded picture at a moment (levels, clipping, colour cast), as the editor's scopes see it; also what a grade layer or a clip's masks select. See Color and Masks below.
  • fablecut_track - motion tracking: follow a region of a video clip, store it as a track, and make a mask or another clip follow it. See Tracking below.
  • fablecut_proxy - make, check or delete proxies: light copies of heavy footage the editor plays while editing (export always reads the originals). See Media management below.
  • fablecut_projects - list, open, create (from a canvas or a saved template), duplicate, rename, annotate, archive and delete projects. ./project.json is always the open one. See Projects below.
  • fablecut_versions - a project's saved versions: save one before big edits, compare a version with now, restore one (never destructive), mark the final cut. See Versions below.

Token-efficient editing important for agents#

Editing via full get→modify→set costs thousands of tokens per change. Cheaper:

  1. Plan from fablecut_get_project {compact:true} (≈10× smaller than the JSON) and fablecut_status - fetch the full JSON only to inspect exact keyframes.
  2. Edit with fablecut_patch_project ops - send only what changes, e.g. {ops:[{op:"updateClip", id:"c_v2", set:{props:{filterPreset:"noir"}}}]}. It re-reads the latest document internally, so it is merge-safe by design (no CONFLICT dance) and never destroys concurrent UI tweaks. To also be sure the clips you touch haven't changed since you looked, pass baseRevision (the revision you planned from - fablecut_get_project, fablecut_status or the last "Patched (revision N)" result): if the project has moved past it, the patch is refused with "CONFLICT - not saved" and the current revision. Re-check the clips, then retry with that revision.
  3. Docs: request fablecut_docs {section:"schema"} (or Recipes, "Remake", …) instead of the whole manual; skip it entirely if the schema is already in context.
  4. Media questions (duration, resolution, fps, codec, audio channels, file size, how often it is used): read them from the registered media entries or the compact view's MEDIA lines - don't shell out to ffprobe; the editor probes every file and writes them back (see Media management). For what the footage looks like, use fablecut_frame - it is far cheaper than reading a file, and far more reliable than inferring from a number.
  5. Batch related changes into ONE patch call (ops apply in order, one revision bump).
  6. Cut and trim with the edit ops (next section) rather than recomputing start / in / duration by hand - they keep linked stems in sync.

Timeline edit ops fablecut_patch_project#

The editor's own split / ripple / trim code (edit-ops.js), run on the document - so linked audio stems ride along, edits land on the targeted tracks (untargetedTracks, see Semantics), and locked clips stay put, exactly as with the keyboard shortcuts. Times are seconds.

opdoes
{op:"split", at, ids?}cut at at - the named clips (and their stems), or every targeted track
{op:"rippleDelete", ids}remove clips; later clips on those tracks close the hole
{op:"closeGap", at}close the gap under at on every targeted track
{op:"lift" | "extract", from?, to?}remove a range (default: inPoint→outPoint, which then clear); extract also closes it
{op:"insert" | "overwrite", mediaId, at, in?, duration?}three-point edit: place in→in+duration of the media at at (default: the rest of the media). Insert pushes later clips right; overwrite replaces what is under it. A video brings one linked audio stem per channel.
{op:"rippleTrim", id, side:"in"|"out", delta}move a head / tail; everything after follows
{op:"roll", id, side, delta}move the cut between two clips; nothing else moves
{op:"slip", id, delta} · {op:"slide", id, delta}new source window in place · move a clip between its neighbors
{op:"crossfade", ids? | at, duration?}constant-power audio crossfade at the cuts touching ids, or the cut nearest at (handles borrowed from both sides)

Trims are clamped to the source media, the free room and MIN_DUR; the result note shows the applied delta (… (asked +5, clamped)). Any edit op takes tracks:[…] to target lanes for that op only, and force:true to edit locked material (only when the user asked). A refused op (nothing under at, a locked clip, a media window past the file's end) aborts the whole patch unsaved. setProject also sets inPoint / outPoint (null clears).

Example - cut the 2 s from 10 s to 12 s out of the edit, then crossfade the new cut: {ops:[{op:"extract", from:10, to:12}, {op:"crossfade", at:10, duration:0.5}]}

fablecut_set_project is conflict-checked. The MCP server remembers the revision from the most recent fablecut_get_project call. If project.json has been written by anyone else since that read (e.g. the user dragged a clip in the UI), fablecut_set_project refuses with a "CONFLICT - not saved" error instead of overwriting. Protocol:

  1. fablecut_get_project → read the document and note its revision.
  2. Apply your edits in memory, bump revision.
  3. fablecut_set_project → if it succeeds you're done.
  4. On conflict: call fablecut_get_project again to get the latest document, re-apply your intended changes on top of it, bump revision, and call fablecut_set_project again.

Pass force: true to fablecut_set_project only when the user explicitly asks to overwrite conflicting changes. fablecut_import_media only appends a new media entry and always merges safely - no conflict check needed.

For Claude Desktop, add to its MCP config: {"mcpServers":{"fablecut":{"command":"npx","args":["-y","fablecut","mcp"]}}} (or "command":"node","args":["<path-to>/fablecut/mcp-server.js"] from a clone) Direct file editing of project.json (below) works too and is equivalent.

Installing as a Claude Code plugin (/plugin marketplace add ronak-create/FableCut, then /plugin install fablecut@fablecut) does the registration for you.

Where the files are#

project.json, projects/, media/, exports/, analysis/ and library/ normally sit in the repo next to server.js; installed from npm (npx fablecut) they sit in ~/FableCut. Set FABLECUT_DATA_DIR to move all six somewhere else; the code and the static app files stay in the install directory either way. The plugin sets this so a plugin update can replace the install directory without touching anyone's timeline or footage. Don't assume project.json is beside mcp-server.js - call fablecut_status, which reports the real paths.

Tests (and nothing else) may set FABLECUT_NO_FS_WATCH=1 to skip fs.watch. On Windows, libuv can abort the process when a file is created under a temp data dir. Production leaves watching on so the UI live-reloads. Tests may also set FABLECUT_NO_AUTOSTART=1 so ensureUIServer() reports a missing editor server instead of spawning one - the auto-start is detached, so a test that triggers it would leave a server.js running after it finishes.

+

Register the MCP server once at user scope as fablecut: claude mcp add -s user fablecut -- npx -y fablecut mcp (from npm, no path needed), or from a clone claude mcp add -s user fablecut -- node "<path-to>/fablecut/mcp-server.js". Every Claude Code session then has these tools:

  • fablecut_status - auto-starts the editor server, returns URL + project summary. Call first.
  • fablecut_docs - returns this document (section: "…" returns only matching ## sections).
  • fablecut_get_project / fablecut_set_project - read / replace the timeline JSON. fablecut_get_project {compact:true} returns a one-line-per-clip summary instead.
  • fablecut_patch_project - apply targeted ops (add/update/remove clip/media, set project fields, add and open sequences) without round-tripping the document. Prefer this for edits.
  • fablecut_import_media - copy a local file (or download an https:// URL) into ./media/ and register it. The stored src is always /media/….
  • fablecut_files - the real folders in ./media/: list one, make folders, move or rename files and folders, trash and restore (nothing is deleted). See Media management below.
  • fablecut_analyze_reference - turn a reference video into an edit blueprint (shots, beats, BPM, energy, drop) + extract its music. See Remake a reference video.
  • fablecut_frame - look at a moment and get back an actual image. {path, t} returns one frame of a source clip; {path, frames} returns a contact sheet across it; with no path, {time} renders the composed timeline. See Look at the footage below.
  • fablecut_encode_profiles - list the delivery presets (YouTube, Shorts, Reels, TikTok, X, LinkedIn, Master, Broadcast, Web, Archive, saved ones) and the raw ffmpeg encoding profiles from encoding-profiles.json. {preset:"youtube"} returns one preset's spec. See Export below.
  • fablecut_normalize_audio - measure clips (BS.1770 LUFS or sample peak, via ffmpeg) and set their clip gain to a loudness target. See Audio mix below.
  • fablecut_auto_duck - find where the voice tracks speak and write duck keyframes that dip the music under it. See Audio mix below.
  • fablecut_frame - see a moment. {path, t} → one JPEG frame of a source clip; {path, frames:12} → a contact sheet across it; {time} → the composed timeline, graded, as export renders it. Returns a real image, not numbers. See Look at the footage below.
  • fablecut_denoise - reduce background noise on audio clips (renders a cleaned copy of the file and switches the clip's stems to it). See Audio mix below.
  • fablecut_silence - find the pauses in speech and, with cut:true, cut them out (extract on the targeted tracks, stems in step). See Audio mix below.
  • fablecut_beats - find a music clip's tempo, beat and drop; mark the beats, snap the cuts to them, or re-cut a track's clips on the beat. See Audio mix below.
  • fablecut_reframe - reframe for another shape (9:16, 1:1, 4:5): a copy of the sequence on that canvas whose shots follow the subject. See Sequences below.
  • fablecut_highlights - the best moments of long footage cut into a short edit, in a new sequence. See Sequences below.
  • fablecut_transcribe - turn speech into words with times (Whisper, in the browser), read them on the timeline, find a phrase and cut it out. See Transcripts and text-based editing below.
  • fablecut_captions - caption clips from the transcript, timed word by word (subtitle, karaoke, highlight, word pop); export or import SRT / WebVTT. See Captions below.
  • fablecut_export - render the timeline to a file in exports/ with the editor's own Fast export (open tab, or headless Chrome / Edge). See Export below.
  • fablecut_scopes - measure the graded picture at a moment (levels, clipping, colour cast), as the editor's scopes see it; also what a grade layer or a clip's masks select. See Color and Masks below.
  • fablecut_track - motion tracking: follow a region of a video clip, store it as a track, and make a mask or another clip follow it. See Tracking below.
  • fablecut_proxy - make, check or delete proxies: light copies of heavy footage the editor plays while editing (export always reads the originals). See Media management below.
  • fablecut_projects - list, open, create (from a canvas or a saved template), duplicate, rename, annotate, archive and delete projects. ./project.json is always the open one. See Projects below.
  • fablecut_versions - a project's saved versions: save one before big edits, compare a version with now, restore one (never destructive), mark the final cut. See Versions below.
  • fablecut_workflows - saved workflows: recipes of steps (and the tool calls that did them) the user wants repeated on other projects. Save one, list them, show one and follow it. See Workflows below.

Token-efficient editing important for agents#

Editing via full get→modify→set costs thousands of tokens per change. Cheaper:

  1. Plan from fablecut_get_project {compact:true} (≈10× smaller than the JSON) and fablecut_status - fetch the full JSON only to inspect exact keyframes.
  2. Edit with fablecut_patch_project ops - send only what changes, e.g. {ops:[{op:"updateClip", id:"c_v2", set:{props:{filterPreset:"noir"}}}]}. It re-reads the latest document internally, so it is merge-safe by design (no CONFLICT dance) and never destroys concurrent UI tweaks. To also be sure the clips you touch haven't changed since you looked, pass baseRevision (the revision you planned from - fablecut_get_project, fablecut_status or the last "Patched (revision N)" result): if the project has moved past it, the patch is refused with "CONFLICT - not saved" and the current revision. Re-check the clips, then retry with that revision.
  3. Docs: request fablecut_docs {section:"schema"} (or Recipes, "Remake", …) instead of the whole manual; skip it entirely if the schema is already in context.
  4. Media questions (duration, resolution, fps, codec, audio channels, file size, how often it is used): read them from the registered media entries or the compact view's MEDIA lines - don't shell out to ffprobe; the editor probes every file and writes them back (see Media management). For what the footage looks like, use fablecut_frame - it is far cheaper than reading a file, and far more reliable than inferring from a number.
  5. Batch related changes into ONE patch call (ops apply in order, one revision bump).
  6. Cut and trim with the edit ops (next section) rather than recomputing start / in / duration by hand - they keep linked stems in sync.

Timeline edit ops fablecut_patch_project#

The editor's own split / ripple / trim code (edit-ops.js), run on the document - so linked audio stems ride along, edits land on the targeted tracks (untargetedTracks, see Semantics), and locked clips stay put, exactly as with the keyboard shortcuts. Times are seconds.

opdoes
{op:"split", at, ids?}cut at at - the named clips (and their stems), or every targeted track
{op:"rippleDelete", ids}remove clips; later clips on those tracks close the hole
{op:"closeGap", at}close the gap under at on every targeted track
{op:"lift" | "extract", from?, to?}remove a range (default: inPoint→outPoint, which then clear); extract also closes it
{op:"insert" | "overwrite", mediaId, at, in?, duration?}three-point edit: place in→in+duration of the media at at (default: the rest of the media). Insert pushes later clips right; overwrite replaces what is under it. A video brings one linked audio stem per channel.
{op:"rippleTrim", id, side:"in"|"out", delta}move a head / tail; everything after follows
{op:"roll", id, side, delta}move the cut between two clips; nothing else moves
{op:"slip", id, delta} · {op:"slide", id, delta}new source window in place · move a clip between its neighbors
{op:"crossfade", ids? | at, duration?}constant-power audio crossfade at the cuts touching ids, or the cut nearest at (handles borrowed from both sides)

Trims are clamped to the source media, the free room and MIN_DUR; the result note shows the applied delta (… (asked +5, clamped)). Any edit op takes tracks:[…] to target lanes for that op only, and force:true to edit locked material (only when the user asked). A refused op (nothing under at, a locked clip, a media window past the file's end) aborts the whole patch unsaved. setProject also sets inPoint / outPoint (null clears).

Example - cut the 2 s from 10 s to 12 s out of the edit, then crossfade the new cut: {ops:[{op:"extract", from:10, to:12}, {op:"crossfade", at:10, duration:0.5}]}

fablecut_set_project is conflict-checked. The MCP server remembers the revision from the most recent fablecut_get_project call. If project.json has been written by anyone else since that read (e.g. the user dragged a clip in the UI), fablecut_set_project refuses with a "CONFLICT - not saved" error instead of overwriting. Protocol:

  1. fablecut_get_project → read the document and note its revision.
  2. Apply your edits in memory, bump revision.
  3. fablecut_set_project → if it succeeds you're done.
  4. On conflict: call fablecut_get_project again to get the latest document, re-apply your intended changes on top of it, bump revision, and call fablecut_set_project again.

Pass force: true to fablecut_set_project only when the user explicitly asks to overwrite conflicting changes. fablecut_import_media only appends a new media entry and always merges safely - no conflict check needed.

For Claude Desktop, add to its MCP config: {"mcpServers":{"fablecut":{"command":"npx","args":["-y","fablecut","mcp"]}}} (or "command":"node","args":["<path-to>/fablecut/mcp-server.js"] from a clone) Direct file editing of project.json (below) works too and is equivalent.

Installing as a Claude Code plugin (/plugin marketplace add ronak-create/FableCut, then /plugin install fablecut@fablecut) does the registration for you.

Where the files are#

project.json, projects/, media/, exports/, analysis/ and library/ normally sit in the repo next to server.js; installed from npm (npx fablecut) they sit in ~/FableCut. Set FABLECUT_DATA_DIR to move all six somewhere else; the code and the static app files stay in the install directory either way. The plugin sets this so a plugin update can replace the install directory without touching anyone's timeline or footage. Don't assume project.json is beside mcp-server.js - call fablecut_status, which reports the real paths.

Tests (and nothing else) may set FABLECUT_NO_FS_WATCH=1 to skip fs.watch. On Windows, libuv can abort the process when a file is created under a temp data dir. Production leaves watching on so the UI live-reloads. Tests may also set FABLECUT_NO_AUTOSTART=1 so ensureUIServer() reports a missing editor server instead of spawning one - the auto-start is detached, so a test that triggers it would leave a server.js running after it finishes.

Edit this in CLAUDE.md The whole manual as Markdown diff --git a/docs/docs/media/index.html b/docs/docs/media/index.html index e05e1434e..10d8d5f18 100644 --- a/docs/docs/media/index.html +++ b/docs/docs/media/index.html @@ -75,14 +75,14 @@

Media management

File details, search, filters, sorting, tags and collections, where each file is used, relinking missing files, and proxies for heavy footage.

The Project bin knows each file's details and helps find, group and track footage. The bin's organizing (details, favorites, tags, collections, search) changes nothing that plays or exports; moving and trashing the files themselves ("Files on disk" below) does what it says.

Metadata. The editor reads every file in media/ and library/ with ffprobe (via GET /api/media-info) and writes what it finds onto the media entry. These fields are read-only - they describe the file:

keydoes
fpsvideo frame rate (29.97, 25, 59.94 …); absent for stills and audio
codecvideo codec (h264, hevc, prores, vp9 …), or the image format (png, mjpeg)
audioCodec · audioChannels · sampleRatefirst audio stream: codec, channel count (0 = the file has no audio), Hz
size · bitratefile size in bytes · overall bitrate, bits per second
width · height · durationas before; filled in when missing (phone footage shot rotated reports its upright size)

Without ffprobe on PATH only size is filled in; the browser still probes duration, width and height.

Organizing. favorite: true stars a file; tags is a list of free-form labels (at most 24, each up to 32 characters, matched without regard to case). collections at the top of the document group media across folders - a file can be in any number of them, while it sits in one folder (folderId).

Usage. A file's placements are the clips that show it, on the main timeline and inside every composition. A video and the audio stems linked to it count as one placement, so a shot used twice reads "used 2×".

In the editor, the Project tab has:

  • Search - every word must match the name, kind, extension, codec, resolution (3840x2160, 2160p) or a tag; #word matches tags only. Esc clears it.
  • Show - All media · ★ Favorites · Used in the edit · Unused · a kind · a collection · a tag. While searching or filtering, the bin lists the hits flat (each with its folder), with a count and Clear; a collection's view also has Rename and Delete (its media stay).
  • Sort - name (natural: shot 2 before shot 10), kind, duration, resolution, frame rate, codec, audio channels, file size or times used, with ↑ / ↓. Files missing a value sort last either way. Folders keep their tree; the sort applies inside each.
  • ☰ List view - one row per file with columns: name, duration, resolution, FPS, codec, audio, size and uses; click a column heading to sort by it. On a narrow bin the columns drop out right to left; widen the panel to see them all.
  • On each file: ☆ stars it, the uses badge opens its placements. Right-click a file → Open in Source, Find timeline instances (every placement, main timeline and comps, with track and time - click one to jump there, opening its comp if needed), Media info…, favorites, Tags…, Add to / Remove from a collection, New collection…, Remove from project.
  • Right-click a clip on the timeline → Reveal in project scrolls the bin to its file (or its comp), opening folders and clearing a search that hides it.

Offline media. A file is offline when its src names nothing under media/ or library/ - it was moved, renamed or deleted. The editor checks on load and whenever those folders change. An offline file's clips stay where they are: the timeline hatches them red (⚠ Offline), the monitor and the export draw a Media offline slate in the picture's place, and its audio is silent. The bin marks the file OFFLINE, says how many are missing, and the Show filter gains ⚠ Offline. The Export dialog warns before rendering one. Files under media/ may sit in subfolders (/media/archive/a.mp4).

  • Relink points a media entry at the same footage where it is now; clips keep their In points, edits and everything else. Right-click the file → Relink… (or Relink… on the offline banner for all of them). The dialog looks through media/ and library/ for each file - same name, the same name with another extension, a similar name, the same size - and picks a same-name match for you. Browse… picks one file and Choose folder… matches a whole folder by name; either copies the chosen files into media/. A relinked file whose length differs from the original gets a warning (is it really the same footage?).
  • Replace file… (right-click a file) puts a different file behind the media entry - a new render, a better take. Every clip using it switches; each keeps its In point and timing, trimmed to fit a shorter file. The name and details follow the new file; favorites, tags and collections stay. To swap the file of one clip only, use the Inspector's Source menu instead.
  • Relink and replace are one undo step each.

Proxies. Heavy footage - 4K, HEVC, ProRes, long phone clips - can stutter while you scrub and play. A proxy is a light copy the editor plays instead while you edit: H.264 at 540p (or 720p / 1080p, never larger than the source), a keyframe every 12 frames so seeking is quick, the source's own timestamps (frame for frame - no frames added or dropped) and its first audio stream. The edit always refers to the original: the timeline, project.json and every clip stay the same whether proxies are on or off.

Export always reads the originals, and so do fablecut_frame (timeline mode), fablecut_scopes, tracking and every other measurement - the players switch to the original files for the render and back afterwards. A proxy only changes how smoothly the preview runs, never the result.

  • Right-click a video in the bin → Create proxy (540p) / (720p); right-click the Project tab → Create proxies for N videos. ffmpeg makes them on the server one at a time in the background; the bin shows each file's progress (P 42%), then a green P once it is ready. Delete proxy removes one. The bin's list view has a Proxy column, Show has Has a proxy / Video without a proxy, and Media info says which file is playing.
  • The monitor's Proxy button turns proxy playback on and off (on by default; remembered in this browser). The Source monitor follows it too.
  • Proxies live in analysis/proxies/, a disposable cache: each is named after its source file and that file's size and modification time, so a re-rendered or replaced original simply has no proxy until you make a new one. Deleting the folder loses nothing but time. Proxies need ffmpeg.

Agents:

  • {op:"updateMedia", id | ids, set:{name?, favorite?, tags?, folderId?}, addTags?, removeTags?} - organize files (favorite:false unstars; tags:[] clears). Metadata keys are refused: they come from the file.
  • {op:"setCollection", id?, name?, media?, add?, remove?} creates a collection (a new id, or a name no collection has) or changes one: media replaces its list, add / remove edit it. {op:"removeCollection", id} deletes it; its media stay. removeMedia takes a file out of every collection.
  • The compact view lists each file with its metadata, ★, tags, folder and uses:N, and the collections on one line: m_abc video "intro.mp4" 12.4s 1920×1080 29.97 fps h264 stereo 48 kHz 45 MB ★ #interview uses:2.
  • fablecut_import_media probes the file as it imports it, so the entry it returns already has these fields.
  • fablecut_status lists offline media, and the compact view marks each OFFLINE (file missing — relinkMedia) and each video with a proxy proxy:540p.
  • fablecut_proxy {} reports every video's proxy; {create:true, mediaIds?, height?} makes them (waits until done unless wait:false); {delete:true, mediaIds?} removes them. Proxies never change what you measure or export, so an agent only needs them when the user asks for smoother playback.
  • {op:"relinkMedia", id, src:"/media/…", name?} - the same footage found elsewhere: put the file in media/ (copy it, or fablecut_import_media and removeMedia the extra entry it registers), then relink. The note warns when the new file's length differs.
  • {op:"replaceMedia", id, src, name?} - a different file behind the entry; clips keep their timing, trimmed to fit (the note says how many). src must be an existing file under /media/ or /library/ of the same kind (an audio entry may use a video container).

Files on disk. The bin's folders (folders, folderId) only organize entries in project.json; the files themselves sit in media/ and may live in subfolders. fablecut_files works on those (or POST /api/files):

  • {action:"list", dir?} (an empty call to the MCP tool lists too) lists one folder: its subfolders and files with sizes and srcs. Dot-folders (media/.trash/) are left out.
  • {action:"mkdir", dir:"b-roll/day 1"} makes a folder (and its parents).
  • {action:"move", from, to} moves a file or folder into an existing folder, or to a new path (a rename); to is required ("/media/" is the top of media/). Every project's media entries that point at a moved file are repointed (the open project gets a new revision, so the editor reloads), a media name that was the old file name follows it, and the file's transcript goes with it (a warning says when one couldn't be). The move is refused while a project can't be read (force:true moves anyway, and the file goes offline there), and a project edited meanwhile stops it (CONFLICT, try again). If a project can't be written, the move is undone; if undoing fails too, the error says where the files are and which project couldn't be put back: check them there and relink. A name that is taken (also one taken while the move runs), and links inside media/, are refused, never replaced.
  • {action:"trash", paths:[…]} moves files or folders into media/.trash/<id>/files/ with a note of where they were; nothing is deleted. A file a project still uses is refused (the reply names the project and how many clips place it): removeMedia it first, or force:true to trash it anyway, and it shows as offline there until it is restored. A project whose project.json can't be read counts as possibly using it, so the same applies. One call can't list a folder and something inside it. When one of several fails, the reply lists the ones already trashed, with their ids, and the path it stopped at. {action:"trash-list"} lists the trash, {action:"restore", id} puts one back where it was (refused while something else has that name; a warning says when its trash entry couldn't be cleaned up).
  • Move, rename and trash only when the user asked: they change the user's folder. Versions keep the paths they were saved with, so restoring an old version after a move may need Relink.
diff --git a/docs/docs/motion-paths/index.html b/docs/docs/motion-paths/index.html index 868a62ea2..23352753a 100644 --- a/docs/docs/motion-paths/index.html +++ b/docs/docs/motion-paths/index.html @@ -75,7 +75,7 @@

In the editor: when the selected clip has two or more position keys, its path shows on the monitor: the curve, a dot per frame (their spacing is the speed), a square per key and the keys' handles. Drag a key to move it, drag a handle to bend the path (Alt breaks the pair), Alt-drag a key to pull new handles, and double-click a key to make it a corner again. Moving the clip on the monitor or typing X / Y keys both channels together. The Inspector's Motion section has Smooth (handles through every position key), Straight, Auto-orient, Motion blur and Blur samples. A title's Text path section sets it on a Line, Arc, Circle, Wave or a Pen path (click points, drag to curve, Enter to finish, click the first point to close it). Edit path shows the path's points on the monitor, and Offset and Align place the text along it.

Agents:

  • Write pin / pout on x / y keys directly, or {op:"setMotionPath", id | ids, path:"smooth" | "straight", autoOrient?: true}. "smooth" needs the position keys first (x and y keyed together at two or more times).
  • Motion blur: updateClip with props:{motionBlur:180, motionBlurSamples:12}.
  • {op:"setTextPath", id | ids, path:"line" | "arc" | "circle" | "wave" | {type:"path", points:[…], closed:false, …} | null, offset?, align?} sets, replaces or removes (null) a title's path; animate pathOffset with keyframes.
  • These are validated on addClip / updateClip too. The compact view shows path:curved after a clip's keyframes, and a title's "textPath":"ellipse 300×300".

Recipes: fly-in on a curve - two position keys, setMotionPath smooth, autoOrient:true, motionBlur:180; orbiting label - circle textPath, pathOffset keyed 0 → 100 linear; stamp along a road - an open path textPath that follows the shape in the footage, pathAlign:"center", textAnim:"letter-pop"; whip without the transition - a fast x move over 4–6 frames with motionBlur:360.

diff --git a/docs/docs/motion/index.html b/docs/docs/motion/index.html index af11ad96c..d9dcf23a4 100644 --- a/docs/docs/motion/index.html +++ b/docs/docs/motion/index.html @@ -75,7 +75,7 @@
keydefaultdoes
typerectrect · ellipse · polygon · star · line · path · group
x · y0position in layer px, from the layer's origin (the clip's x/y, y down)
rotation · scale · opacity0 · 1 · 1about the item's own x, y
w · h200size, px (rect, ellipse, polygon, star)
radius0rect corner radius, px
sides · inner6 / 5 · 0.5polygon / star point count (3–64); a star's inner radius as a fraction of the outer
points-line: exactly 2 · path: 2–128 points [x, y] or [x, y, inX, inY, outX, outY] (curve handles relative to the point), px around the item's x, y
closedtruepath only; false leaves it open (lines are always open)
fill · stroke#ffffff · none"#rrggbb", "#rrggbbaa" or "none"; lines and open paths default to a white stroke and no fill
strokeWidth6 (8 open)px; set with stroke
lineCap · lineJoinround · roundbutt · round · square / miter · round · bevel
dash-[on, off, …] px, e.g. [24, 12]
trimStart · trimEnd0 · 100the part of the outline drawn, % - key trimEnd 0→100 to draw a path on
trimOffset0% of the outline the drawn part is shifted round by (key it to make a dash run round a loop)
items-group only: its items. A group moves, turns, scales, fades and trims them together (groups nest 4 deep)
name · on-a label (agents address items by it); on:false hides it
keys-[{t, ease?, …}], t in seconds from the clip's start. Keyable: x y rotation scale opacity w h radius inner strokeWidth trimStart trimEnd trimOffset fill stroke points. Each value eases between the keys that set it (ease on the arriving key); colours blend; points keys morph the path and need its point count

At most 64 items per layer (group children included). The layer itself is a normal visual clip: its x, y, scale, rotation, opacity, blend, masks, transitions and keyframes all work, as do blur and shake. Its own trimStart / trimEnd / trimOffset (clip props, keyframable) trim every path in it at once. A trimmed shape fills the part that is drawn.

Null objects. kind:"null" (no mediaId) is a clip that never renders. Give it x, y, rotation, scale (and keyframes), and parent clips to it to move them as one. The monitor shows it as a red square while it is on screen.

Parenting. "parent": "<clip id>" (top-level, next to track) makes a clip move, turn and scale with that clip. Its own x/y are then measured in the parent's space: from the parent's centre, turned and scaled with it. Parents chain (a parent can have a parent), and loops are refused. Only the transform follows: the parent's opacity, transitions, shake and effects do not, and the parent's keyframes are read even outside its time range (held at its first or last value). Splitting a parent leaves the children on the left half.

Anchor point. anchorX / anchorY (px from the picture's centre, for any visual clip) pick the point that x/y place and that rotation and scale turn around: anchorY: 200 on a 400 px tall shape spins it about its bottom edge. Moving the anchor without moving the picture means changing x/y with it (the editor's anchor tool does that).

In the editor: the bin's Shapes tab adds a rectangle, ellipse, polygon, star, line or pen-path layer, or a null object, at the playhead. The Shape layer section lists the items; pick one to edit it - the sliders, Fill / Stroke (colour or None), ends and joins, trim, Group / Ungroup / Out, ↑ ↓, Copy, Delete - and on the monitor drag it to move, the knob to turn it (Shift: 15°) and the corners to resize it. On a line or path, drag points and their handles (Alt breaks the pair, Alt-drag pulls new handles); on a path, Ctrl-click the outline to add a point and double-click one to remove it. Pen draws a new path: click points (drag to curve), click the first point to close it or press Enter to keep it open. Each value has its own ◆: key it at the playhead, and from then on changing it keys it. Every visual clip's Transform section has Anchor (✥ Move: drag on the monitor to move the anchor point while the picture stays put, Shift snaps to the centre; Centre puts it back) and Parent. Right-click clips → Parent to a new null groups them under a fresh null at their centre.

Agents:

  • Add a layer with addClip {kind:"shape", track, start, duration, props:{shapes:[…]}}, a null with addClip {kind:"null", track, start, duration, props:{x, y}}.
  • {op:"setShape", id, set:{type:"rect", w:400, h:80, fill:"#ffd166"}} adds an item (no shape, an index one past the end or a new name adds one; a new item needs type). {op:"setShape", id, shape:"Bar", set:{fill:"#22d3ee"}} edits one - by index (0 = first), name, or a path into groups like "2.0" (item 0 of group 2; "2.3" with 3 items adds one there) - merging key by key (null resets a key; a new type keeps the position and paint). replace:true starts it over. keys in set replaces its keys. {op:"removeShape", id, shape} deletes one. ids:[…] edits several clips.
  • {op:"setParent", id | ids, parent:"c_null"} parents clips and keeps them where they are on screen (at time at, default each clip's start; keyed channels are left as they are). keep:false keeps the numbers instead. parent:null unparents. Removing a parent clip unparents its children where they stand.
  • props.shapes and parent written through addClip / updateClip are validated the same way; bad input refuses the whole patch. The compact view lists a layer as [3 shapes: rect #ffd166 2 keys, line stroke #ffffff/6, group(star(5) #ff7ac8)] and a child as parent:c_null.

Recipes: draw-on logo - the logo as path items with a stroke and no fill, trimEnd keyed 0→100 (stagger the items' keys), then fill keyed from "#ffffff00" to "#ffffff"; lower third - a rect bar whose w keys from 0, a line drawn on under it, a title on the track above parented to the shape layer so they slide out together; loading ring - an ellipse with a stroke, trimEnd: 25, trimOffset keyed 0→100 with ease:"linear"; orbit - a null at the centre with rotation keyed 0→360, a shape parented to it with x: 300; swing from the top - anchorY at the top edge (minus half the height) and rotation keyed −10↔10; burst - a group of lines at different rotations with scale keyed 0→1 and opacity 1→0.

diff --git a/docs/docs/presets-templates/index.html b/docs/docs/presets-templates/index.html index 9696cbc1c..a3ce40775 100644 --- a/docs/docs/presets-templates/index.html +++ b/docs/docs/presets-templates/index.html @@ -75,7 +75,7 @@

Animation presets and templates

@@ -88,7 +88,7 @@

Animation presets and templates

{ "key": "name", "label": "Name", "type": "text", "targets": [ "name:props.text" ], "value": "Ava Moreno" }, { "key": "accent", "label": "Accent", "type": "color", "targets": [ "bar:props.shapes.1.fill" ], "value": "#ffd166" } ] } }
templatenamesizelengthfields
lower-third-barLower third - Bar1920×10805 sname title accent panel
lower-third-underlineLower third - Underline1920×10805 sname title accent
lower-third-boxesLower third - Boxes1920×10805 sname title accent box
logo-ringLogo - Ring reveal1920×10804 slogo brand accent
logo-slamLogo - Slam1920×10803.5 slogo accent
logo-linesLogo - Lines1920×10804 slogo tagline lines
social-storyStory - Headline (9:16)1080×19206 sheadline subline button accent background
social-quotePost - Quote (1:1)1080×10806 squote author accent background
social-end-cardEnd card - Follow (16:9)1920×10806 sheading button accent background

Field types: text (a string), color (#rgb, #rrggbb or #rrggbbaa) and media (a media id of a picture: image, svg or video; the clip's kind follows it). A target is "<clip id>:<path>" inside the comp (props.text, props.shapes.1.fill, mediaId, …) or "comp:background"; one field can set several. The logo templates start with a placeholder, /library/elements/logo-placeholder.svg, until the logo field gets a picture. hold is when the exit starts: changing a template's length keeps everything after it at the same distance from the end, so a longer lower third just holds longer (it can't get shorter than its entrance needs).

A saved template (library/templates/<id>.json) is a template object: {id, name, group, width, height, duration, hold, background?, tracks?, clips, media?, fields}; media lists the {id, name, kind, src} entries its clips use (/library/… or /media/…), matched by src when it is placed. A saved preset or template whose name a built-in already has is saved as "<name> (saved)".

In the editor: the bin's Templates tab lists them by group (Lower thirds, Logo animations, Social, then Saved); drag one onto the timeline or click +. The Inspector's Template section on its clip edits the fields, its Length, and offers Use W×H canvas when the template was made for another shape. Right-click a comp in the Project tab → Save as template keeps it (every title's text and every picture become fields). The Motion section's Presets menus (In, Out, At playhead, Loop) put a preset on the selected clips, and Save as preset keeps this clip's keyframes (In: from its start to its last key; Out: from its first key to its end; Loop: the whole clip).

Agents:

  • {op:"applyPreset", id | ids, preset, length?, at?} - preset is a name, a saved one's id, or an inline preset object; at is timeline seconds (for an At preset; default the clip's start). Visual clips only.
  • {op:"addTemplate", template, start?, track?, duration?, fields?:{key: value}, id?, compId?, name?} places one (default track V2, at 0, its own length).
  • {op:"setTemplate", id, fields?:{key: value}, duration?} - id is its comp clip or its comp; a new duration retimes it, and clips that showed it to its end keep doing so.
  • {op:"savePreset", id, name, anchor?, from?, to?} (from/to in clip seconds) or {op:"savePreset", preset:{…}}; {op:"saveTemplate", comp, name?, fields?, hold?} or {op:"saveTemplate", template:{…}}. Files are written once the patch is saved, and later ops in the same patch can use them.
  • applyPreset, addTemplate and setTemplate also run inside inComp.
  • The compact view prints a placed template's fields under its comp: template lower-third-bar — fields (setTemplate): name="Ava Moreno" ….

Recipes: name every speaker - addTemplate lower-third-bar once per speaker with fields:{name, title}; branded intro - addTemplate logo-ring with fields:{logo:"<your logo's media id>", brand, accent} at 0; vertical teaser - set the canvas to 1080×1920, addTemplate social-story; house style - build a comp the way you like it, saveTemplate, then place it in every project; titles that arrive and leave the same way - applyPreset an In and an Out on every title in one patch.

diff --git a/docs/docs/project-json/index.html b/docs/docs/project-json/index.html index 2ebeb7bb3..cf27df4a8 100644 --- a/docs/docs/project-json/index.html +++ b/docs/docs/project-json/index.html @@ -75,7 +75,7 @@ diff --git a/docs/docs/projects/index.html b/docs/docs/projects/index.html index 30539d0a1..e226dee72 100644 --- a/docs/docs/projects/index.html +++ b/docs/docs/projects/index.html @@ -75,14 +75,14 @@

Projects

Keep many projects in one FableCut: a dashboard to open, create from a canvas or template, duplicate, rename, take notes on, tag, archive and delete them, and fablecut_projects for agents.

One FableCut keeps any number of projects. ./project.json is always the open project: the editor, every MCP tool, the REST API and scripts read and edit that file as before. The others wait in projects/, and opening one swaps it in:

pathholds
projects/index.json{active} - the open project's id
projects/<id>/meta.json{id, created, opened, archived, notes, tags, template?}
projects/<id>/project.jsonthe document (while that project is open, ./project.json is the live copy)
projects/<id>/thumb.jpgthe editor's last picture of it
library/project-templates/<id>.jsona saved project template {name, created, project}

media/, exports/, analysis/ and library/ are shared by every project, so a duplicate or a project made from a template copies no footage. The first time projects are used, the existing ./project.json becomes the first project, unchanged. Ids look like p_3f9a01c2de.

Opening a project saves the open one into its folder, then copies the chosen one to ./project.json with a revision above both. A save based on the project that was open before (an editor tab, an agent's fablecut_set_project, a baseRevision patch) is therefore refused as a CONFLICT instead of landing in the wrong project. Editor tabs reload, clear their undo history and close an open composition. GET /api/project names the open project in the X-FableCut-Project header, and the editor sends it back on every save, so an edit made for one project can never be written into another.

In the editor: Projects in the top bar (Ctrl/Cmd+O, or a click on the project name) opens the dashboard: cards with a picture, size, frame rate and length; search by name, notes or #tag; sort by last opened, last modified, created or name. Pick one to rename it, write notes, tag it, Open (or double-click / Enter on its card), Duplicate, Save as template or Archive it. Archived lists archived projects, where Unarchive brings one back and Delete… (click twice) removes it; only archived projects can be deleted, and the open one can be neither archived nor deleted. + New project starts one from a canvas (Landscape 16:9 1080p, Vertical 9:16, Square 1:1, Portrait 4:5, 4K UHD, Landscape 720p) or a saved template, with its own frame rate. Import… adds a project file from elsewhere (an old backup, another machine); its media must be in media/, and Relink finds files that moved.

Agents use fablecut_projects (or GET /api/projects, POST /api/projects):

  • {} or {action:"list", archived?:"only"|"all"} lists them: id, name, size, length, clips, tags, notes, and which is (OPEN).
  • {action:"open", id} switches the editor to that project; re-read it with fablecut_get_project {compact:true} before editing.
  • {action:"new", name, template?, fps?, width?, height?, notes?, tags?, open?} - template is landscape-1080 (default), vertical-1080, square-1080, portrait-1350, uhd-4k, landscape-720 or a saved template's id; it opens unless open:false.
  • {action:"duplicate", id, name?, open?} · {action:"update", id, name?, notes?, tags?} · {action:"archive" | "unarchive" | "delete", id}.
  • fablecut_status also counts the open project's versions; see Versions for them.
  • {action:"templates"} · {action:"save_template", id, name} (the project's canvas, tracks, clips and media references) · {action:"delete_template", template}.
  • Opening, archiving or deleting changes what the user sees: do it only when they asked. fablecut_status says how many projects there are.

Recipes: one edit, three versions - duplicate the project per client cut, put the brief in notes; house canvas - build an empty project with your tracks, intro and outro, save_template, then new from it for every episode; park finished work - archive delivered projects to keep the list short without deleting anything.

diff --git a/docs/docs/props/index.html b/docs/docs/props/index.html index 604254b4f..5c6e1b31f 100644 --- a/docs/docs/props/index.html +++ b/docs/docs/props/index.html @@ -75,14 +75,14 @@

Clip props

Every property a clip can carry and its default. A key a clip leaves out falls back to these.

Transform & compositing all visual kinds#

propdefaultnotes
x, y0px offset from canvas center
scale1
rotation0degrees
opacity10–1
anchorX, anchorY0anchor point, px from the picture's centre: the point x/y place and rotation/scale turn around
autoOrientfalseturn the clip with its direction of travel along its motion path (rotation adds on top)
motionBlur · motionBlurSamples0 · 8motion blur: shutter angle in degrees (0 = off, 180 = film look, up to 720) · sub-frame samples 2–32
blend"normal"how the clip lays over what is under it (see Track mattes and blending)
matte · matteTrack-a track matte (see Track mattes and blending)

Layout video/image/svg#

propdefaultnotes
fit"contain"contain · cover (fill canvas, crop overflow) · stretch · none (native px)
cropL cropR cropT cropB0% of the source trimmed off each edge
cornerRadius0px, rounded corners - the PiP look
reframe-set by Reframe ("follow" or "centre"): the clip's fit and position are Reframe's own, so running it again replaces them (see Sequences)
flipH, flipVfalsemirror

Filter / color video/image/svg#

propdefaultnotes
filterPreset"none"one of: cinematic · teal-orange · noir · vintage · faded · warm · cold · pop · dreamy · retro · bw-soft · cyberpunk · sunset · midnight. Combines non-destructively with the sliders below.
brightness contrast saturation100% (100 = neutral)
hue0degrees
temperature0−100 (cool blue) … +100 (warm orange)
tint0−100 (magenta) … +100 (green)
blur0px
grayscale sepia invert vignette0%

These are quick looks. For real grading use props.grade (see Color below).

Motion FX video/image/svg/adjust - all animatable#

propdefaultnotes
shake0camera-shake amplitude in px (deterministic - identical in export)
shakeSpeed8shake frequency
rgbSplit0chromatic aberration / RGB channel split, px
grain0animated film grain, %

Keying / cut-out video/image#

propdefaultnotes
chromaKey""hex key color, e.g. "#00ff00" for green screen ("" = off)
chromaTolerance260–100, how much color distance is keyed out
chromaSoftness120–100, edge feather + spill suppression
bgRemovefalseAI person cut-out (MediaPipe, loads from CDN on first use; needs internet once)

Audio / time video/audio#

propdefaultnotes
volume10–2 (linear; animatable - fades, ducking)
gain0clip gain in dB (−60…+24), applied before volume, so keyframes and fades ride on top. Set by Normalize.
channelMode"stereo"stereo · mono (L+R folded to one channel) · left · right (use one side) · swap (exchange L/R). Ignored on linked stems - audioChannel already picks their channel.
duck0ducking in dB (≤ 0), multiplied into volume. Normally keyframed by Auto-duck (keyframes.duck), so the clip's own volume, keyframes and fades are untouched.
pan0−1 (full left) … 0 (center) … +1 (full right). Linked stems default L −1 / R +1 / other 0. Projects saved before pan migrate once on load (panSchema); keep panSchema: 1 (and explicit pan on stems) when rewriting the document so a centered stem is not re-hard-panned.
speed10.25–4× playback rate. Keyframable → speed ramps: with keyframes.speed the engine time-remaps (media time = in + ∫speed dt), in preview and in the export audio mix. Static case: source window consumed = duration × speed, so in + duration×speed ≤ media.duration.

Text clips only#

propdefaultnotes
text"Title"\n for multi-line
fontSize72px
color"#ffffff"fill
color2""if set: vertical gradient fill color→color2
font"Segoe UI"system font, a library/fonts family, or ANY Google Font name - unknown names are fetched from Google Fonts automatically
bold / weighttrue / 0weight (300–900) overrides bold when non-zero
italic uppercasefalse
align"center"left · center · right · justify (inserts spaces between words to fill the text box width, or ~85% of the canvas when no box)
boxW boxH0px text box; 0 = hug content. When both > 0, corner handles resize the box (not scale). Default: fixed fontSize, word-wrap inside the box.
boxFitfalsewhen a box is set: false = wrap at fixed font size; true = scale font down (up to fontSize) so the whole text fits
vAlign"middle"top · middle · bottom - vertical alignment of the text block inside the box
direction"auto"auto · ltr · rtl - auto detects per line (Hebrew/Arabic → RTL); all textAnim modes honor reading direction (wipe, typewriter reveal, word/letter layout)
letterSpacing0px
lineHeight1.2multiplier
textShadow12soft drop shadow amount, 0 = off
glow0neon glow strength (0–100); replaces the drop shadow
glowColor""glow color ("" = use the text color)
strokeWidth strokeColor0, "#000"text outline
bgColor bgOpacity"#000", 0rounded pill behind each line
textAnim"none"typewriter · word-pop · word-slide · karaoke · highlight (every word shown; the one being said in highlightColor) · letter-pop (per-character entrance; Arabic/Indic auto-fallback to per-word clusters so joined letters shape correctly) · wave (looping per-character ride; same shaping fallback) · bounce (looping per-word hop) · shake (looping jitter) · clip-reveal (wipe-mask sweep, per line) · zoom-in (scale + opacity settle) · font-cut (rhythmically swaps typeface, then settles - see fontCutSet) · rise-mask (line rises from behind its baseline, lower-third reveal)
wordRate0.15seconds per word (typewriter: /4, letter-pop: /3 per character); also staggers clip-reveal/zoom-in/rise-mask per line
wordTimes-[[start, end], …], one pair per word (seconds from the clip's start): word-pop, word-slide, karaoke and highlight follow these instead of wordRate - a caption timed to speech. If the text is edited to another number of words they are spread over the clip. See Captions
highlightColor"#ffd166"the colour of the word being said in highlight
caption · captionStyle-set on caption clips (see Captions): how they are found, replaced and exported
textPath-set the title along a path: one shape item (path, line, ellipse, rect, polygon, star) whose outline is the baseline; more lines follow on parallel curves below it. See Motion paths, motion blur and text on a path
pathOffset · pathAlign0 · "start"where along the path the text sits (% of its length, keyframable, wraps on closed paths) · which end of the text sits there: start · center · end
fontCutSet(curated)array of font family names cycled by font-cut, e.g. ["Anton","Bebas Neue","Archivo Black","Oswald"]; each is auto-loaded

Title styles one-tap cohesive looks#

Text clips created in the UI now rotate through curated styles so titles vary instead of all looking basic (the old flat Segoe UI / no-animation default). Each style bundles a different font, placement and animation. Apply one in the inspector (Title style dropdown + Shuffle), or reproduce it from an agent by writing the same props:

StyleFontLook
impactAntonuppercase, lower third, word-pop, big shadow
elegantPlayfair Displaywhite→gold gradient, centered, clip-reveal
kineticBebas Neuegold, font-cut cycling Anton/Bebas/Archivo/Oswald
neonBebas Neuecyan glow, wave
handwrittenCaveatrotated −4°, lower-left, word-slide
serifDropAbril Fatfacecentered, zoom-in
subtitleRobotosmall, bottom, bg pill, karaoke
boldRiseArchivo Blackuppercase, lower third, rise-mask
luxuryCinzeluppercase, cream→gold gradient, wide letterSpacing, clip-reveal
popOutlineMontserrat 900uppercase, gold with a dark outline, letter-pop
boxedInter 800dark text on a white box, lower third, word-slide
headlineMontserrat 900uppercase, outlined, the word being said in pink (highlight)
comicBangersyellow with a thick outline, tilted −3°, bounce
typewriterSpecial Elitecream, lower-left, typewriter
minimalInter 300uppercase, very wide letterSpacing, no shadow, rise-mask
scriptGreat Vibeswhite→blush gradient, clip-reveal
retroMonotonuppercase, pink glow, letter-pop
stickerFredoka 700white on a violet box, tilted −2°, lower third, word-pop
glitchRusso Oneuppercase, red glow, shake
cinematicCormorant Garamond 500uppercase, wide letterSpacing, rise-mask

Rule for agents: vary the font per title - never reuse one font across a whole edit. Any Google Font name auto-loads; some display faces ship in library/fonts/. The font picker lists about sixty Google fonts by look (Display, Sans, Serif, Script & hand, Retro & mono) and loads one on first use. Placement props (x/y) are canvas-aware in the styles (lower third ≈ y: height*0.30).

Switching the style on an existing title (inspector dropdown/Shuffle) only restyles the look (font, size, colors, shadow/glow, animation) - the clip's x/y/scale/rotation/align and its text are preserved. The style's canvas-aware placement is applied only when a title is first created.

Adjustment layers kind:"adjust", mediaId:null#

A clip that re-renders everything drawn below it (lower tracks + earlier clips) through its own filter stack - Premiere-style. Supports all Filter/Color props, vignette, grain, rgbSplit, temperature/tint, whole-frame shake, and opacity as the intensity. Keyframe/transition it like any clip. Put it on V2/V3 above the footage. Example: 0.3 s impact shake over everything = {kind:"adjust", track:"V3", duration:0.3, props:{shake:18}}.

Masks masks, video/image/svg/text/adjust#

Shapes that cut what the clip shows - rect, ellipse, bezier, free-hand; feather, expand, invert, add / subtract / intersect, keyframes. See Masks below.

Shape layers kind:"shape"#

props.shapes (rectangles, ellipses, polygons, stars, lines, bezier paths, groups) and trimStart / trimEnd / trimOffset (%, a draw-on of every path). Null objects (kind:"null") never render; other clips are parented to them. See Shapes, nulls and parenting.

Comp clips kind:"comp", compId#

A composition placed as one clip - it draws like a picture of the comp's size (fit defaults to none) and its media plays and exports. See "Compositions (nested sequences)".

Animatable props usable in keyframes#

X, y, scale, rotation, opacity, anchorX, anchorY, trimStart, trimEnd, trimOffset, pathOffset, volume, pan, duck, speed, brightness, contrast, saturation, hue, blur, grayscale, sepia, invert, temperature, tint, vignette, cornerRadius, shake, rgbSplit, grain, fontSize, letterSpacing, glow.

Transition types#

Fade · slide-left/right/up/down · zoom · wipe (=wipe-left) · wipe-right/up/down · iris (circular) · spin · blur · whip (whip-pan) · glitch (RGB split + jitter) · pop (overshoot scale - stickers/captions).

diff --git a/docs/docs/recipes/index.html b/docs/docs/recipes/index.html index d6115a1a1..9d16a4264 100644 --- a/docs/docs/recipes/index.html +++ b/docs/docs/recipes/index.html @@ -75,14 +75,14 @@

Recipes

Short answers for common edits: grades, captions, speed ramps, transitions and more, each one a few props away.

Assemble a rough cut#

Clips back-to-back on V1; each start = running sum of previous durations.

Insert / replace at playhead 3-point editing#

Load media into the Source monitor (double-click a bin item or timeline clip), mark the window with I/O, then , (insert icon) splits straddling clips on targeted tracks at the playhead, ripples everything later to the right by the window length, and drops the Source window in - video brings its linked audio stems. . (replace icon) overwrites instead: punches the placement tracks (V1 + linked stems) over [playhead, +window) with no ripple. Placement lanes are resolved against the live track list and follow targeting - if V1 / A1 / A2 were removed or untargeted, the lowest remaining targeted lanes of the right kind are used instead. Locked clips are never punched or split. A locked clip loaded into Source can't be retargeted with . (toast) until it is unlocked. When Source was loaded from a timeline clip, . instead retargets that clip's In/Out (and its linked stems) and ripples later clips on its tracks if the duration changed.

Ripple delete#

Select clip(s), then ⇧Del or the timeline-toolbar Ripple delete - removes the selection (linked partners included) and pulls later clips left on each targeted track to close the gap. Plain Del lifts (leaves a gap). Sync lock applies: linked partners on untargeted tracks move with the ripple, and locked clips are neither deleted nor moved. An unselected clip that merely overlaps the deleted range stays put - its overlap ends up bridging the shifted-in clip, so a crossfade across the cut survives.

Tighten a cut without breaking the rest#

Ripple edit (B) on the tail of the shot that runs long - the rest of the edit follows. To change where a cut falls between two shots without shifting anything else, Rolling edit (R) the cut. To keep a shot's timing but use a better take of the same moment, Slip (Y) it. To pull a whole segment out of the middle: set IN / OUT around it and Extract (').

Jump to cut#

Select a clip, then ↑ / ↓ - playhead snaps to its In, then Out (further taps walk neighboring cuts). No selection → previous / next cut on targeted tracks. Source monitor: same keys jump among 0 / In / Out / duration.

Protect finished work#

Lock the lanes you are done with (lockedTracks, or the padlock), e.g. setProject {lockedTracks:["A3"]} for a music bed. Now insert, ripple delete and close gap re-time the picture without touching it. To try an alternative without deleting a clip, disable it (⇧E / disabled:true).

Title card#

{kind:"text", mediaId:null, track:"V2", props:{text,fontSize,color}}.

Music bed#

Audio file on A1, props.volume: 0.3, trim with in/duration.

Level a voice-over edit#

fablecut_normalize_audio {clipIds:[…every VO clip…], target:-16} so all takes sit at one loudness, then keep the music on its own lane and pull that lane down: {op:"setTrack", id:"A3", set:{gain:-14}}. Then dip it under the voice: fablecut_auto_duck {clipIds:[<music clip>], under:["A1"], amount:-10}.

Cut a montage to the music#

Put the shots on V1 in the order you want (rough lengths are fine) and the music on an audio lane, then fablecut_beats {clipId:<the music>, retime:{every:2}} - each shot gets two beats where its footage allows (fewer when it runs out; clips past the music keep their length; one with less than a beat of footage refuses the re-cut), the cuts land on the beat. every:1 for a fast reel, 4 for a calm one; re-cut the part after the drop separately with retime:{from:<the drop>, every:1}. For an edit whose cuts are already chosen, snap:true just nudges each one onto the nearest beat (cuts on untargeted tracks, beside locked clips, or without spare footage to reach it stay where they are; the reply counts them). Check a cut with fablecut_frame before exporting.

Tighten a talking-head take#

Lock the music lane (setProject {lockedTracks:["A3"]}), then fablecut_silence {clipIds:[<the take>]} to see the pauses (it does the listening; fablecut_frame only shows the picture, handy to check a cut won't land mid-gesture), and fablecut_silence {clipIds:[<the take>], cut:true}. Add {op:"crossfade", ids:[…]} on the new audio cuts if a breath clicks.

Cut an interview down by text#

Lock the music lane, fablecut_transcribe {clipIds:[<the interview>]} to read what was said (name the speech clips, or the music bed is transcribed too), decide what stays, then fablecut_transcribe {clipIds:[<the interview>], find:["the sentence to drop", "and this one"], cut:true}. Then fablecut_silence {clipIds:[…], cut:true} for the pauses that are left.

Caption a talking-head reel#

Finish the cut first, then fablecut_captions {style:"highlight", clipIds:[<the talking-head clips>]} (name the speech clips, or a music bed with vocals gets captioned too), fablecut_frame {time:<mid-sentence>} to check the size and placement, and fablecut_captions {export:"srt"} for the platform's own subtitle upload.

Center a mono stem#

Linked or standalone audio clip with props.pan: 0 (inspector Pan slider, −1…+1). Stereo video stems default to L −1 / R +1; set A1 to 0 to center that channel in the mix.

Cinematic grade#

props.filterPreset: "teal-orange" (tweak with temperature/vignette on top).

Balanced, contrasty base grade then measure with fablecut_scopes#

{op:"setGrade", id, grade:{contrast:1.15, pivot:0.42, shadows:-10, highlights:-20, highSoft:30, saturation:108}}. Teal shadows / warm highlights: add lift:[-0.034, 0.008, 0.012, 0] and gain:[0.04, 0, -0.06, 0]. Film-style S-curve, muted greens, yellows pushed toward orange: grade:{curves:{y:[[0.25, 0.2], [0.75, 0.82]]}, hueSat:[[115, 0.7]], hueHue:[[60, -12]]} - then fablecut_scopes to check the blacks didn't crush. A grade on an adjustment layer over the whole edit = one look for every shot.

Green-screen composite#

Subject clip on V2 with props: {chromaKey:"#00ff00", chromaTolerance:30, chromaSoftness:15}, background footage on V1.

Remove background without a green screen people#

props: {bgRemove:true} - then put anything behind it on V1.

Picture-in-picture#

Clip on V3 with props: {scale:0.35, x:380, y:-200, cornerRadius:24} - add transitionIn: {type:"slide-right", duration:0.5} to fly it in.

Slow motion / timelapse#

props.speed: 0.5 (half speed) or 4 (4×). Remember the source window is duration × speed.

Speed ramp the reel move - fast into slow on the beat#

keyframes: { speed: [ {t:0, v:3}, {t:1.1, v:3}, {t:1.3, v:0.4, "ease":"ease-out"} ] } - sync the drop (t:1.3) to a marker; add transitionIn:{type:"whip",duration:0.2} before it.

Impact hit#

Adjustment layer, 0.25–0.4 s at the hit: {kind:"adjust", track:"V3", props:{shake:20, rgbSplit:8}} + impact-hit.mp3 from library/sfx on A2.

VHS / glitch look#

props: {rgbSplit:4, grain:35, saturation:120} + library/elements/vhs-scanlines.svg on V3 with blend:"soft-light", fit:"stretch". Cut between shots with transitionIn:{type:"glitch",duration:0.3}.

Film look#

Adjustment layer across the whole edit: props: {filterPreset:"cinematic", grain:18} - one clip grades every shot.

Neon caption#

props: {glow:60, glowColor:"#22d3ee", color:"#ffffff", font:"Bebas Neue", textAnim:"wave"} on a dark shot.

Light leak accent#

library/elements/light-leak-warm.svg on V3, props:{blend:"screen", fit:"cover", opacity:0.7}, 1–2 s at scene changes, transitionIn/Out: fade.

Light-leak / dust overlay#

Element from library/elements on V3 with props: {blend:"screen", opacity:0.6, fit:"cover"}.

Reel caption#

Text clip with props: {textAnim:"word-pop", wordRate:0.15, strokeWidth:6, bgColor:"#000000", bgOpacity:0.45, fontSize:88}. karaoke dims words until "spoken"; typewriter for terminal vibes.

RTL / Hebrew / Arabic caption#

Omit direction (defaults to "auto") or set direction:"rtl" explicitly; pick a font with the script's glyphs (Google Fonts work). Animations wipe and stagger in reading order automatically. letter-pop / wave animate whole words on Arabic/Indic lines (not isolated letters) so cursive joining stays correct.

Branded title#

props: {font:"Bebas Neue", weight:700, letterSpacing:6, uppercase:true, color:"#ffffff", color2:"#7b6cff", textShadow:20} - any Google Font name just works.

Kinetic font-cut title rhythmic typeface cuts on the beat, then settle#

props: {font:"Bebas Neue", fontSize:120, uppercase:true, color:"#ffd166", textAnim:"font-cut", fontCutSet:["Anton","Bebas Neue","Archivo Black","Oswald"]}.

Elegant clip-on title letters wipe in#

props: {font:"Playfair Display", fontSize:88, color:"#ffffff", color2:"#ffd166", letterSpacing:2, textAnim:"clip-reveal"} - centered, one clean sweep.

Lower-third reveal#

props: {font:"Archivo Black", fontSize:92, uppercase:true, textAnim:"rise-mask", y:<height*0.30>} - the line rises from behind its baseline. Pair with a serifDrop/zoom-in kicker above it.

Custom font#

Drop MyBrand.ttf into library/fonts/, then props.font: "MyBrand".

Animated sticker#

Author an SVG (convention above) into library/svg/, register {kind:"svg", src:"/library/svg/foo.svg"}, clip on V2/V3. Scale/move/ rotate with normal props & keyframes; the SVG's own CSS animation plays on top, frame-accurately.

Whoosh on a cut#

0.4 s sfx clip from library/sfx on A2 aligned to the cut.

Ken Burns slow push on a photo#

keyframes: { scale:[{t:0,v:1},{t:D,v:1.2,ease:"linear"}], x:[{t:0,v:0},{t:D,v:-40,ease:"linear"}] }.

Crossfade#

Overlap two clips on the same track by ~1 s; later clip gets transitionIn: {type:"fade", duration:1}. For audio give the earlier clip the matching transitionOut and both curve:"power" (or select a clip and press Shift+D in the editor).

Whip-pan cut#

A gets transitionOut:{type:"whip",duration:0.25}, B gets transitionIn:{type:"whip",duration:0.25}.

Beat-synced cut#

Write beat times into markers, then align clip starts to them (the UI also snaps drags to markers).

Label the structure#

Write named, coloured markers for sections the user can jump between (⇧M / Alt+⇧M, or the Markers list): setProject {markers:[{t:0,label:"intro",color:"blue"},{t:8.5,label:"drop",color:"red"},{t:24,label:"outro",color:"purple"}]}. setProject replaces the whole list - include the existing markers you want to keep.

Music fade-out#

Audio clip keyframes: { volume:[{t:D-3,v:0.8},{t:D,v:0}] } or simply transitionOut: {type:"fade", duration:3, curve:"exp"}.

Pulse / emphasis#

keyframes: { scale:[{t:0,v:1},{t:0.3,v:1.12},{t:0.6,v:1}] }.

Reframe horizontal → vertical#

Keep a wide composition canvas and crop for delivery - e.g. width:1920, height:1080 with exportFrame:{x:656,y:0,w:608,h:1080} (9:16 fitted to canvas height). Position footage with clip x/y/scale; the export frame can be dragged in the UI. Omit exportFrame to export the full canvas.

Vertical reel#

Set project width:1080, height:1920; use the UI's safe-area guides (▦) to keep captions out of platform UI zones.

Project frame rate#

Set fps in project.json (or the Program Monitor FPS dropdown - 24 / 25 / 30 / 50 / 60). Preview stepping, timecode frames, Fast / WebCodecs / Realtime export, and /api/export/begin all use this value; pass the same fps when starting an export via the API.

diff --git a/docs/docs/remake/index.html b/docs/docs/remake/index.html index 4b3028ed6..5761e0d25 100644 --- a/docs/docs/remake/index.html +++ b/docs/docs/remake/index.html @@ -75,7 +75,7 @@

threshold tunes cut sensitivity (default adapts 0.30→0.20→0.12): lower it if obvious cuts were missed, raise it if motion is being misread as cuts.

Rebuild recipe - the analysis is deterministic; the creative mapping is yours:

  1. setProject: copy the reference's width/height/fps; write beats (or the cuts) into markers so the user sees the grid.
  2. Music: the extracted track on A1, in:0, duration:<ref duration>.
  3. Structure: one clip per shots[] entry on V1 at the same start/duration (hard cuts by default - that's what shot detection saw). Pick source footage whose motion matches each shot's energy (calm ≤40, action ≥70), and choose each clip's in so something interesting happens inside the window. Then look: fablecut_frame {path, frames:12} to survey a candidate clip, {path, t} at the exact moment you want, before committing to an in.
  4. The drop: put the hero shot there; classic garnish = a speed ramp landing on it, an impact adjust layer (shake+rgbSplit), or a whip transition.
  5. Pacing garnish to taste: shots shorter than ~0.6 s read as beat-flashes; avgShotLen tells you the reference's overall pace. Captions/grade/SFX per the Recipes section - the blueprint gives structure, not style.
diff --git a/docs/docs/rest-api/index.html b/docs/docs/rest-api/index.html index 907c19253..c8311dded 100644 --- a/docs/docs/rest-api/index.html +++ b/docs/docs/rest-api/index.html @@ -75,14 +75,14 @@

REST API

The HTTP endpoints behind the editor, for scripts and tools that don't speak MCP.

-
  • GET /api/project - current project JSON
  • PUT /api/project - replace project JSON (body = full document). Conflict-safe: if the body's revision ≤ the revision currently on disk, the server rejects with 409 and returns {"error":"…","revision":<current>}. Append ?force=1 to overwrite unconditionally. A request with an X-FableCut-Project header (the editor sends the id of the project it loaded) is also refused with 409 when another project is open (see Projects). Writes are atomic (tmp file + rename), so a crashed write never corrupts the file.
  • GET /api/media - list files in ./media (name, src, size)
  • GET /api/media-info?src=/media/x.mp4 → {src, info} · POST /api/media-info {srcs:[…], stat?} → {info:{src: info}} (up to 2000; stat:true answers only {size, mtimeMs}, no ffprobe - how the editor checks for offline files) - a file's metadata from ffprobe: size, fps, codec, audioCodec, audioChannels, sampleRate, bitrate, duration, width, height and probe ("ffprobe", or "stat" when only the size could be read). info is null when the src names no file under /media/ or /library/. Cached per file version.
  • POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} queues proxies (ffmpeg, one at a time); POST /api/proxy/status {srcs} → {status:{src: status | null}}; POST /api/proxy/delete {srcs} → {deleted:{src: n}}. A status is {state:"ready", src:"/proxies/…", width, height, size}, {state:"queued"|"running", progress, height}, {state:"failed", error} or {state:"none"} (null = no such source file). Progress and results are also pushed as SSE event proxy ({src, status}). GET /proxies/<name> serves a proxy file from analysis/proxies/. /api/proxy answers 503 without ffmpeg.
  • POST /api/relink/candidates {media:[{id, name, src?, size?, kind?}]} → {candidates:{id:[{src, name, size, score, why}]}} - where a missing file might be now: files under media/ and library/ (subfolders included) of the same kind, ranked by name (same name, same name with another extension, similar name) and size, best 5 each.
  • GET /api/projects[?archived=only|all] → {active, projects:[{id, name, active, archived, notes, tags, created, opened, modified, width, height, fps, duration, clips, media, thumb}], templates:[…]} · POST /api/projects {action, …} - the actions of fablecut_projects (plus import {project, name?}). The answer depends on the action: {id, project} for open / new / duplicate / update / archive / unarchive / import (plus from when the open project changed, already when it was open), {id, deleted} for delete, {templates} for templates, {template} for save_template (the saved one) and {template, deleted} for delete_template · GET / PUT /api/projects/thumb?id= - a project's JPEG thumbnail (1 MB max). SSE event projects ({action, id, active}) after each change. See Projects.
  • GET /api/versions[?project=] → {project, versions:[{v, name, note, kind, created, revision, clips, duration, final}]} (newest first; default the open project) · POST /api/versions {action, project?, version?, …} - save {name?, note?, final?} → {project, version} · diff {version, to?} → {same, lines, added, removed, changed, mediaAdded, mediaRemoved, settings} · restore {version} → {restored, saved} · update {version, name?, note?, final?} → {version} · delete {version} → {deleted}. GET /api/versions/file?project=&version= is that version's document; GET /api/projects/backup?id= a project with all its versions (import it with POST /api/projects {action:"import", project:<the backup>}). SSE event versions ({project, action}). See Versions.
  • POST /api/files {action, …} - the files in media/: list {dir?} → {dir, folders, files:[{name, src, size}]} · mkdir {dir} · move {from, to, force?} → {from, to, moved:[{from, to}], repointed:[{project, open, media}], warning?} (from / to are the item itself; moved lists each file in it, so it is empty for an empty folder or a no-op; 409 while a project can't be read, unless force:true) · trash {paths, force?} → {trashed:[{id, src}], offline} (409 while a project uses one or can't be read, unless force:true; a batch that stops part-way answers 400 with trashed and failed; stillThere lists uses whose file is still in place) · trash-list → {items} · restore {id}. See Media management.
  • GET /api/library?dir=sfx|elements|svg|fonts|presets|templates - list library assets
  • GET /api/presets · GET /api/templates - the saved presets / templates, validated (bad files skipped); POST /api/presets {preset} · POST /api/templates {template} - validate one and save it as library/presets/<id>.json / library/templates/<id>.json, returning {id, name, file}
  • POST /api/upload?name=foo.mp4 - raw body saved into ./media, returns {src}. MP4/MOV/M4V uploads are auto-remuxed with +faststart (needs ffmpeg on PATH). Files copied straight into ./media by external tools skip this - remux big ones yourself (ffmpeg -i in.mp4 -c copy -movflags +faststart out.mp4) or playback stalls.
  • POST /api/import-url - body {url:"https://…"} downloads the file into ./media/ and returns {src,name} (same-origin /media/…, like upload). HTTPS only; rejects localhost, private/link-local/CGNAT addresses, and redirects to those. Remote SVG is refused (/media/*.svg is served same-origin as image/svg+xml - a scripted SVG opened as a document would run on the editor origin). Does not write project.json - register the media afterwards (UI and fablecut_import_media do this). Do not put a raw https:// URL (or another origin, including localhost on a different port) in media.src: canvas CORS would taint the compositor and Fast / WebCodecs export cannot JPEG-encode. Import into ./media so src is /media/…, or serve the remote with Access-Control-Allow-Origin.
  • GET /api/transcript?src=/media/x.mp4 → {transcript} (null when the file has none yet; 404 when the file is missing) · POST /api/transcript?src= (a transcript document) → {src, words} · POST /api/transcript/status {srcs} → {status:{src: {words, language, model, duration, created} | false | null}} · POST /api/transcript/delete {src} → {deleted}. SSE event transcript ({src}) after each save or delete. POST /api/transcribe/request {transcribe:{srcs, model?, language?, again?}, where?} queues a transcription on the export-job queue (poll GET /api/export/job?id=); the tab saves each transcript, and the job's result lists done, skipped and failed. See Transcripts and text-based editing.
  • POST /api/denoise - body {src:"/media/…", amount:"light"|"medium"|"strong"}: writes a noise-reduced FLAC of the whole file into ./media/ (reused if it exists) and returns {src, name, duration, channels}. Does not touch project.json (see Audio mix).
  • POST /api/analyze - body {src:"/media/ref.mp4", threshold?, music?}: analyze a reference video into an edit blueprint (see Remake a reference video); extracts its music into ./media. GET /api/analyze?src=… returns the cached blueprint.
  • GET /api/frame?src=/media/x.mp4&t=3.2 - one JPEG still of a source clip, the "eyes" to go with /api/analyze's ears (see Look at the footage). Optional w (pixel width, default 768) and q (ffmpeg -q:v 1–31, default 4). &frames=N[&cols=][&from=][&to=][&w=320] instead returns one N-up contact sheet across the clip (N 2–60; cols omitted → the squarest layout, so 6 frames give 3×2 rather than 4×2 with two black cells). src must name an existing file under /media/ or /library/ (404 otherwise). ?path= reads any file on the machine but only with the X-FableCut-Client: mcp request header, which only the local MCP client sends - without it the request is refused (403) before the path is even resolved. Results are cached in analysis/frames/ keyed by source path, size and mtime; the cache is capped (500 files / 128 MB, oldest first). The response carries X-FableCut-Frame-Times (comma-separated sample times, so a sheet's cells can be mapped back to timestamps) and X-FableCut-Frame-Source.
  • POST /api/scopes/request also takes {"image":true}, which makes the editor return the measured still as a JPEG data URL in result.image - how fablecut_frame {time} shows an agent the composed program picture.
  • GET /api/events - SSE: named event change when project.json, ./media or ./library changes; named event profiles when encoding-profiles.json changes (UI refreshes the export-profile list only - no project reload); named event proxy as a proxy is queued, makes progress, finishes or is deleted
  • Fast / WebCodecs export (browser compositor → server ffmpeg): GET /api/export/ffmpeg → {available} · GET /api/export/profiles[?detail=1] → {default, profiles, issues} · POST /api/export/begin {fps,name,mode?,profile?,hasAudio?,pixelFormat?,width?,height?} → {id,mode,profile?,label,summary} (fps is required - pass project.fps, no server-side default; mode is "jpeg" (default, Fast) or "annexb" (WebCodecs H.264 elementary stream); jpeg 400 if profile is not a defined id, or if ffmpeg rejects its args in the dry run; optional pixelFormat:"rgba" plus width/height pipes raw canvas frames instead of JPEG) · POST /api/export/frame?id= (JPEG body for jpeg mode; raw RGBA if begin used pixelFormat:"rgba"; Annex-B for annexb - one POST may concatenate frames or AUs. Must be after audio; ffmpeg is spawned on the first frame in both modes) · POST /api/export/audio?id= (WAV body - must be sent before the first frame) · POST /api/export/end?id=[&discard=1] → {src} under /exports/
  • Export jobs (what fablecut_export drives): POST /api/export/request {range?, profile?, where?:"auto"|"tab"|"headless"} → {id, status, via, …} (409 if one is already running, or nothing can render it) · GET /api/export/job?id= → {status: pending|running|done|failed|cancelled, progress 0–1, src, error} · POST /api/export/job/cancel?id=. The editor tab side: SSE event export (a ticket), GET /api/export/job/ticket?id=, POST /api/export/job/claim?id= (first tab wins, else 409), POST /api/export/job/report?id= {progress} | {status:"done", src} | {status:"failed", error} → {cancel}.
+
  • GET /api/project - current project JSON
  • PUT /api/project - replace project JSON (body = full document). Conflict-safe: if the body's revision ≤ the revision currently on disk, the server rejects with 409 and returns {"error":"…","revision":<current>}. Append ?force=1 to overwrite unconditionally. A request with an X-FableCut-Project header (the editor sends the id of the project it loaded) is also refused with 409 when another project is open (see Projects). Writes are atomic (tmp file + rename), so a crashed write never corrupts the file.
  • GET /api/media - list files in ./media (name, src, size)
  • GET /api/media-info?src=/media/x.mp4 → {src, info} · POST /api/media-info {srcs:[…], stat?} → {info:{src: info}} (up to 2000; stat:true answers only {size, mtimeMs}, no ffprobe - how the editor checks for offline files) - a file's metadata from ffprobe: size, fps, codec, audioCodec, audioChannels, sampleRate, bitrate, duration, width, height and probe ("ffprobe", or "stat" when only the size could be read). info is null when the src names no file under /media/ or /library/. Cached per file version.
  • POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} queues proxies (ffmpeg, one at a time); POST /api/proxy/status {srcs} → {status:{src: status | null}}; POST /api/proxy/delete {srcs} → {deleted:{src: n}}. A status is {state:"ready", src:"/proxies/…", width, height, size}, {state:"queued"|"running", progress, height}, {state:"failed", error} or {state:"none"} (null = no such source file). Progress and results are also pushed as SSE event proxy ({src, status}). GET /proxies/<name> serves a proxy file from analysis/proxies/. /api/proxy answers 503 without ffmpeg.
  • POST /api/relink/candidates {media:[{id, name, src?, size?, kind?}]} → {candidates:{id:[{src, name, size, score, why}]}} - where a missing file might be now: files under media/ and library/ (subfolders included) of the same kind, ranked by name (same name, same name with another extension, similar name) and size, best 5 each.
  • GET /api/projects[?archived=only|all] → {active, projects:[{id, name, active, archived, notes, tags, created, opened, modified, width, height, fps, duration, clips, media, thumb}], templates:[…]} · POST /api/projects {action, …} - the actions of fablecut_projects (plus import {project, name?}). The answer depends on the action: {id, project} for open / new / duplicate / update / archive / unarchive / import (plus from when the open project changed, already when it was open), {id, deleted} for delete, {templates} for templates, {template} for save_template (the saved one) and {template, deleted} for delete_template · GET / PUT /api/projects/thumb?id= - a project's JPEG thumbnail (1 MB max). SSE event projects ({action, id, active}) after each change. See Projects.
  • GET /api/versions[?project=] → {project, versions:[{v, name, note, kind, created, revision, clips, duration, final}]} (newest first; default the open project) · POST /api/versions {action, project?, version?, …} - save {name?, note?, final?} → {project, version} · diff {version, to?} → {same, lines, added, removed, changed, mediaAdded, mediaRemoved, settings} · restore {version} → {restored, saved} · update {version, name?, note?, final?} → {version} · delete {version} → {deleted}. GET /api/versions/file?project=&version= is that version's document; GET /api/projects/backup?id= a project with all its versions (import it with POST /api/projects {action:"import", project:<the backup>}). SSE event versions ({project, action}). See Versions.
  • POST /api/files {action, …} - the files in media/: list {dir?} → {dir, folders, files:[{name, src, size}]} · mkdir {dir} · move {from, to, force?} → {from, to, moved:[{from, to}], repointed:[{project, open, media}], warning?} (from / to are the item itself; moved lists each file in it, so it is empty for an empty folder or a no-op; 409 while a project can't be read, unless force:true) · trash {paths, force?} → {trashed:[{id, src}], offline} (409 while a project uses one or can't be read, unless force:true; a batch that stops part-way answers 400 with trashed and failed; stillThere lists uses whose file is still in place) · trash-list → {items} · restore {id}. See Media management.
  • GET /api/library?dir=sfx|elements|svg|fonts|presets|templates - list library assets
  • GET /api/presets · GET /api/templates - the saved presets / templates, validated (bad files skipped); POST /api/presets {preset} · POST /api/templates {template} - validate one and save it as library/presets/<id>.json / library/templates/<id>.json, returning {id, name, file}
  • GET /api/workflows[?id=] - the saved workflows, validated (bad files skipped), or one by id or name (404 if none) · POST /api/workflows {workflow} - validate and save it as library/workflows/<id>.json, returning it with created / updated · POST /api/workflows/delete {id} → {deleted}. See Workflows.
  • POST /api/upload?name=foo.mp4 - raw body saved into ./media, returns {src}. MP4/MOV/M4V uploads are auto-remuxed with +faststart (needs ffmpeg on PATH). Files copied straight into ./media by external tools skip this - remux big ones yourself (ffmpeg -i in.mp4 -c copy -movflags +faststart out.mp4) or playback stalls.
  • POST /api/import-url - body {url:"https://…"} downloads the file into ./media/ and returns {src,name} (same-origin /media/…, like upload). HTTPS only; rejects localhost, private/link-local/CGNAT addresses, and redirects to those. Remote SVG is refused (/media/*.svg is served same-origin as image/svg+xml - a scripted SVG opened as a document would run on the editor origin). Does not write project.json - register the media afterwards (UI and fablecut_import_media do this). Do not put a raw https:// URL (or another origin, including localhost on a different port) in media.src: canvas CORS would taint the compositor and Fast / WebCodecs export cannot JPEG-encode. Import into ./media so src is /media/…, or serve the remote with Access-Control-Allow-Origin.
  • GET /api/transcript?src=/media/x.mp4 → {transcript} (null when the file has none yet; 404 when the file is missing) · POST /api/transcript?src= (a transcript document) → {src, words} · POST /api/transcript/status {srcs} → {status:{src: {words, language, model, duration, created} | false | null}} · POST /api/transcript/delete {src} → {deleted}. SSE event transcript ({src}) after each save or delete. POST /api/transcribe/request {transcribe:{srcs, model?, language?, again?}, where?} queues a transcription on the export-job queue (poll GET /api/export/job?id=); the tab saves each transcript, and the job's result lists done, skipped and failed. See Transcripts and text-based editing.
  • POST /api/denoise - body {src:"/media/…", amount:"light"|"medium"|"strong"}: writes a noise-reduced FLAC of the whole file into ./media/ (reused if it exists) and returns {src, name, duration, channels}. Does not touch project.json (see Audio mix).
  • POST /api/analyze - body {src:"/media/ref.mp4", threshold?, music?}: analyze a reference video into an edit blueprint (see Remake a reference video); extracts its music into ./media. GET /api/analyze?src=… returns the cached blueprint.
  • GET /api/frame?src=/media/x.mp4&t=3.2 - one JPEG still of a source clip, the "eyes" to go with /api/analyze's ears (see Look at the footage). Optional w (pixel width, default 768) and q (ffmpeg -q:v 1–31, default 4). &frames=N[&cols=][&from=][&to=][&w=320] instead returns one N-up contact sheet across the clip (N 2–60; cols omitted → the squarest layout, so 6 frames give 3×2 rather than 4×2 with two black cells). src must name an existing file under /media/ or /library/ (404 otherwise). ?path= reads any file on the machine but only with the X-FableCut-Client: mcp request header, which only the local MCP client sends - without it the request is refused (403) before the path is even resolved. Results are cached in analysis/frames/ keyed by source path, size and mtime; the cache is capped (500 files / 128 MB, oldest first). The response carries X-FableCut-Frame-Times (comma-separated sample times, so a sheet's cells can be mapped back to timestamps) and X-FableCut-Frame-Source.
  • POST /api/scopes/request also takes {"image":true}, which makes the editor return the measured still as a JPEG data URL in result.image - how fablecut_frame {time} shows an agent the composed program picture.
  • GET /api/events - SSE: named event change when project.json, ./media or ./library changes; named event profiles when encoding-profiles.json changes (UI refreshes the export-profile list only - no project reload); named event proxy as a proxy is queued, makes progress, finishes or is deleted
  • Fast / WebCodecs export (browser compositor → server ffmpeg): GET /api/export/ffmpeg → {available} · GET /api/export/profiles[?detail=1] → {default, profiles, issues} · POST /api/export/begin {fps,name,mode?,profile?,hasAudio?,pixelFormat?,width?,height?} → {id,mode,profile?,label,summary} (fps is required - pass project.fps, no server-side default; mode is "jpeg" (default, Fast) or "annexb" (WebCodecs H.264 elementary stream); jpeg 400 if profile is not a defined id, or if ffmpeg rejects its args in the dry run; optional pixelFormat:"rgba" plus width/height pipes raw canvas frames instead of JPEG) · POST /api/export/frame?id= (JPEG body for jpeg mode; raw RGBA if begin used pixelFormat:"rgba"; Annex-B for annexb - one POST may concatenate frames or AUs. Must be after audio; ffmpeg is spawned on the first frame in both modes) · POST /api/export/audio?id= (WAV body - must be sent before the first frame) · POST /api/export/end?id=[&discard=1] → {src} under /exports/
  • Export jobs (what fablecut_export drives): POST /api/export/request {range?, profile?, where?:"auto"|"tab"|"headless"} → {id, status, via, …} (409 if one is already running, or nothing can render it) · GET /api/export/job?id= → {status: pending|running|done|failed|cancelled, progress 0–1, src, error} · POST /api/export/job/cancel?id=. The editor tab side: SSE event export (a ticket), GET /api/export/job/ticket?id=, POST /api/export/job/claim?id= (first tab wins, else 409), POST /api/export/job/report?id= {progress} | {status:"done", src} | {status:"failed", error} → {cancel}.
diff --git a/docs/docs/sequences/index.html b/docs/docs/sequences/index.html index df61a5f27..3f73df508 100644 --- a/docs/docs/sequences/index.html +++ b/docs/docs/sequences/index.html @@ -75,7 +75,7 @@

Opening another sequence parks the top-level keys in the open one's entry and brings the other's up, with a new revision - like any edit. A clip in a sequence that isn't open still counts: its media shows "used" in the bin, can't be removed while it is there (removeMedia and Remove from project refuse and name the sequence), and Replace file… trims it too; a comp it places can't be removed either. A project with one sequence named Main has neither key.

In the editor: the sequence menu at the left of the timeline toolbar (it shows the open sequence's name, and how many there are) lists them - click one to open it - and has New sequence… (a name, a canvas - the same as the open one, or 16:9, 9:16, 4:5, 1:1 - and, optionally, a copy of the open sequence's timeline to start from), Duplicate, Rename… and Delete… (click twice; the project is first kept as a version, so a deleted sequence can be restored from Projects → Versions). For the session each sequence keeps its own undo history, playhead and selection. The Export dialog, the Mixer, IN / OUT and the canvas settings all belong to the open sequence. Find timeline instances lists placements in other sequences too; clicking one opens its sequence.

Agents (fablecut_patch_project):

  • {op:"addSequence", name?, id?, from?, width?, height?, fps?, open?:true} - from:"empty" (default; the open sequence's canvas and frame rate, no clips), "open" (a copy of the open sequence's timeline) or a sequence id (a copy of that one). width / height / fps change the copy's canvas: the clips keep their positions relative to the centre, and an exportFrame is dropped.
  • {op:"inSequence", sequence, ops:[…]} runs ops on a sequence without opening it: clip and timeline ops, setProject (its canvas, markers, IN / OUT, delivery), setTrack, setBus, setFx on its tracks, and updateSequence (name, index) - not addSequence, openSequence, removeSequence or another inSequence. The user's editor stays where it is.
  • {op:"openSequence", id} changes what the user's editor shows, and what fablecut_export, fablecut_frame {time} and fablecut_scopes render: do it when the user asked, or to export that sequence.
  • {op:"updateSequence", id, set:{name?, index?}} renames or reorders one; {op:"removeSequence", id} deletes one (only when asked; the last one stays, deleting the open one opens its neighbour, and one holding locked clips or tracks needs force:true).
  • The compact view and fablecut_status list every sequence (id, name, canvas, clips, length, which is open). A version's Compare reports each sequence's changes on its own, sequences added and removed, and which one was open.

Reframe - fablecut_reframe {aspect?:"9:16"|"1:1"|"4:5"|"16:9"|"4:3"|"2:3", name?, clipIds?, follow?, smooth?, force?} makes a copy of the open sequence on that canvas shape and opens it (the project's shorter side kept: 1920×1080 → 1080×1920 for 9:16, 1080×1080 for 1:1), so the original cut stays as it was; without aspect it reframes the open sequence on its own canvas. Each full-frame shot - a video or still that isn't moved, scaled, cropped or keyed by hand - gets fit:"cover" and an x (or y) that keeps its subject in view. Frames are sampled 5 times a second at 96 px; the subject is where motion (against the shot's own movement, so a pan or a flicker doesn't count), detail and colour gather, pulled gently toward the centre. A virtual camera operator then holds still while the subject stays inside a dead zone and eases after it no faster than a pan speed, and the path becomes ordinary keyframes (thinned to within ~2 px), or one steady position. Shots with no clear subject are centred. Titles, picture-in-picture, clips placed or animated by hand and locked clips (unless force:true) are left alone and listed in the reply - check them on the new canvas with fablecut_frame {time}. follow:false only fits and centres; smooth 0…1 (default 0.5) holds longer and pans slower as it rises. props.reframe marks what Reframe did, so running it again replaces its own keys. A version is kept first. In the editor: New sequence… with a copy of the open sequence on another shape has Follow the subject in each shot; the Inspector's Reframe section on a video or picture of another shape than the canvas has Follow subject, Centre and Lively / Balanced / Steady (the selected clips, one undo step, with Cancel).

Highlights - fablecut_highlights {duration?, shot?, clipIds?, mediaIds?, name?, aspect?} finds the best moments of long footage and cuts them into a short edit: a new sequence (Highlights 30 s, or name), opened, so the timeline it came from stays as it was. It reads the video clips on the open timeline (clipIds limits them; mediaIds reads whole files instead), up to an hour of footage at a time: frames twice a second at 64 px, and the sound. Every half second is scored for movement, sound louder than the 20 s around it (a cheer, a laugh, a hit), its overall level, and a clear picture; black frames and flat colour count for little. Cuts already in the footage are found, and a moment never crosses one. It then takes the best moments of shot seconds (default duration / 8, kept within 1.5–4 s), apart in the same footage (by half a moment, at least a second) and spread over its shots, until the edit is duration seconds (default 30; 5…600), trims the last ones to fit exactly, and nudges each end up to 0.3 s to the quietest point near it, so no word or hit is cut through. The moments go back to back on V1 in story order, each a clip of its source with its props (a reframed clip's framing isn't carried over) and its linked sound clips beside it (their own tracks, linked again); their keyframes aren't carried over. A moment from a whole file (mediaIds) is one video clip that plays its own sound, with no separate audio clips. A clip played faster or slower counts by its length on the timeline: duration and shot are always seconds of the edit. In the editor (and Studio) the sound of a file longer than 30 minutes isn't read, so as not to decode it whole in the browser; its picture decides. Disabled clips and clips with a speed ramp are not read. aspect makes the new sequence 9:16, 1:1 or 4:5: the shots are then letterboxed, and fablecut_reframe {} fits them and follows the subject. The reply lists each moment (its source, times, length, why it was picked and its score). A version is kept first. In the editor: the sequence menu's Highlights… (15, 30, 60 or 90 s; a canvas, and Follow the subject in each shot on another shape) reads the selected video clips, else every video clip on the timeline, with progress and Cancel.

Recipes: vertical cut of a finished edit - fablecut_reframe {aspect:"9:16"}, then check the titles with fablecut_frame; by hand, addSequence {name:"Reel 9:16", from:"open", width:1080, height:1920}, then inSequence ops to re-position or re-scale the shots and setProject {delivery:"instagram-reels"} in it; reel from a long video - fablecut_highlights {duration:30, aspect:"9:16"}, then fablecut_reframe {}, music on an audio track and fablecut_beats {clipId:<the music>, retime:{every:2}}, then captions; cut-downs - duplicate the edit as "30 s" and "15 s" and tighten each with the trim ops inside inSequence; selects reel - an empty sequence the user drops favourite takes on, cut into the edit from the Source monitor.

- +
diff --git a/docs/docs/studio/index.html b/docs/docs/studio/index.html index d3e1d8426..d5eccb68d 100644 --- a/docs/docs/studio/index.html +++ b/docs/docs/studio/index.html @@ -75,7 +75,7 @@

FableCut Studio

diff --git a/docs/docs/tracking/index.html b/docs/docs/tracking/index.html index 3eb228fa7..a6745184d 100644 --- a/docs/docs/tracking/index.html +++ b/docs/docs/tracking/index.html @@ -75,7 +75,7 @@
keydoes
namehow masks, clips and agents refer to it (default Track n, or the mask's name)
kindpoint (position) or box (position, size and rotation were followed)
w · hthe region that was matched, fractions of the clip's picture
samplesone per frame: [t, x, y, s, r, q]. t is seconds from the clip's start, x, y is the centre (fractions of the picture, like masks), s is the scale and r the rotation (°) relative to the first sample, q is the match quality 0…1

The tracker matches a small greyscale template of the region (normalized cross-correlation, sub-pixel, optionally over scale and rotation) and keeps the template fresh while anchoring it to the first frame so it does not drift. It stops where the match quality drops below 0.45 (the region was covered, left the frame or changed too much) and keeps what it tracked up to there. Pick regions with detail: corners, text, edges. Flat sky or a blank wall can't be tracked. A track without scale follows position only: if the thing grows, shrinks or turns noticeably, turn on Scale / Rotate (scale / rotation), or the match fades and the track stops early. Tracks are stored in clip time, so they move with the clip and follow trims and splits (re-track after changing its speed).

In the editor:

  • Mask tracking. Select a mask on a video clip. Under its mode row, ◀ Back and On ▶ follow what the mask covers from the playhead to the clip's start or end, and key the mask's x / y. Turn on Scale and Rotate to key those too. The keys are linear and simplified (a key only where the motion turns, within ~1.5 px). Keys the mask had in that range lose their position and keep everything else.
  • Point tracking. The Inspector's Tracking section (video clips): + Track point, then click the spot on the monitor. It tracks from the playhead to the clip's end. Region sets the matched area (% of the picture's width). Pick a track's chip to see its path and region on the monitor, ◀ Track back / Track on ▶ to extend it from the playhead, and Delete it.
  • Attach a clip. With a track picked, choose a clip in Attach (any visual clip that overlaps it in time) and press Attach to the track. The clip gets x / y keyframes (plus scale / rotation with those toggles on) that ride on the track and keep it where it is at the playhead. Stickers, titles, a blur box or a highlight then stay pinned to the moving thing.
  • Tracking runs from a private copy of the video, so the monitor does not move. Progress shows in the Inspector, and Esc stops it and keeps what it has. Each finished track is one undo step.

Agents: fablecut_track runs the tracker in the editor (an open tab, else headless Chrome / Edge) and saves the result:

  • {clip, point:{x:0.62, y:0.4}, at:12} follows a spot from at to the clip's end. region:{x, y, w, h} gives the area instead, size sets a point's region (default 0.08 of the width), direction:"backward"|"both" and to (timeline seconds) set the range, and scale / rotation follow those too.
  • apply:{mask:"Face"} bakes the result into that mask's keys. Leave out point / region and the mask's own outline is what gets followed.
  • apply:{clip:"c_sticker", scale?, rotation?, at?} pins another clip to the track.
  • name names the track. Passing an existing name with apply and no region re-applies the stored track without tracking again.
  • The reply gives the range, the match quality (min / mean; ≥ 0.8 is solid), where it was lost, and what was keyed.
  • {op:"removeTrack", id, track} deletes a stored track; what followed it keeps its keys. The compact project view lists tracks as [tracks: "Logo" point 0.00–4.20 s (127 samples)], never their samples.

Recipes: a title that follows a car - track a point on the car, attach the title; blur a face or a plate - an ellipse mask on a blurred copy of the shot on the track above, then apply:{mask:"Face"}; a screen replacement - track the screen with Scale and Rotate on and attach the new picture, cropped to fit; a highlight that stays on a UI element in a screen recording - track the button, attach a rect svg.

diff --git a/docs/docs/transcripts/index.html b/docs/docs/transcripts/index.html index 3ebad8830..3ca44f087 100644 --- a/docs/docs/transcripts/index.html +++ b/docs/docs/transcripts/index.html @@ -75,14 +75,14 @@

Transcripts and text-based editing

Turn speech into words with times, in the browser, then read, search and cut the edit like text: in the Transcript tab, or from an agent with fablecut_transcribe.

FableCut turns the speech in a clip into words with times, so an edit can be read, searched and cut like text. Transcription runs in the browser: Whisper (OpenAI's speech model, through transformers.js) in a background worker of the editor tab. The library and the model are fetched from a CDN the first time and kept by the browser after that; the audio never leaves the machine.

modeldownload
base (default)77 MBquick: about 15 s per minute of speech on a fast desktop
small250 MBoften more accurate (accents, noisy rooms, numbers); about twice as slow

Whisper detects the language by itself; give it one (en, es, hi, ja, … any Whisper code) when a clip is short or mixes languages. Long files are split at their quietest moments into pieces of at most 28 s, and stretches of silence are skipped (Whisper invents words in silence).

One transcript per file, kept by the server in analysis/transcripts/: {v, src, model, language, duration, created, words:[[text, start, end], …]}, times in seconds of the file. Like a proxy it belongs to the file's size and modification time, so a replaced or re-rendered file has none until it is transcribed again. It is not stored in project.json, so it never bloats the timeline, and every clip and sequence that uses the file reads the same one.

On the timeline a clip shows the words its window of the file holds, placed through its in point and speed (a word counts when its middle is inside the clip). A clip with a speed ramp is left out, and so are disabled clips and pictures whose sound is off.

Cutting words extracts on the targeted tracks, from just before the first word to just before the word after the last one: the pause after the cut goes too, the pause before it stays. Cuts land on whole frames, never in a neighbouring word or past the clip. Several cuts go last first, as one undo step (one revision for an agent): later material moves up, linked stems stay in step, and locked clips stay put - lock the music bed first if it should keep running under the tightened edit. Find matches whole words and ignores case, accents, punctuation and spacing: "ai powered" finds "A.I.-powered", and "cat" doesn't find "category".

In the editor, the Transcript tab beside the Inspector:

  • Transcribe works on the selected clips' files (a selection with no speech, such as a title, transcribes nothing), else on every file on the timeline that has no transcript yet; once every file has one (an agent may have made them), it reads Transcribe again and redoes them all. The model and the language are beside it. Progress shows below (the first time, the model download), with Cancel. A line above the words says which model and language made them: when the words look wrong, pick the language spoken and the Small model, then Transcribe again.
  • The timeline's words, in paragraphs with timecodes. Click a word to go there; the word under the playhead is underlined and followed while playing. ⇧-click or drag to select a run of words, then press Delete (or Cut) to extract it.
  • Find words marks every match, Enter steps through them, and Cut N extracts them all. Copy copies the text with its timecodes.

Agents use fablecut_transcribe. It transcribes in an open editor tab, else in headless Chrome / Edge, whose profile is kept in analysis/browser-profile/ so the model downloads once:

  • {} transcribes every clip with sound that has no transcript yet, then returns the timeline's words as timed lines: [0:12.08] Open the demo, nothing to install. clipIds limits it to some clips; from / to limit the time (the reply stops at 300 lines); mediaIds reads whole files in file seconds instead.
  • model:"small", language:"es", and again:true (transcribe again, with another model or language).
  • find:"phrase" (or a list) reports each place it is said, with its span, the words around it and how much cutting them would remove; cut:true extracts them (tracks and force as for fablecut_silence). A version of the project is kept before the cut.

Whisper writes clean text: it often leaves out fillers ("um", "uh") and false starts, so find those by ear (fablecut_silence for the pauses), not by text. Word times are good to about a tenth of a second; listen to a cut that matters, or check it with fablecut_frame.

diff --git a/docs/docs/versions/index.html b/docs/docs/versions/index.html index fa5c8f551..2e6e4405c 100644 --- a/docs/docs/versions/index.html +++ b/docs/docs/versions/index.html @@ -75,17 +75,17 @@

Versions

Saved copies of a project you can compare and go back to, made by you, every few minutes, and before an agent edits; restoring is never destructive, and a backup carries them all.

Every edit is saved as it happens, and undo covers the session. An edit that reaches the open editor from outside (an agent, another tab) is one undo step of its own there: Ctrl+Z takes it back first, then the user's own edits. Versions are what you come back to later: full copies of a project, kept beside it, that are never overwritten. Restoring one is not destructive either - what is there is saved as a version first, so a restore can be undone by restoring that.

pathholds
projects/<id>/history/v0007.jsonthe project as it was
projects/<id>/history/v0007.meta.json{v, name, note, kind, created, revision, clips, duration, final}

A version's kind says where it came from:

kindmade
manualby you (Save version, Ctrl/Cmd+S) or an agent (fablecut_versions {action:"save"})
autoevery 10 minutes while the open project changes, whoever changes it (FABLECUT_AUTO_VERSION_MIN sets the minutes); the newest 30 are kept
agentbefore an agent's first edit of a session (again after 10 quiet minutes), and before every fablecut_set_project rewrite
restorewhat was there just before a restore

One version per project can be marked final (the cut that went out); a final version can't be deleted until it is unmarked. Manual, agent and restore versions are never pruned.

Compare tells what changed between a version and now (or two versions): clips added, removed and changed (timing, which props, keyframes, effects, transitions, source, track), media added and removed, the length, and project settings (name, canvas, frame rate, IN / OUT, tracks, markers, comps, mix, delivery, …).

Backup and recovery. Download backup saves a project with all its versions as one .fablecut-backup.json file; Import… in the dashboard brings it back, versions included. When project.json can't be read as the server starts (another tool crashed mid-write, a bad hand edit), the server keeps the broken file as project.corrupt-<time>.json and puts back the newest good copy: the latest version, or the project's last parked copy.

In the editor: Ctrl/Cmd+S saves a version of the open project. In the Projects dashboard, a project's Versions… lists its versions, newest first, with Save version (name and note), and per version Compare with now, Restore… (click twice), Mark final, Rename, Download and Delete… (click twice). Esc goes back to the projects.

Agents use fablecut_versions (or GET / POST /api/versions):

  • {} lists the open project's versions (project picks another one).
  • {action:"save", name?, note?, final?} - save one before a big or risky change (a restructure, a remake, a new grade on every shot) and when the user is happy with a cut, so there is a named point to go back to.
  • {action:"diff", version, to?} - what changed since that version (to now, or to version to). Use it to tell the user what an edit session changed.
  • {action:"restore", version} - only when the user asked; then re-read the project. {action:"update", version, name?, note?, final?} · {action:"delete", version}.

Recipes: try a bold alternative - save a version, make the change, compare, and restore if the user prefers the old one; client rounds - save "Round 1", "Round 2", … with the feedback in the note, mark the approved one final; what did the agent do? - diff against the "Before agent edits" version.

- +
diff --git a/docs/docs/workflows/index.html b/docs/docs/workflows/index.html new file mode 100644 index 000000000..5b14fdb95 --- /dev/null +++ b/docs/docs/workflows/index.html @@ -0,0 +1,126 @@ + + + + + +Workflows - FableCut docs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+

Workflows

+

Save a routine you want repeated - steps in plain words plus the tool calls that did them - and have an agent follow it on the next project.

+

A workflow is a recipe the user wants repeated on other projects: "my podcast clean-up", "the weekly reel", "client delivery". It is a name, what it is for, and its steps in order. Each step says in plain words what to do, and may carry the tool call that did it last time. Workflows are shared by every project, one JSON file each in library/workflows/<id>.json:

{ "id": "podcast-clean-up", "name": "Podcast clean-up",
+  "description": "Voice level, no dead air, captions, a Shorts cut.", "tags": ["podcast"],
+  "steps": [
+    { "text": "Reduce the room noise on the voice clips.",
+      "call": { "tool": "fablecut_denoise", "args": { "clipIds": ["c_vo"], "amount": "medium" } } },
+    { "text": "Normalize the voice to -16 LUFS.",
+      "call": { "tool": "fablecut_normalize_audio", "args": { "clipIds": ["c_vo"], "target": -16 } } },
+    { "text": "Cut the pauses longer than half a second, keeping the music bed running." },
+    { "text": "Export for YouTube Shorts.", "call": { "tool": "fablecut_export", "args": { "preset": "youtube-shorts" } } } ],
+  "created": "…", "updated": "…" }
keydoes
name · idup to 80 characters; the id is made from the name, and saving the same name again updates that workflow (it keeps its created)
description · tagswhat it is for (up to 600 characters) · up to 12 labels
steps1–50, each {text, call?} (a plain string is a step with only text); text up to 1000 characters
call{tool, args}: a FableCut tool (not fablecut_workflows) and the arguments it was given, up to 20 000 characters

Following one is a job for judgement, not a replay. The new project has other clips, ids and times, so a step's call is a worked example: read what the step says, look at the project (fablecut_get_project {compact:true}, fablecut_frame), and make the call that does that here. A step with no call is one only the agent's judgement can do ("pick the three strongest shots").

Agents use fablecut_workflows (or the REST endpoints below):

  • {} lists them (id, name, steps, tags, description); {action:"show", id} gives the steps to follow (id or name).
  • {action:"save", workflow:{name, description?, tags?, steps}} keeps one. Save when the user asks to keep or repeat what was just done: write each step the way you would explain it to another editor, and attach the calls that worked. A call to a tool that doesn't exist refuses the save.
  • {action:"delete", id} removes one: only when the user asks.

Recipes: "do what you did last week" - {}, then show the one that matches and do its steps; a house style for every episode - after the first episode is right, save its loudness, captions, grade and export steps as one workflow; hand a routine to another agent - the file in library/workflows/ is plain JSON any agent can read.

+ + +
+ +
+ + + + + + diff --git a/docs/index.html b/docs/index.html index aa08a01f8..86d8c1f99 100644 --- a/docs/index.html +++ b/docs/index.html @@ -69,6 +69,7 @@ "Media management: frame rate, codec, audio and size of every file, search, filters, sorting, favorites, tags, collections, usage counts, find-all-instances, offline detection, relink and replace; agents make folders, move and rename files and trash them into a restorable trash", "Projects dashboard: open, create from canvas presets or saved project templates, duplicate, rename, notes, tags, archive, delete and import projects", "Versions: non-destructive project history with automatic and agent versions, compare, restore, final cut, backups and crash recovery", + "Workflows: saved routines of steps and the tool calls that did them, which an agent follows again on the next project", "Sequences: several timelines in one project, each with its own canvas, frame rate, mix and delivery, sharing the media and compositions", "Proxy workflow: frame-accurate H.264 proxies of 4K / HEVC / ProRes footage made in the background; edit on proxies, export from the originals", "Animation presets and templates: entrances, exits and loops for any clip; lower thirds, logo animations and social layouts with editable fields", diff --git a/docs/llms.txt b/docs/llms.txt index 6fa16f5b1..3f0c93ce5 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -93,6 +93,9 @@ about 150 ms. A human and an agent can work the same timeline at once. changes, and before an agent edits); compare one with now, restore it (the current state is kept as a version first), mark the final cut; backups carry every version. Agents use `fablecut_versions`. +- Workflows: save a routine you want repeated (a podcast clean-up, the weekly + reel) as steps plus the tool calls that did them; an agent lists them and + follows one on the next project. Agents use `fablecut_workflows`. - Sequences: several timelines in one project (a 16:9 and a 9:16 cut, cut-downs, alternatives) sharing its media and compositions, each with its own canvas, frame rate, mix and delivery. Agents add, open and edit them with diff --git a/docs/sitemap.xml b/docs/sitemap.xml index 10f9c2909..b0864c679 100644 --- a/docs/sitemap.xml +++ b/docs/sitemap.xml @@ -132,6 +132,12 @@ monthly 0.6 + + https://fablecut.space/docs/workflows/ + 2026-11-20 + monthly + 0.6 + https://fablecut.space/docs/sequences/ 2026-10-21 diff --git a/manifest.json b/manifest.json index 42ff3c6f9..a4c85eaad 100644 --- a/manifest.json +++ b/manifest.json @@ -46,6 +46,7 @@ { "name": "fablecut_transcribe", "description": "Transcribe speech word by word in the browser, read it on the timeline, find a phrase and cut it out (text-based editing)" }, { "name": "fablecut_captions", "description": "Make captions from the transcript (subtitle, karaoke, word highlight, word pop), timed word by word; export or import SRT / WebVTT" }, { "name": "fablecut_proxy", "description": "Make, check or delete proxies: light copies of heavy footage the editor plays while editing (export always uses the originals)" }, + { "name": "fablecut_workflows", "description": "Save workflows (recipes of steps and the tool calls that did them) and follow them again on other projects" }, { "name": "fablecut_versions", "description": "Save, compare, restore and mark final versions of a project; restoring never loses the current state" }, { "name": "fablecut_projects", "description": "List, open, create, duplicate, rename, annotate, archive and delete projects; start new ones from canvas presets or saved project templates" }, { "name": "fablecut_export", "description": "Render the timeline to a video file with the editor's Fast export, in an open editor tab or a headless browser" }, diff --git a/mcp-server.js b/mcp-server.js index e385384d4..f3dde898e 100644 --- a/mcp-server.js +++ b/mcp-server.js @@ -38,6 +38,7 @@ const Motion = require("./motion"); const CompLib = require("./comp"); const SeqLib = require("./sequences"); const Templates = require("./templates"); +const Workflows = require("./workflows"); const Delivery = require("./delivery"); const { probeFile, infoForEntry } = require("./media-probe"); const { findProxies } = require("./proxy"); @@ -449,6 +450,27 @@ const TOOLS = [ }, }, }, + { + name: "fablecut_workflows", + description: "Saved workflows: recipes the user wants repeated on other projects (\"my podcast clean-up\", \"the weekly reel\"). A workflow is a name, what it is for, and its steps in order; each step says in plain words what to do and may carry the tool call that did it last time. Actions: list (default) · show {id} — the steps, to follow now · save {workflow:{name, description?, tags?, steps:[{text, call?:{tool, args}}]}} — keep one (the same name updates it) · delete {id} (only when the user asks). To run one: show it, then do each step yourself on the open project, using judgement where the footage differs (which clips, where cuts land); a step's call is a worked example, not a script, so change its ids and times to fit. Save one when the user asks to keep or repeat what you just did: write the steps the way you would explain them to another editor, and attach the calls that worked. Saved in library/workflows/, shared by every project.", + inputSchema: { + type: "object", + properties: { + action: { type: "string", enum: ["list", "show", "save", "delete"], description: "What to do (default list)" }, + id: { type: "string", description: "show / delete: the workflow's id or name" }, + workflow: { + type: "object", + description: "save: {name, description?, tags?, steps:[{text, call?:{tool, args}}]} (a step may also be a plain string)", + properties: { + name: { type: "string" }, + description: { type: "string" }, + tags: { type: "array", items: { type: "string" } }, + steps: { type: "array", items: { anyOf: [{ type: "string" }, { type: "object" }] } }, + }, + }, + }, + }, + }, { name: "fablecut_proxy", description: "Proxies: light H.264 copies (540p by default, 720p or 1080p; never larger than the source) of heavy footage — 4K, HEVC, ProRes, long phone clips — that the editor plays while the user edits, so playback and scrubbing stay smooth. Export, fablecut_frame, fablecut_scopes and every measurement always read the original, so a proxy never changes the result. Without create or delete it reports each video's proxy (ready, being made with its progress, failed, none). create:true makes them (one at a time, in the background on the server) and waits until they are done unless wait:false; delete:true removes them. mediaIds defaults to every video in the project. The user turns proxy playback on or off with the monitor's Proxy button. Needs ffmpeg on PATH.", @@ -1276,6 +1298,34 @@ async function projectsTool(args) { if (out.from) return `Opened ${describeProject(out.project)}\nThe editor switched to it (${out.from} was saved first). Read it with fablecut_get_project {compact:true} before editing.`; return describeProject(out.project); } +/* fablecut_workflows: saved recipes in library/workflows/, read and written here directly + (like saved presets), so it works without the editor server. */ +function savedWorkflows() { + return readSaved("workflows").map((x) => Workflows.normalizeWorkflow(x.data)).filter(Boolean); +} +function workflowsTool(args) { + const action = args.action || "list", all = savedWorkflows(); + if (action === "list") return all.length + ? [`${all.length} saved workflow(s) — {action:"show", id} gives the steps:`, ...all.map(Workflows.workflowLine)].join("\n") + : "No saved workflows yet. When the user wants something you did kept for next time, save it: {action:\"save\", workflow:{name, description, steps:[{text, call?}]}}."; + if (action === "show" || action === "delete") { + const w = Workflows.findWorkflow(all, args.id); + if (!w) throw new Error(`no workflow "${args.id || ""}"` + (all.length ? ` — saved: ${all.map((x) => x.id).join(", ")}` : " — none saved yet")); + if (action === "show") return Workflows.describeWorkflow(w) + + "\n\nDo each step on the open project. A \"last time\" call is an example: fit its ids, times and values to this project."; + fs.rmSync(path.join(LIBRARY_DIR, "workflows", w.id + ".json"), { force: true }); + return `Deleted workflow "${w.name}" (${w.id}).`; + } + if (action === "save") { + const w = Workflows.normalizeWorkflow(args.workflow, true, TOOLS.map((t) => t.name)); + const prev = all.find((x) => x.id === w.id), now = new Date().toISOString(); + const item = { ...w, created: prev && prev.created || now, updated: now }; + writeSaved("workflows", item.id, item); + return `${prev ? "Updated" : "Saved"} workflow "${item.name}" (${item.id}), ${item.steps.length} step(s), in library/workflows/${item.id}.json. {action:"show", id:"${item.id}"} reads it back.`; + } + throw new Error(`unknown action "${action}" — list, show, save or delete`); +} + /* fablecut_versions: through the editor server, like fablecut_projects. */ const KIND_LABEL = { manual: "", auto: " (auto)", agent: " (before agent edits)", restore: " (before a restore)" }; function describeVersion(e) { @@ -1665,6 +1715,8 @@ async function callTool(name, args, attempt = 0) { return projectsTool(args); case "fablecut_versions": return versionsTool(args); + case "fablecut_workflows": + return workflowsTool(args); case "fablecut_status": { const up = await ensureUIServer(); const proj = readProject(); diff --git a/paths.js b/paths.js index e75ba0caa..9cd9e1adb 100644 --- a/paths.js +++ b/paths.js @@ -40,7 +40,7 @@ const FRAMES_DIR = path.join(ANALYSIS_DIR, "frames"); A regenerable cache too, so also inside analysis/. */ const PROXIES_DIR = path.join(ANALYSIS_DIR, "proxies"); const PROJECT_FILE = path.join(DATA_DIR, "project.json"); -const LIBRARY_SUBDIRS = ["sfx", "elements", "svg", "fonts", "presets", "templates"]; +const LIBRARY_SUBDIRS = ["sfx", "elements", "svg", "fonts", "presets", "templates", "workflows"]; /* The asset library ships with the repo but users also drop their own files in (library/sfx is gitignored precisely for that). When the data dir is split @@ -106,8 +106,9 @@ function ensureDirs() { seedLibrary(); } -/* Saved animation presets and templates: one JSON file each in library/presets/ - and library/templates/ (templates.js validates them). Unreadable files are skipped. */ +/* Saved animation presets, templates and workflows: one JSON file each in library/presets/, + library/templates/ and library/workflows/ (templates.js / workflows.js validate them). + Unreadable files are skipped. */ function readSaved(kind) { const dir = path.join(LIBRARY_DIR, kind); let names = []; diff --git a/server.js b/server.js index 1bbfaa709..b2d6147e7 100644 --- a/server.js +++ b/server.js @@ -43,6 +43,7 @@ const { PROJECT_FILE, LIBRARY_SUBDIRS, FRAMES_DIR, PROXIES_DIR, ensureDirs, readSaved, writeSaved, } = require("./paths"); const Templates = require("./templates"); +const Workflows = require("./workflows"); const { probeFile } = require("./media-probe"); const MediaLib = require("./media-lib"); const { createProxies } = require("./proxy"); @@ -384,6 +385,15 @@ function deliveryEncoders() { return deliveryEncodersP; } /** Saved delivery presets: library/delivery/.json, each a spec plus a label. */ +/** Validate and save a workflow; one with the same id keeps its created date. */ +function saveWorkflow(input, all) { + const w = Workflows.normalizeWorkflow(input, true); + const prev = all.find((x) => x.id === w.id); + const now = new Date().toISOString(); + const item = { ...w, created: prev && prev.created || now, updated: now }; + writeSaved("workflows", item.id, item); + return item; +} function savedDeliveryPresets() { return Delivery.savedPresets(readSaved("delivery")); } /* One render, several files: `deliveries:[{delivery, name}, …]` (up to 8) or a single `delivery` + name. Every output gets its own ffmpeg, fed the same @@ -867,7 +877,7 @@ const server = http.createServer(async (req, res) => { for (const e of list) { if (e.name.startsWith(".")) continue; const full = path.join(d, e.name); - if (e.isDirectory()) { if (depth < 6 && !(root === LIBRARY_DIR && /^(presets|templates|fonts)$/.test(e.name) && depth === 0)) walk(root, prefix, full, depth + 1); continue; } + if (e.isDirectory()) { if (depth < 6 && !(root === LIBRARY_DIR && /^(presets|templates|workflows|fonts)$/.test(e.name) && depth === 0)) walk(root, prefix, full, depth + 1); continue; } let size = 0; try { size = fs.statSync(full).size; } catch { continue; } const rel = path.relative(root, full).split(path.sep).map(encodeURIComponent).join("/"); @@ -1114,6 +1124,36 @@ const server = http.createServer(async (req, res) => { return; } + /* API: saved workflows (library/workflows) — recipes an agent repeats on another project. + GET /api/workflows → [ …validated workflows… ] (bad files skipped) + GET /api/workflows?id= → one, or 404 + POST /api/workflows {workflow} → saved as library/workflows/.json (same id: updated) + POST /api/workflows/delete {id} */ + if (p === "/api/workflows" || p === "/api/workflows/delete") { + try { + const all = readSaved("workflows").map((x) => Workflows.normalizeWorkflow(x.data)).filter(Boolean); + if (req.method === "GET" && p === "/api/workflows") { + const id = url.searchParams.get("id"); + if (id == null) { sendJSON(res, 200, all); return; } + const w = Workflows.findWorkflow(all, id); + if (w) sendJSON(res, 200, w); else sendJSON(res, 404, { error: `no workflow "${id}"` }); + return; + } + if (req.method !== "POST") { sendJSON(res, 405, { error: "GET or POST" }); return; } + const body = JSON.parse((await readBody(req)).toString("utf8") || "{}"); + if (p === "/api/workflows/delete") { + const w = Workflows.findWorkflow(all, body.id); + if (!w) { sendJSON(res, 404, { error: `no workflow "${body.id}"` }); return; } + fs.rmSync(path.join(LIBRARY_DIR, "workflows", w.id + ".json"), { force: true }); + sendJSON(res, 200, { deleted: w.id }); + return; + } + const item = saveWorkflow(body.workflow, all); + sendJSON(res, 200, item); + } catch (e) { sendJSON(res, 400, { error: String(e.message || e) }); } + return; + } + /* API: upload → saved into ./media */ if (p === "/api/upload" && req.method === "POST") { try { diff --git a/test/workflows.test.js b/test/workflows.test.js new file mode 100644 index 000000000..17a7de794 --- /dev/null +++ b/test/workflows.test.js @@ -0,0 +1,98 @@ +/* Saved workflows (workflows.js, /api/workflows, fablecut_workflows): recipes of + plain-language steps, each with the tool call that did it, kept in + library/workflows/ for an agent to follow again on another project. */ +"use strict"; +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const W = require("../workflows"); +const { makeDataDir, startServer, startMcp } = require("./helpers"); + +const podcast = { + name: "Podcast clean-up", + description: "Voice level, no dead air, captions, a Shorts cut.", + tags: ["podcast", "audio"], + steps: [ + { text: "Reduce the room noise on the voice clips.", call: { tool: "fablecut_denoise", args: { clipIds: ["c_vo"], amount: "medium" } } }, + { text: "Normalize the voice to -16 LUFS.", call: { tool: "fablecut_normalize_audio", args: { clipIds: ["c_vo"], target: -16 } } }, + "Cut the pauses longer than half a second.", + { text: "Export for YouTube Shorts.", call: { tool: "fablecut_export", args: { preset: "youtube-shorts" } } }, + ], +}; + +test("normalizeWorkflow: an id from the name, plain-string steps, calls kept as given", () => { + const w = W.normalizeWorkflow(podcast, true); + assert.equal(w.id, "podcast-clean-up"); + assert.equal(w.steps.length, 4); + assert.deepEqual(w.steps[2], { text: "Cut the pauses longer than half a second." }); + assert.deepEqual(w.steps[1].call, { tool: "fablecut_normalize_audio", args: { clipIds: ["c_vo"], target: -16 } }); + assert.deepEqual(w.tags, ["podcast", "audio"]); +}); + +test("normalizeWorkflow refuses what it can't keep, and reading skips bad files instead", () => { + const bad = [ + [{ steps: ["x"] }, /name is required/], + [{ name: "x", steps: [] }, /at least one step/], + [{ name: "x", steps: [{ text: "" }] }, /step 1: text is required/], + [{ name: "x", steps: [{ text: "a", call: { tool: "rm", args: {} } }] }, /not a FableCut tool/], + [{ name: "x", steps: [{ text: "a", call: { tool: "fablecut_workflows" } }] }, /not a FableCut tool/], + [{ name: "x", steps: [{ text: "a", call: { tool: "fablecut_export", args: [1] } }] }, /args is an object/], + [{ name: "x", steps: Array(51).fill("a") }, /at most 50 steps/], + [{ name: "x".repeat(81), steps: ["a"] }, /longer than 80/], + ]; + for (const [w, re] of bad) { + assert.throws(() => W.normalizeWorkflow(w, true), re); + assert.equal(W.normalizeWorkflow(w), null); + } + // a known-tools list narrows calls to the tools that exist + assert.throws(() => W.normalizeWorkflow({ name: "x", steps: [{ text: "a", call: { tool: "fablecut_nope" } }] }, true, ["fablecut_export"]), /not a FableCut tool/); +}); + +test("findWorkflow by id or name; describeWorkflow lists the steps with last time's calls", () => { + const all = [W.normalizeWorkflow(podcast)]; + assert.equal(W.findWorkflow(all, "podcast-clean-up").id, "podcast-clean-up"); + assert.equal(W.findWorkflow(all, "Podcast Clean-up").id, "podcast-clean-up"); + assert.equal(W.findWorkflow(all, "nope"), null); + const text = W.describeWorkflow(all[0]); + assert.match(text, /^Workflow "Podcast clean-up" \(podcast-clean-up\) #podcast #audio/); + assert.match(text, /2\. Normalize the voice to -16 LUFS\.\n {3}last time: fablecut_normalize_audio \{"clipIds":\["c_vo"\],"target":-16\}/); + assert.match(text, /3\. Cut the pauses longer than half a second\.\n4\./); + assert.match(W.workflowLine(all[0]), /^podcast-clean-up — "Podcast clean-up", 4 steps #podcast #audio: Voice level/); +}); + +test("/api/workflows and fablecut_workflows: save, list, show, update keeps created, delete", async (t) => { + const dir = makeDataDir(t); + const { base, port } = await startServer(t, dir, { FABLECUT_NO_FS_WATCH: "1" }); + const post = (p, body) => fetch(base + p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + + const saved = await (await post("/api/workflows", { workflow: podcast })).json(); + assert.equal(saved.id, "podcast-clean-up"); + assert.ok(saved.created && saved.updated); + const file = path.join(dir, "library", "workflows", "podcast-clean-up.json"); + assert.ok(fs.existsSync(file)); + assert.equal((await post("/api/workflows", { workflow: { name: "x", steps: [] } })).status, 400); + // a broken file in the folder is skipped, not fatal + fs.writeFileSync(path.join(dir, "library", "workflows", "broken.json"), "{ nope"); + const list = await (await fetch(base + "/api/workflows")).json(); + assert.deepEqual(list.map((w) => w.id), ["podcast-clean-up"]); + assert.equal((await fetch(base + "/api/workflows?id=Podcast%20clean-up")).status, 200); + assert.equal((await fetch(base + "/api/workflows?id=nope")).status, 404); + + const mcp = startMcp(t, dir, { FABLECUT_PORT: String(port), FABLECUT_NO_AUTOSTART: "1" }); + const text = async (args) => (await mcp.callTool("fablecut_workflows", args)).content[0].text; + assert.match(await text({}), /1 saved workflow\(s\)[^\n]*\npodcast-clean-up — "Podcast clean-up", 4 steps/); + assert.match(await text({ action: "show", id: "podcast-clean-up" }), /1\. Reduce the room noise[\s\S]*fit its ids, times and values/); + const upd = await text({ action: "save", workflow: { ...podcast, steps: [...podcast.steps, "Add highlight captions."] } }); + assert.match(upd, /^Updated workflow "Podcast clean-up" \(podcast-clean-up\), 5 step\(s\)/); + const after = JSON.parse(fs.readFileSync(file, "utf8")); + assert.equal(after.created, saved.created, "an update keeps when it was first saved"); + assert.equal(after.steps.length, 5); + const refused = await mcp.callTool("fablecut_workflows", { action: "save", workflow: { name: "y", steps: [{ text: "a", call: { tool: "fablecut_nope" } }] } }); + assert.equal(refused.isError, true); + assert.match(refused.content[0].text, /not a FableCut tool/); + assert.match(await text({ action: "delete", id: "Podcast clean-up" }), /Deleted workflow "Podcast clean-up"/); + assert.ok(!fs.existsSync(file)); + assert.match(await text({}), /No saved workflows yet/); + assert.equal((await post("/api/workflows/delete", { id: "podcast-clean-up" })).status, 404); +}); diff --git a/workflows.js b/workflows.js new file mode 100644 index 000000000..4c3dd15ba --- /dev/null +++ b/workflows.js @@ -0,0 +1,95 @@ +/* FableCut saved workflows. Zero dependencies. Required by the server, the MCP + server and the tests. + + A WORKFLOW is a recipe an agent can repeat on another project: a name, what + it is for, and its steps in order. Each step is plain language ("Normalize the + voice to -16 LUFS"), and may carry the tool call that did it last time: + { id, name, description?, tags?, steps: [{ text, call?: { tool, args } }], created, updated } + The agent reads the steps and does them again, using its own judgement where + the footage differs (which clips, where the cuts go); a call is a worked + example, not a script to replay blindly. Saved as library/workflows/.json, + shared by every project. */ +"use strict"; + +const LIMITS = { name: 80, description: 600, step: 1000, steps: 50, tags: 12, tag: 32, args: 20000 }; +const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60); +const clean = (s) => String(s == null ? "" : s).replace(/\r\n?/g, "\n").trim(); + +/** A checked copy of a workflow. strict: throw on anything wrong (saving); + * otherwise return null (reading files, where a bad one is skipped). + * tools: the tool names a call may use (default: any fablecut_ tool but this one). */ +function normalizeWorkflow(w, strict, tools) { + const bad = (msg) => { if (strict) throw new Error("workflow: " + msg); return null; }; + if (!w || typeof w !== "object" || Array.isArray(w)) return bad("expected an object {name, steps}"); + const name = clean(w.name); + if (!name) return bad("name is required"); + if (name.length > LIMITS.name) return bad(`name is longer than ${LIMITS.name} characters`); + const id = slug(w.id || name); + if (!id) return bad("name needs a letter or digit"); + const description = clean(w.description); + if (description.length > LIMITS.description) return bad(`description is longer than ${LIMITS.description} characters`); + if (!Array.isArray(w.steps) || !w.steps.length) return bad("steps: at least one step"); + if (w.steps.length > LIMITS.steps) return bad(`at most ${LIMITS.steps} steps`); + const steps = []; + for (let i = 0; i < w.steps.length; i++) { + const s = typeof w.steps[i] === "string" ? { text: w.steps[i] } : w.steps[i]; + const at = `step ${i + 1}`; + if (!s || typeof s !== "object") return bad(`${at}: expected {text, call?}`); + const text = clean(s.text); + if (!text) return bad(`${at}: text is required (say what the step does)`); + if (text.length > LIMITS.step) return bad(`${at}: text is longer than ${LIMITS.step} characters`); + const step = { text }; + if (s.call != null) { + const c = s.call; + if (typeof c !== "object" || Array.isArray(c)) return bad(`${at}: call is {tool, args}`); + const tool = String(c.tool || ""); + const allowed = tools ? tools.includes(tool) : /^fablecut_[a-z_]+$/.test(tool); + if (!allowed || tool === "fablecut_workflows") return bad(`${at}: call.tool "${tool}" is not a FableCut tool${tools ? " (" + tools.join(", ") + ")" : ""}`); + const args = c.args == null ? {} : c.args; + if (typeof args !== "object" || Array.isArray(args)) return bad(`${at}: call.args is an object`); + if (JSON.stringify(args).length > LIMITS.args) return bad(`${at}: call.args is larger than ${LIMITS.args} characters`); + step.call = { tool, args: JSON.parse(JSON.stringify(args)) }; + } + steps.push(step); + } + const out = { id, name }; + if (description) out.description = description; + if (w.tags != null) { + if (!Array.isArray(w.tags)) return bad("tags is a list of words"); + const tags = [...new Set(w.tags.map(clean).filter(Boolean))]; + if (tags.length > LIMITS.tags) return bad(`at most ${LIMITS.tags} tags`); + if (tags.some((t) => t.length > LIMITS.tag)) return bad(`a tag is longer than ${LIMITS.tag} characters`); + if (tags.length) out.tags = tags; + } + out.steps = steps; + if (typeof w.created === "string") out.created = w.created; + if (typeof w.updated === "string") out.updated = w.updated; + return out; +} + +/** Find a saved workflow by id or name (case-insensitive). */ +function findWorkflow(list, key) { + const k = String(key || "").trim().toLowerCase(); + if (!k) return null; + return list.find((w) => w.id === k) || list.find((w) => w.name.toLowerCase() === k) || list.find((w) => w.id === slug(k)) || null; +} + +/** One line per workflow, for listings. */ +function workflowLine(w) { + return `${w.id} — "${w.name}", ${w.steps.length} step${w.steps.length === 1 ? "" : "s"}` + + (w.tags ? ` #${w.tags.join(" #")}` : "") + (w.description ? `: ${w.description.length > 140 ? w.description.slice(0, 140) + "…" : w.description}` : ""); +} + +/** The whole workflow as text an agent follows. */ +function describeWorkflow(w) { + const lines = [`Workflow "${w.name}" (${w.id})` + (w.tags ? ` #${w.tags.join(" #")}` : "")]; + if (w.description) lines.push(w.description); + lines.push(""); + w.steps.forEach((s, i) => { + lines.push(`${i + 1}. ${s.text}`); + if (s.call) lines.push(` last time: ${s.call.tool} ${JSON.stringify(s.call.args)}`); + }); + return lines.join("\n"); +} + +module.exports = { LIMITS, slug, normalizeWorkflow, findWorkflow, workflowLine, describeWorkflow }; From 35c755f0c36ae41532e280f40f71cdd419b55a4a Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:06:16 +0530 Subject: [PATCH 2/6] Workflows: same tool check on REST and MCP, stable ids, skip odd files CodeRabbit on #168: - REST saves check step calls against the MCP tools (read from manifest.json, which now ships in the npm package), like fablecut_workflows - POST reads the saved workflows after the body, so an interleaved save can't reset another's created date - slugs are trimmed after the 60-character cut, so an id is stable when read back; delete removes the file a workflow came from - a field that isn't text refuses a save and skips that file when reading, instead of failing the whole listing --- mcp-server.js | 4 ++-- package.json | 1 + server.js | 19 ++++++++++++++++--- test/npm-package.test.js | 2 +- test/workflows.test.js | 36 ++++++++++++++++++++++++++++++++++++ workflows.js | 39 +++++++++++++++++++++++++++++++++++---- 6 files changed, 91 insertions(+), 10 deletions(-) diff --git a/mcp-server.js b/mcp-server.js index f3dde898e..da9e0d320 100644 --- a/mcp-server.js +++ b/mcp-server.js @@ -1301,7 +1301,7 @@ async function projectsTool(args) { /* fablecut_workflows: saved recipes in library/workflows/, read and written here directly (like saved presets), so it works without the editor server. */ function savedWorkflows() { - return readSaved("workflows").map((x) => Workflows.normalizeWorkflow(x.data)).filter(Boolean); + return Workflows.fromFiles(readSaved("workflows")); } function workflowsTool(args) { const action = args.action || "list", all = savedWorkflows(); @@ -1313,7 +1313,7 @@ function workflowsTool(args) { if (!w) throw new Error(`no workflow "${args.id || ""}"` + (all.length ? ` — saved: ${all.map((x) => x.id).join(", ")}` : " — none saved yet")); if (action === "show") return Workflows.describeWorkflow(w) + "\n\nDo each step on the open project. A \"last time\" call is an example: fit its ids, times and values to this project."; - fs.rmSync(path.join(LIBRARY_DIR, "workflows", w.id + ".json"), { force: true }); + fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(w.file || w.id + ".json")), { force: true }); return `Deleted workflow "${w.name}" (${w.id}).`; } if (action === "save") { diff --git a/package.json b/package.json index f5aca0853..08f1e0f69 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "favicon.svg", "icons/", "encoding-profiles.json", + "manifest.json", "CLAUDE.md", "library/README.md", "library/elements/", diff --git a/server.js b/server.js index f33b99ca5..9189938ab 100644 --- a/server.js +++ b/server.js @@ -385,9 +385,20 @@ function deliveryEncoders() { return deliveryEncodersP; } /** Saved delivery presets: library/delivery/.json, each a spec plus a label. */ +/* The tools a workflow step may call: the MCP server's, as manifest.json lists them + (the same list fablecut_workflows checks against). */ +let workflowTools; +function workflowToolNames() { + if (workflowTools === undefined) { + try { workflowTools = Workflows.manifestTools(JSON.parse(fs.readFileSync(path.join(APP_DIR, "manifest.json"), "utf8"))); } + catch { workflowTools = null; } + } + return workflowTools || undefined; +} +const savedWorkflows = () => Workflows.fromFiles(readSaved("workflows")); /** Validate and save a workflow; one with the same id keeps its created date. */ function saveWorkflow(input, all) { - const w = Workflows.normalizeWorkflow(input, true); + const w = Workflows.normalizeWorkflow(input, true, workflowToolNames()); const prev = all.find((x) => x.id === w.id); const now = new Date().toISOString(); const item = { ...w, created: prev && prev.created || now, updated: now }; @@ -1146,8 +1157,8 @@ const server = http.createServer(async (req, res) => { POST /api/workflows/delete {id} */ if (p === "/api/workflows" || p === "/api/workflows/delete") { try { - const all = readSaved("workflows").map((x) => Workflows.normalizeWorkflow(x.data)).filter(Boolean); if (req.method === "GET" && p === "/api/workflows") { + const all = savedWorkflows(); const id = url.searchParams.get("id"); if (id == null) { sendJSON(res, 200, all); return; } const w = Workflows.findWorkflow(all, id); @@ -1156,10 +1167,12 @@ const server = http.createServer(async (req, res) => { } if (req.method !== "POST") { sendJSON(res, 405, { error: "GET or POST" }); return; } const body = JSON.parse((await readBody(req)).toString("utf8") || "{}"); + // read now, after the body: another save may have landed while it arrived + const all = savedWorkflows(); if (p === "/api/workflows/delete") { const w = Workflows.findWorkflow(all, body.id); if (!w) { sendJSON(res, 404, { error: `no workflow "${body.id}"` }); return; } - fs.rmSync(path.join(LIBRARY_DIR, "workflows", w.id + ".json"), { force: true }); + fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(w.file || w.id + ".json")), { force: true }); sendJSON(res, 200, { deleted: w.id }); return; } diff --git a/test/npm-package.test.js b/test/npm-package.test.js index 01548ef32..8bf485cb8 100644 --- a/test/npm-package.test.js +++ b/test/npm-package.test.js @@ -33,7 +33,7 @@ test("package.json exposes the command and ships the files it runs from", () => (p.endsWith("/") && f.startsWith(p))); for (const [, f] of html.matchAll(/(?:src|href)="\/?([^"#:?]+)"/g)) assert.ok(shipped(f), `index.html loads ${f}, which the npm package would not ship`); - for (const f of ["server.js", "mcp-server.js", "CLAUDE.md", "encoding-profiles.json"]) + for (const f of ["server.js", "mcp-server.js", "CLAUDE.md", "encoding-profiles.json", "manifest.json"]) assert.ok(shipped(f), `${f} must ship`); }); diff --git a/test/workflows.test.js b/test/workflows.test.js index 17a7de794..361e39c99 100644 --- a/test/workflows.test.js +++ b/test/workflows.test.js @@ -96,3 +96,39 @@ test("/api/workflows and fablecut_workflows: save, list, show, update keeps crea assert.match(await text({}), /No saved workflows yet/); assert.equal((await post("/api/workflows/delete", { id: "podcast-clean-up" })).status, 404); }); + +test("slug is stable after the cut, odd field types are refused (or skipped when reading), files are remembered", () => { + const long = "a".repeat(59) + " b"; + const id = W.slug(long); + assert.ok(!id.endsWith("-"), id); + assert.equal(W.slug(id), id, "a slug of the slug is the same slug"); + const odd = { name: { toString: null }, steps: ["Inspect"] }; + assert.throws(() => W.normalizeWorkflow(odd, true), /name is text/); + assert.equal(W.normalizeWorkflow(odd), null, "reading: skipped, not thrown"); + assert.throws(() => W.normalizeWorkflow({ name: "x", steps: [{ text: { a: 1 } }] }, true), /step 1: text is text/); + assert.throws(() => W.normalizeWorkflow({ name: "x", tags: [{}], steps: ["a"] }, true), /tags are words/); + const list = W.fromFiles([{ file: "old-name.json", data: podcast }, { file: "odd.json", data: odd }, { file: "x.json", data: null }]); + assert.deepEqual(list.map((w) => w.id), ["podcast-clean-up"]); + assert.equal(list[0].file, "old-name.json"); + assert.ok(!JSON.stringify(list[0]).includes("old-name"), "the file stays out of JSON"); + assert.deepEqual(W.manifestTools({ tools: [{ name: "fablecut_export" }, {}] }), ["fablecut_export"]); + assert.equal(W.manifestTools({}), null); +}); + +test("REST checks calls against the real tools, and deletes a workflow saved under another file name", async (t) => { + const dir = makeDataDir(t); + const { base } = await startServer(t, dir, { FABLECUT_NO_FS_WATCH: "1" }); + const post = (p, body) => fetch(base + p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + const nope = await post("/api/workflows", { workflow: { name: "x", steps: [{ text: "a", call: { tool: "fablecut_nope" } }] } }); + assert.equal(nope.status, 400); + assert.match((await nope.json()).error, /not a FableCut tool/); + assert.equal((await post("/api/workflows", { workflow: { name: "y", steps: [{ text: "a", call: { tool: "fablecut_export" } }] } })).status, 200); + // a file whose name isn't its id (an older save, or written by hand) + const wdir = path.join(dir, "library", "workflows"); + fs.writeFileSync(path.join(wdir, "hand-made.json"), JSON.stringify({ name: "Hand made", steps: ["Do it"] })); + assert.equal((await post("/api/workflows/delete", { id: "hand-made" })).status, 200); + assert.ok(!fs.existsSync(path.join(wdir, "hand-made.json"))); + fs.writeFileSync(path.join(wdir, "renamed.json"), JSON.stringify({ name: "Other name", steps: ["Do it"] })); + assert.equal((await post("/api/workflows/delete", { id: "Other name" })).status, 200); + assert.ok(!fs.existsSync(path.join(wdir, "renamed.json")), "deleted by the file it came from"); +}); diff --git a/workflows.js b/workflows.js index 4c3dd15ba..f2854ca4e 100644 --- a/workflows.js +++ b/workflows.js @@ -12,21 +12,30 @@ "use strict"; const LIMITS = { name: 80, description: 600, step: 1000, steps: 50, tags: 12, tag: 32, args: 20000 }; -const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60); -const clean = (s) => String(s == null ? "" : s).replace(/\r\n?/g, "\n").trim(); +// trimmed again after the cut, so a slug of a slug is the same slug (the file name is the id) +const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 60).replace(/^-+|-+$/g, ""); +/** A text field as a trimmed string; "" when absent; null when it isn't text at all. */ +const clean = (s) => (s == null ? "" : typeof s === "string" || typeof s === "number" ? String(s).replace(/\r\n?/g, "\n").trim() : null); /** A checked copy of a workflow. strict: throw on anything wrong (saving); * otherwise return null (reading files, where a bad one is skipped). * tools: the tool names a call may use (default: any fablecut_ tool but this one). */ function normalizeWorkflow(w, strict, tools) { + if (strict) return checkWorkflow(w, true, tools); + // reading files: anything odd in one skips that file, never the whole listing + try { return checkWorkflow(w, false, tools); } catch { return null; } +} +function checkWorkflow(w, strict, tools) { const bad = (msg) => { if (strict) throw new Error("workflow: " + msg); return null; }; if (!w || typeof w !== "object" || Array.isArray(w)) return bad("expected an object {name, steps}"); const name = clean(w.name); + if (name === null) return bad("name is text"); if (!name) return bad("name is required"); if (name.length > LIMITS.name) return bad(`name is longer than ${LIMITS.name} characters`); - const id = slug(w.id || name); + const id = slug(typeof w.id === "string" && w.id ? w.id : name); if (!id) return bad("name needs a letter or digit"); const description = clean(w.description); + if (description === null) return bad("description is text"); if (description.length > LIMITS.description) return bad(`description is longer than ${LIMITS.description} characters`); if (!Array.isArray(w.steps) || !w.steps.length) return bad("steps: at least one step"); if (w.steps.length > LIMITS.steps) return bad(`at most ${LIMITS.steps} steps`); @@ -36,6 +45,7 @@ function normalizeWorkflow(w, strict, tools) { const at = `step ${i + 1}`; if (!s || typeof s !== "object") return bad(`${at}: expected {text, call?}`); const text = clean(s.text); + if (text === null) return bad(`${at}: text is text`); if (!text) return bad(`${at}: text is required (say what the step does)`); if (text.length > LIMITS.step) return bad(`${at}: text is longer than ${LIMITS.step} characters`); const step = { text }; @@ -56,6 +66,7 @@ function normalizeWorkflow(w, strict, tools) { if (description) out.description = description; if (w.tags != null) { if (!Array.isArray(w.tags)) return bad("tags is a list of words"); + if (w.tags.some((t) => clean(t) === null)) return bad("tags are words"); const tags = [...new Set(w.tags.map(clean).filter(Boolean))]; if (tags.length > LIMITS.tags) return bad(`at most ${LIMITS.tags} tags`); if (tags.some((t) => t.length > LIMITS.tag)) return bad(`a tag is longer than ${LIMITS.tag} characters`); @@ -67,6 +78,26 @@ function normalizeWorkflow(w, strict, tools) { return out; } +/** The workflows in readSaved("workflows") entries ({file, data}); bad files are skipped. Each + * remembers the file it came from (not enumerable, so it never shows in JSON), so delete + * removes that file even when its name isn't exactly the id. */ +function fromFiles(entries) { + const out = []; + for (const x of entries || []) { + const w = normalizeWorkflow(x && x.data); + if (!w) continue; + Object.defineProperty(w, "file", { value: x.file, enumerable: false }); + out.push(w); + } + return out; +} + +/** The tool names in a .mcpb manifest ({tools:[{name}]}), or null when it can't be read. */ +function manifestTools(manifest) { + const t = manifest && Array.isArray(manifest.tools) ? manifest.tools.map((x) => x && x.name).filter((n) => typeof n === "string") : []; + return t.length ? t : null; +} + /** Find a saved workflow by id or name (case-insensitive). */ function findWorkflow(list, key) { const k = String(key || "").trim().toLowerCase(); @@ -92,4 +123,4 @@ function describeWorkflow(w) { return lines.join("\n"); } -module.exports = { LIMITS, slug, normalizeWorkflow, findWorkflow, workflowLine, describeWorkflow }; +module.exports = { LIMITS, slug, normalizeWorkflow, fromFiles, manifestTools, findWorkflow, workflowLine, describeWorkflow }; From 166f5f3c46b9e382bec2d28675b751830dbb14bd Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:57:58 +0530 Subject: [PATCH 3/6] Workflows: an update moves a workflow kept under another file name to .json, so one workflow stays one file --- mcp-server.js | 1 + server.js | 1 + test/workflows.test.js | 24 ++++++++++++++++++++++++ workflows.js | 8 +++++++- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/mcp-server.js b/mcp-server.js index da9e0d320..9543c7d23 100644 --- a/mcp-server.js +++ b/mcp-server.js @@ -1321,6 +1321,7 @@ function workflowsTool(args) { const prev = all.find((x) => x.id === w.id), now = new Date().toISOString(); const item = { ...w, created: prev && prev.created || now, updated: now }; writeSaved("workflows", item.id, item); + for (const f of Workflows.staleFiles(all, item.id)) fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(f)), { force: true }); return `${prev ? "Updated" : "Saved"} workflow "${item.name}" (${item.id}), ${item.steps.length} step(s), in library/workflows/${item.id}.json. {action:"show", id:"${item.id}"} reads it back.`; } throw new Error(`unknown action "${action}" — list, show, save or delete`); diff --git a/server.js b/server.js index 9189938ab..ab52b7ee8 100644 --- a/server.js +++ b/server.js @@ -403,6 +403,7 @@ function saveWorkflow(input, all) { const now = new Date().toISOString(); const item = { ...w, created: prev && prev.created || now, updated: now }; writeSaved("workflows", item.id, item); + for (const f of Workflows.staleFiles(all, item.id)) fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(f)), { force: true }); return item; } function savedDeliveryPresets() { return Delivery.savedPresets(readSaved("delivery")); } diff --git a/test/workflows.test.js b/test/workflows.test.js index 361e39c99..02b6a63b3 100644 --- a/test/workflows.test.js +++ b/test/workflows.test.js @@ -132,3 +132,27 @@ test("REST checks calls against the real tools, and deletes a workflow saved und assert.equal((await post("/api/workflows/delete", { id: "Other name" })).status, 200); assert.ok(!fs.existsSync(path.join(wdir, "renamed.json")), "deleted by the file it came from"); }); + +test("updating a workflow kept under another file name leaves one file; deleting it then removes it for good", async (t) => { + const dir = makeDataDir(t); + const { base, port } = await startServer(t, dir, { FABLECUT_NO_FS_WATCH: "1" }); + const post = (p, body) => fetch(base + p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + const wdir = path.join(dir, "library", "workflows"); + fs.mkdirSync(wdir, { recursive: true }); + const files = () => fs.readdirSync(wdir).sort(); + fs.writeFileSync(path.join(wdir, "renamed.json"), JSON.stringify({ name: "Other name", steps: ["Old step"], created: "2026-01-01T00:00:00.000Z" })); + const up = await (await post("/api/workflows", { workflow: { name: "Other name", steps: ["New step"] } })).json(); + assert.equal(up.created, "2026-01-01T00:00:00.000Z", "created kept"); + assert.deepEqual(files(), ["other-name.json"], "the old file went with the update"); + assert.equal((await post("/api/workflows/delete", { id: "other-name" })).status, 200); + assert.deepEqual(files(), []); + assert.deepEqual(await (await fetch(base + "/api/workflows")).json(), [], "the old steps don't come back"); + // the same through MCP; and a normal id-named save stays one file + fs.writeFileSync(path.join(wdir, "renamed.json"), JSON.stringify({ name: "Other name", steps: ["Old step"] })); + const mcp = startMcp(t, dir, { FABLECUT_PORT: String(port), FABLECUT_NO_AUTOSTART: "1" }); + await mcp.callTool("fablecut_workflows", { action: "save", workflow: { name: "Other name", steps: ["New step"] } }); + await mcp.callTool("fablecut_workflows", { action: "save", workflow: { name: "Other name", steps: ["Newer step"] } }); + assert.deepEqual(files(), ["other-name.json"]); + assert.match((await mcp.callTool("fablecut_workflows", { action: "delete", id: "other-name" })).content[0].text, /Deleted/); + assert.deepEqual(files(), []); +}); diff --git a/workflows.js b/workflows.js index f2854ca4e..ccda6e665 100644 --- a/workflows.js +++ b/workflows.js @@ -92,6 +92,12 @@ function fromFiles(entries) { return out; } +/** After saving workflow `id` as .json: the other files that held that id (an older or + * hand-written file under another name), to remove so one workflow stays one file. */ +function staleFiles(all, id) { + return all.filter((w) => w.id === id && w.file && w.file !== id + ".json").map((w) => w.file); +} + /** The tool names in a .mcpb manifest ({tools:[{name}]}), or null when it can't be read. */ function manifestTools(manifest) { const t = manifest && Array.isArray(manifest.tools) ? manifest.tools.map((x) => x && x.name).filter((n) => typeof n === "string") : []; @@ -123,4 +129,4 @@ function describeWorkflow(w) { return lines.join("\n"); } -module.exports = { LIMITS, slug, normalizeWorkflow, fromFiles, manifestTools, findWorkflow, workflowLine, describeWorkflow }; +module.exports = { LIMITS, slug, normalizeWorkflow, fromFiles, staleFiles, manifestTools, findWorkflow, workflowLine, describeWorkflow }; From 8bb1facbdee5cf1c7e2402bc39fc115fdd23ac59 Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:07:14 +0530 Subject: [PATCH 4/6] Workflows: stale-file cleanup re-reads each file and skips the one just written (any case) --- mcp-server.js | 2 +- server.js | 2 +- test/workflows.test.js | 16 ++++++++++++++++ workflows.js | 24 ++++++++++++++++++++++-- 4 files changed, 40 insertions(+), 4 deletions(-) diff --git a/mcp-server.js b/mcp-server.js index 9543c7d23..931acd52f 100644 --- a/mcp-server.js +++ b/mcp-server.js @@ -1321,7 +1321,7 @@ function workflowsTool(args) { const prev = all.find((x) => x.id === w.id), now = new Date().toISOString(); const item = { ...w, created: prev && prev.created || now, updated: now }; writeSaved("workflows", item.id, item); - for (const f of Workflows.staleFiles(all, item.id)) fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(f)), { force: true }); + Workflows.removeStale(path.join(LIBRARY_DIR, "workflows"), all, item.id, fs, path); return `${prev ? "Updated" : "Saved"} workflow "${item.name}" (${item.id}), ${item.steps.length} step(s), in library/workflows/${item.id}.json. {action:"show", id:"${item.id}"} reads it back.`; } throw new Error(`unknown action "${action}" — list, show, save or delete`); diff --git a/server.js b/server.js index ab52b7ee8..c9b540bec 100644 --- a/server.js +++ b/server.js @@ -403,7 +403,7 @@ function saveWorkflow(input, all) { const now = new Date().toISOString(); const item = { ...w, created: prev && prev.created || now, updated: now }; writeSaved("workflows", item.id, item); - for (const f of Workflows.staleFiles(all, item.id)) fs.rmSync(path.join(LIBRARY_DIR, "workflows", path.basename(f)), { force: true }); + Workflows.removeStale(path.join(LIBRARY_DIR, "workflows"), all, item.id, fs, path); return item; } function savedDeliveryPresets() { return Delivery.savedPresets(readSaved("delivery")); } diff --git a/test/workflows.test.js b/test/workflows.test.js index 02b6a63b3..136b98a29 100644 --- a/test/workflows.test.js +++ b/test/workflows.test.js @@ -156,3 +156,19 @@ test("updating a workflow kept under another file name leaves one file; deleting assert.match((await mcp.callTool("fablecut_workflows", { action: "delete", id: "other-name" })).content[0].text, /Deleted/); assert.deepEqual(files(), []); }); + +test("stale-file cleanup: never the file just written (any case), never a file that now holds another workflow", (t) => { + const os = require("node:os"); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fc-wf-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const put = (f, w) => fs.writeFileSync(path.join(dir, f), JSON.stringify(w)); + // listed before the save: renamed.json and swapped.json both held "Podcast" + const all = W.fromFiles([{ file: "renamed.json", data: { name: "Podcast", steps: ["a"] } }, { file: "swapped.json", data: { name: "Podcast", steps: ["a"] } }, + { file: "PODCAST.JSON", data: { name: "Podcast", steps: ["a"] } }]); + assert.deepEqual(W.staleFiles(all, "podcast"), ["renamed.json", "swapped.json"], "a case-only difference is the same file"); + put("podcast.json", { name: "Podcast", steps: ["new"] }); + put("renamed.json", { name: "Podcast", steps: ["a"] }); + put("swapped.json", { name: "Something else", steps: ["b"] }); // another process saved here meanwhile + W.removeStale(dir, all, "podcast", fs, path); + assert.deepEqual(fs.readdirSync(dir).sort(), ["podcast.json", "swapped.json"]); +}); diff --git a/workflows.js b/workflows.js index ccda6e665..07d1421fe 100644 --- a/workflows.js +++ b/workflows.js @@ -95,7 +95,27 @@ function fromFiles(entries) { /** After saving workflow `id` as .json: the other files that held that id (an older or * hand-written file under another name), to remove so one workflow stays one file. */ function staleFiles(all, id) { - return all.filter((w) => w.id === id && w.file && w.file !== id + ".json").map((w) => w.file); + // compared without case: on Windows / macOS "PODCAST.JSON" is the file just written + return all.filter((w) => w.id === id && w.file && w.file.toLowerCase() !== (id + ".json").toLowerCase()).map((w) => w.file); +} + +/** Remove the stale files of workflow `id` from `dir` (fs and path passed in, so this module + * stays free of I/O). Each is read again first and removed only while it still holds that + * workflow and is not the file just written: another process may have saved a different one + * under that name since the listing was read. */ +function removeStale(dir, all, id, fs, path) { + const dest = path.join(dir, id + ".json"); + let destStat = null; + try { destStat = fs.statSync(dest); } catch { } + for (const f of staleFiles(all, id)) { + const p = path.join(dir, path.basename(f)); + try { + const st = fs.statSync(p); + if (destStat && st.ino === destStat.ino && st.dev === destStat.dev && st.ino !== 0) continue; + const w = normalizeWorkflow(JSON.parse(fs.readFileSync(p, "utf8").replace(/^/, ""))); + if (w && w.id === id) fs.rmSync(p, { force: true }); + } catch { } + } } /** The tool names in a .mcpb manifest ({tools:[{name}]}), or null when it can't be read. */ @@ -129,4 +149,4 @@ function describeWorkflow(w) { return lines.join("\n"); } -module.exports = { LIMITS, slug, normalizeWorkflow, fromFiles, staleFiles, manifestTools, findWorkflow, workflowLine, describeWorkflow }; +module.exports = { LIMITS, slug, normalizeWorkflow, fromFiles, staleFiles, removeStale, manifestTools, findWorkflow, workflowLine, describeWorkflow }; From 151f1d5c1706dfce00dde0f78bc4f4f65f431a27 Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:14:33 +0530 Subject: [PATCH 5/6] Workflows: a case-only file name is stale on a case-sensitive disk; the file's identity guards the one just written --- test/workflows.test.js | 20 +++++++++++++------- workflows.js | 7 ++++--- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/test/workflows.test.js b/test/workflows.test.js index 136b98a29..f9d4f722a 100644 --- a/test/workflows.test.js +++ b/test/workflows.test.js @@ -162,13 +162,19 @@ test("stale-file cleanup: never the file just written (any case), never a file t const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fc-wf-")); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); const put = (f, w) => fs.writeFileSync(path.join(dir, f), JSON.stringify(w)); - // listed before the save: renamed.json and swapped.json both held "Podcast" - const all = W.fromFiles([{ file: "renamed.json", data: { name: "Podcast", steps: ["a"] } }, { file: "swapped.json", data: { name: "Podcast", steps: ["a"] } }, - { file: "PODCAST.JSON", data: { name: "Podcast", steps: ["a"] } }]); - assert.deepEqual(W.staleFiles(all, "podcast"), ["renamed.json", "swapped.json"], "a case-only difference is the same file"); - put("podcast.json", { name: "Podcast", steps: ["new"] }); - put("renamed.json", { name: "Podcast", steps: ["a"] }); + const old = { name: "Podcast", steps: ["old"] }; + // listed before the save: three files held "Podcast" + const all = W.fromFiles([{ file: "renamed.json", data: old }, { file: "swapped.json", data: old }, { file: "PODCAST.JSON", data: old }]); + assert.deepEqual(W.staleFiles(all, "podcast"), ["renamed.json", "swapped.json", "PODCAST.JSON"]); + put("renamed.json", old); + put("PODCAST.JSON", old); put("swapped.json", { name: "Something else", steps: ["b"] }); // another process saved here meanwhile + put("podcast.json", { name: "Podcast", steps: ["new"] }); // the save (the same file as PODCAST.JSON on Windows / macOS) W.removeStale(dir, all, "podcast", fs, path); - assert.deepEqual(fs.readdirSync(dir).sort(), ["podcast.json", "swapped.json"]); + const left = fs.readdirSync(dir).sort(); + assert.ok(left.includes("swapped.json"), "a file now holding another workflow stays"); + assert.ok(!left.includes("renamed.json")); + const podcasts = left.filter((f) => /^podcast.json$/i.test(f)); + assert.equal(podcasts.length, 1, "one podcast file: a distinct PODCAST.JSON is removed, an alias of the new one kept"); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, podcasts[0]), "utf8")).steps, ["new"]); }); diff --git a/workflows.js b/workflows.js index 07d1421fe..72f8b741a 100644 --- a/workflows.js +++ b/workflows.js @@ -95,8 +95,9 @@ function fromFiles(entries) { /** After saving workflow `id` as .json: the other files that held that id (an older or * hand-written file under another name), to remove so one workflow stays one file. */ function staleFiles(all, id) { - // compared without case: on Windows / macOS "PODCAST.JSON" is the file just written - return all.filter((w) => w.id === id && w.file && w.file.toLowerCase() !== (id + ".json").toLowerCase()).map((w) => w.file); + // exact names: "PODCAST.JSON" is a file of its own on a case-sensitive disk; removeStale + // checks the file's identity, so on Windows / macOS it is never the file just written + return all.filter((w) => w.id === id && w.file && w.file !== id + ".json").map((w) => w.file); } /** Remove the stale files of workflow `id` from `dir` (fs and path passed in, so this module @@ -111,7 +112,7 @@ function removeStale(dir, all, id, fs, path) { const p = path.join(dir, path.basename(f)); try { const st = fs.statSync(p); - if (destStat && st.ino === destStat.ino && st.dev === destStat.dev && st.ino !== 0) continue; + if (destStat && st.dev === destStat.dev && (st.ino !== 0 ? st.ino === destStat.ino : f.toLowerCase() === (id + ".json").toLowerCase())) continue; const w = normalizeWorkflow(JSON.parse(fs.readFileSync(p, "utf8").replace(/^/, ""))); if (w && w.id === id) fs.rmSync(p, { force: true }); } catch { } From 812fc4b24d7aa164b396f2edd2ce421b9b774fca Mon Sep 17 00:00:00 2001 From: Ronak Parmar <84374383+ronak-create@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:14:45 +0530 Subject: [PATCH 6/6] test: escape the dot --- test/workflows.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/workflows.test.js b/test/workflows.test.js index f9d4f722a..cd0c38a13 100644 --- a/test/workflows.test.js +++ b/test/workflows.test.js @@ -174,7 +174,7 @@ test("stale-file cleanup: never the file just written (any case), never a file t const left = fs.readdirSync(dir).sort(); assert.ok(left.includes("swapped.json"), "a file now holding another workflow stays"); assert.ok(!left.includes("renamed.json")); - const podcasts = left.filter((f) => /^podcast.json$/i.test(f)); + const podcasts = left.filter((f) => /^podcast\.json$/i.test(f)); assert.equal(podcasts.length, 1, "one podcast file: a distinct PODCAST.JSON is removed, an alias of the new one kept"); assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, podcasts[0]), "utf8")).steps, ["new"]); });