commit 903604ca0dcb9a7af89ebffdb44aa23aed85557b
parent 42d362f4307520a0f7fedfa0941de9cbfbedc668
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 12:18:06 -0500
Merge lane/lookout (slice 2): a lookout's run reads -- the job makes the plan at its turn and reads exactly its list on the local model, one call a chunk, each in the job's model log; a kept quote is the transcript's own words; notes are kept per model and reused, so a cancelled or capped run resumes; a render is waited for ten minutes at most; the notes and .lookouts never reach the index, a site, an archive, the MCP or the source mirror; an idea with no cited moment is not surfaced; run, cancel and last run from pnpm ops
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
26 files changed, 2847 insertions(+), 75 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -227,7 +227,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
-| `lookout-run` | lookout-run lists what a saved lookout (settings.lookouts) would read: {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}. Every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing; without "dryRun": true it is refused (the model run is not in this build). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'` |
+| `lookout-run` | lookout-run runs a saved lookout (settings.lookouts), or lists what it would read. {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"} is the list: every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing. Without "dryRun" it is the RUN, a lookout-run job on draft:local: {"id", "days"?, "maxVideos"?, "until"?, "model"?, "maxCalls"?}. The same list, made at the job's turn, read by the local model one chunk a call (every call through the GPU arbiter, after render mode, in the job's model log) into each video's private reading-notes.json; the notes grouped into ideas of at least two located, dated moments; the run written to transcripts/.lookouts/<id>/runs/. A video whose notes are fresh is not read again, so a cancelled run's next start continues where it stopped. maxCalls caps the reading calls (default 400; past it the run ends partial). Refused with lookouts off (settings.lookouts.enabled), the lookout route not local (model names a local one), a run of it already queued or running, a damaged verdicts.json, or under 3 GB of free memory at its turn. --wait prints the log's @@lookout-run line. {"id", "cancel": true} cancels its queued or running run (answers the job ids; the notes read so far are kept). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'`<br>`pnpm ops lookout-run --json '{"id":"example-week"}' --wait`<br>`pnpm ops lookout-run --json '{"id":"example-week","cancel":true}'` |
### Usage, flags and environment
@@ -254,6 +254,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get cleanup <slug>
pnpm ops get speakers
pnpm ops get lookouts [<id>]
+ pnpm ops get lookout-run <id> [--run <runId>]
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
@@ -352,6 +353,11 @@ get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):
<id>/), the latest run (when, window, model, calls, seconds, ideas), how
many of that run's ideas have no verdict yet, and the verdicts given.
Reads settings and the store only, never a channel's videos.
+get lookout-run <id> [--run <runId>] is one lookout's latest run (or the
+ one named), whole: its window, the selection it read, calls, seconds,
+ the reading counts (read, reused from fresh notes, failed), its ideas and
+ what was dropped and why; null before the first. With it, the lookout's
+ run queued or running now ({jobId, status}).
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1169,6 +1169,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `clips-suggest` | `"local"` | The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`). |
| `video-assist` | `"local"` | The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words ("make the joins 0.15 s with less smear") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). |
| `propose-groups` | `"local"` | Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). |
+| `lookout` | `"local"` | A saved lookout's run (`settings.lookouts`, `pnpm ops lookout-run`): the model reads each recent recording's transcript, one call per chunk, into its private reading notes (`reading-notes.json` beside the cues), then groups the notes into video ideas, each a story of at least two located, dated moments. Local in `balanced` and `local`; this build runs it on the local model only — a `code` or `api` route is refused unless the run names a local `model`. |
| `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. |
#### `generation.models`
@@ -1284,7 +1285,8 @@ Default:
"frames": "api",
"clips-suggest": "local",
"video-assist": "local",
- "propose-groups": "local"
+ "propose-groups": "local",
+ "lookout": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/common/bin/lookoutPrivacy.test.ts b/common/bin/lookoutPrivacy.test.ts
@@ -0,0 +1,196 @@
+// A LOOKOUT'S PRIVATE FILES NEVER LEAVE (lane/lookout slice 2, acceptance 2b):
+// a video's `reading-notes.json` (what the model found reading it) and
+// everything under `transcripts/.lookouts/` (runs, ideas, verdicts, traces)
+// are planted in a temp corpus with a marker in every one, then each consumer
+// that enumerates the corpus's files runs FOR REAL and its whole output is
+// searched — file names and contents — for the names and the markers. A
+// positive control in each (the video's own public cue) proves the consumer
+// did read the video.
+//
+// the index build (controller/buildIndex.ts: export index files + LMDB)
+// the site compose (bin/compose-site.ts: the public dir)
+// the archive bundles (controller/archiveTranscripts.ts: the ZIP)
+// the editor's reader (controller/videoCues.ts readVideoCues — what
+// `pnpm ops get transcript` and the MCP's editor-side
+// transcript ask read)
+// The MCP's own readers are mcp/src/lookoutPrivacy.test.ts (over this same
+// kind of composed dir), the source mirror publish/source.test.ts.
+//
+// Run with: node_modules/.bin/tsx --test common/bin/lookoutPrivacy.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execa } from "execa";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "lookout-privacy-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+});
+delete process.env.ARCHILYZER_INDEX_ALLOW_HELD;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { main: composeSite } = await import("./compose-site");
+const { archiveTranscripts } = await import("../controller/archiveTranscripts");
+const { readVideoCues } = await import("../controller/videoCues");
+const { READING_NOTES_FILENAME } = await import("../lib/readingNotes-server");
+const { LOOKOUTS_DIRNAME } = await import("../lib/lookoutStore");
+const { open } = await import("lmdb");
+
+const paths = getPaths();
+const CH = "alpha-news";
+const VIDEO = "PublicVid01";
+const PUBLIC_CUE = "an ordinary public cue about the weather";
+// One marker per private file, so a leak names its source.
+const NOTES_MARK = "notesmarkerq7x";
+const RUN_MARK = "runmarkerz4k";
+const VERDICT_MARK = "verdictmarkerw2p";
+const TRACE_MARK = "tracemarkerj9m";
+const MARKS = [NOTES_MARK, RUN_MARK, VERDICT_MARK, TRACE_MARK];
+const NAMES = [READING_NOTES_FILENAME, LOOKOUTS_DIRNAME, "verdicts.json", "trace.jsonl"];
+const quiet = () => {};
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+
+writeJson(paths.settingsFile, {});
+writeJson(path.join(paths.channelsDir, CH, "config.json"), { handling: "youtube", name: "Alpha News", url: "https://www.youtube.com/@alpha-news/videos" });
+const video = path.join(paths.channelsDir, CH, "data", VIDEO);
+writeJson(path.join(video, "metadata.info.json"), {
+ id: VIDEO, title: "A public video", upload_date: "20261103", timestamp: 1793750000, duration: 120,
+ webpage_url: `https://www.youtube.com/watch?v=${VIDEO}`, extractor_key: "Youtube",
+});
+writeFileSync(path.join(video, "transcript.en.vtt"), `WEBVTT\n\n00:00:01.000 --> 00:00:04.000\n${PUBLIC_CUE}\n`);
+writeJson(path.join(video, "transcript.cues.json"), {
+ version: 2, id: VIDEO, title: "A public video", uploadDate: "20261103", duration: 120, platform: "youtube",
+ webpageUrl: `https://www.youtube.com/watch?v=${VIDEO}`, cues: [{ start: 1, end: 4, text: PUBLIC_CUE }],
+});
+// The private files, as a lookout run writes them.
+writeJson(path.join(video, READING_NOTES_FILENAME), {
+ version: 1,
+ provenance: { model: "stub-local:1b", promptVersion: 1, chunkChars: 7000, cues: { size: 1, mtimeMs: 1 } },
+ chunkCount: 1,
+ chunks: [{ index: 0, from: 1, to: 1, covers: `covers ${NOTES_MARK}`, items: [{ kind: "claim", quote: `a quote ${NOTES_MARK}`, start: 1, end: 4, why: "why", voice: "own", people: [] }], dropped: 0 }],
+ complete: true,
+ updatedAt: "2026-11-11T12:00:00.000Z",
+});
+const store = path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME, "example-week");
+writeJson(path.join(store, "runs", "20261111T120000Z-abcd.json"), { version: 1, lookoutId: "example-week", runId: "20261111T120000Z-abcd", ideas: [{ workingTitle: RUN_MARK }] });
+writeFileSync(path.join(store, "runs", "20261111T120000Z-abcd.trace.jsonl"), `${JSON.stringify({ t: TRACE_MARK })}\n`);
+writeJson(path.join(store, "verdicts.json"), { version: 1, ideas: { "FAKE-TEST-VALUE": { verdict: "make", at: "x", note: VERDICT_MARK } } });
+
+writeJson(path.join(paths.sitesDir, "pub", "site.json"), {
+ siteId: "pub", siteTitle: "pub", siteDescription: "fixture", headerTitle: "pub", homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: [{ slug: CH, groupId: "default" }],
+ siteUrl: "https://pub.example.test", archives: false,
+});
+
+/** Every file under `dir`: its path relative to `dir`, and its bytes as text. */
+function filesUnder(dir: string): { rel: string; text: string }[] {
+ const out: { rel: string; text: string }[] = [];
+ const walk = (d: string) => {
+ for (const e of readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.isFile() || (e.isSymbolicLink() && statSync(p).isFile())) out.push({ rel: path.relative(dir, p), text: readFileSync(p).toString("latin1") });
+ }
+ };
+ walk(dir);
+ return out;
+}
+
+function assertNoLeak(files: { rel: string; text: string }[], where: string) {
+ for (const f of files) {
+ for (const name of NAMES) assert.ok(!f.rel.split(path.sep).includes(name) && !f.rel.endsWith(name), `${where}: a file named ${f.rel}`);
+ for (const mark of MARKS) assert.ok(!f.text.includes(mark), `${where}: ${f.rel} holds ${mark}`);
+ for (const name of [READING_NOTES_FILENAME, LOOKOUTS_DIRNAME]) assert.ok(!f.text.includes(name), `${where}: ${f.rel} names ${name}`);
+ }
+}
+
+const hasPublicCue = (files: { text: string }[]) => files.some((f) => f.text.includes(PUBLIC_CUE));
+
+test("the index build: neither the export index files nor any LMDB record carries a lookout's file", async () => {
+ await buildIndex({ paths, onLog: quiet });
+ const files = filesUnder(paths.exportIndexDir);
+ assert.ok(hasPublicCue(files), "control: the video's cue is in the index");
+ assertNoLeak(files, "export index");
+ // Every record of every sub-database, keys and values (LMDB compresses, so
+ // the bytes on disk are not searched; the records are).
+ const root = open({ path: paths.lmdbPath, maxDbs: 18, compression: true });
+ try {
+ let seenCue = false;
+ for (const name of ["sums", "cues", "subs", "alts", "mtimes", "byChannel", "pageHashes", "subPageHashes", "channelStats", "posts", "postPageHashes", "channelPostsStats", "digests", "digestPageHashes", "channelDigestStats", "videoState", "meta"]) {
+ const db = root.openDB({ name, encoding: "msgpack" });
+ for (const { key, value } of db.getRange()) {
+ const text = JSON.stringify([key, value]);
+ if (text.includes(PUBLIC_CUE)) seenCue = true;
+ for (const mark of MARKS) assert.ok(!text.includes(mark), `LMDB ${name}: a record holds ${mark}`);
+ for (const n of [READING_NOTES_FILENAME, LOOKOUTS_DIRNAME]) assert.ok(!text.includes(n), `LMDB ${name}: a record names ${n}`);
+ }
+ }
+ assert.ok(seenCue, "control: the cue is in LMDB");
+ } finally {
+ await root.close();
+ }
+});
+
+test("the site compose: nothing in the public dir carries a lookout's file", async () => {
+ await buildIndex({ paths, onLog: quiet });
+ const log = console.log;
+ console.log = quiet;
+ try {
+ await composeSite({ siteId: "pub", paths });
+ } finally {
+ console.log = log;
+ }
+ const files = filesUnder(paths.exportPublicDir);
+ assert.ok(hasPublicCue(files), "control: the video's cue is composed");
+ assertNoLeak(files, "public dir");
+});
+
+test("the archive bundles: a channel's ZIP, with metadata, holds the cues and the channel and nothing of a lookout's", async () => {
+ for (const includeMetadata of [true, false]) {
+ const result = await archiveTranscripts({ paths, channelSlugs: [CH], build: { format: "zip", includeMetadata }, onLog: quiet });
+ assert.equal(result.archives.length, 1);
+ const archive = result.archives[0]!.archivePath;
+ const names = (await execa("unzip", ["-Z1", archive])).stdout.split(/\r?\n/).filter((n) => n && !n.endsWith("/"));
+ const files = await Promise.all(names.map(async (rel) => ({ rel, text: (await execa("unzip", ["-p", archive, rel])).stdout })));
+ assert.ok(hasPublicCue(files), "control: the cue is in the ZIP");
+ assertNoLeak(files, `ZIP (metadata=${includeMetadata})`);
+ }
+});
+
+test("the editor's transcript reader: a video's cues, never its reading notes", async () => {
+ const out = await readVideoCues(paths, { slug: CH, id: VIDEO });
+ const text = JSON.stringify(out);
+ assert.ok(text.includes(PUBLIC_CUE), text.slice(0, 400));
+ for (const mark of MARKS) assert.ok(!text.includes(mark), mark);
+ assert.ok(!text.includes(READING_NOTES_FILENAME));
+});
+
+test("the search itself catches a leak: a planted name or marker fails it", () => {
+ assert.throws(() => assertNoLeak([{ rel: path.join("transcripts", CH, READING_NOTES_FILENAME), text: "" }], "x"));
+ assert.throws(() => assertNoLeak([{ rel: path.join(LOOKOUTS_DIRNAME, "a"), text: "" }], "x"));
+ for (const mark of MARKS) assert.throws(() => assertNoLeak([{ rel: "page-0001.json", text: `{"q":"${mark}"}` }], "x"));
+ assert.doesNotThrow(() => assertNoLeak([{ rel: "page-0001.json", text: PUBLIC_CUE }], "x"));
+});
diff --git a/common/controller/lookoutPlan.ts b/common/controller/lookoutPlan.ts
@@ -1,6 +1,7 @@
// WHAT A LOOKOUT WOULD READ — stages 1 and 2 of a lookout run, with no model
// (lane/lookout slice 1). `pnpm ops lookout-run {"id", "dryRun": true}` answers
-// this; the run itself (slice 2) reads exactly the `read` list it returns.
+// this; the run itself (controller/lookoutRun.ts) reads exactly the `read`
+// list it returns, chunked the same way (`cueLines`).
//
// Stage 1, select: every video of the lookout's channels whose AIR date
// (lib/lookout.ts airDateOf: `release_timestamp`, else `timestamp`, in the
@@ -275,10 +276,23 @@ type Loaded = {
shingles: Set<string>;
};
-function cueLines(cues: readonly Cue[]): [number, string][] {
+/**
+ * A transcript's lines as the model reads them: each cue with text, at its
+ * whole second. THE one chunking a plan counts and a run reads
+ * (`chunksOf(cueLines(cues), CHUNK_CHARS)`), so the plan's `chunks` are the
+ * run's reading calls.
+ */
+export function cueLines(cues: readonly Cue[]): [number, string][] {
return cues.filter((c) => c.text.trim()).map((c) => [Math.floor(c.start), c.text.trim()] as [number, string]);
}
+/** The cues of a cues document, as the plan takes them (malformed cues left out). */
+export function cuesOfDoc(doc: Record<string, unknown>): Cue[] {
+ return (Array.isArray(doc.cues) ? doc.cues : []).filter(
+ (x): x is Cue => !!x && typeof (x as Cue).start === "number" && typeof (x as Cue).text === "string",
+ );
+}
+
const NOT_FINISHED = new Set(["is_live", "is_upcoming"]);
/**
@@ -401,9 +415,7 @@ export async function planLookout(
skipped.push({ ...brief(c), reason: "no-transcript" });
continue;
}
- const cues = (Array.isArray(doc.cues) ? doc.cues : []).filter(
- (x): x is Cue => !!x && typeof (x as Cue).start === "number" && typeof (x as Cue).text === "string",
- );
+ const cues = cuesOfDoc(doc);
const lastEnd = cues.length ? Math.round(cues[cues.length - 1]!.end) : null;
const duration = (typeof doc.duration === "number" && doc.duration > 0 ? doc.duration : null) ?? c.meta?.duration ?? lastEnd;
const video = brief(c, {
diff --git a/common/controller/lookoutRun.test.ts b/common/controller/lookoutRun.test.ts
@@ -0,0 +1,583 @@
+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<import("./lookoutRun").LookoutRunOptions> = {}) => {
+ 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<string, unknown> } };
+ 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<void>((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"]);
+});
diff --git a/common/controller/lookoutRun.ts b/common/controller/lookoutRun.ts
@@ -0,0 +1,637 @@
+// A LOOKOUT RUN — `pnpm ops lookout-run {"id"}` (lane/lookout slice 2): a
+// saved lookout's recent recordings read by the local model and grouped into
+// video ideas, as a `lookout-run` job on `draft:local`.
+//
+// WHAT IS READ IS THE PLAN'S `read` LIST, computed IN THE JOB at its turn
+// (planLookout, controller/lookoutPlan.ts) — the one enumeration the dry run
+// shows, never a second one that could disagree with it — and each recording
+// is chunked as the plan counted it (`chunksOf(cueLines(cues))`).
+//
+// stage 3, read one call per chunk (READ_SYSTEM, lib/lookoutRead.ts); every
+// quote located in the chunk by code or dropped; the chunk's
+// items appended to the video's reading notes
+// (lib/readingNotes-server.ts, its one writer) AFTER EVERY
+// CALL. A video whose notes are fresh and complete is not read
+// again; one whose notes are fresh and partial (a cancelled or
+// interrupted run) is read from the chunks it lacks. So a run
+// stopped anywhere continues, on its next start, where it
+// stopped, and re-reads nothing already judged.
+// stage 4, group the window's items as numbered lines, at most GROUP_CHARS a
+// call, date order; more than one call → one merge call over
+// the candidates; the lookout's `prompt` steers this only.
+// stage 5, check lib/lookoutRead.ts checkIdeas: ids that exist, at least two
+// moments, a story key, caveats from the voice.
+// 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. 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)
+// and is recorded in the job's model log (CallSlot, controller/jobModelLog.ts);
+// render mode is read before every call and a held one is waited out with one
+// log line (render mode does not hold `draft:local` by itself); the job
+// refuses to start under LOOKOUT_MIN_FREE_MB of MemAvailable; the model is
+// unloaded when the job ends; no call is made with an aborted signal. The run
+// makes no other network request.
+//
+// LOCAL ONLY in this build: a lookout routed to `code` or `api` is refused
+// unless the run names a local model (no `answers`, no API spend yet).
+
+import path from "node:path";
+import { readFile, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import type { GenerationSettings } from "../lib/generationSettings";
+import { lookoutById, type LookoutItem } from "../lib/lookoutSettings";
+import {
+ assertLookoutVerdictsReadable,
+ newLookoutRunId,
+ writeLookoutRun,
+ type LookoutRun,
+} from "../lib/lookoutStore";
+import {
+ CHUNK_CHARS,
+ GROUP_SCHEMA,
+ GROUP_SYSTEM,
+ MERGE_SCHEMA,
+ MERGE_SYSTEM,
+ READING_PROMPT_VERSION,
+ READ_SCHEMA,
+ READ_SYSTEM,
+ applyMerges,
+ checkIdeas,
+ checkReading,
+ groupBatches,
+ groupPrompt,
+ ideasOf,
+ mergeLine,
+ readPrompt,
+ type GroupItem,
+ type RawIdea,
+} from "../lib/lookoutRead";
+import {
+ loadReadingNotes,
+ newReadingNotes,
+ sameReadingProvenance,
+ writeReadingNotes,
+ withReadingChunk,
+ type ReadingNotes,
+ type ReadingProvenance,
+} from "../lib/readingNotes-server";
+import { chunksOf } from "../lib/report/draft/tasks/sweep-pipeline";
+import { CallSlot } from "../lib/llm/callLog-server";
+import { providerOf, structuredAnswer, unloadOllama, type LlmConfig } from "../lib/llm";
+import { DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { describeRenderPriority, readRenderPriority, renderPriorityFile } from "../lib/renderPriority.mjs";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { getRegistry } from "../jobs/registry";
+import { CUES_JSON_FILENAME } from "../lib/videoStatus";
+import { cueLines, cuesOfDoc, planLookout, type LookoutPlanOptions } from "./lookoutPlan";
+import { modelLogged } from "./jobModelLog";
+import { readMemAvailableMb } from "./persistVideos";
+import { llmConfigOf } from "./reportDraft";
+
+export const LOOKOUT_RUN_JOB_KIND = "lookout-run";
+export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run ";
+export const LOOKOUT_TASK = "lookout" as const;
+/** Reading calls one run may make; past it the run ends `partial` with what it has. */
+export const LOOKOUT_MAX_CALLS = 400;
+/** The job does not start with less MemAvailable than this (MiB). */
+export const LOOKOUT_MIN_FREE_MB = 3072;
+/** This many failed calls in a row end the run `failed`. */
+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 {}
+
+/** One model call: the generation route's structured answer, or a test's stub. */
+export type LookoutAsk = (o: {
+ system: string;
+ user: string;
+ schema: object;
+ phase: "reading" | "grouping";
+ label: string;
+ slot: CallSlot;
+ signal: AbortSignal;
+}) => Promise<unknown>;
+
+export type LookoutRunDeps = {
+ ask: LookoutAsk;
+ /** Why render mode holds the machine now, or null (default: its state file). */
+ 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;
+};
+
+export type LookoutRunOptions = Pick<LookoutPlanOptions, "days" | "maxVideos" | "until"> & {
+ model: string;
+ maxCalls?: number;
+ signal: AbortSignal;
+ onLog: (line: string) => void;
+ onProgress?: (done: number, total: number) => void;
+};
+
+export type LookoutRunOutcome = { run: LookoutRun; file: string };
+
+/** Render mode, as the heavy slot's gate reads it: why it holds, or null. */
+export function renderModeHeld(): string | null {
+ try {
+ const s = readRenderPriority(renderPriorityFile(process.env, { root: process.cwd() }));
+ return s.held && s.state ? describeRenderPriority(s.state) : null;
+ } catch {
+ return null; // an unreadable state file holds nothing (queue-lock's rule)
+ }
+}
+
+function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted) return resolve();
+ const t = setTimeout(done, ms);
+ function done() {
+ clearTimeout(t);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+type Cued = { cues: ReturnType<typeof cuesOfDoc>; size: number; mtimeMs: number };
+
+async function readCues(dir: string): Promise<Cued | null> {
+ const file = path.join(dir, CUES_JSON_FILENAME);
+ try {
+ const st = await stat(file);
+ const doc = JSON.parse(await readFile(file, "utf8")) as Record<string, unknown>;
+ return { cues: cuesOfDoc(doc), size: st.size, mtimeMs: st.mtimeMs };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * One lookout run, start to end: plan, read, group, check, write the run.
+ * Never throws for a model failure, a cancel or the cap — those end the run
+ * `partial` or `failed`, and it is written; a refusal (damaged verdicts, a
+ * lookout with no channels) throws before anything is read.
+ */
+export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunOptions, deps: LookoutRunDeps): Promise<LookoutRunOutcome> {
+ const now = deps.now ?? (() => new Date());
+ const startedAt = now();
+ const runId = newLookoutRunId(startedAt);
+ const { signal, onLog, model } = o;
+ const maxCalls = o.maxCalls ?? LOOKOUT_MAX_CALLS;
+ await assertLookoutVerdictsReadable(paths, item.id);
+ const plan = await planLookout(paths, item, { days: o.days, maxVideos: o.maxVideos, until: o.until, now: startedAt });
+ for (const r of plan.refused) onLog(`not read: ${r.channel} — ${r.reason}`);
+ onLog(
+ `lookout ${item.id}: ${plan.window.from} to ${plan.window.to} (${plan.window.timeZone}), ` +
+ `${plan.read.length} recording(s) to read, ${plan.estimate.readCalls} chunk(s), on ${model}`,
+ );
+
+ 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, 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 —
+ // 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 || 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) {
+ 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;
+ };
+
+ const call = async (phase: "reading" | "grouping", label: string, system: string, user: string, schema: object, slot: CallSlot): Promise<unknown | null> => {
+ const t0 = Date.now();
+ try {
+ const answer = await deps.ask({ system, user, schema, phase, label, slot, signal });
+ seconds += (Date.now() - t0) / 1000;
+ failedInRow = 0;
+ return answer;
+ } catch (err) {
+ seconds += (Date.now() - t0) / 1000;
+ 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";
+ 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 (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);
+ if (!cued) {
+ onLog(`${key}: transcript.cues.json is not readable now — not read`);
+ count("unreadableCues");
+ continue;
+ }
+ const chunks = chunksOf(cueLines(cued.cues), CHUNK_CHARS);
+ 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 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 && !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 transcript) — read again`);
+ notes = newReadingNotes(prov, chunks.length, now());
+ }
+ 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;
+ if (readCalls >= maxCalls) {
+ stopped ??= "cap";
+ break;
+ }
+ if (!(await mayCall())) break;
+ const slot = new CallSlot();
+ const label = `${key} part ${i + 1}/${chunks.length}`;
+ const answer = await call("reading", label, READ_SYSTEM, readPrompt({ title: r.title, airDate: r.airDate }, chunks[i]!, i, chunks.length), READ_SCHEMA, slot);
+ readCalls++;
+ o.onProgress?.(readCalls, progressTotal);
+ if (answer === null) {
+ if (!signal.aborted) reading.chunksFailed++;
+ if (stopped || signal.aborted) break;
+ continue;
+ }
+ const checked = checkReading(answer, chunks[i]!, cued.cues, i);
+ for (const d of checked.dropped) count(`quote:${d.reason}`);
+ const fates = [
+ ...checked.chunk.items.map((it) => ({ outcome: "kept" as const, why: `located at ${it.start}s`, text: it.quote })),
+ ...checked.dropped.map((d) => ({ outcome: "dropped" as const, why: d.reason, text: d.quote })),
+ ];
+ 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");
+ 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);
+ reading.chunksRead++;
+ }
+ if (notes.complete) reading.videosComplete++;
+ }
+ if (signal.aborted) stopped = "cancelled";
+
+ // ─── Stage 4: group ───
+ const items = new Map<string, GroupItem>();
+ for (const r of plan.read) {
+ const notes = notesOf.get(`${r.channel}/${r.video}`);
+ if (!notes) continue;
+ for (const c of notes.chunks) {
+ for (const it of c.items) {
+ const id = `i${items.size + 1}`;
+ items.set(id, { ...it, id, channel: r.channel, video: r.video, recordId: r.id, platform: r.platform, url: r.url, title: r.title, date: r.airDate });
+ }
+ }
+ }
+ reading.items = items.size;
+ let raw: RawIdea[] = [];
+ if (stopped === "cancelled") {
+ onLog("cancelled — the reading notes so far are kept; the next run continues from them");
+ } else if (stopped === "failed") {
+ 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 {
+ const batches = groupBatches([...items.values()]);
+ const candidates = new Map<string, RawIdea>();
+ const datesOf = new Map<string, string[]>();
+ const going = () => !signal.aborted && stopped !== "failed";
+ for (let b = 0; b < batches.length && going(); b++) {
+ if (!(await mayCall())) break;
+ const slot = new CallSlot();
+ 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) {
+ 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) {
+ const id = `c${candidates.size + 1}`;
+ candidates.set(id, idea);
+ datesOf.set(id, [...new Set(batch.map((x) => x.date))]);
+ }
+ }
+ if (signal.aborted) stopped = "cancelled";
+ raw = [...candidates.values()];
+ if (going() && batches.length > 1 && candidates.size > 1 && (await mayCall())) {
+ const slot = new CallSlot();
+ const lines = [...candidates].map(([id, idea]) => mergeLine(id, idea, datesOf.get(id) ?? []));
+ const answer = await call("grouping", "merge the groups", MERGE_SYSTEM, `Candidates:\n${lines.join("\n").slice(0, 12_000)}`, MERGE_SCHEMA, slot);
+ groupCalls++;
+ if (answer !== null) {
+ 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";
+ if (stopped === "cancelled") raw = [];
+ }
+
+ // ─── Stage 5: check ───
+ const checked = checkIdeas(raw, items, { siteOrigin: item.siteOrigin });
+ count("idea:inventedItemId", checked.dropped.inventedItemIds);
+ count("idea:oneMoment", checked.dropped.oneMoment);
+ count("idea:noCitation", checked.dropped.noCitation);
+ count("idea:sameStory", checked.dropped.sameStory);
+ reading.readCalls = readCalls;
+ reading.groupCalls = groupCalls;
+ reading.groupCallsFailed = groupFailed;
+ reading.renderWaitSeconds = Math.round(renderWaited / 1000);
+
+ // 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,
+ runId,
+ startedAt: startedAt.toISOString(),
+ endedAt: now().toISOString(),
+ status,
+ window: { from: plan.window.from, to: plan.window.to, days: plan.window.days, timeZone: plan.window.timeZone },
+ model,
+ calls: readCalls + groupCalls,
+ seconds: Math.round(seconds * 10) / 10,
+ selection: plan,
+ ideas: checked.ideas,
+ dropped,
+ ...(stopped ? { stopped } : {}),
+ reading,
+ ...(note ? { note } : {}),
+ };
+ const file = await writeLookoutRun(paths, run);
+ onLog(
+ `lookout ${item.id}: ${status}${stopped ? ` (${stopped})` : ""} — ${reading.chunksRead} chunk(s) read, ${reading.chunksReused} reused, ` +
+ `${reading.chunksFailed} failed, ${items.size} moment(s), ${checked.ideas.length} idea(s), ${run.calls} call(s), ${run.seconds}s`,
+ );
+ return { run, file };
+}
+
+// ─── The job ───
+
+// Which lookout each live job is of (the registry record has no field for
+// it); per process, on globalThis (Next may load a module twice).
+const JOBS_KEY = Symbol.for("archilyzer.lookoutRun.jobs");
+function jobsOf(): Map<string, string> {
+ const g = globalThis as unknown as Record<symbol, Map<string, string> | undefined>;
+ return (g[JOBS_KEY] ??= new Map());
+}
+
+const ENQUEUEING_KEY = Symbol.for("archilyzer.lookoutRun.enqueueing");
+function enqueueingOf(): Set<string> {
+ const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
+ return (g[ENQUEUEING_KEY] ??= new Set());
+}
+
+/** The queued or running lookout-run jobs of a lookout: `{jobId, status}`. */
+export function lookoutRunJobs(id: string): { jobId: string; status: string }[] {
+ const mine = jobsOf();
+ const live = getRegistry()
+ .list()
+ .filter((j) => j.kind === LOOKOUT_RUN_JOB_KIND && mine.has(j.id) && (j.status === "queued" || j.status === "running"));
+ // An ended job is forgotten here as it is in the registry.
+ const ids = new Set(live.map((j) => j.id));
+ for (const jobId of [...mine.keys()]) if (!ids.has(jobId)) mine.delete(jobId);
+ return live.filter((j) => mine.get(j.id) === id).map((j) => ({ jobId: j.id, status: j.status }));
+}
+
+/** Cancel a lookout's queued or running run; the job ids cancelled. */
+export function cancelLookoutRuns(id: string): string[] {
+ const out: string[] = [];
+ for (const j of lookoutRunJobs(id)) if (getRegistry().cancel(j.jobId)) out.push(j.jobId);
+ return out;
+}
+
+/** The model a run reads with: the asked one, else the `lookout` route's — local only in this build. */
+export function lookoutModel(gen: GenerationSettings, asked?: string): string {
+ const route = gen.routes[LOOKOUT_TASK];
+ const model = asked ?? (route === "local" ? gen.models.local : null);
+ if (!model) {
+ throw new LookoutRunRefusal(
+ `lookout is routed to ${route === "code" ? "Claude Code" : "the API"} (settings.generation.routes.lookout) — this build reads on the local model only: route it to local, or name a local "model"`,
+ );
+ }
+ if (providerOf(model) !== "local") throw new LookoutRunRefusal(`"${model}" is not a local model — this build reads a lookout on the local model only`);
+ return model;
+}
+
+export type LookoutRunBody = { id: string; model?: string; days?: number; maxVideos?: number; until?: string; maxCalls?: number };
+
+export type LookoutRunJobDeps = {
+ paths: Paths;
+ settings?: () => ReturnType<typeof getSettings>;
+ /** The run's model calls (default: structuredAnswer on the generation route's ollama, through the GPU arbiter). */
+ ask?: (llm: LlmConfig, model: string) => LookoutAsk;
+ memAvailableMb?: () => Promise<number | null>;
+ renderHeld?: () => string | null;
+ unload?: (model: string) => Promise<void>;
+ now?: () => Date;
+};
+
+/** The run's calls on the generation route: structuredAnswer, recorded in the model log with the call's slot. */
+export const structuredAsk =
+ (llm: LlmConfig, model: string): LookoutAsk =>
+ (q) =>
+ structuredAnswer({ llm, model, system: q.system, user: q.user, schema: q.schema, signal: q.signal, call: { phase: q.phase, label: q.label, slot: q.slot } });
+
+export type LookoutRunEnqueued = { result: StreamActionResult; model: string } | { result: StreamActionResult & { ok: false } };
+
+/**
+ * A lookout run as a `lookout-run` job. Refused before any job: lookouts off
+ * (`settings.lookouts.enabled`), an unknown id, a route this build does not
+ * read on, a run of the same lookout already queued or running, a damaged
+ * verdicts.json. At the job's turn: the lookout read from settings again,
+ * MemAvailable under the floor refused.
+ */
+export async function enqueueLookoutRun(body: LookoutRunBody, deps: LookoutRunJobDeps): Promise<LookoutRunEnqueued> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ const settings = deps.settings ?? getSettings;
+ const s = settings();
+ if (!s.lookouts.enabled) {
+ return refuse('lookouts are off (settings.lookouts.enabled) — a dry run ("dryRun": true) still lists what a lookout would read');
+ }
+ const item = lookoutById(s.lookouts, body.id);
+ if (!item) return refuse(`no lookout "${body.id}" — settings.lookouts.items names ${s.lookouts.items.map((i) => i.id).join(", ") || "none"}`);
+ let model: string;
+ try {
+ model = lookoutModel(s.generation, body.model);
+ await assertLookoutVerdictsReadable(deps.paths, item.id);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const busy = lookoutRunJobs(item.id);
+ if (busy.length) return refuse(`a run of lookout "${item.id}" is already ${busy[0]!.status} (job ${busy[0]!.jobId})`);
+ // Two asks at once: the second is refused while the first is being queued.
+ const enqueueing = enqueueingOf();
+ if (enqueueing.has(item.id)) return refuse(`a run of lookout "${item.id}" is being queued`);
+ enqueueing.add(item.id);
+ const paths = deps.paths;
+ let result: StreamActionResult;
+ try {
+ result = await runManagedFunction({
+ kind: LOOKOUT_RUN_JOB_KIND,
+ queueKey: DRAFT_LOCAL_QUEUE,
+ paths,
+ fn: modelLogged({ paths, task: LOOKOUT_TASK, model }, async (onLog, signal, setProgress) => {
+ const now = settings();
+ const at = lookoutById(now.lookouts, item.id);
+ if (!now.lookouts.enabled) throw new Error("lookouts were turned off (settings.lookouts.enabled) while this run waited");
+ if (!at) throw new Error(`lookout "${item.id}" is no longer in settings.lookouts.items`);
+ const mb = await (deps.memAvailableMb ?? readMemAvailableMb)();
+ if (mb !== null && mb < LOOKOUT_MIN_FREE_MB) {
+ throw new Error(`refused: ${mb} MB available is under the ${LOOKOUT_MIN_FREE_MB} MB a lookout run starts with — run it when the machine is quieter`);
+ }
+ const g = now.generation;
+ const llm = llmConfigOf(g, paths, { onLog, signal });
+ let out: LookoutRunOutcome | null = null;
+ try {
+ out = await runLookout(
+ paths,
+ at,
+ {
+ model,
+ ...(body.days !== undefined ? { days: body.days } : {}),
+ ...(body.maxVideos !== undefined ? { maxVideos: body.maxVideos } : {}),
+ ...(body.until !== undefined ? { until: body.until } : {}),
+ ...(body.maxCalls !== undefined ? { maxCalls: body.maxCalls } : {}),
+ signal,
+ onLog,
+ onProgress: (done, total) => setProgress({ metric: "calls", initial: 0, target: Math.max(total, done), current: done }),
+ },
+ { ask: (deps.ask ?? structuredAsk)(llm, model), ...(deps.renderHeld ? { renderHeld: deps.renderHeld } : {}), ...(deps.now ? { now: deps.now } : {}) },
+ );
+ } finally {
+ await (deps.unload ?? ((m: string) => unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, m)))(model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ const r = out.run;
+ onLog(
+ `${LOOKOUT_RUN_RESULT_MARKER}${JSON.stringify({
+ id: r.lookoutId,
+ runId: r.runId,
+ status: r.status,
+ ...(r.stopped ? { stopped: r.stopped } : {}),
+ window: r.window,
+ model: r.model,
+ calls: r.calls,
+ seconds: r.seconds,
+ reading: r.reading,
+ ideas: r.ideas.length,
+ dropped: r.dropped,
+ file: out.file,
+ })}`,
+ );
+ if (r.stopped === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (r.status === "failed") throw new Error("the model kept failing — the run is written as failed");
+ }),
+ });
+ if (result.ok) jobsOf().set(result.jobId, item.id);
+ } finally {
+ enqueueing.delete(item.id);
+ }
+ if (!result.ok) return { result };
+ return { result, model };
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -218,7 +218,9 @@ export function isKnownApiModel(model: string): boolean {
// `frames` is routed by settings.generation like every task, but it is the
// frame scan's (`pnpm ops frame-scan`), never a report-draft.
-const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS.filter((t) => t !== "frames"), REFRESH_TASK, TRIAGE_DRAFT_TASK];
+// Neither a frame scan nor a lookout run is a report-draft job: each is its own
+// kind (frame-scan, lookout-run).
+const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS.filter((t) => t !== "frames" && t !== "lookout"), REFRESH_TASK, TRIAGE_DRAFT_TASK];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -870,6 +872,7 @@ async function runReportDraft(
case "clips-suggest":
case "video-assist":
case "propose-groups":
+ case "lookout":
// A refresh, a triage, verdict proposals, a frame scan, the clip finder's labels and the video assistant are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts, ./videoAssist.ts), never this one.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1363,6 +1363,24 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsMedia: true,
},
+ // A lookout run (lane/lookout slice 2, controller/lookoutRun.ts): a saved
+ // lookout's recent recordings read by the local model into each video's
+ // reading notes, then grouped into ideas — `pnpm ops lookout-run {"id"}`.
+ // On `draft:local`, every call through the GPU arbiter. It reads cues and
+ // metadata and writes `reading-notes.json` beside them — the TEXT side:
+ // needsText. Its channels are several, so the job carries no channelSlug
+ // and the plan asks each channel's text guard, refusing an unreadable one
+ // by name. Not replayable and not resumed at boot (a run is a person's
+ // ask); the next run of the same lookout continues from the notes, so
+ // nothing already read is read again.
+ "lookout-run": {
+ kind: "lookout-run",
+ label: "Lookout run",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsText: true,
+ },
// The mirror scan (release 31, lane D): a mirror channel's videos paired
// with its creator's channels (`mirror.of`) by date and title, into
// `transcripts/mirrors/<slug>.json` — `pnpm ops mirror-scan`, the channel
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -39,7 +39,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri
// (`<project>/group-proposals.json`), each accepted or rejected by the
// operator in umtool's Cut tab. Routed as video-assist: local in every preset
// but `api`; `code` = a Claude Code session answers the request.
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist", "propose-groups"] as const;
+// `lookout` (lane/lookout slice 2): a saved lookout's run — the model reads
+// each recent recording's transcript chunk by chunk into its reading notes,
+// then groups the notes into video ideas (controller/lookoutRun.ts). Local in
+// `balanced` and `local`; this build runs it on the local model only (a
+// `code` or `api` route is refused unless the run names a local model).
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist", "propose-groups", "lookout"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
// The tasks every settings file since release 27 S6 routes.
const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
@@ -51,12 +56,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const;
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local", "propose-groups": "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local", "propose-groups": "local", lookout: "code" },
// A frame scan is on the API in `balanced`: a vision model is not a given
// on the local card, and the cheap model's reads cost cents an hour.
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api", "propose-groups": "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local", lookout: "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api", "propose-groups": "api", lookout: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local", lookout: "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -263,6 +268,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
"The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words (\"make the joins 0.15 s with less smear\") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).",
"propose-groups":
"Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).",
+ lookout:
+ "A saved lookout's run (`settings.lookouts`, `pnpm ops lookout-run`): the model reads each recent recording's transcript, one call per chunk, into its private reading notes (`reading-notes.json` beside the cues), then groups the notes into video ideas, each a story of at least two located, dated moments. Local in `balanced` and `local`; this build runs it on the local model only — a `code` or `api` route is refused unless the run names a local `model`.",
verdicts:
"Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.",
};
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
@@ -0,0 +1,502 @@
+// A LOOKOUT RUN'S MODEL STAGES, the pure half (lane/lookout slice 2, stages
+// 3–5): the prompts and schemas, and the code that checks every answer. No
+// I/O — controller/lookoutRun.ts reads the cues, asks the model and writes.
+//
+// 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 (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
+// dropped and counted), takes its moments' quotes from the items — it can
+// add none of its own — and needs at least two moments; one with none has
+// no story key and is no finding (lookoutStore `ideaKey`).
+//
+// The reading prompt is FIXED and generic, so every lookout (and later the
+// 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, norm } from "./report/draft/tasks/sweep-pipeline";
+import { momentHref } from "./report/draft/tasks/links";
+import { platformMomentUrl } from "./momentUrl";
+import type { Platform } from "./platform";
+import type { Cue } from "./vtt";
+import { ideaKey, type LookoutIdea, type LookoutMoment } from "./lookoutStore";
+import { READING_VOICES, type ReadingChunk, type ReadingItem, type ReadingVoice } from "./readingNotes-server";
+
+export { CHUNK_CHARS };
+
+/** Bumped when the reading prompt or schema changes: every video's notes go stale with it. */
+export const READING_PROMPT_VERSION = 1;
+export const READING_MAX_ITEMS = 3;
+/** A grouping call's numbered lines, at most. */
+export const GROUP_CHARS = 6000;
+/** A quote cut to this many words on a grouping line. */
+export const GROUP_QUOTE_WORDS = 40;
+/** An idea is a story: at least this many moments. */
+export const MIN_IDEA_MOMENTS = 2;
+export const MAX_IDEA_CAVEATS = 8;
+
+export const READING_KINDS = ["announcement", "claim", "feud", "reversal", "admission", "prediction", "running-story"] as const;
+export type ReadingKind = (typeof READING_KINDS)[number];
+
+// ─── Stage 3: read ───
+
+export const READ_SYSTEM =
+ "You read one stretch of a video's transcript for material a short news-style video could be built from. " +
+ "Wanted, by kind: announcement (a change in the speaker's business, channels, schedule, health or plans); " +
+ "claim (a new claim or accusation about a named person or company); feud (a reply to, or fight with, someone named); " +
+ "reversal (contradicting or walking back something said earlier); admission (a personal disclosure or a mistake owned); " +
+ "prediction (a forecast with stakes); running-story (a story the speaker keeps returning to). " +
+ "Not wanted: plain reaction to a news story with nothing of the speaker's own, sponsor reads, chat banter, isolated one-liners. " +
+ `Give at most ${READING_MAX_ITEMS} items, none when nothing qualifies. Each quote is copied WORD FOR WORD from the transcript, ` +
+ `${MIN_QUOTE_WORDS} to ${MAX_QUOTE_WORDS} words in one contiguous run — never a paraphrase, never joined from two places. ` +
+ "voice says whose words the quote is: own (the speaker's), reading (a tweet, headline, article or message read aloud), " +
+ "clip (a clip being played), unsure. covers is one line on what this stretch is about.";
+
+export const READ_SCHEMA = {
+ type: "object",
+ properties: {
+ covers: { type: "string" },
+ items: {
+ type: "array",
+ maxItems: READING_MAX_ITEMS,
+ items: {
+ type: "object",
+ properties: {
+ kind: { type: "string", enum: [...READING_KINDS] },
+ quote: { type: "string" },
+ why: { type: "string" },
+ voice: { type: "string", enum: [...READING_VOICES] },
+ people: { type: "array", items: { type: "string" } },
+ },
+ required: ["kind", "quote", "why", "voice", "people"],
+ },
+ },
+ },
+ required: ["covers", "items"],
+} as const;
+
+/** `m:ss` / `h:mm:ss`. */
+export function clockOf(seconds: number): string {
+ const s = Math.max(0, Math.floor(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+}
+
+export function readPrompt(
+ v: { title: string; airDate: string },
+ chunk: readonly [number, string][],
+ index: number,
+ total: number,
+): string {
+ const lines = chunk.map(([sec, text]) => `[${clockOf(sec)}] ${text}`).join("\n");
+ return `Video: ${v.title || "(untitled)"}, aired ${v.airDate}. Part ${index + 1} of ${total}.\n\nTranscript:\n${lines}`;
+}
+
+export type ReadDropReason = "not-in-transcript" | "too-short" | "too-long" | "not-a-kind" | "repeated" | "over-limit" | "malformed";
+
+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);
+
+/** 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 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;
+ });
+}
+
+/**
+ * One reading answer, checked against the chunk it was asked about: each item
+ * kept only when its quote is in the chunk verbatim and of the right length,
+ * its kind one of the list; start and end from the cues. Never throws: a
+ * malformed answer is an empty chunk with what it held counted as dropped.
+ */
+export function checkReading(
+ answer: unknown,
+ chunk: readonly [number, string][],
+ cues: readonly Cue[],
+ index: number,
+): { chunk: ReadingChunk; dropped: { quote: string; reason: ReadDropReason }[] } {
+ const a = (answer && typeof answer === "object" ? answer : {}) as Record<string, unknown>;
+ const rawItems = Array.isArray(a.items) ? a.items : [];
+ 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) : "";
+ if (!r || !quote) {
+ dropped.push({ quote, reason: "malformed" });
+ continue;
+ }
+ if (items.length >= READING_MAX_ITEMS) {
+ dropped.push({ quote, reason: "over-limit" });
+ continue;
+ }
+ if (!(READING_KINDS as readonly string[]).includes(str(r.kind))) {
+ dropped.push({ quote, reason: "not-a-kind" });
+ continue;
+ }
+ const n = normWords(quote).length;
+ if (n < MIN_QUOTE_WORDS) {
+ dropped.push({ quote, reason: "too-short" });
+ continue;
+ }
+ if (n > MAX_QUOTE_WORDS) {
+ dropped.push({ quote, reason: "too-long" });
+ continue;
+ }
+ const span = quoteSpan(quote, chunk);
+ if (span === null) {
+ dropped.push({ quote, reason: "not-in-transcript" });
+ continue;
+ }
+ 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),
+ // The transcript's words, never the model's string.
+ quote: span.text,
+ start,
+ 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) : [],
+ });
+ }
+ return {
+ chunk: {
+ index,
+ from: chunk[0]?.[0] ?? 0,
+ to: chunk[chunk.length - 1]?.[0] ?? 0,
+ covers: str(a.covers),
+ items,
+ dropped: dropped.length,
+ },
+ dropped,
+ };
+}
+
+// ─── Stage 4: group ───
+
+/** A located item as the grouping sees it, with what its moment needs. */
+export type GroupItem = ReadingItem & {
+ /** `i<n>`: what the model answers with. */
+ id: string;
+ channel: string;
+ video: string;
+ /** The record's id and platform (a moment link on a site needs them). */
+ recordId: string;
+ platform: string;
+ url: string | null;
+ title: string;
+ date: string;
+};
+
+export const GROUP_SYSTEM =
+ "You are given numbered moments found in a creator's recent videos: id | date | channel | kind | quote | why. " +
+ "Group them into video ideas. An idea is ONE STORY told by several moments — the same subject across days or videos, " +
+ "a claim and its reversal, an announcement and its follow-up — never one moment alone. Answer with the moments' ids only " +
+ "(itemIds); never write a quote. workingTitle: a short title. angle: two sentences. whyNow: one line. kind: the story's kind. " +
+ "confidence: high, medium or low that this is a real, self-contained story, and confidenceWhy in one line. caveats: what a " +
+ "reviewer must check. sensitive: true when it touches health, family, a minor, a legal matter or an accusation. " +
+ "Give the strongest ideas first; fewer good ideas beat many weak ones.";
+
+export const GROUP_SCHEMA = {
+ type: "object",
+ properties: {
+ ideas: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ workingTitle: { type: "string" },
+ angle: { type: "string" },
+ whyNow: { type: "string" },
+ kind: { type: "string" },
+ itemIds: { type: "array", items: { type: "string" } },
+ confidence: { type: "string", enum: ["high", "medium", "low"] },
+ confidenceWhy: { type: "string" },
+ caveats: { type: "array", items: { type: "string" } },
+ sensitive: { type: "boolean" },
+ },
+ required: ["workingTitle", "angle", "whyNow", "kind", "itemIds", "confidence", "confidenceWhy", "caveats", "sensitive"],
+ },
+ },
+ },
+ required: ["ideas"],
+} as const;
+
+export function groupLine(i: GroupItem): string {
+ const q = words(i.quote);
+ const quote = q.length > GROUP_QUOTE_WORDS ? `${q.slice(0, GROUP_QUOTE_WORDS).join(" ")} …` : q.join(" ");
+ return `${i.id} | ${i.date} | ${i.channel} | ${i.kind} | "${quote}" | ${i.why}`.replace(/\s*\n\s*/g, " ");
+}
+
+/** The items as grouping calls' line sets: in date order, each at most `maxChars`. */
+export function groupBatches(items: readonly GroupItem[], maxChars = GROUP_CHARS): GroupItem[][] {
+ const sorted = [...items].sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0) || (a.channel < b.channel ? -1 : a.channel > b.channel ? 1 : 0) || a.start - b.start);
+ const out: GroupItem[][] = [];
+ let cur: GroupItem[] = [];
+ let size = 0;
+ for (const i of sorted) {
+ const l = groupLine(i).length + 1;
+ if (cur.length && size + l > maxChars) {
+ out.push(cur);
+ cur = [];
+ size = 0;
+ }
+ cur.push(i);
+ size += l;
+ }
+ if (cur.length) out.push(cur);
+ return out;
+}
+
+export function groupPrompt(batch: readonly GroupItem[], o: { prompt: string; from: string; to: string }): string {
+ const ask = o.prompt.trim() ? `\n\nWhat the operator wants from these ideas: ${o.prompt.trim()}` : "";
+ return `Moments from ${o.from} to ${o.to}:\n${batch.map(groupLine).join("\n")}${ask}`;
+}
+
+/** A grouping answer's idea, as the model gave it (before stage 5). */
+export type RawIdea = Record<string, unknown>;
+
+export function ideasOf(answer: unknown): RawIdea[] {
+ const a = (answer && typeof answer === "object" ? answer : {}) as Record<string, unknown>;
+ return Array.isArray(a.ideas) ? a.ideas.filter((x): x is RawIdea => !!x && typeof x === "object" && !Array.isArray(x)) : [];
+}
+
+// ─── Merging the batches' ideas ───
+
+export const MERGE_SYSTEM =
+ "You are given candidate video ideas, each found in a different stretch of days: id | dates | title | angle. " +
+ "Some may be the same story seen on different days. Answer with the groups of candidate ids that are ONE story " +
+ "(two or more ids each), with a title and a two-sentence angle for the merged story. Leave a candidate out when it " +
+ "stands alone.";
+
+export const MERGE_SCHEMA = {
+ type: "object",
+ properties: {
+ merges: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ ids: { type: "array", items: { type: "string" } },
+ workingTitle: { type: "string" },
+ angle: { type: "string" },
+ },
+ required: ["ids", "workingTitle", "angle"],
+ },
+ },
+ },
+ required: ["merges"],
+} as const;
+
+export function mergeLine(id: string, idea: RawIdea, dates: string[]): string {
+ return `${id} | ${dates.join(", ")} | ${str(idea.workingTitle, 160)} | ${str(idea.angle, 400)}`.replace(/\s*\n\s*/g, " ");
+}
+
+/**
+ * Candidates merged by a merge answer: each group of two or more KNOWN ids
+ * becomes one idea whose item ids are the union of theirs (and the first's
+ * other fields, its title and angle the merge's); a candidate in no group, or
+ * named twice, is kept as it was. Ids the model invented are ignored.
+ */
+export function applyMerges(candidates: ReadonlyMap<string, RawIdea>, answer: unknown): { ideas: RawIdea[]; merged: number } {
+ const a = (answer && typeof answer === "object" ? answer : {}) as Record<string, unknown>;
+ const merges = Array.isArray(a.merges) ? a.merges : [];
+ const used = new Set<string>();
+ const out: RawIdea[] = [];
+ let merged = 0;
+ for (const m of merges) {
+ if (!m || typeof m !== "object") continue;
+ const r = m as Record<string, unknown>;
+ const ids = Array.isArray(r.ids) ? [...new Set(r.ids.filter((x): x is string => typeof x === "string" && candidates.has(x) && !used.has(x)))] : [];
+ if (ids.length < 2) continue;
+ for (const id of ids) used.add(id);
+ const parts = ids.map((id) => candidates.get(id)!);
+ const itemIds = [...new Set(parts.flatMap((p) => (Array.isArray(p.itemIds) ? p.itemIds : [])))];
+ const caveats = [...new Set(parts.flatMap((p) => (Array.isArray(p.caveats) ? p.caveats : [])))];
+ out.push({
+ ...parts[0],
+ workingTitle: str(r.workingTitle, 160) || parts[0]!.workingTitle,
+ angle: str(r.angle, 600) || parts[0]!.angle,
+ itemIds,
+ caveats,
+ sensitive: parts.some((p) => p.sensitive === true),
+ });
+ merged++;
+ }
+ for (const [id, idea] of candidates) if (!used.has(id)) out.push(idea);
+ return { ideas: out, merged };
+}
+
+// ─── Stage 5: check ───
+
+export type IdeaDropCounts = {
+ /** Item ids the model named that no item has. */
+ inventedItemIds: number;
+ /** Ideas left with one moment: not a story. */
+ oneMoment: number;
+ /** Ideas left with no moment: no citation, no key, no finding. */
+ noCitation: number;
+ /** Ideas whose moments are another idea's (the same story key). */
+ sameStory: number;
+};
+
+const CONFIDENCE = ["high", "medium", "low"] as const;
+const VOICE_WORDS: Record<Exclude<ReadingVoice, "own">, string> = {
+ reading: "reading something aloud",
+ clip: "playing a clip",
+ unsure: "possibly not speaking in his own voice",
+};
+
+function linkOf(i: GroupItem, siteOrigin: string): string | undefined {
+ if (siteOrigin) return momentHref(siteOrigin, i.channel, i.recordId || i.video, i.start, i.platform || null);
+ return platformMomentUrl(i.url, (i.platform || null) as Platform | null, i.start) ?? undefined;
+}
+
+/**
+ * Stage 5: the model's ideas made findings. Every idea keeps only item ids that
+ * exist, each at most once; its moments are those items' (quote, times, date —
+ * code's, never the model's); one with fewer than two moments is dropped and
+ * counted (one with none has no key at all); a moment whose voice is not
+ * "own" becomes a caveat; two ideas with the same story key are one (the
+ * first kept). Ordered by confidence, then distinct days, then moments.
+ */
+export function checkIdeas(
+ raw: readonly RawIdea[],
+ items: ReadonlyMap<string, GroupItem>,
+ o: { siteOrigin: string },
+): { ideas: LookoutIdea[]; dropped: IdeaDropCounts } {
+ const dropped: IdeaDropCounts = { inventedItemIds: 0, oneMoment: 0, noCitation: 0, sameStory: 0 };
+ const keyed = new Map<string, LookoutIdea>();
+ for (const r of raw) {
+ const ids = Array.isArray(r.itemIds) ? r.itemIds : [];
+ const found: GroupItem[] = [];
+ const seen = new Set<string>();
+ for (const id of ids) {
+ const it = typeof id === "string" ? items.get(id.trim()) : undefined;
+ if (!it) {
+ dropped.inventedItemIds++;
+ continue;
+ }
+ if (seen.has(it.id)) continue;
+ seen.add(it.id);
+ found.push(it);
+ }
+ found.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0) || (a.channel < b.channel ? -1 : a.channel > b.channel ? 1 : 0) || a.start - b.start);
+ const moments: (LookoutMoment & { voice: ReadingVoice })[] = found.map((i) => ({
+ channel: i.channel,
+ video: i.video,
+ date: i.date,
+ start: i.start,
+ end: i.end,
+ quote: i.quote,
+ ...(linkOf(i, o.siteOrigin) ? { link: linkOf(i, o.siteOrigin) } : {}),
+ ...(i.title ? { title: i.title } : {}),
+ voice: i.voice,
+ }));
+ const key = ideaKey(moments);
+ if (key === null) {
+ dropped.noCitation++;
+ continue;
+ }
+ if (moments.length < MIN_IDEA_MOMENTS) {
+ dropped.oneMoment++;
+ continue;
+ }
+ if (keyed.has(key)) {
+ dropped.sameStory++;
+ continue;
+ }
+ const caveats = (Array.isArray(r.caveats) ? r.caveats : []).map((c) => str(c, 300)).filter(Boolean);
+ moments.forEach((m, n) => {
+ if (m.voice !== "own") caveats.push(`Moment ${n + 1} (${m.date}, ${clockOf(m.start)}): the model thinks he may be ${VOICE_WORDS[m.voice]} — check by ear.`);
+ });
+ const confidence = (CONFIDENCE as readonly string[]).includes(str(r.confidence)) ? (str(r.confidence) as LookoutIdea["confidence"]) : "low";
+ keyed.set(key, {
+ id: "",
+ key,
+ workingTitle: str(r.workingTitle, 160) || "(untitled idea)",
+ angle: str(r.angle, 600),
+ whyNow: str(r.whyNow, 300),
+ kind: str(r.kind, 40),
+ estimatedLengthSec: Math.round(moments.reduce((s, m) => s + Math.max(0, m.end - m.start), 0)),
+ confidence,
+ confidenceWhy: str(r.confidenceWhy, 300),
+ moments: moments.map(({ voice: _voice, ...m }) => m),
+ caveats: [...new Set(caveats)].slice(0, MAX_IDEA_CAVEATS + moments.length),
+ sensitive: r.sensitive === true,
+ });
+ }
+ const rank = (c: LookoutIdea["confidence"]) => CONFIDENCE.indexOf(c);
+ const days = (i: LookoutIdea) => new Set(i.moments.map((m) => m.date)).size;
+ const ideas = [...keyed.values()].sort(
+ (a, b) => rank(a.confidence) - rank(b.confidence) || days(b) - days(a) || b.moments.length - a.moments.length || (a.key < b.key ? -1 : 1),
+ );
+ ideas.forEach((i, n) => (i.id = `idea-${n + 1}`));
+ return { ideas, dropped };
+}
diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts
@@ -17,6 +17,7 @@ import {
readLookoutVerdicts,
sanitizeLookoutVerdicts,
setLookoutVerdict,
+ surfacedIdeas,
writeLookoutRun,
type LookoutIdea,
type LookoutRun,
@@ -31,13 +32,20 @@ async function corpus() {
}
const M = (channel: string, video: string, start: number) => ({ channel, video, start });
+type Mo = ReturnType<typeof M>;
+// The key of moments that have one (every list here cites at least one).
+const K = (ms: Mo[]): string => {
+ const k = ideaKey(ms);
+ assert.ok(k, "a cited idea has a key");
+ return k;
+};
test("an idea's key is its story: order-free, 5-second grain, changed by a moment added", () => {
- const a = ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000)]);
+ const a = K([M("example-news", "v1", 100), M("example-live", "v2", 2000)]);
assert.match(a, /^[0-9a-f]{16}$/);
- assert.equal(ideaKey([M("example-live", "v2", 2001), M("example-news", "v1", 99)]), a);
- assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2010)]), a);
- assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000), M("example-news", "v3", 5)]), a);
+ assert.equal(K([M("example-live", "v2", 2001), M("example-news", "v1", 99)]), a);
+ assert.notEqual(K([M("example-news", "v1", 100), M("example-live", "v2", 2010)]), a);
+ assert.notEqual(K([M("example-news", "v1", 100), M("example-live", "v2", 2000), M("example-news", "v3", 5)]), a);
});
test("the store is a dot path under the corpus, and ids are checked before any path is made", async () => {
@@ -56,8 +64,8 @@ test("the store is a dot path under the corpus, and ids are checked before any p
test("a verdict is set atomically, keeps the note it had, and two at once both land", async () => {
const p = await corpus();
try {
- const k1 = ideaKey([M("example-news", "v1", 10), M("example-news", "v2", 20)]);
- const k2 = ideaKey([M("example-news", "v3", 10), M("example-news", "v4", 20)]);
+ const k1 = K([M("example-news", "v1", 10), M("example-news", "v2", 20)]);
+ const k2 = K([M("example-news", "v3", 10), M("example-news", "v4", 20)]);
const now = new Date("2026-11-11T12:00:00Z");
await setLookoutVerdict(p, "weekly", { key: k1, verdict: "maybe", note: " check the date ", now });
const made = await setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", project: "shorts-2026-11/x", now });
@@ -83,7 +91,7 @@ test("a verdict is set atomically, keeps the note it had, and two at once both l
});
test("a hand-damaged verdicts file reads as what is valid in it", async () => {
- const k = ideaKey([M("a", "b", 0)]);
+ const k = K([M("a", "b", 0)]);
assert.deepEqual(
sanitizeLookoutVerdicts({ ideas: { [k]: { verdict: "make", at: "x" }, bad: { verdict: "make", at: "x" }, [k.replace(/^./, "f")]: { verdict: "meh", at: "x" } } }),
{ version: 1, ideas: { [k]: { verdict: "make", at: "x" } } },
@@ -101,7 +109,8 @@ test("a hand-damaged verdicts file reads as what is valid in it", async () => {
}
});
-function idea(key: string): LookoutIdea {
+function idea(moments: Mo[]): LookoutIdea {
+ const key = K(moments);
return {
id: key.slice(0, 6),
key,
@@ -112,7 +121,7 @@ function idea(key: string): LookoutIdea {
estimatedLengthSec: 60,
confidence: "high",
confidenceWhy: "c",
- moments: [],
+ moments: moments.map((m) => ({ ...m, date: "2026-11-10", end: m.start + 10, quote: "q" })),
caveats: [],
sensitive: false,
};
@@ -145,10 +154,11 @@ test("runs: listed newest first, the latest summarised, unruled ideas counted, s
verdicts: { make: 0, maybe: 0, no: 0 },
});
assert.equal(await measuredSecondsPerCall(p, "weekly"), null);
- const k1 = ideaKey([M("a", "b", 0), M("a", "c", 0)]);
- const k2 = ideaKey([M("a", "d", 0), M("a", "e", 0)]);
- await writeLookoutRun(p, run("20261110T120000Z-aaaa", [idea(k1)], 100, 400));
- await writeLookoutRun(p, run("20261111T120000Z-bbbb", [idea(k1), idea(k2)], 50, 100));
+ const m1 = [M("a", "b", 0), M("a", "c", 0)];
+ const m2 = [M("a", "d", 0), M("a", "e", 0)];
+ const k1 = K(m1);
+ await writeLookoutRun(p, run("20261110T120000Z-aaaa", [idea(m1)], 100, 400));
+ await writeLookoutRun(p, run("20261111T120000Z-bbbb", [idea(m1), idea(m2)], 50, 100));
await setLookoutVerdict(p, "weekly", { key: k1, verdict: "no" });
assert.deepEqual(await listLookoutRunIds(p, "weekly"), ["20261111T120000Z-bbbb", "20261110T120000Z-aaaa"]);
const r = await lookoutReadout(p, "weekly");
@@ -165,3 +175,44 @@ test("runs: listed newest first, the latest summarised, unruled ideas counted, s
await rm(p.transcriptsDir, { recursive: true, force: true });
}
});
+
+test("no citation, no key: a moment-less idea has none, and a stored one is not surfaced, counted or ruled", async () => {
+ assert.equal(ideaKey([]), null);
+ // Two moment-less ideas would otherwise share one key (the empty list's
+ // hash) — and one verdict, and the de-duplication would fold them.
+ const cited = idea([M("a", "b", 0), M("a", "c", 30)]);
+ const uncited: LookoutIdea = { ...cited, id: "bare", key: "FAKE-TEST-VALUE", moments: [] };
+ const forged: LookoutIdea = { ...cited, id: "forged", key: "FAKE-TEST-VALUE" };
+ assert.deepEqual(
+ surfacedIdeas({ ideas: [cited, uncited, forged] }).map((i) => i.id),
+ [cited.id],
+ "an idea with no moment, and one whose key is not its moments', are not findings",
+ );
+ const p = await corpus();
+ try {
+ await writeLookoutRun(p, run("20261111T120000Z-dddd", [cited, uncited, forged]));
+ 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 });
+ }
+});
+
+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
@@ -115,12 +115,40 @@ const grain = (s: number) => Math.round(s / 5) * 5;
* rounded to 5 s). The same moments in any order give the same key; a moment
* nudged by a second or two gives the same key; a moment added or removed
* gives another.
+ *
+ * NO CITATION, NO KEY: an idea with no moment answers null. Every moment-less
+ * idea would hash the same empty list, so one verdict on one of them would
+ * rule them all, and the run's de-duplication by key would fold distinct
+ * ideas into one. Such an idea is not a finding: a run drops it (counted),
+ * and a stored one is not surfaced (`surfacedIdeas`).
*/
-export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video" | "start">[]): string {
+export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video" | "start">[]): string | null {
const parts = [...new Set(moments.map((m) => `${m.channel}/${m.video}@${grain(m.start)}`))].sort();
+ if (parts.length === 0) return null;
return createHash("sha1").update(parts.join("\n")).digest("hex").slice(0, 16);
}
+/**
+ * The ideas of a stored run that are findings: each cites at least one moment
+ * 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[] {
+ 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 ───
export type LookoutRunStatus = "done" | "partial" | "failed";
@@ -147,6 +175,22 @@ 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, 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;
+ videosComplete: number;
+ chunks: number;
+ chunksRead: number;
+ chunksReused: number;
+ chunksFailed: number;
+ items: number;
+ readCalls: number;
+ groupCalls: number;
+ groupCallsFailed?: number;
+ renderWaitSeconds?: number;
+ };
note?: string;
};
@@ -212,7 +256,7 @@ export function summarizeLookoutRun(run: LookoutRun): LookoutRunSummary {
model: run.model,
calls: run.calls,
seconds: run.seconds,
- ideas: run.ideas.length,
+ ideas: surfacedIdeas(run).length,
};
}
@@ -295,6 +339,19 @@ export async function readLookoutVerdicts(
return read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts();
}
+/**
+ * Refused when verdicts.json is there and is not readable JSON (the run reads
+ * its rulings, and a damaged file would read as none) — the file is never
+ * written over or ignored as if it were empty.
+ */
+export async function assertLookoutVerdictsReadable(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<void> {
+ const file = lookoutVerdictsFile(paths, id);
+ const read = await readJsonFile(file);
+ if (!read.ok && read.reason !== "absent") {
+ throw new LookoutStoreError(`${file} is ${read.reason} — mend the file or move it aside first`);
+ }
+}
+
export type SetVerdictInput = {
key: string;
verdict: LookoutVerdictValue;
@@ -361,7 +418,7 @@ export async function lookoutReadout(paths: Pick<Paths, "transcriptsDir">, id: s
latest = await readLookoutRun(paths, id, runId);
if (latest) break;
}
- const unruled = latest ? latest.ideas.filter((i) => !verdicts.ideas[i.key]).length : 0;
+ const unruled = latest ? surfacedIdeas(latest).filter((i) => !verdicts.ideas[i.key]).length : 0;
return {
lastRun: latest ? summarizeLookoutRun(latest) : null,
runs: runIds.length,
diff --git a/common/lib/readingNotes-server.ts b/common/lib/readingNotes-server.ts
@@ -0,0 +1,236 @@
+// A VIDEO'S READING NOTES — `channels/<slug>/data/<id>/reading-notes.json`
+// (lane/lookout slice 2). What a model found reading the video's transcript,
+// chunk by chunk: per chunk a line on what it covers and at most three items,
+// each a verbatim quote CODE located in the cues (start and end stamped from
+// them), a kind, one line of why, whose voice the model thinks it is and the
+// people named. Written by a lookout run (controller/lookoutRun.ts), its ONE
+// writer; read back by later runs, so a recording already read is never read
+// again while its notes are fresh.
+//
+// BESIDE THE CUES because it is derived from them and must go stale with them.
+// 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,
+// and the next run reads only the chunks that are not there.
+//
+// PRIVATE. Never composed, indexed, exported, archived or served by the MCP:
+// every consumer of a video dir reads its files by name (the cues, the
+// metadata, subtitle tracks named transcript.<x>.<y>), and the privacy tests
+// (lane/lookout slice 2, 2b) plant this file and look for it in their output.
+//
+// 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];
+
+/** One located moment the model found. */
+export type ReadingItem = {
+ kind: string;
+ /** Verbatim, as the model copied it and code found it in the cues. */
+ quote: string;
+ /** Seconds, from the cues: the cue the quote starts in, the end of the one it ends in. */
+ start: number;
+ end: number;
+ why: string;
+ /** The model's guess whose words they are — a caveat on a card, never a guarantee. */
+ voice: ReadingVoice;
+ people: string[];
+};
+
+export type ReadingChunk = {
+ /** The chunk's place in the video's chunks (lookoutPlan's chunking), from 0. */
+ index: number;
+ /** Its first and last line's second. */
+ from: number;
+ to: number;
+ covers: string;
+ items: ReadingItem[];
+ /** Items the model gave that code dropped (not found verbatim, too short or long, not a kind). */
+ dropped: number;
+};
+
+export type ReadingProvenance = {
+ model: string;
+ promptVersion: number;
+ chunkChars: number;
+ cues: { size: number; mtimeMs: number };
+};
+
+export type ReadingNotes = {
+ version: number;
+ provenance: ReadingProvenance;
+ /** How many chunks the video has. */
+ chunkCount: number;
+ /** The chunks read, in the order they were. */
+ chunks: ReadingChunk[];
+ /** Every chunk read. */
+ complete: boolean;
+ updatedAt: string;
+};
+
+const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
+const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+
+function coerceProvenance(v: unknown): ReadingProvenance | null {
+ if (!isObj(v) || typeof v.model !== "string" || !isNum(v.promptVersion) || !isNum(v.chunkChars) || !isObj(v.cues)) return null;
+ if (!isNum(v.cues.size) || !isNum(v.cues.mtimeMs)) return null;
+ return { model: v.model, promptVersion: v.promptVersion, chunkChars: v.chunkChars, cues: { size: v.cues.size, mtimeMs: v.cues.mtimeMs } };
+}
+
+function coerceItem(v: unknown): ReadingItem | null {
+ if (!isObj(v) || typeof v.kind !== "string" || typeof v.quote !== "string" || !isNum(v.start) || !isNum(v.end)) return null;
+ const voice = (READING_VOICES as readonly string[]).includes(v.voice as string) ? (v.voice as ReadingVoice) : "unsure";
+ return {
+ kind: v.kind,
+ quote: v.quote,
+ start: v.start,
+ end: v.end,
+ why: typeof v.why === "string" ? v.why : "",
+ voice,
+ people: Array.isArray(v.people) ? v.people.filter((p): p is string => typeof p === "string") : [],
+ };
+}
+
+function coerceChunk(v: unknown): ReadingChunk | null {
+ if (!isObj(v) || !Number.isInteger(v.index) || !isNum(v.from) || !isNum(v.to) || !Array.isArray(v.items)) return null;
+ const items: ReadingItem[] = [];
+ for (const raw of v.items) {
+ const i = coerceItem(raw);
+ if (!i) return null;
+ items.push(i);
+ }
+ return { index: v.index as number, from: v.from, to: v.to, covers: typeof v.covers === "string" ? v.covers : "", items, dropped: isNum(v.dropped) ? v.dropped : 0 };
+}
+
+/** A notes file coerced; null (read again) when any part of it is not notes. */
+export function coerceReadingNotes(value: unknown): ReadingNotes | null {
+ if (!isObj(value) || value.version !== READING_NOTES_VERSION || !Number.isInteger(value.chunkCount) || !Array.isArray(value.chunks)) return null;
+ const provenance = coerceProvenance(value.provenance);
+ if (!provenance) return null;
+ const chunks: ReadingChunk[] = [];
+ const seen = new Set<number>();
+ for (const raw of value.chunks) {
+ const c = coerceChunk(raw);
+ if (!c || seen.has(c.index) || c.index < 0 || c.index >= (value.chunkCount as number)) return null;
+ seen.add(c.index);
+ chunks.push(c);
+ }
+ return {
+ version: READING_NOTES_VERSION,
+ provenance,
+ chunkCount: value.chunkCount as number,
+ chunks,
+ complete: chunks.length === value.chunkCount,
+ updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : "",
+ };
+}
+
+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 (
+ a.model === b.model &&
+ a.promptVersion === b.promptVersion &&
+ a.chunkChars === b.chunkChars &&
+ a.cues.size === b.cues.size &&
+ a.cues.mtimeMs === b.cues.mtimeMs
+ );
+}
+
+/** Empty notes for a video about to be read. */
+export function newReadingNotes(provenance: ReadingProvenance, chunkCount: number, now: Date): ReadingNotes {
+ return { version: READING_NOTES_VERSION, provenance, chunkCount, chunks: [], complete: chunkCount === 0, updatedAt: now.toISOString() };
+}
+
+/** The notes with one more chunk read (replacing one of the same index), sorted by index. */
+export function withReadingChunk(notes: ReadingNotes, chunk: ReadingChunk, now: Date): ReadingNotes {
+ const chunks = [...notes.chunks.filter((c) => c.index !== chunk.index), chunk].sort((a, b) => a.index - b.index);
+ return { ...notes, chunks, complete: chunks.length === notes.chunkCount, updatedAt: now.toISOString() };
+}
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -18,6 +18,7 @@ import "./transcriptPin-server";
import "./wayback-server";
import "./wordTimings-server";
import "./findClipsRecord-server";
+import "./readingNotes-server";
import {
availabilitySidecar,
loadAvailability,
@@ -50,7 +51,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all twenty are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -67,6 +68,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are
"find-clips.json",
"frame-scan.poker.json",
"metadata.history.json",
+ "reading-notes.json",
"transcribe-outcome.json",
"transcript-pin.json",
"wayback.json",
diff --git a/common/publish/source.test.ts b/common/publish/source.test.ts
@@ -612,6 +612,54 @@ test("session links never ship: the trailer goes from every message and file, a
assert.equal(readFileSync(path.join(clone, "rules.md"), "utf8"), "End every commit with:\n\n\nor see [session link removed] for the run.\n");
});
+// A LOOKOUT'S PRIVATE FILES (lane/lookout slice 2, acceptance 2b): a video's
+// reading-notes.json and transcripts/.lookouts/ live in the corpus, which the
+// workspace ignores (`/transcripts`). Planted in the checkout's working tree
+// beside a committed .gitignore saying so, with a marker in each: no
+// published object, tree page, tarball entry or clone carries either.
+test("a lookout's files in the working tree never ship: no object, tree page, tarball entry or clone holds them", async (t) => {
+ if (filterRepoProblem) return t.skip(`git-filter-repo unavailable: ${filterRepoProblem}`);
+ const repo = sourceRepo({ ".gitignore": "/transcripts\n" });
+ const NOTES = "notesmarkerq7x";
+ const RUN = "runmarkerz4k";
+ const plant = (rel: string, text: string) => {
+ mkdirSync(path.dirname(path.join(repo, rel)), { recursive: true });
+ writeFileSync(path.join(repo, rel), text);
+ };
+ plant("transcripts/channels/alpha-news/data/PublicVid01/reading-notes.json", JSON.stringify({ covers: NOTES }));
+ plant("transcripts/.lookouts/example-week/runs/20261111T120000Z-abcd.json", JSON.stringify({ ideas: [{ workingTitle: RUN }] }));
+ plant("transcripts/.lookouts/example-week/verdicts.json", JSON.stringify({ note: RUN }));
+ assert.equal(gitIn(repo, "status", "--porcelain"), "", "the corpus is ignored: nothing to commit");
+ const logs: string[] = [];
+ const o = opts(repo, operatorFiles("", ""), logs);
+ assert.equal(await publishSource(o), 0, logs.join("\n"));
+ const pub = o.publicDir!;
+
+ const mirror = path.join(pub, "source", MIRROR_DIR);
+ const copy = path.join(dir("copy"), "m.git");
+ cpSync(mirror, copy, { recursive: true });
+ const all = execFileSync("git", ["--git-dir", copy, "cat-file", "--batch-all-objects", "--batch"], { maxBuffer: 1 << 26 }).toString("latin1");
+ for (const s of [NOTES, RUN, "reading-notes.json", ".lookouts"]) assert.equal(all.indexOf(s), -1, `an object holds ${s}`);
+ assert.ok(all.includes("/transcripts"), "control: the .gitignore was published");
+
+ // Every published file: the tree pages, the mirror, the downloads.
+ const walk = (d: string): string[] => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]));
+ for (const f of walk(pub)) {
+ assert.ok(!/reading-notes\.json|\.lookouts/.test(path.relative(pub, f)), `published: ${f}`);
+ const text = readFileSync(f).toString("latin1");
+ for (const s of [NOTES, RUN]) assert.ok(!text.includes(s), `${path.relative(pub, f)} holds ${s}`);
+ }
+ // The tarball's entries, by name.
+ const tarball = path.join(pub, "downloads", path.basename(TARBALL_HREF));
+ const entries = execFileSync("tar", ["-tzf", tarball]).toString();
+ assert.match(entries, /\.gitignore/, "control: the tarball lists the tree");
+ assert.doesNotMatch(entries, /transcripts|reading-notes|\.lookouts/);
+
+ const clone = path.join(dir("clone"), "c");
+ execFileSync("git", ["clone", "-q", `file://${mirror}`, clone], { stdio: "pipe" });
+ assert.ok(!existsSync(path.join(clone, "transcripts")), "the clone has no corpus");
+});
+
test("a denied literal no rule removes: refused, nothing written, the report never prints it", async (t) => {
if (filterRepoProblem) return t.skip(`git-filter-repo unavailable: ${filterRepoProblem}`);
const repo = sourceRepo({ "keys.txt": `the ${SECRET} is here\n` });
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [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 (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
@@ -1,8 +1,9 @@
// Run with:
// pnpm -C editor exec tsx --test "app/api/ops/_lookouts.test.ts"
//
-// `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, the only
-// one there is yet), against the route handlers over a temp corpus. Every
+// `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, and the
+// run's refusals — the run itself is common/controller/lookoutRun.test.ts's,
+// on a stub model), against the route handlers over a temp corpus. Every
// channel and lookout here is invented. Never the live editor's settings.
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -12,7 +13,8 @@ import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
const corpus = await setupOpsCorpus(null);
const { GET } = await import("./lookouts/route");
-const { POST } = await import("./lookout-run/route");
+const { POST, GET: GET_RUN } = await import("./lookout-run/route");
+const { writeLookoutRun } = await import("yt-dlp-transcript-common/lib/lookoutStore");
test.after(() => corpus.cleanup());
const LOOKOUTS = {
@@ -74,12 +76,23 @@ test("lookout-run: the dry run lists what would be read, on air dates, and write
assert.deepEqual(await corpus.listJobIds(), []);
});
-test("lookout-run refuses before reading anything: no dryRun, an unknown lookout or key, bad overrides", async () => {
+test("lookout-run refuses before reading anything: lookouts off, an unknown lookout or key, bad overrides", async () => {
await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ // The run (no dryRun) with lookouts off: refused, no job.
const run = await callPost(POST!, { id: "example-week" });
assert.equal(run.status, 400);
- assert.match(String(run.body.error), /dryRun/);
+ assert.match(String(run.body.error), /lookouts are off/);
assert.equal((await callPost(POST!, { id: "example-week", dryRun: false })).status, 400);
+ assert.deepEqual(await corpus.listJobIds(), []);
+ // On with a route this build does not read on: refused, no job.
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { ...LOOKOUTS, enabled: true }, generation: { routes: { lookout: "code" } } });
+ const code = await callPost(POST!, { id: "example-week" });
+ assert.equal(code.status, 400);
+ assert.match(String(code.body.error), /routed to Claude Code/);
+ assert.equal((await callPost(POST!, { id: "example-week", model: "claude-haiku-4-5" })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", maxCalls: 99999 })).status, 400);
+ assert.deepEqual(await corpus.listJobIds(), []);
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
assert.equal((await callPost(POST!, { id: "nope", dryRun: true })).status, 404);
assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, model: "x" })).status, 400);
assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, days: 99 })).status, 400);
@@ -90,3 +103,98 @@ test("lookout-run refuses before reading anything: no dryRun, an unknown lookout
assert.equal(none.status, 400);
assert.match(String(none.body.error), /names no channels/);
});
+
+test("get lookout-run: the latest run whole, or the one named; cancel answers the jobs it cancelled", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ const none = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week");
+ assert.equal(none.status, 200, JSON.stringify(none.body));
+ assert.equal(none.body.run, null);
+ assert.deepEqual(none.body.running, []);
+ const run = (runId: string, title: string) => ({
+ version: 1, lookoutId: "example-week", runId, startedAt: "2026-11-11T12:00:00.000Z", endedAt: "2026-11-11T12:10:00.000Z",
+ status: "done" as const, window: { from: "2026-11-09", to: "2026-11-11", days: 3, timeZone: "UTC" }, model: "stub-local:1b",
+ calls: 3, seconds: 9, selection: null, ideas: [], note: title,
+ });
+ await writeLookoutRun({ transcriptsDir: corpus.transcripts }, run("20261110T120000Z-aaaa", "older"));
+ await writeLookoutRun({ transcriptsDir: corpus.transcripts }, run("20261111T120000Z-bbbb", "newer"));
+ const latest = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week");
+ assert.equal((latest.body.run as { note: string }).note, "newer");
+ const named = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=20261110T120000Z-aaaa");
+ assert.equal((named.body.run as { note: string }).note, "older");
+ assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=20261109T120000Z-cccc")).status, 404);
+ assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=../x")).status, 400);
+ assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=nope")).status, 404);
+ assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run")).status, 400);
+ assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&x=1")).status, 400);
+
+ const cancel = await callPost(POST!, { id: "example-week", cancel: true });
+ assert.equal(cancel.status, 200, JSON.stringify(cancel.body));
+ assert.deepEqual(cancel.body.cancelled, [], "nothing running: nothing cancelled");
+ assert.equal((await callPost(POST!, { id: "example-week", cancel: true, days: 2 })).status, 400);
+ 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,36 +2,65 @@ 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 { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib";
+import { LOOKOUT_MAX_CALLS, cancelLookoutRuns, enqueueLookoutRun, lookoutRunJobs } from "yt-dlp-transcript-common/controller/lookoutRun";
+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";
export const dynamic = "force-dynamic";
// POST { id, dryRun: true, days?, maxVideos?, until? } -> { ok: true, plan }
+// POST { id, days?, maxVideos?, until?, model?, maxCalls? } -> { ok: true, jobId, model }
//
-// What a saved lookout (settings.lookouts.items, SETTINGS.md) would read
-// (common/controller/lookoutPlan.ts): every video of its channels whose AIR
-// date — `release_timestamp`, else `timestamp`, in its time zone — falls in
-// the window; duplicate uploads and a stream's cut-downs folded into one
-// recording; the longest `maxVideos` read and the rest listed as skipped for
-// the cap, with why for every video left out; the reading calls and, once a
-// run has been measured, the seconds they would take. `days` and `maxVideos`
-// override the lookout's for this answer; `until` (YYYY-MM-DD) ends the window
-// on another day than today. A local media library channel, or a slug this
-// archive does not hold, is named in `refused`. Reads text only and writes
-// nothing; synchronous, no job, no model, no network.
+// A saved lookout (settings.lookouts.items, SETTINGS.md).
//
-// Only the dry run exists in this build: without `dryRun: true` the request is
-// refused, never run.
+// DRY RUN — what it would read (common/controller/lookoutPlan.ts): every video
+// of its channels whose AIR date — `release_timestamp`, else `timestamp`, in
+// its time zone — falls in the window; duplicate uploads and a stream's
+// cut-downs folded into one recording; the longest `maxVideos` read and the
+// rest listed as skipped for the cap, with why for every video left out; the
+// reading calls and, once a run has been measured, the seconds they would
+// take. `days` and `maxVideos` override the lookout's for this answer; `until`
+// (YYYY-MM-DD) ends the window on another day than today. A local media
+// library channel, or a slug this archive does not hold, is named in
+// `refused`. Reads text only and writes nothing; synchronous, no job, no
+// model, no network.
+//
+// THE RUN — a `lookout-run` job on `draft:local`
+// (common/controller/lookoutRun.ts): the same plan made at the job's turn, its
+// `read` list read by the local model one chunk a call into each video's
+// private reading notes, the notes grouped into ideas, the run written under
+// transcripts/.lookouts/<id>/runs/. A recording whose notes are fresh is not
+// read again, so a cancelled run's next start continues where it stopped.
+// `model` names a local model (default: the `lookout` route's); `maxCalls`
+// caps the reading calls (default 400; past it the run ends partial). Refused
+// before any job: lookouts off (settings.lookouts.enabled), the route not
+// local, a run of this lookout already queued or running, a damaged
+// verdicts.json. The log ends `@@lookout-run {id, runId, status, …}`.
+//
+// POST { id, cancel: true } -> { ok: true, cancelled: [jobId, …] }: the
+// 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 `[]`.
+//
+// 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; 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;
+
export async function POST(request: Request) {
- return ops(request, ["id", "dryRun", "days", "maxVideos", "until"], async (body) => {
+ return ops(request, ["id", "dryRun", "days", "maxVideos", "until", "model", "maxCalls", "cancel"], async (body) => {
const id = reqString(body, "id");
- if (optBool(body, "dryRun") !== true) {
- throw new OpsInputError(
- 'a lookout run reads with a model, which this build does not do yet — send "dryRun": true to list what it would read',
- );
- }
+ const dryRun = optBool(body, "dryRun") === true;
+ const cancel = optBool(body, "cancel") === true;
const days = optPositiveInt(body, "days");
if (days !== undefined && days > LOOKOUT_MAX_DAYS) throw new OpsInputError(`"days" is at most ${LOOKOUT_MAX_DAYS}`);
const maxVideos = optPositiveInt(body, "maxVideos");
@@ -40,11 +69,27 @@ export async function POST(request: Request) {
}
const until = optString(body, "until");
if (until !== undefined && !isIsoDate(until)) throw new OpsInputError('"until" is a date, YYYY-MM-DD');
+ const model = optString(body, "model");
+ const maxCalls = optPositiveInt(body, "maxCalls");
+ if (maxCalls !== undefined && maxCalls > MAX_CALLS) throw new OpsInputError(`"maxCalls" is at most ${MAX_CALLS}`);
+ if (dryRun && (model !== undefined || maxCalls !== undefined)) throw new OpsInputError('a dry run calls no model: "model" and "maxCalls" are the run\'s');
+ 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 (!dryRun) {
+ const out = await enqueueLookoutRun({ id, days, maxVideos, until, model, maxCalls }, { paths: getPaths() });
+ if (!out.result.ok || !("model" in out)) return jobResponse(out.result);
+ void out.result.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: out.result.jobId, model: out.model });
+ }
try {
const plan = await planLookout(getPaths(), item, { days, maxVideos, until });
return NextResponse.json({ ok: true, plan });
@@ -54,3 +99,33 @@ export async function POST(request: Request) {
}
});
}
+
+export async function GET(request: Request) {
+ return readRoute(request, ["id", "run"], async (q) => {
+ const id = q.get("id");
+ if (!id) return opsFail('"id" names the lookout: ?id=<lookout>');
+ const lookouts = getSettings().lookouts;
+ if (!lookoutById(lookouts, id)) {
+ return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404);
+ }
+ const paths = getPaths();
+ const asked = q.get("run");
+ if (asked !== null && !LOOKOUT_RUN_ID_RE.test(asked)) return opsFail(`"${asked}" is not a lookout run id`);
+ let run = null;
+ if (asked !== null) {
+ run = await readLookoutRun(paths, id, asked);
+ if (!run) return opsFail(`lookout "${id}" has no run "${asked}"`, 404);
+ } else {
+ for (const runId of await listLookoutRunIds(paths, id)) {
+ run = await readLookoutRun(paths, id, runId);
+ if (run) break;
+ }
+ }
+ // 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) };
+ });
+}
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -154,6 +154,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
"video-assist": "api",
// Claim groups for a cut (lane L4): api only in the api preset.
"propose-groups": "api",
+ // A lookout's run (lane/lookout slice 2): routed like every task.
+ lookout: "api",
},
},
},
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -50,7 +50,8 @@ export type GenerationUsageDay = { day: string; usd: number; jobs: number; daily
// The tasks `generate` takes: the policy's (research included, S11).
// Not `frames`: a frame scan is `frame-scan`, not a generation of an article.
-export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS.filter((t) => t !== "frames"), "research"])];
+// A lookout run is `pnpm ops lookout-run`, not a generation this tool starts.
+export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS.filter((t) => t !== "frames" && t !== "lookout"), "research"])];
const ARTICLE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
const JOB_RE = /^[A-Za-z0-9_-]+$/;
diff --git a/mcp/src/lookoutPrivacy.test.ts b/mcp/src/lookoutPrivacy.test.ts
@@ -0,0 +1,118 @@
+// A LOOKOUT'S PRIVATE FILES NEVER REACH THE MCP (lane/lookout slice 2,
+// acceptance 2b). The MCP reads a COMPOSED site (`--local`, TRANSCRIPT_LOCAL_DIR,
+// export/public) or a published one, never the corpus. So the corpus is made
+// for real — a video with a public cue, its `reading-notes.json` beside it and
+// a run, a trace and verdicts under `transcripts/.lookouts/`, each with a
+// marker — indexed and composed with the real build, and every read-only
+// corpus tool is asked over the composed dir: none answers with a marker or
+// the private files' names, and each does answer with the video's cue (the
+// control). common/bin/lookoutPrivacy.test.ts holds the index, compose,
+// archive and editor-reader halves.
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "mcp-lookout-privacy-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+});
+delete process.env.ARCHILYZER_INDEX_ALLOW_HELD;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { buildIndex } = await import("yt-dlp-transcript-common/controller/buildIndex");
+const { main: composeSite } = await import("yt-dlp-transcript-common/bin/compose-site");
+const { READING_NOTES_FILENAME } = await import("yt-dlp-transcript-common/lib/readingNotes-server");
+const { LOOKOUTS_DIRNAME } = await import("yt-dlp-transcript-common/lib/lookoutStore");
+const { createCorpusTools } = await import("./callTool");
+
+const paths = getPaths();
+const CH = "alpha-news";
+const VIDEO = "PublicVid01";
+const PUBLIC_CUE = "an ordinary public cue about the weather";
+const MARKS = ["notesmarkerq7x", "runmarkerz4k", "verdictmarkerw2p", "tracemarkerj9m"];
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+
+writeJson(paths.settingsFile, {});
+writeJson(path.join(paths.channelsDir, CH, "config.json"), { handling: "youtube", name: "Alpha News", url: "https://www.youtube.com/@alpha-news/videos" });
+const video = path.join(paths.channelsDir, CH, "data", VIDEO);
+writeJson(path.join(video, "metadata.info.json"), {
+ id: VIDEO, title: "A public video", upload_date: "20261103", timestamp: 1793750000, duration: 120,
+ webpage_url: `https://www.youtube.com/watch?v=${VIDEO}`, extractor_key: "Youtube",
+});
+writeFileSync(path.join(video, "transcript.en.vtt"), `WEBVTT\n\n00:00:01.000 --> 00:00:04.000\n${PUBLIC_CUE}\n`);
+writeJson(path.join(video, READING_NOTES_FILENAME), {
+ version: 1,
+ provenance: { model: "stub-local:1b", promptVersion: 1, chunkChars: 7000, cues: { size: 1, mtimeMs: 1 } },
+ chunkCount: 1,
+ chunks: [{ index: 0, from: 1, to: 1, covers: `weather ${MARKS[0]}`, items: [{ kind: "claim", quote: `weather ${MARKS[0]}`, start: 1, end: 4, why: "why", voice: "own", people: [] }], dropped: 0 }],
+ complete: true,
+ updatedAt: "2026-11-11T12:00:00.000Z",
+});
+const store = path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME, "example-week");
+writeJson(path.join(store, "runs", "20261111T120000Z-abcd.json"), { version: 1, lookoutId: "example-week", ideas: [{ workingTitle: `weather ${MARKS[1]}` }] });
+writeFileSync(path.join(store, "runs", "20261111T120000Z-abcd.trace.jsonl"), `${JSON.stringify({ t: `weather ${MARKS[3]}` })}\n`);
+writeJson(path.join(store, "verdicts.json"), { version: 1, ideas: { "FAKE-TEST-VALUE": { verdict: "make", at: "x", note: `weather ${MARKS[2]}` } } });
+writeJson(path.join(paths.sitesDir, "pub", "site.json"), {
+ siteId: "pub", siteTitle: "pub", siteDescription: "fixture", headerTitle: "pub", homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: [{ slug: CH, groupId: "default" }],
+ siteUrl: "https://pub.example.test", archives: false,
+});
+
+test("every read-only corpus tool over the composed site: the cue, never a lookout's file", async () => {
+ await buildIndex({ paths, onLog: () => {} });
+ const log = console.log;
+ console.log = () => {};
+ try {
+ await composeSite({ siteId: "pub", paths });
+ } finally {
+ console.log = log;
+ }
+ const corpus = await createCorpusTools({ source: `local:${paths.exportPublicDir}` });
+ try {
+ const answers: Record<string, string> = {
+ list_channels: await corpus.call("list_channels"),
+ search_cue: await corpus.call("search_transcripts", { query: "weather" }),
+ enumerate: await corpus.call("enumerate_matches", { query: "weather" }),
+ get_transcript: await corpus.call("get_transcript", { video_id: VIDEO, channel: CH }),
+ get_transcripts: await corpus.call("get_transcripts", { video_ids: [VIDEO] }),
+ get_video_metadata: await corpus.call("get_video_metadata", { video_id: VIDEO }),
+ };
+ // A search for each marker finds nothing to quote.
+ for (const mark of MARKS) answers[`search ${mark}`] = await corpus.call("search_transcripts", { query: mark }).catch((e: Error) => e.message);
+ assert.match(answers.get_transcript!, new RegExp(PUBLIC_CUE), "control: the video's cue is read");
+ assert.match(answers.search_cue!, new RegExp(VIDEO), "control: the cue is searchable");
+ for (const [tool, text] of Object.entries(answers)) {
+ if (tool.startsWith("search ")) {
+ // The search for a marker may echo its query; it finds no video.
+ assert.ok(!text.includes(VIDEO), `${tool}: a hit`);
+ } else {
+ for (const mark of MARKS) assert.ok(!text.includes(mark), `${tool}: answers with ${mark}`);
+ }
+ for (const name of [READING_NOTES_FILENAME, LOOKOUTS_DIRNAME]) assert.ok(!text.includes(name), `${tool}: names ${name}`);
+ }
+ } finally {
+ await corpus.close();
+ }
+});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -214,6 +214,9 @@
// pnpm ops get lookouts
// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'
// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'
+// pnpm ops lookout-run --json '{"id":"example-week"}' --wait
+// pnpm ops lookout-run --json '{"id":"example-week","cancel":true}'
+// pnpm ops get lookout-run example-week [--run 20261111T120000Z-1a2b]
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -324,6 +327,14 @@ const GETTERS = {
// The saved lookouts (settings.lookouts) and what the store holds for each:
// the latest run, how many of its ideas wait for a verdict.
lookouts: (id) => (id ? `/api/ops/lookouts?id=${encodeURIComponent(id)}` : "/api/ops/lookouts"),
+ // One lookout's latest run (or the one --run names) whole — its window, the
+ // selection it read, calls, seconds, ideas, what was dropped — and its run
+ // queued or running now.
+ "lookout-run": (id, { jobs }) => {
+ const q = new URLSearchParams({ id });
+ if (jobs.run) q.set("run", jobs.run);
+ return `/api/ops/lookout-run?${q.toString()}`;
+ },
// What a channel holds, by date, and its gaps (release 19 A9): each video
// dated by its recorded date when the channel has a title rule, else upload.
coverage: (slug) => `/api/ops/coverage?slug=${encodeURIComponent(slug)}`,
@@ -383,6 +394,7 @@ const GET_ARG_OPTIONAL = new Set([
// The flags each noun takes beyond the shared ones; any other is refused.
const GET_FLAGS = {
transcript: ["slug"],
+ "lookout-run": ["run"],
channel: ["counts", "leads", "limit"],
job: ["tail"],
jobs: ["active", "failed", "kind", "slug", "limit"],
@@ -725,8 +737,8 @@ const ACTIONS = [
"x-run",
// What a saved lookout would read ({id, dryRun: true, days?, maxVideos?,
// until?}): its channels' videos by air date, duplicate uploads and stream
- // cut-downs folded in, the cap. Synchronous; no job, nothing written. Only
- // the dry run exists yet.
+ // cut-downs folded in, the cap — synchronous, nothing written; or, without
+ // dryRun, the run itself as a lookout-run job on draft:local.
"lookout-run",
];
@@ -766,6 +778,9 @@ export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
export const LIVE_CLIP_RESULT_MARKER = "@@live-clip ";
// The same for an X run (X_RUN_RESULT_MARKER in common/controller/xRun.ts).
export const X_RUN_RESULT_MARKER = "@@x-run ";
+// The same for a lookout run (LOOKOUT_RUN_RESULT_MARKER in
+// common/controller/lookoutRun.ts).
+export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run ";
// The provenance a tag write from this CLI carries. Everything else ignores it.
function agentSource() {
@@ -826,8 +841,8 @@ export function parseArgs(argv) {
} else if (arg === "--active" || arg === "--failed") {
jobs[arg.slice(2)] = true;
used.add(arg.slice(2));
- } else if (/^--(kind|slug|limit)(=|$)/.test(arg)) {
- const [, key, eq] = /^--(kind|slug|limit)(=?)/.exec(arg);
+ } else if (/^--(kind|slug|limit|run)(=|$)/.test(arg)) {
+ const [, key, eq] = /^--(kind|slug|limit|run)(=?)/.exec(arg);
const raw = eq ? arg.slice(key.length + 3) : argv[++i];
if (raw === undefined || raw === "") {
return { error: `--${key} needs a value` };
@@ -1015,6 +1030,7 @@ export function parseArgs(argv) {
...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}),
...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}),
...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}),
+ ...(action === "lookout-run" ? { resultMarker: LOOKOUT_RUN_RESULT_MARKER } : {}),
...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}),
...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}),
@@ -1108,6 +1124,7 @@ export function usage() {
" pnpm ops get cleanup <slug>",
" pnpm ops get speakers",
" pnpm ops get lookouts [<id>]",
+ " pnpm ops get lookout-run <id> [--run <runId>]",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
@@ -1208,6 +1225,11 @@ export function usage() {
" <id>/), the latest run (when, window, model, calls, seconds, ideas), how",
" many of that run's ideas have no verdict yet, and the verdicts given.",
" Reads settings and the store only, never a channel's videos.",
+ "get lookout-run <id> [--run <runId>] is one lookout's latest run (or the",
+ " one named), whole: its window, the selection it read, calls, seconds,",
+ " the reading counts (read, reused from fresh notes, failed), its ideas and",
+ " what was dropped and why; null before the first. With it, the lookout's",
+ " run queued or running now ({jobId, status}).",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1297,19 +1319,33 @@ export function usage() {
' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,',
' start a run) | "pause" (hold; stays armed).',
"",
- 'lookout-run lists what a saved lookout (settings.lookouts) would read:',
- ' {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}.',
- " Every video of its channels whose AIR date (release_timestamp, else",
- " timestamp, in the lookout's timeZone — not the UTC upload_date) falls in",
- " the window; a duplicate upload of one recording, and a stream's cut-down,",
- " folded into it (each named, with why and its score); the longest",
- " maxVideos recordings read and the rest listed as skipped for the cap;",
- " under minSeconds and no transcript yet listed too. A local media library",
- " channel or a slug this archive does not hold is named in \"refused\".",
- " Answers {plan: {window, counts, read, skipped, refused, estimate}}:",
- " readCalls is one per transcript chunk, priced once a run has been",
- " measured. Synchronous, reads text only, writes nothing; without",
- ' "dryRun": true it is refused (the model run is not in this build).',
+ 'lookout-run runs a saved lookout (settings.lookouts), or lists what it',
+ ' would read. {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?:',
+ ' "YYYY-MM-DD"} is the list: every video of its channels whose AIR date',
+ " (release_timestamp, else timestamp, in the lookout's timeZone — not the",
+ " UTC upload_date) falls in the window; a duplicate upload of one",
+ " recording, and a stream's cut-down, folded into it (each named, with why",
+ " and its score); the longest maxVideos recordings read and the rest listed",
+ " as skipped for the cap; under minSeconds and no transcript yet listed",
+ " too. A local media library channel or a slug this archive does not hold",
+ ' is named in "refused". Answers {plan: {window, counts, read, skipped,',
+ " refused, estimate}}: readCalls is one per transcript chunk, priced once a",
+ " run has been measured. Synchronous, reads text only, writes nothing.",
+ ' Without "dryRun" it is the RUN, a lookout-run job on draft:local:',
+ ' {"id", "days"?, "maxVideos"?, "until"?, "model"?, "maxCalls"?}. The',
+ " same list, made at the job's turn, read by the local model one chunk a",
+ " call (every call through the GPU arbiter, after render mode, in the",
+ " job's model log) into each video's private reading-notes.json; the notes",
+ " grouped into ideas of at least two located, dated moments; the run",
+ " written to transcripts/.lookouts/<id>/runs/. A video whose notes are",
+ " fresh is not read again, so a cancelled run's next start continues where",
+ " it stopped. maxCalls caps the reading calls (default 400; past it the",
+ " run ends partial). Refused with lookouts off (settings.lookouts.enabled),",
+ " the lookout route not local (model names a local one), a run of it",
+ " already queued or running, a damaged verdicts.json, or under 3 GB of",
+ " free memory at its turn. --wait prints the log's @@lookout-run line.",
+ ' {"id", "cancel": true} cancels its queued or running run (answers the',
+ " job ids; the notes read so far are kept).",
"",
'render-mode gives a render the operator is waiting for the machine:',
' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -7,6 +7,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
FIND_CLIPS_RESULT_MARKER,
+ LOOKOUT_RUN_RESULT_MARKER,
REMOTE_LISTING_RESULT_MARKER,
TRANSCRIBE_RESULT_MARKER,
TTS_RESULT_MARKER,
@@ -638,6 +639,27 @@ test("capture-posts is a POST to its route, named in the usage", () => {
// Lane x-console: the X run is a POST to its route whose --wait prints the
// run's result line; `get x-run` reads the console, the latest run or one named.
+// A lookout (lane/lookout slice 2): run now and cancel are POSTs to
+// lookout-run, the run's result printed by --wait; get lookout-run reads the
+// latest run or the one --run names.
+test("lookout-run: run, dry run and cancel are POSTs, --wait prints the run's line; get lookout-run reads a run", () => {
+ const run = parseArgs(["lookout-run", "--json", '{"id":"example-week"}', "--wait"]);
+ assert.equal(run.method, "POST");
+ assert.equal(run.path, "/api/ops/lookout-run");
+ assert.deepEqual(run.body, { id: "example-week" });
+ assert.equal(run.resultMarker, LOOKOUT_RUN_RESULT_MARKER);
+ assert.equal(LOOKOUT_RUN_RESULT_MARKER, "@@lookout-run ");
+ assert.deepEqual(parseArgs(["lookout-run", "--json", '{"id":"example-week","cancel":true}']).body, { id: "example-week", cancel: true });
+ assert.equal(parseArgs(["get", "lookout-run", "example-week"]).path, "/api/ops/lookout-run?id=example-week");
+ assert.equal(
+ parseArgs(["get", "lookout-run", "example-week", "--run", "20261111T120000Z-1a2b"]).path,
+ "/api/ops/lookout-run?id=example-week&run=20261111T120000Z-1a2b",
+ );
+ assert.match(String(parseArgs(["get", "lookout-run"]).error), /lookout-run/);
+ assert.match(String(parseArgs(["get", "lookouts", "--run", "x"]).error), /--run/);
+ assert.match(usage(), /get lookout-run <id> \[--run <runId>\]/);
+});
+
test("x-run is a POST to its route with a result marker; get x-run reads the console", () => {
const p = parseArgs(["x-run", "--json", '{"channels":["a-x","b-x"],"limit":50}', "--wait"]);
assert.equal(p.method, "POST");
diff --git a/settings.json.example b/settings.json.example
@@ -300,7 +300,8 @@
"frames": "api",
"clips-suggest": "local",
"video-assist": "local",
- "propose-groups": "local"
+ "propose-groups": "local",
+ "lookout": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs
@@ -31,6 +31,7 @@ const TASK_WORD = {
"clips-suggest": "clip labels",
"video-assist": "the video assistant",
"propose-groups": "claim groups for a cut",
+ lookout: "lookouts",
};
/**