commit 080b892a8710938bd659d80b546b73892f475210
parent 917c9d39649de7d87cf3db94b0fd839f6f45fbd5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 5 Nov 2026 00:33:02 -0500
Merge lane/take-items: a take is edited as a take -- posts set-item | roles | narrate | reread | fx --in-take <t> write the take's patch (its own undo point) and never the project or the projects its items came from; take <p> --id <t> --import-item <project>:<item>[,…] [--after|--before <entry>] clones items from another project into a take with their files hard-linked in; take --draft --from <take>; umtool lint <p> [--take <t>]; a thread read finds the editor's token itself; render.posts' knob check no longer refuses progress, clock, panel, join, linkVisit or threadMap (the mr-obvious cut failed lint on render.posts.progress) (operator, 4 Nov: "we want the plain apps to do as much heavy lifting as possible so cheaper models can more easily do these tasks without having to improvise shell scripts and instead call real tools")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
24 files changed, 1463 insertions(+), 11 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A take can carry items of other projects, and be edited without touching the project.** A cut assembled as a take of one project from the items of several (the mid cut: a take of the full cut, items from the full cut and a staging project) needed a script to clone the entries, hard-link their narration in and copy each re-read into the take's patch by hand. `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--after|--before <entry>]` now clones the items with their narration and its pick, hard-links every file they name into the take's project (another file already at a path: linked under `imports/<source>/` instead, never written over), places them, and is safe to run again (`updated`, or `unchanged` with no write). `posts set-item`, `roles`, `narrate`, `reread` and `fx` take `--in-take <take>`: the same edit lands in the take's patch with an undo point of the take's own (`umtool timeline <p> --take <t> undo`), the project's manifest untouched. `umtool take … --draft --from <take>` starts a draft from another take's patch, and `umtool lint <p> [--take <t>]` runs the build's lint on a take and checks that every file its items name is in the project. `posts narrate --thread` finds the editor's WORKER_TOKEN in `editor/.env` as umtool's other editor calls do. A cut whose posts carry the progress bar (`posts progress auto`) no longer fails its lint (`render.posts.progress is not a knob`), nor does one with the clock, panel, join, link-visit or branch-map knobs.
- **Every umtool take render records itself, and umtool runs a queue of steps in order.** A render that died at exit 1 behind a filtered shell chain left no trace (`take.json` kept `builtAt: null`, no log), and the next chain read the chain's own DONE as success. Now every render, whoever starts it, writes `takes/<id>/render.json` (running, waiting at the heavy slot, done, failed or cancelled; its stage; on failure the first error line and the log's last 40 lines; on done the mp4 and its seconds) and the full `takes/<id>/render.log`; done needs exit 0 and a non-empty mp4, and a record whose process is gone reads failed. `umtool take status <p> --id <t>` exits 0 done, 3 still going, 1 failed. `umtool queue add [--after <qid>] -- <command…>` queues a umtool command that the umtool app runs, one step at a time, surviving the session, a restart or a ship: a failure blocks what waits on it, `retry` puts both back, a step that was running when the app died is failed with its log and never re-run. `umtool queue ls|status|wait|log|cancel|retry` and `umtool jobs` poll them; `/jobs` (the rail's *Running*) and the Takes page show the queue and the records, with the error and the log. umtool/docs/cli.md, "Queue and poll instead of scripting".
- **A small fix to a report-video take re-renders in minutes, not half an hour.** A take renders hard cuts, and its final picture was one overlay pass over the whole cut on every take -- 12.6 of mid-6's 30 minutes, 26 of mid-7's 60 -- however small the change. The pass is now in keyed chunks, one segment's run each: `umtool take … --from <take>` re-encodes only the chunks of the post it touched, and a post that grew or shrank moves the chunks after it without changing them (the deck's frames after it are the same frames, later). The deck is drawn only where a chunk to encode reads it, so a take `--from` a pruned one no longer captures the whole deck again (12,347 captures, ~3 minutes on mid-7), and the cut's sound is keyed by each segment's audio, so a caption or a knob that moves no word keeps it. The picture is now frame-exact: the old pass laid each next segment at the longer of its picture and its sound, the footage up to 0.3 s behind the deck by the end of the cut.
- **A recorded take can be cleaned up, or given a stock synthetic voice, by the editor.** umtool's derived takes (`umtool posts narrate <p> <item> --derive <n> --op enhance|convert`, the post bench's **run AI on take #n**) said "not installed": the editor had no voice ops. It now has two, each a job on a new `voice` queue, its engine run behind the machine's heavy slot with a declared memory estimate: `pnpm ops voice-enhance` (denoise, soften the room, level — DeepFilterNet 3, or RNNoise through ffmpeg with nothing to install) and `pnpm ops voice-convert` (the timing and pitch contour kept, the timbre swapped — OpenVoice v2's converter or Seed-VC). The result is a 48 kHz mono WAV exactly as long as the take, so a derived take lines up with its source; a take recorded part by part is processed part by part. A conversion lands only on a STOCK voice of our own TTS engines (`zac`, `orpheus:leah`, `kokoro:am_michael`): a file or a recording is refused as a target, whatever it holds. The engines are installed by `archilyzer voice setup --engine <id>`, which says what it downloads and how big first; `settings.voice` picks the defaults (SETTINGS.md); OPERATING.md, "Enhance or convert a recorded take".
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -74,6 +74,8 @@
// [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take
// [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut
// [--priority] render mode for the take's lifetime: the machine is the render's (AGENTS.md "Render mode")
+// --id <id> --import-item <project>:<item>[,…] [--after|--before <entry>] items of another project into the take
+// umtool lint <project> [--take <id>] [--json] the manifest lint (lint.mjs) on the cut or a take, + the files it names
// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]
// | ls <project> | relabel <project> <take> <label> | supersede <project> <take> [--by T] [--clear]
// | delete <project> <take> [--dry-run] [--force] take housekeeping
@@ -116,6 +118,7 @@
// set-item <project> <item> hold=… media.<i>.start=… a post item's knobs
// narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration
// narrate <project> <item> --take --thread [--parents 0|all] … a thread read (postThreadRead.mjs)
+// set-item | roles | narrate | reread | fx … --in-take <take> the edit on a take's patch (takeScope.mjs)
// say <project> ls | add | remove | try | stale · voices <project> ls | set | remove lexicon, voice map
// fit <project> --all | <item>… narrated posts' videos cut to their best part
// avatar <project> <handle> <image> | avatars <project> the authors' pictures
@@ -963,6 +966,13 @@ function usage() {
" (`umtool take <p> --id <id> --full` renders a draft from its stored patch)",
" --priority: render mode for the take's lifetime -- every other heavy job waits for it, the",
" editor's transcription and download lanes are held; all let go at its end, failure or signal",
+ " --draft --from TAKE: a draft that starts from that take's patch (its timeline its own from then on)",
+ " umtool take <project> --id <id> --import-item <project>:<item>[,<item>…] [--after <entry>|--before <entry>]",
+ " [--as <id>] [--dry-run] [--json] items of ANOTHER project cloned into the take (its patch), their",
+ " narration and pick kept, the files they name hard-linked into this project; again: updated or unchanged",
+ " umtool lint <project> [--take <id>] [--variant sourced|full] [--final] [--json] the manifest lint a build runs",
+ " first, on the project's manifest or a take's (its patches applied), and the files its post items",
+ " name (a picked read, an attachment not in the project: an error) -- exit 0 clean, 1 an error",
" umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
" manifest, one undo point (revisions/…-auto-before-promote-take)",
" umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render record (every render",
@@ -1055,6 +1065,10 @@ function usage() {
" umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]",
" [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date",
" order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)",
+ " umtool posts set-item | roles | narrate | reread | fx … --in-take <take> the same edit on a TAKE of the project:",
+ " its manifest read as the take's, the write in takes/<take>/take.json's patch (an undo point of the take's,",
+ " `umtool timeline <p> --take <take> undo`), the project's manifest untouched; set-item/roles/reread/fx",
+ " take --take <take> for it too (narrate's --take is a new read)",
" umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale",
" the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)",
" umtool posts voices <project> ls | set <handle|*> <voice> | remove <handle> the voice map a thread read uses",
@@ -1120,6 +1134,7 @@ const COMMANDS = {
notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))),
// The take maker (release 33): lib/report/takeCli.mjs.
take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))),
+ lint: async () => process.exit(await (await import("../lib/report/lintCli.mjs")).lintCommand(argv.slice(argv.indexOf("lint") + 1))),
takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))),
// The durable queue and every render's record (4 Nov 2026): lib/queue/cli.mjs.
queue: async () =>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -57,6 +57,9 @@ Inbox cannot disagree about what is wrong with one.
| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) |
| `take <project> --id <id> … --uncensored` · build-video `--uncensored` | the **uncensored cut** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): the same cut with the post items' slur filter off -- `render.posts.slurs.on: false` in the take's patch (a `--rebuild` keeps it; a censored take is not rebuilt uncensored, **exit 2**: make a take of its own), its label gains "(uncensored)", take.json's `slurs` records `censored` or `uncensored`. The redaction of private words and censored attachments stay on |
+| `take <project> --id <id> --draft --from <take> [--label L] [--patch F \| --patch-json J \| --set p=v …]` | a **draft made from another take**: that take's style and patch (a `--patch` merged over it), its label "<that label> (from <take>)" unless `--label`, nothing rendered; its timeline is its own from then on, and its render's `--from` (segments reused) is a separate flag of the render ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits)) |
+| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** |
+| `lint <project> [--take <take>] [--variant sourced\|full] [--final] [--json]` | **the manifest lint** (`report-to-video/lint.mjs`, what a build runs before it renders a frame) from umtool: the project's manifest, or with `--take` the take's (its patches applied, written beside the project's manifest for the lint as its render's is, then removed) -- plus the **files its post items name**: a picked read, an attachment or a context post's media not in the project is an ERROR, another kept take a warning. Run it after an import and before queueing the render. `--json`: `{ok, entries, errors, warnings}`. **Exit 0 no error · 1 an error · 2 usage** |
| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) |
@@ -85,6 +88,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` |
| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.enter=post\|item] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit; `media.<i>.enter=` when its own attachment comes in -- with his own post's read (`post`, the default: a parent or a quote read first shows none of it) or with the item (`item`) |
+| `posts set-item \| roles \| narrate \| reread \| fx <project> … --in-take <take>` (set-item, roles, reread, fx: `--take <take>` too) | **a take-scoped edit** (`takeScope.mjs`): the same command, on a TAKE of the project -- its manifest read as the take's (the project's now with the take's patches), every write landing in `takes/<take>/take.json`'s patch with an undo point of the take's own (`timeline <p> --take <take> undo`). The project's manifest, and any project the take's items were imported from, are untouched; a new read (`narrate --take`, `--thread`, `reread`) lands in the project's `narration/` under a take number no file or entry has. A writer not routed to the take refuses and writes nothing. `--json`: the command's own object plus `take {id, edits, revisions, undo}`. narrate's own `--take` is "make a new read": `narrate … --take <a take's id>` is refused (exit 2) naming `--in-take`. **Exit 1** when the take is not there or is rendering ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits)) |
| `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) |
| `posts reread <project> <item> --tempo-for "4-16=1.35,21-25=1.3" \| --tempo <x> --parts <runs> [--stretch atempo\|rubberband] [--dry-run] [--json]` | a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: "tempo", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo="4-16=1.35"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1** |
| `posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run] [--json]` · `posts yell <project> --all \| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]` | a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: "yell", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings |
@@ -196,6 +200,48 @@ node umtool/bin/umtool.mjs jobs
- The page is **/jobs** (the queue with Cancel and Retry, the take renders, the app's jobs); the
Takes page shows a take's render record and the project's queue.
+## Edit a take, not the project: items from other projects and take-scoped edits
+
+A cut assembled as a TAKE of one project from items of several (the Mr. Obvious mid cut: a take of
+the full cut, items from the full cut and a staging project) used to need a script: clone the
+entries, hard-link their narration into the take's project (the lint refuses a file that is not
+in it), copy a re-read's narration into the patch JSON and restore the source's pick. Three
+commands do it now, and none of them touch the project's manifest or the source's.
+
+```sh
+U="node umtool/bin/umtool.mjs"
+# 0. A draft take made from the take before it (its patch; nothing rendered).
+$U take emberparadox/mr-obvious --id mid-15 --draft --from mid-14 --label "mid cut 15"
+# 1. Posts X and Y of project A into the take, after item Z (their narration and pick come along,
+# their files hard-linked in). --dry-run first to see where they land.
+$U take emberparadox/mr-obvious --id mid-15 --import-item emberparadox/mr-obvious-mid-stage:p-X,p-Y --after p-Z --json
+# 2. Item Z's parent drawn as context, in the take only (a read that reads it is re-joined first).
+$U posts set-item emberparadox/mr-obvious p-Z thread.parent=context --in-take mid-15 --json
+# 3. Any other edit of an item, in the take: the pick, a fresh thread read, a re-join, an effect.
+$U posts narrate emberparadox/mr-obvious p-X --pick 2 --in-take mid-15
+$U posts narrate emberparadox/mr-obvious p-X --take --thread --in-take mid-15
+$U posts reread emberparadox/mr-obvious p-X --without parent:0 --in-take mid-15
+$U posts fx emberparadox/mr-obvious p-X add caption --match "…" --text "…" --in-take mid-15
+# Look, check, take back, render.
+$U timeline emberparadox/mr-obvious --take mid-15 # the take's timeline, in order
+$U lint emberparadox/mr-obvious --take mid-15 # exit 0: the lint passes and every file it names is there
+$U timeline emberparadox/mr-obvious --take mid-15 undo # its newest edit taken back
+$U queue add --label "render mid-15" -- take emberparadox/mr-obvious --id mid-15 --full --priority --from mid-14
+```
+
+- **`--in-take <take>` is the flag on all five** (`posts set-item`, `roles`, `narrate`, `reread`,
+ `fx`). On set-item, roles, reread and fx `--take <take>` is the same; on narrate `--take` means
+ "synthesize a new read", so say `--in-take` there.
+- **The import is safe to run again**: an item already in the take is updated from the source in
+ place (`updated`), or left alone with no write (`unchanged`). Edit it in the take afterwards
+ with `--in-take`; a re-import puts the source's version back.
+- **The files are hard links**, not copies: the source's files are never written. When the
+ take's project already has ANOTHER file at the same path, the import links the source's under
+ `imports/<source project>/…` and the clone names that path -- nothing is written over.
+- A take that is rendering is not edited (exit 1): wait for it (`take status`) or cancel it.
+- Exit codes: **0** done (also "nothing changed"), **1** refused (no such take, item or entry; a
+ rendering take; a link out of the project), **2** usage.
+
## `check` is the one to run before every build
```
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1176,6 +1176,31 @@ has the walk-through; in short:
| a take's render record | `umtool take status <p> --id <take> [--json] [--log] [--tail N]` (exit 0 done · 3 queued/waiting/running · 1 failed) | the take's card (a render running now, or a later one that failed), **first render failed** above the takes, the project's **Queue** | `GET /api/report/takes/render?project=&take=` (`&log=1` the full log) |
| everything, across projects | `umtool jobs [--json]` | **/jobs** (the rail's *Running*) | `GET /api/queue`, `GET /api/jobs` |
+## A take's own items (imported from other projects, edited in the take only)
+
+A take is a merge patch over the project's manifest (`takes/<take>/take.json`'s `patch`); a cut
+assembled as a take can carry items of OTHER projects and edits of its own, and none of it
+reaches the project's manifest or the projects it came from.
+[cli.md](cli.md#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits)
+has the recipe.
+
+| | From a terminal | What it writes |
+|---|---|---|
+| a draft from another take | `umtool take <p> --id <t> --draft --from <take> [--label L] [--patch F]` | `takes/<t>/take.json`: that take's style and patch (yours over it); nothing rendered |
+| items of another project into the take | `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | the entries cloned (narration, takes, pick, knobs) into the take's timeline, one undo point; their files **hard-linked** into `<p>` (another file at a path: `imports/<source>/…`); authors' pictures the take lacks into its `postAvatars`. Again: `updated` in place, or `unchanged` (no write) |
+| a post item's knobs, in the take | `umtool posts set-item <p> <item> k=v … --in-take <t>` (or `--take <t>`) | the take's entry; a piece made context or hidden that its read reads is re-joined first, as on the project |
+| the read's pieces, in the take | `umtool posts roles <p> <item> --set n=role --in-take <t>` | the take's entry's take parts |
+| the pick, a new read, a thread read, the mix | `umtool posts narrate <p> <item> --pick <n> \| --take [--thread …] \| --script "…" \| k=v --in-take <t>` | the take's entry; a new read's file in `<p>/narration/` under a number no file or entry has |
+| a re-join (no TTS) | `umtool posts reread <p> <item> --without parent:0 … --in-take <t>` | the take's entry, the new take picked there (the project keeps its pick) |
+| an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` |
+| look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte |
+
+Each edit is an undo point of the take's (`takes/<t>/revisions/`). An edit that changes nothing
+writes nothing. A take that is rendering is not edited (exit 1). The narration's lexicon and
+voice map a new read uses are `<p>`'s (`umtool posts say <p>`, `posts voices <p>`), not the
+source project's. `--json` on a take-scoped edit is the command's own object with
+`take: {id, edits, revisions, undo}`.
+
## Takes: relabel, supersede, cancel, delete, fork as variant, compare
| | In umtool | From a terminal | Route |
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -55,6 +55,7 @@ import { makeReelFixture } from "./reel-fixture.mjs";
import { makeIntakeFixture } from "./intake-fixture.mjs";
import { makePostItemsFixture } from "./post-items-fixture.mjs";
import { makePostNarrationFixture } from "./post-narration-fixture.mjs";
+import { makeTakeItemsFixture } from "./take-items-fixture.mjs";
import { makePlayPreloadFixture } from "./play-preload-fixture.mjs";
import { makePostComboFixture } from "./post-combo-fixture.mjs";
import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs";
@@ -1916,6 +1917,8 @@ makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: pat
makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Narrated post items (report-to-video/post-narration.mjs): a take read over a video, four pictures cycling (post-narration.spec.ts).
makePostNarrationFixture({ reports, deckManifest });
+// A take's own items (takeImport.mjs, takeScope.mjs): a post imported from another project into a draft take, edited in the take only (take-items.spec.ts).
+makeTakeItemsFixture({ reports, deckManifest });
// A fast burst of narrated posts (Play's prefetch and its gate: play-preload.spec.ts).
makePlayPreloadFixture({ reports, deckManifest });
// The combo counter (report-to-video/post-combo.mjs): one GIF answering three people (post-combo.spec.ts).
diff --git a/umtool/e2e/fixtures/take-items-fixture.mjs b/umtool/e2e/fixtures/take-items-fixture.mjs
@@ -0,0 +1,68 @@
+// A TAKE'S OWN ITEMS (take-items.spec.ts; umtool/docs/cli.md, "Edit a take, not
+// the project"): items of another project imported into a take, edited in the
+// take only. Two projects, written by that spec alone:
+//
+// take-items-fixture the take's project: two post items (p-1, p-3) and a
+// DRAFT take `t1` with no patch of its own yet
+// take-items-src-fixture the source: a narrated post item p-2 whose take
+// (narration/posts/2/take-1.orpheus-thread.wav, a 2 s
+// tone; its parts meta beside it) and attachment
+// (posts-media/takeitems-x/2/2_1.png) are files of
+// this project only, and a second take for the pick
+//
+// Synthetic, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+
+const ff = (args) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);
+ if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`);
+};
+
+/** @param {{ reports: string, deckManifest: Function }} o */
+export function makeTakeItemsFixture({ reports, deckManifest }) {
+ const base = (id, date, text, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `takeitems-x/${id}`, platform: "x", author: "Take Subject", handle: "takesubject",
+ date, text, url: `https://x.com/takesubject/status/${id}`, engagement: { likes: 2 }, subjects: ["takesubject"], ...o,
+ });
+
+ // The source: p-2, narrated (two takes, the first picked), with a picture.
+ const src = path.join(reports, "take-items-src-fixture");
+ const takes = path.join(src, "narration", "posts", "2");
+ mkdirSync(takes, { recursive: true });
+ for (const [n, hz] of [[1, 262], [2, 330]]) {
+ ff(["-f", "lavfi", "-i", `sine=frequency=${hz}:sample_rate=24000:duration=2`, "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, `take-${n}.orpheus-thread.wav`)]);
+ }
+ writeFileSync(path.join(takes, "take-1.parts.json"), JSON.stringify([{ n: 1, para: 100, text: "The imported words.", start: 0, seconds: 2 }]));
+ mkdirSync(path.join(src, "posts-media", "takeitems-x", "2"), { recursive: true });
+ ff(["-f", "lavfi", "-i", "color=c=teal:size=320x180", "-frames:v", "1", path.join(src, "posts-media", "takeitems-x", "2", "2_1.png")]);
+ const take = (n) => ({ file: `narration/posts/2/take-${n}.orpheus-thread.wav`, engine: "orpheus", voice: "zac", seconds: 2, script: "The imported words.", at: "2026-11-04T00:00:00.000Z" });
+ const sm = deckManifest("take-items-src-fixture", "The Take Items Source", [
+ base("2", "2026-11-02T10:00:00.000Z", "The imported words.", {
+ media: [{ src: "posts-media/takeitems-x/2/2_1.png", kind: "image", width: 320, height: 180 }],
+ narration: { script: "The imported words.", takes: [take(1), take(2)], pick: 0 },
+ }),
+ ]);
+ mkdirSync(src, { recursive: true });
+ writeFileSync(path.join(src, "video.manifest.json"), JSON.stringify(sm, null, 2) + "\n");
+
+ // The take's project: p-1 and p-3, and the draft take t1 (no patch: the project's timeline until its first edit).
+ const dir = path.join(reports, "take-items-fixture");
+ mkdirSync(dir, { recursive: true });
+ const m = deckManifest("take-items-fixture", "The Take Items Fixture", [
+ base("1", "2026-11-01T10:00:00.000Z", "The first post of the cut."),
+ base("3", "2026-11-03T10:00:00.000Z", "The last post of the cut."),
+ ]);
+ const text = JSON.stringify(m, null, 2) + "\n";
+ writeFileSync(path.join(dir, "video.manifest.json"), text);
+ const tdir = path.join(dir, "takes", "t1");
+ mkdirSync(tdir, { recursive: true });
+ writeFileSync(path.join(tdir, "take.json"), JSON.stringify({
+ id: "t1", group: "takes", order: 1, label: "Take one — with an imported post", kind: "different", summary: "", changes: [],
+ preview: "preview.mp4", seconds: null, builtAt: null, style: null, patch: null, window: null, draft: true,
+ draftedAt: "2026-11-04T00:00:00.000Z", baseHash: createHash("sha256").update(text).digest("hex"),
+ }, null, 2) + "\n");
+ return { dir, src };
+}
diff --git a/umtool/e2e/take-items.spec.ts b/umtool/e2e/take-items.spec.ts
@@ -0,0 +1,105 @@
+import { test, expect } from "@playwright/test";
+import { spawnSync } from "node:child_process";
+import { readFileSync, statSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A TAKE'S OWN ITEMS (umtool/docs/cli.md, "Edit a take, not the project"):
+// `umtool take <p> --id <t> --import-item <src>:<item>` clones an item of
+// another project into a draft take with its files hard-linked in, and
+// `umtool posts … --in-take <t>` edits it in the take -- the take's project
+// manifest and the source's byte for byte the same throughout. Then Play on
+// the take plays the imported item, its narration and picture there.
+//
+// Fixture (fixtures/take-items-fixture.mjs), written by this file alone:
+// take-items-fixture (p-1, p-3; the draft take t1) and take-items-src-fixture
+// (p-2, narrated, two takes, a picture). The tests run in order.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "take-items-fixture");
+const SRC = path.join(FIXTURE, "reports", "take-items-src-fixture");
+const P = "reports/take-items-fixture";
+const S = "reports/take-items-src-fixture";
+const TAKE = "t1";
+const env = { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_MEDIA_DIR: "" };
+const umtool = (args: string[]) => spawnSync("node", ["bin/umtool.mjs", ...args], { cwd: path.join(HERE, ".."), encoding: "utf8", env });
+const ok = (args: string[]) => {
+ const r = umtool(args);
+ expect(r.status, `umtool ${args.join(" ")}\n${r.stdout}\n${r.stderr}`).toBe(0);
+ return r.stdout;
+};
+const text = (dir: string) => readFileSync(path.join(dir, "video.manifest.json"), "utf8");
+type Entry = { id: string; hold?: number; narration?: { pick?: number; takes: { file: string }[] } };
+const takeTimeline = () => (JSON.parse(readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8")).patch?.timeline ?? []) as Entry[];
+
+let projectBefore = "";
+let sourceBefore = "";
+test.beforeAll(() => {
+ projectBefore = text(DIR);
+ sourceBefore = text(SRC);
+});
+
+test("import: the source's item cloned into the take after p-1, its narration and picture hard-linked in; again: unchanged; lint --take passes", () => {
+ const plan = JSON.parse(ok(["take", P, "--id", TAKE, "--import-item", `${S}:p-2`, "--after", "p-1", "--dry-run", "--json"]));
+ expect(plan.dryRun).toBe(true);
+ expect(plan.items[0].at).toEqual({ index: 1, after: "p-1", before: "p-3" });
+ expect(() => statSync(path.join(DIR, "narration/posts/2/take-1.orpheus-thread.wav"))).toThrow();
+
+ const r = JSON.parse(ok(["take", P, "--id", TAKE, "--import-item", `${S}:p-2`, "--after", "p-1", "--json"]));
+ expect(r.items.map((x: { id: string; action: string }) => [x.id, x.action])).toEqual([["p-2", "added"]]);
+ expect(r.items[0].narration).toEqual({ takes: 2, pick: 1, file: "narration/posts/2/take-1.orpheus-thread.wav" });
+ expect(r.revision).toMatch(/^takes\/t1\/revisions\/.*-auto-before-import-item\.take\.json$/);
+ expect(takeTimeline().map((e) => e.id)).toEqual(["p-1", "p-2", "p-3"]);
+ for (const rel of ["narration/posts/2/take-1.orpheus-thread.wav", "narration/posts/2/take-1.parts.json", "narration/posts/2/take-2.orpheus-thread.wav", "posts-media/takeitems-x/2/2_1.png"]) {
+ expect(statSync(path.join(DIR, rel)).ino, rel).toBe(statSync(path.join(SRC, rel)).ino);
+ }
+ const again = JSON.parse(ok(["take", P, "--id", TAKE, "--import-item", `${S}:p-2`, "--after", "p-1", "--json"]));
+ expect([again.unchanged, again.items[0].action, again.revision]).toEqual([true, "unchanged", null]);
+ const lint = umtool(["lint", P, "--take", TAKE, "--json"]);
+ const doc = JSON.parse(lint.stdout);
+ expect(doc.errors, lint.stdout).toEqual([]);
+ expect(lint.status).toBe(0);
+ expect(text(DIR)).toBe(projectBefore);
+ expect(text(SRC)).toBe(sourceBefore);
+});
+
+test("--in-take: set-item and narrate --pick land in the take's patch only; narrate --take <the take> is refused naming --in-take; undo takes the pick back", () => {
+ const set = JSON.parse(ok(["posts", "set-item", P, "p-2", "hold=4", "--in-take", TAKE, "--json"]));
+ expect(set.take).toMatchObject({ id: TAKE, edits: 1, undo: `umtool timeline ${P} --take ${TAKE} undo` });
+ ok(["posts", "narrate", P, "p-2", "--pick", "2", "--in-take", TAKE]);
+ const e = takeTimeline().find((x) => x.id === "p-2");
+ expect(e?.hold).toBe(4);
+ expect(e?.narration?.pick).toBe(1);
+ const wrong = umtool(["posts", "narrate", P, "p-2", "--take", TAKE]);
+ expect(wrong.status).toBe(2);
+ expect(wrong.stderr).toContain(`to edit take ${TAKE}, say --in-take ${TAKE}`);
+ ok(["timeline", P, "--take", TAKE, "undo"]);
+ expect(takeTimeline().find((x) => x.id === "p-2")?.narration?.pick).toBe(0);
+ expect(text(DIR)).toBe(projectBefore);
+ expect(text(SRC)).toBe(sourceBefore);
+ // The project's own cut has no p-2: the same edit without --in-take is refused.
+ expect(umtool(["posts", "set-item", P, "p-2", "hold=4"]).status).not.toBe(0);
+});
+
+test("Play on the take plays the imported item: its row between p-1 and p-3, narrated, its picture beside the card -- the project's cut has no p-2", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(P, { take: TAKE, clip: "p-2" }));
+ await expect(page.locator(`[data-play-take="${TAKE}"]`)).toBeVisible();
+ const rows = page.locator("[data-play-row]");
+ await expect(rows).toHaveCount(3);
+ expect(await rows.evaluateAll((els) => els.map((x) => x.getAttribute("data-play-row")))).toEqual(["p-1", "p-2", "p-3"]);
+ await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-item", "p-2");
+ await expect(page.locator('[data-post-play="p-2"]')).toBeVisible();
+ // Narrated (its imported take plays) and its imported picture beside the card.
+ await expect(page.locator('[data-post-play="p-2"]')).toHaveAttribute("data-post-narrated", "1");
+ await expect(page.locator('[data-post-play="p-2"]')).toHaveAttribute("data-post-step", "image");
+ await page.screenshot({ path: test.info().outputPath("take-items-play.png") });
+ await page.goto(urls.playHref(P, { bare: true }));
+ await expect(page.locator("[data-play-row]")).toHaveCount(2);
+});
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -45,6 +45,7 @@ import { montageOn } from "umtool-report-to-video/montage";
import { validateGaps } from "umtool-report-to-video/gaps";
import { fileSig, pathCache } from "../pathCache.mjs";
import { citeOffsets } from "../report/citeFollow.mjs";
+import { takeScopeOf } from "../report/takeScope.mjs";
import { PATCH_FILE_RE, stalePatchMarkers } from "../report/patchMarkers.mjs";
import { linkVerdicts, linksFile, readLinkCheck } from "../report/linkCheck.mjs";
import { deployBehindWhy, projectSites, sitesByOrigin } from "../report/siteDeploys.mjs";
@@ -185,6 +186,12 @@ const hmsShort = (sec) => {
export const manifestPath = (dir) => path.join(dir, MANIFEST_NAME);
export async function readManifest(dir) {
+ // A take-scoped edit (lib/report/takeScope.mjs): the project's manifest is read as the take's.
+ const scope = takeScopeOf(dir);
+ if (scope) {
+ const { resolveTakeManifest } = await import("../report/takeManifest.mjs");
+ return (await resolveTakeManifest(scope.dir, scope.take)).manifest;
+ }
try {
return JSON.parse(await readFile(manifestPath(dir), "utf8"));
} catch {
diff --git a/umtool/lib/report/edit-guard.mjs b/umtool/lib/report/edit-guard.mjs
@@ -17,6 +17,7 @@
import { projectTargetFor } from "../annotations/targets.mjs";
import { readManifest } from "../projects/report.mjs";
import { editsBetween, recordEdits } from "./edit-notes.mjs";
+import { takeScopeOf } from "./takeScope.mjs";
/**
* @template T
@@ -26,6 +27,8 @@ import { editsBetween, recordEdits } from "./edit-notes.mjs";
* @returns {Promise<{ result: T, editNotes: { generatedBy: string, added: number, updated: number, deleted: number, errors: string[] } | null }>}
*/
export async function withEditNotes(project, write, opts = {}) {
+ // A take-scoped edit (takeScope.mjs) writes the take's patch, not the generated manifest: nothing to port.
+ if (takeScopeOf(project.dir)) return { result: await write(), editNotes: null };
const before = await readManifest(project.dir);
const result = await write();
const generatedBy = typeof before?.generatedBy === "string" ? before.generatedBy.trim() : "";
diff --git a/umtool/lib/report/lintCli.mjs b/umtool/lib/report/lintCli.mjs
@@ -0,0 +1,131 @@
+// `umtool lint <project> [--take <t>]`: THE MANIFEST LINT (report-to-video/lint.mjs, what a build runs before it
+// renders a frame) from umtool, on the project's manifest or on a TAKE's -- the take's manifest resolved as its
+// render resolves it (the project's now + its style's and its own patches) and written beside the project's
+// manifest for the lint, so a relative path in it is read as the render reads it -- plus the FILES the post items
+// name: a post item whose picked read, attachment or context media is not in the project would render a broken
+// item (a take's imported items are hard-linked in by `umtool take --import-item`; this says when one is not).
+//
+// exit 0 no error (warnings said) · 1 an error · 2 usage
+import { rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+
+export const LINT_USAGE = [
+ "usage: umtool lint <project> [--take <take>] [--variant sourced|full] [--final] [--json]",
+ " the manifest lint (report-to-video/lint.mjs, what a build runs before it renders) on the project's manifest, or",
+ " with --take on the take's (its patches applied, as its render reads it), and the files its post items name: a",
+ " picked read, an attachment, a context post's media not in the project is an ERROR; another named file a warning.",
+ " Exit 0 no error · 1 an error · 2 usage.",
+].join("\n");
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const exists = async (f) => !!(await stat(f).catch(() => null));
+
+/**
+ * The files the post items of `manifest` name that are not in `dir`: `{ errors, warnings }`.
+ * An error: the picked narration take, an attachment (`media[].src`), a context post's or a link's media.
+ * A warning: any other narration take the item keeps.
+ * @param {Record<string, any>} manifest
+ * @param {string} dir
+ */
+export async function namedFileProblems(manifest, dir) {
+ const errors = [];
+ const warnings = [];
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (!isObj(e) || e.type !== "post") continue;
+ const takes = Array.isArray(e.narration?.takes) ? e.narration.takes : [];
+ const pick = Number.isInteger(e.narration?.pick) ? e.narration.pick : 0;
+ for (const [i, t] of takes.entries()) {
+ if (typeof t?.file !== "string" || (await exists(path.join(dir, t.file)))) continue;
+ if (i === pick && e.narration?.off !== true) errors.push(`timeline ${e.id}: its picked read ${t.file} is not in the project`);
+ else warnings.push(`timeline ${e.id}: its take ${i + 1} (${t.file}) is not in the project`);
+ }
+ const media = [
+ ...(Array.isArray(e.media) ? e.media.map((m, i) => [`media[${i}]`, m]) : []),
+ ...(Array.isArray(e.parents) ? e.parents.flatMap((p, k) => (Array.isArray(p?.media) ? p.media.map((m, i) => [`parents[${k}].media[${i}]`, m]) : [])) : []),
+ ...(Array.isArray(e.links) ? e.links.flatMap((l, k) => (Array.isArray(l?.media) ? l.media.map((m, i) => [`links[${k}].media[${i}]`, m]) : [])) : []),
+ ];
+ for (const [where, m] of media) {
+ const src = isObj(m) ? m.src : typeof m === "string" ? m : null;
+ if (typeof src !== "string" || /^[a-z][a-z0-9+.-]*:/i.test(src)) continue;
+ if (!(await exists(path.join(dir, src)))) errors.push(`timeline ${e.id}.${where}: ${src} is not in the project`);
+ }
+ }
+ return { errors, warnings };
+}
+
+/**
+ * @param {string[]} args the words after `lint`
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [opts]
+ */
+export async function lintCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) {
+ const valued = new Set(["--take", "--variant"]);
+ const flags = new Map();
+ const positional = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (valued.has(a)) {
+ if (args[i + 1] === undefined) {
+ err(`${a} needs a value\n${LINT_USAGE}`);
+ return 2;
+ }
+ flags.set(a, args[++i]);
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else positional.push(a);
+ }
+ if (flags.has("--help") || positional.length !== 1) {
+ (flags.has("--help") ? log : err)(LINT_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const variant = String(flags.get("--variant") ?? "sourced");
+ if (!["sourced", "full"].includes(variant)) {
+ err(`--variant takes sourced or full\n${LINT_USAGE}`);
+ return 2;
+ }
+ const r = await resolveProject(positional[0], reportsRoot);
+ if (r.ambiguous || !r.project) {
+ err(r.ambiguous ? `"${positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id` : `no project matches "${positional[0]}"`);
+ return 2;
+ }
+ const project = r.project;
+ const take = flags.has("--take") ? String(flags.get("--take")) : null;
+ const { lintManifestFile, lintReport } = await import("umtool-report-to-video/lint");
+ const { selectVariant } = await import("umtool-report-to-video/build-video");
+ let file = path.join(project.dir, "video.manifest.json");
+ let manifest;
+ let scratch = null;
+ try {
+ if (take) {
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ try {
+ manifest = (await resolveTakeManifest(project.dir, take)).manifest;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+ // Beside the project's manifest, as the render's own (.take-<t>.render.json) is: its paths read as the render's.
+ scratch = path.join(project.dir, `.take-${take}.lint.json`);
+ await writeFile(scratch, JSON.stringify(manifest, null, 2) + "\n", "utf8");
+ file = scratch;
+ } else {
+ const { readFile } = await import("node:fs/promises");
+ manifest = JSON.parse(await readFile(file, "utf8").catch(() => "null"));
+ if (!isObj(manifest)) {
+ err(`${project.id} has no readable video.manifest.json`);
+ return 1;
+ }
+ }
+ const lint = await lintManifestFile(file, { variant, final: flags.has("--final") });
+ const files = await namedFileProblems(selectVariant(manifest, variant), project.dir);
+ const errors = [...lint.errors, ...files.errors];
+ const warnings = [...lint.warnings, ...files.warnings];
+ if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings }, null, 2));
+ else {
+ for (const line of lintReport({ errors, warnings })) log(line);
+ log(`${project.id}${take ? ` take ${take}` : ""}: ${manifest.timeline?.length ?? 0} entries, ${errors.length ? "NOT ready to render" : "ready to render as far as the lint can tell"}`);
+ }
+ return errors.length ? 1 : 0;
+ } finally {
+ if (scratch) await rm(scratch, { force: true });
+ }
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -69,6 +69,7 @@ import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webp
import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs";
import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs";
+import { TakeScopeRefused, scopedTakeToken, takeScopeOf } from "./takeScope.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo";
import { SCENE_DEFAULTS, validatePostSceneRender } from "umtool-report-to-video/post-media-scene";
@@ -143,6 +144,9 @@ const round2 = (n) => Number(Number(n).toFixed(2));
* @returns {Promise<string | null>}
*/
export async function manifestToken(dir) {
+ // A take-scoped edit (takeScope.mjs): the token is the take's own (take.json's mtime).
+ const scope = takeScopeOf(dir);
+ if (scope) return scopedTakeToken(scope);
const st = await stat(manifestFile(dir)).catch(() => null);
return st ? String(Math.round(st.mtimeMs)) : null;
}
@@ -174,6 +178,9 @@ async function backupOnce(file) {
* on disk, which every caller read inside the same lock.
*/
async function writeManifestAtomic(dir, manifest) {
+ // A take-scoped edit never writes the project's manifest (takeScope.mjs): a writer that is not routed to the take is refused.
+ const scope = takeScopeOf(dir);
+ if (scope) throw new TakeScopeRefused(`this edit cannot be made on a take yet (it writes the project's manifest, not take ${scope.take}'s patch) -- nothing was written`);
const file = manifestFile(dir);
const before = await readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
if (before) clearEditedDrafts(before, manifest);
@@ -2111,6 +2118,17 @@ export function reanchorAfterRemove(m, removed, i) {
* build's checks, the auto snapshot of the file as it still is, then the write.
*/
async function structural(dir, op, token, mutate, { snapshotEvery = undefined, prepare = null } = {}) {
+ // A take-scoped edit (takeScope.mjs): the same mutation and the same checks, over the take's manifest, written
+ // into its patch with an undo point of the take's own -- the project's manifest, its snapshots and the other
+ // takes' markers untouched.
+ const scope = takeScopeOf(dir);
+ if (scope) {
+ const { editTakeManifest } = await import("./takeEdit.mjs");
+ return editTakeManifest(scope.dir, scope.take, op, token, async (manifest) => {
+ const prepared = prepare ? await prepare(manifest) : undefined;
+ return applyStructural(manifest, (m) => mutate(m, prepared));
+ });
+ }
return withManifestLock(async () => {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs
@@ -34,7 +34,7 @@ import { manifestToken, updatePostClock, updatePostFx, updatePostNarration } fro
import { findPostItem } from "./postNarrationCli.mjs";
export const FX_USAGE = [
- "usage: umtool posts fx <project> <item> [ls] [--json]",
+ "usage: umtool posts fx <project> <item> [ls] [--json] (any form, + --in-take <take> or --take <take>: on a take's patch)",
" umtool posts fx <project> <item> add word-zoom --match \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
" [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]",
" umtool posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -46,6 +46,8 @@ export const NARRATE_USAGE = [
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
" [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]",
+ " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new",
+ " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)",
" umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]",
" umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… pace=fast|normal engine=… voice=… follow=on|off follow.dim=… follow.ease=…",
" --cut thread.parent=auto|full|excerpt|context|carry|hidden thread.quoted=… thread.carry=auto|on|off thread.reveal=on|off thread.shrink=… thread.dim=… thread.seconds=… thread.pan=…",
diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs
@@ -39,6 +39,7 @@ export const REREAD_USAGE = [
" umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]",
" umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" | --tempo 1.3 --parts 4-16,21-25 [--stretch atempo|rubberband] [--dry-run] [--json]",
" umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]",
+ " (any form, + --in-take <take> or --take <take>: the new take picked in a take's patch, the project's pick kept)",
" A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with",
" the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without",
" drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;",
diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs
@@ -21,7 +21,7 @@ import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarrations } from "./manifest.mjs";
export const ROLES_USAGE = [
- " umtool posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]",
+ " umtool posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json] (+ --in-take <take> or --take <take>: a take's)",
" A READ's PIECES (post-thread.mjs): the text each part of a narrated item's read reads -- parent:<i> (the post it",
" answers, nearest first), quoted, post (his words), media:<i> (an attachment's words, a screenshot) -- its own",
" role, else INFERRED (its piece, para div 100, matched by its word pairs), what the card shows for each (full,",
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -139,6 +139,13 @@ export const POSTS_USAGE = [
" panel=: where the attachments sit -- beside the card, or at full width above (top) or below it (a wide one: auto).",
...ROLES_LINES,
...REREAD_LINES,
+ " umtool posts set-item | roles | narrate | reread | fx <project> … --in-take <take> A TAKE-SCOPED EDIT: the same",
+ " command on a take of the project (`umtool take <p> --id <take> --draft --from <take>` makes one): the manifest read",
+ " as the take's, the write landing in takes/<take>/take.json's patch with an undo point of the take's own (`umtool",
+ " timeline <p> --take <take> undo`); the project's manifest, and the project an imported item came from, untouched. A",
+ " new read's file lands in the project's narration/ under a number no file has. set-item, roles, reread and fx take",
+ " --take <take> for it too; narrate's --take is a new read, so narrate says --in-take. --json: the command's own",
+ " object with take: {id, edits, revisions, undo}. Refused (exit 1) for a take that is not there or renders now.",
" umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix,",
" a thread read (--take --thread) (umtool posts narrate --help)",
" umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
@@ -172,7 +179,7 @@ export const POSTS_USAGE = [
" umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment",
].join("\n");
-const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--parents", "--skip-parent", "--voice-for", "--item"]);
+const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--parents", "--skip-parent", "--voice-for", "--item"]);
/** The valued flags that may be given more than once (each value kept, in order). */
const MULTI = new Set(["--skip-parent", "--voice-for"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
@@ -422,6 +429,15 @@ export async function addPostFromArchive(project, { slug, postId, attach = null,
* @returns {Promise<number>} the exit code
*/
export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ // A TAKE-SCOPED EDIT (`--in-take <take>`, takeScope.mjs): the same command over the take's manifest, written into its patch.
+ let scoped;
+ try {
+ scoped = inTakeArgs(args);
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return 2;
+ }
+ if (scoped) return inTakeCommand(scoped, { root, out, err });
const words = [];
const flags = new Map();
const multis = new Map();
@@ -490,7 +506,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
err(NARRATE_USAGE);
return 2;
}
- return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str, multi });
+ const project = await projectOf(projectArg, root);
+ // `--take` here is "synthesize a new read"; a take's id after it was meant as the take to edit (`--in-take`).
+ if (flags.has("--take")) {
+ const { listTakes } = await import("./takes.mjs");
+ const takes = new Set((await listTakes(project.dir)).takes.map((t) => t.id));
+ const named = words.slice(3).find((w) => takes.has(w));
+ if (named) throw new CliError(`posts narrate: --take makes a NEW READ (TTS); "${named}" is a take of ${project.id} -- to edit take ${named}, say --in-take ${named}`);
+ }
+ return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi });
}
if (verb === "fx") {
const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
@@ -674,6 +698,96 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) {
return 0;
}
+/** The verbs `--in-take <take>` scopes (each writes a post item through manifest.mjs's structural writers). */
+export const IN_TAKE_VERBS = ["set-item", "roles", "narrate", "reread", "fx"];
+/** The verbs whose `--take <take>` is `--in-take <take>` (narrate's `--take` is its own: a new read). */
+const TAKE_ALIAS_VERBS = new Set(["set-item", "roles", "reread", "fx"]);
+
+/**
+ * `--in-take <take>` (or, on set-item/roles/reread/fx, `--take <take>`) taken out of a posts command line:
+ * `{ verb, take, rest }`, or null when the line has neither.
+ * @param {string[]} args
+ */
+export function inTakeArgs(args) {
+ const verb = args.find((a) => !a.startsWith("--")) ?? null;
+ const rest = [];
+ let take = null;
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ const v = args[i + 1];
+ if (a === "--in-take" || (a === "--take" && verb && TAKE_ALIAS_VERBS.has(verb) && v !== undefined && !v.startsWith("--"))) {
+ if (v === undefined || v.startsWith("--")) throw new CliError(`${a} needs a take id`);
+ if (take !== null && take !== v) throw new CliError(`two takes named (${take}, ${v}): one edit, one take`);
+ take = v;
+ i += 1;
+ } else {
+ rest.push(a);
+ if (VALUED.has(a) || a === "--channel") {
+ if (v !== undefined) rest.push(v);
+ i += 1;
+ }
+ }
+ }
+ return take === null ? null : { verb, take, rest };
+}
+
+/**
+ * `umtool posts <verb> <project> … --in-take <take>`: the verb run with the project's manifest READ as the take's and
+ * every write landing in the take's patch (takeScope.mjs) -- the project's manifest, and any project the take's
+ * items came from, untouched. Refused for another verb, a take that is not there, or one rendering now. --json: the
+ * command's own object with `take: { id, edits, undo }`.
+ */
+async function inTakeCommand({ verb, take, rest }, { root, out, err }) {
+ try {
+ if (!verb || !IN_TAKE_VERBS.includes(verb)) throw new CliError(`--in-take <take> works with posts ${IN_TAKE_VERBS.join(", ")} (not posts ${verb ?? "(no verb)"})`);
+ const words = [];
+ for (let i = 0; i < rest.length; i += 1) {
+ if (VALUED.has(rest[i]) || rest[i] === "--channel") i += 1;
+ else if (!rest[i].startsWith("--")) words.push(rest[i]);
+ }
+ if (!words[1]) throw new CliError(`which project? umtool posts ${verb} <project> … --in-take ${take}`);
+ const project = await projectOf(words[1], root);
+ const { isTakeId, takesDirOf, TAKE_FILE } = await import("./takes.mjs");
+ if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id (lower-case letters, digits, dashes)`);
+ if (!(await stat(path.join(takesDirOf(project.dir), take, TAKE_FILE)).catch(() => null))) {
+ err(`${project.id} has no take ${take} (no takes/${take}/${TAKE_FILE}) -- record one: umtool take ${project.id} --id ${take} --draft --from <take>`);
+ return 1;
+ }
+ const { takeRenderingNow } = await import("./takeImport.mjs");
+ const busy = await takeRenderingNow(project.dir, take);
+ if (busy) {
+ err(`not edited: ${busy}`);
+ return 1;
+ }
+ const { withTakeScope } = await import("./takeScope.mjs");
+ const { listTakeRevisions } = await import("./takeEdit.mjs");
+ const autos = async () => (await listTakeRevisions(project.dir, take)).filter((r) => r.auto);
+ const had = new Set((await autos()).map((r) => r.name));
+ const json = rest.includes("--json");
+ const lines = [];
+ const code = await withTakeScope(project.dir, take, () => postsCommand(rest, { root, out: json ? (s) => lines.push(s) : out, err }));
+ const made = (await autos()).filter((r) => !had.has(r.name));
+ const undo = `umtool timeline ${project.id} --take ${take} undo`;
+ const about = { id: take, edits: made.length, revisions: made.map((r) => `takes/${take}/${r.rel}`), undo: made.length ? undo : null };
+ if (json) {
+ for (const l of lines) {
+ let doc = null;
+ try {
+ doc = JSON.parse(l);
+ } catch {
+ doc = null;
+ }
+ out(doc && typeof doc === "object" && !Array.isArray(doc) ? JSON.stringify({ ...doc, take: about }, null, 2) : l);
+ }
+ } else if (made.length) out(` on take ${take} (its patch; ${project.id}'s manifest untouched): ${made.length} edit(s), undo point takes/${take}/${made[0].rel} -- ${undo}`);
+ else if (code === 0) out(` on take ${take}: its patch is unchanged`);
+ return code;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError ? 2 : 1;
+ }
+}
+
async function projectOf(projectArg, root) {
const r = await resolveProject(projectArg, root);
if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -49,6 +49,16 @@ export const TAKE_USAGE = [
" umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,",
" nothing rendered: it can be walked (/projects/<p>/takes/<id>/walk, `umtool walk <p> --take <id>`)",
" and its clips edited into its patch; `umtool take <p> --id <id> --full` renders it later",
+ " umtool take <project> --id <id> --draft --from <take> [--label L] [--patch F | …] a draft made FROM another",
+ " take: its style and patch (then --patch's over it), nothing rendered; its timeline its own from then on",
+ " umtool take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> |",
+ " --before <entry>] [--as <new id>] [--dry-run] [--json] ITEMS OF ANOTHER PROJECT cloned into the take's",
+ " timeline (its patch; one undo point, `umtool timeline <p> --take <id> undo`) with their narration and",
+ " its pick, the files they name (narration takes, parts, attachments, authors' pictures) hard-linked",
+ " into this project's dir (another file at the path: linked under imports/<source>/ instead). The source",
+ " project and this one's manifest are only read. Placed --after/--before an entry (several: in the",
+ " order named), else by date when the take's posts are in date order, else at the end. Again:",
+ " updated in place from the source (`unchanged` when it already is). EXIT 0 ok · 1 refused · 2 usage",
" umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render RECORD",
" (takes/<id>/render.json, written by every render whoever started it): state, stage, percent,",
" the error and the log's last lines, the full log (takes/<id>/render.log); a take waiting in the",
@@ -121,6 +131,7 @@ function parse(args) {
const valued = new Set([
"--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect",
"--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name", "--tail",
+ "--import-item", "--after", "--before", "--as",
]);
/** @type {Record<string, string[]>} */
const flags = {};
@@ -253,6 +264,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
const id = p.one("--id");
if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)");
if (p.has("--promote")) return await promote(project, id, p, log, err);
+ if (p.has("--import-item")) return await importItems(project, id, p, { reportsRoot, log, err });
const draft = p.has("--draft") || p.has("--no-render");
const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null);
// A DRAFT named with no patch of its own is rendered from what it stores --
@@ -289,6 +301,19 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
quick: p.has("--quick"),
};
}
+ // A DRAFT MADE FROM ANOTHER TAKE (`--draft --from <t>`): that take's style and patch, then this one's (if any)
+ // over it -- its timeline its own from then on. A render's --from is only the segments it reuses.
+ if (draft && p.has("--from") && !fromStored) {
+ const fromId = /** @type {string} */ (p.one("--from"));
+ const from = await readFile(path.join(takesDirOf(project.dir), fromId, TAKE_FILE), "utf8").then(JSON.parse, () => null);
+ if (!from) throw new CliError(`${project.id} has no take ${fromId} to draft from (\`umtool takes ls ${project.id}\`)`);
+ const { composePatch } = await import("./takeEdit.mjs");
+ const base = from.patch && typeof from.patch === "object" && !Array.isArray(from.patch) ? from.patch : {};
+ spec.patch = spec.patch ? composePatch(base, spec.patch) : structuredClone(base);
+ if (!p.has("--style") && from.style) spec.style = from.style;
+ if (!p.has("--label") && !spec.label) spec.label = `${from.label ?? fromId} (from ${fromId})`;
+ if (spec.window === undefined && from.window) spec.window = from.window;
+ }
// THE UNCENSORED CUT (post-slurs.mjs): the slur filter off in the take's own patch; the redaction stays.
if (p.has("--uncensored") && !fromStored) {
spec.patch = mergePatch(spec.patch ?? {}, UNCENSORED_PATCH);
@@ -334,6 +359,54 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
}
}
+/**
+ * `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <id> | --before <id>]
+ * [--as <id>] [--dry-run] [--json]`: items of other projects cloned into the take, their files linked in (takeImport.mjs).
+ */
+async function importItems(project, id, p, { reportsRoot, log, err }) {
+ const { ImportRefused, importTakeItems, parseImportRef } = await import("./takeImport.mjs");
+ const refs = [];
+ for (const raw of p.flags["--import-item"]) {
+ const r = parseImportRef(raw);
+ if (!r) throw new CliError(`--import-item takes <project>:<item>[,<item>…] (not ${raw})`);
+ const src = await resolveProject(r.project, reportsRoot);
+ if (src.ambiguous) throw new CliError(`"${r.project}" is the name of ${src.ambiguous.length} projects — pass its id`);
+ if (!src.project) throw new CliError(`no project matches "${r.project}"`);
+ for (const item of r.items) refs.push({ project: src.project, item, as: null });
+ }
+ if (p.has("--as")) {
+ if (refs.length !== 1) throw new CliError("--as names ONE item's id in the take: import one item with it");
+ refs[0].as = /** @type {string} */ (p.one("--as"));
+ if (!/^[A-Za-z0-9._:-]{1,120}$/.test(refs[0].as)) throw new CliError(`--as ${refs[0].as}: an entry id is letters, digits, dots, dashes`);
+ }
+ if (p.has("--after") && p.has("--before")) throw new CliError("--after or --before, not both");
+ try {
+ const r = await importTakeItems(project, id, refs, { after: p.one("--after") ?? null, before: p.one("--before") ?? null, dryRun: p.has("--dry-run") });
+ if (p.has("--json")) {
+ log(JSON.stringify({ ok: true, ...r }, null, 2));
+ return 0;
+ }
+ const verb = r.dryRun ? "would import" : "imported";
+ for (const x of r.items) {
+ const at = x.at ? ` at ${x.at.index}${x.at.after ? `, after ${x.at.after}` : ""}${x.at.before ? `, before ${x.at.before}` : ""}` : "";
+ log(`${x.id}: ${r.dryRun ? `would be ${x.action}` : x.action} from ${x.ref}${at}`);
+ if (x.narration) log(` narration: ${x.narration.takes} take(s), pick ${x.narration.pick ?? "none"}${x.narration.file ? ` (${x.narration.file})` : ""}`);
+ const linked = x.files.filter((f) => !f.how.startsWith("already"));
+ if (x.files.length) log(` files: ${linked.length} ${r.dryRun ? "to link" : "linked"}, ${x.files.length - linked.length} already there${linked.some((f) => f.was) ? `; renamed (another file had the path): ${linked.filter((f) => f.was).map((f) => `${f.was} -> ${f.path}`).join(", ")}` : ""}`);
+ if (x.avatars.length) log(` authors' pictures added: ${x.avatars.join(", ")}`);
+ if (x.missing.length) err(` named but not in ${x.source}: ${x.missing.join(", ")}`);
+ }
+ log(r.unchanged ? `take ${id}: nothing changed (already imported as it is)` : r.dryRun ? `take ${id}: a dry run, nothing written (${verb} ${r.items.length} item(s))` : `take ${id}: ${r.items.length} item(s); undo point ${r.revision} (umtool timeline ${project.id} --take ${id} undo)`);
+ return 0;
+ } catch (e) {
+ if (e instanceof ImportRefused) {
+ err(e.message);
+ return 1;
+ }
+ throw e;
+ }
+}
+
/** `umtool take <p> --id X --promote [--anyway]`: make the take the cut (takeEdit.mjs promoteTake). */
async function promote(project, id, p, log, err) {
const { PromoteStale, promoteTake } = await import("./takeEdit.mjs");
diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs
@@ -176,6 +176,97 @@ async function editTakeTimeline(projectDir, id, op, token, mutate, { now = new D
});
}
+// THE PATCH ARITHMETIC of a take-scoped edit (editTakeManifest): what the edit
+// changed outside the timeline, as a merge patch of the take's resolved
+// manifest (diffPatch), composed onto the take's own patch (composePatch) so
+// that applying the composed patch to the project's manifest gives what the
+// edit left -- the keys the take's patch already set are kept, a key the edit
+// removes is `null` (removed from the project's too), and an array is whole.
+
+/** The RFC 7386 merge patch that takes `a` to `b`; undefined when they are the same. */
+export function diffPatch(a, b) {
+ if (JSON.stringify(a) === JSON.stringify(b)) return undefined;
+ if (!isObj(a) || !isObj(b)) return b === undefined ? null : clone(b);
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) {
+ if (!(k in b)) out[k] = null;
+ else if (!(k in a)) out[k] = clone(b[k]);
+ else {
+ const d = diffPatch(a[k], b[k]);
+ if (d !== undefined) out[k] = d;
+ }
+ }
+ return Object.keys(out).length ? out : undefined;
+}
+
+/** A merge patch with its nulls dropped (what it sets when nothing is under it). */
+const stripNulls = (v) => (isObj(v) ? Object.fromEntries(Object.entries(v).filter(([, x]) => x !== null).map(([k, x]) => [k, stripNulls(x)])) : clone(v));
+
+/**
+ * `p` then `d` as ONE merge patch: mergePatch(base, composePatch(p, d)) is
+ * mergePatch(mergePatch(base, p), d) for the shapes a manifest has -- a null in
+ * `d` stays a null (removed from the base too), an object merges into what `p`
+ * set, and an object over a key `p` replaced with something else is all of it.
+ */
+export function composePatch(p, d) {
+ const out = isObj(p) ? clone(p) : {};
+ for (const [k, v] of Object.entries(isObj(d) ? d : {})) {
+ if (v === null) out[k] = null;
+ else if (isObj(v) && isObj(out[k])) out[k] = composePatch(out[k], v);
+ else if (isObj(v) && k in out) out[k] = stripNulls(v);
+ else out[k] = clone(v);
+ }
+ return out;
+}
+
+/**
+ * ONE WRITE TO A TAKE'S MANIFEST, whatever it changes (a take-scoped edit,
+ * takeScope.mjs; the take's item import, importTakeItems): the token, the
+ * take's manifest resolved as it is now, `mutate` over it (which throws to
+ * refuse; it may be async), then -- only when something changed -- the undo
+ * point and take.json's patch: the WHOLE timeline when the timeline changed
+ * (as editTakeTimeline writes it), and every other change composed onto the
+ * patch (diffPatch, composePatch). The project's manifest is never touched.
+ * Nothing changed: no write, no undo point, `unchanged: true`.
+ *
+ * @template T
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {string} op
+ * @param {string | null} token
+ * @param {(manifest: Record<string, any>) => T | Promise<T>} mutate
+ * @param {{ now?: Date, dryRun?: boolean }} [opts]
+ * @returns {Promise<Awaited<T> & { token: string | null, revision: { rel: string, name: string } | null, unchanged: boolean, take: string, snapshot: null, patchKeys: string[] }>}
+ */
+export async function editTakeManifest(projectDir, id, op, token, mutate, { now = new Date(), dryRun = false } = {}) {
+ return withTakeEditLock(async () => {
+ const current = await takeToken(projectDir, id);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const { text, doc } = await readTakeDoc(projectDir, id);
+ const resolved = await resolveTakeManifest(projectDir, id);
+ const before = clone(resolved.manifest);
+ const manifest = clone(resolved.manifest);
+ const result = await mutate(manifest);
+ const { timeline: tlBefore, ...restBefore } = before;
+ const { timeline: tlAfter, ...restAfter } = manifest;
+ const timelineChanged = JSON.stringify(tlBefore) !== JSON.stringify(tlAfter);
+ const rest = diffPatch(restBefore, restAfter);
+ const patchKeys = [...(timelineChanged ? ["timeline"] : []), ...Object.keys(rest ?? {})];
+ // The project's snapshot is not this write's: `snapshot: null`, and the undo point is the take's `revision`.
+ const same = { take: id, snapshot: null, patchKeys };
+ if (!timelineChanged && rest === undefined) return { ...result, ...same, token: current, revision: null, unchanged: true };
+ if (dryRun) return { ...result, ...same, token: current, revision: null, unchanged: false, dryRun: true };
+ const revision = await keepRevision(projectDir, id, text, `${AUTO}${op}`, now);
+ const patch = rest ? composePatch(isObj(doc.patch) ? doc.patch : {}, rest) : isObj(doc.patch) ? clone(doc.patch) : {};
+ if (timelineChanged) patch.timeline = tlAfter;
+ doc.patch = patch;
+ doc.editedAt = now.toISOString();
+ const nextToken = await writeTakeAtomic(projectDir, id, doc);
+ return { ...result, ...same, token: nextToken, revision, unchanged: false };
+ });
+}
+
/**
* The bench's save, on a take: one clip's window, locks, attribution,
* verdict and the rest -- updateClip's whitelist and its rules
diff --git a/umtool/lib/report/takeImport.mjs b/umtool/lib/report/takeImport.mjs
@@ -0,0 +1,349 @@
+// AN ITEM OF ANOTHER PROJECT, INTO A TAKE (slice C of "the apps do the work",
+// 4 Nov; it replaces mid-assemble's sources.json and the hand links):
+//
+// umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--import-item …]
+// [--after <id> | --before <id>] [--as <new id>] [--dry-run] [--json]
+//
+// The entry is CLONED from the source project's manifest as it is now -- its
+// card, its context, its knobs, its narration with its takes and its pick --
+// into take <t>'s timeline (its patch, takeEdit.mjs editTakeManifest: one undo
+// point of the take's, `umtool timeline <p> --take <t> undo`). The source
+// project is only read. <p>'s manifest is never touched.
+//
+// THE FILES IT NAMES come too, HARD-LINKED into <p>'s dir at the same relative
+// path, so the take's render (and the lint) finds them beside <p>'s manifest:
+// every string of the entry that is a project-relative path to a file of the
+// source (a narration take, its parts' cache files, an attachment, a context
+// post's media), a narration take's sidecars (`take-<n>.*` beside it: its parts
+// meta), and the picture of each author it draws that the take has none for
+// (the source's `postAvatars`, added to the take's).
+//
+// the path free in <p> linked (copied when the two are on other filesystems)
+// the same file there (inode or bytes) left as it is
+// ANOTHER file there linked under imports/<source>/<path> instead, and the
+// clone names that path (never written over)
+// a directory of <p> that leads out of refused: a link there would write into somebody else's
+// it (a symlink) tree
+//
+// PLACEMENT: --after/--before an entry of the take; several items keep the
+// order they are named in, one after the other. Without either: by the post's
+// date when the take's posts are in date order (each before the first post
+// that is later), else at the end.
+//
+// AGAIN: an item already in the take (by its id, or --as's) is UPDATED in place
+// from the source as it is now (its files linked again as above) -- moved only
+// when --after/--before is given -- and an update that changes nothing writes
+// nothing (`unchanged`): re-running an import is safe.
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
+import path from "node:path";
+import { handleKey } from "umtool-report-to-video/post-avatars";
+import { applyStructural } from "./manifest.mjs";
+import { editTakeManifest, takeToken } from "./takeEdit.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+
+export const IMPORTS_DIR = "imports";
+
+export class ImportRefused extends Error {
+ /** @param {string} message */
+ constructor(message) {
+ super(message);
+ this.name = "ImportRefused";
+ }
+}
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const clone = (v) => JSON.parse(JSON.stringify(v));
+
+/**
+ * `<project>:<item>[,<item>…]` → `{ project, items }` (the LAST colon splits: a project id has slashes, never a
+ * colon). null when it is not that shape.
+ * @param {string} ref
+ */
+export function parseImportRef(ref) {
+ const s = String(ref ?? "");
+ const i = s.lastIndexOf(":");
+ if (i <= 0 || i === s.length - 1) return null;
+ const items = s.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean);
+ return items.length ? { project: s.slice(0, i), items } : null;
+}
+
+/** The entry `ref` names in a timeline: its id, its post's id, or `p-<postId>`. */
+export function findEntry(timeline, ref) {
+ const r = String(ref ?? "");
+ const tl = Array.isArray(timeline) ? timeline : [];
+ return tl.find((e) => isObj(e) && e.id === r) ?? tl.find((e) => isObj(e) && (String(e.post ?? "").split("/")[1] === r || e.id === `p-${r}`)) ?? null;
+}
+
+/** A string that may name a file of the project: relative, no `..`, no scheme, a directory in it, one line. */
+const pathLike = (s) =>
+ typeof s === "string" && s.length < 512 && s.includes("/") && !/[\n\r\t]/.test(s) && !/^[a-z][a-z0-9+.-]*:/i.test(s) && !s.startsWith("/") && !s.startsWith("~") && !s.split("/").includes("..") && !s.split("/").includes("");
+
+/** Every path-like string in `v`, deep. */
+function pathStrings(v, out = new Set()) {
+ if (Array.isArray(v)) v.forEach((x) => pathStrings(x, out));
+ else if (isObj(v)) Object.values(v).forEach((x) => pathStrings(x, out));
+ else if (pathLike(v)) out.add(v);
+ return out;
+}
+
+/** `v` with each string `map` names replaced, deep. */
+function renamePaths(v, map) {
+ if (!map.size) return v;
+ if (Array.isArray(v)) return v.map((x) => renamePaths(x, map));
+ if (isObj(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, renamePaths(x, map)]));
+ return typeof v === "string" && map.has(v) ? map.get(v) : v;
+}
+
+/** The handles an entry draws: its own, its context posts', its quoted post's, its links'. */
+export function entryHandles(e) {
+ const hs = [e?.handle, e?.quoted?.handle, ...(Array.isArray(e?.parents) ? e.parents.map((p) => p?.handle) : []), ...(Array.isArray(e?.links) ? e.links.map((l) => l?.handle) : [])];
+ return [...new Set(hs.filter((h) => typeof h === "string" && h.trim()).map(handleKey))];
+}
+
+async function sha256(file) {
+ const h = createHash("sha256");
+ for await (const chunk of createReadStream(file)) h.update(chunk);
+ return h.digest("hex");
+}
+
+/** Are two files the same file, or the same bytes? */
+async function sameFile(a, b) {
+ const [x, y] = await Promise.all([stat(a), stat(b)]);
+ if (x.dev === y.dev && x.ino === y.ino) return "inode";
+ if (x.size !== y.size) return null;
+ return (await sha256(a)) === (await sha256(b)) ? "bytes" : null;
+}
+
+/** The project dir `rel`'s directory would be written in, refused when a link in it leads out of the project. */
+async function assertInside(projectDir, rel) {
+ const root = await realpath(projectDir);
+ // The nearest directory of the path that exists: a link there is where the write would land.
+ let dir = path.dirname(path.join(projectDir, rel));
+ while (!(await lstat(dir).catch(() => null))) dir = path.dirname(dir);
+ const real = await realpath(dir);
+ if (real !== root && !real.startsWith(root + path.sep)) {
+ throw new ImportRefused(`${path.relative(projectDir, dir) || "."} leads out of the project (a link, to ${real}) -- not linking ${rel} through it`);
+ }
+}
+
+/**
+ * A narration take's sidecars: the other `take-<n>.*` files beside `rel` in the source (its parts meta, its words).
+ * @param {string} srcDir
+ * @param {string} rel
+ */
+async function sidecarsOf(srcDir, rel) {
+ const m = /^(narration\/posts\/[^/]+)\/(take-\d+)\.[^/]+$/.exec(rel);
+ if (!m) return [];
+ const names = await readdir(path.join(srcDir, m[1])).catch(() => []);
+ return names.filter((n) => n.startsWith(`${m[2]}.`)).map((n) => `${m[1]}/${n}`).filter((r) => r !== rel);
+}
+
+/**
+ * The plan for one file: `{ rel, to, how }` -- how is "link" (free), "same" (that file is there), or "renamed"
+ * (another file there: linked under imports/<source>/), or null when the source has no such file.
+ */
+async function planFile(srcDir, dstDir, rel, sourceSlug) {
+ const from = path.join(srcDir, rel);
+ const st = await stat(from).catch(() => null);
+ if (!st?.isFile()) return null;
+ for (const to of [rel, `${IMPORTS_DIR}/${sourceSlug}/${rel}`]) {
+ const at = path.join(dstDir, to);
+ if (!(await lstat(at).catch(() => null))) return { rel, to, from, how: to === rel ? "link" : "renamed" };
+ const same = await sameFile(from, at).catch(() => null);
+ if (same) return { rel, to, from, how: "same", same };
+ }
+ throw new ImportRefused(`${rel}: another file is at ${rel} and at ${IMPORTS_DIR}/${sourceSlug}/${rel} in the project -- not writing over either`);
+}
+
+/** Link (else copy, across filesystems) one planned file into the project. */
+async function placeFile(dstDir, f) {
+ await assertInside(dstDir, f.to);
+ const at = path.join(dstDir, f.to);
+ await mkdir(path.dirname(at), { recursive: true });
+ try {
+ await link(f.from, at);
+ return "linked";
+ } catch (e) {
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EXDEV") throw e;
+ await copyFile(f.from, at);
+ return "copied";
+ }
+}
+
+/** Is the take rendering now (its own build lock live)? The sentence, or null. */
+async function renderingNow(projectDir, take) {
+ const { BUILD_LOCK, lockIsLive, readBuildLock } = await import("./takePrune.mjs");
+ const lock = await readBuildLock(path.join(projectDir, "takes", take, BUILD_LOCK));
+ return lock && lockIsLive(lock) ? `take ${take} is rendering now (pid ${lock.pid}${lock.startedAt ? `, since ${lock.startedAt}` : ""}) -- wait for it, or cancel it` : null;
+}
+export { renderingNow as takeRenderingNow };
+
+/** Do the take's post items stand in date order (each no earlier than the one before)? */
+export function postsInDateOrder(timeline) {
+ let last = -Infinity;
+ for (const e of timeline) {
+ if (!isObj(e) || e.type !== "post") continue;
+ const t = Date.parse(String(e.date ?? ""));
+ if (!Number.isFinite(t)) return false;
+ if (t < last) return false;
+ last = t;
+ }
+ return true;
+}
+
+/**
+ * IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file).
+ *
+ * @param {{ id: string, dir: string }} project the take's project
+ * @param {string} take
+ * @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs
+ * @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts]
+ */
+export async function importTakeItems(project, take, refs, { after = null, before = null, dryRun = false, now = new Date() } = {}) {
+ if (!refs.length) throw new ImportRefused("nothing to import");
+ if (after && before) throw new ImportRefused("--after or --before, not both");
+ const busy = await renderingNow(project.dir, take);
+ if (busy) throw new ImportRefused(`not imported: ${busy}`);
+ const takeNow = await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take
+ const tl = takeNow.manifest.timeline;
+ const anchor = after ?? before;
+ if (anchor && !findEntry(tl, anchor)) throw new ImportRefused(`take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`);
+
+ // Each source manifest read once, as it is on disk (never a take of it).
+ /** @type {Map<string, Record<string, any>>} */
+ const sources = new Map();
+ const plans = [];
+ const seen = new Set();
+ for (const r of refs) {
+ if (!sources.has(r.project.dir)) {
+ const text = await readFile(path.join(r.project.dir, "video.manifest.json"), "utf8").catch(() => null);
+ if (text === null) throw new ImportRefused(`${r.project.id} has no video.manifest.json`);
+ sources.set(r.project.dir, JSON.parse(text));
+ }
+ const src = /** @type {Record<string, any>} */ (sources.get(r.project.dir));
+ const e = findEntry(src.timeline, r.item);
+ if (!e) throw new ImportRefused(`${r.project.id} has no item ${r.item} (its id, or its post's id)`);
+ const id = r.as ?? e.id;
+ if (seen.has(id)) throw new ImportRefused(`${id} is named twice -- import it once (or give the second --as <id>)`);
+ seen.add(id);
+ const same = path.resolve(r.project.dir) === path.resolve(project.dir);
+ const slug = r.project.id.replace(/[^A-Za-z0-9._-]+/g, "__");
+ // The files it names, their sidecars, and the pictures of the authors it draws that the take has none for.
+ const rels = new Set(pathStrings(e));
+ for (const rel of [...rels]) for (const s of await sidecarsOf(r.project.dir, rel)) rels.add(s);
+ const have = isObj(takeNow.manifest.postAvatars) ? takeNow.manifest.postAvatars : {};
+ const haveKeys = new Set(Object.keys(have).map(handleKey));
+ const srcAvatars = isObj(src.postAvatars) ? src.postAvatars : {};
+ const avatars = {};
+ for (const h of entryHandles(e)) {
+ if (haveKeys.has(h)) continue;
+ const k = Object.keys(srcAvatars).find((x) => handleKey(x) === h);
+ if (!k || !isObj(srcAvatars[k])) continue;
+ avatars[k] = clone(srcAvatars[k]);
+ if (pathLike(srcAvatars[k].src)) rels.add(srcAvatars[k].src);
+ }
+ const files = [];
+ const missing = [];
+ if (!same) {
+ for (const rel of [...rels].sort()) {
+ const f = await planFile(r.project.dir, project.dir, rel, slug);
+ if (f) files.push(f);
+ else if (/^(narration|posts-media)\//.test(rel)) missing.push(rel);
+ }
+ }
+ const renames = new Map(files.filter((f) => f.to !== f.rel).map((f) => [f.rel, f.to]));
+ const entry = renamePaths({ ...clone(e), id }, renames);
+ for (const a of Object.values(avatars)) if (isObj(a) && renames.has(a.src)) a.src = renames.get(a.src);
+ plans.push({ ref: `${r.project.id}:${r.item}`, source: r.project.id, id, entry, files, missing, avatars });
+ }
+
+ // The files first: a take whose entry names a file not there would render a broken card.
+ if (!dryRun) {
+ /** @type {Map<string, string>} the paths placed by this import (two items naming one file) */
+ const placedTo = new Map();
+ for (const p of plans) {
+ for (const f of p.files) {
+ if (f.how === "same") continue;
+ f.done = placedTo.get(f.to) ?? (await placeFile(project.dir, f));
+ placedTo.set(f.to, f.done);
+ }
+ }
+ }
+
+ const placed = [];
+ const write = await editTakeManifest(
+ project.dir,
+ take,
+ "import-item",
+ await takeToken(project.dir, take),
+ (m) =>
+ applyStructural(m, (mm) => {
+ const timeline = mm.timeline;
+ const order = timeline.map((x) => (isObj(x) ? x.id : null)).join("\n");
+ let cursor = null; // the id the next item goes after (several items keep their order)
+ for (const p of plans) {
+ const at = timeline.findIndex((x) => isObj(x) && x.id === p.id);
+ const was = at >= 0 ? timeline[at] : null;
+ let action;
+ if (was && !anchor) {
+ action = JSON.stringify(was) === JSON.stringify(p.entry) ? "unchanged" : "updated";
+ timeline[at] = p.entry;
+ } else {
+ if (was) timeline.splice(at, 1);
+ let i;
+ if (cursor) i = timeline.findIndex((x) => x.id === cursor) + 1;
+ else if (after) i = timeline.findIndex((x) => x.id === findEntry(timeline, after)?.id) + 1;
+ else if (before) i = timeline.findIndex((x) => x.id === findEntry(timeline, before)?.id);
+ else if (postsInDateOrder(timeline) && Number.isFinite(Date.parse(String(p.entry.date ?? "")))) {
+ const t = Date.parse(String(p.entry.date));
+ i = timeline.findIndex((x) => isObj(x) && x.type === "post" && Date.parse(String(x.date ?? "")) > t);
+ if (i < 0) i = timeline.length;
+ } else i = timeline.length;
+ if (i < 0) i = timeline.length;
+ timeline.splice(i, 0, p.entry);
+ action = was ? (JSON.stringify(was) === JSON.stringify(p.entry) ? "moved" : "updated") : "added";
+ }
+ if (anchor) cursor = p.id;
+ if (Object.keys(p.avatars).length) mm.postAvatars = { ...(isObj(mm.postAvatars) ? mm.postAvatars : {}), ...p.avatars };
+ placed.push({ id: p.id, action });
+ }
+ // Placed where it already stood, as it was: unchanged, not moved.
+ if (timeline.map((x) => (isObj(x) ? x.id : null)).join("\n") === order) for (const pl of placed) if (pl.action === "moved") pl.action = "unchanged";
+ // Where each one stands now (a dry run says it too).
+ for (const pl of placed) {
+ const i = timeline.findIndex((x) => isObj(x) && x.id === pl.id);
+ pl.at = { index: i, after: i > 0 ? timeline[i - 1].id : null, before: i + 1 < timeline.length ? timeline[i + 1].id : null };
+ }
+ return { ids: plans.map((p) => p.id) };
+ }),
+ { now, dryRun },
+ );
+ const items = plans.map((p) => {
+ const pl = placed.find((x) => x.id === p.id);
+ const n = isObj(p.entry.narration) ? p.entry.narration : null;
+ const takes = Array.isArray(n?.takes) ? n.takes : [];
+ const pick = Number.isInteger(n?.pick) ? n.pick : takes.length ? 0 : null;
+ return {
+ ref: p.ref,
+ source: p.source,
+ id: p.id,
+ action: pl?.action ?? "unchanged",
+ at: pl?.at ?? null,
+ narration: n ? { takes: takes.length, pick: pick === null ? null : pick + 1, file: pick === null ? null : takes[pick]?.file ?? null } : null,
+ files: p.files.map((f) => ({ path: f.to, ...(f.to !== f.rel ? { was: f.rel } : {}), how: f.how === "same" ? "already there" : dryRun ? (f.how === "renamed" ? "would link (renamed)" : "would link") : f.done === "copied" ? "copied" : f.how === "renamed" ? "linked (renamed)" : "linked" })),
+ missing: p.missing,
+ avatars: Object.keys(p.avatars),
+ };
+ });
+ return {
+ project: project.id,
+ take,
+ dryRun,
+ unchanged: write.unchanged,
+ items,
+ revision: write.revision ? `takes/${take}/${write.revision.rel}` : null,
+ token: write.token,
+ };
+}
diff --git a/umtool/lib/report/takeScope.mjs b/umtool/lib/report/takeScope.mjs
@@ -0,0 +1,85 @@
+// A TAKE-SCOPED EDIT (slice C of "the apps do the work", 4 Nov): run an
+// existing manifest command -- `umtool posts set-item`, `posts roles`, `posts
+// narrate`, `posts reread`, `posts fx` -- against a TAKE of the project
+// instead of the project's manifest.
+//
+// withTakeScope(projectDir, take, fn) fn runs with the project's manifest
+// READ as the take's (takeManifest.mjs
+// resolveTakeManifest: the project's now
+// + the style's patch + the take's) and
+// every write landing in the take's
+// patch (takeEdit.mjs editTakeManifest)
+//
+// The commands are not rewritten for it. They read through readManifest
+// (projects/report.mjs), take a token from manifestToken, and write through
+// manifest.mjs's `structural` -- and those three ask takeScopeOf(dir) first:
+//
+// readManifest(dir) the take's resolved manifest
+// manifestToken(dir) take.json's mtime (the take's own token)
+// structural(dir, …) the mutation applied to the take's manifest, written
+// into takes/<id>/take.json's patch with an undo point
+// of the take's own (`umtool timeline <p> --take <id> undo`)
+// writeManifestAtomic REFUSED (TakeScopeRefused): a writer that has not been
+// routed to the take would otherwise change the
+// project's manifest, which a take-scoped edit never does
+// withEditNotes no edit notes: the take's patch is not the generated
+// manifest, so there is nothing for its generator to port
+//
+// Files a scoped command makes (a new read's wav, its parts) land in the
+// project's own dirs exactly as an unscoped one's do -- the take renders from
+// the project's dir (takeMaker.mjs renderManifestPath), so it finds them -- and
+// their names come from nextTakeNumber over the take's entry AND the files on
+// disk, so a take's read never overwrites one the project's manifest names.
+//
+// The scope is an AsyncLocalStorage store, so it follows the command through
+// every await and never leaks into a concurrent request of the app. It names
+// ONE project dir: a read or write of any other project inside it is the
+// plain, unscoped one.
+//
+// Plain ESM with no imports of the writers (they import this): the CLI runs it
+// under bare node.
+import { AsyncLocalStorage } from "node:async_hooks";
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import { TAKE_FILE, isTakeId, takesDirOf } from "./takes.mjs";
+
+/** @type {AsyncLocalStorage<{ dir: string, take: string }>} */
+const als = new AsyncLocalStorage();
+
+export class TakeScopeRefused extends Error {
+ /** @param {string} message */
+ constructor(message) {
+ super(message);
+ this.name = "TakeScopeRefused";
+ }
+}
+
+/**
+ * Run `fn` with `projectDir`'s manifest read and written as take `take`'s.
+ * @template T
+ * @param {string} projectDir
+ * @param {string} take
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export function withTakeScope(projectDir, take, fn) {
+ if (!isTakeId(take)) throw new TakeScopeRefused(`"${take}" is not a take id (lower-case letters, digits, dashes)`);
+ return als.run({ dir: path.resolve(projectDir), take }, fn);
+}
+
+/**
+ * The take a read or write of `dir` is scoped to, or null (no scope, or a scope of another project).
+ * @param {string} dir
+ * @returns {{ dir: string, take: string } | null}
+ */
+export function takeScopeOf(dir) {
+ const s = als.getStore();
+ if (!s || typeof dir !== "string") return null;
+ return path.resolve(dir) === s.dir ? s : null;
+}
+
+/** The scoped take's token (its take.json's mtime, takeEdit.mjs takeToken's), or null when it has none. */
+export async function scopedTakeToken(scope) {
+ const st = await stat(path.join(takesDirOf(scope.dir), scope.take, TAKE_FILE)).catch(() => null);
+ return st ? String(Math.round(st.mtimeMs)) : null;
+}
diff --git a/umtool/lib/report/takeScope.test.mjs b/umtool/lib/report/takeScope.test.mjs
@@ -0,0 +1,300 @@
+// TAKE-SCOPED EDITS (takeScope.mjs) and A TAKE'S ITEMS FROM OTHER PROJECTS
+// (takeImport.mjs): `posts set-item|roles|narrate|reread|fx … --in-take <t>`
+// write the take's patch and never the project's manifest; `take --import-item
+// <project>:<item>` clones an item into a take with its files hard-linked in,
+// placed, idempotent; `take --draft --from <t>` starts a draft from a take's
+// patch; and the editor's token is found in its env files.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { composePatch, diffPatch, listTakeRevisions } from "./takeEdit.mjs";
+import { mergePatch } from "umtool-report-to-video/montage-styles";
+import { TakeScopeRefused, withTakeScope } from "./takeScope.mjs";
+import { updateRender } from "./manifest.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+import { postsInDateOrder, parseImportRef } from "./takeImport.mjs";
+import { lintCommand, namedFileProblems } from "./lintCli.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { takeCommand } from "./takeCli.mjs";
+import { timelineCommand } from "./timelineCli.mjs";
+import { editorFromEnv } from "umtool-report-to-video/narrate-via-editor";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-take-scope-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+let haveFfmpeg = true;
+try {
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+} catch {
+ haveFfmpeg = false;
+}
+
+const REPLY = "That is exactly what I was saying yesterday morning.";
+const PARENT = "The first thing anyone notices is the noise from the street.";
+const post = (id, date, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date, text: `${REPLY} ${id}`,
+ ...o,
+});
+const narrated = (id, date, o = {}) =>
+ post(id, date, {
+ parents: [{ id: `9${id}`, author: "Neighbour", handle: "neighbour_one", date: "2026-10-29T10:00:00.000Z", text: PARENT }],
+ narration: {
+ script: REPLY,
+ takes: [{
+ file: `narration/posts/${id}/take-1.orpheus-thread.wav`, engine: "orpheus", voice: "leo+zac", seconds: 6,
+ parts: [
+ { n: 1, para: 0, text: PARENT, voice: "leo", role: "parent:0", piece: 0, file: `narration/parts-cache/${id}a.wav`, start: 0, seconds: 3 },
+ { n: 2, para: 100, text: REPLY, voice: "zac", role: "post", piece: 1, file: `narration/parts-cache/${id}b.wav`, start: 3.5, seconds: 2.5 },
+ ],
+ }],
+ pick: 0,
+ },
+ ...o,
+ });
+
+async function tone(file, seconds = 6) {
+ await mkdir(path.dirname(file), { recursive: true });
+ if (haveFfmpeg) execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", `sine=frequency=220:duration=${seconds}:sample_rate=24000`, file]);
+ else await writeFile(file, `tone ${seconds}`);
+}
+
+async function project(name, timeline, extra = {}) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline, ...extra }, null, 2) + "\n");
+ return { id: name, dir };
+}
+const text = (p) => readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+const takeDoc = async (p, t) => JSON.parse(await readFile(path.join(p.dir, "takes", t, "take.json"), "utf8"));
+async function cli(fn, args) {
+ const out = [];
+ const err = [];
+ const code = await fn(args, { root: REPORTS, reportsRoot: REPORTS, out: (s) => out.push(s), log: (s) => out.push(s), err: (s) => err.push(s) });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+}
+const posts = (...args) => cli(postsCommand, args);
+const take = (...args) => cli(takeCommand, args);
+
+test("THE PATCH ARITHMETIC: a diff composed onto a take's patch gives, over the project's manifest, what the edit left", () => {
+ const base = { render: { a: 1, b: { c: 2, d: 3 }, list: [1, 2] }, keep: "x" };
+ const p = { render: { b: { c: 5 }, e: 7 }, drop: null };
+ const resolved = mergePatch(base, p);
+ const edited = structuredClone(resolved);
+ edited.render.b.d = 9;
+ delete edited.render.a;
+ edited.render.list = [3];
+ edited.added = { z: 1 };
+ const d = diffPatch(resolved, edited);
+ assert.deepEqual(d, { render: { a: null, b: { d: 9 }, list: [3] }, added: { z: 1 } });
+ assert.deepEqual(mergePatch(base, composePatch(p, d)), edited);
+ assert.equal(diffPatch(resolved, structuredClone(resolved)), undefined, "nothing changed: no patch");
+ assert.deepEqual(parseImportRef("emberparadox/mr-obvious-mid-stage:p-1,p-2"), { project: "emberparadox/mr-obvious-mid-stage", items: ["p-1", "p-2"] });
+ assert.equal(parseImportRef("no-colon"), null);
+ assert.equal(postsInDateOrder([post("1", "2026-10-01T00:00:00Z"), { type: "clip", id: "c" }, post("2", "2026-10-02T00:00:00Z")]), true);
+ assert.equal(postsInDateOrder([post("2", "2026-10-02T00:00:00Z"), post("1", "2026-10-01T00:00:00Z")]), false);
+});
+
+test("--in-take: set-item, narrate --pick, roles --set and fx land in the take's patch -- the project's manifest byte for byte the same; undo takes each back", async () => {
+ const a = await project("scope-a", [post("1", "2026-10-30T10:00:00.000Z"), narrated("2", "2026-10-30T11:00:00.000Z", { narration: { ...narrated("2", "x").narration, takes: [narrated("2", "x").narration.takes[0], { ...narrated("2", "x").narration.takes[0], file: "narration/posts/2/take-2.orpheus-thread.wav" }] } })]);
+ const before = await text(a);
+ assert.equal((await take("scope-a", "--id", "t1", "--label", "T one", "--draft")).code, 0);
+ // set-item: one knob, into the take's timeline.
+ let r = await posts("set-item", "scope-a", "p-1", "hold=4", "--in-take", "t1");
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /on take t1 \(its patch; scope-a's manifest untouched\): 1 edit\(s\), undo point takes\/t1\/revisions\/.*-auto-before-post-item\.take\.json -- umtool timeline scope-a --take t1 undo/);
+ assert.equal(await text(a), before, "the project's manifest is never written");
+ assert.equal((await takeDoc(a, "t1")).patch.timeline.find((e) => e.id === "p-1").hold, 4);
+ // The alias: set-item's --take <t> is --in-take <t>; --json is the command's own object with the take.
+ r = await posts("set-item", "scope-a", "p-1", "thread.group=g1", "--take", "t1", "--json");
+ assert.equal(r.code, 0, r.err);
+ const doc = JSON.parse(r.out);
+ assert.equal(doc.ok, true);
+ assert.equal(doc.entry.thread.group, "g1");
+ assert.equal(doc.take.id, "t1");
+ assert.equal(doc.take.edits, 1);
+ assert.equal(doc.take.undo, "umtool timeline scope-a --take t1 undo");
+ // narrate --pick (1 = the first) in the take.
+ r = await posts("narrate", "scope-a", "p-2", "--pick", "2", "--in-take", "t1");
+ assert.equal(r.code, 0, r.err);
+ assert.equal((await resolveTakeManifest(a.dir, "t1")).manifest.timeline.find((e) => e.id === "p-2").narration.pick, 1);
+ assert.equal(JSON.parse(await text(a)).timeline[1].narration.pick, 0, "the project's pick is its own");
+ // roles --set and fx in the take.
+ r = await posts("roles", "scope-a", "p-2", "--set", "1=parent:0,2=post", "--in-take", "t1");
+ assert.equal(r.code, 0, r.err + r.out);
+ assert.match(r.out, /on take t1: its patch is unchanged/, "the roles it already stores: no write, no undo point");
+ r = await posts("fx", "scope-a", "p-2", "add", "caption", "--match", "exactly", "--text", "A word", "--in-take", "t1");
+ assert.equal(r.code, 0, r.err + r.out);
+ const tl = (await resolveTakeManifest(a.dir, "t1")).manifest.timeline;
+ assert.equal(tl.find((e) => e.id === "p-2").fx.length, 1);
+ assert.equal(await text(a), before, "still untouched");
+ // Each edit is an undo point of the take's; undo takes the newest back.
+ const autos = (await listTakeRevisions(a.dir, "t1")).filter((x) => x.auto);
+ assert.equal(autos.length, 4, "set-item twice, the pick, the caption");
+ const u = await cli(timelineCommand, ["scope-a", "--take", "t1", "undo"]);
+ assert.equal(u.code, 0, u.err);
+ assert.equal((await resolveTakeManifest(a.dir, "t1")).manifest.timeline.find((e) => e.id === "p-2").fx, undefined);
+});
+
+test("--in-take refuses what it cannot do: no such take (1), another verb (2), a writer not routed to the take writes nothing (TakeScopeRefused), narrate --take <a take> is named", async () => {
+ const a = await project("scope-b", [post("1", "2026-10-30T10:00:00.000Z")]);
+ const before = await text(a);
+ let r = await posts("set-item", "scope-b", "p-1", "hold=4", "--in-take", "nope");
+ assert.equal(r.code, 1);
+ assert.match(r.err, /has no take nope/);
+ assert.equal((await take("scope-b", "--id", "t1", "--label", "T", "--draft")).code, 0);
+ r = await posts("avatar", "scope-b", "--in-take", "t1");
+ assert.equal(r.code, 2);
+ assert.match(r.err, /works with posts set-item, roles, narrate, reread, fx/);
+ // A writer that is not routed (updateRender writes the manifest directly): refused, the manifest untouched.
+ await assert.rejects(withTakeScope(a.dir, "t1", () => updateRender(a.dir, { transition: 0.3 })), TakeScopeRefused);
+ assert.equal(await text(a), before);
+ // Reads in the scope are the take's; outside it, the project's.
+ assert.equal(await withTakeScope(a.dir, "t1", async () => (await readManifest(a.dir)).timeline.length), 1);
+ // narrate's --take is a new read: a take's id after it was meant as --in-take.
+ r = await posts("narrate", "scope-b", "p-1", "--take", "t1");
+ assert.equal(r.code, 2);
+ assert.match(r.err, /to edit take t1, say --in-take t1/);
+ assert.equal(await text(a), before);
+});
+
+test("reread --in-take: the new read's file lands in the project's dir under a fresh number, the take picks it, the project keeps its pick", { skip: !haveFfmpeg && "needs ffmpeg" }, async () => {
+ const a = await project("scope-c", [narrated("1", "2026-10-30T10:00:00.000Z")]);
+ await tone(path.join(a.dir, "narration/posts/1/take-1.orpheus-thread.wav"));
+ const before = await text(a);
+ assert.equal((await take("scope-c", "--id", "t1", "--label", "T", "--draft")).code, 0);
+ const r = await posts("reread", "scope-c", "p-1", "--without", "parent:0", "--in-take", "t1");
+ assert.equal(r.code, 0, r.err + r.out);
+ assert.equal(await text(a), before);
+ const n = (await resolveTakeManifest(a.dir, "t1")).manifest.timeline[0].narration;
+ assert.equal(n.pick, 1);
+ assert.match(n.takes[1].file, /^narration\/posts\/1\/take-2\./);
+ assert.ok(await stat(path.join(a.dir, n.takes[1].file)));
+});
+
+test("--import-item: an item of another project cloned into the take with its narration and pick, its files HARD-LINKED in, the authors' pictures; placed; again: unchanged; the source and the project untouched", async () => {
+ const src = await project("imp-src", [narrated("10", "2026-10-30T12:30:00.000Z"), narrated("11", "2026-10-30T12:40:00.000Z"), narrated("12", "2026-10-30T12:50:00.000Z")], {
+ postAvatars: { neighbour_one: { src: "posts-media/_avatars/neighbour_one.jpg", source: "archive" } },
+ });
+ for (const id of ["10", "11", "12"]) {
+ await tone(path.join(src.dir, `narration/posts/${id}/take-1.orpheus-thread.wav`));
+ await writeFile(path.join(src.dir, `narration/posts/${id}/take-1.parts.json`), "[]");
+ await mkdir(path.join(src.dir, "narration/parts-cache"), { recursive: true });
+ await writeFile(path.join(src.dir, `narration/parts-cache/${id}a.wav`), `a${id}`);
+ await writeFile(path.join(src.dir, `narration/parts-cache/${id}b.wav`), `b${id}`);
+ }
+ await mkdir(path.join(src.dir, "posts-media/_avatars"), { recursive: true });
+ await writeFile(path.join(src.dir, "posts-media/_avatars/neighbour_one.jpg"), "jpg");
+ const dst = await project("imp-dst", [post("1", "2026-10-30T10:00:00.000Z"), post("2", "2026-10-30T11:00:00.000Z"), post("3", "2026-10-30T13:00:00.000Z")]);
+ // ANOTHER file already at one of the paths: the import links under imports/<source>/ and names that.
+ await mkdir(path.join(dst.dir, "narration/parts-cache"), { recursive: true });
+ await writeFile(path.join(dst.dir, "narration/parts-cache/11a.wav"), "a different read");
+ const [srcBefore, dstBefore] = [await text(src), await text(dst)];
+ assert.equal((await take("imp-dst", "--id", "t1", "--label", "T", "--draft")).code, 0);
+
+ // A dry run: the plan, nothing written, nothing linked.
+ let r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-10", "--dry-run", "--json");
+ assert.equal(r.code, 0, r.err);
+ let doc = JSON.parse(r.out);
+ assert.equal(doc.dryRun, true);
+ assert.equal(doc.items[0].at.index, 2, "by date: the take's posts are in date order");
+ assert.ok(!(await stat(path.join(dst.dir, "narration/posts/10")).catch(() => null)), "a dry run links nothing");
+ assert.equal((await takeDoc(dst, "t1")).patch, null, "nor writes the take");
+
+ // Two items after p-1, in the order named; the third by date.
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-11,p-10", "--after", "p-1", "--json");
+ assert.equal(r.code, 0, r.err);
+ doc = JSON.parse(r.out);
+ assert.deepEqual(doc.items.map((x) => [x.id, x.action, x.at.after]), [["p-11", "added", "p-1"], ["p-10", "added", "p-11"]]);
+ assert.deepEqual(doc.items[0].narration, { takes: 1, pick: 1, file: "narration/posts/11/take-1.orpheus-thread.wav" });
+ const renamed = doc.items[0].files.find((f) => f.was === "narration/parts-cache/11a.wav");
+ assert.equal(renamed.path, "imports/imp-src/narration/parts-cache/11a.wav");
+ assert.deepEqual(doc.items[0].avatars, ["neighbour_one"]);
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:12", "--before", "p-3");
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /p-12: added from imp-src:12 at 4, after p-2, before p-3/);
+ const m = (await resolveTakeManifest(dst.dir, "t1")).manifest;
+ assert.deepEqual(m.timeline.map((e) => e.id), ["p-1", "p-11", "p-10", "p-2", "p-12", "p-3"]);
+ assert.equal(m.timeline[1].narration.takes[0].parts[0].file, "imports/imp-src/narration/parts-cache/11a.wav", "the clone names the renamed path");
+ assert.equal(m.postAvatars.neighbour_one.src, "posts-media/_avatars/neighbour_one.jpg");
+ // Hard links: the same inode as the source's; the sidecar came too; the other file was not written over.
+ const [s1, d1] = await Promise.all([stat(path.join(src.dir, "narration/posts/11/take-1.orpheus-thread.wav")), stat(path.join(dst.dir, "narration/posts/11/take-1.orpheus-thread.wav"))]);
+ assert.equal(d1.ino, s1.ino);
+ assert.ok(await stat(path.join(dst.dir, "narration/posts/11/take-1.parts.json")));
+ assert.equal(await readFile(path.join(dst.dir, "narration/parts-cache/11a.wav"), "utf8"), "a different read");
+ assert.equal(await text(src), srcBefore, "the source is only read");
+ assert.equal(await text(dst), dstBefore, "the take's project manifest is untouched");
+
+ // Again: nothing changes, nothing written (no undo point).
+ const revs = (await listTakeRevisions(dst.dir, "t1")).length;
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-11", "--json");
+ doc = JSON.parse(r.out);
+ assert.equal(doc.unchanged, true);
+ assert.equal(doc.items[0].action, "unchanged");
+ assert.equal((await listTakeRevisions(dst.dir, "t1")).length, revs);
+ // An edit in the take, then an import again: updated from the source, in place.
+ assert.equal((await posts("set-item", "imp-dst", "p-11", "hold=5", "--in-take", "t1")).code, 0);
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-11", "--json");
+ doc = JSON.parse(r.out);
+ assert.equal(doc.items[0].action, "updated");
+ assert.equal(doc.items[0].at.index, 1, "in place");
+ // Again with the same --after: where they already stand, as they are -- unchanged, no write.
+ const revs2 = (await listTakeRevisions(dst.dir, "t1")).length;
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-11,p-10", "--after", "p-1", "--json");
+ doc = JSON.parse(r.out);
+ assert.deepEqual([doc.unchanged, ...doc.items.map((x) => x.action)], [true, "unchanged", "unchanged"]);
+ assert.equal((await listTakeRevisions(dst.dir, "t1")).length, revs2);
+ // The lint of the take: every file its items name is there.
+ const files = await namedFileProblems((await resolveTakeManifest(dst.dir, "t1")).manifest, dst.dir);
+ assert.deepEqual(files, { errors: [], warnings: [] });
+ // Refusals: no such item (1), a malformed ref (2), an anchor not in the take (1).
+ assert.equal((await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-99")).code, 1);
+ assert.equal((await take("imp-dst", "--id", "t1", "--import-item", "imp-src")).code, 2);
+ r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:p-10", "--after", "p-77");
+ assert.equal(r.code, 1);
+ assert.match(r.err, /has no entry p-77/);
+});
+
+test("--draft --from <take>: a draft that starts from another take's patch (a --patch over it), its timeline its own", async () => {
+ const a = await project("draft-from", [post("1", "2026-10-30T10:00:00.000Z"), post("2", "2026-10-30T11:00:00.000Z")]);
+ assert.equal((await take("draft-from", "--id", "base", "--label", "Base", "--draft", "--patch-json", JSON.stringify({ timeline: [post("2", "2026-10-30T11:00:00.000Z")], render: { posts: { slurs: { on: false } } } }))).code, 0);
+ const r = await take("draft-from", "--id", "next", "--draft", "--from", "base", "--patch-json", JSON.stringify({ render: { transition: 0.2 } }));
+ assert.equal(r.code, 0, r.err);
+ const d = await takeDoc(a, "next");
+ assert.deepEqual(d.patch.timeline.map((e) => e.id), ["p-2"]);
+ assert.equal(d.patch.render.posts.slurs.on, false);
+ assert.equal(d.patch.render.transition, 0.2);
+ assert.match(d.label, /Base \(from base\)/);
+ assert.equal((await take("draft-from", "--id", "x", "--draft", "--from", "nope")).code, 2);
+});
+
+test("the editor's token: the environment's, else the editor's env files'; an explicit empty one is none; never in the message", async () => {
+ const dir = path.join(ROOT, "env");
+ await mkdir(dir, { recursive: true });
+ const file = path.join(dir, ".env");
+ await writeFile(file, "OTHER=1\nWORKER_TOKEN=from-the-file\n");
+ assert.equal(editorFromEnv({}, [file]).token, "from-the-file");
+ assert.equal(editorFromEnv({ WORKER_TOKEN: "env" }, [file]).token, "env");
+ assert.throws(() => editorFromEnv({ WORKER_TOKEN: "" }, [file]), /WORKER_TOKEN is not set/);
+ assert.throws(() => editorFromEnv({}, [path.join(dir, "missing")]), (e) => /WORKER_TOKEN is not set/.test(e.message) && !e.message.includes("from-the-file"));
+});
+
+test("umtool lint --take: the take's manifest linted as its render reads it, and a picked read not in the project is an ERROR (exit 1)", async () => {
+ const a = await project("lint-a", [narrated("1", "2026-10-30T10:00:00.000Z")]);
+ assert.equal((await take("lint-a", "--id", "t1", "--label", "T", "--draft")).code, 0);
+ let r = await cli(lintCommand, ["lint-a", "--take", "t1", "--json"]);
+ let doc = JSON.parse(r.out);
+ assert.equal(r.code, 1);
+ assert.ok(doc.errors.some((e) => /timeline p-1: its picked read narration\/posts\/1\/take-1\.orpheus-thread\.wav is not in the project/.test(e)), doc.errors.join("\n"));
+ await tone(path.join(a.dir, "narration/posts/1/take-1.orpheus-thread.wav"));
+ r = await cli(lintCommand, ["lint-a", "--take", "t1", "--json"]);
+ doc = JSON.parse(r.out);
+ assert.equal(doc.errors.filter((e) => /not in the project/.test(e)).length, 0, doc.errors.join("\n"));
+ assert.equal(doc.take, "t1");
+ assert.ok(!(await stat(path.join(a.dir, ".take-t1.lint.json")).catch(() => null)), "the scratch manifest is gone");
+ assert.equal((await cli(lintCommand, ["lint-a", "--take", "nope"])).code, 1);
+ assert.equal((await cli(lintCommand, [])).code, 2);
+});
diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs
@@ -37,6 +37,7 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
+import { agentToken, editorEnvFiles } from "../lib/annotations/agentAuth.mjs";
import { narrationsOf } from "./narration.mjs";
import { keepNarration, narrationDir, readNarrationRecord } from "./narration-store.mjs";
@@ -53,13 +54,19 @@ const RESULT_RETRIES = 10;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
-/** The editor to ask and the token to ask with, from the environment; throws naming the variable. */
-export function editorFromEnv(env = process.env) {
+/**
+ * The editor to ask and the token to ask with: ARCHILYZER_EDITOR_URL, and WORKER_TOKEN from the environment, else
+ * the editor's own env files (editor/.env.local, editor/.env, then the main worktree's -- agentAuth.mjs agentToken,
+ * the rule `pnpm ops` and umtool's other editor calls read it by). Throws naming the variable and the files; the
+ * token itself is never in a message.
+ */
+export function editorFromEnv(env = process.env, files = editorEnvFiles()) {
const url = (env.ARCHILYZER_EDITOR_URL || DEFAULT_EDITOR).replace(/\/+$/, "");
- const token = env.WORKER_TOKEN ?? "";
+ const token = agentToken(env, files);
if (!token) {
throw new Error(
- "WORKER_TOKEN is not set, so the editor cannot be asked for the narration. " +
+ "WORKER_TOKEN is not set, so the editor cannot be asked for the narration " +
+ `(not in the environment, nor in ${files.length ? files.join(", ") : "an editor env file"}). ` +
"Set WORKER_TOKEN to the same value the editor runs with.",
);
}
diff --git a/umtool/report-to-video/post-combo.mjs b/umtool/report-to-video/post-combo.mjs
@@ -413,14 +413,20 @@ function knobErrors(o, where, keys) {
return errors;
}
+/** The keys `render.posts` holds, each its own module's. */
+export const POSTS_RENDER_KEYS = ["combo", "redact", "slurs", "scene", "clock", "progress", "panel", "join", "linkVisit", "threadMap"];
+
/** Every reason `render.posts.combo` cannot be built. */
export function validatePostComboRender(render) {
const p = render?.posts;
if (p === undefined || p === null) return [];
if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"];
- // render.posts is shared: `redact` and `slurs` are post-redact.mjs's (validatePostsRender checks them), `scene`
- // post-media-scene.mjs's (validatePostSceneRender).
- const errors = Object.keys(p).filter((k) => !["combo", "redact", "slurs", "scene"].includes(k)).map((k) => `render.posts.${k} is not a knob (combo, redact, slurs, scene)`);
+ // render.posts is shared: `redact`, `slurs`, `clock` and `progress` are post-redact.mjs's (validatePostsRender checks
+ // them), `scene` post-media-scene.mjs's, `panel` post-item.mjs's, `join` post-join.mjs's, `linkVisit`
+ // post-link-visit.mjs's, `threadMap` post-branch-map.mjs's -- each validated by its own module. A key none of
+ // them owns (a typo) is refused here. (`posts progress auto` wrote a `progress` this list refused: every cut
+ // with the cut's progress bar failed its lint, 4 Nov.)
+ const errors = Object.keys(p).filter((k) => !POSTS_RENDER_KEYS.includes(k)).map((k) => `render.posts.${k} is not a knob (${POSTS_RENDER_KEYS.join(", ")})`);
if (p.combo === undefined) return errors;
if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"];
return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))];
diff --git a/umtool/report-to-video/post-combo.test.mjs b/umtool/report-to-video/post-combo.test.mjs
@@ -253,4 +253,6 @@ test("the sound's print: the same clip re-encoded matches, another sound does no
test("render.posts is shared: the combo validator leaves redact and slurs to post-redact.mjs (a cut with redacted words built again)", () => {
assert.deepEqual(validatePostComboRender({ posts: { redact: [{ term: "Someone" }], slurs: { on: true }, combo: { on: true } } }), []);
assert.match(validatePostComboRender({ posts: { comb: {} } }).join(" "), /render\.posts\.comb is not a knob/);
+ // Every module's key under render.posts passes this one (the progress bar's failed every cut that had it, 4 Nov).
+ assert.deepEqual(validatePostComboRender({ posts: { progress: "auto", clock: { on: true }, panel: {}, join: {}, linkVisit: {}, threadMap: {}, scene: {} } }), []);
});