Archilyzer · Source

archilyzer

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

commit 514899e7c1a3a5f7b342ce7d32b81b3a75d72acf
parent fcaf0358fc7f4ba900e4541231589049b680ff74
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 09:33:14 -0500

Merge lane/local-media: a local library's short-form subtitle timings are read (mm:ss.mmm, hours capped, a cue's body stops at the next cue line, an end before its start is not a cue) with the long form unchanged, and a recording whose file name a reference cannot hold is held in the preview with the reason (local media, slice 2)

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/buildIndexLocalRecording.test.ts | 2+-
Mcommon/controller/localMediaImport.test.ts | 6+++---
Mcommon/lib/localMedia.ts | 18++++++++++++------
Mcommon/lib/localMediaCommit-server.test.ts | 2+-
Mcommon/lib/localMediaScan.test.ts | 31+++++++++++++++++++++++--------
Mcommon/lib/localMediaScan.ts | 11+++++++++--
Mcommon/lib/localMediaTranscript.test.ts | 2+-
Mcommon/lib/vtt.test.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/vtt.ts | 85++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Meditor/CHANGELOG.md | 1+
Meditor/e2e/local-media.spec.ts | 13++++++++++++-
11 files changed, 288 insertions(+), 39 deletions(-)

diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts @@ -39,7 +39,7 @@ const writeJson = (file: string, value: unknown) => { }; const channel = "classroom"; const dataDirectory = path.join(paths.channelsDir, channel, "data"); -const transcript = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSynthetic classroom discovery phrase\n"; +const transcript = "WEBVTT\n\n00:00.000 --> 00:02.000\nSynthetic classroom discovery phrase\n"; const first = "local-" + "a".repeat(32), second = "local-" + "b".repeat(32); const metadata = (id: string, recordedDate?: string) => prepareManualLocalRecordingMetadata({id, filename: "Lesson 2020-01-01.mp4", recordedDate}); diff --git a/common/controller/localMediaImport.test.ts b/common/controller/localMediaImport.test.ts @@ -17,7 +17,7 @@ async function fixture(t: TestContext) { async function add(name: string, id = name) { await writeFile(path.join(source, name + ".mp4"), "synthetic video"); await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` })); - await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n"); + await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:01.000 --> 00:02.000\nSynthetic cue\n"); } return { root, source, paths, channel, config, add }; } @@ -48,7 +48,7 @@ test("preview creates nothing; import then rescan detects additions without chan }); test("changed transcript after preview is stale and no record is written", async (t) => { const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample"); - await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged text\n"); + await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:01.000 --> 00:02.000\nChanged text\n"); const result=await importLocalMedia(f.paths,"sample",selection(p)); assert.equal(result.records[0].status,"stale"); assert.equal(result.needsIndexUpdate,false); assert.deepEqual(await readdir(f.channel),["config.json"]); @@ -173,7 +173,7 @@ test("managed job fails honestly for a stale selection after publishing another const f = await fixture(t); await f.add("first"); await f.add("second"); const p = await previewLocalMedia(f.paths, "sample"); const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p)); - await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged\n"); + await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:01.000 --> 00:02.000\nChanged\n"); const log: string[] = []; await assert.rejects(job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext()), /require review/); assert.deepEqual(await readdir(path.join(f.channel, "data")), ["first"]); diff --git a/common/lib/localMedia.ts b/common/lib/localMedia.ts @@ -32,16 +32,22 @@ export function coerceLocalMediaConfig(value: unknown): LocalMediaConfig | undef return { sourceId: value.sourceId, directory, ...(value.playback === true ? { playback: true as const } : {}) }; } +// Whether a library-relative path can be stored in a reference. Literal +// filenames with '/' separators, never URL-decoded; both OSes' escape syntax +// (\ and :) and control characters are refused regardless of the machine doing +// the read. No path normalization: it would conceal traversal or change a +// source name. The scan asks this too, so a recording whose name a reference +// cannot hold is an issue in its preview, not a failed import. +export function isExternalMediaRelativePath(relativePath: string): boolean { + return !!relativePath && relativePath.length <= 4096 && !/[\\:\x00-\x1f\x7f]/.test(relativePath) + && !relativePath.split("/").some((part) => !part || part === "." || part === "..") + && /\.mp4$/i.test(relativePath); +} export function coerceExternalMediaReference(value: unknown): ExternalMediaReference | null { if (!record(value) || value.version !== 1 || value.kind !== "external" || !isLocalMediaSourceId(value.sourceId) || typeof value.relativePath !== "string") return null; const relativePath = value.relativePath; - // Store literal filenames using '/' separators, never URL-decode them. - // Reject both OSes' escape syntax regardless of the machine doing the read. - // No path normalization: it would conceal traversal or change a source name. - if (!relativePath || relativePath.length > 4096 || /[\\:\x00-\x1f\x7f]/.test(relativePath) - || relativePath.split("/").some((part) => !part || part === "." || part === "..") - || !/\.mp4$/i.test(relativePath)) return null; + if (!isExternalMediaRelativePath(relativePath)) return null; return { version: 1, kind: "external", sourceId: value.sourceId, relativePath }; } diff --git a/common/lib/localMediaCommit-server.test.ts b/common/lib/localMediaCommit-server.test.ts @@ -11,7 +11,7 @@ async function fixture(t: TestContext) { const dataDirectory = path.join(root, "data"); await mkdir(dataDirectory); const input = { dataDirectory, directoryId: "test-id", metadata: JSON.stringify({ id: "test-id", title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: "https://www.youtube.com/watch?v=test-id" }), - transcript: "WEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nSynthetic cue\r\n", + transcript: "WEBVTT\r\n\r\n00:01.000 --> 00:02.000\r\nSynthetic cue\r\n", reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "Original ⧸ $title.mp4" } }; return { root, input, target: path.join(dataDirectory, "test-id") }; } diff --git a/common/lib/localMediaScan.test.ts b/common/lib/localMediaScan.test.ts @@ -145,22 +145,19 @@ test("read-only source files remain readable and unchanged", async (t) => { } finally { for (const file of files) await chmod(path.join(root, file), 0o644); } }); -// The parser reads only hh:mm:ss.mmm cue timings until slice 2 lands its -// short-form support (with a corpus regression check). Until then a short-form -// VTT is held for review, never imported with missing or misread cues. -test("short-form timestamps are held for review, not imported", async (t) => { +test("short timestamps produce index-compatible cues", async (t) => { const root = await fixture(t); await add(root, "short"); await writeFile(path.join(root, "short.vtt"), "WEBVTT\n\n00:00.250 --> 00:01.910\nShort cue\n"); const row = (await scan(root)).candidates[0]; - assert.equal(row.status, "issue"); - assert.match(row.issues.join(), /no usable cues/); - assert.equal(row.fingerprint, undefined); + assert.equal(row.status, "new"); + assert.equal(row.cueCount, 1); + assert.deepEqual(row.warnings, []); }); test("isolated zero-duration cues warn without changing source; all-point transcripts remain blocked", async (t) => { const root = await fixture(t); await add(root, "mixed"); await add(root, "points"); - const point = "00:00:03.000 --> 00:00:03.000\nPoint cue\n"; + const point = "00:03.000 --> 00:03.000\nPoint cue\n"; const mixed = VTT + "\n" + point; await writeFile(path.join(root, "mixed.vtt"), mixed); await writeFile(path.join(root, "points.vtt"), "WEBVTT\n\n" + point); @@ -172,3 +169,21 @@ test("isolated zero-duration cues warn without changing source; all-point transc assert.match(result.candidates[1].issues.join(), /no positive-duration/); assert.equal(await readFile(path.join(root, "mixed.vtt"), "utf8"), mixed); }); +// A name a library reference cannot hold (coerceExternalMediaReference refuses +// a control character, \ or :) is an issue in the preview: offered as new, its +// import could only fail. No fingerprint of any kind is offered for it. +test("a recording whose file name a reference cannot hold is held for review", async (t) => { + const root = await fixture(t); + for (const name of ["colon:name", "back\\slash", "tab\tname", "line\nbreak"]) await add(root, name, "id-" + name.length); + await writeFile(path.join(root, "bare\u0001.mp4"), "synthetic video bytes"); + await writeFile(path.join(root, "bare\u0001.vtt"), VTT); + const result = await scan(root); + assert.equal(result.candidates.length, 5); + for (const row of result.candidates) { + assert.equal(row.status, "issue", JSON.stringify(row.media)); + assert.match(row.issues[0], /^Media: the file name has a control character/); + assert.equal(row.fingerprint, undefined); + assert.equal(row.preparationFingerprint, undefined); + assert.equal(row.transcriptionFingerprint, undefined); + } +}); diff --git a/common/lib/localMediaScan.ts b/common/lib/localMediaScan.ts @@ -4,6 +4,7 @@ import type { Stats } from "node:fs"; import path from "node:path"; import { lstat, open, readdir, realpath } from "node:fs/promises"; import { extractVideoId } from "./videoId"; +import { isExternalMediaRelativePath } from "./localMedia"; import { parseVtt } from "./vtt"; // Read-only discovery, not an executable import plan. The caller supplies the @@ -114,8 +115,14 @@ export async function scanLocalMedia(options: { let metadataMissing = false; let transcriptText = ""; let metadataUsable = false; - try { mediaStat = await lstat(await regularFile(root, media)); } - catch (error) { row.issues.push(`Media: ${reason(error)}`); } + // A name the library reference cannot hold (a control character, \ or :) + // is held here: offered as new, its import could only fail. + if (!isExternalMediaRelativePath(media)) { + row.issues.push("Media: the file name has a control character, \\ or :, which a library reference cannot hold; rename the file"); + } else { + try { mediaStat = await lstat(await regularFile(root, media)); } + catch (error) { row.issues.push(`Media: ${reason(error)}`); } + } try { metadataText = await readLocalMediaText(root, row.metadata); const meta = JSON.parse(metadataText.replace(/^\uFEFF/, "")); diff --git a/common/lib/localMediaTranscript.test.ts b/common/lib/localMediaTranscript.test.ts @@ -7,7 +7,7 @@ test("SRT preserves multiline Unicode dialogue, emphasis, overlaps and milliseco assert.equal(srtToVtt(input), "WEBVTT\n\n00:00:01.001 --> 00:00:03.999\n<i>Hello</i> &amp; welcome\n録画\n\n00:00:02.050 --> 00:00:04.500\nSecond line\n"); }); test("VTT remains byte-for-byte text and SRT freshness includes unconverted source", () => { - const vtt = "\uFEFFWEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nHi\r\n"; + const vtt = "\uFEFFWEBVTT\r\n\r\n00:01.000 --> 00:02.000\r\nHi\r\n"; assert.equal(localTranscriptVtt("lesson.vtt", vtt), vtt); assert.equal(localTranscriptFingerprint("lesson.vtt",vtt), vtt); const srt = "1\n00:00:01,000 --> 00:00:02,000\nHi\n"; diff --git a/common/lib/vtt.test.ts b/common/lib/vtt.test.ts @@ -95,3 +95,159 @@ test("parseVtt reads cue identifiers and settings as structure, not text", () => { start: 3, end: 4, text: "Second line" }, ]); }); + +// Regression: short FFmpeg timestamps previously produced zero index cues. +// Test numeric seconds, not just cue counts, to catch unit/field shifts. +test("parseVtt accepts short timestamps, mixed forms, settings, and CRLF", () => { + const src = "WEBVTT\r\n\r\n1\r\n00:00.250 --> 00:01.910 line:90%\r\nFirst\r\n\r\n" + + "2\r\n59:59.500 --> 01:00:01.250\r\nBoundary\r\n"; + assert.deepEqual(parseVtt(src), [ + { start: 0.25, end: 1 + 910 / 1000, text: "First" }, + { start: 3599.5, end: 3601.25, text: "Boundary" }, + ]); +}); +test("parseVtt accepts hours longer than two digits", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n100:00:01.000 --> 100:00:02.000\nLong recording\n"), + [{ start: 360001, end: 360002, text: "Long recording" }]); +}); +test("short inline timing retains rolling-caption classification and strips timing tags", () => { + const src = "WEBVTT\n\n00:01.000 --> 00:02.000\n<00:01.000><c>Hello</c> <00:01.500><c>world</c>\n\n" + + "00:02.000 --> 00:02.010\nHello world\n"; + assert.equal(hasWordTiming(src), true); + assert.deepEqual(parseVtt(src), [{ start: 1, end: 2, text: "Hello world" }]); +}); +test("timing lines do not partially match malformed or out-of-range stamps", () => { + for (const stamp of ["00:60.000", "60:00.000", "00:00:60.000", "-00:01.000", "x00:01.000", "00:01.0000"]) { + assert.deepEqual(parseVtt(`WEBVTT\n\n${stamp} --> 00:02.000\nInvalid\n`), [], stamp); + } +}); +test("a short-form stamp whose hours do not fit a number is not a cue line", () => { + const hours = "9".repeat(400); + assert.deepEqual(parseVtt(`WEBVTT\n\n${hours}:00:01.000 --> ${hours}:00:02.000\nToo long\n`), []); + assert.deepEqual(parseVtt(`WEBVTT\n\n00:01.000 --> ${hours}:00:02.000\nToo long\n\n00:03.000 --> 00:04.000\nKept\n`), + [{ start: 3, end: 4, text: "Kept" }]); +}); +// A hostile line (a long run of digits, spaces, tags or stamps) is read in time +// proportional to its length: every timing pattern is anchored or bounded. +test("a long hostile timing line is read in linear time", () => { + const lines = [ + "1".repeat(200_000) + ":00:01.000 --> 00:02.000", + "00:01.000" + " ".repeat(200_000) + "x", + "00:01.000 --> 00:02.000" + " ".repeat(200_000) + "\u0000", + "<".repeat(100_000) + "00:01.000".repeat(20_000), + "00:00:01.000 ".repeat(20_000), + ]; + const started = Date.now(); + for (const line of lines) parseVtt(`WEBVTT\n\n${line}\nText\n`); + assert.ok(Date.now() - started < 2000, `took ${Date.now() - started} ms`); +}); +test("point cues preserve original text and timestamps", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:01.000\nPoint\n"), + [{ start: 1, end: 1, text: "Point" }]); +}); + +// THE OLD CUE LINE STAYS LENIENT. Short-form support is a second reading, tried +// only on a line the hh:mm:ss.mmm one does not match; every published site's +// cues came through the lenient one, so what it accepted it still accepts, to +// the same numbers. Each test below is a tightening the contributed parser +// made; each passes on the parser as it was before short-form support. +test("a hh:mm:ss.mmm cue line is found anywhere in its line, as before", () => { + const cue = (line: string) => parseVtt(`WEBVTT\n\n${line}\nText\n`); + const want = [{ start: 1, end: 2, text: "Text" }]; + assert.deepEqual(cue("x00:00:01.000 --> 00:00:02.000"), want); + assert.deepEqual(cue("-00:00:01.000 --> 00:00:02.000"), want); + assert.deepEqual(cue("cue-7 00:00:01.000 --> 00:00:02.000"), want); + assert.deepEqual(cue("00:00:01.000 --> 00:00:02.000align:start"), want); + // More than two hour digits at the START: the last two are read. + assert.deepEqual(cue("100:00:01.000 --> 00:00:02.000"), want); +}); + +test("a hh:mm:ss.mmm cue line's minutes and seconds are not range-checked, as before", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n00:75:90.000 --> 01:99:60.500\nOut of range\n"), [ + { start: 75 * 60 + 90, end: 3600 + 99 * 60 + 60.5, text: "Out of range" }, + ]); +}); + +test("a hh:mm:ss.mmm end stamp with extra millisecond digits reads its first three, as before", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> 00:00:02.5009\nLong fraction\n"), [ + { start: 1, end: 2.5, text: "Long fraction" }, + ]); +}); + +test("a hh:mm:ss.mmm cue line takes any whitespace around the arrow, as before", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> \t00:00:02.000\nSpaced\n"), [ + { start: 1, end: 2, text: "Spaced" }, + ]); +}); + +// The contributed parser returned NaN for a stamp it could not read where the +// old one returned 0. Neither is reachable through a matched hh:mm:ss.mmm line; +// what is pinned is that every lenient line above yields finite numbers. +test("no cue the old line accepts carries a NaN time", () => { + const src = "WEBVTT\n\nx00:00:01.000 --> 00:00:02.0009\nA\n\n00:75:90.000 --> 00:99:99.000\nB\n"; + const cues = parseVtt(src); + assert.equal(cues.length, 2); + for (const c of cues) assert.ok(Number.isFinite(c.start) && Number.isFinite(c.end)); +}); + +// A document the old parser read cues from keeps its SHAPE: short-form word +// tags make a document rolling only when it has no hh:mm:ss.mmm cue line. +test("short-form word tags do not reclassify a document with hh:mm:ss.mmm cue lines", () => { + const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n<00:01.000><c>Hello</c> <00:01.500><c>world</c>\n\n" + + "00:00:02.000 --> 00:00:02.010\nHello again\n"; + assert.equal(hasWordTiming(src), false); + assert.deepEqual(parseVtt(src), [ + { start: 1, end: 2, text: "Hello world" }, + { start: 2, end: 2.01, text: "Hello again" }, + ]); +}); + +test("a short-form tag inside a hh:mm:ss.mmm rolling line stays text, as before", () => { + const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\none<00:00:01.500><c> two</c><00:01.800>\n"; + assert.deepEqual(parseVtt(src), [{ start: 1, end: 2, text: "one two<00:01.800>" }]); +}); + +test("a short-form cue line in a body is that cue's text, and one on its own is a cue", () => { + const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nFirst\n00:03.000 --> 00:04.000\n\n" + + "00:05.000 --> 00:06.000\nSecond\n"; + assert.deepEqual(parseVtt(src), [ + { start: 1, end: 2, text: "First 00:03.000 --> 00:04.000" }, + { start: 5, end: 6, text: "Second" }, + ]); +}); + +// Review 2 should-fixes: a short-form cue line never takes a line the old +// parser read, and is held to the shape of a real cue line. +test("a short-form cue's body stops at a hh:mm:ss.mmm cue line, which is read as the old parser read it", () => { + const src = "WEBVTT\n\n01:00.000 --> 01:02.000\n00:00:05.000 --> 00:00:06.000\nkept?\n"; + // The short cue is left with no body and dropped, as a bodiless long cue is. + assert.deepEqual(parseVtt(src), [{ start: 5, end: 6, text: "kept?" }]); + assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n\nA\n"), []); +}); +test("a short-form cue's body stops at another short-form cue line", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000\nOne\n00:03.000 --> 00:04.000\nTwo\n"), [ + { start: 1, end: 2, text: "One" }, + { start: 3, end: 4, text: "Two" }, + ]); +}); +test("a short-form line that ends before it starts is not a cue line", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n01:00.000 --> 00:01.000\nBackwards\n"), []); + // Nor does it end a short cue's body: it is that cue's text. + assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000\nOne\n01:00.000 --> 00:01.000\n"), + [{ start: 1, end: 2, text: "One 01:00.000 --> 00:01.000" }]); +}); +test("short-form hours are two to four digits", () => { + assert.deepEqual(parseVtt("WEBVTT\n\n99999999999999999999:00:01.000 --> 99999999999999999999:00:02.000\nToo long\n"), []); + assert.deepEqual(parseVtt("WEBVTT\n\n12345:00:01.000 --> 12345:00:02.000\nFive\n"), []); + assert.deepEqual(parseVtt("WEBVTT\n\n1000:00:01.000 --> 1000:00:02.000\nFour\n"), + [{ start: 3600000 + 1, end: 3600000 + 2, text: "Four" }]); + assert.deepEqual(parseVtt("WEBVTT\n\n100:00:01.000 --> 100:00:02.000\nThree\n"), + [{ start: 360001, end: 360002, text: "Three" }]); +}); +test("a short-form line ending in a stray \\r (a \\r\\r\\n file) reads like a hh:mm:ss.mmm one", () => { + const short = "WEBVTT\r\r\n\r\r\n00:01.000 --> 00:02.000\r\r\nHi\r\r\n"; + const long = "WEBVTT\r\r\n\r\r\n00:00:01.000 --> 00:00:02.000\r\r\nHi\r\r\n"; + assert.deepEqual(parseVtt(short), [{ start: 1, end: 2, text: "Hi" }]); + assert.deepEqual(parseVtt(short), parseVtt(long)); + assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000 align:start\r\nHi\n"), [{ start: 1, end: 2, text: "Hi" }]); +}); diff --git a/common/lib/vtt.ts b/common/lib/vtt.ts @@ -1,12 +1,41 @@ export type Cue = { start: number; end: number; text: string }; const TIMING_TAG_RE = /<\d{2}:\d{2}:\d{2}\.\d{3}>/; +// The cue line every existing corpus is read with: hh:mm:ss.mmm on both sides, +// found ANYWHERE in the line and not range-checked. Lenient on purpose now — +// every published site's cues came through it, so a line it matches is read +// exactly as it always was (vtt.test.ts pins the leniencies). +const CUE_TIMING_RE = + /(\d{2}:\d{2}:\d{2}\.\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2}\.\d{3})/; + +// SHORT FORM (mm:ss.mmm — legal WebVTT, what FFmpeg and hand-made subtitle +// files write). Tried only on a line CUE_TIMING_RE did not match, so it can add +// cues to a document and never change one: it is strict where the old line is +// lenient (anchored, minutes and seconds 00–59, exactly three millisecond +// digits, end not before start), either side may carry hours, of two to four +// digits. A stray \r before the line's end (a \r\r\n file) is allowed, as +// the old line, unanchored, always allowed it. +const SHORT_TIMESTAMP = "(?:\\d{2,4}:)?[0-5]\\d:[0-5]\\d\\.\\d{3}"; +const SHORT_TIMING_TAG_RE = new RegExp("<" + SHORT_TIMESTAMP + ">"); +const SHORT_TIMING_TAG_RE_G = new RegExp("<" + SHORT_TIMESTAMP + ">", "g"); +const SHORT_CUE_TIMING_RE = new RegExp( + "^[ \\t]*(" + SHORT_TIMESTAMP + ")[ \\t]+-->[ \\t]+(" + SHORT_TIMESTAMP + ")(?:[ \\t].*)?[ \\t\\r]*$", +); + +// A rolling track written with short-form word tags (<mm:ss.mmm>). It counts +// only in a document with no hh:mm:ss.mmm tag and no hh:mm:ss.mmm cue line — +// one the old parser read no cue from — so a document it could read keeps the +// shape it was always read as. +function hasShortWordTiming(src: string): boolean { + if (!SHORT_TIMING_TAG_RE.test(src)) return false; + return !src.split("\n").some((line) => CUE_TIMING_RE.test(line)); +} -// Whether VTT text carries inline word timing (<hh:mm:ss.mmm>) — the mark of -// YouTube's rolling auto-caption shape, which parseVtt reads differently from -// plain cue blocks. +// Whether VTT text carries inline word timing (<hh:mm:ss.mmm>, or <mm:ss.mmm> +// in a short-form document) — the mark of YouTube's rolling auto-caption +// shape, which parseVtt reads differently from plain cue blocks. export function hasWordTiming(src: string): boolean { - return TIMING_TAG_RE.test(src); + return TIMING_TAG_RE.test(src) || hasShortWordTiming(src); } function parseTimestamp(ts: string): number { @@ -16,6 +45,24 @@ function parseTimestamp(ts: string): number { return +h * 3600 + +mm * 60 + +s + +ms / 1000; } +// A stamp SHORT_CUE_TIMING_RE captured: hours optional. +function parseShortTimestamp(ts: string): number { + const m = ts.match(/^(?:(\d+):)?(\d{2}):(\d{2})\.(\d{3})$/); + if (!m) return Number.NaN; + const [, h = "0", mm, s, ms] = m; + return +h * 3600 + +mm * 60 + +s + +ms / 1000; +} + +// A short-form cue line's times, or null when the line is not one: it must +// match SHORT_CUE_TIMING_RE and not end before it starts. +function shortCueTiming(line: string): { start: number; end: number } | null { + const m = line.match(SHORT_CUE_TIMING_RE); + if (!m) return null; + const start = parseShortTimestamp(m[1]); + const end = parseShortTimestamp(m[2]); + return Number.isFinite(start) && Number.isFinite(end) && end >= start ? { start, end } : null; +} + function decodeEntities(s: string): string { return s .replace(/&nbsp;/g, " ") @@ -26,9 +73,9 @@ function decodeEntities(s: string): string { .replace(/&quot;/g, '"'); } -function stripTags(s: string): string { +function stripTags(s: string, shortForm: boolean): string { return decodeEntities(s) - .replace(/<\d{2}:\d{2}:\d{2}\.\d{3}>/g, "") + .replace(shortForm ? SHORT_TIMING_TAG_RE_G : /<\d{2}:\d{2}:\d{2}\.\d{3}>/g, "") .replace(/<\/?c[^>]*>/g, "") .replace(/\s+/g, " ") .trim(); @@ -59,23 +106,29 @@ function stripPlainLine(s: string): string { export function parseVtt(src: string): Cue[] { const lines = src.replace(/\r\n/g, "\n").split("\n"); const cues: Cue[] = []; - const rolling = hasWordTiming(src); + const shortRolling = !TIMING_TAG_RE.test(src) && hasShortWordTiming(src); + const rolling = shortRolling || TIMING_TAG_RE.test(src); + const tagRe = shortRolling ? SHORT_TIMING_TAG_RE : TIMING_TAG_RE; let i = 0; while (i < lines.length) { const line = lines[i]; - const m = line.match( - /(\d{2}:\d{2}:\d{2}\.\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2}\.\d{3})/, - ); - if (!m) { + const m = line.match(CUE_TIMING_RE); + const short = m ? null : shortCueTiming(line); + if (!m && !short) { i++; continue; } - const start = parseTimestamp(m[1]); - const end = parseTimestamp(m[2]); + const start = m ? parseTimestamp(m[1]) : short!.start; + const end = m ? parseTimestamp(m[2]) : short!.end; i++; + // A hh:mm:ss.mmm cue's body runs to the blank line, as it always did. A + // short-form cue's body also stops at the next cue line of either form, + // so a line the old parser read as a cue is still read as one. A short + // cue left with no body is dropped, as a bodiless hh:mm:ss.mmm cue is. const body: string[] = []; - while (i < lines.length && lines[i].trim() !== "") { + while (i < lines.length && lines[i].trim() !== "" + && (m || !(CUE_TIMING_RE.test(lines[i]) || shortCueTiming(lines[i])))) { body.push(lines[i]); i++; } @@ -84,9 +137,9 @@ export function parseVtt(src: string): Cue[] { if (!rolling) { text = body.map(stripPlainLine).filter(Boolean).join(" "); } else { - const taggedLines = body.filter((l) => TIMING_TAG_RE.test(l)); + const taggedLines = body.filter((l) => tagRe.test(l)); if (taggedLines.length === 0) continue; - text = stripTags(taggedLines[taggedLines.length - 1]); + text = stripTags(taggedLines[taggedLines.length - 1], shortRolling); } if (text) cues.push({ start, end, text }); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -4,6 +4,7 @@ - **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). A log holds 20,000 calls or 32 MB; past that the panel says the log is full, and later calls are not recorded. The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run. - **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, anything shaped like a credential (a URL's user and password, a token in a query string however its `&` and `=` are written — `\u0026`, `&amp;`, `%26`, `%3D` — an `Authorization` value of any scheme, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, while a date or a time after `secret:` or `token:` is left as it is, and a failed call's message has its URLs and addresses removed. Links are kept. - **Cancelling a job whose program never started no longer stops the editor.** A download cancelled after its channel directory was gone sent SIGTERM to the editor's whole process group: Node's `kill()` on a child that failed to spawn has no pid and signals the caller's own group. A kill on such a child is now a no-op in the editor, and umtool and the standalone scripts (the queue lock, `render-mode on -- <cmd>`, loudness, voice, TTS, diarization, `pnpm e2e:all`) check the child's pid before every kill; a sweep test holds them to it. +- **A local media library's subtitles may use short cue timings (`01:02.500 --> 01:04.000`).** A Local Archive channel (New channel → Local Archive, or `pnpm ops local-media-configure`) scans a folder of recordings with their `.info.json` and `.vtt` or `.srt`, and imports them as records whose video stays in the library. A `.vtt` written with minutes and seconds only — what FFmpeg and hand-made subtitle files write — read as "no usable cues" and was held for review; it is now read, previewed with its cue count and imported byte for byte. The hours form every published site's captions are read with is unchanged and tried first, so no existing caption file reads differently (checked against 10,874 of the corpus's caption files: 0 cues differ); a short-form line is read only where it does not match, and only strictly: minutes and seconds 00–59, exactly three millisecond digits, hours optional and at most four digits, an end not before its start, and its text stopping at the next cue line of either form, so a line the old reading took as a cue is still one. A recording whose file name holds a control character, `\` or `:` is now held for review in the preview, saying so, instead of being offered as new and refused at import. - **A published archive is a source: connect it once, sweep it, and fetch its cited clips with no local corpus.** A fresh clone pointed at jeralyzer.pages.dev could search it through the MCP and do nothing else: Create had no corpus to offer, and every clip of a channel the editor did not archive was a 404 `Channel "<slug>" not found`. An archive is now connected by its origin — `/sites` → **Connected archives**, or `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev"}'` (`"dryRun": true` reads it and writes nothing; `pnpm ops get archives` lists them) — and kept in `settings.remoteArchives`. `TRANSCRIPT_SITE_URL`'s archive is offered without being connected, so a clone set up as AGENTS.md says starts with one. Create offers each connected archive as a sweep's source, preselected when this machine has no corpus of its own, the MCP's `list_sources` lists them and `generate` passes the choice. A sweep over an archive cites that archive's origin, whatever `generation.citationOrigin` says, and its revisions, drafts and refreshes inherit it. A clip window cited from one registers its channel **remote-only** on first need (`fetch-windows` and `fetch-window` take `"archive"`, and the MCP's `fetch_clip` names it): a `config.json` and nothing else, shown as "remote only" in the channel list, skipped by every sync, lane, scan and site build, and left out of the site form's channel picker. On a whole-recording platform (Rumble) a window means downloading the whole recording, which nobody planned for a channel that is not archived here: it is refused with the recording's length and estimated size until the ask carries `"allowWholeRecording": true`. The archive's documents are cached on disk by its build (512 MB by default), read one at a time and paced. `corpus.json` is spec 6 (the export's changelog): each channel names its platform and its page there; an older archive's platform is read from a record's `webpageUrl`. - **A connected archive is untrusted input.** umtool can connect one and is open on the LAN, and everything an archive serves is someone else's JSON. An archive on this machine or its network — loopback, private, link-local and CGNAT addresses in any spelling (decimal, hex, IPv4 carried inside IPv6), a `.local`/`.internal`/`.lan` name, or a name that resolves to one — is refused at connect, before anything is asked of it, unless the editor runs with `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1` or the origin is `TRANSCRIPT_SITE_URL`'s or already in `settings.json`; the check is made once, at connect. Its documents are read on its own origin only: a redirect elsewhere is refused unfollowed, a manifest its `corpus.json` names on another origin is not followed, and no document past 32 MB is read or kept. A record's page URL is fetched only when its host is its channel's video platform's own domain or a subdomain (`evilyoutube.com` and `youtube.com.evil.example` are not YouTube); a URL carrying a backslash, whitespace or a control character is refused unparsed, because Node and yt-dlp's Python read its host differently; and what reaches yt-dlp is the URL the check parsed, never the archive's own string. A remote-only channel whose archive was removed from settings is refused before its record is read. - **umtool: the Source chip connects an archive, and an article swept over one is cut from it.** The Source chip takes an archive's address, reads it and connects it through the editor; a connected archive is offered as the source of **Article from a question** and of a new article, first when this machine has no corpus. The chain of an article swept over an archive asks the editor for its windows with the archive named and each record's page URL, so the cited channels are registered remote-only and fetched; a manifest with no sweep naming an origin takes the archive as its QR origin. A Rumble window fails the step with every recording's size, nothing fetched, until **Fetch the whole recordings** (`umtool chain <article> <n> --allow-whole-recording`). `--stop-before-render` ends Draft everything before the voices, and its new `cut-windows` step fetches the drafted cut's windows, asking the editor only for those not on disk. The cue walk, the link check and a source's build identity read an archive under the same rules as the editor (its own origin, 32 MB), and a chain whose archive is no longer connected stops and says to connect it again. diff --git a/editor/e2e/local-media.spec.ts b/editor/e2e/local-media.spec.ts @@ -13,6 +13,11 @@ import { join } from "node:path"; import { resetData, testPaths, writeChannelConfig } from "./helpers"; const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nA synthetic library cue\n"; +// Short-form cue timings (mm:ss.mmm), what FFmpeg and hand-made subtitle files +// write: the prepared recording carries them through preview (both cues +// counted) and import (byte for byte). Its index is +// common/controller/buildIndexLocalRecording.test.ts. +const SHORT_VTT = "WEBVTT\n\n00:01.000 --> 00:03.000\nA short-form library cue\n\n01:02.500 --> 01:04.000\nA second short-form cue\n"; test("a Local Archive channel imports a library recording and a prepared one, playback left off", async ({ page }) => { await resetData("empty"); @@ -26,7 +31,7 @@ test("a Local Archive channel imports a library recording and a prepared one, pl })); await writeFile(join(library, "aaaaaaaaaaa.vtt"), VTT); await writeFile(join(library, "talk.mp4"), "synthetic mp4 talk"); - await writeFile(join(library, "talk.vtt"), VTT); + await writeFile(join(library, "talk.vtt"), SHORT_VTT); const before = (await readdir(library)).sort(); await page.goto("/channels/new"); @@ -44,6 +49,10 @@ test("a Local Archive channel imports a library recording and a prepared one, pl await expect(page.getByRole("status").filter({ hasText: "discovered" })).toHaveText( "2 discovered · 1 new · 0 occupied · 1 need review", ); + // Cues / notes: the short-form transcript's two cues are read, not "no usable cues". + const cuesOf = (media: string) => page.getByRole("row").filter({ has: page.getByLabel(`Import ${media}`) }).getByRole("cell").nth(3); + await expect(cuesOf("talk.mp4")).toHaveText(/^2(?!\d)/); + await expect(cuesOf("aaaaaaaaaaa.mp4")).toHaveText(/^1(?!\d)/); await page.getByLabel("Import aaaaaaaaaaa.mp4").check(); await page.getByRole("button", { name: "Prepare details for talk.mp4" }).click(); @@ -66,6 +75,8 @@ test("a Local Archive channel imports a library recording and a prepared one, pl const local = ids.find((id) => id.startsWith("local-"))!; expect((await readdir(join(data, local))).sort()).toEqual(["external-media.json", "metadata.info.json", "transcript.en.vtt"]); expect(JSON.parse(await readFile(join(data, local, "metadata.info.json"), "utf8")).title).toBe("A prepared talk"); + // The short-form transcript is imported byte for byte, never rewritten. + expect(await readFile(join(data, local, "transcript.en.vtt"), "utf8")).toBe(SHORT_VTT); // A local record's page names it a local recording, with no download card. await page.goto(`/channels/local-spec-library/videos/${local}`);