Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2916f0a1d627506a825ed8101fd6131c1da942ff
parent 75d0be65ea31c02c4ce70304b9cda72e62147453
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 23:42:44 -0500

umtool: take-scoped edits -- posts set-item, roles, narrate, reread and fx take --in-take <take>; take --import-item <project>:<item> clones items of another project into a take with their files hard-linked; take --draft --from <take>; the narration's WORKER_TOKEN found in the editor's env files

A take-scoped edit (takeScope.mjs) runs the existing command with the project's
manifest read as the take's and every structural write landing in the take's
patch (takeEdit.mjs editTakeManifest: the timeline whole, any other change
composed onto the patch, an undo point of the take's own; nothing changed,
nothing written). A writer not routed to the take refuses and writes nothing;
edit notes are skipped. The import (takeImport.mjs) clones an entry from another
project's manifest with its narration and pick, hard-links the files it names
(narration takes and sidecars, parts, attachments, authors' pictures) into the
take's project (another file at the path: imports/<source>/...), places it
--after/--before an entry, by date in a date-ordered take, else at the end, and
re-runs as updated or unchanged. The source project and the take's project
manifest are only read.

Operator, 4 Nov: "it'd be better to have Archilyzer or umtool handle it and you
simply poll them"; "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:
Mumtool/bin/umtool.mjs | 10++++++++++
Mumtool/lib/projects/report.mjs | 7+++++++
Mumtool/lib/report/edit-guard.mjs | 3+++
Mumtool/lib/report/manifest.mjs | 18++++++++++++++++++
Mumtool/lib/report/postFxCli.mjs | 2+-
Mumtool/lib/report/postNarrationCli.mjs | 2++
Mumtool/lib/report/postReread.mjs | 1+
Mumtool/lib/report/postThreadCli.mjs | 2+-
Mumtool/lib/report/postsCli.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takeCli.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeEdit.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeImport.mjs | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeScope.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeScope.test.mjs | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/narrate-via-editor.mjs | 15+++++++++++----
15 files changed, 1038 insertions(+), 8 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -74,6 +74,7 @@ // [--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 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 +117,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 +965,10 @@ 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 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 +1061,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", 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/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,346 @@ +// 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; + 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 }); + } + // 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,273 @@ +// 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 { 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"); + // 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")); +}); 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.", ); }