Archilyzer · Source

archilyzer

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

commit 00218022a1e51deca31e8dbd93b6844821853a77
parent aaf385c5e35f85d5e5ff1335a8749696e27d85bc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 13:20:46 -0400

umtool: release 27 S8 — /articles/new, the Iterations tab, compare, the policy panel; /drafts redirects

- /articles/new: question, the editor's channels, dates, the sweep (agent on
  Claude, pipeline on the local model), model, the cap (the policy's default,
  editable down); Start is a report-draft through the editor, then the
  article's Iterations tab.
- An article's Iterations tab (the article store's): every iteration with its
  kind, model, parent, copy, status, cost per model, minutes, ops, checks and
  which is the article and the video; use this iteration (common's
  makeCurrent), new iteration (report or video, model, feedback), copy with
  model, narrate (the step's model), cancel and live progress from the
  editor's job (polled at 2.5 s), make the video (S7's chain as a umtool job:
  its steps, resume or from a step, cancel), compare. A research iteration
  gets its slot (ResearchSlot) for S11.
- /articles/<id>/compare?a=&b=: two iterations side by side.
- The policy panel (on /articles/new): presets, routes, models, caps, written
  through the editor's settings action; the key file's path and whether it
  exists, never the key.
- /articles lists the articles in the making; its link goes to /articles/new.
- /drafts redirects; the POC's lib, panel and route are gone.
- e2e: the editor stub answers settings, channels, report-draft (iterations
  written into the fixture's store), job reads and cancel; the fixture gains
  zeta (an article in the making with four iterations) and today's usage row.

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

Diffstat:
Aumtool/app/api/articles/chain/route.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/articles/channels/route.ts | 12++++++++++++
Aumtool/app/api/articles/generate/route.ts | 23+++++++++++++++++++++++
Aumtool/app/api/articles/iterations/route.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/articles/job/route.ts | 27+++++++++++++++++++++++++++
Aumtool/app/api/articles/policy/route.ts | 30++++++++++++++++++++++++++++++
Dumtool/app/api/drafts/route.ts | 75---------------------------------------------------------------------------
Aumtool/app/articles/[report]/compare/page.tsx | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/articles/new/page.tsx | 30++++++++++++++++++++++++++++++
Mumtool/app/articles/page.tsx | 36++++++++++++++++++++++++++++++++----
Mumtool/app/drafts/page.tsx | 19+++++--------------
Mumtool/components/articles/ArticlePage.tsx | 42+++++++++++++++++++++++++++++++++++++-----
Aumtool/components/articles/ChainPanel.tsx | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/IterationsTab.tsx | 465+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/IterationsView.tsx | 17+++++++++++++++++
Aumtool/components/articles/NewArticleForm.tsx | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/PolicyPanel.tsx | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/ResearchSlot.tsx | 18++++++++++++++++++
Dumtool/components/drafts/DraftsPanel.tsx | 408-------------------------------------------------------------------------------
Mumtool/e2e/fixtures/editor-stub.mjs | 256++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/e2e/fixtures/iterations-fixture.mjs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/lib/articles/compare.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/articles/generation.ts | 407+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dumtool/lib/drafts.ts | 428-------------------------------------------------------------------------------
Mumtool/playwright.config.ts | 9+++++++++
26 files changed, 2485 insertions(+), 935 deletions(-)

diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts @@ -0,0 +1,70 @@ +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { cancelJob, getJob, startJob } from "@/lib/jobs"; +import { ARTICLES_DIR } from "@/lib/paths"; +import { planChain } from "@/lib/report/chain.mjs"; +import { chainKind, chainViewOf, errorResponse, projectsRootOf, readArticleIterations, readPolicy } from "@/lib/articles/generation"; + +export const dynamic = "force-dynamic"; + +// MAKE THE VIDEO (release 27 S8): the pipeline chain over a done iteration +// (lib/report/chain.mjs, S7) as a umtool job (lib/jobs.ts: one process group +// per step, cancel, per-step timeouts). The chain records each step in the +// iteration's `steps`, so a start resumes at the first step not done, or at +// `from`. The projects root is the editor's policy's (generation.projectsRoot). +// +// GET ?article=<id>&n=<n> -> { chain } the steps, where it resumes, its job +// POST { article, n, from? } -> { ok, job } started +// POST { cancel: <jobId> } -> { cancelled } +function parse(article: unknown, n: unknown): { article: string; n: number } | string { + const a = String(article ?? ""); + const k = Number(n); + if (!isReportId(a)) return `"${a}" is not an article id`; + if (!Number.isInteger(k) || k < 1) return "n is an iteration number"; + return { article: a, n: k }; +} + +async function chainOf(article: string, n: number) { + const its = await readArticleIterations(article); + const it = its.iterations.find((r) => r.n === n); + if (!it) return null; + return chainViewOf(article, it); +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const p = parse(url.searchParams.get("article"), url.searchParams.get("n")); + if (typeof p === "string") return Response.json({ error: p }, { status: 400 }); + try { + const chain = await chainOf(p.article, p.n); + if (!chain) return Response.json({ error: `no iteration i${p.n}` }, { status: 404 }); + return Response.json({ chain }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown }; + if (body.cancel !== undefined) { + const id = String(body.cancel); + if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json({ cancelled: cancelJob(id) }); + } + const p = parse(body.article, body.n); + if (typeof p === "string") return Response.json({ error: p }, { status: 400 }); + try { + let projectsRoot: string | undefined; + try { + projectsRoot = projectsRootOf((await readPolicy()).generation); + } catch { + projectsRoot = undefined; // the editor unreachable: the chain reads settings.json itself + } + const from = body.from ? String(body.from) : null; + const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, ...(projectsRoot ? { projectsRoot } : {}) }); + if (plan.steps.length === 0) return Response.json({ error: "every step of the chain is done — pick a step to run from" }, { status: 400 }); + const job = startJob(chainKind(p.article, p.n), plan.steps); + return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n) }); + } catch (err) { + return Response.json({ error: (err as Error).message }, { status: 400 }); + } +} diff --git a/umtool/app/api/articles/channels/route.ts b/umtool/app/api/articles/channels/route.ts @@ -0,0 +1,12 @@ +import { errorResponse, listEditorChannels } from "@/lib/articles/generation"; + +export const dynamic = "force-dynamic"; + +// The editor's channels, for /articles/new's picker (GET /api/ops/channels). +export async function GET() { + try { + return Response.json({ channels: await listEditorChannels() }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/api/articles/generate/route.ts b/umtool/app/api/articles/generate/route.ts @@ -0,0 +1,23 @@ +import { enqueueDraft, errorResponse } from "@/lib/articles/generation"; + +export const dynamic = "force-dynamic"; + +// START A GENERATION (release 27 S8): the body is `pnpm ops report-draft`'s — +// { task, article, iteration?, model?, feedback?, question?, channels?, from?, +// to?, copyOf?, maxUsd?, cards?, force? } — forwarded to the editor, which +// creates the iteration and runs the job. Answers { ok, jobId, iteration }. +// +// a new article task sweep, question, channels (from, to) +// a new iteration task revise-report | revise-video, iteration, feedback +// copy with model the iteration's task, copyOf, model +// narration task narrate, iteration, model (a step) +export async function POST(request: Request) { + try { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "send the generation as an object" }, { status: 400 }); + const out = await enqueueDraft(body); + return Response.json({ ok: true, ...out }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/api/articles/iterations/route.ts b/umtool/app/api/articles/iterations/route.ts @@ -0,0 +1,45 @@ +import { makeCurrent } from "yt-dlp-transcript-common/lib/report/iterations"; +import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { errorResponse, readArticleIterations } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; + +export const dynamic = "force-dynamic"; + +// AN ARTICLE'S ITERATIONS (release 27 S8). +// +// GET ?article=<id> -> the list (lib/articles/generation.ts), polled by the +// Iterations tab while one is queued or running +// POST { article, n, action: "use" } +// -> USE THIS ITERATION: common's makeCurrent, the +// registry's one writer of an article's report.json from +// an iteration (locked, validated; the article's +// audience and attached video kept). The page never +// writes it. +export async function GET(request: Request) { + const article = new URL(request.url).searchParams.get("article") ?? ""; + if (!isReportId(article)) return Response.json({ error: `"${article}" is not an article id` }, { status: 400 }); + try { + return Response.json(await readArticleIterations(article), { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; action?: unknown }; + const article = String(body.article ?? ""); + const n = Number(body.n); + if (!isReportId(article)) return Response.json({ error: `"${article}" is not an article id` }, { status: 400 }); + if (!Number.isInteger(n) || n < 1) return Response.json({ error: "n is an iteration number" }, { status: 400 }); + if (body.action !== "use") return Response.json({ error: 'action is "use"' }, { status: 400 }); + try { + const { current } = await makeCurrent(article, n, sitesPaths()); + return Response.json({ ok: true, current }); + } catch (err) { + if (err instanceof ArticleRegistryError) { + return Response.json({ error: err.message, problems: err.problems ?? [] }, { status: 400 }); + } + return errorResponse(err); + } +} diff --git a/umtool/app/api/articles/job/route.ts b/umtool/app/api/articles/job/route.ts @@ -0,0 +1,27 @@ +import { cancelDraftJob, errorResponse, readDraftJob } from "@/lib/articles/generation"; + +export const dynamic = "force-dynamic"; + +// AN EDITOR JOB'S PROGRESS (release 27 S8): GET ?id=<jobId>&tail=N reads the +// editor's GET /api/ops/job/<id> (its status, its place in the queue, its +// log's last lines); POST { cancel: <jobId> } is `pnpm ops job cancel`. The +// page polls this no faster than every two seconds. +export async function GET(request: Request) { + const url = new URL(request.url); + const id = url.searchParams.get("id") ?? ""; + try { + return Response.json({ job: await readDraftJob(id, Number(url.searchParams.get("tail") ?? 12) || 12) }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { cancel?: unknown }; + try { + await cancelDraftJob(String(body.cancel ?? "")); + return Response.json({ ok: true }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/api/articles/policy/route.ts b/umtool/app/api/articles/policy/route.ts @@ -0,0 +1,30 @@ +import { errorResponse, readPolicy, readToday, writePolicy } from "@/lib/articles/generation"; + +export const dynamic = "force-dynamic"; + +// THE GENERATION POLICY (release 27 S8): settings.generation, read from and +// written through the editor's settings action (POST /api/ops/settings) — +// routes per task, the models, the caps. Never the API key: the key FILE's +// path and whether a file is there. +// +// GET -> { policy, today } +// POST { routes?, models?, caps?, cacheTtl? } -> { policy } (a preset is its routes) +export async function GET() { + try { + const policy = await readPolicy(); + const today = await readToday(policy.generation.caps.daily); + return Response.json({ policy, today }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + try { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "send the policy's changes as an object" }, { status: 400 }); + return Response.json({ ok: true, policy: await writePolicy(body) }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/api/drafts/route.ts b/umtool/app/api/drafts/route.ts @@ -1,75 +0,0 @@ -import { - apiKeyReady, cancelStep, compareHtml, copyRun, createRun, createVersion, listChannels, listRuns, PRESETS, readPolicy, runFile, startStep, STEPS, writePolicy, - type GenPolicy, type Step, -} from "@/lib/drafts"; - -export const dynamic = "force-dynamic"; - -// Report drafts with no Claude Code (lib/drafts.ts). GET: the runs, or one -// run's file (?run=&file=). POST {action:"create", …} makes a run and starts its -// sweep; POST {action:"step", name, step, model?} (re)starts a step on that model; {action:"copy", name, model} -// copies a run onto another model (compare: GET ?compare=a,b). -export async function GET(request: Request) { - const url = new URL(request.url); - const run = url.searchParams.get("run"); - const file = url.searchParams.get("file"); - if (run && file) { - const f = runFile(run, file); - return f ? new Response(f.body, { headers: { "content-type": f.type } }) : new Response("not found", { status: 404 }); - } - const cmp = url.searchParams.get("compare"); - if (cmp) { - const [a, b] = cmp.split(","); - return new Response(compareHtml(a, b), { headers: { "content-type": "text/html; charset=utf-8" } }); - } - if (url.searchParams.get("channels")) return Response.json({ channels: listChannels() }); - return Response.json({ runs: listRuns(), keyReady: apiKeyReady(), policy: readPolicy(), presets: PRESETS }, { headers: { "cache-control": "no-store" } }); -} - -export async function POST(request: Request) { - try { - const b = await request.json(); - if (b.action === "create") { - const m = createRun({ - name: String(b.name ?? ""), - question: String(b.question ?? ""), - channels: String(b.channels ?? "").replace(/\s+/g, ""), - model: String(b.model ?? ""), - id: b.id ? String(b.id) : undefined, - terms: b.terms ? String(b.terms) : undefined, - maxUsd: b.maxUsd ? Number(b.maxUsd) : undefined, - }); - startStep(m.name, "sweep"); - return Response.json({ ok: true, name: m.name }); - } - if (b.action === "version") { - const m = createVersion(String(b.parent ?? ""), { - what: b.what === "video" ? "video" : "report", - model: String(b.model ?? ""), - feedback: String(b.feedback ?? ""), - maxUsd: b.maxUsd ? Number(b.maxUsd) : undefined, - }); - startStep(m.name, "sweep"); - return Response.json({ ok: true, name: m.name }); - } - if (b.action === "copy") { - const m = copyRun(String(b.name ?? ""), String(b.model ?? "")); - startStep(m.name, "sweep"); - return Response.json({ ok: true, name: m.name }); - } - if (b.action === "cancel" && (STEPS as readonly string[]).includes(b.step)) { - cancelStep(String(b.name), b.step as Step); - return Response.json({ ok: true }); - } - if (b.action === "policy") { - return Response.json({ ok: true, policy: writePolicy(b.policy as GenPolicy) }); - } - if (b.action === "step" && (STEPS as readonly string[]).includes(b.step)) { - startStep(String(b.name), b.step as Step, b.model ? String(b.model) : undefined); - return Response.json({ ok: true }); - } - return Response.json({ error: "unknown action" }, { status: 400 }); - } catch (e) { - return Response.json({ error: (e as Error).message }, { status: 400 }); - } -} diff --git a/umtool/app/articles/[report]/compare/page.tsx b/umtool/app/articles/[report]/compare/page.tsx @@ -0,0 +1,184 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import BrowseHeader from "@/components/BrowseHeader"; +import { badgeVariants } from "@/components/ui/badge"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { readCompareSide, type CompareSide } from "@/lib/articles/compare"; + +export const dynamic = "force-dynamic"; + +// TWO ITERATIONS OF AN ARTICLE SIDE BY SIDE (release 27 S8): +// /articles/<id>/compare?a=<n>&b=<n>. Each side's report — sections, and the +// findings in them, a finding the other side does not have marked — the ops +// its revision applied and refused, its failed checks; and, when both have a +// project, the two cuts. Server-rendered, zero client JS. + +const num = (v: string | undefined) => { + const n = Number(v); + return Number.isInteger(n) && n > 0 ? n : null; +}; + +function Side({ side, other, both }: { side: CompareSide; other: CompareSide; both: boolean }) { + const otherFindings = new Set(other.sections.flatMap((s) => s.findings.map((f) => f.text))); + const otherTitles = new Set(other.sections.map((s) => s.title)); + const otherCut = new Set((other.cut?.entries ?? []).map((e) => `${e.type}:${e.id}:${e.narration ?? e.quote ?? ""}`)); + return ( + <section aria-label={side.label} data-side={side.n} className="min-w-0 space-y-3"> + <header className="space-y-1 border-b border-[var(--color-line)] pb-2"> + <div className="flex flex-wrap items-baseline gap-2"> + <h2 className="font-mono text-[16px]">{side.label}</h2> + <span className="text-[12px] text-[var(--color-dim)]">{side.kind}</span> + <span className="font-mono text-[12px]">{side.model}</span> + <span className={badgeVariants({ variant: side.status === "done" ? "on" : side.status === "failed" ? "blocking" : "open", size: "sm" })}>{side.status}</span> + <span className="num ml-auto text-[12px] text-[var(--color-meter)]">${side.usd.toFixed(2)}</span> + </div> + <p className="text-[12px] text-[var(--color-dim)]"> + {side.parent !== null ? `of i${side.parent}` : "first sweep"} + {side.copyOf !== null ? ` · copy of i${side.copyOf}` : ""} + {side.reportFrom !== null && side.reportFrom !== side.n ? ` · report of i${side.reportFrom}` : ""} + {side.minutes !== null ? ` · ${side.minutes.toFixed(1)} min` : ""} + </p> + {(side.feedback ?? side.question) && <p className="text-[13px]">{side.feedback ? `“${side.feedback}”` : side.question}</p>} + </header> + + <div className="text-[12px]" data-ops-applied={side.applied.length} data-ops-refused={side.refused.length}> + <div className="micro"> + ops: {side.applied.length} applied · {side.refused.length} refused + </div> + {side.applied.length + side.refused.length > 0 && ( + <ul className="mt-1 space-y-0.5 font-mono text-[11px]"> + {side.applied.map((o) => ( + <li key={`a${o.index}`} data-op="applied"> + <span className="text-[var(--color-good)]">✓</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span> + </li> + ))} + {side.refused.map((o) => ( + <li key={`r${o.index}`} data-op="refused"> + <span className="text-[var(--color-bad)]">✗</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span> + {o.why && <div className="pl-4 font-sans text-[var(--color-bad)]">{o.why}</div>} + </li> + ))} + </ul> + )} + </div> + + {side.failedChecks.length > 0 && ( + <div className="text-[12px]" data-failed-checks={side.failedChecks.length}> + <div className="micro">failed checks</div> + <ul className="mt-1 list-disc pl-5 text-[var(--color-dirty)]"> + {side.failedChecks.map((c, i) => ( + <li key={i}> + {c.name} + {c.detail ? `: ${c.detail}` : ""} + </li> + ))} + </ul> + </div> + )} + + {side.title ? ( + <article className="space-y-3"> + <h3 className="text-[15px] font-semibold">{side.title}</h3> + {side.summary && <p className="text-[13px] text-[var(--color-dim)]">{side.summary}</p>} + {side.sections.map((s, i) => ( + <div key={i} data-section={s.title} data-only={otherTitles.has(s.title) ? undefined : "here"}> + <h4 className="text-[13px] font-semibold"> + {s.title} + {!otherTitles.has(s.title) && <span className={`ml-2 ${badgeVariants({ variant: "open", size: "sm" })}`}>only here</span>} + </h4> + <ul className="mt-1 space-y-1"> + {s.findings.map((f, j) => { + const changed = !otherFindings.has(f.text); + return ( + <li + key={j} + data-finding + data-changed={changed ? "yes" : undefined} + className={`border-l-2 pl-2 text-[13px] ${changed ? "border-[var(--color-sel)]" : "border-transparent text-[var(--color-dim)]"}`} + > + {f.text} + {f.cites > 0 && <span className="num ml-1 text-[11px] text-[var(--color-dim)]">[{f.cites}]</span>} + </li> + ); + })} + </ul> + </div> + ))} + </article> + ) : ( + <p className="text-[12px] text-[var(--color-dim)]">no report</p> + )} + + {both && side.cut && ( + <div data-cut={side.cut.entries.length} className="text-[12px]"> + <div className="micro">cut{side.cut.title ? `: ${side.cut.title}` : ""}</div> + <ol className="mt-1 space-y-1"> + {side.cut.entries.map((e, i) => { + const changed = !otherCut.has(`${e.type}:${e.id}:${e.narration ?? e.quote ?? ""}`); + return ( + <li key={i} data-cut-entry={e.id} data-changed={changed ? "yes" : undefined} className={`border-l-2 pl-2 ${changed ? "border-[var(--color-sel)]" : "border-transparent"}`}> + {e.type === "card" ? ( + <> + <span className="font-semibold">▌ {e.heading}</span> + {e.narration && <div className="text-[var(--color-dim)]">{e.narration}</div>} + </> + ) : ( + <> + <span className="font-mono text-[11px] text-[var(--color-dim)]"> + {e.id} {e.span} + </span>{" "} + {e.quote && `“${e.quote}”`} + </> + )} + </li> + ); + })} + </ol> + </div> + )} + </section> + ); +} + +export default async function ComparePage({ + params, + searchParams, +}: { + params: Promise<{ report: string }>; + searchParams: Promise<{ a?: string; b?: string }>; +}) { + const { report } = await params; + const sp = await searchParams; + if (!isReportId(report)) notFound(); + const a = num(sp.a); + const b = num(sp.b); + const [left, right] = a && b ? await Promise.all([readCompareSide(report, a), readCompareSide(report, b)]) : [null, null]; + const header = <BrowseHeader active="articles" crumbs={[{ href: "/articles", label: "articles" }, { href: `/articles/${report}?tab=iterations`, label: report }, { label: "compare" }]} />; + if (!left || !right) { + return ( + <div className="flex h-full flex-col"> + {header} + <main className="deck-main flex-1 p-4"> + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + {!a || !b ? "name two iterations: ?a=<n>&b=<n>" : `no iteration ${!left ? `i${a}` : `i${b}`}`} —{" "} + <Link href={`/articles/${report}?tab=iterations`} className="text-[var(--color-sel)] hover:underline"> + the iterations + </Link> + </p> + </main> + </div> + ); + } + const both = !!left.cut && !!right.cut; + return ( + <div className="flex h-full flex-col"> + {header} + <main className="deck-main flex-1 p-4"> + <div className="grid gap-6 md:grid-cols-2"> + <Side side={left} other={right} both={both} /> + <Side side={right} other={left} both={both} /> + </div> + </main> + </div> + ); +} diff --git a/umtool/app/articles/new/page.tsx b/umtool/app/articles/new/page.tsx @@ -0,0 +1,30 @@ +import BrowseHeader from "@/components/BrowseHeader"; +import NewArticleForm from "@/components/articles/NewArticleForm"; +import { listArticleDirs, listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; +import { readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; + +export const dynamic = "force-dynamic"; + +// A NEW ARTICLE (release 27 S8): its first iteration, a sweep the editor runs +// (`report-draft`), and the generation policy it starts from. The article is +// in the making — on /articles as generating — until an iteration is used. +export default async function NewArticlePage() { + let policy: PolicyView | null = null; + try { + policy = await readPolicy(); + } catch { + policy = null; + } + const today = policy ? await readToday(policy.generation.caps.daily).catch(() => null) : null; + const paths = sitesPaths(); + const taken = [...(await listArticleDirs(paths)), ...(await listPendingArticles(paths))]; + return ( + <div className="flex h-full flex-col"> + <BrowseHeader active="articles" crumbs={[{ label: "articles", href: "/articles" }, { label: "new" }]} /> + <main className="deck-main flex-1 p-4"> + <NewArticleForm initialPolicy={policy} today={today} taken={taken} /> + </main> + </div> + ); +} diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx @@ -3,19 +3,21 @@ import BrowseHeader from "@/components/BrowseHeader"; import ArticleTable from "@/components/articles/ArticleTable"; import { badgeVariants } from "@/components/ui/badge"; import { readStoreRow, type ArticleRow } from "@/lib/articles/sites"; +import { readPendingArticles } from "@/lib/articles/generation"; export const dynamic = "force-dynamic"; // The homepage's articles (transcripts/reports/, release 26): published in // reports/index.json's order, then drafts, each with its audience, notes, // video project and source. Zero client JS: the filters are links. A site's -// own pages are on /sites. +// own pages are on /sites. Above them, the articles in the making (release +// 27: iterations, no report.json yet), each with its newest iteration. type Search = { status?: string; notes?: string; audience?: string }; export default async function ArticlesPage({ searchParams }: { searchParams: Promise<Search> }) { const sp = await searchParams; - const store = await readStoreRow(); + const [store, pending] = await Promise.all([readStoreRow(), readPendingArticles()]); const keep = (a: ArticleRow) => (!sp.status || a.status === sp.status) && (!sp.audience || a.audience === sp.audience) && @@ -49,13 +51,39 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro <span className="micro ml-3">notes</span> <Chip href={qs({ notes: "" })} on={sp.notes !== "open"} label="all" /> <Chip href={qs({ notes: "open" })} on={sp.notes === "open"} label={`open ${count((a) => a.openNotes > 0)}`} /> - <Link href="/drafts" className="ml-auto text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> - draft a report + <Link href="/articles/new" className="ml-auto text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> + new article </Link> <Link href="/sites" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> site pages </Link> </div> + {pending.length > 0 && ( + <section aria-label="in the making" className="mb-4"> + <div className="micro mb-1">in the making</div> + <ul className="flex flex-col gap-1 text-[12px]"> + {pending.map((p) => ( + <li key={p.id} data-pending-article={p.id} data-status={p.newest?.status ?? "none"} className="flex flex-wrap items-baseline gap-2"> + <Link href={`/articles/${p.id}?tab=iterations`} className="font-mono text-[var(--color-text)] hover:text-[var(--color-sel)]"> + {p.id} + </Link> + {p.newest && ( + <> + <span className={badgeVariants({ variant: p.newest.status === "failed" ? "blocking" : p.newest.status === "done" ? "on" : "open", size: "sm" })}> + {p.newest.label} {p.newest.status === "queued" || p.newest.status === "running" ? "generating" : p.newest.status} + </span> + <span className="font-mono text-[var(--color-dim)]">{p.newest.model}</span> + {p.newest.question && <span className="text-[var(--color-dim)]">{p.newest.question}</span>} + </> + )} + <span className="text-[var(--color-dim)]"> + {p.count} iteration{p.count === 1 ? "" : "s"} + </span> + </li> + ))} + </ul> + </section> + )} {store.indexError && ( <p role="alert" className="mb-3 text-[12px] text-[var(--color-bad)]"> {store.indexError} diff --git a/umtool/app/drafts/page.tsx b/umtool/app/drafts/page.tsx @@ -1,17 +1,8 @@ -import BrowseHeader from "@/components/BrowseHeader"; -import DraftsPanel from "@/components/drafts/DraftsPanel"; +import { redirect } from "next/navigation"; -export const dynamic = "force-dynamic"; - -// Report drafts with no Claude Code: a local model or Claude on an API key -// (lib/drafts.ts; the scripts are ~/reports/local-reports, its RUNBOOK.html). +// The proof of concept's page (2026-10-12) is the application's now: a new +// article on /articles/new, its iterations on the article's Iterations tab +// (release 27 S8). export default function DraftsPage() { - return ( - <div className="flex h-full flex-col"> - <BrowseHeader active="articles" crumbs={[{ label: "articles", href: "/articles" }, { label: "draft a report" }]} /> - <main className="deck-main flex-1 p-4"> - <DraftsPanel /> - </main> - </div> - ); + redirect("/articles/new"); } diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -1,3 +1,4 @@ +import { stat } from "node:fs/promises"; import path from "node:path"; import Link from "next/link"; import { notFound } from "next/navigation"; @@ -6,6 +7,7 @@ import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides import BrowseHeader, { type Crumb } from "@/components/BrowseHeader"; import ArticleReader from "@/components/articles/ArticleReader"; import WorkspacePanel from "@/components/articles/WorkspacePanel"; +import IterationsView from "@/components/articles/IterationsView"; import { badgeVariants } from "@/components/ui/badge"; import { articleView } from "@/lib/articles/article"; import { articleHref } from "@/lib/articles/href"; @@ -13,7 +15,7 @@ import { articleWorkspaceListing, openWorkspaceFile } from "@/lib/articles/files import { linkedProjects } from "@/lib/articles/links.mjs"; import { readArticleNotes, readReportFile, reportDirFor } from "@/lib/articles/sites"; import { sourceFor } from "@/lib/articles/sources.mjs"; -import { corpusNotesFile } from "@/lib/paths"; +import { ARTICLES_KEY, corpusNotesFile } from "@/lib/paths"; import type { NotesRead } from "@/lib/annotations/types"; // ONE ARTICLE's page, wherever it lives: a site's report @@ -28,6 +30,9 @@ import type { NotesRead } from "@/lib/annotations/types"; // ?status=open|resolved|all the notes filter it opens with // ?note=<id> the note it opens on (the decisions inbox links here) // ?ws=&rel= a workspace file open on the source tab +// ?tab=iterations the article store's only (release 27 S8): its +// iterations (IterationsView). An article in the +// making — iterations, no report.json — opens here. export type ArticleSearch = { tab?: string; status?: string; note?: string; ws?: string; rel?: string }; @@ -50,14 +55,18 @@ export default async function ArticlePage({ published: boolean; }) { const read = await readReportFile(site, reportId); - if (!read.report && read.problems[0]?.message === "no report.json") notFound(); + const store = site === ARTICLES_KEY; + const hasIterations = + store && (await stat(/* turbopackIgnore: true */ path.join(reportDirFor(site, reportId), "iterations")).then((s) => s.isDirectory(), () => false)); + const missing = !read.report && read.problems[0]?.message === "no report.json"; + if (missing && !hasIterations) notFound(); const [notes, source] = await Promise.all([readArticleNotes(site, reportId), sourceFor(site, reportId)]); const links = await linkedProjects(site, reportId, { workspace: source?.workspace ?? null }); const gitDir = path.join(/* turbopackIgnore: true */ reportDirFor(site, reportId), REPORT_HISTORY_GIT_DIRNAME); const head = await readRevisionHead(gitDir).catch(() => null); const r = read.report; - const tab = sp.tab === "source" ? "source" : "article"; + const tab = missing || (store && sp.tab === "iterations") ? "iterations" : sp.tab === "source" ? "source" : "article"; const base = articleHref({ site, id: reportId }); const media = (file: string) => `/api/sites/media?site=${encodeURIComponent(site)}&report=${encodeURIComponent(reportId)}&file=${encodeURIComponent(file)}`; @@ -67,8 +76,8 @@ export default async function ArticlePage({ <Link href={home.href} className="hover:text-[var(--color-text)]"> {home.label} </Link> - <span data-status={published ? "published" : "draft"} className={badgeVariants({ variant: published ? "on" : "neutral", size: "sm" })}> - {published ? "published" : "draft"} + <span data-status={missing ? "pending" : published ? "published" : "draft"} className={badgeVariants({ variant: published ? "on" : missing ? "open" : "neutral", size: "sm" })}> + {missing ? "in the making" : published ? "published" : "draft"} </span> {r?.published && <span>published {r.published}</span>} {r?.updated && <span>updated {r.updated}</span>} @@ -93,6 +102,15 @@ export default async function ArticlePage({ <Link href={`${base}/evidence`} className="hover:text-[var(--color-text)]"> evidence </Link> + {store && ( + <Link + href={`${base}?tab=iterations`} + aria-current={tab === "iterations" ? "page" : undefined} + className={tab === "iterations" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"} + > + iterations + </Link> + )} </nav> {source && ( <div className="w-full font-mono text-[11px]" title={source.how}> @@ -111,6 +129,20 @@ export default async function ArticlePage({ /> ); + if (tab === "iterations") { + return ( + <div className="flex h-full flex-col"> + {header} + <main className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-5xl space-y-4"> + {meta} + <IterationsView article={reportId} /> + </div> + </main> + </div> + ); + } + if (!r) { return ( <div className="flex h-full flex-col"> diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx @@ -0,0 +1,137 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { badgeVariants } from "@/components/ui/badge"; +import type { ChainView } from "@/lib/articles/generation"; + +// MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten +// steps (lib/report/chain.mjs) as a umtool job — what each step last did, where +// a start resumes, the running step's log, cancel. A step the chain records +// done is skipped by a resume; "from" re-runs from a named step. + +const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neutral"> = { + done: "on", + failed: "blocking", + running: "open", + cancelled: "info", +}; + +export default function ChainPanel({ article, n, label }: { article: string; n: number; label: string }) { + const [chain, setChain] = useState<ChainView | null>(null); + const [from, setFrom] = useState<string>(""); + const [error, setError] = useState(""); + const [sending, setSending] = useState(false); + + const load = useCallback(async () => { + const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }); + const b = await r.json(); + if (!r.ok) { + setError(b.error ?? `HTTP ${r.status}`); + return null; + } + setChain(b.chain); + return b.chain as ChainView; + }, [article, n]); + + const running = chain?.job?.state === "running"; + useEffect(() => { + void load(); + }, [load]); + useEffect(() => { + if (!running) return; + const t = setInterval(() => void load(), 2500); + return () => clearInterval(t); + }, [running, load]); + + async function start() { + setError(""); + setSending(true); + try { + const r = await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ article, n, ...(from ? { from } : {}) }) }); + const b = await r.json(); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + if (b.chain) setChain(b.chain); + else await load(); + } catch (e) { + setError((e as Error).message); + } finally { + setSending(false); + } + } + + async function cancel() { + if (!chain?.job) return; + await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ cancel: chain.job.id }) }); + await load(); + } + + const startAt = from || chain?.resumeAt || ""; + return ( + <section aria-label={`${label} video chain`} data-chain={label} className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]"> + {chain && ( + <ol className="grid gap-x-4 gap-y-0.5 sm:grid-cols-2"> + {chain.steps.map((s, i) => ( + <li key={s.name} data-chain-step={s.name} data-step-status={s.status} className="flex items-center gap-2"> + <span className="num w-5 text-right text-[var(--color-dim)]">{i + 1}</span> + <span className={s.name === startAt && !running ? "text-[var(--color-sel)]" : ""}>{s.label}</span> + {s.status !== "pending" && ( + <span className={badgeVariants({ variant: STATUS_VARIANT[s.status] ?? "neutral", size: "sm" })}>{s.status}</span> + )} + </li> + ))} + </ol> + )} + <div className="mt-2 flex flex-wrap items-center gap-2"> + {running ? ( + <> + <span role="status" className="text-[var(--color-dirty)]"> + step {(chain?.job?.stepIndex ?? 0) + 1}/{chain?.job?.of}: {chain?.job?.label} + </span> + <Button size="sm" variant="destructive" onClick={cancel}> + Cancel the chain + </Button> + </> + ) : ( + <> + <label className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">from</span> + <select + aria-label={`${label} chain from step`} + className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5" + value={from} + onChange={(e) => setFrom(e.target.value)} + > + <option value="">{chain?.resumeAt ? `resume (${chain.resumeAt})` : "every step done"}</option> + {chain?.steps.map((s) => ( + <option key={s.name} value={s.name}> + {s.name} + </option> + ))} + </select> + </label> + <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={start}> + Run the chain + </Button> + </> + )} + {chain?.job && !running && ( + <span data-chain-job={chain.job.state} className={chain.job.state === "failed" ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}> + last run {chain.job.state} + {chain.job.error ? `: ${chain.job.error}` : ""} + </span> + )} + </div> + {chain?.job && chain.job.log.length > 0 && ( + <pre aria-label={`${label} chain log`} className="mt-2 max-h-48 overflow-auto rounded bg-[var(--color-panel)] p-2 font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]"> + {chain.job.log.join("\n")} + </pre> + )} + {error && ( + <p role="alert" className="mt-1 text-[var(--color-bad)]"> + {error} + </p> + )} + </section> + ); +} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -0,0 +1,465 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { badgeVariants } from "@/components/ui/badge"; +import ChainPanel from "@/components/articles/ChainPanel"; +import ResearchSlot from "@/components/articles/ResearchSlot"; +import { usd, type Today } from "@/components/articles/PolicyPanel"; +import type { ArticleIterations, DraftJobView, IterationRow, PolicyView } from "@/lib/articles/generation"; + +// AN ARTICLE'S ITERATIONS (release 27 S8): every generation of its report or +// its video, newest first — what made it (kind, model, parent, copy), how it +// went (status, cost per model, minutes, ops applied and refused, checks), and +// which is the article and which its video. Each action asks the editor (a +// `report-draft` job) or the registry (use this iteration) through umtool's +// routes; nothing here writes a file. While anything is queued or running the +// list is re-read every 3 s, and a running job's log every 2.5 s. + +const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; + +const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neutral"> = { + done: "on", + failed: "blocking", + running: "open", + queued: "open", + cancelled: "info", +}; + +// The report-draft task that made an iteration of this kind (a copy re-runs it). +const TASK_OF: Record<string, string | null> = { sweep: "sweep", "revise-report": "revise-report", "revise-video": "revise-video", research: null }; + +const fmtTokens = (n: number) => (n >= 10_000 ? `${Math.round(n / 1000)}k` : n.toLocaleString()); + +type Ctx = { + article: string; + policy: PolicyView | null; + allModels: string[]; + /** Start a report-draft job (the editor makes the iteration). */ + post: (body: Record<string, unknown>) => Promise<boolean>; + /** Make an iteration the article's (the registry's makeCurrent). */ + use: (n: number) => Promise<boolean>; + refresh: () => void; +}; + +function ModelSelect({ value, onChange, label, models }: { value: string; onChange: (v: string) => void; label: string; models: string[] }) { + return ( + <select aria-label={label} className={`${field} font-mono`} value={value} onChange={(e) => onChange(e.target.value)}> + {[...new Set([value, ...models].filter(Boolean))].map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + ); +} + +/** The editor job behind a queued or running iteration (or step): its place, its log, cancel. */ +function JobProgress({ jobId, label, onEnd }: { jobId: string; label: string; onEnd: () => void }) { + const [job, setJob] = useState<DraftJobView | null>(null); + const [error, setError] = useState(""); + useEffect(() => { + let alive = true; + let ended = false; + const tick = async () => { + try { + const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=12`, { cache: "no-store" }); + const b = await r.json(); + if (!alive) return; + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setJob(b.job); + setError(""); + if (!ended && ["done", "failed", "cancelled"].includes(b.job.status)) { + ended = true; + onEnd(); + } + } catch (e) { + if (alive) setError((e as Error).message); + } + }; + void tick(); + const t = setInterval(tick, 2500); + return () => { + alive = false; + clearInterval(t); + }; + }, [jobId, onEnd]); + const queued = job?.queue && (job.queue.position ?? 0) > 0; + return ( + <div className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2" data-job={jobId} data-job-status={job?.status ?? "unknown"}> + <div className="flex flex-wrap items-center gap-2 text-[11px]"> + <span className="font-mono text-[var(--color-dim)]">{jobId}</span> + <span role="status" className="text-[var(--color-dirty)]"> + {job ? (queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status) : "asking the editor…"} + </span> + <Button + size="sm" + variant="destructive" + className="ml-auto" + aria-label={`Cancel ${label}`} + onClick={async () => { + const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) }); + const b = await r.json().catch(() => ({})); + if (!r.ok) setError(b.error ?? `HTTP ${r.status}`); + onEnd(); + }} + > + Cancel + </Button> + </div> + {job && job.tail.length > 0 && ( + <pre role="log" aria-label={`${label} progress`} className="mt-1 max-h-40 overflow-auto font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]"> + {job.tail.join("\n")} + </pre> + )} + {error && <p className="mt-1 text-[11px] text-[var(--color-bad)]">{error}</p>} + </div> + ); +} + +function NewIterationForm({ it, ctx, onDone }: { it: IterationRow; ctx: Ctx; onDone: () => void }) { + const [target, setTarget] = useState<"report" | "video">("report"); + const g = ctx.policy?.generation; + const route = g?.routes[target === "report" ? "revise-report" : "revise-video"]; + const [model, setModel] = useState(route === "local" ? (g?.models.local ?? "") : (g?.models.api ?? "")); + const [feedback, setFeedback] = useState(""); + const capDefault = g?.caps.revision ?? 2; + const [cap, setCap] = useState(String(capDefault)); + const claude = model.startsWith("claude-"); + return ( + <form + aria-label={`new iteration from ${it.label}`} + className="mt-2 flex flex-col gap-2 rounded border border-dashed border-[var(--color-line)] p-2 text-[12px]" + onSubmit={async (e) => { + e.preventDefault(); + const ok = await ctx.post({ + task: target === "report" ? "revise-report" : "revise-video", + article: ctx.article, + iteration: it.n, + model, + feedback, + ...(claude ? { maxUsd: Number(cap) } : {}), + }); + if (ok) onDone(); + }} + > + <div className="flex flex-wrap items-center gap-3"> + <fieldset className="flex gap-3"> + <legend className="sr-only">what to change</legend> + <label className="flex items-center gap-1"> + <input type="radio" name={`target-${it.n}`} checked={target === "report"} onChange={() => setTarget("report")} /> + report + </label> + <label className="flex items-center gap-1"> + <input type="radio" name={`target-${it.n}`} checked={target === "video"} onChange={() => setTarget("video")} /> + video + </label> + </fieldset> + <ModelSelect label={`model for the new iteration from ${it.label}`} value={model} onChange={setModel} models={ctx.allModels} /> + {claude && ( + <label className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">cap $</span> + <input aria-label="cap" className={`${field} num w-14`} inputMode="decimal" value={cap} onChange={(e) => setCap(e.target.value)} /> + </label> + )} + </div> + <textarea + aria-label="feedback" + className={field} + rows={2} + required + placeholder={target === "report" ? "drop, merge or reword findings; find more on…; retitle" : "cut or reorder clips; card headings; narration; title"} + value={feedback} + onChange={(e) => setFeedback(e.target.value)} + /> + <div> + <Button type="submit" size="sm" variant="primary"> + Start iteration + </Button> + </div> + </form> + ); +} + +function IterationCard({ + it, + ctx, + comparing, + onCompare, +}: { + it: IterationRow; + ctx: Ctx; + comparing: boolean; + onCompare: (on: boolean) => void; +}) { + const [open, setOpen] = useState<"new" | "chain" | null>(null); + const g = ctx.policy?.generation; + const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model); + const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? "")); + const done = it.status === "done"; + const active = it.status === "queued" || it.status === "running"; + const runningStep = it.steps.find((s) => s.status === "running" && s.jobId && !s.task.startsWith("chain:")); + const sideSteps = it.steps.filter((s) => !s.task.startsWith("chain:")); + const failedChecks = it.checks.filter((c) => !c.ok); + const task = TASK_OF[it.kind]; + return ( + <article + aria-label={it.label} + data-iteration={it.n} + data-kind={it.kind} + data-status={it.status} + className={`rounded border p-3 ${it.currentReport || it.currentVideo ? "border-[var(--color-sel)]" : "border-[var(--color-line)]"} bg-[var(--color-panel)]`} + > + <header className="flex flex-wrap items-baseline gap-x-2 gap-y-1"> + <h3 className="font-mono text-[15px] text-[var(--color-text)]">{it.label}</h3> + <span className="text-[12px] text-[var(--color-dim)]">{it.kind}</span> + <span className="font-mono text-[12px]">{it.model}</span> + {it.parent !== null && <span className="text-[12px] text-[var(--color-dim)]">of i{it.parent}</span>} + {it.copyOf !== null && ( + <span data-copy-of={it.copyOf} className="text-[12px] text-[var(--color-dim)]"> + copy of i{it.copyOf} + </span> + )} + <span className={badgeVariants({ variant: STATUS_VARIANT[it.status] ?? "neutral", size: "sm" })}>{it.status}</span> + {it.currentReport && ( + <span data-current="article" className={badgeVariants({ variant: "on", size: "sm" })}> + article + </span> + )} + {it.currentVideo && ( + <span data-current="video" className={badgeVariants({ variant: "meter", size: "sm" })}> + video + </span> + )} + <span className="num ml-auto text-[12px] text-[var(--color-dim)]" data-usd={it.usd.toFixed(2)}> + <span className="text-[var(--color-meter)]">{usd(it.usd)}</span> + {it.minutes !== null ? ` · ${it.minutes.toFixed(1)} min` : ""} + </span> + </header> + + {(it.feedback ?? it.question) && <p className="mt-1 text-[13px]">{it.feedback ? `“${it.feedback}”` : it.question}</p>} + {it.scope?.channels && ( + <p className="font-mono text-[11px] text-[var(--color-dim)]"> + {it.scope.channels.join(", ")} + {it.scope.from || it.scope.to ? ` · ${it.scope.from ?? "…"} – ${it.scope.to ?? "…"}` : ""} + </p> + )} + + <dl className="mt-1.5 flex flex-wrap gap-x-5 gap-y-0.5 text-[12px]"> + {(it.ops.applied > 0 || it.ops.refused > 0) && ( + <div className="flex gap-1"> + <dt className="text-[var(--color-dim)]">ops</dt> + <dd data-ops-applied={it.ops.applied} data-ops-refused={it.ops.refused} className="num"> + {it.ops.applied} applied · {it.ops.refused} refused + </dd> + </div> + )} + {it.usage.map((u) => ( + <div key={u.model} className="flex gap-1" data-usage-model={u.model}> + <dt className="font-mono text-[var(--color-dim)]">{u.model}</dt> + <dd className="num"> + {usd(u.usd)} <span className="text-[var(--color-dim)]">({fmtTokens(u.inputTokens)} in / {fmtTokens(u.outputTokens)} out)</span> + </dd> + </div> + ))} + {it.checks.length > 0 && ( + <div className="flex gap-1"> + <dt className="text-[var(--color-dim)]">checks</dt> + <dd data-checks-failed={failedChecks.length}> + {failedChecks.length === 0 ? `${it.checks.length} passed` : `${failedChecks.length} of ${it.checks.length} failed`} + </dd> + </div> + )} + {sideSteps.map((s) => ( + <div key={s.task} className="flex gap-1" data-step={s.task} data-step-status={s.status}> + <dt className="text-[var(--color-dim)]">{s.task}</dt> + <dd> + {s.status} + {s.model ? <span className="font-mono text-[var(--color-dim)]"> {s.model}</span> : null} + {s.cost ? ` ${usd(s.cost)}` : ""} + </dd> + </div> + ))} + </dl> + {failedChecks.length > 0 && ( + <ul className="mt-1 list-disc pl-5 text-[12px] text-[var(--color-dirty)]"> + {failedChecks.map((c, i) => ( + <li key={i}> + {c.name} + {c.detail ? `: ${c.detail}` : ""} + </li> + ))} + </ul> + )} + {it.error && <p className="mt-1 text-[12px] text-[var(--color-bad)]">{it.error}</p>} + + {active && it.jobId && <JobProgress jobId={it.jobId} label={it.label} onEnd={ctx.refresh} />} + {runningStep?.jobId && <JobProgress jobId={runningStep.jobId} label={`${it.label} ${runningStep.task}`} onEnd={ctx.refresh} />} + + {it.kind === "research" && <ResearchSlot article={ctx.article} iteration={it} />} + + <div className="mt-2 flex flex-wrap items-center gap-2"> + {done && it.reportFrom !== null && !it.currentReport && ( + <Button size="sm" variant="primary" onClick={() => void ctx.use(it.n)}> + Use this iteration + </Button> + )} + {done && it.kind !== "research" && ( + <Button size="sm" aria-expanded={open === "new"} onClick={() => setOpen(open === "new" ? null : "new")}> + New iteration + </Button> + )} + {task && !active && ( + <span className="flex items-center gap-1"> + <ModelSelect label={`copy ${it.label} on model`} value={copyModel} onChange={setCopyModel} models={ctx.allModels} /> + <Button size="sm" onClick={() => void ctx.post({ task, article: ctx.article, copyOf: it.n, model: copyModel })}> + Copy with model + </Button> + </span> + )} + {done && it.hasManifest && !runningStep && ( + <span className="flex items-center gap-1"> + <ModelSelect label={`narration model for ${it.label}`} value={narrateModel} onChange={setNarrateModel} models={ctx.allModels} /> + <Button size="sm" onClick={() => void ctx.post({ task: "narrate", article: ctx.article, iteration: it.n, model: narrateModel })}> + Narrate + </Button> + </span> + )} + {done && it.reportFrom !== null && ( + <Button size="sm" aria-expanded={open === "chain"} onClick={() => setOpen(open === "chain" ? null : "chain")}> + Make the video + </Button> + )} + <label className="ml-auto flex items-center gap-1 text-[12px] text-[var(--color-dim)]"> + <input type="checkbox" checked={comparing} onChange={(e) => onCompare(e.target.checked)} aria-label={`compare ${it.label}`} /> + compare + </label> + </div> + {open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />} + {open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />} + </article> + ); +} + +export default function IterationsTab({ + initial, + policy, + today: initialToday, +}: { + initial: ArticleIterations; + policy: PolicyView | null; + today: Today | null; +}) { + const article = initial.article; + const [data, setData] = useState(initial); + const [today, setToday] = useState(initialToday); + const [error, setError] = useState(""); + const [note, setNote] = useState(""); + const [compare, setCompare] = useState<number[]>([]); + + const refresh = useCallback(async () => { + const r = await fetch(`/api/articles/iterations?article=${encodeURIComponent(article)}`, { cache: "no-store" }); + if (r.ok) setData(await r.json()); + const p = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null); + if (p?.ok) setToday((await p.json()).today ?? null); + }, [article]); + const refreshNow = useCallback(() => void refresh(), [refresh]); + + const stepRunning = data.iterations.some((it) => it.steps.some((s) => s.status === "running" && !s.task.startsWith("chain:"))); + useEffect(() => { + if (!data.busy && !stepRunning) return; + const t = setInterval(refreshNow, 3000); + return () => clearInterval(t); + }, [data.busy, stepRunning, refreshNow]); + + const ask = useCallback( + async (url: string, body: Record<string, unknown>, said: (b: { iteration?: number; jobId?: string }) => string) => { + setError(""); + setNote(""); + try { + const r = await fetch(url, { method: "POST", body: JSON.stringify(body) }); + const b = await r.json(); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setNote(said(b)); + await refresh(); + return true; + } catch (e) { + setError((e as Error).message); + return false; + } + }, + [refresh], + ); + const post = useCallback( + (body: Record<string, unknown>) => ask("/api/articles/generate", body, (b) => `i${b.iteration} started (${b.jobId})`), + [ask], + ); + const use = useCallback( + (n: number) => ask("/api/articles/iterations", { article, n, action: "use" }, () => `the article is i${n}`), + [ask, article], + ); + + const allModels = policy ? [...new Set([...policy.models.api, ...policy.models.local])] : []; + const ctx: Ctx = { article, policy, allModels, post, use, refresh: refreshNow }; + const spent = data.iterations.reduce((s, it) => s + it.usd, 0); + + return ( + <section aria-label="iterations" className="flex flex-col gap-3" data-iterations={data.iterations.length}> + <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[12px] text-[var(--color-dim)]"> + <span> + {data.iterations.length} iteration{data.iterations.length === 1 ? "" : "s"} + </span> + <span data-current-report={data.current.report ?? ""}>article {data.current.report ? `i${data.current.report}` : "—"}</span> + <span data-current-video={data.current.video ?? ""}>video {data.current.video ? `i${data.current.video}` : "—"}</span> + <span className="num"> + spent <span className="text-[var(--color-meter)]">{usd(spent)}</span> + </span> + {today && ( + <span className="num" data-today-usd={today.usd.toFixed(2)}> + today {usd(today.usd)} + {today.daily > 0 ? ` of ${usd(today.daily)}` : ""} + </span> + )} + {compare.length === 2 && ( + <Link + href={`/articles/${article}/compare?a=${Math.min(...compare)}&b=${Math.max(...compare)}`} + className="ml-auto text-[var(--color-sel)] hover:underline" + > + Compare i{Math.min(...compare)} and i{Math.max(...compare)} + </Link> + )} + </div> + {!policy && ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + The editor did not answer: new iterations, copies and narration need it. + </p> + )} + {note && ( + <p role="status" className="text-[12px] text-[var(--color-dim)]"> + {note} + </p> + )} + {error && ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + {error} + </p> + )} + {data.problems.map((p) => ( + <p key={p.n} className="text-[12px] text-[var(--color-bad)]"> + i{p.n}: {p.problems.join("; ")} + </p> + ))} + {data.iterations.length === 0 && <p className="text-[12px] text-[var(--color-dim)]">no iterations</p>} + {data.iterations.map((it) => ( + <IterationCard + key={it.n} + it={it} + ctx={ctx} + comparing={compare.includes(it.n)} + onCompare={(on) => setCompare(on ? [...compare.filter((n) => n !== it.n)].slice(-1).concat(it.n) : compare.filter((n) => n !== it.n))} + /> + ))} + </section> + ); +} diff --git a/umtool/components/articles/IterationsView.tsx b/umtool/components/articles/IterationsView.tsx @@ -0,0 +1,17 @@ +import IterationsTab from "@/components/articles/IterationsTab"; +import { readArticleIterations, readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; + +// The Iterations tab's server half (release 27 S8): the article's iterations +// as the store has them, the policy and the day's spend as the editor has +// them (null when the editor does not answer: the list still reads). +export default async function IterationsView({ article }: { article: string }) { + const initial = await readArticleIterations(article); + let policy: PolicyView | null = null; + try { + policy = await readPolicy(); + } catch { + policy = null; + } + const today = policy ? await readToday(policy.generation.caps.daily).catch(() => null) : null; + return <IterationsTab initial={initial} policy={policy} today={today} />; +} diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -0,0 +1,244 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; +import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; + +// /articles/new (release 27 S8): a question over channels becomes an article's +// first iteration — a `report-draft` sweep the editor runs and writes. The +// sweep is the agent on a Claude model, or the code-driven pipeline on the +// local model; the cap starts at the policy's per-job default and goes down. + +const field = + "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] text-[var(--color-text)] focus-visible:border-[var(--color-sel)] focus-visible:outline-none"; +const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; + +type Task = "agent" | "pipeline"; + +function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) { + const [all, setAll] = useState<EditorChannel[] | null>(null); + const [error, setError] = useState(""); + const [q, setQ] = useState(""); + useEffect(() => { + fetch("/api/articles/channels", { cache: "no-store" }) + .then(async (r) => { + const b = await r.json(); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setAll(b.channels); + }) + .catch((e) => setError((e as Error).message)); + }, []); + const shown = useMemo(() => { + const k = q.trim().toLowerCase(); + return (all ?? []).filter((c) => !k || c.slug.includes(k) || c.name.toLowerCase().includes(k)).slice(0, 80); + }, [all, q]); + const toggle = (slug: string) => onChange(value.includes(slug) ? value.filter((s) => s !== slug) : [...value, slug]); + const nameOf = (slug: string) => all?.find((c) => c.slug === slug)?.name ?? slug; + return ( + <fieldset className="flex flex-col gap-1.5" aria-label="channels"> + <div className="flex flex-wrap items-center gap-1.5"> + {value.map((s) => ( + <button + key={s} + type="button" + data-picked={s} + aria-label={`remove ${nameOf(s)}`} + className="rounded border border-[var(--color-sel)] px-1.5 py-0.5 text-[12px] text-[var(--color-sel)] hover:bg-[var(--color-panel-2)]" + onClick={() => toggle(s)} + > + {nameOf(s)} × + </button> + ))} + <input + className={`${field} w-64`} + aria-label="find a channel" + placeholder={all ? `find a channel (${all.length})` : "loading channels…"} + value={q} + onChange={(e) => setQ(e.target.value)} + /> + </div> + {error && ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + channels: {error} + </p> + )} + {q && ( + <ul className="flex max-h-44 flex-wrap gap-1 overflow-auto" aria-label="matching channels"> + {shown.map((c) => ( + <li key={c.slug}> + <button + type="button" + aria-pressed={value.includes(c.slug)} + title={`${c.slug}${c.sites.length ? ` · on ${c.sites.join(", ")}` : " · on no site"}`} + className={`rounded border px-1.5 py-0.5 text-[12px] hover:bg-[var(--color-panel-2)] ${value.includes(c.slug) ? "border-[var(--color-sel)] text-[var(--color-sel)]" : "border-[var(--color-line)]"}`} + onClick={() => toggle(c.slug)} + > + {c.name} + <span className="ml-1 font-mono text-[10px] text-[var(--color-dim)]">{c.slug}</span> + </button> + </li> + ))} + {shown.length === 0 && <li className="text-[12px] text-[var(--color-dim)]">no channel matches</li>} + </ul> + )} + </fieldset> + ); +} + +export default function NewArticleForm({ initialPolicy, today, taken }: { initialPolicy: PolicyView | null; today: Today | null; taken: string[] }) { + const router = useRouter(); + const [policy, setPolicy] = useState(initialPolicy); + const onPolicy = useCallback((p: PolicyView) => setPolicy(p), []); + const defaultTask: Task = policy?.generation.routes.sweep === "local" ? "pipeline" : "agent"; + const [task, setTask] = useState<Task>(defaultTask); + const models = task === "agent" ? (policy?.models.api ?? []) : (policy?.models.local ?? []); + const routeModel = task === "agent" ? policy?.generation.models.api : policy?.generation.models.local; + const [model, setModel] = useState(routeModel ?? ""); + const capDefault = policy?.generation.caps.sweep ?? 5; + const [cap, setCap] = useState(String(capDefault)); + const [id, setId] = useState(""); + const [question, setQuestion] = useState(""); + const [channels, setChannels] = useState<string[]>([]); + const [from, setFrom] = useState(""); + const [to, setTo] = useState(""); + const [error, setError] = useState(""); + const [sending, setSending] = useState(false); + + useEffect(() => { + setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? "")); + }, [task, policy]); + + const idProblem = !id ? null : !ID_RE.test(id) ? "a lowercase slug: a-z, 0-9 and -" : taken.includes(id) ? "an article by that id exists — add an iteration on its page" : null; + + async function start(e: React.FormEvent) { + e.preventDefault(); + setError(""); + if (idProblem) return setError(`article id: ${idProblem}`); + if (!channels.length) return setError("pick at least one channel"); + const maxUsd = Number(cap); + if (task === "agent" && !(maxUsd > 0 && maxUsd <= capDefault)) return setError(`the cap is above $0 and at most the policy's $${capDefault}`); + setSending(true); + try { + const r = await fetch("/api/articles/generate", { + method: "POST", + body: JSON.stringify({ + task: "sweep", + article: id, + question, + channels, + model, + ...(from ? { from } : {}), + ...(to ? { to } : {}), + ...(task === "agent" ? { maxUsd } : {}), + }), + }); + const b = await r.json(); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + router.push(`/articles/${id}?tab=iterations`); + } catch (err) { + setError((err as Error).message); + setSending(false); + } + } + + return ( + <div className="flex max-w-4xl flex-col gap-4"> + {policy ? ( + <PolicyPanel initial={policy} today={today} onChange={onPolicy} /> + ) : ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + The editor did not answer, so the policy and the channels are unknown. Start it, then reload. + </p> + )} + + <form onSubmit={start} aria-label="new article" className="flex flex-col gap-3 rounded border border-[var(--color-line)] p-3"> + <label className="flex flex-col gap-1"> + <span className="micro">question</span> + <textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" /> + </label> + + <div className="flex flex-col gap-1"> + <span className="micro">channels</span> + <ChannelPicker value={channels} onChange={setChannels} /> + </div> + + <div className="flex flex-wrap items-end gap-4"> + <label className="flex flex-col gap-1"> + <span className="micro">article id</span> + <input + className={`${field} font-mono`} + aria-label="article id" + aria-invalid={idProblem ? true : undefined} + required + value={id} + onChange={(e) => setId(e.target.value.trim())} + /> + </label> + <label className="flex flex-col gap-1"> + <span className="micro">from</span> + <input className={field} type="date" aria-label="from" value={from} onChange={(e) => setFrom(e.target.value)} /> + </label> + <label className="flex flex-col gap-1"> + <span className="micro">to</span> + <input className={field} type="date" aria-label="to" value={to} onChange={(e) => setTo(e.target.value)} /> + </label> + </div> + {idProblem && <p className="text-[12px] text-[var(--color-dirty)]">article id: {idProblem}</p>} + + <div className="flex flex-wrap items-end gap-4"> + <fieldset className="flex flex-col gap-1"> + <legend className="micro mb-1">sweep</legend> + <div className="flex gap-3 text-[12px]"> + <label className="flex items-center gap-1"> + <input type="radio" name="task" checked={task === "agent"} onChange={() => setTask("agent")} /> + agent <span className="text-[var(--color-dim)]">(Claude)</span> + </label> + <label className="flex items-center gap-1"> + <input type="radio" name="task" checked={task === "pipeline"} onChange={() => setTask("pipeline")} /> + pipeline <span className="text-[var(--color-dim)]">(local)</span> + </label> + </div> + </fieldset> + <label className="flex flex-col gap-1"> + <span className="micro">model</span> + <select className={`${field} font-mono`} aria-label="model" value={model} onChange={(e) => setModel(e.target.value)}> + {[...new Set([model, ...models].filter(Boolean))].map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + {task === "agent" && ( + <label className="flex flex-col gap-1"> + <span className="micro">cap $</span> + <input + className={`${field} num w-20`} + aria-label="cap" + inputMode="decimal" + value={cap} + onChange={(e) => setCap(e.target.value)} + title={`at most the policy's $${capDefault} a sweep`} + /> + </label> + )} + <Button type="submit" variant="primary" size="lg" disabled={sending || !policy}> + {sending ? "Starting…" : "Start"} + </Button> + </div> + {task === "agent" && policy && !policy.keyFile.exists && ( + <p className="text-[12px] text-[var(--color-dirty)]"> + No key file at <code className="font-mono">{policy.keyFile.path}</code>; the editor needs ANTHROPIC_API_KEY in its environment. + </p> + )} + {error && ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + {error} + </p> + )} + </form> + </div> + ); +} diff --git a/umtool/components/articles/PolicyPanel.tsx b/umtool/components/articles/PolicyPanel.tsx @@ -0,0 +1,175 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { badgeVariants } from "@/components/ui/badge"; +import type { PolicyView } from "@/lib/articles/generation"; + +// THE GENERATION POLICY (release 27 S8): where each task runs (Claude Code, +// the API, the local model), the presets that set all four at once, the +// models, the caps. Written through the editor's settings action +// (/api/articles/policy -> POST /api/ops/settings). The API key is never here: +// the key FILE's path, and whether a file is there. + +export type Today = { day: string; usd: number; jobs: number; daily: number }; + +const ROUTE_LABEL: Record<string, string> = { code: "Claude Code", api: "API", local: "local" }; +const CAP_KEYS = ["sweep", "revision", "narration", "daily", "max"] as const; +const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; + +export const usd = (v: number) => `$${v.toFixed(2)}`; + +export default function PolicyPanel({ + initial, + today: initialToday, + onChange, +}: { + initial: PolicyView; + today: Today | null; + onChange?: (p: PolicyView) => void; +}) { + const [policy, setPolicy] = useState(initial); + const [today] = useState(initialToday); + const [caps, setCaps] = useState(() => Object.fromEntries(CAP_KEYS.map((k) => [k, String(initial.generation.caps[k])]))); + const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); + const [busy, setBusy] = useState(false); + const g = policy.generation; + + useEffect(() => onChange?.(policy), [policy, onChange]); + + async function save(patch: Record<string, unknown>, what: string) { + setBusy(true); + setStatus(null); + try { + const r = await fetch("/api/articles/policy", { method: "POST", body: JSON.stringify(patch) }); + const body = await r.json(); + if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); + setPolicy(body.policy); + setCaps(Object.fromEntries(CAP_KEYS.map((k) => [k, String(body.policy.generation.caps[k])]))); + setStatus({ ok: true, text: `saved ${what}` }); + } catch (e) { + setStatus({ ok: false, text: (e as Error).message }); + } finally { + setBusy(false); + } + } + + return ( + <section aria-label="generation policy" data-policy-preset={g.preset} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]"> + <div className="flex flex-wrap items-center gap-2"> + <span className="micro">policy</span> + <div role="group" aria-label="presets" className="flex gap-1"> + {Object.keys(policy.presets).map((p) => ( + <Button + key={p} + size="sm" + variant={g.preset === p ? "primary" : "outline"} + aria-pressed={g.preset === p} + disabled={busy} + onClick={() => save({ routes: { ...policy.presets[p] } }, `preset ${p}`)} + > + {p} + </Button> + ))} + </div> + {g.preset === "custom" && <span className={badgeVariants({ variant: "info", size: "sm" })}>custom</span>} + {today && ( + <span data-today-usd={today.usd.toFixed(2)} className="num ml-auto text-[var(--color-dim)]"> + today <span className="text-[var(--color-meter)]">{usd(today.usd)}</span> + {today.daily > 0 ? ` of ${usd(today.daily)}` : " (no daily cap)"} + </span> + )} + </div> + + <div className="mt-3 grid gap-x-6 gap-y-2 sm:grid-cols-[auto_1fr]"> + <div className="micro pt-1">routes</div> + <div className="flex flex-wrap gap-x-4 gap-y-1"> + {policy.tasks.map((t) => ( + <label key={t} className="flex items-center gap-1.5"> + <span className="text-[var(--color-dim)]">{t}</span> + <select + aria-label={`route ${t}`} + className={field} + value={g.routes[t as keyof typeof g.routes]} + disabled={busy} + onChange={(e) => save({ routes: { ...g.routes, [t]: e.target.value } }, `route ${t}`)} + > + {policy.routes.map((r) => ( + <option key={r} value={r}> + {ROUTE_LABEL[r] ?? r} + </option> + ))} + </select> + </label> + ))} + </div> + + <div className="micro pt-1">models</div> + <div className="flex flex-wrap gap-x-4 gap-y-1"> + {(["api", "local", "extractor"] as const).map((k) => { + const list = k === "local" ? policy.models.local : k === "extractor" ? [...policy.models.api, ...policy.models.local] : policy.models.api; + const opts = [...new Set([g.models[k], ...list])]; + return ( + <label key={k} className="flex items-center gap-1.5"> + <span className="text-[var(--color-dim)]">{k}</span> + <select + aria-label={`${k} model`} + className={`${field} font-mono`} + value={g.models[k]} + disabled={busy} + onChange={(e) => save({ models: { ...g.models, [k]: e.target.value } }, `${k} model`)} + > + {opts.map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + ); + })} + </div> + + <div className="micro pt-1">caps</div> + <form + className="flex flex-wrap items-center gap-x-4 gap-y-1" + onSubmit={(e) => { + e.preventDefault(); + save({ caps: Object.fromEntries(CAP_KEYS.map((k) => [k, Number(caps[k])])) }, "caps"); + }} + > + {CAP_KEYS.map((k) => ( + <label key={k} className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">{k}</span> + <span className="text-[var(--color-dim)]">$</span> + <input + aria-label={`cap ${k}`} + className={`${field} num w-16`} + inputMode="decimal" + value={caps[k]} + onChange={(e) => setCaps({ ...caps, [k]: e.target.value })} + /> + </label> + ))} + <Button size="sm" type="submit" disabled={busy}> + Save caps + </Button> + </form> + + <div className="micro pt-1">API key</div> + <div className="flex items-center gap-2" data-key-file-exists={policy.keyFile.exists ? "yes" : "no"}> + <code className="font-mono text-[11px]">{policy.keyFile.path}</code> + <span className={badgeVariants({ variant: policy.keyFile.exists ? "info" : "blocking", size: "sm" })}> + {policy.keyFile.exists ? "file found" : "no file"} + </span> + </div> + </div> + + {status && ( + <p role={status.ok ? "status" : "alert"} className={`mt-2 ${status.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}`}> + {status.text} + </p> + )} + </section> + ); +} diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx @@ -0,0 +1,18 @@ +"use client"; + +import type { IterationRow } from "@/lib/articles/generation"; + +// THE RESEARCH QUEUE's place in an iteration of kind `research` (release 27 +// S11 fills it: the proposals, yes/no per item, the acquisition jobs, and +// continue). Until then it names the run's phase by its status. +export default function ResearchSlot({ article, iteration }: { article: string; iteration: IterationRow }) { + return ( + <section + aria-label={`${iteration.label} research`} + data-research-slot={`${article}/${iteration.n}`} + className="mt-2 rounded border border-dashed border-[var(--color-line)] p-2 text-[12px] text-[var(--color-dim)]" + > + <span className="micro">research</span> {iteration.status} + </section> + ); +} diff --git a/umtool/components/drafts/DraftsPanel.tsx b/umtool/components/drafts/DraftsPanel.tsx @@ -1,408 +0,0 @@ -"use client"; - -import { useCallback, useEffect, useMemo, useState } from "react"; -import type { GenPolicy, Route, RunView, Step } from "@/lib/drafts"; - -// The /drafts page (lib/drafts.ts): start a report on a local model or Claude on an API key, iterate on it — a new -// VERSION of its report or its video from your feedback — and run each version's article, narration and video. -// Runs poll every 3 s off their logs. The generation policy (which tasks go to Claude Code, the API or the local -// model) is the file bin/gen and Claude Code's /gen read. - -const MODELS = ["qwen3:8b", "claude-sonnet-5-5", "claude-sonnet-5", "claude-opus-5-5"]; -const STEPS: Step[] = ["sweep", "article", "narrate", "video"]; -const TASKS = ["sweep", "revise-report", "revise-video", "narrate"]; -const HINT: Record<Step, string> = { - sweep: "the report (sweep, or this version's revision)", - article: "private draft article + clip fetches + video project", - narrate: "card narration drafts — review them before the video", - video: "voices + cut + podcast, attached to the article", -}; -type Channel = { slug: string; name: string; videos: number; builds: string[] }; - -const input = "rounded border border-[var(--color-line)] bg-transparent px-2 py-1 text-[13px]"; -const btn = - "rounded border border-[var(--color-line)] px-2 py-0.5 text-[12px] hover:bg-[var(--color-line)] disabled:opacity-40"; -const stateColor: Record<string, string> = { - idle: "text-[var(--color-dim)]", - running: "text-amber-500", - done: "text-emerald-500", - failed: "text-red-500", - cancelled: "text-[var(--color-dim)] line-through", -}; -const label = (m: string) => (m.startsWith("claude-") ? `${m} (API key)` : `${m} (local)`); - -function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) { - const [all, setAll] = useState<Channel[]>([]); - const [q, setQ] = useState(""); - useEffect(() => { - fetch("/api/drafts?channels=1").then((r) => r.json()).then((r) => setAll(r.channels)); - }, []); - const shown = useMemo(() => { - const k = q.toLowerCase(); - return all.filter((c) => !k || c.slug.includes(k) || c.name.toLowerCase().includes(k)).slice(0, 60); - }, [all, q]); - const toggle = (slug: string) => onChange(value.includes(slug) ? value.filter((s) => s !== slug) : [...value, slug]); - return ( - <div className="flex flex-col gap-1"> - <div className="flex flex-wrap items-center gap-1"> - {value.map((s) => ( - <button key={s} type="button" className={`${btn} border-emerald-600`} onClick={() => toggle(s)} title="remove"> - {all.find((c) => c.slug === s)?.name ?? s} × - </button> - ))} - <input className={`${input} w-56`} placeholder={`find a channel (${all.length})`} value={q} onChange={(e) => setQ(e.target.value)} /> - </div> - {q && ( - <div className="flex max-h-40 flex-wrap gap-1 overflow-auto"> - {shown.map((c) => ( - <button - key={c.slug} - type="button" - className={`${btn} ${value.includes(c.slug) ? "border-emerald-600" : ""}`} - title={`${c.slug} · in ${c.builds.join(", ")}`} - onClick={() => toggle(c.slug)} - > - {c.name} <span className="text-[var(--color-dim)]">{c.videos.toLocaleString()}</span> - </button> - ))} - </div> - )} - </div> - ); -} - -function PolicyPanel({ policy, presets, save }: { policy: GenPolicy; presets: Record<string, Record<string, Route>>; save: (p: GenPolicy) => void }) { - const set = (p: Partial<GenPolicy>) => save({ ...policy, ...p }); - return ( - <details className="rounded border border-[var(--color-line)] p-3 text-[12px]"> - <summary className="cursor-pointer"> - generation policy: <b>{policy.preset}</b> — {TASKS.map((t) => `${t} → ${policy.routes[t] ?? "?"}`).join(" · ")} - </summary> - <div className="mt-2 flex flex-wrap items-center gap-3"> - <label> - preset{" "} - <select className={input} value={policy.preset} onChange={(e) => set({ preset: e.target.value, routes: { ...presets[e.target.value] } })}> - {Object.keys(presets).map((p) => ( - <option key={p}>{p}</option> - ))} - <option value="custom">custom</option> - </select> - </label> - {TASKS.map((t) => ( - <label key={t}> - {t}{" "} - <select - className={input} - value={policy.routes[t]} - onChange={(e) => set({ preset: "custom", routes: { ...policy.routes, [t]: e.target.value as Route } })} - > - <option value="code">Claude Code</option> - <option value="api">API</option> - <option value="local">local</option> - </select> - </label> - ))} - <label> - API model{" "} - <select className={input} value={policy.models.api} onChange={(e) => set({ models: { ...policy.models, api: e.target.value } })}> - {MODELS.filter((m) => m.startsWith("claude-")).map((m) => ( - <option key={m}>{m}</option> - ))} - </select> - </label> - <label> - local model{" "} - <select className={input} value={policy.models.local} onChange={(e) => set({ models: { ...policy.models, local: e.target.value } })}> - {MODELS.filter((m) => !m.startsWith("claude-")).map((m) => ( - <option key={m}>{m}</option> - ))} - </select> - </label> - </div> - <p className="mt-2 text-[var(--color-dim)]"> - Claude Code&apos;s <code>/gen</code> and <code>bin/gen run</code> follow these routes; this page uses them as its defaults. - </p> - </details> - ); -} - -function VersionForm({ run, defaults, post }: { run: RunView; defaults: GenPolicy; post: (b: object) => Promise<{ ok?: boolean }> }) { - const [what, setWhat] = useState<"report" | "video">("report"); - const route = defaults.routes[what === "report" ? "revise-report" : "revise-video"]; - const [model, setModel] = useState(route === "local" ? defaults.models.local : defaults.models.api); - const [feedback, setFeedback] = useState(""); - const [maxUsd, setMaxUsd] = useState("2"); - return ( - <form - className="mt-2 flex flex-col gap-1 rounded border border-dashed border-[var(--color-line)] p-2" - onSubmit={async (e) => { - e.preventDefault(); - const r = await post({ action: "version", parent: run.name, what, model, feedback, maxUsd }); - if (r.ok) setFeedback(""); - }} - > - <div className="flex flex-wrap items-center gap-2 text-[12px]"> - new version of the - <select className={input} value={what} onChange={(e) => setWhat(e.target.value as "report" | "video")}> - <option value="report">article (report)</option> - <option value="video">video (cut, cards, narration)</option> - </select> - on - <select className={input} value={model} onChange={(e) => setModel(e.target.value)}> - {MODELS.map((m) => ( - <option key={m} value={m}> - {label(m)} - </option> - ))} - </select> - {model.startsWith("claude-") && ( - <label> - max $<input className={`${input} w-14`} value={maxUsd} onChange={(e) => setMaxUsd(e.target.value)} /> - </label> - )} - </div> - <textarea - className={input} - rows={2} - required - placeholder={what === "report" ? "What to change: drop/merge findings, reword claims, find more on X, retitle…" : "What to change: cut or reorder clips, card headings, narration, title…"} - value={feedback} - onChange={(e) => setFeedback(e.target.value)} - /> - <div> - <button className={btn} type="submit"> - Make version - </button> - </div> - </form> - ); -} - -export default function DraftsPanel() { - const [runs, setRuns] = useState<RunView[]>([]); - const [keyReady, setKeyReady] = useState<boolean | null>(null); - const [policy, setPolicy] = useState<GenPolicy | null>(null); - const [presets, setPresets] = useState<Record<string, Record<string, Route>>>({}); - const [err, setErr] = useState(""); - const [channels, setChannels] = useState<string[]>([]); - const [form, setForm] = useState({ question: "", model: "", name: "", terms: "", maxUsd: "5" }); - const [runModel, setRunModel] = useState<Record<string, string>>({}); - const [compare, setCompare] = useState<string[]>([]); - const [open, setOpen] = useState<string | null>(null); - const [iterating, setIterating] = useState<string | null>(null); - - const load = useCallback(async () => { - const r = await fetch("/api/drafts", { cache: "no-store" }).then((x) => x.json()); - setRuns(r.runs); - setKeyReady(r.keyReady); - setPolicy(r.policy); - setPresets(r.presets); - }, []); - useEffect(() => { - load(); - const t = setInterval(load, 3000); - try { - const saved = JSON.parse(localStorage.getItem("drafts.channels") ?? "[]"); - if (Array.isArray(saved)) setChannels(saved); - } catch {} - return () => clearInterval(t); - }, [load]); - useEffect(() => { - try { - localStorage.setItem("drafts.channels", JSON.stringify(channels)); - } catch {} - }, [channels]); - const routeModel = (task: string) => - policy ? (policy.routes[task] === "local" ? policy.models.local : policy.models.api) : "qwen3:8b"; - const model = form.model || routeModel("sweep"); - - async function post(body: object) { - setErr(""); - const r = await fetch("/api/drafts", { method: "POST", body: JSON.stringify(body) }).then((x) => x.json()); - if (r.error) setErr(r.error); - load(); - return r; - } - - const claude = model.startsWith("claude-"); - const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm({ ...form, [k]: e.target.value }); - const groups = useMemo(() => { - const g = new Map<string, RunView[]>(); - for (const r of runs) g.set(r.id, [...(g.get(r.id) ?? []), r]); - return [...g.entries()]; - }, [runs]); - - return ( - <div className="flex max-w-5xl flex-col gap-5"> - {policy && <PolicyPanel policy={policy} presets={presets} save={(p) => post({ action: "policy", policy: p })} />} - - <form - className="flex flex-col gap-2 rounded border border-[var(--color-line)] p-3" - onSubmit={async (e) => { - e.preventDefault(); - if (!channels.length) return setErr("pick at least one channel"); - const r = await post({ action: "create", ...form, model, channels: channels.join(",") }); - if (r.ok) { - setOpen(r.name); - setForm({ ...form, question: "", name: "" }); - } - }} - > - <div className="text-[13px] font-semibold">New report</div> - <textarea className={input} rows={2} placeholder="Question" value={form.question} onChange={set("question")} required /> - <ChannelPicker value={channels} onChange={setChannels} /> - <div className="flex flex-wrap gap-2"> - <input className={input} placeholder="article id (a-z0-9-)" value={form.name} onChange={set("name")} pattern="[a-z0-9][a-z0-9-]*" required /> - <input className={input} placeholder="search terms (optional)" value={form.terms} onChange={set("terms")} /> - <select className={input} value={model} onChange={set("model")}> - {MODELS.map((m) => ( - <option key={m} value={m}> - {label(m)} - </option> - ))} - </select> - {claude && ( - <label className="flex items-center gap-1 text-[12px]"> - max $<input className={`${input} w-16`} value={form.maxUsd} onChange={set("maxUsd")} /> - </label> - )} - <button className={btn} type="submit"> - Start sweep - </button> - </div> - {claude && keyReady === false && ( - <div className="text-[12px] text-red-500">No API key: put ANTHROPIC_API_KEY=… in ~/.config/archilyzer/anthropic.env (chmod 600).</div> - )} - {err && <div className="text-[12px] text-red-500">{err}</div>} - </form> - - {compare.length > 0 && ( - <div className="text-[12px]"> - compare: {compare.join(" vs ")}{" "} - {compare.length === 2 && ( - <a className="underline" href={`/api/drafts?compare=${compare.join(",")}`} target="_blank"> - open side by side - </a> - )}{" "} - <button className={btn} onClick={() => setCompare([])}> - clear - </button> - </div> - )} - - {groups.length === 0 && <div className="text-[13px] text-[var(--color-dim)]">No runs yet.</div>} - {groups.map(([id, versions]) => ( - <section key={id} className="flex flex-col gap-2"> - <h2 className="text-[13px] font-semibold"> - article {id} <span className="font-normal text-[var(--color-dim)]">· {versions.length} version(s)</span> - </h2> - {versions.map((r) => { - const busy = STEPS.some((s) => r.steps[s].state === "running"); - const m = runModel[r.name] ?? r.model; - return ( - <div key={r.name} className="rounded border border-[var(--color-line)] p-3"> - <div className="flex flex-wrap items-baseline gap-2"> - <button className="text-[13px] font-semibold hover:underline" onClick={() => setOpen(open === r.name ? null : r.name)}> - v{r.version} · {r.name} - </button> - <span className="text-[12px] text-[var(--color-dim)]"> - {r.kind && r.kind !== "sweep" ? `${r.kind} of ${r.parent} · ` : ""} - {r.copyOf ? `copy of ${r.copyOf} · ` : ""} - {r.model} · {r.channels} - {typeof r.usd === "number" ? ` · ~$${r.usd.toFixed(2)}` : ""} - </span> - {r.currentArticle && <span className="rounded bg-emerald-700/40 px-1 text-[11px]">current article</span>} - {r.currentVideo && <span className="rounded bg-sky-700/40 px-1 text-[11px]">current video</span>} - </div> - <div className="mb-2 text-[13px]">{r.feedback ? `“${r.feedback}”` : r.question}</div> - <div className="flex flex-wrap items-center gap-3"> - {STEPS.filter((s) => !(s === "article" && r.kind === "revise-video")).map((s) => ( - <span key={s} className="flex items-center gap-1"> - <button - className={btn} - title={HINT[s]} - disabled={busy} - onClick={() => { - setOpen(r.name); - post({ action: "step", name: r.name, step: s, model: s === "sweep" || s === "narrate" ? m : undefined }); - }} - > - {s === "sweep" && r.kind && r.kind !== "sweep" ? "revise" : s} - </button> - <span className={`text-[11px] ${stateColor[r.steps[s].state]}`}>{r.steps[s].state}</span> - {r.steps[s].state === "running" && ( - <button - className={`${btn} border-red-700 text-red-500`} - title="stop this step (an editor job it started finishes on the editor)" - onClick={() => { - if (confirm(`Cancel ${s} on ${r.name}?`)) post({ action: "cancel", name: r.name, step: s }); - }} - > - cancel - </button> - )} - </span> - ))} - {r.files.map((f) => ( - <a key={f} className="text-[12px] underline" href={`/api/drafts?run=${r.name}&file=${f}`} target="_blank"> - {f} - </a> - ))} - {r.steps.narrate.state === "done" && ( - <a className="text-[12px] underline" href={r.narrationReview}> - review narration - </a> - )} - {(r.currentArticle || r.currentVideo) && ( - <a className="text-[12px] underline" href={`/articles/${r.id}`}> - article - </a> - )} - <select - className={input} - title="the model this run's sweep/revise and narrate steps use" - value={m} - onChange={(e) => setRunModel({ ...runModel, [r.name]: e.target.value })} - > - {MODELS.map((x) => ( - <option key={x} value={x}> - {label(x)} - </option> - ))} - </select> - <button - className={btn} - title="a copy of this run on the model picked here: the same question or feedback, the same base" - onClick={() => post({ action: "copy", name: r.name, model: m })} - > - copy with {m.replace("claude-", "")} - </button> - <label className="flex items-center gap-1 text-[12px]"> - <input - type="checkbox" - checked={compare.includes(r.name)} - onChange={(e) => - setCompare(e.target.checked ? [...compare.filter((x) => x !== r.name)].slice(-1).concat(r.name) : compare.filter((x) => x !== r.name)) - } - /> - compare - </label> - <button className={btn} disabled={!policy} onClick={() => setIterating(iterating === r.name ? null : r.name)}> - new version… - </button> - </div> - {iterating === r.name && policy && <VersionForm run={r} defaults={policy} post={post} />} - {open === r.name && - STEPS.filter((s) => r.steps[s].tail).map((s) => ( - <pre key={s} className="mt-2 max-h-64 overflow-auto rounded bg-black/30 p-2 text-[11px] leading-snug whitespace-pre-wrap"> - {`[${s}]\n${r.steps[s].tail}`} - </pre> - ))} - </div> - ); - })} - </section> - ))} - </div> - ); -} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -17,7 +17,7 @@ import http from "node:http"; import { spawnSync } from "node:child_process"; -import { mkdirSync, writeFileSync, statSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, statSync } from "node:fs"; import path from "node:path"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; @@ -78,6 +78,258 @@ function writeWindow(dir, name, seconds) { return out; } +// ─── GENERATION (release 27 S8) ─────────────────────────────────────────── +// +// The editor's side of /articles/new and the Iterations tab, stubbed: +// GET /api/ops/settings?key=generation the policy (apiKeyFile redacted, as +// the editor's read redacts it) +// POST /api/ops/settings {patch} merged one level, as saveSettings +// GET /api/ops/channels two channels +// POST /api/ops/report-draft an iteration written into the +// fixture's article store, then +// "run": running after 1 s, done +// after 3 s with its report.json — +// never an LLM +// GET /api/ops/job/<id>?tail=N that job's state and log +// POST /api/ops/job {verb: cancel, ids} cancelled, its iteration too +// Sentinels: a question or feedback containing "slow" keeps running until +// cancelled; feedback "refuse" is refused (400) as the editor refuses. +const ARTICLES = process.env.ARTICLES_DIR ?? ""; +const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? ""; +const PRESETS = { + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local" }, +}; +const generation = { + preset: "balanced", + routes: { ...PRESETS.balanced }, + models: { api: "claude-sonnet-5-5", local: "qwen3:8b", extractor: "claude-haiku-4-5" }, + caps: { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 }, + cacheTtl: "5m", + apiKeyFile: "~/.config/archilyzer/anthropic.env", + anthropicBaseUrl: "", + ollamaUrl: "", + projectsRoot: GEN_PROJECTS, + web: { provider: "duckduckgo", searchUrl: "" }, + citationOrigin: "", +}; +const presetOf = (routes) => + Object.keys(PRESETS).find((p) => Object.keys(PRESETS[p]).every((t) => routes[t] === PRESETS[p][t])) ?? "custom"; +const draftJobs = new Map(); + +const itDir = (article, n) => path.join(ARTICLES, article, "iterations", String(n)); +const readIt = (article, n) => JSON.parse(readFileSync(path.join(itDir(article, n), "iteration.json"), "utf8")); +const writeIt = (it) => writeFileSync(path.join(itDir(it.article, it.n), "iteration.json"), JSON.stringify(it, null, 2) + "\n"); +const patchIt = (article, n, patch) => { + const it = { ...readIt(article, n), ...patch, updatedAt: new Date().toISOString() }; + writeIt(it); + return it; +}; +const nextN = (article) => { + const dir = path.join(ARTICLES, article, "iterations"); + if (!existsSync(dir)) return 1; + const ns = readdirSync(dir).filter((d) => /^\d+$/.test(d)).map(Number); + return (ns.length ? Math.max(...ns) : 0) + 1; +}; + +// A report the registry's validator accepts: two sections, one citing the +// fixture's sitechan/sv1 as delta does. +function stubReport(article, title, extra = "") { + return { + format: "archilyzer-report", + version: 1, + id: article, + kind: "sweep", + title, + summary: "Made by the editor stub.", + citations: { + c1: { kind: "video", channel: "sitechan", id: "sv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew.", speaker: "Site Channel", date: "2024-03-15" }, + }, + sections: [ + { id: "s1", title: "The claim", body: `She said [the vote was rigged](cite:c1).${extra}` }, + { id: "s2", title: "Coverage", body: "One channel was read." }, + ], + }; +} + +function finishDraft(job) { + const { article, n, task } = job; + const it = readIt(article, n); + if (it.status === "cancelled") return; + const now = new Date().toISOString(); + if (task === "narrate") { + const steps = it.steps.map((s) => (s.task === "narrate" && s.jobId === job.id ? { ...s, status: "done", endedAt: now, minutes: 0.1, detail: "2 card(s) narrated" } : s)); + patchIt(article, n, { steps }); + job.status = "done"; + job.log.push("narrate: 2 card(s)", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`); + return; + } + const claude = it.model.startsWith("claude-"); + const usage = claude ? { [it.model]: { usd: 0.37, inputTokens: 41000, outputTokens: 2100, calls: 6 } } : {}; + const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [{ name: "strict-quotes", ok: true }] }; + if (it.kind === "sweep") { + writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, `Sweep: ${it.question ?? "a copy"}`), null, 2) + "\n"); + writeFileSync(path.join(itDir(article, n), "sweep.md"), `# Sweep\n\n## The claim\n\n- She said [the vote was rigged](https://priv.example/?v=sv1&t=3).\n`); + } else if (it.kind === "revise-report") { + writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, `Revised: ${it.feedback}`, " Nobody checked it."), null, 2) + "\n"); + patch.ops = { + applied: [{ index: 0, op: { op: "title", title: "Revised" } }, { index: 1, op: { op: "claim", finding: "f1", text: "Reworded" } }], + refused: [{ index: 2, op: { op: "drop", finding: "f9" }, why: "no finding f9" }], + }; + } else if (it.kind === "revise-video") { + const proj = path.join(GEN_PROJECTS, article, `i${n}`); + mkdirSync(proj, { recursive: true }); + writeFileSync(path.join(proj, "video.manifest.json"), JSON.stringify({ title: "The cut", timeline: [{ type: "card", id: "t0", heading: "Revised heading" }] }, null, 2)); + patch.projectDir = proj; + patch.ops = { applied: [{ index: 0, op: { op: "heading", card: "t0", heading: "Revised heading" } }], refused: [] }; + } + patchIt(article, n, patch); + job.status = "done"; + job.log.push("stub: wrote the iteration", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`); +} + +function startDraft(body) { + const { task, article } = body; + const now = new Date().toISOString(); + const id = `stub-draft-${nextJob++}`; + let n; + if (task === "narrate") { + n = body.iteration; + const it = readIt(article, n); + if (it.status !== "done") throw new Error(`"${article}" i${n} is ${it.status}: a narration runs over a done iteration`); + patchIt(article, n, { steps: [...it.steps, { task: "narrate", model: body.model ?? generation.models.local, status: "running", startedAt: now, jobId: id }] }); + } else { + n = nextN(article); + let base; + if (body.copyOf) { + const src = readIt(article, body.copyOf); + base = { kind: src.kind, parent: src.parent, copyOf: src.n, ...(src.question ? { question: src.question } : {}), ...(src.feedback ? { feedback: src.feedback } : {}), ...(src.scope ? { scope: src.scope } : {}) }; + } else if (task === "sweep") { + base = { kind: "sweep", parent: null, copyOf: null, question: body.question, scope: { channels: body.channels, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }; + } else { + const parent = readIt(article, body.iteration); + if (parent.status !== "done") throw new Error(`"${article}" i${parent.n} is ${parent.status}: only a done iteration is revised`); + base = { kind: task, parent: body.iteration, copyOf: null, feedback: body.feedback }; + } + const model = body.model ?? (generation.routes[task] === "local" ? generation.models.local : generation.models.api); + mkdirSync(itDir(article, n), { recursive: true }); + writeIt({ format: "archilyzer-iteration", version: 1, article, n, ...base, model, status: "queued", usage: {}, steps: [], jobId: id, createdAt: now, updatedAt: now }); + } + const slow = /slow/.test(String(body.question ?? body.feedback ?? "")); + const job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] }; + draftJobs.set(id, job); + job.timers.push( + setTimeout(() => { + job.status = "running"; + job.log.push("turn 1: reading the corpus (stub)"); + if (task !== "narrate") patchIt(article, n, { status: "running" }); + }, 1000), + ); + if (!slow) job.timers.push(setTimeout(() => finishDraft(job), 3000)); + return { jobId: id, iteration: n }; +} + +function cancelDraft(id) { + const job = draftJobs.get(id); + if (!job || !["queued", "running"].includes(job.status)) return false; + for (const t of job.timers) clearTimeout(t); + job.status = "cancelled"; + job.log.push("cancelled"); + const it = readIt(job.article, job.n); + if (job.task === "narrate") { + patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) }); + } else { + patchIt(job.article, job.n, { status: "cancelled", endedAt: new Date().toISOString() }); + } + return true; +} + +function readBody(req, then) { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + let body; + try { + body = JSON.parse(raw || "{}"); + } catch { + body = null; + } + then(body); + }); +} + +function generationRoute(req, res, url, auth) { + if (req.method === "GET" && url.pathname === "/api/ops/settings") { + req.resume(); + const value = { ...generation, apiKeyFile: "<redacted>" }; + return json(res, 200, url.searchParams.get("key") === "generation" ? { ok: true, key: "generation", value } : { ok: true, settings: { generation: value } }); + } + if (req.method === "POST" && url.pathname === "/api/ops/settings") { + return readBody(req, (body) => { + requests.push({ route: "settings", ...(body ?? {}), authorization: auth }); + record(); + const g = body?.patch?.generation; + if (!g || typeof g !== "object") return json(res, 400, { ok: false, error: '"patch" is required' }); + if ("apiKeyFile" in g) return json(res, 400, { ok: false, error: "the stub's settings take no apiKeyFile" }); + const caps = g.caps ? { ...g.caps } : null; + if (caps) { + for (const k of ["sweep", "revision", "narration"]) { + if (caps[k] > caps.max) return json(res, 400, { ok: false, error: `generation.caps.${k}: sent ${caps[k]}, would be saved as ${caps.max}` }); + } + } + for (const [k, v] of Object.entries(g)) generation[k] = v; + generation.preset = presetOf(generation.routes); + return json(res, 200, { ok: true, changed: ["generation"], value: { generation: { ...generation, apiKeyFile: "<redacted>" } } }); + }); + } + if (req.method === "GET" && url.pathname === "/api/ops/channels") { + req.resume(); + return json(res, 200, { + ok: true, + channels: [ + { slug: "sitechan", name: "Site Channel", kind: "video", platform: "youtube", handling: "youtube", url: null, sites: ["priv", "pub"] }, + { slug: "otherchan", name: "Other Channel", kind: "video", platform: "rumble", handling: "rumble", url: null, sites: [] }, + ], + }); + } + if (req.method === "POST" && url.pathname === "/api/ops/report-draft") { + return readBody(req, (body) => { + requests.push({ route: "report-draft", ...(body ?? {}), authorization: auth }); + record(); + if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" }); + if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" }); + try { + return json(res, 202, { ok: true, ...startDraft(body) }); + } catch (err) { + return json(res, 400, { ok: false, error: String(err.message) }); + } + }); + } + if (req.method === "POST" && url.pathname === "/api/ops/job") { + return readBody(req, (body) => { + requests.push({ route: "job", ...(body ?? {}), authorization: auth }); + record(); + const results = (body?.ids ?? []).map((id) => ({ id, ok: body?.verb === "cancel" && cancelDraft(id) })); + const ok = results.length > 0 && results.every((r) => r.ok); + return json(res, ok ? 200 : 400, { ok, results, ...(ok ? {} : { error: "not queued or running (or unknown)" }) }); + }); + } + const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && m && draftJobs.has(m[1])) { + req.resume(); + const j = draftJobs.get(m[1]); + const tail = Number(url.searchParams.get("tail") ?? 0); + return json(res, 200, { + ok: true, + job: { id: j.id, kind: "report-draft", status: j.status, ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}) }, + ...(tail ? { tail: j.log.slice(-tail) } : {}), + }); + } + return null; +} + const server = http.createServer((req, res) => { const url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`); @@ -89,6 +341,8 @@ const server = http.createServer((req, res) => { return json(res, 401, { error: "missing bearer token" }); } + if (url.pathname.startsWith("/api/ops/") && generationRoute(req, res, url, auth) !== null) return; + // THE OPS DOOR, stubbed alongside the media one. // // /api/report/tag forwards to the editor's /api/ops/tag-videos, and what a diff --git a/umtool/e2e/fixtures/iterations-fixture.mjs b/umtool/e2e/fixtures/iterations-fixture.mjs @@ -0,0 +1,134 @@ +// An article IN THE MAKING for the release 27 specs (article-compare, +// article-iterations): `zeta`, iterations and no report.json, so the registry +// does not list it (/articles shows it under "in the making"). Plus the usage +// ledger's row for today, which the policy's "today" reads. +// +// articles/zeta/iterations/ +// 1 sweep, claude-sonnet-5-5, done, $0.42; its report; a project with a cut +// 2 revise-report of i1, qwen3:8b, done: 2 ops applied, 1 refused, a strict +// check failed; its report (one finding reworded, a section added) +// 3 revise-video of i1, qwen3:8b, done: no report (i1's); its own cut +// 4 sweep, a copy of i1 on claude-haiku-4-5, failed +// gen-projects/zeta/i{1,3}/video.manifest.json +// generation-usage.jsonl today's row: $0.42 +// +// Synthetic, like every fixture: invented text, the fixture's own channel. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); +}; + +const AT = "2026-10-13T10:00:00.000Z"; +const CITE = { kind: "video", channel: "sitechan", id: "sv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew.", speaker: "Site Channel", date: "2024-03-15" }; + +const report = (sections) => ({ + format: "archilyzer-report", + version: 1, + id: "zeta", + kind: "sweep", + title: "Zeta: what the channel said about the vote", + citations: { c1: CITE }, + sections, +}); + +const iteration = (n, extra) => ({ + format: "archilyzer-iteration", + version: 1, + article: "zeta", + n, + parent: null, + copyOf: null, + status: "done", + usage: {}, + steps: [], + createdAt: AT, + updatedAt: AT, + endedAt: AT, + ...extra, +}); + +export function makeIterationsFixture({ dest, articles }) { + const dir = (n) => path.join(articles, "zeta", "iterations", String(n)); + const projects = path.join(dest, "gen-projects"); + const p1 = path.join(projects, "zeta", "i1"); + const p3 = path.join(projects, "zeta", "i3"); + + put(path.join(dir(1), "iteration.json"), iteration(1, { + kind: "sweep", + model: "claude-sonnet-5-5", + question: "What did the channel say about the vote?", + scope: { channels: ["sitechan"] }, + usage: { "claude-sonnet-5-5": { usd: 0.42, inputTokens: 52000, outputTokens: 3100, calls: 7 } }, + minutes: 2.5, + checks: [{ name: "strict-quotes", ok: true }], + projectDir: p1, + })); + put(path.join(dir(1), "report.json"), report([ + { id: "s1", title: "The claim", body: "She said [the vote was rigged](cite:c1) in the first stream." }, + { id: "s2", title: "Coverage", body: "One channel was read." }, + ])); + put(path.join(p1, "video.manifest.json"), { + title: "Zeta", + timeline: [ + { type: "card", id: "t0", heading: "Zeta", narration: { text: "What the channel said about the vote." } }, + { type: "clip", id: "a1", video: "sv1", channel: "sitechan", start: 3, end: 6, quote: "The vote was rigged" }, + ], + }); + + put(path.join(dir(2), "iteration.json"), iteration(2, { + kind: "revise-report", + model: "qwen3:8b", + parent: 1, + feedback: "Say when, and add what came later.", + minutes: 1.2, + ops: { + applied: [ + { index: 0, op: { op: "claim", finding: "f1", text: "In the first stream she said the vote was rigged." } }, + { index: 1, op: { op: "section", title: "Later" } }, + ], + refused: [{ index: 2, op: { op: "drop", finding: "f7" }, why: "no finding f7" }], + }, + checks: [{ name: "strict-quotes", ok: false, detail: "f2: a quote not found within ±90 s" }], + })); + put(path.join(dir(2), "report.json"), report([ + { id: "s1", title: "The claim", body: "In the first stream [she said the vote was rigged](cite:c1)." }, + { id: "s3", title: "Later", body: "The story changed again." }, + { id: "s2", title: "Coverage", body: "One channel was read." }, + ])); + + put(path.join(dir(3), "iteration.json"), iteration(3, { + kind: "revise-video", + model: "qwen3:8b", + parent: 1, + feedback: "A shorter title card.", + minutes: 0.8, + ops: { applied: [{ index: 0, op: { op: "narration", card: "t0", text: "The vote, in her words." } }], refused: [] }, + projectDir: p3, + })); + put(path.join(p3, "video.manifest.json"), { + title: "Zeta", + timeline: [ + { type: "card", id: "t0", heading: "Zeta", narration: { text: "The vote, in her words." } }, + { type: "clip", id: "a1", video: "sv1", channel: "sitechan", start: 3, end: 6, quote: "The vote was rigged" }, + ], + }); + + put(path.join(dir(4), "iteration.json"), iteration(4, { + kind: "sweep", + model: "claude-haiku-4-5", + copyOf: 1, + question: "What did the channel say about the vote?", + scope: { channels: ["sitechan"] }, + status: "failed", + error: "the model stopped at its cap", + usage: { "claude-haiku-4-5": { usd: 0.05, inputTokens: 30000, outputTokens: 900 } }, + })); + + const day = new Date().toISOString().slice(0, 10); + const ledger = path.join(dest, "generation-usage.jsonl"); + put(ledger, `${JSON.stringify({ at: AT, day, jobId: "fixture-1", article: "zeta", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 52000, outputTokens: 3100, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0.42 })}\n`); + return { projects, ledger }; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -23,6 +23,7 @@ import path from "node:path"; import { SONG_DATA } from "../../song/paths.mjs"; import { songCapabilities } from "./song-capabilities.mjs"; import { makeSitesFixture } from "./sites-fixture.mjs"; +import { makeIterationsFixture } from "./iterations-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1907,6 +1908,8 @@ writeProject("timeline-fixture", { }); const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); +// Release 27: an article in the making (zeta), its projects, today's usage. +makeIterationsFixture({ dest, articles: ARTICLES }); console.log(`fixture at ${dest}`); console.log(` SITES_DIR=${SITES}`); diff --git a/umtool/lib/articles/compare.ts b/umtool/lib/articles/compare.ts @@ -0,0 +1,126 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { readIteration, readIterationFile, reportSourceOf, iterationLabel, iterationUsd, type Iteration } from "yt-dlp-transcript-common/lib/report/iterations"; +import { parseReport } from "yt-dlp-transcript-common/lib/report/validate"; +import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; +import { sitesPaths } from "./sites"; + +// TWO ITERATIONS SIDE BY SIDE (release 27 S8, /articles/<id>/compare): each +// side's report (its sections and the findings in them), the ops its revision +// applied and refused, its checks that failed, and — when it has a project — +// its cut (the clips and the cards' narration). Read-only. + +export type CompareFinding = { text: string; cites: number }; +export type CompareSection = { title: string; findings: CompareFinding[] }; +export type CompareOp = { index: number; op: string; detail: string; why?: string }; +export type CompareCutEntry = { type: "card" | "clip"; id: string; heading?: string; narration?: string; quote?: string; span?: string }; + +export type CompareSide = { + n: number; + label: string; + kind: Iteration["kind"]; + model: string; + status: Iteration["status"]; + parent: number | null; + copyOf: number | null; + feedback: string | null; + question: string | null; + usd: number; + minutes: number | null; + /** The iteration whose report this side shows (itself, or the nearest ancestor that made one). */ + reportFrom: number | null; + title: string | null; + summary: string | null; + sections: CompareSection[]; + applied: CompareOp[]; + refused: CompareOp[]; + failedChecks: { name: string; detail: string | null }[]; + cut: { title: string | null; entries: CompareCutEntry[] } | null; +}; + +const CITE = /\]\(cite:[^)]+\)/g; + +// A section's findings: its claims, else its body's paragraphs (a sweep's +// findings are its paragraphs, each with its citing links). +function findingsOf(section: Report["sections"][number]): CompareFinding[] { + if (section.claims?.length) { + return section.claims.map((c) => ({ text: c.text, cites: (c.citations?.length ?? 0) + (c.text.match(CITE)?.length ?? 0) })); + } + return (section.body ?? "") + .split(/\n\s*\n/) + .map((p) => p.trim()) + .filter(Boolean) + .map((p) => ({ text: p.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "“$1”"), cites: p.match(CITE)?.length ?? 0 })); +} + +function opOf(raw: unknown): CompareOp { + const r = (raw ?? {}) as { index?: number; op?: Record<string, unknown>; why?: string }; + const op = r.op ?? {}; + const { op: name, ...rest } = op as { op?: string } & Record<string, unknown>; + const detail = JSON.stringify(rest); + return { + index: typeof r.index === "number" ? r.index : 0, + op: String(name ?? "?"), + detail: detail.length > 220 ? `${detail.slice(0, 217)}…` : detail, + ...(r.why ? { why: String(r.why) } : {}), + }; +} + +async function cutOf(projectDir: string | undefined): Promise<CompareSide["cut"]> { + if (!projectDir) return null; + let manifest: { title?: string; timeline?: Record<string, unknown>[] }; + try { + manifest = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(projectDir, "video.manifest.json"), "utf8")); + } catch { + return null; + } + const entries: CompareCutEntry[] = []; + for (const e of manifest.timeline ?? []) { + const id = String(e.id ?? ""); + if (e.type === "card") { + const narration = (e.narration as { text?: string } | undefined)?.text; + entries.push({ type: "card", id, heading: String(e.heading ?? e.title ?? id), ...(narration ? { narration } : {}) }); + } else if (e.type === "clip") { + const span = typeof e.start === "number" && typeof e.end === "number" ? `${e.video ?? ""} ${e.start}–${e.end}` : undefined; + entries.push({ type: "clip", id, ...(e.quote ? { quote: String(e.quote) } : {}), ...(span ? { span } : {}) }); + } + } + return { title: manifest.title ?? null, entries }; +} + +export async function readCompareSide(article: string, n: number): Promise<CompareSide | null> { + const paths = sitesPaths(); + const it = await readIteration(article, n, paths); + if (!it) return null; + const from = await reportSourceOf(article, n, paths).catch(() => null); + let report: Report | null = null; + if (from !== null) { + try { + const parsed = parseReport(JSON.parse((await readIterationFile(article, from, "report.json", paths)) ?? ""), { id: article }); + report = parsed.ok ? parsed.value : null; + } catch { + report = null; + } + } + return { + n, + label: iterationLabel(n), + kind: it.kind, + model: it.model, + status: it.status, + parent: it.parent, + copyOf: it.copyOf, + feedback: it.feedback ?? null, + question: it.question ?? null, + usd: iterationUsd(it), + minutes: it.minutes ?? null, + reportFrom: from, + title: report?.title ?? null, + summary: report?.summary ?? null, + sections: (report?.sections ?? []).map((s) => ({ title: s.title, findings: findingsOf(s) })), + applied: (it.ops?.applied ?? []).map(opOf), + refused: (it.ops?.refused ?? []).map(opOf), + failedChecks: (it.checks ?? []).filter((c) => !c.ok).map((c) => ({ name: c.name, detail: c.detail ?? null })), + cut: await cutOf(it.projectDir), + }; +} diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -0,0 +1,407 @@ +import { readFileSync, statSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; +import { + iterationLabel, + iterationUsd, + readIterationFile, + readIterations, + type Iteration, + type IterationsCurrent, +} from "yt-dlp-transcript-common/lib/report/iterations"; +import { dayUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { + DEFAULT_API_KEY_FILE, + GENERATION_PRESETS, + GENERATION_ROUTES, + GENERATION_TASKS, + sanitizeGeneration, + type GenerationSettings, +} from "yt-dlp-transcript-common/lib/generationSettings"; +import { PRICES } from "yt-dlp-transcript-common/lib/llm/prices"; +import { agentToken } from "@/lib/annotations/agentAuth.mjs"; +import { CHAIN_STEPS, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, doneSteps } from "@/lib/report/chain.mjs"; +import { recentJobs, type Job } from "@/lib/jobs"; +import { sitesPaths } from "./sites"; + +// GENERATION, AS UMTOOL SEES IT (release 27 S8): an article's iterations, the +// policy, the editor's channels, and the editor's report-draft jobs. +// +// UMTOOL WRITES NOTHING OF THE CORPUS HERE. A generation is a `report-draft` +// job the EDITOR runs and writes (POST /api/ops/report-draft); the policy is +// the editor's settings (POST /api/ops/settings); a job is cancelled there +// (POST /api/ops/job). Each call carries the shared WORKER_TOKEN, which never +// reaches the browser. What this module reads directly is read-only: the +// iterations store (common's reader) and the usage ledger's day total. +// +// The API KEY is never read, shown or accepted: the policy names the key +// FILE's path and whether it exists — a stat, never an open. +// +// SERVER-ONLY. + +const DEFAULT_EDITOR = "http://localhost:3001"; + +export function editorUrl(): string { + return (process.env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""); +} + +export class EditorError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + } +} + +/** + * Ask the editor's ops API. Answers its JSON; an editor that refuses (`ok: + * false`, or a non-2xx) throws an EditorError carrying its words and status. + */ +export async function askEditor<T = Record<string, unknown>>( + route: string, + init: { method?: "GET" | "POST"; body?: unknown } = {}, +): Promise<T> { + const token = agentToken(); + if (!token) { + throw new EditorError( + "WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with.", + 400, + ); + } + let res: Response; + try { + res = await fetch(`${editorUrl()}${route}`, { + method: init.method ?? "GET", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), + cache: "no-store", + }); + } catch (err) { + throw new EditorError(`could not reach the editor at ${editorUrl()}: ${(err as Error).message}`, 502); + } + const body = (await res.json().catch(() => ({}))) as Record<string, unknown>; + if (!res.ok || body.ok === false) { + const status = res.status >= 400 ? res.status : 400; + throw new EditorError(String(body.error ?? `the editor answered HTTP ${res.status}`), status); + } + return body as T; +} + +/** A route's answer for an error: the editor's status and words, else a 500. */ +export function errorResponse(err: unknown): Response { + const status = err instanceof EditorError ? err.status : 500; + return Response.json({ error: (err as Error).message }, { status, headers: { "cache-control": "no-store" } }); +} + +// ─── The policy ─── + +export type PolicyView = { + generation: GenerationSettings; + presets: Record<string, Record<string, string>>; + tasks: readonly string[]; + routes: readonly string[]; + /** The key file's path (as configured, `~` kept) and whether a file is there. Never its content. */ + keyFile: { path: string; exists: boolean }; + /** The models a picker offers: Claude's priced ones, and the local route's. */ + models: { api: string[]; local: string[] }; +}; + +const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p); + +/** + * The key file's configured path. The editor's settings read redacts it (its + * name reads as a secret), so it is read from the checkout's settings.json, + * as the chain reads `projectsRoot` (SETTINGS_FILE overrides). + */ +function configuredKeyFile(): string { + const file = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); + try { + const v = JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8"))?.generation?.apiKeyFile; + return typeof v === "string" && v.trim() ? sanitizeGeneration({ apiKeyFile: v }).apiKeyFile : DEFAULT_API_KEY_FILE; + } catch { + return DEFAULT_API_KEY_FILE; + } +} + +function keyFileExists(p: string): boolean { + try { + return statSync(/* turbopackIgnore: true */ expandHome(p)).isFile(); + } catch { + return false; + } +} + +export async function readPolicy(): Promise<PolicyView> { + const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation"); + const raw = (answer.value ?? {}) as Record<string, unknown>; + const generation = sanitizeGeneration(raw); + const keyPath = typeof raw.apiKeyFile === "string" && raw.apiKeyFile !== "<redacted>" ? generation.apiKeyFile : configuredKeyFile(); + generation.apiKeyFile = keyPath; + const claude = Object.keys(PRICES).filter((m) => m.startsWith("claude-")); + const api = [...new Set([generation.models.api, generation.models.extractor, ...claude].filter((m) => m.startsWith("claude-")))]; + const local = [...new Set([generation.models.local, "qwen3:8b"])]; + return { + generation, + presets: GENERATION_PRESETS as unknown as Record<string, Record<string, string>>, + tasks: GENERATION_TASKS, + routes: GENERATION_ROUTES, + keyFile: { path: keyPath, exists: keyFileExists(keyPath) }, + models: { api, local }, + }; +} + +// What umtool may write of `generation`. The key file's path is not here: the +// panel shows it, and the editor's own settings page sets it. +const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl"] as const; + +/** Write the policy through the editor's settings action. Answers the policy as read back. */ +export async function writePolicy(patch: Record<string, unknown>): Promise<PolicyView> { + const out: Record<string, unknown> = {}; + for (const [k, v] of Object.entries(patch)) { + if (!(POLICY_KEYS as readonly string[]).includes(k)) { + throw new EditorError(`"${k}" is not written here — the policy writes ${POLICY_KEYS.join(", ")}`, 400); + } + out[k] = v; + } + if (!Object.keys(out).length) throw new EditorError("nothing to change", 400); + await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: out } } }); + return readPolicy(); +} + +// ─── The editor's channels ─── + +export type EditorChannel = { slug: string; name: string; kind: string; platform: string | null; sites: string[] }; + +export async function listEditorChannels(): Promise<EditorChannel[]> { + const answer = await askEditor<{ channels?: EditorChannel[] }>("/api/ops/channels"); + return (answer.channels ?? []) + .map((c) => ({ slug: c.slug, name: c.name ?? c.slug, kind: c.kind ?? "video", platform: c.platform ?? null, sites: c.sites ?? [] })) + .sort((a, b) => a.name.localeCompare(b.name)); +} + +// ─── The editor's jobs ─── + +export type DraftJobView = { + id: string; + kind: string | null; + status: string; + queue: { key?: string; position?: number } | null; + tail: string[]; +}; + +export async function readDraftJob(id: string, tail = 12): Promise<DraftJobView> { + if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new EditorError(`"${id}" is not a job id`, 400); + const n = Math.max(1, Math.min(200, Math.floor(tail))); + const answer = await askEditor<{ job?: Record<string, unknown>; queue?: Record<string, unknown>; tail?: string[] }>( + `/api/ops/job/${id}?tail=${n}`, + ); + const job = answer.job ?? {}; + const queue = (answer.queue ?? job.queue ?? null) as DraftJobView["queue"]; + return { + id, + kind: typeof job.kind === "string" ? job.kind : null, + status: String(job.status ?? "unknown"), + queue, + tail: Array.isArray(answer.tail) ? answer.tail.map(String) : [], + }; +} + +export async function cancelDraftJob(id: string): Promise<void> { + if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new EditorError(`"${id}" is not a job id`, 400); + await askEditor("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [id] } }); +} + +// The body umtool sends to `report-draft`: the action's own keys, nothing else +// (the editor refuses an unknown key; this refuses it first, by name). +const DRAFT_KEYS = ["task", "article", "iteration", "model", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "force"]; + +export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> { + const out: Record<string, unknown> = {}; + for (const [k, v] of Object.entries(body)) { + if (v === undefined || v === null || v === "") continue; + if (!DRAFT_KEYS.includes(k)) throw new EditorError(`"${k}" is not a report-draft key`, 400); + out[k] = v; + } + const answer = await askEditor<{ jobId: string; iteration: number }>("/api/ops/report-draft", { method: "POST", body: out }); + return { jobId: answer.jobId, iteration: answer.iteration }; +} + +// ─── An article's iterations ─── + +export type IterationRow = { + n: number; + label: string; + kind: Iteration["kind"]; + model: string; + parent: number | null; + copyOf: number | null; + status: Iteration["status"]; + error: string | null; + question: string | null; + feedback: string | null; + scope: Iteration["scope"] | null; + usage: { model: string; usd: number; inputTokens: number; outputTokens: number }[]; + usd: number; + minutes: number | null; + ops: { applied: number; refused: number }; + checks: { name: string; ok: boolean; detail: string | null }[]; + steps: { task: string; model: string | null; status: string; cost: number | null; minutes: number | null; detail: string | null; jobId: string | null }[]; + jobId: string | null; + createdAt: string; + endedAt: string | null; + /** It made a report.json of its own. */ + hasReport: boolean; + /** The iteration whose report it carries (itself, or the nearest ancestor that made one). */ + reportFrom: number | null; + projectDir: string | null; + hasManifest: boolean; + currentReport: boolean; + currentVideo: boolean; +}; + +export type ChainView = { + steps: { name: string; label: string; status: string }[]; + /** Where a start resumes: the first step not done, or null (all done). */ + resumeAt: string | null; + job: { id: string; state: string; stepIndex: number; of: number; label: string; error: string | null; log: string[] } | null; +}; + +export type ArticleIterations = { + article: string; + /** No report.json yet: an article in the making. */ + pending: boolean; + iterations: IterationRow[]; + problems: { n: number; problems: string[] }[]; + current: IterationsCurrent; + /** Something is queued or running (the page polls while it is). */ + busy: boolean; +}; + +const exists = (p: string) => { + try { + return statSync(/* turbopackIgnore: true */ p).isFile(); + } catch { + return false; + } +}; + +function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number, Iteration>, current: IterationsCurrent): IterationRow { + let reportFrom: number | null = null; + for (let at: number | null = it.n; at !== null; at = byN.get(at)?.parent ?? null) { + if (hasReport.get(at)) { + reportFrom = at; + break; + } + if (!byN.has(at)) break; + } + const projectDir = it.projectDir ?? null; + return { + n: it.n, + label: iterationLabel(it.n), + kind: it.kind, + model: it.model, + parent: it.parent, + copyOf: it.copyOf, + status: it.status, + error: it.error ?? null, + question: it.question ?? null, + feedback: it.feedback ?? null, + scope: it.scope ?? null, + usage: Object.entries(it.usage).map(([model, u]) => ({ model, usd: u.usd, inputTokens: u.inputTokens, outputTokens: u.outputTokens })), + usd: iterationUsd(it), + minutes: it.minutes ?? null, + ops: { applied: it.ops?.applied.length ?? 0, refused: it.ops?.refused.length ?? 0 }, + checks: (it.checks ?? []).map((c) => ({ name: c.name, ok: c.ok, detail: c.detail ?? null })), + steps: it.steps.map((s) => ({ + task: s.task, + model: s.model ?? null, + status: s.status, + cost: s.cost ?? null, + minutes: s.minutes ?? null, + detail: s.detail ?? null, + jobId: s.jobId ?? null, + })), + jobId: it.jobId ?? null, + createdAt: it.createdAt, + endedAt: it.endedAt ?? null, + hasReport: hasReport.get(it.n) ?? false, + reportFrom, + projectDir, + hasManifest: projectDir ? exists(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")) : false, + currentReport: current.report === it.n, + currentVideo: current.video === it.n, + }; +} + +export async function readArticleIterations(article: string): Promise<ArticleIterations> { + const paths = sitesPaths(); + const read = await readIterations(article, paths); + const hasReport = new Map<number, boolean>(); + for (const it of read.iterations) hasReport.set(it.n, (await readIterationFile(article, it.n, "report.json", paths)) !== null); + const byN = new Map(read.iterations.map((it) => [it.n, it])); + const rows = read.iterations.map((it) => rowOf(it, hasReport, byN, read.current)).reverse(); + return { + article, + pending: !exists(path.join(/* turbopackIgnore: true */ paths.articlesDir, article, "report.json")), + iterations: rows, + problems: read.problems, + current: read.current, + busy: rows.some((r) => r.status === "queued" || r.status === "running"), + }; +} + +/** The articles in the making, each with its newest iteration. */ +export async function readPendingArticles(): Promise<{ id: string; newest: IterationRow | null; count: number }[]> { + const ids = await listPendingArticles(sitesPaths()); + return Promise.all( + ids.map(async (id) => { + const its = await readArticleIterations(id).catch(() => null); + return { id, newest: its?.iterations[0] ?? null, count: its?.iterations.length ?? 0 }; + }), + ); +} + +/** The day's API spend (UTC), from the editor's usage ledger, against the daily cap. */ +export async function readToday(daily: number): Promise<{ day: string; usd: number; jobs: number; daily: number }> { + const d = await dayUsage(getPaths().generationUsageFile); + return { ...d, daily }; +} + +// ─── The chain ("make the video") ─── + +/** The chain job's kind for an iteration, as lib/jobs.ts records it. */ +export const chainKind = (article: string, n: number) => `chain ${article} ${iterationLabel(n)}`; + +/** The projects root the editor's policy names (`~` expanded), else the default. */ +export function projectsRootOf(gen: GenerationSettings): string { + return gen.projectsRoot ? expandHome(gen.projectsRoot) : DEFAULT_PROJECTS_ROOT; +} + +export function chainViewOf(article: string, it: IterationRow): ChainView { + const done = new Set(doneSteps({ steps: it.steps })); + const byTask = new Map(it.steps.map((s) => [s.task, s.status])); + const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n)); + return { + steps: CHAIN_STEPS.map((s: { name: string; label: string }) => ({ + name: s.name, + label: s.label, + status: byTask.get(`chain:${s.name}`) ?? "pending", + })), + // chain.mjs's JSDoc types `done` by its default ([]), so it is cast. + resumeAt: (chainStart as (o: { done: string[] }) => string | null)({ done: [...done] }), + job: job + ? { + id: job.id, + state: job.state, + stepIndex: job.stepIndex, + of: job.steps.length, + label: job.steps[job.stepIndex]?.label ?? "", + error: job.error, + log: job.log.slice(-12), + } + : null, + }; +} diff --git a/umtool/lib/drafts.ts b/umtool/lib/drafts.ts @@ -1,428 +0,0 @@ -import { execFileSync, spawn } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -// Report drafts with no Claude Code (proof of concept, 2026-10-12). A page over -// the scripts in ~/reports/local-reports (its RUNBOOK.html): a sweep by a local -// model (bin/local-sweep, ollama) or by Claude on an API key (bin/api-sweep), -// then the article, the narration draft and the video. Each step runs DETACHED, -// its log and exit code in the run's directory, so a run outlives a restart and -// its state is read off the disk, never kept in memory. Arguments reach the -// scripts as argv, never through a shell string. - -export const LOCAL_REPORTS = process.env.LOCAL_REPORTS_DIR ?? path.join(os.homedir(), "reports/local-reports"); -const RUNS = path.join(LOCAL_REPORTS, "runs"); - -export const MODELS = ["qwen3:8b", "claude-sonnet-5-5", "claude-sonnet-5", "claude-opus-5-5"] as const; -export const STEPS = ["sweep", "article", "narrate", "video"] as const; -export type Step = (typeof STEPS)[number]; - -export type RunMeta = { - name: string; - question: string; - channels: string; - model: string; - id: string; - terms?: string; - maxUsd?: number; - createdAt: string; - // A VERSION (lib/drafts "new version"): what it revises, from which run, by what feedback. Its video project is - // its own (videos/<project>); a first draft's project is its article id. - kind?: "sweep" | "revise-report" | "revise-video"; - parent?: string; - version?: number; - feedback?: string; - project?: string; - // A copy of another run (same base, another model) — to compare models on the same work. - copyOf?: string; -}; - -export type StepState = { state: "idle" | "running" | "done" | "failed" | "cancelled"; exit?: number; tail?: string }; -export type RunView = RunMeta & { - steps: Record<Step, StepState>; - files: string[]; - usd?: number; - narrationReview: string; - version: number; - currentArticle: boolean; - currentVideo: boolean; -}; - -const projectOf = (m: RunMeta) => m.project ?? m.id; -const exitMtime = (dir: string, step: Step): number => { - const f = path.join(dir, `ui-${step}.exit`); - try { - return readFileSync(f, "utf8").trim() === "0" ? statSync(f).mtimeMs : 0; - } catch { - return 0; - } -}; - -const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/; -const CHANNELS = /^[a-z0-9_-]+(,[a-z0-9_-]+)*$/; - -export function runDir(name: string): string { - if (!NAME.test(name)) throw new Error(`bad run name: ${name}`); - return path.join(RUNS, name); -} - -function stepState(dir: string, step: Step): StepState { - const log = path.join(dir, `ui-${step}.log`); - if (!existsSync(log)) return { state: "idle" }; - const tail = readFileSync(log, "utf8").split("\n").slice(-14).join("\n"); - const ex = path.join(dir, `ui-${step}.exit`); - if (!existsSync(ex)) return { state: "running", tail }; - const raw = readFileSync(ex, "utf8").trim(); - if (raw === "cancelled") return { state: "cancelled", tail }; - const exit = Number(raw); - return { state: exit === 0 ? "done" : "failed", exit, tail }; -} - -export function listRuns(): RunView[] { - if (!existsSync(RUNS)) return []; - const out: (RunView & { aT: number; vT: number })[] = []; - for (const name of readdirSync(RUNS)) { - const dir = path.join(RUNS, name); - const metaFile = path.join(dir, "ui.json"); - if (!existsSync(metaFile)) continue; - const meta = JSON.parse(readFileSync(metaFile, "utf8")) as RunMeta; - const steps = Object.fromEntries(STEPS.map((s) => [s, stepState(dir, s)])) as Record<Step, StepState>; - let usd: number | undefined; - for (const f of ["run.json", "revise.json"]) { - try { - const v = JSON.parse(readFileSync(path.join(dir, f), "utf8")).usd_estimate; - if (typeof v === "number" && Number.isFinite(v)) usd = (usd ?? 0) + v; // a local run has no cost - } catch {} - } - out.push({ - ...meta, - steps, - usd, - files: ["sweep.md", "review.html", "run.json", "revise.json"].filter((f) => existsSync(path.join(dir, f))), - narrationReview: `/browse/local-reports/videos/${projectOf(meta)}/narration`, - version: meta.version ?? 1, - currentArticle: false, - currentVideo: false, - aT: exitMtime(dir, "article"), - vT: exitMtime(dir, "video"), - }); - } - // The article and its video are whichever version last wrote them. - for (const id of new Set(out.map((r) => r.id))) { - const mine = out.filter((r) => r.id === id); - const a = mine.reduce((b, r) => (r.aT > (b?.aT ?? 0) ? r : b), undefined as (typeof out)[number] | undefined); - const v = mine.reduce((b, r) => (r.vT > (b?.vT ?? 0) ? r : b), undefined as (typeof out)[number] | undefined); - if (a) a.currentArticle = true; - if (v) v.currentVideo = true; - } - return out - .map(({ aT: _a, vT: _v, ...r }) => r) - .sort((a, b) => (a.id === b.id ? b.version - a.version : b.createdAt.localeCompare(a.createdAt))); -} - -/** A new version of a run: a revision of its report or of its video, by feedback, on a model. */ -export function createVersion(parentName: string, input: { - what: "report" | "video"; - model: string; - feedback: string; - maxUsd?: number; -}): RunMeta { - const parent = JSON.parse(readFileSync(path.join(runDir(parentName), "ui.json"), "utf8")) as RunMeta; - if (!input.feedback.trim()) throw new Error("say what to change"); - if (!(MODELS as readonly string[]).includes(input.model)) throw new Error(`model: one of ${MODELS.join(", ")}`); - if (input.what === "video" && !existsSync(path.join(LOCAL_REPORTS, "videos", projectOf(parent), "video.manifest.json"))) { - throw new Error("this version has no video project yet — run its article step first"); - } - const root = parent.name.replace(/-v\d+$/, ""); - const taken = existsSync(RUNS) ? readdirSync(RUNS).filter((n) => n === root || n.startsWith(`${root}-v`)) : []; - const version = Math.max(1, ...taken.map((n) => Number(n.match(/-v(\d+)$/)?.[1] ?? 1))) + 1; - const name = `${root}-v${version}`; - mkdirSync(runDir(name), { recursive: true }); - const meta: RunMeta = { - name, - question: parent.question, - channels: parent.channels, - model: input.model, - id: parent.id, - createdAt: new Date().toISOString(), - kind: input.what === "report" ? "revise-report" : "revise-video", - parent: parent.name, - version, - feedback: input.feedback.trim(), - project: name, - ...(input.maxUsd ? { maxUsd: input.maxUsd } : {}), - }; - writeFileSync(path.join(runDir(name), "ui.json"), JSON.stringify(meta, null, 2)); - return meta; -} - -/** A copy of a run on another model: the same question (a sweep) or the same parent and feedback (a revision). It is - * a version of the same article, made current only when its own article/video step runs. */ -export function copyRun(name: string, model: string): RunMeta { - const src = JSON.parse(readFileSync(path.join(runDir(name), "ui.json"), "utf8")) as RunMeta; - if (!(MODELS as readonly string[]).includes(model)) throw new Error(`model: one of ${MODELS.join(", ")}`); - const root = src.name.replace(/-v\d+$/, ""); - const taken = readdirSync(RUNS).filter((n) => n === root || n.startsWith(`${root}-v`)); - const version = Math.max(1, ...taken.map((n) => Number(n.match(/-v(\d+)$/)?.[1] ?? 1))) + 1; - const newName = `${root}-v${version}`; - mkdirSync(runDir(newName), { recursive: true }); - const meta: RunMeta = { - ...src, - name: newName, - model, - version, - project: newName, - copyOf: src.name, - kind: src.kind ?? "sweep", - createdAt: new Date().toISOString(), - }; - writeFileSync(path.join(runDir(newName), "ui.json"), JSON.stringify(meta, null, 2)); - return meta; -} - -/** Two runs side by side: each one's report (or, for a video version, its cut), cost and ops. */ -export function compareHtml(a: string, b: string): string { - const esc = (t: string) => t.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]!); - const col = (name: string) => { - const dir = runDir(name); - const m = JSON.parse(readFileSync(path.join(dir, "ui.json"), "utf8")) as RunMeta; - const read = (f: string) => (existsSync(f) ? readFileSync(f, "utf8") : ""); - let body = read(path.join(dir, "sweep.md")); - const proj = path.join(LOCAL_REPORTS, "videos", projectOf(m)); - if (m.kind === "revise-video" || !body) { - const man = read(path.join(proj, "video.manifest.json")); - if (man) { - const j = JSON.parse(man) as { title?: string; timeline?: { type: string; id: string; heading?: string; quote?: string; narration?: { text?: string } }[] }; - body = `${body ? `${body}\n\n── video cut ──\n` : ""}TITLE: ${j.title ?? ""}\n` + (j.timeline ?? []).map((e) => - e.type === "card" ? `▌ ${e.heading ?? e.id}${e.narration?.text ? `\n 🔊 ${e.narration.text}` : ""}` : ` ▶ ${e.id} “${e.quote ?? ""}”`).join("\n"); - } - } - const rev = read(path.join(dir, "revise.json")) || read(path.join(proj, "revise.json")); - let cost = ""; - for (const f of [path.join(dir, "run.json"), path.join(dir, "revise.json"), path.join(proj, "revise.json")]) { - try { - const u = JSON.parse(read(f)).usd_estimate; - if (typeof u === "number") cost = `~$${u.toFixed(2)}`; - } catch {} - } - let ops = ""; - try { - const r = JSON.parse(rev); - ops = `${r.applied?.length ?? 0} op(s) applied, ${r.refused?.length ?? 0} refused`; - } catch {} - return `<section><h2>v${m.version ?? 1} · ${esc(m.name)}</h2><p class="m">${esc(m.model)} ${cost} ${ops}${m.feedback ? ` · “${esc(m.feedback)}”` : ""}${m.copyOf ? ` · copy of ${esc(m.copyOf)}` : ""}</p><pre>${esc(body || "(nothing yet)")}</pre></section>`; - }; - const id = (JSON.parse(readFileSync(path.join(runDir(a), "ui.json"), "utf8")) as RunMeta).id; - return `<!doctype html><meta charset="utf-8"><title>compare ${esc(a)} · ${esc(b)}</title><style> -body{font:13px/1.45 system-ui;margin:0;background:#111;color:#ddd}header{padding:8px 12px;border-bottom:1px solid #333} -a{color:#8cf}main{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:12px}section{min-width:0} -h2{font-size:14px;margin:0}.m{color:#999;margin:2px 0 8px}pre{white-space:pre-wrap;word-break:break-word;background:#1a1a1a;padding:8px;border-radius:4px} -@media (max-width:800px){main{grid-template-columns:1fr}}</style> -<header><a href="/drafts">← drafts</a> · <a href="/articles/${esc(id)}">the article (${esc(id)})</a></header><main>${col(a)}${col(b)}</main>`; -} - -/** The channels the composed builds hold (the sweeps read a build): slug, name, videos, which builds. */ -export function listChannels(): { slug: string; name: string; videos: number; builds: string[] }[] { - const root = path.join(LOCAL_REPORTS_REPO(), "export/.export-builds"); - const by = new Map<string, { slug: string; name: string; videos: number; builds: string[] }>(); - if (!existsSync(root)) return []; - for (const b of readdirSync(root)) { - const f = path.join(root, b, "out", "corpus.json"); - if (!existsSync(f)) continue; - try { - const c = JSON.parse(readFileSync(f, "utf8")) as { channels?: { slug?: string; name?: string; videoCount?: number }[] }; - for (const ch of c.channels ?? []) { - if (!ch.slug) continue; - const cur = by.get(ch.slug) ?? { slug: ch.slug, name: ch.name ?? ch.slug, videos: 0, builds: [] }; - cur.videos = Math.max(cur.videos, Number(ch.videoCount ?? 0)); - cur.builds.push(b); - by.set(ch.slug, cur); - } - } catch {} - } - return [...by.values()].sort((a, b) => a.name.localeCompare(b.name)); -} -const LOCAL_REPORTS_REPO = () => process.env.ARCHILYZER_REPO ?? path.join(os.homedir(), "Projects/yt-dlp-transcript-browser"); - -// ─── the generation policy (~/.config/archilyzer/generation.json; bin/gen reads the same file) ─── -export const GEN_TASKS = ["sweep", "revise-report", "revise-video", "narrate"] as const; -export type Route = "code" | "api" | "local"; -export type GenPolicy = { preset: string; routes: Record<string, Route>; models: { api: string; local: string } }; -const POLICY = path.join(os.homedir(), ".config/archilyzer/generation.json"); -export const PRESETS: Record<string, Record<string, Route>> = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code" }, - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local" }, -}; -export function readPolicy(): GenPolicy { - try { - return JSON.parse(readFileSync(POLICY, "utf8")) as GenPolicy; - } catch { - return { preset: "balanced", routes: { ...PRESETS.balanced }, models: { api: "claude-sonnet-5-5", local: "qwen3:8b" } }; - } -} -export function writePolicy(p: GenPolicy): GenPolicy { - for (const [k, v] of Object.entries(p.routes)) { - if (!(GEN_TASKS as readonly string[]).includes(k) || !["code", "api", "local"].includes(v)) throw new Error(`bad route ${k}=${v}`); - } - if (!(MODELS as readonly string[]).includes(p.models.api) || !(MODELS as readonly string[]).includes(p.models.local)) { - throw new Error("unknown model"); - } - mkdirSync(path.dirname(POLICY), { recursive: true }); - writeFileSync(`${POLICY}.tmp`, JSON.stringify(p, null, 2)); - renameSync(`${POLICY}.tmp`, POLICY); - return p; -} - -export function createRun(input: { - name: string; - question: string; - channels: string; - model: string; - id?: string; - terms?: string; - maxUsd?: number; -}): RunMeta { - const dir = runDir(input.name); - if (existsSync(path.join(dir, "ui.json"))) throw new Error(`run ${input.name} exists`); - if (!input.question.trim()) throw new Error("no question"); - if (!CHANNELS.test(input.channels)) throw new Error("channels: comma-separated slugs"); - if (!(MODELS as readonly string[]).includes(input.model)) throw new Error(`model: one of ${MODELS.join(", ")}`); - const id = input.id || input.name; - if (!NAME.test(id)) throw new Error(`bad article id: ${id}`); - mkdirSync(dir, { recursive: true }); - const meta: RunMeta = { - name: input.name, - question: input.question.trim(), - channels: input.channels, - model: input.model, - id, - ...(input.terms ? { terms: input.terms } : {}), - ...(input.maxUsd ? { maxUsd: input.maxUsd } : {}), - createdAt: new Date().toISOString(), - }; - writeFileSync(path.join(dir, "ui.json"), JSON.stringify(meta, null, 2)); - return meta; -} - -function argvFor(step: Step, m: RunMeta, dir: string, narrateModel: string): string[] { - const bin = (b: string) => path.join(LOCAL_REPORTS, "bin", b); - const claude = m.model.startsWith("claude-"); - const usd = ["--max-usd", String(m.maxUsd ?? (m.kind && m.kind !== "sweep" ? 2 : 5))]; - switch (step) { - case "sweep": - if (m.kind === "revise-report") { - return [bin("revise"), "report", runDir(m.parent!), "--out", dir, "--feedback", m.feedback!, "--model", m.model, - "--id", m.id, ...usd]; - } - if (m.kind === "revise-video") { - const parent = JSON.parse(readFileSync(path.join(runDir(m.parent!), "ui.json"), "utf8")) as RunMeta; - return [bin("revise"), "video", path.join(LOCAL_REPORTS, "videos", projectOf(parent)), "--out", - path.join(LOCAL_REPORTS, "videos", projectOf(m)), "--feedback", m.feedback!, "--model", m.model, ...usd]; - } - return claude - ? [bin("api-sweep"), m.question, "--channels", m.channels, "--id", m.id, "--out", dir, "--model", m.model, - ...usd, ...(m.terms ? ["--terms", m.terms] : [])] - : [bin("local-sweep"), m.question, "--channels", m.channels, "--id", m.id, "--out", dir, "--model", m.model, - "--max-videos", "15", "--max-claims", "15", ...(m.terms ? ["--terms", m.terms] : [])]; - case "article": - if (m.kind === "revise-video") throw new Error("a video version keeps its parent's article — run narrate, then video"); - return [bin("local-article"), dir, m.id]; - case "narrate": - return [bin("local-narrate"), path.join(LOCAL_REPORTS, "videos", projectOf(m)), "--model", narrateModel]; - case "video": - return [bin("local-video"), m.id]; - } -} - -function envFor(m: RunMeta): Record<string, string> { - const env: Record<string, string> = { LR_PROJECT: projectOf(m) }; - if (m.parent && m.kind === "revise-report") { - try { - env.LR_PARENT_PROJECT = projectOf(JSON.parse(readFileSync(path.join(runDir(m.parent), "ui.json"), "utf8")) as RunMeta); - } catch {} - } - return env; -} - -export function startStep(name: string, step: Step, model?: string): void { - const dir = runDir(name); - const meta = JSON.parse(readFileSync(path.join(dir, "ui.json"), "utf8")) as RunMeta; - if (stepState(dir, step).state === "running") throw new Error(`${step} is already running`); - const pick = model && (MODELS as readonly string[]).includes(model) ? model : undefined; - if (pick && step === "sweep" && pick !== meta.model) { - meta.model = pick; // the run's draft (sweep or revision) is re-run on the model picked for it - writeFileSync(path.join(dir, "ui.json"), JSON.stringify(meta, null, 2)); - } - const nm = pick ?? meta.model; - const argv = argvFor(step, meta, dir, nm); - const log = path.join(dir, `ui-${step}.log`); - const ex = path.join(dir, `ui-${step}.exit`); - rmSync(ex, { force: true }); - writeFileSync(log, `$ ${argv.map((a) => a.replace(os.homedir(), "~")).join(" ")}\n`); - const tmp = path.join(os.homedir(), ".cache/local-reports"); - mkdirSync(tmp, { recursive: true }); - const child = spawn("bash", ["-c", '"$@" >> "$UI_LOG" 2>&1; echo $? > "$UI_EXIT"', "ui-step", ...argv], { - detached: true, - stdio: "ignore", - env: { ...process.env, ...envFor(meta), UI_LOG: log, UI_EXIT: ex, TMPDIR: tmp, PYTHONDONTWRITEBYTECODE: "1" }, - }); - writeFileSync(path.join(dir, `ui-${step}.pid`), String(child.pid)); - child.unref(); -} - -/** Every descendant of a pid (ps), children first. */ -function descendants(pid: number): number[] { - const rows = execFileSync("ps", ["-eo", "pid=,ppid="], { encoding: "utf8" }) - .trim().split("\n").map((l) => l.trim().split(/\s+/).map(Number)); - const out: number[] = []; - const walk = (p: number) => { - for (const [c, pp] of rows) if (pp === p) { walk(c); out.push(c); } - }; - walk(pid); - return out; -} - -/** - * Cancel a running step: SIGTERM its whole process tree (the wrapper, the heavy-slot queue, the script and what it - * runs), then SIGKILL what is left after 5 s. Its exit file says "cancelled". A job the step had already handed to - * the EDITOR (a clip fetch, a voice) is the editor's: it finishes there, and its result is cached for a re-run. - */ -export function cancelStep(name: string, step: Step): void { - const dir = runDir(name); - if (stepState(dir, step).state !== "running") throw new Error(`${step} is not running`); - const pid = Number(readFileSync(path.join(dir, `ui-${step}.pid`), "utf8").trim()); - const ex = path.join(dir, `ui-${step}.exit`); - const tree = pid > 0 ? [...descendants(pid), pid] : []; - writeFileSync(ex, "cancelled"); - const kill = (sig: NodeJS.Signals) => { - for (const p of tree) { - try { - process.kill(p, sig); - } catch {} - } - }; - kill("SIGTERM"); - writeFileSync(path.join(dir, `ui-${step}.log`), - `${readFileSync(path.join(dir, `ui-${step}.log`), "utf8")}\n[cancelled ${new Date().toISOString()} — editor jobs it started finish on the editor (cached for a re-run)]\n`); - setTimeout(() => { - kill("SIGKILL"); - writeFileSync(ex, "cancelled"); // the wrapper may have written its own exit code on the way down - }, 5000).unref?.(); -} - -/** Whether Claude can be asked: a key in the env or the key file (claude_api.py reads the same two). */ -export function apiKeyReady(): boolean { - return !!process.env.ANTHROPIC_API_KEY || existsSync(path.join(os.homedir(), ".config/archilyzer/anthropic.env")); -} - -/** A run's own output files, read for the page (sweep.md, review.html, run.json only). */ -export function runFile(name: string, file: string): { body: string; type: string } | null { - if (!["sweep.md", "review.html", "run.json", "revise.json"].includes(file)) return null; - const p = path.join(runDir(name), file); - if (!existsSync(p) || !statSync(p).isFile()) return null; - const type = file.endsWith(".html") ? "text/html" : file.endsWith(".json") ? "application/json" : "text/plain"; - return { body: readFileSync(p, "utf8"), type: `${type}; charset=utf-8` }; -} diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -11,6 +11,8 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // spec can press Stop mid-job // E2E_EDITOR_STUB_LOG set below on the editor stub: where it records what // it was asked (e2e/fixtures/editor-stub.mjs) +// E2E_GEN_PROJECTS set below on the editor stub: where a stubbed video +// revision writes its project (release 27) // E2E_UMTOOL_EXTRA_KINDS set by projects.spec.ts on the CLI it runs: a kind // injected into the registry (lib/projects/kinds.mjs) // E2E_MODE `start` (the default): the app runs under @@ -107,6 +109,10 @@ export default defineConfig({ CHANNELS_DIR: `${FIXTURE}/channels`, WORKER_TOKEN: "umtool-e2e-token", E2E_EDITOR_STUB_LOG: `${FIXTURE}/editor-stub.requests.json`, + // Release 27: report-draft writes iterations into the fixture's + // article store, and a video revision's project under gen-projects. + ARTICLES_DIR: `${FIXTURE}/articles`, + E2E_GEN_PROJECTS: `${FIXTURE}/gen-projects`, }, }, { @@ -129,6 +135,9 @@ export default defineConfig({ // The article store (/articles, release 26): the fixture's own, for the // same reason -- an article's notes.json is written beside it. `ARTICLES_DIR=${FIXTURE}/articles ` + + // The generation usage ledger (release 27): the fixture's, never the + // checkout's .generation/usage.jsonl. + `GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` + // The cache (the project index, posters, analyses) is no longer under // SONG_DIR (release 17): its default is the user's ~/.cache, which a // suite must never write. The fixture's own, rebuilt with it every run.