Archilyzer · Source

archilyzer

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

commit 17f809f172340ef92bef3a90cb72ce7ce2b0f205
parent 3e708b06480756b905118deb2420bee00f118363
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 12 Oct 2026 16:21:55 -0400

umtool /drafts: versions of an article's report or video from feedback, a channel picker, the generation policy

A run gets new versions (<name>-vN): a revision of its report or of its video cut,
from the operator's feedback, on the local model or Claude on an API key
(~/reports/local-reports/bin/revise). A video version has its own project; a report
version's article step seeds its project from the parent's (narration carried, voices
linked). Current article / current video = the version that last wrote them. Channels
are picked from the composed builds. The routes of the generation policy
(~/.config/archilyzer/generation.json: Claude Code, API or local per task — bin/gen
and Claude Code's /gen read it) are edited here. Sonnet 5.5 is a model choice.

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

Diffstat:
Mumtool/app/api/drafts/route.ts | 21+++++++++++++++++++--
Mumtool/components/drafts/DraftsPanel.tsx | 344+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/drafts.ts | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
3 files changed, 446 insertions(+), 93 deletions(-)

diff --git a/umtool/app/api/drafts/route.ts b/umtool/app/api/drafts/route.ts @@ -1,4 +1,7 @@ -import { apiKeyReady, createRun, listRuns, runFile, startStep, STEPS, type Step } from "@/lib/drafts"; +import { + apiKeyReady, createRun, createVersion, listChannels, listRuns, PRESETS, readPolicy, runFile, startStep, STEPS, writePolicy, + type GenPolicy, type Step, +} from "@/lib/drafts"; export const dynamic = "force-dynamic"; @@ -13,7 +16,8 @@ export async function GET(request: Request) { const f = runFile(run, file); return f ? new Response(f.body, { headers: { "content-type": f.type } }) : new Response("not found", { status: 404 }); } - return Response.json({ runs: listRuns(), keyReady: apiKeyReady() }, { headers: { "cache-control": "no-store" } }); + 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) { @@ -32,6 +36,19 @@ export async function POST(request: Request) { 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 === "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.narrateModel ? String(b.narrateModel) : undefined); return Response.json({ ok: true }); diff --git a/umtool/components/drafts/DraftsPanel.tsx b/umtool/components/drafts/DraftsPanel.tsx @@ -1,20 +1,23 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; -import type { RunView, Step } from "@/lib/drafts"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { GenPolicy, Route, RunView, Step } from "@/lib/drafts"; -// The /drafts page (lib/drafts.ts): start a sweep on a local model or Claude on -// an API key, then the article, narration and video, each a button; the runs -// poll every 3 s off their logs. +// 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", "claude-opus-5-5"]; +const MODELS = ["qwen3:8b", "claude-sonnet-5-5", "claude-sonnet-5", "claude-opus-5-5"]; const STEPS: Step[] = ["sweep", "article", "narrate", "video"]; -const NEXT_HINT: Record<Step, string> = { - sweep: "sweep → report.json (quotes checked)", +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 = @@ -25,25 +28,192 @@ const stateColor: Record<string, string> = { done: "text-emerald-500", failed: "text-red-500", }; +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 [form, setForm] = useState({ question: "", channels: "", model: "qwen3:8b", name: "", terms: "", maxUsd: "5" }); - const [narrateModel, setNarrateModel] = useState("claude-sonnet-5"); + const [channels, setChannels] = useState<string[]>([]); + const [form, setForm] = useState({ question: "", model: "", name: "", terms: "", maxUsd: "5" }); + const [narrateModel, setNarrateModel] = useState(""); 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"); + const nModel = narrateModel || routeModel("narrate"); async function post(body: object) { setErr(""); @@ -53,16 +223,24 @@ export default function DraftsPanel() { return r; } - const claude = form.model.startsWith("claude-"); + 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-6"> + <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(); - const r = await post({ action: "create", ...form }); + 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: "" }); @@ -71,14 +249,14 @@ export default function DraftsPanel() { > <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="channels (slug,slug)" value={form.channels} onChange={set("channels")} required /> - <input className={input} placeholder="run / article id (a-z0-9-)" value={form.name} onChange={set("name")} pattern="[a-z0-9][a-z0-9-]*" required /> + <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={form.model} onChange={set("model")}> + <select className={input} value={model} onChange={set("model")}> {MODELS.map((m) => ( <option key={m} value={m}> - {m.startsWith("claude-") ? `${m} (API key)` : `${m} (local)`} + {label(m)} </option> ))} </select> @@ -92,81 +270,91 @@ export default function DraftsPanel() { </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> + <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> <label className="flex items-center gap-2 text-[12px]"> narration model - <select className={input} value={narrateModel} onChange={(e) => setNarrateModel(e.target.value)}> + <select className={input} value={nModel} onChange={(e) => setNarrateModel(e.target.value)}> {MODELS.map((m) => ( <option key={m}>{m}</option> ))} </select> </label> - <div className="flex flex-col gap-2"> - {runs.length === 0 && <div className="text-[13px] text-[var(--color-dim)]">No runs yet.</div>} - {runs.map((r) => { - const busy = STEPS.some((s) => r.steps[s].state === "running"); - 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)}> - {r.name} - </button> - <span className="text-[12px] text-[var(--color-dim)]"> - {r.model} · {r.channels} - {r.usd !== undefined ? ` · ~$${r.usd.toFixed(2)}` : ""} - </span> - </div> - <div className="mb-2 text-[13px]">{r.question}</div> - <div className="flex flex-wrap items-center gap-3"> - {STEPS.map((s) => ( - <span key={s} className="flex items-center gap-1"> - <button - className={btn} - title={NEXT_HINT[s]} - disabled={busy} - onClick={() => { - setOpen(r.name); - post({ action: "step", name: r.name, step: s, narrateModel }); - }} - > - {s} - </button> - <span className={`text-[11px] ${stateColor[r.steps[s].state]}`}>{r.steps[s].state}</span> + {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"); + 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.model} · {r.channels} + {r.usd !== undefined ? ` · ~$${r.usd.toFixed(2)}` : ""} </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.steps.article.state === "done" && ( - <a className="text-[12px] underline" href={`/articles/${r.id}`}> - article - </a> - )} + {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, narrateModel: nModel }); + }} + > + {s === "sweep" && r.kind && r.kind !== "sweep" ? "revise" : s} + </button> + <span className={`text-[11px] ${stateColor[r.steps[s].state]}`}>{r.steps[s].state}</span> + </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> + )} + <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> - {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> - ); - })} - </div> + ); + })} + </section> + ))} </div> ); } diff --git a/umtool/lib/drafts.ts b/umtool/lib/drafts.ts @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -14,7 +14,7 @@ import path from "node:path"; 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", "claude-opus-5-5"] as const; +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]; @@ -27,6 +27,13 @@ export type RunMeta = { 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; }; export type StepState = { state: "idle" | "running" | "done" | "failed"; exit?: number; tail?: string }; @@ -35,6 +42,19 @@ export type RunView = RunMeta & { 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}$/; @@ -57,7 +77,7 @@ function stepState(dir: string, step: Step): StepState { export function listRuns(): RunView[] { if (!existsSync(RUNS)) return []; - const out: RunView[] = []; + 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"); @@ -65,18 +85,125 @@ export function listRuns(): RunView[] { 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; - try { - usd = JSON.parse(readFileSync(path.join(dir, "run.json"), "utf8")).usd_estimate; - } catch {} + for (const f of ["run.json", "revise.json"]) { + try { + usd = (usd ?? 0) + JSON.parse(readFileSync(path.join(dir, f), "utf8")).usd_estimate; + } catch {} + } out.push({ ...meta, steps, usd, - files: ["sweep.md", "review.html", "run.json"].filter((f) => existsSync(path.join(dir, f))), - narrationReview: `/browse/local-reports/videos/${meta.id}/narration`, + 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"), }); } - return out.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + // 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; +} + +/** 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: { @@ -113,22 +240,43 @@ export function createRun(input: { 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, - "--max-usd", String(m.maxUsd ?? 5), ...(m.terms ? ["--terms", m.terms] : [])] + ...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", m.id), "--model", narrateModel]; + 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, narrateModel?: string): void { const dir = runDir(name); const meta = JSON.parse(readFileSync(path.join(dir, "ui.json"), "utf8")) as RunMeta; @@ -144,7 +292,7 @@ export function startStep(name: string, step: Step, narrateModel?: string): void const child = spawn("bash", ["-c", '"$@" >> "$UI_LOG" 2>&1; echo $? > "$UI_EXIT"', "ui-step", ...argv], { detached: true, stdio: "ignore", - env: { ...process.env, UI_LOG: log, UI_EXIT: ex, TMPDIR: tmp, PYTHONDONTWRITEBYTECODE: "1" }, + env: { ...process.env, ...envFor(meta), UI_LOG: log, UI_EXIT: ex, TMPDIR: tmp, PYTHONDONTWRITEBYTECODE: "1" }, }); child.unref(); } @@ -156,7 +304,7 @@ export function apiKeyReady(): boolean { /** 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"].includes(file)) return 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";