commit b38d78f6fee59f4948991158784bb99dc5b46d79
parent 0e01105cee4d9bc062c2b69ca3c5e381e0913d17
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 16:38:02 -0400
common: delete an article or an iteration — a plan with sizes, then the delete under the registry's lock
planArticleDelete / deleteArticle and planIterationDelete / deleteIteration
(lib/report/delete.ts). An article: its directory, its iterations' video
projects under the projects root, its staged exports; refused while published
or named by a site page with no report of its own unless forced (then
unpublished and dropped through the registry and patchSite), and always while
an iteration runs. An iteration: refused when current (article, its report's
source or video), busy, or a parent or original of another; its number is
retired (current.json highest). The store's writes and one rename are made
under the lock; the bulk is removed after it. Nothing outside the known roots;
a project link is followed to its target only when it is the umtool media
mirror.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 1050 insertions(+), 3 deletions(-)
diff --git a/common/lib/report/delete.test.ts b/common/lib/report/delete.test.ts
@@ -0,0 +1,309 @@
+// Deleting an article or an iteration (release 27 follow-up, lane I): a plan
+// that reads only, then the delete — refused for what is in use, never outside
+// the known roots. Temp stores only.
+//
+// Run with: node_modules/.bin/tsx --test lib/report/delete.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { configureArticle, readArticlesIndex, writeArticle } from "./registry";
+import {
+ createIteration,
+ currentIteration,
+ makeCurrent,
+ projectOf,
+ setCurrentVideo,
+ updateIteration,
+ writeIterationFile,
+} from "./iterations";
+import {
+ DeleteRefusedError,
+ deleteArticle,
+ deleteBlocked,
+ deleteIteration,
+ formatDeletePlan,
+ planArticleDelete,
+ planIterationDelete,
+} from "./delete";
+
+const ROOTS: string[] = [];
+after(() => {
+ for (const r of ROOTS) rmSync(r, { recursive: true, force: true });
+});
+
+function setup() {
+ const root = mkdtempSync(path.join(tmpdir(), "article-delete-"));
+ ROOTS.push(root);
+ const paths = {
+ articlesDir: path.join(root, "transcripts", "reports"),
+ exportIndexDir: path.join(root, ".export-index"),
+ sitesDir: path.join(root, "transcripts", "sites"),
+ };
+ mkdirSync(paths.articlesDir, { recursive: true });
+ mkdirSync(paths.sitesDir, { recursive: true });
+ const reportsRoot = path.join(root, "reports");
+ const projectsRoot = path.join(reportsRoot, "articles");
+ const mediaRoot = path.join(root, "media");
+ mkdirSync(projectsRoot, { recursive: true });
+ mkdirSync(mediaRoot, { recursive: true });
+ return { root, paths, projectsRoot, reportsRoot, mediaRoot, opts: { paths, projectsRoot } };
+}
+
+const doc = (id: string, over: Record<string, unknown> = {}) => ({
+ format: "archilyzer-report",
+ version: 1,
+ id,
+ kind: "sweep",
+ title: `Article ${id}`,
+ sections: [{ id: "s1", title: "One", body: "Plain words." }],
+ ...over,
+});
+
+const NOW = new Date("2026-10-13T12:00:00.000Z");
+const put = (file: string, text = "x") => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, text);
+};
+
+type Setup = ReturnType<typeof setup>;
+
+async function iteration(s: Setup, id: string, over: { parent?: number; copyOf?: number; report?: boolean; status?: "done" | "running" | "queued" } = {}) {
+ const it = await createIteration(
+ id,
+ over.parent
+ ? { kind: "revise-report", model: "qwen3:8b", parent: over.parent, feedback: "tighter" }
+ : over.copyOf
+ ? { kind: "sweep", model: "qwen3:8b", copyOf: over.copyOf }
+ : { kind: "sweep", model: "qwen3:8b", question: "What was said?" },
+ s.paths,
+ NOW,
+ );
+ if (over.report !== false) await writeIterationFile(id, it.n, "report.json", doc(id, { title: `i${it.n}` }), s.paths);
+ await updateIteration(id, it.n, { status: over.status ?? "done", projectDir: projectOf(s.projectsRoot, id, it.n) }, s.paths, NOW);
+ put(path.join(projectOf(s.projectsRoot, id, it.n), "video.manifest.json"), "{}");
+ put(path.join(projectOf(s.projectsRoot, id, it.n), "out", "final.mp4"), "y".repeat(1000));
+ return it.n;
+}
+
+test("a draft with iterations, projects and staged exports: planned with sizes, then all of it goes", async () => {
+ const s = setup();
+ await writeArticle(doc("draft-a"), { paths: s.paths });
+ put(path.join(s.paths.articlesDir, "draft-a", "video.mp4"), "v".repeat(5000));
+ put(path.join(s.paths.articlesDir, "draft-a", "notes.json"), "{}");
+ await iteration(s, "draft-a");
+ await iteration(s, "draft-a", { parent: 1 });
+ put(path.join(s.paths.exportIndexDir, "articles", "report-exports", "draft-a", "report.html"), "<p>");
+ // Another article's files are never touched.
+ await writeArticle(doc("other"), { paths: s.paths });
+ put(path.join(s.projectsRoot, "other", "i1", "video.manifest.json"), "{}");
+
+ const plan = await planArticleDelete("draft-a", s.opts);
+ assert.deepEqual(plan.refusals, []);
+ assert.equal(deleteBlocked(plan), false);
+ assert.deepEqual(
+ plan.remove.map((e) => e.label),
+ ["reports/draft-a/", "articles/draft-a/i1/", "articles/draft-a/i2/", ".export-index/articles/report-exports/draft-a/"],
+ );
+ const dir = plan.remove[0];
+ assert.equal(dir.parts?.[0].name, "video.mp4", "the biggest part first");
+ assert.ok(dir.parts?.some((p) => p.name === "iterations/"));
+ assert.ok(plan.bytes >= 5000 + 2000);
+ assert.ok(plan.kept.some((k) => /usage ledger/.test(k.what)));
+ assert.ok(formatDeletePlan(plan).some((l) => l.includes("remove reports/draft-a/")));
+ // A plan writes nothing.
+ assert.ok(existsSync(path.join(s.paths.articlesDir, "draft-a", "report.json")));
+
+ const res = await deleteArticle("draft-a", s.opts, NOW);
+ assert.deepEqual(res.failed, []);
+ assert.equal(existsSync(path.join(s.paths.articlesDir, "draft-a")), false);
+ assert.equal(existsSync(path.join(s.projectsRoot, "draft-a")), false, "the emptied projects folder goes too");
+ assert.equal(existsSync(path.join(s.paths.exportIndexDir, "articles", "report-exports", "draft-a")), false);
+ assert.deepEqual(readdirSync(s.paths.articlesDir).filter((n) => !n.startsWith(".registry")).sort(), ["other"], "no .deleting- leftover");
+ assert.ok(existsSync(path.join(s.projectsRoot, "other", "i1", "video.manifest.json")));
+ await assert.rejects(planArticleDelete("draft-a", s.opts), /no article "draft-a"/);
+});
+
+test("an article in the making (no report.json) is deleted like any other", async () => {
+ const s = setup();
+ await iteration(s, "pending-b", { report: false });
+ const plan = await planArticleDelete("pending-b", s.opts);
+ assert.equal(plan.hasReport, false);
+ assert.match(plan.remove[0].what, /in the making/);
+ await deleteArticle("pending-b", s.opts, NOW);
+ assert.equal(existsSync(path.join(s.paths.articlesDir, "pending-b")), false);
+});
+
+test("a published article is refused unless forced; force unpublishes it through the registry", async () => {
+ const s = setup();
+ await writeArticle(doc("pub"), { paths: s.paths });
+ await writeArticle(doc("stays"), { paths: s.paths });
+ await configureArticle("pub", { published: true }, s.paths);
+ await configureArticle("stays", { published: true }, s.paths);
+ const plan = await planArticleDelete("pub", s.opts);
+ assert.equal(plan.refusals.length, 1);
+ assert.equal(plan.refusals[0].forceable, true);
+ assert.match(plan.refusals[0].reason, /is published/);
+ await assert.rejects(deleteArticle("pub", s.opts, NOW), (e: unknown) => e instanceof DeleteRefusedError && /published/.test(e.message));
+ assert.ok(existsSync(path.join(s.paths.articlesDir, "pub", "report.json")), "refused: nothing written");
+ assert.deepEqual((await readArticlesIndex(s.paths)).published, ["pub", "stays"]);
+
+ const forced = await planArticleDelete("pub", { ...s.opts, force: true });
+ assert.ok(forced.steps.some((l) => /unpublish "pub"/.test(l)));
+ assert.equal(deleteBlocked(forced, true), false);
+ await deleteArticle("pub", { ...s.opts, force: true }, NOW);
+ assert.deepEqual((await readArticlesIndex(s.paths)).published, ["stays"]);
+ assert.equal(existsSync(path.join(s.paths.articlesDir, "pub")), false);
+});
+
+test("a queued or running iteration refuses the article's delete, force or not", async () => {
+ const s = setup();
+ await writeArticle(doc("busy"), { paths: s.paths });
+ await iteration(s, "busy", { status: "running" });
+ const plan = await planArticleDelete("busy", { ...s.opts, force: true });
+ assert.equal(deleteBlocked(plan, true), true);
+ assert.match(plan.refusals[0].reason, /i1 is running/);
+ await assert.rejects(deleteArticle("busy", { ...s.opts, force: true }, NOW), DeleteRefusedError);
+ // A narration step running counts too.
+ await updateIteration("busy", 1, { status: "done", steps: [{ task: "narrate", status: "running", jobId: "j9" }] }, s.paths, NOW);
+ assert.match((await planArticleDelete("busy", s.opts)).refusals[0].reason, /narrate step is running \(job j9\)/);
+});
+
+test("site pages: the site's own report of the same id is kept; a page with no report of its own refuses unless forced", async () => {
+ const s = setup();
+ await writeArticle(doc("dup"), { paths: s.paths });
+ put(path.join(s.paths.sitesDir, "owner", "site.json"), JSON.stringify({ siteTitle: "Owner", pages: ["dup"] }));
+ put(path.join(s.paths.sitesDir, "owner", "reports", "dup", "report.json"), JSON.stringify(doc("dup")));
+ put(path.join(s.paths.sitesDir, "stale", "site.json"), JSON.stringify({ siteTitle: "Stale", pages: ["dup", "keep-me"] }));
+ const plan = await planArticleDelete("dup", s.opts);
+ assert.equal(plan.refusals.length, 1);
+ assert.match(plan.refusals[0].reason, /site stale lists a page "dup"/);
+ assert.ok(plan.kept.some((k) => /site owner's page "dup"/.test(k.what)));
+ await deleteArticle("dup", { ...s.opts, force: true }, NOW);
+ const stale = JSON.parse(readFileSync(path.join(s.paths.sitesDir, "stale", "site.json"), "utf8")) as { pages: string[] };
+ assert.deepEqual(stale.pages, ["keep-me"]);
+ const owner = JSON.parse(readFileSync(path.join(s.paths.sitesDir, "owner", "site.json"), "utf8")) as { pages: string[] };
+ assert.deepEqual(owner.pages, ["dup"], "the owner's page is its own report: untouched");
+ assert.ok(existsSync(path.join(s.paths.sitesDir, "owner", "reports", "dup", "report.json")));
+});
+
+test("links: a project's out/ linked to its media mirror goes with its target; any other link's target is kept", async () => {
+ const s = setup();
+ const media = { reportsRoot: s.reportsRoot, mediaRoot: s.mediaRoot };
+ await writeArticle(doc("tiered"), { paths: s.paths });
+ const n = await iteration(s, "tiered");
+ const proj = projectOf(s.projectsRoot, "tiered", n);
+ rmSync(path.join(proj, "out"), { recursive: true });
+ const mirror = path.join(s.mediaRoot, "articles", "tiered", "i1", "out");
+ put(path.join(mirror, "final.mp4"), "m".repeat(3000));
+ symlinkSync(mirror, path.join(proj, "out"));
+ // A link to somewhere else: removed as a link, its target untouched.
+ const elsewhere = path.join(s.root, "elsewhere");
+ put(path.join(elsewhere, "keep.mp4"), "k");
+ symlinkSync(elsewhere, path.join(proj, "clips"));
+ // Without the media root named, the mirror is not known: kept.
+ const blind = await planArticleDelete("tiered", s.opts);
+ assert.ok(blind.kept.some((k) => k.path === mirror));
+ const plan = await planArticleDelete("tiered", { ...s.opts, media });
+ const m = plan.remove.find((e) => e.path === mirror);
+ assert.ok(m, "the mirror is listed");
+ assert.equal(m.bytes, 3000);
+ assert.ok(plan.kept.some((k) => k.path === elsewhere));
+ await deleteArticle("tiered", { ...s.opts, media }, NOW);
+ assert.equal(existsSync(mirror), false);
+ assert.ok(existsSync(path.join(elsewhere, "keep.mp4")));
+ assert.ok(existsSync(s.mediaRoot), "the media root itself stays");
+});
+
+test("an article directory that is a link is refused; a project recorded outside the root is kept", async () => {
+ const s = setup();
+ const real = path.join(s.root, "real-dir");
+ put(path.join(real, "report.json"), JSON.stringify(doc("linked")));
+ symlinkSync(real, path.join(s.paths.articlesDir, "linked"));
+ const plan = await planArticleDelete("linked", s.opts);
+ assert.equal(deleteBlocked(plan, true), true);
+ assert.match(plan.refusals[0].reason, /is a link/);
+
+ await writeArticle(doc("far"), { paths: s.paths });
+ const it = await createIteration("far", { kind: "sweep", model: "qwen3:8b", question: "Q?" }, s.paths, NOW);
+ const outside = path.join(s.root, "outside-project");
+ put(path.join(outside, "video.manifest.json"), "{}");
+ await updateIteration("far", it.n, { status: "done", projectDir: outside }, s.paths, NOW);
+ const far = await planArticleDelete("far", s.opts);
+ assert.ok(far.kept.some((k) => k.path === outside && /outside the projects root/.test(k.why)));
+ await deleteArticle("far", s.opts, NOW);
+ assert.ok(existsSync(path.join(outside, "video.manifest.json")));
+});
+
+test("a cut delete's parked directory is listed and removed by the next delete", async () => {
+ const s = setup();
+ await writeArticle(doc("cut"), { paths: s.paths });
+ put(path.join(s.paths.articlesDir, ".deleting-cut-20261013T000000Z-1", "video.mp4"), "v");
+ const plan = await planArticleDelete("cut", s.opts);
+ assert.ok(plan.remove.some((e) => e.label === "reports/.deleting-cut-20261013T000000Z-1/"));
+ await deleteArticle("cut", s.opts, NOW);
+ assert.deepEqual(readdirSync(s.paths.articlesDir).filter((n) => n !== ".registry.lock"), []);
+});
+
+test("an iteration: refused when current, the report's source, the video, busy or a parent; a leaf goes with its project", async () => {
+ const s = setup();
+ await writeArticle(doc("its"), { paths: s.paths });
+ await iteration(s, "its"); // i1
+ await iteration(s, "its", { parent: 1 }); // i2 revises i1
+ await iteration(s, "its", { copyOf: 1 }); // i3 copy of i1
+ await iteration(s, "its", { parent: 1 }); // i4
+ await iteration(s, "its", { status: "running" }); // i5
+ await makeCurrent("its", 2, s.paths, NOW);
+ await setCurrentVideo("its", 4, s.paths, NOW);
+
+ const reasons = async (n: number) => (await planIterationDelete("its", n, s.opts)).refusals.map((r) => r.reason).join(" | ");
+ assert.match(await reasons(1), /i2 revises it; i3 is a copy of it; i4 revises it: delete those first/);
+ assert.match(await reasons(2), /i2 is the current article/);
+ assert.match(await reasons(4), /i4 is the article's current video/);
+ assert.match(await reasons(5), /i5 is running/);
+ for (const n of [1, 2, 4, 5]) await assert.rejects(deleteIteration("its", n, s.opts, NOW), DeleteRefusedError);
+
+ const plan = await planIterationDelete("its", 3, s.opts);
+ assert.deepEqual(plan.refusals, []);
+ assert.deepEqual(plan.remove.map((e) => e.label), ["reports/its/iterations/3/", "articles/its/i3/"]);
+ await deleteIteration("its", 3, s.opts, NOW);
+ assert.equal(existsSync(path.join(s.paths.articlesDir, "its", "iterations", "3")), false);
+ assert.equal(existsSync(projectOf(s.projectsRoot, "its", 3)), false);
+ assert.ok(existsSync(projectOf(s.projectsRoot, "its", 1)));
+ assert.deepEqual(readdirSync(path.join(s.paths.articlesDir, "its", "iterations")).filter((n) => n.startsWith(".")), []);
+ // The current is kept, and the number is retired.
+ const cur = await currentIteration("its", s.paths);
+ assert.deepEqual([cur.report, cur.video, cur.highest], [2, 4, 5]);
+ await assert.rejects(planIterationDelete("its", 3, s.opts), /has no iteration i3/);
+
+ // The report's source: i6 a video revision of i2 made current reads i2's report.
+ const i6 = await createIteration("its", { kind: "revise-video", model: "qwen3:8b", parent: 2, feedback: "shorter" }, s.paths, NOW);
+ assert.equal(i6.n, 6, "never 3 again");
+ await updateIteration("its", 6, { status: "done" }, s.paths, NOW);
+ await makeCurrent("its", 6, s.paths, NOW);
+ assert.match(await reasons(2), /report\.json is i2's \(current: i6\)/);
+});
+
+test("the highest number survives deleting the newest iteration: the next is not reused", async () => {
+ const s = setup();
+ await iteration(s, "nums", { report: false }); // i1
+ await iteration(s, "nums", { report: false }); // i2
+ await deleteIteration("nums", 2, s.opts, NOW);
+ const next = await createIteration("nums", { kind: "sweep", model: "qwen3:8b", question: "Q?" }, s.paths, NOW);
+ assert.equal(next.n, 3);
+ await updateIteration("nums", 3, { status: "cancelled" }, s.paths, NOW);
+ // An article in the making with its last iteration gone: the project folder goes once empty.
+ await deleteIteration("nums", 3, s.opts, NOW);
+ await deleteIteration("nums", 1, s.opts, NOW);
+ assert.equal(existsSync(path.join(s.projectsRoot, "nums")), false);
+ assert.ok(lstatSync(path.join(s.paths.articlesDir, "nums", "iterations")).isDirectory());
+});
+
+test("ids and numbers are checked before anything is read", async () => {
+ const s = setup();
+ await assert.rejects(planArticleDelete("../etc", s.opts), /not an article id/);
+ await assert.rejects(planIterationDelete("ok-id", 0, s.opts), /not an iteration number/);
+ await assert.rejects(planIterationDelete("ok-id", 1, s.opts), /has no iteration i1/);
+});
diff --git a/common/lib/report/delete.ts b/common/lib/report/delete.ts
@@ -0,0 +1,660 @@
+// DELETING AN ARTICLE OR ONE OF ITS ITERATIONS (release 27 follow-up, lane I).
+//
+// Each is a PLAN and an APPLY:
+//
+// planArticleDelete / planIterationDelete READ ONLY: what would go (every
+// path, with its size), what is
+// kept and why, and what refuses
+// deleteArticle / deleteIteration the same plan made again under
+// the article store's lock, then
+// done
+//
+// WHAT AN ARTICLE IS, on disk (the survey, plans/release-27.md "Follow-up:
+// delete, as shipped"):
+// transcripts/reports/<id>/ report.json, video.mp4,
+// poster.jpg, stills/, sources/,
+// history-git/, notes.json,
+// iterations/ — removed whole
+// transcripts/reports/index.json the published list: a published
+// article is refused, unless
+// `force` (then unpublished first,
+// through the registry)
+// <projectsRoot>/<id>/i<n>/ each iteration's video project
+// (D1) — removed; the article's
+// folder too once it is empty
+// .export-index/articles/report-exports/<id>/ its staged exports — removed
+// sites/<s>/site.json `pages` a site's pages are the SITE's
+// reports (sites/<s>/reports/<r>/),
+// a different document: one of the
+// same id is kept and named. A page
+// naming the id with no report of
+// its own (a leftover of the
+// release 26 move) is refused,
+// unless `force` (then dropped,
+// through patchSite)
+// KEPT, always: the generation usage ledger (spend history); the shared
+// prepared-media cache (`report-media/`, pruned by the next prepare); the git
+// history of transcripts/ (the corpus repo's own business); a published
+// build until it is rebuilt and deployed.
+//
+// AN ITERATION: `iterations/<n>/` and its project `projectOf(projectsRoot,
+// id, n)` (and a recorded `projectDir` inside the projects root). Refused:
+// the current article or video, the iteration the article's report.json came
+// from, one that is queued or running (or a step of it is), and one another
+// iteration names as `parent` or `copyOf` (delete those first). Its NUMBER is
+// retired (`current.json` `highest`): the ledger and job logs name it.
+//
+// NEVER OUTSIDE THE KNOWN ROOTS. Every path removed is inside the articles
+// directory, the projects root, the export staging or — for a project's
+// `out/`, `clips/` or `share-*` that umtool's move-out made a link to the
+// media root — exactly that link's mirror under the media root
+// (`<mediaRoot>/<path relative to reportsRoot>`, umtool/lib/paths.mjs
+// mediaMirror), when the caller names the media root. Any other link is
+// removed as a link and its target kept and named. Nothing follows a link.
+//
+// THE LOCK IS HELD FOR THE STORE'S WRITES ONLY: unpublishing, the site
+// pages, and one rename that parks the directory as `.deleting-…` (no reader
+// sees it from then on). The bulk — gigabytes of renders — is removed after
+// the lock is let go, so a long delete never makes the lock look stale. A
+// delete cut in the middle leaves a `.deleting-…` directory, which the next
+// plan of the same article lists and removes.
+//
+// SERVER-ONLY (node:fs).
+
+import type { Dirent } from "node:fs";
+import { lstat, readdir, readlink, realpath, rm, rmdir, stat } from "node:fs/promises";
+import path from "node:path";
+import { getPaths, type Paths } from "../paths";
+import { getSite, listSiteIds, patchSite } from "../site";
+import { isCitedSite, parseSiteReports } from "../siteSchema";
+import {
+ ARTICLE_DELETING_PREFIX,
+ ArticleRegistryError,
+ assertArticleId,
+ articleDir,
+ parkArticleDirHoldingLock,
+ readArticlesIndex,
+ unpublishHoldingLock,
+ withArticleStoreLock,
+} from "./registry";
+import {
+ DELETING_PREFIX,
+ iterationDir,
+ iterationDirNumbers,
+ iterationLabel,
+ iterationsDir,
+ projectOf,
+ readIterations,
+ retireIterationHoldingLock,
+ type Iteration,
+} from "./iterations";
+import { articleReportStore } from "./store";
+
+// The paths a delete reads and writes. A full Paths satisfies it; a test
+// names its own three directories.
+export type DeletePaths = Pick<Paths, "articlesDir" | "exportIndexDir" | "sitesDir">;
+
+// Where umtool keeps a tiered project's bulk (umtool/lib/paths.mjs
+// REPORTS_ROOT and MEDIA_ROOT). Given, a project link that is exactly its
+// mirror there has its target removed too.
+export type DeleteMedia = { reportsRoot: string; mediaRoot: string };
+
+export type DeleteOptions = {
+ // settings.generation.projectsRoot, resolved (`~` expanded; blank =
+ // ~/reports/articles) — the caller's, as every generation path is.
+ projectsRoot: string;
+ media?: DeleteMedia | null;
+ paths?: DeletePaths;
+ // An article: unpublish it and drop its leftover site pages first.
+ force?: boolean;
+ // Sizes: on by default. Off for the re-plan under the lock.
+ measure?: boolean;
+};
+
+// One thing that would go: a directory, a file or a link.
+export type DeleteEntry = {
+ path: string;
+ // How a person reads it: `reports/<id>/`, `projects/<id>/i3/`, ….
+ label: string;
+ what: string;
+ kind: "dir" | "file" | "link" | "absent";
+ bytes: number;
+ files: number;
+ // A directory's top-level entries, biggest first (an article dir's
+ // report.json, video.mp4, iterations/, …).
+ parts?: { name: string; bytes: number }[];
+};
+
+export type DeleteKept = { what: string; path?: string; why: string };
+export type DeleteRefusal = { reason: string; forceable: boolean };
+
+export type DeletePlan = {
+ article: string;
+ // The iteration, for an iteration's plan.
+ n?: number;
+ // An article: whether report.json is there (false: in the making).
+ hasReport?: boolean;
+ published?: boolean;
+ refusals: DeleteRefusal[];
+ // Store writes made before anything is removed (with `force`).
+ steps: string[];
+ remove: DeleteEntry[];
+ kept: DeleteKept[];
+ bytes: number;
+ files: number;
+};
+
+// Refused: nothing was written. The plan says why.
+export class DeleteRefusedError extends ArticleRegistryError {
+ constructor(
+ message: string,
+ readonly plan: DeletePlan,
+ ) {
+ super(message, plan.refusals.map((r) => r.reason));
+ this.name = "DeleteRefusedError";
+ }
+}
+
+export type DeleteResult = {
+ plan: DeletePlan;
+ // What was removed, and what could not be (the rest was still tried).
+ removed: string[];
+ failed: { path: string; error: string }[];
+};
+
+// Whether a plan stops a delete: any refusal, or — with `force` — any that
+// force does not answer.
+export function deleteBlocked(plan: Pick<DeletePlan, "refusals">, force = false): boolean {
+ return plan.refusals.some((r) => !force || !r.forceable);
+}
+
+// ─── Paths ───
+
+const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep);
+const strictlyInside = (root: string, p: string) => p !== root && inside(root, p);
+
+// `p` is under `root` lexically, and its parent's real path is under the
+// root's real path (a link on the way out of the root is refused).
+async function assertUnder(root: string, p: string, what: string): Promise<void> {
+ const r = path.resolve(root);
+ const abs = path.resolve(p);
+ if (!strictlyInside(r, abs)) throw new ArticleRegistryError(`${what} (${abs}) is not inside ${r}: refused`);
+ const [realRoot, realParent] = await Promise.all([realpath(r).catch(() => null), realpath(path.dirname(abs)).catch(() => null)]);
+ if (realRoot && realParent && !inside(realRoot, realParent)) {
+ throw new ArticleRegistryError(`${what} (${abs}) resolves outside ${r} (${realParent}): refused`);
+ }
+}
+
+type Measured = {
+ kind: DeleteEntry["kind"];
+ bytes: number;
+ files: number;
+ parts: { name: string; bytes: number }[];
+ // Links met inside a directory, with their targets (resolved, not followed).
+ links: { path: string; target: string }[];
+};
+
+async function linkTarget(p: string): Promise<string> {
+ return path.resolve(path.dirname(p), await readlink(p));
+}
+
+// Sizes, never following a link. `measure: false` answers the kind only.
+async function measure(p: string, sizes: boolean): Promise<Measured> {
+ const st = await lstat(p).catch(() => null);
+ if (!st) return { kind: "absent", bytes: 0, files: 0, parts: [], links: [] };
+ if (st.isSymbolicLink()) return { kind: "link", bytes: 0, files: 0, parts: [], links: [{ path: p, target: await linkTarget(p) }] };
+ if (!st.isDirectory()) return { kind: "file", bytes: st.size, files: 1, parts: [], links: [] };
+ const out: Measured = { kind: "dir", bytes: 0, files: 0, parts: [], links: [] };
+ const walk = async (dir: string, top: { name: string; bytes: number } | null): Promise<void> => {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ const child = path.join(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 linkTarget(child).catch(() => "?") });
+ if (!top) part.name = `${e.name} (link)`;
+ } else if (e.isDirectory()) {
+ if (sizes) await walk(child, part);
+ } else if (sizes) {
+ const s = await lstat(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;
+}
+
+async function entryOf(p: string, label: string, what: string, sizes: boolean): Promise<{ entry: DeleteEntry; links: Measured["links"] }> {
+ const m = await measure(p, sizes);
+ 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,
+ };
+}
+
+const LINK_KEPT_WHY = "a link: it is removed, and what it points at is kept (not this project's own media copy)";
+
+// The links met in what is removed: a project link that is exactly its
+// umtool media mirror is removed with its target; any other link's target is
+// kept, and named.
+async function linkEntries(
+ links: Measured["links"],
+ removing: readonly string[],
+ media: DeleteMedia | null | undefined,
+ sizes: boolean,
+): Promise<{ remove: DeleteEntry[]; kept: DeleteKept[] }> {
+ const out = { remove: [] as DeleteEntry[], kept: [] as DeleteKept[] };
+ for (const l of links) {
+ if (removing.some((r) => inside(r, l.target))) continue; // goes with the tree
+ const mirror = media && strictlyInside(path.resolve(media.reportsRoot), l.path)
+ ? path.join(path.resolve(media.mediaRoot), path.relative(path.resolve(media.reportsRoot), l.path))
+ : null;
+ if (media && mirror && l.target === mirror && strictlyInside(path.resolve(media.mediaRoot), l.target)) {
+ const { entry } = await entryOf(l.target, l.target, `the media copy ${path.basename(l.path)}/ links to`, sizes);
+ if (entry.kind !== "absent") out.remove.push(entry);
+ continue;
+ }
+ out.kept.push({ what: `${l.path} → ${l.target}`, path: l.target, why: LINK_KEPT_WHY });
+ }
+ return out;
+}
+
+const ITERATION_PROJECT_RE = /^i[1-9]\d{0,8}$/;
+
+const ledgerKept = (): DeleteKept => ({
+ what: "the generation usage ledger's rows",
+ why: "spend history: kept whatever is deleted",
+});
+
+const busyReason = (it: Iteration): string | null => {
+ if (it.status === "queued" || it.status === "running") {
+ return `${iterationLabel(it.n)} is ${it.status}${it.jobId ? ` (job ${it.jobId})` : ""}: cancel it, or wait for it to end`;
+ }
+ const step = it.steps.find((s) => s.status === "running");
+ return step ? `${iterationLabel(it.n)}'s ${step.task} step is running${step.jobId ? ` (job ${step.jobId})` : ""}: wait for it to end` : null;
+};
+
+function totals(plan: Omit<DeletePlan, "bytes" | "files">): DeletePlan {
+ return {
+ ...plan,
+ bytes: plan.remove.reduce((s, e) => s + e.bytes, 0),
+ files: plan.remove.reduce((s, e) => s + e.files, 0),
+ };
+}
+
+// ─── An article ───
+
+type SitePage = { site: string; ownReport: boolean };
+
+async function sitePagesNaming(paths: DeletePaths, id: string): Promise<SitePage[]> {
+ const out: SitePage[] = [];
+ for (const site of listSiteIds(paths as Paths)) {
+ const pages = parseSiteReports(getSite(site, paths as Paths).pages);
+ if (!pages.includes(id)) continue;
+ const own = await stat(path.join(paths.sitesDir, site, "reports", id)).then((s) => s.isDirectory(), () => false);
+ out.push({ site, ownReport: own });
+ }
+ return out;
+}
+
+// The export staging of the article store: `<stagingDir>/report-exports/<id>/`
+// (publish/reportExportFiles.ts REPORT_EXPORTS_DIRNAME; lib may not import
+// publish).
+const ARTICLE_EXPORTS_DIRNAME = "report-exports";
+
+export function articleExportsDir(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): string {
+ return path.join(articleReportStore(paths).stagingDir, ARTICLE_EXPORTS_DIRNAME, id);
+}
+
+async function leftoverParks(dir: string, prefix: string): Promise<string[]> {
+ const names = await readdir(dir).catch(() => [] as string[]);
+ return names.filter((n) => n.startsWith(prefix)).sort().map((n) => path.join(dir, n));
+}
+
+// WHAT DELETING ARTICLE `id` WOULD DO. Reads only. Throws for an id that is
+// not one, and for an article that is nowhere (no directory, not published,
+// no projects, nothing staged).
+export async function planArticleDelete(id: string, opts: DeleteOptions): Promise<DeletePlan> {
+ assertArticleId(id);
+ const paths = opts.paths ?? getPaths();
+ const sizes = opts.measure !== false;
+ const projectsRoot = path.resolve(opts.projectsRoot);
+ const refusals: DeleteRefusal[] = [];
+ const steps: string[] = [];
+ const remove: DeleteEntry[] = [];
+ const kept: DeleteKept[] = [];
+ const links: Measured["links"] = [];
+ const add = async (p: string, label: string, what: string) => {
+ const e = await entryOf(p, label, what, sizes);
+ if (e.entry.kind === "absent") return false;
+ remove.push(e.entry);
+ links.push(...e.links);
+ return true;
+ };
+
+ const dir = articleDir(paths, id);
+ const dirSt = await lstat(dir).catch(() => null);
+ const index = await readArticlesIndex(paths);
+ const published = index.published.includes(id);
+ const hasReport = !!(await stat(path.join(dir, "report.json")).catch(() => null))?.isFile();
+
+ if (dirSt?.isSymbolicLink()) {
+ refusals.push({ reason: `reports/${id} is a link (to ${await linkTarget(dir)}), not an article directory: remove it by hand`, forceable: false });
+ } else if (dirSt && !dirSt.isDirectory()) {
+ refusals.push({ reason: `reports/${id} is not a directory: remove it by hand`, forceable: false });
+ }
+
+ // Its iterations: any busy one refuses; each one's project goes.
+ const recorded = new Set<string>();
+ if (dirSt?.isDirectory()) {
+ const read = await readIterations(id, paths);
+ for (const it of read.iterations) {
+ const busy = busyReason(it);
+ if (busy) refusals.push({ reason: busy, forceable: false });
+ if (it.projectDir) recorded.add(path.resolve(it.projectDir));
+ }
+ for (const p of read.problems) {
+ kept.push({ what: `${iterationLabel(p.n)}'s iteration.json`, why: `unsound (${p.problems.join("; ")}): its directory goes with the article all the same` });
+ }
+ }
+
+ if (published) {
+ refusals.push({
+ reason: `"${id}" is published (reports/index.json, position ${index.published.indexOf(id)}): unpublish it first, or delete with force`,
+ forceable: true,
+ });
+ if (opts.force) steps.push(`unpublish "${id}" (reports/index.json)`);
+ }
+
+ for (const page of await sitePagesNaming(paths, id)) {
+ if (page.ownReport) {
+ kept.push({
+ what: `site ${page.site}'s page "${id}"`,
+ path: path.join(paths.sitesDir, page.site, "reports", id),
+ why: "the site's own report (sites/<site>/reports/), a different document from the article: untouched",
+ });
+ continue;
+ }
+ refusals.push({
+ reason: `site ${page.site} lists a page "${id}" with no report of its own (sites/${page.site}/reports/${id}/ is not there): drop it from the site's pages, or delete with force`,
+ forceable: true,
+ });
+ if (opts.force) steps.push(`drop the page "${id}" from site ${page.site} (site.json pages)`);
+ }
+
+ if (dirSt?.isDirectory()) await add(dir, `reports/${id}/`, hasReport ? "the article directory" : "the article in the making (iterations, no report.json)");
+ for (const p of await leftoverParks(paths.articlesDir, `${ARTICLE_DELETING_PREFIX}${id}-`)) {
+ await add(p, `reports/${path.basename(p)}/`, "what a cut delete of this article left");
+ }
+
+ // The video projects: <projectsRoot>/<id>/i<n>/, and any recorded elsewhere
+ // under the root.
+ const projectsDir = path.join(projectsRoot, id);
+ const projectsSt = await lstat(projectsDir).catch(() => null);
+ let projectsFolderEmptied = false;
+ if (projectsSt?.isSymbolicLink()) {
+ kept.push({ what: projectsDir, path: await linkTarget(projectsDir), why: "the article's projects folder is a link: nothing under it is removed" });
+ } else if (projectsSt?.isDirectory()) {
+ await assertUnder(projectsRoot, projectsDir, "the article's projects folder");
+ const names = await readdir(projectsDir).catch(() => [] as string[]);
+ let others = 0;
+ for (const name of names.sort()) {
+ const p = path.join(projectsDir, name);
+ if (ITERATION_PROJECT_RE.test(name)) {
+ await add(p, `${path.basename(projectsRoot)}/${id}/${name}/`, `${name}'s video project`);
+ recorded.delete(path.resolve(p));
+ } else {
+ others += 1;
+ kept.push({ what: p, path: p, why: "not an iteration's project (i<n>): kept, and the folder with it" });
+ }
+ }
+ projectsFolderEmptied = others === 0;
+ }
+ for (const p of recorded) {
+ if (inside(projectsDir, p)) continue;
+ if (strictlyInside(projectsRoot, p)) {
+ await assertUnder(projectsRoot, p, "an iteration's recorded project");
+ await add(p, p, "an iteration's video project (as recorded)");
+ } else {
+ kept.push({ what: p, path: p, why: "an iteration's recorded project outside the projects root: never removed from here" });
+ }
+ }
+
+ await add(articleExportsDir(paths, id), `.export-index/articles/${ARTICLE_EXPORTS_DIRNAME}/${id}/`, "its staged exports");
+
+ if (remove.length === 0 && !published && refusals.length === 0) {
+ throw new ArticleRegistryError(`no article "${id}" (no reports/${id}/, not published, no projects or staged exports)`);
+ }
+
+ const removing = remove.map((e) => e.path);
+ const l = await linkEntries(links, removing, opts.media, sizes);
+ remove.push(...l.remove);
+ kept.push(...l.kept);
+ if (projectsFolderEmptied && projectsSt?.isDirectory()) steps.push(`remove ${projectsDir} once it is empty`);
+ kept.push(
+ ledgerKept(),
+ { what: "the prepared media cache (.export-index/articles/report-media/)", why: "shared by every article: the next `reports prepare --articles` prunes what no published article cites" },
+ { what: "the git history of transcripts/", why: "the corpus repo's own business: never rewritten" },
+ );
+ if (published) kept.push({ what: "the published homepage", why: "carries the article until the homepage is rebuilt and deployed" });
+
+ return totals({ article: id, hasReport, published, refusals, steps, remove, kept });
+}
+
+// Remove what a plan lists, after the store's writes: every path checked
+// against its root again, a link removed as a link.
+async function removeEntries(
+ entries: readonly DeleteEntry[],
+ roots: readonly string[],
+): Promise<Pick<DeleteResult, "removed" | "failed">> {
+ const out: Pick<DeleteResult, "removed" | "failed"> = { removed: [], failed: [] };
+ for (const e of entries) {
+ try {
+ const root = roots.map((r) => path.resolve(r)).find((r) => strictlyInside(r, path.resolve(e.path)));
+ if (!root) throw new Error(`not inside a known root (${roots.join(", ")}): refused`);
+ await assertUnder(root, e.path, e.label);
+ await rm(e.path, { recursive: true, force: true });
+ out.removed.push(e.path);
+ } catch (err) {
+ out.failed.push({ path: e.path, error: (err as Error).message });
+ }
+ }
+ return out;
+}
+
+const stampOf = (now: Date) => `${now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${process.pid}`;
+
+// DELETE ARTICLE `id`. Refused (DeleteRefusedError, nothing written) while
+// the plan has a refusal `force` does not answer. Under the store's lock: the
+// plan made again, the site pages (force), the unpublish (force), and the
+// directory parked; then the bulk removed.
+export async function deleteArticle(id: string, opts: DeleteOptions, now: Date = new Date()): Promise<DeleteResult> {
+ const paths = opts.paths ?? getPaths();
+ const first = await planArticleDelete(id, opts);
+ if (deleteBlocked(first, opts.force)) throw new DeleteRefusedError(`"${id}" is not deleted`, first);
+ const stamp = stampOf(now);
+ const locked = await withArticleStoreLock(async () => {
+ const plan = await planArticleDelete(id, { ...opts, measure: false });
+ if (deleteBlocked(plan, opts.force)) throw new DeleteRefusedError(`"${id}" is not deleted`, plan);
+ if (opts.force) {
+ for (const page of await sitePagesNaming(paths, id)) {
+ if (page.ownReport) continue;
+ await patchSite(
+ page.site,
+ (cur) => {
+ const pages = (cur.pages ?? []).filter((x) => x !== id);
+ // Its last page gone, a search-off site would be refused on save
+ // (siteSearchProblem): it is retired as move-to-articles retires one.
+ return pages.length === 0 && isCitedSite(cur) ? { pages, search: true } : { pages };
+ },
+ paths as Paths,
+ );
+ }
+ await unpublishHoldingLock(id, paths);
+ }
+ const parked = await parkArticleDirHoldingLock(id, paths, stamp);
+ return { plan, parked };
+ }, paths);
+ const projectsRoot = path.resolve(opts.projectsRoot);
+ const entries = first.remove.map((e) =>
+ locked.parked && e.path === articleDir(paths, id) ? { ...e, path: locked.parked } : e,
+ );
+ const roots = [paths.articlesDir, projectsRoot, paths.exportIndexDir, ...(opts.media ? [opts.media.mediaRoot] : [])];
+ const done = await removeEntries(entries, roots);
+ const projectsDir = path.join(projectsRoot, id);
+ if (first.steps.some((s) => s.startsWith(`remove ${projectsDir}`))) {
+ await rmdir(projectsDir).then(
+ () => done.removed.push(projectsDir),
+ () => {},
+ );
+ }
+ return { plan: first, ...done };
+}
+
+// ─── An iteration ───
+
+// WHAT DELETING ITERATION `n` OF `id` WOULD DO. Reads only. Throws for an
+// iteration that is not there.
+export async function planIterationDelete(id: string, n: number, opts: DeleteOptions): Promise<DeletePlan> {
+ assertArticleId(id);
+ if (!Number.isInteger(n) || n < 1) throw new ArticleRegistryError(`${String(n)} is not an iteration number (1, 2, …)`);
+ const paths = opts.paths ?? getPaths();
+ const sizes = opts.measure !== false;
+ const projectsRoot = path.resolve(opts.projectsRoot);
+ const label = iterationLabel(n);
+ if (!(await iterationDirNumbers(id, paths)).includes(n)) throw new ArticleRegistryError(`"${id}" has no iteration ${label}`);
+ const read = await readIterations(id, paths);
+ const it = read.iterations.find((x) => x.n === n) ?? null;
+ const refusals: DeleteRefusal[] = [];
+ const refuse = (reason: string) => refusals.push({ reason, forceable: false });
+ const cur = read.current;
+ if (cur.report === n) refuse(`${label} is the current article: use another iteration first`);
+ else if (cur.reportFrom === n) refuse(`the article's report.json is ${label}'s (current: ${iterationLabel(cur.report ?? n)}): use another iteration first`);
+ if (cur.video === n) refuse(`${label} is the article's current video: attach another iteration's video first`);
+ if (it) {
+ const busy = busyReason(it);
+ if (busy) refuse(busy);
+ }
+ const children = read.iterations.filter((x) => x.n !== n && (x.parent === n || x.copyOf === n));
+ if (children.length) {
+ refuse(
+ `${children.map((c) => `${iterationLabel(c.n)} ${c.parent === n ? "revises" : "is a copy of"} it`).join("; ")}: delete ${children.length === 1 ? "it" : "those"} first`,
+ );
+ }
+
+ const remove: DeleteEntry[] = [];
+ const kept: DeleteKept[] = [];
+ const links: Measured["links"] = [];
+ const add = async (p: string, l: string, what: string) => {
+ const e = await entryOf(p, l, what, sizes);
+ if (e.entry.kind === "absent") return;
+ remove.push(e.entry);
+ links.push(...e.links);
+ };
+ await add(iterationDir(paths, id, n), `reports/${id}/iterations/${n}/`, `${label}: its iteration.json, report, sweep and turns`);
+ for (const p of await leftoverParks(iterationsDir(paths, id), `${DELETING_PREFIX}${n}-`)) {
+ await add(p, `reports/${id}/iterations/${path.basename(p)}/`, `what a cut delete of ${label} left`);
+ }
+ const projects = new Set<string>([path.resolve(projectOf(projectsRoot, id, n))]);
+ if (it?.projectDir) projects.add(path.resolve(it.projectDir));
+ for (const p of projects) {
+ if (!strictlyInside(projectsRoot, p)) {
+ kept.push({ what: p, path: p, why: "a recorded project outside the projects root: never removed from here" });
+ continue;
+ }
+ const st = await lstat(p).catch(() => null);
+ if (!st) continue;
+ await assertUnder(projectsRoot, p, `${label}'s video project`);
+ await add(p, path.relative(path.dirname(projectsRoot), p) + "/", `${label}'s video project`);
+ }
+ const l = await linkEntries(links, remove.map((e) => e.path), opts.media, sizes);
+ remove.push(...l.remove);
+ kept.push(...l.kept, ledgerKept(), { what: `the number ${label}`, why: "retired: the next iteration is never numbered n again (current.json highest)" });
+ const steps = [`retire ${label}'s number (iterations/current.json)`];
+ const projectsDir = path.join(projectsRoot, id);
+ if (remove.some((e) => strictlyInside(projectsDir, e.path))) steps.push(`remove ${projectsDir} if nothing else is left in it`);
+ return totals({ article: id, n, refusals, steps, remove, kept });
+}
+
+// DELETE ITERATION `n` OF `id`. Refused (DeleteRefusedError, nothing written)
+// while its plan has any refusal. Under the store's lock: the plan made
+// again, the number retired and the directory parked; then the bulk removed.
+export async function deleteIteration(id: string, n: number, opts: DeleteOptions, now: Date = new Date()): Promise<DeleteResult> {
+ const paths = opts.paths ?? getPaths();
+ const first = await planIterationDelete(id, n, opts);
+ if (deleteBlocked(first)) throw new DeleteRefusedError(`"${id}" ${iterationLabel(n)} is not deleted`, first);
+ const stamp = stampOf(now);
+ const parked = await withArticleStoreLock(async () => {
+ const plan = await planIterationDelete(id, n, { ...opts, measure: false });
+ if (deleteBlocked(plan)) throw new DeleteRefusedError(`"${id}" ${iterationLabel(n)} is not deleted`, plan);
+ return retireIterationHoldingLock(id, n, paths, stamp);
+ }, paths);
+ const projectsRoot = path.resolve(opts.projectsRoot);
+ const own = iterationDir(paths, id, n);
+ const entries = first.remove.map((e) => (e.path === own ? { ...e, path: parked } : e));
+ const roots = [paths.articlesDir, projectsRoot, ...(opts.media ? [opts.media.mediaRoot] : [])];
+ const done = await removeEntries(entries, roots);
+ const projectsDir = path.join(projectsRoot, id);
+ if (strictlyInside(projectsRoot, projectsDir) && (await readdir(projectsDir).catch(() => null))?.length === 0) {
+ await rmdir(projectsDir).then(
+ () => done.removed.push(projectsDir),
+ () => {},
+ );
+ }
+ return { plan: first, ...done };
+}
+
+// ─── Saying it ───
+
+export function formatBytes(n: number): string {
+ if (n < 1024) return `${n} B`;
+ const units = ["KiB", "MiB", "GiB", "TiB"];
+ let v = n / 1024;
+ let u = 0;
+ while (v >= 1024 && u < units.length - 1) {
+ v /= 1024;
+ u += 1;
+ }
+ return `${v.toFixed(v >= 100 ? 0 : 1)} ${units[u]}`;
+}
+
+// A plan as lines, for a terminal or a job log.
+export function formatDeletePlan(plan: DeletePlan, opts: { force?: boolean } = {}): string[] {
+ const what = plan.n !== undefined ? `"${plan.article}" ${iterationLabel(plan.n)}` : `"${plan.article}"`;
+ const out: string[] = [];
+ const blocked = deleteBlocked(plan, opts.force);
+ out.push(
+ `delete ${what}: ${plan.remove.length} path(s), ${formatBytes(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`,
+ );
+ for (const r of plan.refusals) {
+ out.push(` refused${r.forceable ? (opts.force ? " (force answers it)" : " (unless --force)") : ""}: ${r.reason}`);
+ }
+ for (const s of plan.steps) out.push(` then: ${s}`);
+ for (const e of plan.remove) {
+ out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${formatBytes(e.bytes)} in ${e.files} file(s)`}${e.label === e.path ? "" : ` (${e.path})`}`);
+ for (const p of (e.parts ?? []).slice(0, 12)) out.push(` ${p.name} ${formatBytes(p.bytes)}`);
+ if ((e.parts?.length ?? 0) > 12) out.push(` … ${e.parts!.length - 12} more`);
+ }
+ for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`);
+ return out;
+}
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -33,7 +33,7 @@
//
// SERVER-ONLY (node:fs).
-import { appendFile, mkdir, readdir, readFile } from "node:fs/promises";
+import { appendFile, mkdir, readdir, readFile, rename } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { getPaths, type Paths } from "../paths";
@@ -165,6 +165,11 @@ export type IterationsCurrent = {
video: number | null;
reportAt?: string;
videoAt?: string;
+ // The highest iteration number ever allocated, kept once an iteration is
+ // deleted (./delete.ts) so a number is never handed out twice: the usage
+ // ledger and job logs name iterations by number. Absent = the highest
+ // directory on disk.
+ highest?: number;
};
const NO_CURRENT: IterationsCurrent = { report: null, reportFrom: null, video: null };
@@ -270,6 +275,7 @@ async function readCurrent(paths: StorePaths, id: string): Promise<IterationsCur
video: num(v.video),
...(typeof v.reportAt === "string" ? { reportAt: v.reportAt } : {}),
...(typeof v.videoAt === "string" ? { videoAt: v.videoAt } : {}),
+ ...(num(v.highest) !== null ? { highest: num(v.highest) as number } : {}),
};
}
@@ -404,7 +410,7 @@ async function createLocked(id: string, input: NewIteration, paths: StorePaths,
throw new ArticleRegistryError(`a ${input.kind} iteration needs its question`);
}
const taken = await iterationNumbers(paths, id);
- const n = (taken[taken.length - 1] ?? 0) + 1;
+ const n = Math.max(taken[taken.length - 1] ?? 0, (await readCurrent(paths, id)).highest ?? 0) + 1;
const at = now.toISOString();
const raw: Iteration = {
format: ITERATION_FORMAT,
@@ -742,6 +748,36 @@ export async function setCurrentVideo(
}, paths);
}
+// The numbers of an article's iteration directories, ascending (a sound
+// iteration.json or not) — what a delete plans over.
+export async function iterationDirNumbers(id: string, paths: StorePaths = getPaths()): Promise<number[]> {
+ assertId(id);
+ return iterationNumbers(paths, id);
+}
+
+// RETIRE ITERATION `n`'s NUMBER and take its directory out of the store, for
+// a caller HOLDING withArticleStoreLock (./delete.ts deleteIteration, which
+// has already refused a current, busy or parent iteration). The directory is
+// RENAMED to `iterations/.deleting-<n>-<stamp>` — not an iteration name, so no
+// reader sees it from here on — and the caller removes it after the lock is
+// let go. `current.json` keeps `highest`, so `n` is never allocated again.
+// Answers the parked directory.
+export async function retireIterationHoldingLock(id: string, n: number, paths: StorePaths, stamp: string): Promise<string> {
+ assertId(id);
+ assertN(n);
+ const taken = await iterationNumbers(paths, id);
+ if (!taken.includes(n)) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ const was = await readCurrent(paths, id);
+ const highest = Math.max(was.highest ?? 0, ...taken);
+ await writeCurrent(paths, id, { ...was, highest });
+ const parked = path.join(iterationsDir(paths, id), `${DELETING_PREFIX}${n}-${stamp}`);
+ await rename(iterationDir(paths, id, n), parked);
+ return parked;
+}
+
+// What a delete parks a directory as, until it is removed (./delete.ts).
+export const DELETING_PREFIX = ".deleting-";
+
// Whether the article has a report.json (an article in the making has not).
export async function hasArticleReport(id: string, paths: StorePaths = getPaths()): Promise<boolean> {
return (await readJsonFile(articleFile(paths, id))).ok;
diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts
@@ -19,6 +19,10 @@
// an article in the making, not
// listed (listPendingArticles)
// transcripts/reports/.registry.lock held while a write runs
+// transcripts/reports/.deleting-<id>-… an article a delete has parked
+// (./delete.ts): not an id, so
+// never listed; removed after the
+// lock is let go
//
// THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and
// server actions) around an O_EXCL lock file (across processes: a generator
@@ -40,7 +44,7 @@
// SERVER-ONLY (node:fs).
import type { Dirent } from "node:fs";
-import { mkdir, open, readdir, readFile, rm, stat } from "node:fs/promises";
+import { lstat, mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { getPaths, type Paths } from "../paths";
@@ -577,3 +581,41 @@ export async function writeArticleHoldingLock(doc: unknown, opts: WriteArticleOp
await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true });
return parsed.value;
}
+
+// ─── Deleting (./delete.ts) ───
+//
+// The two writes a delete makes to the store, for a caller HOLDING
+// withArticleStoreLock (./delete.ts deleteArticle, which plans, refuses and
+// removes the bulk). Nothing else calls them.
+
+// What a delete parks a directory as until it is removed: not an article id,
+// so no listing sees it from the moment it is renamed.
+export const ARTICLE_DELETING_PREFIX = ".deleting-";
+
+// Take `id` out of the published list. Answers whether it was in it.
+export async function unpublishHoldingLock(id: string, paths: Pick<Paths, "articlesDir">): Promise<boolean> {
+ assertId(id);
+ const index = await readArticlesIndex(paths);
+ if (!index.published.includes(id)) return false;
+ await writeIndex(paths, { published: index.published.filter((x) => x !== id) });
+ return true;
+}
+
+// Rename `reports/<id>/` to `reports/.deleting-<id>-<stamp>/` (one rename: the
+// article is gone for every reader at once). Answers the parked directory, or
+// null when there was none. A directory that is a symlink is refused — the
+// planner refuses it first.
+export async function parkArticleDirHoldingLock(
+ id: string,
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir">,
+ stamp: string,
+): Promise<string | null> {
+ assertId(id);
+ const dir = articleDir(paths, id);
+ const st = await lstat(dir).catch(() => null);
+ if (!st) return null;
+ if (!st.isDirectory()) throw new ArticleRegistryError(`reports/${id} is not a directory (a link?): remove it by hand`);
+ const parked = path.join(paths.articlesDir, `${ARTICLE_DELETING_PREFIX}${id}-${stamp}`);
+ await rename(dir, parked);
+ return parked;
+}