Archilyzer · Source

archilyzer

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

commit 165548d8decf4e06178c379e786c113676f83531
parent d9fc2ca3578853b48ee59cf65b4fff6dbe0134a7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 16:49:33 -0400

umtool: delete an article, an iteration, a project or a take — the plan shown, then "Confirm delete"

lib/report/delete.mjs plans and deletes a project (its directory, and its
out/ or deliverable media copy when the link is umtool's own mirror) and a
take (takes/<id>/); refused while a job works in the project, for an
article's current video or a running iteration's project, through a link;
a project whose manifest names an article with a video, and the take the
project's manifest is, only with "delete anyway". Articles and iterations go
through common's registry delete (/api/articles/delete), with a running chain
job refusing. One component (components/DeletePlan.tsx) asks for the plan,
shows what goes with sizes, what is kept and what refuses, and deletes on
confirm: "Delete article" on the article page, "Delete i<n>" on the
Iterations tab, "Delete project" on a report-video project, "Delete take <id>"
on each take.

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

Diffstat:
Aumtool/app/api/articles/delete/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/projects/delete/route.ts | 35+++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/takes/delete/route.ts | 33+++++++++++++++++++++++++++++++++
Mumtool/app/articles/page.tsx | 10++++++++--
Mumtool/app/browse/page.tsx | 9++++++++-
Aumtool/components/DeletePlan.tsx | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/ArticlePage.tsx | 2++
Aumtool/components/articles/DeleteArticle.tsx | 21+++++++++++++++++++++
Mumtool/components/articles/IterationsTab.tsx | 23++++++++++++++++++++++-
Aumtool/components/projects/DeleteProject.tsx | 19+++++++++++++++++++
Mumtool/components/projects/ReportProject.tsx | 7+++++++
Mumtool/components/projects/TakesBench.tsx | 12++++++++++++
Aumtool/lib/delete-plan.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/delete-context.ts | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/delete.mjs | 312+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/delete.test.mjs | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 1024 insertions(+), 4 deletions(-)

diff --git a/umtool/app/api/articles/delete/route.ts b/umtool/app/api/articles/delete/route.ts @@ -0,0 +1,85 @@ +import { + DeleteRefusedError, + deleteArticle, + deleteIteration, + planArticleDelete, + planIterationDelete, + type DeleteOptions, + type DeletePlan, +} from "yt-dlp-transcript-common/lib/report/delete"; +import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { chainKind, errorResponse, projectsRootOf, readPolicy } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; +import { clearLinksCache, videoProjects } from "@/lib/articles/links.mjs"; +import { configuredProjectsRoot } from "@/lib/report/chain.mjs"; +import { answerDelete } from "@/lib/delete-plan"; +import { invalidateProjects, pruneIndex } from "@/lib/projects"; +import { runningJob } from "@/lib/jobs"; +import { ARTICLES_KEY, MEDIA_ROOT, MEDIA_TIERED, REPORTS_ROOT } from "@/lib/paths"; + +export const dynamic = "force-dynamic"; + +// DELETE AN ARTICLE, OR ONE ITERATION OF IT (release 27 follow-up). +// +// POST { article, n?, dryRun?, force? } +// +// Common's lib/report/delete.ts — the article registry's delete, under its +// lock — as `archilyzer reports delete` and the editor's ops run it: the +// article's directory, its iterations' video projects under the generation +// projects root (the policy's, as "Make the video" reads it), its staged +// exports; or one iteration and its project. umtool adds what only it knows: +// a chain job of this article running here refuses, and a report-video +// project whose manifest names the article is named (kept: delete it on its +// own page). `force` (an article only) unpublishes it first. The answer is +// lib/delete-plan.ts's. +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; dryRun?: unknown; force?: unknown }; + const article = String(body.article ?? ""); + if (!isReportId(article)) return Response.json({ error: `"${article}" is not an article id` }, { status: 400 }); + const n = body.n === undefined || body.n === null ? null : Number(body.n); + if (n !== null && (!Number.isInteger(n) || n < 1)) return Response.json({ error: "n is an iteration number" }, { status: 400 }); + const force = body.force === true && n === null; + let projectsRoot: string; + try { + projectsRoot = projectsRootOf((await readPolicy()).generation); + } catch { + projectsRoot = configuredProjectsRoot(); // the editor unreachable: settings.json, as the chain reads it + } + const opts: DeleteOptions = { + paths: sitesPaths(), + projectsRoot, + media: MEDIA_TIERED ? { reportsRoot: REPORTS_ROOT, mediaRoot: MEDIA_ROOT } : null, + force, + }; + try { + const plan: DeletePlan = n === null ? await planArticleDelete(article, opts) : await planIterationDelete(article, n, opts); + const job = runningJob(); + if (job && (n === null ? job.kind.startsWith(`chain ${article} `) : job.kind === chainKind(article, n))) { + plan.refusals.push({ reason: `${job.kind} is running here: cancel the chain, or wait for it`, forceable: false }); + } + if (n === null) { + for (const p of await videoProjects(REPORTS_ROOT).catch(() => [])) { + if (p.article !== `${ARTICLES_KEY}/${article}`) continue; + if (plan.remove.some((e) => e.path === p.dir)) continue; + plan.kept.push({ what: `the project ${p.id}`, path: p.dir, why: "its manifest names this article: kept (delete it on its own page)" }); + } + } + const dryRun = body.dryRun === true; + return await answerDelete(plan, { dryRun, force }, async () => { + const r = n === null ? await deleteArticle(article, opts) : await deleteIteration(article, n, opts); + invalidateProjects(); + clearLinksCache(); + await pruneIndex().catch(() => 0); + return { ...r, plan }; + }); + } catch (err) { + if (err instanceof DeleteRefusedError) { + return Response.json({ error: `refused: ${err.problems.join("; ")}`, plan: err.plan }, { status: 409 }); + } + if (err instanceof ArticleRegistryError) { + return Response.json({ error: err.message }, { status: /^no article|has no iteration/.test(err.message) ? 404 : 400 }); + } + return errorResponse(err); + } +} diff --git a/umtool/app/api/projects/delete/route.ts b/umtool/app/api/projects/delete/route.ts @@ -0,0 +1,35 @@ +import { DeleteRefused, deleteProject, planProjectDelete } from "@/lib/report/delete.mjs"; +import { projectDeleteContext } from "@/lib/report/delete-context"; +import { answerDelete, type DeletePlanView } from "@/lib/delete-plan"; +import { invalidateProjects, projectRef, pruneIndex } from "@/lib/projects"; +import { clearLinksCache } from "@/lib/articles/links.mjs"; + +export const dynamic = "force-dynamic"; + +// DELETE A PROJECT (release 27 follow-up): the "new project" door's other +// half. POST { project, dryRun?, force? } — lib/report/delete.mjs: its +// directory under the reports root and, for a link umtool's move-out made, its +// media copy; refused while a job works in it, when it is an article's current +// video (or a running iteration's project), or reached through a link; a +// project whose manifest names an article with a video attached only with +// `force`. The answer is lib/delete-plan.ts's. +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { project?: unknown; dryRun?: unknown; force?: unknown }; + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const force = body.force === true; + const opts = { ...(await projectDeleteContext(project.id)), force }; + try { + const plan = (await planProjectDelete(project, opts)) as DeletePlanView; + return await answerDelete(plan, { dryRun: body.dryRun === true, force }, async () => { + const r = await deleteProject(project, opts); + invalidateProjects(); + clearLinksCache(); + await pruneIndex().catch(() => 0); + return r as { plan: DeletePlanView; removed: string[]; failed: { path: string; error: string }[] }; + }); + } catch (err) { + if (err instanceof DeleteRefused) return Response.json({ error: err.message, plan: err.plan }, { status: 409 }); + return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 }); + } +} diff --git a/umtool/app/api/report/takes/delete/route.ts b/umtool/app/api/report/takes/delete/route.ts @@ -0,0 +1,33 @@ +import { DeleteRefused, deleteTake, planTakeDelete } from "@/lib/report/delete.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; +import { projectDeleteContext } from "@/lib/report/delete-context"; +import { answerDelete, type DeletePlanView } from "@/lib/delete-plan"; +import { projectRef } from "@/lib/projects"; + +export const dynamic = "force-dynamic"; + +// DELETE A TAKE (release 27 follow-up). POST { project, take, dryRun?, force? } +// — lib/report/delete.mjs: `takes/<id>/` whole. Refused while a job works in +// the project; the take the project's manifest is (what its deliverable is +// built from) only with `force`. Its verdict row and the notes on it are kept. +// The answer is lib/delete-plan.ts's. +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as { project?: unknown; take?: unknown; dryRun?: unknown; force?: unknown }; + if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); + const take = body.take; + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const force = body.force === true; + const opts = { ...(await projectDeleteContext(project.id)), force }; + try { + const plan = (await planTakeDelete(project, take, opts)) as DeletePlanView; + return await answerDelete(plan, { dryRun: body.dryRun === true, force }, async () => { + const r = await deleteTake(project, take, opts); + return r as { plan: DeletePlanView; removed: string[]; failed: { path: string; error: string }[] }; + }); + } catch (err) { + if (err instanceof DeleteRefused) return Response.json({ error: err.message, plan: err.plan }, { status: 409 }); + const message = err instanceof Error ? err.message : String(err); + return Response.json({ error: message }, { status: /has no take/.test(message) ? 404 : 500 }); + } +} diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx @@ -13,7 +13,7 @@ export const dynamic = "force-dynamic"; // 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 }; +type Search = { status?: string; notes?: string; audience?: string; deleted?: string; freed?: string }; export default async function ArticlesPage({ searchParams }: { searchParams: Promise<Search> }) { const sp = await searchParams; @@ -25,7 +25,7 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro const shown = store.articles.filter(keep); const qs = (next: Partial<Search>) => { const p = new URLSearchParams(); - for (const [k, v] of Object.entries({ ...sp, ...next })) if (v) p.set(k, String(v)); + for (const [k, v] of Object.entries({ ...sp, ...next })) if (v && k !== "deleted" && k !== "freed") p.set(k, String(v)); const s = p.toString(); return `/articles${s ? `?${s}` : ""}`; }; @@ -39,6 +39,12 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro note={`${store.published} published (${store.publicCount} public) · ${store.drafts} drafts · ${store.openNotes} open notes`} /> <main className="deck-main flex-1 p-4"> + {sp.deleted && ( + <p role="status" data-deleted={sp.deleted} className="mb-2 text-[12px] text-[var(--color-dim)]"> + Deleted {sp.deleted} + {Number(sp.freed) > 0 ? ` (${(Number(sp.freed) / 1024 / 1024).toFixed(1)} MiB)` : ""}. + </p> + )} <div className="mb-3 flex flex-wrap items-center gap-1.5"> <span className="micro">status</span> <Chip href={qs({ status: "" })} on={!sp.status} label="all" /> diff --git a/umtool/app/browse/page.tsx b/umtool/app/browse/page.tsx @@ -29,6 +29,8 @@ type Search = { open?: string; q?: string; sort?: string; + // A project just deleted (components/projects/DeleteProject.tsx). + deleted?: string; }; export default async function BrowsePage({ @@ -64,7 +66,7 @@ export default async function BrowsePage({ const qs = (next: Partial<Search>) => { const p = new URLSearchParams(); - for (const [k, v] of Object.entries({ ...sp, ...next })) if (v) p.set(k, String(v)); + for (const [k, v] of Object.entries({ ...sp, ...next })) if (v && k !== "deleted") p.set(k, String(v)); const s = p.toString(); return `/browse${s ? `?${s}` : ""}`; }; @@ -97,6 +99,11 @@ export default async function BrowsePage({ note={projectsNote(all.length, blocking, openN)} /> <main className="deck-main flex-1 p-4"> + {sp.deleted && ( + <p role="status" data-deleted={sp.deleted} className="mb-2 text-[12px] text-[var(--color-dim)]"> + Deleted {sp.deleted}. + </p> + )} {/* --- filters, as links ---------------------------------------- */} <div className="mb-2 flex flex-wrap items-center gap-1.5"> <span className="micro">kind</span> diff --git a/umtool/components/DeletePlan.tsx b/umtool/components/DeletePlan.tsx @@ -0,0 +1,207 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { blockedBy, type DeleteAnswer, type DeletePlanView } from "@/lib/delete-plan"; + +// ONE WAY TO DELETE ANYTHING (release 27 follow-up): an article, an iteration, +// a project, a take. The button asks the route for the PLAN (a dry run: every +// path that would go, with its size, what is kept and why, what refuses), shows +// it, and deletes only on "Confirm delete". A refusal force can answer (a +// published article, a take the manifest is) offers "Delete anyway", which +// asks for the plan again with force before the confirm is offered. +// +// Labels are contracts (e2e/article-delete.spec.ts): the trigger is `label` +// ("Delete article", "Delete i3", "Delete project", "Delete take <id>"); the +// plan is the region "delete <subject>" holding the lists "what goes", "what is +// kept", "refused", the checkbox "delete anyway", and the buttons +// "Confirm delete" and "Keep it". + +const fmt = (n: number) => { + if (n < 1024) return `${n} B`; + const u = ["KiB", "MiB", "GiB", "TiB"]; + let v = n / 1024; + let i = 0; + while (v >= 1024 && i < u.length - 1) { + v /= 1024; + i += 1; + } + return `${v.toFixed(v >= 100 ? 0 : 1)} ${u[i]}`; +}; + +type Phase = + | { at: "closed" } + | { at: "asking" } + | { at: "plan"; plan: DeletePlanView; error: string | null } + | { at: "deleting"; plan: DeletePlanView } + | { at: "error"; error: string }; + +export default function DeletePlan({ + label, + subject, + endpoint, + body, + forceLabel = "delete anyway", + onDone, + size = "sm", +}: { + label: string; + subject: string; + endpoint: string; + body: Record<string, unknown>; + forceLabel?: string; + onDone: (answer: Extract<DeleteAnswer, { applied: true }>) => void; + size?: "sm" | "md"; +}) { + const [phase, setPhase] = useState<Phase>({ at: "closed" }); + const [force, setForce] = useState(false); + + const ask = async (withForce: boolean) => { + setPhase({ at: "asking" }); + try { + const r = await fetch(endpoint, { method: "POST", body: JSON.stringify({ ...body, dryRun: true, force: withForce }) }); + const b = (await r.json()) as { plan?: DeletePlanView; error?: string }; + if (b.plan) setPhase({ at: "plan", plan: b.plan, error: null }); + else setPhase({ at: "error", error: b.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "error", error: (e as Error).message }); + } + }; + + const confirm = async (plan: DeletePlanView) => { + setPhase({ at: "deleting", plan }); + try { + const r = await fetch(endpoint, { method: "POST", body: JSON.stringify({ ...body, force }) }); + const b = (await r.json()) as DeleteAnswer & { error?: string }; + if (r.ok && b.applied) { + setPhase({ at: "closed" }); + onDone(b); + return; + } + setPhase({ at: "plan", plan: b.plan ?? plan, error: b.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "plan", plan, error: (e as Error).message }); + } + }; + + if (phase.at === "closed") { + return ( + <Button size={size} variant="destructive" onClick={() => void ask(false)}> + {label} + </Button> + ); + } + if (phase.at === "asking") return <span className="text-[12px] text-[var(--color-dim)]">reading what would go…</span>; + if (phase.at === "error") { + return ( + <span role="alert" className="flex items-center gap-2 text-[12px] text-[var(--color-bad)]"> + {phase.error} + <Button size="sm" variant="ghost" onClick={() => setPhase({ at: "closed" })}> + Keep it + </Button> + </span> + ); + } + const plan = phase.plan; + const blocked = blockedBy(plan, force); + const forceable = plan.refusals.length > 0 && plan.refusals.every((r) => r.forceable); + return ( + <section + role="region" + aria-label={`delete ${subject}`} + data-delete-blocked={blocked.length > 0 ? "yes" : "no"} + className="mt-2 basis-full rounded border border-[var(--color-bad)] bg-[var(--color-ink)] p-2 text-[12px]" + > + <p className="font-medium"> + Delete {subject}: {plan.remove.length} path{plan.remove.length === 1 ? "" : "s"},{" "} + <span className="num" data-delete-bytes={plan.bytes}> + {fmt(plan.bytes)} + </span>{" "} + in {plan.files} file{plan.files === 1 ? "" : "s"}. There is no undo. + </p> + {plan.refusals.length > 0 && ( + <ul aria-label="refused" className="mt-1 list-disc pl-5 text-[var(--color-bad)]"> + {plan.refusals.map((r, i) => ( + <li key={i} data-forceable={r.forceable ? "yes" : "no"}> + {r.reason} + </li> + ))} + </ul> + )} + {plan.steps.length > 0 && ( + <ul aria-label="first" className="mt-1 list-disc pl-5 text-[var(--color-dim)]"> + {plan.steps.map((s, i) => ( + <li key={i}>{s}</li> + ))} + </ul> + )} + <ul aria-label="what goes" className="mt-1 flex flex-col gap-0.5"> + {plan.remove.map((e) => ( + <li key={e.path} data-delete-path={e.path} className="font-mono text-[11px]"> + <span className="text-[var(--color-text)]">{e.label}</span> <span className="text-[var(--color-dim)]">{e.what}</span>{" "} + <span className="num">{e.kind === "link" ? "a link" : fmt(e.bytes)}</span> + {e.parts && e.parts.length > 0 && ( + <span className="block pl-4 text-[var(--color-dim)]"> + {e.parts + .slice(0, 8) + .map((p) => `${p.name} ${fmt(p.bytes)}`) + .join(" · ")} + {e.parts.length > 8 ? ` · … ${e.parts.length - 8} more` : ""} + </span> + )} + </li> + ))} + </ul> + {plan.kept.length > 0 && ( + <details className="mt-1"> + <summary className="cursor-pointer text-[var(--color-dim)]">kept ({plan.kept.length})</summary> + <ul aria-label="what is kept" className="list-disc pl-5 text-[var(--color-dim)]"> + {plan.kept.map((k, i) => ( + <li key={i}> + {k.what}: {k.why} + </li> + ))} + </ul> + </details> + )} + {phase.at === "plan" && phase.error && ( + <p role="alert" className="mt-1 text-[var(--color-bad)]"> + {phase.error} + </p> + )} + <div className="mt-2 flex flex-wrap items-center gap-2"> + {forceable && ( + <label className="flex items-center gap-1"> + <input + type="checkbox" + aria-label="delete anyway" + checked={force} + onChange={(e) => { + setForce(e.target.checked); + void (async () => { + const r = await fetch(endpoint, { method: "POST", body: JSON.stringify({ ...body, dryRun: true, force: e.target.checked }) }); + const b = (await r.json().catch(() => ({}))) as { plan?: DeletePlanView }; + if (b.plan) setPhase({ at: "plan", plan: b.plan, error: null }); + })(); + }} + /> + {forceLabel} + </label> + )} + <Button size="sm" variant="destructive" disabled={blocked.length > 0 || phase.at === "deleting"} onClick={() => void confirm(plan)}> + {phase.at === "deleting" ? "Deleting…" : "Confirm delete"} + </Button> + <Button + size="sm" + variant="ghost" + onClick={() => { + setForce(false); + setPhase({ at: "closed" }); + }} + > + Keep it + </Button> + </div> + </section> + ); +} diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -5,6 +5,7 @@ import { notFound } from "next/navigation"; import { readRevisionHead, REPORT_HISTORY_GIT_DIRNAME } from "yt-dlp-transcript-common/publish/reportHistory"; import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides"; import BrowseHeader, { type Crumb } from "@/components/BrowseHeader"; +import DeleteArticle from "@/components/articles/DeleteArticle"; import ArticleReader from "@/components/articles/ArticleReader"; import WorkspacePanel from "@/components/articles/WorkspacePanel"; import IterationsView from "@/components/articles/IterationsView"; @@ -112,6 +113,7 @@ export default async function ArticlePage({ </Link> )} </nav> + {store && <DeleteArticle article={reportId} published={published} />} {source && ( <div className="w-full font-mono text-[11px]" title={source.how}> {source.draft && <span>draft {source.draft}</span>} diff --git a/umtool/components/articles/DeleteArticle.tsx b/umtool/components/articles/DeleteArticle.tsx @@ -0,0 +1,21 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import DeletePlan from "@/components/DeletePlan"; + +// "Delete article" on an article of the store (release 27 follow-up): the +// plan, then the registry's delete (POST /api/articles/delete); done, back to +// the article list, which says what went. +export default function DeleteArticle({ article, published }: { article: string; published: boolean }) { + const router = useRouter(); + return ( + <DeletePlan + label="Delete article" + subject={`the article ${article}`} + endpoint="/api/articles/delete" + body={{ article }} + forceLabel={published ? "unpublish it first, then delete" : "delete anyway"} + onDone={(a) => router.push(`/articles?deleted=${encodeURIComponent(article)}&freed=${a.plan.bytes}`)} + /> + ); +} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -6,6 +6,7 @@ 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 DeletePlan from "@/components/DeletePlan"; import { usd, type Today } from "@/components/articles/PolicyPanel"; import type { ArticleIterations, DraftJobView, IterationRow, PolicyView } from "@/lib/articles/generation"; @@ -41,6 +42,8 @@ type Ctx = { /** Make an iteration the article's (the registry's makeCurrent). */ use: (n: number) => Promise<boolean>; refresh: () => void; + /** An iteration was deleted (the registry's delete, through /api/articles/delete). */ + deleted: (n: number) => void; }; function ModelSelect({ value, onChange, label, models }: { value: string; onChange: (v: string) => void; label: string; models: string[] }) { @@ -339,6 +342,15 @@ function IterationCard({ Make the video </Button> )} + {!active && ( + <DeletePlan + label={`Delete ${it.label}`} + subject={it.label} + endpoint="/api/articles/delete" + body={{ article: ctx.article, n: it.n }} + onDone={() => ctx.deleted(it.n)} + /> + )} <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 @@ -409,7 +421,16 @@ export default function IterationsTab({ ); const allModels = policy ? [...new Set([...policy.models.api, ...policy.models.local])] : []; - const ctx: Ctx = { article, policy, allModels, post, use, refresh: refreshNow }; + const deleted = useCallback( + (n: number) => { + setError(""); + setNote(`i${n} deleted`); + setCompare((c) => c.filter((x) => x !== n)); + void refresh(); + }, + [refresh], + ); + const ctx: Ctx = { article, policy, allModels, post, use, refresh: refreshNow, deleted }; const spent = data.iterations.reduce((s, it) => s + it.usd, 0); return ( diff --git a/umtool/components/projects/DeleteProject.tsx b/umtool/components/projects/DeleteProject.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import DeletePlan from "@/components/DeletePlan"; + +// "Delete project" (release 27 follow-up): the plan, then the delete (POST +// /api/projects/delete, lib/report/delete.mjs); done, back to the projects. +export default function DeleteProject({ project }: { project: string }) { + const router = useRouter(); + return ( + <DeletePlan + label="Delete project" + subject={`the project ${project}`} + endpoint="/api/projects/delete" + body={{ project }} + onDone={() => router.push(`/browse?deleted=${encodeURIComponent(project)}`)} + /> + ); +} diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -26,6 +26,7 @@ import OnscreenSection from "./OnscreenSection"; import PodcastExport from "./PodcastExport"; import ReportBuildChain from "./ReportBuildChain"; import SnapshotButton from "./SnapshotButton"; +import DeleteProject from "./DeleteProject"; import TagCitedButton from "./TagCitedButton"; import { RowControls, RowNotes, TimelineList } from "./TimelineEditor"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; @@ -84,6 +85,9 @@ export default async function ReportProject({ <p className="text-[12px] text-[var(--color-bad)]"> <code className="font-mono">video.manifest.json</code> could not be parsed. </p> + <div className="mt-2"> + <DeleteProject project={project.id} /> + </div> </main> </div> ); @@ -282,6 +286,9 @@ export default async function ReportProject({ </Link> </div> )} + <div className="flex basis-full justify-end sm:basis-auto"> + <DeleteProject project={project.id} /> + </div> </div> <NotesProvider target={{ project: project.id }}> diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -1,6 +1,8 @@ "use client"; import { useCallback, useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import DeletePlan from "@/components/DeletePlan"; import AnchoredNotes from "@/components/notes/AnchoredNotes"; import { NotesProvider, useSharedNotes } from "@/components/notes/NotesProvider"; import TimedNotes from "@/components/notes/TimedNotes"; @@ -229,6 +231,7 @@ function TakeCard({ save: (patch: { verdict?: Verdict | null; note?: string }) => Promise<void>; }) { const notes = useSharedNotes({ project }); + const router = useRouter(); // The element, for the timed notes; the parent's callback (audio routing) // still gets it. Stable, so it runs once per mount, not once per render. const [el, setEl] = useState<HTMLVideoElement | null>(null); @@ -350,6 +353,15 @@ function TakeCard({ Both land in the project's notes.json, which the agent that made the takes reads back (`umtool notes`) beside verdicts.json. */} <AnchoredNotes notes={notes} pin={{ kind: "take", take: t.id }} label="take notes" /> + <div className="flex flex-wrap"> + <DeletePlan + label={`Delete take ${t.id}`} + subject={`take ${t.id}`} + endpoint="/api/report/takes/delete" + body={{ project, take: t.id }} + onDone={() => router.refresh()} + /> + </div> {t.previewSize != null && ( <TimedNotes notes={notes} file={`takes/${t.id}/${t.preview}`} video={el} take={t.id} resolveProject={project} /> )} diff --git a/umtool/lib/delete-plan.ts b/umtool/lib/delete-plan.ts @@ -0,0 +1,53 @@ +// THE DELETE ROUTES' ONE ANSWER (release 27 follow-up): an article, an +// iteration, a project and a take are each deleted by a plan and then the +// delete — common's lib/report/delete.ts for the first two, lib/report/ +// delete.mjs for the others — and answered the same way, so one page component +// (components/DeletePlan.tsx) shows every plan and asks before it acts. +// +// 200 { ok, applied: false, plan } a dry run +// 200 { ok, applied: true, plan, removed, failed } done +// 409 { error, plan } refused: nothing removed +// 400/404 { error } no such thing +// +// Types only, and the answer: no node: import, so a client component can take +// the types. + +export type DeletePlanEntry = { + path: string; + label: string; + what: string; + kind: "dir" | "file" | "link" | "absent"; + bytes: number; + files: number; + parts?: { name: string; bytes: number }[]; +}; + +export type DeletePlanView = { + refusals: { reason: string; forceable: boolean }[]; + steps: string[]; + remove: DeletePlanEntry[]; + kept: { what: string; path?: string; why: string }[]; + bytes: number; + files: number; +}; + +export type DeleteAnswer = + | { ok: boolean; applied: false; plan: DeletePlanView } + | { ok: boolean; applied: true; plan: DeletePlanView; removed: string[]; failed: { path: string; error: string }[] }; + +export const blockedBy = (plan: Pick<DeletePlanView, "refusals">, force: boolean) => + plan.refusals.filter((r) => !force || !r.forceable); + +/** Answer a plan: a refusal is a 409 carrying it; a dry run answers it; else `apply` runs. */ +export async function answerDelete( + plan: DeletePlanView, + { dryRun, force }: { dryRun: boolean; force: boolean }, + apply: () => Promise<{ plan: DeletePlanView; removed: string[]; failed: { path: string; error: string }[] }>, +): Promise<Response> { + const blocked = blockedBy(plan, force); + const headers = { "cache-control": "no-store" }; + if (blocked.length) return Response.json({ error: `refused: ${blocked.map((r) => r.reason).join("; ")}`, plan }, { status: 409, headers }); + if (dryRun) return Response.json({ ok: true, applied: false, plan }, { headers }); + const r = await apply(); + return Response.json({ ok: r.failed.length === 0, applied: true, plan: r.plan, removed: r.removed, failed: r.failed }, { headers }); +} diff --git a/umtool/lib/report/delete-context.ts b/umtool/lib/report/delete-context.ts @@ -0,0 +1,41 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { runningJob } from "@/lib/jobs"; +import { reportDirFor, sitesPaths } from "@/lib/articles/sites"; +import { projectsRootOf, readPolicy } from "@/lib/articles/generation"; +import { configuredProjectsRoot } from "@/lib/report/chain.mjs"; +import { MEDIA_ROOT, REPORTS_ROOT } from "@/lib/paths"; + +// What the project and take delete routes tell lib/report/delete.mjs that it +// cannot see from a plain module (release 27 follow-up): the umtool job working +// in the project, the generation projects root and the article store (an +// iteration project's article), and whether an article a manifest names has a +// video attached. SERVER-ONLY. + +export async function projectDeleteContext(projectId: string) { + const job = runningJob(); + let projectsRoot: string; + try { + projectsRoot = projectsRootOf((await readPolicy()).generation); + } catch { + projectsRoot = configuredProjectsRoot(); + } + return { + reportsRoot: REPORTS_ROOT, + mediaRoot: MEDIA_ROOT, + busyJob: job && job.project === projectId ? job.kind : null, + projectsRoot, + articlesDir: sitesPaths().articlesDir, + // `<site>/<report>` (articles/<id> for an article): its report.json has a `video`. + articleVideo: async (ref: string) => { + const [site, report] = ref.split("/"); + if (!site || !report) return false; + try { + const doc = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ reportDirFor(site, report), "report.json"), "utf8")); + return !!doc?.video; + } catch { + return false; + } + }, + }; +} diff --git a/umtool/lib/report/delete.mjs b/umtool/lib/report/delete.mjs @@ -0,0 +1,312 @@ +// DELETING A PROJECT OR A TAKE (release 27 follow-up, lane I): a PLAN that +// reads only -- every path that would go, with its size, what is kept and why, +// and what refuses -- then the delete. The plan's shape is common's +// (common/lib/report/delete.ts DeletePlan), so one page component shows both. +// +// a PROJECT its directory under REPORTS_ROOT, whatever its kind; and, for +// a top-level link umtool's move-out made (`out`, `clips`, +// `share-*` -> `<MEDIA_ROOT>/<project-relative>/<name>`), that +// link's target on the media root. Any other link is removed as +// a link and its target kept. Refused: a project reached through +// a link, or that is one; a umtool job working in it; the +// project of an article's CURRENT video (an iteration project +// `current.json` names as the video), or of an iteration that is +// queued or running; a project whose manifest names an article +// (`"article": "<site>/<report>"`) with a video attached -- +// unless `force` (the article keeps its attached copy). +// a TAKE `takes/<id>/` -- its take.json, preview, manifest and out/. +// Refused: a umtool job working in the project; the take the +// project's video.manifest.json IS (byte for byte: what its +// deliverable is built from) -- unless `force`. Kept: its row in +// takes/verdicts.json and the notes on it (the agent that made +// the takes reads both; a verdict on a take that is gone is +// shown as missing). +// +// Never outside REPORTS_ROOT and MEDIA_ROOT, and never either root itself. +// Plain ESM (node --test runs it; the routes import it). Every path op carries +// `turbopackIgnore`: the app's routes import this module (plans/FACTS.md). +import { lstat, readFile, readdir, readlink, realpath, rm, rmdir } from "node:fs/promises"; +import path from "node:path"; +import { MEDIA_ROOT, REPORTS_ROOT, inside } from "../paths.mjs"; +import { isTakeId, takesDirOf } from "./takes.mjs"; + +const strictlyInside = (root, p) => p !== root && inside(root, p); + +/** One project's or take's plan: common's DeletePlan shape (`article` is the project id). */ +function plan(project, extra) { + const remove = extra.remove; + return { + project, + ...extra, + bytes: remove.reduce((s, e) => s + e.bytes, 0), + files: remove.reduce((s, e) => s + e.files, 0), + }; +} + +/** Whether a plan stops a delete: any refusal, or -- with `force` -- one force does not answer. */ +export const deleteBlocked = (p, force = false) => p.refusals.some((r) => !force || !r.forceable); + +/** Sizes and links, never following a link. */ +async function measure(p) { + const st = await lstat(/* turbopackIgnore: true */ p).catch(() => null); + if (!st) return { kind: "absent", bytes: 0, files: 0, parts: [], links: [] }; + const target = async (l) => path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ l), await readlink(/* turbopackIgnore: true */ l)); + if (st.isSymbolicLink()) return { kind: "link", bytes: 0, files: 0, parts: [], links: [{ path: p, target: await target(p) }] }; + if (!st.isDirectory()) return { kind: "file", bytes: st.size, files: 1, parts: [], links: [] }; + const out = { kind: "dir", bytes: 0, files: 0, parts: [], links: [] }; + const walk = async (dir, top) => { + const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); + for (const e of entries) { + const child = path.join(/* turbopackIgnore: true */ dir, e.name); + const part = top ?? { name: e.isDirectory() ? `${e.name}/` : e.name, bytes: 0 }; + if (!top) out.parts.push(part); + if (e.isSymbolicLink()) { + out.links.push({ path: child, target: await target(child).catch(() => "?") }); + if (!top) part.name = `${e.name} (link)`; + } else if (e.isDirectory()) { + await walk(child, part); + } else { + const s = await lstat(/* turbopackIgnore: true */ child).catch(() => null); + if (s) { + out.bytes += s.size; + out.files += 1; + part.bytes += s.size; + } + } + } + }; + await walk(p, null); + out.parts.sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name)); + return out; +} + +/** `{ entry, links }` for one path, or a null entry when it is not there. */ +async function entryOf(p, label, what) { + const m = await measure(p); + if (m.kind === "absent") return { entry: null, links: [] }; + return { + entry: { path: p, label, what, kind: m.kind, bytes: m.bytes, files: m.files, ...(m.kind === "dir" && m.parts.length ? { parts: m.parts } : {}) }, + links: m.links, + }; +} + +/** + * The links met in what goes: one that is exactly its media mirror goes with + * its target; any other's target is kept and named. + */ +async function linkEntries(links, removing, roots) { + const out = { remove: [], kept: [] }; + for (const l of links) { + if (removing.some((r) => inside(r, l.target))) continue; + const rel = path.relative(/* turbopackIgnore: true */ roots.reportsRoot, l.path); + const mirror = roots.tiered && rel && !rel.startsWith("..") && !path.isAbsolute(rel) + ? path.join(/* turbopackIgnore: true */ roots.mediaRoot, rel) + : null; + if (mirror && l.target === mirror && strictlyInside(roots.mediaRoot, l.target)) { + const e = await entryOf(l.target, l.target, `the media copy ${path.basename(/* turbopackIgnore: true */ l.path)}/ links to`); + if (e.entry) out.remove.push(e.entry); + continue; + } + out.kept.push({ what: `${l.path} → ${l.target}`, path: l.target, why: "a link: it is removed, and what it points at is kept (not this project's own media copy)" }); + } + return out; +} + +function rootsOf(opts = {}) { + const reportsRoot = path.resolve(/* turbopackIgnore: true */ opts.reportsRoot ?? REPORTS_ROOT); + const mediaRoot = path.resolve(/* turbopackIgnore: true */ opts.mediaRoot ?? MEDIA_ROOT); + return { reportsRoot, mediaRoot, tiered: mediaRoot !== reportsRoot }; +} + +/** `dir` is strictly inside the reports root, is not a link, and its real path is inside the root's. */ +async function placeProblem(dir, roots, what) { + const abs = path.resolve(/* turbopackIgnore: true */ dir); + if (!strictlyInside(roots.reportsRoot, abs)) return `${what} ${abs} is not inside the reports root ${roots.reportsRoot}`; + const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); + if (!st) return `${what} ${abs} is not there`; + if (st.isSymbolicLink()) return `${what} ${abs} is a link: remove the link by hand`; + const [realRoot, real] = await Promise.all([ + realpath(/* turbopackIgnore: true */ roots.reportsRoot).catch(() => null), + realpath(/* turbopackIgnore: true */ abs).catch(() => null), + ]); + if (!realRoot || !real || !strictlyInside(realRoot, real)) return `${what} ${abs} is reached through a link (it is ${real}): remove it by hand`; + return null; +} + +const readJson = async (file) => { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +}; + +/** + * What an iteration project is to the article store, when `dir` is + * `<projectsRoot>/<article>/i<n>` or an iteration records it as its + * `projectDir`: `{ article, n, current: "video" | null, status }`, else null. + * Read-only reads of `ARTICLES_DIR/<article>/iterations/`. + */ +export async function iterationOfProject(dir, { projectsRoot, articlesDir }) { + if (!projectsRoot || !articlesDir) return null; + const abs = path.resolve(/* turbopackIgnore: true */ dir); + const rel = path.relative(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ projectsRoot), abs).split(path.sep); + if (rel.length !== 2 || rel[0].startsWith(".") || rel[0] === ".." || !/^i[1-9]\d{0,8}$/.test(rel[1])) return null; + const [article, label] = rel; + const n = Number(label.slice(1)); + const its = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations"); + const it = await readJson(path.join(/* turbopackIgnore: true */ its, String(n), "iteration.json")); + if (!it || it.article !== article || it.n !== n) return null; + const cur = (await readJson(path.join(/* turbopackIgnore: true */ its, "current.json"))) ?? {}; + const running = it.status === "queued" || it.status === "running" || (Array.isArray(it.steps) && it.steps.some((s) => s?.status === "running")); + return { article, n, current: cur.video === n ? "video" : null, status: running ? "busy" : String(it.status) }; +} + +/** + * WHAT DELETING PROJECT `project` WOULD DO. Reads only. + * + * @param {{ id: string, dir: string }} project + * @param {{ reportsRoot?: string, mediaRoot?: string, busyJob?: string | null, + * projectsRoot?: string, articlesDir?: string, + * articleVideo?: (ref: string) => Promise<boolean>, force?: boolean }} [opts] + * `busyJob`: the umtool job working in it, by name, if one is; `articleVideo`: + * whether the article a manifest names (`<site>/<report>`) has a video attached. + */ +export async function planProjectDelete(project, opts = {}) { + const roots = rootsOf(opts); + const refusals = []; + const kept = []; + const steps = []; + const remove = []; + const place = await placeProblem(project.dir, roots, "the project"); + if (place) refusals.push({ reason: place, forceable: false }); + if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in it: wait for it, or cancel it`, forceable: false }); + + const it = await iterationOfProject(project.dir, opts); + if (it?.current === "video") { + refusals.push({ reason: `it is i${it.n}'s project, and i${it.n} is the article "${it.article}"'s current video: attach another iteration's video, or delete the article`, forceable: false }); + } else if (it?.status === "busy") { + refusals.push({ reason: `it is i${it.n}'s project, and i${it.n} of "${it.article}" is running`, forceable: false }); + } else if (it) { + kept.push({ what: `i${it.n}'s iteration record (article "${it.article}")`, why: "kept, without its project: delete the iteration on the article's Iterations tab to remove both" }); + } + + const manifest = await readJson(path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json")); + const ref = typeof manifest?.article === "string" ? manifest.article : null; + if (ref && opts.articleVideo && (await opts.articleVideo(ref).catch(() => false))) { + refusals.push({ + reason: `its manifest names the article ${ref}, which has a video attached: delete anyway to remove the project (the article keeps its attached copy)`, + forceable: true, + }); + } else if (ref) { + kept.push({ what: `the article ${ref} its manifest names`, why: "untouched (no video attached from it)" }); + } + + if (!place) { + const e = await entryOf(project.dir, project.id, "the project directory"); + if (e.entry) { + remove.push(e.entry); + const l = await linkEntries(e.links, [path.resolve(/* turbopackIgnore: true */ project.dir)], roots); + remove.push(...l.remove); + kept.push(...l.kept); + } + } + if (it) steps.push(`remove ${path.dirname(/* turbopackIgnore: true */ project.dir)} if nothing else is left in it`); + kept.push({ what: "notes on it", why: "they live in its notes.json, which goes with the directory" }); + return plan(project.id, { refusals, steps, remove, kept }); +} + +/** Remove what a plan lists: each path inside a root and not a root, re-checked. */ +async function removeEntries(entries, roots) { + const out = { removed: [], failed: [] }; + for (const e of entries) { + try { + const abs = path.resolve(/* turbopackIgnore: true */ e.path); + const root = [roots.reportsRoot, ...(roots.tiered ? [roots.mediaRoot] : [])].find((r) => strictlyInside(r, abs)); + if (!root) throw new Error("not inside the reports or media root: refused"); + const realParent = await realpath(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ abs)).catch(() => null); + const realRoot = await realpath(/* turbopackIgnore: true */ root).catch(() => null); + if (!realParent || !realRoot || !inside(realRoot, realParent)) throw new Error("resolves outside its root: refused"); + await rm(/* turbopackIgnore: true */ abs, { recursive: true, force: true }); + out.removed.push(abs); + } catch (err) { + out.failed.push({ path: e.path, error: err instanceof Error ? err.message : String(err) }); + } + } + return out; +} + +/** A refusal: nothing was removed. `plan` says why. */ +export class DeleteRefused extends Error { + constructor(message, plan) { + super(message); + this.name = "DeleteRefused"; + this.plan = plan; + } +} + +/** DELETE PROJECT `project`: the plan made again, then done. Throws DeleteRefused. */ +export async function deleteProject(project, opts = {}) { + const roots = rootsOf(opts); + const p = await planProjectDelete(project, opts); + if (deleteBlocked(p, opts.force)) throw new DeleteRefused(`${project.id} is not deleted: ${p.refusals.map((r) => r.reason).join("; ")}`, p); + const done = await removeEntries(p.remove, roots); + // An iteration project's article folder (<projectsRoot>/<article>/) goes once empty. + if (p.steps.length) { + const parent = path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ project.dir)); + if (strictlyInside(roots.reportsRoot, parent)) await rmdir(/* turbopackIgnore: true */ parent).then(() => done.removed.push(parent), () => {}); + } + return { plan: p, ...done }; +} + +/** + * WHAT DELETING TAKE `takeId` OF A PROJECT WOULD DO. Reads only. + * + * @param {{ id: string, dir: string }} project + * @param {string} takeId + * @param {{ reportsRoot?: string, mediaRoot?: string, busyJob?: string | null }} [opts] + */ +export async function planTakeDelete(project, takeId, opts = {}) { + if (!isTakeId(takeId)) throw new Error("not a take id"); + const roots = rootsOf(opts); + const refusals = []; + const kept = []; + const remove = []; + const dir = path.join(/* turbopackIgnore: true */ takesDirOf(project.dir), takeId); + const st = await lstat(/* turbopackIgnore: true */ dir).catch(() => null); + if (!st) throw new Error(`${project.id} has no take ${takeId}`); + const place = await placeProblem(project.dir, roots, "the project"); + if (place) refusals.push({ reason: place, forceable: false }); + if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in ${project.id}: wait for it, or cancel it`, forceable: false }); + const [mine, theirs] = await Promise.all([ + readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").catch(() => null), + readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), + ]); + if (mine !== null && theirs !== null && mine === theirs) { + refusals.push({ + reason: `the project's video.manifest.json is this take's: the deliverable is built from it — delete anyway to remove the take (the project keeps its manifest)`, + forceable: true, + }); + } + if (!place) { + const e = await entryOf(dir, `${project.id}/takes/${takeId}/`, st.isSymbolicLink() ? "the take (a link)" : "the take: take.json, its preview, its manifest and renders"); + if (e.entry) { + remove.push(e.entry); + const l = await linkEntries(e.links, [path.resolve(/* turbopackIgnore: true */ dir)], roots); + remove.push(...l.remove); + kept.push(...l.kept); + } + } + kept.push( + { what: `its row in takes/verdicts.json`, why: "kept: the agent that made the takes reads it (a verdict on a take that is gone shows as missing)" }, + { what: "notes on it", why: "kept in the project's notes.json (never hand-edited); they say the take is no longer in takes/" }, + ); + return plan(project.id, { take: takeId, refusals, steps: [], remove, kept }); +} + +/** DELETE TAKE `takeId`: the plan made again, then done. Throws DeleteRefused. */ +export async function deleteTake(project, takeId, opts = {}) { + const p = await planTakeDelete(project, takeId, opts); + if (deleteBlocked(p, opts.force)) throw new DeleteRefused(`take ${takeId} is not deleted: ${p.refusals.map((r) => r.reason).join("; ")}`, p); + return { plan: p, ...(await removeEntries(p.remove, rootsOf(opts))) }; +} diff --git a/umtool/lib/report/delete.test.mjs b/umtool/lib/report/delete.test.mjs @@ -0,0 +1,159 @@ +// Deleting a project or a take (release 27 follow-up): the plan reads only, +// the delete refuses what is in use, never leaves the roots, and follows a link +// only to its own media mirror. Temp trees only. +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { DeleteRefused, deleteBlocked, deleteProject, deleteTake, planProjectDelete, planTakeDelete } from "./delete.mjs"; + +const ROOTS = []; +after(() => { + for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); +}); + +const put = (file, text = "x") => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, text); +}; + +function tree() { + const root = mkdtempSync(path.join(tmpdir(), "umtool-delete-")); + ROOTS.push(root); + const reportsRoot = path.join(root, "reports"); + const mediaRoot = path.join(root, "media"); + const articlesDir = path.join(root, "transcripts", "reports"); + mkdirSync(reportsRoot, { recursive: true }); + mkdirSync(mediaRoot, { recursive: true }); + return { root, reportsRoot, mediaRoot, articlesDir, projectsRoot: path.join(reportsRoot, "articles") }; +} + +const project = (t, id, manifest = { slug: path.basename(id) }) => { + const dir = path.join(t.reportsRoot, id); + put(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)); + put(path.join(dir, "out", "final.mp4"), "f".repeat(2000)); + return { id, dir }; +}; + +test("a project: planned with sizes, then removed; its out/ media mirror goes too, another link's target stays", async () => { + const t = tree(); + const p = project(t, "folder/cut"); + rmSync(path.join(p.dir, "out"), { recursive: true }); + const mirror = path.join(t.mediaRoot, "folder", "cut", "out"); + put(path.join(mirror, "final.mp4"), "m".repeat(4000)); + symlinkSync(mirror, path.join(p.dir, "out")); + const elsewhere = path.join(t.root, "elsewhere"); + put(path.join(elsewhere, "keep.mp4")); + symlinkSync(elsewhere, path.join(p.dir, "clips")); + const sibling = project(t, "folder/other"); + const opts = { reportsRoot: t.reportsRoot, mediaRoot: t.mediaRoot }; + + const plan = await planProjectDelete(p, opts); + assert.deepEqual(plan.refusals, []); + assert.deepEqual(plan.remove.map((e) => e.path), [p.dir, mirror]); + assert.equal(plan.bytes, plan.remove[0].bytes + 4000); + assert.ok(plan.kept.some((k) => k.path === elsewhere)); + assert.ok(existsSync(p.dir), "a plan removes nothing"); + + const res = await deleteProject(p, opts); + assert.deepEqual(res.failed, []); + assert.equal(existsSync(p.dir), false); + assert.equal(existsSync(mirror), false); + assert.ok(existsSync(path.join(elsewhere, "keep.mp4"))); + assert.ok(existsSync(sibling.dir)); + assert.ok(existsSync(path.join(t.reportsRoot, "folder")), "a plain folder is not tidied away"); +}); + +test("a project is refused while a job works in it, outside the root, or as a link", async () => { + const t = tree(); + const opts = { reportsRoot: t.reportsRoot, mediaRoot: t.mediaRoot }; + const p = project(t, "busy"); + const busy = await planProjectDelete(p, { ...opts, busyJob: "build busy" }); + assert.equal(deleteBlocked(busy, true), true); + await assert.rejects(deleteProject(p, { ...opts, busyJob: "build busy", force: true }), DeleteRefused); + assert.ok(existsSync(p.dir)); + + const out = { id: "x", dir: path.join(t.root, "x") }; + mkdirSync(out.dir); + assert.match((await planProjectDelete(out, opts)).refusals[0].reason, /not inside the reports root/); + assert.match((await planProjectDelete({ id: "root", dir: t.reportsRoot }, opts)).refusals[0].reason, /not inside the reports root/); + + const real = path.join(t.root, "real-project"); + put(path.join(real, "video.manifest.json"), "{}"); + symlinkSync(real, path.join(t.reportsRoot, "linked")); + const linked = await planProjectDelete({ id: "linked", dir: path.join(t.reportsRoot, "linked") }, opts); + assert.match(linked.refusals[0].reason, /is a link/); + assert.deepEqual(linked.remove, []); +}); + +test("an iteration project: refused as the current video or while it runs; else its record is named and the emptied folder goes", async () => { + const t = tree(); + const opts = { reportsRoot: t.reportsRoot, mediaRoot: t.mediaRoot, projectsRoot: t.projectsRoot, articlesDir: t.articlesDir }; + const its = path.join(t.articlesDir, "art", "iterations"); + const iteration = (n, status) => put(path.join(its, String(n), "iteration.json"), JSON.stringify({ article: "art", n, status, steps: [] })); + iteration(1, "done"); + iteration(2, "running"); + iteration(3, "done"); + put(path.join(its, "current.json"), JSON.stringify({ report: 1, video: 1 })); + const p1 = project(t, "articles/art/i1"); + const p2 = project(t, "articles/art/i2"); + const p3 = project(t, "articles/art/i3"); + assert.match((await planProjectDelete(p1, opts)).refusals[0].reason, /current video/); + assert.match((await planProjectDelete(p2, opts)).refusals[0].reason, /i2 of "art" is running/); + const plan3 = await planProjectDelete(p3, opts); + assert.deepEqual(plan3.refusals, []); + assert.ok(plan3.kept.some((k) => /i3's iteration record/.test(k.what))); + await deleteProject(p3, opts); + assert.equal(existsSync(p3.dir), false); + assert.ok(existsSync(path.join(t.projectsRoot, "art")), "the folder still holds i1 and i2"); +}); + +test("a project linked to an article with a video is refused unless forced", async () => { + const t = tree(); + const opts = { reportsRoot: t.reportsRoot, mediaRoot: t.mediaRoot, articleVideo: async (ref) => ref === "articles/withvideo" }; + const p = project(t, "linked-video", { slug: "x", article: "articles/withvideo" }); + const plan = await planProjectDelete(p, opts); + assert.equal(plan.refusals.length, 1); + assert.equal(plan.refusals[0].forceable, true); + await assert.rejects(deleteProject(p, opts), DeleteRefused); + await deleteProject(p, { ...opts, force: true }); + assert.equal(existsSync(p.dir), false); + const q = project(t, "linked-plain", { slug: "y", article: "articles/novideo" }); + assert.deepEqual((await planProjectDelete(q, opts)).refusals, []); +}); + +test("a take: removed with its renders; the one the project's manifest is refused unless forced; its verdict is kept", async () => { + const t = tree(); + const opts = { reportsRoot: t.reportsRoot, mediaRoot: t.mediaRoot }; + const p = project(t, "takes-proj", { slug: "p", v: 1 }); + const take = (id, manifest) => { + const dir = path.join(p.dir, "takes", id); + put(path.join(dir, "take.json"), JSON.stringify({ id, group: "g", order: 1, label: id, kind: "similar", preview: "preview.mp4" })); + put(path.join(dir, "preview.mp4"), "p".repeat(500)); + put(path.join(dir, "video.manifest.json"), manifest); + return dir; + }; + const chosen = take("chosen", readFileSync(path.join(p.dir, "video.manifest.json"), "utf8")); + const other = take("other", JSON.stringify({ slug: "p", v: 2 })); + put(path.join(p.dir, "takes", "verdicts.json"), JSON.stringify({ other: { verdict: "no", note: "", at: "" } })); + + const refused = await planTakeDelete(p, "chosen", opts); + assert.equal(refused.refusals[0].forceable, true); + assert.match(refused.refusals[0].reason, /the deliverable is built from it/); + await assert.rejects(deleteTake(p, "chosen", opts), DeleteRefused); + + const plan = await planTakeDelete(p, "other", opts); + assert.deepEqual(plan.refusals, []); + assert.deepEqual(plan.remove.map((e) => e.label), ["takes-proj/takes/other/"]); + await deleteTake(p, "other", opts); + assert.equal(existsSync(other), false); + assert.ok(existsSync(chosen)); + assert.match(readFileSync(path.join(p.dir, "takes", "verdicts.json"), "utf8"), /"other"/, "the verdict row is kept"); + + await deleteTake(p, "chosen", { ...opts, force: true }); + assert.equal(existsSync(chosen), false); + assert.ok(existsSync(path.join(p.dir, "video.manifest.json"))); + await assert.rejects(planTakeDelete(p, "chosen", opts), /has no take chosen/); + await assert.rejects(planTakeDelete(p, "../x", opts), /not a take id/); +});