// 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/-auto-before-`) 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 `-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: `h.progress` counts the units drafted of those // to draft (`spec.progressMetric`, default "entries"; narrate's "cards"). // Batching (`spec.batch`, release 28 M2) asks several units at once. import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { structuredAnswer } from "../../../llm"; import type { CallItem } from "../../../llm/callLog"; import { CallSlot } from "../../../llm/callLog-server"; 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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; 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; /** What a spec is handed: the run, the project, the manifest as read, the report. */ export type MediaContext = { 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 = { 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"; }; /** `-draft.json`: the run's record. */ export type DraftFile = { task: string; model: string; at: string; article: string; iteration: number; units: Record>; checks: { name: string; ok: boolean; detail?: string }[]; alternatives: DraftAlternative[]; }; export type MediaTaskSpec = { // The task's name: the step's, the provenance's, the default file's. task: string; // Default `-draft.json`. draftFile?: string; // The snapshot's op (`auto-before-`); 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: " (s) "; defaults "field", "drafted". noun?: string; verb?: string; units(ctx: MediaContext): (U | MediaSkip)[] | Promise<(U | MediaSkip)[]>; schema(unit: U, ctx: MediaContext): object; system(unit: U, ctx: MediaContext): string; user(unit: U, ctx: MediaContext): string; // The model's answer to a value; a throw is that attempt's hard failure. parse(answer: unknown, unit: U, ctx: MediaContext): V; // The code checks: `hard` refuses the value, `soft` is a flag. check(value: V, unit: U, ctx: MediaContext): { hard: string[]; soft: string[] }; // Lower is better, compared element by element. Default [hard, soft]. score?(a: MediaAttempt): 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[], unit: U, ctx: MediaContext): MediaAttempt | null; // The re-ask's added words; default "Your last draft was refused for: …". retry?(last: MediaAttempt, 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): ApplyDraftResult; // A line for the log per unit kept; default the value as JSON. describe?(value: V, unit: U): string; // Who owns the unit's field, for the skip (default drafted.mjs `ownerOf`): // "empty" is drafted, anything else only with `force`. The cut's: a // timeline the converter made is nobody's. owner?(manifest: VideoManifest, unit: U, ctx: MediaContext): "empty" | "drafted" | "operator"; // What the job's progress counts (release 28 F3); default "entries". progressMetric?: "cards" | "entries"; // Several units in one ask (the local model's 8k prompt holds more than // one on-screen line). Without it, one ask per unit. batch?: MediaBatch; }; /** * Units asked together: `group` cuts the units to draft into asks (each list * one ask, in order); `split` gives each unit's own answer out of the * batch's, keyed by unit id (one with none is that attempt's hard failure), * which `parse` and `check` then judge as a single unit's. A re-ask carries * only the units the first ask did not settle cleanly (`retry`'s words). */ export type MediaBatch = { group(units: U[], ctx: MediaContext): U[][]; schema(units: U[], ctx: MediaContext): object; system(units: U[], ctx: MediaContext): string; user(units: U[], ctx: MediaContext): string; split(answer: unknown, units: U[], ctx: MediaContext): Record; retry?(failing: { id: string; last: MediaAttempt }[]): 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 = (a: MediaAttempt) => [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(attempts: MediaAttempt[], score: (a: MediaAttempt) => number[] = defaultScore): MediaAttempt[] { 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 { 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(); 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 = tmpPathFor(file); 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(h: TaskHandle, input: I): Promise> { 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 = (last: MediaAttempt) => `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`; const batchRefusedFor = (failing: { id: string; last: MediaAttempt }[]) => `\n\nYour last drafts were refused: ${failing.map((f) => `${f.id}: ${[...f.last.hard, ...f.last.soft].join("; ")}`).join(" | ")}. ` + "Write those again without those problems."; // At most two asks per unit: alone (the spec's schema, system and user), or // with the others of its batch (`spec.batch`); the second ask carries only the // units the first did not settle cleanly, and what each was refused for. async function askUnits( spec: MediaTaskSpec, h: TaskHandle, ctx: MediaContext, group: U[], ): Promise[]>> { const { deps } = h; const out = new Map[]>(group.map((u) => [u.id, []])); const judge = (raw: unknown, u: U): MediaAttempt => { try { const value = spec.parse(raw, u, ctx); return { value, ...spec.check(value, u, ctx) }; } catch (e) { return { value: null, hard: [(e as Error).message], soft: [] }; } }; const ask = (system: string, user: string, schema: object, label: string, slot: CallSlot) => structuredAnswer({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal, call: { phase: "draft", label, slot } }); // What code did with one unit's attempt (the model log): a clean value is // kept, a hard problem drops it, soft ones keep it flagged. const fate = (id: string, a: MediaAttempt, k: number): CallItem => a.hard.length ? { text: id, outcome: "dropped", why: `${a.hard.join("; ")}${k === 0 ? " (asked again)" : ""}` } : a.soft.length ? { text: id, outcome: k === 0 ? "dropped" : "kept", why: `flagged: ${a.soft.join("; ")}${k === 0 ? " (asked again)" : ""}` } : { text: id, outcome: "kept", why: "passes the checks" }; const b = spec.batch; // Computed once per unit (a batch: once for the whole), as narrate always did. const first = b ? { system: b.system(group, ctx), user: b.user(group, ctx) } : null; const single = new Map(b ? [] : group.map((u) => [u.id, { system: spec.system(u, ctx), user: spec.user(u, ctx) }])); let pending = group; for (let k = 0; k < 2 && pending.length; k++) { deps.signal?.throwIfAborted(); if (!b) { const u = pending[0]!; const list = out.get(u.id)!; const extra = list.length ? (spec.retry ?? refusedFor)(list.at(-1)!, u) : ""; let a: MediaAttempt; const slot = new CallSlot(); try { a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx), `${u.label ?? u.id}${k ? ` · attempt ${k + 1}` : ""}`, slot), u); } catch (e) { if (deps.signal?.aborted) throw e; list.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } list.push(a); const f = fate(u.id, a, k); slot.decide(f.outcome, f.why); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); if (!a.hard.length && !a.soft.length) pending = []; continue; } // A batch: the first ask is the whole group's; a re-ask names only the // units still refused or flagged. const failing = pending.map((u) => ({ id: u.id, last: out.get(u.id)!.at(-1) })).filter((f): f is { id: string; last: MediaAttempt } => !!f.last); const user = (k === 0 ? first!.user : b.user(pending, ctx)) + (failing.length ? (b.retry ?? batchRefusedFor)(failing) : ""); const system = k === 0 ? first!.system : b.system(pending, ctx); let answers: Record; const slot = new CallSlot(); try { answers = b.split(await ask(system, user, b.schema(pending, ctx), `${pending.length} unit${pending.length === 1 ? "" : "s"}${k ? ` · attempt ${k + 1}` : ""}`, slot), pending, ctx); } catch (e) { if (deps.signal?.aborted) throw e; for (const u of pending) out.get(u.id)!.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } const fates: CallItem[] = []; for (const u of pending) { const a: MediaAttempt = answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); fates.push(fate(u.label ?? u.id, a, k)); out.get(u.id)!.push(a); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); } const nKept = fates.filter((f) => f.outcome === "kept").length; slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} kept`, fates); pending = pending.filter((u) => { const last = out.get(u.id)!.at(-1)!; return last.hard.length > 0 || last.soft.length > 0; }); } return out; } /** * 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( spec: MediaTaskSpec, input: I, deps: TaskDeps, ): Promise { 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( spec: MediaTaskSpec, h: TaskHandle, input: I, ): Promise { 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> = {}; const kept: { unit: U; value: V; attempt: 1 | 2 }[] = []; h.log(`${spec.task} on i${h.n}, ${input.model} (${dir})`); // The units to draft: the ones asked for, with a field nobody owns (or // `force`); the rest are recorded as skipped. const eligible: U[] = []; 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 = spec.owner ? spec.owner(manifest, u, ctx) : 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; } eligible.push(u); } // Progress (release 28 F3): the units drafted of those to draft. const metric = spec.progressMetric ?? "entries"; let drafted = 0; h.progress({ metric, current: 0, total: eligible.length }); const groups = spec.batch ? spec.batch.group(eligible, ctx).filter((g) => g.length) : eligible.map((u) => [u]); for (const group of groups) { const attemptsOf = await askUnits(spec, h, ctx, group); for (const u of group) { const attempts = attemptsOf.get(u.id) ?? []; const ranked = rankAttempts(attempts, score); let chosen: MediaAttempt | 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 }; drafted++; 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("; ")}]` : ""}`); } h.progress({ metric, current: drafted, total: eligible.length }); } const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt | 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 };