// THE LOOKOUT STORE — a lookout's runs, ideas and verdicts on disk, and the one // writer of each (lane/lookout). SERVER-ONLY (node:fs). // // transcripts/.lookouts//runs/.json one run: window, selection, calls, ideas // transcripts/.lookouts//runs/.trace.jsonl its trace (slice 2) // transcripts/.lookouts//verdicts.json the operator's Make / Maybe / No per idea // // A DOT PATH, like the corpus root's other runtime state (.x-runs, .jobs, // .speakers-run.json): it is never a channel, a site or a report, so nothing // that composes, indexes, exports or serves the corpus walks into it, and the // corpus repo's own .gitignore question does not arise for a name nobody // enumerates. Nothing here is published (the lane's rule): a run's ideas carry // quotes from transcripts and the operator's notes on them. // // ONE WRITER PER FILE, atomic (jsonFile-server), in the manner of // curatedTagsStore: a verdict is a read-modify-write of the whole // verdicts.json under the file's lock, so two marks never interleave. A run // file is written whole by the job that made it and never edited after. // // A VERDICT IS KEYED BY THE IDEA'S STORY, not by the run: `ideaKey` hashes the // idea's moments (channel, video, start rounded to 5 s), so the same story // found by a later run keeps the verdict it was given. import { createHash, randomBytes } from "node:crypto"; import { readdir } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "./paths"; import { LOOKOUT_ID_RE } from "./lookoutSettings"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; export const LOOKOUTS_DIRNAME = ".lookouts"; export const LOOKOUT_VERDICTS_FILENAME = "verdicts.json"; export const LOOKOUT_STORE_VERSION = 1; // `20261111T174500Z-1a2b`: sorts by time, safe as a file name. export const LOOKOUT_RUN_ID_RE = /^\d{8}T\d{6}Z-[0-9a-f]{4}$/; export class LookoutStoreError extends Error {} function assertLookoutId(id: string): void { if (!LOOKOUT_ID_RE.test(id)) throw new LookoutStoreError(`"${id}" is not a lookout id (a lowercase slug)`); } function assertRunId(runId: string): void { if (!LOOKOUT_RUN_ID_RE.test(runId)) throw new LookoutStoreError(`"${runId}" is not a lookout run id`); } export function lookoutsRoot(paths: Pick): string { return path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME); } export function lookoutDir(paths: Pick, id: string): string { assertLookoutId(id); return path.join(lookoutsRoot(paths), id); } export function lookoutRunFile(paths: Pick, id: string, runId: string): string { assertRunId(runId); return path.join(lookoutDir(paths, id), "runs", `${runId}.json`); } export function lookoutTraceFile(paths: Pick, id: string, runId: string): string { assertRunId(runId); return path.join(lookoutDir(paths, id), "runs", `${runId}.trace.jsonl`); } export function lookoutVerdictsFile(paths: Pick, id: string): string { return path.join(lookoutDir(paths, id), LOOKOUT_VERDICTS_FILENAME); } export function newLookoutRunId(now: Date = new Date()): string { const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); return `${stamp}-${randomBytes(2).toString("hex")}`; } // ─── Ideas ─── /** One dated, verbatim moment of an idea, located by code in its video's cues. */ export type LookoutMoment = { channel: string; /** The video's directory under `channels//data/`. */ video: string; /** Its air date, YYYY-MM-DD in the lookout's zone. */ date: string; start: number; end: number; quote: string; link?: string; title?: string; }; export type LookoutVerdictValue = "make" | "maybe" | "no"; /** An idea as a run stores it: the pilot's shape plus `key` and `sensitive`. */ export type LookoutIdea = { id: string; key: string; workingTitle: string; angle: string; whyNow: string; kind: string; estimatedLengthSec: number; confidence: "high" | "medium" | "low"; confidenceWhy: string; moments: LookoutMoment[]; caveats: string[]; sensitive: boolean; }; /** Seconds rounded to the nearest 5, the grain a story's key is cut at. */ const grain = (s: number) => Math.round(s / 5) * 5; /** * The idea's story key: a hash of its sorted moments (channel, video, start * rounded to 5 s). The same moments in any order give the same key; a moment * nudged by a second or two gives the same key; a moment added or removed * gives another. * * NO CITATION, NO KEY: an idea with no moment answers null. Every moment-less * idea would hash the same empty list, so one verdict on one of them would * rule them all, and the run's de-duplication by key would fold distinct * ideas into one. Such an idea is not a finding: a run drops it (counted), * and a stored one is not surfaced (`surfacedIdeas`). */ export function ideaKey(moments: readonly Pick[]): string | null { const parts = [...new Set(moments.map((m) => `${m.channel}/${m.video}@${grain(m.start)}`))].sort(); if (parts.length === 0) return null; return createHash("sha1").update(parts.join("\n")).digest("hex").slice(0, 16); } /** * The ideas of a stored run that are findings: each cites at least one moment * and carries the key its moments give. A damaged run file never throws here: * an idea that is not an object is skipped, a moment that is not one (no * channel, video or start) is dropped from its idea, and an idea left with no * moment, or whose key is not its remaining moments', is left out — never * shown, counted or ruled. What comes back is clean copies. */ export function surfacedIdeas(run: Pick): LookoutIdea[] { const out: LookoutIdea[] = []; for (const i of Array.isArray(run?.ideas) ? (run.ideas as unknown[]) : []) { if (!isObject(i) || !Array.isArray(i.moments) || !isIdeaKey(i.key)) continue; const moments = (i.moments as unknown[]).filter( (m): m is LookoutMoment => isObject(m) && typeof m.channel === "string" && typeof m.video === "string" && typeof m.start === "number" && Number.isFinite(m.start), ); if (moments.length === 0 || ideaKey(moments) !== i.key) continue; out.push({ ...(i as unknown as LookoutIdea), moments }); } return out; } // ─── Runs ─── export type LookoutRunStatus = "done" | "partial" | "failed"; /** * A run as stored. Slice 1 defines the shape and reads it; the job that writes * one (and fills `selection`, `calls`, `ideas`) is slice 2's. */ export type LookoutRun = { version: number; lookoutId: string; runId: string; startedAt: string; endedAt: string | null; status: LookoutRunStatus; window: { from: string; to: string; days: number; timeZone: string }; model: string | null; /** Model calls made. */ calls: number; /** Wall seconds the model calls took, summed. */ seconds: number; /** The selection as the dry run lists it (controller/lookoutPlan.ts LookoutPlan), read and skipped and why. */ selection: unknown; ideas: LookoutIdea[]; /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */ dropped?: Record; /** Why a run that is not `done` stopped: cancelled, the per-run call cap, held for a render past its wait, or a failure (the model, a notes write). */ stopped?: "cancelled" | "cap" | "failed" | "render"; /** What the reading stage did: recordings and chunks read now, reused from fresh notes, failed. */ reading?: { videos: number; videosComplete: number; chunks: number; chunksRead: number; chunksReused: number; chunksFailed: number; items: number; readCalls: number; groupCalls: number; groupCallsFailed?: number; renderWaitSeconds?: number; }; note?: string; }; export type LookoutRunSummary = { runId: string; startedAt: string; endedAt: string | null; status: LookoutRunStatus; window: LookoutRun["window"]; model: string | null; calls: number; seconds: number; ideas: number; }; function isObject(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); } /** Write a run whole (its job is the only writer, once). */ export async function writeLookoutRun(paths: Pick, run: LookoutRun): Promise { const file = lookoutRunFile(paths, run.lookoutId, run.runId); await writeJsonAtomic(file, run, { mkdir: true }); return file; } /** One run, or null when it is absent or not a run. */ export async function readLookoutRun( paths: Pick, id: string, runId: string, ): Promise { const read = await readJsonFile(lookoutRunFile(paths, id, runId)); if (!read.ok || !isObject(read.value)) return null; const v = read.value; if (v.lookoutId !== id || v.runId !== runId || !Array.isArray(v.ideas)) return null; return v as unknown as LookoutRun; } /** The lookout's run ids, newest first. */ export async function listLookoutRunIds(paths: Pick, id: string): Promise { let names: string[]; try { names = await readdir(path.join(lookoutDir(paths, id), "runs")); } catch { return []; } return names .filter((n) => n.endsWith(".json")) .map((n) => n.slice(0, -".json".length)) .filter((n) => LOOKOUT_RUN_ID_RE.test(n)) .sort() .reverse(); } export function summarizeLookoutRun(run: LookoutRun): LookoutRunSummary { return { runId: run.runId, startedAt: run.startedAt, endedAt: run.endedAt, status: run.status, window: run.window, model: run.model, calls: run.calls, seconds: run.seconds, ideas: surfacedIdeas(run).length, }; } /** * Seconds per model call measured over the lookout's latest runs that made * calls (at most `recent`), or null when none has. What a dry run's estimate * is priced from. */ export async function measuredSecondsPerCall( paths: Pick, id: string, recent = 3, ): Promise<{ secondsPerCall: number; runs: number; calls: number } | null> { let calls = 0; let seconds = 0; let runs = 0; for (const runId of await listLookoutRunIds(paths, id)) { if (runs >= recent) break; const run = await readLookoutRun(paths, id, runId); if (!run || !(run.calls > 0) || !(run.seconds > 0)) continue; calls += run.calls; seconds += run.seconds; runs++; } return calls > 0 ? { secondsPerCall: seconds / calls, runs, calls } : null; } // ─── Verdicts ─── export type LookoutVerdict = { verdict: LookoutVerdictValue; /** ISO 8601, when it was given. */ at: string; note?: string; /** The Shorts project "Make" opened, when it did. */ project?: string; }; export type LookoutVerdicts = { version: number; /** Keyed by the idea's story key (`ideaKey`). */ ideas: Record; }; const IDEA_KEY_RE = /^[0-9a-f]{16}$/; const VERDICTS: readonly LookoutVerdictValue[] = ["make", "maybe", "no"]; export function isLookoutVerdict(v: unknown): v is LookoutVerdictValue { return typeof v === "string" && (VERDICTS as readonly string[]).includes(v); } export function isIdeaKey(v: unknown): v is string { return typeof v === "string" && IDEA_KEY_RE.test(v); } export function emptyLookoutVerdicts(): LookoutVerdicts { return { version: LOOKOUT_STORE_VERSION, ideas: {} }; } /** A verdicts file coerced: an ill-typed entry is dropped, never thrown on. */ export function sanitizeLookoutVerdicts(value: unknown): LookoutVerdicts { const out = emptyLookoutVerdicts(); const ideas = isObject(value) ? value.ideas : null; if (!isObject(ideas)) return out; for (const [key, raw] of Object.entries(ideas)) { if (!isIdeaKey(key) || !isObject(raw) || !isLookoutVerdict(raw.verdict) || typeof raw.at !== "string") continue; const v: LookoutVerdict = { verdict: raw.verdict, at: raw.at }; if (typeof raw.note === "string" && raw.note.trim()) v.note = raw.note.trim(); if (typeof raw.project === "string" && raw.project.trim()) v.project = raw.project.trim(); out.ideas[key] = v; } return out; } export async function readLookoutVerdicts( paths: Pick, id: string, ): Promise { const read = await readJsonFile(lookoutVerdictsFile(paths, id)); 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, id: string): Promise { 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; note?: string; project?: string; now?: Date; }; /** * THE writer of verdicts.json: one idea's verdict set (replacing the one it * had), under the file's lock, written atomically. A note or project not sent * is kept from the verdict before, so "Make" recording its project does not * erase the operator's note. Refused when verdicts.json is there and is not * readable JSON — it is never overwritten as if it were empty. */ export async function setLookoutVerdict( paths: Pick, id: string, input: SetVerdictInput, ): Promise { if (!isIdeaKey(input.key)) throw new LookoutStoreError(`"${input.key}" is not an idea key`); if (!isLookoutVerdict(input.verdict)) throw new LookoutStoreError(`verdict is one of ${VERDICTS.join(", ")}`); const file = lookoutVerdictsFile(paths, id); return withJsonFileLock(file, async () => { // A file that is there and cannot be read is NOT an empty one: writing over // it would drop every verdict it holds for the one being set. const read = await readJsonFile(file); if (!read.ok && read.reason !== "absent") { throw new LookoutStoreError( `${file} is ${read.reason} — the verdict was not written; mend the file or move it aside first`, ); } const current = read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts(); const before = current.ideas[input.key]; const v: LookoutVerdict = { verdict: input.verdict, at: (input.now ?? new Date()).toISOString() }; const note = input.note !== undefined ? input.note.trim() : before?.note; if (note) v.note = note; const project = input.project !== undefined ? input.project.trim() : before?.project; if (project) v.project = project; current.ideas[input.key] = v; await writeJsonAtomic(file, current, { mkdir: true }); return v; }); } // ─── The readout (`pnpm ops get lookouts`) ─── export type LookoutReadout = { lastRun: LookoutRunSummary | null; runs: number; /** Ideas in the latest run with no verdict yet. */ unruled: number; verdicts: Record; }; /** What the store holds for one lookout: its runs, the latest one, and how many of its ideas wait for a verdict. */ export async function lookoutReadout(paths: Pick, id: string): Promise { const runIds = await listLookoutRunIds(paths, id); const verdicts = await readLookoutVerdicts(paths, id); const counts: Record = { make: 0, maybe: 0, no: 0 }; for (const v of Object.values(verdicts.ideas)) counts[v.verdict]++; let latest: LookoutRun | null = null; for (const runId of runIds) { latest = await readLookoutRun(paths, id, runId); if (latest) break; } const unruled = latest ? surfacedIdeas(latest).filter((i) => !verdicts.ideas[i.key]).length : 0; return { lastRun: latest ? summarizeLookoutRun(latest) : null, runs: runIds.length, unruled, verdicts: counts, }; }