Archilyzer · Source

archilyzer

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

commit 487ddbbd09aef3246a56ff9124b745eff7a47c53
parent 0e01105cee4d9bc062c2b69ca3c5e381e0913d17
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 17:08:21 -0400

Merge r27/delete: release 27 follow-up — delete an article, an iteration, a project or a take

Diffstat:
MCOMMANDS.md | 3+++
MENVIRONMENT.md | 3+++
MOPERATING.md | 30++++++++++++++++++++++++++++++
MREPORT.md | 8++++++++
Mcommon/bin/archilyzer.ts | 15+++++++++++++++
Acommon/bin/reports-delete.test.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/reports-delete.ts | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 3+++
Acommon/lib/report/delete.test.ts | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/delete.ts | 679+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/docs.ts | 32++++++++++++++++++++++++++++++++
Mcommon/lib/report/iterations.ts | 40++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/report/registry.ts | 44+++++++++++++++++++++++++++++++++++++++++++-
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/ops/_articleDelete.test.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/_articleDelete.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/delete-article/route.ts | 29+++++++++++++++++++++++++++++
Aeditor/app/api/ops/delete-iteration/route.ts | 25+++++++++++++++++++++++++
Mplans/FACTS.md | 5++++-
Mplans/release-27.md | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 23+++++++++++++++++++++++
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++++++++++++
Mumtool/docs/e2e.md | 1+
Mumtool/docs/projects.md | 16+++++++++++++++-
Mumtool/docs/report-video.md | 8++++++++
Mumtool/docs/sites.md | 7+++++++
Aumtool/e2e/article-delete.spec.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/delete-fixture.mjs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 5+++++
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44 files changed, 3068 insertions(+), 9 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -35,6 +35,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports verify-quotes` | `<report.json> \| --article <articleId>` | \[--json\] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) | | `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster &lt;image&gt;\] \[--caption &lt;line&gt;\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) | | `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/&lt;id&gt;/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) | +| `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | | `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers | | `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) | @@ -90,6 +91,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | +| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | +| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` | | `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -87,6 +87,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `CLAUDE_DIGEST_MODEL` | the CLI's default | The model the metered digest lane asks `claude` for when settings name none. | common/lib/digestApps.ts | | `NITTER_INSTANCES` | a built-in list | Comma-separated Nitter instances for the X fallback fetcher, in order of preference. | common/social/xNitterFetcher.ts | | `ARCHILYZER_X_BROWSER` | the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium | The Chromium-family browser /settings' "Connect X account" opens (a path, or a name looked up on PATH), and a forum-thread channel's "Connect forum session" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser. | common/social/xBrowser.ts | +| `UMTOOL_MEDIA_DIR` | unset (no media root: a project link's target is kept) | umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md). | common/lib/report/delete.ts, umtool (lib/paths.mjs) | +| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, umtool (lib/paths.mjs) | +| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does). | common/lib/report/delete.ts, umtool (song/paths.mjs) | | `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts | | `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -252,6 +252,36 @@ pnpm ops report-draft --json '{"task":"sweep","article":"example-article","i editor's queues, holds and cooldowns (one stream, real gaps, backing off on a 429), never yt-dlp or gallery-dl by hand. Keep a local-only subject on no site. +## Delete an article, an iteration, a project or a take + +```sh +pnpm archilyzer reports delete example-article # the plan; nothing is written +pnpm archilyzer reports delete example-article --apply +pnpm archilyzer reports delete example-article --apply --force # a published one: unpublished first +pnpm archilyzer reports delete example-article --iteration 3 --apply +pnpm ops delete-article --json '{"id":"example-article","dryRun":true}' +pnpm ops delete-iteration --json '{"id":"example-article","n":3}' +``` + +- Every delete is a **plan** first: each path that would go with its size, what is kept and why, what refuses. In + umtool the buttons are **Delete article** (the article's page), `Delete i<n>` (its Iterations tab), **Delete + project** (a report-video project's page) and `Delete take <id>` (its takes page); each shows the plan and acts + only on **Confirm delete**. +- **An article** takes its directory (report, video, history, notes, iterations), its iterations' video projects + under the projects root and its staged exports. Refused while published or named by a site page with no report of + its own (force unpublishes and drops the page), and while any iteration runs. +- **An iteration** takes `iterations/<n>/` and its project. Refused: the current article or video, the iteration + the article's report came from, a running one, one another iteration revises or copies. Its number is never + reused. +- **A project** takes its directory, and its `out/` or deliverables on the media drive when they are its own media + copy. Refused while a umtool job works in it, when it is an article's current video or a running iteration's + project, and (unless **delete anyway**) when its manifest names an article with a video attached. +- **A take** takes `takes/<id>/`. The take the project's manifest is (what the deliverable is built from) needs + **delete anyway**. Its verdict and the notes on it are kept. +- Kept always: the generation usage ledger, the shared prepared-media cache (the next prepare prunes it), the git + history of `transcripts/`, a deployed site until it is rebuilt. Nothing outside the known roots is touched; a link + is removed as a link. + ## Publish ```sh diff --git a/REPORT.md b/REPORT.md @@ -136,6 +136,14 @@ An article made or revised by a model keeps each generation as an **iteration**, - An iteration's video project is off the corpus disk, in `<settings.generation.projectsRoot>/<id>/i<n>/` (blank: `~/reports/articles`). - `archilyzer reports iterations <id>` lists an article's iterations; `pnpm ops get iterations <id>` reads them from the editor. +## Deleting an article or an iteration + +`archilyzer reports delete <id> [--iteration <n>] [--apply] [--force]` (also `pnpm ops delete-article` / `delete-iteration`, and umtool's **Delete article** and `Delete i<n>`) deletes through the registry (`lib/report/delete.ts`). Without `--apply` it prints the plan and writes nothing: every path that would go with its size, what is kept and why, and what refuses. + +- **An article:** its directory (report, video, poster, stills, history, notes, iterations), each iteration's video project under the projects root, and its staged exports. Refused while it is published, or while a site's `pages` names its id with no report of its own (`--force` unpublishes it and drops that page first, through the registry and the site's writer); refused while any iteration is queued or running, force or not. A site page that is the site's own report of the same id is a different document and is not touched. +- **An iteration:** `iterations/<n>/` and its project. Refused, with no override: the current article, the iteration its `report.json` came from, the current video, a queued or running one, and one another iteration revises or copies. Its number is retired (`current.json` `highest`): no later iteration is numbered `n` again. +- **Kept:** the generation usage ledger (spend history), the shared prepared-media cache (the next prepare prunes it), the git history of `transcripts/`, and a published build until it is rebuilt. Nothing outside the articles directory, the projects root and the export staging is removed; a link is removed as a link, and its target only when it is the project's own umtool media copy (`UMTOOL_MEDIA_DIR`). + ## Checking quotes `archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`. diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -399,6 +399,21 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["reports", "delete"], + usage: + "<articleId> [--iteration <n>] [--apply] [--force] [--json] delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration)", + flags: { iteration: "string", apply: "boolean", force: "boolean", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [article] = positionals; + if (!article) { + console.error("reports delete: give <articleId>"); + return 2; + } + return (await import("./reports-delete")).deleteRow(article, flags as Parameters<typeof import("./reports-delete").deleteRow>[1]); + }, + }, + { path: ["reports", "import-local-runs"], usage: "[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>] ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused)", diff --git a/common/bin/reports-delete.test.ts b/common/bin/reports-delete.test.ts @@ -0,0 +1,105 @@ +// `archilyzer reports delete` (release 27 follow-up): a dry run by default, +// --apply deletes, --force answers a published article, exit codes. Temp +// stores only. +// +// Run with: node_modules/.bin/tsx --test bin/reports-delete.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { configureArticle, writeArticle } from "../lib/report/registry"; +import { createIteration, updateIteration } from "../lib/report/iterations"; +import { deleteMain, mediaFromEnv } from "./reports-delete"; + +const ROOTS: string[] = []; +after(() => { + for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); +}); + +function setup() { + const root = mkdtempSync(path.join(tmpdir(), "reports-delete-")); + ROOTS.push(root); + const paths = { + articlesDir: path.join(root, "reports"), + exportIndexDir: path.join(root, ".export-index"), + sitesDir: path.join(root, "sites"), + }; + mkdirSync(paths.sitesDir, { recursive: true }); + return { paths, projectsRoot: path.join(root, "projects") }; +} + +const doc = (id: string) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "One", body: "Plain words." }], +}); + +function capture() { + const lines: string[] = []; + const errors: string[] = []; + return { out: { log: (s: string) => lines.push(s), error: (s: string) => errors.push(s) }, lines, errors }; +} + +test("dry by default; --apply deletes; a published article is refused until --force", async () => { + const s = setup(); + await writeArticle(doc("pub"), { paths: s.paths }); + await configureArticle("pub", { published: true }, s.paths); + const base = { article: "pub", projectsRoot: s.projectsRoot, paths: s.paths }; + + const dry = capture(); + assert.equal(await deleteMain({ ...base, force: true }, dry.out), 0); + assert.ok(dry.lines.some((l) => /dry run: nothing deleted/.test(l))); + assert.ok(existsSync(path.join(s.paths.articlesDir, "pub"))); + + const refused = capture(); + assert.equal(await deleteMain({ ...base, apply: true }, refused.out), 1); + assert.ok(refused.lines.some((l) => /refused \(unless --force\): "pub" is published/.test(l))); + assert.ok(existsSync(path.join(s.paths.articlesDir, "pub"))); + + const forced = capture(); + assert.equal(await deleteMain({ ...base, apply: true, force: true }, forced.out), 0); + assert.ok(forced.lines.some((l) => /"pub": deleted/.test(l))); + assert.equal(existsSync(path.join(s.paths.articlesDir, "pub")), false); + + const gone = capture(); + assert.equal(await deleteMain(base, gone.out), 2); + assert.match(gone.errors.join("\n"), /no article "pub"/); +}); + +test("--iteration plans and deletes one iteration; --json carries the plan", async () => { + const s = setup(); + await createIteration("mk", { kind: "sweep", model: "qwen3:8b", question: "Q?" }, s.paths); + await updateIteration("mk", 1, { status: "done" }, s.paths); + await createIteration("mk", { kind: "sweep", model: "qwen3:8b", question: "Q?" }, s.paths); + await updateIteration("mk", 2, { status: "running" }, s.paths); + mkdirSync(path.join(s.projectsRoot, "mk", "i1"), { recursive: true }); + writeFileSync(path.join(s.projectsRoot, "mk", "i1", "video.manifest.json"), "{}"); + const base = { article: "mk", projectsRoot: s.projectsRoot, paths: s.paths }; + + const busy = capture(); + assert.equal(await deleteMain({ ...base, iteration: 2, apply: true }, busy.out), 1); + assert.ok(busy.lines.some((l) => /i2 is running/.test(l))); + + const json = capture(); + assert.equal(await deleteMain({ ...base, iteration: 1, json: true }, json.out), 0); + const parsed = JSON.parse(json.lines.join("\n")) as { applied: boolean; plan: { remove: { label: string }[] } }; + assert.equal(parsed.applied, false); + assert.equal(parsed.plan.remove.length, 2); + + assert.equal(await deleteMain({ ...base, iteration: 1, apply: true }, capture().out), 0); + assert.equal(existsSync(path.join(s.paths.articlesDir, "mk", "iterations", "1")), false); + assert.equal(existsSync(path.join(s.projectsRoot, "mk", "i1")), false); + assert.equal(await deleteMain({ ...base, iteration: 1 }, capture().out), 2); +}); + +test("the media root comes from umtool's environment, and only when it is its own", () => { + assert.equal(mediaFromEnv({}), null); + assert.deepEqual(mediaFromEnv({ UMTOOL_MEDIA_DIR: "/m", REPORTS_DIR: "/r" }), { reportsRoot: "/r", mediaRoot: "/m" }); + assert.equal(mediaFromEnv({ UMTOOL_MEDIA_DIR: "/r", REPORTS_DIR: "/r" }), null); + assert.deepEqual(mediaFromEnv({ UMTOOL_MEDIA_DIR: "/m", SONG_REPORTS_DIR: "/x/reports" }), { reportsRoot: "/x", mediaRoot: "/m" }); +}); diff --git a/common/bin/reports-delete.ts b/common/bin/reports-delete.ts @@ -0,0 +1,138 @@ +// `archilyzer reports delete <id> [--iteration <n>] [--apply] [--force] [--json]` +// (release 27 follow-up) — delete an article, or one of its iterations, through +// the registry (lib/report/delete.ts). +// +// DRY RUN BY DEFAULT: it prints the plan — every path that would go, with its +// size, what is kept and why, and what refuses — and writes nothing. `--apply` +// deletes. `--force` (an article only) unpublishes it and drops a site page +// that names it with no report of its own, first; it never overrides a running +// iteration. +// +// The projects root is settings.generation.projectsRoot (`~` expanded; blank = +// ~/reports/articles). umtool's media root, when UMTOOL_MEDIA_DIR is set here, +// is where a tiered project's `out/` link points (its reports root REPORTS_DIR, +// else ~/reports, as umtool/lib/paths.mjs reads them): such a link's target +// goes with the project. Without it, the target is kept and named. +// +// Exit 0 when the plan is clean (and applied, with --apply); 1 when it is +// refused, or a path could not be removed; 2 for usage, or no such article or +// iteration. + +import os from "node:os"; +import path from "node:path"; +import type { GenerationSettings } from "../lib/generationSettings"; +import type { Paths } from "../lib/paths"; +import { + deleteArticle, + deleteBlocked, + deleteIteration, + DeleteRefusedError, + formatDeletePlan, + planArticleDelete, + planIterationDelete, + deleteMediaFromEnv, + type DeleteMedia, + type DeletePaths, + type DeletePlan, + type DeleteResult, +} from "../lib/report/delete"; +import { ArticleRegistryError } from "../lib/report/registry"; + +export { deleteMediaFromEnv as mediaFromEnv }; + +type Out = { log: (s: string) => void; error: (s: string) => void }; + +export type DeleteMainOptions = { + article: string; + iteration?: number; + apply?: boolean; + force?: boolean; + json?: boolean; + projectsRoot: string; + media?: DeleteMedia | null; + paths: DeletePaths; +}; + +export async function deleteMain(o: DeleteMainOptions, out: Out = console): Promise<number> { + const opts = { projectsRoot: o.projectsRoot, media: o.media ?? null, paths: o.paths, force: o.force === true }; + const name = o.iteration !== undefined ? `"${o.article}" i${o.iteration}` : `"${o.article}"`; + let plan: DeletePlan; + try { + plan = o.iteration !== undefined ? await planIterationDelete(o.article, o.iteration, opts) : await planArticleDelete(o.article, opts); + } catch (err) { + if (err instanceof ArticleRegistryError) { + out.error(`reports delete: ${err.message}`); + return 2; + } + throw err; + } + const blocked = deleteBlocked(plan, opts.force); + if (!o.apply || blocked) { + if (o.json) out.log(JSON.stringify({ applied: false, blocked, plan }, null, 2)); + else { + for (const l of formatDeletePlan(plan, { force: opts.force })) out.log(l); + out.log(blocked ? `nothing deleted: ${name} is refused` : `dry run: nothing deleted — run again with --apply to delete ${name}`); + } + return blocked ? 1 : 0; + } + let result: DeleteResult; + try { + result = o.iteration !== undefined ? await deleteIteration(o.article, o.iteration, opts) : await deleteArticle(o.article, opts); + } catch (err) { + if (err instanceof DeleteRefusedError) { + // Something changed between the plan and the lock. + if (o.json) out.log(JSON.stringify({ applied: false, blocked: true, plan: err.plan }, null, 2)); + else for (const l of formatDeletePlan(err.plan, { force: opts.force })) out.log(l); + out.error(`reports delete: ${err.message}`); + return 1; + } + throw err; + } + if (o.json) out.log(JSON.stringify({ applied: true, ...result }, null, 2)); + else { + for (const l of formatDeletePlan(result.plan, { force: opts.force })) out.log(l); + for (const p of result.removed) out.log(`removed ${p}`); + for (const f of result.failed) out.error(`NOT removed ${f.path}: ${f.error}`); + out.log(result.failed.length ? `${name}: deleted, ${result.failed.length} path(s) left (above)` : `${name}: deleted`); + } + return result.failed.length ? 1 : 0; +} + +const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p); + +// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles +// (controller/reportDraft.ts projectsRootOf, which a bin does not import). +export const projectsRootOf = (gen: Pick<GenerationSettings, "projectsRoot">): string => + gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles"); + +// The CLI row's options, from the flags and the settings. +export async function deleteRow( + article: string, + flags: { iteration?: string; apply?: boolean; force?: boolean; json?: boolean }, +): Promise<number> { + let iteration: number | undefined; + if (flags.iteration !== undefined) { + iteration = Number(flags.iteration); + if (!Number.isInteger(iteration) || iteration < 1) { + console.error(`reports delete: --iteration takes an iteration number (1, 2, …), not "${flags.iteration}"`); + return 2; + } + if (flags.force) { + console.error("reports delete: --force is for an article (unpublish, site pages); an iteration's refusals have no override"); + return 2; + } + } + const { getPaths } = await import("../lib/paths"); + const { getSettings } = await import("../lib/settings"); + const paths: Paths = getPaths(); + return deleteMain({ + article, + ...(iteration !== undefined ? { iteration } : {}), + apply: flags.apply === true, + force: flags.force === true, + json: flags.json === true, + projectsRoot: projectsRootOf(getSettings().generation), + media: deleteMediaFromEnv(), + paths, + }); +} diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -123,6 +123,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "CLAUDE_DIGEST_MODEL", audience: "runtime", default: "the CLI's default", readBy: "common/lib/digestApps.ts", doc: "The model the metered digest lane asks `claude` for when settings name none." }, { name: "NITTER_INSTANCES", audience: "runtime", default: "a built-in list", readBy: "common/social/xNitterFetcher.ts", doc: "Comma-separated Nitter instances for the X fallback fetcher, in order of preference." }, { name: "ARCHILYZER_X_BROWSER", audience: "runtime", default: "the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium", readBy: "common/social/xBrowser.ts", doc: "The Chromium-family browser /settings' \"Connect X account\" opens (a path, or a name looked up on PATH), and a forum-thread channel's \"Connect forum session\" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser." }, + { name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." }, + { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, + { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does)." }, { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, 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,679 @@ +// 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 os from "node:os"; +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); +} + +// umtool's reports and media roots from this process's environment, as +// umtool/lib/paths.mjs reads them (REPORTS_DIR, else dirname of +// SONG_REPORTS_DIR, else ~/reports; UMTOOL_MEDIA_DIR); null when no media root +// of its own is set. +export function deleteMediaFromEnv(env: NodeJS.ProcessEnv = process.env): DeleteMedia | null { + const mediaRoot = env.UMTOOL_MEDIA_DIR; + if (!mediaRoot) return null; + const reportsRoot = env.REPORTS_DIR ?? (env.SONG_REPORTS_DIR ? path.dirname(path.resolve(env.SONG_REPORTS_DIR)) : path.join(os.homedir(), "reports")); + const r = path.resolve(reportsRoot); + const m = path.resolve(mediaRoot); + return r === m ? null : { reportsRoot: r, mediaRoot: m }; +} + +// ─── 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 uniqueByPath = (entries: readonly DeleteEntry[]): DeleteEntry[] => [...new Map(entries.map((e) => [e.path, e])).values()]; + +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); + // What either plan lists — the one made under the lock is what is there now; + // the first walked every link (a media copy) — the article directory as it + // was parked. + const entries = uniqueByPath([...locked.plan.remove, ...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 locked = 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 { plan, parked: await retireIterationHoldingLock(id, n, paths, stamp) }; + }, paths); + const projectsRoot = path.resolve(opts.projectsRoot); + const own = iterationDir(paths, id, n); + const entries = uniqueByPath([...locked.plan.remove, ...first.remove]).map((e) => (e.path === own ? { ...e, path: locked.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/docs.ts b/common/lib/report/docs.ts @@ -197,6 +197,38 @@ export function renderReportMarkdown(): string { "iterations <id>` reads them from the editor.", ); out.push(""); + out.push("## Deleting an article or an iteration"); + out.push(""); + out.push( + "`archilyzer reports delete <id> [--iteration <n>] [--apply] [--force]` (also `pnpm ops " + + "delete-article` / `delete-iteration`, and umtool's **Delete article** and `Delete i<n>`) " + + "deletes through the registry (`lib/report/delete.ts`). Without `--apply` it prints the plan " + + "and writes nothing: every path that would go with its size, what is kept and why, and what " + + "refuses.", + ); + out.push(""); + out.push( + "- **An article:** its directory (report, video, poster, stills, history, notes, iterations), " + + "each iteration's video project under the projects root, and its staged exports. Refused " + + "while it is published, or while a site's `pages` names its id with no report of its own " + + "(`--force` unpublishes it and drops that page first, through the registry and the site's " + + "writer); refused while any iteration is queued or running, force or not. A site page that " + + "is the site's own report of the same id is a different document and is not touched.", + ); + out.push( + "- **An iteration:** `iterations/<n>/` and its project. Refused, with no override: the " + + "current article, the iteration its `report.json` came from, the current video, a queued " + + "or running one, and one another iteration revises or copies. Its number is retired " + + "(`current.json` `highest`): no later iteration is numbered `n` again.", + ); + out.push( + "- **Kept:** the generation usage ledger (spend history), the shared prepared-media cache " + + "(the next prepare prunes it), the git history of `transcripts/`, and a published build " + + "until it is rebuilt. Nothing outside the articles directory, the projects root and the " + + "export staging is removed; a link is removed as a link, and its target only when it is " + + "the project's own umtool media copy (`UMTOOL_MEDIA_DIR`).", + ); + out.push(""); out.push("## Checking quotes"); out.push(""); out.push( 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; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan. +- **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept. - **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor. - **umtool makes and iterates articles: `/articles/new` and an article's Iterations tab.** `/articles/new` takes a question, channels picked from the editor's list, dates, the sweep (the agent on a Claude model or the pipeline on the local model), the model and a cap (the policy's default, which can only go down); **Start** has the editor run it as a report draft and opens the article's iterations. Each iteration shows its kind, model, parent, copy, status, cost per model, minutes, ops applied and refused, and checks, and which one is the article and which the video. On an iteration: **Use this iteration** (the article's report becomes its report), **New iteration** (a revision of the report or the video from your feedback, on a model), **Copy with model**, **Narrate**, **Cancel** (with the running job's log), and **Make the video** (the pipeline chain as a umtool job, step by step, resumable). An article whose only content is iterations is listed on `/articles` as in the making. umtool's `/drafts` page is gone; it opens `/articles/new`. Needs a restart of umtool. - **umtool shows a research run's queue, and /articles/new can start with research.** On an article's Iterations tab, a research iteration lists each acquisition it proposed: what it fetches, why, its evidence links, its estimate, and why it waits or was refused. Each one that waits has Yes and No (with an optional reason). An approved one shows its editor job's state as it runs. Once nothing is pending, **Continue into a sweep** starts the sweep over the run's channels and every channel it acquired into. On /articles/new, "start with research" takes an autonomy (propose, limits or auto; default the settings') and needs no channel. diff --git a/editor/app/api/ops/_articleDelete.test.ts b/editor/app/api/ops/_articleDelete.test.ts @@ -0,0 +1,99 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { callPost, setupOpsCorpus } from "./_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_articleDelete.test.ts" +// +// delete-article and delete-iteration (release 27 follow-up): adapters over +// lib/report/delete.ts — behind the token, a dry run that writes nothing, a +// refusal that is a 409 carrying the plan, and the projects root read from +// settings.generation. + +const corpus = await setupOpsCorpus(null); +const projectsRoot = path.join(corpus.root, "projects"); +await corpus.writeSettings({ minFreeDiskGB: 0, generation: { projectsRoot } }); +test.after(() => corpus.cleanup()); + +type Post = Parameters<typeof callPost>[0]; +const route = async (name: string) => (await import(`./${name}/route`)).POST as Post; +const articles = path.join(corpus.transcripts, "reports"); + +const doc = (id: string) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "One", body: "Plain words." }], +}); + +test("both routes are behind the token and refuse unknown keys", async () => { + for (const name of ["delete-article", "delete-iteration"]) { + const res = await callPost(await route(name), { id: "a" }, {}); + assert.equal(res.status, 401, name); + } + const stray = await callPost(await route("delete-article"), { id: "a", confirm: "a" }); + assert.equal(stray.status, 400); + const badN = await callPost(await route("delete-iteration"), { id: "a", n: "1" }); + assert.equal(badN.status, 400); + assert.match(String(badN.body.error), /iteration number/); +}); + +test("delete-article: a dry run plans, a published one is a 409 with its plan, force deletes", async () => { + const { writeArticle, configureArticle } = await import("yt-dlp-transcript-common/lib/report/registry"); + const { createIteration, updateIteration } = await import("yt-dlp-transcript-common/lib/report/iterations"); + await writeArticle(doc("gone")); + await configureArticle("gone", { published: true }); + await createIteration("gone", { kind: "sweep", model: "qwen3:8b", question: "Q?" }); + await updateIteration("gone", 1, { status: "done" }); + await mkdir(path.join(projectsRoot, "gone", "i1"), { recursive: true }); + await writeFile(path.join(projectsRoot, "gone", "i1", "video.manifest.json"), "{}"); + const post = await route("delete-article"); + + const missing = await callPost(post, { id: "nope", dryRun: true }); + assert.equal(missing.status, 400); + assert.match(String(missing.body.error), /no article "nope"/); + + const refused = await callPost(post, { id: "gone", dryRun: true }); + assert.equal(refused.status, 409); + assert.match(String(refused.body.error), /is published/); + assert.ok((refused.body.plan as { remove: unknown[] }).remove.length >= 2); + + const dry = await callPost(post, { id: "gone", dryRun: true, force: true }); + assert.equal(dry.status, 200); + assert.equal(dry.body.applied, false); + const labels = (dry.body.plan as { remove: { label: string }[] }).remove.map((e) => e.label); + assert.deepEqual(labels, ["reports/gone/", "projects/gone/i1/"]); + assert.ok(existsSync(path.join(articles, "gone", "report.json")), "a dry run writes nothing"); + + const done = await callPost(post, { id: "gone", force: true }); + assert.equal(done.status, 200); + assert.equal(done.body.applied, true); + assert.deepEqual(done.body.failed, []); + assert.equal(existsSync(path.join(articles, "gone")), false); + assert.equal(existsSync(path.join(projectsRoot, "gone")), false); +}); + +test("delete-iteration: a parent is refused with its children named; a leaf goes", async () => { + const { createIteration, updateIteration } = await import("yt-dlp-transcript-common/lib/report/iterations"); + await createIteration("its", { kind: "sweep", model: "qwen3:8b", question: "Q?" }); + await updateIteration("its", 1, { status: "done" }); + await createIteration("its", { kind: "sweep", model: "claude-sonnet-5-5", copyOf: 1 }); + await updateIteration("its", 2, { status: "done" }); + const post = await route("delete-iteration"); + + const parent = await callPost(post, { id: "its", n: 1 }); + assert.equal(parent.status, 409); + assert.match(String(parent.body.error), /i2 is a copy of it/); + + const leaf = await callPost(post, { id: "its", n: 2 }); + assert.equal(leaf.status, 200); + assert.equal(existsSync(path.join(articles, "its", "iterations", "2")), false); + const none = await callPost(post, { id: "its", n: 2, dryRun: true }); + assert.equal(none.status, 400); + assert.match(String(none.body.error), /has no iteration i2/); +}); diff --git a/editor/app/api/ops/_articleDelete.ts b/editor/app/api/ops/_articleDelete.ts @@ -0,0 +1,50 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { projectsRootOf } from "yt-dlp-transcript-common/controller/reportDraft"; +import { + DeleteRefusedError, + deleteBlocked, + deleteMediaFromEnv, + type DeleteOptions, + type DeletePlan, + type DeleteResult, +} from "yt-dlp-transcript-common/lib/report/delete"; +import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry"; +import { OpsInputError, opsFail } from "./_lib"; + +// The two delete routes' shared half (delete-article, delete-iteration): the +// options every generation path resolves the same way, and the one answer +// shape. The rules are lib/report/delete.ts's; nothing here decides. + +export function articleDeleteOptions(force?: boolean): DeleteOptions { + return { + paths: getPaths(), + projectsRoot: projectsRootOf(getSettings().generation), + media: deleteMediaFromEnv(), + ...(force ? { force: true } : {}), + }; +} + +// A dry run answers the plan; a delete the plan and what it removed. A plan +// with a refusal is a 409 carrying the plan, so a caller can say why. +export async function articleDeleteAnswer( + dryRun: boolean, + force: boolean, + plan: () => Promise<DeletePlan>, + apply: () => Promise<DeleteResult>, +): Promise<NextResponse> { + try { + const p = await plan(); + if (deleteBlocked(p, force)) { + return opsFail(`refused: ${p.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason).join("; ")}`, 409, { plan: p }); + } + if (dryRun) return NextResponse.json({ ok: true, applied: false, plan: p }); + const r = await apply(); + return NextResponse.json({ ok: r.failed.length === 0, applied: true, plan: r.plan, removed: r.removed, failed: r.failed }); + } catch (err) { + if (err instanceof DeleteRefusedError) return opsFail(`refused: ${err.problems.join("; ")}`, 409, { plan: err.plan }); + if (err instanceof ArticleRegistryError) throw new OpsInputError(err.message); + throw err; + } +} diff --git a/editor/app/api/ops/delete-article/route.ts b/editor/app/api/ops/delete-article/route.ts @@ -0,0 +1,29 @@ +import { deleteArticle, planArticleDelete } from "yt-dlp-transcript-common/lib/report/delete"; +import { ops, optBool, reqString } from "../_lib"; +import { articleDeleteAnswer, articleDeleteOptions } from "../_articleDelete"; + +export const dynamic = "force-dynamic"; + +// POST { id: string, force?: boolean, dryRun?: boolean } +// -> { ok, applied, plan, removed?, failed? } +// +// DELETE AN ARTICLE (release 27 follow-up), as `archilyzer reports delete` +// does: its directory under transcripts/reports/ (report, video, history, +// notes, iterations), each iteration's video project under +// settings.generation.projectsRoot, and its staged exports — through +// lib/report/delete.ts, under the article registry's lock. `dryRun` answers +// the plan (every path with its size, what is kept and why) and writes +// nothing. Refused (409, with the plan): a published article, or a site page +// naming it with no report of its own — `force` unpublishes it and drops the +// page first; a queued or running iteration, force or not. +// +// There is no undo, and transcripts/ is its own git repo — the only way back +// is a commit there. +export async function POST(request: Request) { + return ops(request, ["id", "force", "dryRun"], async (body) => { + const id = reqString(body, "id"); + const force = optBool(body, "force") === true; + const opts = articleDeleteOptions(force); + return articleDeleteAnswer(optBool(body, "dryRun") === true, force, () => planArticleDelete(id, opts), () => deleteArticle(id, opts)); + }); +} diff --git a/editor/app/api/ops/delete-iteration/route.ts b/editor/app/api/ops/delete-iteration/route.ts @@ -0,0 +1,25 @@ +import { deleteIteration, planIterationDelete } from "yt-dlp-transcript-common/lib/report/delete"; +import { OpsInputError, ops, optBool, reqString } from "../_lib"; +import { articleDeleteAnswer, articleDeleteOptions } from "../_articleDelete"; + +export const dynamic = "force-dynamic"; + +// POST { id: string, n: number, dryRun?: boolean } +// -> { ok, applied, plan, removed?, failed? } +// +// DELETE ONE ITERATION of an article (release 27 follow-up), as `archilyzer +// reports delete <id> --iteration <n>` does: `iterations/<n>/` and its video +// project, through lib/report/delete.ts under the article registry's lock; its +// number is retired. `dryRun` answers the plan and writes nothing. Refused +// (409, with the plan; no override): the current article, the iteration its +// report.json came from, the current video, a queued or running one, and one +// another iteration revises or copies. +export async function POST(request: Request) { + return ops(request, ["id", "n", "dryRun"], async (body) => { + const id = reqString(body, "id"); + const n = body.n; + if (typeof n !== "number" || !Number.isInteger(n) || n < 1) throw new OpsInputError('"n" is an iteration number (1, 2, …)'); + const opts = articleDeleteOptions(); + return articleDeleteAnswer(optBool(body, "dryRun") === true, false, () => planIterationDelete(id, n, opts), () => deleteIteration(id, n, opts)); + }); +} diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9156,7 +9156,10 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri (`writeArticleHoldingLock`, audience and video kept). - **An article in the making** is a directory with `iterations/` and no `report.json` (`isPendingArticleDir`, `registry.ts`). `listArticleDirs` and `readArticleState` leave it out; `listPendingArticles` lists it. The - registry has no delete: an article directory is removed by hand only after the operator's OK. + registry deletes through `common/lib/report/delete.ts` (`planArticleDelete` / `deleteArticle`, `planIterationDelete` + / `deleteIteration`; `archilyzer reports delete`, `pnpm ops delete-article|delete-iteration`, umtool's Delete + buttons): a plan first, then the store's writes and one rename (`.deleting-…`) under the lock, the bulk after it. + An iteration's number is never reused (`current.json` `highest`). - **An article may not be called `new`** (`RESERVED_ARTICLE_IDS`, `assertArticleId`): umtool's `/articles/new` is a page. - **Generation jobs** are job kind `report-draft` on the queues `draft:api` and `draft:local` (`DRAFT_API_QUEUE`, diff --git a/plans/release-27.md b/plans/release-27.md @@ -796,6 +796,126 @@ policy. Owed to the operator: read `$T/r27h-import-dry.txt`, then `archilyzer reports import-local-runs --apply`; then the OK for the 15 test leftovers (307 MB; three registry drafts by hand); `runs/api-shondo-fishing` undecided. +### Follow-up: delete, as shipped (2026-10-13, lane I, `r27/delete`) + +The operator (2026-10-13): "add a delete path for all currently used paths for similar features." Nothing could remove +an article, an iteration, its video project, a umtool report-video project or a take; test drafts could only go by +hand under `transcripts/`. + +**The survey** (each thing, every place it lives or is named): +- **An article:** `reports/<id>/` holds `report.json`, `video.mp4` and `poster.jpg` (real files: articles have no + media tier; `attach-video` writes them in place), `stills/`, `history-git/`, `notes.json` and `iterations/`. + `reports/index.json` lists the published ones. Its staged exports are `.export-index/articles/report-exports/<id>/`. + Its prepared clips are in the shared `report-media/` cache, keyed by moment, not by article (the next prepare + prunes what no published article cites). Its iterations' projects are `<projectsRoot>/<id>/i<n>/`. A umtool + project whose manifest says `"article": "articles/<id>"` links to it. + - A site's `pages` name the SITE's reports (`sites/<s>/reports/<r>/`): a different store and a different + document. The release 26 move dropped each moved id from its site. On this machine, no site's pages name an + article id (one site page, the site's own report). +- **An iteration:** `iterations/<n>/` plus `current.json` (report, reportFrom, video). Its project is `projectOf(…)`, + or the recorded `projectDir`. Other iterations name it as `parent` or `copyOf`. A running job, or a running step + (narration, `chain:*`), is recorded in `iteration.json`. The usage ledger names it by number. +- **A umtool project:** its directory under `REPORTS_ROOT`. A tiered project's `out/`, `clips/` and `share-*` may be + absolute links to `<MEDIA_ROOT>/<project-relative>/<name>` (`storage.mjs`). Its `notes.json`, `revisions/` and + `takes/` are inside it. The project index (`CACHE_DIR/index`) and the links cache are derived. A project is a leaf + of the walk, and may be reached through a link. +- **A take:** `takes/<id>/` (`take.json`, `preview.mp4`, `video.manifest.json`, `out/`). Its verdict is a row of + `takes/verdicts.json`. Notes on it are in the project's `notes.json`. **Nothing records which take a deliverable + was built from**, so "in use" is decided as: the take whose `video.manifest.json` is byte for byte the project's. + +| Commit | What | +| --- | --- | +| `528b08f8` | common `lib/report/delete.ts`: `planArticleDelete`, `deleteArticle`, `planIterationDelete`, `deleteIteration`, `formatDeletePlan`. Registry additions: `unpublishHoldingLock`, `parkArticleDirHoldingLock`. Iteration additions: `current.json` `highest`, `retireIterationHoldingLock`, `iterationDirNumbers` (+ tests) | +| `304a8cd3` | `archilyzer reports delete <id> [--iteration n] [--apply] [--force] [--json]` (`bin/reports-delete.ts`, its row, COMMANDS.md) | +| `051d92fb` | editor `POST /api/ops/delete-article {id, force?, dryRun?}` and `delete-iteration {id, n, dryRun?}` (`_articleDelete.ts`); ACTIONS rows and help; COMMANDS.md | +| `19e62dcc` | umtool `lib/report/delete.mjs` (projects and takes, + tests); routes `/api/articles/delete`, `/api/projects/delete`, `/api/report/takes/delete`; `components/DeletePlan.tsx` and the four controls; `/articles` and `/browse` say what went | +| `c7620bc9`, `28565971` | umtool e2e `article-delete.spec.ts` and its fixture (`delete-fixture.mjs`; the spec writes its draft itself) | +| `4b848a5d`, `ea1bc1cc` | REPORT.md (generated), OPERATING.md "Delete …", `umtool/docs/{projects,report-video,sites,e2e}.md`; ENVIRONMENT.md: `UMTOOL_MEDIA_DIR`, `REPORTS_DIR`, `SONG_REPORTS_DIR` (common reads them now) | +| `c6efc792` | the delete removes what the plan made under the lock lists, plus the first plan's media copies | +| (this commit) | this record; FACTS; CHANGELOG | + +**The design:** +- **Plan, then apply.** A plan reads only. It lists every path that would go (with bytes, files and its biggest + parts), what is kept and why, refusals (each `forceable` or not), and the store writes `force` makes first. Every + surface shows the plan before it acts: the CLI is dry unless `--apply`, ops take `dryRun`, and umtool has + **Confirm delete**. +- **Under the lock:** the plan is made again; with `force`, the site pages are dropped (`patchSite`) and the article + unpublished (`unpublishHoldingLock`). Then ONE rename parks the directory as `.deleting-<id>-<stamp>` + (`iterations/.deleting-<n>-<stamp>` for an iteration; not an id, so no reader sees it). The bulk is removed after + the lock is let go, so a delete of gigabytes never makes the lock look stale. A cut delete's park is listed and + removed by the next plan. +- **Refusals.** + - **An article:** published, or a site page naming its id with no report of its own (forceable: force unpublishes + and drops the page). Any iteration queued or running, or with a running step (never forceable). Its directory + being a link. + - **An iteration (no override):** the current article; the iteration the article's report came from + (`reportFrom`); the current video; busy; a parent or original of another (named). + - **A project:** a link, or reached through one; a umtool job in it; an article's current-video iteration + project; a running iteration's project. A manifest naming an article with a video attached is forceable. + - **A take:** a job in the project. The take the project's manifest is, is forceable. + - **umtool's article route** also refuses while a `chain <id> …` job runs here, and names (and keeps) each + project whose manifest links the article. +- **Roots.** Every removal is strictly inside the articles directory, the projects root, the export staging, or + (for a link that is exactly its umtool media mirror, `<mediaRoot>/<relative to reportsRoot>`) the media root. + Each is re-checked against its root's real path before it is removed. Any other link is removed as a link, and + its target kept and named. + - The media root is umtool's `MEDIA_ROOT` in umtool, and `UMTOOL_MEDIA_DIR` (+ `REPORTS_DIR`) in the CLI and + the editor. Unset, a mirror is kept and named. + - A recorded `projectDir` outside the projects root is kept and named. +- **Numbers are never reused.** `current.json` keeps `highest`, and `createIteration` allocates above it. The + ledger and job logs name iterations by number. +- **Kept, always:** the usage ledger, the shared `report-media/` cache, the git history of `transcripts/`, a deployed + site until rebuilt. A take's verdict row and notes are kept too: the agent reads them, and a missing take shows + as missing. +- **Labels (contracts):** buttons `Delete article`, `Delete i<n>`, `Delete project`, `Delete take <id>`, `Confirm + delete`, `Keep it`. Region `delete <subject>` (`delete i3`, `delete the article <id>`, `delete the project <id>`, + `delete take <id>`). Lists `what goes`, `what is kept`, `refused`. Checkbox `delete anyway`. Attributes + `data-delete-blocked`, `data-delete-path`, `data-delete-bytes`, `data-deleted`. + +Gates: +- tsc clean (all packages), at every commit. +- Unit suites: + - common 4017/4017 (14 new: `lib/report/delete.test.ts` 11, `bin/reports-delete.test.ts` 3; the env test + caught the three umtool variables); + - editor unit 288/288 (`_articleDelete.test.ts` 3 new); + - mcp 343/343; + - `test:scripts` 858 pass + 2 skipped of 860 (`umtool/lib/report/delete.test.mjs` 5 new). +- `docs cli|files|env --check`, `settings example --check`: clean. +- Builds (heavy slot, 5 GB cap): + - editor 54 s (`/api/ops/delete-article`, `/api/ops/delete-iteration`); + - umtool 30 s, the corpus linked for the build only and removed (`/api/articles/delete`, `/api/projects/delete`, + `/api/report/takes/delete`). +- e2e (umtool, foreground, two specs a run): + - `article-delete` + `article-iterations`: 7/7, 39.3 s at `19e62dcc`; 7/7, 39.3 s at `c6efc792`. + - `projects` + `articles`: 24 passed, 1 failed (`articles.spec` counts the store's rows, and the fixture's draft + `omega` was a third). The spec now writes and removes `omega` itself (`28565971`); `article-delete` + + `articles` then went 5/5. + - `takes` + `sites`: 9/9. + - The editor's `ops-api.spec.ts` covers no route of this lane and was not run; the two routes have unit tests + instead. +- **The dry run for the six test articles** (read-only, against the live corpus; `$T/r27i-delete-dry.txt`): none + refused. + + | Article | Paths | Size | + | --- | --- | --- | + | `local-test-shondo-baking` | 1 | 18.6 MiB | + | `local-test-shondo-fishing` | 2 (+ staged exports) | 25.8 MiB | + | `ui-test-shondo-cats` | 1 | 23.4 MiB | + | `r27-smoke-shondo` | 4 (+ `~/reports/articles/…/i5`, `i8`, exports) | 196 MiB | + | `r27-smoke-cancel` | 1, in the making | 38 KiB | + | `r27-smoke-research` | 1, in the making | 332 KiB | + + - About 264 MiB in all. No umtool project's manifest names any of the six. + - The lock file and every directory were checked unchanged after the run. + +Left: +- `busy.mjs`'s `/proc` scan (pipeline processes started outside umtool's job registry) is the CLI's, not a route's. + The project route sees umtool's own jobs only, as the storage movers' routes do. +- A take that fails validation (listed under **skipped**) has no delete button. `planTakeDelete` takes it by + directory name. +- The registry's per-article `.deleting-…` park is listed and removed by the next plan of the same article. Nothing + sweeps a park whose article id is never deleted again. + ## Not in this release - Release 28: the remaining media tasks (clip selection and order, on-screen titles, teaser, flips, threads, YouTube diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -55,6 +55,9 @@ // pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}' // pnpm ops articles-config --json '{"id":"demo-article","published":true}' // pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}' +// pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}' +// pnpm ops delete-article --json '{"id":"demo-article","force":true}' +// pnpm ops delete-iteration --json '{"id":"demo-article","n":3}' // pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' // pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}' // pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}' @@ -262,6 +265,11 @@ const ACTIONS = [ // An article's audience and its place in the published list ({id, // audience?, published?, position?}), through the article registry. "articles-config", + // Delete an article ({id, force?, dryRun?}) or one of its iterations ({id, + // n, dryRun?}) through the article registry: the plan, then the delete. + // Synchronous; no job. + "delete-article", + "delete-iteration", // The channel's lifecycle: the New channel form, and the channel page's // Danger → Rename and Danger → Delete. Synchronous; no job. "create-channel", @@ -957,6 +965,21 @@ export function usage() { ' publishing an article whose report.json has problems (listed). Answers', ' the article as saved.', "", + 'delete-article deletes an article, as `archilyzer reports delete <id>`', + ' does: {"id"}, "dryRun"? (answer the plan — every path with its size, what', + ' is kept and why — and write nothing), "force"? (unpublish it, and drop a', + ' site page naming it with no report of its own, first). It removes the', + ' article\'s directory (report, video, history, notes, iterations), each', + ' iteration\'s video project under settings.generation.projectsRoot and its', + ' staged exports. Refused with the plan (409): a published article or such', + ' a site page without "force"; a queued or running iteration, force or not.', + '', + 'delete-iteration deletes one iteration and its video project: {"id", "n"},', + ' "dryRun"?. Its number is never given again. Refused with the plan (409),', + ' no override: the current article, the iteration its report.json came', + ' from, the current video, a queued or running one, one another revises', + ' or copies.', + "", 'create-channel is the New channel form: {"fields": {"name", "handling":', ' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,', ' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else', 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/docs/e2e.md b/umtool/docs/e2e.md @@ -38,6 +38,7 @@ rendered over a deliverable would be indistinguishable from a person doing it. | `gone-fixture` | its source is gone — the preflight must block it | | `no-origin-fixture` / `localhost-fixture` | the two defects that shipped | | `takes-fixture` | takes **write** `takes/verdicts.json` — two groups, a take with no preview, one skipped take.json, a work dir that is not a take | +| `delete-fixture` | `article-delete.spec.ts` **deletes** a take of it, then the project (`e2e/fixtures/delete-fixture.mjs`, with the article `psi`; the spec writes its draft `omega` itself, since `articles.spec.ts` counts the store's rows) | | `bike-fixture` | the third kind | | `find/` | shadowed by a tool page | | `deep/nested/solo-fixture` | a pass-through chain, for the collapse | diff --git a/umtool/docs/projects.md b/umtool/docs/projects.md @@ -63,7 +63,20 @@ address of its own; it is listed with an `info` decision and reached the same wa `RESERVED_BROWSE` is asserted by an e2e spec to equal the real directory listing of `app/browse/`, so a tenth tool page cannot quietly make a project unreachable. -## Adding a kind +## Deleting a project + +**Delete project** on a report-video project's page (`POST /api/projects/delete`, +`lib/report/delete.mjs`) is the "new project" door's other half. It shows the +plan first — the directory with its size and its biggest parts, and, for an +`out/`, `clips/` or `share-*` that `umtool storage` linked to the media root, +that media copy — and removes it on **Confirm delete**. Refused: a project that +is a link or is reached through one, one a umtool job is working in, an +article's current video (an iteration project `current.json` names) or a running +iteration's project. A project whose manifest names an article with a video +attached needs **delete anyway** (the article keeps its attached copy). Any +other link is removed as a link; its target is kept and named. Nothing outside +`REPORTS_ROOT` and `MEDIA_ROOT` is touched, and neither root itself. + **A registry entry and one view. Nothing else.** @@ -91,6 +104,7 @@ fail when somebody special-cases a kind in a page — which no page test can see | `lib/projects/{report,song,sweep}.mjs` | per-kind reading | | `lib/projects/core.mjs` | the CLI's assembled view | | `lib/projects.ts` | the app's façade: caching, dispatch, the index | +| `lib/report/delete.mjs` | deleting a project or a take: the plan, then the delete | | `lib/project-types.ts` | types only, **no `node:` import ever** | ## Discovered by getting it wrong once diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -715,6 +715,14 @@ Each take also takes notes (a `take` anchor) and timed notes on its preview; the verdicts and those notes reach the agent through `umtool notes <project>`, which lists every take with its verdict and note ([notes.md](notes.md)). +`Delete take <id>` on a take's card shows the plan (`takes/<id>/` with its +size) and removes it on **Confirm delete** (`POST /api/report/takes/delete`, +`lib/report/delete.mjs`). The take whose `video.manifest.json` is byte for byte +the project's own — what the deliverable is built from — needs **delete +anyway**; a umtool job working in the project refuses. Its verdict row and the +notes on it are kept: the agent reads them back, and a verdict on a take that is +gone shows as missing. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/docs/sites.md b/umtool/docs/sites.md @@ -52,6 +52,13 @@ a `report-draft` job the EDITOR runs, asked over its ops API with the shared | **Cancel** | `job cancel` on its editor job; the log's last lines are polled every 2.5 s while it runs | | **Make the video** | the chain (`lib/report/chain.mjs`) as a umtool job: its ten steps, each one's status, resume or **from** a step, cancel | | **compare** | tick two, then **Compare iN and iM** | +| **Delete iN** | the plan (its directory and its project, with sizes; what refuses), then **Confirm delete** — common's `deleteIteration` under the registry's lock. Refused: the current article or video, the iteration the article's report came from, a running one, one another revises or copies | + +**Delete article** (on any article of the store, in the making too) shows the +plan — the article's directory, its iterations' projects, its staged exports, +what is kept — and deletes on **Confirm delete** (common's `deleteArticle`; a +chain of it running here refuses). A published article offers **delete anyway**, +which unpublishes it first. `/articles?deleted=<id>` says what went. The list shows each one's kind, model, parent, copy, status, cost per model, minutes, ops applied and refused, and checks; which is the article and which the diff --git a/umtool/e2e/article-delete.spec.ts b/umtool/e2e/article-delete.spec.ts @@ -0,0 +1,145 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; +import { makeOmega } from "./fixtures/delete-fixture.mjs"; + +// --------------------------------------------------------------------------- +// Deleting (release 27 follow-up): every delete shows its PLAN — what goes, +// with sizes, what is kept, what refuses — and acts only on "Confirm delete". +// The fixture's own (e2e/fixtures/delete-fixture.mjs), so no other spec's +// article or project is touched: +// +// omega a draft, written here (articles.spec.ts counts the +// store's rows): i1 (a parent), i2 (the current +// article), i3 (a copy of i1, with a project) — i3 +// goes, then the whole article +// psi an article in the making — it goes +// reports/delete-fixture a project with takes keep (the project's own +// manifest: refused) and drop — drop goes, then the +// project +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const PROJECTS = path.join(FIXTURE, "gen-projects"); +const PROJECT = path.join(FIXTURE, "reports", "delete-fixture"); + +const dropOmega = () => { + rmSync(path.join(ARTICLES, "omega"), { recursive: true, force: true }); + rmSync(path.join(PROJECTS, "omega"), { recursive: true, force: true }); +}; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + dropOmega(); + makeOmega({ articles: ARTICLES, projects: PROJECTS }); + await warm(playwright, [ + "/articles/omega?tab=iterations", + "/articles/psi", + "/articles", + "/browse/reports/delete-fixture", + "/browse/reports/delete-fixture/takes", + "/browse", + ]); +}); + +test.afterAll(dropOmega); + +const card = (page: Page, n: number) => page.locator(`[data-iteration='${n}']`); + +test("an iteration: the current one and a parent are refused with the reason; a leaf goes with its project; then the draft", async ({ page }) => { + await page.goto("/articles/omega?tab=iterations"); + await expect(page.getByRole("region", { name: "iterations", exact: true })).toHaveAttribute("data-iterations", "3"); + + // The current article: refused, and nothing to confirm. + await card(page, 2).getByRole("button", { name: "Delete i2" }).click(); + const current = page.getByRole("region", { name: "delete i2" }); + await expect(current.getByRole("list", { name: "refused" })).toContainText("i2 is the current article"); + await expect(current.getByRole("button", { name: "Confirm delete" })).toBeDisabled(); + await expect(current.getByRole("checkbox", { name: "delete anyway" })).toHaveCount(0); + await current.getByRole("button", { name: "Keep it" }).click(); + await expect(current).toHaveCount(0); + + // A parent: the iterations that name it are said. + await card(page, 1).getByRole("button", { name: "Delete i1" }).click(); + const parent = page.getByRole("region", { name: "delete i1" }); + await expect(parent.getByRole("list", { name: "refused" })).toContainText("i2 revises it; i3 is a copy of it"); + await expect(parent.getByRole("button", { name: "Confirm delete" })).toBeDisabled(); + await parent.getByRole("button", { name: "Keep it" }).click(); + + // A leaf: the plan names its directory and its project, then it goes. + await card(page, 3).getByRole("button", { name: "Delete i3" }).click(); + const leaf = page.getByRole("region", { name: "delete i3" }); + const goes = leaf.getByRole("list", { name: "what goes" }); + await expect(goes).toContainText("reports/omega/iterations/3/"); + await expect(goes).toContainText("gen-projects/omega/i3/"); + await expect(leaf).toHaveAttribute("data-delete-blocked", "no"); + expect(existsSync(path.join(ARTICLES, "omega", "iterations", "3")), "the plan removes nothing").toBe(true); + await leaf.getByRole("button", { name: "Confirm delete" }).click(); + + await expect(page.getByRole("region", { name: "iterations", exact: true }).getByRole("status")).toContainText("i3 deleted"); + await expect(card(page, 3)).toHaveCount(0); + await expect(page.getByRole("region", { name: "iterations", exact: true })).toHaveAttribute("data-iterations", "2"); + expect(existsSync(path.join(ARTICLES, "omega", "iterations", "3"))).toBe(false); + expect(existsSync(path.join(PROJECTS, "omega", "i3"))).toBe(false); + expect(existsSync(path.join(PROJECTS, "omega", "i1", "video.manifest.json"))).toBe(true); + expect(existsSync(path.join(ARTICLES, "omega", "report.json"))).toBe(true); + + // Then the draft itself: its directory, its iterations and their projects. + await page.getByRole("button", { name: "Delete article" }).click(); + const all = page.getByRole("region", { name: "delete the article omega" }); + await expect(all.getByRole("list", { name: "what goes" })).toContainText("reports/omega/"); + await expect(all.getByRole("list", { name: "what goes" })).toContainText("gen-projects/omega/i1/"); + await all.getByRole("button", { name: "Confirm delete" }).click(); + await expect(page).toHaveURL(/\/articles\?deleted=omega/); + await expect(page.locator("[data-article='articles/omega']")).toHaveCount(0); + expect(existsSync(path.join(ARTICLES, "omega"))).toBe(false); + expect(existsSync(path.join(PROJECTS, "omega")), "the emptied projects folder goes too").toBe(false); +}); + +test("an article in the making is deleted from its page, and /articles says so", async ({ page }) => { + await page.goto("/articles/psi"); + await expect(page.locator("[data-article-meta] [data-status]")).toHaveAttribute("data-status", "pending"); + await page.getByRole("button", { name: "Delete article" }).click(); + const plan = page.getByRole("region", { name: "delete the article psi" }); + await expect(plan.getByRole("list", { name: "what goes" })).toContainText("reports/psi/"); + await plan.getByRole("button", { name: "Confirm delete" }).click(); + + await expect(page).toHaveURL(/\/articles\?deleted=psi/); + await expect(page.locator("[data-deleted='psi']")).toContainText("Deleted psi"); + await expect(page.locator("[data-pending-article='psi']")).toHaveCount(0); + expect(existsSync(path.join(ARTICLES, "psi"))).toBe(false); +}); + +test("a take the project's manifest is, is refused until forced; another take and then the project go", async ({ page }) => { + await page.goto("/browse/reports/delete-fixture/takes"); + const keep = page.locator("[data-take='keep']"); + await keep.getByRole("button", { name: "Delete take keep" }).click(); + const refused = page.getByRole("region", { name: "delete take keep" }); + await expect(refused.getByRole("list", { name: "refused" })).toContainText("the deliverable is built from it"); + await expect(refused.getByRole("button", { name: "Confirm delete" })).toBeDisabled(); + await expect(refused.getByRole("checkbox", { name: "delete anyway" })).toBeVisible(); + await refused.getByRole("button", { name: "Keep it" }).click(); + + await page.locator("[data-take='drop']").getByRole("button", { name: "Delete take drop" }).click(); + const drop = page.getByRole("region", { name: "delete take drop" }); + await expect(drop.getByRole("list", { name: "what goes" })).toContainText("reports/delete-fixture/takes/drop/"); + await drop.getByRole("button", { name: "Confirm delete" }).click(); + await expect(page.locator("[data-take='drop']")).toHaveCount(0); + await expect(keep).toBeVisible(); + expect(existsSync(path.join(PROJECT, "takes", "drop"))).toBe(false); + expect(existsSync(path.join(PROJECT, "takes", "keep", "take.json"))).toBe(true); + + await page.goto("/browse/reports/delete-fixture"); + await page.getByRole("button", { name: "Delete project" }).click(); + const plan = page.getByRole("region", { name: "delete the project reports/delete-fixture" }); + await expect(plan.getByRole("list", { name: "what goes" })).toContainText("reports/delete-fixture"); + await plan.getByRole("button", { name: "Confirm delete" }).click(); + await expect(page).toHaveURL(/\/browse\?deleted=reports%2Fdelete-fixture/); + await expect(page.locator("[data-deleted='reports/delete-fixture']")).toContainText("Deleted reports/delete-fixture"); + await expect(page.locator("[data-project='reports/delete-fixture']")).toHaveCount(0); + expect(existsSync(PROJECT)).toBe(false); +}); diff --git a/umtool/e2e/fixtures/delete-fixture.mjs b/umtool/e2e/fixtures/delete-fixture.mjs @@ -0,0 +1,105 @@ +// What article-delete.spec.ts deletes (release 27 follow-up): its own, so the +// other specs' fixtures (zeta, the report projects) are never touched. +// +// articles/omega/ (makeOmega, written by the spec) a DRAFT +// article (report.json) with iterations: +// iterations/1 sweep, done; project gen-projects/omega/i1 +// iterations/2 revise-report of i1, done: the CURRENT article +// iterations/3 a copy of i1, done; project gen-projects/omega/i3 +// iterations/current.json report i2 +// articles/psi/ an article IN THE MAKING: i1 only +// reports/delete-fixture/ a report-video project with out/ and two takes: +// takes/keep/ its manifest IS the project's (refused) +// takes/drop/ another (deleted) +// +// Synthetic, like every fixture: invented text, the fixture's own channel. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); +}; + +const AT = "2026-10-13T10:00:00.000Z"; +const CITE = { kind: "video", channel: "sitechan", id: "sv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew.", speaker: "Site Channel", date: "2024-03-15" }; + +const report = (id, title) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title, + citations: { c1: CITE }, + sections: [{ id: "s1", title: "The claim", body: "She said [the vote was rigged](cite:c1) in the first stream." }], +}); + +const iteration = (article, n, extra) => ({ + format: "archilyzer-iteration", + version: 1, + article, + n, + parent: null, + copyOf: null, + status: "done", + model: "qwen3:8b", + question: "What did the channel say about the vote?", + scope: { channels: ["sitechan"] }, + usage: {}, + steps: [], + createdAt: AT, + updatedAt: AT, + endedAt: AT, + ...extra, +}); + +const videoManifest = (title) => ({ + title, + provenance: { siteOrigin: "https://archive.example" }, // /browse scans every project: no origin is a BLOCKING defect + timeline: [ + { type: "card", id: "t0", heading: title, narration: { text: "What the channel said about the vote." } }, + { type: "clip", id: "a1", video: "sv1", channel: "sitechan", start: 3, end: 6, quote: "The vote was rigged" }, + ], +}); + +// omega: a draft with three iterations, i2 current — written by the spec +// itself (beforeAll) and removed after, because a draft is a row of /articles +// and articles.spec.ts counts the store's rows. +export function makeOmega({ articles, projects }) { + const its = (id, n) => path.join(articles, id, "iterations", String(n)); + put(path.join(articles, "omega", "report.json"), report("omega", "Omega: the vote, revised")); + put(path.join(its("omega", 1), "iteration.json"), iteration("omega", 1, { kind: "sweep", projectDir: path.join(projects, "omega", "i1") })); + put(path.join(its("omega", 1), "report.json"), report("omega", "Omega: the vote")); + put(path.join(its("omega", 2), "iteration.json"), iteration("omega", 2, { kind: "revise-report", parent: 1, feedback: "Say when.", question: undefined })); + put(path.join(its("omega", 2), "report.json"), report("omega", "Omega: the vote, revised")); + put(path.join(its("omega", 3), "iteration.json"), iteration("omega", 3, { kind: "sweep", copyOf: 1, model: "claude-haiku-4-5", projectDir: path.join(projects, "omega", "i3") })); + put(path.join(its("omega", 3), "report.json"), report("omega", "Omega: the vote, on another model")); + put(path.join(articles, "omega", "iterations", "current.json"), { format: "archilyzer-iterations-current", version: 1, report: 2, reportFrom: 2, video: null, reportAt: AT }); + for (const n of [1, 3]) { + put(path.join(projects, "omega", `i${n}`, "video.manifest.json"), videoManifest(`Omega i${n}`)); + put(path.join(projects, "omega", `i${n}`, "out", "omega.mp4"), "not really a video\n"); + } +} + +export function makeDeleteFixture({ dest, articles, reports }) { + const its = (id, n) => path.join(articles, id, "iterations", String(n)); + + // psi: in the making (not a row of /articles: listed "in the making"). + put(path.join(its("psi", 1), "iteration.json"), iteration("psi", 1, { kind: "sweep" })); + put(path.join(its("psi", 1), "report.json"), report("psi", "Psi: a first look")); + + // A report-video project with two takes. + const project = path.join(reports, "delete-fixture"); + const m = videoManifest("The Delete Fixture"); + put(path.join(project, "video.manifest.json"), m); + put(path.join(project, "out", "final", "delete-fixture.mp4"), "not really a video\n"); + for (const [id, order, manifest] of [ + ["keep", 1, m], + ["drop", 2, { ...m, title: "The Delete Fixture, shorter" }], + ]) { + put(path.join(project, "takes", id, "take.json"), { id, group: "ending", order, label: id === "keep" ? "Kept ending" : "Dropped ending", kind: "similar", preview: "preview.mp4" }); + put(path.join(project, "takes", id, "preview.mp4"), "not really a video\n"); + put(path.join(project, "takes", id, "video.manifest.json"), manifest); + } + return { project }; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -24,6 +24,7 @@ import { SONG_DATA } from "../../song/paths.mjs"; import { songCapabilities } from "./song-capabilities.mjs"; import { makeSitesFixture } from "./sites-fixture.mjs"; import { makeIterationsFixture } from "./iterations-fixture.mjs"; +import { makeDeleteFixture } from "./delete-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1910,6 +1911,10 @@ writeProject("timeline-fixture", { const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); // Release 27: an article in the making (zeta), its projects, today's usage. makeIterationsFixture({ dest, articles: ARTICLES }); +// The release 27 follow-up's deletes: psi (in the making) and +// reports/delete-fixture (a project with two takes); article-delete.spec.ts +// writes its draft (omega) itself. +makeDeleteFixture({ dest, articles: ARTICLES, reports }); console.log(`fixture at ${dest}`); console.log(` SITES_DIR=${SITES}`); 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/); +});