// settings.generation — report and video generation (release 27, S6; D6). // // Pure: the type, its defaults, the sanitizer settingsSchema.ts runs it // through, the per-field docs SETTINGS.md renders, the routing presets (the // stopgap's gen.py), and the caps a `report-draft` job is held to. It replaces // the stopgap's ~/.config/archilyzer/generation.json; the API KEY itself is // never a setting — only the path of the mode-600 file that holds it (a value // that looks like a key is refused, and never stored). import type { FieldDocs } from "./fieldDocs"; import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, type Autonomy } from "./report/draft/research/decide"; // The media tasks (release 28): each drafts fields of a done iteration's video // manifest, and runs as a STEP on that iteration (recorded in its `steps`, // never an iteration of its own), as narrate did first. THE one list: the // controller, the job, the MCP and umtool ask `isStepTask`. export const MEDIA_STEP_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"] as const; export type MediaStepTask = (typeof MEDIA_STEP_TASKS)[number]; export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "string" && (MEDIA_STEP_TASKS as readonly string[]).includes(t); // `verdicts` (release 29 M8): verdict proposals for a fact-check's unruled // claims — no iteration, no step: a sidecar beside the article, and only on a // model in `verdicts.models` (the bench's bar). // `frames` (release 30, lane P): a frame scan's readings of a saved stream's // frames by a vision model — no article, no iteration: a sidecar beside the // video. `api` or `local`; `code` = none unless the job names a model. // `clips-suggest` (release 36 lane D): the clip finder's optional AI pass — // labels and a rank for a reactions project's proposals // (`/clip-suggestions.json`), and an answer to a comment on a clip — // no article, no iteration. Routed like a media draft; `code` = a Claude Code // session answers the request (`/gen`, the MCP's `generate`). // `video-assist` (release 38 lane E): "make the joins 0.15 s" on a video // project — proposed look / clip / composition edits // (`/assist-proposals.json`) the operator applies. LOCAL in every // preset but `api` (the point is small edits with no Claude at hand); // `code` = a Claude Code session answers the request. // `propose-groups` (lane L4, 2026-11-02): claim groups proposed for a video // project's cut — runs of clips in a section that make one claim // (`/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. // `cast-assign` (characters C3, 2026-11-12): a character proposed for each post // author of a video project -- a name, a stock voice, a speed, a direction -- // asked ONLY on request (`umtool cast assign

--model`); umtool's rule has // proposed already, and these are laid over its rows (`narration/cast-assign.json` // → the project's characters file, through umtool's one writer). Routed as // propose-groups: local in every preset but `api`. // `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", "cast-assign", "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"]; export const GENERATION_ROUTES = ["code", "api", "local"] as const; export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; // The media tasks other than narrate take narrate's route in every preset. const mediaRoutes = (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", "cast-assign": "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", "cast-assign": "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", "cast-assign": "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", "cast-assign": "local", lookout: "local" }, } as const satisfies Record>; export type GenerationPreset = keyof typeof GENERATION_PRESETS; export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[]; export type GenerationRoutes = Record; export type GenerationModels = { api: string; local: string; extractor: string }; // USD. A job's cap defaults by its task; `max` bounds any cap a job asks for; // `daily` refuses a job that would start past it. export type GenerationCaps = { sweep: number; revision: number; narration: number; daily: number; max: number }; export type GenerationWeb = { provider: "duckduckgo"; searchUrl: string }; // A research run's autonomy and limits (release 27 S11): the default a run // takes when it names none. export type GenerationResearch = { autonomy: Autonomy; maxItemsPerRun: number; maxGbPerRun: number; maxTranscribeHours: number; newChannelsNeedApproval: boolean; postWalksNeedApproval: boolean; }; // The cut task's limits (release 28 M1). export type GenerationCut = { maxClips: number }; // The verdict bench's bar and the models that cleared it (release 28 M7): // the bar is the operator's, set on umtool's /bench after reading a run; // `models` are the passing models the operator ticked — never set // automatically. M8's verdict proposals run only on these. export type GenerationVerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number }; // The transcript window a verdict proposal reads (release 29): set to the // bench run's the bar was set on, so a proposal reads what the model was // measured on. export type GenerationVerdictWindow = { mode: "seconds" | "turn"; seconds: number }; export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[]; window: GenerationVerdictWindow }; // Triage first (umtool R6): the cheap pass a recurring report may run before // its sweep — the model it judges on, the threshold it escalates at, and how // many escalations a day may run. export type GenerationTriage = { model: "local" | "extractor"; strong: number; weak: number; maxEscalationsPerDay: number; maxCandidates: number; }; export const DEFAULT_GENERATION_TRIAGE: GenerationTriage = { model: "local", strong: 1, weak: 3, maxEscalationsPerDay: 3, maxCandidates: 40 }; // The frame scan (release 30, lane P): the vision models each route reads // frames on, a scan's default spend cap and its default sampling step. export type GenerationFrames = { apiModel: string; localModel: string; maxUsd: number; everySeconds: number }; export const DEFAULT_GENERATION_FRAMES: GenerationFrames = { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 }; // The local sweep (demo epic D2, round b): the `local` route's sweep is a // pipeline of code around a small model (report/draft/tasks/sweep-pipeline.ts). // `claimForm`: who writes a finding's line — `neutral` (code: "In // (<date>), on <topic>: "<quote>"", the model only picks the quote and labels // its topic) or `sentence` (the model drafts "He says …" and a meaning check // judges it). `readAloud`: what happens to a quote whose transcript has a sign // of reading aloud around it (a tweet, a headline, "it says"; code's patterns, // report/draft/tasks/readAloud.ts) — `flag` (kept, marked "check by ear"), // `drop`, or `off`. export const CLAIM_FORMS = ["sentence", "neutral"] as const; export type ClaimForm = (typeof CLAIM_FORMS)[number]; export const READ_ALOUD_MODES = ["off", "flag", "drop"] as const; export type ReadAloudMode = (typeof READ_ALOUD_MODES)[number]; export type GenerationLocalSweep = { claimForm: ClaimForm; readAloud: ReadAloudMode }; export const DEFAULT_GENERATION_LOCAL_SWEEP: GenerationLocalSweep = { claimForm: "neutral", readAloud: "flag" }; export type GenerationSettings = { preset: GenerationPreset | "custom"; routes: GenerationRoutes; models: GenerationModels; caps: GenerationCaps; cacheTtl: "5m" | "1h"; apiKeyFile: string; anthropicBaseUrl: string; ollamaUrl: string; projectsRoot: string; web: GenerationWeb; citationOrigin: string; research: GenerationResearch; cut: GenerationCut; verdicts: GenerationVerdicts; triage: GenerationTriage; frames: GenerationFrames; localSweep: GenerationLocalSweep; }; export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 }; export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } }; export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS }; export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env"; export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { preset: "balanced", routes: { ...GENERATION_PRESETS.balanced }, models: { api: "claude-sonnet-5-5", local: "qwen3:8b", extractor: "claude-haiku-4-5" }, caps: { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 }, cacheTtl: "5m", apiKeyFile: DEFAULT_API_KEY_FILE, anthropicBaseUrl: "", ollamaUrl: "", projectsRoot: "", web: { provider: "duckduckgo", searchUrl: "" }, citationOrigin: "", research: { ...DEFAULT_GENERATION_RESEARCH }, cut: { maxClips: 20 }, verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } }, triage: { ...DEFAULT_GENERATION_TRIAGE }, frames: { ...DEFAULT_GENERATION_FRAMES }, localSweep: { ...DEFAULT_GENERATION_LOCAL_SWEEP }, }; export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { preset: "The balance knob: `code` (Claude Code does every task but the video assistant's, which stays local), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", routes: "Where each task runs: `code`, `api` or `local` (below).", models: "The model each route runs (below).", caps: "The spend caps in USD (below).", cacheTtl: "The prompt cache's lifetime on the Claude API: `5m` (writes bill 1.25× input) or `1h` (2×, for long runs with pauses).", apiKeyFile: "The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file.", anthropicBaseUrl: "Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake.", ollamaUrl: "The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434).", projectsRoot: "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports volume: `/data/reports/articles`), else `~/reports/articles` (common/lib/projectsRoot.mjs).", web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.", citationOrigin: "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", research: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.", cut: "The cut task's limits (below).", verdicts: "The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.", triage: "Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below).", frames: "The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below).", localSweep: "The `local` route's sweep (a pipeline of code around the local model): who writes a finding's line and what happens to a quote that may be read aloud (below). `archilyzer gen local-sweep` sets both; the Claude routes' sweeps are not affected.", }; export const GENERATION_LOCAL_SWEEP_FIELD_DOCS: FieldDocs<GenerationLocalSweep> = { claimForm: "`neutral`: code writes each finding — `In <recording's title> (<date>), on <topic>: \"<quote>\"` — and the model only copies the quote and labels its topic in a few words (a label that names the speaker, has a verb of saying or thinking, or uses words found in neither the quote, the transcript before it, the title nor the question is replaced by the question's topic); the line says where the words are, never who is speaking. `sentence`: the model drafts a one-line claim (\"He says …\") and a meaning check, one more call an item, judges it against the transcript around the quote.", readAloud: "A quote whose transcript has a sign of reading aloud around it — a tweet, likes and retweets, a headline or article being introduced, \"it says\", \"he writes\", \"according to\", a clip, a chat message, the host named in the third person: `flag` keeps it in 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`; `drop` leaves it out (counted in the coverage line); `off` does not look. The patterns are code's (`common/lib/report/draft/tasks/readAloud.ts`) and miss a reading nothing in the transcript announces.", }; export const GENERATION_FRAMES_FIELD_DOCS: FieldDocs<GenerationFrames> = { apiModel: "The Claude model a scan on the `api` route reads frames with (it must take images). Haiku: about a cent a hundred frames.", localModel: "The ollama vision model a scan on the `local` route reads frames with (one frame an ask, under the 8k prompt cap; through the GPU arbiter on `draft:local`).", maxUsd: "A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read.", everySeconds: "Seconds between two sampled frames when the job names none (1 to 600).", }; export const GENERATION_TRIAGE_FIELD_DOCS: FieldDocs<GenerationTriage> = { model: "What the window judge runs on: `local` (`models.local`, through the GPU arbiter on `draft:local`, $0 marginal) or `extractor` (`models.extractor`, on the API, metered).", strong: "Escalate when this many STRONG flags (the judge's score 3: the line directly answers the question) are found. 0 = strong flags alone never escalate. A schedule may set its own.", weak: "Escalate when this many flags of any strength (score 2 or 3) are found. 0 = off. A schedule may set its own.", maxEscalationsPerDay: "The most escalations (tier 2 sweeps) a day (UTC) across every schedule. Past it a tick is held by the cap — a Your call card — with its flags kept. 0 = no cap.", maxCandidates: "The most candidates one triage judges; the rest stay new for the next tick.", }; export const GENERATION_VERDICTS_FIELD_DOCS: FieldDocs<GenerationVerdicts> = { bar: "The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set.", models: "The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals.", window: "The transcript a verdict proposal reads around each cited span (below): set it to the bench run's the bar was set on (its window mode and `--window`).", }; export const GENERATION_VERDICT_WINDOW_FIELD_DOCS: FieldDocs<GenerationVerdictWindow> = { mode: "`seconds` (the cues within `seconds` either side of the cited span) or `turn` (the cited speaker's turn, bounded by `seconds` either side) — the bench's `--window-mode`.", seconds: "Seconds either side of the cited span, 0 to 600 — the bench's `--window`.", }; export const GENERATION_VERDICT_BAR_FIELD_DOCS: FieldDocs<GenerationVerdictBar> = { agreement: "The least share of claims on which the model's verdict must equal the operator's (strictly: PARTLY is not CORROBORATED).", contradictedRecall: "The least share of the claims the operator ruled CONTRADICTED that the model must rule so.", notFoundRecall: "The least share of the claims the operator ruled NOT_FOUND that the model must rule so.", }; export const GENERATION_CUT_FIELD_DOCS: FieldDocs<GenerationCut> = { maxClips: "The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says).", }; export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { sweep: "A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`).", "revise-report": "A report iteration from feedback, through checked ops.", "revise-video": "A video-cut iteration from feedback, through checked ops.", narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.", research: "A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP.", cut: "A media draft (a step on a done iteration, as narration): the cut's clips and their order, chosen from the report's citations.", onscreen: "A media draft: each clip's on-screen title and subtitle.", teaser: "A media draft: the teaser's lines.", flips: "A media draft: THEN/NOW pairs over the cut's clips.", threads: "A media draft: the cut's threads and each clip's thread.", youtube: "A media draft: the YouTube title and description.", social: "A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code.", frames: "A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model.", "clips-suggest": "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": "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`).", "cast-assign": "A character proposed for each post author of a video project (umtool's Voices page: Ask the model too; `umtool cast assign <p> --model`) -- a name, a stock voice, a speed and a direction line, from the author's display name, bio and words (untrusted: checked field by field) -- laid over the rule's proposed rows, each accepted or rejected by the operator; never asked without the flag or the button. Local in every preset but `api`; `code` = a Claude Code session's answer (`pnpm ops report-draft` with `answers`).", 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.", }; export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { api: "The Claude model the `api` route runs (Sonnet 5.5: no temperature, no forced tool choice, thinking between tools).", local: "The ollama model the `local` route runs. Prompts stay under 8k tokens and `num_ctx` under 12k on the 8 GB card.", extractor: "The cheap model an API sweep's `extract_batch` runs — the plan's dumb extractor (Claude or a local model).", }; export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = { sweep: "A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap.", revision: "A report or video revision job's cap when it names none.", narration: "A narration (or other media draft) job's cap when it names none.", daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.", max: "The most a job may ask for: a larger `maxUsd` is refused.", }; export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = { provider: "The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search.", searchUrl: "Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake.", }; export const GENERATION_RESEARCH_FIELD_DOCS: FieldDocs<GenerationResearch> = { autonomy: "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.", maxItemsPerRun: "The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits.", maxGbPerRun: "The most GB one run may download without approval. An acquisition of unknown size waits.", maxTranscribeHours: "The most hours of transcription one run may queue without approval. One of unknown length waits.", newChannelsNeedApproval: "Under `limits`, a new channel waits for approval. (A new channel is always created on no site.)", postWalksNeedApproval: "Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval.", }; // What a key looks like: the API's own prefix, or one long unbroken token with // no path in it. export function looksLikeApiKey(v: string): boolean { const s = v.trim(); // The API key prefix, written so the release's privacy grep (which counts the // literal) does not count this rule. return /sk-an[t]-/i.test(s) || (!s.includes("/") && !s.startsWith("~") && /^[A-Za-z0-9_-]{32,}$/.test(s)); } const str = (v: unknown, d: string) => (typeof v === "string" ? v.trim() : d); const url = (v: unknown, d: string) => { const s = typeof v === "string" ? v.trim().replace(/\/+$/, "") : null; if (s === null) return d; if (s === "") return ""; return /^https?:\/\/[^\s]+$/.test(s) ? s : d; }; const usd = (v: unknown, d: number, max = 1000) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v * 100) / 100) : d; export function sanitizeGeneration(value: unknown): GenerationSettings { const d = DEFAULT_GENERATION_SETTINGS; const r = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; const rr = r.routes && typeof r.routes === "object" ? (r.routes as Record<string, unknown>) : {}; const routes = {} as GenerationRoutes; for (const t of GENERATION_TASKS) { const v = rr[t]; routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t]; } // A file from before a task had a route (research, S11; the media tasks, // release 28) keeps its preset: a task it does not name takes the route of // the preset the tasks it names are routed by. // (Only a file that routes release 27's first four names a preset this way; // a partial patch is not one.) const named = (t: GenerationTask) => typeof rr[t] === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr[t] as string); const unnamed = GENERATION_TASKS.filter((t) => !named(t)); if (unnamed.length && FIRST_TASKS.every(named)) { const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => !named(t) || routes[t] === GENERATION_PRESETS[p][t])); if (was) for (const t of unnamed) routes[t] = GENERATION_PRESETS[was][t]; } // The ROUTES are the truth; the preset names them (the preset whose routes // they are, else `custom`). Choosing a preset is writing its routes. const preset: GenerationSettings["preset"] = presetOf(routes); const m = r.models && typeof r.models === "object" ? (r.models as Record<string, unknown>) : {}; const model = (v: unknown, fallback: string) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(v.trim()) ? v.trim() : fallback; const c = r.caps && typeof r.caps === "object" ? (r.caps as Record<string, unknown>) : {}; const max = usd(c.max, d.caps.max); const w = r.web && typeof r.web === "object" ? (r.web as Record<string, unknown>) : {}; const keyFile = str(r.apiKeyFile, d.apiKeyFile); const rs = r.research && typeof r.research === "object" && !Array.isArray(r.research) ? (r.research as Record<string, unknown>) : {}; const count = (v: unknown, def: number, max: number) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v * 100) / 100) : def; const dr = d.research; return { preset, routes, models: { api: model(m.api, d.models.api), local: model(m.local, d.models.local), extractor: model(m.extractor, d.models.extractor) }, caps: { sweep: Math.min(max, usd(c.sweep, d.caps.sweep)), revision: Math.min(max, usd(c.revision, d.caps.revision)), narration: Math.min(max, usd(c.narration, d.caps.narration)), daily: usd(c.daily, d.caps.daily, 100_000), max, }, cacheTtl: r.cacheTtl === "1h" ? "1h" : "5m", // Never a key: a value that looks like one is the default path. apiKeyFile: keyFile && !looksLikeApiKey(keyFile) ? keyFile : d.apiKeyFile, anthropicBaseUrl: url(r.anthropicBaseUrl, d.anthropicBaseUrl), ollamaUrl: url(r.ollamaUrl, d.ollamaUrl), projectsRoot: str(r.projectsRoot, d.projectsRoot), web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) }, citationOrigin: url(r.citationOrigin, d.citationOrigin), cut: { maxClips: (() => { const ct = r.cut && typeof r.cut === "object" && !Array.isArray(r.cut) ? (r.cut as Record<string, unknown>) : {}; return typeof ct.maxClips === "number" && Number.isInteger(ct.maxClips) && ct.maxClips >= 3 && ct.maxClips <= 500 ? ct.maxClips : d.cut.maxClips; })(), }, research: { autonomy: (AUTONOMIES as readonly string[]).includes(String(rs.autonomy)) ? (rs.autonomy as Autonomy) : dr.autonomy, maxItemsPerRun: Math.floor(count(rs.maxItemsPerRun, dr.maxItemsPerRun, 10_000)), maxGbPerRun: count(rs.maxGbPerRun, dr.maxGbPerRun, 10_000), maxTranscribeHours: count(rs.maxTranscribeHours, dr.maxTranscribeHours, 10_000), newChannelsNeedApproval: typeof rs.newChannelsNeedApproval === "boolean" ? rs.newChannelsNeedApproval : dr.newChannelsNeedApproval, postWalksNeedApproval: typeof rs.postWalksNeedApproval === "boolean" ? rs.postWalksNeedApproval : dr.postWalksNeedApproval, }, verdicts: sanitizeVerdicts(r.verdicts), triage: sanitizeTriage(r.triage), frames: sanitizeFrames(r.frames, model), localSweep: sanitizeLocalSweep(r.localSweep), }; } export function sanitizeLocalSweep(v: unknown): GenerationLocalSweep { const d = DEFAULT_GENERATION_LOCAL_SWEEP; const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; return { claimForm: (CLAIM_FORMS as readonly unknown[]).includes(o.claimForm) ? (o.claimForm as ClaimForm) : d.claimForm, readAloud: (READ_ALOUD_MODES as readonly unknown[]).includes(o.readAloud) ? (o.readAloud as ReadAloudMode) : d.readAloud, }; } function sanitizeFrames(v: unknown, model: (v: unknown, fallback: string) => string): GenerationFrames { const d = DEFAULT_GENERATION_FRAMES; const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; return { apiModel: model(o.apiModel, d.apiModel), localModel: model(o.localModel, d.localModel), maxUsd: usd(o.maxUsd, d.maxUsd, 1000), everySeconds: typeof o.everySeconds === "number" && Number.isFinite(o.everySeconds) && o.everySeconds >= 1 && o.everySeconds <= 600 ? Math.round(o.everySeconds * 100) / 100 : d.everySeconds, }; } function sanitizeTriage(v: unknown): GenerationTriage { const d = DEFAULT_GENERATION_TRIAGE; const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; const int = (x: unknown, def: number, min: number, max: number) => (typeof x === "number" && Number.isInteger(x) && x >= min && x <= max ? x : def); return { model: o.model === "extractor" ? "extractor" : "local", strong: int(o.strong, d.strong, 0, 50), weak: int(o.weak, d.weak, 0, 50), maxEscalationsPerDay: int(o.maxEscalationsPerDay, d.maxEscalationsPerDay, 0, 1000), maxCandidates: int(o.maxCandidates, d.maxCandidates, 1, 500), }; } /** The model a triage judges on: the asked one, else the settings' (`local` → models.local, `extractor` → models.extractor). */ export function triageModelOf(gen: GenerationSettings, asked?: string): string { if (asked) return asked; return gen.triage.model === "extractor" ? gen.models.extractor : gen.models.local; } function sanitizeVerdicts(v: unknown): GenerationVerdicts { const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; const b = o.bar && typeof o.bar === "object" && !Array.isArray(o.bar) ? (o.bar as Record<string, unknown>) : {}; const frac = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? Math.min(1, Math.max(0, Math.round(x * 10_000) / 10_000)) : 0); const models = Array.isArray(o.models) ? [...new Set(o.models.filter((m): m is string => typeof m === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m.trim())).map((m) => m.trim()))] : []; const w = o.window && typeof o.window === "object" && !Array.isArray(o.window) ? (o.window as Record<string, unknown>) : {}; const window: GenerationVerdictWindow = { mode: w.mode === "turn" ? "turn" : "seconds", seconds: typeof w.seconds === "number" && Number.isFinite(w.seconds) && w.seconds >= 0 && w.seconds <= 600 ? Math.round(w.seconds) : DEFAULT_GENERATION_VERDICT_WINDOW.seconds, }; return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models, window }; } // The model a task will run on as the policy stands (demo epic D3, the // settings page's per-task row): its route's model — a frame scan's the // vision model of its route — or none on `code` (a Claude Code session // answers it). `needsKey`: the Claude API is called, so a key must be there. export function plannedModelOf(gen: GenerationSettings, task: GenerationTask): { route: GenerationRoute; model: string | null; needsKey: boolean } { const route = gen.routes[task]; if (route === "code") return { route, model: null, needsKey: false }; const model = task === "frames" ? (route === "api" ? gen.frames.apiModel : gen.frames.localModel) : route === "api" ? gen.models.api : gen.models.local; return { route, model, needsKey: route === "api" }; } export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" { return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom"; } // The cap a job runs under: the task's default, or the asked one when it is // within `max` (else an error naming both). export function capFor(caps: GenerationCaps, task: "sweep" | "revision" | "narration", asked?: number): number { if (asked === undefined || asked === null) return caps[task]; if (!Number.isFinite(asked) || asked <= 0) throw new Error(`maxUsd must be a positive number of dollars`); if (asked > caps.max) throw new Error(`maxUsd $${asked} is over the settings' max of $${caps.max} (settings.generation.caps.max)`); return asked; }