Archilyzer · Source

archilyzer

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

commit bbdf0f479d1eca39b1fff88d22d5f420f340af06
parent ed801b0685740dccd770ccd75fbc515731c19aeb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 11:56:55 -0500

lookouts: review should-fixes -- a kept quote is the transcript's own text, a run held by a render ends after ten minutes, notes are one reading per model

1. A quote is evidence: its words are counted after normalising (a run
   of dashes is no words), and what is stored is the transcript's own
   text for the located span (quoteSpan: the cues' tokens, case and
   punctuation, the cue break a space), never the model's string; the
   end is the cue the span ends in (lib/lookoutRead.test.ts, probe 2).
2. A failed grouping or merge call is counted (groupCallsFailed) and the
   run is partial, never done.
3. surfacedIdeas never throws on a damaged run file: an idea or moment
   that is not one is skipped, the moments kept are clean copies
   (probe 1); `get lookouts` answers.
4. `get lookout-run` shows the ideas `get lookouts` counts
   (surfacedIdeas) and says how many it left out (ideasNotSurfaced).
5. Render mode is waited out for at most ten minutes in all per run
   (LOOKOUT_RENDER_WAIT_MAX_MS): past it the run ends partial, stopped
   "render", "held for a render"; its notes are kept and the next run
   resumes (tested with a stub reader and a fake clock).
6. After the cap, a render or a failure, later recordings' notes are
   still loaded, so the grouping covers everything already read; no
   reading call past the cap.
7. A reading-notes write that fails (a channel renamed or deleted under
   the run) ends the run failed with why, the run recorded, what was
   written kept. The job registry has no multi-channel declaration (a
   job names one channelSlug; channelWriters matches on it), so rename
   and delete do not see a lookout run's channels: left, and said in the
   controller's header.
8. A damaged reading-notes.json is said by name in the log
   (damagedNotes counted), read again and written over.
9. Cancel is by the job's lookout id: a run of a lookout since removed
   from settings is still cancelled; no live job and no lookout is a 404.
10. reading-notes.json holds one reading per model, prompt version and
    chunk size (`{version: 2, readings: {key: notes}}`, at most four, the
    newest kept; a version-1 file reads as its one reading), so two
    lookouts on two models never write over each other.

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

Diffstat:
Mcommon/controller/lookoutRun.test.ts | 133++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/lookoutRun.ts | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Acommon/lib/lookoutRead.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/lookoutRead.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mcommon/lib/lookoutStore.test.ts | 18++++++++++++++++++
Mcommon/lib/lookoutStore.ts | 27+++++++++++++++++++--------
Mcommon/lib/readingNotes-server.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Meditor/CHANGELOG.md | 2+-
Meditor/app/api/ops/_lookouts.test.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/lookout-run/route.ts | 26++++++++++++++++++++------
10 files changed, 532 insertions(+), 74 deletions(-)

diff --git a/common/controller/lookoutRun.test.ts b/common/controller/lookoutRun.test.ts @@ -1,7 +1,7 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; -import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -35,7 +35,8 @@ const { sanitizeLookoutItem, sanitizeLookouts } = await import("../lib/lookoutSe const { sanitizeGeneration } = await import("../lib/generationSettings"); const { planLookout } = await import("./lookoutPlan"); const L = await import("./lookoutRun"); -const { readingNotesSidecar } = await import("../lib/readingNotes-server"); +const { readingNotesSidecar, loadReadingNotes, readingKeyOf } = await import("../lib/readingNotes-server"); +const { READING_PROMPT_VERSION, CHUNK_CHARS } = await import("../lib/lookoutRead"); const { readLookoutRun, lookoutVerdictsFile, listLookoutRunIds, ideaKey } = await import("../lib/lookoutStore"); const { ModelLogWriter, modelLogFilesIn, readModelLog, runWithModelLog } = await import("../lib/llm/callLog-server"); const { kindNeedsText, jobKindLabel } = await import("../jobs/jobKinds"); @@ -133,7 +134,9 @@ const opts = (signal: AbortSignal, extra: Partial<import("./lookoutRun").Lookout const lines: string[] = []; return { lines, o: { model: "stub-local:1b", until: UNTIL, signal, onLog: (l: string) => lines.push(l), ...extra } }; }; -const notesOf = (channel: string, dir: string) => readingNotesSidecar.load(path.join(paths.channelsDir, channel, "data", dir)); +const videoDir = (channel: string, dir: string) => path.join(paths.channelsDir, channel, "data", dir); +const notesOf = async (channel: string, dir: string, model = "stub-local:1b") => + (await loadReadingNotes(videoDir(channel, dir), { model, promptVersion: READING_PROMPT_VERSION, chunkChars: CHUNK_CHARS })).notes; async function clearNotes() { for (const [c, d] of [["alpha-news", "News0000001"], ["alpha-live", "Live0000001"], ["alpha-news", "News0000002"]] as const) { await readingNotesSidecar.remove(path.join(paths.channelsDir, c, "data", d)); @@ -266,17 +269,36 @@ test("cancelled before it starts: no call at all", async () => { assert.equal(run.stopped, "cancelled"); }); -test("another model's notes are stale: read again from the start", async () => { +test("two models keep two readings in one notes file: neither writes over the other", async () => { await clearNotes(); const s1 = stub(); await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: s1.ask, renderHeld: noRender }); + const total = s1.asked.filter((x) => x.phase === "reading").length; const s2 = stub(); const b = opts(new AbortController().signal, { model: "another-local:2b" }); const { run } = await L.runLookout(paths, ITEM, b.o, { ask: s2.ask, renderHeld: noRender }); - assert.equal(run.reading?.chunksReused, 0); - assert.equal(s2.asked.filter((x) => x.phase === "reading").length, s1.asked.filter((x) => x.phase === "reading").length); - assert.ok(b.lines.some((l) => /reading notes are stale/.test(l))); - assert.equal((await notesOf("alpha-news", "News0000001"))?.provenance.model, "another-local:2b"); + assert.equal(run.reading?.chunksReused, 0, "another model reads for itself"); + assert.equal(s2.asked.filter((x) => x.phase === "reading").length, total); + assert.equal((await notesOf("alpha-news", "News0000001", "another-local:2b"))?.provenance.model, "another-local:2b"); + assert.ok((await notesOf("alpha-news", "News0000001"))?.complete, "the first model's reading is still there"); + const file = JSON.parse(await readFile(readingNotesSidecar.path(videoDir("alpha-news", "News0000001")), "utf8")); + assert.deepEqual(Object.keys(file.readings).sort(), [readingKeyOf({ model: "another-local:2b", promptVersion: READING_PROMPT_VERSION, chunkChars: CHUNK_CHARS }), readingKeyOf({ model: "stub-local:1b", promptVersion: READING_PROMPT_VERSION, chunkChars: CHUNK_CHARS })].sort()); + // The first model again: nothing to read. + const s3 = stub(); + const again = await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: s3.ask, renderHeld: noRender }); + assert.equal(s3.asked.filter((x) => x.phase === "reading").length, 0); + assert.equal(again.run.reading?.chunksReused, total); +}); + +test("a damaged reading-notes.json is said by name, read again and written over", async () => { + await clearNotes(); + await writeFile(readingNotesSidecar.path(videoDir("alpha-news", "News0000002")), "{ not json"); + const s = stub(); + const { o, lines } = opts(new AbortController().signal); + const { run } = await L.runLookout(paths, ITEM, o, { ask: s.ask, renderHeld: noRender }); + assert.ok(lines.some((l) => /^alpha-news\/News0000002: its reading-notes\.json is damaged/.test(l)), lines.join("\n")); + assert.equal(run.dropped?.damagedNotes, 1); + assert.ok((await notesOf("alpha-news", "News0000002"))?.complete, "rebuilt"); }); test("render mode held: one wait line and no call until it is off", async () => { @@ -316,6 +338,101 @@ test("the per-run cap ends the run partial and groups what it read; the model fa assert.equal(out.run.reading?.chunksFailed, L.LOOKOUT_MAX_FAILED_IN_A_ROW); }); +test("a failed grouping call leaves the run partial, never done", async () => { + await clearNotes(); + const s = stub(); + let grouping = 0; + const { run } = await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { + ask: async (q) => { + if (q.phase === "grouping" && grouping++ === 0) throw new Error("stub: grouping failed once"); + return s.ask(q); + }, + renderHeld: noRender, + }); + assert.equal(run.status, "partial"); + assert.equal(run.reading?.groupCallsFailed, 1); + assert.match(run.note ?? "", /grouping call\(s\) failed/); +}); + +test("render mode is waited out for at most ten minutes in all, then the run ends partial, held for a render; the next run resumes", async () => { + await clearNotes(); + // A fake clock: every poll's sleep moves it on by what it was asked to wait. + let clock = Date.parse("2026-11-12T10:00:00Z"); + let reads = 0; + let held = false; + const s = stub(); + const { o, lines } = opts(new AbortController().signal); + const { run } = await L.runLookout(paths, ITEM, o, { + ask: async (q) => { + // Render mode goes on after two reading calls, and stays on. + if (q.phase === "reading" && ++reads === 2) held = true; + return s.ask(q); + }, + renderHeld: () => (held ? "umtool take p --id t, since 10:00" : null), + sleep: async (ms) => { + clock += ms; + }, + now: () => new Date(clock), + }); + assert.equal(reads, 2, "no call while it holds"); + assert.equal(run.status, "partial"); + assert.equal(run.stopped, "render"); + assert.match(run.note ?? "", /held for a render \(10 min waited\)/); + assert.equal(run.reading?.renderWaitSeconds, 600); + assert.equal(lines.filter((l) => /render mode holds the machine/.test(l)).length, 1); + assert.equal(run.reading?.chunksRead, 2, "what it read before the hold is kept"); + // The next run, with render mode off, reads only what is left. + const s2 = stub(); + const next = await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: s2.ask, renderHeld: noRender }); + assert.equal(next.run.reading?.chunksReused, 2); + assert.equal(next.run.status, "done"); +}); + +test("past the cap, recordings already read are still loaded and grouped; no reading call past it", async () => { + await clearNotes(); + // Read everything, then forget the first recording's notes only. + await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: stub().ask, renderHeld: noRender }); + const plan = await planLookout(paths, ITEM, { until: UNTIL }); + const first = plan.read[0]!; + await readingNotesSidecar.remove(videoDir(first.channel, first.video)); + const s = stub(); + const { run } = await L.runLookout(paths, ITEM, opts(new AbortController().signal, { maxCalls: 1 }).o, { ask: s.ask, renderHeld: noRender }); + assert.equal(s.asked.filter((x) => x.phase === "reading").length, 1); + assert.equal(run.stopped, "cap"); + const others = plan.read.slice(1).reduce((n, r) => n + r.chunks, 0); + assert.equal(run.reading?.chunksReused, others, "the later recordings' notes were loaded"); + assert.equal(run.reading?.items, others + 1, "and their moments grouped with the one chunk read"); + assert.equal(run.ideas.length, 1); +}); + +test("a reading-notes write that fails ends the run failed, with why, and keeps what was written", async () => { + await clearNotes(); + const plan = await planLookout(paths, ITEM, { until: UNTIL }); + const first = plan.read[0]!; + const dir = videoDir(first.channel, first.video); + const s = stub(); + let n = 0; + try { + const { run } = await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { + ask: async (q) => { + // The channel's directory goes read-only under the run after its first write. + if (++n === 2) await chmod(dir, 0o555); + return s.ask(q); + }, + renderHeld: noRender, + }); + assert.equal(run.status, "failed"); + assert.equal(run.stopped, "failed"); + assert.match(run.note ?? "", new RegExp(`${first.channel}/${first.video}: the reading notes could not be written`)); + assert.equal(run.reading?.chunksRead, 1); + assert.equal(s.asked.length, 2, "no call after the failed write"); + assert.equal((await readLookoutRun(paths, "example-week", run.runId))?.status, "failed", "the run is recorded"); + } finally { + await chmod(dir, 0o755); + } + assert.equal((await notesOf(first.channel, first.video))?.chunks.length, 1, "the chunk written before it stays"); +}); + test("a damaged verdicts.json is refused before anything is read", async () => { const file = lookoutVerdictsFile(paths, "example-week"); await mkdir(path.dirname(file), { recursive: true }); diff --git a/common/controller/lookoutRun.ts b/common/controller/lookoutRun.ts @@ -24,7 +24,15 @@ // The run is written whole once, when it ends however it ends // (lib/lookoutStore.ts writeLookoutRun): `done`, `partial` (cancelled, the // per-run call cap, a chunk that failed) or `failed` (the model kept failing). -// A cancelled run groups nothing: its notes are kept for the next run. +// A cancelled run groups nothing: its notes are kept for the next run. After +// the cap, a render held past LOOKOUT_RENDER_WAIT_MAX_MS ("held for a render": +// the wait holds the one-at-a-time draft:local queue) or a failure, the later +// recordings' notes are still LOADED, so what is already read is grouped, and +// no reading call is made past it. A failed grouping call leaves the run +// `partial`. A reading-notes write that fails (the channel renamed or deleted +// under the run) ends it `failed` with why, keeping what was written: the job +// record names ONE channel (the registry has no multi-channel declaration), +// so rename and delete do not see a lookout run's channels as busy. // // THE MACHINE: every model call goes through the generation route's ollama // config, whose fetch waits for the GPU (transcription first; gpuArbiter.ts) @@ -71,9 +79,10 @@ import { type RawIdea, } from "../lib/lookoutRead"; import { + loadReadingNotes, newReadingNotes, - readingNotesSidecar, sameReadingProvenance, + writeReadingNotes, withReadingChunk, type ReadingNotes, type ReadingProvenance, @@ -102,6 +111,8 @@ export const LOOKOUT_MIN_FREE_MB = 3072; export const LOOKOUT_MAX_FAILED_IN_A_ROW = 3; /** Render mode is looked at again this often while it holds. */ export const LOOKOUT_RENDER_POLL_MS = 15_000; +/** A run waits for render mode at most this long in all, then ends partial ("held for a render"). */ +export const LOOKOUT_RENDER_WAIT_MAX_MS = 10 * 60_000; export class LookoutRunRefusal extends Error {} @@ -122,6 +133,8 @@ export type LookoutRunDeps = { renderHeld?: () => string | null; sleep?: (ms: number, signal: AbortSignal) => Promise<void>; renderPollMs?: number; + /** The longest a run waits for render mode in all (default LOOKOUT_RENDER_WAIT_MAX_MS). */ + renderWaitMaxMs?: number; now?: () => Date; }; @@ -193,28 +206,44 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO let readCalls = 0; let groupCalls = 0; + let groupFailed = 0; let seconds = 0; let failedInRow = 0; let stopped: LookoutRun["stopped"]; + let failure: string | null = null; const dropped: Record<string, number> = {}; const count = (k: string, n = 1) => { if (n) dropped[k] = (dropped[k] ?? 0) + n; }; - const reading = { videos: plan.read.length, videosComplete: 0, chunks: 0, chunksRead: 0, chunksReused: 0, chunksFailed: 0, items: 0, readCalls: 0, groupCalls: 0 }; + const reading = { videos: plan.read.length, videosComplete: 0, chunks: 0, chunksRead: 0, chunksReused: 0, chunksFailed: 0, items: 0, readCalls: 0, groupCalls: 0, groupCallsFailed: 0, renderWaitSeconds: 0 }; const sleep = deps.sleep ?? abortableSleep; const renderHeld = deps.renderHeld ?? renderModeHeld; + const renderWaitMax = deps.renderWaitMaxMs ?? LOOKOUT_RENDER_WAIT_MAX_MS; const progressTotal = Math.max(1, plan.estimate.readCalls); + let renderWaited = 0; - // Before every call: not cancelled; render mode, waited out with one line. + // Before every call: not cancelled; render mode waited out with one line — + // at most LOOKOUT_RENDER_WAIT_MAX_MS in all for the run, since the wait + // holds the one-at-a-time draft:local queue. Past it the run ends partial, + // "held for a render"; its notes are kept and the next run resumes. const mayCall = async (): Promise<boolean> => { - if (signal.aborted) return false; + if (signal.aborted || stopped === "render") return false; let why = renderHeld(); if (why) { onLog(`render mode holds the machine (${why}) — waiting before the next model call`); + const t0 = now().getTime(); + const waited = () => renderWaited + (now().getTime() - t0); while (why && !signal.aborted) { - await sleep(deps.renderPollMs ?? LOOKOUT_RENDER_POLL_MS, signal); + if (waited() >= renderWaitMax) { + renderWaited = waited(); + stopped = "render"; + onLog(`held for a render for ${Math.round(renderWaited / 60_000)} min — the run ends here; the next run resumes from the notes`); + return false; + } + await sleep(Math.min(deps.renderPollMs ?? LOOKOUT_RENDER_POLL_MS, Math.max(1, renderWaitMax - waited())), signal); why = renderHeld(); } + renderWaited = waited(); if (!signal.aborted) onLog("render mode is off — reading again"); } return !signal.aborted; @@ -232,15 +261,21 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO if (signal.aborted) return null; failedInRow++; onLog(`${label}: the model call failed — ${(err as Error).message}`); - if (failedInRow >= LOOKOUT_MAX_FAILED_IN_A_ROW) stopped = "failed"; + if (failedInRow >= LOOKOUT_MAX_FAILED_IN_A_ROW) { + stopped = "failed"; + failure ??= `the model failed ${LOOKOUT_MAX_FAILED_IN_A_ROW} times in a row`; + } return null; } }; // ─── Stage 3: read ─── + // Every recording's notes are LOADED, even after the run has stopped reading + // (the cap, a render, a failure): what is already read is grouped. Only a + // cancel stops the loop. const notesOf = new Map<string, ReadingNotes>(); for (const r of plan.read) { - if (stopped || signal.aborted) break; + if (signal.aborted) break; const key = `${r.channel}/${r.video}`; const dir = path.join(paths.channelsDir, r.channel, "data", r.video); const cued = await readCues(dir); @@ -253,21 +288,27 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO if (chunks.length !== r.chunks) onLog(`${key}: ${chunks.length} chunk(s) now, ${r.chunks} when planned (its transcript changed)`); reading.chunks += chunks.length; const prov: ReadingProvenance = { model, promptVersion: READING_PROMPT_VERSION, chunkChars: CHUNK_CHARS, cues: { size: cued.size, mtimeMs: cued.mtimeMs } }; - const had = await readingNotesSidecar.load(dir); + const loaded = await loadReadingNotes(dir, prov); + if (loaded.state === "damaged") { + onLog(`${key}: its reading-notes.json is damaged — what is whole in it is kept, this model's reading is read again and written over`); + count("damagedNotes"); + } + const had = loaded.notes; let notes: ReadingNotes; if (had && had.chunkCount === chunks.length && sameReadingProvenance(had.provenance, prov)) { notes = had; reading.chunksReused += had.chunks.length; - if (had.chunks.length && !had.complete) onLog(`${key}: resuming its reading notes at ${had.chunks.length} of ${chunks.length} chunk(s)`); + if (had.chunks.length && !had.complete && !stopped) onLog(`${key}: resuming its reading notes at ${had.chunks.length} of ${chunks.length} chunk(s)`); } else { - if (had) onLog(`${key}: its reading notes are stale (another model, prompt or transcript) — read again`); + if (had) onLog(`${key}: its reading notes are stale (another transcript) — read again`); notes = newReadingNotes(prov, chunks.length, now()); } - notesOf.set(key, notes); + if (notes.chunks.length) notesOf.set(key, notes); if (notes.complete) { reading.videosComplete++; continue; } + if (stopped) continue; const done = new Set(notes.chunks.map((c) => c.index)); for (let i = 0; i < chunks.length; i++) { if (done.has(i)) continue; @@ -294,10 +335,20 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO ]; if (fates.length) slot.decide(checked.chunk.items.length ? "kept" : "dropped", `${checked.chunk.items.length} of ${fates.length} item(s) kept`, fates); else slot.decide("n/a", "nothing in this part"); - notes = withReadingChunk(notes, checked.chunk, now()); + const next = withReadingChunk(notes, checked.chunk, now()); + // After every call: a run stopped anywhere keeps what it read. A write + // that fails (the channel renamed or deleted under the run) ends the run + // failed, with why, and what was written before it stays. + try { + await writeReadingNotes(dir, next); + } catch (err) { + stopped = "failed"; + failure = `${key}: the reading notes could not be written — ${(err as Error).message}`; + onLog(failure); + break; + } + notes = next; notesOf.set(key, notes); - // After every call: a run stopped anywhere keeps what it read. - await readingNotesSidecar.write(dir, notes); reading.chunksRead++; } if (notes.complete) reading.videosComplete++; @@ -321,7 +372,7 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO if (stopped === "cancelled") { onLog("cancelled — the reading notes so far are kept; the next run continues from them"); } else if (stopped === "failed") { - onLog(`the model failed ${LOOKOUT_MAX_FAILED_IN_A_ROW} times in a row — nothing grouped`); + onLog(`${failure ?? "the run failed"} — nothing grouped`); } else if (items.size < 2) { onLog(`${items.size} located moment(s): too few for a story — nothing to group`); } else { @@ -335,7 +386,10 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO const batch = batches[b]!; const answer = await call("grouping", `group ${b + 1}/${batches.length}`, GROUP_SYSTEM, groupPrompt(batch, { prompt: item.prompt, from: plan.window.from, to: plan.window.to }), GROUP_SCHEMA, slot); groupCalls++; - if (answer === null) continue; + if (answer === null) { + if (!signal.aborted) groupFailed++; + continue; + } const got = ideasOf(answer); slot.decide(got.length ? "kept" : "n/a", `${got.length} candidate idea(s)`); for (const idea of got) { @@ -355,6 +409,8 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO const m = applyMerges(candidates, answer); slot.decide(m.merged ? "kept" : "n/a", `${m.merged} merge(s)`); raw = m.ideas; + } else if (!signal.aborted) { + groupFailed++; } } if (signal.aborted) stopped = "cancelled"; @@ -369,8 +425,23 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO count("idea:sameStory", checked.dropped.sameStory); reading.readCalls = readCalls; reading.groupCalls = groupCalls; + reading.groupCallsFailed = groupFailed; + reading.renderWaitSeconds = Math.round(renderWaited / 1000); - const status: LookoutRun["status"] = stopped === "failed" ? "failed" : stopped || reading.chunksFailed ? "partial" : "done"; + // A failed reading or grouping call leaves the run partial, never done. + const status: LookoutRun["status"] = stopped === "failed" ? "failed" : stopped || reading.chunksFailed || groupFailed ? "partial" : "done"; + const note = + stopped === "cap" + ? `stopped at the per-run cap of ${maxCalls} reading calls; the next run continues from the notes` + : stopped === "cancelled" + ? "cancelled; the next run continues from the reading notes" + : stopped === "render" + ? `held for a render (${Math.round(renderWaited / 60_000)} min waited); the next run continues from the reading notes` + : stopped === "failed" + ? (failure ?? "failed") + : groupFailed + ? `${groupFailed} grouping call(s) failed: the ideas are from the rest` + : null; const run: LookoutRun = { version: 1, lookoutId: item.id, @@ -387,8 +458,7 @@ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunO dropped, ...(stopped ? { stopped } : {}), reading, - ...(stopped === "cap" ? { note: `stopped at the per-run cap of ${maxCalls} reading calls; the next run continues from the notes` } : {}), - ...(stopped === "cancelled" ? { note: "cancelled; the next run continues from the reading notes" } : {}), + ...(note ? { note } : {}), }; const file = await writeLookoutRun(paths, run); onLog( diff --git a/common/lib/lookoutRead.test.ts b/common/lib/lookoutRead.test.ts @@ -0,0 +1,46 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { checkReading, quoteSpan } from "./lookoutRead"; +import type { Cue } from "./vtt"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutRead.test.ts +// +// A quote is evidence: what a reading keeps is the TRANSCRIPT's text for the +// words the model pointed at, byte for byte as the cues say it, and its words +// are counted after normalising — punctuation is no word (lane/lookout slice 2 +// review, probe 2). + +const chunk: [number, string][] = [ + [10, "I never said that he was lying about the money!"], + [20, "And that is the truth, folks."], +]; +const cues: Cue[] = [ + { start: 10.4, end: 15.2, text: chunk[0]![1] }, + { start: 20, end: 25.5, text: chunk[1]![1] }, +]; +const read = (quote: string) => checkReading({ covers: "x", items: [{ kind: "claim", quote, why: "w", voice: "own", people: [] }] }, chunk, cues, 0); + +test("punctuation is no word: a quote of dashes and one word is too short", () => { + const r = read("- - - - - - lying"); + assert.deepEqual(r.chunk.items, []); + assert.deepEqual(r.dropped.map((d) => d.reason), ["too-short"]); +}); + +test("the stored quote is the transcript's text, never the model's case or punctuation", () => { + const r = read("he was LYING about the money!!! And that"); + assert.equal(r.chunk.items.length, 1); + const [it] = r.chunk.items; + assert.equal(it!.quote, "he was lying about the money! And that", "the cues' own words, across the cue break"); + assert.equal(it!.start, 10); + assert.equal(it!.end, 25.5, "the end of the cue it ends in"); +}); + +test("a quote within one cue keeps that cue's words; a paraphrase or a skipped word is not found", () => { + assert.equal(read("I never said that he was lying")!.chunk.items[0]!.quote, "I never said that he was lying"); + assert.equal(read("I never said that he was lying")!.chunk.items[0]!.end, 15.2); + assert.equal(read("said that he was lying about the money and that is the truth")!.chunk.items[0]!.quote, "said that he was lying about the money! And that is the truth,"); + assert.deepEqual(read("never said that he was lying about money").dropped.map((d) => d.reason), ["not-in-transcript"]); + assert.equal(quoteSpan("he was lying", [[0, "he was\tlying"]])?.text, "he was\tlying", "the cue's own spacing"); + assert.equal(quoteSpan("", chunk), null); +}); diff --git a/common/lib/lookoutRead.ts b/common/lib/lookoutRead.ts @@ -4,10 +4,13 @@ // // THE MODEL NEVER PUTS WORDS IN ANYONE'S MOUTH: // - stage 3 (read): every quote the model gives is LOCATED in the chunk it -// was shown (sweep-pipeline's `locate`, the words verbatim and contiguous -// after normalising case and punctuation); one that is not there — a -// paraphrase — is dropped and counted. Start and end come from the cues, -// never from the model. +// was shown (its words verbatim and contiguous after normalising case and +// punctuation, sweep-pipeline's `norm`, as its `locate` matches); one that +// is not there — a paraphrase — is dropped and counted. What is STORED is +// the transcript's own text for the located span, byte for byte as the +// cues say it, never the model's string; its words are counted after +// normalising, so punctuation is no word. Start and end come from the +// cues, never from the model. // - stage 4 (group): the model sees the located items as numbered lines and // answers with item ids only; // - stage 5 (check): an idea keeps only ids that exist (an invented one is @@ -19,7 +22,7 @@ // digest) can share one notes file per video; a lookout's own prompt steers // only the grouping. -import { CHUNK_CHARS, MAX_QUOTE_WORDS, MIN_QUOTE_WORDS, locate, norm } from "./report/draft/tasks/sweep-pipeline"; +import { CHUNK_CHARS, MAX_QUOTE_WORDS, MIN_QUOTE_WORDS, norm } from "./report/draft/tasks/sweep-pipeline"; import { momentHref } from "./report/draft/tasks/links"; import { platformMomentUrl } from "./momentUrl"; import type { Platform } from "./platform"; @@ -103,22 +106,56 @@ export type ReadDropReason = "not-in-transcript" | "too-short" | "too-long" | "n const words = (s: string) => s.trim().split(/\s+/).filter(Boolean); const str = (v: unknown, max = 400) => (typeof v === "string" ? v.trim().slice(0, max) : ""); +/** A text's words after normalising (case, punctuation): what the quote limits count. */ +const normWords = (s: string) => norm(s).split(" ").filter(Boolean); -// The end of the cue the quote ends in: cues from the one the quote starts in -// until their joined text holds the quote. -function endOf(quote: string, start: number, cues: readonly Cue[]): number { - const q = norm(quote); - let i = cues.findIndex((c) => Math.floor(c.start) === start && c.text.trim()); - if (i < 0) i = cues.findIndex((c) => c.start >= start); - if (i < 0) return start; - let text = ""; - for (let j = i; j < cues.length && j < i + 60; j++) { - const n = norm(cues[j]!.text); - if (!n) continue; - text = text ? `${text} ${n}` : n; - if (` ${text} `.includes(` ${q} `)) return Math.round(cues[j]!.end * 100) / 100; +/** Where a quote is in a chunk: its first and last line, and the TRANSCRIPT's text for it. */ +export type QuoteSpan = { startLine: number; endLine: number; text: string }; + +/** + * The quote found in the chunk, word for word after normalising — and the + * transcript's own text for those words: from the first word's token in its + * line to the last word's token in its line, the lines between whole, joined + * by a space (the cue break). A token is the transcript's, whole (its + * punctuation and case kept). Null when the words are not there, contiguous. + */ +export function quoteSpan(quote: string, chunk: readonly [number, string][]): QuoteSpan | null { + const q = normWords(quote); + if (!q.length) return null; + const toks: { w: string; line: number; from: number; to: number }[] = []; + chunk.forEach(([, text], line) => { + for (const m of text.matchAll(/\S+/g)) { + for (const w of normWords(m[0])) toks.push({ w, line, from: m.index!, to: m.index! + m[0].length }); + } + }); + outer: for (let i = 0; i + q.length <= toks.length; i++) { + for (let k = 0; k < q.length; k++) if (toks[i + k]!.w !== q[k]) continue outer; + const a = toks[i]!; + const b = toks[i + q.length - 1]!; + const parts: string[] = []; + for (let l = a.line; l <= b.line; l++) { + const t = chunk[l]![1]; + parts.push(t.slice(l === a.line ? a.from : 0, l === b.line ? b.to : t.length)); + } + return { startLine: a.line, endLine: b.line, text: parts.join(" ") }; } - return Math.round((cues[i]!.end ?? start) * 100) / 100; + return null; +} + +// Each chunk line's cue end: the cue at that whole second with that text, +// found in order (a chunk's lines are cueLines of the cues, in order). +function lineEnds(chunk: readonly [number, string][], cues: readonly Cue[]): number[] { + let p = 0; + return chunk.map(([sec, text]) => { + for (let j = p; j < cues.length; j++) { + const c = cues[j]!; + if (Math.floor(c.start) === sec && c.text.trim() === text) { + p = j + 1; + return Math.round(c.end * 100) / 100; + } + } + return sec; + }); } /** @@ -138,6 +175,7 @@ export function checkReading( const items: ReadingItem[] = []; const dropped: { quote: string; reason: ReadDropReason }[] = []; const seen = new Set<string>(); + let ends: number[] | null = null; for (const raw of rawItems) { const r = (raw && typeof raw === "object" ? raw : null) as Record<string, unknown> | null; const quote = r ? str(r.quote, 2000) : ""; @@ -153,7 +191,7 @@ export function checkReading( dropped.push({ quote, reason: "not-a-kind" }); continue; } - const n = words(quote).length; + const n = normWords(quote).length; if (n < MIN_QUOTE_WORDS) { dropped.push({ quote, reason: "too-short" }); continue; @@ -162,23 +200,26 @@ export function checkReading( dropped.push({ quote, reason: "too-long" }); continue; } - const start = locate(quote, chunk); - if (start === null) { + const span = quoteSpan(quote, chunk); + if (span === null) { dropped.push({ quote, reason: "not-in-transcript" }); continue; } - const key = `${start}\n${norm(quote)}`; + const start = chunk[span.startLine]![0]; + const key = `${start}\n${norm(span.text)}`; if (seen.has(key)) { dropped.push({ quote, reason: "repeated" }); continue; } seen.add(key); + ends ??= lineEnds(chunk, cues); const voice = (READING_VOICES as readonly string[]).includes(str(r.voice)) ? (str(r.voice) as ReadingVoice) : "unsure"; items.push({ kind: str(r.kind), - quote, + // The transcript's words, never the model's string. + quote: span.text, start, - end: endOf(quote, start, cues), + end: ends[span.endLine]!, why: str(r.why), voice, people: Array.isArray(r.people) ? r.people.map((p) => str(p, 80)).filter(Boolean).slice(0, 8) : [], diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts @@ -198,3 +198,21 @@ test("no citation, no key: a moment-less idea has none, and a stored one is not await rm(p.transcriptsDir, { recursive: true, force: true }); } }); + +test("a damaged run file never throws: a moment or idea that is not one is skipped, and the readout still answers", async () => { + const good = [M("a", "v", 10), M("a", "w", 20)]; + const k = K(good); + const ideaOf = (moments: unknown[]) => ({ ...idea(good), key: k, moments }) as unknown as LookoutIdea; + const clean = surfacedIdeas({ ideas: [ideaOf(good), ideaOf([null, ...good]), ideaOf(["x"]), null as never, "y" as never] }); + assert.equal(clean.length, 2, "the idea and the one whose null moment is skipped"); + assert.ok(clean.every((i) => i.moments.length === 2 && i.moments.every((m) => typeof m === "object" && m !== null))); + const p = await corpus(); + try { + await writeLookoutRun(p, run("20261111T120000Z-eeee", [ideaOf([null, ...good]), ideaOf([7])])); + const r = await lookoutReadout(p, "weekly"); + assert.equal(r.lastRun?.ideas, 1); + assert.equal(r.unruled, 1); + } finally { + await rm(p.transcriptsDir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/lookoutStore.ts b/common/lib/lookoutStore.ts @@ -130,14 +130,23 @@ export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video /** * The ideas of a stored run that are findings: each cites at least one moment - * and carries the key its moments give. A hand-edited or older run's idea - * with no moment, or a key that is not its moments', is left out — never - * shown, counted or ruled. + * and carries the key its moments give. A damaged run file never throws here: + * an idea that is not an object is skipped, a moment that is not one (no + * channel, video or start) is dropped from its idea, and an idea left with no + * moment, or whose key is not its remaining moments', is left out — never + * shown, counted or ruled. What comes back is clean copies. */ export function surfacedIdeas(run: Pick<LookoutRun, "ideas">): LookoutIdea[] { - return run.ideas.filter( - (i) => isObject(i) && Array.isArray(i.moments) && i.moments.length > 0 && isIdeaKey(i.key) && ideaKey(i.moments) === i.key, - ); + const out: LookoutIdea[] = []; + for (const i of Array.isArray(run?.ideas) ? (run.ideas as unknown[]) : []) { + if (!isObject(i) || !Array.isArray(i.moments) || !isIdeaKey(i.key)) continue; + const moments = (i.moments as unknown[]).filter( + (m): m is LookoutMoment => isObject(m) && typeof m.channel === "string" && typeof m.video === "string" && typeof m.start === "number" && Number.isFinite(m.start), + ); + if (moments.length === 0 || ideaKey(moments) !== i.key) continue; + out.push({ ...(i as unknown as LookoutIdea), moments }); + } + return out; } // ─── Runs ─── @@ -166,8 +175,8 @@ export type LookoutRun = { ideas: LookoutIdea[]; /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */ dropped?: Record<string, number>; - /** Why a run that is not `done` stopped: cancelled, the per-run call cap, or the model failing. */ - stopped?: "cancelled" | "cap" | "failed"; + /** Why a run that is not `done` stopped: cancelled, the per-run call cap, held for a render past its wait, or a failure (the model, a notes write). */ + stopped?: "cancelled" | "cap" | "failed" | "render"; /** What the reading stage did: recordings and chunks read now, reused from fresh notes, failed. */ reading?: { videos: number; @@ -179,6 +188,8 @@ export type LookoutRun = { items: number; readCalls: number; groupCalls: number; + groupCallsFailed?: number; + renderWaitSeconds?: number; }; note?: string; }; diff --git a/common/lib/readingNotes-server.ts b/common/lib/readingNotes-server.ts @@ -8,11 +8,15 @@ // again while its notes are fresh. // // BESIDE THE CUES because it is derived from them and must go stale with them. -// FRESH iff its provenance is today's: the same model, the same reading -// prompt (`promptVersion`), the same chunk size, and the same cues file (size -// and mtime) — the digest's rule. A stale or unreadable file is read again -// from the start and written over: it is a cache of model calls, never the -// operator's data. +// ONE READING PER MODEL, in one file: `{ version: 2, readings: { "<model>|p<prompt +// version>|c<chunk chars>": notes } }`, so two lookouts on two models share +// the file without writing over each other's reading on every run (at most +// READING_NOTES_MAX_READINGS kept, the most recently written). A reading is +// FRESH iff its provenance is today's: that key and the same cues file (size +// and mtime) — the digest's rule. A stale reading is read again from the start +// and replaces its key; a damaged file (not JSON, not notes) is said by name in +// the run's log, read again and written over: it is a cache of model calls, +// never the operator's data. // // RESUMABLE: the notes are written after every chunk, with the chunks read so // far and `complete: false`; a cancelled or interrupted run leaves them so, @@ -25,10 +29,16 @@ // // SERVER-ONLY. +import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; import { sidecar, sidecarField } from "./sidecar-server"; export const READING_NOTES_FILENAME = "reading-notes.json"; +/** One reading's shape. */ export const READING_NOTES_VERSION = 1; +/** The file's shape: a reading per model (and prompt and chunk size). */ +export const READING_NOTES_FILE_VERSION = 2; +/** Readings kept in one file, the most recently written first. */ +export const READING_NOTES_MAX_READINGS = 4; export const READING_VOICES = ["own", "reading", "clip", "unsure"] as const; export type ReadingVoice = (typeof READING_VOICES)[number]; @@ -135,7 +145,74 @@ export function coerceReadingNotes(value: unknown): ReadingNotes | null { }; } -export const readingNotesSidecar = sidecar(READING_NOTES_FILENAME, sidecarField(coerceReadingNotes), { indent: 2 }); +export type ReadingNotesFile = { version: number; readings: Record<string, ReadingNotes> }; + +/** The key a reading is kept under: its model, prompt version and chunk size. */ +export function readingKeyOf(p: Pick<ReadingProvenance, "model" | "promptVersion" | "chunkChars">): string { + return `${p.model}|p${p.promptVersion}|c${p.chunkChars}`; +} + +/** + * A notes file coerced: `{file, damaged}` — every reading that is one, and + * whether anything in it was not (the whole file, or one reading). A version-1 + * file (one reading, slice 2's first form) is a file of that one reading. + */ +export function coerceReadingNotesFile(value: unknown): { file: ReadingNotesFile; damaged: boolean } { + const file: ReadingNotesFile = { version: READING_NOTES_FILE_VERSION, readings: {} }; + if (isObj(value) && value.version === READING_NOTES_VERSION) { + const one = coerceReadingNotes(value); + if (!one) return { file, damaged: true }; + file.readings[readingKeyOf(one.provenance)] = one; + return { file, damaged: false }; + } + if (!isObj(value) || value.version !== READING_NOTES_FILE_VERSION || !isObj(value.readings)) return { file, damaged: true }; + let damaged = false; + for (const [key, raw] of Object.entries(value.readings)) { + const notes = coerceReadingNotes(raw); + if (!notes || readingKeyOf(notes.provenance) !== key) { + damaged = true; + continue; + } + file.readings[key] = notes; + } + return { file, damaged }; +} + +// Declared for the per-video sidecar registry (its name, its removal); the +// run reads and writes through loadReadingNotes / writeReadingNotes. +export const readingNotesSidecar = sidecar(READING_NOTES_FILENAME, sidecarField((v) => coerceReadingNotesFile(v).file), { indent: 2 }); + +export type LoadedReadingNotes = { + /** The reading under this provenance's key, or null (none yet, or none whole). */ + notes: ReadingNotes | null; + /** "absent": no file; "damaged": a file that is not JSON or holds what is not notes. */ + state: "absent" | "damaged" | "ok"; +}; + +/** This model's reading of a video (any freshness: the caller compares the provenance). */ +export async function loadReadingNotes(videoDir: string, key: Pick<ReadingProvenance, "model" | "promptVersion" | "chunkChars">): Promise<LoadedReadingNotes> { + const read = await readJsonFile(readingNotesSidecar.path(videoDir)); + if (!read.ok) return { notes: null, state: read.reason === "absent" ? "absent" : "damaged" }; + const { file, damaged } = coerceReadingNotesFile(read.value); + return { notes: file.readings[readingKeyOf(key)] ?? null, state: damaged ? "damaged" : "ok" }; +} + +/** + * THE writer: this reading put under its key, the file's other readings kept + * (what of them is whole; a damaged file is written over), at most + * READING_NOTES_MAX_READINGS, the most recently written kept. Atomic. + */ +export async function writeReadingNotes(videoDir: string, notes: ReadingNotes): Promise<void> { + const at = readingNotesSidecar.path(videoDir); + const read = await readJsonFile(at); + const file = read.ok ? coerceReadingNotesFile(read.value).file : { version: READING_NOTES_FILE_VERSION, readings: {} }; + const key = readingKeyOf(notes.provenance); + const others = Object.entries(file.readings) + .filter(([k]) => k !== key) + .sort((a, b) => (a[1].updatedAt < b[1].updatedAt ? 1 : a[1].updatedAt > b[1].updatedAt ? -1 : 0)) + .slice(0, READING_NOTES_MAX_READINGS - 1); + await writeJsonAtomic(at, { version: READING_NOTES_FILE_VERSION, readings: { [key]: notes, ...Object.fromEntries(others) } }, { indent: 2 }); +} export function sameReadingProvenance(a: ReadingProvenance, b: ReadingProvenance): boolean { return ( diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,7 +2,7 @@ ## [Unreleased] - **A lookout run can be cancelled by the lookout's name, and its last run read whole.** `pnpm ops lookout-run --json '{"id":"…","cancel":true}'` cancels that lookout's queued or running run (the reading notes it wrote are kept, so the next run picks up from them), and `pnpm ops get lookout-run <id> [--run <runId>]` shows the latest run, or the one named: its window, what it read, the calls and seconds, how much was read now or reused, the ideas, and what was dropped and why — with the run of that lookout running now, if any. `--wait` on a run prints its result line. -- **Lookouts run: the local model reads what the dry run lists and answers with video ideas, and a stopped run continues where it stopped.** `pnpm ops lookout-run --json '{"id":"…"}'` (no `dryRun`) is a `lookout-run` job on the local model's queue: it makes the same list the dry run shows at its turn and reads exactly that, one call per transcript chunk. What the model finds is kept in a private `reading-notes.json` beside each video's transcript, written after every call, so a cancelled or interrupted run's next start reads only what is left, and a week already read is not read again. Every quote is found word for word in the transcript by code, or dropped; the notes are grouped into ideas of at least two dated moments, with an idea that cites an invented moment, only one, or none dropped and counted; a moment the model thinks is read aloud or a played clip becomes a caveat to check by ear. The calls wait for transcription and for render mode, are in the job's Model log, and the model is unloaded at the end; the run does not start under 3 GB of free memory, nor while lookouts are off (`settings.lookouts.enabled`, off by default). It runs on the local model only for now (a new `lookout` task in `settings.generation.routes`: local in the balanced and local presets). The run, its ideas and what was dropped are written to `transcripts/.lookouts/<id>/runs/`, never published. +- **Lookouts run: the local model reads what the dry run lists and answers with video ideas, and a stopped run continues where it stopped.** `pnpm ops lookout-run --json '{"id":"…"}'` (no `dryRun`) is a `lookout-run` job on the local model's queue: it makes the same list the dry run shows at its turn and reads exactly that, one call per transcript chunk. What the model finds is kept in a private `reading-notes.json` beside each video's transcript (one reading per model, so two lookouts on two models never write over each other), written after every call, so a cancelled or interrupted run's next start reads only what is left, and a week already read is not read again. Every quote is found word for word in the transcript by code, or dropped, and what is kept is the transcript's own text for those words, never the model's; the notes are grouped into ideas of at least two dated moments, with an idea that cites an invented moment, only one, or none dropped and counted; a moment the model thinks is read aloud or a played clip becomes a caveat to check by ear. The calls wait for transcription and for render mode (at most ten minutes in all for a run; then it ends partial, "held for a render", and the next run picks up), are in the job's Model log, and the model is unloaded at the end; the run does not start under 3 GB of free memory, nor while lookouts are off (`settings.lookouts.enabled`, off by default). It runs on the local model only for now (a new `lookout` task in `settings.generation.routes`: local in the balanced and local presets). The run, its ideas and what was dropped are written to `transcripts/.lookouts/<id>/runs/`, never published. - **A local sweep's topic labels and section headings never attribute, a refresh keeps the local sweep's settings, and a revision keeps a speaker-neutral report neutral.** A heading the model wrote was kept unless it held one of a few words, and was never checked against the quotes, so a section could be headed "Main Actress's Comments" over quotes none of them hers, or "Fan Reactions"; a label could still say "acolyte writer blames filon" or "his love of the show" when the quote held those words. A label and a heading are now noun-phrase topics, read word by word against closed lists: no personal or possessive pronoun, no word of saying, thinking, feeling or judging in any of its forms (comments, reaction, response, statement, accusation, criticism, blames, hates, loves, admission, lying, defending, …), no "is / was / has / been" or contracted verb, no person-role in the possessive ("the showrunner's …"), no host's name — and every word found in the section's quotes, labels or titles, or the question. A heading that fails is written by code from its quotes' labels; the question's topic, the fallback label and the report's title, goes through the same rules. A recurring **refresh** of a report on the local route swept the new recordings in the old drafted-sentence form with no read-aloud check; it now uses `generation.localSweep`. A **revision** of a speaker-neutral report keeps its lines code's (a line is not rewritten; an added finding's line is written again from its recording's title and date and its checked topic), refuses a heading, a title or a summary that attributes, and keeps each claim's `check by ear` flag, which it used to lose. In the drafted-sentence form, a quote marked to check by ear is meaning-checked last, so it no longer takes the place of an unmarked one in the check's budget. The read-aloud patterns run in linear time: one of them took over a second on 40 letters of transcript and never returned on 60. In the **Model log**, each of these is said on the call it came from: an extract's quote "dropped: read aloud: <cue>", "kept: … flagged: check by ear (read-aloud cue: …)" or "kept: … label refused: <reason> — the run's topic used"; the grouping's heading "rewritten: heading refused: <reason> — replaced by “…” (written by code)"; a refused topic on the terms call; each meaning check kept, rewritten, dropped or flagged; and a local revision's ops applied or refused with code's reason. - **A local model's sweep no longer says who said it: code writes each finding around the quote, and a quote that may be read aloud is marked to check by ear.** A sweep on the `local` route (a small model on this machine) wrote "Jeremy says …" over words the host was reading out — a tweet, a headline, a review — because nothing in an automatic transcript marks a quotation and a small model cannot tell the reading from the speaking. Its findings are now written by code as `In <recording's title> (<date>), on <topic>: "<quote>"`, with the citation and the link: the model only copies the quote and names its topic in a few words, and a topic that names the speaker, says who thinks what, or uses words found nowhere around the quote is replaced by the question's topic. The report's title is written the same way, and it says where the words are, not whose they are. Before a quote is kept, code also looks at the transcript around it for signs of reading aloud — a tweet, likes and retweets read out, an article or headline being introduced, "it says", "he writes", "according to", a clip, a chat message, the host named in the third person. Such a quote goes to a last section, **To check by ear**, its line starting `Check by ear:` and its claim carrying the flag `check by ear: may be read aloud`; it can be left out instead. The signs are patterns, so a headline read with nothing announcing it is not caught: the section is where to listen first, not a guarantee about the rest. Both are settings (`generation.localSweep.claimForm`: `neutral` or `sentence`, the earlier drafted sentence with its meaning check; `generation.localSweep.readAloud`: `flag`, `drop` or `off`), set with `archilyzer gen local-sweep [--form …] [--read-aloud …]` or on umtool's **Settings → Generation**. Sweeps by Claude (Claude Code or the API) are not changed. - **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. diff --git a/editor/app/api/ops/_lookouts.test.ts b/editor/app/api/ops/_lookouts.test.ts @@ -134,3 +134,67 @@ test("get lookout-run: the latest run whole, or the one named; cancel answers th assert.equal((await callPost(POST!, { id: "nope", cancel: true })).status, 404); assert.deepEqual(await corpus.listJobIds(), []); }); + +test("get lookout-run counts ideas as get lookouts does: a damaged idea is left out and counted", async () => { + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); + const { ideaKey } = await import("yt-dlp-transcript-common/lib/lookoutStore"); + const moments = [ + { channel: "example-news", video: "v1", date: "2026-11-10", start: 10, end: 14, quote: "q" }, + { channel: "example-news", video: "v2", date: "2026-11-11", start: 20, end: 24, quote: "q" }, + ]; + const key = ideaKey(moments)!; + const idea = { id: "idea-1", key, workingTitle: "t", angle: "", whyNow: "", kind: "claim", estimatedLengthSec: 8, confidence: "high", confidenceWhy: "", moments, caveats: [], sensitive: false }; + await writeLookoutRun({ transcriptsDir: corpus.transcripts }, { + version: 1, lookoutId: "example-week", runId: "20261112T120000Z-dddd", startedAt: "2026-11-12T12:00:00.000Z", endedAt: "2026-11-12T12:10:00.000Z", + status: "done", window: { from: "2026-11-10", to: "2026-11-12", days: 3, timeZone: "UTC" }, model: "stub-local:1b", + calls: 3, seconds: 9, selection: null, + ideas: [idea as never, { ...idea, id: "idea-2", moments: [null] } as never, { ...idea, id: "idea-3", moments: [null, ...moments] } as never], + }); + const r = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week"); + assert.equal(r.status, 200, JSON.stringify(r.body)); + const ideas = (r.body.run as { ideas: { id: string; moments: unknown[] }[] }).ideas; + assert.deepEqual(ideas.map((i) => i.id), ["idea-1", "idea-3"]); + assert.ok(ideas.every((i) => i.moments.length === 2)); + assert.equal(r.body.ideasNotSurfaced, 1); + const all = await callGet(GET!, "http://localhost/api/ops/lookouts?id=example-week"); + assert.equal(all.status, 200, JSON.stringify(all.body)); + assert.equal((all.body.lookouts as { lastRun: { ideas: number } }[])[0]!.lastRun.ideas, 2, "the same count"); +}); + +test("cancel is by the job's lookout id: a run of a lookout since removed from settings is still cancelled", async () => { + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); + await corpus.writeChannelConfig("example-news", {}); + const { enqueueLookoutRun } = await import("yt-dlp-transcript-common/controller/lookoutRun"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + const { sanitizeLookouts } = await import("yt-dlp-transcript-common/lib/lookoutSettings"); + const { sanitizeGeneration } = await import("yt-dlp-transcript-common/lib/generationSettings"); + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + // A run that never reaches a model: it waits at render mode until released. + const out = await enqueueLookoutRun( + { id: "example-week", until: "2026-11-05" }, + { + paths: getPaths(), + settings: () => ({ lookouts: sanitizeLookouts({ ...LOOKOUTS, enabled: true }), generation: sanitizeGeneration({ routes: { lookout: "local" }, models: { local: "stub-local:1b" } }) }) as never, + ask: () => async () => { + await gate; + throw new Error("stub: no model in this test"); + }, + memAvailableMb: async () => 8000, + renderHeld: () => null, + unload: async () => {}, + }, + ); + assert.ok(out.result.ok, JSON.stringify(out.result)); + if (!out.result.ok) return; + void out.result.stream.cancel(); + // The lookout is removed from settings while its run is live. + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { enabled: false, items: [] } }); + const c = await callPost(POST!, { id: "example-week", cancel: true }); + assert.equal(c.status, 200, JSON.stringify(c.body)); + assert.deepEqual(c.body.cancelled, [out.result.jobId]); + release(); + assert.equal((await out.result.done).status, "cancelled"); + // Nothing live and not in settings: a 404. + assert.equal((await callPost(POST!, { id: "example-week", cancel: true })).status, 404); +}); diff --git a/editor/app/api/ops/lookout-run/route.ts b/editor/app/api/ops/lookout-run/route.ts @@ -2,10 +2,10 @@ import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { isIsoDate } from "yt-dlp-transcript-common/lib/lookout"; -import { LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings"; +import { LOOKOUT_ID_RE, LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings"; import { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan"; import { LOOKOUT_MAX_CALLS, cancelLookoutRuns, enqueueLookoutRun, lookoutRunJobs } from "yt-dlp-transcript-common/controller/lookoutRun"; -import { LOOKOUT_RUN_ID_RE, listLookoutRunIds, readLookoutRun } from "yt-dlp-transcript-common/lib/lookoutStore"; +import { LOOKOUT_RUN_ID_RE, listLookoutRunIds, readLookoutRun, surfacedIdeas } from "yt-dlp-transcript-common/lib/lookoutStore"; import { OpsInputError, jobResponse, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib"; import { readRoute } from "../_read"; @@ -44,10 +44,15 @@ export const dynamic = "force-dynamic"; // lookout's queued or running run is cancelled (the reading notes it wrote // are kept; the next run continues from them). Nothing to cancel is `[]`. // -// GET ?id=<lookout>[&run=<runId>] -> { ok: true, run, running } — `pnpm ops +// A lookout removed from settings while its run was live is still cancelled by +// its id. +// +// GET ?id=<lookout>[&run=<runId>] -> { ok: true, run, ideasNotSurfaced, running } — `pnpm ops // get lookout-run <id> [--run R]`: the latest run (or the one named) whole — // window, the selection it read, calls, seconds, reading counts, ideas and -// what was dropped — or null before the first; and the lookout's run queued +// what was dropped — or null before the first; its ideas are the ones `get +// lookouts` counts (surfacedIdeas: a damaged idea left out, counted in +// `ideasNotSurfaced`); and the lookout's run queued // or running now ([{jobId, status}]). const MAX_CALLS = LOOKOUT_MAX_CALLS * 5; @@ -71,10 +76,14 @@ export async function POST(request: Request) { if (cancel && Object.keys(body).some((k) => k !== "id" && k !== "cancel")) throw new OpsInputError('"cancel" takes the lookout\'s "id" alone'); const lookouts = getSettings().lookouts; const item = lookoutById(lookouts, id); + // A cancel is by the job's recorded lookout id: a run of a lookout since + // removed from settings is still cancelled by its id. + if (cancel && LOOKOUT_ID_RE.test(id) && (item || lookoutRunJobs(id).length)) { + return NextResponse.json({ ok: true, cancelled: cancelLookoutRuns(id) }); + } if (!item) { return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404); } - if (cancel) return NextResponse.json({ ok: true, cancelled: cancelLookoutRuns(item.id) }); if (!dryRun) { const out = await enqueueLookoutRun({ id, days, maxVideos, until, model, maxCalls }, { paths: getPaths() }); if (!out.result.ok || !("model" in out)) return jobResponse(out.result); @@ -112,6 +121,11 @@ export async function GET(request: Request) { if (run) break; } } - return { run, running: lookoutRunJobs(id) }; + // Its ideas counted and shown as `get lookouts` counts them + // (surfacedIdeas): an idea with no whole moment, or whose key is not its + // moments', is not a finding; how many the file held beside them is said. + if (!run) return { run: null, running: lookoutRunJobs(id) }; + const ideas = surfacedIdeas(run); + return { run: { ...run, ideas }, ideasNotSurfaced: (Array.isArray(run.ideas) ? run.ideas.length : 0) - ideas.length, running: lookoutRunJobs(id) }; }); }