import { stat } from "node:fs/promises"; import path from "node:path"; import { articleDir } from "yt-dlp-transcript-common/lib/report/registry"; import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; import { articleHref, ARTICLES_KEY } from "@/lib/articles/href"; import { projectHref } from "@/lib/hrefs"; import { enqueueDraft, readPolicy } from "@/lib/articles/generation"; import { sitesPaths } from "@/lib/articles/sites"; import { REPORTS_ROOT } from "../paths.mjs"; import { invalidateProjects } from "../projects"; import { scaffoldReportVideo, SLUG_RE } from "../projects/scaffold.mjs"; import { exportMarkdown, localOnlyQuotes } from "./board.mjs"; import { isLocalOnly } from "./rules.mjs"; import { runHref } from "./runs-hrefs"; import { CaseError, recordHandoff } from "./cases.mjs"; import { boardGroups, caseView, mutateBoard } from "./boards"; import { boardGate } from "./case-private"; import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types"; import { CALLS_PER_RECORDING, MEASURED_SECONDS_PER_CALL, readingSize } from "yt-dlp-transcript-common/lib/report/draft/tasks/selection"; // --------------------------------------------------------------------------- // HAND-OFFS from a board (plans/umtool-redesign.md, R2), both PLAN THEN // CONFIRM: POST without `confirm` answers the plan and writes nothing; POST // with `confirm: true` (and anything the plan let the operator change) does it // and answers `{ href }`. // // "Draft an article from this board" is a `report-draft` SWEEP (the editor's // job, POST /api/ops/report-draft -- umtool writes nothing of the article // store) over the board's question and channels, SEEDED with the board as // cited markdown (through enqueueDraft, the one door): the editor keeps it as the iteration's seed.md and the // sweep's report starts from it (common/controller/reportDraft.ts `seed`, // added for this hand-off -- the editor had no way to take a board's cites). // A seeded sweep runs the API agent (the local pipeline writes its report from // scratch), so the model is the policy's API model, whatever the sweep route. // It spends money: the plan says on what, and under which cap. // // "Start a video from this board" scaffolds a report-video project under // REPORTS_ROOT (lib/projects/scaffold.mjs, its `timeline`): one clip per // pinned quote, in board order, its window the quote's cue span. It spends // nothing; it writes a project. // // "Run a sweep on this scope" (R3) is the same door without the seed: a // report-draft sweep over the case's scope (its query, channels, dates and // source), on the policy's sweep route -- the API agent and its extractor, or // the local pipeline; a route to Claude Code (a session's, not a job's) runs // the API agent, as a seeded sweep does -- planned and confirmed the same way, and answered with // the run's page (/research/runs/
/), which follows it live. // // RESEARCH RULES: a board holding a local-only quote (Candace's channels, // rules.mjs) never hands off to an article -- the article store publishes. // Its video project is local, and the plan says it must stay so. // --------------------------------------------------------------------------- const exists = (p: string) => stat(p).then(() => true, () => false); /** The board's channels (slugs): the scope's, else every quoted one. */ function channelsOf(doc: CaseDoc): string[] { const fromScope = (doc.scope.channels ?? []).map((k) => k.split(":").pop()!).filter(Boolean); const quoted = [...new Set(doc.quotes.map((q) => q.cite.channel))]; return fromScope.length ? [...new Set(fromScope)] : quoted; } // ── the article ── export type ArticleOver = { article?: string; model?: string; question?: string; dateFrom?: string; dateTo?: string }; const YMD = /^\d{4}-\d{2}-\d{2}$/; export async function planArticle( id: string, over: ArticleOver = {}, o: { seeded?: boolean } = {}, ): Promise<{ plan: ArticlePlan; seed: string }> { const seeded = o.seeded !== false; const view = await caseView(id); const doc = view.case; const refusals: string[] = []; const warnings: string[] = []; const article = (over.article ?? doc.id).trim(); if (!isReportId(article)) refusals.push(`"${article}" is not an article id (lowercase letters, digits and dashes)`); if (seeded && !doc.quotes.length) refusals.push("the board has no quotes: pin some first"); const local = localOnlyQuotes(doc).length; if (local && seeded) refusals.push(`${local} ${local === 1 ? "quote is" : "quotes are"} from a local-only channel: an article can be published, so this board never becomes one (export the markdown instead)`); const channels = channelsOf(doc); if (!channels.length) refusals.push(seeded ? "the board names no channel to sweep" : "the case's scope names no channel: set the scope's channels (search and pin first)"); const localChannels = channels.filter((c) => isLocalOnly(c)); if (!seeded && localChannels.length) refusals.push(`${localChannels.join(", ")} ${localChannels.length === 1 ? "is" : "are"} local-only: a sweep makes an article, which can be published`); const question = (over.question ?? doc.scope.query ?? doc.title).trim(); // The sweep's dates (D2): the run's own when the plan names them, else the scope's. const dateFrom = over.dateFrom ?? doc.scope.dateFrom; const dateTo = over.dateTo ?? doc.scope.dateTo; for (const [k, v] of [["from", dateFrom], ["to", dateTo]] as const) if (v && !YMD.test(v)) refusals.push(`the "${k}" date "${v}" is not YYYY-MM-DD`); if (dateFrom && dateTo && YMD.test(dateFrom) && YMD.test(dateTo) && dateFrom > dateTo) refusals.push(`the dates run backwards: ${dateFrom} is after ${dateTo}`); if (seeded) { const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`); const unverified = doc.quotes.filter((q) => !q.verify).length; if (unverified) warnings.push(`${unverified} ${unverified === 1 ? "quote was" : "quotes were"} never re-verified`); const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length; if (unchecked) warnings.push(`${unchecked} with the speaker not checked: the seed says so on each`); } const articleExists = isReportId(article) ? await exists(articleDir(sitesPaths(), article)) : false; if (articleExists) warnings.push(`the article "${article}" exists: the sweep adds an iteration to it`); let model: string | null = null; let extractor: string | null = null; let route: string | null = null; let capUsd: number | null = null; let policyError: string | undefined; try { const p = await readPolicy(); route = p.generation.routes.sweep; if (seeded) { model = over.model?.trim() || p.generation.models.api; if (route !== "api") warnings.push(`the policy routes sweeps to ${route === "code" ? "Claude Code" : "the local model"}; a seeded sweep runs the API agent on ${model}`); } else if (over.model?.trim()) { model = over.model.trim(); } else if (route === "code") { // Claude Code runs in a session, not as an editor job: the API agent // runs it here, as a seeded sweep does, and the plan says so. model = p.generation.models.api; warnings.push(`the policy routes sweeps to Claude Code, which runs in a session; this sweep runs the API agent on ${model}`); } else { model = route === "api" ? p.generation.models.api : p.generation.models.local; } if (model?.startsWith("claude-")) { capUsd = Math.min(p.generation.caps.sweep, p.generation.caps.max); extractor = p.generation.models.extractor; } } catch (e) { policyError = (e as Error).message; model = over.model?.trim() || null; } if (seeded && model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`); const seed = seeded ? exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }) : ""; // The case pipeline's privacy gate: quote ids and counts, never the name. const blocked = seeded ? await boardGate(doc, "this hand-off") : null; if (blocked) refusals.push(blocked.message); return { plan: { to: "article", article, articleExists, question, channels, ...(dateFrom ? { dateFrom } : {}), ...(dateTo ? { dateTo } : {}), ...(!seeded && model && !model.startsWith("claude-") ? { reading: readingOf(model) } : {}), source: doc.scope.source, model, extractor, route, capUsd, seeded, seed: { chars: seed.length, quotes: seeded ? doc.quotes.length : 0 }, spends: true, refusals, warnings, ...(policyError ? { policyError } : {}), }, seed, }; } export async function confirmArticle(id: string, over: ArticleOver): Promise<{ href: string; jobId: string; iteration: number }> { const { plan, seed } = await planArticle(id, over); if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409); if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502); // The one way umtool asks the editor for a draft (lib/articles/generation.ts). const answer = await enqueueDraft({ task: "sweep", article: plan.article, question: plan.question, channels: plan.channels, from: plan.dateFrom, to: plan.dateTo, source: plan.source, model: plan.model, seed, }); const href = articleHref({ site: ARTICLES_KEY, id: plan.article }); await mutateBoard(id, (doc) => recordHandoff(doc, { to: "article", href, what: `${plan.article} i${answer.iteration}, job ${answer.jobId}` }), ); return { href, jobId: answer.jobId, iteration: answer.iteration }; } // ── a sweep on the case's scope (R3) ── export const planScopeSweep = (id: string, over: ArticleOver = {}) => planArticle(id, over, { seeded: false }); /** What a local sweep reads (D2): the top N by rarity × hits plus the date spread, and about how long. */ function readingOf(model: string): NonNullable { const recordings = readingSize(); const spreadMax = Math.ceil(recordings / 2); const perCall = MEASURED_SECONDS_PER_CALL[model]; return { recordings, spreadMax, ...(perCall ? { minutes: Math.round((recordings * CALLS_PER_RECORDING * perCall) / 60) } : {}) }; } export async function confirmScopeSweep(id: string, over: ArticleOver): Promise<{ href: string; jobId: string; iteration: number }> { const { plan } = await planScopeSweep(id, over); if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409); if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502); const answer = await enqueueDraft({ task: "sweep", article: plan.article, question: plan.question, channels: plan.channels, from: plan.dateFrom, to: plan.dateTo, source: plan.source, model: plan.model, }); const href = runHref(plan.article, answer.iteration); await mutateBoard(id, (doc) => recordHandoff(doc, { to: "article", href: articleHref({ site: ARTICLES_KEY, id: plan.article }), what: `a sweep on the scope: ${plan.article} i${answer.iteration}, job ${answer.jobId}` }), ); return { href, jobId: answer.jobId, iteration: answer.iteration }; } // ── the video ── /** The viewer origin every quote's link shares, else "" (the project's `check` asks for it). */ function originOf(doc: CaseDoc): string { const origins = new Set(); for (const q of doc.quotes) { if (q.cite.kind !== "video" || !q.cite.url) continue; try { const u = new URL(q.cite.url); if (!u.searchParams.has("v")) return ""; origins.add(u.origin); } catch { return ""; } } return origins.size === 1 ? [...origins][0] : ""; } const r2 = (n: number) => Math.round(n * 100) / 100; export function clipsOf(doc: CaseDoc): { clips: Record[]; skipped: number } { const clips: Record[] = []; let skipped = 0; let n = 0; for (const g of boardGroups(doc)) { for (const q of g.quotes) { if (q.cite.kind !== "video" || !(q.cite.end > q.cite.t)) { skipped++; continue; } const c = q.cite; const date = /^\d{8}$/.test(c.date ?? "") ? `${c.date!.slice(0, 4)}-${c.date!.slice(4, 6)}-${c.date!.slice(6, 8)}` : undefined; clips.push({ type: "clip", id: `c${String(n++).padStart(2, "0")}`, // The editor's directory (a Rumble clip's URL slug); the archive's ids // beside it when they differ, so its cues resolve (report-to-video/cues.mjs). channel: c.channel, video: c.dirVideo ?? c.video, ...(c.dirVideo ? { siteVideo: c.video, siteChannel: c.channel } : {}), start: r2(c.t), end: r2(c.end), cite: Math.floor(c.t), quote: q.text, ...(date ? { date } : {}), ...(q.claim ? { note: q.claim } : {}), ...(c.trackId ? { track: c.trackId } : {}), }); } } return { clips, skipped }; } export async function planVideo(id: string, over: { slug?: string; title?: string } = {}): Promise { const view = await caseView(id); const doc = view.case; const refusals: string[] = []; const warnings: string[] = []; const slug = (over.slug ?? doc.id).trim(); if (!SLUG_RE.test(slug)) refusals.push(`"${slug}" will not route: lowercase letters, digits and dashes`); else if (await exists(path.join(REPORTS_ROOT, slug))) refusals.push(`a project folder "${slug}" already exists under the reports root: name another`); const { clips, skipped } = clipsOf(doc); if (!clips.length) refusals.push("the board has no video quotes to clip"); if (skipped) warnings.push(`${skipped} ${skipped === 1 ? "quote has" : "quotes have"} no window (a post, or no cue span) and ${skipped === 1 ? "is" : "are"} left out`); const local = localOnlyQuotes(doc).length; if (local) warnings.push(`${local} local-only ${local === 1 ? "quote" : "quotes"}: this project must never be published`); const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; if (drifted) warnings.push(`${drifted} drifted or missing at the last re-verify: their windows are the pinned seconds`); const blocked = await boardGate(doc, "this hand-off"); if (blocked) refusals.push(blocked.message); const siteOrigin = originOf(doc); if (!siteOrigin) warnings.push("no one viewer origin in the quotes' links: set provenance.siteOrigin before the build"); return { to: "video", slug, title: (over.title ?? doc.title).trim() || doc.title, siteOrigin, clips: clips.map((c) => ({ id: String(c.id), channel: String(c.channel), video: String(c.video), start: Number(c.start), end: Number(c.end), quote: String(c.quote) })), writes: `${slug}/ (video.manifest.json, README.md) under the reports root`, spends: false, refusals, warnings, }; } export async function confirmVideo(id: string, over: { slug?: string; title?: string }): Promise<{ href: string }> { const plan = await planVideo(id, over); if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409); const doc = (await caseView(id)).case; const { clips } = clipsOf(doc); try { await scaffoldReportVideo({ root: REPORTS_ROOT, slug: plan.slug, title: plan.title, siteOrigin: plan.siteOrigin || null, timeline: clips, timelineFrom: `“${doc.title}” (c:${doc.id})` }); } catch (e) { const msg = (e as Error).message; throw new CaseError(msg, /already exists/.test(msg) ? 409 : 400); } invalidateProjects(); const href = projectHref(plan.slug); await mutateBoard(id, (d) => recordHandoff(d, { to: "video", href, what: `${clips.length} clips` })); return { href }; }