Archilyzer · Source

archilyzer

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

commit e4fc7d242918a42573e4af88cc52be1792179153
parent e2fcd8922cdd9f7098382669f956645266cc80e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 10:38:14 -0500

Merge main (E1) into lane/vertical-deck

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

Diffstat:
MCOMMANDS.md | 4+++-
MENVIRONMENT.md | 2+-
Acommon/brand/archilyzer-avatar-1024.png | 0
Acommon/brand/archilyzer-avatar.svg | 2++
Mcommon/controller/operationBatch.ts | 13+++++++++++++
Mcommon/controller/operationBatchRelocation.test.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/persistKept.test.ts | 33+++++++++++++++++++++++++++++++++
Mcommon/controller/persistKept.ts | 27+++++++++++++++++++++++++++
Mcommon/controller/persistVideos.test.ts | 27+++++++++++++++++++++++++++
Mcommon/controller/persistVideos.ts | 25+++++++++++++++++++++++--
Mcommon/controller/storageWatch.test.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/storageWatch.ts | 40+++++++++++++++++++++++++++++++++++++---
Mcommon/controller/transcribeError.ts | 22++++++++++++++++++++++
Mcommon/controller/transcribeOne.test.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/transcribeOne.ts | 37++++++++++++++++++++++++++++++++++++-
Mcommon/controller/transcribeOneFromQueue.ts | 6+++++-
Mcommon/controller/whisperBatch.ts | 17++++++++++++++++-
Acommon/lib/brandAvatar.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/lib/channelMedia.ts | 10++++++++++
Mcommon/lib/envVars.ts | 2+-
Acommon/lib/mediaStallHold.test.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mediaStallHold.ts | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoStore.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoStore.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/storageHealth.test.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/storageHealth.ts | 236++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/storageHealthCounters.test.ts | 50+++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/storageVolumes.ts | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/views/names.ts | 5+++++
Mcommon/views/storage.test.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/storage.ts | 19+++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 21++++++++++++++++-----
Meditor/CHANGELOG.md | 3+++
Aeditor/app/api/test/drive-health/route.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/view/[name]/route.test.ts | 2+-
Meditor/app/api/view/views.ts | 6++++++
Meditor/app/channels/[slug]/persistActions.ts | 6+++++-
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 11+++++++++--
Meditor/app/components/dashboard/DashboardCockpit.tsx | 13+++++++++++++
Aeditor/app/components/dashboard/DriveHealthBanner.tsx | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/page.tsx | 5++++-
Meditor/app/storage/buildStorage.ts | 17+++++++++++++++++
Meditor/app/storage/components/StorageLocationsTable.tsx | 21+++++++++++++++++++++
Aeditor/app/storage/lib/driveHealth.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/e2e/drive-health.spec.ts | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/package.json | 2+-
Mplans/FACTS.md | 46++++++++++++++++++++++++++++++++++++++++++++++
Mplans/brand-and-themes.md | 1+
Mscripts/archilyzer-ops.mjs | 4+++-
Mumtool/app/api/report/bench/route.ts | 5+++--
Mumtool/app/api/report/takes/timeline/route.ts | 13+++++++++++--
Mumtool/app/api/report/takes/tools/route.ts | 22+++++++++++++++++++---
Mumtool/app/api/report/timeline/route.ts | 5+++++
Aumtool/app/icon.svg | 1+
Mumtool/bin/umtool.mjs | 1+
Mumtool/components/projects/ClipBench.tsx | 167+++++++++++++++++++++++++------------------------------------------------------
Mumtool/components/projects/ClipBenchPage.tsx | 9+--------
Mumtool/components/projects/TakeTools.tsx | 33++++++++++++++++++---------------
Mumtool/components/projects/TakesBench.tsx | 4++--
Mumtool/components/projects/cutApp/CutApp.tsx | 22+++++-----------------
Mumtool/components/projects/report/CutTab.tsx | 20+++++++++++++++++++-
Aumtool/components/projects/report/RemovedClips.tsx | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 5++++-
Mumtool/docs/knobs.md | 16++++++++++++----
Mumtool/e2e/fixtures/ingredient-rail-fixture.mjs | 18+++++++++++++-----
Mumtool/e2e/fixtures/post-narration-fixture.mjs | 41++++++++++++++++++++++++++++++++++++++++-
Mumtool/e2e/long-reads.spec.ts | 8++++++++
Mumtool/e2e/post-narration.spec.ts | 11+++++------
Mumtool/e2e/shell.spec.ts | 11+++++++++++
Mumtool/e2e/take-items.spec.ts | 30++++++++++++++++++++++++++++++
Mumtool/e2e/take-walk.spec.ts | 14++++++++++++++
Mumtool/e2e/timeline-edit.spec.ts | 26++++++++++++++++++++++++++
Aumtool/lib/brandIcon.test.ts | 17+++++++++++++++++
Mumtool/lib/cli/groups.mjs | 2+-
Mumtool/lib/cli/verbs.mjs | 5+++++
Aumtool/lib/e2eEnvGuard.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/e2eEnvGuard.test.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/ingredients/usedIn.mjs | 5++++-
Mumtool/lib/report/benchData.ts | 73+++++++++++++++++++++++++------------------------------------------------
Mumtool/lib/report/cast.test.mjs | 2+-
Mumtool/lib/report/knobsCli.mjs | 25++++++++++++++++++++++---
Mumtool/lib/report/knobsCli.test.mjs | 28++++++++++++++++++++++++++++
Mumtool/lib/report/linkCheck.mjs | 9++++++---
Mumtool/lib/report/manifest.mjs | 117++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/postsCli.mjs | 2++
Aumtool/lib/report/restore-removed.test.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeDeprecation.mjs | 23+++++++++++++++++++++++
Aumtool/lib/report/takeDeprecation.test.mjs | 12++++++++++++
Mumtool/lib/report/takeEdit.test.mjs | 5+++++
Mumtool/lib/report/takeImport.mjs | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/takeManifest.mjs | 11+++++++++--
Mumtool/lib/report/takeManifest.test.mjs | 16++++++++++++++++
Mumtool/lib/report/takeScope.test.mjs | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/timelineCli.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/package.json | 2+-
Mumtool/playwright.config.ts | 17++++++++++++++---
Mumtool/report-to-video/cues.mjs | 76+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/report-to-video/cues.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
98 files changed, 3267 insertions(+), 337 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -281,7 +281,9 @@ job resume-interrupted does by hand what the editor does at boot: re-queues get settings [<key>] is settings.json as the editor reads it (migrated and defaulted; a secret is "<redacted>"), or one top-level key of it. -get storage is /storage: each location, mounted or not, free space, tiers. +get storage is /storage: each location, mounted or not, free space, tiers, + and its drive's health (rows[].drive: ok | slow | stalled | unmounted, + since, lastOkAt, latencyMs, the cause and the one-line text). get saved-alternates [<slug>] lists every saved video holding two copies: a download over a container already in the store keeps both — an explicit persist (persist-videos, Persist source video, a whole-recording diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -106,7 +106,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `AUDIO_CHECK_BACKOFF_FACTOR` | the built-in factor | The audio check's interval backoff factor, in (0, 1], for a one-off run. | common/ytdlp/audioCheckedDownload.ts | | `ARCHILYZER_STATS_ALLOW_DOWNGRADE` | off | `1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions. | common/controller/buildStats.ts | | `ARCHILYZER_INDEX_ALLOW_HELD` | off | `1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel. | common/controller/buildIndex.ts | -| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh) | +| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh) | | `MCP_IO_STATS` | off | `1` turns on per-call I/O accounting, for `mcp/bench`. | common/lib/archive/io-stats.ts | | `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it. | scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts | | `ARCHILYZER_AGENT` | `cli` | Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`. | scripts/archilyzer-ops.mjs | diff --git a/common/brand/archilyzer-avatar-1024.png b/common/brand/archilyzer-avatar-1024.png Binary files differ. diff --git a/common/brand/archilyzer-avatar.svg b/common/brand/archilyzer-avatar.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#151b20"/><g transform="translate(51.2 51.2) scale(0.8)"><rect x="112" y="128" width="288" height="44" rx="22" fill="#3f4c56"/><polygon points="112,210 172,234 112,258" fill="#e7edf1"/><rect x="188" y="212" width="212" height="44" rx="22" fill="#e7edf1"/><rect x="112" y="296" width="232" height="44" rx="22" fill="#3f4c56"/><rect x="112" y="380" width="152" height="44" rx="22" fill="#3f4c56"/></g></svg> +\ No newline at end of file diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts @@ -41,8 +41,10 @@ import { isGateHeld } from "../lib/pauseGates"; import { assertChannelMediaReachable, assertChannelTextReadable, + readChannelMediaConfig, readRelocationMarker, } from "../lib/channelMedia"; +import { mediaStallHold } from "../lib/mediaStallHold"; import { runPool } from "../jobs/concurrentRunner"; import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; @@ -1601,6 +1603,16 @@ export async function runOperationBatch( } else { await assertChannelMediaReachable(opts.paths, opts.channelSlug); } + // THE BACKFILL LANE OPENS MEDIA, so it holds while the channel's media drive + // is not answering (lib/mediaStallHold.ts); the digest lane reads text only. + const stallHold = run.digest + ? null + : mediaStallHold( + await readChannelMediaConfig(opts.paths, opts.channelSlug), + log, + "backfill unit", + { reloadConfig: () => readChannelMediaConfig(opts.paths, opts.channelSlug) }, + ); const dataDir = path.join(opts.paths.channelsDir, opts.channelSlug, "data"); const allDirs = await readdir(dataDir).catch(() => [] as string[]); const onDisk = new Set(allDirs); @@ -1851,6 +1863,7 @@ export async function runOperationBatch( next, run: runOne, limit: () => { + if (stallHold?.check()) return 0; const live = operationLaneLive(run, opts.concurrency); const verdict = laneLimit(getSettings(), live); if (verdict.hold) { diff --git a/common/controller/operationBatchRelocation.test.ts b/common/controller/operationBatchRelocation.test.ts @@ -26,6 +26,9 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "batch-relocation-")); process.env.TRANSCRIPTS_DIR = ROOT; const SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.SETTINGS_FILE = SETTINGS_FILE; +// No engine ever runs: the one case that dispatches (the drive-stall hold, +// below) gets an "engine" that exits 1 at once. +process.env.DIARIZE_BIN = "/bin/false"; // The backfill lane armed with ONE operation, and that operation's cheapest // classification: every seeded video has a transcript and no audio, so @@ -141,3 +144,70 @@ test("a marker written mid-run ends the batch instead of racing the copy", async assert.ok(stop, `expected a stop line, got:\n${lines.join("\n")}`); assert.match(stop as string, /\(out\) of omni to \/platter\/omni\/data/); }); + +// A DRIVE THAT STOPS ANSWERING MID-RUN HOLDS THE BATCH (lane drive-stall). The +// start-of-work guard passed (the drive answered); the second pull finds the +// channel's media location stalled in the health record, and the pool's limit +// is 0 until it answers again — nothing is dispatched onto a drive that would +// hold a file thread per unit, nothing is failed, and the run resumes. +test("a media drive that stops answering mid-run holds the backfill batch until it answers", async () => { + const { + recordLocationHealth, + registerLocationHealth, + resetStorageHealth, + } = await import("../lib/storageHealth"); + resetStorageHealth(); + await seed("held", ["v1", "v2"]); + const platter = path.join(ROOT, "platter"); + const mediaDir = path.join(platter, "held", "media"); + await mkdir(mediaDir, { recursive: true }); + const channelDir = path.join(getPaths().channelsDir, "held"); + const { symlink } = await import("node:fs/promises"); + await symlink(mediaDir, path.join(channelDir, "media")); + await writeFile( + path.join(channelDir, "config.json"), + JSON.stringify({ handling: "transcribe", url: "https://example.com/c", mediaDir }), + ); + // Audio on both, so diarization dispatches (and fails on the fixture's + // missing models — what is under test is when it is dispatched). + for (const id of ["v1", "v2"]) { + await writeFile(path.join(channelDir, "data", id, "audio.mp3"), "ID3audio"); + } + const loc = { id: "platter", label: "Platter", root: platter }; + registerLocationHealth([loc]); + + // The pool's idle poll is unref'd (a server keeps the loop alive; a test + // process would exit under a paused pool). + const keepAlive = setInterval(() => {}, 1_000); + let progressCalls = 0; + const lines: string[] = []; + const result = await runOperationBatch({ + lane: "backfill", + channelSlug: "held", + paths: getPaths(), + operationIds: ["diarization"], + onLog: (m) => lines.push(m), + setProgress: () => { + progressCalls++; + if (progressCalls !== 2) return; + recordLocationHealth(loc, "stalled", { cause: "test: no answer" }); + // It answers again a moment later: two clean answers clear it. + setTimeout(() => { + recordLocationHealth(loc, "ok"); + recordLocationHealth(loc, "ok"); + }, 300); + }, + }); + clearInterval(keepAlive); + // Both videos were dispatched in the end (and failed on the fake engine): + // held, not dropped. + assert.equal(result.attempted, 2); + const at = (prefix: string) => lines.findIndex((l) => l.startsWith(prefix)); + const v1 = at("Diarize v1 start"); + const hold = at("Holding: the media drive"); + const resume = at(`The media drive "Platter" answers again — resuming.`); + const v2 = at("Diarize v2 start"); + assert.ok(v1 >= 0 && hold > v1 && resume > hold && v2 > resume, `the order was:\n${lines.join("\n")}`); + assert.match(lines[hold], /"Platter" is not answering \(since \d\d:\d\d\) — no new backfill unit starts/); + resetStorageHealth(); +}); diff --git a/common/controller/persistKept.test.ts b/common/controller/persistKept.test.ts @@ -59,6 +59,7 @@ test("persistKept is a no-op when keep-latest is off", async () => { persisted: 0, failed: 0, skippedNoUrl: 0, + skippedStoreUnavailable: 0, skippedLowDisk: 0, }); }); @@ -83,3 +84,35 @@ test("persistKept counts in-window videos already saved without re-downloading", assert.equal(res.skippedNoUrl, 0); }); }); + +// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE PASS BEFORE ANY FETCH (review +// of lane drive-stall): the store's drive is not answering, so nothing is +// downloaded to land nowhere; every unsaved kept video is counted skipped. +test("persistKept stops before fetching when the saved-video store's drive is not answering", async () => { + const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth"); + await withPaths(async (paths) => { + for (const id of ["20240101_a", "20240202_b", "20240303_c"]) { + await mkdir(path.join(paths.channelsDir, "alpha", "data", id), { recursive: true }); + } + recordLocationHealth( + { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) }, + "stalled", + ); + const lines: string[] = []; + try { + const res = await persistKept({ + paths, + channelSlug: "alpha", + channelConfig: { handling: "transcribe", keepLatest: 2 }, + onLog: (l: string) => lines.push(l), + }); + assert.equal(res.kept, 2); + assert.equal(res.persisted, 0); + assert.equal(res.failed, 0); + assert.equal(res.skippedStoreUnavailable, 2); + assert.match(lines.join("\n"), /The saved-video store's drive "Store drive" is not answering .* — stopping/); + } finally { + resetStorageHealth(); + } + }); +}); diff --git a/common/controller/persistKept.ts b/common/controller/persistKept.ts @@ -5,6 +5,8 @@ import { getSettings } from "../lib/settings"; import { diskGate } from "../lib/diskSpace"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { isSavedVideo } from "../lib/savedVideo-server"; +import { savedVideoDir } from "../lib/savedVideo"; +import { savedVideosStoreRefusal } from "../lib/savedVideoStore"; import { computeKeptVideoIds } from "./keptVideos"; import { findVideoSourceUrl } from "./undownloadedVideos"; import { @@ -40,6 +42,9 @@ export type PersistKeptResult = { failed: number; // No resolvable source URL (no metadata + not in the playlist). skippedNoUrl: number; + // Not attempted because the saved-video store could not take a container + // (its drive not answering, or mid-move) — asked before each fetch. + skippedStoreUnavailable: number; // Not attempted because free disk fell under the floor part-way through. A // refusal to start, not a failure — these videos are still kept, still // unpersisted, and the next pass picks them up. @@ -81,6 +86,7 @@ export async function persistKept({ failed: 0, skippedNoUrl: 0, skippedLowDisk: 0, + skippedStoreUnavailable: 0, }; if (keptIds.size === 0) { log( @@ -105,17 +111,35 @@ export async function persistKept({ // Set once the disk gate closes mid-pass. Everything after it is counted as // skipped rather than attempted, so the log says how much was left. let lowDisk = false; + let storeUnavailable = false; for (const videoId of ordered) { if (signal?.aborted) break; if (lowDisk) { result.skippedLowDisk += 1; continue; } + if (storeUnavailable) { + result.skippedStoreUnavailable += 1; + continue; + } const videoDir = path.join(dataDir, videoId); if (await isSavedVideo(videoDir)) { result.alreadySaved += 1; continue; } + // THE STORE MUST BE ABLE TO TAKE IT (review of lane drive-stall): asked + // before the fetch, so a stalled store drive or a store mid-move stops the + // pass instead of downloading containers that land nowhere. + const refusal = await savedVideosStoreRefusal( + paths, + savedVideoDir(paths, channelConfig, channelSlug, videoId), + ); + if (refusal) { + storeUnavailable = true; + result.skippedStoreUnavailable += 1; + log(` ${videoId}: ${refusal.message} — stopping; remaining videos skipped.`); + continue; + } // PER ITEM, not once at the start. This pass writes full source containers — // the largest files the app produces — so the twentieth video must not // inherit the first one's headroom. Same shape as backfillReacquire's @@ -175,6 +199,9 @@ export async function persistKept({ (result.skippedLowDisk > 0 ? `, ${result.skippedLowDisk} skipped (low disk)` : "") + + (result.skippedStoreUnavailable > 0 + ? `, ${result.skippedStoreUnavailable} skipped (saved-video store unavailable)` + : "") + ` of ${result.kept} kept.`, ); return result; diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts @@ -538,3 +538,30 @@ test("a dry run buckets every item and fetches nothing", async () => { assert.equal(res.plan.willFetch, 2); }); }); + +// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE RUN BEFORE THE FETCH (review +// of lane drive-stall): its drive is not answering, so no container is +// downloaded only to be left in the data dir. +test("a saved-video store whose drive is not answering stops the run before any fetch", async () => { + const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth"); + await withPaths(async (paths) => { + for (const id of ["aaa111", "bbb222"]) await seedVideo(paths, "demo-channel", id); + recordLocationHealth( + { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) }, + "stalled", + ); + try { + const h = harness(paths); + const res = await persistVideos({ + paths, + items: ["aaa111", "bbb222"].map((id) => ({ slug: "demo-channel", id })), + deps: h.deps, + }); + assert.deepEqual(h.downloads, []); + assert.equal(res.stopped, "store-unavailable"); + assert.deepEqual(res.notAttempted.map((i) => i.id), ["aaa111", "bbb222"]); + } finally { + resetStorageHealth(); + } + }); +}); diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts @@ -5,9 +5,10 @@ import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; import { getSettings } from "../lib/settings"; import { diskGate, type DiskGateStatus } from "../lib/diskSpace"; +import { savedVideosStoreRefusal } from "../lib/savedVideoStore"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; -import type { SavedVideoPointer } from "../lib/savedVideo"; +import { savedVideoDir, type SavedVideoPointer } from "../lib/savedVideo"; import { loadSavedVideo, restoreSavedVideoProvenance, @@ -94,7 +95,15 @@ export type PersistVideosPlan = { willFetch: number; }; -export type PersistVideosStop = "low-disk" | "rate-limit" | "cancelled" | "drained"; +// `store-unavailable`: the saved-video store cannot take a container (its +// drive is not answering, or it is being moved) — the run stops before +// downloading one only to leave it in the data dir. +export type PersistVideosStop = + | "low-disk" + | "rate-limit" + | "store-unavailable" + | "cancelled" + | "drained"; export type PersistVideosResult = { plan: PersistVideosPlan; @@ -459,6 +468,18 @@ export async function persistVideos({ stop("low-disk", i); break; } + // THE STORE MUST BE ABLE TO TAKE IT, asked before the fetch: a stalled + // drive or a store mid-move would refuse the container after a whole + // download. Memory and the corpus disk only. + const refusal = await savedVideosStoreRefusal( + paths, + savedVideoDir(paths, config, p.slug, p.id), + ); + if (refusal) { + log(` ${label(p)}: ${refusal.message} — stopping; the rest are left for a later run.`); + stop("store-unavailable", i); + break; + } const replacing = p.bucket === "wrongHeight"; log( ` ${label(p)}: ${replacing ? "replacing the saved container" : "fetching the source container"} (${quality})…`, diff --git a/common/controller/storageWatch.test.ts b/common/controller/storageWatch.test.ts @@ -24,6 +24,7 @@ import { import { inspectChannelMedia } from "../lib/channelMedia"; import { applyHealthTimings, + driveHealthView, healthTimings, locationHealth, resetStorageHealth, @@ -661,3 +662,98 @@ test("DT: a changed pass interval re-arms the armed pass; an explicit interval f } }); }); + +// THE PASS'S WRITE WAITS FOR THE SETTINGS LOCK (lane drive-stall). The +// editor's priority writer holds the per-process lock on settings.json for its +// whole read-modify-write (editor/app/settings/saveSettings.ts, +// `withSettingsLock`); a pass that wrote in the middle of it would be written +// over by the writer's stale document, and the pause lost. +test("the pass writes under the settings lock: a writer holding it is not interleaved", async () => { + const { withJsonFileLock } = await import("../lib/jsonFile-server"); + const { getPaths } = await import("../lib/paths"); + await withTmp(async (h) => { + await seedRelocated(h, "gone", { targetExists: false }); + await seedRelocated(h, "other", { targetExists: true }); + const pass = () => runStorageWatchPass({ paths: h.paths, io: h.io, bins: h.paths }); + await pass(); // the suspicion + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const order: string[] = []; + // The "priority writer": reads, waits while holding the lock, writes. + const writer = withJsonFileLock(getPaths().settingsFile, async () => { + const before = h.io.read(); + await gate; + order.push("writer"); + await h.io.write({ + ...before, + channelPriority: sanitizeChannelPriority({ + ...before.channelPriority, + channels: { ...before.channelPriority.channels, other: { tier: "low" } }, + }), + }); + }); + const confirming = pass().then((r) => { + order.push("pass"); + return r; + }); + // Give the pass every chance to write while the lock is held. + await new Promise((r) => setTimeout(r, 50)); + assert.equal(h.writes, 0, "the pass did not write while the lock was held"); + release(); + await writer; + const second = await confirming; + assert.deepEqual(second.paused, ["gone"]); + assert.deepEqual(order, ["writer", "pass"]); + // Both survive: the writer's tier and the pass's pause. + assert.equal(tierOf(h, "other"), "low"); + assert.equal(tierOf(h, "gone"), "paused"); + }); +}); + +// THE PROBE'S STATE MACHINE WITH A FAKE PROBER (lane drive-stall): the +// verdicts a detector gives, pass by pass, and the view every surface reports +// from them — ok, slow (an answer at half the budget or more), stalled (no +// answer: the gate refuses), ok again after two clean passes. No drive, no +// subprocess: the probe is a script. +test("a fake prober walks the drive ok -> slow -> stalled -> ok, and the gate follows only the stall", async () => { + await withTmp(async (h) => { + await seedRelocated(h, "on-cold", { targetExists: true }); + const verdicts = [ + { answer: "ok" as const, detector: "stat" as const, latencyMs: 4 }, + { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_100 }, + { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_200 }, + { answer: "stalled" as const, detector: "stat" as const, cause: "a stat of its root did not answer within 3 s" }, + { answer: "ok" as const, detector: "stat" as const, latencyMs: 6 }, + { answer: "ok" as const, detector: "stat" as const, latencyMs: 5 }, + ]; + let i = 0; + const probe = async () => verdicts[Math.min(i++, verdicts.length - 1)]; + const loc = { id: "cold", label: "Cold" }; + const view = () => driveHealthView(loc, locationHealth("cold")); + const pass = () => runStorageHealthPass({ io: h.io, probe }); + + await pass(); + assert.equal(view().state, "ok"); + assert.equal(view().latencyMs, 4); + assert.equal(typeof view().lastOkAt, "number"); + + await pass(); // one slow reading: not yet slow + assert.equal(view().state, "ok"); + await pass(); + assert.equal(view().state, "slow"); + assert.match(String(view().cause), /^a stat of its root took 2.2 s$/); + // Slow is shown, never acted on: the channel's media still answers ok. + assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok"); + + await pass(); + assert.equal(view().state, "stalled"); + assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "stalled"); + + await pass(); // one clean answer: still stalled + assert.equal(view().state, "stalled"); + await pass(); // two in a row: answering again, and not slow + assert.equal(view().state, "ok"); + assert.equal(view().latencyMs, 5); + assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok"); + }); +}); diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts @@ -1,4 +1,5 @@ import { getPaths, type Paths } from "../lib/paths"; +import { withJsonFileLock } from "../lib/jsonFile-server"; import { getSettings, writeSettings, @@ -34,6 +35,7 @@ import { NOT_ANSWERING, applyHealthTimings, healthTimings, + noteDriveAnswer, noteLocationDetector, onPassIntervalChange, pruneLocationHealth, @@ -297,6 +299,29 @@ export async function runStorageWatchPass( if (out.paused.length === 0 && out.restored.length === 0) return out; if (opts.write === false) return out; + // UNDER THE SETTINGS LOCK (lane drive-stall, after lane editor-gaps). The + // editor's other read-modify-write of `channelPriority` — the priority + // writer, which also clears `autoPaused` on a manual tier change — runs inside + // `withSettingsLock` (editor/app/settings/saveSettings.ts), which is this same + // per-process lock on settings.json. Without it the two interleave: the + // operator's tier change lands between this pass's read and its write and is + // written over, or the pass's pause is. The lock is not re-entrant, and + // nothing called inside it takes it. + await withJsonFileLock(getPaths().settingsFile, () => + writePassResult(io, paths, configs, out, pauseCauses), + ); + out.wrote = true; + return out; +} + +// THE PASS'S ONE WRITE, with the settings lock held by the caller. +async function writePassResult( + io: NonNullable<StorageWatchOpts["io"]>, + paths: Paths, + configs: ReadonlyArray<{ slug: string }>, + out: StorageWatchResult, + pauseCauses: ReadonlyMap<string, AutoPauseCause>, +): Promise<void> { // ONE WRITE PER PASS, whatever the pass found. Ten channels on one drive that // vanished is one settings write and one pulse bump, not ten. // @@ -349,8 +374,6 @@ export async function runStorageWatchPass( } } await io.write({ ...latest, channelPriority: merged, autoQueue }); - out.wrote = true; - return out; } // Five minutes. A drive does not come and go on a timescale a person would @@ -436,12 +459,23 @@ function recordVerdict( if (verdict.detector) noteLocationDetector(loc.id, verdict.detector, device); return null; } - return recordLocationHealth(loc, verdict.answer, { + const t = recordLocationHealth(loc, verdict.answer, { now, cause: verdict.cause ?? statCause(), ...(verdict.detector ? { detector: verdict.detector } : {}), ...(device !== undefined ? { device } : {}), }); + // How long it took, when the detector measured it (lane drive-stall): the + // counters' average per request, or the child stat's round trip. + if (verdict.answer === "ok" && verdict.latencyMs !== undefined) { + noteDriveAnswer( + loc.id, + verdict.latencyMs, + verdict.detector === "counters" ? "counters" : "stat", + now, + ); + } + return t; } export async function runStorageHealthPass( diff --git a/common/controller/transcribeError.ts b/common/controller/transcribeError.ts @@ -17,3 +17,25 @@ export class TranscribeError extends Error { this.name = "TranscribeError"; } } + +// THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lane drive-stall): the audio is +// not opened, and the video is skipped like a "no-audio" one — never recorded +// in failed-transcriptions, transcribed on a later pass once the drive answers. +// Its own class so a batch's log says the drive, not "no audio file". +export class MediaDriveHeldError extends TranscribeError { + // Read by `isMediaDriveHeld`, which also answers for a copy of this class + // from another module instance (instanceof does not). + readonly mediaDriveHeld = true; + constructor(message: string) { + super(message, "no-audio"); + } +} + +// A transcription refused because its channel's media drive is not answering: +// a skip for every caller, never a failed transcription or a failed download. +export function isMediaDriveHeld(err: unknown): err is MediaDriveHeldError { + return ( + err instanceof MediaDriveHeldError || + (err instanceof Error && (err as { mediaDriveHeld?: unknown }).mediaDriveHeld === true) + ); +} diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts @@ -71,3 +71,68 @@ test("an engine that exits 0 with no output, audio gone, is a skip too", async ( assert.ok(err instanceof TranscribeError, `not a TranscribeError: ${err}`); assert.equal(err.failureClass, "no-audio"); }); + +// THE TRANSCRIPTION SOURCE IS NOT OPENED ON A DRIVE THAT IS NOT ANSWERING +// (lane drive-stall). The channel's config names a media location the health +// record has stalled: the video is refused before its audio is looked for, +// as a skip (never failed-transcriptions), and the engine never runs. +test("a channel whose media drive is not answering is refused before its audio is opened", async () => { + const { MediaDriveHeldError } = await import("./transcribeError"); + const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth"); + const { mkdir } = await import("node:fs/promises"); + const { existsSync } = await import("node:fs"); + const dir = await mkdtemp(path.join(tmpdir(), "transcribe-held-")); + try { + const platter = path.join(dir, "platter"); + const channelDir = path.join(dir, "channels", "held"); + const videoDir = path.join(channelDir, "data", "vid1"); + await mkdir(videoDir, { recursive: true }); + await writeFile( + path.join(channelDir, "config.json"), + JSON.stringify({ handling: "transcribe", mediaDir: path.join(platter, "held", "media") }), + ); + await writeFile(path.join(videoDir, "audio.mp3"), "not really audio"); + const ran = path.join(dir, "engine-ran"); + const bin = path.join(dir, "fake-engine.sh"); + await writeFile(bin, `#!/bin/sh\ntouch ${ran}\nexit 1\n`, { mode: 0o755 }); + recordLocationHealth({ id: "platter", label: "Platter", root: platter }, "stalled"); + const err = await transcribeOneVideo({ + paths: {} as Paths, + videoDir, + videoId: "vid1", + audioFilename: "audio.mp3", + worker: { + id: "w1", + name: "fake", + kind: "local", + enabled: true, + priority: 0, + appId: "whisper-cpp", + config: { bin, model: "model.bin" }, + }, + onLog: () => {}, + }).then( + (v) => v, + (e) => e, + ); + assert.ok(err instanceof MediaDriveHeldError, `not a MediaDriveHeldError: ${err}`); + assert.equal(err.failureClass, "no-audio"); + assert.match(err.message, /^the media drive "Platter" is not answering \(since \d\d:\d\d\) — vid1 is left for when it answers$/); + assert.equal(existsSync(ran), false, "the engine never ran"); + } finally { + resetStorageHealth(); + await rm(dir, { recursive: true, force: true }); + } +}); + +// Every caller reads a held transcription as a skip through ONE predicate, +// which also answers for a copy of the class from another module instance. +test("isMediaDriveHeld: the held class, by instance or by its flag; nothing else", async () => { + const { isMediaDriveHeld, MediaDriveHeldError } = await import("./transcribeError"); + assert.equal(isMediaDriveHeld(new MediaDriveHeldError("the media drive \"x\" is not answering")), true); + const foreign = Object.assign(new Error("copy"), { mediaDriveHeld: true }); + assert.equal(isMediaDriveHeld(foreign), true); + assert.equal(isMediaDriveHeld(new TranscribeError("no audio file", "no-audio")), false); + assert.equal(isMediaDriveHeld(new Error("boom")), false); + assert.equal(isMediaDriveHeld(null), false); +}); diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -2,6 +2,7 @@ import path from "node:path"; import fs from "fs-extra"; import { execa } from "execa"; import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; import type { Worker } from "../lib/workers"; import { getTranscriptionApp } from "../lib/transcriptionApps"; import { detectTranscriptFormat } from "../lib/whisper"; @@ -16,7 +17,9 @@ import { normalizeTranscript } from "./normalizeTranscript"; import { diarizeOneVideo } from "./diarizeOne"; import { getSettings } from "../lib/settings"; import { pingRemoteHealth, transcribeViaRemote } from "./remoteTranscribe"; -import { TranscribeError } from "./transcribeError"; +import { MediaDriveHeldError, TranscribeError } from "./transcribeError"; +import { channelMediaStall } from "../lib/channelMedia"; +import { mediaDriveHeldText } from "../lib/mediaStallHold"; import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus"; import { pickPreferredAudio } from "../lib/mediaFiles"; import { heldAudioDamage } from "../lib/audioIntegrity-server"; @@ -67,6 +70,23 @@ async function resolveAudioFile( return null; } +// THE CHANNEL'S CONFIG FOR THE STALL CHECK, read at most once per 10 s per +// channel (review of lane drive-stall): a batch transcribes a channel's videos +// one after another, and each asked config.json again. Its media targets are +// all the check reads, and a move rewrites them seldom; ten seconds late is +// within the health pass's own cadence. +const STALL_CONFIG_TTL_MS = 10_000; +const stallConfigMemo = new Map<string, { at: number; config: ChannelConfig | null }>(); + +async function channelConfigForStall(file: string): Promise<ChannelConfig | null> { + const now = Date.now(); + const hit = stallConfigMemo.get(file); + if (hit && now - hit.at < STALL_CONFIG_TTL_MS) return hit.config; + const config = await readChannelConfigFile(file).catch(() => null); + stallConfigMemo.set(file, { at: now, config }); + return config; +} + // A CONTAINER TO TRANSCRIBE FROM, before any audio download (release 23 F2). // // The page's Transcribe (and `pnpm ops transcribe-one`) used to download the @@ -200,6 +220,21 @@ export async function transcribeOneVideo( return "already-exists"; } + // NOT OPENED ON A DRIVE THAT IS NOT ANSWERING (lane drive-stall). The audio + // is a tierable file, a link onto the channel's media drive; asking for it + // there in-process holds one of Node's file threads until the kernel gives + // up (~30 s). The health record is memory, the config the corpus disk's. + const stall = channelMediaStall( + await channelConfigForStall( + path.join(path.dirname(path.dirname(opts.videoDir)), "config.json"), + ), + ); + if (stall) { + throw new MediaDriveHeldError( + `${mediaDriveHeldText(stall)} — ${opts.videoId} is left for when it answers`, + ); + } + const resolvedAudio = await resolveAudioFile( opts.videoDir, opts.audioFilename, diff --git a/common/controller/transcribeOneFromQueue.ts b/common/controller/transcribeOneFromQueue.ts @@ -7,7 +7,7 @@ import { readVideoFiles, } from "../lib/videoStatus"; import { transcribeWithWorker } from "./transcribeOne"; -import { TranscribeError } from "./transcribeError"; +import { isMediaDriveHeld, TranscribeError } from "./transcribeError"; import type { TaskTracker } from "../jobs/taskHooks"; const { pathExists, appendFile } = fs; @@ -157,6 +157,10 @@ export async function transcribeOneFromQueue({ // A missing audio file is a download/source problem, not a transcription // failure — skip it (it transcribes once a good audio file exists) rather // than permanently recording it in failed-transcriptions. + if (isMediaDriveHeld(err)) { + log(`Skipping ${videoId}: ${err.message}`); + return { attempted: true, outcome: "skipped" }; + } if (err instanceof TranscribeError && err.failureClass === "no-audio") { log(`Skipping ${videoId}: no audio file (download/source problem)`); return { attempted: true, outcome: "skipped" }; diff --git a/common/controller/whisperBatch.ts b/common/controller/whisperBatch.ts @@ -13,6 +13,8 @@ import { runPool } from "../jobs/concurrentRunner"; import { pruneFailedTranscriptions } from "./failedTranscriptions"; import { resolveShardItems } from "./shard"; import { countNotYetTranscribed } from "./channels"; +import { mediaStallHold } from "../lib/mediaStallHold"; +import { readChannelMediaConfig } from "../lib/channelMedia"; import { getWorkerPool } from "../jobs/workerPool"; import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; @@ -224,6 +226,17 @@ export async function runWhisperBatch({ // transcribe is shared with the auto-runner via transcribeOneFromQueue. const NEVER = new AbortController().signal; let idx = 0; + // HELD WHILE THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lib/mediaStallHold.ts): + // the limit is 0, the pool pauses, and it resumes when the drive answers. + // The check is memory; the config is re-read in the background. + const stallHold = mediaStallHold( + await readChannelMediaConfig(paths, channelSlug), + log, + "transcription", + // Re-read in the background (at most every 10 s): a move mid-batch is + // held by the drive the media is on now. + { reloadConfig: () => readChannelMediaConfig(paths, channelSlug) }, + ); const runOne = async (videoDir: string, runSignal: AbortSignal): Promise<void> => { const res = await transcribeOneFromQueue({ paths, @@ -250,7 +263,9 @@ export async function runWhisperBatch({ // Eligible (enabled, non-degraded) worker slots — the real throughput // ceiling. 0 ⇒ paused until a worker is re-enabled (runPool idle-waits). limit: () => - pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length, + stallHold.check() + ? 0 + : pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length, signal: signal ?? NEVER, drainSignal: drainSignal ?? NEVER, finite: true, diff --git a/common/lib/brandAvatar.test.ts b/common/lib/brandAvatar.test.ts @@ -0,0 +1,32 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { ICON_PALETTES, markSvg } from "./brand"; + +// common/brand/archilyzer-avatar.svg + archilyzer-avatar-1024.png: the profile +// picture the operator chose on 9 Nov (PLAIN over Signal), copied verbatim from +// the approved pair. They are the source of truth for the avatar on every +// account; nothing renders them. This holds the SVG to the mark's geometry so a +// change to MARK cannot leave the picture silently off-model: it is markSvg's +// maskable variant (full-bleed ground, lines at 0.8 in the safe zone) on the +// parent slate, lit achromatic, with the dim the pair was drawn with before +// 2026-09-27's 3:1 bump (#3f4c56; the live mark's is ICON_PALETTES.archilyzer.dim). +const AVATAR_DIM = "#3f4c56"; +const file = (name: string) => fileURLToPath(new URL(`../brand/${name}`, import.meta.url)); + +test("the avatar SVG is the parent mark, maskable, plain (achromatic lit)", () => { + const svg = readFileSync(file("archilyzer-avatar.svg"), "utf8").trimEnd(); + assert.equal( + svg, + markSvg({ ground: ICON_PALETTES.archilyzer.ground, dim: AVATAR_DIM, lit: ICON_PALETTES.archilyzer.lit }, { variant: "maskable" }), + ); +}); + +test("the avatar PNG is a 1024 x 1024 PNG", () => { + const png = readFileSync(file("archilyzer-avatar-1024.png")); + assert.deepEqual([...png.subarray(0, 8)], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + assert.equal(png.subarray(12, 16).toString("ascii"), "IHDR"); + assert.equal(png.readUInt32BE(16), 1024); + assert.equal(png.readUInt32BE(20), 1024); +}); diff --git a/common/lib/channelMedia.ts b/common/lib/channelMedia.ts @@ -271,6 +271,16 @@ function configuredOf(config: ChannelMediaConfig | null | undefined): Configured // `mediaDir` and the retired `dataDir`, read straight off config.json. // Deliberately NOT parseChannelConfig: this runs in guards on hot paths and // must not depend on the controller that owns the rest of the schema. +// A channel's configured media targets (`mediaDir`, the retired `dataDir`) +// off its config.json on the corpus disk; `{}` for none or an unreadable file. +// What a caller with only a slug hands `channelMediaStall`. +export function readChannelMediaConfig( + paths: ChannelMediaPaths, + slug: string, +): Promise<ChannelMediaConfig> { + return readConfigured(paths, slug); +} + async function readConfigured( paths: ChannelMediaPaths, slug: string, diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -142,7 +142,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "AUDIO_CHECK_BACKOFF_FACTOR", audience: "runtime", default: "the built-in factor", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "The audio check's interval backoff factor, in (0, 1], for a one-off run." }, { name: "ARCHILYZER_STATS_ALLOW_DOWNGRADE", audience: "runtime", default: "off", readBy: "common/controller/buildStats.ts", doc: "`1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions." }, { name: "ARCHILYZER_INDEX_ALLOW_HELD", audience: "runtime", default: "off", readBy: "common/controller/buildIndex.ts", doc: "`1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel." }, - { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." }, + { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." }, { name: "MCP_IO_STATS", audience: "runtime", default: "off", readBy: "common/lib/archive/io-stats.ts", doc: "`1` turns on per-call I/O accounting, for `mcp/bench`." }, { name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts", doc: "Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it." }, { name: "ARCHILYZER_AGENT", audience: "runtime", default: "`cli`", readBy: "scripts/archilyzer-ops.mjs", doc: "Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`." }, diff --git a/common/lib/mediaStallHold.test.ts b/common/lib/mediaStallHold.test.ts @@ -0,0 +1,172 @@ +import { beforeEach, test } from "node:test"; +import assert from "node:assert/strict"; +import { mediaDriveHeldText, mediaStallHold } from "./mediaStallHold"; +import { + recordLocationHealth, + registerLocationHealth, + resetStorageHealth, +} from "./storageHealth"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mediaStallHold.test.ts +// +// The batch hold (lane drive-stall): memory only, edge-logged. + +beforeEach(() => resetStorageHealth()); + +const USB = { id: "usb", label: "USB drive", root: "/mnt/usb" }; + +test("the hold follows the channel's media location, and logs once per edge", () => { + registerLocationHealth([USB]); + const lines: string[] = []; + const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription"); + assert.equal(hold.check(), null); + recordLocationHealth(USB, "stalled", { now: Date.now() }); + assert.equal(hold.check()?.id, "usb"); + assert.equal(hold.check()?.id, "usb"); + recordLocationHealth(USB, "ok"); + recordLocationHealth(USB, "ok"); + assert.equal(hold.check(), null); + assert.equal(hold.check(), null); + assert.equal(lines.length, 2); + assert.match(lines[0], /^Holding: the media drive "USB drive" is not answering \(since \d\d:\d\d\) — no new transcription starts until it answers again\.$/); + assert.equal(lines[1], `The media drive "USB drive" answers again — resuming.`); +}); + +test("a channel in place, or on another location, is never held", () => { + registerLocationHealth([USB]); + recordLocationHealth(USB, "stalled"); + const lines: string[] = []; + assert.equal(mediaStallHold({}, (l) => lines.push(l), "x").check(), null); + assert.equal(mediaStallHold(null, (l) => lines.push(l), "x").check(), null); + assert.equal(mediaStallHold({ mediaDir: "/mnt/other/c/media" }, (l) => lines.push(l), "x").check(), null); + assert.deepEqual(lines, []); + // A legacy channel's retired dataDir on the location is held too. + assert.equal(mediaStallHold({ dataDir: "/mnt/usb/c/data" }, () => {}, "x").check()?.id, "usb"); +}); + +test("the refusal sentence names the drive and since when", () => { + assert.match(mediaDriveHeldText({ label: "USB drive", since: Date.now() }), /^the media drive "USB drive" is not answering \(since \d\d:\d\d\)$/); +}); + +// ── the hold heals itself (review of lane drive-stall) ────────────────────── + +const tick = () => new Promise((r) => setImmediate(r)); + +test("held past reprobeAfterMs with no pass keeping the record: one out-of-process probe answers and clears it", async () => { + const { locationHealth } = await import("./storageHealth"); + let t = 1_000_000; + registerLocationHealth([USB], t); + // Recorded once, long ago — no pass refreshes it (a CLI, an idle record). + recordLocationHealth(USB, "stalled", { now: t }); + const probed: string[] = []; + const lines: string[] = []; + const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription", { + now: () => t, + reprobeAfterMs: 60_000, + stillHoldingEveryMs: 600_000, + reprobe: async (root) => { + probed.push(root); + return "ok"; + }, + }); + assert.ok(hold.check()); + t += 30_000; + assert.ok(hold.check()); + await tick(); + assert.deepEqual(probed, [], "not before reprobeAfterMs"); + t += 31_000; + assert.ok(hold.check(), "the probe is asynchronous: this pull is still held"); + await tick(); + await tick(); + assert.deepEqual(probed, ["/mnt/usb"]); + assert.notEqual(locationHealth("usb")?.state, "stalled", "a stale record is cleared by the answer"); + assert.equal(hold.check(), null, "and the next pull resumes"); + assert.match(lines.join("\n"), /answered a stat of its root after 1 min held — no health pass was keeping its stall record/); + assert.equal(lines.at(-1), `The media drive "USB drive" answers again — resuming.`); +}); + +test("a record a pass still keeps: the probe's answer counts once, and the pass decides", async () => { + const { locationHealth } = await import("./storageHealth"); + let t = Date.now(); + registerLocationHealth([USB], t); + recordLocationHealth(USB, "stalled", { now: t }); + const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x", { + now: () => t, + reprobeAfterMs: 1_000, + reprobe: async () => "ok", + }); + hold.check(); + t += 1_500; + // A pass answered moments ago (the counters still say stalled). + recordLocationHealth(USB, "stalled", { now: t }); + hold.check(); + await tick(); + await tick(); + const h = locationHealth("usb"); + assert.equal(h?.state, "stalled", "one clean answer does not clear (two are needed)"); + assert.equal(h?.cleanStreak, 1); +}); + +test("a drive that does not answer the probe stays held, and 'still holding' is logged every interval", async () => { + let t = 5_000_000; + registerLocationHealth([USB], t); + recordLocationHealth(USB, "stalled", { now: t }); + const lines: string[] = []; + let probes = 0; + const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, (l) => lines.push(l), "x", { + now: () => t, + reprobeAfterMs: 300_000, + stillHoldingEveryMs: 600_000, + reprobe: async () => { + probes++; + return "stalled"; + }, + }); + for (let i = 0; i < 25; i++) { + hold.check(); + await tick(); + t += 60_000; + } + assert.ok(hold.check()); + const still = lines.filter((l) => l.startsWith("Still holding")); + assert.deepEqual(still, [ + `Still holding: the media drive "USB drive" has not answered after 10 min.`, + `Still holding: the media drive "USB drive" has not answered after 20 min.`, + ]); + // Once per reprobeAfterMs (5 min) after the first 5 min: at 5, 10, 15, 20, 25. + assert.equal(probes, 5); +}); + +test("the config is re-read: a channel moved off the stalled drive mid-batch resumes", async () => { + let t = 0; + registerLocationHealth([USB], t); + recordLocationHealth(USB, "stalled", { now: t }); + let config = { mediaDir: "/mnt/usb/c/media" }; + const hold = mediaStallHold(config, () => {}, "x", { + now: () => t, + reloadEveryMs: 10_000, + reloadConfig: async () => config, + }); + assert.ok(hold.check()); + config = { mediaDir: "/mnt/other/c/media" }; + t += 5_000; + hold.check(); + await tick(); + assert.ok(hold.check(), "not re-read before reloadEveryMs"); + t += 6_000; + hold.check(); + await tick(); + assert.equal(hold.check(), null); +}); + +test("pruning a location no longer configured clears its record, and a hold on it releases", async () => { + const { pruneLocationHealth, locationHealth } = await import("./storageHealth"); + registerLocationHealth([USB]); + recordLocationHealth(USB, "stalled"); + const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x"); + assert.ok(hold.check()); + pruneLocationHealth(["some-other-location"]); + assert.equal(locationHealth("usb"), undefined); + assert.equal(hold.check(), null); +}); diff --git a/common/lib/mediaStallHold.ts b/common/lib/mediaStallHold.ts @@ -0,0 +1,179 @@ +import { channelMediaStall, type ChannelMediaConfig } from "./channelMedia"; +import { + healthTimings, + locationHealth, + recordLocationHealth, + sinceText, + type LocationHealth, + type LocationHealthState, +} from "./storageHealth"; +import { probeLocationHealth } from "./storageVolumes"; + +// A BATCH THAT OPENS MEDIA HOLDS WHILE ITS CHANNEL'S MEDIA DRIVE IS NOT +// ANSWERING (lane drive-stall). +// +// The start-of-work guard (`assertChannelMediaReachable`) refuses a job whose +// channel's drive is already stalled. A batch that started while the drive +// answered, and is still pulling videos when it stops, was not asked again: +// each next unit opened its audio in-process, held one of Node's file threads +// for the ~30 s the drive takes to give up, and failed — over and over, a +// thread at a time. So a batch over a channel's media asks this before every +// pull: while the drive is stalled the pool's limit is 0 (runPool PAUSES, as +// it does with every worker disabled), and when it answers the batch resumes. +// The units already in flight finish or fail on their own; nothing cancels a +// read the kernel holds. +// +// THE CHECK IS MEMORY: `channelMediaStall` reads the process's health record +// (the health pass and the watchdog write it), never the drive. Edge-logged, +// once when the hold begins and once when it ends, and "still holding" every +// `stillHoldingEveryMs` (10 min) between. +// +// IT HEALS ITSELF (review of lane drive-stall). The record is cleared by the +// health pass; a process with no pass covering the location (a CLI, a stall +// recorded for a location the pass no longer covers) would otherwise hold for +// ever. So once the hold has lasted `reprobeAfterMs` (5 min), and at most once +// per that interval, it asks the drive itself — OUT OF PROCESS, a child `stat` +// of the root raced against the probe timeout, which holds no thread of ours. +// When the root answers: +// - a record no pass has refreshed for three pass intervals is stale: the +// answer clears it (as many clean answers as the clear rule needs), and +// the batch resumes; +// - a record a pass still keeps counts the answer once, as /storage's +// Refresh does, and the pass decides: a child `stat` can be answered from +// the kernel's cache while the device's own counters say stalled. +// +// THE CONFIG IS RE-READ (`reloadConfig`, at most every `reloadEveryMs`, 10 s, +// in the background): a channel moved to another location mid-batch is held +// by the drive its media is on now. + +export type MediaStallHold = { + // The stalled location now, or null. Logs on each edge. + check: () => LocationHealth | null; +}; + +export type MediaStallHoldOptions = { + // Re-read the channel's targets (default: never). The check uses the last + // answer; a read that fails keeps the one before. + reloadConfig?: () => Promise<ChannelMediaConfig | null | undefined>; + reloadEveryMs?: number; + // The out-of-process probe of a root (default: a child `stat`, + // `probeLocationHealth`). Test seam. + reprobe?: (root: string) => Promise<LocationHealthState>; + reprobeAfterMs?: number; + stillHoldingEveryMs?: number; + now?: () => number; +}; + +export const MEDIA_HOLD_REPROBE_AFTER_MS = 5 * 60_000; +export const MEDIA_HOLD_STILL_EVERY_MS = 10 * 60_000; +const RELOAD_EVERY_MS = 10_000; + +function minutesText(ms: number): string { + const m = Math.max(0, Math.round(ms / 60_000)); + return `${m} min`; +} + +export function mediaStallHold( + initialConfig: ChannelMediaConfig | null | undefined, + log: (line: string) => void, + what: string, + opts: MediaStallHoldOptions = {}, +): MediaStallHold { + const now = opts.now ?? Date.now; + const reprobeAfter = opts.reprobeAfterMs ?? MEDIA_HOLD_REPROBE_AFTER_MS; + const stillEvery = opts.stillHoldingEveryMs ?? MEDIA_HOLD_STILL_EVERY_MS; + const reloadEvery = opts.reloadEveryMs ?? RELOAD_EVERY_MS; + const reprobe = opts.reprobe ?? ((root: string) => probeLocationHealth({ root })); + let config = initialConfig; + let lastReload = now(); + let reloading = false; + let holding: LocationHealth | null = null; + let heldAt = 0; + let lastStill = 0; + let lastReprobe = 0; + let reprobing = false; + + const maybeReload = () => { + if (!opts.reloadConfig || reloading || now() - lastReload < reloadEvery) return; + reloading = true; + lastReload = now(); + void opts + .reloadConfig() + .then( + (next) => { + if (next !== undefined) config = next; + }, + () => {}, + ) + .finally(() => { + reloading = false; + }); + }; + + const maybeReprobe = (stall: LocationHealth) => { + const t = now(); + if (reprobing || t - heldAt < reprobeAfter || t - lastReprobe < reprobeAfter) return; + reprobing = true; + lastReprobe = t; + void reprobe(stall.root) + .then( + (answer) => { + if (answer === "stalled") return; + const current = locationHealth(stall.id); + if (!current || current.root !== stall.root || current.state !== "stalled") return; + const loc = { id: stall.id, label: stall.label, root: stall.root }; + const stale = now() - current.checkedAt >= healthTimings().passIntervalMs * 3; + // Stale: no pass is keeping it, and the drive answered — enough + // clean answers to clear it. Kept by a pass: one answer. + const answers = stale ? healthTimings().clearAfterCleanPasses : 1; + for (let i = 0; i < answers; i++) { + recordLocationHealth(loc, answer, { detector: "stat", device: null }); + } + log( + `The media drive "${stall.label}" answered a stat of its root after ` + + `${minutesText(t - heldAt)} held` + + (stale + ? " — no health pass was keeping its stall record, so the stall is cleared." + : "; its health pass decides when the stall ends."), + ); + }, + () => {}, + ) + .finally(() => { + reprobing = false; + }); + }; + + return { + check: () => { + maybeReload(); + const stall = channelMediaStall(config); + const t = now(); + if (stall && !holding) { + heldAt = t; + lastStill = t; + log( + `Holding: the media drive "${stall.label}" is not answering (${sinceText(stall.since)}) — ` + + `no new ${what} starts until it answers again.`, + ); + } else if (stall && holding) { + if (t - lastStill >= stillEvery) { + lastStill = t; + log( + `Still holding: the media drive "${stall.label}" has not answered after ${minutesText(t - heldAt)}.`, + ); + } + } else if (!stall && holding) { + log(`The media drive "${holding.label}" answers again — resuming.`); + } + holding = stall; + if (stall) maybeReprobe(stall); + return stall; + }, + }; +} + +// The sentence a unit refuses with when its channel's drive is not answering. +export function mediaDriveHeldText(stall: Pick<LocationHealth, "label" | "since">): string { + return `the media drive "${stall.label}" is not answering (${sinceText(stall.since)})`; +} diff --git a/common/lib/savedVideoStore.test.ts b/common/lib/savedVideoStore.test.ts @@ -166,3 +166,53 @@ async function exists(p: string): Promise<boolean> { return (err as NodeJS.ErrnoException).code === "EISDIR"; } } + +// A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall): +// the corpus store through its link, a channel's own store as given; the +// container stays in the video dir, and nothing touches the stalled drive. +test("a store whose drive is not answering refuses the write, and the container stays put", async () => { + const { symlink } = await import("node:fs/promises"); + const { recordLocationHealth, resetStorageHealth } = await import("./storageHealth"); + const { SavedVideosStoreNotAnsweringError } = await import("./savedVideoStore"); + await withTmp(async (paths, videoDir) => { + const platter = path.join(path.dirname(paths.transcriptsDir), "platter"); + const target = path.join(platter, "saved-videos"); + await mkdir(target, { recursive: true }); + await rm(paths.savedVideosDir, { recursive: true, force: true }); + await symlink(target, paths.savedVideosDir); + const loc = { id: "platter", label: "Platter", root: platter }; + try { + // Answering: the guard passes. + recordLocationHealth(loc, "ok"); + await assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan")); + // Not answering: refused, for the corpus store and for a channel store on it. + recordLocationHealth(loc, "stalled", { cause: "test" }); + await assert.rejects( + assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan")), + (err: unknown) => + err instanceof SavedVideosStoreNotAnsweringError && + /^The saved-video store's drive "Platter" is not answering \(since \d\d:\d\d\)/.test(err.message), + ); + await assert.rejects( + assertSavedVideosStoreWritable(paths, path.join(platter, "own-store")), + SavedVideosStoreNotAnsweringError, + ); + // A store elsewhere is not held by this drive. + await assertSavedVideosStoreWritable(paths, path.join(paths.transcriptsDir, "elsewhere")); + await writeFile(path.join(videoDir, "source-media.mp4"), "container"); + await assert.rejects( + persistSourceVideo({ + videoDir, + sourceFilename: "source-media.mp4", + storeDir: path.join(paths.savedVideosDir, "chan"), + keepReason: "pin", + paths, + }), + SavedVideosStoreNotAnsweringError, + ); + assert.equal(await readFile(path.join(videoDir, "source-media.mp4"), "utf8"), "container"); + } finally { + resetStorageHealth(); + } + }); +}); diff --git a/common/lib/savedVideoStore.ts b/common/lib/savedVideoStore.ts @@ -1,7 +1,8 @@ import path from "node:path"; -import { readFile } from "node:fs/promises"; +import { readFile, readlink } from "node:fs/promises"; import type { Paths } from "./paths"; import type { RelocationMarker } from "./channelMedia"; +import { sinceText, stalledLocationForPath, type LocationHealth } from "./storageHealth"; // IS THE SAVED-VIDEO STORE SAFE TO WRITE INTO RIGHT NOW? // @@ -109,7 +110,58 @@ export async function assertSavedVideosStoreWritable( paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">, storeDir: string, ): Promise<void> { - if (!isInCorpusSavedVideoStore(paths, storeDir)) return; + const corpus = isInCorpusSavedVideoStore(paths, storeDir); + // A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall). + // The move into it is in-process (`moveFileCrossDevice`), and on a stalled + // drive every call of it holds one of Node's file threads until the kernel + // gives up. Memory only: the health record, matched against the store's + // path — a channel's own store as given, the corpus store through its link + // (`readlink` reads the corpus disk, never the target). + const where = corpus + ? await readlink(paths.savedVideosDir).catch(() => paths.savedVideosDir) + : storeDir; + const stall = stalledLocationForPath(where); + if (stall) throw new SavedVideosStoreNotAnsweringError(stall); + if (!corpus) return; const marker = await readSavedVideosMarker(paths); if (marker) throw new SavedVideosStoreInTransitionError(marker); } + +// Thrown by assertSavedVideosStoreWritable when the store's drive is not +// answering. Every persist caller already catches a refusal here and leaves +// the container where it is, to be persisted on a later pass. +export class SavedVideosStoreNotAnsweringError extends Error { + readonly health: LocationHealth; + constructor(health: LocationHealth) { + super( + `The saved-video store's drive "${health.label}" is not answering ` + + `(${sinceText(health.since)}) — nothing is written into it until it answers.`, + ); + this.name = "SavedVideosStoreNotAnsweringError"; + this.health = health; + } +} + +// THE STORE'S REFUSAL, AS A VALUE (review of lane drive-stall): the error the +// guard above would throw for a write into `storeDir` — the store's drive not +// answering, or the store mid-move — or null. A batch that FETCHES before it +// persists (persist-videos, persist-kept: a whole source container per video) +// asks this before each download, so a store that cannot take the container +// stops the run instead of downloading one only to leave it in the data dir. +export async function savedVideosStoreRefusal( + paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">, + storeDir: string, +): Promise<SavedVideosStoreNotAnsweringError | SavedVideosStoreInTransitionError | null> { + try { + await assertSavedVideosStoreWritable(paths, storeDir); + return null; + } catch (err) { + if ( + err instanceof SavedVideosStoreNotAnsweringError || + err instanceof SavedVideosStoreInTransitionError + ) { + return err; + } + throw err; + } +} diff --git a/common/lib/storageHealth.test.ts b/common/lib/storageHealth.test.ts @@ -3,6 +3,10 @@ import assert from "node:assert/strict"; import { DriveNotAnsweringError, allLocationHealth, + driveHealthView, + noteDriveAnswer, + slowThresholdMs, + slowWindowMs, applyHealthTimings, driveCallsInFlight, healthTimings, @@ -689,3 +693,108 @@ test("rootOfUnknownPath strips <root>/<slug>/media (release 17) and the retired assert.equal(rootOfUnknownPath("/mnt/p/chan/data"), "/mnt/p"); assert.equal(rootOfUnknownPath("/mnt/p/chan/other"), "/mnt/p/chan/other"); }); + +// ── answering, slow, not answering, not mounted (lane drive-stall) ────────── + +test("the drive's four words: ok → slow → stalled → ok, from what the watchdog measured", async () => { + registerLocationHealth([USB], 1_000); + const fresh = driveHealthView(USB, locationHealth("usb")); + assert.equal(fresh.state, "ok"); + assert.equal(fresh.lastOkAt, undefined, "a registration is not an answer"); + assert.equal(fresh.text, "answering (not asked yet)"); + + // A quick unit: answered, measured, ok. + setDriveCallBudget(200); + assert.equal(slowThresholdMs(), 100); + await onDrive(USB, async () => "quick"); + const ok = driveHealthView(USB, locationHealth("usb")); + assert.equal(ok.state, "ok"); + assert.equal(typeof ok.lastOkAt, "number"); + assert.equal(ok.latencyFrom, "call"); + assert.match(ok.text, /^answering — \d+ ms \(a read in the editor\), last at \d\d:\d\d$/); + + // A unit past half the budget: answered. One is not slow (a big unit, a + // spin-up); two in a row are. Nothing refuses either. + const lateUnit = () => onDrive(USB, () => new Promise((r) => setTimeout(() => r("late"), 130))); + assert.equal(await lateUnit(), "late"); + assert.equal(driveHealthView(USB, locationHealth("usb")).state, "ok", "one slow reading is not slow"); + assert.equal(await lateUnit(), "late"); + const slow = driveHealthView(USB, locationHealth("usb")); + assert.equal(slow.state, "slow"); + assert.match(String(slow.cause), /^a read in the editor took \d+ ms$/); + assert.match(slow.text, /^slow at \d\d:\d\d — a read in the editor took/); + assert.equal(stalledLocation(USB), null, "slow is shown, never acted on"); + + // A unit that never answers: stalled, and the stall supersedes slow. + await assert.rejects(onDrive(USB, () => new Promise(() => {})), DriveNotAnsweringError); + const stalled = driveHealthView(USB, locationHealth("usb")); + assert.equal(stalled.state, "stalled"); + assert.match(stalled.text, /^not answering since \d\d:\d\d — a read in the editor did not answer/); + + // Two clean answers clear it — and it is ok, not slow, after. + recordLocationHealth(USB, "ok"); + recordLocationHealth(USB, "ok"); + const back = driveHealthView(USB, locationHealth("usb")); + assert.equal(back.state, "ok"); + assert.equal(locationHealth("usb")?.slowAt, undefined); +}); + +test("slow lasts two passes from its last sighting, then reads ok again", () => { + registerLocationHealth([USB], 0); + noteDriveAnswer("usb", 2_000, "stat", 9_000); + assert.equal(locationHealth("usb")?.slowAt, undefined, "one reading is not slow"); + noteDriveAnswer("usb", 2_000, "stat", 10_000); + const h = locationHealth("usb"); + assert.equal(h?.slowAt, 10_000); + assert.equal(h?.lastOkAt, 10_000); + assert.equal(slowWindowMs(), 30_000); + assert.equal(driveHealthView(USB, h, { now: 10_000 + 29_999 }).state, "slow"); + assert.equal(driveHealthView(USB, h, { now: 10_000 + 30_000 }).state, "ok"); + // The counters' average is the disk's own figure: it sets the latency and + // can be slow, but it is not an answer to us. + noteDriveAnswer("usb", 5, "counters", 50_000); + const after = locationHealth("usb"); + assert.equal(after?.latencyMs, 5); + assert.equal(after?.latencyFrom, "counters"); + assert.equal(after?.lastOkAt, 10_000); + // A location with no entry records nothing. + noteDriveAnswer("nowhere", 9_000, "call"); + assert.equal(locationHealth("nowhere"), undefined); +}); + +test("not mounted: the health record's `absent`, or the mount probe's word; a stall wins over both", () => { + recordLocationHealth(USB, "absent", { now: 7 }); + const gone = driveHealthView(USB, locationHealth("usb")); + assert.equal(gone.state, "unmounted"); + assert.equal(gone.since, 7); + assert.equal(gone.text, "not mounted"); + resetStorageHealth(); + registerLocationHealth([USB]); + assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "unmounted"); + assert.equal(driveHealthView(USB, undefined, { mounted: false }).state, "unmounted"); + recordLocationHealth(USB, "stalled", { cause: "no answer" }); + assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "stalled"); +}); + +test("the watchdog's slow refusal is a sighting of slow, and marks nothing", async () => { + registerLocationHealth([USB]); + setDriveCallBudget(60); + let completed = 0; + setCounterReader(() => ({ completed: (completed += 5), inFlight: 1 })); + recordLocationHealth(USB, "ok", { detector: "counters", device: "sdz" }); + await assert.rejects(onDrive(USB, () => new Promise(() => {})), /drive slow/); + const h = locationHealth("usb"); + assert.equal(h?.state, "ok"); + assert.match(String(h?.slowCause), /did not answer within .*still completing others/); + assert.equal(driveHealthView(USB, h).state, "slow"); +}); + +test("a fast reading between two slow ones starts the count again", () => { + registerLocationHealth([USB], 0); + noteDriveAnswer("usb", 2_000, "call", 1); + noteDriveAnswer("usb", 3, "call", 2); + noteDriveAnswer("usb", 2_000, "call", 3); + assert.equal(locationHealth("usb")?.slowAt, undefined); + noteDriveAnswer("usb", 2_000, "call", 4); + assert.equal(locationHealth("usb")?.slowAt, 4); +}); diff --git a/common/lib/storageHealth.ts b/common/lib/storageHealth.ts @@ -102,6 +102,28 @@ export type LocationHealth = { // The block device the counters detector reads for this location, when it // could name one. The watchdog reads its counters too (see `onDrive`). device?: string; + // WHEN THE DRIVE LAST ANSWERED, ms since epoch (lane drive-stall): a pass's + // clean verdict that found the root (`ok`), or a call through `onDrive` that + // answered within its budget. Absent: not yet, in this process. + lastOkAt?: number; + // HOW LONG IT TOOK, the latest measurement, in ms, and what measured it: + // `call`, a whole unit through `onDrive`; `stat`, the health pass's child + // `stat` of the root (its round trip, process start included); `counters`, + // the block device's own average per completed request over the pass's + // sample interval (`/sys/class/block/<dev>/stat` fields 4 and 8, the time + // its reads and writes took, over the requests that completed). + latencyMs?: number; + latencyFrom?: "call" | "stat" | "counters"; + // WHEN IT WAS LAST SEEN SLOW, and why: answering, but two measurements in a row reached + // `slowThresholdMs()` (half the budget), or the watchdog refused a call as + // slow (its disk still completing others). Slow is shown, never acted on: + // nothing refuses a slow drive that the budget does not. + slowAt?: number; + slowCause?: string; + // Consecutive measurements at or past `slowThresholdMs()`. Slow is sighted + // at SLOW_READINGS_IN_A_ROW (2): one long unit (a big walk, a cold spin-up) + // is not a slow drive. + slowStreak?: number; }; // THE DEFAULTS, and why they are what they are (lib/storageHealthTimings.ts @@ -259,7 +281,9 @@ export function recordLocationHealth( device?: string | null; } = {}, ): HealthTransition | null { - const t = recordAnswer(loc, answer, opts); + // Every answer recorded here is a detector's (a pass, a Refresh, the + // watchdog); `registerLocationHealth` creates entries without one. + const t = recordAnswer(loc, answer, { ...opts, answered: true }); // EVERY TRANSITION TO STALLED refuses the calls waiting for a slot on the // location, whoever decided it (the pass, the watchdog, a Refresh): they // would otherwise wait for a slot held by a call the drive is not answering. @@ -277,6 +301,8 @@ function recordAnswer( cause?: string; detector?: HealthDetector; device?: string | null; + // A detector's answer, not a registration: an `ok` then sets `lastOkAt`. + answered?: boolean; }, ): HealthTransition | null { const now = opts.now ?? Date.now(); @@ -296,11 +322,14 @@ function recordAnswer( checkedAt: now, cleanStreak: 0, ...(answer === "stalled" && opts.cause ? { cause: opts.cause } : {}), + ...(answer === "ok" && opts.answered ? { lastOkAt: now } : {}), }); return { id: loc.id, from: null, to: answer }; } prev.label = label; prev.checkedAt = now; + // An `ok` from a detector is the drive answering (a registration is not). + if (answer === "ok" && opts.answered) prev.lastOkAt = now; if (opts.detector) prev.detector = opts.detector; if (opts.device === null) delete prev.device; else if (opts.device) prev.device = opts.device; @@ -311,6 +340,11 @@ function recordAnswer( prev.state = "stalled"; prev.since = now; if (opts.cause) prev.cause = opts.cause; + // A stall supersedes slow: once it clears, the drive starts answering + // afresh, and an old slow sighting is not what it is doing now. + delete prev.slowAt; + delete prev.slowCause; + delete prev.slowStreak; return { id: loc.id, from, to: "stalled" }; } if (prev.state === "stalled") { @@ -344,7 +378,8 @@ export function registerLocationHealth( prev.label = loc.label || loc.id; continue; } - recordLocationHealth(loc, "ok", { now }); + // Not an answer: an entry with no `lastOkAt` (nothing has asked yet). + recordAnswer(loc, "ok", { now }); } } @@ -408,10 +443,10 @@ export function stalledLocation( return h && h.state === "stalled" && h.root === loc.root ? { ...h } : null; } -// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the -// stall began on another day than `now`. -export function sinceText(since: number, now: number = Date.now()): string { - const d = new Date(since); +// "11:35" in the server's clock, or "2026-09-28 11:35" when `at` is on another +// day than `now`. +export function clockText(at: number, now: number = Date.now()): string { + const d = new Date(at); const n = new Date(now); const pad = (x: number) => String(x).padStart(2, "0"); const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`; @@ -419,9 +454,13 @@ export function sinceText(since: number, now: number = Date.now()): string { d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate(); - return sameDay - ? `since ${hm}` - : `since ${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`; + return sameDay ? hm : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`; +} + +// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the +// stall began on another day than `now`. +export function sinceText(since: number, now: number = Date.now()): string { + return `since ${clockText(since, now)}`; } // "not answering since 11:35" — the one line /storage, the /channels volume bar @@ -431,6 +470,162 @@ export function notAnsweringText(h: Pick<LocationHealth, "since">, now?: number) } // --------------------------------------------------------------------------- +// Answering, slow, not answering, not mounted: the four words a surface shows +// --------------------------------------------------------------------------- +// +// THE STATE ABOVE IS WHAT THE GATE ACTS ON (`stalled` or not). A person asking +// "is the drive all right" wants two more facts: whether it is there at all +// (an unmounted drive answers at once, with ENOENT — not a stall, and not +// health), and whether it is answering SLOWLY — a disk grinding through a long +// write answers every read, a second late. Slow is shown and never acted on: +// the budget is what refuses, and a slow drive under it is still working. + +// A measurement at or past this is slow: half the watchdog's budget (1.5 s by +// default). A unit at half its budget is half way to being refused. +export function slowThresholdMs(): number { + return Math.round(driveCallBudget() / 2); +} + +// How long one slow measurement keeps a drive "slow": two passes (30 s by +// default), so a single slow read is visible for a pass or two and a drive +// slow on every read stays slow. +export function slowWindowMs(): number { + return healthTimings().passIntervalMs * 2; +} + +// "12 ms", "1.4 s". +export function latencyText(ms: number): string { + return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`; +} + +const LATENCY_WORDS: Record<NonNullable<LocationHealth["latencyFrom"]>, string> = { + call: "a read in the editor", + stat: "a stat of its root", + counters: "its disk's average request", +}; + +// THE DRIVE ANSWERED: a measurement of how long it took. Recorded for a +// location that has an entry (registered or answered); a path on no +// configured location has none, and this does nothing for it. The second +// measurement in a row at or past `slowThresholdMs()` is a sighting of slow. +export function noteDriveAnswer( + id: string, + latencyMs: number, + from: NonNullable<LocationHealth["latencyFrom"]>, + now: number = Date.now(), +): void { + const h = healthState().byId.get(id); + if (!h || !Number.isFinite(latencyMs) || latencyMs < 0) return; + h.latencyMs = Math.round(latencyMs); + h.latencyFrom = from; + // An average per request is the disk's own figure, not an answer to us; the + // other two are the drive answering. + if (from !== "counters") h.lastOkAt = now; + if (latencyMs >= slowThresholdMs()) { + h.slowStreak = (h.slowStreak ?? 0) + 1; + if (h.slowStreak >= SLOW_READINGS_IN_A_ROW) { + h.slowAt = now; + h.slowCause = `${LATENCY_WORDS[from]} took ${latencyText(latencyMs)}`; + } + } else { + h.slowStreak = 0; + } +} + +// Two slow measurements in a row before a drive reads slow (review of lane +// drive-stall): one long unit must not flash the banner. +export const SLOW_READINGS_IN_A_ROW = 2; + +// THE DRIVE IS SLOW, NOT STALLED: the watchdog refused a call past its budget +// while the disk was still completing others (`onDrive`, `acquireSlot`). +export function noteDriveSlow(id: string, cause: string, now: number = Date.now()): void { + const h = healthState().byId.get(id); + if (!h) return; + h.slowAt = now; + h.slowCause = cause; +} + +export type DriveHealthState = "ok" | "slow" | "stalled" | "unmounted"; + +// ONE LOCATION'S DRIVE, as every surface and `pnpm ops get storage` reports it. +export type DriveHealthView = { + id: string; + label: string; + state: DriveHealthState; + // stalled: when it stopped answering; slow: when it was last seen slow; + // unmounted: when the health record last found the root missing (absent + // when only the mount probe says so). + since?: number; + // When the drive last answered (see `LocationHealth.lastOkAt`). + lastOkAt?: number; + latencyMs?: number; + latencyFrom?: LocationHealth["latencyFrom"]; + detector?: HealthDetector; + // stalled: what did not answer; slow: what was slow. + cause?: string; + // The one line: "answering — 12 ms (a read in the editor) at 11:42", + // "slow at 11:42 — a read in the editor took 2.1 s", "not answering since + // 11:35 — …", "not mounted". + text: string; +}; + +// The view of one location's drive. `mounted: false` is the mount probe's +// answer (`StorageLocationStatus` other than available or stalled), which +// the health record does not carry when the counters detector watches it; +// omitted, only the record decides. +export function driveHealthView( + loc: Pick<StorageLocation, "id" | "label">, + h: LocationHealth | undefined, + opts: { now?: number; mounted?: boolean } = {}, +): DriveHealthView { + const now = opts.now ?? Date.now(); + const base = { + id: loc.id, + label: loc.label || loc.id, + ...(h?.lastOkAt !== undefined ? { lastOkAt: h.lastOkAt } : {}), + ...(h?.latencyMs !== undefined ? { latencyMs: h.latencyMs } : {}), + ...(h?.latencyFrom ? { latencyFrom: h.latencyFrom } : {}), + ...(h?.detector ? { detector: h.detector } : {}), + }; + if (h?.state === "stalled") { + return { + ...base, + state: "stalled", + since: h.since, + ...(h.cause ? { cause: h.cause } : {}), + text: `${notAnsweringText(h, now)}${h.cause ? ` — ${h.cause}` : ""}`, + }; + } + if (h?.state === "absent" || opts.mounted === false) { + return { + ...base, + state: "unmounted", + ...(h?.state === "absent" ? { since: h.since } : {}), + text: "not mounted", + }; + } + if (h?.slowAt !== undefined && now - h.slowAt < slowWindowMs()) { + return { + ...base, + state: "slow", + since: h.slowAt, + ...(h.slowCause ? { cause: h.slowCause } : {}), + text: `slow at ${clockText(h.slowAt, now)}${h.slowCause ? ` — ${h.slowCause}` : ""}`, + }; + } + const measured = + h?.latencyMs !== undefined && h.latencyFrom + ? ` — ${latencyText(h.latencyMs)} (${LATENCY_WORDS[h.latencyFrom]})` + : ""; + const last = h?.lastOkAt !== undefined ? `, last at ${clockText(h.lastOkAt, now)}` : ""; + return { + ...base, + state: "ok", + text: h?.lastOkAt === undefined && !measured ? "answering (not asked yet)" : `answering${measured}${last}`, + }; +} + +// --------------------------------------------------------------------------- // The watchdog: every call the gate covers, raced against the budget // --------------------------------------------------------------------------- // @@ -589,11 +784,11 @@ async function acquireSlot(r: Resolved): Promise<void> { const oldest = overdue.reduce((a, b) => (b.startedAt < a.startedAt ? b : a)); const now = readDeviceCounters(r.loc); if (oldest.before && now && now.completed > oldest.before.completed) { - throw new DriveNotAnsweringError( - null, - `drive slow (${overdue.length} reads on it are past ` + - `${secondsText(driveCallBudget())}, while its disk is still completing others)`, - ); + const detail = + `${overdue.length} reads on it are past ` + + `${secondsText(driveCallBudget())}, while its disk is still completing others`; + if (r.loc) noteDriveSlow(r.loc.id, detail); + throw new DriveNotAnsweringError(null, `drive slow (${detail})`); } let health: LocationHealth | null = null; if (r.loc) { @@ -768,6 +963,9 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise< } if (answer !== TIMED_OUT) { release(); + // THE DRIVE ANSWERED, and how long the unit took. A call that threw + // answered too, but its time says nothing (ENOENT is instant). + if (r.loc) noteDriveAnswer(r.loc.id, Date.now() - startedAt, "call"); return answer; } // The call is still waiting on the drive. Its slot stays held, and counted @@ -784,11 +982,11 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise< const after = readDeviceCounters(r.loc); if (before && after && after.completed > before.completed) { // SLOW, NOT STALLED: the disk completed requests while this call waited. - throw new DriveNotAnsweringError( - null, - `drive slow (a read did not answer within ${secondsText(budget)}, ` + - `while its disk was still completing others)`, - ); + const detail = + `a read did not answer within ${secondsText(budget)}, ` + + `while its disk was still completing others`; + if (r.loc) noteDriveSlow(r.loc.id, detail); + throw new DriveNotAnsweringError(null, `drive slow (${detail})`); } if (r.loc) { recordLocationHealth(r.loc, "stalled", { diff --git a/common/lib/storageHealthCounters.test.ts b/common/lib/storageHealthCounters.test.ts @@ -5,6 +5,8 @@ import { tmpdir } from "node:os"; import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { blockDeviceName, + blockStatTicksMs, + countersLatencyMs, detectLocationHealth, minCounterIntervalMs, resetHealthDetector, @@ -193,9 +195,13 @@ test("no device → the child stat, and the verdict says so", async () => { const opts = { sysBlockDir: h.sys, now: 0 }; // A tmpfs or network source names no block device. await h.control({ source: "tmpfs" }); - assert.deepEqual(await detectLocationHealth(loc(h.root), h.bins, opts), { + // The verdict carries the child's round trip (lane drive-stall). + const viaStat = await detectLocationHealth(loc(h.root), h.bins, opts); + assert.equal(typeof viaStat.latencyMs, "number"); + assert.deepEqual({ ...viaStat, latencyMs: 0 }, { answer: "ok", detector: "stat", + latencyMs: 0, }); // findmnt cannot say (no such path, a container without it). await h.control({ exit: 1 }); @@ -258,3 +264,45 @@ test("a device already named is read without findmnt; findmnt again only when it assert.ok(globalThis.__yttHealthDetector__); }); }); + +// ── the disk's own latency (lane drive-stall) ─────────────────────────────── + +test("the stat line's request time: fields 4 + 8 (+ 15 + 17), and the average per completed request", () => { + // The real line above: 80435430 ms reading, 167469727 writing, 4100450 + // discarding, 1212688 flushing. + assert.equal(blockStatTicksMs(LINE), 80435430 + 167469727 + 4100450 + 1212688); + // An 11-field line has no discard or flush time. + assert.equal(blockStatTicksMs("10 0 0 40 5 0 0 20 3 0 0"), 60); + assert.equal(blockStatTicksMs("1 2 3"), null); + // 30 requests completed in 900 ms of request time: 30 ms each. + assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 130, ticksMs: 1900 }), 30); + // Nothing completed: no latency to report (an idle disk, or a stalled one). + assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 100, ticksMs: 1000 }), undefined); + // No time fields on one side: nothing. + assert.equal(countersLatencyMs({ completed: 100 }, { completed: 130, ticksMs: 5 }), undefined); +}); + +test("counters: an ok verdict carries the disk's average request time; a stalled one none", async () => { + await withHarness(async (h) => { + await h.control({ source: "/dev/fakedisk2", uuid: "u-2" }); + const at = (i: number) => ({ sysBlockDir: h.sys, now: i * 15_000 }); + const line = async (completed: number, readMs: number, inFlight: number) => { + await mkdir(path.join(h.sys, "fakedisk2"), { recursive: true }); + await writeFile( + path.join(h.sys, "fakedisk2", "stat"), + `${completed} 0 0 ${readMs} 0 0 0 0 ${inFlight} 0 0 0 0 0 0 0 0\n`, + ); + }; + await line(100, 1_000, 1); + assert.equal((await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(1))).answer, null); + // 10 completed in 20 s of request time: 2 s each — a slow disk, answering. + await line(110, 21_000, 1); + const slow = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(2)); + assert.equal(slow.answer, "ok"); + assert.equal(slow.latencyMs, 2_000); + await line(110, 21_000, 1); + const stuck = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(3)); + assert.equal(stuck.answer, "stalled"); + assert.equal(stuck.latencyMs, undefined); + }); +}); diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts @@ -377,6 +377,10 @@ export type HealthVerdict = { cause?: string; // The block device the counters were read from. device?: string; + // How long the drive took (lib/storageHealth.ts `noteDriveAnswer`): the + // counters' average per completed request between the two samples, or the + // child `stat`'s round trip. Absent when nothing was measured. + latencyMs?: number; }; // What the health pass asks about a location. A bare state is a verdict with @@ -473,7 +477,31 @@ export function minCounterIntervalMs(): number { return counterSampleMinimumMs(healthTimings().passIntervalMs); } -type CounterSample = BlockStatSample & { device: string; at: number }; +// `ticksMs`: fields 4 + 8 (+ 15 + 17 on kernels that count discards and +// flushes) — the milliseconds the device's completed requests took, summed. +type CounterSample = BlockStatSample & { device: string; at: number; ticksMs?: number }; + +// The time the device's completed requests took, summed, from a stat line: +// fields 4 (reads), 8 (writes) and, where counted, 15 (discards) and 17 +// (flushes). Null on a line too short to carry them. +export function blockStatTicksMs(line: string): number | null { + const f = line.trim().split(/\s+/).map(Number); + if (f.length < 9 || !Number.isFinite(f[3]) || !Number.isFinite(f[7])) return null; + const opt = (i: number) => (Number.isFinite(f[i]) ? f[i] : 0); + return f[3] + f[7] + opt(14) + opt(16); +} + +// THE DISK'S OWN AVERAGE per completed request between two samples, or +// undefined when none completed (an idle disk has no latency to report). +export function countersLatencyMs( + prev: Pick<CounterSample, "completed" | "ticksMs">, + cur: Pick<CounterSample, "completed" | "ticksMs">, +): number | undefined { + const done = cur.completed - prev.completed; + if (done <= 0 || prev.ticksMs === undefined || cur.ticksMs === undefined) return undefined; + const ticks = cur.ticksMs - prev.ticksMs; + return ticks >= 0 ? ticks / done : undefined; +} type DetectorState = { samples: Map<string, CounterSample>; @@ -594,9 +622,13 @@ async function blockDeviceOfRoot( async function readBlockStat( device: string, sysBlockDir: string, -): Promise<BlockStatSample | null> { +): Promise<(BlockStatSample & { ticksMs?: number }) | null> { try { - return parseBlockStat(await readFile(path.join(sysBlockDir, device, "stat"), "utf8")); + const line = await readFile(path.join(sysBlockDir, device, "stat"), "utf8"); + const sample = parseBlockStat(line); + if (!sample) return null; + const ticksMs = blockStatTicksMs(line); + return ticksMs === null ? sample : { ...sample, ticksMs }; } catch { return null; } @@ -637,10 +669,12 @@ export async function detectLocationHealth( return { answer: null, detector: "counters", device }; } const answer = countersVerdict(prev, sample); + const latencyMs = answer === "ok" ? countersLatencyMs(prev, sample) : undefined; return { answer, detector: "counters", device, + ...(latencyMs !== undefined ? { latencyMs } : {}), ...(answer === "stalled" ? { cause: @@ -652,10 +686,12 @@ export async function detectLocationHealth( } } detector.samples.delete(loc.id); + const asked = Date.now(); const answer = await probeLocationHealth(loc, opts); return { answer, detector: "stat", + ...(answer === "ok" ? { latencyMs: Date.now() - asked } : {}), ...(answer === "stalled" ? { cause: `a stat of its root did not answer within ${secondsText(timeoutMs)}` } : {}), @@ -732,11 +768,24 @@ export type MemoizedProbe = StorageLocationProbe & { export const PROBE_MEMO_MS = 10_000; type MemoEntry = { root: string; probedAt: number; probe: StorageLocationProbe }; -const probeMemo = new Map<string, MemoEntry>(); + +declare global { + // eslint-disable-next-line no-var + var __yttStorageProbeMemo__: Map<string, MemoEntry> | undefined; +} + +// ON globalThis, the house pattern (lane drive-stall): a page, a poll and the +// e2e `invalidate-cache` route can each be a different copy of this module, +// and a reset in one copy that leaves another's map standing answers the next +// page with a root that is no longer there — for up to ten seconds. +function probeMemo(): Map<string, MemoEntry> { + globalThis.__yttStorageProbeMemo__ ??= new Map(); + return globalThis.__yttStorageProbeMemo__; +} // Test seam, and the escape hatch for a process that has just written a root. export function resetStorageProbeMemo(): void { - probeMemo.clear(); + probeMemo().clear(); } // Probe a location, at most once per PROBE_MEMO_MS. @@ -765,7 +814,7 @@ export async function probeLocationMemo( if (stalledLocation(loc)) { return { status: "stalled", identity: { known: false }, probedAt: now }; } - const hit = probeMemo.get(loc.id); + const hit = probeMemo().get(loc.id); if ( !opts.refresh && hit && @@ -775,6 +824,6 @@ export async function probeLocationMemo( return { ...hit.probe, probedAt: hit.probedAt }; } const probe = await probeLocation(loc, bins, opts); - probeMemo.set(loc.id, { root: loc.root, probedAt: now, probe }); + probeMemo().set(loc.id, { root: loc.root, probedAt: now, probe }); return { ...probe, probedAt: now }; } diff --git a/common/views/names.ts b/common/views/names.ts @@ -30,6 +30,10 @@ export const VIEW_NAMES = [ // /review's X run console (common/controller/xRun.ts xRunConsole): the // latest run, the X posts channels, the jar's age. Reads disk only. "xRun", + // The dashboard's drive banner (editor/app/storage/lib/driveHealth.ts): + // every storage location whose drive is slow, not answering or not mounted. + // The health record is memory; the mount half is /storage's 10 s probe memo. + "driveHealth", ] as const; export type ViewName = (typeof VIEW_NAMES)[number]; @@ -58,4 +62,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = { cleanable: "construct", cookieAlerts: "construct", xRun: "construct", + driveHealth: "construct", }; diff --git a/common/views/storage.test.ts b/common/views/storage.test.ts @@ -507,3 +507,60 @@ test("a location whose drive is not answering reads so, and says since when", () }).rows[0]; assert.equal(quiet.notAnswering, undefined); }); + +// THE DRIVE'S HEALTH ON EACH ROW (lane drive-stall) — what `pnpm ops get +// storage` reports: the shell's view, carried as it is; the internal row has +// none. `probeMounted` is the mount half of it. +test("each location row carries its drive's health view; the internal row none", async () => { + const { driveHealthView, recordLocationHealth, registerLocationHealth, noteDriveAnswer, locationHealth, resetStorageHealth } = + await import("../lib/storageHealth"); + const { probeMounted } = await import("./storage"); + resetStorageHealth(); + const cold = loc("cold", "/mnt/cold"); + const warm = loc("warm", "/mnt/warm"); + const gone = loc("gone", "/mnt/gone"); + registerLocationHealth([cold, warm, gone], NOW); + recordLocationHealth(cold, "stalled", { now: NOW, cause: "its disk (sdz) had 1 request(s) in flight and completed none in 15 s" }); + noteDriveAnswer("warm", 2_400, "call", NOW - 1); + noteDriveAnswer("warm", 2_400, "call", NOW); + const probes = { + cold: { status: "stalled" as const, identity: { known: false as const }, probedAt: NOW }, + warm: { status: "available" as const, identity: { known: false as const }, probedAt: NOW }, + gone: { status: "unmounted" as const, identity: { known: false as const }, probedAt: NOW }, + }; + const drives = Object.fromEntries( + [cold, warm, gone].map((l) => [ + l.id, + driveHealthView(l, locationHealth(l.id), { now: NOW, mounted: probeMounted(probes[l.id as keyof typeof probes].status) }), + ]), + ); + const { rows } = buildStorageRows({ + locations: [cold, warm, gone], + defaultLocationId: "", + probes, + drives, + rollups: {}, + internal: { root: "/corpus/channels" }, + registry: NO_JOBS, + now: NOW, + }); + const by = Object.fromEntries(rows.map((r) => [r.id, r])); + assert.equal(by.internal.drive, undefined); + assert.equal(by.cold.drive?.state, "stalled"); + assert.equal(by.cold.drive?.since, NOW); + assert.match(String(by.cold.drive?.text), /^not answering since \d\d:\d\d — its disk \(sdz\)/); + assert.equal(by.warm.drive?.state, "slow"); + assert.equal(by.warm.drive?.latencyMs, 2_400); + assert.equal(by.warm.drive?.lastOkAt, NOW); + assert.match(String(by.warm.drive?.text), /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/); + assert.equal(by.gone.drive?.state, "unmounted"); + assert.equal(by.gone.drive?.text, "not mounted"); + // The mount half: available is mounted, stalled did not ask, the rest are not. + assert.equal(probeMounted("available"), true); + assert.equal(probeMounted("stalled"), undefined); + assert.equal(probeMounted(undefined), undefined); + for (const st of ["unmounted", "absent", "missing", "mounted-elsewhere"] as const) { + assert.equal(probeMounted(st), false); + } + resetStorageHealth(); +}); diff --git a/common/views/storage.ts b/common/views/storage.ts @@ -9,6 +9,7 @@ import type { } from "../controller/storageLocations"; import type { SavedVideosStoreStatus } from "../controller/relocateSavedVideos"; import type { RegistryReader } from "./inputs"; +import type { DriveHealthView } from "../lib/storageHealth"; // THE /storage PAYLOAD — one row per storage location, and for each row the // list of things the operator may do to it and why the rest are withheld. @@ -115,6 +116,12 @@ export type StorageRow = { // "not answering since 11:35 — …", while the health probe finds this // location's drive not answering (lib/storageHealth.ts). Absent otherwise. notAnswering?: string; + // THE DRIVE'S HEALTH (lane drive-stall): answering, slow, not answering or + // not mounted, with when it last answered and how fast + // (lib/storageHealth.ts `driveHealthView`). What `pnpm ops get storage` + // reports per location. Absent on the internal row, and when the shell + // passed none. + drive?: DriveHealthView; warning?: string; candidateRoot?: string; // Why every action on this row is withheld, or null. One re-point runs at a @@ -235,6 +242,9 @@ export type StorageRowsInputs = { // Worded by the shell (lib/storageHealth.ts's `notAnsweringText`), because // this module takes types only from lib/. notAnswering?: Record<string, string | undefined>; + // By location id: the drive's health view, built by the shell from the + // health record and this probe (`driveHealthView`). + drives?: Record<string, DriveHealthView | undefined>; rollups: Record<string, LocationRollup | undefined>; registry: RegistryReader; udisksctlAvailable?: boolean; @@ -254,6 +264,14 @@ export const STORAGE_STATUS_LABEL: Record<StorageLocationStatus, string> = { stalled: "Not answering", }; +// WHETHER A PROBE STATUS MEANS THE DRIVE IS MOUNTED, for the drive's health +// view: `available` is, `stalled` did not ask (the health record decides), and +// every other status is a root that is not there. Undefined for no probe. +export function probeMounted(status: StorageLocationStatus | undefined): boolean | undefined { + if (status === undefined || status === "stalled") return undefined; + return status === "available"; +} + export const REPOINT_JOB_KIND = "repoint-storage-location"; export const SAVED_VIDEOS_JOB_KIND = "relocate-saved-videos"; @@ -453,6 +471,7 @@ export function buildStorageRows(i: StorageRowsInputs): StorageRowsPayload { ...(i.notAnswering?.[loc.id] ? { notAnswering: i.notAnswering[loc.id] } : {}), + ...(i.drives?.[loc.id] ? { drive: i.drives[loc.id] } : {}), ...(probe?.warning ? { warning: probe.warning } : {}), ...(candidateRoot ? { candidateRoot } : {}), busy, diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -87,6 +87,7 @@ import { } from "../lib/transcriptCoverage"; import type { Paths } from "../lib/paths"; import { transcribeWithWorker } from "../controller/transcribeOne"; +import { isMediaDriveHeld } from "../controller/transcribeError"; import { extractVideoId, outputArgsForUrl } from "./runYtdlp"; import { channelExtraArgs, channelPaceSeconds } from "./channelArgs"; import { @@ -1855,11 +1856,21 @@ async function runManagedDownload( }); status = "ok-auto-transcribed"; } catch (err) { - opts.onLog( - `Whisper failed after no-subs fallback: ${(err as Error).message}\n`, - ); - status = "failed"; - lastSucceeded = false; + if (isMediaDriveHeld(err)) { + // THE AUDIO IS HERE; ITS DRIVE IS NOT ANSWERING (lane + // drive-stall). The download succeeded — the status stays the + // attempt's, as when inline whisper is off, and the transcription + // lane picks the video up once the drive answers. + opts.onLog( + `Audio downloaded for ${videoId}; not transcribed inline: ${(err as Error).message}.\n`, + ); + } else { + opts.onLog( + `Whisper failed after no-subs fallback: ${(err as Error).message}\n`, + ); + status = "failed"; + lastSucceeded = false; + } } } else { opts.onLog( diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text. +- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it. +- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do. - **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`). - **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site. - **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`). diff --git a/editor/app/api/test/drive-health/route.ts b/editor/app/api/test/drive-health/route.ts @@ -0,0 +1,53 @@ +import { NextResponse } from "next/server"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { + noteDriveSlow, + recordLocationHealth, + registerLocationHealth, +} from "yt-dlp-transcript-common/lib/storageHealth"; +import { forgetChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia"; +import { resetStorageProbeMemo } from "yt-dlp-transcript-common/controller/storageLocations"; +import { testRouteDenied } from "../_guard"; + +export const dynamic = "force-dynamic"; + +// E2E test harness only (guarded by `E2E_TEST_ROUTES`, see _guard.ts). +// +// A STALLED DRIVE WITHOUT A HUNG MOUNT. No fixture can make a real drive stop +// answering, and none should: this records what a detector would have said +// about a configured location — `stalled` (one answer marks it, as the +// counters or the watchdog would) or `slow` (the watchdog's slow refusal) — +// into the process's health record, which every gate, page and poll reads. +// The health pass then sees the fixture's drive answering and clears a stall +// after `clearAfterCleanPasses` passes (30 s at the defaults), so a spec +// asserts within that window. `/api/test/invalidate-cache` forgets it all. +// +// POST {"id": "<location id>", "state": "stalled" | "slow", "cause"?: "…"} +export async function POST(req: Request) { + const denied = testRouteDenied(); + if (denied) return denied; + const body = (await req.json().catch(() => ({}))) as { + id?: string; + state?: string; + cause?: string; + }; + const loc = getSettings().storage.locations.find((l) => l.id === body.id); + if (!loc) { + return NextResponse.json({ error: `no storage location "${body.id}"` }, { status: 404 }); + } + registerLocationHealth([loc]); + if (body.state === "stalled") { + recordLocationHealth(loc, "stalled", { + cause: body.cause ?? "a read in the editor did not answer within 3 s", + }); + } else if (body.state === "slow") { + noteDriveSlow(loc.id, body.cause ?? "a read in the editor took 2.4 s"); + } else { + return NextResponse.json({ error: `state must be "stalled" or "slow"` }, { status: 400 }); + } + // The channels' five-second answers and the ten-second probes, so the next + // page sees the drive as it is now. + forgetChannelMedia(); + resetStorageProbeMemo(); + return NextResponse.json({ ok: true }); +} diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts @@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [ // Views born after the consolidation: there is no old path to rewrite, so // they are served only at /api/view/<name>. -const NEW_VIEWS = ["cookieAlerts", "xRun"]; +const NEW_VIEWS = ["cookieAlerts", "xRun", "driveHealth"]; async function view(name: string): Promise<number> { const res = await GET(new Request(`http://localhost/api/view/${name}`), { diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts @@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status"; import { widgetSyncInputs } from "../../widget/lib/syncInputs"; import { cleanableChannels } from "../../cleanup/lib/loadCleanup"; import { loadCookieAlerts } from "../../lib/cookieAlerts"; +import { buildDriveHealthPayload } from "../../storage/lib/driveHealth"; import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun"; import { loadActionableSummary, @@ -83,6 +84,11 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = { // recorded job's status. cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())), + // The dashboard's drive banner: the storage locations whose drive is slow, + // not answering or not mounted. Polled slow; the health record is memory and + // the mount probe is memoised 10 s (no drive is asked in-process). + driveHealth: async () => NextResponse.json(await buildDriveHealthPayload()), + // /review's X run console: the latest run (each channel's state, the // summary), the X posts channels in the default order and the jar's age // against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X. diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts @@ -122,7 +122,11 @@ export async function persistChannelVideosAction( safeRevalidate([`/channels/${slug}`, "/saved-videos"]); // A run that stopped short or lost a video did not do what it was asked: // the job says so, and the re-run picks up the rest. - if (result.stopped === "low-disk" || result.stopped === "rate-limit") { + if ( + result.stopped === "low-disk" || + result.stopped === "rate-limit" || + result.stopped === "store-unavailable" + ) { throw new Error( `Stopped (${result.stopped}) with ${result.notAttempted.length} video(s) not attempted — run it again later.`, ); diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -82,7 +82,10 @@ import { unpersistSavedVideo, type DropSavedAlternateResult, } from "yt-dlp-transcript-common/lib/savedVideo-server"; -import { SavedVideosStoreInTransitionError } from "yt-dlp-transcript-common/lib/savedVideoStore"; +import { + SavedVideosStoreInTransitionError, + SavedVideosStoreNotAnsweringError, +} from "yt-dlp-transcript-common/lib/savedVideoStore"; import { savedVideoPath, type SavedVideoOrigin, @@ -1457,7 +1460,11 @@ export async function dropSavedAlternateAction( paths, }); } catch (e) { - if (e instanceof SavedAlternateRefusal || e instanceof SavedVideosStoreInTransitionError) { + if ( + e instanceof SavedAlternateRefusal || + e instanceof SavedVideosStoreInTransitionError || + e instanceof SavedVideosStoreNotAnsweringError + ) { return { ok: false, error: e.message }; } throw e; diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx @@ -10,6 +10,8 @@ import { NeedsWorkPanel } from "./NeedsWorkPanel"; import { QuickAddPanel } from "./QuickAddPanel"; import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel"; import { CookieAlertsPanel } from "./CookieAlertsPanel"; +import { DriveHealthBanner } from "./DriveHealthBanner"; +import type { DriveHealthPayload } from "../../storage/lib/driveHealth"; import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies"; import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow"; import { ChannelsTable } from "../../channels/components/ChannelsTable"; @@ -40,9 +42,12 @@ export type DashboardCockpitInitial = { firstRun?: FirstRunState | null; // The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this. cookieAlerts?: ServiceCookieAlertsPayload; + // The drive banner (storage/lib/driveHealth.ts), polled SLOW after this. + driveHealth?: DriveHealthPayload; }; const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] }; +const NO_DRIVE_TROUBLE: DriveHealthPayload = { drives: [] }; // The mission-control cockpit. A server component (app/page.tsx) SSRs the // initial payloads for a flicker-free first paint; this client shell then polls @@ -87,9 +92,17 @@ export function DashboardCockpit({ initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS, ); + const { data: driveHealth } = usePolledPayload<DriveHealthPayload>( + "/api/view/driveHealth", + true, + SLOW_MS, + initial.driveHealth ?? NO_DRIVE_TROUBLE, + ); + return ( <div className="flex flex-col gap-6"> <h1 className="sr-only">Dashboard</h1> + <DriveHealthBanner data={driveHealth ?? NO_DRIVE_TROUBLE} /> <CookieAlertsPanel data={cookieAlerts ?? EMPTY_COOKIE_ALERTS} onChange={() => void refetchCookieAlerts()} diff --git a/editor/app/components/dashboard/DriveHealthBanner.tsx b/editor/app/components/dashboard/DriveHealthBanner.tsx @@ -0,0 +1,84 @@ +"use client"; + +// THE DRIVE BANNER (lane drive-stall): one card per storage location whose +// drive is not answering, slow, or not mounted with channels on it — the +// dashboard's top slot, beside the cookie banners. Not answering and not +// mounted are different troubles with different fixes, so they read +// differently: a drive that is here and stalled (a USB enclosure resetting) +// is waited out, or unplugged and replugged; a drive that is not mounted is +// mounted. The words come from the server (lib/storageHealth.ts +// `driveHealthView`), so /storage and this banner cannot disagree. + +import Link from "next/link"; +import type { + DriveHealthBannerRow, + DriveHealthPayload, +} from "../../storage/lib/driveHealth"; + +const HEADLINE: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = { + stalled: "is not answering", + slow: "is answering slowly", + unmounted: "is not mounted", +}; + +const WHAT_HAPPENS: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = { + stalled: + "Pages and polls skip it and its channels' jobs are held until it answers again; nothing else in the editor waits on it.", + slow: "Everything still runs; reads on it take longer than they should.", + unmounted: "Its channels' jobs are held until it is back.", +}; + +function DriveCard({ drive }: { drive: DriveHealthBannerRow }) { + if (drive.state === "ok") return null; + const severe = drive.state !== "slow"; + return ( + <section + role={severe ? "alert" : "status"} + aria-label={`drive ${drive.id}`} + data-state={drive.state} + className={`rounded-md border bg-card px-4 py-3 ${ + severe ? "border-destructive/50" : "border-amber-500/50" + }`} + > + <p + className={`text-sm font-medium ${ + severe ? "text-destructive" : "text-amber-700 dark:text-amber-300" + }`} + > + The media drive {drive.label} {HEADLINE[drive.state]} + </p> + <p className="text-xs" aria-label={`drive ${drive.id} health`}> + {drive.text} + </p> + <p className="text-xs text-muted-foreground"> + {WHAT_HAPPENS[drive.state]} + {" · "} + <Link href="/storage" className="underline underline-offset-2 hover:text-foreground"> + Storage + </Link> + {drive.channels > 0 && ( + <> + {" · "} + <Link + href={drive.channelsHref} + className="underline underline-offset-2 hover:text-foreground" + > + {drive.channels} channel(s) on it + </Link> + </> + )} + </p> + </section> + ); +} + +export function DriveHealthBanner({ data }: { data: DriveHealthPayload }) { + if (data.drives.length === 0) return null; + return ( + <div aria-label="drive health" className="flex flex-col gap-2"> + {data.drives.map((d) => ( + <DriveCard key={d.id} drive={d} /> + ))} + </div> + ); +} diff --git a/editor/app/page.tsx b/editor/app/page.tsx @@ -20,6 +20,7 @@ import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSyn import { widgetSyncInputs } from "./widget/lib/syncInputs"; import { DashboardCockpit } from "./components/dashboard/DashboardCockpit"; import { loadCookieAlerts } from "./lib/cookieAlerts"; +import { buildDriveHealthPayload } from "./storage/lib/driveHealth"; import { buildChannelRowView, channelVolumeOf, @@ -134,10 +135,11 @@ export default async function Dashboard({ // active site for the SSR seed. const actionable = buildWidgetActionablePayload(widgetActionableRows(rows)); - const [jobs, sync, cookieAlerts] = await Promise.all([ + const [jobs, sync, cookieAlerts, driveHealth] = await Promise.all([ buildActiveJobsPayload(), widgetSyncInputs().then(buildWidgetSyncPayload), loadCookieAlerts(paths), + buildDriveHealthPayload(), ]); const workers = buildWorkersPayload(); const changelogSource = loadChangelog(); @@ -153,6 +155,7 @@ export default async function Dashboard({ changelogSource, firstRun: summary.rows.length === 0 ? firstRunState(paths) : null, cookieAlerts, + driveHealth, }} /> ); diff --git a/editor/app/storage/buildStorage.ts b/editor/app/storage/buildStorage.ts @@ -4,11 +4,14 @@ import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { getFreeBytes } from "yt-dlp-transcript-common/lib/diskSpace"; import { udisksctlAvailable } from "yt-dlp-transcript-common/lib/storageVolumes"; import { + driveHealthView, healthTimings, isDriveNotAnswering, + locationHealth, notAnsweringText, onDrive, stalledLocation, + type DriveHealthView, } from "yt-dlp-transcript-common/lib/storageHealth"; import { clearRuleText } from "yt-dlp-transcript-common/lib/storageHealthTimings"; import { listChannelBriefs } from "yt-dlp-transcript-common/controller/channels"; @@ -24,6 +27,7 @@ import { import { pathExists } from "yt-dlp-transcript-common/controller/relocateDir"; import { buildStorageRows, + probeMounted, type StorageRowsPayload, } from "yt-dlp-transcript-common/views/storage"; @@ -136,6 +140,18 @@ export async function buildStorage(): Promise<StorageRowsPayload> { `Pages and polls skip this drive until it answers ${clears}.${watched}`; } } + // EACH DRIVE'S HEALTH, from memory and this render's probe: answering, slow, + // not answering or not mounted (lib/storageHealth.ts `driveHealthView`). A + // record for another root under the same id (a re-point the pass has not + // seen yet) is not this drive's. + const drives: Record<string, DriveHealthView> = {}; + for (const loc of locations) { + const h = locationHealth(loc.id); + drives[loc.id] = driveHealthView(loc, h && h.root === loc.root ? h : undefined, { + now, + mounted: probeMounted(probes[loc.id]?.status), + }); + } const store = await inspectSavedVideosStore(paths, settings); // A store on a location walks that location's drive: through the watchdog, // so a drive that stops answering mid-walk leaves the size at 0 (the store's @@ -173,6 +189,7 @@ export async function buildStorage(): Promise<StorageRowsPayload> { defaultLocationId: settings.storage.defaultLocationId, probes, notAnswering, + drives, rollups, registry: getRegistry(), udisksctlAvailable: udisksctl, diff --git a/editor/app/storage/components/StorageLocationsTable.tsx b/editor/app/storage/components/StorageLocationsTable.tsx @@ -173,6 +173,17 @@ function LocationCard({ > {row.statusLabel} </span> + {/* SLOW IS NOT A STATUS: the drive is there and answering, a beat + late (lib/storageHealth.ts `driveHealthView`). A chip beside the + status, so "Available" stays true and the slowness is still seen. */} + {row.drive?.state === "slow" && ( + <span + aria-label="location slow" + className="rounded-full border border-amber-500/50 bg-amber-500/10 px-2 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-300" + > + slow + </span> + )} {row.isDefault && ( <span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground"> default @@ -264,6 +275,16 @@ function LocationCard({ </dd> <dt className="text-muted-foreground">Last probe</dt> <dd aria-label="location last probe">{formatAge(row.lastProbeAgeMs)}</dd> + {/* THE DRIVE'S HEALTH in one line: answering (how fast, when last), + slow, not answering since, or not mounted. */} + {row.drive && ( + <> + <dt className="text-muted-foreground">Drive</dt> + <dd aria-label="location drive" className="text-xs"> + {row.drive.text} + </dd> + </> + )} </dl> {row.notAnswering && ( diff --git a/editor/app/storage/lib/driveHealth.ts b/editor/app/storage/lib/driveHealth.ts @@ -0,0 +1,71 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { locationOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations"; +import { + driveHealthView, + locationHealth, + type DriveHealthView, +} from "yt-dlp-transcript-common/lib/storageHealth"; +import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; +import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations"; +import { + channelsHrefForLocation, + probeMounted, +} from "yt-dlp-transcript-common/views/storage"; + +// THE DASHBOARD'S DRIVE BANNER — every storage location whose drive is slow, +// not answering or not mounted, and how many channels have their media there. +// +// NOTHING HERE ASKS A DRIVE IN-PROCESS. The health record is memory (the +// health pass and the watchdog write it, lib/storageHealth.ts), and the mount +// half is the same probe /storage renders from: memoised 10 s, a stalled +// location answered without a call. The channel configs are read only when +// some drive is in trouble — the corpus disk, one small file per channel — +// because a drive nobody's media is on is not worth a banner when it is merely +// unplugged. +// +// SERVER ONLY (it reaches the controller, which imports execa). + +export type DriveHealthBannerRow = DriveHealthView & { + // Channels whose media is on this location (by `mediaDir`, or a legacy + // channel's retired `dataDir`). + channels: number; + // `/channels?location=<id>`: the list of them. + channelsHref: string; +}; + +export type DriveHealthPayload = { drives: DriveHealthBannerRow[] }; + +export async function buildDriveHealthPayload(): Promise<DriveHealthPayload> { + const paths = getPaths(); + const locations = getSettings().storage.locations; + if (locations.length === 0) return { drives: [] }; + const probes = await probeAllLocations(locations, paths); + const now = Date.now(); + const troubled = locations + .map((loc) => { + const h = locationHealth(loc.id); + return driveHealthView(loc, h && h.root === loc.root ? h : undefined, { + now, + mounted: probeMounted(probes[loc.id]?.status), + }); + }) + .filter((v) => v.state !== "ok"); + if (troubled.length === 0) return { drives: [] }; + const counts = new Map<string, number>(); + for (const { config } of await listChannelConfigs(paths)) { + const dir = config.mediaDir?.trim() || config.dataDir?.trim(); + const loc = dir ? locationOfDataDir(dir, locations) : null; + if (loc) counts.set(loc.id, (counts.get(loc.id) ?? 0) + 1); + } + return { + drives: troubled + .map((v) => ({ + ...v, + channels: counts.get(v.id) ?? 0, + channelsHref: channelsHrefForLocation(v.id), + })) + // An unplugged drive with nobody's media on it is not news. + .filter((v) => v.state !== "unmounted" || v.channels > 0), + }; +} diff --git a/editor/e2e/drive-health.spec.ts b/editor/e2e/drive-health.spec.ts @@ -0,0 +1,162 @@ +import { mkdir, rm, symlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { test, expect, type Page } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers"; + +// A DRIVE THAT IS NOT ANSWERING, ONE THAT IS SLOW, ONE THAT IS NOT MOUNTED — +// and that /storage and the dashboard tell them apart (lane drive-stall). +// +// NO FIXTURE HANGS A MOUNT. `/api/test/drive-health` records what a detector +// would have said about a configured location (a stall, or the watchdog's +// slow refusal) into the editor's health record, which every gate, page and +// poll reads; the health pass then sees the fixture's drive answering and +// clears a stall after two clean passes (15–30 s), so each step marks the +// drive again just before it looks. "Not mounted" is real: the location's +// root is removed. The detectors and the state machine are unit-tested +// (common/lib/storageHealth.test.ts, controller/storageWatch.test.ts). + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "test-youtube"; +const VIDEO = "20240101_test1234567"; + +const channelDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`); + +// The fixture channel's media tier on `root`, as a finished move leaves it +// (storage-locations.spec.ts builds it the same way). +async function relocateOnDisk(root: string): Promise<void> { + const target = join(root, SLUG, "media"); + await mkdir(join(target, VIDEO), { recursive: true }); + await writeFile(join(target, VIDEO, "audio.mp3"), "ID3audio"); + await symlink( + join("..", "..", "media", VIDEO, "audio.mp3"), + join(channelDir(), "data", VIDEO, "audio.mp3"), + ); + await symlink(target, join(channelDir(), "media")); + const config = await readJson<Record<string, unknown>>( + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, + ); + await writeFile( + join(channelDir(), "config.json"), + JSON.stringify({ ...config, mediaDir: target }, null, 2) + "\n", + ); + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); +} + +async function mark(id: string, state: "stalled" | "slow"): Promise<void> { + const res = await fetch(`${baseUrl}/api/test/drive-health`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ id, state }), + }); + expect(res.ok, await res.clone().text()).toBe(true); +} + +async function setUp(root: string): Promise<void> { + await resetData("one-youtube-channel-with-data"); + await mkdir(root, { recursive: true }); + await relocateOnDisk(root); + await writeSettings({ + adminTitle: "Test Admin", + minFreeDiskGB: 0, + storage: { + locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }], + defaultLocationId: "cold", + }, + }); +} + +function row(page: Page, id: string) { + return page.getByLabel(`storage location: ${id}`); +} + +test("a stalled drive reads 'not answering' on /storage and the dashboard; an unmounted one 'not mounted'", async ({ + page, +}, testInfo) => { + test.setTimeout(120_000); + const root = testInfo.outputPath("platter"); + await setUp(root); + + // --- not answering ------------------------------------------------------ + await mark("cold", "stalled"); + await page.goto("/storage"); + const cold = row(page, "cold"); + await expect(cold.getByLabel("location status")).toHaveText("Not answering"); + await expect(cold.getByLabel("location drive")).toHaveText(/^not answering since \d\d:\d\d — /); + await expect(cold.getByLabel("location slow")).toHaveCount(0); + await page.setViewportSize({ width: 1366, height: 768 }); + await cold.screenshot({ path: testInfo.outputPath("storage-not-answering.png") }); + + await mark("cold", "stalled"); + await page.goto("/"); + const card = page.getByLabel("drive cold", { exact: true }); + await expect(card).toBeVisible(); + await expect(card).toHaveAttribute("data-state", "stalled"); + await expect(card).toHaveAttribute("role", "alert"); + await expect(card).toContainText("The media drive Cold is not answering"); + await expect(page.getByLabel("drive cold health")).toHaveText(/^not answering since \d\d:\d\d/); + await expect(card.getByRole("link", { name: "1 channel(s) on it" })).toHaveAttribute( + "href", + /^\/channels\?location=cold(&|$)/, + ); + await page.setViewportSize({ width: 1366, height: 768 }); + await page.screenshot({ path: testInfo.outputPath("dashboard-not-answering.png") }); + + // --- the drive answers again: no banner ----------------------------------- + await fetch(`${baseUrl}/api/test/invalidate-cache`); + await page.goto("/"); + await expect(page.getByRole("heading", { name: "Dashboard" })).toBeAttached(); + await expect(page.getByLabel("drive health")).toHaveCount(0); + + // --- not mounted (the root is gone; its channel's media was on it) -------- + await rm(root, { recursive: true, force: true }); + await fetch(`${baseUrl}/api/test/invalidate-cache`); + await page.goto("/"); + const gone = page.getByLabel("drive cold", { exact: true }); + await expect(gone).toHaveAttribute("data-state", "unmounted"); + await expect(gone).toContainText("The media drive Cold is not mounted"); + await expect(page.getByLabel("drive cold health")).toHaveText("not mounted"); + await page.goto("/storage"); + await expect(row(page, "cold").getByLabel("location status")).not.toHaveText("Not answering"); + await expect(row(page, "cold").getByLabel("location drive")).toHaveText("not mounted"); +}); + +test("a slow drive stays Available with a slow chip, and its dashboard card is a status, not an alert", async ({ + page, +}, testInfo) => { + test.setTimeout(120_000); + const root = testInfo.outputPath("platter"); + await setUp(root); + + await mark("cold", "slow"); + await page.goto("/storage"); + const cold = row(page, "cold"); + await expect(cold.getByLabel("location status")).toHaveText("Available"); + await expect(cold.getByLabel("location slow")).toHaveText("slow"); + await expect(cold.getByLabel("location drive")).toHaveText( + /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/, + ); + await page.setViewportSize({ width: 1366, height: 768 }); + await cold.screenshot({ path: testInfo.outputPath("storage-slow.png") }); + + await mark("cold", "slow"); + await page.goto("/"); + const card = page.getByLabel("drive cold", { exact: true }); + await expect(card).toHaveAttribute("data-state", "slow"); + await expect(card).toHaveAttribute("role", "status"); + await expect(card).toContainText("The media drive Cold is answering slowly"); + await page.setViewportSize({ width: 1366, height: 768 }); + await page.screenshot({ path: testInfo.outputPath("dashboard-slow.png") }); + + // `pnpm ops get storage` reports the same view per location. + await mark("cold", "slow"); + const res = await page.request.get(`${baseUrl}/api/ops/storage`, { headers: AUTH }); + expect(res.ok(), await res.text()).toBe(true); + const body = (await res.json()) as { + storage: { rows: Array<{ id: string; drive?: { state: string; text: string; lastOkAt?: number } }> }; + }; + const drive = body.storage.rows.find((r) => r.id === "cold")?.drive; + expect(drive?.state).toBe("slow"); + expect(drive?.text).toMatch(/^slow at /); + expect(body.storage.rows.find((r) => r.id === "internal")?.drive).toBeUndefined(); +}); diff --git a/editor/package.json b/editor/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev --port ${EDITOR_PORT:-3001}", + "dev": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next dev --port ${EDITOR_PORT:-3001}", "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", "build": "next build", diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -8147,6 +8147,52 @@ shipped". Anchors are at slice DT's tip (`r15/drive-timings`). stalled at boot before the second counter sample, unless a page reaches it; per-click server actions; the file route's stream; the corpus disk itself. +### Lane drive-stall additions (2026-11-09, branch `lane/drive-stall`) + +- **The record says more than ok | stalled | absent.** `LocationHealth` gains `lastOkAt` (a pass's + clean `ok`, or an `onDrive` call answered in its budget; a registration sets none), `latencyMs` + + `latencyFrom` (`call`: the unit's time; `stat`: the child stat's round trip, process start + included; `counters`: the device's own average per completed request, Δ(fields 4 + 8 (+ 15 + 17)) / + Δcompleted between two samples — `blockStatTicksMs`, `countersLatencyMs` in `storageVolumes.ts`; + `parseBlockStat`'s shape is unchanged), and `slowAt`/`slowCause` (a measurement ≥ + `slowThresholdMs()` = budget / 2 TWICE IN A ROW (`slowStreak`, `SLOW_READINGS_IN_A_ROW`; a fast one resets it), or either of the watchdog's "drive slow" refusals at once, `noteDriveSlow`). A + transition to stalled deletes slowAt. `noteDriveAnswer` writes only to an existing entry. +- **`driveHealthView(loc, health, { mounted })`** (`lib/storageHealth.ts`, pure) is the one view: + `stalled` (the record) > `unmounted` (record `absent`, or `mounted: false`) > `slow` (slowAt within + `slowWindowMs()` = 2 × passIntervalMs) > `ok`. `probeMounted(status)` (`views/storage.ts`): + available → true, stalled/undefined → undefined, the rest → false. Slow is shown, never acted on. +- **Surfaces.** `StorageRow.drive` (the shell passes `drives`, a record for another root under the + same id is dropped) → `pnpm ops get storage` `rows[].drive`; /storage's Drive line + (`aria-label="location drive"`) and `slow` chip (`location slow`). The dashboard banner: view + `driveHealth` (`storage/lib/driveHealth.ts`, `DriveHealthBanner`, cards `aria-label="drive <id>"`, + `data-state`, role alert for stalled/unmounted, status for slow); unmounted shows only with ≥ 1 + channel's media on the location; configs are read only when a drive is in trouble. +- **Batches hold mid-run.** `mediaStallHold(config, log, what)` (`lib/mediaStallHold.ts`, memory + only, edge-logged) is asked in the pool `limit()` of `runWhisperBatch` and of the backfill lane of + `runOperationBatch` (not digest): 0 while the channel's media location is stalled, so runPool + pauses (its idle poll is unref'd — a unit test needs a keep-alive). It heals itself: after `MEDIA_HOLD_REPROBE_AFTER_MS` (5 min) held, at most once per 5 min, a child + `stat` of the root (`probeLocationHealth`); answering clears a STALE record (no pass refreshed it for + 3 pass intervals) or counts once on a kept one. "Still holding" every 10 min; `reloadConfig` re-reads + the channel's targets at most every 10 s. Persist-videos and persist-kept ask + `savedVideosStoreRefusal` before each fetch and stop (`store-unavailable`, `skippedStoreUnavailable`); + `isMediaDriveHeld` is the one predicate (downloadOneManaged's inline whisper keeps the download's status). It gates DISPATCH only: the + batch's classification reads `data/` (readdir, the corpus disk) and never waits. The autoRunner + lanes were already held at pick time (`buildChannelWork`). `transcribeOneVideo` refuses before + `resolveAudioFile` with `MediaDriveHeldError` (`failureClass` "no-audio": skipped, never + failed-transcriptions; `transcribeOneFromQueue` logs its message). +- **The five-minute watch writes under the settings lock** (`withJsonFileLock(getPaths().settingsFile)`, + the lock `editor/app/settings/saveSettings.ts` `withSettingsLock` takes). `storageLocations.ts`'s and + `relocateSavedVideos.ts`'s settings writers still do not take it. +- **`/api/test/drive-health`** (`POST {id, state: "stalled"|"slow", cause?}`, E2E_TEST_ROUTES only) + records a detector's answer for a configured location; the pass clears a stall in 15–30 s. +- **The persist guard asks the record too.** `assertSavedVideosStoreWritable` throws + `SavedVideosStoreNotAnsweringError` for a store on a stalled location (the corpus store via + `readlink(savedVideosDir)`, a channel store by its path) before the marker check; persist callers + already catch and leave the container in `data/<id>/`. +- **The location probe memo is on `globalThis.__yttStorageProbeMemo__`** (was a module Map): a + `resetStorageProbeMemo()` from the e2e `invalidate-cache` route did not reach the page's copy, which + answered "available" for a removed root for up to 10 s. + ## The source's history (stagit) (verified 2026-09-30, branch `r15/stagit`) Release 15 slice SG ([`release-15.md`](release-15.md)); the operator-facing doc is `PUBLISH.md`, "The diff --git a/plans/brand-and-themes.md b/plans/brand-and-themes.md @@ -1296,6 +1296,7 @@ S4 ships after release 10's cut and is **not part of the site rollout**: it touc - **Mark M2 · Signal.** The parent mark's geometry, lit in Signal: ground `#151b20`, dim `#3f4c56`, lit `#5fa8a0`. (Dim `#586977` since 2026-09-27, with the parent mark's; see "The design".) The avatar uses the maskable variant (scale 0.8 on full-bleed ground). +- **The profile picture is PLAIN** (operator, 2026-11-09, over the Signal one): `common/brand/archilyzer-avatar.svg` + `archilyzer-avatar-1024.png` are its source of truth (maskable, achromatic lit, dim `#3f4c56`; `common/lib/brandAvatar.test.ts`). - **Lockup "flush · caps matched".** The `Archi|lyzer` wordmark sits over `MEDIA`: - Both are Archivo at wdth 118. The wordmark is 720 / 380 at -0.01em; MEDIA is 700, in Signal. - MEDIA's size is **1.035×** the wordmark's, and it is letter-spaced to exactly the wordmark's diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1097,7 +1097,9 @@ export function usage() { "", "get settings [<key>] is settings.json as the editor reads it (migrated and", " defaulted; a secret is \"<redacted>\"), or one top-level key of it.", - "get storage is /storage: each location, mounted or not, free space, tiers.", + "get storage is /storage: each location, mounted or not, free space, tiers,", + " and its drive's health (rows[].drive: ok | slow | stalled | unmounted,", + " since, lastOkAt, latencyMs, the cause and the one-line text).", "get saved-alternates [<slug>] lists every saved video holding two copies:", " a download over a container already in the store keeps both — an", " explicit persist (persist-videos, Persist source video, a whole-recording", diff --git a/umtool/app/api/report/bench/route.ts b/umtool/app/api/report/bench/route.ts @@ -4,7 +4,8 @@ import { clipBenchData } from "@/lib/report/benchData"; export const dynamic = "force-dynamic"; // THE CLIP BENCH'S DATA as JSON, for Play's in-place bench (components/projects/cutApp/CutApp.tsx): -// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] +// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] (`take`: the take Play was on, for +// Back; the clip is always the draft's -- a take's clip is never benched, L3) // // The same function the bench's own page renders from (lib/report/benchData.ts), // so the bench inside Play and the one on its own page cannot disagree. A clip @@ -15,7 +16,7 @@ export async function GET(request: Request) { if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const clip = q.get("clip") ?? ""; const search = Object.fromEntries([...q.entries()].filter(([k]) => k !== "project" && k !== "clip")); - const r = await clipBenchData(project, clip, { search, take: q.get("walkTake") || null, order: q.get("order") === "cut" ? "cut" : "walk" }); + const r = await clipBenchData(project, clip, { search, order: q.get("order") === "cut" ? "cut" : "walk" }); if (!r) return Response.json({ error: `${clip} is not a clip of the cut` }, { status: 404 }); return Response.json(r, { headers: { "cache-control": "no-store" } }); } diff --git a/umtool/app/api/report/takes/timeline/route.ts b/umtool/app/api/report/takes/timeline/route.ts @@ -4,6 +4,7 @@ import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; import { insertTakeEntry, moveTakeEntry, removeTakeEntry, takeToken, undoTakeEdit } from "@/lib/report/takeEdit.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; +import { takeEditDeprecation } from "@/lib/report/takeDeprecation.mjs"; export const dynamic = "force-dynamic"; @@ -22,6 +23,13 @@ export const dynamic = "force-dynamic"; // timeline, as the project's GET /api/report/timeline lists it (Add a clip's place picker, on a take). // // A stale token is a 409; a structure the build would refuse is a 400 with its sentences. +// +// DEPRECATED (L3 S6): no page calls it (edits land in the draft; a take is opened there first). Each call says +// so in one line on the server's stderr and answers with a `Deprecation: true` header. +const deprecated = (project: string | null, take: string | null) => { + console.warn(takeEditDeprecation("/api/report/takes/timeline", { project, take })); + return { deprecation: "true" }; +}; export async function GET(request: Request) { const url = new URL(request.url); const take = url.searchParams.get("take"); @@ -39,7 +47,7 @@ export async function GET(request: Request) { channel: str(e.channel), words: (str(e.quote) ?? str(e.text) ?? str(e.title) ?? "").replace(/\s+/g, " ").slice(0, 60), })); - return Response.json({ take, token: await takeToken(project.dir, take), timeline }, { headers: { "cache-control": "no-store" } }); + return Response.json({ take, token: await takeToken(project.dir, take), timeline }, { headers: { "cache-control": "no-store", ...deprecated(project.id, take) } }); } catch (e) { const message = e instanceof Error ? e.message : String(e); return Response.json({ error: message }, { status: /^no take /.test(message) ? 404 : 400 }); @@ -55,6 +63,7 @@ export async function POST(request: Request) { const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const take = body.take; + const dep = deprecated(project.id, take); const token = body.token === undefined || body.token === null ? null : String(body.token); const at = body.at === undefined || body.at === null ? null : Number(body.at); const id = typeof body.id === "string" ? body.id : ""; @@ -74,7 +83,7 @@ export async function POST(request: Request) { } else { return Response.json({ error: "op must be move, remove, undo or insert" }, { status: 400 }); } - return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store" } }); + return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store", ...dep } }); } catch (e) { if (e instanceof StaleToken) return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); diff --git a/umtool/app/api/report/takes/tools/route.ts b/umtool/app/api/report/takes/tools/route.ts @@ -2,6 +2,8 @@ import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; import { lintCommand } from "@/lib/report/lintCli.mjs"; import { takeCommand } from "@/lib/report/takeCli.mjs"; +import { timelineCommand } from "@/lib/report/timelineCli.mjs"; +import { ImportRefused, draftImportArgv } from "@/lib/report/takeImport.mjs"; import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; import { REPORTS_ROOT } from "@/lib/paths"; import { addStep } from "@/lib/queue/store.mjs"; @@ -18,9 +20,11 @@ export const dynamic = "force-dynamic"; // -> { exit, report: { ok, errors[], warnings[], entries } } // POST { project, take, op: "draft-from", id?, label? } umtool take <p> --id <id> --draft --from <take> --json // -> { exit, id, report } (id: the next free `<take>-d<n>` when none is given) -// POST { project, take, op: "import", refs: "<project>:<item>[,…]", after?, before?, dryRun? } -// umtool take <p> --id <take> --import-item … [--dry-run] --json -// -> { exit, report } +// POST { project, op: "import", refs: "<project>:<item>[,…]", after?, before?, dryRun? } +// umtool timeline <p> import-item … [--dry-run] --json: INTO +// -> { exit, report } THE DRAFT (the Cut tab's Add items from another project; L3: +// every edit lands in the draft). With `take`: the old take +// patch path, umtool take <p> --id <take> --import-item … // POST { project, op: "draft-new", label, group?, style?, patch?, window? } // umtool take <p> --id <slug of label> --label L --draft // -> { exit, id, report } [--group G] [--style S] [--patch-json P] [--full | --at A --dur D] @@ -87,6 +91,18 @@ export async function POST(request: Request) { kickQueue(); return Response.json({ exit: 0, queued: step.qid }, { headers: { "cache-control": "no-store" } }); } + if (body.op === "import" && !take) { + // Every word checked before it becomes argv (draftImportArgv): no flag rides in on the refs. + let argv: string[]; + try { + argv = draftImportArgv(project.id, { refs: body.refs, after: body.after, before: body.before, dryRun: !!body.dryRun }); + } catch (e) { + if (e instanceof ImportRefused) return Response.json({ error: e.message }, { status: 400 }); + throw e; + } + const exit = await timelineCommand(argv, { root: REPORTS_ROOT, out: io.log, err: io.err }); + return answer(exit); + } if (!take) return Response.json({ error: `${String(body.op)} needs a take` }, { status: 400 }); if (body.op === "draft-from") { let id = typeof body.id === "string" && body.id ? body.id : null; diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -15,6 +15,7 @@ import { removeSection, sectionsOf, rejectClip, + restoreRemoved, removeWrongSpeaker, removePost, undoStructural, @@ -50,6 +51,7 @@ export const dynamic = "force-dynamic"; // remove { id, at? } // reject { id, at?, reason, note? } rejected (rejectReasons.mjs) and removed, on record // wrong-speaker { id, at?, correction? } reject with the reason wrong-speaker +// restore { id } un-reject: a removed clip back from the newest revision holding it // duplicate { id, at? } // insert { afterId: id | null, at?, entry: "<channel>/<video>@<start>-<end>" | { type, … } } // teaser { id, at?, patch: { lines?, beat?, dip?, tail?, tailWait? } } @@ -157,6 +159,9 @@ export async function POST(request: Request) { case "reject": // Rejected for `reason` (rejectReasons.mjs) and removed in one write, on the record (removed.json). return rejectClip(dir, id, String(body.reason ?? ""), { token, at, note: typeof body.note === "string" ? body.note : null }); + case "restore": + // Un-reject: the removed clip back, as the newest revision holding it had it, at its old place. + return restoreRemoved(dir, id, { token }); case "duplicate": return duplicateEntry(dir, id, { token, at }); case "insert": diff --git a/umtool/app/icon.svg b/umtool/app/icon.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="112" fill="#151b20"/><rect x="112" y="128" width="288" height="44" rx="22" fill="#586977"/><polygon points="112,210 172,234 112,258" fill="#5fa8a0"/><rect x="188" y="212" width="212" height="44" rx="22" fill="#5fa8a0"/><rect x="112" y="296" width="232" height="44" rx="22" fill="#586977"/><rect x="112" y="380" width="152" height="44" rx="22" fill="#586977"/></svg> diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -1163,6 +1163,7 @@ async function cmdWindow() { // same rules, an undo point first -- never into the project's manifest. const take = val("--take"); if (take !== undefined) { + (await import("../lib/report/takeDeprecation.mjs")).warnTakeEdit("window --take", { project: p.id, take }); try { const { updateTakeClip } = await import("../lib/report/takeEdit.mjs"); const res = await updateTakeClip(p.dir, take, clipId, patch); diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -328,37 +328,11 @@ export type ClipBenchData = { * returns -- the project's cut at this clip -- and the take that was playing, * if one was (its render does not change when this manifest does). */ - /** Opened from Play: where Back lands; the take that was playing; `editsTake`: this bench edits that take (its own timeline). */ - fromPlay?: { href: string; take: string | null; editsTake?: boolean } | null; - /** Walk → Play: the cut from this clip (the bench opened on its own, not from Play, not a take's). */ + fromPlay?: { href: string; take: string | null } | null; + /** Walk → Play: the cut from this clip (the bench opened on its own, not from Play). */ playHere?: string | null; /** The working cut's name (lib/report/workingCut.mjs): the latest whole-cut take and the edits since it. */ working?: WorkingCut; - /** - * WALKING A TAKE (/projects/<p>/takes/<take>/clip/<id>): the clip is the - * take's -- the project's manifest with the take's patch applied -- and - * every save goes into the take's patch (takes/<id>/take.json), never the - * project's manifest. Every route this bench calls is asked with `take`. - * `all`: the walk visits every fetched clip, judged or not. - */ - take?: { - id: string; - label: string; - draft: boolean; - /** take.json exists, so there is somewhere for an edit to land (a recipe-only take is read only). */ - editable: boolean; - all: boolean; - /** The Takes page, and this walk's own start (with `all` as it is). */ - takesHref: string; - walkHref: string; - /** The same clip on the walk of every clip / of the unjudged ones. */ - toggleAllHref: string; - /** Clip id -> its bench address on this take's walk (siblings link through it). */ - clipHref: Record<string, string>; - /** This clip's index in the take's timeline, and the timeline's length (the strip's moves). */ - at: number; - entries: number; - } | null; }; const hms = (t: number) => { @@ -407,8 +381,6 @@ type UndoRec = { before: Record<string, unknown>; /** The Confirm carried a moved window, so Undo puts the edges back too. */ moved: boolean; - /** Walking a take: the take the Confirm was written into. */ - take?: string | null; }; const readUndo = (): UndoRec | null => { try { @@ -555,13 +527,9 @@ export default function ClipBench({ // The project's notes: this clip's row notes, and the edit notes a save on a // generated manifest leaves (the save says so, and they are re-read). const notes = useSharedNotes({ project: data.project }); - // Walking a take: every route is asked about the TAKE's clip, and every - // save lands in the take's patch (see ClipBenchData.take). - const takeId = data.take?.id ?? null; - const tq = takeId ? `&take=${encodeURIComponent(takeId)}` : ""; - const takeBody = takeId ? { take: takeId } : {}; - // Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk. - const clipExport = useClipExport(data.project, takeId); + // The DRAFT's clip, always (L3): a take's clip is never benched -- its old address is Open in draft. + // Export clip (ClipExport.tsx): this clip, clean, into the project's exports/. + const clipExport = useClipExport(data.project, null); const [clip, setClip] = useState<Clip>(data.clip); // Export ▾'s full exchange starts from the clip's saved extent. const clipAround = useMemo(() => ({ start: clip.start, end: clip.end }), [clip.start, clip.end]); @@ -581,7 +549,7 @@ export default function ClipBench({ const after = edgesAfter(clip, sel, mode); // Where the render will actually cut the drafted selection (bench/RenderGhosts.tsx): the // desk's waveform and the phone's edge strip both draw it. - const renderEdges = useRenderEdges(data.project, clip, { from: after.start, to: after.end }, takeId, { cutStart: after.cutStart, cutEnd: after.cutEnd }); + const renderEdges = useRenderEdges(data.project, clip, { from: after.start, to: after.end }, null, { cutStart: after.cutStart, cutEnd: after.cutEnd }); /** The patch that writes a span as the handles' (no mute mark): edgesAfter, as keys. */ const edgePatch = useCallback( (span: { from: number; to: number }): WindowPatch => { @@ -759,10 +727,11 @@ export default function ClipBench({ } catch { /* nothing to clear */ } - if (u.project !== data.project || (u.take ?? null) !== takeId || (u.next !== data.clip.id && u.clip !== data.clip.id)) return; + // A record a take's walk left (`take` set, before L3) is not this bench's to undo. + if (u.project !== data.project || (u as { take?: unknown }).take || (u.next !== data.clip.id && u.clip !== data.clip.id)) return; if (Date.now() - u.at >= UNDO_MS) return; setUndo(u); - }, [data.project, data.clip.id, takeId]); + }, [data.project, data.clip.id]); useEffect(() => { if (!undo) return; const id = window.setTimeout(() => setUndo(null), Math.max(0, undo.at + UNDO_MS - Date.now())); @@ -790,10 +759,10 @@ export default function ClipBench({ // What plays (bench/benchMedia.ts): the widest cached window, on the source clock. const media = useMemo( - () => sourceWindowMedia({ project: data.project, clip: clip.id, take: takeId, win: cached }), + () => sourceWindowMedia({ project: data.project, clip: clip.id, take: null, win: cached }), // The window by its name and the version of its bytes: a refresh returning the same one is the same media. // eslint-disable-next-line react-hooks/exhaustive-deps - [data.project, clip.id, takeId, cached?.name, cached?.v, cached?.from, cached?.to], + [data.project, clip.id, cached?.name, cached?.v, cached?.from, cached?.to], ); // Read by play() at the moment it schedules, so a mark moved since the last // render is the one you hear -- without re-creating play() on every nudge. @@ -842,7 +811,7 @@ export default function ClipBench({ void (async () => { const r = await fetch( `/api/report/cues?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` + - `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}${tq}`, + `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}`, { cache: "no-store" }, ); if (!r.ok || !live) return; @@ -852,7 +821,7 @@ export default function ClipBench({ return () => { live = false; }; - }, [data.project, clip.id, view.from, view.to, peekPad, tq]); + }, [data.project, clip.id, view.from, view.to, peekPad]); // ---- playback preferences ------------------------------------------------ useEffect(() => setPlayback(readPlayback()), []); @@ -1033,7 +1002,7 @@ export default function ClipBench({ const r = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current, ...patch }), + body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current, ...patch }), }); const j = (await r.json()) as Record<string, unknown>; lastSaved.current = j; @@ -1238,7 +1207,7 @@ export default function ClipBench({ // A verdict is a state change, and a thumb lands where it did not mean to. const before = (lastSaved.current?.before ?? null) as Record<string, unknown> | null; if (before) { - const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win, take: takeId }; + const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win }; try { sessionStorage.setItem(UNDO_KEY, JSON.stringify(rec)); } catch { @@ -1260,8 +1229,7 @@ export default function ClipBench({ async (u: UndoRec) => { setUndo(null); const b = u.before; - const uq = u.take ? `&take=${encodeURIComponent(u.take)}` : ""; - const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}${uq}`, { + const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}`, { cache: "no-store", }); if (!r.ok) { @@ -1280,11 +1248,11 @@ export default function ClipBench({ const w = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: u.project, clip: u.clip, ...(u.take ? { take: u.take } : {}), token: tok, ...patch }), + body: JSON.stringify({ project: u.project, clip: u.clip, token: tok, ...patch }), }); const j = (await w.json()) as Record<string, unknown>; if (!w.ok) { - setNote(j.stale ? `could not undo: the ${u.take ? "take" : "manifest"} changed since — reload` : `could not undo: ${String(j.error ?? w.status)}`); + setNote(j.stale ? "could not undo: the manifest changed since — reload" : `could not undo: ${String(j.error ?? w.status)}`); return; } if (wroteNotes(j)) void notes.reload(); @@ -1304,11 +1272,7 @@ export default function ClipBench({ const q = new URLSearchParams(window.location.search); q.delete("at"); const qs = q.toString(); - router.push( - u.take - ? `/projects/${u.project}/takes/${encodeURIComponent(u.take)}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}` - : `/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`, - ); + router.push(`/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`); }, // `notes.reload` is the stable part of `notes`. // eslint-disable-next-line react-hooks/exhaustive-deps @@ -1744,7 +1708,7 @@ export default function ClipBench({ const refresh = useCallback(async (): Promise<ClipBenchData | null> => { const r = await fetch( - `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`, + `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}`, { cache: "no-store" }, ); if (!r.ok) return null; @@ -1787,7 +1751,6 @@ export default function ClipBench({ body: JSON.stringify({ project: data.project, clip: clip.id, - ...takeBody, padBefore: round2(pads.padBefore), padAfter: round2(pads.padAfter), ...storedAsk, @@ -1858,7 +1821,7 @@ export default function ClipBench({ const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, full: true }), + body: JSON.stringify({ project: data.project, clip: clip.id, full: true }), }); if (!r.ok) { const j = (await r.json()) as { error?: string }; @@ -1945,7 +1908,7 @@ export default function ClipBench({ const r = await fetch("/api/report/cut", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current }), + body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current }), }); const j = (await r.json()) as { ok?: boolean; @@ -2132,8 +2095,7 @@ export default function ClipBench({ const padLabelForCue = (c: Cue) => c.end > view.to ? `+${padsForCue(c).padAfter} s` : `−${padsForCue(c).padBefore} s`; - // A take's clip has no segment of the project's (ClipBenchPage passes none). - const segSrc = segment && !takeId + const segSrc = segment ? `/api/report/segment?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&v=${segmentMtime ?? 0}` : null; @@ -2177,7 +2139,7 @@ export default function ClipBench({ const ok = () => !returnState.current.busy && returnState.current.clean; if (!ok()) return; const r = await fetch( - `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`, + `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}`, { cache: "no-store" }, ).catch(() => null); if (!r?.ok) return; @@ -2203,7 +2165,7 @@ export default function ClipBench({ setDraft(emptyDraft(next)); setOs(osDraftOf(next.onscreen)); } - }, [data.project, clip.id, tq]); + }, [data.project, clip.id]); const resyncRef = useRef(resync); resyncRef.current = resync; useEffect(() => { @@ -2661,19 +2623,12 @@ export default function ClipBench({ <p data-walk-quote="" className="m-0 font-serif text-[18px] leading-snug text-text"> {draft.quote.trim() ? `“${draft.quote.trim()}”` : <span className="text-muted">no quote on this entry</span>} </p> - {data.fromPlay?.take && - (data.fromPlay.editsTake ? ( - <p data-walk-take-note={data.fromPlay.take} data-walk-take-edits="take" className="m-0 text-[12.5px] leading-snug text-text-2"> - Opened from take <span className="font-mono">{data.fromPlay.take}</span>, which has its own timeline. Edits here go to the - take (<code className="font-mono">takes/{data.fromPlay.take}/take.json</code>), never the project&rsquo;s cut; Back plays - the take. - </p> - ) : ( - <p data-walk-take-note={data.fromPlay.take} className="m-0 text-[12.5px] leading-snug text-text-2"> - Opened from take <span className="font-mono">{data.fromPlay.take}</span>. Edits here go to the project&rsquo;s cut, not - to the take&rsquo;s render, so Back plays the project&rsquo;s cut. - </p> - ))} + {data.fromPlay?.take && ( + <p data-walk-take-note={data.fromPlay.take} className="m-0 text-[12.5px] leading-snug text-text-2"> + Opened from take <span className="font-mono">{data.fromPlay.take}</span>. Edits here go to the project&rsquo;s cut, not + to the take&rsquo;s render, so Back plays the project&rsquo;s cut. + </p> + )} </div> {cached && ( <EdgeStrip @@ -2770,12 +2725,12 @@ export default function ClipBench({ /** * Reject ▾ (RejectClip) on this clip: the bench's own writer for a keep in * place (its token, its state), the project's structural write for a - * removal -- and on a take's walk, a keep only (a take's timeline is a patch). + * removal. */ const rejectPanel = (className: string, opened = false) => ( <RejectClip project={data.project} - take={takeId ?? null} + take={null} hotkey={opened ? false : "digits"} control={opened ? undefined : rejectCtl} initialOpen={opened} @@ -2930,10 +2885,8 @@ export default function ClipBench({ {unsaved ? "Save and back to the cut" : "‹ Back to the cut"} </button> {data.fromPlay.take && ( - <span data-back-take={data.fromPlay.take} data-back-take-edits={data.fromPlay.editsTake ? "take" : "cut"} className="ml-2 text-[11.5px] text-muted-2"> - {data.fromPlay.editsTake - ? `edits go to take ${data.fromPlay.take}, not the project’s cut` - : <>edits go to the project&rsquo;s cut, not take {data.fromPlay.take}</>} + <span data-back-take={data.fromPlay.take} data-back-take-edits="cut" className="ml-2 text-[11.5px] text-muted-2"> + edits go to the project&rsquo;s cut, not take {data.fromPlay.take} </span> )} </>, @@ -2961,12 +2914,11 @@ export default function ClipBench({ {/* On a phone the banner is one muted line under Notes (phoneNotesHead). The wrapper only when there is a banner: an empty one would be a flex item, and a gap, on the desk. */} - {data.generatedBy && !data.take && ( + {data.generatedBy && ( <div className="max-md:hidden"> <GeneratedBanner generatedBy={data.generatedBy} /> </div> )} - {/* A take's clip is never benched from the UI now (L3: Open in draft first); `umtool window --take` edits one. */} {/* ---- where you are, where you can go, and what will be burned in ---- */} <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents"> {/* On a phone both counts are the place bar's `50/51` and its hairline. */} @@ -2979,7 +2931,7 @@ export default function ClipBench({ ready {data.ready} of {data.needing} needing judgement </span> {/* The working cut's name: what this bench edits, and the latest take it was made into. */} - {data.working && !data.take && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} + {data.working && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} {!data.fetched && ( <span className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")} data-clip-unfetched=""> not fetched yet @@ -3540,7 +3492,7 @@ export default function ClipBench({ Fetch whole source via editor </button> {/* A window known bad, evicted and fetched again: a queue step (lane/ui-simplify). */} - <RefetchButton project={data.project} clip={clip.id} take={takeId} disabled={!!busy} /> + <RefetchButton project={data.project} clip={clip.id} take={null} disabled={!!busy} /> {storedOffered && ( <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> )} @@ -3841,33 +3793,20 @@ export default function ClipBench({ nothing rendered for this clip yet </div> )} - {data.take ? ( - // The one-clip render builds the PROJECT's segment; a take is rendered whole. - <p data-take-no-rerender="" className="text-[11px] leading-snug text-[var(--color-dim)]"> - A take is rendered as a whole, from its own patch:{" "} - <Link href={data.take.takesHref} className="ink-link"> - Render on the Takes page - </Link>{" "} - or <code className="font-mono">umtool take {data.project} --id {data.take.id} --full</code>. - </p> - ) : ( - <> - <button - type="button" - data-rerender="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - onClick={() => void rerender()} - > - Re-render this clip - </button> - <p className="text-[11px] leading-snug text-[var(--color-dim)]"> - One clip, no crossfade, no chapters — it overwrites this clip&rsquo;s segment and - nothing else. The header is drawn by ffmpeg from a text file, so this is the only - place the line above can be checked rather than believed. - </p> - </> - )} + <button + type="button" + data-rerender="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + onClick={() => void rerender()} + > + Re-render this clip + </button> + <p className="text-[11px] leading-snug text-[var(--color-dim)]"> + One clip, no crossfade, no chapters — it overwrites this clip&rsquo;s segment and + nothing else. The header is drawn by ffmpeg from a text file, so this is the only + place the line above can be checked rather than believed. + </p> </div> {/* ---- lock, explained rather than labelled ---- */} @@ -3961,7 +3900,7 @@ export default function ClipBench({ {siblings.map((sb) => ( <li key={sb.id} data-sibling={sb.id} className="leading-snug"> <Link - href={data.take?.clipHref[sb.id] ?? `/projects/${data.project}/clip/${sb.id}`} + href={`/projects/${data.project}/clip/${sb.id}`} className="font-mono ink-link" > {sb.id} diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -11,19 +11,12 @@ export default async function ClipBenchPage({ project, clipId, search = {}, - take = null, }: { project: ProjectRef; clipId: string; search?: Record<string, string | undefined>; - /** - * WALKING A TAKE (`/projects/<p>/takes/<take>/clip/<id>`): the clip is the - * take's -- the project's manifest with the take's patch applied - * (lib/report/walkData.mjs) -- and the bench's saves go into the take. - */ - take?: string | null; }) { - const { data, top } = await clipBenchDataOr404(project, clipId, { search, take, order: search.order === "cut" ? "cut" : "walk" }); + const { data, top } = await clipBenchDataOr404(project, clipId, { search, order: search.order === "cut" ? "cut" : "walk" }); return ( // The bench shell (P4b): its top bar here, the body -- the work, the // verdict bar, the reader -- in ClipBench, which owns their state. diff --git a/umtool/components/projects/TakeTools.tsx b/umtool/components/projects/TakeTools.tsx @@ -15,8 +15,9 @@ import PlayLink from "./PlayLink"; // // Check before render umtool lint <p> --take <t> // New draft from this take umtool take <p> --id <t>-d<n> --draft --from <t> -// Add items from another umtool take <p> --id <t> --import-item <src>:<a,b> [--after|--before <e>] -// project [--dry-run]: Preview shows the plan, Import does it +// Add items from another umtool timeline <p> import-item <src>:<a,b> [--after|--before <e>] +// project (the Cut tab) [--dry-run]: INTO THE DRAFT (L3: every edit lands there; E1, 9 Nov) -- +// Preview shows the plan, Import does it // --------------------------------------------------------------------------- type Tools = { exit: number; report: Record<string, unknown> | null; said?: string; id?: string; error?: string }; @@ -97,8 +98,8 @@ export function DraftFromButton({ project, take }: { project: string; take: stri type Entry = { id: string; type: string; words?: string }; -/** Add items from another project: cloned into this take only, their files hard-linked in; Preview first. */ -export function ImportItems({ project, take }: { project: string; take: string }) { +/** Add items from another project: cloned into the DRAFT, their files hard-linked in; Preview first. */ +export function ImportItems({ project }: { project: string }) { const router = useRouter(); const [open, setOpen] = useState(false); const [source, setSource] = useState(""); @@ -112,8 +113,8 @@ export function ImportItems({ project, take }: { project: string; take: string } const [done, setDone] = useState<Tools | null>(null); useEffect(() => { if (!open) return; - // The take's entries as Play reads them (its frozen manifest, or its patch over the draft): where an item lands. - void fetch(`/api/report/play-view?${new URLSearchParams({ project, take })}`, { cache: "no-store" }) + // The draft's entries as Play reads them: where an item lands. + void fetch(`/api/report/play-view?${new URLSearchParams({ project })}`, { cache: "no-store" }) .then((r) => r.json()) .then((j) => setEntries(Array.isArray(j.entries) ? (j.entries as { id: string; type: string; heading?: string }[]).map((e) => ({ id: e.id, type: e.type, words: e.heading })) : [])) .catch(() => {}); @@ -121,11 +122,11 @@ export function ImportItems({ project, take }: { project: string; take: string } .then((r) => r.json()) .then((j) => setProjects(((j.pieces ?? []) as { id: string; kind: string }[]).filter((p) => p.kind === "project" && p.id.startsWith("p:")).map((p) => p.id.slice(2)))) .catch(() => {}); - }, [open, project, take]); + }, [open, project]); const refs = items.trim() ? `${source.trim()}:${items.replace(/\s+/g, "")}` : ""; const run = async (dryRun: boolean) => { setBusy(true); - const r = await tool({ project, take, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun }); + const r = await tool({ project, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun }); setBusy(false); if (dryRun) { setPlan(r); @@ -139,14 +140,14 @@ export function ImportItems({ project, take }: { project: string; take: string } const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; const rows = (t: Tools | null) => ((t?.report as { items?: { id: string; action: string; at?: { index?: number; after?: string | null; before?: string | null } }[] } | null)?.items ?? []); return ( - <span className="inline-flex basis-full flex-col gap-1.5" data-take-import={take}> + <span className="inline-flex basis-full flex-col gap-1.5" data-take-import="draft"> <button type="button" data-action="import-open" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), "self-start")}> Add items from another project </button> {open && ( <span className="flex flex-wrap items-center gap-1.5 rounded border border-seam p-2 text-[11.5px]"> - <input data-import-source="" list={`import-projects-${take}`} value={source} onChange={(e) => setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} /> - <datalist id={`import-projects-${take}`}> + <input data-import-source="" list="import-projects-draft" value={source} onChange={(e) => setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} /> + <datalist id="import-projects-draft"> {projects.filter((p) => p !== project).map((p) => ( <option key={p} value={p} /> ))} @@ -172,7 +173,7 @@ export function ImportItems({ project, take }: { project: string; take: string } Preview </button> <button type="button" data-action="import-go" disabled={busy || !refs || !source.trim()} onClick={() => void run(false)} className={buttonVariants({ variant: "go", size: "sm" })}> - Import into {take} + Import into the draft </button> </span> )} @@ -221,14 +222,16 @@ export function CheckJoinsButton({ project, take }: { project: string; take: str ); } -/** The take's tools, as a take card's or a take walk's row. */ -export default function TakeTools({ project, take, editable = true, rendered = false }: { project: string; take: string; editable?: boolean; rendered?: boolean }) { +/** + * The take's tools, as a take card's row. Add items from another project is the draft's now (the Cut tab): + * a take is not edited in place (L3). + */ +export default function TakeTools({ project, take, rendered = false }: { project: string; take: string; rendered?: boolean }) { return ( <span className="flex flex-wrap items-start gap-1.5" data-take-tools={take}> <LintButton project={project} take={take} /> {rendered && <CheckJoinsButton project={project} take={take} />} <DraftFromButton project={project} take={take} /> - {editable && <ImportItems project={project} take={take} />} </span> ); } diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -876,7 +876,7 @@ function TakeCard({ </p> )} {/* Everything but play, judge, walk and render, folded (lane/ui-simplify): Options the common, Advanced the rare. */} - <Options id="take-card" hint="use · rebuild · check · draft · import · fork · compare"> + <Options id="take-card" hint="use · rebuild · check · draft · fork · compare"> <div className="flex flex-wrap items-center gap-1.5"> {!t.draft && ( <button @@ -902,7 +902,7 @@ function TakeCard({ </button> )} </div> - <TakeTools project={project} take={t.id} editable={walkable} rendered={!!t.builtAt && !t.draft} /> + <TakeTools project={project} take={t.id} rendered={!!t.builtAt && !t.draft} /> <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}> <ForkVariant project={project} take={t.id} ready={ready} /> <CompareWith project={project} take={t.id} options={compareOptions} /> diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx @@ -28,9 +28,8 @@ import type { BenchTopSpec } from "@/lib/report/benchData"; // the view is read again (router.refresh: the bench may have saved), and // Play recomposes only when the manifest's token moved. // -// A TAKE WITH ITS OWN TIMELINE is edited on its own bench (PlayCut's Edit: -// `/takes/<take>/clip/<id>?from=play`) -- in place too, the bench's data asked -// with `walkTake`, so its saves go into the take's patch and Back plays it. +// A take's clip is not benched here (L3): its old address +// (`/takes/<take>/clip/<id>`) is the Open in draft page, a navigation of its own. // --------------------------------------------------------------------------- type View = { kind: "play" } | { kind: "clip"; id: string; href: string }; @@ -47,21 +46,13 @@ const Ctx = createContext<CutAppApi | null>(null); /** Play's handle on the app: null when Play is drawn on its own (a test page, an old build). */ export const useCutApp = () => useContext(Ctx); -/** - * The clip id in a bench address of this project, or null: the cut's - * (`/clip/<id>`) or a take's (`/takes/<take>/clip/<id>`, `take` set). - */ -function benchOf(pathname: string, project: string): { id: string; take: string | null } | null { +/** The clip id in a bench address of this project (`/clip/<id>`), or null. */ +function clipOf(pathname: string, project: string): string | null { const root = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/`; if (!pathname.startsWith(root)) return null; const rest = pathname.slice(root.length).split("/"); - if (rest.length === 2 && rest[0] === "clip" && rest[1]) return { id: decodeURIComponent(rest[1]), take: null }; - if (rest.length === 4 && rest[0] === "takes" && rest[1] && rest[2] === "clip" && rest[3]) { - return { id: decodeURIComponent(rest[3]), take: decodeURIComponent(rest[1]) }; - } - return null; + return rest.length === 2 && rest[0] === "clip" && rest[1] ? decodeURIComponent(rest[1]) : null; } -const clipOf = (pathname: string, project: string): string | null => benchOf(pathname, project)?.id ?? null; const isPlay = (pathname: string, project: string) => pathname === `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; export default function CutApp({ project, playTop, children }: { project: string; playTop: React.ReactNode; children: React.ReactNode }) { @@ -92,9 +83,6 @@ export default function CutApp({ project, playTop, children }: { project: string q.set("project", project); q.set("clip", id); q.set("order", "cut"); - // A take's bench (its own timeline): the take's clip, its saves into the take's patch. - const walkTake = benchOf(u.pathname, project)?.take; - if (walkTake) q.set("walkTake", walkTake); return fetch(`/api/report/bench?${q.toString()}`, { cache: "no-store" }).then(async (r) => ({ ok: r.ok, status: r.status, body: (await r.json().catch(() => ({}))) as Bench & { error?: string } })); }, [project], diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -17,7 +17,7 @@ import { AddClipToggle } from "../AddClip"; import { Advanced, Options } from "@/components/ui/disclosure"; import PronunciationPanel from "../PronunciationPanel"; import AddPosts from "../AddPosts"; -import { LintButton } from "../TakeTools"; +import { ImportItems, LintButton } from "../TakeTools"; import TightWindowsPanel from "./TightWindowsPanel"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { Fragment } from "react"; @@ -38,6 +38,9 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/ import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; import IntroRow from "./IntroEditor"; +import RemovedClips, { type RemovedRow } from "./RemovedClips"; +import { readRemoved, removedOutOfCut } from "@/lib/report/manifest.mjs"; +import { rejectReasonOf } from "@/lib/report/rejectReasons.mjs"; // The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector. import { InspectorToggle, WhenOpen } from "../inspector/shared"; import TitleInspector from "../inspector/TitleInspector"; @@ -64,6 +67,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor verdict: "confirmed" | "incorrect" | "rejected" | "unreviewed"; }[]; const clips = entries.filter((e) => e.kind === "clip"); + // The clips taken out on record and still out (removed.json), each with Restore (un-reject). + const removed: RemovedRow[] = (removedOutOfCut(await readRemoved(project.dir), m) as Record<string, unknown>[]).map((r) => ({ + id: String(r.id), + channel: typeof r.channel === "string" ? r.channel : null, + video: typeof r.video === "string" ? r.video : null, + start: typeof r.start === "number" ? r.start : null, + end: typeof r.end === "number" ? r.end : null, + why: rejectReasonOf(String(r.reason ?? ""))?.label ?? String(r.reason ?? "removed"), + note: typeof r.note === "string" ? r.note : typeof r.correction === "string" ? r.correction : null, + when: typeof r.when === "string" ? r.when : null, + })); // The walk's ★ clips, as trailer beats (lib/report/trailerCandidates.mjs). const candidates = trailerCandidates(m); // How much of the cut has been walked. One definition, shared with the bench @@ -463,6 +477,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {!postsFirst && <AddPosts project={project.id} channels={postChannels} />} {/* Check before render, on the cut itself (umtool lint <p>): the build's lint and the files its posts name. */} {entries.length > 0 && <LintButton project={project.id} />} + {/* Items of another project into the draft (umtool timeline <p> import-item): cloned, their files linked in. */} + <ImportItems project={project.id} /> {/* A montage's instances, ruled by ear before a render (release 34). */} {montage.length > 0 && ( <Link @@ -635,6 +651,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </section> )} + <RemovedClips project={project.id} rows={removed} /> + {/* --- corrections ------------------------------------------------ */} {/* Not a decision and not a defect in the CUT: a correction says the diff --git a/umtool/components/projects/report/RemovedClips.tsx b/umtool/components/projects/report/RemovedClips.tsx @@ -0,0 +1,82 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { clipBenchHref } from "@/lib/hrefs"; +import { announceManifestChanged, refusalOf, timelineOp } from "../timelineApi"; + +// THE REMOVED LIST (the Cut tab): the clips taken out on record (removed.json: Reject, Wrong speaker) that are +// still out of the cut, newest first, each with Restore -- un-reject (lib/report/manifest.mjs restoreRemoved): +// the clip back as the newest revision holding it had it, at its old place, every later write kept. The CLI +// twin is `umtool timeline <p> removed` and `restore <id>`. + +export type RemovedRow = { + id: string; + channel: string | null; + video: string | null; + start: number | null; + end: number | null; + why: string; + note: string | null; + when: string | null; +}; + +export default function RemovedClips({ project, rows }: { project: string; rows: RemovedRow[] }) { + const router = useRouter(); + const [busy, setBusy] = useState<string | null>(null); + const [said, setSaid] = useState<{ id: string; ok: boolean; text: string } | null>(null); + const restore = async (id: string) => { + setBusy(id); + setSaid(null); + // No token: a restore is an insert, never a rollback, so a write since this page read the cut is kept, not refused. + const res = await timelineOp(project, null, "restore", { id }); + setBusy(null); + if (!res.ok) { + setSaid({ id, ok: false, text: refusalOf(res) }); + return; + } + const j = res.json as { at?: number; notPutBack?: string[] }; + const left = Array.isArray(j.notPutBack) && j.notPutBack.length ? ` Not put back: ${j.notPutBack.join("; ")}.` : ""; + setSaid({ id, ok: true, text: `${id} is back in the cut at ${j.at}.${left}` }); + announceManifestChanged(project); + router.refresh(); + }; + if (!rows.length && !said) return null; + return ( + <section data-removed-clips="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <h2 className="micro mb-1.5">removed from the cut — {rows.length}</h2> + {rows.length > 0 && ( + <ul className="space-y-1"> + {rows.map((r) => ( + <li key={r.id} data-removed-clip={r.id} className="flex flex-wrap items-baseline gap-x-2 text-[12px] leading-snug"> + <Link href={clipBenchHref(project, r.id)} className="ink-link font-mono text-[11px]"> + {r.id} + </Link> + <span className="text-[11px] text-[var(--color-dim)]"> + {r.channel ?? "?"}/{r.video ?? "?"} @ {r.start ?? "?"}–{r.end ?? "?"} + </span> + <span data-removed-why=""> + {r.why} + {r.note ? `: ${r.note}` : ""} + </span> + {r.when && <span className="text-[11px] text-[var(--color-dim)]">{r.when.slice(0, 10)}</span>} + <Button type="button" size="sm" variant="outline" className="ml-auto" data-removed-restore={r.id} disabled={busy !== null} onClick={() => void restore(r.id)}> + {busy === r.id ? "Restoring…" : "Restore"} + </Button> + </li> + ))} + </ul> + )} + {said && ( + <p role="status" data-removed-said={said.ok ? "ok" : "refused"} className={`mt-1 text-[12px] ${said.ok ? "" : "text-[var(--color-bad)]"}`}> + {said.text} + </p> + )} + <p className="mt-1.5 text-[11px] text-[var(--color-dim)]"> + <code className="font-mono">umtool timeline {project} restore &lt;id&gt;</code> + </p> + </section> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -104,7 +104,7 @@ Inbox cannot disagree about what is wrong with one. | `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` | | `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | -| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | +| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `import-item <src>:<item>[,…]` clones items of another project INTO THE DRAFT, as `take --import-item` does into a take (their files hard-linked in, placed `--after`/`--before` an entry or by date, again: updated in place or unchanged; the Cut tab's **Add items from another project**); `removed` lists the clips on that record still out of the cut, and `restore <id>` un-rejects one — the entry from the newest revision that holds it (claim, quote, cite and edges as they were) at its old place (after the entry before it there, else before the one after), every later write kept, an undo point first, and what its removal re-anchored or dropped listed as `not put back:` (the Cut tab's **Removed** list, **Restore**); `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | | `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo \| insert <spec> --after <id>\|-]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it. `insert` puts a clip (`<channel>/<video>@<start>-<end>`) into the take only (`takeEdit.mjs insertTakeEntry`) -- the app's **+ Add a clip to <take> only** on the take walk page, and Play's **+ Add a clip here** on a take with its own timeline | @@ -309,6 +309,9 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `timeline <project> duplicate <id> [--at N]` | an entry twice | form · *draft* | | `timeline <project> reject <id> not-matching\|wrong-speaker\|irrelevant\|repeats\|weak\|privacy\|other [--note NOTE]` | an entry rejected and removed, on the record | form · *draft* | | `timeline <project> wrong-speaker <id> [--correction CORRECTION]` | an entry removed: the wrong speaker | form · *draft* | +| `timeline <project> import-item <refs>… [--after AFTER] [--before BEFORE] [--as AS] [--dry-run]` | items of another project into the draft, their files linked in | form · *draft* | +| `timeline <project> removed` | the clips removed on record and still out of the cut | form · *project* | +| `timeline <project> restore <id>` | un-reject: a removed clip back as it was, at its old place | form · *draft* | | `timeline <project> post <post>` | a post added, or the one with its id replaced | form · *draft* | | `timeline <project> post-remove <id>` | a post out of the cut | form · *draft* | | `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -304,7 +304,9 @@ that mentions the seizure in question and one before it. The Marks box is on eve mark's); **Remove** one; **Clear** them all. - **From a terminal:** `umtool set <p> <clip> mark.add=<verdict>[@<sec>]` (or a JSON object with knobs), `mark.remove=<id>`, `mark.verdict=<verdict> [--mark <id>]`, `marks='[…]'` (all; `marks=` none); the `claim.*` keys - set the first mark's knobs, or `--mark <id>`'s. `umtool show` prints a clip's marks (`--json`: `marks`, each with + set the first mark's knobs, or `--mark <id>`'s. `claim=` (or `claim=none`) takes the clip's claim pin off — every + mark it carries — on the draft; a version's clip is cleared after **Open in draft** (`umtool takes open <p> <v>`), + so `claim= --take <v>` is refused and says so. `umtool show` prints a clip's marks (`--json`: `marks`, each with `stampsOn`). - **On a teaser** (a post shown as a text card; lane counter-zero): a teaser carries marks as a clip does — stamped over the card, counted, validated — with `at` in seconds from the CARD's start (after a dip's black), 0 to its @@ -718,6 +720,10 @@ in `removed.json` — or **Reject, keep in place** writes the verdict only, for it is the same flow with its reason preset ([report-video.md](report-video.md#verdict--what-the-walk-said)). Not on a take. +| knob | UI | CLI | route | +|---|---|---|---| +| un-reject: a removed clip back — the entry from the newest revision that holds it (claim, quote, cite, edges as they were), at its old place, every later write kept; what its removal re-anchored or dropped is said, not put back | the Cut tab's **removed from the cut** list (the clips on record in `removed.json` still out), **Restore** | `umtool timeline <p> removed` (the list), `umtool timeline <p> restore <id>` | `POST /api/report/timeline {op: "restore", id}` | + **Play and the clip bench are one app.** **Edit this clip** (E) opens the bench IN PLACE: Play is hidden and paused but never unmounted, so its composed deck, decoded sound, measured edges, the strip's zoom and the take stay as they were (`components/projects/cutApp/CutApp.tsx`; the bench's data is `GET /api/report/bench`, the same function its own @@ -1620,6 +1626,7 @@ has the recipe. | | From a terminal | What it writes | |---|---|---| | a draft from another take | `umtool take <p> --id <t> --draft --from <take> [--label L] [--patch F]` | `takes/<t>/take.json`: that take's style and patch (yours over it); nothing rendered | +| items of another project **into the draft** | `umtool timeline <p> import-item <project>:<item>[,<item>…] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | the same clone into the project's own cut (the draft), one undo point of the project's (`umtool timeline <p> undo`); the Cut tab's Options, **Add items from another project** | | items of another project into the take | `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | the entries cloned (narration, takes, pick, knobs) into the take's timeline, one undo point; their files **hard-linked** into `<p>` (another file at a path: `imports/<source>/…`); authors' pictures the take lacks into its `postAvatars`. Again: `updated` in place, or `unchanged` (no write) | | a post item's knobs, in the take | `umtool posts set-item <p> <item> k=v … --in-take <t>` (or `--take <t>`) | the take's entry; a piece made context or hidden that its read reads is re-joined first, as on the project | | the read's pieces, in the take | `umtool posts roles <p> <item> --set n=role --in-take <t>` | the take's entry's take parts | @@ -1630,9 +1637,10 @@ has the recipe. | an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` | | look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte | -**In umtool** (lane/ui-simplify): a take card's Options have **Check before render** (the lint), **New draft from this -take** (the next free `<take>-d<n>`) and **Add items from another project** (the project, the items, by date or -after/before an entry; **Preview** is `--dry-run`, then **Import into <take>**); New take has **Save as a draft**. The +**In umtool** (lane/ui-simplify): a take card's Options have **Check before render** (the lint) and **New draft from this +take** (the next free `<take>-d<n>`); **Add items from another project** is the Cut tab's, into the DRAFT (E1, 9 Nov: +the project, the items, by date or after/before an entry; **Preview** is `--dry-run`, then **Import into the draft** — +`umtool timeline <p> import-item`; a take's patch is the terminal's `take --import-item`); New take has **Save as a draft**. The post bench's take-only scope and the take walk's **+ Add a clip to <take> only** are RETIRED (umtool redesign L3: every UI edit lands in the draft — open the take in the draft first); their writes are the terminal's (`--in-take`, `umtool timeline <p> --take <t> insert <spec> --after <id>`, `POST /api/report/post-narration {…, inTake}`). diff --git a/umtool/e2e/fixtures/ingredient-rail-fixture.mjs b/umtool/e2e/fixtures/ingredient-rail-fixture.mjs @@ -22,6 +22,7 @@ // Synthetic, like every fixture. import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; +import { archiveMomentUrl } from "umtool-report-to-video/site-links"; export const RAIL_SITE = "http://127.0.0.1:9"; @@ -58,11 +59,18 @@ export function makeIngredientRailFixture({ reports, channels, manifest, cachedW write(rv, "transcript.cues.json", JSON.stringify({ version: 2, source: "whisper", id: "v7rembd1", title: "The Rumble Rail Recording", duration: 120, cues: [{ start: 0, end: 4, text: "rumble." }] })); // ── the projects ── - const origin = { siteOrigin: RAIL_SITE, channelSlug: "railchan" }; - const a = manifest("rail-a", "The Rail A Fixture", origin, [ + // provenance.siteOrigin stays public-looking (a loopback origin is a BLOCKING decision, projects.spec), and each + // clip's citeUrl names RAIL_SITE explicitly -- the moment URL the origin would have derived, on the placeholder. + const PUBLIC = "https://archive.example"; + const origin = { siteOrigin: PUBLIC, channelSlug: "railchan" }; + const cited = (m) => { + for (const e of m.timeline) e.citeUrl = archiveMomentUrl({ ...e, channel: e.channel ?? m.provenance.channelSlug }, m.provenance, e.start ?? 0, { origin: RAIL_SITE }); + return m; + }; + const a = cited(manifest("rail-a", "The Rail A Fixture", origin, [ { type: "clip", id: "ra1", video: "railvid", start: 12, end: 20, cite: 12, section: 0, quote: "the rail recording says line 2." }, { type: "clip", id: "ra2", video: "railvid", start: 100, end: 110, cite: 100, section: 0, quote: "the rail recording says line 17." }, - ]); + ])); const aDir = path.join(reports, "rail-a"); write(aDir, "video.manifest.json", a); const base = manifest("rail-a", "The Rail A Fixture", origin, [a.timeline[0]]); @@ -74,10 +82,10 @@ export function makeIngredientRailFixture({ reports, channels, manifest, cachedW write(aDir, "quote-check.json", { version: 1, checkedAt: "2026-11-06T12:00:00.000Z", clips: { ra1: { status: "ok", offset: 0.02, against: "cues", cut: { from: 12, to: 20 }, quote: "the rail recording says line 2." } } }); const bDir = path.join(reports, "rail-b"); - write(bDir, "video.manifest.json", manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }])); + write(bDir, "video.manifest.json", cited(manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }]))); write(path.join(bDir, "out"), "links.json", { version: 1, checkedAt: "2026-11-07T00:00:00.000Z", fetched: 1, origins: {}, links: [{ clip: "rb1", url: `${RAIL_SITE}/?v=railchan%2Frailvid&t=15`, state: "ok", origin: RAIL_SITE }] }); const rDir = path.join(reports, "rail-r"); - write(rDir, "video.manifest.json", manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: RAIL_SITE, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }])); + write(rDir, "video.manifest.json", cited(manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: PUBLIC, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }]))); return { aDir, bDir, rDir }; } diff --git a/umtool/e2e/fixtures/post-narration-fixture.mjs b/umtool/e2e/fixtures/post-narration-fixture.mjs @@ -13,7 +13,7 @@ // it back before each test. // // Synthetic, like every fixture. -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { spawnSync } from "node:child_process"; import path from "node:path"; @@ -22,6 +22,45 @@ const ff = (args) => { if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); }; +/** + * Every file the fixture writes under its narration/, relative to it. Nothing + * else under narration/ is the fixture's: it is a take, a part, a cache or a + * trash a spec made. + */ +export const POST_NARRATION_OWN_FILES = ["posts/11/take-1.orpheus-zac.wav", "posts/11/take-1.orpheus-zac.wav.heard.json"]; + +/** + * Put the fixture's narration/ back to what it built, removing what any spec + * left there. Several specs share this project (long-reads writes a take-7 of + * p-11 and re-reads it into more), and a new take is numbered past every + * take-N on disk (report-to-video/post-narration.mjs nextTakeNumber) -- so + * without this, which spec ran first decided post-narration's take numbers. + * @param {string} dir the project's directory + */ +export function resetPostNarrationFiles(dir) { + const root = path.join(dir, "narration"); + const keep = new Set(POST_NARRATION_OWN_FILES.map((f) => path.join(root, f))); + const prune = (d) => { + let entries = []; + try { + entries = readdirSync(d, { withFileTypes: true }); + } catch { + return false; + } + let kept = false; + for (const e of entries) { + const p = path.join(d, e.name); + if (e.isDirectory() && !e.isSymbolicLink()) { + if (prune(p)) kept = true; + else rmSync(p, { recursive: true, force: true }); + } else if (keep.has(p)) kept = true; + else rmSync(p, { force: true }); + } + return kept; + }; + prune(root); +} + /** @param {{ reports: string, deckManifest: Function }} o */ export function makePostNarrationFixture({ reports, deckManifest }) { const name = "post-narration-fixture"; diff --git a/umtool/e2e/long-reads.spec.ts b/umtool/e2e/long-reads.spec.ts @@ -4,6 +4,7 @@ import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "n import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { resetPostNarrationFiles } from "./fixtures/post-narration-fixture.mjs"; // --------------------------------------------------------------------------- // LONG READS (operator, 4 Nov, a 6.5-minute post): a read's parts RE-TIMED with @@ -38,6 +39,13 @@ const picked = () => { test.beforeAll(() => { if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); }); +// The project is shared (post-narration, post-captions, picture-replies, thread-* read it after this file): leave +// it as the fixture built it -- its manifest, and no take-7 or re-read of p-11 on disk to number their takes past. +test.afterAll(() => { + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + resetPostNarrationFiles(DIR); +}); test.beforeEach(() => { test.setTimeout(120_000); copyFileSync(`${MANIFEST}.pristine`, MANIFEST); diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -5,6 +5,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSyn import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { resetPostNarrationFiles } from "./fixtures/post-narration-fixture.mjs"; // --------------------------------------------------------------------------- // NARRATED POST ITEMS (report-to-video/post-narration.mjs; knobs.md, "A narrated @@ -47,12 +48,10 @@ test.beforeEach(() => { copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); - for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav", "take-2.convert-zac.wav", "take-3.convert-zac.wav", "take-2.pause-orpheus.wav", "take-2.revoice-orpheus.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true }); - // The parts cache a re-voice's phrase lands in (the fixture has none of its own). - rmSync(path.join(DIR, "narration", "parts-cache"), { recursive: true, force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true }); + // narration/ back to the fixture's own two files: this test's takes, parts, the parts cache a re-voice's phrase + // lands in, .trash and .recording-* -- and ANOTHER spec's (long-reads leaves a take-7 of p-11, and a new take is + // numbered past every take-N on disk, so the run order used to decide this spec's take numbers). + resetPostNarrationFiles(DIR); }); const root = (page: Page) => page.locator("[data-play-cut]"); diff --git a/umtool/e2e/shell.spec.ts b/umtool/e2e/shell.spec.ts @@ -246,3 +246,14 @@ test("the head glides, and does not under reduced motion", async ({ page }) => { await expect(page.locator("[data-lit-list] .lit-head[data-placed]").first()).toBeAttached(); expect(await duration()).toMatch(/^0s/); }); + +test("every page links the umtool icon -- the parent mark lit in Signal -- and it is served", async ({ page, request }) => { + await page.goto(urls.homeHref()); + const href = await page.locator("head link[rel=icon][type='image/svg+xml']").first().getAttribute("href"); + expect(href).toMatch(/^\/icon\.svg/); + const res = await request.get(href!); + expect(res.status()).toBe(200); + expect(res.headers()["content-type"]).toContain("image/svg+xml"); + // Signal's on-dark value is the lit line (common/lib/brand.ts ACCENTS.signal.onDark). + expect(await res.text()).toContain('fill="#5fa8a0"'); +}); diff --git a/umtool/e2e/take-items.spec.ts b/umtool/e2e/take-items.spec.ts @@ -4,6 +4,7 @@ import { readFileSync, statSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // A TAKE'S OWN ITEMS (umtool/docs/cli.md, "Edit a take, not the project"): @@ -103,3 +104,32 @@ test("Play on the take plays the imported item: its row between p-1 and p-3, nar await page.goto(urls.playHref(P, { bare: true })); await expect(page.locator("[data-play-row]")).toHaveCount(2); }); + +test("the Cut tab's Add items from another project imports INTO THE DRAFT (L3): Preview writes nothing, Import adds p-2 to the project's cut, its files linked; the source untouched", async ({ page }) => { + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut"); + const box = page.locator('[data-take-import="draft"]'); + await box.locator('[data-action="import-open"]').click(); + await box.locator("[data-import-source]").fill(S); + await box.locator("[data-import-items]").fill("p-2"); + await box.locator('[data-action="import-preview"]').click(); + await expect(page.locator('[data-import-result="plan"] [data-import-row="p-2"]')).toContainText("p-2 added"); + // REMOVED_LIST_SHOTS=<dir> (the lane's shots): the draft import at 1366×768. + if (process.env.REMOVED_LIST_SHOTS) { + await page.setViewportSize({ width: 1366, height: 768 }); + await box.scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(process.env.REMOVED_LIST_SHOTS, "draft-import.png") }); + } + expect(text(DIR), "a preview writes nothing").toBe(projectBefore); + await expect(box.locator('[data-action="import-go"]')).toHaveText("Import into the draft"); + await box.locator('[data-action="import-go"]').click(); + await expect(page.locator('[data-import-result="done"]')).toHaveAttribute("data-import-exit", "0"); + await expect.poll(() => (JSON.parse(text(DIR)).timeline as Entry[]).map((e) => e.id)).toEqual(["p-1", "p-2", "p-3"]); + expect(statSync(path.join(DIR, "narration/posts/2/take-1.orpheus-thread.wav")).ino).toBe(statSync(path.join(SRC, "narration/posts/2/take-1.orpheus-thread.wav")).ino); + expect(text(SRC)).toBe(sourceBefore); + // The take cards no longer carry it: a take is opened in the draft first. + await page.goto(urls.takesHref(P)); + await openPanel(page, "options", "take-card"); + await expect(page.locator(`[data-take-tools="${TAKE}"]`)).toBeVisible(); + await expect(page.locator("[data-take-import]")).toHaveCount(0); +}); diff --git a/umtool/e2e/take-walk.spec.ts b/umtool/e2e/take-walk.spec.ts @@ -58,6 +58,20 @@ test("the Takes page: the draft take and the saved version each Play and Open in await expect(page.locator('[data-take="v1"] [data-take-draft="v1"]')).toContainText("saved version — not rendered"); }); +test("the bench's data is the draft's whatever a take is named: a take's clip is not benched (its take paths are gone, E1)", async ({ request }) => { + // t01a is the take's, not the draft's: once the bench walked the take with `walkTake`; now it is a 404. + const theirs = await request.get(`/api/report/bench?project=${encodeURIComponent(PROJECT)}&clip=t01a&walkTake=${TAKE}`); + expect(theirs.status()).toBe(404); + const ours = await request.get(`/api/report/bench?project=${encodeURIComponent(PROJECT)}&clip=w01&walkTake=${TAKE}&take=${TAKE}&from=play`); + expect(ours.status()).toBe(200); + const j = (await ours.json()) as { data: { take?: unknown; fromPlay: { take: string } }; top: { kind: string } }; + expect(j.data.take).toBeUndefined(); + expect(j.top.kind).toBe("Clip bench"); + // `take` with from=play is only the take Play was on: Back keeps it, edits go to the draft. + expect(j.data.fromPlay.take).toBe(TAKE); + expect(manifestText()).toBe(masterBefore); +}); + test("the walk's old address asks to open the take in the draft; the walk's data route still reads the take", async ({ page, request }) => { await page.goto(urls.takeWalkHref(PROJECT, TAKE)); const ask = page.locator(`[data-open-draft="${TAKE}"]`); diff --git a/umtool/e2e/timeline-edit.spec.ts b/umtool/e2e/timeline-edit.spec.ts @@ -36,6 +36,7 @@ test.beforeEach(() => { copyFileSync(PRISTINE, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); + rmSync(path.join(DIR, "removed.json"), { force: true }); }); /** The project page on the tab that holds `name`: the timeline (the Cut), or the on-screen panel's structure editors (Build). */ @@ -157,3 +158,28 @@ test("a post added, then removed; the fact-check's labels once the deck is on", .poll(() => ((manifest().render.chrome as { factcheck?: { tally?: unknown } }).factcheck ?? {}).tally) .toEqual({ showAt: "first" }); }); + +test("the Removed list: a rejected clip is listed and Restore puts it back as it was, at its old place", async ({ page, request }) => { + // a03 (a02 carries the post p1: rejecting it is refused by the build). + const a03 = manifest().timeline.find((e) => e.id === "a03")!; + const rej = await request.post("/api/report/timeline", { data: { project: PROJECT, op: "reject", id: "a03", reason: "repeats", note: "covered by a01" } }); + expect(rej.ok(), await rej.text()).toBe(true); + await expect.poll(order).toEqual(["t1", "a01", "a02"]); + await open(page); + const list = page.locator("[data-removed-clips]"); + await expect(list.locator("[data-removed-clip]")).toHaveCount(1); + await expect(list.locator('[data-removed-clip="a03"] [data-removed-why]')).toContainText("covered by a01"); + // REMOVED_LIST_SHOTS=<dir>: the list at a laptop's 1366×768. + if (process.env.REMOVED_LIST_SHOTS) { + await page.setViewportSize({ width: 1366, height: 768 }); + await list.scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(process.env.REMOVED_LIST_SHOTS, "removed-list.png") }); + } + await list.locator('[data-removed-restore="a03"]').click(); + await expect(list.locator('[data-removed-said="ok"]')).toContainText("a03 is back in the cut at 3"); + await expect.poll(order).toEqual(["t1", "a01", "a02", "a03"]); + // The entry as it was before the reject: no verdict, every field it had. + expect(manifest().timeline.find((e) => e.id === "a03")).toEqual(a03); + await expect.poll(() => shownOrder(page)).toEqual(["t1", "a01", "a02", "a03"]); + await expect(page.locator("[data-removed-clip]")).toHaveCount(0); +}); diff --git a/umtool/lib/brandIcon.test.ts b/umtool/lib/brandIcon.test.ts @@ -0,0 +1,17 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { markSvg } from "yt-dlp-transcript-common/lib/brand"; +import { MEDIA_MARK_PALETTE } from "yt-dlp-transcript-common/lib/brandMedia"; + +// umtool/app/icon.svg is umtool's favicon (Next's app/icon.svg file convention +// links it from every page). umtool makes the media, so its icon is the parent +// mark lit in Signal -- mark M2, the slate ground and dim of +// ICON_PALETTES.archilyzer with Signal's on-dark lit line -- and it must stay +// the mark: markSvg is the geometry, this file a copy of it. Regenerate with +// markSvg(MEDIA_MARK_PALETTE) if this fails. +test("app/icon.svg is markSvg(MEDIA_MARK_PALETTE), byte for byte", () => { + const file = fileURLToPath(new URL("../app/icon.svg", import.meta.url)); + assert.equal(readFileSync(file, "utf8").trimEnd(), markSvg(MEDIA_MARK_PALETTE)); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -907,7 +907,7 @@ export const GROUPS = [ ["`timeline <project> teaser-insert [--at start\\|end \\| --after <id> \\| --before <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"] [--hold S] [--line …] \\| --lines-json <json\\|@file> [--json]`", "a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], ["`timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\\|@file>` · `undo`", - "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"], + "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `import-item <src>:<item>[,…]` clones items of another project INTO THE DRAFT, as `take --import-item` does into a take (their files hard-linked in, placed `--after`/`--before` an entry or by date, again: updated in place or unchanged; the Cut tab's **Add items from another project**); `removed` lists the clips on that record still out of the cut, and `restore <id>` un-rejects one — the entry from the newest revision that holds it (claim, quote, cite and edges as they were) at its old place (after the entry before it there, else before the one after), every later write kept, an undo point first, and what its removal re-anchored or dropped listed as `not put back:` (the Cut tab's **Removed** list, **Restore**); `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"], ["`timeline <project> insert (--to-section N \\| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]`", "a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press))"], ["`timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\\|@file\\|id…>`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -380,6 +380,11 @@ function timeline() { tl("duplicate", "draft", "an entry twice", [id(), num("--at")]), tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })]), tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })]), + tl("import-item", "draft", "items of another project into the draft, their files linked in", [ + many("refs", { required: true, item: "ref", help: "<project>:<item>[,<item>…], one per line" }), opt("--after"), opt("--before"), opt("--as"), dry(), + ]), + tl("removed", "project", "the clips removed on record and still out of the cut", []), + tl("restore", "draft", "un-reject: a removed clip back as it was, at its old place", [arg("id", { help: "the removed clip's id (timeline removed lists them)" })]), tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]), tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]), tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]), diff --git a/umtool/lib/e2eEnvGuard.mjs b/umtool/lib/e2eEnvGuard.mjs @@ -0,0 +1,65 @@ +// The umtool e2e suite's refusal of an inherited data root. +// +// Playwright hands the app server, the editor stub and every CLI a spec spawns +// this shell's whole environment. The config confines what it sets (the +// fixture's SONG_DIR, CHANNELS_DIR, ...), but a variable it does NOT set wins +// by inheritance: REPORTS_DIR is read before the fixture's SONG_REPORTS_DIR +// (lib/paths.mjs REPORTS_ROOT), and a spec's own spawn of a CLI with +// `{ ...process.env }` carries CHANNELS_DIR and SONG_DIR along. On 2 Nov a run +// that inherited them wrote fixture state into real projects under ~/reports. +// +// So a data root in the environment is refused, loudly and by name, unless it +// already points inside the suite's own fixture. Unset (or empty) is the +// normal case; the gate scripts `unset REPORTS_DIR CHANNELS_DIR SONG_DIR`. +// +// SONG_DIR IS NOT ONE OF THEM. It is the documented way to run the song-data +// specs against a copy (AGENTS.md; e2e/fixtures/make-fixture.mjs), and only the +// fixture builder reads it -- READ-ONLY, to derive the empty-state copy and link +// the heavy audio; the app server is given the fixture's own SONG_DIR after it. +import { realpathSync } from "node:fs"; +import path from "node:path"; + +/** The variables that name a data root the suite must never inherit. */ +export const INHERITED_DATA_ROOTS = ["REPORTS_DIR", "CHANNELS_DIR"]; + +/** A path with its links resolved (a worktree reached through a symlinked parent), else as given. */ +const real = (p) => { + const abs = path.resolve(p); + try { + return realpathSync(abs); + } catch { + // Missing: resolve the nearest parent that exists, and keep the rest as written. + const parent = path.dirname(abs); + return parent === abs ? abs : path.join(real(parent), path.basename(abs)); + } +}; + +const inside = (p, root) => { + const rel = path.relative(real(root), real(p)); + return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)); +}; + +/** + * Every inherited data root that is not the fixture's, as `{ name, value }`. + * @param {Record<string, string | undefined>} env + * @param {string} fixture the suite's fixture directory (e2e/.e2e-song) + */ +export function foreignDataRoots(env, fixture) { + const root = fixture; + return INHERITED_DATA_ROOTS.filter((name) => { + const v = env[name]; + return typeof v === "string" && v.trim() !== "" && !inside(v, root); + }).map((name) => ({ name, value: env[name] })); +} + +/** The refusal, naming each variable; null when there is nothing to refuse. */ +export function dataRootRefusal(env, fixture) { + const bad = foreignDataRoots(env, fixture); + if (!bad.length) return null; + return ( + `umtool e2e refuses to run: ${bad.map((b) => `${b.name}=${b.value}`).join(", ")} ` + + `${bad.length === 1 ? "is" : "are"} set in this shell and not the suite's fixture (${path.resolve(fixture)}). ` + + `The app server and the CLIs the specs spawn inherit it and would read and write real data there ` + + `(2 Nov: a run wrote fixture state into ~/reports). Unset it: \`unset ${bad.map((b) => b.name).join(" ")}\`.` + ); +} diff --git a/umtool/lib/e2eEnvGuard.test.mjs b/umtool/lib/e2eEnvGuard.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { dataRootRefusal, foreignDataRoots } from "./e2eEnvGuard.mjs"; + +const FIX = "/w/umtool/e2e/.e2e-song"; + +test("nothing set, or set empty, is the normal case", () => { + assert.equal(dataRootRefusal({}, FIX), null); + assert.equal(dataRootRefusal({ REPORTS_DIR: "", CHANNELS_DIR: " " }, FIX), null); +}); + +test("a root inside the fixture is the suite's own, and passes", () => { + assert.equal(dataRootRefusal({ CHANNELS_DIR: `${FIX}/channels`, REPORTS_DIR: FIX }, FIX), null); +}); + +test("an inherited REPORTS_DIR or CHANNELS_DIR anywhere else is refused, naming each variable", () => { + const env = { REPORTS_DIR: "/home/u/reports", CHANNELS_DIR: "/home/u/transcripts/channels", HOME: "/home/u" }; + assert.deepEqual(foreignDataRoots(env, FIX).map((b) => b.name), ["REPORTS_DIR", "CHANNELS_DIR"]); + const msg = dataRootRefusal(env, FIX); + assert.match(msg, /REPORTS_DIR=\/home\/u\/reports/); + assert.match(msg, /CHANNELS_DIR=\/home\/u\/transcripts\/channels/); + assert.match(msg, /unset REPORTS_DIR CHANNELS_DIR/); +}); + +test("SONG_DIR elsewhere is accepted: the documented copy the fixture builder reads from, and nothing else sees", () => { + assert.equal(dataRootRefusal({ SONG_DIR: "/elsewhere/song-copy/data" }, FIX), null); + assert.deepEqual(foreignDataRoots({ SONG_DIR: "/elsewhere", REPORTS_DIR: "/home/u/reports" }, FIX).map((b) => b.name), ["REPORTS_DIR"]); +}); + +test("a sibling whose name merely starts with the fixture's is not inside it", () => { + assert.deepEqual(foreignDataRoots({ CHANNELS_DIR: `${FIX}-other/channels` }, FIX).map((b) => b.name), ["CHANNELS_DIR"]); + assert.deepEqual(foreignDataRoots({ REPORTS_DIR: `${FIX}/../reports` }, FIX).map((b) => b.name), ["REPORTS_DIR"]); +}); + +test("a worktree reached through a symlinked parent is its own fixture, either way round", async () => { + const root = await mkdtemp(path.join(tmpdir(), "e2e-guard-")); + try { + const realFix = path.join(root, "real", "umtool", ".e2e-song"); + await mkdir(path.join(realFix, "channels"), { recursive: true }); + await symlink(path.join(root, "real"), path.join(root, "link")); + const viaLink = path.join(root, "link", "umtool", ".e2e-song"); + assert.equal(dataRootRefusal({ CHANNELS_DIR: path.join(viaLink, "channels") }, realFix), null); + assert.equal(dataRootRefusal({ CHANNELS_DIR: path.join(realFix, "channels"), REPORTS_DIR: path.join(viaLink, "reports-not-yet") }, viaLink), null); + assert.deepEqual(foreignDataRoots({ REPORTS_DIR: path.join(root, "real", "elsewhere") }, viaLink).map((b) => b.name), ["REPORTS_DIR"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -38,6 +38,7 @@ import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; import { walkProjects } from "../projects/walk.mjs"; export const USAGE_INDEX_FORMAT = "umtool-usage-index"; @@ -148,7 +149,9 @@ export async function buildUsageIndex({ reportsRoot, channelsDir, previous = nul return dir; }; - const projects = (await walk(reportsRoot)).filter((p) => p.kind === "report-video" || p.kind === undefined); + // A project whose kind makes takes is one whose manifests hold clips (the registry says which; a kind id is + // never written here -- e2e/projects.spec.ts). A walk that reports no kind (a test's) is read as one. + const projects = (await walk(reportsRoot)).filter((p) => p.kind === undefined || kindMakesTakes(p.kind)); const files = {}; let parsed = 0; let reused = 0; diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -1,5 +1,5 @@ import { notFound } from "next/navigation"; -import { projectsHref, clipBenchHref, ingredientHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; +import { projectsHref, clipBenchHref, ingredientHref, playHref } from "@/lib/hrefs"; import type { ClipBenchData } from "@/components/projects/ClipBench"; import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell"; import { @@ -27,6 +27,10 @@ import type { ProjectRef } from "@/lib/project-types"; // `order: "cut"` (the bench opened inside Play): p / n step along the CUT -- // the reel strip's neighbours, every clip judged or not -- not the walk's // recording order; the walk is a different journey. +// +// The DRAFT's clips only (L3): a take's clip is never benched -- its old +// address (`…/takes/<t>/clip/<id>`) is the Open in draft page -- so there is +// no take here (the take walk's paths went with E1, 9 Nov). /** BenchTop's props, as data (the server page and the app both draw it). */ export type BenchTopSpec = { @@ -46,18 +50,18 @@ export type BenchTopSpec = { }; /** - * @returns null when the clip is not a clip of the cut (or the take) -- the page's 404 + * @returns null when the clip is not a clip of the cut -- the page's 404 */ export async function clipBenchData( project: ProjectRef, clipId: string, - { search = {}, take = null, order = "walk" }: { search?: Record<string, string | undefined>; take?: string | null; order?: "walk" | "cut" } = {}, + { search = {}, order = "walk" }: { search?: Record<string, string | undefined>; order?: "walk" | "cut" } = {}, ): Promise<{ data: ClipBenchData; top: BenchTopSpec } | null> { // `?all=1`: the walk visits every fetched clip, judged or not. const all = search.all === "1"; let walk: Awaited<ReturnType<typeof walkOf>>; try { - walk = await walkOf(project, { take, all }); + walk = await walkOf(project, { all }); } catch { return null; } @@ -95,9 +99,8 @@ export async function clipBenchData( const windows = await windowsFor(project, entry, await projectCache(project, manifest)); // The mtime rides along so a re-render busts the browser's cache: the segment // is written back to the SAME path, and without it the player would keep - // showing the cut from before the edit. A take's clip has none: the - // project's segments are the project's cut. - const seg = take ? null : await segmentFor(project, clipId); + // showing the cut from before the edit. + const seg = await segmentFor(project, clipId); const widest = windows[0] ?? null; const view = widest ? { from: widest.from, to: widest.to } @@ -176,7 +179,7 @@ export async function clipBenchData( endsSentence: entry.endsSentence ?? null, noPunctuation: !!entry.noPunctuation, sourceDuration: entry.duration ?? null, - segment: take ? null : (seg?.rel ?? entry.segment ?? null), + segment: seg?.rel ?? entry.segment ?? null, segmentMtime: seg?.mtimeMs ?? null, // What the header would say with no overrides. Shown beside the fields that // replace it, because "the archive says 2019" is the whole reason `date` @@ -200,7 +203,7 @@ export async function clipBenchData( ).length, cues: cues?.cues ?? [], siblings: siblingsOf(manifest, clipId), - // The project's manifest token, or -- walking a take -- the take's. + // The project's manifest token. token: walk.token, fetchPad: manifest.render?.fetchPad ?? 3, // The widest the fetch route will go. The BUTTON has to know it: it names @@ -225,67 +228,41 @@ export async function clipBenchData( }; // The piece this view belongs to: the article's when an article claims the project (P4a-2). - // Walking a take, Back is the take's walk (its overview), on the Takes page's side. - const back = take ? takeWalkHref(project.id, take, { all }) : await pieceHrefOfProject(project.id, { tab: "cut" }); + const back = await pieceHrefOfProject(project.id, { tab: "cut" }); // ---- opened from Play the cut ("Edit this clip") -------------------------- // // `?from=play` rides every walk link from here (p / n / Confirm's advance), // so "Back to the cut" survives walking on; `at` is only ever the clip Play // was on. Back lands on the PROJECT's cut, positioned by clip id plus the // offset into it -- never by raw cut seconds, which the edit just moved for - // everything after this clip. A take without a timeline of its own plays - // the project's cut, so its Edit lands here and its Back is the project's - // cut too, and the bench says so (`take`). A take WITH its own timeline is - // walked on its own bench (`take`: `…/takes/<take>/clip/<id>?from=play`): - // its saves go into the take's patch, and Back plays that take. + // everything after this clip. An address that names the take Play was on + // (`?take=`) keeps it on Back, and the bench says its edits go to the cut. const fromPlay = search.from === "play"; const withOrder = (h: string) => (order === "cut" ? `${h}${h.includes("?") ? "&" : "?"}order=cut` : h); - const playTake = take && fromPlay ? take : fromPlay && search.take ? search.take : null; + const playTake = fromPlay && search.take ? search.take : null; const atRaw = Number(search.at); const at = fromPlay && Number.isFinite(atRaw) && atRaw > 0 ? atRaw : 0; - const href = (id: string) => - take - ? withOrder(takeClipHref(project.id, take, id, { all, play: fromPlay ? {} : null })) - : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); + const href = (id: string) => withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); data.walkHrefs = { prev: prev ? href(prev) : null, next: next ? href(next) : null, back, - backLabel: take ? `take ${take}` : project.name, + backLabel: project.name, }; - if (take && walk.take) { - const timeline = (manifest.timeline ?? []) as { id: string }[]; - data.take = { - id: take, - label: walk.take.label, - draft: walk.take.draft, - editable: walk.take.editable, - all, - takesHref: takesHref(project.id), - walkHref: takeWalkHref(project.id, take, { all }), - toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }), - clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all, play: fromPlay ? {} : null })])), - at: timeline.findIndex((e) => e.id === clipId), - entries: timeline.length, - }; - } - // `editsTake`: this bench writes the take Play was playing (its own timeline), not the project's cut. - data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake, editsTake: !!take } : null; + data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake } : null; // Walk → Play (the audit's "no way back"): the cut, from this clip. - data.playHere = take || fromPlay ? null : playHref(project.id, { clip: clipId }); + data.playHere = fromPlay ? null : playHref(project.id, { clip: clipId }); // The working cut's name: the bench edits the project's manifest, the latest take is what it was made into. - data.working = take - ? null - : await readWorkingCut(project.dir).catch(() => null); + data.working = await readWorkingCut(project.dir).catch(() => null); const top: BenchTopSpec = { - trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }], - back: { href: back, label: take ? `take ${take}` : project.name }, - kind: take ? "Take walk" : order === "cut" ? "Clip bench · the cut's order" : "Clip bench", + trail: [{ href: projectsHref(), label: "Projects" }], + back: { href: back, label: project.name }, + kind: order === "cut" ? "Clip bench · the cut's order" : "Clip bench", here: clipId, // The walk on a phone draws its own place bar (ClipBench). phone: "hidden", // The head's slot: Back to the cut (from Play), or Play from here. - slot: fromPlay || !take, + slot: true, pos: { index: order === "cut" ? ci + 1 : i + 1, total: order === "cut" ? cutClips.length : clips.length }, prev: prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null, next: next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null, diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -74,7 +74,7 @@ const CH = path.join(ROOT, "channels"); ); await mkdir(DIR, { recursive: true }); await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ - schemaVersion: 1, slug: "voices", title: "Voices", kind: "report-video", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + schemaVersion: 1, slug: "voices", title: "Voices", provenance: { channelsDir: "../channels", channelSlug: "chan" }, render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline, }, null, 2)); await wavOf(path.join(DIR, "narration", "posts", "1", "take-1.orpheus-zac.wav"), VOICE_A, 1.5); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -58,7 +58,7 @@ const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect", "vertical.crops"]); export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]); const SET_KEYS = [ - ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, + "claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", // The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post. ...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS, @@ -71,7 +71,9 @@ export const SET_USAGE = [ " (read from the last clip carrying the claim); claim.hold s (0.5–10); claim.stamp true|false;", " claim.count 1–99; claim.label ≤ 20 chars; claim.eventDate YYYY-MM-DD, the day the event it counts", " happened when not the clip's (a deck claim's window dates it so: render.chrome.deck.claims).", - " The claim.* keys set the clip's first mark, or --mark <id>'s.", + " The claim.* keys set the clip's first mark, or --mark <id>'s. `claim=` (or claim=none) takes the clip's claim", + " pin off -- every mark it carries, as marks= does -- on the DRAFT; a version's clip is opened in the draft first", + " (umtool takes open <p> <v>), so claim= with --take is refused.", " Marks (a clip may carry up to 8, each its own stamp and count): mark.add=<verdict>[@<sec>] adds one", " (the verdict by name or by this cut's label, e.g. Episodes@190.2; a JSON object for its knobs too);", " mark.remove=<id>; mark.verdict=<verdict> (the first mark's, or --mark <id>'s; every clip carrying", @@ -226,6 +228,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const markChanges = []; /** @type {Record<string, unknown>} */ const entryPatch = {}; + let claimOff = false; for (const [key, value] of parseAssignments(rest)) { if (!SET_KEYS.includes(key)) throw new CliError(`${key} is not a clip knob (${SET_KEYS.join(", ")})`); if (key === "layout") { @@ -273,6 +276,16 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso } continue; } + if (key === "claim") { + // The clip's claim pin, off (owed 6 Nov: there was no way to take one off but a hand edit). Only clearing: + // a claim is added as a mark (mark.add=<verdict>[@<s>]), its id and verdict edited in the On-screen table. + if (value !== null && !(typeof value === "string" && /^\s*none\s*$/i.test(value))) { + throw new CliError(`claim=${typeof value === "string" ? value : JSON.stringify(value)}: claim= (or claim=none) takes the clip's claim off; to add one, mark.add=<verdict>[@<source second>]`); + } + claimOff = true; + markChanges.push({ set: null }); + continue; + } if (MARK_KEYS.includes(key)) { markChanges.push(markChangeOf(key, value, mark)); continue; @@ -285,6 +298,12 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const takeFlag = flags.get("--take"); const take = typeof takeFlag === "string" && takeFlag ? takeFlag : null; if (flags.has("--take") && !take) throw new CliError("--take needs a take id"); + // A version is frozen (L3): its clip's claim comes off in the draft, after Open in draft brings the version there. + if (take && claimOff) { + throw new CliError( + `claim= --take ${take}: a version's clips are not edited in place -- open it in the draft first (umtool takes open ${project.id} ${take}), then \`umtool set ${project.id} ${clipId} claim=\``, + ); + } if (take && (markChanges.length || Object.keys(claim).length)) throw new CliError("--take sets a take's entry knobs; claim.* and marks are the project's (set them without --take)"); // `blur.on=` (or false): no blur at all, whatever else was given. if (Object.keys(blur).length) entryPatch.blur = "on" in blur && (blur.on === null || blur.on === false) ? null : blur; @@ -340,7 +359,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso return 0; } if (results.marks) { - out(`${clipId}: ${results.marks.length ? `marks ${results.marks.map((m) => markLine(m, results.stampsOnByMark?.[m.id], clipId)).join(" | ")}` : "no marks"}`); + out(`${clipId}: ${results.marks.length ? `marks ${results.marks.map((m) => markLine(m, results.stampsOnByMark?.[m.id], clipId)).join(" | ")}` : claimOff ? "no claim (its pin taken off)" : "no marks"}`); if (results.added) out(` added ${results.added.join(", ")}`); } if (results.claim) { diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -153,6 +153,34 @@ test("umtool set: claim and audio knobs through the writers; key= clears; a bad assert.equal("layout" in (await read(dir)).timeline[0], false); }); +test("umtool set claim=: the clip's claim pin off on the draft; claim=none too; a value or --take is refused", async () => { + const dir = await project("claimoff"); + const { lines, run } = runner(setCommand); + assert.equal(await run("claimoff", "c01", "claim=x"), 2); + assert.match(lines.at(-1), /claim= \(or claim=none\) takes the clip's claim off; to add one, mark\.add=/); + assert.deepEqual((await read(dir)).timeline[0].claim, { id: "k1", verdict: "CONTRADICTED" }, "untouched"); + // A version (L3): refused, with the way there -- nothing written to the take or the draft. + const { draftTake } = await import("./takeMaker.mjs"); + await draftTake(dir, { id: "v1", label: "Version 1", patch: {} }); + const takeBefore = await readFile(path.join(dir, "takes", "v1", "take.json"), "utf8"); + assert.equal(await run("claimoff", "c01", "claim=", "--take", "v1"), 2); + assert.match(lines.at(-1), /open it in the draft first \(umtool takes open claimoff v1\)/); + assert.equal(await readFile(path.join(dir, "takes", "v1", "take.json"), "utf8"), takeBefore); + assert.deepEqual((await read(dir)).timeline[0].claim, { id: "k1", verdict: "CONTRADICTED" }); + // The draft: the pin comes off. + assert.equal(await run("claimoff", "c01", "claim="), 0, lines.join("\n")); + assert.equal("claim" in (await read(dir)).timeline[0], false); + assert.match(lines.at(-1), /c01: no claim \(its pin taken off\)/); + // A clip of two marks: claim=none takes both (claims), as marks= would. + const m = await read(dir); + m.timeline[1].claims = [{ id: "a", verdict: "CONTRADICTED", at: 32 }, { id: "b", verdict: "CONTRADICTED", at: 38 }]; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + assert.equal(await run("claimoff", "c02", "claim=none", "--json"), 0, lines.join("\n")); + const c2 = (await read(dir)).timeline[1]; + assert.equal("claims" in c2 || "claim" in c2, false); + assert.deepEqual(JSON.parse(lines.at(-1)).marks, []); +}); + test("umtool look: the fact-check's stamp, a verdict's stamp word, markers, layout, the ladder, a look key", async () => { const dir = await project("look"); const { lines, run } = runner(lookCommand); diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -28,7 +28,7 @@ // Plain ESM: the CLI runs it under bare node. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; -import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; +import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; @@ -247,9 +247,12 @@ export async function checkLinks( let found = false; let error = null; try { - found = has(await getJson(pageUrl)); + // Keyed by the manifest's generation (cues.mjs pagesVersionOf), so a shard cached from an older deploy is + // fetched again rather than read. + const version = pagesVersionOf(man.doc); + found = has(await getJson(pageUrl, { version })); // A cached shard older than the deploy: read it again, once. - if (!found) found = has(await getJson(pageUrl, { refresh: true })); + if (!found) found = has(await getJson(pageUrl, { refresh: true, version })); } catch (e) { error = errText(e); } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -77,7 +77,7 @@ import { DELIVERABLES_MODES } from "./storage.mjs"; import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo"; import { SCENE_DEFAULTS, validatePostSceneRender } from "umtool-report-to-video/post-media-scene"; import { PICTURE_REPLY_DEFAULTS, validatePictureReplyRender } from "umtool-report-to-video/post-picture"; -import { createSnapshot, listSnapshots } from "./snapshots.mjs"; +import { createSnapshot, listSnapshots, readSnapshot } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; import { syncPatchMarkers, syncSectionMarkers } from "./patchMarkers.mjs"; @@ -2484,6 +2484,20 @@ async function structural(dir, op, token, mutate, { snapshotEvery = undefined, p } /** + * A structural edit of the DRAFT by a writer outside this file (takeImport.mjs importDraftItems): `mutate` over + * the manifest in the lock, the build's checks, an undo point, the take patches' markers following -- what every + * structural writer here does. Returns mutate's result with `snapshot` and `token`. + * + * @param {string} dir + * @param {string} op the undo point's name (`auto-before-<op>`) + * @param {string | null} token + * @param {(m: Record<string, any>) => any} mutate + */ +export async function editDraftStructure(dir, op, token, mutate) { + return structural(dir, op, token, (m) => mutate(m)); +} + +/** * Move one entry to `toIndex` (its index in the timeline AFTER the move). * `sectionEnter` is recomputed by report-to-video's own rule (sections.mjs), * and only on a manifest that already uses it. @@ -2596,6 +2610,107 @@ export async function rejectClip(dir, id, reason, { token = null, at = null, not return { ...res, record }; } +/** + * The clips removed on record (removed.json) that are still out of the cut, one per id -- its newest removal -- + * newest first. A clip put back (undo, restore) drops off; its lines stay on record. + * + * @param {Array<Record<string, any>>} rows readRemoved's + * @param {Record<string, any> | null} manifest + */ +export function removedOutOfCut(rows, manifest) { + const inCut = new Set((manifest?.timeline ?? []).map((e) => (isObj(e) ? e.id : null))); + const seen = new Set(); + const out = []; + for (const r of [...(rows ?? [])].reverse()) { + const id = isObj(r) && typeof r.id === "string" ? r.id : null; + if (!id || seen.has(id)) continue; + seen.add(id); + if (!inCut.has(id)) out.push(r); + } + return out; +} + +/** + * The newest revision of the manifest (revisions/, newest first; then a legacy copy) whose timeline holds clip `id`: the entry as it + * was there -- claim, quote, cite, edges and all -- with the ids before and after it. null when none does. + * + * @param {string} dir + * @param {string} id + */ +export async function removedClipInRevisions(dir, id) { + // The undo points in revisions/ first, newest first; then a legacy copy beside the manifest (the writer's + // rate-limited .bak, a hand-made copy), which may be older than they are. + const snaps = await listSnapshots(dir); + for (const snap of [...snaps.filter((x) => !x.legacy), ...snaps.filter((x) => x.legacy)]) { + let m = null; + try { + m = await readSnapshot(dir, snap.rel); + } catch { + continue; + } + const tl = Array.isArray(m?.timeline) ? m.timeline : []; + const k = tl.findIndex((e) => isObj(e) && e.id === id && e.type === "clip"); + if (k < 0) continue; + const ids = (xs) => xs.map((e) => (isObj(e) ? e.id : null)).filter((x) => typeof x === "string"); + return { entry: JSON.parse(JSON.stringify(tl[k])), from: snap.rel, before: ids(tl.slice(0, k)).reverse(), after: ids(tl.slice(k + 1)) }; + } + return null; +} + +/** + * UN-REJECT: put clip `id`, taken out of the cut (Reject, Wrong speaker, a plain remove), back -- the entry from + * the newest revision that holds it, so its claim, quote, cite and edges are as they were, at its old place: after + * the nearest entry that came before it there and is still in the cut, else before the nearest that came after + * it, else at the index its removal was recorded at. Every later write to the cut is kept (it is an insert, not + * a rollback); an undo point first. What its removal re-anchored or dropped (a marker moved, a deck claim, its + * claim group) is not put back, and is returned as `notPutBack` to say so. The draft's only: a version is opened + * in the draft first. `umtool timeline <p> restore <id>`, the Cut tab's Removed list. + * + * @param {string} dir + * @param {string} id + * @param {{ token?: string | null }} [opts] + */ +export async function restoreRemoved(dir, id, { token = null } = {}) { + if (takeScopeOf(dir)) throw new Error("a removed clip is restored into the draft (open the version in the draft first)"); + const clipId = String(id ?? "").trim(); + if (!clipId) throw new Error("restore needs the removed clip's id"); + const record = (await readRemoved(dir)).filter((r) => isObj(r) && r.id === clipId).at(-1) ?? null; + return prepAfter(dir, clipIdOf, structural(dir, "restore", token, (m, found) => { + if (m.timeline.some((e) => isObj(e) && e.id === clipId)) throw new Error(`${clipId} is in the cut already`); + if (!found) { + throw new Error( + `no revision of the manifest holds ${clipId} (revisions/ keeps the newest ${AUTO_SNAPSHOT_KEEP} undo points)` + + (record ? `: re-add it from its record -- umtool timeline <p> insert ${record.channel}/${record.video}@${record.start}-${record.end}` : ""), + ); + } + const tl = m.timeline; + const indexOf = (x) => tl.findIndex((e) => isObj(e) && e.id === x); + let at = -1; + let placed = null; + for (const x of found.before) { + const k = indexOf(x); + if (k >= 0) { + at = k + 1; + placed = { after: x }; + break; + } + } + if (at < 0) { + for (const x of found.after) { + const k = indexOf(x); + if (k >= 0) { + at = k; + placed = { before: x }; + break; + } + } + } + if (at < 0) at = Math.max(0, Math.min(tl.length, Number.isInteger(record?.at) ? record.at : tl.length)); + tl.splice(at, 0, found.entry); + return { id: clipId, at, entry: found.entry, from: found.from, ...(placed ?? {}), notPutBack: Array.isArray(record?.reanchored) ? record.reanchored : [] }; + }, { prepare: () => removedClipInRevisions(dir, clipId) })); +} + /** Copy one entry to just after itself, under a fresh id. A copied claim is dropped (one claim, one entry). * * @param {string} dir * @param {string} id diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -771,6 +771,8 @@ async function inTakeCommand({ verb, take, rest }, { root, out, err }) { } if (!words[1]) throw new CliError(`which project? umtool posts ${verb} <project> … --in-take ${take}`); const project = await projectOf(words[1], root); + // Deprecated (L3 S6): it still lands, and says so in one line naming the project as parsed. + err((await import("./takeDeprecation.mjs")).takeEditDeprecation(`posts ${verb} --in-take`, { project: project.id, take })); const { isTakeId, takesDirOf, TAKE_FILE } = await import("./takes.mjs"); if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id (lower-case letters, digits, dashes)`); if (!(await stat(path.join(takesDirOf(project.dir), take, TAKE_FILE)).catch(() => null))) { diff --git a/umtool/lib/report/restore-removed.test.mjs b/umtool/lib/report/restore-removed.test.mjs @@ -0,0 +1,100 @@ +// UN-REJECT (owed 6 Nov: removed.json keeps id/window/reason only): `umtool timeline <p> restore <id>` puts a +// removed clip back from the newest revision that holds it -- claim, quote, cite and edges as they were -- at its +// old place, every later write kept; `removed` lists what is still out. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-restore-")); +process.env.REPORTS_DIR = ROOT; +const { MANIFEST_NAME, readRemoved, rejectClip, removeEntry, removedOutOfCut, restoreRemoved, updateClip } = await import("./manifest.mjs"); +const { timelineCommand } = await import("./timelineCli.mjs"); + +const C02 = { + type: "clip", id: "c02", channel: "chan", video: "v2", start: 30, end: 44, cutStart: 31.2, cutEnd: 42.8, lockEnd: true, + cite: 31, quote: "the whole sentence, as cited", citeUrl: "https://example.test/v/chan/v2?t=31", + claim: { id: "k1", verdict: "CONTRADICTED", at: 35, label: "1 SEIZURE" }, +}; +const base = () => ({ + schemaVersion: 1, slug: "r", title: "R", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 20 }, + structuredClone(C02), + { type: "clip", id: "c03", video: "v3", start: 50, end: 60 }, + ], +}); +async function project(name) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(base(), null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); +const ids = async (dir) => (await read(dir)).timeline.map((e) => e.id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("restore: the rejected clip back as it was, at its old place, every later write kept", async () => { + const dir = await project("back"); + await rejectClip(dir, "c02", "irrelevant", { note: "off topic" }); + assert.deepEqual(await ids(dir), ["c01", "c03"]); + // Later writes: c01 trimmed, a clip inserted at the end. The restore must keep both. + await updateClip(dir, "c01", { start: 11, end: 19 }); + const m = await read(dir); + m.timeline.push({ type: "clip", id: "c04", video: "v4", start: 70, end: 80 }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + assert.deepEqual(removedOutOfCut(await readRemoved(dir), await read(dir)).map((r) => r.id), ["c02"]); + + const r = await restoreRemoved(dir, "c02"); + assert.equal(r.at, 1); + assert.equal(r.after, "c01"); + assert.match(r.from, /^revisions\/.*auto-before-reject\.manifest\.json$/); + const now = await read(dir); + assert.deepEqual(now.timeline.map((e) => e.id), ["c01", "c02", "c03", "c04"]); + // The entry as it was before the reject: no rejected verdict, claim/quote/cite/edges intact. + assert.deepEqual(now.timeline[1], C02); + assert.deepEqual([now.timeline[0].start, now.timeline[0].end], [11, 19], "the trim after the reject is kept"); + // Off the list; its line stays on record. + assert.deepEqual(removedOutOfCut(await readRemoved(dir), now), []); + assert.equal((await readRemoved(dir)).length, 1); + await assert.rejects(restoreRemoved(dir, "c02"), /c02 is in the cut already/); +}); + +test("restore: its neighbour before gone too, it goes before the one after; nothing holds it -- refused, naming the insert", async () => { + const dir = await project("neighbour"); + await rejectClip(dir, "c02", "weak"); + await removeEntry(dir, "c01"); + await restoreRemoved(dir, "c02"); + assert.deepEqual(await ids(dir), ["c02", "c03"]); + + const bare = await project("bare"); + await rejectClip(bare, "c02", "weak"); + await rm(path.join(bare, "revisions"), { recursive: true, force: true }); + await rm(path.join(bare, `${MANIFEST_NAME}.bak`), { force: true }); + await assert.rejects(restoreRemoved(bare, "c02"), /no revision of the manifest holds c02.*insert chan\/v2@30-44/s); + assert.deepEqual(await ids(bare), ["c01", "c03"], "nothing written"); +}); + +test("umtool timeline <p> removed | restore <id>: the list, then the clip back, with an undo point", async () => { + const dir = await project("cli"); + await rejectClip(dir, "c02", "repeats", { note: "covered by c01" }); + const lines = []; + const run = (...a) => timelineCommand(a, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); + assert.equal(await run("cli", "removed"), 0, lines.join("\n")); + assert.match(lines.join("\n"), /c02\s+chan\/v2@30-44\s+.*covered by c01/); + assert.match(lines.at(-1), /1 removed clip out of cli -- umtool timeline cli restore <id> puts one back/); + assert.equal(await run("cli", "restore", "c02"), 0, lines.join("\n")); + assert.match(lines.join("\n"), /restored c02 at 1 \(after c01\), as it was in revisions\//); + assert.match(lines.join("\n"), /undo point: revisions\/.*auto-before-restore/); + assert.deepEqual(await ids(dir), ["c01", "c02", "c03"]); + assert.equal(await run("cli", "removed", "--json"), 0); + assert.deepEqual(JSON.parse(lines.at(-1)).removed, []); + assert.equal(await run("cli", "restore", "c02"), 1); + assert.match(lines.at(-1), /c02 is in the cut already/); +}); diff --git a/umtool/lib/report/takeDeprecation.mjs b/umtool/lib/report/takeDeprecation.mjs @@ -0,0 +1,23 @@ +// THE TAKE-PATCH EDITS, DEPRECATED (umtool redesign L3, S6). Every edit lands in the working draft now; a saved +// version is frozen and is edited by opening it in the draft (`umtool takes open <p> <v>`). The CLI paths that +// still write a take's patch -- `--in-take`, `timeline --take`, `window --take` -- and the route behind the +// old take walk (/api/report/takes/timeline) keep working for now, each saying so in ONE line on stderr, so a +// script that leans on them hears it before they go. +// +// Plain ESM: the CLI and the route both read it. + +/** + * The one line, for `what` (the flag or route as typed) on take `take` of project `project`. + * @param {string} what + * @param {{ project?: string | null, take?: string | null }} [o] + */ +export function takeEditDeprecation(what, { project = null, take = null } = {}) { + const p = project ?? "<p>"; + const t = take ?? "<take>"; + return `umtool: ${what} is deprecated -- edits land in the draft now; open the take there first (umtool takes open ${p} ${t}) and edit without it`; +} + +/** Say it on stderr (once per call). */ +export function warnTakeEdit(what, o = {}, write = (s) => process.stderr.write(`${s}\n`)) { + write(takeEditDeprecation(what, o)); +} diff --git a/umtool/lib/report/takeDeprecation.test.mjs b/umtool/lib/report/takeDeprecation.test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { takeEditDeprecation, warnTakeEdit } from "./takeDeprecation.mjs"; + +test("the take-patch edits' deprecation: one line, naming the flag and the way there", () => { + const line = takeEditDeprecation("window --take", { project: "reports/x", take: "v2" }); + assert.equal(line, "umtool: window --take is deprecated -- edits land in the draft now; open the take there first (umtool takes open reports/x v2) and edit without it"); + assert.doesNotMatch(line, /\n/); + const said = []; + warnTakeEdit("--in-take", {}, (s) => said.push(s)); + assert.deepEqual(said, ["umtool: --in-take is deprecated -- edits land in the draft now; open the take there first (umtool takes open <p> <take>) and edit without it"]); +}); diff --git a/umtool/lib/report/takeEdit.test.mjs b/umtool/lib/report/takeEdit.test.mjs @@ -303,6 +303,9 @@ test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --p out.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "move", "t03a", "--to", "0"], io), 0, err.join("\n")); assert.match(out.join("\n"), /take tight: moved t03a: 3 -> 0/); + // Deprecated (L3 S6): one line on stderr for a write, and it still works; `ls` (a read) says nothing. + assert.deepEqual(err, ["umtool: timeline move --take is deprecated -- edits land in the draft now; open the take there first (umtool takes open proj tight) and edit without it"]); + err.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); // "Add to this take only" (lane/ui-simplify): a clip into the take's timeline, never the project's. const masterBefore = await masterText(dir); @@ -316,8 +319,10 @@ test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --p assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "chan/vid@1-5"], io), 2, "insert needs --after"); out.length = 0; + err.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n")); assert.match(out.join("\n"), /4 entries in take tight of proj$/, "the move was undone: nothing left to undo"); + assert.deepEqual(err, [], "ls reads: no warning"); const log = []; const before = await masterText(dir); diff --git a/umtool/lib/report/takeImport.mjs b/umtool/lib/report/takeImport.mjs @@ -39,7 +39,7 @@ import { createReadStream } from "node:fs"; import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { handleKey } from "umtool-report-to-video/post-avatars"; -import { applyStructural } from "./manifest.mjs"; +import { applyStructural, editDraftStructure, manifestToken } from "./manifest.mjs"; import { editTakeManifest, takeToken } from "./takeEdit.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; @@ -69,6 +69,36 @@ export function parseImportRef(ref) { return items.length ? { project: s.slice(0, i), items } : null; } +/** + * The argv of `umtool timeline <project> import-item …` for a page's ask (POST /api/report/takes/tools, op + * "import" with no take), every word CHECKED: the refs are split on whitespace, and a word that starts with "-" is + * refused -- a flag smuggled in the refs ("p:1 --take t1" would take the take-patch path, "--as x" rename the + * item) -- as is any word that is not `<project>:<item>[,<item>…]`. The anchor is an entry id. Throws + * ImportRefused (the route's 400) saying which word and why. + * + * @param {string} projectId + * @param {{ refs?: unknown, after?: unknown, before?: unknown, dryRun?: unknown }} ask + * @returns {string[]} + */ +export function draftImportArgv(projectId, { refs, after = null, before = null, dryRun = false }) { + const words = typeof refs === "string" ? refs.trim().split(/\s+/).filter(Boolean) : []; + if (!words.length) throw new ImportRefused("import needs <project>:<item>[,<item>…]"); + for (const w of words) { + if (w.startsWith("-")) throw new ImportRefused(`"${w}" is a flag, not an item: the refs are <project>:<item>[,<item>…] only`); + if (!parseImportRef(w)) throw new ImportRefused(`"${w}" is not <project>:<item>[,<item>…]`); + } + const anchor = (v, name) => { + if (v === null || v === undefined || v === "") return null; + const a = String(v); + if (!/^[A-Za-z0-9._:-]{1,120}$/.test(a) || a.startsWith("-")) throw new ImportRefused(`${name} "${a}" is not an entry id`); + return a; + }; + const a = anchor(after, "after"); + const b = anchor(before, "before"); + if (a && b) throw new ImportRefused("after or before, not both"); + return [projectId, "import-item", ...words, ...(a ? ["--after", a] : b ? ["--before", b] : []), ...(dryRun ? ["--dry-run"] : []), "--json"]; +} + /** The entry `ref` names in a timeline: its id, its post's id, or `p-<postId>`. */ export function findEntry(timeline, ref) { const r = String(ref ?? ""); @@ -194,22 +224,44 @@ export function postsInDateOrder(timeline) { } /** - * IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file). + * Items of other projects INTO THE DRAFT -- the project's own manifest, where every edit lands now (umtool + * redesign L3; E1, 9 Nov: the Cut tab's "Add items from another project"). importTakeItems with no take: the + * same clone, the same files linked in, the same placement and the same "again: unchanged", written through the + * draft's structural writer (an undo point of the project's, `umtool timeline <p> undo`). + * + * @param {{ id: string, dir: string }} project + * @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs + * @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts] + */ +export const importDraftItems = (project, refs, opts = {}) => importTakeItems(project, null, refs, opts); + +/** + * IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file) -- or, `take` null, into the draft + * (importDraftItems). * * @param {{ id: string, dir: string }} project the take's project - * @param {string} take + * @param {string | null} take * @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs * @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts] */ export async function importTakeItems(project, take, refs, { after = null, before = null, dryRun = false, now = new Date() } = {}) { if (!refs.length) throw new ImportRefused("nothing to import"); if (after && before) throw new ImportRefused("--after or --before, not both"); - const busy = await renderingNow(project.dir, take); + const draft = take === null; + const busy = draft ? null : await renderingNow(project.dir, take); if (busy) throw new ImportRefused(`not imported: ${busy}`); - const takeNow = await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take + const takeNow = draft + ? { manifest: JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8").catch(() => { throw new ImportRefused(`${project.id} has no video.manifest.json`); })) } + : await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take const tl = takeNow.manifest.timeline; const anchor = after ?? before; - if (anchor && !findEntry(tl, anchor)) throw new ImportRefused(`take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`); + if (anchor && !findEntry(tl, anchor)) { + throw new ImportRefused( + draft + ? `the draft has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id}\` lists them)` + : `take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`, + ); + } // Each source manifest read once, as it is on disk (never a take of it). /** @type {Map<string, Record<string, any>>} */ @@ -272,14 +324,10 @@ export async function importTakeItems(project, take, refs, { after = null, befor } } - const placed = []; - const write = await editTakeManifest( - project.dir, - take, - "import-item", - await takeToken(project.dir, take), - (m) => - applyStructural(m, (mm) => { + let placed = []; + /** The placement, over a manifest held in memory (the take's resolved one, or the draft's). */ + const place = (mm) => { + placed = []; const timeline = mm.timeline; const order = timeline.map((x) => (isObj(x) ? x.id : null)).join("\n"); let cursor = null; // the id the next item goes after (several items keep their order) @@ -317,9 +365,10 @@ export async function importTakeItems(project, take, refs, { after = null, befor pl.at = { index: i, after: i > 0 ? timeline[i - 1].id : null, before: i + 1 < timeline.length ? timeline[i + 1].id : null }; } return { ids: plans.map((p) => p.id) }; - }), - { now, dryRun }, - ); + }; + const write = draft + ? await writeDraft(project.dir, place, { dryRun }) + : await editTakeManifest(project.dir, take, "import-item", await takeToken(project.dir, take), (m) => applyStructural(m, place), { now, dryRun }); const items = plans.map((p) => { const pl = placed.find((x) => x.id === p.id); const n = isObj(p.entry.narration) ? p.entry.narration : null; @@ -343,7 +392,22 @@ export async function importTakeItems(project, take, refs, { after = null, befor dryRun, unchanged: write.unchanged, items, - revision: write.revision ? `takes/${take}/${write.revision.rel}` : null, + revision: draft ? write.revision : write.revision ? `takes/${take}/${write.revision.rel}` : null, token: write.token, }; } + +/** + * The draft's import write: the placement tried on a copy first -- nothing changed (or a dry run) writes nothing -- + * then done again inside the draft's structural writer, on the file as it is then. `revision`: its undo point. + */ +async function writeDraft(dir, place, { dryRun }) { + const token = await manifestToken(dir); + const now = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const tried = clone(now); + applyStructural(tried, place); + if (JSON.stringify(tried) === JSON.stringify(now)) return { unchanged: true, token, revision: null }; + if (dryRun) return { unchanged: false, dryRun: true, token, revision: null }; + const r = await editDraftStructure(dir, "import-item", token, place); + return { unchanged: false, token: r.token, revision: r.snapshot?.rel && !r.snapshot.skipped ? r.snapshot.rel : null }; +} diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs @@ -206,10 +206,17 @@ export async function cachedTakeManifest(projectDir, id) { return value; } -/** Write a take's play manifest (tmp + rename); returns its path. */ +// Each write's own tmp name. Play asks for a take's pages twice at once when it opens one -- the chrome preview +// (POST /api/report/chrome/preview) and the intro (POST /api/report/chrome/intro) both write this file, in one +// server process -- and with `<file>.<pid>.tmp` the two shared the tmp: the first rename took it, the second +// failed ENOENT, and Play said "the intro did not compose" (the intro-play flake, L8a/L4, 9 Nov). The last +// rename wins; both write the same take as it is. +let playManifestSeq = 0; + +/** Write a take's play manifest (tmp + rename); returns its path. Safe to call concurrently. */ export async function writePlayManifest(projectDir, id, manifest) { const file = playManifestPath(projectDir, id); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = `${file}.${process.pid}.${++playManifestSeq}.tmp`; await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/umtool/lib/report/takeManifest.test.mjs b/umtool/lib/report/takeManifest.test.mjs @@ -123,3 +123,19 @@ test("the play manifest is written beside the project's; the cache follows the f await rm(dir, { recursive: true, force: true }); } }); + +test("two writes of one take's play manifest at once both land (Play's preview and intro ask together)", async () => { + const dir = await project(); + try { + // Before, both used `<file>.<pid>.tmp`: one rename took the other's tmp and the second threw ENOENT. + const docs = Array.from({ length: 12 }, (_, i) => ({ timeline: [], n: i })); + const files = await Promise.all(docs.map((d) => writePlayManifest(dir, "short", d))); + assert.ok(files.every((f) => f === playManifestPath(dir, "short"))); + const n = JSON.parse(await readFile(playManifestPath(dir, "short"), "utf8")).n; + assert.ok(Number.isInteger(n) && n >= 0 && n < docs.length); + const { readdir } = await import("node:fs/promises"); + assert.deepEqual((await readdir(dir)).filter((f) => f.endsWith(".tmp")), []); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeScope.test.mjs b/umtool/lib/report/takeScope.test.mjs @@ -16,7 +16,7 @@ import { TakeScopeRefused, withTakeScope } from "./takeScope.mjs"; import { updateRender } from "./manifest.mjs"; import { readManifest } from "../projects/report.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; -import { postsInDateOrder, parseImportRef } from "./takeImport.mjs"; +import { ImportRefused, draftImportArgv, postsInDateOrder, parseImportRef } from "./takeImport.mjs"; import { lintCommand, namedFileProblems } from "./lintCli.mjs"; import { postsCommand } from "./postsCli.mjs"; import { takeCommand } from "./takeCli.mjs"; @@ -108,6 +108,8 @@ test("--in-take: set-item, narrate --pick, roles --set and fx land in the take's assert.match(r.out, /on take t1 \(its patch; scope-a's manifest untouched\): 1 edit\(s\), undo point takes\/t1\/revisions\/.*-auto-before-post-item\.take\.json -- umtool timeline scope-a --take t1 undo/); assert.equal(await text(a), before, "the project's manifest is never written"); assert.equal((await takeDoc(a, "t1")).patch.timeline.find((e) => e.id === "p-1").hold, 4); + // Deprecated (L3 S6): it still lands, and says so in one line on stderr. + assert.equal(r.err, "umtool: posts set-item --in-take is deprecated -- edits land in the draft now; open the take there first (umtool takes open scope-a t1) and edit without it"); // The alias: set-item's --take <t> is --in-take <t>; --json is the command's own object with the take. r = await posts("set-item", "scope-a", "p-1", "thread.group=g1", "--take", "t1", "--json"); assert.equal(r.code, 0, r.err); @@ -276,6 +278,71 @@ test("--import-item: an item of another project cloned into the take with its na assert.match(r.err, /has no entry p-77/); }); +test("timeline import-item: items of another project INTO THE DRAFT -- cloned, files linked, placed; again: unchanged; an undo point; the source untouched", async () => { + const src = await project("dimp-src", [narrated("20", "2026-10-30T12:30:00.000Z"), narrated("21", "2026-10-30T12:40:00.000Z")]); + for (const id of ["20", "21"]) { + await tone(path.join(src.dir, `narration/posts/${id}/take-1.orpheus-thread.wav`)); + await writeFile(path.join(src.dir, `narration/posts/${id}/take-1.parts.json`), "[]"); + } + await project("dimp-dst", [post("1", "2026-10-30T10:00:00.000Z"), post("3", "2026-10-30T13:00:00.000Z")]); + const srcBefore = await text(src); + const timeline = (...a) => cli(timelineCommand, a); + const dst = { dir: path.join(REPORTS, "dimp-dst") }; + const ids = async () => (await readManifest(dst.dir)).timeline.map((e) => e.id); + + // A dry run: the plan, nothing written, nothing linked. + let r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--dry-run", "--json"); + assert.equal(r.code, 0, r.err); + let doc = JSON.parse(r.out); + assert.deepEqual([doc.dryRun, doc.take, doc.items[0].at.index], [true, null, 1], "by date: between p-1 and p-3"); + assert.deepEqual(await ids(), ["p-1", "p-3"]); + assert.ok(!(await stat(path.join(dst.dir, "narration/posts/20")).catch(() => null)), "a dry run links nothing"); + + // Into the draft after p-1, in the order named; the files hard-linked; an undo point of the project's. + r = await timeline("dimp-dst", "import-item", "dimp-src:p-21,p-20", "--after", "p-1", "--json"); + assert.equal(r.code, 0, r.err); + doc = JSON.parse(r.out); + assert.deepEqual(doc.items.map((x) => [x.id, x.action]), [["p-21", "added"], ["p-20", "added"]]); + assert.match(doc.revision, /^revisions\/.*-auto-before-import-item\.manifest\.json$/); + assert.deepEqual(await ids(), ["p-1", "p-21", "p-20", "p-3"]); + const [s1, d1] = await Promise.all([stat(path.join(src.dir, "narration/posts/21/take-1.orpheus-thread.wav")), stat(path.join(dst.dir, "narration/posts/21/take-1.orpheus-thread.wav"))]); + assert.equal(d1.ino, s1.ino); + assert.equal(await text(src), srcBefore, "the source is only read"); + + // Again: unchanged, nothing written. + const before = await readFile(path.join(dst.dir, "video.manifest.json"), "utf8"); + r = await timeline("dimp-dst", "import-item", "dimp-src:p-21", "--json"); + doc = JSON.parse(r.out); + assert.deepEqual([doc.unchanged, doc.items[0].action, doc.revision], [true, "unchanged", null]); + assert.equal(await readFile(path.join(dst.dir, "video.manifest.json"), "utf8"), before); + // Words, and the refusals. + r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--before", "p-1"); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /p-20: moved from dimp-src:p-20 at 0, before p-1/); + // The undo point of a second import-item inside the undo window is the first's (autoSnapshot's rate). + assert.match(r.out, /the draft: 1 item\(s\)$/); + r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--after", "p-77"); + assert.equal(r.code, 1); + assert.match(r.err, /the draft has no entry p-77/); + assert.equal((await timeline("dimp-dst", "import-item", "dimp-src")).code, 2); + assert.equal((await timeline("dimp-dst", "import-item", "dimp-src:p-99")).code, 1); +}); + +test("draftImportArgv: a page's import ask becomes checked argv -- no flag rides in on the refs, every word a ref, the anchor an entry id", () => { + assert.deepEqual(draftImportArgv("p", { refs: " src:p-1,p-2 other/x:7 ", after: "p-1", dryRun: true }), ["p", "import-item", "src:p-1,p-2", "other/x:7", "--after", "p-1", "--dry-run", "--json"]); + assert.deepEqual(draftImportArgv("p", { refs: "src:p-1", before: "c02" }), ["p", "import-item", "src:p-1", "--before", "c02", "--json"]); + const refused = (ask, re) => assert.throws(() => draftImportArgv("p", ask), (e) => e instanceof ImportRefused && re.test(e.message)); + refused({ refs: "src:p-1 --take t1" }, /"--take" is a flag, not an item/); + refused({ refs: "src:p-1 --as x" }, /"--as" is a flag/); + refused({ refs: "-x" }, /is a flag/); + refused({ refs: "src:p-1 t1" }, /"t1" is not <project>:<item>/); + refused({ refs: " " }, /import needs/); + refused({ refs: 7 }, /import needs/); + refused({ refs: "src:p-1", after: "--take" }, /after "--take" is not an entry id/); + refused({ refs: "src:p-1", before: "a b" }, /before "a b" is not an entry id/); + refused({ refs: "src:p-1", after: "a", before: "b" }, /not both/); +}); + test("--draft --from <take>: a draft that starts from another take's patch (a --patch over it), its timeline its own", async () => { const a = await project("draft-from", [post("1", "2026-10-30T10:00:00.000Z"), post("2", "2026-10-30T11:00:00.000Z")]); assert.equal((await take("draft-from", "--id", "base", "--label", "Base", "--draft", "--patch-json", JSON.stringify({ timeline: [post("2", "2026-10-30T11:00:00.000Z")], render: { posts: { slurs: { on: false } } } }))).code, 0); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -73,6 +73,9 @@ import { removeEntry, removeSection, rejectClip, + readRemoved, + removedOutOfCut, + restoreRemoved, sectionsOf, updateSection, removeWrongSpeaker, @@ -92,7 +95,7 @@ import { upsertPost, } from "./manifest.mjs"; -import { REJECT_REASON_IDS, rejectionOf } from "./rejectReasons.mjs"; +import { REJECT_REASON_IDS, rejectReasonOf, rejectionOf } from "./rejectReasons.mjs"; import { groupModel, parseOrderText } from "./claimGroups.mjs"; import { sectionModel } from "./sectionEdit.mjs"; @@ -123,6 +126,17 @@ export const TIMELINE_USAGE = [ ` <why> is ${REJECT_REASON_IDS.join("|")} -- not-matching and wrong-speaker are fact`, " errors (incorrect, the note its correction; not-matching needs one), the rest cut reasons (rejected; other needs a note)", " umtool timeline <project> wrong-speaker <id> [--correction TEXT] the same as reject <id> wrong-speaker", + " umtool timeline <project> import-item <src>:<item>[,<item>…] [<src>:…] [--after <id> | --before <id>] [--as <id>] [--dry-run]", + " items of another project INTO THE DRAFT: cloned as they are there (their card, context, knobs,", + " narration with its takes and pick), the files they name hard-linked in (another file at the path:", + " under imports/<src>/), placed after/before an entry (else by date among the posts, else at the end);", + " again: updated in place, or unchanged and nothing written; one undo point (the Cut tab's", + " Add items from another project)", + " umtool timeline <project> removed [--json] the clips taken out on record (removed.json) and still out", + " umtool timeline <project> restore <id> UN-REJECT: put a removed clip back -- the entry from the newest", + " revision that holds it (claim, quote, cite, edges intact) at its old place (after the entry", + " before it there), every later write kept; an undo point first; a marker or deck claim its", + " removal moved or dropped stays as it is, and is listed", " a removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; pair/status/deck-claim references dropped) and says so", " umtool timeline <project> post <json|@file> add a post, or replace the one with its id", " umtool timeline <project> post-remove <id>", @@ -184,9 +198,9 @@ export const TIMELINE_USAGE = [ ].join("\n"); const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; -const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; +const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; -const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]); +const VALUED = new Set(["--as", "--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo", "insert"]; @@ -552,7 +566,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => const project = await projectOf(projectArg, root); // A video entry (video-entry.mjs), into the cut or a take's timeline. if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json }); - if (flags.has("--take")) return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); + if (flags.has("--take")) { + // `ls` only reads; a write into a take's patch is the deprecated path (L3 S6). + if (verb !== "ls") err((await import("./takeDeprecation.mjs")).takeEditDeprecation(`timeline ${verb} --take`, { project: project.id, take: String(flags.get("--take")) })); + return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); + } const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); @@ -579,6 +597,22 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => if (verb === "threads") return await threadsCommand(project, manifest, { write: flags.has("--write"), only: flags.has("--conversation") ? String(flags.get("--conversation")) : null, json, out }); + if (verb === "import-item") return await importItemsIntoDraft(project, rest, flags, { root, out, err, json }); + + if (verb === "removed") { + const rows = removedOutOfCut(await readRemoved(project.dir), manifest); + if (json) { + out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), removed: rows }, null, 2)); + return 0; + } + for (const r of rows) { + const why = rejectReasonOf(String(r.reason ?? "")); + out(`${String(r.id).padEnd(10)} ${r.channel ?? "?"}/${r.video ?? "?"}@${r.start ?? "?"}-${r.end ?? "?"} ${why?.label ?? r.reason ?? ""}${r.note || r.correction ? `: ${r.note ?? r.correction}` : ""} (${String(r.when ?? "").slice(0, 16)}, was at ${r.at})`); + } + out(`${rows.length} removed clip${rows.length === 1 ? "" : "s"} out of ${project.id}${rows.length ? ` -- umtool timeline ${project.id} restore <id> puts one back` : ""}`); + return 0; + } + if (verb === "ls") { const rows = timelineRows(manifest); if (json) { @@ -718,6 +752,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write((token) => removeWrongSpeaker(project.dir, id, { token, at, correction }))); break; } + case "restore": { + const id = need(rest[0], "the removed clip's id (umtool timeline <project> removed lists them)"); + ({ result, editNotes } = await write((token) => restoreRemoved(project.dir, id, { token }))); + break; + } case "duplicate": { const id = need(rest[0], "an entry id"); ({ result, editNotes } = await write((token) => duplicateEntry(project.dir, id, { token, at }))); @@ -885,6 +924,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } out(summaryOf(verb, result, attribution)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + // What a restored clip's removal re-anchored or dropped stays as it is now: said, not undone. + for (const line of result.notPutBack ?? []) out(` not put back: ${line}`); // The claim groups following the edit (claimGroups.mjs syncGroups), and an import's words. for (const line of result.groupNotes ?? []) out(` groups: ${line}`); for (const line of result.notes ?? []) out(` ${line}`); @@ -916,6 +957,54 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } /** + * `umtool timeline <p> import-item <src>:<item>[,…] … [--after|--before <id>] [--as <id>] [--dry-run] [--json]`: + * items of other projects into the DRAFT (takeImport.mjs importDraftItems). EXIT 0 done (or unchanged) · 1 refused + * · 2 usage. + */ +async function importItemsIntoDraft(project, rest, flags, { root, out, err, json }) { + const { ImportRefused, importDraftItems, parseImportRef } = await import("./takeImport.mjs"); + if (!rest.length) throw new CliError("import-item needs <project>:<item>[,<item>…] (the item ids of another project)"); + const refs = []; + for (const raw of rest) { + const r = parseImportRef(raw); + if (!r) throw new CliError(`import-item takes <project>:<item>[,<item>…] (not ${raw})`); + for (const item of r.items) refs.push({ project: await projectOf(r.project, root), item, as: null }); + } + if (flags.has("--as")) { + if (refs.length !== 1) throw new CliError("--as names ONE item's id in the draft: import one item with it"); + refs[0].as = String(flags.get("--as")); + if (!/^[A-Za-z0-9._:-]{1,120}$/.test(refs[0].as)) throw new CliError(`--as ${refs[0].as}: an entry id is letters, digits, dots, dashes`); + } + if (flags.has("--after") && flags.has("--before")) throw new CliError("--after or --before, not both"); + const one = (k) => (typeof flags.get(k) === "string" && flags.get(k) ? String(flags.get(k)) : null); + let r; + try { + r = await importDraftItems(project, refs, { after: one("--after"), before: one("--before"), dryRun: flags.has("--dry-run") }); + } catch (e) { + if (e instanceof ImportRefused) { + err(`umtool timeline: ${e.message}`); + return 1; + } + throw e; + } + if (json) { + out(JSON.stringify({ ok: true, op: "import-item", ...r }, null, 2)); + return 0; + } + for (const x of r.items) { + const at = x.at ? ` at ${x.at.index}${x.at.after ? `, after ${x.at.after}` : ""}${x.at.before ? `, before ${x.at.before}` : ""}` : ""; + out(`${x.id}: ${r.dryRun ? `would be ${x.action}` : x.action} from ${x.ref}${at}`); + if (x.narration) out(` narration: ${x.narration.takes} take(s), pick ${x.narration.pick ?? "none"}${x.narration.file ? ` (${x.narration.file})` : ""}`); + const linked = x.files.filter((f) => !f.how.startsWith("already")); + if (x.files.length) out(` files: ${linked.length} ${r.dryRun ? "to link" : "linked"}, ${x.files.length - linked.length} already there${linked.some((f) => f.was) ? `; renamed (another file had the path): ${linked.filter((f) => f.was).map((f) => `${f.was} -> ${f.path}`).join(", ")}` : ""}`); + if (x.avatars.length) out(` authors' pictures added: ${x.avatars.join(", ")}`); + if (x.missing.length) err(` named but not in ${x.source}: ${x.missing.join(", ")}`); + } + out(r.unchanged ? `the draft: nothing changed (already imported as it is)` : r.dryRun ? `the draft: a dry run, nothing written (would import ${r.items.length} item(s))` : `the draft: ${r.items.length} item(s)${r.revision ? `; undo point ${r.revision} (umtool timeline ${project.id} undo)` : ""}`); + return 0; +} + +/** * `umtool timeline <p> --take <id> ls|move|remove|undo`: a take's timeline * (walk a take). The writes go into the take's patch through takeEdit.mjs -- * the same structure rules, an undo point of the take's own first -- and the @@ -1250,6 +1339,8 @@ function summaryOf(verb, r, attribution) { const why = rejectionOf(r.removed); return `removed ${r.id} (was at ${r.at}): ${why?.fact ? "marked incorrect" : "rejected"}, ${why?.label ?? r.record?.reason}`; } + case "restore": + return `restored ${r.id} at ${r.at}${r.after ? ` (after ${r.after})` : r.before ? ` (before ${r.before})` : ""}, as it was in ${r.from}`; case "duplicate": return `duplicated as ${r.id} at ${r.at}`; case "post": diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts", + "test": "tsx --test lib/brandIcon.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs"; // Test-only environment, declared here (one-core Phase 4 slice 3); every one // carries the E2E_ prefix: @@ -52,6 +53,19 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); +// The package is "type": "module", so there is no __dirname here. +const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), ".e2e-song"); + +// An inherited REPORTS_DIR / CHANNELS_DIR that is not the fixture's (SONG_DIR is read only by +// the fixture builder, and only to copy from: the documented way to run against a copy) +// is refused before anything runs -- before the start-mode build, the fixture +// builder or a single spec (lib/e2eEnvGuard.mjs; 2 Nov a run wrote into +// ~/reports). +{ + const refusal = dataRootRefusal(process.env, FIXTURE); + if (refusal) throw new Error(refusal); +} + // The preflight's per-platform pacing, against the fixture's stub yt-dlp: 50 ms, // not the 30 s a real YouTube probe waits. On process.env, so the app server // and every worker (and the CLIs they spawn) inherit it. @@ -100,9 +114,6 @@ const APP_SERVER = // is in common/lib/ports.mjs (so scripts/worktree.mjs gives a worktree its own) // and in package.json's --ports spec (so the preflight sees it). const STUB_PORT = portFor("EDITOR_STUB_PORT"); -// The package is "type": "module", so there is no __dirname here. -const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), ".e2e-song"); - // The suite NEVER runs against the real song dir. The tool writes to the same // files the CLI scripts do, and those hold thousands of real human verdicts -- // a spec that judged a clip would be indistinguishable from a person doing it. diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -53,8 +53,10 @@ // manifests through createJsonCache below, the same files on disk, and on a // post it cannot find it fetches them again and rewrites them. The cue walk // never refreshes, but it can read a corpus.json post-links rewrote: newer, so -// a channel the stale copy lacked is found. Manifest and shard URLs carry no -// version, so a cue window does not move because of it. +// a channel the stale copy lacked is found. Shard pages are cached by the +// generation of the transcripts manifest that named them (its generatedAt), so +// when linkCheck refreshes a manifest after an archive rebuild, the walk fetches +// that channel's pages again instead of reading the old build's forever. import { readFile, writeFile, mkdir, lstat, readlink, readdir, stat } from "node:fs/promises"; import path from "node:path"; @@ -78,12 +80,33 @@ export const DEFAULT_CACHE_DIR = // A shard page is capped at 8 MB and holds ~100 videos, so refetching one per // clip — across two separate processes, resolve-windows then build-video — is -// the difference between usable and painful. Cached by URL on disk; archives are -// rebuilt rarely and a stale page only matters if the cues themselves changed. +// the difference between usable and painful. Cached by URL on disk, and a page +// by the generation of the manifest that named it (pagesVersionOf): an archive +// rebuild bumps the manifest's generatedAt, and its pages are fetched again. function cacheKey(url) { return createHash("sha1").update(url).digest("hex") + ".json"; } +// The key a versioned copy on disk carries its version under (createJsonCache, +// `version`). No published document has a key like it. +export const CACHE_VERSION_KEY = "__umtoolCacheVersion"; + +/** A document as the disk cache holds it -> `{ version, body }` (version null when unversioned). */ +function unwrapCached(doc) { + if (doc && typeof doc === "object" && !Array.isArray(doc) && CACHE_VERSION_KEY in doc) { + return { version: doc[CACHE_VERSION_KEY], body: doc.body }; + } + return { version: null, body: doc }; +} + +/** + * The generation a channel's shard pages belong to: its transcripts manifest's + * `generatedAt` (every published manifest carries one), or null for a manifest + * without it -- whose pages are then cached by URL alone, as before. + */ +export const pagesVersionOf = (manifest) => + typeof manifest?.generatedAt === "string" && manifest.generatedAt ? manifest.generatedAt : null; + export function pageFileName(pageNumber) { return `page-${String(pageNumber).padStart(4, "0")}.json`; } @@ -170,6 +193,17 @@ export class CueLookupError extends Error { * `refreshAfterMs` ago. The default, Infinity, makes that "at most once per * process": a build re-reads a stale cached document once, never twice. A * long-lived server passes a window instead. + * + * `getJson(url, { version })` is for a document whose URL never changes but + * whose content belongs to a generation of something else -- a shard page to + * the `generatedAt` of the channel manifest that named it. The copy on disk is + * then stored with that version beside it (`{ [CACHE_VERSION_KEY]: v, body }`, + * the same one file per URL), and a cached copy of any other version (or of + * none) is a miss: the page is fetched again and the old generation's copy + * overwritten. Without this a page was kept forever while its manifest moved on + * (linkCheck refreshes manifests), so the walk could read a record from a page + * the new manifest no longer puts it on, or cues an archive rebuild rewrote. + * A read with no `version` takes either form. */ export function createJsonCache({ cacheDir = DEFAULT_CACHE_DIR, @@ -177,51 +211,59 @@ export function createJsonCache({ log = () => {}, refreshAfterMs = Infinity, } = {}) { + /** URL -> { version, body }: version null for a document cached without one. */ const mem = new Map(); /** URL -> when this cache last fetched it from the network (ms). */ const fetchedAt = new Map(); - /** URL -> the network fetch of it in progress. */ + /** URL (+ version) -> the network fetch of it in progress. */ const inflight = new Map(); - async function getJson(url, { refresh = false } = {}) { + const fits = (have, version) => version == null || have === version; + + async function getJson(url, { refresh = false, version = null } = {}) { const recent = fetchedAt.has(url) && Date.now() - fetchedAt.get(url) < refreshAfterMs; const useCache = !refresh || recent; - if (useCache && mem.has(url)) return mem.get(url); + const held = mem.get(url); + if (useCache && held && fits(held.version, version)) return held.body; const disk = cacheDir ? path.join(cacheDir, cacheKey(url)) : null; if (useCache && disk) { try { - const cached = JSON.parse(await readFile(disk, "utf8")); - mem.set(url, cached); - return cached; + const cached = unwrapCached(JSON.parse(await readFile(disk, "utf8"))); + if (fits(cached.version, version)) { + mem.set(url, cached); + return cached.body; + } + log(`stale ${url}: cached for ${cached.version ?? "no version"}, wanted ${version}`); } catch { /* cold cache */ } } // Callers that ask for the same URL while it is on its way share the one // fetch (umtool's preview routes run side by side). - if (inflight.has(url)) return inflight.get(url); + const flight = version == null ? url : `${url}\0${version}`; + if (inflight.has(flight)) return inflight.get(flight); const pending = (async () => { log(`fetch ${url}`); const res = await fetchImpl(url); if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); const json = await res.json(); - mem.set(url, json); + mem.set(url, { version, body: json }); fetchedAt.set(url, Date.now()); if (disk) { try { await mkdir(path.dirname(disk), { recursive: true }); - await writeFile(disk, JSON.stringify(json)); + await writeFile(disk, JSON.stringify(version == null ? json : { [CACHE_VERSION_KEY]: version, body: json })); } catch { // A cache we cannot write is a slow run, not a failed one. } } return json; })(); - inflight.set(url, pending); + inflight.set(flight, pending); try { return await pending; } finally { - inflight.delete(url); + inflight.delete(flight); } } @@ -285,7 +327,7 @@ export function createCueSource({ const manifest = await getJson(entry.manifests.transcripts); log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`); for (let n = 0; n < manifest.pageCount; n += 1) { - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) }); const hit = page.find( (r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted), ); @@ -327,7 +369,7 @@ export function createCueSource({ ); } - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) }); const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo); if (!record) { throw new CueLookupError( diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -14,6 +14,7 @@ import path from "node:path"; import { CAPTION_TRACK_RULE_VERSION, createCueSource, + createJsonCache, pageFileName, pageUrlFrom, siteOriginFromManifest, @@ -122,6 +123,60 @@ test("fetches each URL once, however many videos are read", async () => { ]); }); +// --- the disk cache follows the manifest's generation ---------------------- + +test("a shard page cached on disk is fetched again when its channel manifest's generatedAt moves", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const MAN = `${ORIGIN}/transcripts/chan/manifest.json`; + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + const gen1 = { ...ROUTES, [MAN]: { ...ROUTES[MAN], generatedAt: "2026-08-07T00:00:00.000Z" } }; + // A run against the first deploy fills the disk cache. + const seen1 = []; + const first = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen1) }).load("chan", "vid1"); + assert.equal(first.cues[1].text, "second line."); + assert.ok(seen1.includes(PAGE)); + + // A second process with the same generation reads everything from disk. + const seen2 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen2) }).load("chan", "vid1"); + assert.deepEqual(seen2, []); + + // The archive is rebuilt: the cues were rewritten and the manifest carries a new generatedAt. Something + // refreshes the manifest on disk (linkCheck does, with refresh: true) ... + const rewritten = { ...RECORD, cues: [{ start: 0, end: 3.1, text: "first line, re-transcribed" }, { start: 3.1, end: 5, text: "second." }] }; + const gen2 = { ...gen1, [MAN]: { ...gen1[MAN], generatedAt: "2026-11-01T00:00:00.000Z" }, [PAGE]: [rewritten] }; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(gen2) }).getJson(MAN, { refresh: true }); + + // ... and the cue walk, which never refreshes, follows it: the page of the old generation is a miss. + const seen3 = []; + const after = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen3) }).load("chan", "vid1"); + assert.deepEqual(seen3, [PAGE]); + assert.equal(after.cues[0].text, "first line, re-transcribed"); + + // And the refetched page is the one on disk now: a third run fetches nothing. + const seen4 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen4) }).load("chan", "vid1"); + assert.deepEqual(seen4, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("a versioned copy on disk still reads as the document to a caller that asks with no version", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES) }).getJson(PAGE, { version: "g1" }); + const seen = []; + const doc = await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES, seen) }).getJson(PAGE); + assert.deepEqual(doc, [RECORD]); + assert.deepEqual(seen, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + // --- local wins ------------------------------------------------------------- test("a local corpus is preferred over the network", async () => {