Archilyzer · Source

archilyzer

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

commit 6dee892f51804a7d0a2fa621c364fed2a2344504
parent 207ad6cd2e21d922c7ca60fb1f93d0c775c710a1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 11:08:38 -0500

lookouts: the run -- the local model reads the dry run's list into private reading notes and groups them into ideas; a stopped run continues where it stopped

lookout-run without dryRun is a `lookout-run` job on draft:local
(controller/lookoutRun.ts). At its turn it makes planLookout's plan and
reads exactly its `read` list, chunked as the plan counted
(cueLines/chunksOf, now exported) -- no second enumeration.

- Stage 3, read: one call per chunk (lib/lookoutRead.ts READ_SYSTEM, a
  fixed generic prompt); every quote located verbatim in its chunk by
  code or dropped and counted; start and end from the cues. Each video's
  items go to data/<id>/reading-notes.json (lib/readingNotes-server.ts,
  a sidecar, the run its one writer), written after every call. Fresh
  iff the model, prompt version, chunk size and cues file match: a
  complete fresh file is not read again, a partial one is read from the
  chunks it lacks -- so a cancelled or interrupted run's next start
  re-reads nothing already judged.
- Stage 4, group: the items as numbered lines, at most 6,000 characters
  a call in date order, the lookout's prompt added here only; more than
  one call -> one merge call over the candidates (code unions their ids).
- Stage 5, check: ids that exist, at least two moments, a story key; an
  invented id, a one-moment and a moment-less idea dropped and counted; a
  voice other than his own a caveat; links on siteOrigin or the source.

Every call through the generation route's ollama (the GPU arbiter's
fetch), recorded in the job's model log with its CallSlot decision and
items; render mode read before every call and waited out with one line;
no call with an aborted signal; the model unloaded at the end; refused
under 3 GB MemAvailable at its turn, with lookouts off, off the local
route, with a run of the lookout already live, or a damaged
verdicts.json. A new generation task `lookout` (local in balanced and
local, code in code, api in api; not a report-draft or MCP generate
task). Job kind `lookout-run`: needsText. --wait prints @@lookout-run.
COMMANDS.md, SETTINGS.md and settings.json.example regenerated.

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

Diffstat:
MCOMMANDS.md | 2+-
MSETTINGS.md | 4+++-
Mcommon/controller/lookoutPlan.ts | 22+++++++++++++++++-----
Acommon/controller/lookoutRun.test.ts | 465+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/lookoutRun.ts | 552+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/reportDraft.ts | 5++++-
Mcommon/jobs/jobKinds.ts | 18++++++++++++++++++
Mcommon/lib/generationSettings.ts | 17++++++++++++-----
Acommon/lib/lookoutRead.ts | 461+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/lookoutStore.ts | 27+++++++++++++++++++++++++++
Acommon/lib/readingNotes-server.ts | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/sidecar-server.test.ts | 4+++-
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/_lookouts.test.ts | 20++++++++++++++++----
Meditor/app/api/ops/lookout-run/route.ts | 61+++++++++++++++++++++++++++++++++++++++++--------------------
Mmcp/src/generation.ts | 3++-
Mscripts/archilyzer-ops.mjs | 47++++++++++++++++++++++++++++++++---------------
Msettings.json.example | 3++-
Mumtool/lib/create/policy.mjs | 1+
19 files changed, 1817 insertions(+), 55 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/&lt;id&gt;/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": "&lt;run id&gt;"} 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/&lt;id&gt;/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. | `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` | ### Usage, flags and environment 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/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,465 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { 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"), +}); +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 } = await import("../lib/readingNotes-server"); +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 notesOf = (channel: string, dir: string) => readingNotesSidecar.load(path.join(paths.channelsDir, channel, "data", dir)); +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("another model's notes are stale: read again from the start", async () => { + await clearNotes(); + const s1 = stub(); + await L.runLookout(paths, ITEM, opts(new AbortController().signal).o, { ask: s1.ask, renderHeld: noRender }); + const s2 = stub(); + const b = opts(new AbortController().signal, { model: "another-local:2b" }); + const { run } = await L.runLookout(paths, ITEM, b.o, { ask: s2.ask, renderHeld: noRender }); + assert.equal(run.reading?.chunksReused, 0); + assert.equal(s2.asked.filter((x) => x.phase === "reading").length, s1.asked.filter((x) => x.phase === "reading").length); + assert.ok(b.lines.some((l) => /reading notes are stale/.test(l))); + assert.equal((await notesOf("alpha-news", "News0000001"))?.provenance.model, "another-local:2b"); +}); + +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 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,552 @@ +// 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. +// +// 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 { + newReadingNotes, + readingNotesSidecar, + sameReadingProvenance, + 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; + +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; + 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 seconds = 0; + let failedInRow = 0; + let stopped: LookoutRun["stopped"]; + const dropped: Record<string, number> = {}; + const count = (k: string, n = 1) => { + if (n) dropped[k] = (dropped[k] ?? 0) + n; + }; + const reading = { videos: plan.read.length, videosComplete: 0, chunks: 0, chunksRead: 0, chunksReused: 0, chunksFailed: 0, items: 0, readCalls: 0, groupCalls: 0 }; + const sleep = deps.sleep ?? abortableSleep; + const renderHeld = deps.renderHeld ?? renderModeHeld; + const progressTotal = Math.max(1, plan.estimate.readCalls); + + // Before every call: not cancelled; render mode, waited out with one line. + const mayCall = async (): Promise<boolean> => { + if (signal.aborted) return false; + let why = renderHeld(); + if (why) { + onLog(`render mode holds the machine (${why}) — waiting before the next model call`); + while (why && !signal.aborted) { + await sleep(deps.renderPollMs ?? LOOKOUT_RENDER_POLL_MS, signal); + why = renderHeld(); + } + 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"; + return null; + } + }; + + // ─── Stage 3: read ─── + const notesOf = new Map<string, ReadingNotes>(); + for (const r of plan.read) { + if (stopped || 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 had = await readingNotesSidecar.load(dir); + let notes: ReadingNotes; + if (had && had.chunkCount === chunks.length && sameReadingProvenance(had.provenance, prov)) { + notes = had; + reading.chunksReused += had.chunks.length; + if (had.chunks.length && !had.complete) onLog(`${key}: resuming its reading notes at ${had.chunks.length} of ${chunks.length} chunk(s)`); + } else { + if (had) onLog(`${key}: its reading notes are stale (another model, prompt or transcript) — read again`); + notes = newReadingNotes(prov, chunks.length, now()); + } + notesOf.set(key, notes); + if (notes.complete) { + reading.videosComplete++; + 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"); + notes = withReadingChunk(notes, checked.chunk, now()); + notesOf.set(key, notes); + // After every call: a run stopped anywhere keeps what it read. + await readingNotesSidecar.write(dir, notes); + reading.chunksRead++; + } + if (notes.complete) reading.videosComplete++; + } + 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(`the model failed ${LOOKOUT_MAX_FAILED_IN_A_ROW} times in a row — 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) 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; + } + } + 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; + + const status: LookoutRun["status"] = stopped === "failed" ? "failed" : stopped || reading.chunksFailed ? "partial" : "done"; + 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, + ...(stopped === "cap" ? { note: `stopped at the per-run cap of ${maxCalls} reading calls; the next run continues from the notes` } : {}), + ...(stopped === "cancelled" ? { note: "cancelled; the next run continues from the reading notes" } : {}), + }; + 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()); +} + +/** 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})`); + const paths = deps.paths; + const 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); + 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.ts b/common/lib/lookoutRead.ts @@ -0,0 +1,461 @@ +// 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 (sweep-pipeline's `locate`, the words verbatim and contiguous +// after normalising case and punctuation); one that is not there — a +// paraphrase — is dropped and counted. Start and end come from the cues, +// never from the model. +// - 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, locate, 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) : ""); + +// The end of the cue the quote ends in: cues from the one the quote starts in +// until their joined text holds the quote. +function endOf(quote: string, start: number, cues: readonly Cue[]): number { + const q = norm(quote); + let i = cues.findIndex((c) => Math.floor(c.start) === start && c.text.trim()); + if (i < 0) i = cues.findIndex((c) => c.start >= start); + if (i < 0) return start; + let text = ""; + for (let j = i; j < cues.length && j < i + 60; j++) { + const n = norm(cues[j]!.text); + if (!n) continue; + text = text ? `${text} ${n}` : n; + if (` ${text} `.includes(` ${q} `)) return Math.round(cues[j]!.end * 100) / 100; + } + return Math.round((cues[i]!.end ?? start) * 100) / 100; +} + +/** + * 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>(); + 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 = words(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 start = locate(quote, chunk); + if (start === null) { + dropped.push({ quote, reason: "not-in-transcript" }); + continue; + } + const key = `${start}\n${norm(quote)}`; + if (seen.has(key)) { + dropped.push({ quote, reason: "repeated" }); + continue; + } + seen.add(key); + const voice = (READING_VOICES as readonly string[]).includes(str(r.voice)) ? (str(r.voice) as ReadingVoice) : "unsure"; + items.push({ + kind: str(r.kind), + quote, + start, + end: endOf(quote, start, cues), + 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.ts b/common/lib/lookoutStore.ts @@ -166,6 +166,20 @@ export type LookoutRun = { ideas: LookoutIdea[]; /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */ dropped?: Record<string, number>; + /** Why a run that is not `done` stopped: cancelled, the per-run call cap, or the model failing. */ + stopped?: "cancelled" | "cap" | "failed"; + /** 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; + }; note?: string; }; @@ -314,6 +328,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; diff --git a/common/lib/readingNotes-server.ts b/common/lib/readingNotes-server.ts @@ -0,0 +1,159 @@ +// 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. +// FRESH iff its provenance is today's: the same model, the same reading +// prompt (`promptVersion`), the same chunk size, and the same cues file (size +// and mtime) — the digest's rule. A stale or unreadable file is read again +// from the start and written over: it is a cache of model calls, never the +// operator's data. +// +// 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 { sidecar, sidecarField } from "./sidecar-server"; + +export const READING_NOTES_FILENAME = "reading-notes.json"; +export const READING_NOTES_VERSION = 1; + +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 const readingNotesSidecar = sidecar(READING_NOTES_FILENAME, sidecarField(coerceReadingNotes), { 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/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Lookouts run: the local model reads what the dry run lists and answers with video ideas, and a stopped run continues where it stopped.** `pnpm ops lookout-run --json '{"id":"…"}'` (no `dryRun`) is a `lookout-run` job on the local model's queue: it makes the same list the dry run shows at its turn and reads exactly that, one call per transcript chunk. What the model finds is kept in a private `reading-notes.json` beside each video's transcript, written after every call, so a cancelled or interrupted run's next start reads only what is left, and a week already read is not read again. Every quote is found word for word in the transcript by code, or dropped; the notes are grouped into ideas of at least two dated moments, with an idea that cites an invented moment, only one, or none dropped and counted; a moment the model thinks is read aloud or a played clip becomes a caveat to check by ear. The calls wait for transcription and for render mode, are in the job's Model log, and the model is unloaded at the end; the run does not start under 3 GB of free memory, nor while lookouts are off (`settings.lookouts.enabled`, off by default). It runs on the local model only for now (a new `lookout` task in `settings.generation.routes`: local in the balanced and local presets). The run, its ideas and what was dropped are written to `transcripts/.lookouts/<id>/runs/`, never published. - **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"; @@ -74,12 +75,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); diff --git a/editor/app/api/ops/lookout-run/route.ts b/editor/app/api/ops/lookout-run/route.ts @@ -4,34 +4,45 @@ 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 { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan"; -import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib"; +import { LOOKOUT_MAX_CALLS, enqueueLookoutRun } from "yt-dlp-transcript-common/controller/lookoutRun"; +import { OpsInputError, jobResponse, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib"; 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, …}`. +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"], 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 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 +51,21 @@ 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'); const lookouts = getSettings().lookouts; const item = lookoutById(lookouts, 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 }); 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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -214,6 +214,7 @@ // 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 // // --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 @@ -725,8 +726,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 +767,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() { @@ -1015,6 +1019,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 } : {}), @@ -1297,19 +1302,31 @@ 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.", "", '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/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", }; /**