commit bcaa31578c53c9a14aca2fdde2bba472d1e3b9e8
parent 442926c9db15d745ff1e0942bb08605019e39267
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 21:16:03 -0400
common: drafted fields and the media task scaffold; narrate is a spec on it
drafted.mjs (plain JS, typed by drafted.d.mts) is the one copy of where a
drafted field says so: `entry.drafted.<onscreen|narration|lines>` and the
top-level `drafted` map for `timeline`, `render.chrome.flips`,
`render.chrome.threads` and `publish.youtube`, each a provenance
{ task, model, at, iteration?, attempt }. `applyDraft` is the one writer: an
operator's field (a value with no mark) is never replaced, forced or not.
`clearEditedDrafts` is the operator's edit, `pruneDrafted` drops orphans,
`validateDrafted` and `validatePublish` refuse a mark or a publish block that
is out of place, and `reviewAddress` / `fieldKey` are the review's address and
key.
tasks/media.ts is the scaffold every media task builds on (`runMediaTask`):
units, two attempts against a schema, the code checks, the better kept, the
snapshot, `applyDraft`, the alternatives, `<task>-draft.json`. Narrate is
refactored onto it (its file keeps the name narration-draft.json, now with
`units` and `alternatives`); a narration it writes carries drafted.narration.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 1443 insertions(+), 106 deletions(-)
diff --git a/common/lib/report/draft/tasks/media.test.ts b/common/lib/report/draft/tasks/media.test.ts
@@ -0,0 +1,201 @@
+// The media task scaffold (release 28, M0): a toy task over the fake ollama
+// — two attempts, the better kept, an operator's field never replaced and its
+// draft kept as an alternative — and narrate on it writing its drafted marks.
+// Real iterations store and project in a temp dir; no model but the fake.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations";
+import { reviewAddress } from "../../drafted.mjs";
+import { narrate } from "./narrate";
+import {
+ mergeAlternatives,
+ rankAttempts,
+ runMediaTask,
+ type DraftAlternative,
+ type DraftFile,
+ type MediaTaskSpec,
+ type MediaUnit,
+} from "./media";
+import type { TaskDeps } from "./types";
+
+const DRAFT = new URL("../../../../testing/draft/", import.meta.url);
+const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8"));
+
+let tmp: string;
+let ol: FakeOllama;
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "media-task-"));
+ ol = await startFakeOllama();
+});
+after(async () => {
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+let caseN = 0;
+// A done sweep iteration with a project holding `manifest` and the basic report.
+async function project(manifest: unknown) {
+ caseN++;
+ const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) };
+ const projectsRoot = path.join(tmp, `projects-${caseN}`);
+ await mkdir(paths.articlesDir, { recursive: true });
+ await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const report = await kit("reports/basic.report.json");
+ await writeIterationFile("synth-basic", 1, "report.json", report, paths);
+ const dir = projectOf(projectsRoot, "synth-basic", 1);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ await writeFile(path.join(dir, "report.json"), JSON.stringify(report));
+ await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths);
+ const lines: string[] = [];
+ const deps: TaskDeps = {
+ llm: { ollama: { baseUrl: ol.url } },
+ corpus: { source: "none", tools: [], call: async () => "" },
+ cuesOf: async () => null,
+ paths,
+ log: (l) => lines.push(l),
+ now: () => new Date("2026-10-13T12:00:00.000Z"),
+ };
+ const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ return { dir, paths, projectsRoot, deps, lines, manifestNow };
+}
+
+// A toy task: a title for each clip, at most 20 characters, never "BAD".
+type ToyUnit = MediaUnit & { quote: string };
+const TOY: MediaTaskSpec<ToyUnit, { title: string }> = {
+ task: "toy",
+ units: (ctx) =>
+ ctx.manifest.timeline
+ .filter((e) => e.type === "clip")
+ .slice(0, 3)
+ .map((e) => ({ id: e.id, target: { entry: e.id, field: "onscreen" }, quote: String(e.quote ?? "") })),
+ schema: () => ({ type: "object", properties: { title: { type: "string" } }, required: ["title"] }),
+ system: () => "Write a short title. Rules: at most 20 characters.",
+ user: (u) => `Quote: ${u.quote}`,
+ parse: (a) => ({ title: String((a as { title?: unknown }).title ?? "").trim() }),
+ check: (v) => ({
+ hard: [...(v.title.length > 20 ? [`${v.title.length} characters (at most 20)`] : []), ...(v.title === "BAD" ? ["bad"] : [])],
+ soft: v.title.endsWith("!") ? ["an exclamation"] : [],
+ }),
+};
+
+test("the scaffold: two attempts and the better kept; the operator's field kept and the draft an alternative; marks, snapshot, draft file", async () => {
+ const m = await kit("manifests/full.video.manifest.json");
+ const p = await project(m);
+ // c01 has hand-written on-screen text (the operator's); c02 and c03 none.
+ ol.push(
+ // c01 (forced): clean — but the field is the operator's.
+ jsonReply({ title: "Not for sale?" }),
+ // c02: too long, then clean.
+ jsonReply({ title: "A title far too long for the frame" }),
+ jsonReply({ title: "The old oven" }),
+ // c03: a soft flag, then worse (hard): the first is kept.
+ jsonReply({ title: "The mixer!" }),
+ jsonReply({ title: "BAD" }),
+ );
+ const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ assert.equal(ol.remaining(), 0);
+ assert.match(out.summary, /^2 field\(s\) drafted, 1 as alternatives \(see toy-draft\.json\) \(undo: revisions\/.*-auto-before-toy\.manifest\.json\)$/);
+ const after = await p.manifestNow();
+ const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id);
+ assert.deepEqual(e("c01").onscreen, m.timeline.find((x: { id: string }) => x.id === "c01").onscreen, "the operator's words stand");
+ assert.equal(e("c01").drafted, undefined);
+ assert.deepEqual(e("c02").onscreen, { title: "The old oven" });
+ assert.deepEqual(e("c02").drafted.onscreen, { task: "toy", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 });
+ assert.deepEqual(e("c03").onscreen, { title: "The mixer!" });
+ assert.equal(e("c03").drafted.onscreen.attempt, 1, "the better of two: the first");
+ assert.equal((await readdir(path.join(p.dir, "revisions"))).length, 1);
+ const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.equal(file.task, "toy");
+ assert.equal(file.iteration, 1);
+ assert.equal((file.units.c02!.attempts as unknown[]).length, 2);
+ assert.equal(file.units.c01!.applied, "operator");
+ assert.equal(file.units.c02!.applied, "applied");
+ assert.deepEqual(file.alternatives.map((a) => [a.target, a.value, a.reason]), [[{ entry: "c01", field: "onscreen" }, { title: "Not for sale?" }, "operator"]]);
+ assert.equal(file.checks.find((c) => c.name === "toy")!.ok, true);
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.status, "done", "a step leaves the iteration's status");
+ assert.equal(it.steps.find((s) => s.task === "toy")!.status, "done");
+
+ // Again, unforced: every field has a value now, so nothing is asked; the
+ // alternative from the run before is carried over.
+ const again = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps);
+ assert.equal(again.status, "failed");
+ assert.match(again.summary, /no field drafted/);
+ const file2 = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.match(String(file2.units.c02!.skipped), /has a value \(a draft\); force re-drafts it/);
+ assert.match(String(file2.units.c01!.skipped), /the operator's/);
+ assert.equal(file2.alternatives.length, 1);
+});
+
+test("the scaffold: entries keeps only the named units; a unit with no clean value is not written", async () => {
+ const m = await kit("manifests/full.video.manifest.json");
+ const p = await project(m);
+ ol.push(jsonReply({ title: "BAD" }), jsonReply({ title: "BAD" }));
+ const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, entries: ["c02"] }, p.deps);
+ assert.equal(out.status, "failed");
+ assert.equal(ol.remaining(), 0, "only c02 was asked");
+ const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.deepEqual(Object.keys(file.units), ["c02"]);
+ assert.deepEqual(await p.manifestNow(), m, "nothing written");
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.checks!.find((c) => c.name === "toy")!.ok, false);
+});
+
+test("rankAttempts and mergeAlternatives", () => {
+ const a = { value: 1, hard: ["x"], soft: [] };
+ const b = { value: 2, hard: [], soft: ["y", "z"] };
+ const c = { value: 3, hard: [], soft: ["y", "z"] };
+ assert.deepEqual(rankAttempts([a, b, c]).map((x) => x.value), [2, 3, 1], "stable among equals");
+ const alt = (entry: string, title: string): DraftAlternative => ({
+ target: { entry, field: "onscreen" },
+ value: { title },
+ provenance: { task: "toy", model: "m", at: "2026-10-13T00:00:00.000Z", attempt: 1 },
+ reason: "operator",
+ });
+ const many = Array.from({ length: 7 }, (_, i) => alt("c01", `t${i}`));
+ const merged = mergeAlternatives(many.slice(0, 4), [...many.slice(4), alt("c01", "t0"), alt("c02", "x")]);
+ assert.deepEqual(
+ merged.map((x) => `${reviewAddress(x.target)}:${(x.value as { title: string }).title}`),
+ ["onscreen/c01/onscreen:t3", "onscreen/c01/onscreen:t4", "onscreen/c01/onscreen:t5", "onscreen/c01/onscreen:t6", "onscreen/c01/onscreen:t0", "onscreen/c02/onscreen:x"],
+ "five per field, the newest; a repeat keeps its newest place",
+ );
+});
+
+test("narrate on the scaffold: a narration it writes carries drafted.narration; the operator's is kept and its draft an alternative", async () => {
+ const m = await kit("manifests/basic.video.manifest.json");
+ const contest = m.timeline.find((e: { id: string }) => e.id === "the-contest");
+ contest.narration = { text: "Words the operator wrote." };
+ const p = await project(m);
+ // Each card's words by its heading, however many times it is asked.
+ const byCard = (body: { messages: { content: string }[] }) => {
+ const user = body.messages.at(-1)!.content;
+ if (/heading on screen: The bakery/.test(user)) return jsonReply({ text: "First, the bakery. She won't sell it, and she paid for the mixer herself." });
+ if (/heading on screen: The contest/.test(user)) return jsonReply({ text: "Then the contest. She stayed out of it this year." });
+ return jsonReply({ text: "What does the baker say about her bakery? And about the contest?" });
+ };
+ ol.push(byCard, byCard, byCard, byCard, byCard, byCard);
+ const out = await narrate({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ assert.match(out.summary, /^2 card\(s\) narrated, 1 as alternatives \(see narration-draft\.json\)/);
+ const after = await p.manifestNow();
+ const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id);
+ assert.equal(e("the-bakery").narration.text, "First, the bakery. She won't sell it, and she paid for the mixer herself.");
+ assert.equal(e("the-bakery").seconds, "auto");
+ assert.deepEqual(e("the-bakery").drafted, { narration: { task: "narrate", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 1 } });
+ assert.equal(e("title").drafted.narration.task, "narrate");
+ assert.equal(e("the-contest").narration.text, "Words the operator wrote.");
+ assert.equal(e("the-contest").drafted, undefined);
+ const file = JSON.parse(await readFile(path.join(p.dir, "narration-draft.json"), "utf8")) as DraftFile;
+ assert.deepEqual(file.alternatives.map((a) => [a.target.entry, (a.value as { text: string }).text]), [["the-contest", "Then the contest. She stayed out of it this year."]]);
+ const revisions = await readdir(path.join(p.dir, "revisions"));
+ assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/);
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.checks!.find((c) => c.name === "narration")!.ok, true);
+});
diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts
@@ -0,0 +1,406 @@
+// THE MEDIA TASK SCAFFOLD (release 28, M0) — what every task that drafts a
+// field of an iteration's video manifest is, extracted from narrate (the
+// first; ./narrate.ts is now a spec on this). Phase 2's tasks (cut, onscreen,
+// teaser, flips, threads, youtube) are small files on it: a spec and an input.
+//
+// A media task is a STEP on a done iteration (recorded in its `steps`, its
+// status left as it is), run by `runMediaTask(spec, input, deps)`:
+//
+// 1. the iteration's project: its `video.manifest.json` (none: the task
+// cannot start) and its report (the project's `report.json`, else the
+// iteration's source report);
+// 2. `spec.units(ctx)`: one UNIT per field to draft -- its `target`
+// (`{ entry?, field }`, drafted.mjs) and whatever evidence the prompt
+// needs -- or a skip record (`{ id, skipped }`) for one that is not
+// drafted and says why. `input.entries` keeps only the units it names
+// (by entry id or unit id). A unit whose field has a value is skipped
+// unless `input.force` (then an operator's field is drafted anyway, and
+// the refused draft becomes an ALTERNATIVE);
+// 3. per unit, at most two attempts: `structuredAnswer` against
+// `spec.schema(unit)` with `spec.system` / `spec.user` (the second ask
+// carries what the first was refused for), `spec.parse` (a throw is a
+// hard failure of that attempt), then the task's CODE checks
+// (`spec.check` → `{ hard, soft }`: counts, lengths, ids that exist,
+// grounding). A clean first attempt is not asked again;
+// 4. the better attempt (`spec.score`, default fewest hard then fewest soft
+// problems); one still failing a hard check goes to `spec.repair` (narrate
+// removes the failing sentences), and a unit with no clean value is not
+// written;
+// 5. the manifest is snapshotted (`revisions/<stamp>-auto-before-<op>`) and
+// each kept value is written through `applyDraft` (drafted.mjs) -- or
+// `spec.apply`, which must call it -- with the provenance
+// `{ task, model, at, iteration, attempt }`. A field that is the
+// operator's is NEVER replaced: its value goes to `alternatives[]`;
+// 6. orphan marks dropped, the manifest written whole (only when something
+// was applied), and `<task>-draft.json` (`spec.draftFile`) written beside
+// it: every unit's attempts and checks, the kept value, what was applied,
+// and the alternatives (earlier runs' carried over, newest five per field).
+//
+// Q0 binds every spec: counts and lengths are enforced in `check`, never only
+// asked for; prompts carry rules, never worked examples; a local prompt stays
+// under 8k tokens. Progress reporting is not here yet (release 28 F3 adds
+// `TaskDeps.progress`; phase 2 wires the media tasks to it).
+
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { structuredAnswer } from "../../../llm";
+import { readIteration, readIterationFile, reportSourceOf } from "../../iterations";
+import {
+ applyDraft,
+ makeProvenance,
+ ownerOf,
+ pruneDrafted,
+ reviewAddress,
+ stableStringify,
+ valueKey,
+ type ApplyDraftResult,
+ type DraftTarget,
+ type Provenance,
+} from "../../drafted.mjs";
+import { groundingInputOf, type GroundingInput } from "../grounding";
+import type { VideoManifest } from "../videoOps";
+import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project";
+import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import type { TaskDeps, TaskResult } from "./types";
+
+export type { DraftTarget, Provenance } from "../../drafted.mjs";
+
+/** What every media task takes (its own input extends it). */
+export type MediaTaskInput = {
+ article: string;
+ n: number;
+ model: string;
+ projectsRoot: string;
+ // Only these units: an entry id (every unit on it) or a unit id.
+ entries?: string[];
+ // Re-draft a field that has a value. An operator's field is still never
+ // replaced: the draft becomes an alternative.
+ force?: boolean;
+ maxUsd?: number;
+ jobId?: string;
+};
+
+/** A report as a media task reads it (report.json's shape, loosely). */
+export type MediaReport = Record<string, any>;
+
+/** What a spec is handed: the run, the project, the manifest as read, the report. */
+export type MediaContext<I extends MediaTaskInput = MediaTaskInput> = {
+ handle: TaskHandle;
+ input: I;
+ dir: string;
+ manifest: VideoManifest;
+ report: MediaReport;
+ // groundingInputOf(report): what a spec's check grounds numbers and names in.
+ grounding: GroundingInput;
+};
+
+/** One field to draft. A spec's own units extend it with their evidence. */
+export type MediaUnit = { id: string; target: DraftTarget; label?: string };
+
+/** A unit that is not drafted, and why (recorded in the draft file). */
+export type MediaSkip = { id: string; skipped: string };
+
+/** One attempt: the value parsed (null: none), and the code checks' findings. */
+export type MediaAttempt<V> = { value: V | null; hard: string[]; soft: string[] };
+
+/** A refused value kept for the operator: umtool shows it under its field with "Use this". */
+export type DraftAlternative = {
+ target: DraftTarget;
+ value: unknown;
+ provenance: Provenance;
+ reason: "operator" | "drafted" | "missing";
+};
+
+/** `<task>-draft.json`: the run's record. */
+export type DraftFile = {
+ task: string;
+ model: string;
+ at: string;
+ article: string;
+ iteration: number;
+ units: Record<string, Record<string, unknown>>;
+ checks: { name: string; ok: boolean; detail?: string }[];
+ alternatives: DraftAlternative[];
+};
+
+export type MediaTaskSpec<U extends MediaUnit, V, I extends MediaTaskInput = MediaTaskInput> = {
+ // The task's name: the step's, the provenance's, the default file's.
+ task: string;
+ // Default `<task>-draft.json`.
+ draftFile?: string;
+ // The snapshot's op (`auto-before-<op>`); default the task.
+ snapshotOp?: string;
+ // The iteration check's name; default the task.
+ checkName?: string;
+ // turns.jsonl's `kind` per attempt; default the task.
+ turnKind?: string;
+ // Words for the summary: "<n> <noun>(s) <verb>"; defaults "field", "drafted".
+ noun?: string;
+ verb?: string;
+ units(ctx: MediaContext<I>): (U | MediaSkip)[] | Promise<(U | MediaSkip)[]>;
+ schema(unit: U, ctx: MediaContext<I>): object;
+ system(unit: U, ctx: MediaContext<I>): string;
+ user(unit: U, ctx: MediaContext<I>): string;
+ // The model's answer to a value; a throw is that attempt's hard failure.
+ parse(answer: unknown, unit: U, ctx: MediaContext<I>): V;
+ // The code checks: `hard` refuses the value, `soft` is a flag.
+ check(value: V, unit: U, ctx: MediaContext<I>): { hard: string[]; soft: string[] };
+ // Lower is better, compared element by element. Default [hard, soft].
+ score?(a: MediaAttempt<V>): number[];
+ // When the best attempt still fails a hard check: a clean value made from
+ // the attempts (never a new one), or null. Its own `hard` must be empty.
+ repair?(attempts: MediaAttempt<V>[], unit: U, ctx: MediaContext<I>): MediaAttempt<V> | null;
+ // The re-ask's added words; default "Your last draft was refused for: …".
+ retry?(last: MediaAttempt<V>, unit: U): string;
+ // The field's value for a kept value (default: the value itself) -- what is
+ // written, and what an alternative holds (umtool's "Use this" writes it as is).
+ // Narrate's is the card's narration object with the new words.
+ toField?(value: V, unit: U, manifest: VideoManifest): unknown;
+ // After a value is applied (narrate: the card's `seconds` to "auto").
+ afterApply?(manifest: VideoManifest, unit: U): void;
+ // Write the kept value instead of `applyDraft(manifest, { ...unit.target,
+ // value: toField(value), provenance, force })`; an override must go through
+ // applyDraft.
+ apply?(manifest: VideoManifest, unit: U, value: unknown, provenance: Provenance, force: boolean, ctx: MediaContext<I>): ApplyDraftResult;
+ // A line for the log per unit kept; default the value as JSON.
+ describe?(value: V, unit: U): string;
+};
+
+export const isSkip = (u: MediaUnit | MediaSkip): u is MediaSkip => typeof (u as MediaSkip).skipped === "string";
+
+/** Default score: fewest hard problems, then fewest soft ones. */
+export const defaultScore = <V>(a: MediaAttempt<V>) => [a.hard.length, a.soft.length];
+
+const lexLess = (a: number[], b: number[]) => {
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const x = a[i] ?? 0;
+ const y = b[i] ?? 0;
+ if (x !== y) return x < y;
+ }
+ return false;
+};
+
+/** The attempts best first (a stable sort: the earlier of two equals first). */
+export function rankAttempts<V>(attempts: MediaAttempt<V>[], score: (a: MediaAttempt<V>) => number[] = defaultScore): MediaAttempt<V>[] {
+ return attempts
+ .map((a, i) => ({ a, i, s: score(a) }))
+ .sort((x, y) => (lexLess(x.s, y.s) ? -1 : lexLess(y.s, x.s) ? 1 : x.i - y.i))
+ .map((x) => x.a);
+}
+
+export const draftFileName = (task: string) => `${task}-draft.json`;
+
+/** The newest alternatives kept per field. */
+export const ALTERNATIVES_PER_FIELD = 5;
+
+const targetKey = (t: DraftTarget) => reviewAddress({ entry: t.entry ?? null, field: t.field });
+
+/** A project's draft file, or null (absent or unreadable). */
+export async function readDraftFile(dir: string, file: string): Promise<DraftFile | null> {
+ try {
+ const j = JSON.parse(await readFile(path.join(dir, file), "utf8"));
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as DraftFile) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Earlier alternatives, then these; one per field and value, the newest ALTERNATIVES_PER_FIELD per field. */
+export function mergeAlternatives(earlier: readonly DraftAlternative[], now: readonly DraftAlternative[]): DraftAlternative[] {
+ const seen = new Set<string>();
+ const out: DraftAlternative[] = [];
+ // Newest first while picking, so a repeat keeps its newest copy.
+ for (const a of [...now].reverse().concat([...earlier].reverse())) {
+ if (!a || typeof a !== "object" || !a.target || typeof a.target.field !== "string") continue;
+ const k = `${targetKey(a.target)}\u0000${valueKey(a.value)}`;
+ if (seen.has(k)) continue;
+ if (out.filter((x) => targetKey(x.target) === targetKey(a.target)).length >= ALTERNATIVES_PER_FIELD) continue;
+ seen.add(k);
+ out.push(a);
+ }
+ return out.reverse();
+}
+
+async function writeJsonAtomic(file: string, value: unknown) {
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`);
+ await rename(tmp, file);
+}
+
+/** The project, the manifest and the report a media task reads. */
+export async function loadMediaContext<I extends MediaTaskInput>(h: TaskHandle, input: I): Promise<MediaContext<I>> {
+ const it = (await readIteration(h.article, h.n, h.paths))!;
+ const dir = projectDirOf(it, input.projectsRoot);
+ const manifest = await readManifest(dir);
+ if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`);
+ let report = (await readProjectReport(dir)) as MediaReport | null;
+ if (!report) {
+ const from = await reportSourceOf(h.article, h.n, h.paths);
+ const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths);
+ report = text ? (JSON.parse(text) as MediaReport) : null;
+ }
+ if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to draft from`);
+ return { handle: h, input, dir, manifest, report, grounding: groundingInputOf(report) };
+}
+
+const refusedFor = <V>(last: MediaAttempt<V>) =>
+ `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`;
+
+/**
+ * Run one media task over an iteration (the shape above). The result is the
+ * step's: `done` when at least one unit kept a clean value (applied, or kept
+ * as an alternative), else `failed`.
+ */
+export async function runMediaTask<U extends MediaUnit, V, I extends MediaTaskInput>(
+ spec: MediaTaskSpec<U, V, I>,
+ input: I,
+ deps: TaskDeps,
+): Promise<TaskResult> {
+ return runOnIteration(
+ {
+ article: input.article,
+ n: input.n,
+ deps,
+ maxUsd: input.maxUsd,
+ step: { task: spec.task, model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) },
+ },
+ (h) => mediaBody(spec, h, input),
+ );
+}
+
+async function mediaBody<U extends MediaUnit, V, I extends MediaTaskInput>(
+ spec: MediaTaskSpec<U, V, I>,
+ h: TaskHandle,
+ input: I,
+): Promise<TaskOutcome> {
+ const { deps } = h;
+ const now = () => deps.now?.() ?? new Date();
+ const ctx = await loadMediaContext(h, input);
+ const { dir, manifest } = ctx;
+ const file = spec.draftFile ?? draftFileName(spec.task);
+ const noun = spec.noun ?? "field";
+ const verb = spec.verb ?? "drafted";
+ const score = spec.score ?? defaultScore;
+ const only = input.entries?.length ? new Set(input.entries) : null;
+ const units: Record<string, Record<string, unknown>> = {};
+ const kept: { unit: U; value: V; attempt: 1 | 2 }[] = [];
+ h.log(`${spec.task} on i${h.n}, ${input.model} (${dir})`);
+
+ for (const u of await spec.units(ctx)) {
+ if (only && !only.has(u.id) && !(!isSkip(u) && u.target.entry && only.has(u.target.entry))) continue;
+ if (isSkip(u)) {
+ units[u.id] = { skipped: u.skipped };
+ continue;
+ }
+ const owner = ownerOf(manifest, u.target);
+ if (owner !== "empty" && !input.force) {
+ units[u.id] = { target: u.target, skipped: `has a value (${owner === "operator" ? "the operator's" : "a draft"}); force re-drafts it` };
+ continue;
+ }
+ const system = spec.system(u, ctx);
+ const user = spec.user(u, ctx);
+ const attempts: MediaAttempt<V>[] = [];
+ for (let k = 0; k < 2; k++) {
+ deps.signal?.throwIfAborted();
+ const extra = attempts.length ? (spec.retry ?? refusedFor)(attempts.at(-1)!, u) : "";
+ let a: MediaAttempt<V>;
+ try {
+ const answer = await structuredAnswer<unknown>({
+ llm: deps.llm,
+ model: input.model,
+ system,
+ user: user + extra,
+ schema: spec.schema(u, ctx),
+ meter: h.meter,
+ signal: deps.signal,
+ });
+ try {
+ const value = spec.parse(answer, u, ctx);
+ a = { value, ...spec.check(value, u, ctx) };
+ } catch (e) {
+ a = { value: null, hard: [(e as Error).message], soft: [] };
+ }
+ } catch (e) {
+ if (deps.signal?.aborted) throw e;
+ attempts.push({ value: null, hard: [(e as Error).message], soft: [] });
+ continue;
+ }
+ attempts.push(a);
+ h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]);
+ if (!a.hard.length && !a.soft.length) break;
+ }
+ const ranked = rankAttempts(attempts, score);
+ let chosen: MediaAttempt<V> | null = ranked[0] ?? null;
+ let attemptNo = (chosen ? attempts.indexOf(chosen) + 1 : 1) as 1 | 2;
+ if (chosen && chosen.hard.length) {
+ const fixed = spec.repair?.(attempts, u, ctx) ?? null;
+ if (fixed && !fixed.hard.length && fixed.value !== null) {
+ chosen = fixed;
+ attemptNo = Math.min(2, attempts.length) as 1 | 2;
+ }
+ }
+ units[u.id] = { target: u.target, ...(u.label ? { label: u.label } : {}), attempts, chosen };
+ if (!chosen || chosen.hard.length || chosen.value === null) {
+ h.log(` ${u.id}: NOT written — ${chosen?.hard.join("; ") ?? "no draft"}`);
+ continue;
+ }
+ kept.push({ unit: u, value: chosen.value, attempt: attemptNo });
+ const said = spec.describe ? spec.describe(chosen.value, u) : JSON.stringify(chosen.value);
+ h.log(` ${u.id}: ${said}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`);
+ }
+
+ const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt<V> | null | undefined)?.hard?.length).length;
+ const at = now();
+ const alternatives: DraftAlternative[] = [];
+ const next = JSON.parse(JSON.stringify(manifest)) as VideoManifest;
+ let applied = 0;
+ for (const k of kept) {
+ const provenance = makeProvenance({ task: spec.task, model: input.model, at, iteration: h.n, attempt: k.attempt });
+ const value = spec.toField ? spec.toField(k.value, k.unit, next) : k.value;
+ const res = spec.apply
+ ? spec.apply(next, k.unit, value, provenance, !!input.force, ctx)
+ : applyDraft(next, { ...k.unit.target, value, provenance, force: !!input.force });
+ units[k.unit.id]!.applied = res.applied ? "applied" : res.reason;
+ if (res.applied) {
+ applied++;
+ spec.afterApply?.(next, k.unit);
+ } else alternatives.push({ target: k.unit.target, value, provenance, reason: res.reason });
+ }
+ pruneDrafted(next);
+ let snap: string | null = null;
+ if (applied) {
+ snap = await snapshotManifest(dir, spec.snapshotOp ?? spec.task, at);
+ await writeManifest(dir, next);
+ }
+ h.check({
+ name: spec.checkName ?? spec.task,
+ ok: refused === 0,
+ detail:
+ `${applied} ${noun}(s) ${verb}` +
+ (alternatives.length ? `, ${alternatives.length} kept as an alternative (the field is the operator's)` : "") +
+ (refused ? `, ${refused} not written (a hard check)` : ""),
+ });
+ const earlier = (await readDraftFile(dir, file))?.alternatives ?? [];
+ const record: DraftFile = {
+ task: spec.task,
+ model: input.model,
+ at: at.toISOString(),
+ article: h.article,
+ iteration: h.n,
+ units,
+ checks: h.checks,
+ alternatives: mergeAlternatives(Array.isArray(earlier) ? earlier : [], alternatives),
+ };
+ await writeJsonAtomic(path.join(dir, file), record).catch((e) => h.log(`${file} not written: ${(e as Error).message}`));
+ if (!kept.length) return { status: "failed", summary: `no ${noun} ${verb} (see ${file})` };
+ return {
+ status: "done",
+ summary:
+ `${applied} ${noun}(s) ${verb}` +
+ (alternatives.length ? `, ${alternatives.length} as alternatives (see ${file})` : "") +
+ (snap ? ` (undo: ${snap})` : ""),
+ };
+}
+
+// Exported for tests and for a spec that compares values the way the writer does.
+export { stableStringify, valueKey };
diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts
@@ -11,16 +11,17 @@
// failing a hard check loses its failing sentences, and a card with nothing
// left is not written. The manifest is snapshotted, then written whole; every
// draft and its checks go to the project's narration-draft.json.
+//
+// Release 28 (M0): a spec on the media task scaffold (./media.ts). A narration
+// it writes carries its drafted mark (`entry.drafted.narration`), and a card
+// whose narration is the operator's (words with no mark) is never replaced,
+// even with `force`: the draft goes to narration-draft.json's alternatives.
-import { writeFile } from "node:fs/promises";
-import path from "node:path";
-import { structuredAnswer } from "../../../llm";
-import { readIteration, reportSourceOf, readIterationFile } from "../../iterations";
+import { entriesWithId } from "../../drafted.mjs";
import { NARRATION_HARD_RULE, NARRATION_TASTE, NARRATION_WRITING_RULES, rulesForModel } from "../authoringRules";
import { checkNarration, groundingInputOf, sentencesOf, type GroundingInput } from "../grounding";
import type { ManifestEntry } from "../videoOps";
-import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project";
-import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import { runMediaTask, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media";
import type { TaskDeps, TaskResult } from "./types";
export const TITLE_WORDS = 35;
@@ -28,17 +29,9 @@ export const CHAPTER_WORDS = 45;
// A draft this far over its limit is refused outright.
export const OVER_LIMIT_SLACK = 10;
-export type NarrateInput = {
- article: string;
- n: number;
- model: string;
- projectsRoot: string;
+export type NarrateInput = MediaTaskInput & {
// Only these card ids (default: every title and chapter card).
cards?: string[];
- // Re-draft a card that has narration already.
- force?: boolean;
- maxUsd?: number;
- jobId?: string;
};
type Section = { title?: string; body?: string | null; claims?: { text?: string; citations?: string[] }[] | null };
@@ -118,97 +111,81 @@ export function chooseDraft(attempts: Attempt[], g: GroundingInput, limit: numbe
return best;
}
-export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> {
- return runOnIteration(
- { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, step: { task: "narrate", model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } },
- (h) => narrateBody(h, input),
- );
-}
-
-async function narrateBody(h: TaskHandle, input: NarrateInput): Promise<TaskOutcome> {
- const { deps } = h;
- const it = (await readIteration(h.article, h.n, h.paths))!;
- const dir = projectDirOf(it, input.projectsRoot);
- const manifest = await readManifest(dir);
- if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`);
- let report = (await readProjectReport(dir)) as ReportLike | null;
- if (!report) {
- const from = await reportSourceOf(h.article, h.n, h.paths);
- const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths);
- report = text ? (JSON.parse(text) as ReportLike) : null;
- }
- if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to narrate from`);
- const base = groundingInputOf(report);
- const only = input.cards?.length ? new Set(input.cards) : null;
- const drafts = new Map<string, string>();
- const record: Record<string, unknown> = {};
- h.log(`narrating i${h.n} on ${input.model} (${dir})`);
+// A unit: one card, its limit and evidence.
+type NarrateUnit = MediaUnit & { card: ManifestEntry; limit: number; g: GroundingInput; ctxText: string };
- for (const card of manifest.timeline) {
- if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue;
- if (only && !only.has(card.id)) continue;
- if (card.narration?.text && !input.force) continue;
- if ((card.heading ?? "").trim().toLowerCase() === "coverage") {
- record[card.id] = { skipped: "the Coverage card is not narrated (its numbers are on the page)" };
- continue;
- }
- const ctx = cardContext(card, report);
- if (!ctx) {
- record[card.id] = { skipped: "no section in the report matches this card's heading" };
- continue;
- }
- const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS;
- const g: GroundingInput = { ...base, quotes: ctx.quotes };
- const system = narrationSystem(limit);
- const user = `Card heading on screen: ${card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${ctx.text}\n\nWrite this card's narration.`;
- const attempts: Attempt[] = [];
- for (let k = 0; k < 2; k++) {
- deps.signal?.throwIfAborted();
- const extra = attempts.length
- ? `\n\nYour last draft was refused for: ${[...attempts.at(-1)!.hard, ...attempts.at(-1)!.soft].join("; ")}. Write it again without those problems.`
- : "";
- let text = "";
- try {
- const ans = await structuredAnswer<{ text?: unknown }>({
- llm: deps.llm,
- model: input.model,
- system,
- user: user + extra,
- schema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
- meter: h.meter,
- signal: deps.signal,
- });
- text = String(ans.text ?? "").replace(/\s+/g, " ").trim().replace(/^"+|"+$/g, "");
- } catch (e) {
- if (deps.signal?.aborted) throw e;
- attempts.push({ text: "", hard: [(e as Error).message], soft: [] });
+/** Narrate as a media task (./media.ts): one unit per title and chapter card. */
+export const NARRATE_SPEC: MediaTaskSpec<NarrateUnit, string, NarrateInput> = {
+ task: "narrate",
+ // Its audit file kept its release 27 name.
+ draftFile: "narration-draft.json",
+ snapshotOp: "narration",
+ checkName: "narration",
+ turnKind: "narration",
+ noun: "card",
+ verb: "narrated",
+ units(ctx) {
+ const out: (NarrateUnit | MediaSkip)[] = [];
+ const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null;
+ const seen = new Set<string>();
+ for (const card of ctx.manifest.timeline) {
+ if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue;
+ if (only && !only.has(card.id)) continue;
+ if (seen.has(card.id)) continue;
+ seen.add(card.id);
+ if ((card.heading ?? "").trim().toLowerCase() === "coverage") {
+ out.push({ id: card.id, skipped: "the Coverage card is not narrated (its numbers are on the page)" });
continue;
}
- const a = checkDraft(text, g, limit);
- attempts.push(a);
- h.turns([{ kind: "narration", card: card.id, attempt: k + 1, ...a }]);
- if (!a.hard.length && !a.soft.length) break;
- }
- const chosen = chooseDraft(attempts, g, limit);
- record[card.id] = { heading: card.heading, attempts, chosen };
- if (chosen.hard.length) {
- h.log(` ${card.id}: NOT written — ${chosen.hard.join("; ")}`);
- continue;
+ const c = cardContext(card, ctx.report as ReportLike);
+ if (!c) {
+ out.push({ id: card.id, skipped: "no section in the report matches this card's heading" });
+ continue;
+ }
+ const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS;
+ out.push({
+ id: card.id,
+ target: { entry: card.id, field: "narration" },
+ label: card.heading,
+ card,
+ limit,
+ g: { ...ctx.grounding, quotes: c.quotes },
+ ctxText: c.text,
+ });
}
- drafts.set(card.id, chosen.text);
- h.log(` ${card.id}: ${chosen.text}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`);
- }
- await writeFile(path.join(dir, "narration-draft.json"), `${JSON.stringify(record, null, 2)}\n`).catch(() => {});
- const refused = Object.values(record).filter((r) => (r as { chosen?: Attempt }).chosen?.hard.length).length;
- h.check({ name: "narration", ok: refused === 0, detail: `${drafts.size} card(s) drafted${refused ? `, ${refused} not written (a hard check)` : ""}` });
- if (!drafts.size) return { status: "failed", summary: "no card narrated (see narration-draft.json)" };
- const snap = await snapshotManifest(dir, "narration", deps.now?.() ?? new Date());
- for (const e of manifest.timeline) {
- const text = drafts.get(e.id);
- if (e.type !== "card" || !text) continue;
- e.narration = { ...(e.narration && typeof e.narration === "object" ? e.narration : {}), text };
- e.seconds = "auto";
- }
- await writeManifest(dir, manifest);
- return { status: "done", summary: `${drafts.size} card(s) narrated${snap ? ` (undo: ${snap})` : ""}` };
+ return out;
+ },
+ schema: () => ({ type: "object", properties: { text: { type: "string" } }, required: ["text"] }),
+ system: (u) => narrationSystem(u.limit),
+ user: (u) =>
+ `Card heading on screen: ${u.card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${u.ctxText}\n\nWrite this card's narration.`,
+ parse: (answer) =>
+ String((answer as { text?: unknown } | null)?.text ?? "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^"+|"+$/g, ""),
+ check(text, u) {
+ const a = checkDraft(text, u.g, u.limit);
+ return { hard: a.hard, soft: a.soft };
+ },
+ repair(attempts, u) {
+ const chosen = chooseDraft(
+ attempts.map((a) => ({ text: a.value ?? "", hard: a.hard, soft: a.soft })),
+ u.g,
+ u.limit,
+ );
+ return chosen.hard.length ? null : { value: chosen.text, hard: [], soft: chosen.soft };
+ },
+ toField(text, u, manifest) {
+ const cur = entriesWithId(manifest, u.card.id)[0]?.narration;
+ return { ...(cur && typeof cur === "object" ? cur : {}), text };
+ },
+ afterApply(manifest, u) {
+ for (const e of entriesWithId(manifest, u.card.id)) e.seconds = "auto";
+ },
+ describe: (text) => text,
+};
+
+export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> {
+ return runMediaTask(NARRATE_SPEC, input, deps);
}
diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts
@@ -0,0 +1,47 @@
+// Types for ./drafted.mjs (release 28, M0): the drafted marks, the one draft
+// writer, and the validators. See the module's header for the rules.
+
+export type DraftedEntryField = "onscreen" | "narration" | "lines";
+export type DraftedManifestField = "timeline" | "render.chrome.flips" | "render.chrome.threads" | "publish.youtube";
+export type DraftedField = DraftedEntryField | DraftedManifestField;
+
+/** Where a draft goes: an entry's field (`entry` an id), or the manifest's (`entry` absent or null). */
+export type DraftTarget = { entry?: string | null; field: DraftedField | string };
+
+/** Who drafted a field: `at` ISO, `attempt` the one kept (1 or 2). */
+export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: 1 | 2 };
+
+export type ApplyDraftResult = { applied: true } | { applied: false; reason: "operator" | "drafted" | "missing" };
+
+export const DRAFTED_ENTRY_FIELDS: Readonly<Record<DraftedEntryField, readonly string[] | null>>;
+export const DRAFTED_MANIFEST_FIELDS: readonly DraftedManifestField[];
+export const FIELD_TASKS: Readonly<Record<DraftedField, string>>;
+export const PROVENANCE_KEYS: readonly string[];
+export const PUBLISH_YOUTUBE_LIMITS: Readonly<{ title: number; description: number }>;
+
+export function isEntryField(field: string): field is DraftedEntryField;
+export function isManifestField(field: string): field is DraftedManifestField;
+export function provenanceProblems(v: unknown, where: string): string[];
+export function makeProvenance(p: { task: string; model: string; at?: Date | string; iteration?: number; attempt?: number }): Provenance;
+export function entriesWithId(manifest: unknown, id: string): Record<string, any>[];
+export function readField(manifest: unknown, target: DraftTarget): unknown;
+export function isEmptyField(field: string, v: unknown): boolean;
+export function draftedOf(manifest: unknown, target: DraftTarget): Provenance | null;
+export function ownerOf(manifest: unknown, target: DraftTarget): "empty" | "drafted" | "operator";
+export function applyDraft(
+ manifest: unknown,
+ o: { entry?: string | null; field: DraftedField | string; value: unknown; provenance: Provenance; force?: boolean },
+): ApplyDraftResult;
+export function clearDrafted(manifest: unknown, target: DraftTarget): boolean;
+export function stableStringify(v: unknown): string;
+export function fieldSignature(manifest: unknown, target: DraftTarget): unknown;
+export function valueKey(v: unknown): string;
+export function fieldKey(manifest: unknown, target: DraftTarget): string;
+export function draftedFields(manifest: unknown): { entry: string | null; field: DraftedField; provenance: Provenance; value: unknown }[];
+export function reviewAddress(target: DraftTarget): string;
+export function parseReviewAddress(address: unknown): { task: string; entry: string | null; field: string } | null;
+export function orphanDrafts(manifest: unknown): { where: string; entry: string | null; field: string }[];
+export function pruneDrafted(manifest: unknown): string[];
+export function clearEditedDrafts(before: unknown, after: unknown): { entry: string | null; field: string }[];
+export function validateDrafted(manifest: unknown): string[];
+export function validatePublish(manifest: unknown): string[];
diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs
@@ -0,0 +1,521 @@
+// DRAFTED FIELDS — THE one copy of where a generated manifest field says it was
+// drafted, the one writer every draft task goes through, and the rules that
+// keep an operator's words from being overwritten (release 28, M0).
+//
+// Plain JS (with JSDoc types, and ./drafted.d.mts for TypeScript) for the
+// reason ./verdicts.mjs is: umtool's report-to-video scripts and its manifest
+// writer are `.mjs` run by bare `node`, and the common tasks are TypeScript;
+// both read and write the same marks.
+//
+// WHERE THE MARK LIVES. A provenance is `{ task, model, at, iteration?, attempt }`
+// (`at` ISO; `attempt` 1 or 2, the one kept). An ENTRY's field carries it on the
+// entry, keyed by field — `entry.drafted = { onscreen, narration, lines }` (any
+// entry's on-screen text, a card's narration, a teaser's lines). A MANIFEST
+// field carries it in a top-level map keyed by path — `manifest.drafted =
+// { "timeline", "render.chrome.flips", "render.chrome.threads",
+// "publish.youtube" }` ("timeline" is the cut's ORDER; "render.chrome.threads"
+// covers each clip's `thread` key too). Nowhere else.
+//
+// WHO OWNS A FIELD. Empty: nobody (a draft may fill it). Non-empty with a mark:
+// the task that drafted it (a forced re-draft may replace it). Non-empty with
+// NO mark: the operator — written by hand, or edited since it was drafted —
+// and never replaced, forced or not (`applyDraft`). An edit through umtool's
+// manifest writer removes the mark (`clearEditedDrafts`), which is what makes
+// an edited field the operator's.
+//
+// A mark whose field is gone (an orphan) is dropped with a warning
+// (`pruneDrafted`); a mark that is malformed or in a place no field may be
+// drafted is refused (`validateDrafted`).
+
+import { createHash } from "node:crypto";
+
+/** The entry fields that may be drafted, and the entry types each is on (null: any). */
+export const DRAFTED_ENTRY_FIELDS = Object.freeze({
+ onscreen: null,
+ narration: Object.freeze(["card"]),
+ lines: Object.freeze(["teaser"]),
+});
+
+/** The manifest fields that may be drafted, by path. */
+export const DRAFTED_MANIFEST_FIELDS = Object.freeze(["timeline", "render.chrome.flips", "render.chrome.threads", "publish.youtube"]);
+
+/**
+ * Each draftable field's own task: the one that drafts it, and the `<task>` of
+ * its review address (`reviewAddress`), whichever task drafted it this time —
+ * so a field's review has ONE address.
+ */
+export const FIELD_TASKS = Object.freeze({
+ onscreen: "onscreen",
+ narration: "narrate",
+ lines: "teaser",
+ timeline: "cut",
+ "render.chrome.flips": "flips",
+ "render.chrome.threads": "threads",
+ "publish.youtube": "youtube",
+});
+
+/** The keys of a provenance, in the order they are written. */
+export const PROVENANCE_KEYS = Object.freeze(["task", "model", "at", "iteration", "attempt"]);
+
+/** `publish.youtube`'s limits: YouTube's own (a title of 100, a description of 5000). */
+export const PUBLISH_YOUTUBE_LIMITS = Object.freeze({ title: 100, description: 5000 });
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** @param {string} field */
+export const isEntryField = (field) => Object.prototype.hasOwnProperty.call(DRAFTED_ENTRY_FIELDS, field);
+/** @param {string} field */
+export const isManifestField = (field) => DRAFTED_MANIFEST_FIELDS.includes(field);
+
+/**
+ * Every reason `v` is not a provenance, naming `where` (empty: it is one).
+ *
+ * @param {unknown} v
+ * @param {string} where
+ * @returns {string[]}
+ */
+export function provenanceProblems(v, where) {
+ if (!isObj(v)) return [`${where} must be { task, model, at, iteration?, attempt }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!PROVENANCE_KEYS.includes(k)) errors.push(`${where}.${k} is not a provenance key (${PROVENANCE_KEYS.join(", ")})`);
+ const word = (k, max) => {
+ if (typeof v[k] !== "string" || !v[k].trim()) errors.push(`${where}.${k} must be a name`);
+ else if (v[k].length > max || /[\r\n]/.test(v[k])) errors.push(`${where}.${k} must be one line of at most ${max} characters`);
+ };
+ word("task", 64);
+ word("model", 200);
+ if (typeof v.at !== "string" || Number.isNaN(Date.parse(v.at))) errors.push(`${where}.at must be an ISO date and time`);
+ if (v.iteration !== undefined && !(Number.isInteger(v.iteration) && v.iteration > 0)) errors.push(`${where}.iteration must be a positive whole number`);
+ if (v.attempt !== 1 && v.attempt !== 2) errors.push(`${where}.attempt must be 1 or 2 (the attempt kept)`);
+ return errors;
+}
+
+/**
+ * A provenance, its keys in order. `at` defaults to now.
+ *
+ * @param {{ task: string, model: string, at?: Date | string, iteration?: number, attempt?: number }} p
+ */
+export function makeProvenance({ task, model, at = new Date(), iteration, attempt = 1 }) {
+ return {
+ task,
+ model,
+ at: typeof at === "string" ? at : at.toISOString(),
+ ...(iteration !== undefined && iteration !== null ? { iteration } : {}),
+ attempt,
+ };
+}
+
+/** Every timeline entry with this id (a cut's `variant` twins share one). */
+export function entriesWithId(manifest, id) {
+ return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.id === id);
+}
+
+const pathParts = (field) => field.split(".");
+
+function readPath(obj, field) {
+ let cur = obj;
+ for (const p of pathParts(field)) {
+ if (!isObj(cur)) return undefined;
+ cur = cur[p];
+ }
+ return cur;
+}
+
+/**
+ * A field's value: an entry's (`target.entry` an id; the first entry with it)
+ * or the manifest's (`target.entry` absent). "timeline" is the timeline itself.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function readField(manifest, { entry = null, field }) {
+ if (entry !== null && entry !== undefined) return entriesWithId(manifest, entry)[0]?.[field];
+ return readPath(manifest, field);
+}
+
+/**
+ * Is this value of this field empty -- nothing a person wrote? A narration with
+ * no words, an on-screen block with no text, a list with nothing in it.
+ *
+ * @param {string} field
+ * @param {unknown} v
+ */
+export function isEmptyField(field, v) {
+ if (v === undefined || v === null || v === "") return true;
+ if (field === "narration") return !(isObj(v) && typeof v.text === "string" && v.text.trim());
+ if (field === "onscreen") return !(isObj(v) && ["title", "subtitle"].some((k) => typeof v[k] === "string" && v[k].trim()));
+ if (field === "render.chrome.flips") return !(isObj(v) && Array.isArray(v.pairs) && v.pairs.length);
+ if (field === "render.chrome.threads") return !(isObj(v) && Array.isArray(v.list) && v.list.length);
+ if (field === "publish.youtube") return !(isObj(v) && ["title", "description"].some((k) => typeof v[k] === "string" && v[k].trim()));
+ if (Array.isArray(v)) return v.length === 0;
+ if (isObj(v)) return Object.keys(v).length === 0;
+ return false;
+}
+
+/**
+ * A field's drafted mark, or null.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function draftedOf(manifest, { entry = null, field }) {
+ if (entry !== null && entry !== undefined) {
+ const e = entriesWithId(manifest, entry)[0];
+ const p = isObj(e?.drafted) ? e.drafted[field] : undefined;
+ return isObj(p) ? p : null;
+ }
+ const p = isObj(manifest?.drafted) ? manifest.drafted[field] : undefined;
+ return isObj(p) ? p : null;
+}
+
+/**
+ * Who a field belongs to now: "empty", "drafted" or "operator".
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ * @returns {"empty" | "drafted" | "operator"}
+ */
+export function ownerOf(manifest, target) {
+ if (isEmptyField(target.field, readField(manifest, target))) return "empty";
+ return draftedOf(manifest, target) ? "drafted" : "operator";
+}
+
+function assertTarget({ entry = null, field }) {
+ const onEntry = entry !== null && entry !== undefined;
+ if (onEntry && !isEntryField(field)) throw new Error(`${field} is not a field an entry's draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`);
+ if (!onEntry && !isManifestField(field)) throw new Error(`${field} is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")})`);
+}
+
+function setMark(manifest, { entry = null, field }, provenance) {
+ if (entry !== null && entry !== undefined) {
+ for (const e of entriesWithId(manifest, entry)) e.drafted = { ...(isObj(e.drafted) ? e.drafted : {}), [field]: { ...provenance } };
+ } else {
+ manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), [field]: { ...provenance } };
+ }
+}
+
+/**
+ * THE writer every draft task uses. Sets the field to `value` and marks it
+ * drafted -- unless the field is the operator's (non-empty, no mark), which is
+ * never replaced, `force` or not; or is a draft already and `force` is not set.
+ * The caller keeps a refused value as an alternative (`<task>-draft.json`).
+ * Mutates `manifest`.
+ *
+ * applied: true
+ * applied: false, reason "operator" a field somebody wrote or edited
+ * applied: false, reason "drafted" a draft already, and no `force`
+ * applied: false, reason "missing" no entry with that id, or (flips,
+ * threads) no `render.chrome` to hold it
+ *
+ * An entry id names every entry with it (variant twins). "timeline" takes the
+ * new timeline array; "render.chrome.threads" takes `{ list }` (the task sets
+ * each clip's `thread` key itself once applied).
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string, value: unknown, provenance: Record<string, unknown>, force?: boolean }} o
+ * @returns {{ applied: true } | { applied: false, reason: "operator" | "drafted" | "missing" }}
+ */
+export function applyDraft(manifest, { entry = null, field, value, provenance, force = false }) {
+ const target = { entry, field };
+ assertTarget(target);
+ const bad = provenanceProblems(provenance, "provenance");
+ if (bad.length) throw new Error(bad.join("; "));
+ const onEntry = entry !== null && entry !== undefined;
+ if (onEntry) {
+ const es = entriesWithId(manifest, entry);
+ if (!es.length) return { applied: false, reason: "missing" };
+ const types = DRAFTED_ENTRY_FIELDS[field];
+ if (types && !es.every((e) => types.includes(e.type))) throw new Error(`${entry} is a ${es[0].type}: ${field} is drafted only on a ${types.join(" or ")}`);
+ } else if (field.startsWith("render.chrome.") && !isObj(manifest?.render?.chrome)) {
+ return { applied: false, reason: "missing" };
+ }
+ const owner = ownerOf(manifest, target);
+ if (owner === "operator") return { applied: false, reason: "operator" };
+ if (owner === "drafted" && !force) return { applied: false, reason: "drafted" };
+ const copy = () => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));
+ if (onEntry) {
+ for (const e of entriesWithId(manifest, entry)) e[field] = copy();
+ } else if (field === "timeline") {
+ manifest.timeline = copy();
+ } else {
+ const parts = pathParts(field);
+ let cur = manifest;
+ for (const p of parts.slice(0, -1)) {
+ if (!isObj(cur[p])) cur[p] = {};
+ cur = cur[p];
+ }
+ cur[parts.at(-1)] = copy();
+ }
+ setMark(manifest, target, provenance);
+ return { applied: true };
+}
+
+/**
+ * Remove a field's drafted mark (the operator's edit). True when there was one.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function clearDrafted(manifest, { entry = null, field }) {
+ let had = false;
+ if (entry !== null && entry !== undefined) {
+ for (const e of entriesWithId(manifest, entry)) {
+ if (!isObj(e.drafted) || !(field in e.drafted)) continue;
+ had = true;
+ delete e.drafted[field];
+ if (!Object.keys(e.drafted).length) delete e.drafted;
+ }
+ return had;
+ }
+ if (isObj(manifest?.drafted) && field in manifest.drafted) {
+ had = true;
+ delete manifest.drafted[field];
+ if (!Object.keys(manifest.drafted).length) delete manifest.drafted;
+ }
+ return had;
+}
+
+/** JSON with every object's keys sorted: one text per value, whatever order it was built in. */
+export function stableStringify(v) {
+ if (Array.isArray(v)) return `[${v.map((x) => (x === undefined ? "null" : stableStringify(x))).join(",")}]`;
+ if (isObj(v)) {
+ return `{${Object.keys(v)
+ .filter((k) => v[k] !== undefined)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`)
+ .join(",")}}`;
+ }
+ return JSON.stringify(v ?? null);
+}
+
+/**
+ * What a field IS, for telling an edit from no edit and for a review's key: the
+ * value -- except "timeline", whose draft is the ORDER (the entries' ids), and
+ * "render.chrome.threads", which is the list and every clip's `thread` key.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function fieldSignature(manifest, target) {
+ if ((target.entry === null || target.entry === undefined) && target.field === "timeline") {
+ return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).map((e) => e?.id ?? null);
+ }
+ if ((target.entry === null || target.entry === undefined) && target.field === "render.chrome.threads") {
+ const clips = {};
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && e.thread !== undefined) clips[e.id] = e.thread;
+ return { threads: readField(manifest, target) ?? null, clips };
+ }
+ return readField(manifest, target) ?? null;
+}
+
+/** A value's content key: sha256 of its stable JSON, hex. */
+export function valueKey(v) {
+ return createHash("sha256").update(stableStringify(v)).digest("hex");
+}
+
+/**
+ * A field's content key (`fieldSignature` hashed). A review's verdict is on
+ * this key, so an edit or a re-draft leaves it unapproved. (A card's narration
+ * is keyed by umtool's `narrationKey` instead -- the words and the voice --
+ * report-to-video/drafts-review.mjs.)
+ */
+export function fieldKey(manifest, target) {
+ return valueKey(fieldSignature(manifest, target));
+}
+
+/**
+ * Every drafted field of a manifest, in timeline order then the manifest's:
+ * `{ entry, field, provenance, value }`. An entry id is listed once (variant
+ * twins share a field). Orphans (a mark on an empty field) are left out.
+ *
+ * @param {any} manifest
+ * @returns {{ entry: string | null, field: string, provenance: Record<string, unknown>, value: unknown }[]}
+ */
+export function draftedFields(manifest) {
+ const out = [];
+ const seen = new Set();
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (!isObj(e) || !isObj(e.drafted)) continue;
+ for (const [field, p] of Object.entries(e.drafted)) {
+ const k = `${e.id}\u0000${field}`;
+ if (seen.has(k) || !isEntryField(field) || !isObj(p) || isEmptyField(field, e[field])) continue;
+ seen.add(k);
+ out.push({ entry: e.id, field, provenance: p, value: e[field] });
+ }
+ }
+ if (isObj(manifest?.drafted)) {
+ for (const field of DRAFTED_MANIFEST_FIELDS) {
+ const p = manifest.drafted[field];
+ const value = readField(manifest, { field });
+ if (!isObj(p) || isEmptyField(field, value)) continue;
+ out.push({ entry: null, field, provenance: p, value });
+ }
+ }
+ return out;
+}
+
+/** The review address of a field: `<its task>/<entry id or *>/<field>`. */
+export function reviewAddress({ entry = null, field }) {
+ const task = FIELD_TASKS[field] ?? "draft";
+ return `${task}/${entry === null || entry === undefined ? "*" : entry}/${field}`;
+}
+
+/** An address back to its parts, or null. */
+export function parseReviewAddress(address) {
+ if (typeof address !== "string") return null;
+ const m = /^([A-Za-z0-9_-]{1,64})\/([^/]{1,200})\/([A-Za-z0-9_.-]{1,64})$/.exec(address);
+ if (!m) return null;
+ const [, task, entry, field] = m;
+ return { task, entry: entry === "*" ? null : entry, field };
+}
+
+/**
+ * The marks whose field is gone or empty (or whose key is not a field at
+ * all), as `{ where, entry, field }`. Read-only: `pruneDrafted` drops them.
+ *
+ * @param {any} manifest
+ */
+export function orphanDrafts(manifest) {
+ const out = [];
+ (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => {
+ if (!isObj(e) || !isObj(e.drafted)) return;
+ for (const field of Object.keys(e.drafted)) {
+ if (isEntryField(field) && isEmptyField(field, e[field])) out.push({ where: `timeline[${i}] (${e.id}).drafted.${field}`, entry: e.id, field });
+ }
+ });
+ if (isObj(manifest?.drafted)) {
+ for (const field of Object.keys(manifest.drafted)) {
+ if (isManifestField(field) && isEmptyField(field, readField(manifest, { field }))) out.push({ where: `drafted["${field}"]`, entry: null, field });
+ }
+ }
+ return out;
+}
+
+/**
+ * Drop every orphan mark (and a `drafted` map left empty). Mutates; returns a
+ * sentence per mark dropped.
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function pruneDrafted(manifest) {
+ const dropped = orphanDrafts(manifest);
+ for (const o of dropped) {
+ if (o.entry === null) clearDrafted(manifest, { field: o.field });
+ else {
+ for (const e of Array.isArray(manifest.timeline) ? manifest.timeline : []) {
+ if (!isObj(e) || e.id !== o.entry || !isObj(e.drafted) || !(o.field in e.drafted) || !isEmptyField(o.field, e[o.field])) continue;
+ delete e.drafted[o.field];
+ if (!Object.keys(e.drafted).length) delete e.drafted;
+ }
+ }
+ }
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && isObj(e.drafted) && !Object.keys(e.drafted).length) delete e.drafted;
+ if (isObj(manifest?.drafted) && !Object.keys(manifest.drafted).length) delete manifest.drafted;
+ return dropped.map((o) => `${o.where}: its field is gone, so the drafted mark is dropped`);
+}
+
+/**
+ * The operator's write: every drafted field whose value differs between
+ * `before` and `after` loses its mark in `after` (it is the operator's now),
+ * and orphans are dropped. Mutates `after`; returns the fields cleared as
+ * `{ entry, field }`. What umtool's manifest writer runs on every write.
+ *
+ * @param {any} before
+ * @param {any} after
+ */
+export function clearEditedDrafts(before, after) {
+ const cleared = [];
+ for (const d of draftedFields(after)) {
+ const t = { entry: d.entry, field: d.field };
+ // A mark that was not there before is the writer's own (a draft applied in
+ // this write): leave it.
+ if (!draftedOf(before, t)) continue;
+ if (stableStringify(fieldSignature(before, t)) !== stableStringify(fieldSignature(after, t))) {
+ clearDrafted(after, t);
+ cleared.push(t);
+ }
+ }
+ pruneDrafted(after);
+ return cleared;
+}
+
+/**
+ * Every reason the manifest's drafted marks cannot be built: a mark that is
+ * not a provenance, or one in a place no field may be drafted (an unknown
+ * field, `narration` on a clip, `lines` on a card, a `drafted` key under the
+ * render block or `publish`). An orphan is NOT an error (`orphanDrafts`).
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function validateDrafted(manifest) {
+ const errors = [];
+ if (manifest?.drafted !== undefined) {
+ if (!isObj(manifest.drafted)) errors.push("drafted must be an object of field path → provenance");
+ else {
+ for (const [k, p] of Object.entries(manifest.drafted)) {
+ if (!isManifestField(k)) {
+ errors.push(`drafted["${k}"] is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")}; an entry's own fields are marked on the entry)`);
+ continue;
+ }
+ errors.push(...provenanceProblems(p, `drafted["${k}"]`));
+ }
+ }
+ }
+ (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => {
+ if (!isObj(e)) return;
+ for (const field of Object.keys(DRAFTED_ENTRY_FIELDS)) {
+ if (isObj(e[field]) && "drafted" in e[field]) errors.push(`timeline[${i}] (${e.id}).${field}.drafted: the mark goes on the entry (drafted.${field}), not inside the field`);
+ }
+ if (e.drafted === undefined) return;
+ const w = `timeline[${i}] (${e.id}).drafted`;
+ if (!isObj(e.drafted)) {
+ errors.push(`${w} must be an object of field → provenance`);
+ return;
+ }
+ for (const [field, p] of Object.entries(e.drafted)) {
+ if (!isEntryField(field)) {
+ errors.push(`${w}.${field} is not an entry field a draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`);
+ continue;
+ }
+ const types = DRAFTED_ENTRY_FIELDS[field];
+ if (types && !types.includes(e.type)) errors.push(`${w}.${field}: a ${e.type ?? "entry"} has no ${field} to draft (only a ${types.join(" or ")})`);
+ errors.push(...provenanceProblems(p, `${w}.${field}`));
+ }
+ });
+ if (isObj(manifest?.render) && "drafted" in manifest.render) errors.push("render.drafted: a manifest field's mark goes in the top-level drafted map");
+ if (isObj(manifest?.publish)) {
+ if ("drafted" in manifest.publish) errors.push("publish.drafted: a manifest field's mark goes in the top-level drafted map");
+ if (isObj(manifest.publish.youtube) && "drafted" in manifest.publish.youtube) errors.push("publish.youtube.drafted: the mark goes in the top-level drafted map");
+ }
+ return errors;
+}
+
+/**
+ * `publish` (release 28): what is published beside the video. Only
+ * `publish.youtube { title, description }`, two strings, for now (M6 fills it).
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function validatePublish(manifest) {
+ const p = manifest?.publish;
+ if (p === undefined) return [];
+ if (!isObj(p)) return ["publish must be an object ({ youtube })"];
+ const errors = [];
+ for (const k of Object.keys(p)) if (k !== "youtube" && k !== "drafted") errors.push(`publish.${k} is not a publish key (youtube)`);
+ const y = p.youtube;
+ if (y === undefined) return errors;
+ if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"];
+ for (const k of Object.keys(y)) if (k !== "title" && k !== "description" && k !== "drafted") errors.push(`publish.youtube.${k} is not a YouTube field (title, description)`);
+ for (const k of ["title", "description"]) {
+ if (typeof y[k] !== "string") {
+ errors.push(`publish.youtube.${k} must be a string`);
+ continue;
+ }
+ if (y[k].length > PUBLISH_YOUTUBE_LIMITS[k]) errors.push(`publish.youtube.${k} is ${y[k].length} characters (at most ${PUBLISH_YOUTUBE_LIMITS[k]})`);
+ }
+ if (typeof y.title === "string" && /[\r\n]/.test(y.title)) errors.push("publish.youtube.title must be one line");
+ return errors;
+}
diff --git a/common/lib/report/drafted.test.ts b/common/lib/report/drafted.test.ts
@@ -0,0 +1,183 @@
+// drafted.mjs (release 28, M0): the marks, the one draft writer, the
+// operator's edit, orphans, and the validators — over the S0 kit's `full`
+// manifest (every media field a draft task writes).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import {
+ applyDraft,
+ clearEditedDrafts,
+ draftedFields,
+ draftedOf,
+ fieldKey,
+ makeProvenance,
+ orphanDrafts,
+ ownerOf,
+ parseReviewAddress,
+ pruneDrafted,
+ reviewAddress,
+ validateDrafted,
+ validatePublish,
+} from "./drafted.mjs";
+
+const full = () => JSON.parse(readFileSync(new URL("../../testing/draft/manifests/full.video.manifest.json", import.meta.url), "utf8"));
+const P = (o: Partial<{ task: string; attempt: number }> = {}) =>
+ makeProvenance({ task: o.task ?? "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: o.attempt ?? 1 });
+const entry = (m: { timeline: Record<string, any>[] }, id: string) => m.timeline.find((e) => e.id === id)!;
+
+test("applyDraft: an empty field is drafted and marked; the operator's is never replaced, force or not", () => {
+ const m = full();
+ // c02 has no on-screen text: a draft fills it and says so.
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() }), { applied: true });
+ assert.deepEqual(entry(m, "c02").onscreen, { title: "The oven" });
+ assert.deepEqual(entry(m, "c02").drafted, { onscreen: { task: "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: 1 } });
+ assert.equal(ownerOf(m, { entry: "c02", field: "onscreen" }), "drafted");
+ // c01's was written by hand: kept, with or without force.
+ const before = JSON.stringify(entry(m, "c01"));
+ assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P() }), { applied: false, reason: "operator" });
+ assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P(), force: true }), { applied: false, reason: "operator" });
+ assert.equal(JSON.stringify(entry(m, "c01")), before);
+ // A draft is re-drafted only with force.
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }) }), { applied: false, reason: "drafted" });
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }), force: true }), { applied: true });
+ assert.equal(entry(m, "c02").onscreen.title, "Again");
+ assert.equal(entry(m, "c02").drafted.onscreen.attempt, 2);
+ // No such entry; flips with no deck to hold them.
+ assert.deepEqual(applyDraft(m, { entry: "nope", field: "onscreen", value: { title: "x" }, provenance: P() }), { applied: false, reason: "missing" });
+ const bare = { timeline: [] as unknown[] };
+ assert.deepEqual(applyDraft(bare, { field: "render.chrome.flips", value: { pairs: [{}] }, provenance: P({ task: "flips" }) }), { applied: false, reason: "missing" });
+ // A field in the wrong place is the task's bug, thrown.
+ assert.throws(() => applyDraft(m, { entry: "c01", field: "narration", value: { text: "x" }, provenance: P() }), /narration is drafted only on a card/);
+ assert.throws(() => applyDraft(m, { field: "title", value: "x", provenance: P() }), /not a manifest field/);
+ assert.throws(() => applyDraft(m, { entry: "c03", field: "onscreen", value: { title: "x" }, provenance: { ...P(), attempt: 3 } as never }), /attempt must be 1 or 2/);
+});
+
+test("applyDraft: manifest fields — the teaser's lines on the entry, publish.youtube made, the cut's order; marks in the top-level map", () => {
+ const m = full();
+ // The fixture's teaser lines are hand-written: the operator's.
+ assert.deepEqual(applyDraft(m, { entry: "fin", field: "lines", value: ["a"], provenance: P({ task: "teaser" }), force: true }), { applied: false, reason: "operator" });
+ assert.deepEqual(applyDraft(m, { field: "publish.youtube", value: { title: "T", description: "D" }, provenance: P({ task: "youtube" }) }), { applied: true });
+ assert.deepEqual(m.publish, { youtube: { title: "T", description: "D" } });
+ assert.equal(m.drafted["publish.youtube"].task, "youtube");
+ // The threads exist and are the operator's.
+ assert.deepEqual(applyDraft(m, { field: "render.chrome.threads", value: { list: [] }, provenance: P({ task: "threads" }), force: true }), { applied: false, reason: "operator" });
+ // A cut's timeline with no mark is the operator's (M1 decides what the converter's order counts as).
+ assert.equal(ownerOf(m, { field: "timeline" }), "operator");
+ assert.deepEqual(validateDrafted(m), []);
+ assert.deepEqual(validatePublish(m), []);
+ assert.deepEqual(draftedFields(m).map((d) => [d.entry, d.field]), [[null, "publish.youtube"]]);
+});
+
+test("an operator's edit clears the mark; an untouched field keeps it; each field by its own signature", () => {
+ const m = full();
+ applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() });
+ m.drafted = {
+ timeline: P({ task: "cut" }),
+ "render.chrome.threads": P({ task: "threads" }),
+ "publish.youtube": P({ task: "youtube" }),
+ };
+ m.publish = { youtube: { title: "T", description: "D" } };
+ entry(m, "the-contest").drafted = { narration: P({ task: "narrate" }) };
+ entry(m, "fin").drafted = { lines: P({ task: "teaser" }) };
+ const base = JSON.parse(JSON.stringify(m));
+
+ // Each field edited alone clears only its own mark.
+ const edits: [string, (x: any) => void, string | null, string][] = [
+ ["onscreen", (x) => (entry(x, "c02").onscreen = { title: "Hand" }), "c02", "onscreen"],
+ ["narration", (x) => (entry(x, "the-contest").narration.text = "Mine now."), "the-contest", "narration"],
+ ["lines", (x) => (entry(x, "fin").lines = ["One", "Two", "Three"]), "fin", "lines"],
+ ["order", (x) => x.timeline.splice(3, 0, x.timeline.splice(2, 1)[0]), null, "timeline"],
+ ["a clip's thread", (x) => (entry(x, "c02").thread = "contest"), null, "render.chrome.threads"],
+ ["youtube", (x) => (x.publish.youtube.title = "Mine"), null, "publish.youtube"],
+ ];
+ for (const [what, edit, id, field] of edits) {
+ const after = JSON.parse(JSON.stringify(base));
+ edit(after);
+ const cleared = clearEditedDrafts(base, after);
+ assert.deepEqual(cleared, [{ entry: id, field }], what);
+ assert.equal(draftedOf(after, { entry: id, field }), null, what);
+ assert.equal(ownerOf(after, { entry: id, field }), "operator", what);
+ assert.equal(draftedFields(after).length, draftedFields(base).length - 1, `${what}: the others keep theirs`);
+ }
+ // An edit elsewhere in the entry (its on-screen text) leaves the cut's order and the narration drafted.
+ const same = JSON.parse(JSON.stringify(base));
+ entry(same, "c01").onscreen.title = "Edited";
+ assert.deepEqual(clearEditedDrafts(base, same), []);
+ // A mark the write itself made (a draft applied in it) is the writer's, kept.
+ const fresh = JSON.parse(JSON.stringify(base));
+ applyDraft(fresh, { entry: "c03", field: "onscreen", value: { title: "New" }, provenance: P() });
+ assert.deepEqual(clearEditedDrafts(base, fresh), []);
+ assert.equal(draftedOf(fresh, { entry: "c03", field: "onscreen" })?.task, "onscreen");
+});
+
+test("orphans: a mark whose field is gone is listed, then dropped with a sentence; validation does not refuse it", () => {
+ const m = full();
+ entry(m, "c03").drafted = { onscreen: P() };
+ m.drafted = { "render.chrome.flips": P({ task: "flips" }) };
+ assert.deepEqual(validateDrafted(m), []);
+ assert.deepEqual(orphanDrafts(m).map((o) => o.where), ["timeline[4] (c03).drafted.onscreen", 'drafted["render.chrome.flips"]']);
+ const said = pruneDrafted(m);
+ assert.equal(said.length, 2);
+ assert.match(said[0]!, /its field is gone, so the drafted mark is dropped/);
+ assert.equal(entry(m, "c03").drafted, undefined);
+ assert.equal(m.drafted, undefined);
+ assert.deepEqual(orphanDrafts(m), []);
+});
+
+test("validateDrafted: a mark where no field may be drafted, or not a provenance, is refused", () => {
+ const m = full();
+ entry(m, "c01").drafted = { onscreen: P(), quote: P() };
+ entry(m, "title").drafted = { lines: P() };
+ entry(m, "c02").drafted = { narration: P() };
+ entry(m, "c04").drafted = { onscreen: { task: "", model: "m", at: "yesterday", attempt: 1, extra: true } };
+ entry(m, "c05").onscreen = { title: "x", drafted: P() } as never;
+ m.drafted = { title: P(), timeline: P({ task: "cut" }) };
+ m.render.drafted = {};
+ const errors = validateDrafted(m);
+ for (const re of [
+ /\(c01\)\.drafted\.quote is not an entry field a draft may set/,
+ /\(title\)\.drafted\.lines: a card has no lines to draft \(only a teaser\)/,
+ /\(c02\)\.drafted\.narration: a clip has no narration to draft \(only a card\)/,
+ /\(c04\)\.drafted\.onscreen\.extra is not a provenance key/,
+ /\(c04\)\.drafted\.onscreen\.task must be a name/,
+ /\(c04\)\.drafted\.onscreen\.at must be an ISO date and time/,
+ /\(c05\)\.onscreen\.drafted: the mark goes on the entry/,
+ /drafted\["title"\] is not a manifest field a draft may set/,
+ /render\.drafted: a manifest field's mark goes in the top-level drafted map/,
+ ]) {
+ assert.ok(errors.some((e) => re.test(e)), `${re}\n${errors.join("\n")}`);
+ }
+ assert.equal(errors.length, 9, errors.join("\n"));
+});
+
+test("validatePublish: publish.youtube is two strings, YouTube's limits; nothing else under publish", () => {
+ assert.deepEqual(validatePublish({}), []);
+ assert.deepEqual(validatePublish({ publish: { youtube: { title: "T", description: "" } } }), []);
+ const bad = validatePublish({ publish: { youtube: { title: "a\nb", description: 3, tags: [] }, x: 1 } });
+ assert.deepEqual(bad, [
+ "publish.x is not a publish key (youtube)",
+ "publish.youtube.tags is not a YouTube field (title, description)",
+ "publish.youtube.description must be a string",
+ "publish.youtube.title must be one line",
+ ]);
+ assert.match(validatePublish({ publish: { youtube: { title: "t".repeat(101), description: "" } } })[0]!, /101 characters \(at most 100\)/);
+ assert.deepEqual(validatePublish({ publish: [] }), ["publish must be an object ({ youtube })"]);
+});
+
+test("review addresses and keys: one address per field, a key that moves with the value", () => {
+ assert.equal(reviewAddress({ entry: "k1", field: "narration" }), "narrate/k1/narration");
+ assert.equal(reviewAddress({ field: "render.chrome.flips" }), "flips/*/render.chrome.flips");
+ assert.equal(reviewAddress({ entry: "c01", field: "onscreen" }), "onscreen/c01/onscreen");
+ assert.deepEqual(parseReviewAddress("teaser/fin/lines"), { task: "teaser", entry: "fin", field: "lines" });
+ assert.deepEqual(parseReviewAddress("cut/*/timeline"), { task: "cut", entry: null, field: "timeline" });
+ assert.equal(parseReviewAddress("no"), null);
+ const m = full();
+ const k = fieldKey(m, { entry: "c01", field: "onscreen" });
+ assert.equal(fieldKey(JSON.parse(JSON.stringify(m)), { entry: "c01", field: "onscreen" }), k, "same value, same key");
+ // Key order in the object does not matter.
+ entry(m, "c01").onscreen = { subtitle: entry(m, "c01").onscreen.subtitle, title: entry(m, "c01").onscreen.title };
+ assert.equal(fieldKey(m, { entry: "c01", field: "onscreen" }), k);
+ entry(m, "c01").onscreen.title = "Edited";
+ assert.notEqual(fieldKey(m, { entry: "c01", field: "onscreen" }), k);
+});
diff --git a/common/package.json b/common/package.json
@@ -35,6 +35,7 @@
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
+ "./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs",
"./lib/toolProbe.mjs": "./lib/toolProbe.mjs",
"./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs",
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -303,8 +303,9 @@ test("narrate: a step on a done iteration; a quote read out is re-asked; the man
assert.equal(revisions.length, 1);
assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/);
const draft = JSON.parse(await readFile(path.join(projectDir!, "narration-draft.json"), "utf8"));
- assert.equal(draft["the-bakery"].attempts.length, 2);
- assert.match(draft["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/);
+ assert.equal(draft.units["the-bakery"].attempts.length, 2);
+ assert.match(draft.units["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/);
+ assert.equal(cards["the-bakery"].drafted.narration.task, "narrate", "a narration it writes carries its drafted mark");
// The prompts carry rules, never worked examples, and no tag rule.
const sys = ol.requests.at(-1).messages[0].content as string;
assert.ok(!sys.includes("One file. No title."), "no worked example");