Archilyzer · Source

archilyzer

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

commit faf41080eba24893b9dc3ff1e4afbd15d8e4be4e
parent 969ec546a1bb2841680d9764feb0fc0191cbd6c2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 22:32:26 -0400

common: the media scaffold asks in batches, reports progress, takes an owner; the build's validators for a task's checks

media.ts (additive): `spec.batch` asks several units in one call (`group`,
`split`), the re-ask carrying only the units refused or flagged; the job's
progress counts the units drafted (`progressMetric`: entries, narrate's
cards); `spec.owner` says who owns a unit's field for the skip (the cut's:
a converter-made order is nobody's) — the writer is still applyDraft.
deckChecks.ts loads umtool's report-to-video validators (validateTeaser,
lint's validatorErrors) natively from the checkout as TaskDeps.deckChecks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/lib/report/draft/tasks/deckChecks.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/media.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/media.ts | 186++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mcommon/lib/report/draft/tasks/narrate.ts | 1+
Mcommon/lib/report/draft/tasks/types.ts | 5+++++
5 files changed, 246 insertions(+), 49 deletions(-)

diff --git a/common/lib/report/draft/tasks/deckChecks.ts b/common/lib/report/draft/tasks/deckChecks.ts @@ -0,0 +1,45 @@ +// The build's own validators, for a media task's code checks (release 28). +// +// A drafted teaser must pass `validateTeaser` (the frame's fit per role), and +// a drafted cut must leave the manifest as valid as it found it (posts that +// ride on a clip, flips and threads that name clips). Those rules live in +// umtool's report-to-video (`deck.mjs`, `lint.mjs` `validatorErrors`: what a +// build runs before it renders) — plain `.mjs` that common does not depend on +// (it depends on common). So they are loaded at run time from the checkout, +// natively (the editor is never a standalone bundle: AGENTS.md, "The runtime +// container"), and handed to a task as `TaskDeps.deckChecks`. + +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +export type DeckChecks = { + // umtool/report-to-video/deck.mjs: a teaser entry's problems ([] = it builds). + validateTeaser(entry: unknown, where?: string): string[]; + // umtool/report-to-video/lint.mjs: every validator a build runs on the whole + // manifest, as sentences. + validatorErrors(manifest: unknown): string[]; +}; + +// The checkout's report-to-video directory. +export const deckDirOf = (repoRoot: string) => path.join(/* turbopackIgnore: true */ repoRoot, "umtool", "report-to-video"); + +const load = (file: string) => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ pathToFileURL(file).href); + +/** The validators, from the checkout at `repoRoot` (throws when it has no umtool). */ +export async function loadDeckChecks(repoRoot: string): Promise<DeckChecks> { + const dir = deckDirOf(repoRoot); + const [deck, lint] = await Promise.all([load(path.join(dir, "deck.mjs")), load(path.join(dir, "lint.mjs"))]); + if (typeof deck.validateTeaser !== "function" || typeof lint.validatorErrors !== "function") { + throw new Error(`${dir}: no validateTeaser / validatorErrors (an older checkout?)`); + } + return { + validateTeaser: (entry, where) => deck.validateTeaser(entry, where), + validatorErrors: (manifest) => { + try { + return lint.validatorErrors(manifest); + } catch (e) { + return [(e as Error).message]; + } + }, + }; +} diff --git a/common/lib/report/draft/tasks/media.test.ts b/common/lib/report/draft/tasks/media.test.ts @@ -199,3 +199,61 @@ test("narrate on the scaffold: a narration it writes carries drafted.narration; const it = (await readIteration("synth-basic", 1, p.paths))!; assert.equal(it.checks!.find((c) => c.name === "narration")!.ok, true); }); + +test("the scaffold in batches (release 28): one ask for several units, the re-ask only for the refused; progress per batch; an owner hook", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + m.timeline.find((e: { id: string }) => e.id === "c01").onscreen = { title: "x" }; + const p = await project(m); + // A fake of its own: the script above may have turns left. + const own = await startFakeOllama(); + p.deps.llm = { ollama: { baseUrl: own.url } }; + const progress: { metric: string; current: number; total?: number }[] = []; + p.deps.progress = (x) => progress.push(x); + const BATCHED: MediaTaskSpec<ToyUnit, { title: string }> = { + ...TOY, + task: "toy-batch", + // c01 counts as nobody's although it will have a value (the cut's hook). + owner: (manifest, u) => (u.id === "c01" ? "empty" : undefined) ?? (manifest.timeline.find((e) => e.id === u.id)?.onscreen ? "operator" : "empty"), + batch: { + group: (us) => [us.slice(0, 2), us.slice(2)], + schema: () => ({ type: "object", properties: { entries: { type: "array", items: { type: "object" } } }, required: ["entries"] }), + system: () => TOY.system(null as never, null as never), + user: (us) => us.map((u) => `${u.id}: ${u.quote}`).join("\n"), + split: (a) => Object.fromEntries(((a as { entries: { id: string; title: string }[] }).entries ?? []).map((e) => [e.id, e])), + }, + }; + const asked: string[] = []; + const reply = (entries: { id: string; title: string }[]) => (body: { messages: { content: string }[] }) => { + asked.push(body.messages.at(-1)!.content); + return jsonReply({ entries }); + }; + own.push( + // c01 + c02: c02 refused; c01 clean. + reply([{ id: "c01", title: "Not for sale" }, { id: "c02", title: "BAD" }]), + // the re-ask: c02 alone. + reply([{ id: "c02", title: "The old oven" }]), + // c03 alone in its batch, and no draft for it. + reply([]), + reply([{ id: "c03", title: "The mixer" }]), + ); + const out = await runMediaTask(BATCHED, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps); + await own.close(); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(own.remaining(), 0); + assert.equal(asked.length, 4); + assert.match(asked[1]!, /^c02: we never said/); + assert.match(asked[1]!, /Your last drafts were refused: c02: bad/); + assert.match(asked[3]!, /c03: no draft for c03 in the answer/); + const after = await p.manifestNow(); + const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); + // The hook let c01 be asked; the writer still keeps the operator's words. + assert.deepEqual([e("c01").onscreen, e("c02").onscreen, e("c03").onscreen], [{ title: "x" }, { title: "The old oven" }, { title: "The mixer" }]); + const file = JSON.parse(await readFile(path.join(p.dir, "toy-batch-draft.json"), "utf8")) as DraftFile; + assert.deepEqual(file.alternatives.map((a) => [a.target.entry, a.reason]), [["c01", "operator"]]); + assert.equal(e("c02").drafted.onscreen.attempt, 2); + assert.deepEqual(progress, [ + { metric: "entries", current: 0, total: 3 }, + { metric: "entries", current: 2, total: 3 }, + { metric: "entries", current: 3, total: 3 }, + ]); +}); diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -38,8 +38,9 @@ // // 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). +// 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"; @@ -164,6 +165,31 @@ export type MediaTaskSpec<U extends MediaUnit, V, I extends MediaTaskInput = Med 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; + // 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<I>): "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<U, I>; +}; + +/** + * 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<U extends MediaUnit, I extends MediaTaskInput = MediaTaskInput> = { + group(units: U[], ctx: MediaContext<I>): U[][]; + schema(units: U[], ctx: MediaContext<I>): object; + system(units: U[], ctx: MediaContext<I>): string; + user(units: U[], ctx: MediaContext<I>): string; + split(answer: unknown, units: U[], ctx: MediaContext<I>): Record<string, unknown>; + retry?(failing: { id: string; last: MediaAttempt<unknown> }[]): string; }; export const isSkip = (u: MediaUnit | MediaSkip): u is MediaSkip => typeof (u as MediaSkip).skipped === "string"; @@ -246,6 +272,82 @@ export async function loadMediaContext<I extends MediaTaskInput>(h: TaskHandle, const refusedFor = <V>(last: MediaAttempt<V>) => `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`; +const batchRefusedFor = <V>(failing: { id: string; last: MediaAttempt<V> }[]) => + `\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<U extends MediaUnit, V, I extends MediaTaskInput>( + spec: MediaTaskSpec<U, V, I>, + h: TaskHandle, + ctx: MediaContext<I>, + group: U[], +): Promise<Map<string, MediaAttempt<V>[]>> { + const { deps } = h; + const out = new Map<string, MediaAttempt<V>[]>(group.map((u) => [u.id, []])); + const judge = (raw: unknown, u: U): MediaAttempt<V> => { + 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) => + structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal }); + 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<V>; + try { + a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx)), u); + } catch (e) { + if (deps.signal?.aborted) throw e; + list.push({ value: null, hard: [(e as Error).message], soft: [] }); + continue; + } + list.push(a); + 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<V> } => !!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<string, unknown>; + try { + answers = b.split(await ask(system, user, b.schema(pending, ctx)), 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; + } + for (const u of pending) { + const a: MediaAttempt<V> = + answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); + out.get(u.id)!.push(a); + h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); + } + 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 @@ -286,67 +388,53 @@ async function mediaBody<U extends MediaUnit, V, I extends MediaTaskInput>( 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 = ownerOf(manifest, u.target); + 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; } - 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: [] }; + 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<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; } - } 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 }; + 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("; ")}]` : ""}`); } - 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("; ")}]` : ""}`); + h.progress({ metric, current: drafted, total: eligible.length }); } const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt<V> | null | undefined)?.hard?.length).length; diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts @@ -124,6 +124,7 @@ export const NARRATE_SPEC: MediaTaskSpec<NarrateUnit, string, NarrateInput> = { turnKind: "narration", noun: "card", verb: "narrated", + progressMetric: "cards", units(ctx) { const out: (NarrateUnit | MediaSkip)[] = []; const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null; diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -14,6 +14,7 @@ import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { readIteration } from "../../iterations"; import type { Report } from "../../schema"; import type { ResearchEditor } from "../research/tools"; +import type { DeckChecks } from "./deckChecks"; // The iterations store's paths (S4 takes them on every call). export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>; @@ -62,6 +63,10 @@ export type TaskDeps = { log?: (line: string) => void; // Progress, as the task counts it (the editor job's setProgress). progress?: (p: TaskProgress) => void; + // The build's validators (umtool's report-to-video, loaded from the + // checkout: ./deckChecks.ts) — a media task's checks that the cut it + // drafts still builds (release 28). + deckChecks?: () => Promise<DeckChecks>; signal?: AbortSignal; };