Archilyzer · Source

archilyzer

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

commit 6601f3aa56ca83afed17c791dc38d95f23d4c6d3
parent 870e7434f16daaf4f1c6007a31333b71edcf9706
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 29 Oct 2026 10:30:43 -0400

Merge lane/changelog-amend: /changelog shows its forms first and pages its notes; amend the latest release

Conflict: editor/CHANGELOG.md -- one [Unreleased] heading above [0.11.1]
holding the integration's six bullets and the lane's one.

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

Diffstat:
MCOMMANDS.md | 2++
Mcommon/bin/_cli.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 8++++++++
Mcommon/bin/release.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/components/Changelog.tsx | 35+++++++++++++----------------------
Mcommon/controller/cutRelease.test.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/cutRelease.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/changelog.test.ts | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/changelog.ts | 430+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/amend-release/route.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/changelog/ChangelogAnchorResolver.tsx | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/changelog/ChangelogNotes.tsx | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/changelog/page.tsx | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aeditor/app/sites/components/AmendReleaseForm.tsx | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/sites/lib/amendReleaseAction.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/page.tsx | 13+++++++++++++
Aeditor/e2e/changelog-pages.spec.ts | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 17+++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 13+++++++++++++
20 files changed, 1933 insertions(+), 27 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -95,6 +95,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer doctor` | `[--json]` | read-only report: node, the checkout, the corpus, settings, every tool, the port block; exit 1 on a failure | | `archilyzer release show` | `[editor\|export]` | latest release, its date, how many bullets wait under \[Unreleased\] | | `archilyzer release cut` | `<editor\|export\|all> <X.Y.Z\|next\|next-minor> [--commit] [--date YYYY-MM-DD]` | \[Unreleased\] -&gt; a dated heading; all = both, one version, two commits | +| `archilyzer release amend` | `<editor\|export> <release> [--to patch\|minor\|major\|X.Y.Z] [--date YYYY-MM-DD] [--fold] [--uncut] [--commit]` | amend the LATEST release: its bump (counted from the release before it), its date, \[Unreleased\] folded in; --uncut moves it back under \[Unreleased\]; an older release is refused | ## `pnpm ops` @@ -151,6 +152,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | | `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (&lt;from&gt;-&lt;to&gt;.desynced.&lt;ext&gt;) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | +| `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "&lt;its version, as you saw it&gt;", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | | `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | diff --git a/common/bin/_cli.test.ts b/common/bin/_cli.test.ts @@ -19,6 +19,7 @@ import { formatAllLine, formatCutLines, formatShowLine, + parseAmendArgs, parseCutArgs, parseShowArgs, showMain, @@ -196,6 +197,35 @@ test("parseCutArgs checks the changelog, the version and the date before anythin assert.match((parseShowArgs(["hub"]) as { error: string }).error, /"hub" is not editor or export/); }); +test("parseAmendArgs names the release, checks the version and date, and wants something to do", () => { + assert.deepEqual(parseAmendArgs(["editor", "0.11.1"], { to: "minor", commit: true }), { + workspace: "editor", + release: "0.11.1", + version: "minor", + fold: false, + uncut: false, + commit: true, + }); + assert.deepEqual(parseAmendArgs(["export", "0.11.2"], { uncut: true }), { + workspace: "export", + release: "0.11.2", + fold: false, + uncut: true, + commit: false, + }); + const error = (p: string[], f = {}) => { + const r = parseAmendArgs(p, f); + return "error" in r ? r.error : ""; + }; + assert.match(error([]), /which changelog\? editor or export/); + assert.match(error(["all", "0.11.1"], { to: "minor" }), /"all" is not editor or export/); + assert.match(error(["editor"], { to: "minor" }), /which release\?/); + assert.match(error(["editor", "0.11.1"], { to: "next" }), /"patch", "minor" or "major"/); + assert.match(error(["editor", "0.11.1"], { date: "2026-02-30" }), /not a calendar date/); + assert.match(error(["editor", "0.11.1"], { uncut: true, to: "minor" }), /--uncut takes no --to/); + assert.match(error(["editor", "0.11.1"]), /nothing to amend/); +}); + test("a refused release command exits 2 and prints why, touching nothing", async () => { const errors: string[] = []; const out = { log: () => {}, error: (s: string) => errors.push(s) }; diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -1089,6 +1089,14 @@ export const COMMANDS: Command[] = [ maxPositionals: 2, run: async (ctx) => (await import("./release")).cutMain(ctx), }, + { + path: ["release", "amend"], + usage: + "<editor|export> <release> [--to patch|minor|major|X.Y.Z] [--date YYYY-MM-DD] [--fold] [--uncut] [--commit] amend the LATEST release: its bump (counted from the release before it), its date, [Unreleased] folded in; --uncut moves it back under [Unreleased]; an older release is refused", + flags: { to: "string", date: "string", fold: "boolean", uncut: "boolean", commit: "boolean" }, + maxPositionals: 2, + run: async (ctx) => (await import("./release")).amendMain(ctx), + }, ]; // A string flag's value, or undefined. diff --git a/common/bin/release.ts b/common/bin/release.ts @@ -6,6 +6,8 @@ // // archilyzer release show [editor|export] // archilyzer release cut <editor|export|all> <X.Y.Z|next|next-minor> [--commit] [--date YYYY-MM-DD] +// archilyzer release amend <editor|export> <release> [--to patch|minor|major|X.Y.Z] +// [--date YYYY-MM-DD] [--fold] [--uncut] [--commit] // // It works on the checkout it is run from (the monorepo root above the cwd; // EDITOR_CHANGELOG_FILE / EXPORT_CHANGELOG_FILE are honoured as everywhere). @@ -14,7 +16,10 @@ import type { CommandContext } from "./_cli"; import type { FlagValue } from "./_parseFlags"; import { compareVersions, suggestNextMinorVersion, suggestNextVersion } from "../lib/changelog"; import { + amendRelease, + amendVersionProblem, cutReleases, + describeAmend, dateProblem, describeRelease, isReleaseTarget, @@ -169,3 +174,69 @@ export async function showMain(ctx: CommandContext, out: Out = console): Promise if (all) out.log(all); return summaries.every((s) => s.ok) ? 0 : 1; } + +export type AmendArgs = { + workspace: ReleaseWorkspace; + release: string; + version?: string; + date?: string; + fold: boolean; + uncut: boolean; + commit: boolean; +}; + +/** `release amend`'s arguments, checked before anything is read — or why not. */ +export function parseAmendArgs( + positionals: readonly string[], + flags: Record<string, FlagValue>, +): AmendArgs | { error: string } { + const [workspace, release] = positionals; + if (workspace !== "editor" && workspace !== "export") { + return { + error: workspace + ? `release amend: "${workspace}" is not editor or export` + : "release amend: which changelog? editor or export", + }; + } + if (!release || !release.trim()) { + return { error: "release amend: which release? Its version (only the latest can be amended)" }; + } + const version = typeof flags.to === "string" ? flags.to.trim() : undefined; + if (version !== undefined) { + const problem = amendVersionProblem(version); + if (problem) return { error: `release amend: ${problem}` }; + } + const date = typeof flags.date === "string" ? flags.date.trim() : undefined; + if (date !== undefined) { + const problem = dateProblem(date); + if (problem) return { error: `release amend: ${problem}` }; + } + const fold = flags.fold === true; + const uncut = flags.uncut === true; + if (uncut && (version !== undefined || date !== undefined || fold)) { + return { error: "release amend: --uncut takes no --to, --date or --fold" }; + } + if (!uncut && version === undefined && date === undefined && !fold) { + return { error: "release amend: nothing to amend — give --to, --date, --fold or --uncut" }; + } + return { + workspace, + release: release.trim(), + ...(version !== undefined ? { version } : {}), + ...(date !== undefined ? { date } : {}), + fold, + uncut, + commit: flags.commit === true, + }; +} + +export async function amendMain(ctx: CommandContext, out: Out = console): Promise<number> { + const args = parseAmendArgs(ctx.positionals, ctx.flags); + if ("error" in args) { + out.error(args.error); + return 2; + } + const result = await amendRelease(args); + (result.ok ? out.log : out.error)(`${args.workspace}: ${describeAmend(result)}`); + return result.ok ? 0 : 1; +} diff --git a/common/components/Changelog.tsx b/common/components/Changelog.tsx @@ -1,7 +1,12 @@ import type { ReactNode } from "react"; import { Children } from "react"; import Markdown from "markdown-to-jsx"; -import { sliceTopEntries } from "../lib/changelog"; +import { + changelogAnchor, + headingVersion, + releaseAnchor, + sliceTopEntries, +} from "../lib/changelog"; import { CopyLinkButton } from "./CopyLinkButton"; function flattenText(children: ReactNode): string { @@ -20,35 +25,21 @@ function flattenText(children: ReactNode): string { return out; } -const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; -const ISO_DATE = /(\d{4}-\d{2}-\d{2})/; - -function slugify(input: string): string { - return input - .toLowerCase() - .replace(/[^a-z0-9-]+/g, "-") - .replace(/-+/g, "-") - .replace(/^-|-$/g, ""); -} - -function anchorFor(text: string): string { - if (DATE_ONLY.test(text)) return text; - const dateMatch = text.match(ISO_DATE); - if (dateMatch) return dateMatch[1]; - const slug = slugify(text); - return slug || "section"; -} - function H2({ children }: { children?: ReactNode }) { const text = flattenText(children).trim(); - const anchor = text ? anchorFor(text) : null; + const anchor = text ? changelogAnchor(text) : null; + // A release heading carries its version's id too (`v0.11.1`), which no + // other heading shares; the date id stays for links copied before it. + const version = text ? headingVersion(text) : null; + const own = version ? releaseAnchor(version) : null; return ( <h2 id={anchor ?? undefined} className="scroll-mt-20 mt-8 mb-3 text-base font-semibold text-foreground first:mt-0 flex items-baseline" > + {own && <span id={own} className="scroll-mt-20" aria-hidden="true" />} <span>{children}</span> - {anchor && <CopyLinkButton anchor={anchor} />} + {anchor && <CopyLinkButton anchor={own ?? anchor} />} </h2> ); } diff --git a/common/controller/cutRelease.test.ts b/common/controller/cutRelease.test.ts @@ -5,7 +5,10 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { execa } from "execa"; import { + amendRelease, + amendVersionProblem, cutReleaseForWorkspace, + describeAmend, cutReleases, describeCutFailure, describeRelease, @@ -661,3 +664,148 @@ test( }); }, ); + +// --- amendRelease --------------------------------------------------------------- + +const MISCUT = [ + "# Changelog", + "", + "## [0.11.1] - 2026-10-28", + "- **A major's worth.**", + "", + "## [0.11.0] - 2026-09-30", + "- eleven", + "", +].join("\n"); + +test("amending a patch release to a minor rewrites the heading and commits it as the minor's release", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + const result = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(result.ok, true, describeAmend(result)); + if (!result.ok) return; + assert.deepEqual(result.to, { version: "0.12.0", date: "2026-10-28" }); + assert.equal(result.heading, "## [0.12.0] - 2026-10-28"); + assert.equal(result.changed, true); + assert.equal(result.committed, true); + assert.equal(await read(root, "editor"), MISCUT.replace("[0.11.1]", "[0.12.0]")); + assert.deepEqual((await subjects(root))[0], "Release editor 0.12.0"); + const body = await git(root, "log", "-1", "--format=%b"); + assert.match(body, /Amends release 0\.11\.1 \(2026-10-28\): version 0\.11\.1 -> 0\.12\.0\./); + assert.equal(await git(root, "status", "--porcelain"), ""); + assert.match(describeAmend(result), /^Amended 0\.11\.1 -> \[0\.12\.0\] - 2026-10-28 \(committed [0-9a-f]{8}\)\.$/); + + // The same amend again: nothing written, no commit. + const again = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(again.ok, true); + if (!again.ok) return; + assert.equal(again.changed, false); + assert.equal(again.committed, false); + assert.equal((await subjects(root)).length, 2); + assert.match(describeAmend(again), /already says that; nothing changed\.$/); + }); +}); + +test("an amend refuses an older release, and writes nothing", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + const result = await amendRelease({ + workspace: "editor", + release: "0.11.0", + version: "major", + commit: true, + root, + }); + assert.deepEqual(result, { + ok: false, + workspace: "editor", + error: "Only the latest release can be amended: 0.11.0 is older than 0.11.1.", + }); + assert.equal(await read(root, "editor"), MISCUT); + assert.equal((await subjects(root)).length, 1); + }); +}); + +test("an amend that commits refuses a dirty tree, as a cut does", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + await writeFile(path.join(root, "README.md"), "changed\n"); + const result = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.match(result.error, /Other uncommitted changes present \(README\.md\)\. Commit or stash them before amending a release\./); + assert.equal(await read(root, "editor"), MISCUT); + }); +}); + +test("folding [Unreleased] in, then withdrawing the release, round-trips", async () => { + const pending = MISCUT.replace("# Changelog\n\n", "# Changelog\n\n## [Unreleased]\n- **Later.**\n\n"); + await withRepo({ editor: pending }, async (root) => { + const folded = await amendRelease({ + workspace: "editor", + release: "0.11.1", + fold: true, + date: "2026-10-29", + commit: true, + root, + }); + assert.equal(folded.ok, true, describeAmend(folded)); + if (!folded.ok) return; + assert.equal(folded.folded, 1); + assert.equal( + await read(root, "editor"), + MISCUT.replace("## [0.11.1] - 2026-10-28\n", "## [0.11.1] - 2026-10-29\n- **Later.**\n"), + ); + assert.equal((await subjects(root))[0], "Amend release editor 0.11.1"); + + const withdrawn = await amendRelease({ + workspace: "editor", + release: "0.11.1", + uncut: true, + commit: true, + root, + }); + assert.equal(withdrawn.ok, true, describeAmend(withdrawn)); + if (!withdrawn.ok) return; + assert.equal(withdrawn.to, null); + assert.equal(withdrawn.moved, 2); + assert.equal( + await read(root, "editor"), + MISCUT.replace("## [0.11.1] - 2026-10-28\n", "## [Unreleased]\n- **Later.**\n"), + ); + assert.equal((await subjects(root))[0], "Withdraw release editor 0.11.1"); + }); +}); + +test("amend input is checked before anything is read", async () => { + assert.equal(amendVersionProblem("minor"), null); + assert.equal(amendVersionProblem("1.2.3"), null); + assert.match(amendVersionProblem("next") ?? "", /"patch", "minor" or "major"/); + await withRepo({ editor: MISCUT }, async (root) => { + const bad = await amendRelease({ workspace: "editor", release: "0.11.1", uncut: true, version: "minor", commit: false, root }); + assert.equal(bad.ok, false); + if (!bad.ok) assert.equal(bad.error, "A withdrawal takes no version, date or fold."); + const noName = await amendRelease({ workspace: "editor", release: " ", version: "minor", commit: false, root }); + assert.equal(noName.ok, false); + // Not committing: the file changes, the log does not. + const plain = await amendRelease({ workspace: "editor", release: "0.11.1", version: "major", commit: false, root }); + assert.equal(plain.ok, true); + assert.match(await read(root, "editor"), /^## \[1\.0\.0\] - 2026-10-28$/m); + assert.equal((await subjects(root)).length, 1); + }); +}); diff --git a/common/controller/cutRelease.ts b/common/controller/cutRelease.ts @@ -2,6 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import { getPaths } from "../lib/paths"; import { + amendLatestRelease, + AMEND_BUMPS, compareVersions, countUnreleasedBullets, cutRelease, @@ -12,6 +14,7 @@ import { hasUnreleasedHeading, suggestNextMinorVersion, suggestNextVersion, + uncutLatestRelease, } from "../lib/changelog"; import { commitPath, headSha, listDirtyPaths } from "../lib/git"; import { writeFileAtomic } from "../lib/jsonFile-server"; @@ -25,6 +28,12 @@ import { writeFileAtomic } from "../lib/jsonFile-server"; // workspace is 0.1.0 and stays so) and no tag is made; neither has ever been a // convention in this repo. // +// AN AMEND (`amendRelease`, below) rewrites the LATEST release's heading again +// — its version, its date, the [Unreleased] bullets folded into it — or +// withdraws it back to [Unreleased]; the same file, the same atomic write, the +// same dirty-tree guard and a path-limited commit of its own. History is never +// rewritten: the release commit stays, and the amend is a NEW commit after it. +// // Three callers, one body: the /sites and /changelog "Cut release" form (the // server action, a FormData adapter), `archilyzer release cut` (local, needs no // editor) and `POST /api/ops/cut-release` (`pnpm ops cut-release`). The @@ -469,3 +478,213 @@ export async function describeRelease( nextMinor: suggestNextMinorVersion(latestVersion), }; } + +// --------------------------------------------------------------------------- +// AMEND THE LATEST RELEASE. The same three callers as a cut (the form on +// /changelog and /sites, `archilyzer release amend`, POST +// /api/ops/amend-release), the same read → plan in memory → atomic write → +// path-limited commit. Only the newest release heading; the caller names it +// (`release`), so a form or a command typed against a changelog that has since +// moved on is refused rather than amending something else. +// +// What a cut writes is one heading, so that is all an amend has to put right: +// no package.json, no tag, no generated file carries a release version. The +// commit an amend makes when the version changes has the subject a cut of that +// version would have had (`Release editor 0.12.0`), so the log reads as if the +// release had been cut right; its body says what it amends. + +/** + * Why `version` can never be an amend's — or null: a bump keyword or X.Y.Z(-pre). + */ +export function amendVersionProblem(version: string): string | null { + const v = version.trim(); + if (!v) return "Version is required."; + if ((AMEND_BUMPS as readonly string[]).includes(v) || SEMVER_VERSION.test(v)) return null; + return `Version "${v}" is not a valid semver (expected X.Y.Z or X.Y.Z-prerelease), "patch", "minor" or "major".`; +} + +export type AmendReleaseOptions = { + workspace: ReleaseWorkspace; + // The latest release's version as the caller saw it (the guard). + release: string; + // "patch" | "minor" | "major" (a bump of the release before it) or a + // literal X.Y.Z(-pre). Absent: kept. + version?: string; + // YYYY-MM-DD. Absent: kept. + date?: string; + // Fold the [Unreleased] bullets into it. + fold?: boolean; + // Withdraw it instead: its bullets go back under [Unreleased]. Takes no + // version, date or fold. + uncut?: boolean; + commit: boolean; + root?: string; +}; + +export type AmendReleaseResult = + | { + ok: true; + workspace: ReleaseWorkspace; + from: { version: string; date: string | null }; + // The release as amended; null when it was withdrawn. + to: { version: string; date: string | null } | null; + // The heading now in the file (null when withdrawn). + heading: string | null; + // Bullets folded in from [Unreleased] (an amend) or moved back under it + // (a withdrawal). + folded: number; + moved: number; + // False when the file already said this: nothing written, no commit. + changed: boolean; + committed: boolean; + commitSha?: string; + } + | { + ok: false; + workspace: ReleaseWorkspace; + error: string; + // As a cut's: the file was written and only the commit failed. + written?: true; + }; + +function amendCommitMessage( + workspace: ReleaseWorkspace, + from: { version: string; date: string | null }, + to: { version: string; date: string | null } | null, + folded: number, + moved: number, +): string { + const was = `${from.version}${from.date ? ` (${from.date})` : ""}`; + if (!to) { + return `Withdraw release ${workspace} ${from.version}\n\nIts ${moved} note${ + moved === 1 ? "" : "s" + } are back under [Unreleased].`; + } + const changes: string[] = []; + if (to.version !== from.version) changes.push(`version ${from.version} -> ${to.version}`); + if (to.date !== from.date) changes.push(`date ${from.date ?? "none"} -> ${to.date ?? "none"}`); + if (folded > 0) { + changes.push(`${folded} note${folded === 1 ? "" : "s"} folded in from [Unreleased]`); + } + const body = `Amends release ${was}: ${changes.join("; ") || "no change"}.`; + const subject = + to.version !== from.version + ? `Release ${workspace} ${to.version}` + : `Amend release ${workspace} ${to.version}`; + return `${subject}\n\n${body}`; +} + +/** + * Amend (or withdraw) one workspace's latest release: the dirty-tree guard + * (when committing), the read, the amend in memory, the atomic write, the + * commit. An amend to what the file already says writes and commits nothing. + */ +export async function amendRelease(opts: AmendReleaseOptions): Promise<AmendReleaseResult> { + const { workspace } = opts; + const fail = (error: string): AmendReleaseResult => ({ ok: false, workspace, error }); + const release = opts.release.trim(); + if (!release) return fail("Which release? Name the latest release's version."); + if (opts.uncut && (opts.version || opts.date || opts.fold)) { + return fail("A withdrawal takes no version, date or fold."); + } + if (opts.version !== undefined) { + const problem = amendVersionProblem(opts.version); + if (problem) return fail(problem); + } + if (opts.date !== undefined) { + const problem = dateISOProblem(opts.date); + if (problem) return fail(problem); + } + const repo = releaseRepo(opts.root); + const filePath = repo.changelogs[workspace]; + const relPath = path.relative(repo.root, filePath); + if (opts.commit) { + const problem = await dirtyTreeProblem(repo, [relPath]); + if (problem) return fail(problem.replace("before cutting a release", "before amending a release")); + } + const read = await readChangelog(filePath); + if (!read.ok) return fail(read.error); + + let next: string; + let from: { version: string; date: string | null }; + let to: { version: string; date: string | null } | null; + let folded = 0; + let moved = 0; + try { + if (opts.uncut) { + const plan = uncutLatestRelease(read.source, release); + next = plan.next; + from = { version: plan.version, date: plan.date }; + to = null; + moved = plan.moved; + } else { + const plan = amendLatestRelease(read.source, { + release, + version: opts.version, + date: opts.date, + fold: opts.fold, + }); + next = plan.next; + from = plan.from; + to = plan.to; + folded = plan.folded; + } + } catch (err) { + if (err instanceof CutReleaseError) return fail(err.message); + throw err; + } + const heading = to ? `## [${to.version}]${to.date ? ` - ${to.date}` : ""}` : null; + const done = (changed: boolean, committed: boolean, commitSha?: string): AmendReleaseResult => ({ + ok: true, + workspace, + from, + to, + heading, + folded, + moved, + changed, + committed, + ...(commitSha ? { commitSha } : {}), + }); + if (next === read.source) return done(false, false); + try { + await writeFileAtomic(filePath, next); + } catch (err) { + return fail(`Could not write ${filePath}: ${(err as Error).message}`); + } + if (!opts.commit) return done(true, false); + const result = await commitPath( + repo.root, + relPath, + amendCommitMessage(workspace, from, to, folded, moved), + ); + if (!result.ok) { + return { + ok: false, + workspace, + error: `Amended release ${from.version}, but the commit failed: ${result.error}`, + written: true, + }; + } + return done(true, true, (await headSha(repo.root)) ?? undefined); +} + +/** One line for an amend's outcome — the CLI's, the form's, the route's. */ +export function describeAmend(result: AmendReleaseResult): string { + if (!result.ok) return result.error; + const what = result.to + ? result.changed + ? `Amended ${result.from.version} -> ${result.heading?.replace(/^## /, "")}${ + result.folded ? `, ${result.folded} note${result.folded === 1 ? "" : "s"} folded in` : "" + }` + : `Release ${result.from.version} already says that; nothing changed` + : `Withdrew ${result.from.version}: ${result.moved} note${ + result.moved === 1 ? "" : "s" + } back under [Unreleased]`; + const commit = !result.changed + ? "" + : result.committed + ? ` (committed${result.commitSha ? ` ${result.commitSha.slice(0, 8)}` : ""})` + : " (not committed)"; + return `${what}${commit}.`; +} diff --git a/common/lib/changelog.test.ts b/common/lib/changelog.test.ts @@ -1,7 +1,19 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { + amendLatestRelease, + bumpVersion, + changelogAnchor, + changelogAnchorPages, + changelogPageOf, + clampChangelogPage, compareVersions, + CutReleaseError, + describeAmendTarget, + paginateChangelog, + parseChangelogSections, + suggestNextMajorVersion, + uncutLatestRelease, countUnreleasedBullets, cutRelease, dateISOProblem, @@ -97,3 +109,246 @@ test("countUnreleasedBullets counts the top-level bullets under [Unreleased] onl assert.equal(hasUnreleasedHeading(SOURCE), true); assert.equal(hasUnreleasedHeading("## [0.1.0] - 2026-01-01\n- x\n"), false); }); + +// --- the sections, the pages ------------------------------------------------- + +const RELEASED = [ + "# Changelog", + "", + "## [0.11.1] - 2026-10-28", + "- **Big one.**", + "- **Big two.**", + "", + "## [0.11.0] - 2026-09-30", + "- eleven", + "", + "## [0.10.0] - 2026-09-28", + "- ten", + "", + "## [0.9.4] - 2026-09-28", + "- nine four", +].join("\n"); + +test("parseChangelogSections reads each heading's version, date, anchor and span", () => { + const sections = parseChangelogSections(SOURCE); + assert.deepEqual( + sections.map((s) => [s.title, s.anchor, s.versionAnchor, s.unreleased, s.version, s.date]), + [ + ["[Unreleased]", "unreleased", null, true, null, null], + ["[0.9.0] - 2026-09-26", "2026-09-26", "v0.9.0", false, "0.9.0", "2026-09-26"], + ["[0.8.7] - 2026-08-12", "2026-08-12", "v0.8.7", false, "0.8.7", "2026-08-12"], + ], + ); + // The spans tile the file from the first heading to the end. + assert.equal(sections[0].end, sections[1].start); + assert.equal(sections[2].end, SOURCE.length); + assert.equal(SOURCE.slice(sections[1].bodyStart, sections[1].end), "- released\n\n"); + // `###` is not a section. + assert.equal(parseChangelogSections("## [1.0.0] - 2026-01-01\n### Added\n- x\n").length, 1); +}); + +test("changelogAnchor is the heading's date, else its slug", () => { + assert.equal(changelogAnchor("[0.11.1] - 2026-10-28"), "2026-10-28"); + assert.equal(changelogAnchor("2026-05-19"), "2026-05-19"); + assert.equal(changelogAnchor("[Unreleased]"), "unreleased"); + assert.equal(changelogAnchor("!!!"), "section"); +}); + +test("paginateChangelog fills pages by size, keeps the head on page 1, never splits a section", () => { + const big = "- " + "x".repeat(500); + const src = [ + "# Changelog", + "", + "## [Unreleased]", + big, + "", + "## [1.0.2] - 2026-03-03", + "- small", + "", + "## [1.0.1] - 2026-02-02", + big, + big, + "", + "## [1.0.0] - 2026-01-01", + "- small", + "", + ].join("\n"); + const sections = parseChangelogSections(src); + // A budget below one section: each section a page of its own. + assert.deepEqual(paginateChangelog(sections, 10), [[0], [1], [2], [3]]); + // Room for the head and the small release after it, not for the big one. + assert.deepEqual(paginateChangelog(sections, 600), [[0, 1], [2], [3]]); + // Everything fits. + assert.deepEqual(paginateChangelog(sections, 1_000_000), [[0, 1, 2, 3]]); + const pages = paginateChangelog(sections, 600); + assert.equal(changelogPageOf(sections, pages, "unreleased"), 1); + assert.equal(changelogPageOf(sections, pages, "2026-02-02"), 2); + assert.equal(changelogPageOf(sections, pages, "2026-01-01"), 3); + assert.equal(changelogPageOf(sections, pages, "1999-01-01"), null); + assert.equal(changelogPageOf(sections, pages, "v1.0.1"), 2); + assert.deepEqual(changelogAnchorPages(sections, pages), { + unreleased: 1, + "2026-03-03": 1, + "v1.0.2": 1, + "2026-02-02": 2, + "v1.0.1": 2, + "2026-01-01": 3, + "v1.0.0": 3, + }); + // A changelog with no headings is one empty page. + assert.deepEqual(paginateChangelog(parseChangelogSections("# Changelog\n")), [[]]); +}); + +test("paginateChangelog: a head bigger than the budget is page 1 alone", () => { + const src = `## [Unreleased]\n- ${"y".repeat(300)}\n\n## [1.0.0] - 2026-01-01\n- a\n`; + assert.deepEqual(paginateChangelog(parseChangelogSections(src), 100), [[0], [1]]); +}); + +test("clampChangelogPage reads ?page= leniently", () => { + assert.equal(clampChangelogPage(undefined, 4), 1); + assert.equal(clampChangelogPage("3", 4), 3); + assert.equal(clampChangelogPage("9", 4), 4); + assert.equal(clampChangelogPage("0", 4), 1); + assert.equal(clampChangelogPage("two", 4), 1); + assert.equal(clampChangelogPage(["2", "3"], 4), 2); + assert.equal(clampChangelogPage("2", 0), 1); +}); + +// --- amending the latest release ---------------------------------------------- + +test("bumpVersion counts from the release before: patch, minor, major", () => { + assert.equal(bumpVersion("0.11.0", "patch"), "0.11.1"); + assert.equal(bumpVersion("0.11.0", "minor"), "0.12.0"); + assert.equal(bumpVersion("0.11.0", "major"), "1.0.0"); + assert.equal(suggestNextMajorVersion("1.4.2"), "2.0.0"); + assert.equal(suggestNextMajorVersion(null), "1.0.0"); +}); + +test("describeAmendTarget offers the bumps of the previous release", () => { + const t = describeAmendTarget(`## [Unreleased]\n- a\n- b\n\n${RELEASED.replace("# Changelog\n\n", "")}`); + assert.deepEqual(t, { + latest: { version: "0.11.1", date: "2026-10-28" }, + previous: { version: "0.11.0", date: "2026-09-30" }, + bumps: { patch: "0.11.1", minor: "0.12.0", major: "1.0.0" }, + pending: 2, + }); + assert.equal(describeAmendTarget("# Changelog\n\n## [Unreleased]\n- a\n"), null); +}); + +test("amending a patch cut to a minor gives exactly what a minor cut would have", () => { + const plan = amendLatestRelease(RELEASED, { release: "0.11.1", version: "minor" }); + assert.equal(plan.changed, true); + assert.deepEqual(plan.from, { version: "0.11.1", date: "2026-10-28" }); + assert.deepEqual(plan.to, { version: "0.12.0", date: "2026-10-28" }); + // A minor cut from 0.11.0 on that day, byte for byte. + const minorCut = cutRelease( + RELEASED.replace("## [0.11.1] - 2026-10-28", "## [Unreleased]"), + "0.12.0", + "2026-10-28", + ); + assert.equal(plan.next, minorCut); + // A literal says the same. + assert.equal(amendLatestRelease(RELEASED, { version: "0.12.0" }).next, minorCut); +}); + +test("an amend is idempotent: the same amend again changes nothing", () => { + const once = amendLatestRelease(RELEASED, { release: "0.11.1", version: "minor" }).next; + // A retry naming the release it already amended: no heading is 0.11.1 any + // more, and the latest is already the version asked for. + const twice = amendLatestRelease(once, { release: "0.11.1", version: "minor" }); + assert.equal(twice.changed, false); + assert.equal(twice.next, once); + assert.deepEqual(twice.to, { version: "0.12.0", date: "2026-10-28" }); + // Naming it by its new version, too. + assert.equal(amendLatestRelease(once, { release: "0.12.0", version: "minor" }).changed, false); + // And an amend that asks for nothing. + assert.equal(amendLatestRelease(RELEASED, { release: "0.11.1" }).changed, false); +}); + +test("only the latest release can be amended", () => { + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.11.0", version: "minor" }), + (err: unknown) => + err instanceof CutReleaseError && + err.message === "Only the latest release can be amended: 0.11.0 is older than 0.11.1.", + ); + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.8.0", version: "major" }), + /0\.8\.0 is not a release in this changelog; the latest is 0\.11\.1\./, + ); + // A stale name with no version to tell a retry from a mistake is refused. + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.8.0", date: "2026-10-29" }), + /not a release in this changelog/, + ); + assert.throws(() => amendLatestRelease("# Changelog\n", {}), /There is no release to amend\./); +}); + +test("an amend refuses a version that does not follow the previous release, and bad dates", () => { + assert.throws( + () => amendLatestRelease(RELEASED, { version: "0.11.0" }), + /Version 0\.11\.0 is not newer than the previous release, 0\.11\.0\./, + ); + assert.throws(() => amendLatestRelease(RELEASED, { version: "0.10.5" }), /not newer than the previous/); + assert.throws(() => amendLatestRelease(RELEASED, { version: "twelve" }), /not a valid semver/); + assert.throws(() => amendLatestRelease(RELEASED, { date: "2026-02-30" }), /not a calendar date/); + assert.throws( + () => amendLatestRelease(RELEASED, { date: "2026-09-01" }), + /Date 2026-09-01 is before the previous release \(0\.11\.0, 2026-09-30\)\./, + ); + // A date alone. + const redated = amendLatestRelease(RELEASED, { date: "2026-10-29" }); + assert.match(redated.next, /^## \[0\.11\.1\] - 2026-10-29$/m); + assert.equal(redated.next.replace("2026-10-29", "2026-10-28"), RELEASED); +}); + +test("folding moves what waits under [Unreleased] into the release and drops that heading", () => { + const withPending = RELEASED.replace( + "# Changelog\n\n", + "# Changelog\n\n## [Unreleased]\n- **Later one.**\n- **Later two.**\n\n", + ); + const plan = amendLatestRelease(withPending, { release: "0.11.1", version: "minor", fold: true }); + assert.equal(plan.folded, 2); + assert.equal( + plan.next, + RELEASED.replace( + "## [0.11.1] - 2026-10-28\n", + "## [0.12.0] - 2026-10-28\n- **Later one.**\n- **Later two.**\n", + ), + ); + // Again: nothing left to fold, nothing changes. + const again = amendLatestRelease(plan.next, { release: "0.12.0", version: "minor", fold: true }); + assert.equal(again.changed, false); + assert.equal(again.folded, 0); + // Without fold the pending bullets stay where they are. + const kept = amendLatestRelease(withPending, { version: "minor" }); + assert.match(kept.next, /## \[Unreleased\]\n- \*\*Later one\.\*\*/); + assert.equal(kept.folded, 0); +}); + +test("withdrawing the latest release puts its bullets back under [Unreleased]", () => { + const plain = uncutLatestRelease(RELEASED, "0.11.1"); + assert.equal(plain.moved, 2); + assert.equal(plain.next, RELEASED.replace("## [0.11.1] - 2026-10-28", "## [Unreleased]")); + // Then a minor cut gives what the amend gives. + assert.equal( + cutRelease(plain.next, "0.12.0", "2026-10-28"), + amendLatestRelease(RELEASED, { version: "minor" }).next, + ); + // Under bullets already pending, which are newer. + const withPending = RELEASED.replace( + "# Changelog\n\n", + "# Changelog\n\n## [Unreleased]\n- **Later.**\n\n", + ); + const merged = uncutLatestRelease(withPending); + assert.equal( + merged.next, + RELEASED.replace("## [0.11.1] - 2026-10-28\n", "## [Unreleased]\n- **Later.**\n"), + ); + assert.throws(() => uncutLatestRelease(RELEASED, "0.10.0"), /Only the latest release can be amended/); + // The last release in the file keeps no trailing blank line. + assert.equal( + uncutLatestRelease("# Changelog\n\n## [1.0.0] - 2026-01-01\n- a\n").next, + "# Changelog\n\n## [Unreleased]\n- a\n", + ); +}); diff --git a/common/lib/changelog.ts b/common/lib/changelog.ts @@ -197,3 +197,433 @@ export function cutRelease( const replacement = `## [${version}] - ${dateISO}`; return `${before}${replacement}${after}`; } + +/** + * The major bump: `0.11.1` → `1.0.0`. No release yet (or an unreadable + * version) is `1.0.0`. + */ +export function suggestNextMajorVersion(current: string | null): string { + const parsed = parseVersion(current); + if (!parsed) return "1.0.0"; + return `${parsed.core[0] + 1}.0.0`; +} + +// --------------------------------------------------------------------------- +// THE SECTIONS. A changelog read as its `## ` headings: what /changelog pages +// through and what an amend rewrites. Offsets are into the source, so a +// section is `source.slice(start, end)` and its body +// `source.slice(bodyStart, end)`. + +export type ChangelogSection = { + // The heading's text after `## `: `[0.11.1] - 2026-10-28`. + title: string; + // The id the page gives this heading's <h2> (`changelogAnchor`). + anchor: string; + // A release's own id beside it, `v0.11.1` (`releaseAnchor`): unique where + // the date is not (two releases cut on one day). + versionAnchor: string | null; + unreleased: boolean; + version: string | null; + date: string | null; + start: number; + bodyStart: number; + end: number; +}; + +const H2_LINE = /^##[ \t]+([^\n]*?)[ \t]*$/gm; +const RELEASE_TITLE = + /^\[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\](?:\s+-\s+(\d{4}-\d{2}-\d{2}))?/; +const UNRELEASED_TITLE = /^\[Unreleased\]$/i; +const ANCHOR_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; +const ANCHOR_ISO_DATE = /(\d{4}-\d{2}-\d{2})/; + +/** + * The id a changelog heading gets on the page: its date when it has one (so a + * link copied before a re-cut still lands), else a slug of its text + * (`[Unreleased]` → `unreleased`). Two headings of one date share an id; the + * first one wins, as `getElementById` has it. + */ +export function changelogAnchor(text: string): string { + const t = text.trim(); + if (ANCHOR_DATE_ONLY.test(t)) return t; + const date = t.match(ANCHOR_ISO_DATE); + if (date) return date[1]; + const slug = t + .toLowerCase() + .replace(/[^a-z0-9-]+/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, ""); + return slug || "section"; +} + +/** A release heading's own anchor: `v0.11.1`. */ +export function releaseAnchor(version: string): string { + return `v${version}`; +} + +/** The version a rendered heading's text names (`[0.11.1] - …`), or null. */ +export function headingVersion(text: string): string | null { + const m = RELEASE_TITLE.exec(text.trim()); + return m ? m[1] : null; +} + +/** Every `## ` heading of `source`, in order, with where its section runs. */ +export function parseChangelogSections(source: string): ChangelogSection[] { + const sections: ChangelogSection[] = []; + for (const m of source.matchAll(H2_LINE)) { + const start = m.index ?? 0; + const lineEnd = source.indexOf("\n", start); + const bodyStart = lineEnd === -1 ? source.length : lineEnd + 1; + const title = m[1]; + const release = RELEASE_TITLE.exec(title); + if (sections.length) sections[sections.length - 1].end = start; + sections.push({ + title, + anchor: changelogAnchor(title), + versionAnchor: release ? releaseAnchor(release[1]) : null, + unreleased: UNRELEASED_TITLE.test(title), + version: release ? release[1] : null, + date: release ? (release[2] ?? null) : null, + start, + bodyStart, + end: source.length, + }); + } + return sections; +} + +// --------------------------------------------------------------------------- +// THE PAGES of /changelog. The file is ~760 KB of markdown, and rendering all +// of it made the page a 2.9 MB response the browser took 5-10 s to show. A +// page holds whole sections up to a size budget — at least one, so a section +// bigger than the budget is a page of its own — and the first page always +// opens with everything above the first release ([Unreleased], whatever its +// size). Sizes, not counts: the sections run from 300 bytes to 360 KB. + +export const CHANGELOG_PAGE_BUDGET = 96_000; + +/** The sections of each page, as indexes into `sections`; never empty. */ +export function paginateChangelog( + sections: readonly ChangelogSection[], + budget: number = CHANGELOG_PAGE_BUDGET, +): number[][] { + const pages: number[][] = []; + let current: number[] = []; + let size = 0; + let headDone = false; + sections.forEach((s, i) => { + const len = s.end - s.start; + const head = !headDone && s.version === null; + if (!head) headDone = true; + if (!head && current.length > 0 && size + len > budget) { + pages.push(current); + current = []; + size = 0; + } + current.push(i); + size += len; + }); + if (current.length > 0 || pages.length === 0) pages.push(current); + return pages; +} + +/** + * The 1-based page holding the first section with `anchor` (its date or slug + * id, or its `v<version>` id), or null. + */ +export function changelogPageOf( + sections: readonly ChangelogSection[], + pages: readonly number[][], + anchor: string, +): number | null { + const index = sections.findIndex((s) => s.anchor === anchor || s.versionAnchor === anchor); + if (index === -1) return null; + const page = pages.findIndex((p) => p.includes(index)); + return page === -1 ? null : page + 1; +} + +/** + * Every anchor of the file → the page that holds it (the first section with + * it, as the browser's `getElementById` picks the first): what lets a link + * copied from one page land on the page that now holds it. + */ +export function changelogAnchorPages( + sections: readonly ChangelogSection[], + pages: readonly number[][], +): Record<string, number> { + const out: Record<string, number> = {}; + pages.forEach((indexes, p) => { + for (const i of indexes) { + for (const a of [sections[i].anchor, sections[i].versionAnchor]) { + if (a && !Object.hasOwn(out, a)) out[a] = p + 1; + } + } + }); + return out; +} + +/** `?page=` read leniently: anything not a page number is page 1. */ +export function clampChangelogPage(raw: unknown, pageCount: number): number { + const v = Array.isArray(raw) ? raw[0] : raw; + const n = typeof v === "string" && /^\d+$/.test(v) ? Number(v) : 1; + return Math.min(Math.max(n, 1), Math.max(pageCount, 1)); +} + +// --------------------------------------------------------------------------- +// AMENDING THE LATEST RELEASE. A cut is one heading rewrite; an amend rewrites +// the same heading again — its version (a bump of the release BEFORE it, so a +// patch cut can become the minor it should have been), its date — and can +// fold the bullets that have since gathered under [Unreleased] into it, or +// withdraw it (`uncutLatestRelease`: its bullets go back under [Unreleased]). +// Only the newest release: an older one is history other releases were cut +// after. + +export const AMEND_BUMPS = ["patch", "minor", "major"] as const; +export type AmendBump = (typeof AMEND_BUMPS)[number]; + +export function isAmendBump(v: unknown): v is AmendBump { + return (AMEND_BUMPS as readonly unknown[]).includes(v); +} + +/** `previous` bumped by `kind` — what a cut of that kind would have made. */ +export function bumpVersion(previous: string | null, kind: AmendBump): string { + if (kind === "major") return suggestNextMajorVersion(previous); + if (kind === "minor") return suggestNextMinorVersion(previous); + return suggestNextVersion(previous); +} + +export type AmendTarget = { + // The latest release as it is now. + latest: { version: string; date: string | null }; + // The release before it, which a bump counts from (null: it is the first). + previous: { version: string; date: string | null } | null; + // What each bump would make it. + bumps: Record<AmendBump, string>; + // Top-level bullets under an [Unreleased] heading above it. + pending: number; +}; + +/** What the Amend form offers, read-only; null when there is no release. */ +export function describeAmendTarget(source: string): AmendTarget | null { + const sections = parseChangelogSections(source); + const releases = sections.filter((s) => s.version !== null); + const latest = releases[0]; + if (!latest || latest.version === null) return null; + const prev = releases[1]; + const previous = + prev && prev.version !== null ? { version: prev.version, date: prev.date } : null; + const latestIndex = sections.indexOf(latest); + const unreleased = sections.findIndex((s) => s.unreleased); + const pending = + unreleased !== -1 && unreleased < latestIndex + ? countBullets(source.slice(sections[unreleased].bodyStart, sections[unreleased].end)) + : 0; + return { + latest: { version: latest.version, date: latest.date }, + previous, + bumps: { + patch: bumpVersion(previous?.version ?? null, "patch"), + minor: bumpVersion(previous?.version ?? null, "minor"), + major: bumpVersion(previous?.version ?? null, "major"), + }, + pending, + }; +} + +function countBullets(body: string): number { + return body.split("\n").filter((line) => /^[-*+]\s/.test(line)).length; +} + +export type AmendSpec = { + // The release the caller means (its version). Refused unless it is the + // latest — except a retry: when no heading carries it any more and the + // latest already IS the version asked for, the amend goes on against the + // latest (and is then usually a no-op). + release?: string; + // A bump of the previous release, or a literal X.Y.Z(-pre). Absent: kept. + version?: string; + // YYYY-MM-DD. Absent: kept. + date?: string; + // Fold whatever waits under [Unreleased] into the release, and drop that + // heading — as if those bullets had been there when it was cut. + fold?: boolean; +}; + +export type AmendPlan = { + next: string; + changed: boolean; + from: { version: string; date: string | null }; + to: { version: string; date: string | null }; + // Top-level bullets folded in from [Unreleased]. + folded: number; +}; + +// The latest release, after the `release` guard. `target` is the version the +// amend would give it (for the retry rule); null for a withdrawal. +function latestFor( + sections: readonly ChangelogSection[], + release: string | undefined, + target: (previous: string | null) => string | null, +): { latest: ChangelogSection; previous: ChangelogSection | null } { + const releases = sections.filter((s) => s.version !== null); + const latest = releases[0]; + if (!latest || latest.version === null) { + throw new CutReleaseError("There is no release to amend."); + } + const previous = releases[1] ?? null; + const named = release?.trim(); + if (named && named !== latest.version) { + if (releases.some((r) => r.version === named)) { + throw new CutReleaseError( + `Only the latest release can be amended: ${named} is older than ${latest.version}.`, + ); + } + if (target(previous?.version ?? null) !== latest.version) { + throw new CutReleaseError( + `${named} is not a release in this changelog; the latest is ${latest.version}.`, + ); + } + } + return { latest, previous }; +} + +function resolveAmendVersion(spec: string | undefined, previous: string | null, current: string): string { + const v = spec?.trim(); + if (!v) return current; + if (isAmendBump(v)) return bumpVersion(previous, v); + return v; +} + +// One section's text: its heading, its body, and the blank line before the +// next heading (none at the end of the file). +function sectionText(heading: string, body: string, last: boolean): string { + const b = body.replace(/^\n+/, "").trimEnd(); + const text = b ? `${heading}\n${b}\n` : `${heading}\n`; + return last ? text : `${text}\n`; +} + +/** + * Amend the latest release in memory. Throws CutReleaseError with the + * refusal's sentence: no release, an older release named, a version that is + * not semver or not newer than the release before it, a bad date or one + * before the previous release's, an [Unreleased] heading below the release. + * Amending to what is already there is not an error: `changed` is false. + */ +export function amendLatestRelease(source: string, spec: AmendSpec): AmendPlan { + const sections = parseChangelogSections(source); + const { latest, previous } = latestFor(sections, spec.release, (prev) => + resolveAmendVersion(spec.version, prev, "\u0000"), + ); + const current = latest.version as string; + const prevVersion = previous?.version ?? null; + const version = resolveAmendVersion(spec.version, prevVersion, current); + if (!SEMVER_VERSION.test(version)) { + throw new CutReleaseError( + `Version "${version}" is not a valid semver (expected X.Y.Z or X.Y.Z-prerelease), "patch", "minor" or "major".`, + ); + } + if (prevVersion && compareVersions(version, prevVersion) <= 0) { + throw new CutReleaseError( + `Version ${version} is not newer than the previous release, ${prevVersion}.`, + ); + } + if ( + version !== current && + sections.some((s) => s !== latest && s.version === version) + ) { + throw new CutReleaseError(`There is already a release ${version} in this changelog.`); + } + const date = spec.date?.trim() || latest.date; + if (date) { + const problem = dateISOProblem(date); + if (problem) throw new CutReleaseError(problem); + if (previous?.date && date < previous.date) { + throw new CutReleaseError( + `Date ${date} is before the previous release (${prevVersion}, ${previous.date}).`, + ); + } + } + const latestIndex = sections.indexOf(latest); + const unreleasedIndex = sections.findIndex((s) => s.unreleased); + const heading = `## [${version}]${date ? ` - ${date}` : ""}`; + const last = latestIndex === sections.length - 1; + let folded = 0; + let next: string; + if (spec.fold && unreleasedIndex !== -1) { + if (unreleasedIndex > latestIndex) { + throw new CutReleaseError( + "The [Unreleased] heading is below the latest release; move it to the top before folding.", + ); + } + const u = sections[unreleasedIndex]; + const pendingBody = source.slice(u.bodyStart, u.end).trim(); + folded = countBullets(pendingBody); + const body = [pendingBody, source.slice(latest.bodyStart, latest.end).trim()] + .filter(Boolean) + .join("\n"); + next = + source.slice(0, u.start) + + source.slice(u.end, latest.start) + + sectionText(heading, body, last) + + source.slice(latest.end); + } else { + const lineEnd = latest.bodyStart > latest.start && source[latest.bodyStart - 1] === "\n" + ? latest.bodyStart - 1 + : latest.bodyStart; + next = source.slice(0, latest.start) + heading + source.slice(lineEnd); + } + return { + next, + changed: next !== source, + from: { version: current, date: latest.date }, + to: { version, date }, + folded, + }; +} + +export type UncutPlan = { + next: string; + // The release withdrawn. + version: string; + date: string | null; + // Top-level bullets moved back under [Unreleased]. + moved: number; +}; + +/** + * Withdraw the latest release in memory: its heading becomes `## [Unreleased]`, + * or — when an [Unreleased] heading already sits above it — its bullets join + * that section, under the ones already pending (those are newer). + */ +export function uncutLatestRelease(source: string, release?: string): UncutPlan { + const sections = parseChangelogSections(source); + const { latest } = latestFor(sections, release, () => null); + const latestIndex = sections.indexOf(latest); + const unreleasedIndex = sections.findIndex((s) => s.unreleased); + const releaseBody = source.slice(latest.bodyStart, latest.end).trim(); + const moved = countBullets(releaseBody); + const last = latestIndex === sections.length - 1; + let next: string; + if (unreleasedIndex !== -1 && unreleasedIndex < latestIndex) { + const u = sections[unreleasedIndex]; + const pendingBody = source.slice(u.bodyStart, u.end).trim(); + const between = source.slice(u.end, latest.start); + const body = [pendingBody, releaseBody].filter(Boolean).join("\n"); + // Anything between the two (it should be nothing) stays above them. + next = + source.slice(0, u.start) + + between + + sectionText(`## ${u.title}`, body, last) + + source.slice(latest.end); + } else if (unreleasedIndex !== -1) { + throw new CutReleaseError( + "The [Unreleased] heading is below the latest release; move it to the top before withdrawing.", + ); + } else { + next = + source.slice(0, latest.start) + + sectionText("## [Unreleased]", releaseBody, last) + + source.slice(latest.end); + } + return { next, version: latest.version as string, date: latest.date, moved }; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -7,6 +7,7 @@ - **A report video can draw a reply with the post it answers.** A manifest post's `thread: true` draws its capture's `shot-thread.png` in place of its shot (its own shot while there is none) — set with `umtool posts set <project> <post> thread=on`, `umtool posts add … --thread`, or the **thread** box in the On-screen Posts table. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut. A cut with no thread shot renders byte for byte as before. - **A site build can now run beside a report-video render when there is memory for both.** A render declared nothing to the machine's heavy slot, so it always ran alone: a site build started while a take rendered waited out the whole render (an hour or more for a full cut). A render now says how much memory it will need — measured on the Huck cut: about 6 GB for a whole cut (its widest step, a crossfade over 23 clips at once, peaked at 4.9 GB), about 2.4 GB for a short take of part of a cut, more with more `UMTOOL_CHROME_WORKERS` — and the encode ladder (`umtool variants`) about 1 GB. A capped site build (one run under `systemd-run … -p MemoryMax=5G`) is let in beside it while the memory left after the render's share stays at or above the 6000 MB floor, and waits for it otherwise. On this 16 GB machine that is often for a short take and rare for a whole cut. A publish stage's own build is not capped, so it still waits for the render as before. `UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` set the share by hand, and `0` makes a render run alone again. Start a take or a build-video run as it is, not under `pnpm heavy --`, which makes it run alone. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **Report-video takes no longer keep their build work forever.** On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB), and 131 GB of it was takes' build work: each full take's chrome frames (about 12 GB for the 34-minute Huck cut, kept with `--keep-frames` so a `--from` twin can reuse them), its crossfade batches and its clip segments, swept by hand. `umtool prune <project>` (or `--all`) now lists each take's work files — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — and what freeing them gives back, or why the take keeps them: a build running in it or from it (never freed), the picked take, the take the project's manifest is, a pin in `takes/prune.json`, the newest 2 of its group, anything modified in the last 3 days, and the `--from` bases of those. It is a dry run unless `--yes`. Files hard-linked between takes are counted once, and freed only when every take holding them lets them go, so the numbers are what the disk gets back, not a sum of `du`s. The renders, previews, take.json and manifests are never touched, and nothing is followed out of a take through a link. The Takes page says each take's work and why it is kept, with **Free work files** per take and for the project (the plan first, then **Free them**). A take that finishes building now prunes its project by the same rules and says what it freed in its log, and a render that starts with under 30 GB free does the same across every project, and refuses to start under 10 GB with a sentence saying so. `--keep`, `--older-than`, `takes/prune.json` and `UMTOOL_PRUNE_*` / `UMTOOL_DISK_GUARD*` change the rules or turn them off. A dry run over ~/reports on 2026-10-27, after the hand sweep: 27 GiB of work in 32 projects' takes, 4.0 GiB of it free to go (2.4 GiB in the Huck project, whose last three days of takes are all kept). Needs a restart of umtool for the Takes page and for takes made from it; the CLI has it at once. +- **The changelog page opens with its Cut and Amend forms, and pages its notes; the latest release can be amended.** `/changelog` rendered the whole of `editor/CHANGELOG.md` (760 KB of markdown, a 2.9 MB response) before the Cut release form at its bottom, so the form took 1 s to appear on an idle machine and 5-10 s on a busy one. The forms now come first (the Cut release button shows in about 0.35 s where it took 1 s) and the notes stream in after them a page at a time (`?page=N`: whole releases up to about 96 KB a page, `[Unreleased]` always on page 1, an index of every release under **All releases**); a link to an older release's anchor (`/changelog#2026-09-26`, or the new per-release `#v0.9.0`) goes to the page that holds it. **Amend the latest release** re-picks its bump (patch, minor or major, counted from the release before it), its date, folds the notes now under `[Unreleased]` into it, or moves it back under `[Unreleased]`; only the newest release, and a version change commits as that version's release (`Release editor 0.12.0`, the amend in the body). The same writer is `pnpm ops amend-release` and `archilyzer release amend`; `/sites` has the form for the export changelog. ## [0.11.1] - 2026-10-28 - **An X post's screenshot is of the post, not of a page in the middle of laying itself out.** On 2026-10-27 a forced capture of TheQuartering's post 2114859155022389342 came out shifted about 100 px: its left edge cut off, X's menu laid over its words and the gap beside the column showing; another post once came out as a strip of the post above it. The shot was a full-page capture, which resizes the page for the moment of the capture — in the X session profile the page saw its window go to 1×1 — and X laid itself out again for that size while it was being captured, so the shot was cut from a different layout than the one measured. A post is now shot from the window as it stands: scrolled into it, the window made taller first when the post is taller than it, so nothing is resized under the shot; and the post is measured again after the shot and shot again if it moved. An X Article's shot is taken the same way. Posts taller than the tallest window (16,384 px) are still shot from a full-page capture. Needs a restart of the editor. diff --git a/editor/app/api/ops/amend-release/route.ts b/editor/app/api/ops/amend-release/route.ts @@ -0,0 +1,79 @@ +import { NextResponse } from "next/server"; +import { + amendRelease, + amendVersionProblem, + dateProblem, + describeAmend, + RELEASE_WORKSPACES, +} from "yt-dlp-transcript-common/controller/cutRelease"; +import { revalidateAfterReleaseCut } from "../../../sites/lib/revalidateAfterReleaseCut"; +import { + OpsInputError, + oneOf, + ops, + opsFail, + optBool, + optString, + reqString, +} from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { workspace: "editor" | "export", +// release: "X.Y.Z" (the LATEST release, as you saw it), +// version?: "patch" | "minor" | "major" | "X.Y.Z" (default: kept), +// date?: "YYYY-MM-DD" (default: kept), +// fold?: boolean (fold [Unreleased] into it), +// uncut?: boolean (withdraw it back to [Unreleased] instead), +// commit?: boolean (default false) } +// +// SYNCHRONOUS, like cut-release: one heading rewrite and at most one +// path-limited commit. The writer is the one the Amend form on /changelog and +// /sites and `archilyzer release amend` call (common/controller/cutRelease.ts, +// amendRelease); every refusal is its sentence. Only the newest release can +// be amended — `release` naming an older one is a 400. +// +// 200 { ok: true, message, result } — `result.changed` false when the file +// already said this (nothing written, nothing committed). A refusal is a 400 +// { ok: false, error, written }: `written` true means the changelog was +// rewritten and only its commit failed. +export async function POST(request: Request) { + return ops( + request, + ["workspace", "release", "version", "date", "fold", "uncut", "commit"], + async (body) => { + const workspace = oneOf(body, "workspace", RELEASE_WORKSPACES); + const release = reqString(body, "release"); + const version = optString(body, "version"); + if (version !== undefined) { + const problem = amendVersionProblem(version); + if (problem) throw new OpsInputError(problem); + } + const date = optString(body, "date"); + const badDate = date === undefined ? null : dateProblem(date); + if (badDate) throw new OpsInputError(badDate); + const fold = optBool(body, "fold") ?? false; + const uncut = optBool(body, "uncut") ?? false; + if (uncut && (version !== undefined || date !== undefined || fold)) { + throw new OpsInputError("A withdrawal takes no version, date or fold."); + } + const commit = optBool(body, "commit") ?? false; + + const result = await amendRelease({ + workspace, + release, + version, + date, + fold, + uncut, + commit, + }); + if (result.ok) { + if (result.changed) revalidateAfterReleaseCut(); + return NextResponse.json({ ok: true, message: describeAmend(result), result }); + } + if (result.written) revalidateAfterReleaseCut(); + return opsFail(result.error, 400, { written: result.written === true }); + }, + ); +} diff --git a/editor/app/changelog/ChangelogAnchorResolver.tsx b/editor/app/changelog/ChangelogAnchorResolver.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { useEffect } from "react"; + +// A LINK TO A RELEASE ON ANOTHER PAGE. /changelog is paged (?page=N), and a +// copied link is `/changelog#<anchor>` with no page — so a link to an older +// release would open page 1 and find nothing. This looks the anchor up in the +// map the server sent (every anchor → its page) and, when another page holds +// it, goes there. It sits in the page's shell, outside the streamed notes, so +// it acts as soon as the shell hydrates rather than after page 1's notes load. +export function ChangelogAnchorResolver({ + anchors, + page, +}: { + anchors: Record<string, number>; + page: number; +}) { + useEffect(() => { + const resolve = () => { + let id: string; + try { + id = decodeURIComponent(window.location.hash.slice(1)); + } catch { + return; + } + if (!id || !Object.hasOwn(anchors, id)) return; + const target = anchors[id]; + if (target === page) return; + const query = target === 1 ? "" : `?page=${target}`; + window.location.replace( + `${window.location.pathname}${query}#${encodeURIComponent(id)}`, + ); + }; + resolve(); + window.addEventListener("hashchange", resolve); + return () => window.removeEventListener("hashchange", resolve); + }, [anchors, page]); + return null; +} + +// THE SCROLL A STREAMED PAGE MISSES. The notes arrive after the shell, moved +// into place by React's streaming script, so the browser's own scroll to +// `#anchor` can fire while the heading is still in a hidden holding node and +// leave the page at the top. Rendered at the END of the notes, this mounts +// once they are in the document, and scrolls to the hash's element if it is +// not already in view. +export function ScrollToHash() { + useEffect(() => { + let id: string; + try { + id = decodeURIComponent(window.location.hash.slice(1)); + } catch { + return; + } + if (!id) return; + const el = document.getElementById(id); + if (!el) return; + const box = el.getBoundingClientRect(); + if (box.top >= 0 && box.bottom <= window.innerHeight && box.height > 0) return; + // An empty `v<version>` marker has no box of its own; its heading does. + (box.height > 0 ? el : (el.parentElement ?? el)).scrollIntoView({ block: "start" }); + }, []); + return null; +} diff --git a/editor/app/changelog/ChangelogNotes.tsx b/editor/app/changelog/ChangelogNotes.tsx @@ -0,0 +1,97 @@ +import { readFile } from "node:fs/promises"; +import Link from "next/link"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { Changelog } from "yt-dlp-transcript-common/components/Changelog"; +import { ScrollToHash } from "./ChangelogAnchorResolver"; +import { + clampChangelogPage, + paginateChangelog, + parseChangelogSections, +} from "yt-dlp-transcript-common/lib/changelog"; + +// THE NOTES of /changelog, one page of them, streamed after the page's shell +// (the Cut and Amend forms). Async on purpose: its read is the await that lets +// the shell flush before the markdown of a page is rendered. +// +// A page is whole sections up to a size budget (common/lib/changelog.ts, +// paginateChangelog); page 1 opens with [Unreleased]. + +export function pageHref(page: number, anchor?: string): string { + const base = page <= 1 ? "/changelog" : `/changelog?page=${page}`; + return anchor ? `${base}#${anchor}` : base; +} + +export async function ChangelogNotes({ + searchParams, +}: { + searchParams: Promise<Record<string, string | string[] | undefined>>; +}) { + const [params, source] = await Promise.all([ + searchParams, + readFile(getPaths().editorChangelogFile, "utf8"), + ]); + const sections = parseChangelogSections(source); + const pages = paginateChangelog(sections); + const page = clampChangelogPage(params.page, pages.length); + const indexes = pages[page - 1]; + const slice = + indexes.length > 0 + ? source.slice(sections[indexes[0]].start, sections[indexes[indexes.length - 1]].end) + : ""; + const pageOfSection = new Map<number, number>(); + pages.forEach((p, n) => p.forEach((i) => pageOfSection.set(i, n + 1))); + + const nav = pages.length > 1 && ( + <nav + aria-label="Changelog pages" + className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground" + > + {page > 1 ? ( + <Link href={pageHref(page - 1)} className="underline hover:text-foreground"> + ← Newer + </Link> + ) : ( + <span className="opacity-40">← Newer</span> + )} + <span> + Page {page} of {pages.length} + </span> + {page < pages.length ? ( + <Link href={pageHref(page + 1)} className="underline hover:text-foreground"> + Older → + </Link> + ) : ( + <span className="opacity-40">Older →</span> + )} + </nav> + ); + + return ( + <section className="flex flex-col gap-4" aria-label="Release notes"> + {sections.length > 1 && ( + <details className="text-sm"> + <summary className="cursor-pointer text-muted-foreground"> + All releases ({sections.filter((s) => s.version).length}) + </summary> + <ul className="mt-2 flex flex-wrap gap-x-4 gap-y-1"> + {sections.map((s, i) => ( + <li key={`${s.start}`}> + <a + href={pageHref(pageOfSection.get(i) ?? 1, s.versionAnchor ?? s.anchor)} + className="font-mono underline decoration-muted-foreground hover:decoration-foreground" + > + {s.version ?? (s.unreleased ? "Unreleased" : s.title)} + </a> + {s.date && <span className="text-muted-foreground"> {s.date}</span>} + </li> + ))} + </ul> + </details> + )} + {nav} + <Changelog source={slice} /> + {nav} + <ScrollToHash /> + </section> + ); +} diff --git a/editor/app/changelog/page.tsx b/editor/app/changelog/page.tsx @@ -1,15 +1,23 @@ import { readFileSync } from "node:fs"; +import { Suspense } from "react"; import type { Metadata } from "next"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { Changelog } from "yt-dlp-transcript-common/components/Changelog"; import { + changelogAnchorPages, + clampChangelogPage, + describeAmendTarget, extractUnreleasedSection, getLatestChangelogDate, getLatestReleasedVersion, + paginateChangelog, + parseChangelogSections, suggestNextVersion, } from "yt-dlp-transcript-common/lib/changelog"; import { MarkChangelogSeen } from "../components/MarkChangelogSeen"; import { CutReleaseForm } from "../sites/components/CutReleaseForm"; +import { AmendReleaseForm } from "../sites/components/AmendReleaseForm"; +import { ChangelogAnchorResolver } from "./ChangelogAnchorResolver"; +import { ChangelogNotes } from "./ChangelogNotes"; export const dynamic = "force-dynamic"; export const metadata: Metadata = { title: "Changelog" }; @@ -20,20 +28,34 @@ function loadChangelog(): string { return readFileSync(getPaths().editorChangelogFile, "utf8"); } -export default function ChangelogPage() { +// THE SHELL FIRST. The page used to render all of editor/CHANGELOG.md (~760 +// KB of markdown: a 2.9 MB response the browser took 5-10 s to show) with the +// Cut release form at the bottom. Now the forms come first, from a few regex +// reads of the file, and the notes stream in after them one page at a time +// (ChangelogNotes, ?page=N). +export default async function ChangelogPage({ + searchParams, +}: { + searchParams: Promise<Record<string, string | string[] | undefined>>; +}) { const source = loadChangelog(); const latestDate = getLatestChangelogDate(source); const lastVersion = getLatestReleasedVersion(source); const suggestedVersion = suggestNextVersion(lastVersion); const unreleased = extractUnreleasedSection(source); const hasUnreleased = unreleased.length > 0; + const amendTarget = describeAmendTarget(source); + const sections = parseChangelogSections(source); + const pages = paginateChangelog(sections); + const page = clampChangelogPage((await searchParams).page, pages.length); return ( <div className="flex flex-col gap-6 max-w-3xl"> <h1 className="text-2xl font-semibold">Changelog</h1> - <Changelog source={source} /> - <section className="flex flex-col gap-3 border-t border-border pt-6"> + <section className="flex flex-col gap-3" aria-labelledby="cut-release-heading"> <div> - <h2 className="text-lg font-semibold">Cut release</h2> + <h2 id="cut-release-heading" className="text-lg font-semibold"> + Cut release + </h2> <p className="text-sm text-muted-foreground"> Turns the current <code>## [Unreleased]</code> heading into a dated semver heading. @@ -46,6 +68,34 @@ export default function ChangelogPage() { hasUnreleased={hasUnreleased} /> </section> + <section + className="flex flex-col gap-3 border-t border-border pt-6" + aria-labelledby="amend-release-heading" + > + <div> + <h2 id="amend-release-heading" className="text-lg font-semibold"> + Amend the latest release + </h2> + <p className="text-sm text-muted-foreground"> + Re-pick its bump or date, fold in what is under{" "} + <code>[Unreleased]</code>, or move it back there. Only the newest + release; a version change commits as that version&apos;s release. + </p> + </div> + <AmendReleaseForm workspace="editor" target={amendTarget} /> + </section> + <div className="border-t border-border pt-6"> + <Suspense + fallback={ + <p className="text-sm text-muted-foreground" role="status"> + Loading release notes… + </p> + } + > + <ChangelogNotes searchParams={searchParams} /> + </Suspense> + </div> + <ChangelogAnchorResolver anchors={changelogAnchorPages(sections, pages)} page={page} /> <MarkChangelogSeen latestDate={latestDate} /> </div> ); diff --git a/editor/app/sites/components/AmendReleaseForm.tsx b/editor/app/sites/components/AmendReleaseForm.tsx @@ -0,0 +1,144 @@ +"use client"; + +import { useActionState } from "react"; +import type { AmendTarget } from "yt-dlp-transcript-common/lib/changelog"; +import { + amendReleaseAction, + type AmendReleaseState, +} from "../lib/amendReleaseAction"; +import { SeededInput, SeededSelect } from "../../components/forms/Field"; +import { seedChecked } from "../../lib/formState"; + +// AMEND THE LATEST RELEASE: re-pick its bump (counted from the release before +// it, so a patch cut can become the minor it should have been), its date, fold +// in what has gathered under [Unreleased] since — or move it back under +// [Unreleased] altogether. The writer is common/controller/cutRelease.ts's +// amendRelease; only the newest release can be amended, and the form names +// it, so a stale form is refused rather than amending another. +export function AmendReleaseForm({ + workspace, + target, +}: { + workspace: "editor" | "export"; + target: AmendTarget | null; +}) { + const [state, formAction, pending] = useActionState< + AmendReleaseState | undefined, + FormData + >(amendReleaseAction, undefined); + + if (!target) { + return ( + <p className="text-sm text-muted-foreground">No release to amend yet.</p> + ); + } + const { latest, previous, bumps } = target; + const id = (name: string) => `amend-${name}-${workspace}`; + // The select's default: the bump the latest release already is, if any. + const current = + (["patch", "minor", "major"] as const).find((k) => bumps[k] === latest.version) ?? ""; + return ( + <form + action={formAction} + className="flex flex-col gap-2" + aria-label={`Amend release ${latest.version}`} + > + <input type="hidden" name="workspace" value={workspace} /> + <input type="hidden" name="release" value={latest.version} /> + <div className="text-sm text-muted-foreground"> + Latest release: <span className="font-mono">{latest.version}</span> + {latest.date ? ` (${latest.date})` : ""} + {previous + ? `; a bump counts from ${previous.version}.` + : "; it is the first release."} + </div> + <div className="flex flex-wrap items-end gap-2"> + <label className="flex flex-col gap-1 text-xs text-muted-foreground" htmlFor={id("version")}> + Version + <SeededSelect + state={state} + id={id("version")} + name="version" + initial={current} + disabled={pending} + className="px-3 py-2 rounded-md border border-border bg-card text-sm font-mono" + > + {current === "" && <option value="">Keep {latest.version}</option>} + <option value="patch">patch: {bumps.patch}</option> + <option value="minor">minor: {bumps.minor}</option> + <option value="major">major: {bumps.major}</option> + </SeededSelect> + </label> + <label className="flex flex-col gap-1 text-xs text-muted-foreground" htmlFor={id("date")}> + Date + <SeededInput + state={state} + id={id("date")} + name="date" + type="date" + initial={latest.date ?? ""} + disabled={pending} + className="px-3 py-2 rounded-md border border-border bg-card text-sm font-mono" + /> + </label> + <button + type="submit" + name="intent" + value="amend" + disabled={pending} + className="px-3 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed" + > + {pending ? "Working…" : "Amend release"} + </button> + <button + type="submit" + name="intent" + value="uncut" + disabled={pending} + className="px-3 py-2 rounded-md text-sm border border-border hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed" + > + Move back to [Unreleased] + </button> + </div> + <div className="flex flex-wrap items-center gap-4"> + <label className="flex items-center gap-1 text-sm text-muted-foreground"> + <input + type="checkbox" + name="fold" + value="true" + defaultChecked={seedChecked(state, "fold", false)} + disabled={pending || target.pending === 0} + /> + <span> + {target.pending === 0 + ? "Nothing under [Unreleased] to fold in" + : `Fold the ${target.pending} note${target.pending === 1 ? "" : "s"} under [Unreleased] into it`} + </span> + </label> + <label className="flex items-center gap-1 text-sm text-muted-foreground"> + <input + type="checkbox" + name="commit" + value="true" + defaultChecked={seedChecked(state, "commit", true)} + disabled={pending} + /> + <span>Commit the amend</span> + </label> + </div> + {state && !state.ok && ( + <div + role="alert" + className="text-sm text-destructive bg-destructive-soft border border-destructive/30 rounded-md px-3 py-2" + > + {state.error} + </div> + )} + {state && state.ok && ( + <div role="status" className="text-sm text-success"> + {state.message} + </div> + )} + </form> + ); +} diff --git a/editor/app/sites/lib/amendReleaseAction.ts b/editor/app/sites/lib/amendReleaseAction.ts @@ -0,0 +1,61 @@ +"use server"; + +import { + amendRelease, + describeAmend, +} from "yt-dlp-transcript-common/controller/cutRelease"; +import { revalidateAfterReleaseCut } from "./revalidateAfterReleaseCut"; +import { formValues, type FormState } from "../../lib/formState"; + +// The "Amend release" form's server action: a FormData adapter over the one +// writer, `amendRelease` (common/controller/cutRelease.ts), which +// `archilyzer release amend` and POST /api/ops/amend-release call too. Every +// refusal is that module's sentence. +// +// Fields: workspace, release (the latest version the form was rendered +// against — the guard), version ("" keeps it; patch | minor | major), date +// (YYYY-MM-DD; "" keeps it), fold, commit, and the submit button's `intent`: +// "amend" or "uncut" (withdraw: version, date and fold are ignored). + +export type AmendReleaseState = FormState<{ message: string; changed: boolean }>; + +const str = (formData: FormData, key: string): string => { + const v = formData.get(key); + return typeof v === "string" ? v.trim() : ""; +}; +const checked = (formData: FormData, key: string): boolean => { + const v = formData.get(key); + return v === "true" || v === "on"; +}; + +export async function amendReleaseAction( + _prev: AmendReleaseState | undefined, + formData: FormData, +): Promise<AmendReleaseState> { + const values = formValues(formData); + const workspaceRaw = str(formData, "workspace"); + const workspace = + workspaceRaw === "editor" || workspaceRaw === "export" ? workspaceRaw : null; + if (!workspace) return { ok: false, error: "Invalid workspace.", values }; + const uncut = str(formData, "intent") === "uncut"; + const version = str(formData, "version"); + const date = str(formData, "date"); + const result = await amendRelease({ + workspace, + release: str(formData, "release"), + ...(uncut + ? { uncut: true } + : { + ...(version ? { version } : {}), + ...(date ? { date } : {}), + fold: checked(formData, "fold"), + }), + commit: checked(formData, "commit"), + }); + if (!result.ok) { + if (result.written) revalidateAfterReleaseCut(); + return { ok: false, error: result.error, values }; + } + if (result.changed) revalidateAfterReleaseCut(); + return { ok: true, message: describeAmend(result), changed: result.changed }; +} diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx @@ -4,6 +4,7 @@ import Link from "next/link"; import { Changelog } from "yt-dlp-transcript-common/components/Changelog"; import { extractUnreleasedSection, + describeAmendTarget, getLatestReleasedVersion, suggestNextVersion, } from "yt-dlp-transcript-common/lib/changelog"; @@ -17,6 +18,7 @@ import { liveJobRows } from "../jobs/active/buildActiveJobs"; import { RunningJobsList } from "../jobs/components/RunningJobsList"; import { BuildButtons } from "./components/BuildButtons"; import { CutReleaseForm } from "./components/CutReleaseForm"; +import { AmendReleaseForm } from "./components/AmendReleaseForm"; import { HomepageConfigForm } from "./components/HomepageConfigForm"; import { PublishPanel, type PanelRow } from "./components/PublishPanel"; import { DeleteSiteButton, MigrateButton } from "./components/SiteListActions"; @@ -152,6 +154,17 @@ export default async function SitesPage() { suggestedVersion={suggestedVersion} hasUnreleased={hasUnreleased} /> + <details className="text-sm"> + <summary className="cursor-pointer text-muted-foreground"> + Amend the latest release + </summary> + <div className="mt-2"> + <AmendReleaseForm + workspace="export" + target={source ? describeAmendTarget(source) : null} + /> + </div> + </details> </section> {/* Publish: every site, the hub and the homepage as stages (release diff --git a/editor/e2e/changelog-pages.spec.ts b/editor/e2e/changelog-pages.spec.ts @@ -0,0 +1,213 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { test, expect, type Locator } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { resolvePath, testPaths } from "./helpers"; + +// /changelog as a release tool: the Cut and Amend forms come first and the +// notes stream in after them one PAGE at a time (?page=N, whole releases up to +// a size budget — common/lib/changelog.ts paginateChangelog); a link to an +// older release's anchor lands on the page that holds it; and the latest +// release can be amended (a patch cut made a minor) or moved back under +// [Unreleased], through the same writer as `pnpm ops amend-release`. +// +// The changelog is the test server's disposable EDITOR_CHANGELOG_FILE, as in +// cut-release.spec.ts; "commit" is off everywhere (the commit path is the +// controller's unit tests', each in a git repo of its own). + +const CHANGELOG = resolvePath(testPaths().editorChangelog); +const AUTH = { authorization: "Bearer test-worker-token" }; + +// What cut-release.spec.ts and ops-cut-release.spec.ts leave behind. +const RESTING = "# Changelog\n\n## [9.9.9] - 2024-01-01\n- old released bullet\n"; + +test.afterEach(async () => { + await writeFile(CHANGELOG, RESTING); +}); + +// A release of ~60 KB: two of them never share a page (the budget is ~96 KB), +// so the pages are [Unreleased] + 9.9.12 | 9.9.11 | 9.9.10 + 9.9.9. +function bigRelease(version: string, date: string, word: string): string { + const bullet = `- **${word} change.** ${`${word} `.repeat(120)}`; + return [`## [${version}] - ${date}`, ...Array.from({ length: 70 }, () => bullet), ""].join("\n"); +} + +const PAGED = [ + "# Changelog", + "", + "## [Unreleased]", + "- **A pending note.**", + "", + bigRelease("9.9.12", "2024-04-01", "twelve"), + bigRelease("9.9.11", "2024-03-01", "eleven"), + bigRelease("9.9.10", "2024-02-01", "tenths"), + "## [9.9.9] - 2024-01-01", + "- **The oldest note.**", + "", +].join("\n"); + +const MISCUT = [ + "# Changelog", + "", + "## [9.9.10] - 2024-02-01", + "- **A minor's worth of features.**", + "", + "## [9.9.9] - 2024-01-01", + "- old released bullet", + "", +].join("\n"); + +// A click before React hydrates submits nothing a client action sees. +async function hydrated(form: Locator): Promise<void> { + await expect(async () => { + const ok = await form.evaluate((el) => + Object.keys(el).some((k) => k.startsWith("__reactProps")), + ); + expect(ok).toBe(true); + }).toPass({ timeout: 15_000 }); +} + +test("the forms come first and the notes are paged, older pages by link", async ({ page }) => { + await writeFile(CHANGELOG, PAGED); + await page.goto("/changelog"); + + // The shell: both forms, ahead of the notes. + const cut = page.getByRole("button", { name: /^cut release$/i }); + await expect(cut).toBeEnabled(); + await expect(page.getByRole("button", { name: /^amend release$/i })).toBeVisible(); + const notes = page.getByRole("region", { name: "Release notes" }); + await expect(notes).toBeVisible(); + const cutBox = await cut.boundingBox(); + const notesBox = await notes.boundingBox(); + expect(cutBox!.y).toBeLessThan(notesBox!.y); + + // Page 1: [Unreleased] and the newest release, nothing older. + const nav = notes.getByRole("navigation", { name: "Changelog pages" }).first(); + await expect(nav).toContainText("Page 1 of 3"); + await expect(notes.getByText("A pending note.")).toBeVisible(); + await expect(notes.locator("#v9\\.9\\.12")).toHaveCount(1); + await expect(notes.locator("#v9\\.9\\.11")).toHaveCount(0); + + await nav.getByRole("link", { name: "Older →" }).click(); + await expect(page).toHaveURL(/\/changelog\?page=2$/); + await expect(nav).toContainText("Page 2 of 3"); + await expect(notes.locator("#v9\\.9\\.11")).toHaveCount(1); + await expect(notes.getByText("A pending note.")).toHaveCount(0); + + await nav.getByRole("link", { name: "← Newer" }).click(); + await expect(page).toHaveURL(/\/changelog$/); + await expect(nav).toContainText("Page 1 of 3"); + + // A page past the end is the last page. + await page.goto("/changelog?page=99"); + await expect(nav).toContainText("Page 3 of 3"); + await expect(notes.getByText("The oldest note.")).toBeVisible(); +}); + +test("a link to an older release's anchor lands on the page that holds it", async ({ page }) => { + await writeFile(CHANGELOG, PAGED); + + // By the release's own id… + await page.goto("/changelog#v9.9.10"); + await expect(page).toHaveURL(/\/changelog\?page=3#v9\.9\.10$/); + // (The id is an empty span inside the heading; the heading is what shows.) + await expect(page.locator("h2:has(#v9\\.9\\.10)")).toBeInViewport(); + + // …and by the date id a link copied before this page had pages carries. + await page.goto("/changelog#2024-01-01"); + await expect(page).toHaveURL(/\/changelog\?page=3#2024-01-01$/); + await expect(page.locator('[id="2024-01-01"]')).toBeInViewport(); + + // An anchor on page 1 stays on page 1. + await page.goto("/changelog#unreleased"); + await expect(page.locator("#unreleased")).toBeVisible(); + await expect(page).toHaveURL(/\/changelog#unreleased$/); + + // The index of every release links to each one's page. + const notes = page.getByRole("region", { name: "Release notes" }); + await notes.getByText(/^All releases/).click(); + await expect(notes.getByRole("link", { name: "9.9.11" })).toHaveAttribute( + "href", + "/changelog?page=2#v9.9.11", + ); +}); + +test("amend round trip: a patch made a minor, then moved back and cut again", async ({ page }) => { + await writeFile(CHANGELOG, MISCUT); + await page.goto("/changelog"); + const form = page.getByRole("form", { name: "Amend release 9.9.10" }); + await hydrated(form); + await expect(form).toContainText("a bump counts from 9.9.9"); + + // patch → minor, counted from 9.9.9. + await form.getByLabel("Version").selectOption("minor"); + await form.getByRole("checkbox", { name: "Commit the amend" }).uncheck(); + await form.getByRole("button", { name: /^amend release$/i }).click(); + await expect( + page.getByRole("status").filter({ hasText: "Amended 9.9.10 -> [9.10.0] - 2024-02-01 (not committed)." }), + ).toBeVisible(); + expect(await readFile(CHANGELOG, "utf8")).toBe(MISCUT.replace("[9.9.10]", "[9.10.0]")); + + // The page now offers 9.10.0 as the latest release. + const amended = page.getByRole("form", { name: "Amend release 9.10.0" }); + await expect(amended).toBeVisible(); + await expect(page.getByText("Last released: 9.10.0")).toBeVisible(); + + // Moved back under [Unreleased]: the cut form has something to cut again. + await hydrated(amended); + await amended.getByRole("checkbox", { name: "Commit the amend" }).uncheck(); + await amended.getByRole("button", { name: "Move back to [Unreleased]" }).click(); + await expect( + page.getByRole("status").filter({ hasText: "Withdrew 9.10.0: 1 note back under [Unreleased]" }), + ).toBeVisible(); + expect(await readFile(CHANGELOG, "utf8")).toBe(MISCUT.replace("[9.9.10] - 2024-02-01", "[Unreleased]")); + await expect(page.locator("#version-editor")).toBeEnabled(); +}); + +test("only the latest release can be amended: a stale form is refused, nothing written", async ({ page }) => { + await writeFile(CHANGELOG, MISCUT); + await page.goto("/changelog"); + const form = page.getByRole("form", { name: "Amend release 9.9.10" }); + await hydrated(form); + + // Someone cuts 9.9.11 while the form is open. + const moved = MISCUT.replace("# Changelog\n\n", "# Changelog\n\n## [9.9.11] - 2024-03-01\n- newer\n\n"); + await writeFile(CHANGELOG, moved); + await form.getByLabel("Version").selectOption("major"); + await form.getByRole("checkbox", { name: "Commit the amend" }).uncheck(); + await form.getByRole("button", { name: /^amend release$/i }).click(); + await expect( + page.getByRole("alert").filter({ + hasText: "Only the latest release can be amended: 9.9.10 is older than 9.9.11.", + }), + ).toBeVisible(); + expect(await readFile(CHANGELOG, "utf8")).toBe(moved); +}); + +test("POST /api/ops/amend-release: the same writer over HTTP", async ({ request }) => { + await writeFile(CHANGELOG, MISCUT); + const post = (data: Record<string, unknown>) => + request.post(`${baseUrl}/api/ops/amend-release`, { headers: AUTH, data }); + + const older = await post({ workspace: "editor", release: "9.9.9", version: "minor" }); + expect(older.status()).toBe(400); + expect(await older.json()).toEqual({ + ok: false, + error: "Only the latest release can be amended: 9.9.9 is older than 9.9.10.", + written: false, + }); + const bad = await post({ workspace: "editor", release: "9.9.10", version: "next" }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toMatch(/"patch", "minor" or "major"/); + expect(await readFile(CHANGELOG, "utf8")).toBe(MISCUT); + + const ok = await post({ workspace: "editor", release: "9.9.10", version: "minor" }); + expect(ok.status()).toBe(200); + const body = await ok.json(); + expect(body.message).toBe("Amended 9.9.10 -> [9.10.0] - 2024-02-01 (not committed)."); + expect(body.result).toMatchObject({ changed: true, to: { version: "9.10.0" } }); + // Again: idempotent. + const again = await post({ workspace: "editor", release: "9.9.10", version: "minor" }); + expect(again.status()).toBe(200); + expect((await again.json()).result.changed).toBe(false); + expect(await readFile(CHANGELOG, "utf8")).toBe(MISCUT.replace("[9.9.10]", "[9.10.0]")); +}); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -117,6 +117,7 @@ // pnpm ops get x-session // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}' +// pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}' // pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait // pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait // pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait @@ -477,6 +478,11 @@ const ACTIONS = [ // needs no editor at all — this route exists only on an editor built from // release 10 or later. "cut-release", + // Amend the LATEST release of a changelog: its bump (patch/minor/major of the + // release before it), its date, [Unreleased] folded in — or withdraw it + // ({workspace, release, version?, date?, fold?, uncut?, commit?}). + // Synchronous; the same writer as `archilyzer release amend`. + "amend-release", // ONE local file, or a window of it, through a local transcription worker // ({path, start?, end?, workerId?, out?}) — the corpus's own engine and // model, as a job. With --wait the result JSON is what stdout carries. @@ -1647,6 +1653,17 @@ export function usage() { " (an older one answers 404); with no editor running, `archilyzer release", " cut` does the same locally.", "", + 'amend-release rewrites the LATEST release of one changelog: {"workspace":', + ' "editor" | "export", "release": "<its version, as you saw it>",', + ' "version": "patch" | "minor" | "major" (a bump of the release BEFORE it)', + ' | "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the [Unreleased] bullets', + ' move into it), "commit": boolean (default false)} -- or {"uncut": true}', + " to withdraw it, its bullets back under [Unreleased]. An older release is", + " refused. A version change commits as that version's release (\"Release", + ' editor 0.12.0") with the amend in the body; history is never rewritten.', + " The same amend again changes nothing. With no editor running,", + " `archilyzer release amend` does the same locally.", + "", 'transcribe runs ONE local file through a local transcription worker, as a', ' job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a', ' window, "workerId" (a settings worker id; default: the one auto-transcribe', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -70,6 +70,19 @@ test("cut-release posts its body to /api/ops/cut-release and is a known action", assert.match(usage(), /release 10 or later/); }); +test("amend-release posts its body to /api/ops/amend-release and is a known action", () => { + const p = parseArgs([ + "amend-release", + "--json", + '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}', + ]); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/amend-release"); + assert.deepEqual(p.body, { workspace: "editor", release: "0.11.1", version: "minor", commit: true }); + assert.match(usage(), /amend-release rewrites the LATEST release of one changelog/); + assert.match(usage(), /An older release is/); +}); + test("malformed --json is refused before any request", () => { assert.match(parseArgs(["sync", "--json", "{"]).error, /not valid JSON/); assert.match(parseArgs(["sync", "--json", "[1]"]).error, /must be a JSON object/);