Archilyzer · Source

archilyzer

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

commit 5c79fc2d04cf5a9a7bdac1c8440a0e815649865d
parent cb3200668510f589f26e92042f7d20fee2cd335e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 12:52:23 -0400

Merge r23/fixes (release 23 Lane 1: the Twitch join option (b), transcribe from a saved container, notes' agent write path, the stats signature sees the caption-track pass, test hygiene) into r23/integration

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

Diffstat:
MENVIRONMENT.md | 4++--
Mcommon/controller/buildIndex.ts | 18++++++++++++++++++
Mcommon/controller/buildStats.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/buildStats.ts | 27+++++++++++++++++++++++++--
Mcommon/controller/fetchWindows.test.ts | 27+++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 13++++++++++---
Mcommon/controller/transcribeOne.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/transcriptionContainer.test.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 4++--
Mcommon/lib/evidenceClip-server.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/evidenceClip-server.ts | 4+++-
Mcommon/lib/evidenceClip.mjs | 42++++++++++++++++++++++++++++++------------
Acommon/lib/videoDir-server.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/videoDirId.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/videoDirId.test.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/videoId.ts | 12++++++++++++
Mcommon/package.json | 2++
Mcommon/publish/reportMedia.ts | 3++-
Acommon/publish/reportMediaTwitch.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 5+++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++-----------
Aeditor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 25++++++++++++++++---------
Meditor/e2e/import-video.spec.ts | 19++++++++++++++++++-
Meditor/playwright.config.ts | 8+++++++-
Mexport/playwright.2origin.config.ts | 8+++++++-
Mexport/playwright.config.ts | 8+++++++-
Mexport/playwright.hub.config.ts | 8+++++++-
Mexport/playwright.report.config.ts | 8+++++++-
Mhomepage/playwright.config.ts | 8+++++++-
Mmcp/README.md | 8++++----
Mmcp/src/archivalTools.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mmcp/src/archivalTools.ts | 114++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mmcp/src/instructions.ts | 3++-
Mplans/e2e-speed.md | 37+++++++++++++++++++++++++++++++++++++
Mplans/release-19.md | 27+++++++++++++++++++++++++++
Mplans/release-20.md | 94++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mplans/release-21.md | 45+++++++++++++++++++++++++++++++++++++++++++++
Ascripts/e2e-timings-reporter.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/e2e-timings.mjs | 51++++++++++++++++++++++++++++++++++++++-------------
Mscripts/e2e-timings.test.mjs | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/notes/route.ts | 20++++++++++++--------
Mumtool/docs/notes.md | 14+++++++++++++-
Mumtool/e2e/article-notes.spec.ts | 23+++++++++++++++++++++++
Mumtool/e2e/capabilities.ts | 9+++++++++
Mumtool/e2e/faces.spec.ts | 9++++++++-
Mumtool/e2e/find.spec.ts | 5++++-
Mumtool/e2e/fixtures/song-capabilities.mjs | 10++++++++++
Mumtool/e2e/triage.spec.ts | 9++++++++-
Aumtool/lib/annotations/agentAuth.mjs | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/annotations/agentAuth.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 8+++++++-
Mumtool/report-to-video/cues.mjs | 5++++-
Mumtool/report-to-video/cues.test.mjs | 27+++++++++++++++++++++++++++
55 files changed, 2031 insertions(+), 110 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -53,7 +53,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | Variable | Default | What it does | Read by | |---|---|---|---| -| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback). Set the same value on both ends. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts | +| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs | | `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts | | `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts | | `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts | @@ -82,7 +82,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `CLAUDE_DIGEST_MODEL` | the CLI's default | The model the metered digest lane asks `claude` for when settings name none. | common/lib/digestApps.ts | | `NITTER_INSTANCES` | a built-in list | Comma-separated Nitter instances for the X fallback fetcher, in order of preference. | common/social/xNitterFetcher.ts | | `ARCHILYZER_X_BROWSER` | the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium | The Chromium-family browser /settings' "Connect X account" opens (a path, or a name looked up on PATH), and a forum-thread channel's "Connect forum session" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser. | common/social/xBrowser.ts | -| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts | +| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts | | `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts | | `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts | diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -334,8 +334,25 @@ type MtimeRecord = { isDeleted: boolean; isUnlisted: boolean; indexKey: IndexKey; + // THE CUES THIS RECORD WAS LAST WRITTEN WITH (release 23 F4): cueFingerprint + // over the list stored under `indexKey`. Every input above can stand still + // while the cues move — the caption-track pass re-reads a record under a new + // rule and nothing on disk changed — and buildStats keys a video's stat on + // this record (indexSignature), so without it such a record kept its old + // `hasTranscript` / `cueCount` until something else moved. Absent on a record + // written before it, which buildStats reads as the old signature exactly. + cueFingerprint?: string; }; +// The cue facts a stat is made of — the count, and the last cue's end (the +// coverage) — as one comparable string. +export function cueFingerprint(list: readonly Cue[] | undefined): string { + if (!list || list.length === 0) return "0"; + let lastEnd = 0; + for (const c of list) if ((c.end ?? 0) > lastEnd) lastEnd = c.end ?? 0; + return `${list.length}:${lastEnd}`; +} + // The probe result an MtimeRecord carries, preferring the exact availability // string and falling back to the pre-VideoState booleans. function stateFromRecord(rec: MtimeRecord): VideoState { @@ -1312,6 +1329,7 @@ export async function buildIndex({ isDeleted: availability === "deleted", isUnlisted: availability === "unlisted", indexKey, + cueFingerprint: cueFingerprint(cueList), }); } catch (err) { log(`Failed to process ${s.channelSlug}/${s.videoDir}: ${String(err)}`); diff --git a/common/controller/buildStats.test.ts b/common/controller/buildStats.test.ts @@ -691,6 +691,120 @@ test("(k) the whole-pool bundle leaves out a channel only an unlisted site expos assert.deepEqual(own.map((s) => s.id).sort(), ["s1", "u1", "u2"]); }); +// The index's own sub-DBs, for the caption-track cases: the state an index +// built under the old caption-track rule left (cues stored empty), and its +// records as written before the cue fingerprint. +function withIndex<T>(fn: (db: (name: string) => ReturnType<ReturnType<typeof open>["openDB"]>) => T): T { + const root = open({ path: paths.lmdbPath, maxDbs: 18, compression: true }); + try { + return fn((name) => root.openDB({ name, encoding: "msgpack" })); + } finally { + root.close(); + } +} +type IdxRec = { indexKey: [string, string, string]; cueFingerprint?: string }; + +test("(l) release 23 F4: a record the caption-track pass takes from no text to text recomputes its stat, once", async () => { + resetCorpus(); + seedVideo("blocks"); + addCaptions("blocks", "2026-07-11T12:00:00Z"); + seedVideo("other"); + addCaptions("other", "2026-07-11T12:00:00Z"); + await runIndex(); + // The index as an older build left it: "blocks" read to no cues under the + // old rule, no record carrying a fingerprint, the rule's pass not yet run. + withIndex((db) => { + const mtimes = db("mtimes"); + for (const { key, value } of mtimes.getRange()) { + const { cueFingerprint: _gone, ...old } = value as IdxRec; + mtimes.putSync(key, old); + if ((key as string[])[1] === "blocks") db("cues").putSync((old as IdxRec).indexKey, []); + } + db("meta").removeSync("captionTrackRule"); + }); + const before = await runStats(); + assert.equal(statOf(before.byId, "blocks").hasTranscript, false); + assert.equal(statOf(before.byId, "blocks").cueCount, 0); + + // The pass re-reads "blocks" (its stored cues are empty); no input moved. + await runIndex(); + const after = await runStats(); + assert.equal(after.res.changed, 1, "only the record the pass changed"); + assert.equal(statOf(after.byId, "blocks").hasTranscript, true); + assert.equal(statOf(after.byId, "blocks").cueCount, 2); + assert.equal(statOf(after.byId, "other").cueCount, 2); + + const again = await runStats(); + assert.equal(again.res.changed, 0, "once"); +}); + +test("(l2) release 23 F4: a pass that changes a record's cue count (text to other text) recomputes its stat — the fingerprint alone", async () => { + resetCorpus(); + seedVideo("tracks"); + addCaptions("tracks", "2026-07-11T12:00:00Z"); + // A second English track: a record the caption-track pass reaches. + const en = path.join(videoDir("tracks"), "transcript.en.vtt"); + const orig = path.join(videoDir("tracks"), "transcript.en-orig.vtt"); + writeFileSync(orig, readFileSync(en, "utf8")); + touch(orig, "2026-07-11T12:00:00Z"); + await runIndex(); + // As an older rule left it: one cue of the two, no fingerprint, pass due. + withIndex((db) => { + const mtimes = db("mtimes"); + for (const { key, value } of mtimes.getRange()) { + const { cueFingerprint: _gone, ...old } = value as IdxRec; + mtimes.putSync(key, old); + const list = db("cues").get((old as IdxRec).indexKey) as unknown[]; + db("cues").putSync((old as IdxRec).indexKey, list.slice(0, 1)); + } + db("meta").removeSync("captionTrackRule"); + }); + const before = await runStats(); + assert.equal(statOf(before.byId, "tracks").cueCount, 1); + assert.equal(statOf(before.byId, "tracks").hasTranscript, true); + + await runIndex(); + const after = await runStats(); + assert.equal(after.res.changed, 1); + assert.equal(statOf(after.byId, "tracks").cueCount, 2); + assert.equal((await runStats()).res.changed, 0, "once"); +}); + +test("(m) release 23 F4: a stat a pass left stale before the fingerprint (no text, cues held) is healed, once", async () => { + resetCorpus(); + seedVideo("stale"); + addCaptions("stale", "2026-07-11T12:00:00Z"); + seedVideo("bare"); + await runIndex(); + await runStats(); + // What a caption-track pass that ran before this fix left: the index holds + // the cues, the cached stat still says no transcript, and its key matches. + withDb(({ stats }) => { + for (const { key, value } of stats.getRange()) { + if ((key as string[])[1] !== "stale") continue; + const v = value as { stat: Record<string, unknown> }; + stats.putSync(key, { ...v, stat: { ...v.stat, hasTranscript: false, cueCount: 0 } }); + } + }); + const healed = await runStats(); + assert.equal(healed.res.changed, 1, "the stale stat alone; a video with no cues is not asked again"); + assert.equal(statOf(healed.byId, "stale").hasTranscript, true); + assert.equal(statOf(healed.byId, "stale").cueCount, 2); + assert.equal(statOf(healed.byId, "bare").hasTranscript, false); + assert.equal((await runStats()).res.changed, 0); +}); + +test("(n) release 23 F4: shipping the fingerprint recomputes nothing — an old record's signature is unchanged", async () => { + const { indexSignature } = await import("./buildStats"); + const { cueFingerprint } = await import("./buildIndex"); + const old = { metaMs: 1, transcriptMs: 2, subsMs: null, availabilityMs: null, digestMs: null, indexKey: ["20260601", "c", "v"] as [string, string, string] }; + assert.equal(indexSignature(old), ["1", "2", "", "", "", "20260601", "c", "v"].join("\u0000")); + assert.notEqual(indexSignature({ ...old, cueFingerprint: "2:110" }), indexSignature(old)); + assert.equal(cueFingerprint(undefined), "0"); + assert.equal(cueFingerprint([]), "0"); + assert.equal(cueFingerprint([{ start: 0, end: 5, text: "a" }, { start: 60, end: 110, text: "b" }]), "2:110"); +}); + test("(z) no write this file caused landed outside its temp root", () => { // LMDB writes natively, past the spy: its file must be under the root too. assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath); diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -106,6 +106,9 @@ type IndexRecord = { availabilityMs?: number | null; digestMs?: number | null; indexKey: IndexKey; + // buildIndex's cueFingerprint (release 23 F4): it moves when a pass re-reads + // a record's cues with no input file moving (the caption-track pass). + cueFingerprint?: string; }; // buildIndex has no `mtimes` record for this video. See the two counts below. @@ -116,7 +119,12 @@ const NOT_INDEXED = "-"; // for another reason can read a fresher transcript.cues.json and change the cue // count, and a moved index key moves the cues. Numbers print as their shortest // round-trip form, so an unchanged record gives an identical string. -function indexSignature(r: IndexRecord | undefined): string { +// +// The cue fingerprint (release 23 F4) is appended only when the record has +// one: a record written before it gives the old string exactly, so shipping it +// recomputes nothing by itself; a record the index (re)writes from then on — +// the caption-track pass's included — moves once. +export function indexSignature(r: IndexRecord | undefined): string { if (!r) return NOT_INDEXED; const n = (v: number | null | undefined) => (v == null ? "" : String(v)); return [ @@ -126,9 +134,24 @@ function indexSignature(r: IndexRecord | undefined): string { n(r.availabilityMs), n(r.digestMs), ...r.indexKey, + ...(r.cueFingerprint !== undefined ? [`cues=${r.cueFingerprint}`] : []), ].join("\u0000"); } +// A cached stat that says NO TRANSCRIPT while the index holds cues for it: +// the stale shape a caption-track pass that ran before the fingerprint left +// (a record taken from no text to text with no input moving). Asked only of +// such stats, by the stored value's length — no decode. +function statMissesStoredCues( + prev: StatsRecord, + rec: IndexRecord | undefined, + cues: { getBinaryFast(key: IndexKey): Buffer | undefined }, +): boolean { + if (!rec || prev.stat.hasTranscript) return false; + const raw = cues.getBinaryFast(rec.indexKey); + return raw !== undefined && raw.length > 4; +} + // Set to 1 (or true/yes/on) to let an OLDER build clear a stats cache a newer // one wrote — a deliberate rollback. Declared in lib/envVars.ts. export const STATS_DOWNGRADE_ENV = "ARCHILYZER_STATS_ALLOW_DOWNGRADE"; @@ -471,7 +494,7 @@ export async function buildStats({ if (!prev) { added++; toProcess.push({ e, idx, indexKey: rec?.indexKey }); - } else if (prev.metaMs !== e.metaMs || prev.idx !== idx) { + } else if (prev.metaMs !== e.metaMs || prev.idx !== idx || statMissesStoredCues(prev, rec, cues)) { // The second half is the fix for stats frozen at first sight: a // transcript that arrives later makes buildIndex re-process the video // (and a video first seen before the index had it moves off diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -371,3 +371,30 @@ test("saved containers: a cut that fails is a cut-failed item and the run carrie assert.deepEqual(r.cut.map((i) => i.id), ["v2"]); assert.equal(r.stopped, undefined); }); + +test("a Twitch record's v<n> is fetched into, and read from, its data/<n>/ (release 23 F1)", async () => { + const paths = await corpus(); + const twitch = { url: "https://www.twitch.tv/example" } as unknown as ChannelConfig; + const n = "2700000001"; + const fresh = "2700000002"; + await mkdir(path.join(paths.channelsDir, "c", "data", fresh), { recursive: true }); + const clips = path.join(paths.channelsDir, "c", "data", n, "clips"); + await mkdir(clips, { recursive: true }); + await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4"); + const asked: string[] = []; + const h = harness({ + readChannelConfig: async () => twitch, + findVideoSourceUrl: async (_p, _s, id) => { + asked.push(id); + return `https://www.twitch.tv/videos/${id}`; + }, + }); + const r = await go(paths, [{ slug: "c", id: `v${n}`, from: 5, to: 15 }, { slug: "c", id: `v${fresh}`, from: 5, to: 15 }], h); + // The cached window was found in data/<n>/; the item keeps its record id. + assert.deepEqual(r.cached.map((i) => i.id), [`v${n}`]); + assert.deepEqual(r.fetched.map((i) => i.id), [`v${fresh}`]); + // The URL was looked up, and the window written, under the directory's id. + assert.deepEqual(asked, [fresh]); + const written = await readFile(path.join(paths.channelsDir, "c", "data", fresh, "clips", "5.00-15.00.mp4"), "utf8"); + assert.equal(written, "mp4"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -8,6 +8,8 @@ import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; import { findContainingClipWindow } from "../lib/clipWindow-server"; +import { channelConfigPlatform } from "../lib/videoId"; +import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { cutSavedVideoWindow, savedWindowSource, @@ -365,7 +367,12 @@ export async function fetchWindows({ progress(); continue; } - const videoDir = path.join(paths.channelsDir, item.slug, "data", item.id); + // The item names a RECORD (a report's citation, the MCP); its directory + // may be another id — a Twitch record's v<n> is data/<n>/ (release 23 F1). + const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { + platform: channelConfigPlatform(config), + }); + const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); // THE CACHE FIRST, here rather than only inside fetchWindowManaged, so a // cached window owes no pause and is not counted as a network attempt. @@ -423,7 +430,7 @@ export async function fetchWindows({ const url = item.webpageUrl?.trim() || - (await deps.findVideoSourceUrl(paths, item.slug, item.id, config)); + (await deps.findVideoSourceUrl(paths, item.slug, dirId, config)); if (!url) { fail( item, @@ -500,7 +507,7 @@ export async function fetchWindows({ channelConfig: config, paths, videoDir, - videoId: item.id, + videoId: dirId, videoUrl: url, cwd: path.join(paths.channelsDir, item.slug), from: item.from, diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -22,6 +22,8 @@ import { pickPreferredAudio } from "../lib/mediaFiles"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server"; import { writeFileAtomic } from "../lib/jsonFile-server"; +import { probeMedia } from "../lib/evidenceClip-server"; +import { savedWindowSource } from "../lib/savedVideoWindow-server"; const { pathExists, readdir, rename } = fs; @@ -50,6 +52,58 @@ async function resolveAudioFile( return null; } +// 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 +// audio whenever no extracted audio was on disk — even for a video whose whole +// source is in the saved-video store, which resolveAudioFile above already +// transcribes from. This answers the question first, in resolveAudioFile's +// order (`findSourceMedia(entries) ?? the saved-video pointer`): +// container a container with sound: transcribe it, download nothing. +// no-audio the container has no sound: the download path, as before. +// unreadable a saved-video pointer whose container cannot be read (its +// drive is not mounted or not answering, the file is gone, the +// store is mid-move): REFUSED with the media guard's sentence +// (savedWindowSource's), never a download in its place. +// none no container at all: the download path, as before. +// A `source-media.<ext>` in the video dir that ffprobe cannot read is passed +// over for the pointer, as if it were not there. +export type TranscriptionContainer = + | { kind: "container"; file: string; from: "video-dir" | "saved-video" } + | { kind: "no-audio"; file: string } + | { kind: "unreadable"; error: string } + | { kind: "none" }; + +export async function transcriptionContainer(opts: { + paths: Pick<Paths, "transcriptsDir" | "savedVideosDir" | "ffprobeBin">; + slug: string; + videoDir: string; + entries: string[]; +}): Promise<TranscriptionContainer> { + const local = findSourceMedia(opts.entries); + if (local) { + const file = path.join(opts.videoDir, local); + const p = await probeMedia(file, opts.paths.ffprobeBin); + if (p) return p.hasAudio ? { kind: "container", file, from: "video-dir" } : { kind: "no-audio", file }; + } + // The pointer, through the window path's own reader: its drive watchdog, its + // store-move check and its refusal sentence. [0, 0] is a window every + // readable container holds, so the answer is "none", "unreadable" or + // "covers" with the container's probe. + const saved = await savedWindowSource({ + paths: opts.paths, + slug: opts.slug, + videoDir: opts.videoDir, + from: 0, + to: 0, + }); + if (saved.kind === "unreadable") return { kind: "unreadable", error: saved.error }; + if (saved.kind !== "covers") return { kind: "none" }; + return saved.probe.hasAudio + ? { kind: "container", file: saved.container, from: "saved-video" } + : { kind: "no-audio", file: saved.container }; +} + // The audio we resolved at the top of the run is gone NOW. // // Another lane removed it mid-transcription — today that means the backfill's diff --git a/common/controller/transcriptionContainer.test.ts b/common/controller/transcriptionContainer.test.ts @@ -0,0 +1,116 @@ +// transcriptionContainer (release 23 F2): before the page's Transcribe +// downloads audio, a container already here — a source-media.<ext> in the +// video dir, else the saved-video store's — is transcribed instead; a pointer +// whose container cannot be read is refused with the media guard's sentence; +// a container with no sound, or none at all, takes the download path. +// +// Real ffprobe over tiny lavfi containers (a second at 160×90). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/transcriptionContainer.test.ts + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { transcriptionContainer } from "./transcribeOne"; + +const SLUG = "demo-channel"; +let ROOT = ""; +let WITH_SOUND = ""; +let SILENT = ""; + +const ff = (args: string[]) => execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args]); + +before(async () => { + ROOT = await mkdtemp(path.join(tmpdir(), "transcription-container-")); + WITH_SOUND = path.join(ROOT, "with-sound.mp4"); + SILENT = path.join(ROOT, "silent.mp4"); + ff([ + "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:duration=1", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", WITH_SOUND, + ]); + ff([ + "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", SILENT, + ]); +}); +after(() => rm(ROOT, { recursive: true, force: true })); + +async function video(): Promise<{ paths: Paths; videoDir: string; store: string }> { + const root = await mkdtemp(path.join(ROOT, "t-")); + const paths = { + transcriptsDir: path.join(root, "transcripts"), + savedVideosDir: path.join(root, "transcripts", "saved-videos"), + ffprobeBin: "ffprobe", + } as Paths; + const videoDir = path.join(paths.transcriptsDir, "channels", SLUG, "data", "abc123"); + const store = path.join(paths.savedVideosDir, SLUG, "abc123"); + await mkdir(videoDir, { recursive: true }); + await mkdir(store, { recursive: true }); + return { paths, videoDir, store }; +} + +async function point(videoDir: string, store: string, file: string | null): Promise<string> { + if (file) await copyFile(file, path.join(store, "source-media.mp4")); + await writeFile( + path.join(videoDir, "saved-video.json"), + JSON.stringify({ storedAt: "", dir: store, file: "source-media.mp4", bytes: 1 }), + ); + return path.join(store, "source-media.mp4"); +} + +const ask = (paths: Paths, videoDir: string, entries: string[]) => + transcriptionContainer({ paths, slug: SLUG, videoDir, entries }); + +test("a saved container with sound is transcribed from, not downloaded around", async () => { + const { paths, videoDir, store } = await video(); + const file = await point(videoDir, store, WITH_SOUND); + assert.deepEqual(await ask(paths, videoDir, ["saved-video.json"]), { kind: "container", file, from: "saved-video" }); +}); + +test("a pointer whose container cannot be read is refused with the media guard's sentence", async () => { + const { paths, videoDir, store } = await video(); + const file = await point(videoDir, store, null); + const r = await ask(paths, videoDir, ["saved-video.json"]); + assert.equal(r.kind, "unreadable"); + assert.equal( + r.kind === "unreadable" ? r.error : "", + `Channel "${SLUG}": media is not reachable — its saved video ${file} is not there (drive not mounted?)`, + ); +}); + +test("no container at all: the download path", async () => { + const { paths, videoDir } = await video(); + assert.deepEqual(await ask(paths, videoDir, ["metadata.info.json"]), { kind: "none" }); +}); + +test("a container with no sound: the download path", async () => { + const { paths, videoDir, store } = await video(); + const file = await point(videoDir, store, SILENT); + assert.deepEqual(await ask(paths, videoDir, ["saved-video.json"]), { kind: "no-audio", file }); +}); + +test("a source-media container in the video dir comes first, as resolveAudioFile reads it", async () => { + const { paths, videoDir, store } = await video(); + await point(videoDir, store, SILENT); + await copyFile(WITH_SOUND, path.join(videoDir, "source-media.mp4")); + assert.deepEqual(await ask(paths, videoDir, ["saved-video.json", "source-media.mp4"]), { + kind: "container", + file: path.join(videoDir, "source-media.mp4"), + from: "video-dir", + }); + // A silent one there is the download path (the worker would read it first). + await copyFile(SILENT, path.join(videoDir, "source-media.mp4")); + assert.deepEqual(await ask(paths, videoDir, ["saved-video.json", "source-media.mp4"]), { + kind: "no-audio", + file: path.join(videoDir, "source-media.mp4"), + }); + // One ffprobe cannot read is passed over for the pointer. + await writeFile(path.join(videoDir, "source-media.mp4"), "not a container"); + await point(videoDir, store, WITH_SOUND); + assert.equal((await ask(paths, videoDir, ["saved-video.json", "source-media.mp4"])).kind, "container"); +}); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -89,7 +89,7 @@ const DECLARED: EnvVarDecl[] = [ paths("STAGIT_BIN", "`stagit` on PATH, then `~/.local/bin/stagit`", "stagit, which renders the source's history pages (`/source/git/`: the log and a page per commit with its diff). Optional: without it the source is published without them. See [PUBLISH.md](PUBLISH.md)."), // ── runtime ──────────────────────────────────────────────────────────── - { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback). Set the same value on both ends." }, + { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." }, { name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." }, { name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." }, { name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." }, @@ -118,7 +118,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "CLAUDE_DIGEST_MODEL", audience: "runtime", default: "the CLI's default", readBy: "common/lib/digestApps.ts", doc: "The model the metered digest lane asks `claude` for when settings name none." }, { name: "NITTER_INSTANCES", audience: "runtime", default: "a built-in list", readBy: "common/social/xNitterFetcher.ts", doc: "Comma-separated Nitter instances for the X fallback fetcher, in order of preference." }, { name: "ARCHILYZER_X_BROWSER", audience: "runtime", default: "the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium", readBy: "common/social/xBrowser.ts", doc: "The Chromium-family browser /settings' \"Connect X account\" opens (a path, or a name looked up on PATH), and a forum-thread channel's \"Connect forum session\" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser." }, - { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there (e.g. `http://localhost:3050`)." }, + { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, { name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." }, diff --git a/common/lib/evidenceClip-server.test.ts b/common/lib/evidenceClip-server.test.ts @@ -13,6 +13,7 @@ import { copyFile, mkdir, mkdtemp, readdir, rm, symlink, utimes, writeFile } fro import { tmpdir } from "node:os"; import path from "node:path"; import { + citedEvidenceSpan, evidenceCutArgs, evidenceHash, evidenceSpan, @@ -109,6 +110,35 @@ test("tiers: a clip window, else the saved container, else nothing; the window w assert.equal(both?.kind, "corpus-window"); }); +test("tiers: a Twitch record's v<n> finds its data/<n>/ — every tier, and the duration clamp (release 23 F1)", async () => { + const root = await mkdtemp(path.join(ROOT, "tw-")); + const channelsDir = path.join(root, "channels"); + const slug = "example-twitch"; + const n = "2700000001"; + const dir = path.join(channelsDir, slug, "data", n); + await mkdir(path.join(dir, "clips"), { recursive: true }); + // No platform key: the channel's url says Twitch, as on a real Twitch channel. + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.twitch.tv/example" })); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: `v${n}`, duration: 5 })); + const ask = (span: { from: number; to: number }, audio = false) => + resolveEvidenceSource({ channelsDir, slug, id: `v${n}`, span, audio }); + + await copyFile(SOUND, path.join(dir, "audio.m4a")); + assert.equal((await ask({ from: 1, to: 3 }, true))?.kind, "audio"); + await writeFile(path.join(dir, "saved-video.json"), JSON.stringify({ dir, file: "held.mp4" })); + await copyFile(SMALL, path.join(dir, "held.mp4")); + assert.equal((await ask({ from: 1, to: 3 }))?.kind, "saved-video"); + await copyFile(SMALL, path.join(dir, "clips", "0.00-6.00.mp4")); + const win = await ask({ from: 1, to: 3 }); + assert.equal(win?.kind, "corpus-window"); + assert.equal(win?.path, path.join(dir, "clips", "0.00-6.00.mp4")); + // The duration is read from data/<n>/metadata.info.json. + assert.deepEqual(await citedEvidenceSpan(channelsDir, slug, `v${n}`, { start: 2, end: 9 }), { from: 2, to: 5 }); + // A v-id on a channel of another platform is never mapped. + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); + assert.equal(await ask({ from: 1, to: 3 }), null); +}); + test("tiers: the sound is asked only when allowed, and never beats a picture", async () => { const { channelsDir, videoDir } = await corpus(); const span = { from: 1, to: 3 }; diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts @@ -56,6 +56,7 @@ import { ffprobeSource, resolveCorpusSource, } from "./evidenceClip.mjs"; +import { resolveVideoDir } from "./videoDir-server.mjs"; // Bumped whenever the arguments below change what a clip looks like: it is in // every hash, so a new profile re-cuts rather than serving an old file. @@ -92,8 +93,9 @@ export function clampSpanToDuration(span: EvidenceSpan, duration: number | null } // A record's duration (its metadata.info.json), or null when it is not recorded. +// The record's directory, not a join on its id: a Twitch `v<n>` is `data/<n>/`. export async function recordDuration(channelsDir: string, slug: string, id: string): Promise<number | null> { - const read = await readJsonFile(path.join(channelsDir, slug, "data", id, "metadata.info.json")); + const read = await readJsonFile(path.join(await resolveVideoDir(channelsDir, slug, id), "metadata.info.json")); const d = read.ok ? Number((read.value as { duration?: unknown } | null)?.duration) : NaN; return Number.isFinite(d) && d > 0 ? d : null; } diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs @@ -41,6 +41,7 @@ import { execFile } from "node:child_process"; import { readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; +import { resolveVideoDir } from "./videoDir-server.mjs"; const execFileP = promisify(execFile); @@ -74,7 +75,7 @@ export async function listNames(dir) { * @typedef {{ name: string, path: string, from: number, to: number, height?: number }} SourceWindow * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number }} LocalSource * @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe - * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe }} TierContext + * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null }} TierContext * @typedef {{ kind: string, windows: (ctx: TierContext) => Promise<SourceWindow[]>, audio?: boolean }} SourceTier */ @@ -107,7 +108,9 @@ export function tightestContaining(windows, from, to) { } /** - * A video's directory in a channels tree: `<channelsDir>/<slug>/data/<id>`. + * A video's directory in a channels tree: `<channelsDir>/<slug>/data/<id>`, the + * plain join. A RECORD's id goes through `recordDirOf` instead: a Twitch + * record's `v<n>` lives in `data/<n>/` (./videoDir-server.mjs). * @param {string} channelsDir * @param {string} slug * @param {string} video @@ -117,6 +120,20 @@ export function videoDirOf(channelsDir, slug, video) { } /** + * The directory a RECORD's media lives in: `videoDirOf` over the directory id + * the record maps to (release 23 F1 — a Twitch `v<n>` is `data/<n>/`; every + * other id is itself, with no read). `platform` is the record's when the + * caller knows it, else the channel's config is read. + * @param {string} channelsDir + * @param {string} slug + * @param {string} video + * @param {string | null} [platform] + */ +export function recordDirOf(channelsDir, slug, video, platform) { + return resolveVideoDir(channelsDir, slug, video, platform !== undefined ? { platform } : {}); +} + +/** * Where the editor's fetch-window puts a video's windows (lib/clipWindow.ts). * @param {string} videoDir */ @@ -273,18 +290,18 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr // channelsDir or slug) lists nothing. /** @param {TierContext} ctx */ -async function corpusWindows({ video, slug, channelsDir }) { +async function corpusWindows({ video, slug, channelsDir, platform }) { if (!channelsDir || !slug) return []; - const dir = corpusClipsDir(videoDirOf(channelsDir, slug, video)); + const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform)); return windowsFromBareNames(await listNames(dir), dir); } /** @param {TierContext} ctx */ -async function savedVideoWindows({ video, slug, channelsDir, probe = ffprobeSource }) { +async function savedVideoWindows({ video, slug, channelsDir, platform, probe = ffprobeSource }) { if (!channelsDir || !slug) return []; /** @type {SourceWindow[]} */ const out = []; - for (const c of await wholeContainersOf(videoDirOf(channelsDir, slug, video))) { + for (const c of await wholeContainersOf(await recordDirOf(channelsDir, slug, video, platform))) { // Existence BEFORE the probe: an unmounted drive must not cost a timeout. if (!(await present(c.path))) continue; const info = await probe(c.path); @@ -301,9 +318,9 @@ async function savedVideoWindows({ video, slug, channelsDir, probe = ffprobeSour // The ONE best audio file, not every one: they are all the same recording, and // probing three formats of it would buy nothing. /** @param {TierContext} ctx */ -async function audioWindows({ video, slug, channelsDir, probe = ffprobeSource }) { +async function audioWindows({ video, slug, channelsDir, platform, probe = ffprobeSource }) { if (!channelsDir || !slug) return []; - for (const f of await audioFilesOf(videoDirOf(channelsDir, slug, video))) { + for (const f of await audioFilesOf(await recordDirOf(channelsDir, slug, video, platform))) { if (!(await present(f.path))) continue; const duration = Number((await probe(f.path))?.duration); if (!Number.isFinite(duration) || duration <= 0) continue; @@ -373,15 +390,16 @@ export async function resolveFromTiers(tiers, ctx, from, to, opts = {}) { * * @param {{ video: string, slug: string, from: number, to: number }} want * `from`/`to` are the PADDED span. - * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean }} config - * `audio` admits the audio tier (default false). + * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean, platform?: string | null }} config + * `audio` admits the audio tier (default false); `platform` is the record's, + * when known (else its channel's is read — recordDirOf). * @returns {Promise<LocalSource | null>} */ export async function resolveCorpusSource(want, config) { const { video, slug, from, to } = want; - const { channelsDir, probe, audio = false } = config; + const { channelsDir, probe, audio = false, platform } = config; if (!video || !slug || !Number.isFinite(from) || !Number.isFinite(to)) return null; - return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe }, from, to, { + return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe, platform }, from, to, { allow: (tier) => (tier.audio ? audio : true), }); } diff --git a/common/lib/videoDir-server.mjs b/common/lib/videoDir-server.mjs @@ -0,0 +1,74 @@ +// videoDir-server — the disk half of ./videoDirId.mjs: which `data/<dir>/` a +// record's id lives in ON THIS DISK (release 23 F1, the Twitch join, option +// (b)). Plain JS for umtool's bare-node scripts; server-only (node:fs). It +// never computes a path from the cwd: every root arrives as an argument. + +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { channelConfigPlatform, pickVideoDirId, twitchVodDirId } from "./videoDirId.mjs"; + +/** @param {string} p */ +async function isDir(p) { + try { + return (await stat(p)).isDirectory(); + } catch { + return false; + } +} + +/** + * A channel's platform, read from its config.json; null when unreadable. + * @param {string} channelsDir + * @param {string} slug + * @returns {Promise<string | null>} + */ +export async function readChannelPlatform(channelsDir, slug) { + try { + const raw = JSON.parse( + await readFile(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8"), + ); + return channelConfigPlatform(raw); + } catch { + return null; + } +} + +/** + * The directory id a record lives in, on this disk. Only a `v<digits>` id + * costs a read (the channel's config when no platform is given, and two + * stats); every other id is returned as it is. + * @param {string} channelsDir + * @param {string} slug + * @param {string} recordId + * @param {{ platform?: string | null }} [opts] the record's (or channel's) + * platform, when the caller already knows it. + * @returns {Promise<string>} + */ +export async function resolveVideoDirId(channelsDir, slug, recordId, opts = {}) { + if (twitchVodDirId(recordId) === null) return recordId; + const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug); + if (platform !== "twitch") return recordId; + const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); + const n = /** @type {string} */ (twitchVodDirId(recordId)); + const [hasN, hasV] = await Promise.all([ + isDir(path.join(/* turbopackIgnore: true */ dataDir, n)), + isDir(path.join(/* turbopackIgnore: true */ dataDir, recordId)), + ]); + return pickVideoDirId(recordId, { + platform, + exists: (id) => (id === n ? hasN : id === recordId ? hasV : false), + }); +} + +/** + * The directory a record lives in: `<channelsDir>/<slug>/data/<dir id>`. + * @param {string} channelsDir + * @param {string} slug + * @param {string} recordId + * @param {{ platform?: string | null }} [opts] + * @returns {Promise<string>} + */ +export async function resolveVideoDir(channelsDir, slug, recordId, opts = {}) { + const dirId = await resolveVideoDirId(channelsDir, slug, recordId, opts); + return path.join(/* turbopackIgnore: true */ channelsDir, slug, "data", dirId); +} diff --git a/common/lib/videoDirId.mjs b/common/lib/videoDirId.mjs @@ -0,0 +1,78 @@ +// videoDirId — which `data/<dir>/` a RECORD's id lives in (release 23 F1, the +// Twitch join, option (b), ruled 2026-10-10). +// +// A Twitch VOD's directory is its canonical id, the URL's `/videos/<n>` +// (`extractVideoId`), while its record carries yt-dlp's native id `v<n>`. The +// published `v<n>` URLs stay; the join between the two normalizes on the +// DIRECTORY side, here, once. Records and published ids are never rewritten. +// +// - A record id that is not `v<digits>` passes through untouched, with no +// filesystem read: every other platform, and every record but a Twitch +// VOD's. +// - A `v<digits>` id maps to `<digits>` only for a TWITCH record (the record's +// platform, else its channel's: config.json `platform`, else the host of +// its `url`). A `v`-prefixed id of any other platform (a Rumble slug, a +// YouTube id that happens to read `v` + ten digits) is never guessed at. +// - Between the two directories the one that EXISTS wins, `<n>` first (it is +// the one the download made, with the metadata); with neither, `<n>`, the +// canonical name, so a writer (fetch-window) creates the right one. +// +// Plain JS with JSDoc types, for the reason detectPlatform.mjs is: umtool's +// report-to-video scripts run under bare `node` and read these directories too +// (evidenceClip.mjs, cues.mjs). `lib/videoId.ts` re-exports it; TS callers +// import it from there. PURE (client-safe, as videoId.ts is): the disk half — +// which directory exists — is ./videoDir-server.mjs. + +import { detectPlatform } from "./detectPlatform.mjs"; + +const TWITCH_RECORD_ID_RE = /^v(\d+)$/; +const TWITCH_DIR_ID_RE = /^\d+$/; + +/** + * A Twitch record id's directory id: `v<n>` → `<n>`; anything else → null. + * Pure: says what the id would map to, not that the record is Twitch's. + * @param {string} recordId + * @returns {string | null} + */ +export function twitchVodDirId(recordId) { + const m = TWITCH_RECORD_ID_RE.exec(recordId); + return m ? m[1] : null; +} + +/** + * The reverse: a Twitch VOD directory `<n>` → the record id `v<n>` its record + * carries; anything else → null. + * @param {string} dirId + * @returns {string | null} + */ +export function twitchVodRecordId(dirId) { + return TWITCH_DIR_ID_RE.test(dirId) ? `v${dirId}` : null; +} + +/** + * The platform a channel's config names: `platform`, else its `url`'s host + * (ytdlp/channelArgs.ts channelPlatform's rule). Null for none. + * @param {{ platform?: unknown, url?: unknown } | null | undefined} config + * @returns {string | null} + */ +export function channelConfigPlatform(config) { + if (!config || typeof config !== "object") return null; + if (typeof config.platform === "string" && config.platform) return config.platform; + return typeof config.url === "string" ? detectPlatform(config.url) : null; +} + +/** + * The directory id for a record, given its platform and which directories + * exist. Synchronous over an `exists` callback, so a caller with its own + * listing (or a test) decides without touching the disk. + * @param {string} recordId + * @param {{ platform?: string | null, exists: (dirId: string) => boolean }} opts + * @returns {string} + */ +export function pickVideoDirId(recordId, { platform, exists }) { + const n = twitchVodDirId(recordId); + if (n === null || platform !== "twitch") return recordId; + if (exists(n)) return n; + if (exists(recordId)) return recordId; + return n; +} diff --git a/common/lib/videoDirId.test.ts b/common/lib/videoDirId.test.ts @@ -0,0 +1,95 @@ +// The Twitch join, option (b) (release 23 F1): a record keeps yt-dlp's `v<n>`, +// its directory is the canonical `<n>`, and the join maps one to the other on +// the directory side. Cases from release 20 D2's `twitchId.test.ts` +// (r20/twitch-ids 433815d4), without its re-keying of records. Synthetic ids. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/videoDirId.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + channelConfigPlatform, + extractVideoId, + pickVideoDirId, + twitchVodDirId, + twitchVodRecordId, +} from "./videoId"; +import { resolveVideoDir, resolveVideoDirId } from "./videoDir-server.mjs"; + +const N = "1234567890"; +const META = { id: `v${N}`, webpage_url: `https://www.twitch.tv/videos/${N}` }; + +test("twitchVodDirId drops only a v before digits; twitchVodRecordId is its reverse", () => { + assert.equal(twitchVodDirId(`v${N}`), N); + assert.equal(twitchVodDirId(N), null); + assert.equal(twitchVodDirId("vod-clip-slug"), null); + assert.equal(twitchVodDirId("v"), null); + assert.equal(twitchVodDirId("v12a"), null); + // The id the URL gives, which is what data/<id>/ is named. + assert.equal(extractVideoId(META.webpage_url), twitchVodDirId(META.id)); + assert.equal(twitchVodRecordId(N), `v${N}`); + assert.equal(twitchVodRecordId(`v${N}`), null); + assert.equal(twitchVodRecordId("abc"), null); + assert.equal(twitchVodRecordId(twitchVodDirId(META.id)!), META.id); +}); + +test("channelConfigPlatform: the platform key, else the url's host", () => { + assert.equal(channelConfigPlatform({ platform: "twitch" }), "twitch"); + assert.equal(channelConfigPlatform({ url: "https://www.twitch.tv/example" }), "twitch"); + assert.equal(channelConfigPlatform({ platform: "youtube", url: "https://www.twitch.tv/x" }), "youtube"); + assert.equal(channelConfigPlatform({}), null); + assert.equal(channelConfigPlatform(null), null); +}); + +test("pickVideoDirId: a Twitch v<n> prefers <n>, then v<n>, then the canonical <n>", () => { + const has = (...ids: string[]) => (id: string) => ids.includes(id); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(N) }), N); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(N, `v${N}`) }), N); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(`v${N}`) }), `v${N}`); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has() }), N); + // Already the directory's id. + assert.equal(pickVideoDirId(N, { platform: "twitch", exists: has(N) }), N); +}); + +test("pickVideoDirId never guesses a v-prefixed id of another platform", () => { + const all = () => true; + assert.equal(pickVideoDirId(`v${N}`, { platform: "youtube", exists: all }), `v${N}`); + assert.equal(pickVideoDirId("v4abcde", { platform: "rumble", exists: all }), "v4abcde"); + assert.equal(pickVideoDirId(`v${N}`, { platform: null, exists: all }), `v${N}`); + assert.equal(pickVideoDirId(`v${N}`, { exists: all }), `v${N}`); +}); + +const ROOT = mkdtempSync(path.join(tmpdir(), "video-dir-id-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +function channel(slug: string, config: object, dirs: string[]): string { + const channelsDir = path.join(ROOT, slug + "-root"); + mkdirSync(path.join(channelsDir, slug, "data"), { recursive: true }); + writeFileSync(path.join(channelsDir, slug, "config.json"), JSON.stringify(config)); + for (const d of dirs) mkdirSync(path.join(channelsDir, slug, "data", d), { recursive: true }); + return channelsDir; +} + +test("resolveVideoDirId: a Twitch channel's v<n> record is its data/<n>/", async () => { + // Platform from the url (no platform key), and from the key. + const byUrl = channel("tw-url", { handling: "transcribe", url: "https://www.twitch.tv/example" }, [N]); + assert.equal(await resolveVideoDirId(byUrl, "tw-url", `v${N}`), N); + assert.equal(await resolveVideoDir(byUrl, "tw-url", `v${N}`), path.join(byUrl, "tw-url", "data", N)); + const byKey = channel("tw-key", { handling: "transcribe", platform: "twitch" }, [N]); + assert.equal(await resolveVideoDirId(byKey, "tw-key", `v${N}`), N); + // The id is never rewritten where it is the directory's own. + assert.equal(await resolveVideoDirId(byKey, "tw-key", N), N); + // A caller that knows the platform is believed over the config. + assert.equal(await resolveVideoDirId(byKey, "tw-key", `v${N}`, { platform: "youtube" }), `v${N}`); +}); + +test("resolveVideoDirId: other platforms and other ids pass through", async () => { + const yt = channel("yt", { handling: "youtube", url: "https://www.youtube.com/@x" }, [N, `v${N}`]); + assert.equal(await resolveVideoDirId(yt, "yt", `v${N}`), `v${N}`); + assert.equal(await resolveVideoDirId(yt, "yt", "dQw4w9WgXcQ"), "dQw4w9WgXcQ"); + // No config at all: never guessed. + assert.equal(await resolveVideoDirId(path.join(ROOT, "none"), "nobody", `v${N}`), `v${N}`); +}); diff --git a/common/lib/videoId.ts b/common/lib/videoId.ts @@ -12,6 +12,18 @@ import { isArchiveOrgItemHost, parseArchiveOrgUrl, archiveOrgVideoId } from "./archiveOrgId"; import { isJwPlayerHost, isWaybackHost, jwPlayerMediaId, parseWaybackUrl } from "./wayback"; +// A RECORD's id against its DIRECTORY's (release 23 F1, the Twitch join, +// option (b)): a Twitch record carries yt-dlp's native `v<n>` while its +// directory is the canonical `<n>` below. The join normalizes on the directory +// side; records and published ids are unchanged. Plain JS so umtool's bare-node +// scripts share it (./videoDirId.mjs); the disk half is ./videoDir-server.mjs. +export { + channelConfigPlatform, + pickVideoDirId, + twitchVodDirId, + twitchVodRecordId, +} from "./videoDirId.mjs"; + export function extractVideoId(url: string): string | null { return extractVideoIdAt(url, 0); } diff --git a/common/package.json b/common/package.json @@ -37,6 +37,8 @@ "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", "./lib/toolProbe.mjs": "./lib/toolProbe.mjs", + "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", + "./lib/videoDirId.mjs": "./lib/videoDirId.mjs", "./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs", "./lib/*": "./lib/*.ts", "./controller/*": "./controller/*.ts", diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -67,6 +67,7 @@ import { parseReport } from "../lib/report/validate"; import { isReportId, type Report } from "../lib/report/schema"; import { isPermanentlyGone } from "../lib/availability"; import { loadAvailability } from "../lib/availability-server"; +import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow"; import { citedEvidenceSpan, @@ -521,7 +522,7 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`); continue; } - const availability = (await loadAvailability(path.join(paths.channelsDir, slug, "data", id)))?.availability; + const availability = (await loadAvailability(await resolveVideoDir(paths.channelsDir, slug, id)))?.availability; if (isPermanentlyGone(availability)) { unfetchable("gone", `the source says the video is ${availability}`); continue; diff --git a/common/publish/reportMediaTwitch.test.ts b/common/publish/reportMediaTwitch.test.ts @@ -0,0 +1,88 @@ +// The Twitch join, option (b), in a site's evidence read (release 23 F1): a +// report cites a Twitch record by its `v<n>`, and the media, duration and +// availability are read from its `data/<n>/`. The citation's id is reported +// as cited — never rewritten. Synthetic ids; no ffmpeg (nothing is cut). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/reportMediaTwitch.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "report-media-twitch-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), +}); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { missingEvidenceWindows } = await import("./reportMedia"); + +const paths = getPaths(); +const SITE = "demo-site"; +const CH = "example-twitch"; +const GONE = "2700000001"; +const HELD = "2700000002"; +const OPEN = "2700000003"; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const dataDir = (id: string) => path.join(paths.channelsDir, CH, "data", id); + +writeJson(path.join(paths.channelsDir, CH, "config.json"), { + handling: "transcribe", + name: "Example", + url: "https://www.twitch.tv/example", +}); +for (const id of [GONE, HELD, OPEN]) { + writeJson(path.join(dataDir(id), "metadata.info.json"), { id: `v${id}`, duration: 600 }); +} +writeJson(path.join(dataDir(GONE), "availability.json"), { availability: "deleted", checkedAt: "2026-10-01T00:00:00Z" }); +// A window file is only listed, never probed, by the corpus-window tier. +mkdirSync(path.join(dataDir(HELD), "clips"), { recursive: true }); +writeFileSync(path.join(dataDir(HELD), "clips", "0.00-60.00.mp4"), "mp4"); + +writeJson(path.join(paths.sitesDir, SITE, "site.json"), { + title: "Demo", + channels: [{ slug: CH }], + search: false, + reports: ["r1"], +}); +writeJson(path.join(paths.sitesDir, SITE, "reports", "r1", "report.json"), { + format: "archilyzer-report", + version: 1, + id: "r1", + kind: "sweep", + title: "Report r1", + citations: { + c01: { kind: "video", channel: CH, id: `v${GONE}`, start: 10, end: 12, quote: "one" }, + c02: { kind: "video", channel: CH, id: `v${HELD}`, start: 10, end: 12, quote: "two" }, + c03: { kind: "video", channel: CH, id: `v${OPEN}`, start: 10, end: 12, quote: "three" }, + }, + sections: [{ id: "s1", title: "One", body: "[c01](cite:c01) [c02](cite:c02) [c03](cite:c03)" }], +}); + +test("missingEvidenceWindows reads a Twitch v<n> citation's media and availability from data/<n>/", async () => { + const r = await missingEvidenceWindows(paths, SITE); + assert.deepEqual(r.problems, []); + // The held window is on disk (data/<HELD>/clips/). + assert.equal(r.onDisk, 1); + // The deleted one is gone, read from data/<GONE>/availability.json. + assert.deepEqual( + r.unfetchable.map((w) => [w.id, w.why]), + [[`v${GONE}`, "gone"]], + ); + // The open one is missing, and named by the id the report cites. + assert.deepEqual(r.missing.map((w) => w.id), [`v${OPEN}`]); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -131,6 +131,11 @@ - **A video whose YouTube subtitles answer "Too Many Requests" (HTTP 429) is downloaded anyway, and YouTube is not put in a cooldown for it.** YouTube refuses a subtitle file per video while the video itself downloads fine; every one of the day's 429s on 2026-10-01 was a subtitle fetch, and each failed its download, put all of YouTube in a cooldown that reached 30 minutes, and deferred the video for 6 hours to fail the same way again. Now that refusal is noted and the download goes on to the audio, as for a video with no captions, so the transcription lane transcribes it; nothing platform-wide is backed off. The video's subtitles are deferred: **Download missing subs** skips them for 6 hours, and from the third time they are refused, for 7 days; a download from the video's own page still fetches them. The download lane's page lists them under **Deferred subtitles**, and the video page says how many times and when. **Download missing subs** also goes on to the next video when one video's subtitles are refused, instead of stopping. Any other subtitle failure (a 403, a missing file, a chat replay that fails) still fails the download, as before. Needs a rebuild and restart of the editor. - **The download pace adapts to rate limits, a rate limit that outlasts the cooldown holds the platform, and the auto-download lane waits between downloads.** Every yt-dlp run against a platform now waits its platform's current pace between requests: 1 second for YouTube and Rumble, doubled by each real rate limit (up to 16 seconds) and eased back one step after every 5 clean downloads, and one step for every hour with no rate limit; a subtitle-only refusal never raises it. When a platform has failed three times in a row at the 30-minute cooldown, it is **held**: auto-download tries it once an hour instead of every 30 minutes, and until that try is due a manual **Sync**, download or metadata scan on it is refused with a sentence giving its time. A clean try lifts the hold — the lane's, or a manual Sync, download or scan once the try is due, which is how a hold ends while auto-download is off or has nothing to fetch on that platform — and so does a try whose video came down although its subtitles were refused. The lane page keeps a held platform listed until then (saying when the lane is off), with a **Clear hold** button that drops the hold, the cooldown and the raised pace at once and says so in a job log. The auto-download lane now waits **Sleep between downloads** between two downloads on one platform, as a channel's batch downloads always did, plus whatever the pace was raised by; batch downloads add that too. The lane page's **Rate-limit cooldown** box shows held platforms, the raised paces and the deferred subtitles, the lane says when it is idle because a platform is held or it is pausing between downloads, and `archilyzer doctor` warns about a platform in a cooldown or held, and about a raised pace. **Download missing subs** also waits that gap between videos. The four numbers are the new `pacing` block in `settings.json` (SETTINGS.md). **After the restart, YouTube may be held at its first real failure:** its cooldown count from before the update (the subtitle refusals) still stands, so one failure puts it straight past the cap — **Clear hold** on the download lane's page resets it, and a clean download does too. Needs a rebuild and restart of the editor. - **A podcast channel's episodes imported by their enclosure URL get their titles and dates back from the feed.** Such a record carried only its file name as its title and no upload date, so the index skipped it and every surface showed the file id. `archilyzer feeds backfill-metadata <slug> [--feed <url>] [--dry-run]`, `POST /api/ops/feed-metadata {slug, dryRun?}` and `pnpm ops feed-metadata` (the new `feed-metadata` job, on the channel's download queue) fetch the channel's RSS feed once — no media — and match each record lacking a date or a real title to an item by guid, enclosure URL or enclosure file name; a record more than one item fits is reported, not guessed. A match fills in what the record lacks: the title, the description as plain text, the duration (a measured one is kept), the upload date and timestamp in UTC, and `webpage_url` only when the new URL keeps the record's id. Every change is a `feed-backfill` entry in the video's metadata history; a dry run counts matched, unmatched and already complete and writes nothing. Rebuild the index afterwards for the titles and dates to reach search and the sites. +- **A Twitch VOD cited by its published id is found on disk.** A Twitch video's folder is named by its number while its record (and its public page) says `v` and the number, so a clip fetch asked by the record's id (the MCP's `fetch_clip`, **Fetch missing evidence**, `pnpm ops fetch-windows`), a site's evidence clips and its missing-evidence list, and umtool's local cue lookup looked in a folder that does not exist: a clip or saved video already on disk was not found, and the video's availability and length were not read. They now look in the video's own folder. Published ids and URLs do not change. Needs a rebuild and restart of the editor and of umtool. +- **Transcribe uses a video's saved source video instead of downloading its audio.** A video with no audio on disk but its whole recording in the saved-video store (a persisted video, a whole-source fetch, or one attached from a local archive) was downloaded again for its audio when **Transcribe** was clicked on its page or `pnpm ops transcribe-one` was run. Its saved video is now transcribed as it is, and the job's log says so ("transcribing from the saved container … — nothing downloaded"). When the saved video's drive is not mounted or not answering, the job stops with the same "media is not reachable" sentence as a clip fetch, rather than downloading; a saved video with no sound is downloaded around as before. Needs a rebuild and restart of the editor. +- **An agent can answer the operator's notes in umtool, and its replies say they are an agent's.** The MCP's `notes` tool now writes a reply (`action: "reply"`, with `note_id`, `text` and `resolve`) in umtool instead of answering with the `umtool notes reply` command to run; umtool stamps it "agent" and badges it on the page. umtool takes an agent's write only with the editor's `WORKER_TOKEN` as a bearer token — from its own environment, else the editor's `editor/.env` — and refuses any other token (401); a write from umtool's own page is the operator's as before. Register the MCP with `UMTOOL_URL` and `WORKER_TOKEN`. Needs a rebuild and restart of umtool, and a restart of the MCP server. +- **Captions the index re-read under the newer caption-track rule now reach the stats and charts.** When the index re-reads a video's captions without any of its files changing — as it did once for videos whose served `en` track had parsed to nothing — the stats behind the homepage, the hub and the sites' charts kept the old figures (no transcript, the old cue count) until something else about the video changed. The stats now follow the captions the index holds, and the first stats build after updating corrects the videos already affected. Needs a rebuild and restart of the editor, then a stats build (or a site, hub or homepage build). +- **Every e2e run records its own per-spec timings.** The editor, umtool, homepage and export suites now record each run in the branch's timing history the moment it ends (`scripts/e2e-timings-reporter.mjs`), so re-running a few specs no longer loses the record of the full run before it; `node scripts/e2e-timings.mjs` still prints a run against the last one. umtool's suite skips, with the reason, the face-detector tests on a machine without the detector and the chunk-twin check when the data has no twins, instead of failing. ## [0.11.0] - 2026-09-30 - **Transcripts that arrived after a video was first seen are counted.** The stats behind the homepage, the hub and every site's charts were cached per video and refreshed only when the video's metadata changed, so a transcript that came later — a Whisper run days after the download, or a video downloaded after the last index build — never reached them, and a video with YouTube captions alone had no transcription date. Counts and charts were low; the homepage could show a site with 0 transcripts, 0 channels and 0 hours while it served its videos. A stat is now also redone whenever the index re-reads the video, every transcript has a date, and a captioned video is dated by when its captions arrived rather than by a later Normalize run, so its place on "Transcribed over time" can move. **After updating, rebuild and restart the editor before anything else:** until then, **Build stats dataset** runs the old code and would undo the new stats, while a site, hub or homepage build already runs the new code — and the first stats build of any kind re-reads every video once (about 10–30 minutes on a large archive; it can be stopped and picks up where it stopped). Then build the index, the stats, the homepage, the hub, and the sites. diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -59,7 +59,10 @@ import { removeMediaFile, removeVideoDirMedia, } from "yt-dlp-transcript-common/lib/mediaTier-server"; -import { transcribeWithWorker } from "yt-dlp-transcript-common/controller/transcribeOne"; +import { + transcribeWithWorker, + transcriptionContainer, +} from "yt-dlp-transcript-common/controller/transcribeOne"; import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; import { loadSavedVideo, @@ -88,6 +91,8 @@ import { } from "yt-dlp-transcript-common/ytdlp/fetchWindowManaged"; import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration"; import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; +import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { applyTagAssignmentsAction } from "../../../../tags/actions"; import { heldPlatformRefusal, @@ -120,6 +125,16 @@ function videoDirOf(slug: string, videoId: string): string { return path.join(getPaths().channelsDir, slug, "data", videoId); } +// The DIRECTORY id for an id that may be a RECORD's (release 23 F1). The +// editor's own pages name a video by its directory, but the fetch paths are +// also asked by record id (the MCP's fetch_clip, a report's citations), and a +// Twitch record's `v<n>` lives in `data/<n>/`. Every other id is itself. +async function recordDirIdOf(slug: string, videoId: string, config: ChannelConfig): Promise<string> { + return resolveVideoDirId(getPaths().channelsDir, slug, videoId, { + platform: channelConfigPlatform(config), + }); +} + async function loadConfigOrError( slug: string, ): Promise< @@ -447,7 +462,26 @@ export async function whisperVideoAction( const audioFormat = r.config.audioFormat ?? "mp3"; const entries = await readdir(videoDir).catch(() => [] as string[]); const hasAudio = entries.some(isRealAudioFile); - if (!hasAudio) { + // NO AUDIO, BUT A CONTAINER (release 23 F2): a source-media.<ext> here or + // the saved-video store's container is transcribed as it is — the worker + // resolves it (resolveAudioFile) — and nothing is downloaded. A pointer + // whose container cannot be read is refused with the media guard's + // sentence, never downloaded around; a container with no sound takes the + // download path below. + const held = hasAudio + ? null + : await transcriptionContainer({ paths, slug, videoDir, entries }); + if (held?.kind === "unreadable") throw new Error(held.error); + if (held?.kind === "container") { + onLog( + `No audio on disk for ${videoId}; transcribing from ` + + `${held.from === "saved-video" ? "the saved container" : "the source container"} ` + + `${held.file} — nothing downloaded.`, + ); + } else if (!hasAudio) { + if (held?.kind === "no-audio") { + onLog(`The container ${held.file} has no sound; downloading the audio instead.`); + } // Only this branch writes bytes. Transcribing audio that is already on // disk produces a transcript.json measured in kilobytes, so a low disk // is no reason to refuse it — the gate belongs on the fetch, not on the @@ -1057,7 +1091,7 @@ export async function fetchWindowAction(req: { // which renders the log; the HTTP route leaves it off and polls. stream?: boolean; }): Promise<FetchMediaOutcome> { - const { slug, videoId, from, to } = req; + const { slug, from, to } = req; // THE CAP IS CHECKED HERE TOO, not only at the HTTP door. Retry re-runs from // a stored JobSpec, and a spec is a JSON file on disk — a hand-edited one // must not be able to ask for an hour of source through a path the route @@ -1087,6 +1121,9 @@ export async function fetchWindowAction(req: { const r = await loadConfigOrError(slug); if (!r.ok) return { ok: false, status: 404, error: r.error }; const paths = getPaths(); + // From here on the video is named by its directory: the cache, the job, the + // page revalidated (a Twitch record's v<n> is data/<n>/). + const videoId = await recordDirIdOf(slug, req.videoId, r.config); const videoDir = videoDirOf(slug, videoId); // ASK THE CACHE FIRST, and accept a WIDER file: a report cites the same @@ -1118,13 +1155,12 @@ export async function fetchWindowAction(req: { // job, not a second one for the same seconds (jobs/windowJobs.ts). Retry // (`stream: true`) is an explicit re-run and is not deduplicated. if (!req.stream) { - const inFlight = windowInFlight(getRegistry().list(), { - slug, - videoId, - from, - to, - maxHeight: req.maxHeight, - }); + // A batch's item names the record, this job the directory: either may be + // the one already fetching this window (release 23 F1). + const live = getRegistry().list(); + const inFlight = [...new Set([videoId, req.videoId])] + .map((id) => windowInFlight(live, { slug, videoId: id, from, to, maxHeight: req.maxHeight })) + .find((w) => w); if (inFlight) { return { ok: true, @@ -1341,10 +1377,11 @@ export async function fetchFullSourceAction(req: { // Per-fetch quality; absent = the channel's, else the global setting. quality?: SourceVideoQuality; }): Promise<FetchMediaOutcome> { - const { slug, videoId } = req; + const { slug } = req; const r = await loadConfigOrError(slug); if (!r.ok) return { ok: false, status: 404, error: r.error }; const paths = getPaths(); + const videoId = await recordDirIdOf(slug, req.videoId, r.config); const videoDir = videoDirOf(slug, videoId); const pointer = await loadSavedVideo(videoDir); diff --git a/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts b/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts @@ -0,0 +1,142 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { chmod, copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/videos/*/whisperFromContainer.test.ts" +// +// The page's Transcribe — and `pnpm ops transcribe-one {slug, id}`, which +// calls the same action — over a video with no audio on disk (release 23 F2): +// a saved container with sound transcribed from it, nothing downloaded +// (the e2e fake whisper-cli does the work); +// a pointer whose file is gone refused with the media guard's sentence, +// nothing downloaded; +// no container the download path, as before; +// a container with no sound the download path, as before. +// The download path's yt-dlp is a fake that records its argv and fails, so +// "downloaded" is a recorded argv, never the network. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "whisper-from-container-")); +const SLUG = "demo-channel"; +const YTDLP_LOG = path.join(ROOT, "ytdlp-argv.jsonl"); +const FAKE_YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +await writeFile( + FAKE_YTDLP, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +appendFileSync(${JSON.stringify(YTDLP_LOG)}, JSON.stringify(process.argv.slice(2)) + "\\n"); +process.stderr.write("ERROR: fake yt-dlp: no network in this test\\n"); +process.exit(1); +`, +); +await chmod(FAKE_YTDLP, 0o755); + +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.YTDLP_BIN = FAKE_YTDLP; +process.env.WHISPER_BIN = path.resolve("e2e/fixtures/bin/fake-whisper.mjs"); +process.env.WHISPER_MODEL = "/dev/null"; +delete process.env.FFPROBE_BIN; +delete process.env.FFMPEG_BIN; + +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); +await writeFile( + path.join(ROOT, "channels", SLUG, "config.json"), + JSON.stringify({ name: "Demo", handling: "transcribe", url: "https://www.youtube.com/@demo", platform: "youtube" }), +); + +const ff = (args: string[]) => execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args]); +const WITH_SOUND = path.join(ROOT, "with-sound.mp4"); +const SILENT = path.join(ROOT, "silent.mp4"); +ff([ + "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:duration=1", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", WITH_SOUND, +]); +ff(["-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", SILENT]); + +// A video dir with metadata (so the download path has a URL) and, optionally, +// a saved-video pointer to a container (a missing one when `file` is null). +async function videoWith(id: string, container: string | null | undefined): Promise<string> { + const dir = path.join(ROOT, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ id, title: id, webpage_url: `https://www.youtube.com/watch?v=${id}` }), + ); + if (container !== undefined) { + const store = path.join(ROOT, "saved-videos", SLUG, id); + await mkdir(store, { recursive: true }); + if (container) await copyFile(container, path.join(store, "source-media.mp4")); + await writeFile( + path.join(dir, "saved-video.json"), + JSON.stringify({ storedAt: "", dir: store, file: "source-media.mp4", bytes: 1 }), + ); + } + return dir; +} + +const { whisperVideoAction } = await import("./videoActions"); +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function ytdlpCalls(): Promise<number> { + return (await readFile(YTDLP_LOG, "utf8").catch(() => "")).split("\n").filter(Boolean).length; +} + +// Runs the action to its end: the job's status, and its log. +async function transcribe(id: string): Promise<{ status: string; log: string }> { + const r = await whisperVideoAction(SLUG, id); + if (!r.ok) throw new Error(r.error); + // Drain the stream so the job is never held up on it. + void (async () => { + const reader = r.stream.getReader(); + while (!(await reader.read()).done) {} + })(); + await r.done; + const rec = getRegistry().get(r.jobId); + const log = rec?.logPath ? await readFile(rec.logPath, "utf8").catch(() => "") : ""; + return { status: rec?.status ?? "?", log }; +} + +test("a saved container with sound is transcribed from, and nothing is downloaded", async () => { + const dir = await videoWith("held1", WITH_SOUND); + const before = await ytdlpCalls(); + const r = await transcribe("held1"); + assert.equal(r.status, "done", r.log); + assert.match(r.log, /No audio on disk for held1; transcribing from the saved container .*source-media\.mp4 — nothing downloaded\./); + assert.equal(await ytdlpCalls(), before, "no yt-dlp run"); + const transcript = JSON.parse(await readFile(path.join(dir, "transcript.json"), "utf8")); + assert.ok(Array.isArray(transcript.transcription)); +}); + +test("a pointer whose container is gone is refused with the guard's sentence, and nothing is downloaded", async () => { + await videoWith("gone1", null); + const before = await ytdlpCalls(); + const r = await transcribe("gone1"); + assert.equal(r.status, "failed", r.log); + assert.match(r.log, /Channel "demo-channel": media is not reachable — its saved video .*source-media\.mp4 is not there \(drive not mounted\?\)/); + assert.equal(await ytdlpCalls(), before, "no yt-dlp run"); +}); + +test("no container: the download path, as before", async () => { + await videoWith("plain1", undefined); + const before = await ytdlpCalls(); + const r = await transcribe("plain1"); + assert.equal(r.status, "failed", r.log); + assert.match(r.log, /No audio on disk for plain1; downloading…/); + assert.equal(await ytdlpCalls(), before + 1); +}); + +test("a container with no sound: the download path, as before", async () => { + await videoWith("silent1", SILENT); + const before = await ytdlpCalls(); + const r = await transcribe("silent1"); + assert.equal(r.status, "failed", r.log); + assert.match(r.log, /The container .*source-media\.mp4 has no sound; downloading the audio instead\./); + assert.equal(await ytdlpCalls(), before + 1); +}); diff --git a/editor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts b/editor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/videos/fetchWindowTwitch.test.ts" +// +// The Twitch join, option (b) (release 23 F1), through the editor's two +// fetch-window doors: a Twitch record's `v<n>` (what the MCP's fetch_clip and +// a report's citation send) is answered from its `data/<n>/`. Nothing here +// reaches the network: every window asked for is cached, or the run is dry. +// Synthetic ids. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-twitch-")); +const SLUG = "example-twitch"; +const N = "2700000001"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +// A missing binary: the cached window's height probe answers null, not a throw. +process.env.FFPROBE_BIN = path.join(ROOT, "no-ffprobe"); + +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); +// No platform key: the url says Twitch, as on a real Twitch channel. +await writeFile( + path.join(ROOT, "channels", SLUG, "config.json"), + JSON.stringify({ name: "Example", handling: "transcribe", url: "https://www.twitch.tv/example" }), +); +const DIR = path.join(ROOT, "channels", SLUG, "data", N); +await mkdir(path.join(DIR, "clips"), { recursive: true }); +await writeFile(path.join(DIR, "clips", "0.00-60.00.mp4"), "mp4"); +await writeFile( + path.join(DIR, "metadata.info.json"), + JSON.stringify({ id: `v${N}`, webpage_url: `https://www.twitch.tv/videos/${N}` }), +); + +const { fetchWindowAction } = await import("./[id]/videoActions"); +const { fetchWindowsAction } = await import("./fetchWindowsAction"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("fetchWindowAction answers a v<n> record from its data/<n>/ window cache", async () => { + const r = await fetchWindowAction({ + slug: SLUG, + videoId: `v${N}`, + from: 5, + to: 15, + provenance: { requestedBy: "test" }, + }); + assert.ok(r.ok, JSON.stringify(r)); + if (!r.ok) return; + assert.equal(r.cached, true); + assert.equal("file" in r ? r.file : null, path.join(DIR, "clips", "0.00-60.00.mp4")); +}); + +test("fetchWindowsAction finds a v<n> item cached in data/<n>/, and the item keeps its id", async () => { + const r = await fetchWindowsAction({ + items: [{ slug: SLUG, id: `v${N}`, from: 5, to: 15, clipId: "r#1" }], + requestedBy: "test", + dryRun: true, + }); + assert.ok(r.ok, JSON.stringify(r)); + if (!r.ok) return; + assert.deepEqual(r.cached.map((i) => i.id), [`v${N}`]); + assert.deepEqual(r.groups, []); + assert.deepEqual(r.unresolved, []); +}); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -26,6 +26,8 @@ import { readChannelConfig, } from "yt-dlp-transcript-common/controller/channels"; import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; +import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { fetchWindows, fetchWindowsItemLabel, @@ -174,18 +176,23 @@ async function planFetchWindows( unresolved.push({ item, error: `Channel "${item.slug}" not found` }); continue; } - const videoDir = path.join(paths.channelsDir, item.slug, "data", item.id); + // The item names a RECORD; its directory may be another id — a Twitch + // record's v<n> is data/<n>/ (release 23 F1). The item keeps its id. + const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { + platform: channelConfigPlatform(config), + }); + const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); if (await findContainingClipWindow(videoDir, item.from, item.to)) { cached.push(item); continue; } - const running = windowInFlight(live, { - slug: item.slug, - videoId: item.id, - from: item.from, - to: item.to, - maxHeight, - }); + // A single fetch-window job names the directory; a batch's item, the + // record: either may be the one already fetching this window. + const running = [...new Set([item.id, dirId])] + .map((videoId) => + windowInFlight(live, { slug: item.slug, videoId, from: item.from, to: item.to, maxHeight }), + ) + .find((r) => r); if (running) { inFlight.push({ item, jobId: running.jobId }); continue; @@ -216,7 +223,7 @@ async function planFetchWindows( } const url = item.webpageUrl?.trim() || - (await findVideoSourceUrl(paths, item.slug, item.id, config)); + (await findVideoSourceUrl(paths, item.slug, dirId, config)); if (!url) { unresolved.push({ item, diff --git a/editor/e2e/import-video.spec.ts b/editor/e2e/import-video.spec.ts @@ -78,7 +78,11 @@ test("import rejects a non-URL input", async ({ page }) => { test("a BitChute import runs on BitChute's queue and pace, and is never fetched twice", async ({ page, }) => { - test.setTimeout(90_000); + // Under `next dev` every route and action compiles on first use, and the + // first import's job runs behind BitChute's pace: the overnight dev run + // (2026-10-10) spent the 30 s the second click had on the first job alone. + const dev = (process.env.E2E_MODE ?? "").trim().toLowerCase() === "dev"; + test.setTimeout(dev ? 180_000 : 90_000); await resetData("one-transcribe-channel"); await generateReport(page, "test-transcribe"); await page.goto(channelStage("test-transcribe", "playlist")); @@ -113,6 +117,19 @@ test("a BitChute import runs on BitChute's queue and pace, and is never fetched expect(queues).toEqual(["platform:bitchute"]); }).toPass({ timeout: 15_000 }); + // WAIT ON THE JOB, NOT THE PAGE: the second import can only be refused once + // the first has finished and written its archive entry. + await expect(async () => { + const dir = resolvePath("test-transcripts/.jobs"); + const statuses: string[] = []; + for (const name of await readdir(dir)) { + if (!name.endsWith(".meta.json")) continue; + const m = JSON.parse(await readFile(`${dir}/${name}`, "utf8")); + if (m.kind === "import-one" && m.videoId === id) statuses.push(m.status); + } + expect(statuses).toEqual(["done"]); + }).toPass({ timeout: dev ? 90_000 : 30_000 }); + // Imported again: refused as already downloaded, nothing fetched. The first // run's end refreshes the page, and a click that lands during that refresh // never reaches the button's handler — so click until the notice shows. An diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -187,7 +187,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }], + ], outputDir: "test-results/", // Serial, one worker — deliberate, and not a performance oversight. Three // pieces of shared mutable state are global to the whole run, so two workers diff --git a/export/playwright.2origin.config.ts b/export/playwright.2origin.config.ts @@ -33,7 +33,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results-2origin/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results-2origin/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results-2origin/timings.json" }], + ], outputDir: "test-results-2origin/", fullyParallel: false, workers: 1, diff --git a/export/playwright.config.ts b/export/playwright.config.ts @@ -91,7 +91,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }], + ], outputDir: "test-results/", fullyParallel: false, workers: 1, diff --git a/export/playwright.hub.config.ts b/export/playwright.hub.config.ts @@ -52,7 +52,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results-hub/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results-hub/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results-hub/timings.json" }], + ], outputDir: "test-results-hub/", fullyParallel: false, workers: 1, diff --git a/export/playwright.report.config.ts b/export/playwright.report.config.ts @@ -33,7 +33,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results-report/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results-report/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results-report/timings.json" }], + ], outputDir: "test-results-report/", fullyParallel: false, workers: 1, diff --git a/homepage/playwright.config.ts b/homepage/playwright.config.ts @@ -96,7 +96,13 @@ export default defineConfig({ // scripts/e2e-timings.mjs totals per spec against the branch's last run. reporter: process.env.CI ? "github" - : [["list"], ["json", { outputFile: "test-results/timings.json" }]], + : [ + ["list"], + ["json", { outputFile: "test-results/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }], + ], outputDir: "test-results/", fullyParallel: false, workers: 1, diff --git a/mcp/README.md b/mcp/README.md @@ -11,9 +11,9 @@ The exceptions all ask a local Archilyzer editor (`ARCHILYZER_EDITOR_URL` + `WORKER_TOKEN`, the editor's own) to do the work — `fetch_clip` fetches a clip window, `enqueue` queues archival work, `get_job` / `channel_coverage` read the editor's jobs and disk, and `get_transcript` falls back to the editor's disk for a -video not yet published; `notes` reads umtool (`UMTOOL_URL`). The MCP itself still -writes nothing. Settings, storage and deletes are not reachable from it (`pnpm ops` -only). +video not yet published; `notes` reads umtool (`UMTOOL_URL`) and writes a reply +there as the agent's. The MCP itself still writes nothing. Settings, storage and +deletes are not reachable from it (`pnpm ops` only). ## Tools @@ -32,7 +32,7 @@ only). | `get_job` | One editor job's state — kind, channel, status, times, exit code, where it waits in its queue — and the last `tail` (default 40) log lines (`GET /api/ops/job/<id>`). For the job id `enqueue` or `fetch_clip` returned. Needs the editor. | | `enqueue` | Queue archival work on a channel the editor archives, as its page's buttons do (`POST /api/ops/<kind>`): `sync` (`full`), `download-missing`, `retry-bucket` (`bucket`, `ids` — the way to download chosen videos), `transcribe-bucket` (`ids`), `fetch-posts` (`full` / `older`), `import-video` (`url`). Answers the job id; the editor runs it on its own queues at each platform's pace. Only when the operator asks. Needs the editor. | | `channel_coverage` | What a channel **holds** on the editor's disk by date (`GET /api/ops/coverage`): count, first and last day, per year, and every gap longer than `gap_days` (30); `date_from` / `date_to` narrow it, `list` lists the videos. Each video is dated by its **recorded date** when the channel has a title rule (a VOD mirror, release 20), else its upload date. Needs the editor. | -| `notes` | The operator's notes in umtool on articles and report-video projects: `list` (every open note, by target), `read` (`target` as `list` names it — the digest with anchors resolved and the source file to edit). `reply` answers with the `umtool notes reply` command, because umtool records a reply sent over HTTP as the operator's. Needs `UMTOOL_URL`. | +| `notes` | The operator's notes in umtool on articles and report-video projects: `list` (every open note, by target), `read` (`target` as `list` names it — the digest with anchors resolved and the source file to edit). `reply` (`note_id`, `text`, `resolve`) writes the reply in umtool (`POST /api/notes` with `Authorization: Bearer <WORKER_TOKEN>`), which stamps it "agent" — never the operator's; its `target` is found from the open notes when omitted. Edit the note's source file and regenerate first. Needs `UMTOOL_URL`; a reply needs `WORKER_TOKEN` (the editor's own, which umtool reads too — a 401 means umtool holds another). | | `open_link` | Paste an archilyzer viewer **share link** to re-run that exact search here (query tree + every filter, at full fidelity) — plan, results and corpus handle in **one** call. `dry_run:true` for the plan alone. | | `list_sources` | Show the **default** corpus and, with a hub, its member sites as ready-to-paste handles. A site with reports says how many; a cited-only site says it is one. | | `resolve_source` | Turn a URL or site name into the canonical `source` handle and check it can be read. Changes nothing. | diff --git a/mcp/src/archivalTools.test.ts b/mcp/src/archivalTools.test.ts @@ -144,7 +144,7 @@ test("channel_coverage: the query sent, and the gaps read back", async () => { assert.match(textOf(bad), /date_to is a date, YYYY-MM-DD/); }); -test("notes: list groups open notes by target; read fetches the digest; reply is the CLI command", async () => { +test("notes: list groups open notes by target; read fetches the digest", async () => { const umtool = { UMTOOL_URL: "http://umtool.test/" }; const { deps, sent } = fakeEditor((s) => { if (s.url.includes("/api/browse/decisions")) { @@ -191,14 +191,71 @@ test("notes: list groups open notes by target; read fetches the digest; reply is assert.equal(q.get("status"), "all"); assert.match(read.text, /^# Notes on demo-site\/a-report/); + const none = await notesTool({ action: "list" }, { env: {}, fetch: deps.fetch }); + assert.match(none.text, /no umtool configured\. Set UMTOOL_URL/); +}); + +// ─── notes reply: written through umtool as the agent's (release 23 F3) ─── + +test("notes reply: POSTs the reply to umtool's route with the bearer token, the target found from the open notes", async () => { + const env = { UMTOOL_URL: "http://umtool.test/", WORKER_TOKEN: "tok" }; + const { deps, sent } = fakeEditor((s) => { + if (s.url.includes("/api/browse/decisions")) { + return { + status: 200, + body: { + items: [ + { kind: "open-note", project: "sites/demo-site/a-report", href: "/sites/demo-site/a-report?note=n_abc" }, + { kind: "open-note", project: "demo/video-project", href: "/browse/demo/video-project?note=n_other" }, + ], + }, + }; + } + return { status: 200, body: { note: { id: "n_abc", status: "resolved", replies: [{ author: "agent" }] } } }; + }, env); + const client = await connectWith(deps); const reply = await client.callTool({ name: "notes", arguments: { action: "reply", note_id: "n_abc", text: "Changed it", resolve: true }, }); - assert.equal(isError(reply), true); - assert.match(textOf(reply), /umtool notes reply n_abc "Changed it" --resolve/); - assert.equal(sent.length, 1, "a reply sends nothing"); + assert.equal(isError(reply), false, textOf(reply)); + assert.match(textOf(reply), /^Replied to n_abc on sites\/demo-site\/a-report as the agent; the note is resolved \(1 reply\)\./); + const post = sent.at(-1)!; + assert.equal(post.method, "POST"); + assert.equal(post.url, "http://umtool.test/api/notes?article=demo-site%2Fa-report"); + assert.equal(post.headers?.authorization, "Bearer tok"); + // Who wrote it is the token's to say, never the body's. + assert.deepEqual(post.body, { op: { op: "reply", id: "n_abc", text: "Changed it", resolve: true } }); - const none = await notesTool({ action: "list" }, { env: {}, fetch: deps.fetch }); - assert.match(none.text, /no umtool configured\. Set UMTOOL_URL/); + // An explicit target skips the lookup; a project target is a project param. + const before = sent.length; + await notesTool({ action: "reply", note_id: "n_other", text: "Shortened", target: "demo/video-project" }, deps); + assert.equal(sent.length, before + 1); + assert.equal(sent.at(-1)!.url, "http://umtool.test/api/notes?project=demo%2Fvideo-project"); + assert.equal((sent.at(-1)!.body as { op: { resolve: boolean } }).op.resolve, false); +}); + +test("notes reply: refusals — no token, a bad id, no open note, umtool's 401", async () => { + const noToken = await notesTool( + { action: "reply", note_id: "n_abc", text: "x" }, + { env: { UMTOOL_URL: "http://umtool.test" }, fetch: async () => { throw new Error("must not fetch"); } }, + ); + assert.equal(noToken.isError, true); + assert.match(noToken.text, /a reply needs WORKER_TOKEN/); + + const env = { UMTOOL_URL: "http://umtool.test", WORKER_TOKEN: "wrong" }; + const { deps } = fakeEditor((s) => + s.url.includes("/api/browse/decisions") + ? { status: 200, body: { items: [] } } + : { status: 401, body: { error: "notes: that bearer token is not umtool's WORKER_TOKEN" } }, + env); + assert.match((await notesTool({ action: "reply", note_id: "../x", text: "x" }, deps)).text, /reply needs note_id/); + assert.match((await notesTool({ action: "reply", note_id: "n_abc", text: "" }, deps)).text, /reply needs text/); + assert.match( + (await notesTool({ action: "reply", note_id: "n_gone", text: "x" }, deps)).text, + /no open note n_gone; pass target/, + ); + const refused = await notesTool({ action: "reply", note_id: "n_abc", text: "x", target: "sites/demo-site/a-report" }, deps); + assert.equal(refused.isError, true); + assert.match(refused.text, /umtool refused the token \(HTTP 401\): notes: that bearer token is not umtool's WORKER_TOKEN/); }); diff --git a/mcp/src/archivalTools.ts b/mcp/src/archivalTools.ts @@ -13,14 +13,13 @@ import { describeFetchError, isVideoId, REQUEST_TIMEOUT_MS } from "./fetchClip"; // transcribe-bucket | fetch-posts | import-video} // channel_coverage GET /api/ops/coverage?slug=… // notes umtool (UMTOOL_URL): GET /api/browse/decisions (list), -// GET /api/notes/context (read) +// GET /api/notes/context (read), POST /api/notes (reply) // // Settings, storage and deletes are deliberately absent (operator ruling, -// release 19): `pnpm ops` / `archilyzer` only. A notes REPLY is not written -// from here: umtool stamps every write through its HTTP route as the -// OPERATOR's ("there is no way to claim to be one here", umtool's -// app/api/notes/route.ts), so an agent reply must go through `umtool notes -// reply`, which stamps "agent" — the tool answers with that command. +// release 19): `pnpm ops` / `archilyzer` only. A notes REPLY is written +// through umtool's route with `Authorization: Bearer <WORKER_TOKEN>`, which +// umtool stamps "agent" — never the operator's (release 23 F3, ruled +// 2026-10-10: agents get their own write path). // // Pure apart from the injected deps; server.ts adapts. @@ -306,22 +305,94 @@ export function notesTarget(raw: string): { param: "article" | "project"; value: type Decision = { kind: string; project: string; projectKind?: string; target?: string; why?: string; href?: string }; -export async function notesTool(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { - const action = trimmed(args.action) || "list"; - if (action === "reply") { - const id = trimmed(args.note_id) || "<note id>"; - const text = trimmed(args.text) || "<what changed>"; +const NOTE_ID_RE = /^n_[a-z0-9]+$/; + +// The target an open note is on, from the decisions list (each open note's +// href ends `?note=<id>`, its project is the target as list names it). +async function openNoteTarget(deps: NotesDeps, id: string): Promise<{ target: string } | { error: string }> { + const r = await umtoolGet(deps, "/api/browse/decisions"); + if (!r.ok) return { error: r.error }; + if (r.status !== 200) return { error: `notes: umtool answered HTTP ${r.status}` }; + const items = ((r.json as { items?: Decision[] } | null)?.items ?? []).filter( + (d) => d.kind === "open-note" && (d.href ?? "").endsWith(`note=${encodeURIComponent(id)}`), + ); + const targets = [...new Set(items.map((d) => d.project))]; + if (targets.length === 1) return { target: targets[0] }; + if (targets.length === 0) { + return { error: `notes: no open note ${id}; pass target (as list names it) to reply to a resolved one` }; + } + return { error: `notes: ${id} is open on ${targets.length} targets (${targets.join(", ")}); pass target` }; +} + +// A reply, written through umtool's route as the agent's: Bearer WORKER_TOKEN +// (the editor's, which umtool reads too). No stale-write token: an agent +// writes between the operator's reads, which umtool's page handles (a 409 +// there, and a re-read). +async function notesReply(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { + const id = trimmed(args.note_id); + const text = trimmed(args.text); + if (!NOTE_ID_RE.test(id)) return { text: "notes: reply needs note_id (n_…, as read shows it)", isError: true }; + if (!text) return { text: "notes: reply needs text — what changed", isError: true }; + const base = umtoolFrom(deps.env); + if (!base) return { text: NO_UMTOOL_TEXT, isError: true }; + const token = (deps.env.WORKER_TOKEN ?? "").trim(); + if (!token) { return { + text: + "notes: a reply needs WORKER_TOKEN (the editor's own, which umtool reads too) in this " + + "server's env: umtool writes an agent's reply only for that bearer token.", isError: true, + }; + } + let targetName = trimmed(args.target); + if (!targetName) { + const found = await openNoteTarget(deps, id); + if ("error" in found) return { text: found.error, isError: true }; + targetName = found.target; + } + const target = notesTarget(targetName); + if (!target) { + return { text: 'notes: target is as list names it — "sites/<site>/<report>" for an article, else a video project id', isError: true }; + } + const timeoutMs = deps.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; + const q = new URLSearchParams({ [target.param]: target.value }); + try { + const res = await deps.fetch(`${base}/api/notes?${q.toString()}`, { + method: "POST", + headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, + body: JSON.stringify({ op: { op: "reply", id, text, resolve: args.resolve === true } }), + signal: AbortSignal.timeout(timeoutMs), + }); + const body = (await res.json().catch(() => null)) as + | { error?: string; note?: { status?: string; replies?: unknown[] } } + | null; + if (res.status === 401) { + return { + text: + `notes: umtool refused the token (HTTP 401): ${body?.error ?? "unauthorized"} — this server's ` + + "WORKER_TOKEN must be umtool's (the editor's own).", + isError: true, + }; + } + if (res.status !== 200) { + return { text: `notes: umtool refused (HTTP ${res.status}): ${body?.error ?? "no reason given"}`, isError: true }; + } + const n = body?.note; + return { text: - "notes: a reply is not written from here. umtool records every write through its HTTP " + - "route as the operator's, and an agent's reply must say it is an agent's — so it goes " + - "through umtool's CLI, from the repo checkout:\n\n" + - ` umtool notes reply ${id} ${JSON.stringify(text)}${args.resolve === true ? " --resolve" : ""}\n\n` + - "(`node umtool/bin/umtool.mjs notes reply …` when umtool is not on the PATH.) Edit the " + - "note's SOURCE file first (notes read shows it), regenerate, then reply.", + `Replied to ${id} on ${targetName} as the agent` + + (n?.status ? `; the note is ${n.status}` : "") + + (Array.isArray(n?.replies) ? ` (${n.replies.length} repl${n.replies.length === 1 ? "y" : "ies"})` : "") + + ".", }; + } catch (e) { + return { text: `notes: umtool at ${base} did not answer: ${describeFetchError(e, timeoutMs)}`, isError: true }; } +} + +export async function notesTool(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { + const action = trimmed(args.action) || "list"; + if (action === "reply") return notesReply(args, deps); if (action === "list") { const r = await umtoolGet(deps, "/api/browse/decisions"); if (!r.ok) return { text: r.error, isError: true }; @@ -460,14 +531,15 @@ export const ARCHIVAL_TOOLS = [ '"list": every open note, grouped by target. action "read" with target (as list names ' + 'it: "sites/<site>/<report>" for an article, else a project id): each note with its anchor ' + "resolved and the SOURCE file to edit (status: open, resolved or all). action " + - '"reply" answers with the `umtool notes reply` command to run — umtool records a ' + - "reply sent over HTTP as the operator's, so an agent's reply goes through its CLI. " + - "Needs UMTOOL_URL.", + '"reply" with note_id and text (resolve: true closes it too) writes the reply in ' + + "umtool as the agent's — edit the note's SOURCE file and regenerate first. target is " + + "found from the open notes when omitted. Needs UMTOOL_URL; a reply needs WORKER_TOKEN " + + "(the editor's own, which umtool reads too).", inputSchema: { type: "object", properties: { action: { type: "string", enum: ["list", "read", "reply"], description: 'Default "list".' }, - target: { type: "string", description: 'read: as list names it — "sites/<site>/<report>" (an article) or a project id.' }, + target: { type: "string", description: 'read (and reply, optional): as list names it — "sites/<site>/<report>" (an article) or a project id.' }, status: { type: "string", enum: ["open", "resolved", "all"], description: "read: which notes (default open)." }, note_id: { type: "string", description: "reply: the note id (n_…)." }, text: { type: "string", description: "reply: what changed." }, diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -173,7 +173,8 @@ function archiveStep(): string { `hours; report the job, do not wait it out. \`channel_coverage\` answers ` + `what a channel holds by date and where its gaps are (a VOD mirror's videos ` + `by the day they were recorded). The operator's notes on articles and ` + - `video projects: \`notes\` (list, read; a reply is \`umtool notes reply\`). ` + + `video projects: \`notes\` (list, read; reply — after editing the note's ` + + `source and regenerating — writes the reply in umtool as the agent's). ` + `Settings, storage and deletes are not reachable from here — name the ` + `\`pnpm ops\` command instead.` ); diff --git a/plans/e2e-speed.md b/plans/e2e-speed.md @@ -198,3 +198,40 @@ Not done here, by the brief: the full suites (the orchestrator runs them, start `timings.json` per suite) — S2 keeps one file per run directory, so a re-run of a few specs replaces a full run's record. Per-spec start-mode totals came from the list reporter instead: 19.5 min of test time over 129 specs; the slowest social-channel 86 s, new-channel-onboarding 55 s, channels 48 s, audio-check-scenarios 44 s. + +### Release 23 F5, as shipped — test hygiene and the timing record (2026-10-10, `r23/fixes`) + +**Every run records itself.** `scripts/e2e-timings-reporter.mjs` is a Playwright reporter listed after `json` in all +seven configs (editor, umtool, homepage, and export's default, hub, report and 2origin): at `onExit`, once every +reporter's `onEnd` has written its file, it records the run's `timings.json` in the branch's history and prints the +table (top 10) — `e2e-timings.mjs`'s `recordReport`, shared with the CLI, which now finds such a run "already +recorded". A full run is in the history before any re-run can replace its file (Playwright also empties +`test-results*/` when the next run starts). A run with no tests records nothing; a report it cannot read is one line +on stderr, never a failed run. **A reporter, not a `globalTeardown`** (as the plan named it): Playwright 1.59 runs +every `globalTeardown` before any reporter's `onEnd` (`runner/tasks.js`), so a teardown never sees its own run's json. + +**umtool's environment reds, made skips or fixed:** +- `triage.spec` — `sort` lives in the `song ▸` nav group (folded 2026-08-25): the page check opens the group and finds + `sort` there as the current `menuitem`, then Escape. 9 tests that failed on the missing top-level link now pass. +- `faces.spec` — `facedet` joins `songCapabilities` (`e2e/fixtures/song-capabilities.mjs`: the venv at + `dirname(SONG_DIR)/facedet` and `umtool/models`, the rule `make-fixture.mjs` records from what it linked); + `NO_FACEDET` skips the five tests that need a detector that answers (`:169`, `:212`, `:319`, `:395`, `:447` — the + plan named four; `:447` calls the detect route too) instead of failing on its 503. +- `find.spec:170` — the chunk-twin fold asserts its arithmetic only when the data has twins for the query + (`collapsed > 0`), else skips naming the query. + +**Editor `import-video.spec:78`** waits on the first import's job (`.jobs/*.meta.json` `status: "done"`) before the +second click, and under `E2E_MODE=dev` takes 180 s (90 s otherwise) with a 90 s wait for the job. + +| Commit | What | +|---|---| +| `8458da71` | `e2e:` F5 — the reporter in seven configs, `recordReport`, the umtool skips and nav, import-video's job wait | + +**Gates.** tsc clean. `node --test scripts/e2e-timings.test.mjs` 11/11 (+3: `recordReport` records once and skips an +empty run; the reporter records a full run and a one-spec re-run, both kept; a missing report never fails the run); +`test:scripts` 770 pass, 2 skipped. umtool, one run of `triage.spec.ts faces.spec.ts find.spec.ts`: 29 passed, 6 +skipped (faces 5 `NO_FACEDET` — no venv on this machine; find `:170` — no seam twins for "the"), 24.1 s, recorded by +the reporter (`.git/e2e-timings/umtool/r23_fixes.json`). The first run of the three, before the `menuitem` fix: 20 +passed, 9 failed (triage's page check looked for a `link`), 6 skipped — recorded too, which is the point. +`E2E_MODE=dev pnpm e2e import-video.spec.ts` 3 passed, 33.9 s; the same in start mode (the editor's e2e build rebuilt +through the heavy slot, 42 s) 3 passed, 12.2 s. diff --git a/plans/release-19.md b/plans/release-19.md @@ -339,6 +339,33 @@ files `a-*` in the job's `tmp`. changes nothing itself; README tool table; `UMTOOL_URL`, `WORKER_TOKEN`, `ARCHILYZER_EDITOR_URL` name their MCP readers (ENVIRONMENT.md regenerated). `channel-config`'s help names `recordedDateTitlePattern`. +**A9 follow-up (release 23 F3) — notes get an agent write path.** Ruled 2026-10-10: agents get their own write path, +attributed "agent", never as the operator. **This supersedes A9's ruling above** that the MCP does not write notes. +- umtool's `POST /api/notes` (`umtool/lib/annotations/agentAuth.mjs`, `postNoteOp`): no `Authorization` header → + "operator" (the page, unchanged); `Authorization: Bearer <WORKER_TOKEN>` → "agent"; any other `Authorization` + header — a wrong token, another scheme, or any bearer while umtool holds no token — → 401, nothing written. `by` is + never read from the body. umtool's `WORKER_TOKEN` is read per request: the environment (an explicit value, even + empty, wins), else the first of this checkout's `editor/.env.local` / `editor/.env`, then the main worktree's + (A1's `loadEditorEnv` order). +- The MCP's `notes` `reply` (`note_id`, `text`, `resolve`, optional `target` — else found from the open notes' + `?note=<id>` links) POSTs `{op: {op: "reply", id, text, resolve}}` with its `WORKER_TOKEN` and answers `Replied to + <id> on <target> as the agent; the note is <status> (N replies).`; a 401 names the token mismatch. No stale-write + token is sent (the CLI's way); the page's 409 re-read covers a write in between. +- `mcp/src/instructions.ts`, `mcp/README.md`, `umtool/docs/notes.md`, `common/lib/envVars.ts` (ENVIRONMENT.md + regenerated). umtool's notes UI already badged an agent's note and reply (`NoteCards`, `NoteThread`); unchanged. + +| Commit | What | +|---|---| +| `1b909c89` | `umtool:` F3 — the bearer → "agent" route, the MCP reply through it, docs | + +Gates: tsc clean; `umtool/lib/annotations/agentAuth.test.mjs` 7 (no token → operator; token → agent for a note, a +reply and its resolve; wrong/malformed/no-umtool-token → 401 with nothing written; `by` in the body ignored both ways; +no op → 400; the token read order), annotations 23/23; mcp 305/305 (`archivalTools.test.ts` +2: the POST with the +bearer and the body pinned, an explicit project target; no token, a bad id, no open note, umtool's 401); +`docs env --check` clean; umtool e2e `article-notes.spec.ts` 9 passed, 14.7 s (+1: an agent's reply over HTTP is +stamped agent and badged on the page, a wrong token is a 401); umtool `next build` with the corpus linked (5 GB +scope) green. + #### Track A gates (A1–A5, on the merged tip) - `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean before every commit and on the merged tip diff --git a/plans/release-20.md b/plans/release-20.md @@ -88,7 +88,7 @@ coverage reads. channels whose name or URL says VODs, mirror or archive (listed in the track report). No channel's config was changed; the patterns are the operator's to write. -### Slice D2 — one Twitch id: held, operator ruling owed +### Slice D2 — one Twitch id: held, operator ruling owed (superseded: ruled option (b), shipped as release 23 F1 below) Built as `433815d4` and reverted on this branch; the build is kept on `r20/twitch-ids` (orchestrator, 2026-10-10: it changes published URLs, which is the operator's ruling). @@ -128,6 +128,98 @@ after the upload dropped; a changed rule re-derives once, a removed one drops th (release 21 D2's tests included), and after the revert the touched index, normalize, caption-track and architecture tests 54/54, tsc clean; editor unit 228/228; export unit 118/118; mcp 293/293; `archilyzer docs files --check` and `docs env --check` clean. E2E, one run in the foreground (start of the queue after the heavy slot freed): `transcript-source.spec.ts` (D3's index spec, 4) and `ops-api.spec.ts` (13, the channel-config round trip among them) — 17 passed, 1.5 min. Release end per the plan: the full editor suite once, the orchestrator's. +### Slice D2, as shipped — option (b) (release 23 F1) + +**Ruled 2026-10-10: option (b).** The published `v<n>` stays; the join normalizes on the directory side. Built on +`r23/fixes` (release 23 Lane 1); the held build on `r20/twitch-ids` is not used (its test cases are, without its +re-keying of records). + +**The helper.** `common/lib/videoDirId.mjs` (pure, client-safe; re-exported by `lib/videoId.ts`): +`twitchVodDirId` (`v<n>` → `<n>`), `twitchVodRecordId` (the reverse), `channelConfigPlatform` (config `platform`, else +its `url`'s host), `pickVideoDirId`. Its disk half, `lib/videoDir-server.mjs`: `resolveVideoDirId` / +`resolveVideoDir(channelsDir, slug, recordId, {platform?})`. Plain JS for umtool's bare-node scripts (the +`detectPlatform.mjs` precedent; both exported by exact path from common's `package.json`). +- An id that is not `v<digits>` passes through with no read. +- A `v<digits>` id maps only for a Twitch record: the platform the caller passes, else the channel's config. Any other + platform's `v`-id (a Rumble slug, a YouTube id that reads `v` + ten digits) is never mapped. +- The directory that exists wins, `<n>` first, then `v<n>`; with neither, `<n>` (so a fetch-window creates the + canonical one). + +**The join points** (release 20 D2's list, found in the tree): +- the editor's fetch-window: `fetchWindowAction` and `fetchFullSourceAction` (`videoActions.ts`) name the video by + its directory from the config read on (cache, saved container, job, revalidated page); the in-flight dedupe asks + under both ids. The batch planner (`videos/fetchWindowsAction.ts`) and `controller/fetchWindows.ts` resolve each + item's directory and keep the item's record id in every result; +- the evidence-clip tiers (`common/lib/evidenceClip.mjs`, a new async `recordDirOf`; `TierContext.platform` + optional) and `evidenceClip-server.ts` `recordDuration`, behind reports prepare and report-to-video's local + sources; +- `publish/reportMedia.ts`'s per-record availability read (one line); +- umtool `report-to-video/cues.mjs`'s local cue lookup. + +Records and published ids are unchanged; no index re-key. + +**Live corpus, offline and read-only** (a script over the channels' data dirs, and a key-only `byChannel` scan of +the LMDB index opened `readOnly`; counts only): hasanabi 180 records, all `v<n>`, none equal to its directory; the +plain join finds 0, the helper maps 180 to an existing `data/<n>/`, 0 unmatched. shondo-twitch 37: plain 0, helper 37, +0 unmatched. + +**Found and left (other owners or outside D2's list):** these still join a record's id to `data/<id>/` directly and +miss a Twitch citation: `publish/composeReports.ts` `readCitedRecord` (Lane 2's file this release: a report citing a +Twitch `v<n>` record reads no record), `lib/report/convert-server.ts` (report convert's cue read), umtool +`lib/projects/report.mjs` (`cuePathFor`, and the duration probe in `clipWindowDirs`) and +`report-to-video/check-availability.mjs` (`cueMeta`). Each is one `resolveVideoDir` call. + +**Commits** + +| Commit | What | +|---|---| +| `5f1f4c0a` | `common:` F1 — the helper, the join points, the tests | + +**Gates.** tsc clean (`pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`). New tests: +`lib/videoDirId.test.ts` 6 (D2's id cases, the platform rule, the pick order, the disk resolver over a temp corpus), +`lib/evidenceClip-server.test.ts` +1 (every tier and the duration clamp through `data/<n>/`; a non-Twitch channel's +`v`-id is not mapped), `publish/reportMediaTwitch.test.ts` 1 (cached, gone and missing citations; ids as cited — +fails without the availability line), `controller/fetchWindows.test.ts` +1 (cache hit and fetch under `<n>`), +editor `videos/fetchWindowTwitch.test.ts` 2 (both editor doors), umtool `cues.test.mjs` +1. Common suite 3,681: 3,670 +pass, 11 fail — the same 11 fail on `d3296bab` without this change (`attachMedia.test.ts` 8, `preparePlayable.test.ts` +2 — environment — and `fetchPosts.test.ts` 1, a drain timing that passes alone). Editor unit 239/239; +`test:scripts` 759 pass, 3 skipped, 0 fail (the cwd-join trace guard among them). + +### D3's found-and-left, as shipped (release 23 F4) — the stats cache sees the caption-track pass + +Release 23 Lane 1, on `r23/fixes`. D3 left it: the caption-track pass re-reads a record's cues and writes the same +`mtimes` record back, so `buildStats` (keyed on that record, `indexSignature`) kept `hasTranscript: false` and the +old `cueCount` for a record the pass took from no text to text. + +**What it does.** +- `buildIndex.ts`: the `mtimes` record gains `cueFingerprint` (`cueFingerprint(list)`: `"<count>:<last cue end>"`, + `"0"` for none — the two cue facts a stat is made of, `cueCount` and coverage), written on every (re)process. Any + pass that re-reads a record with no input moving (caption track, alt tracks, platform labels) moves it when the + cues it stores differ. +- `buildStats.ts`: `indexSignature` appends `cues=<fingerprint>` only when the record has one. A record written before + it gives the old string exactly, so the rollout recomputes nothing by itself; a record the index rewrites from then + on (the pass's included) recomputes once. +- **The records a pass already left stale** (the v1 caption-track pass ran on records before this): a cached stat that + says no transcript while the index holds a non-empty cue list under its key is recomputed (`statMissesStoredCues`, + the stored value's length, no decode — `storedCuesEmpty`'s test), asked only of stats that say no transcript. It + heals the no-text-to-text case at the first stats build after the rollout; a text-to-other-text change the v1 pass + already made (a cue count that moved) is not reached by it. +- Not chosen: the caption-track rule version in the signature — it would recompute every stat when the rule moves, + and a rule bump also marks every caption `transcript.cues.json` stale to umtool and normalize. + +| Commit | What | +|---|---| +| `e43f6e4c` | `common:` F4 — `cueFingerprint` in the index record and the signature; the stale-stat heal | + +**Gates.** tsc clean. `controller/buildStats.test.ts` 17/17 (+4, through the real `buildIndex` and `buildStats`): +(l) a record the pass takes from no text to text (stored cues empty, the pass due) recomputes, once; (l2) a pass that +changes a two-track record's cue count (1 → 2, `hasTranscript` true both times) recomputes — red with the fingerprint +taken out of the signature; (m) a stale cached stat (no transcript, cues held, the same key) is healed, a video with +no cues is not asked again, then nothing; (n) an old record's signature is unchanged by the field's absence. Common +3,690: 3,680 pass, 10 fail — the same `attachMedia` 8 and `preparePlayable` 2 that fail on `d3296bab` (environment: +`/tmp` is a 1.7 GB-free tmpfs here). Editor unit 243/243; `test:scripts` 767 pass, 2 skipped; export unit 118/118; +homepage unit 23/23. + ## As it went **The whisper red: "Clear failure list" unmounted its own log** (`r20/whisper-fix`). `whisper.spec.ts:184` diff --git a/plans/release-21.md b/plans/release-21.md @@ -361,6 +361,51 @@ with the window and sidecar on disk while the cooling YouTube group is refused; Editor unit 225/225; the touched common files (clipWindow, evidenceClip, savedVideo*, fetchWindows, windowJobs) 61/61; architecture 6/6; mcp 293/293. The whole common suite runs once at the end of the track (part 2). +### F2 (release 23), as shipped — Transcribe reads a saved container before it downloads audio + +Release 23 Lane 1, on `r23/fixes` (from `r23/integration` `d3296bab`). The pilot's step 2 (`transcribe-one` for the +three videos with media but not held) downloaded audio for a video whose whole source was already in the store. + +**What it does.** `controller/transcribeOne.ts` `transcriptionContainer({paths, slug, videoDir, entries})` answers, +in `resolveAudioFile`'s own order (`findSourceMedia(entries) ?? the saved-video pointer`): +- `container` — a container with sound: a `source-media.<ext>` in the video dir, else the store's (read through + D2's `savedWindowSource` over the window [0, 0], so its drive watchdog, store-move check and sentence are the + same); +- `no-audio` — the container has no sound stream (`probeMedia`); +- `unreadable` — a pointer whose container cannot be read, with the guard's sentence (`Channel "<slug>": media is + not reachable — its saved video <path> is not there (drive not mounted?)`, `… could not be read by ffprobe`, the + watchdog's, or the store-move sentence); +- `none` — no container. A `source-media.<ext>` ffprobe cannot read is passed over for the pointer. + +`whisperVideoAction` (the video page's Transcribe) asks it when no extracted audio is on disk, before the disk gate +and the `download-one-audio` path: `container` → no download, the log line `No audio on disk for <id>; transcribing +from the saved container <file> — nothing downloaded.` (`the source container` for one in the video dir), then +`transcribeWithWorker` as before, which resolves the same file non-strict; `unreadable` → the job fails with the +sentence, nothing downloaded; `no-audio` → `The container <file> has no sound; downloading the audio instead.` and +the download path; `none` → the download path, unchanged. + +**`pnpm ops transcribe-one {slug, id}`** reaches this path unchanged: `api/ops/transcribe-one` calls +`whisperVideoAction` when no `file` is given (with `file`, `transcribeOneAction`, that file through the pool). + +**Found and left.** The e2e server's fake ffprobe answers a bare duration, never `-of json` (D2's note above), so a +saved container probes as unreadable there; the action is proven by an editor unit test with the real ffprobe and +the e2e fake whisper-cli instead, and `whisper.spec` gets no new case. + +**Commits** + +| Commit | What | +|---|---| +| `1c5793e5` | `channels:` F2 — `transcriptionContainer`, `whisperVideoAction` asks it first; 9 tests | + +**Gates.** tsc clean. New tests (real ffmpeg/ffprobe over 1 s lavfi containers): `controller/transcriptionContainer.test.ts` +5 (saved container with sound; a missing container → the exact sentence; none; a silent container; the video dir's +container first, a silent one there → download, an unreadable one passed over), editor +`videos/[id]/whisperFromContainer.test.ts` 4 through `runManagedFunction` (present → `done` with a transcript from +the fake whisper-cli and no yt-dlp run; a gone container → `failed` with the sentence and no yt-dlp run; none and +silent → the download path's yt-dlp, a fake that records its argv and fails). E2E, start mode (the editor's e2e +build rebuilt through the heavy slot, so the editor build is green with F1 and F2): `whisper.spec.ts` 10 passed, +25.4 s. + ## Rollout (pilot) 1. `pnpm ops attach-media --json '{"slug":"the-incredible-salt-mine","source":"<archive>/Uploads/YouTube.zip","dryRun":true}'`. diff --git a/scripts/e2e-timings-reporter.mjs b/scripts/e2e-timings-reporter.mjs @@ -0,0 +1,60 @@ +// A Playwright reporter that RECORDS each run's timings the moment the run's +// json report is written (release 23 F5 — plans/e2e-speed.md S2's gap). +// +// Every suite writes Playwright's `json` report to `<test-results*>/timings.json` +// (one file per run directory: the editor's, umtool's, the homepage's and each +// of the export's four configs), and `scripts/e2e-timings.mjs` turns one into a +// per-spec record in the branch's history (`<.git>/e2e-timings/…`). Recording +// was a step somebody ran by hand, after the run — and Playwright empties +// `test-results*/` when the next run starts, so a solo re-run made between the +// two erased a full run's report before it was ever recorded (the overnight +// 2026-10-10 start-mode run). Listed AFTER the json reporter, this records at +// `onExit`, once every reporter's `onEnd` has written its file. +// +// A REPORTER, NOT A globalTeardown: Playwright (1.59, runner/tasks.js) runs +// every globalTeardown before any reporter's `onEnd`, so a teardown never sees +// its own run's json. +// +// It never fails a run: a report it cannot read or a history it cannot write +// is one line on stderr. A run with no tests (`--list`, a filter that matched +// nothing) records nothing. +// +// reporter: [["list"], ["json", { outputFile: "test-results/timings.json" }], +// ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }]] +// +// `outputFile` is resolved against the config's directory, as the json +// reporter resolves its own. `historyDir` (tests) overrides the history root. +import path from "node:path"; +import { recordReport } from "./e2e-timings.mjs"; + +export default class E2eTimingsReporter { + /** @param {{ outputFile?: string, historyDir?: string, top?: number }} [options] */ + constructor(options = {}) { + this.options = options; + this.base = process.cwd(); + } + + printsToStdio() { + return false; + } + + /** @param {{ configFile?: string, rootDir: string }} config */ + onBegin(config) { + this.base = config.configFile ? path.dirname(config.configFile) : config.rootDir; + } + + async onExit() { + const file = path.resolve(this.base, this.options.outputFile ?? "test-results/timings.json"); + try { + const out = recordReport(file, { + historyDir: this.options.historyDir ?? null, + top: this.options.top ?? 10, + skipEmpty: true, + }); + if (out.run.totals.tests === 0) return; + process.stdout.write(`\n${out.lines.join("\n")}\n${out.note ? `${out.note}\n` : ""}`); + } catch (err) { + process.stderr.write(`e2e-timings: not recorded (${err?.code ?? err?.message ?? err})\n`); + } + } +} diff --git a/scripts/e2e-timings.mjs b/scripts/e2e-timings.mjs @@ -3,6 +3,13 @@ // // node scripts/e2e-timings.mjs [<timings.json>] [--suite <name>] [--top <n>] [--no-record] // +// EVERY RUN IS RECORDED BY ITSELF (release 23 F5): each suite's config also +// lists ./e2e-timings-reporter.mjs, which records the run's report the moment +// Playwright has written it (recordReport below) — so a re-run of a few specs, +// which replaces `timings.json`, can no longer erase a full run's record before +// anyone ran this by hand. Running this afterwards reads the same file and says +// it was already recorded. +// // Every suite's Playwright config writes a `json` report beside `list` // (`<package>/test-results/timings.json`; the hub's, report's and 2origin's in // their own test-results-* dirs). This totals it per spec FILE — every result @@ -198,37 +205,55 @@ export function suiteFromPath(file) { return `${pkg}${extra}`; } -function main(argv) { - const opts = parseArgs(argv); - const report = path.resolve(opts.report ?? path.join(REPO_ROOT, "editor", "test-results", "timings.json")); - let json; - try { - json = JSON.parse(fs.readFileSync(report, "utf8")); - } catch (err) { - process.stderr.write(`e2e-timings: cannot read ${report} (${err.code ?? err.message}) — run the suite first\n`); - return 1; - } +/** + * Read one run's report, record it in the branch's history (unless `record` + * is false, or it is there already) and render it against the runs before + * it. Throws when the report cannot be read. The CLI and the reporter + * (./e2e-timings-reporter.mjs) both come here. + * @param {string} report a timings.json + * @param {{ suite?: string | null, branch?: string | null, historyDir?: string | null, record?: boolean, top?: number, skipEmpty?: boolean }} [opts] + * `skipEmpty`: a run with no tests is neither recorded nor rendered. + * @returns {{ lines: string[], note: string, recorded: boolean, run: ReturnType<typeof summarize> & { head: string | null } }} + */ +export function recordReport(report, opts = {}) { + const json = JSON.parse(fs.readFileSync(report, "utf8")); const suite = opts.suite ?? suiteFromPath(report); const cwd = path.dirname(report); const branch = opts.branch ?? gitOut(["rev-parse", "--abbrev-ref", "HEAD"], cwd) ?? "unknown"; const head = gitOut(["rev-parse", "HEAD"], cwd); const run = { ...summarize(json), head }; + if (opts.skipEmpty && run.totals.tests === 0) return { lines: [], note: "", recorded: false, run }; const dir = opts.historyDir ?? defaultHistoryDir(cwd); let earlier = []; let note = ""; + let recorded = false; if (dir) { const file = historyFile(dir, suite, branch); const placed = placeRun(readHistory(file), run); earlier = placed.earlier; - if (opts.record && placed.recorded) { + if (opts.record !== false && placed.recorded) { writeHistory(file, placed.runs); note = `recorded in ${file}`; + recorded = true; } else if (!placed.recorded) { note = "this run was already recorded"; } } - const lines = render({ suite, branch, head, run, earlier, top: opts.top }); - process.stdout.write(`${lines.join("\n")}\n${note ? `\n${note}\n` : ""}`); + const lines = render({ suite, branch, head, run, earlier, top: opts.top ?? Infinity }); + return { lines, note, recorded, run }; +} + +function main(argv) { + const opts = parseArgs(argv); + const report = path.resolve(opts.report ?? path.join(REPO_ROOT, "editor", "test-results", "timings.json")); + let out; + try { + out = recordReport(report, opts); + } catch (err) { + process.stderr.write(`e2e-timings: cannot read ${report} (${err.code ?? err.message}) — run the suite first\n`); + return 1; + } + process.stdout.write(`${out.lines.join("\n")}\n${out.note ? `\n${out.note}\n` : ""}`); return 0; } diff --git a/scripts/e2e-timings.test.mjs b/scripts/e2e-timings.test.mjs @@ -14,6 +14,7 @@ import { historyFile, placeRun, readHistory, + recordReport, render, suiteFromPath, summarize, @@ -173,3 +174,74 @@ test("the CLI records the first run, then prints the second against it", () => { assert.match(two, /pacing\.spec\.ts\s+2\s+9\.0s\s+−55\.0s/); assert.equal(readHistory(historyFile(hist, "editor", "b")).length, 2); }); + +// ─── recorded by the run itself (release 23 F5) ─── + +import E2eTimingsReporter from "./e2e-timings-reporter.mjs"; + +test("recordReport records a run once; an empty run is neither recorded nor rendered", () => { + const dir = tmp(); + const hist = path.join(dir, "history"); + const file = path.join(dir, "editor", "test-results", "timings.json"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(report())); + const first = recordReport(file, { historyDir: hist, branch: "r23/x" }); + assert.equal(first.recorded, true); + assert.equal(readHistory(historyFile(hist, "editor", "r23/x")).length, 1); + const again = recordReport(file, { historyDir: hist, branch: "r23/x" }); + assert.equal(again.recorded, false); + assert.equal(again.note, "this run was already recorded"); + + fs.writeFileSync(file, JSON.stringify({ stats: { startTime: "2026-10-10T00:00:00.000Z", duration: 1 }, suites: [] })); + const empty = recordReport(file, { historyDir: hist, branch: "r23/x", skipEmpty: true }); + assert.deepEqual([empty.recorded, empty.lines], [false, []]); + assert.equal(readHistory(historyFile(hist, "editor", "r23/x")).length, 1); +}); + +test("the reporter records at onExit: a full run, then a re-run of one spec, are BOTH in the history", async () => { + const dir = tmp(); + const hist = path.join(dir, "history"); + const configDir = path.join(dir, "umtool"); + const file = path.join(configDir, "test-results", "timings.json"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const reporter = () => { + const r = new E2eTimingsReporter({ outputFile: "test-results/timings.json", historyDir: hist }); + r.onBegin({ configFile: path.join(configDir, "playwright.config.ts"), rootDir: configDir }); + return r; + }; + const write = process.stdout.write; + const printed = []; + process.stdout.write = (chunk) => (printed.push(String(chunk)), true); + try { + // The full run's json, as the json reporter wrote it at onEnd. + fs.writeFileSync(file, JSON.stringify(report())); + await reporter().onExit(); + // The re-run REPLACES timings.json (Playwright empties test-results first). + const rerun = report({ startTime: "2026-10-09T21:30:00.000Z", wall: 5_000 }); + rerun.suites = rerun.suites.slice(0, 1); + fs.writeFileSync(file, JSON.stringify(rerun)); + await reporter().onExit(); + } finally { + process.stdout.write = write; + } + // The temp dir is no git checkout: its branch reads "unknown". + const runs = readHistory(historyFile(hist, "umtool", "unknown")); + assert.deepEqual(runs.map((r) => r.startTime), ["2026-10-09T20:40:00.000Z", "2026-10-09T21:30:00.000Z"]); + assert.match(printed.join(""), /e2e timings — umtool on /); + assert.match(printed.join(""), /recorded in /); +}); + +test("the reporter never fails a run: a missing report is one line on stderr", async () => { + const dir = tmp(); + const r = new E2eTimingsReporter({ outputFile: "nowhere/timings.json", historyDir: path.join(dir, "h") }); + r.onBegin({ rootDir: dir }); + const write = process.stderr.write; + const said = []; + process.stderr.write = (chunk) => (said.push(String(chunk)), true); + try { + await r.onExit(); + } finally { + process.stderr.write = write; + } + assert.match(said.join(""), /^e2e-timings: not recorded \(ENOENT\)/); +}); diff --git a/umtool/app/api/notes/route.ts b/umtool/app/api/notes/route.ts @@ -1,6 +1,6 @@ import { errorResponse, targetFrom } from "@/lib/annotations/server"; import { readNotes } from "@/lib/annotations/store.mjs"; -import { writeNote } from "@/lib/annotations/targets.mjs"; +import { agentToken, postNoteOp } from "@/lib/annotations/agentAuth.mjs"; export const dynamic = "force-dynamic"; @@ -14,8 +14,11 @@ export const dynamic = "force-dynamic"; // { doc, token, note }. 409 when `token` is stale or the file on // disk is not a notes doc; 400 for a refused op or target. // -// Every write from here is the OPERATOR's. An agent writes through -// `umtool notes`, which stamps "agent"; there is no way to claim to be one here. +// A write from the page is the OPERATOR's. An agent's (the MCP's `notes` +// reply, release 23 F3) carries `Authorization: Bearer <WORKER_TOKEN>` and is +// stamped "agent"; any other Authorization header is a 401 +// (lib/annotations/agentAuth.mjs). `by` is never read from the body. The CLI, +// `umtool notes`, writes the file directly and stamps "agent" too. const NO_STORE = { "cache-control": "no-store" }; function params(request: Request) { @@ -40,11 +43,12 @@ export async function GET(request: Request) { export async function POST(request: Request) { try { const target = await targetFrom(params(request)); - const body = (await request.json().catch(() => null)) as { token?: unknown; op?: unknown } | null; - if (!body || typeof body.op !== "object" || body.op === null) return Response.json({ error: "body needs an op" }, { status: 400 }); - const token = typeof body.token === "string" ? body.token : null; - const out = await writeNote(target, body.op as Record<string, unknown>, { by: "operator", token }); - return Response.json(out, { headers: NO_STORE }); + const body = await request.json().catch(() => null); + const r = await postNoteOp(target, body, { + authorization: request.headers.get("authorization"), + workerToken: agentToken(), + }); + return Response.json(r.body, { status: r.status, headers: NO_STORE }); } catch (err) { return errorResponse(err); } diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -29,6 +29,8 @@ from the working directory to the checkout. 4. Regenerate. 5. `umtool notes reply <id> "<what changed>" --resolve` — or reply without `--resolve` to ask a question. The operator sees agent replies badged "agent". + An agent on the MCP replies with its `notes` tool (action `reply`), which writes + through the app's route below as the agent's. **Never hand-edit `notes.json`.** The CLI and the app write through one store that validates, takes a lock, and refuses a stale write; a hand edit races the page and @@ -38,6 +40,15 @@ can lose a reply. If the recorded source is wrong, correct it: The same digest is served as text at `GET /api/notes/context?article=<site>/<report>` (or `?project=<id>`); the page's "Copy agent brief" copies it. +**An agent's write over HTTP** (release 23 F3). `POST /api/notes` stamps a write +"operator" when the request carries no `Authorization` header (the page), and +"agent" when it carries `Authorization: Bearer <WORKER_TOKEN>`; any other +`Authorization` header is a 401 and nothing is written. `by` is never read from the +body. umtool's `WORKER_TOKEN` is its environment's (an explicit empty value turns +the agent path off), else the first `editor/.env.local` / `editor/.env` of this +checkout, then of the main worktree, that names it — the editor's own token, as +`pnpm ops` reads it (`lib/annotations/agentAuth.mjs`). + ## Where notes live | Subject | File | @@ -108,5 +119,6 @@ section, with its original quote. | `lib/annotations/store.mjs` | read, lockfile (`notes.json.lock`, stale after 30 s), token, tmp+rename | | `lib/annotations/targets.mjs` | article / project → file, subject, source; `listNotesFiles` | | `lib/annotations/digest.mjs`, `cli.mjs` | the markdown digest and `umtool notes` | -| `app/api/notes/route.ts` | GET / POST (operator-stamped; 409 on a stale token) | +| `app/api/notes/route.ts` | GET / POST (operator-stamped, or agent-stamped for the bearer token; 409 on a stale token) | +| `lib/annotations/agentAuth.mjs` | who a POST is by (`noteWriter`), umtool's `WORKER_TOKEN` (`agentToken`), the POST (`postNoteOp`) | | `lib/annotations/useNotes.ts` | the page's hook | diff --git a/umtool/e2e/article-notes.spec.ts b/umtool/e2e/article-notes.spec.ts @@ -214,6 +214,29 @@ test("open notes are open decisions, linked to the note; ?note= opens on it", as await expect(page.locator(`[data-note-card='${id}']`)).toHaveAttribute("aria-current", "true"); }); +test("an agent's reply over HTTP (the MCP's): stamped agent for umtool's WORKER_TOKEN, 401 for another", async ({ page, request }) => { + await request.post("/api/notes?article=priv/polemic-alpha", { data: { op: { op: "add", text: "Say claimed.", anchor: { kind: "whole" } } } }); + const id = JSON.parse(readFileSync(NOTES, "utf8")).notes[0].id; + // The e2e server's WORKER_TOKEN (playwright.config.ts). + const wrong = await request.post("/api/notes?article=priv/polemic-alpha", { + headers: { authorization: "Bearer not-the-token" }, + data: { op: { op: "reply", id, text: "nope" } }, + }); + expect(wrong.status()).toBe(401); + const ok = await request.post("/api/notes?article=priv/polemic-alpha", { + headers: { authorization: "Bearer umtool-e2e-token" }, + data: { by: "operator", op: { op: "reply", id, text: "Changed it in the draft.", resolve: true } }, + }); + expect(ok.status()).toBe(200); + const note = JSON.parse(readFileSync(NOTES, "utf8")).notes[0]; + expect(note.replies.map((r: { author: string }) => r.author)).toEqual(["agent"]); + expect(note.resolvedBy).toBe("agent"); + + await page.goto(PAGE); + await page.getByRole("button", { name: /^resolved 1$/ }).click(); + await expect(page.locator("[data-note-card] [data-reply='agent']")).toContainText("Changed it in the draft."); +}); + test("writes outside a report are refused", async ({ request }) => { for (const q of ["article=priv/../pub", "article=priv/nope", "article=priv", "article=../x/y"]) { const r = await request.post(`/api/notes?${q}`, { data: { op: { op: "add", text: "x", anchor: { kind: "whole" } } } }); diff --git a/umtool/e2e/capabilities.ts b/umtool/e2e/capabilities.ts @@ -1,3 +1,4 @@ +import path from "node:path"; import { SONG_DATA } from "../song/paths.mjs"; import { songCapabilities } from "./fixtures/song-capabilities.mjs"; @@ -20,6 +21,7 @@ export type FixtureCapabilities = { asr: boolean; media: boolean; song: boolean; + facedet: boolean; songDir: string; }; @@ -40,6 +42,13 @@ export const NO_SOURCE_MEDIA = `needs the song project's source videos (media/), which are not at ` + `${caps.songDir}. Set SONG_DIR to a copy to run these.`; +// The face detector (a python venv, ~200 MB, and its model) is not data at all: +// a machine with every song directory may still not have it, and then every +// detection is a 503. +export const NO_FACEDET = + `needs the face detector — the facedet venv at ${path.join(path.dirname(caps.songDir), "facedet")} ` + + `and umtool/models/ — which this machine does not have.`; + // The phrase console runs against the REAL ASR corpus (`asr/`) — synthesising // one would defeat the point, since what it exercises is chunk seams, // multi-word tokens and a real confidence spread. diff --git a/umtool/e2e/faces.spec.ts b/umtool/e2e/faces.spec.ts @@ -2,7 +2,7 @@ import { test, expect, type APIRequestContext, type Page } from "@playwright/tes import { readFileSync } from "node:fs"; import path from "node:path"; import { autoCrop, scaleOf, CORNER_PX, SHOVE_FLOOR, type Box } from "../lib/face-types"; -import { caps, NO_SOURCE_MEDIA } from "./capabilities"; +import { caps, NO_FACEDET, NO_SOURCE_MEDIA } from "./capabilities"; // The face judger, against the REAL episodes the fixture symlinks -- make-fixture // derives its cover corners from media/ precisely so the frame and detect routes @@ -171,6 +171,7 @@ test("autoCrop() is the same function as facecrop.py's crop maths", async ({ req // THE QUEUE IS BUILT FROM SOURCE VIDEOS. With no `media/` the deck is // empty, and every assertion here is about a frame in it. test.skip(!caps.media, NO_SOURCE_MEDIA); + test.skip(!caps.facedet, NO_FACEDET); const { queue } = await view(request); let compared = 0; @@ -215,6 +216,7 @@ test("the deck states the shove on a corner whose crop was displaced", async ({ // THE QUEUE IS BUILT FROM SOURCE VIDEOS. With no `media/` the deck is // empty, and every assertion here is about a frame in it. test.skip(!caps.media, NO_SOURCE_MEDIA); + test.skip(!caps.facedet, NO_FACEDET); test.slow(); const { queue } = await view(request); let displaced: { key: string; shove: number } | null = null; @@ -315,6 +317,8 @@ test("a recorded crop survives a reload, in source pixels", async ({ page, reque // it would happen on every navigation. One candidate is focused, so exactly one // frame and one detection. test("only the focused candidate costs anything", async ({ page, request }) => { + // Counts detections that ANSWER: with no detector each is a 503. + test.skip(!caps.facedet, NO_FACEDET); const { queue } = await view(request); expect(queue.length).toBeGreaterThan(2); @@ -394,6 +398,8 @@ test("a crop outside the frame is refused and an unknown corner is a 404", async // THE QUEUE IS BUILT FROM SOURCE VIDEOS. With no `media/` the deck is // empty, and every assertion here is about a frame in it. test.skip(!caps.media, NO_SOURCE_MEDIA); + // Its detect-route 404 is asked of the detector, which answers 503 first. + test.skip(!caps.facedet, NO_FACEDET); const { queue } = await view(request); const target = queue[0]; @@ -443,6 +449,7 @@ test("the frame comes back at the source's own size unless a width is asked for" }) => { // Same reason as the rest of this file's frame tests: no `media/`, no queue. test.skip(!caps.media, NO_SOURCE_MEDIA); + test.skip(!caps.facedet, NO_FACEDET); const { queue } = await view(request); const e = queue[0]; const d = await detect(request, e); diff --git a/umtool/e2e/find.spec.ts b/umtool/e2e/find.spec.ts @@ -171,7 +171,10 @@ test("folding chunk twins removes exactly what it says it removed", async ({ req const raw = await find(request, `q=${COMMON}&dupes=0`); const folded = await find(request, `q=${COMMON}&dupes=1`); expect(raw.collapsed).toBe(0); - expect(folded.collapsed).toBeGreaterThan(0); + // Whether the query HAS chunk twins is the data's, not the code's: an ASR + // corpus with none for it has nothing to fold, and the arithmetic is only + // asserted where there is something to count. + test.skip(folded.collapsed === 0, `this ASR corpus has no chunk-seam twins for "${COMMON}": nothing to fold`); expect(raw.total - folded.total).toBe(folded.collapsed); }); diff --git a/umtool/e2e/fixtures/song-capabilities.mjs b/umtool/e2e/fixtures/song-capabilities.mjs @@ -1,5 +1,9 @@ import { existsSync } from "node:fs"; import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// umtool/models, where facecrop.py's model sits (make-fixture links it in). +const MODELS = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "models"); // WHAT THE SONG PROJECT'S BULK DATA OFFERS THIS MACHINE — one rule, two // readers. @@ -38,5 +42,11 @@ export function songCapabilities(songData) { // with no audio are the same failure from two directions, so one flag names // it. caps.song = caps.cand2 && caps.wav48; + // THE FACE DETECTOR: the facedet venv beside the song data (lib/faces.ts + // reads SONG_SCRATCH/facedet, SONG_SCRATCH being SONG_DIR's parent) and the + // model facecrop.py loads. Without either the detect route answers 503, which + // is a machine without the venv, not a regression. make-fixture.mjs records + // the same rule from what it linked. + caps.facedet = existsSync(path.join(path.dirname(songData), "facedet")) && existsSync(MODELS); return caps; } diff --git a/umtool/e2e/triage.spec.ts b/umtool/e2e/triage.spec.ts @@ -16,7 +16,14 @@ test.skip(!caps.song, NO_SONG_DATA); test.beforeEach(async ({ page }) => { await page.goto("/sort"); - await expect(page.getByRole("link", { name: "sort", exact: true })).toBeVisible(); + // The page is up: `sort` lives in the `song ▸` nav group (folded there + // 2026-08-25), which opens to it; Escape folds it away again so the menu does + // not sit over the card. + const group = page.locator("[data-nav-group='song']"); + await expect(group.getByRole("button")).toHaveAttribute("aria-current", "page"); + await group.getByRole("button").click(); + await expect(group.getByRole("menuitem", { name: "sort", exact: true })).toHaveAttribute("aria-current", "page"); + await page.keyboard.press("Escape"); }); test("a clip opens with a window and a waveform", async ({ page }) => { diff --git a/umtool/lib/annotations/agentAuth.mjs b/umtool/lib/annotations/agentAuth.mjs @@ -0,0 +1,149 @@ +// WHO IS WRITING A NOTE over HTTP (release 23 F3; ruled 2026-10-10: agents get +// their own write path, attributed "agent", never as the operator). +// +// The app's /api/notes POST stamps every write from the page as the +// OPERATOR's. An agent — the MCP's `notes` reply — writes through the same +// route with `Authorization: Bearer <WORKER_TOKEN>`, and its write is stamped +// "agent": +// +// no Authorization header "operator" (the page, as before) +// Bearer <umtool's WORKER_TOKEN> "agent" +// any other Authorization header 401, nothing written — including any +// bearer when umtool holds no token +// +// `by` is never read from the request body: who wrote a note is what the +// request proves, not what it says. +// +// umtool's WORKER_TOKEN is read the way the editor's clients read it (`pnpm +// ops`'s loadEditorEnv, release 19 A1): the environment — an explicit value, +// even "", wins — else the first of this checkout's `editor/.env.local`, +// `editor/.env`, then the main worktree's, that names it. The same secret the +// editor's /api/ops takes. Read per request: a token set in editor/.env after +// umtool started is honoured without a restart. + +import crypto from "node:crypto"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { REPO_ROOT } from "../paths.mjs"; +import { writeNote } from "./targets.mjs"; + +/** + * The value of one key in a dotenv text (`KEY=value`, `export KEY=value`, + * quotes stripped, an unquoted value ending at an inline comment), or + * undefined. scripts/archilyzer-ops.mjs parseDotenv's rules. + * @param {string} text + * @param {string} key + * @returns {string | undefined} + */ +export function dotenvValue(text, key) { + let out; + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith("#")) continue; + const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line); + if (!m || m[1] !== key) continue; + let value = m[2].trim(); + const q = value[0]; + if ((q === '"' || q === "'") && value.length >= 2 && value.endsWith(q)) value = value.slice(1, -1); + else value = value.replace(/\s+#.*$/, ""); + out = value; + } + return out; +} + +/** + * The main worktree of a linked worktree, or null (read off disk, as + * scripts/archilyzer-ops.mjs mainWorktreeOf does). + * @param {string} root + */ +function mainWorktreeOf(root) { + try { + const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(path.join(/* turbopackIgnore: true */ root, ".git"), "utf8")); + if (!m) return null; + const gitdir = path.resolve(/* turbopackIgnore: true */ root, m[1].trim()); + const common = path.resolve( + /* turbopackIgnore: true */ gitdir, + readFileSync(path.join(/* turbopackIgnore: true */ gitdir, "commondir"), "utf8").trim(), + ); + return path.dirname(common); + } catch { + return null; + } +} + +/** + * The editor env files consulted, in order. + * @param {string} [root] + * @returns {string[]} + */ +export function editorEnvFiles(root = REPO_ROOT) { + const roots = [root]; + const main = mainWorktreeOf(root); + if (main && path.resolve(/* turbopackIgnore: true */ main) !== path.resolve(/* turbopackIgnore: true */ root)) roots.push(main); + return roots.flatMap((r) => [ + path.join(/* turbopackIgnore: true */ r, "editor", ".env.local"), + path.join(/* turbopackIgnore: true */ r, "editor", ".env"), + ]); +} + +/** + * umtool's WORKER_TOKEN: the environment's, else the editor's env files'. "" + * when none is set — and then no bearer matches. + * @param {Record<string, string | undefined>} [env] + * @param {string[]} [files] + * @returns {string} + */ +export function agentToken(env = process.env, files = editorEnvFiles()) { + if (env.WORKER_TOKEN !== undefined) return env.WORKER_TOKEN; + for (const file of files) { + let text; + try { + text = readFileSync(file, "utf8"); + } catch { + continue; + } + const v = dotenvValue(text, "WORKER_TOKEN"); + if (v !== undefined) return v; + } + return ""; +} + +/** + * Who a request's Authorization header says is writing. + * @param {string | null | undefined} authorization + * @param {string} token umtool's WORKER_TOKEN ("" for none) + * @returns {{ ok: true, by: "operator" | "agent" } | { ok: false, status: 401, error: string }} + */ +export function noteWriter(authorization, token) { + if (authorization === null || authorization === undefined || authorization === "") return { ok: true, by: "operator" }; + const m = /^Bearer\s+(.+)$/i.exec(authorization); + if (!m) return { ok: false, status: 401, error: "notes: an Authorization header must be `Bearer <WORKER_TOKEN>`" }; + if (!token) { + return { ok: false, status: 401, error: "notes: umtool holds no WORKER_TOKEN, so no agent can write here" }; + } + const given = Buffer.from(m[1].trim()); + const want = Buffer.from(token); + if (given.length !== want.length || !crypto.timingSafeEqual(given, want)) { + return { ok: false, status: 401, error: "notes: that bearer token is not umtool's WORKER_TOKEN" }; + } + return { ok: true, by: "agent" }; +} + +/** + * The POST: one op on a target's notes, by whoever the header proves. A refusal + * is `{ status, body: { error } }`; a write `{ status: 200, body }` with what + * writeNote returns. A stale token or a refused op THROWS (the route's + * errorResponse gives each its status). + * @param {Parameters<typeof writeNote>[0]} target + * @param {unknown} body `{ token?, op }` — any `by` in it is ignored + * @param {{ authorization?: string | null, workerToken: string }} auth + */ +export async function postNoteOp(target, body, auth) { + const who = noteWriter(auth.authorization, auth.workerToken); + if (!who.ok) return { status: who.status, body: { error: who.error } }; + const b = /** @type {{ token?: unknown, op?: unknown } | null} */ (body && typeof body === "object" ? body : null); + if (!b || typeof b.op !== "object" || b.op === null) return { status: 400, body: { error: "body needs an op" } }; + const token = typeof b.token === "string" ? b.token : null; + const out = await writeNote(target, /** @type {Record<string, any>} */ (b.op), { by: who.by, token }); + return { status: 200, body: out }; +} diff --git a/umtool/lib/annotations/agentAuth.test.mjs b/umtool/lib/annotations/agentAuth.test.mjs @@ -0,0 +1,102 @@ +// The notes route's writer (release 23 F3): no Authorization is the +// operator, umtool's WORKER_TOKEN as a bearer is an agent, any other header is +// a 401 with nothing written, and `by` in the body is never believed. The +// POST's logic (postNoteOp) over a temp notes.json, and the token read. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { agentToken, dotenvValue, noteWriter, postNoteOp } from "./agentAuth.mjs"; + +const TOKEN = "notes-test-token"; +const SUBJECT = { kind: "article", site: "s1", report: "r1" }; + +async function target() { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-agent-auth-")); + return { dir, target: { file: path.join(dir, "notes.json"), subject: SUBJECT, source: async () => null } }; +} + +const ADD = { op: "add", text: "fix this", anchor: { kind: "whole" } }; + +test("no Authorization: the operator's write, as before", async () => { + const { dir, target: t } = await target(); + const r = await postNoteOp(t, { op: ADD }, { authorization: null, workerToken: TOKEN }); + assert.equal(r.status, 200); + assert.equal(r.body.note.author, "operator"); + await rm(dir, { recursive: true }); +}); + +test("umtool's WORKER_TOKEN as a bearer: the agent's write — a note, a reply, a resolve", async () => { + const { dir, target: t } = await target(); + const auth = { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN }; + const add = await postNoteOp(t, { op: ADD }, { authorization: null, workerToken: TOKEN }); + const id = add.body.note.id; + const r = await postNoteOp(t, { op: { op: "reply", id, text: "done in drafts/x.json", resolve: true } }, auth); + assert.equal(r.status, 200); + assert.equal(r.body.note.replies[0].author, "agent"); + assert.equal(r.body.note.status, "resolved"); + assert.equal(r.body.note.resolvedBy, "agent"); + const own = await postNoteOp(t, { op: ADD }, auth); + assert.equal(own.body.note.author, "agent"); + await rm(dir, { recursive: true }); +}); + +test("a wrong bearer, a malformed header, or any bearer when umtool holds no token: 401, nothing written", async () => { + const { dir, target: t } = await target(); + for (const [authorization, workerToken] of [ + ["Bearer not-the-token", TOKEN], + [`Bearer ${TOKEN}x`, TOKEN], + [`Basic ${TOKEN}`, TOKEN], + [`Bearer ${TOKEN}`, ""], + ]) { + const r = await postNoteOp(t, { op: ADD }, { authorization, workerToken }); + assert.equal(r.status, 401, `${authorization} / ${workerToken || "(none)"}`); + assert.match(r.body.error, /^notes: /); + } + await assert.rejects(stat(t.file), /ENOENT/); + await rm(dir, { recursive: true }); +}); + +test("`by` in the body is never believed", async () => { + const { dir, target: t } = await target(); + const asOperator = await postNoteOp(t, { by: "agent", op: { ...ADD, by: "agent", author: "agent" } }, { authorization: null, workerToken: TOKEN }); + assert.equal(asOperator.body.note.author, "operator"); + const asAgent = await postNoteOp(t, { by: "operator", op: { ...ADD, by: "operator", author: "operator" } }, { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN }); + assert.equal(asAgent.body.note.author, "agent"); + const doc = JSON.parse(await readFile(t.file, "utf8")); + assert.deepEqual(doc.notes.map((n) => n.author), ["operator", "agent"]); + await rm(dir, { recursive: true }); +}); + +test("a body with no op is a 400", async () => { + const { dir, target: t } = await target(); + assert.equal((await postNoteOp(t, null, { authorization: null, workerToken: TOKEN })).status, 400); + assert.equal((await postNoteOp(t, { token: "absent" }, { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN })).status, 400); + await rm(dir, { recursive: true }); +}); + +test("noteWriter: the header alone decides", () => { + assert.deepEqual(noteWriter(undefined, TOKEN), { ok: true, by: "operator" }); + assert.deepEqual(noteWriter("", TOKEN), { ok: true, by: "operator" }); + assert.deepEqual(noteWriter(`bearer ${TOKEN}`, TOKEN), { ok: true, by: "agent" }); + assert.equal(noteWriter("Bearer x", TOKEN).ok, false); +}); + +test("agentToken: the environment first (even empty), else the editor's env files in order", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-agent-token-")); + const local = path.join(dir, ".env.local"); + const plain = path.join(dir, ".env"); + await writeFile(plain, "# the editor's\nOTHER=1\nexport WORKER_TOKEN=\"from-env-file\"\n"); + assert.equal(agentToken({ WORKER_TOKEN: "from-environment" }, [local, plain]), "from-environment"); + assert.equal(agentToken({ WORKER_TOKEN: "" }, [local, plain]), ""); + assert.equal(agentToken({}, [local, plain]), "from-env-file"); + await writeFile(local, "WORKER_TOKEN=from-local # comment\n"); + assert.equal(agentToken({}, [local, plain]), "from-local"); + assert.equal(agentToken({}, [path.join(dir, "missing")]), ""); + assert.equal(dotenvValue("A=1\nWORKER_TOKEN='x y'\n", "WORKER_TOKEN"), "x y"); + assert.equal(dotenvValue("A=1\n", "WORKER_TOKEN"), undefined); + await rm(dir, { recursive: true }); +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -77,7 +77,13 @@ export default defineConfig({ workers: 1, // `json` beside `list`: the run's timing record, which // scripts/e2e-timings.mjs totals per spec against the branch's last run. - reporter: [["list"], ["json", { outputFile: "test-results/timings.json" }]], + reporter: [ + ["list"], + ["json", { outputFile: "test-results/timings.json" }], + // Records this run in the branch's history once the json is written + // (scripts/e2e-timings-reporter.mjs), so a re-run never erases it. + ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }], + ], use: { baseURL: `http://localhost:${PORT}`, trace: "retain-on-failure", diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -61,6 +61,7 @@ import path from "node:path"; import os from "node:os"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; // This file lives at <repo>/umtool/report-to-video/, so the corpus a plain // checkout would have is two levels up. Previously this defaulted to an absolute @@ -455,7 +456,9 @@ export function createCueSource({ // Throws a CueLookupError — which carries no `code`, so `load`'s ENOENT // fallback rethrows it rather than reaching for the archive. await assertChannelReachable(channelSlug); - const p = path.join(channelsDir, channelSlug, "data", videoId, "transcript.cues.json"); + // The record's DIRECTORY: a Twitch record's v<n> lives in data/<n>/ + // (release 23 F1); every other id is its own directory, with no read. + const p = path.join(await resolveVideoDir(channelsDir, channelSlug, videoId), "transcript.cues.json"); const parsed = JSON.parse(await readFile(p, "utf8")); if (await staleCaptionRecord(path.dirname(p), parsed)) { throw new CueLookupError( diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -149,6 +149,33 @@ test("a local corpus is preferred over the network", async () => { } }); +test("a Twitch record's v<n> reads its local cues from data/<n>/, and keeps its id (release 23 F1)", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "cues-twitch-")); + try { + const n = "2700000001"; + await mkdir(path.join(dir, "tw", "data", n), { recursive: true }); + // No platform key: the channel's url says Twitch. + await writeFile(path.join(dir, "tw", "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.twitch.tv/example" })); + await writeFile( + path.join(dir, "tw", "data", n, "transcript.cues.json"), + JSON.stringify({ ...RECORD, id: `v${n}`, slug: `tw/v${n}`, channelSlug: "tw", platform: "twitch" }), + ); + const seen = []; + const src = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, fetchImpl: stubFetch(ROUTES, seen) }); + const got = await src.load("tw", `v${n}`); + assert.equal(got.from, "local"); + assert.equal(got.id, `v${n}`); + assert.equal(got.cues.length, 2); + assert.deepEqual(seen, []); + // A v-id on a channel of another platform is never mapped: no local cues. + await writeFile(path.join(dir, "tw", "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); + const strict = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, prefer: "local", fetchImpl: stubFetch(ROUTES) }); + await assert.rejects(() => strict.load("tw", `v${n}`), /no local cues/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + // --- a caption record normalized under an older caption-track rule --------- test("a local caption record from before the caption-track rule is refused where the rule could read other words", async () => {