import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { chmod, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/lookoutRun.test.ts // // A lookout run (lane/lookout slice 2) over a fixture corpus with a STUB // model — no model, no ollama, no network: the plan's read list is what is // read; a paraphrase, an invented item id and a one-moment idea are dropped // and counted; a cancelled run continues where it stopped and re-reads nothing // already judged; no call is made with an aborted signal; render mode is // waited out with one line; the calls are in the model log. Every channel and // lookout here is invented. const ROOT = mkdtempSync(path.join(tmpdir(), "lookout-run-")); Object.assign(process.env, { TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), SETTINGS_FILE: path.join(ROOT, "settings.json"), SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), RENDER_PRIORITY_FILE: path.join(ROOT, "render.json"), GENERATION_USAGE_FILE: path.join(ROOT, ".generation", "usage.jsonl"), }); after(() => rmSync(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); const { sanitizeLookoutItem, sanitizeLookouts } = await import("../lib/lookoutSettings"); const { sanitizeGeneration } = await import("../lib/generationSettings"); const { planLookout } = await import("./lookoutPlan"); const L = await import("./lookoutRun"); 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"); const paths = getPaths(); const UNTIL = "2026-11-05"; const T = (iso: string) => Math.floor(Date.parse(iso) / 1000); // A cue's text: twelve words, unique to its video and line (no two videos // share text, so none is folded into another), a quote found in one place only. function lineText(video: string, i: number): string { let x = [...`${video}:${i}`].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619) >>> 0, 2166136261); const w: string[] = []; for (let k = 0; k < 9; k++) { x = (Math.imul(x, 1664525) + 1013904223) >>> 0; w.push(`w${(x >>> 12) % 50000}`); } return `in ${video} line${i} ${w.join(" ")}`; } async function video(channel: string, dir: string, o: { title: string; at: string; seconds: number; lines?: number }) { const d = path.join(paths.channelsDir, channel, "data", dir); await mkdir(d, { recursive: true }); const ts = T(o.at); const upload = new Date(ts * 1000).toISOString().slice(0, 10).replace(/-/g, ""); await writeFile( path.join(d, "metadata.info.json"), JSON.stringify({ id: dir, title: o.title, duration: o.seconds, live_status: "not_live", webpage_url: `https://www.youtube.com/watch?v=${dir}`, upload_date: upload, timestamp: ts }), ); if (o.lines === undefined) return; const step = o.seconds / o.lines; const cues = Array.from({ length: o.lines }, (_, i) => ({ start: Math.round(i * step), end: Math.round((i + 1) * step), text: lineText(dir, i) })); await writeFile( path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id: dir, title: o.title, uploadDate: upload, duration: o.seconds, platform: "youtube", webpageUrl: `https://www.youtube.com/watch?v=${dir}`, cues }), ); } async function channel(slug: string) { await mkdir(path.join(paths.channelsDir, slug, "data"), { recursive: true }); await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", url: `https://www.youtube.com/@${slug}` })); } await channel("alpha-news"); await channel("alpha-live"); // ~74 characters a line: 240 lines are three chunks of CHUNK_CHARS. await video("alpha-news", "News0000001", { title: "Monday News", at: "2026-11-03T15:00:00Z", seconds: 2400, lines: 240 }); await video("alpha-live", "Live0000001", { title: "Tuesday Live", at: "2026-11-04T23:00:00Z", seconds: 3600, lines: 240 }); await video("alpha-news", "News0000002", { title: "Wednesday Short Take", at: "2026-11-05T12:00:00Z", seconds: 600, lines: 60 }); // In the window, no transcript yet: listed, named, not read. await video("alpha-news", "NoCues00001", { title: "Not Transcribed Yet", at: "2026-11-05T13:00:00Z", seconds: 900 }); const ITEM = sanitizeLookoutItem({ id: "example-week", label: "Example week", channels: ["alpha-news", "alpha-live"], days: 3, timeZone: "UTC", prompt: "the operator's ask" })!; // ─── The stub model ─── type Asked = { phase: string; label: string; user: string; aborted: boolean }; // A reading answer: the chunk's first line copied verbatim, and a paraphrase // (never in the transcript). A grouping answer: one good story, one with an // invented id, one with a single moment, one with none, and a repeat. function stub(o: { failReading?: number; onCall?: (n: number) => void } = {}) { const asked: Asked[] = []; const ask: import("./lookoutRun").LookoutAsk = async (q) => { asked.push({ phase: q.phase, label: q.label, user: q.user, aborted: q.signal.aborted }); o.onCall?.(asked.length); if (q.phase === "reading") { if (o.failReading && asked.filter((a) => a.phase === "reading").length <= o.failReading) throw new Error("stub: the model is down"); const first = /\] (in \S+ line\d+ (?:w\d+ ?){9})/.exec(q.user)![1]!.trim(); return { covers: "a stretch of the show", items: [ { kind: "claim", quote: first, why: "a claim of his own", voice: "own", people: ["Someone"] }, { kind: "claim", quote: "he basically said that the whole thing matters a great deal now", why: "a paraphrase", voice: "own", people: [] }, ], }; } if (q.label === "merge the groups") return { merges: [] }; const ids = [...q.user.matchAll(/^(i\d+) \|/gm)].map((m) => m[1]!); return { ideas: [ { workingTitle: "The number story", angle: "a. b.", whyNow: "now", kind: "running-story", itemIds: [ids[0], ids[2], ids[4]], confidence: "high", confidenceWhy: "three days", caveats: ["check the number"], sensitive: false }, { workingTitle: "Invented", angle: "", whyNow: "", kind: "claim", itemIds: ["i999", ids[1]], confidence: "medium", confidenceWhy: "", caveats: [], sensitive: false }, { workingTitle: "One moment", angle: "", whyNow: "", kind: "claim", itemIds: [ids[3]], confidence: "low", confidenceWhy: "", caveats: [], sensitive: false }, { workingTitle: "No moment", angle: "", whyNow: "", kind: "claim", itemIds: [], confidence: "low", confidenceWhy: "", caveats: [], sensitive: false }, { workingTitle: "The same story again", angle: "", whyNow: "", kind: "claim", itemIds: [ids[4], ids[0], ids[2]], confidence: "low", confidenceWhy: "", caveats: [], sensitive: true }, ], }; }; return { ask, asked }; } const noRender = () => null; const opts = (signal: AbortSignal, extra: Partial = {}) => { const lines: string[] = []; return { lines, o: { model: "stub-local:1b", until: UNTIL, signal, onLog: (l: string) => lines.push(l), ...extra } }; }; 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)); } } test("the job kind reads text only, and the plan's read list is exactly what is read", async () => { assert.equal(kindNeedsText("lookout-run"), true); assert.equal(jobKindLabel("lookout-run"), "Lookout run"); await clearNotes(); const plan = await planLookout(paths, ITEM, { until: UNTIL }); assert.deepEqual(plan.read.map((r) => r.video).sort(), ["Live0000001", "News0000001", "News0000002"]); const { ask, asked } = stub(); const { o } = opts(new AbortController().signal); const { run } = await L.runLookout(paths, ITEM, o, { ask, renderHeld: noRender }); const reads = asked.filter((a) => a.phase === "reading"); // One reading call per chunk the plan counted, of the plan's videos and no other. assert.equal(reads.length, plan.estimate.readCalls); for (const r of plan.read) { assert.equal(reads.filter((a) => a.label.startsWith(`${r.channel}/${r.video} `)).length, r.chunks, r.video); } assert.equal(run.reading?.chunksRead, plan.estimate.readCalls); assert.equal(run.status, "done"); assert.equal(run.model, "stub-local:1b"); assert.equal(run.calls, reads.length + run.reading!.groupCalls); // The stored selection is the plan: the video with no transcript keeps its title and URL. const sel = run.selection as typeof plan; const bare = sel.skipped.find((s) => s.video === "NoCues00001")!; assert.equal(bare.reason, "no-transcript"); assert.equal(bare.title, "Not Transcribed Yet"); assert.equal(bare.url, "https://www.youtube.com/watch?v=NoCues00001"); }); test("a paraphrase, an invented item id, a one-moment idea and a moment-less one are dropped and counted; every quote is code's", async () => { await clearNotes(); const { ask } = stub(); const { o } = opts(new AbortController().signal); const { run, file } = await L.runLookout(paths, ITEM, o, { ask, renderHeld: noRender }); const reads = run.reading!.chunksRead; assert.equal(run.dropped?.["quote:not-in-transcript"], reads, "every paraphrase dropped"); assert.equal(run.reading?.items, reads, "one located item per chunk"); assert.equal(run.dropped?.["idea:inventedItemId"], 1); assert.equal(run.dropped?.["idea:oneMoment"], 2, "the one-moment idea, and the invented one left with one"); assert.equal(run.dropped?.["idea:noCitation"], 1); assert.equal(run.dropped?.["idea:sameStory"], 1); assert.equal(run.ideas.length, 1); const [idea] = run.ideas; assert.equal(idea!.workingTitle, "The number story"); assert.equal(idea!.moments.length, 3); assert.equal(idea!.key, ideaKey(idea!.moments)); for (const m of idea!.moments) { const cues = JSON.parse(await readFile(path.join(paths.channelsDir, m.channel, "data", m.video, "transcript.cues.json"), "utf8")).cues as { start: number; end: number; text: string }[]; const cue = cues.find((c) => c.text === m.quote); assert.ok(cue, `the quote is a cue's text, verbatim: ${m.quote}`); assert.equal(m.start, Math.floor(cue!.start)); assert.equal(m.end, cue!.end, "the end is the cue's"); assert.match(m.link!, /^https:\/\/www\.youtube\.com\/watch\?v=.*&t=\d+s$|^https:\/\/www\.youtube\.com\/watch\?v=[^&]+$/); } assert.ok(idea!.caveats.includes("check the number")); // Written whole, under the dot path, and readable back. assert.ok(file.includes(`${path.sep}.lookouts${path.sep}example-week${path.sep}runs${path.sep}`)); assert.deepEqual((await readLookoutRun(paths, "example-week", run.runId))?.ideas, run.ideas); // The notes are beside the cues, complete, with what was dropped counted per chunk. const n = await notesOf("alpha-news", "News0000001"); assert.ok(n?.complete); assert.equal(n!.chunks.length, n!.chunkCount); assert.ok(n!.chunks.every((c) => c.items.length === 1 && c.dropped === 1)); }); test("a voice other than his own is a caveat, and a site origin builds the links", async () => { const { checkIdeas } = await import("../lib/lookoutRead"); const base = { kind: "claim", why: "w", people: [], channel: "alpha-news", platform: "youtube", url: "https://www.youtube.com/watch?v=x", title: "T" }; const items = new Map([ ["i1", { ...base, id: "i1", quote: "q one", start: 10, end: 14, voice: "reading" as const, video: "v1", recordId: "v1", date: "2026-11-03" }], ["i2", { ...base, id: "i2", quote: "q two", start: 70, end: 75, voice: "own" as const, video: "v2", recordId: "v2", date: "2026-11-04" }], ]); const out = checkIdeas([{ workingTitle: "w", itemIds: ["i2", "i1"], confidence: "high", caveats: [] }], items, { siteOrigin: "https://example.pages.dev" }); assert.equal(out.ideas.length, 1); assert.deepEqual(out.ideas[0]!.moments.map((m) => m.video), ["v1", "v2"], "date order"); assert.equal(out.ideas[0]!.moments[0]!.link, "https://example.pages.dev/?v=alpha-news%2Fv1&t=10"); assert.match(out.ideas[0]!.caveats.join("\n"), /Moment 1 \(2026-11-03, 0:10\): .*reading something aloud.*check by ear/); assert.equal(out.ideas[0]!.estimatedLengthSec, 9); }); test("cancelled mid-read: no call after the cancel, the notes kept; the next run continues and re-reads nothing judged", async () => { await clearNotes(); const plan = await planLookout(paths, ITEM, { until: UNTIL }); const total = plan.estimate.readCalls; const ac = new AbortController(); const first = stub({ onCall: (n) => n === 5 && ac.abort() }); const a = opts(ac.signal); const one = await L.runLookout(paths, ITEM, a.o, { ask: first.ask, renderHeld: noRender }); assert.equal(first.asked.length, 5, "the call in flight finished; none started after the cancel"); assert.ok(first.asked.every((x) => !x.aborted), "never a call with an aborted signal"); assert.equal(one.run.status, "partial"); assert.equal(one.run.stopped, "cancelled"); assert.deepEqual(one.run.ideas, [], "a cancelled run groups nothing"); assert.equal(one.run.reading?.chunksRead, 5, "the call in flight when it was cancelled finished, and its answer is kept with the four before it"); const judged = new Set(first.asked.map((x) => x.label)); const second = stub(); const b = opts(new AbortController().signal); const two = await L.runLookout(paths, ITEM, b.o, { ask: second.ask, renderHeld: noRender }); const reads = second.asked.filter((x) => x.phase === "reading"); assert.equal(reads.length, total - 5, "only the chunks not yet read"); for (const r of reads) assert.ok(!judged.has(r.label), `${r.label} was read again`); assert.equal(two.run.reading?.chunksReused, 5); assert.ok(b.lines.some((l) => /: resuming its reading notes at 1 of \d+ chunk/.test(l)), b.lines.join("\n")); assert.equal(two.run.status, "done"); assert.equal(two.run.ideas.length, 1); // A third run reads nothing at all: every recording's notes are fresh and complete. const third = stub(); const c = opts(new AbortController().signal); const three = await L.runLookout(paths, ITEM, c.o, { ask: third.ask, renderHeld: noRender }); assert.equal(third.asked.filter((x) => x.phase === "reading").length, 0); assert.equal(three.run.reading?.chunksReused, total); assert.equal(three.run.ideas[0]?.key, two.run.ideas[0]?.key, "the same story, the same key"); assert.ok((await listLookoutRunIds(paths, "example-week")).length >= 3); }); test("cancelled before it starts: no call at all", async () => { await clearNotes(); const ac = new AbortController(); ac.abort(); const s = stub(); const { o } = opts(ac.signal); const { run } = await L.runLookout(paths, ITEM, o, { ask: s.ask, renderHeld: noRender }); assert.equal(s.asked.length, 0); assert.equal(run.stopped, "cancelled"); }); 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, "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 () => { await clearNotes(); let polls = 0; const s = stub(); const { o, lines } = opts(new AbortController().signal); const held = () => (polls < 3 ? "umtool take p --id t, since 13:31" : null); const { run } = await L.runLookout(paths, ITEM, o, { ask: async (q) => { assert.ok(polls >= 3, "no call while render mode holds"); return s.ask(q); }, renderHeld: held, sleep: async () => { polls++; }, }); assert.equal(lines.filter((l) => /render mode holds the machine/.test(l)).length, 1, lines.join("\n")); assert.equal(run.status, "done"); }); test("the per-run cap ends the run partial and groups what it read; the model failing ends it failed", async () => { await clearNotes(); const s = stub(); const { run } = await L.runLookout(paths, ITEM, opts(new AbortController().signal, { maxCalls: 4 }).o, { ask: s.ask, renderHeld: noRender }); assert.equal(s.asked.filter((x) => x.phase === "reading").length, 4); assert.equal(run.status, "partial"); assert.equal(run.stopped, "cap"); assert.ok(run.reading!.groupCalls >= 1, "what it read is still grouped"); await clearNotes(); const f = stub({ failReading: 99 }); const out = await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: f.ask, renderHeld: noRender }); assert.equal(f.asked.length, L.LOOKOUT_MAX_FAILED_IN_A_ROW); assert.equal(out.run.status, "failed"); 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 }); await writeFile(file, "{ not json"); try { const s = stub(); await assert.rejects(L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: s.ask, renderHeld: noRender }), /unparseable/); assert.equal(s.asked.length, 0); } finally { await writeFile(file, JSON.stringify({ version: 1, ideas: {} })); } }); test("through the generation route: every call recorded in the model log with its decision, and no other request", async () => { await clearNotes(); const s = stub(); const sent: string[] = []; // ollama, stubbed at its fetch: the only door a call goes through. const ollamaFetch = (async (url: string, init: { body: string }) => { sent.push(String(url)); const body = JSON.parse(init.body) as { messages: { role: string; content: string }[]; format: { properties: Record } }; const user = body.messages.find((m) => m.role === "user")!.content; const phase = "covers" in body.format.properties ? "reading" : "grouping"; const label = "merges" in body.format.properties ? "merge the groups" : "x"; const answer = await s.ask({ system: "", user, schema: {}, phase, label, slot: undefined as never, signal: new AbortController().signal }); return new Response(JSON.stringify({ done: true, message: { role: "assistant", content: JSON.stringify(answer) }, prompt_eval_count: 100, eval_count: 20 }), { status: 200 }); }) as unknown as typeof fetch; const realFetch = globalThis.fetch; globalThis.fetch = (async () => { throw new Error("a lookout run makes no network request"); }) as typeof fetch; const dir = path.join(ROOT, "calls"); const writer = new ModelLogWriter({ files: modelLogFilesIn(dir), task: "lookout" }); try { const ask = L.structuredAsk({ ollama: { baseUrl: "http://ollama.invalid", fetch: ollamaFetch } }, "stub-local:1b"); const { run } = await runWithModelLog(writer, () => L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask, renderHeld: noRender })); await writer.flush(); assert.equal(run.status, "done"); assert.equal(run.ideas.length, 1); assert.ok(sent.length > 0 && sent.every((u) => u === "http://ollama.invalid/api/chat")); const log = await readModelLog(modelLogFilesIn(dir)); assert.equal(log.calls.length, run.calls); const reading = log.calls.filter((c) => c.phase === "reading"); assert.equal(reading.length, run.reading!.readCalls); assert.ok(reading.every((c) => c.decision?.outcome === "kept" && (c.items ?? []).some((i) => i.outcome === "dropped" && i.why === "not-in-transcript"))); assert.ok(log.calls.some((c) => c.phase === "grouping")); } finally { globalThis.fetch = realFetch; } }); test("as a job: refused when lookouts are off, for an unknown id, on a route it does not read on; it runs, logs its marker, and a second run of it is refused while it is live", async () => { await clearNotes(); const { getRegistry } = await import("../jobs/registry"); const settings = (o: { enabled?: boolean; route?: string } = {}) => () => ({ lookouts: sanitizeLookouts({ enabled: o.enabled ?? true, items: [ITEM] }), generation: sanitizeGeneration({ routes: { lookout: o.route ?? "local" }, models: { local: "stub-local:1b" } }), }) as never; const s = stub(); const unloaded: string[] = []; const deps = (o: { enabled?: boolean; route?: string } = {}) => ({ paths, settings: settings(o), ask: () => s.ask, memAvailableMb: async () => 8000, renderHeld: noRender, unload: async (m: string) => { unloaded.push(m); }, }); const off = await L.enqueueLookoutRun({ id: ITEM.id }, deps({ enabled: false })); assert.match(String((off.result as { error?: string }).error), /lookouts are off/); const unknown = await L.enqueueLookoutRun({ id: "nope" }, deps()); assert.match(String((unknown.result as { error?: string }).error), /no lookout "nope"/); const code = await L.enqueueLookoutRun({ id: ITEM.id }, deps({ route: "code" })); assert.match(String((code.result as { error?: string }).error), /routed to Claude Code/); const api = await L.enqueueLookoutRun({ id: ITEM.id, model: "claude-haiku-4-5" }, deps()); assert.match(String((api.result as { error?: string }).error), /not a local model/); assert.equal(s.asked.length, 0); const out = await L.enqueueLookoutRun({ id: ITEM.id, until: UNTIL }, deps()); assert.ok(out.result.ok, JSON.stringify(out.result)); if (!out.result.ok) return; const job = getRegistry().get(out.result.jobId)!; assert.equal(job.kind, "lookout-run"); assert.equal(job.queueKey, "draft:local"); const again = await L.enqueueLookoutRun({ id: ITEM.id }, deps()); assert.match(String((again.result as { error?: string }).error), /already (queued|running)/); void out.result.stream.cancel(); const end = await out.result.done; const log = await readFile(job.logPath, "utf8"); assert.equal(end.status, "done", log); const line = log.split("\n").find((l) => l.startsWith(L.LOOKOUT_RUN_RESULT_MARKER))!; const marker = JSON.parse(line.slice(L.LOOKOUT_RUN_RESULT_MARKER.length)); assert.equal(marker.status, "done"); assert.equal(marker.ideas, 1); assert.deepEqual(unloaded, ["stub-local:1b"], "the model unloaded at the end"); assert.deepEqual(L.lookoutRunJobs(ITEM.id), []); // Under the memory floor the job refuses to start: no call. const before = s.asked.length; const low = await L.enqueueLookoutRun({ id: ITEM.id, until: UNTIL }, { ...deps(), memAvailableMb: async () => 1000 }); assert.ok(low.result.ok); if (!low.result.ok) return; void low.result.stream.cancel(); const lowEnd = await low.result.done; assert.equal(lowEnd.status, "failed"); assert.match(await readFile(getRegistry().get(low.result.jobId)?.logPath ?? job.logPath.replace(job.id, low.result.jobId), "utf8"), /under the 3072 MB/); assert.equal(s.asked.length, before); }); test("cancel: a queued or running run of a lookout is cancelled by the lookout's id", async () => { await clearNotes(); let release!: () => void; const gate = new Promise((r) => (release = r)); const s = stub(); let started = 0; const out = await L.enqueueLookoutRun( { id: ITEM.id, until: UNTIL }, { paths, settings: () => ({ lookouts: sanitizeLookouts({ enabled: true, items: [ITEM] }), generation: sanitizeGeneration({ routes: { lookout: "local" }, models: { local: "stub-local:1b" } }) }) as never, ask: () => async (q) => { started++; await gate; return s.ask(q); }, memAvailableMb: async () => 8000, renderHeld: noRender, unload: async () => {}, }, ); assert.ok(out.result.ok); if (!out.result.ok) return; void out.result.stream.cancel(); // Wait for it to be running (its first call waits on the gate). for (let i = 0; i < 500 && started === 0; i++) await new Promise((r) => setTimeout(r, 10)); assert.equal(started, 1); assert.deepEqual(L.cancelLookoutRuns(ITEM.id), [out.result.jobId]); release(); const end = await out.result.done; assert.equal(end.status, "cancelled"); // Nothing after the cancel: the call that was in flight is the last. await new Promise((r) => setTimeout(r, 50)); assert.equal(started, 1); assert.deepEqual(await readdir(path.join(paths.transcriptsDir, ".lookouts", "example-week")).then((x) => x.sort()), ["runs", "verdicts.json"]); });