Archilyzer · Source

archilyzer

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

commit b3aba111faa50d5d8c361617751e0f19525a3bda
parent 2d8359b904712a23b816e360237febdabce15d65
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:50:54 -0400

Merge r28/quality: release 28 Q1–Q3, F2, F3 — first person refused, fragment quotes, local-first revisions, per-job extractor, report-draft progress

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	editor/CHANGELOG.md
#	plans/FACTS.md
#	plans/release-28.md

Diffstat:
MCOMMANDS.md | 2+-
MREPORT.md | 2+-
Mcommon/bin/reports-check.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/bin/reports-check.ts | 53++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/reportDraft.ts | 43+++++++++++++++++++++++++++++++++++++++----
Mcommon/jobs/registry.ts | 9++++++++-
Acommon/lib/citations/fragment.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/citations/fragment.ts | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/structured.ts | 15++++++++++++++-
Mcommon/lib/report/docs.ts | 8++++++--
Mcommon/lib/report/draft/authoringRules.ts | 9++++++++-
Mcommon/lib/report/draft/grounding.test.ts | 34+++++++++++++++++++++++++++++++++-
Mcommon/lib/report/draft/grounding.ts | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/report/draft/reportOps.test.ts | 19+++++++++++++++++++
Mcommon/lib/report/draft/reportOps.ts | 13++++++++++---
Mcommon/lib/report/draft/sweepModel.test.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/report/draft/sweepModel.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/quotes.ts | 25+++++++++++++++++++++++--
Mcommon/lib/report/draft/tasks/research.ts | 6++++--
Mcommon/lib/report/draft/tasks/revise-report.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/lib/report/draft/tasks/revise-video.ts | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mcommon/lib/report/draft/tasks/run.ts | 11++++++++++-
Mcommon/lib/report/draft/tasks/sweep-agent.ts | 18++++++++++++++----
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 25++++++++++++++++++++++---
Mcommon/lib/report/draft/tasks/tasks.test.ts | 23+++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/types.ts | 9+++++++++
Mcommon/lib/report/draft/videoOps.test.ts | 18+++++++++++++++++-
Mcommon/lib/report/draft/videoOps.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 2+-
Mcommon/testing/draft/derive.ts | 2+-
Acommon/testing/draft/sweeps/fragment.md | 11+++++++++++
Meditor/CHANGELOG.md | 5+++++
Meditor/app/api/ops/_reportDraft.test.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 9+++++----
Meditor/app/jobs/components/JobProgressBars.tsx | 9+++++++++
Meditor/e2e/report-draft.spec.ts | 2++
Mmcp/src/draftTasks.test.ts | 116++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mmcp/src/generation.test.ts | 6++++++
Mmcp/src/generation.ts | 10+++++++++-
Mplans/FACTS.md | 8++++++++
Mplans/release-28.md | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 9++++++---
Mumtool/app/api/articles/generate/route.ts | 8+++++---
Aumtool/components/articles/ExtractorSelect.tsx | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/IterationsTab.tsx | 20+++++++++++++++++++-
Mumtool/components/articles/NewArticleForm.tsx | 6++++++
Mumtool/components/articles/ResearchSlot.tsx | 17++++++++++++++++-
Mumtool/e2e/article-new.spec.ts | 6++++++
Mumtool/lib/articles/generation.ts | 2+-
49 files changed, 1497 insertions(+), 144 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -143,7 +143,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | -| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate" \| "research", "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration; a narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` | +| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate" \| "research", "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration; a narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | ### Usage, flags and environment diff --git a/REPORT.md b/REPORT.md @@ -146,7 +146,7 @@ An article made or revised by a model keeps each generation as an **iteration**, ## Checking quotes -`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`. +`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. A quote under four words, or one that stops on a function word (`as`, `to`, `the`, …), is a **`fragment`**: a warning too, with the full sentence to quote when the record has one; a GENERATED fragment fails, and the repair round is handed that sentence. `drift` and `en-orig-drift` come before `inexact`, and `inexact` before `fragment`. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `fragment`, `missing-record`, `no-cues`, `missing-post`, `unreadable`. ## Making a report from what exists diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts @@ -249,6 +249,38 @@ test("verify-quotes: `inexact` — recall passes, the strict check does not — assert.match(w.text(), /2 quote\(s\): 1 inexact, 1 ok \(inexact is a warning\)/); }); +test("verify-quotes: `fragment` — verbatim, but stopping mid-thought — is a warning with the full sentence (testing/draft/sweeps/fragment.md)", async () => { + // The kitchen channel's records are on disk from the test above. + const { report } = await convertFixture("fragment"); + const file = path.join(ROOT, "fragment.report.json"); + writeJson(file, report); + const c = capture(); + const code = await verifyQuotesMain({ file, json: true, paths }, c.out); + const { results } = JSON.parse(c.text()) as { results: { citation: string; status: string; sentence?: string; message?: string }[] }; + const by = Object.fromEntries(results.map((r) => [r.citation, r])); + assert.equal(by.c01.status, "fragment"); + assert.equal(by.c01.sentence, "I paid for the new mixer myself"); + assert.match(by.c01.message!, /ends on “the”/); + assert.equal(by.c02.status, "fragment"); + assert.equal(by.c02.sentence, "my lawyer told me not to talk about the lease"); + assert.equal(by.c03.status, "fragment"); + assert.match(by.c03.message!, /under 4 words/); + assert.equal(by.c03.sentence, "I did not enter the contest this year"); + assert.equal(by.c04.status, "ok"); + assert.equal(code, 0, "a fragment is a warning"); + const w = capture(); + assert.equal(await verifyQuotesMain({ file, paths }, w.out), 0); + assert.match(w.text(), /FRAGMENT \(warning\) c01/); + assert.match(w.text(), /4 quote\(s\): 3 fragment, 1 ok \(fragment is a warning\)/); + // Precedence: a quote that is not verbatim is `inexact`, never `fragment`. + const reversed = { ...report, citations: { ...report.citations, c01: { ...report.citations!.c01!, quote: "I paid for a" } } }; + writeJson(file, reversed); + const r = capture(); + await verifyQuotesMain({ file, json: true, paths }, r.out); + const rc01 = (JSON.parse(r.text()) as { results: { citation: string; status: string }[] }).results.find((x) => x.citation === "c01")!; + assert.notEqual(rc01.status, "fragment"); +}); + // ─── attach-video ─── test("encodePlan: remux an H.264 mp4 under the limit; encode the rest to fit; refuse what cannot", () => { diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -25,6 +25,11 @@ // and counted, and does not change the exit code; compose and publish do not // use it. // +// A quote that is a FRAGMENT — under four words, or stopping on a function +// word (lib/citations/fragment.ts, release 28 Q2) — is `fragment`: a WARNING +// too, with the full sentence to quote when the record has one. Precedence: +// `drift` / `en-orig-drift` > `inexact` > `fragment` > `ok`. +// // `--article <id>` checks one ARTICLE (release 26: transcripts/reports/<id>/, // published or a draft) as the homepage's compose would — any channel of the // corpus citable, the articles' prepared media. @@ -51,6 +56,7 @@ import { strictTextCheck, type StrictQuoteResult, } from "../lib/citations/verify"; +import { fragmentOf, fullSentenceFor, type FragmentFinding } from "../lib/citations/fragment"; import { ComposeReportsError, checkSpanQuote, @@ -142,6 +148,9 @@ export type QuoteStatus = | "en-orig-drift" // Recall passes, the strict check does not: a warning (release 27 D3). | "inexact" + // Verbatim, but under four words or stopping on a function word: a + // warning (release 28 Q2). + | "fragment" | "missing-record" | "no-cues" | "missing-post" @@ -165,11 +174,13 @@ export type QuoteResult = { // The strict check (verbatim within ±90 s): whether it passed, and the // first fragment it did not find. Absent where recall already failed. strict?: { ok: boolean; failed?: string }; + // A fragment's full sentence, from the record, when one fits. + sentence?: string; message?: string; }; // Statuses that are warnings: printed and counted, never a failure. -export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact"]); +export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact", "fragment"]); const strictOf = (r: StrictQuoteResult): NonNullable<QuoteResult["strict"]> => r.ok ? { ok: true } : { ok: false, ...(r.failed !== undefined ? { failed: r.failed } : {}) }; @@ -181,6 +192,14 @@ export function inexactMessage(failed: string | undefined): string { ); } +export function fragmentMessage(f: FragmentFinding, sentence: string | null): string { + return ( + `"${f.part.slice(0, 120)}" is a fragment (${f.why}): quote the whole sentence` + + (sentence ? ` — "${sentence}"` : " or clause") + + " — a warning; compose is unchanged" + ); +} + export const EN_ORIG_TRACK = "transcript.en-orig.vtt"; // Every video, audio and post citation of a report, checked against the @@ -233,18 +252,23 @@ export async function verifyReportQuotes( } const v = quoteVerification(c.quote, postText, now); const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText); - const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : "ok"; + const frag = fragmentOf(c.quote); + const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : frag ? "fragment" : "ok"; + const sentence = status === "fragment" ? fullSentenceFor(frag!.part, [{ start: 0, end: 1, text: postText }], 0) : null; results.push({ ...base, score: v.quoteScore, track: "post", status, ...(strict ? { strict: strictOf(strict) } : {}), + ...(sentence ? { sentence } : {}), ...(status === "drift" ? { message: quoteDriftMessage(v.quoteScore) } : status === "inexact" ? { message: inexactMessage(strict?.failed) } - : {}), + : status === "fragment" + ? { message: fragmentMessage(frag!, sentence) } + : {}), }); continue; } @@ -269,14 +293,19 @@ export async function verifyReportQuotes( // The strict check passes when any track has the quote verbatim near // the cited second (as recall takes the best track). let strict: StrictQuoteResult | null = null; + let strictCues = record.cues; if (!quoteDrifted(checked.verification)) { const tracks = record.tracks.length ? record.tracks.map((t) => t.cues) : [record.cues]; for (const cues of tracks) { const r = strictQuoteCheck(c.quote, cues, c.start); if (!strict || r.ok) strict = r; - if (r.ok) break; + if (r.ok) { + strictCues = cues; + break; + } } } + let sentence: string | null = null; if (quoteDrifted(checked.verification)) { status = "drift"; message = quoteDriftMessage(score); @@ -288,6 +317,13 @@ export async function verifyReportQuotes( } else if (strict && !strict.ok) { status = "inexact"; message = inexactMessage(strict.failed); + } else { + const frag = fragmentOf(c.quote); + if (frag) { + status = "fragment"; + sentence = fullSentenceFor(frag.part, strictCues, c.start); + message = fragmentMessage(frag, sentence); + } } results.push({ ...base, @@ -296,6 +332,7 @@ export async function verifyReportQuotes( tracks: checked.tracks, ...(enOrig !== undefined ? { enOrig } : {}), ...(strict ? { strict: strictOf(strict) } : {}), + ...(sentence ? { sentence } : {}), status, ...(message ? { message } : {}), }); @@ -343,8 +380,14 @@ export async function verifyQuotesMain( `reports verify-quotes: ${results.length} quote(s): ` + [...counts].map(([s, n]) => `${n} ${s}`).join(", ") + (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : "") + - (results.some((r) => QUOTE_WARNING_STATUSES.has(r.status)) ? " (inexact is a warning)" : ""), + warningsNote(results), ); } return bad.length > 0 || parsed.problems.length > 0 ? 1 : 0; } + +// " (inexact is a warning)", " (inexact and fragment are warnings)", or "". +function warningsNote(results: readonly QuoteResult[]): string { + const seen = [...QUOTE_WARNING_STATUSES].filter((w) => results.some((r) => r.status === w)); + return seen.length ? ` (${seen.join(" and ")} ${seen.length > 1 ? "are warnings" : "is a warning"})` : ""; +} diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -8,6 +8,9 @@ // sweep, the research run it CONTINUES (S11: its question, and its // channels widened by what it acquired, are the defaults); else none // model default: settings.generation.models[route] for the task's route +// extractorModel an API sweep's extractor (default: +// settings.generation.models.extractor): a Claude model id the +// price table knows (release 28 F2) // question / channels / from / to a sweep's // feedback a revision's // copyOf run iteration N again on another model (same kind and inputs) @@ -33,12 +36,13 @@ import os from "node:os"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import type { Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { capFor, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; -import { providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { PRICES, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; import { webTools } from "../lib/web/tools"; import { copyIteration, @@ -72,6 +76,7 @@ export const REPORT_DRAFT_BODY_KEYS = [ "article", "iteration", "model", + "extractorModel", "feedback", "question", "channels", @@ -93,6 +98,7 @@ export type ReportDraftBody = { article: string; iteration?: number; model?: string; + extractorModel?: string; feedback?: string; question?: string; channels?: string[]; @@ -107,6 +113,12 @@ export type ReportDraftBody = { autonomy?: Autonomy; }; +// A Claude model the price table knows: one of its ids, or a dated id of one +// (`claude-haiku-4-5-20251001`). +export function isKnownApiModel(model: string): boolean { + return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`)); +} + const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate", "research"]; const ymd = /^\d{4}-\d{2}-\d{2}$/; @@ -146,6 +158,14 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod set("iteration", int("iteration")); set("copyOf", int("copyOf")); set("model", text("model")); + const extractor = text("extractorModel"); + if (extractor !== undefined) { + if (!isKnownApiModel(extractor)) { + fail(`"extractorModel" is a Claude model id (${Object.keys(PRICES).filter((m) => m.startsWith("claude-")).join(", ")}): an API sweep's extractor runs on the API`); + } + if (task !== "sweep") fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)'); + out.extractorModel = extractor; + } set("feedback", text("feedback")); set("question", text("question")); set("channels", list("channels")); @@ -334,6 +354,9 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep } const model = modelFor(gen, body.task, body.model); const provider = providerOf(model); + if (body.extractorModel && provider === "local") { + warnings.push(`extractorModel ${body.extractorModel} is unused: a sweep on a local model runs the pipeline, which has no extractor`); + } let maxUsd: number | undefined; if (provider === "api") { maxUsd = capFor(gen.caps, CAP_OF[body.task], body.maxUsd); @@ -382,7 +405,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, _progress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal }, deps), + fn: (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps), }); if (!result.ok) { if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); @@ -405,7 +428,16 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep } async function runReportDraft( - o: { body: ReportDraftBody; model: string; maxUsd?: number; n: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal }, + o: { + body: ReportDraftBody; + model: string; + maxUsd?: number; + n: number; + jobId: string; + onLog: (l: string) => void; + signal: AbortSignal; + setProgress?: (snap: JobProgress) => void; + }, deps: ReportDraftDeps, ): Promise<void> { const { body, model, n, onLog, signal } = o; @@ -455,6 +487,9 @@ async function runReportDraft( .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })), paths, log: onLog, + // The task's count as the job's progress (release 28 F3): turns, cards + // or entries, the runner's own `current` (nothing on disk re-counts it). + progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }), signal, ...(deps.now ? { now: deps.now } : {}), ...(body.task === "research" && deps.researchEditor ? { editor: deps.researchEditor, editorChannels: () => editorChannelsOf(paths) } : {}), @@ -462,7 +497,7 @@ async function runReportDraft( const projectsRoot = projectsRootOf(gen); // A local run costs nothing: it has no dollar cap. const cap = provider === "api" ? o.maxUsd! : Number.POSITIVE_INFINITY; - const extractor = gen.models.extractor; + const extractor = body.extractorModel ?? gen.models.extractor; let input: TaskInput; switch (body.task) { case "sweep": diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -26,7 +26,14 @@ export type JobProgressMetric = // Clip windows of a fetch-windows batch (controller/fetchWindows.ts). Spans // channels, so there is no channel count to re-count; the runner always sets // `current`. - | "clips"; + | "clips" + // A report-draft job (controller/reportDraft.ts, release 28 F3): an agent + // task's model turns (the target is its turn cap), a media task's cards, a + // pipeline's recordings read or a media task's entries. Nothing on disk to + // re-count; the runner always sets `current`. + | "turns" + | "cards" + | "entries"; export type JobProgress = { metric: JobProgressMetric; diff --git a/common/lib/citations/fragment.test.ts b/common/lib/citations/fragment.test.ts @@ -0,0 +1,58 @@ +// Fragment quotes (release 28 Q2): what is one, and the full sentence code offers. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { FRAGMENT_END_WORDS, fragmentOf, fullSentenceFor, isFragmentQuote } from "./fragment"; +import { strictQuoteCheck } from "./verify"; +import { cuesOf } from "../../testing/draft/corpus.mjs"; + +const cue = (start: number, text: string) => ({ start, end: start + 4.8, text }); + +test("a fragment: under four words, or a part ending on a function word", () => { + assert.deepEqual(fragmentOf("I priced it as"), { why: "ends on “as”", part: "I priced it as" }); + assert.equal(fragmentOf("never again")?.why, "under 4 words"); + assert.equal(fragmentOf("my lawyer told me not to")?.why, "ends on “to”"); + // Case and punctuation aside; an ellipsis part is judged on its own. + assert.equal(fragmentOf("I paid for THE")?.why, "ends on “the”"); + assert.equal(fragmentOf("I would never sell the bakery … to a chain and")?.part, "to a chain and"); + // Whole sentences and clauses pass. + assert.equal(fragmentOf("I would never sell the bakery to a chain"), null); + assert.equal(fragmentOf("What are you even looking at?"), null, "sentence punctuation ends a sentence whatever its last word"); + assert.equal(isFragmentQuote("the judges were friends of mine so it felt wrong"), false); + assert.equal(fragmentOf(""), null); + assert.ok(FRAGMENT_END_WORDS.includes("as") && FRAGMENT_END_WORDS.includes("her")); +}); + +test("the full sentence: unpunctuated captions extend to the end of the quote's cue", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + assert.equal(fullSentenceFor("I paid for the", cues, 45), "I paid for the new mixer myself"); + const pie = (await cuesOf("synth-kitchen", "pie-stream-02"))!; + assert.equal(fullSentenceFor("my lawyer told me not to", pie, 40), "my lawyer told me not to talk about the lease"); + // Under four words: the cue's run holds it. + assert.equal(fullSentenceFor("I did not", pie, 10), "I did not enter the contest this year"); + // Not there verbatim: nothing to offer. + assert.equal(fullSentenceFor("I sold the bakery as", cues, 15), null); +}); + +test("the full sentence: punctuation, a new cue's capital, one more cue, and the cap", () => { + const punct = [cue(0, "So the price. I priced it as a loss, and"), cue(5, "then I moved on. Next")]; + assert.equal(fullSentenceFor("I priced it as", punct, 0), "I priced it as a loss, and then I moved on."); + // A cue boundary where the next cue starts a sentence ends it (the pronoun I does not). + const caps = [cue(0, "we said that the oven ran hot"), cue(5, "Then we left"), cue(10, "I think")]; + assert.equal(fullSentenceFor("the oven ran", caps, 0), "the oven ran hot"); + // Still under four words: back to the sentence's start. + assert.equal(fullSentenceFor("ran hot", caps, 0), "we said that the oven ran hot"); + // The quote's cue ends on a function word: one more cue. + const more = [cue(0, "she told me that the shop is"), cue(5, "closing in the spring"), cue(10, "and nobody knew")]; + assert.equal(fullSentenceFor("the shop is", more, 0), "the shop is closing in the spring"); + // Too long to be offered. + const long = [cue(0, `the ${"very ".repeat(40)}long one of`), cue(5, "and of")]; + assert.equal(fullSentenceFor("the very very", long, 0, { maxWords: 10 }), null); +}); + +test("the full sentence passes the strict check wherever the quote did", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + const s = fullSentenceFor("I paid for the", cues, 45)!; + assert.equal(strictQuoteCheck(s, cues, 45).ok, true); + assert.equal(fragmentOf(s), null); +}); diff --git a/common/lib/citations/fragment.ts b/common/lib/citations/fragment.ts @@ -0,0 +1,155 @@ +// FRAGMENT QUOTES — a quote that stops mid-thought (release 28, Q2). +// +// A quote is a FRAGMENT when it has fewer than FRAGMENT_MIN_WORDS words, or +// one of its parts (the runs convertSweep joins with an ellipsis) ends on a +// function word — "I priced it as", "my lawyer told me not to". A part that +// ends on sentence punctuation (. ! ? …) is a whole sentence whatever its last +// word ("What are you looking at?"). Accepted collateral of the end-word rule: +// a sentence that really ends on an object pronoun ("I told her") when its +// transcript is unpunctuated. +// +// `fullSentenceFor` is what code offers instead: the smallest run of the +// record's text, from the quote's first word, that ends at sentence +// punctuation or at a cue boundary where the next cue starts a new sentence; +// with unpunctuated captions, the end of the cue the quote ends in, then one +// more cue while it is still a fragment. Capped at FULL_SENTENCE_MAX_WORDS +// (or the quote's own length and a margin, when the quote is longer). A +// result still under the minimum is widened back to the sentence's start. +// The words are the cues' own, joined with single spaces, so the sentence +// passes the strict check wherever the quote did. +// +// Pure, no imports but ./verify (also pure). + +import { STRICT_QUOTE_WINDOW_SECONDS, quoteFragments, strictNormalize } from "./verify"; + +export const FRAGMENT_MIN_WORDS = 4; + +// The words a quote may not end on (lowercase; compared normalised). +export const FRAGMENT_END_WORDS = [ + "as", "to", "the", "and", "of", "a", "an", "in", "on", "for", "with", "at", "by", "from", "that", "which", + "but", "or", "if", "is", "was", "be", "i", "my", "your", "their", "our", "his", "her", +] as const; + +export const FULL_SENTENCE_MAX_WORDS = 30; + +const END_WORDS = new Set<string>(FRAGMENT_END_WORDS); + +// A word that ends a sentence: its last letter is followed by . ! ? or … +// (closing quotes and brackets allowed after). +const SENTENCE_END_RE = /[.!?…]["'”’)\]]*$/; + +const wordsOf = (text: string) => strictNormalize(text).split(" ").filter(Boolean); + +export type FragmentFinding = { + // Why it is a fragment: "under 4 words", or "ends on “as”". + why: string; + // The part (an ellipsis-joined run, or the whole quote) that is one. + part: string; +}; + +// Whether a quote is a fragment, and which part; null when it is not. +export function fragmentOf(quote: string): FragmentFinding | null { + const total = wordsOf(quote).length; + if (total === 0) return null; + const parts = quoteFragments(quote); + if (total < FRAGMENT_MIN_WORDS) return { why: `under ${FRAGMENT_MIN_WORDS} words`, part: parts.at(-1) ?? quote.trim() }; + for (const part of parts) { + if (SENTENCE_END_RE.test(part.trim())) continue; + const last = wordsOf(part).at(-1); + if (last && END_WORDS.has(last)) return { why: `ends on “${last}”`, part }; + } + return null; +} + +export const isFragmentQuote = (quote: string) => fragmentOf(quote) !== null; + +type TimedText = { start: number; end: number; text: string }; + +type Word = { raw: string; cue: number; norms: string[] }; + +// A cue's first word starts a new sentence when it is capitalised and is not +// the pronoun I (or a contraction of it). +const startsSentence = (raw: string) => /^["'“‘(]?[A-Z]/.test(raw) && !/^["'“‘(]?I(['’][a-z]+)?$/.test(raw); + +// The full sentence a quote (or one part of it) stops short of, from the cues +// overlapping ±windowSeconds of `second`; null when the quote is not found +// there verbatim, or no whole sentence fits the cap. +export function fullSentenceFor( + quote: string, + cues: readonly TimedText[], + second: number, + opts: { windowSeconds?: number; maxWords?: number } = {}, +): string | null { + const win = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS; + const window = cues.filter((c) => c.end > second - win && c.start < second + win); + const words: Word[] = []; + window.forEach((c, k) => { + for (const raw of c.text.split(/\s+/).filter(Boolean)) words.push({ raw, cue: k, norms: wordsOf(raw) }); + }); + const flat: { tok: string; w: number }[] = []; + words.forEach((w, i) => w.norms.forEach((tok) => flat.push({ tok, w: i }))); + const q = wordsOf(quote); + if (!q.length) return null; + // Every place the quote occurs; the one nearest the cited second wins. + let best: { from: number; to: number; dist: number } | null = null; + for (let i = 0; i + q.length <= flat.length; i++) { + let ok = true; + for (let k = 0; k < q.length && ok; k++) ok = flat[i + k]!.tok === q[k]; + if (!ok) continue; + const from = flat[i]!.w; + const to = flat[i + q.length - 1]!.w; + const dist = Math.abs(window[words[from]!.cue]!.start - second); + if (!best || dist < best.dist) best = { from, to, dist }; + } + if (!best) return null; + const cap = Math.max(opts.maxWords ?? FULL_SENTENCE_MAX_WORDS, q.length + 15); + const text = (a: number, b: number) => words.slice(a, b + 1).map((w) => w.raw).join(" "); + const span = (a: number, b: number) => wordsOf(text(a, b)).length; + const lastOfCue = (cue: number) => { + let j = -1; + words.forEach((w, i) => { + if (w.cue === cue) j = i; + }); + return j; + }; + + let start = best.from; + let end = -1; + // 1. Forward to sentence punctuation, or to a cue boundary before a new sentence. + for (let j = best.to; j < words.length && span(start, j) <= cap; j++) { + if (SENTENCE_END_RE.test(words[j]!.raw)) { + end = j; + break; + } + const next = words[j + 1]; + if (next && next.cue !== words[j]!.cue && startsSentence(next.raw)) { + end = j; + break; + } + } + // 2. Unpunctuated: the end of the quote's last cue, then one more cue. + if (end < 0) { + end = lastOfCue(words[best.to]!.cue); + if (fragmentOf(text(start, end)) && end + 1 < words.length) end = lastOfCue(words[end + 1]!.cue); + if (span(start, end) > cap) return null; + } + // 3. Still too short: back to the sentence's start (the previous sentence + // punctuation, else the start of the quote's first cue). + if (wordsOf(text(start, end)).length < FRAGMENT_MIN_WORDS) { + let i = start; + while (i > 0 && !SENTENCE_END_RE.test(words[i - 1]!.raw) && words[i - 1]!.cue === words[start]!.cue) i--; + while (i > 0 && !SENTENCE_END_RE.test(words[i - 1]!.raw) && span(i - 1, end) <= cap && !startsSentence(words[i]!.raw)) i--; + start = i; + } + const out = text(start, end); + return fragmentOf(out) ? null : out; +} + +// The words a check hands back for a fragment: what it is, and the sentence +// to quote instead when there is one — the repair hint. +export function fragmentHint(f: FragmentFinding, sentence: string | null): string { + return ( + `a fragment (${f.why}): "${f.part.slice(0, 120)}" — quote the whole sentence` + + (sentence ? `: "${sentence}"` : " or clause") + ); +} diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -20,7 +20,7 @@ import { } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; import type { Meter } from "./meter"; -import { ollamaChat, OllamaError, PromptTooLargeError } from "./ollama"; +import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; const ASK = "Answer by calling the `answer` tool."; @@ -105,6 +105,19 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`); } +// What a local structuredAnswer's prompt is estimated at — the very request +// localAnswer sends (its messages and its format), counted as ollamaChat +// counts it against the cap (release 28 Q3: a caller fits its text first). +export function structuredPromptEstimate(o: { system: string; user: string; schema: object }): number { + return promptEstimate({ + messages: [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ], + format: o.schema, + }); +} + async function localAnswer<T>(o: Opts): Promise<T> { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts @@ -238,8 +238,12 @@ export function renderReportMarkdown(): string { "recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its " + "cited second is **`inexact`**: a warning, printed and counted, that does not change the " + "exit code; compose and publish do not use it. A GENERATED quote must pass that strict " + - "check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, " + - "`en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.", + "check: a finding whose quote fails it is dropped. A quote under four words, or one that " + + "stops on a function word (`as`, `to`, `the`, …), is a **`fragment`**: a warning too, with the " + + "full sentence to quote when the record has one; a GENERATED fragment fails, and the repair " + + "round is handed that sentence. `drift` and `en-orig-drift` come before `inexact`, and " + + "`inexact` before `fragment`. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, " + + "`fragment`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.", ); out.push(""); out.push("## Making a report from what exists"); diff --git a/common/lib/report/draft/authoringRules.ts b/common/lib/report/draft/authoringRules.ts @@ -32,7 +32,8 @@ export const NARRATION_TASTE = [ "No expressive tags or stage directions of any kind, nothing in angle brackets.", "No stock phrases or filler openers; start with the point.", "Every number and every name you use must already be in the evidence below; add no facts.", - "Do not read quotes out; the clips that follow say them. Do not put a speaker's words in your own mouth.", + "Do not read quotes out; the clips that follow say them.", + "The narrator is third person: never I, me, my, we, us or our, and never a speaker's words as your own.", "Keep every negation and hedge the evidence has; say what was said, not why.", ] as const; @@ -68,6 +69,12 @@ export const VERBATIM_QUOTES_RULE = "never fix a transcript's spelling, grammar or names inside quotes, never join words from two moments " + "into one quote. A quote that is not word for word what was said within 90 seconds of its link is refused."; +// A quote that stops mid-thought (release 28 Q2, lib/citations/fragment.ts) +// is refused in code; the refusal carries the sentence to quote. +export const WHOLE_SENTENCE_QUOTE_RULE = + "Quote a whole sentence or clause: a quote under four words, or one that stops on a function word (an " + + "article, a preposition, a conjunction, a possessive), is refused as a fragment."; + export const ONE_QUOTE_PER_FINDING_RULE = "Each finding is a list item under a `## section`: the claim in plain words, the quoted words in double " + "quotes, then the citation link. One quote, one link per item."; diff --git a/common/lib/report/draft/grounding.test.ts b/common/lib/report/draft/grounding.test.ts @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { checkNarration, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE } from "./grounding"; +import { checkNarration, firstPersonWords, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE, THIRD_PERSON_MESSAGE } from "./grounding"; const REPORTS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/reports"); const basic = JSON.parse(await readFile(path.join(REPORTS, "basic.report.json"), "utf8")); @@ -75,3 +75,35 @@ test("checkNarration carries the lints as soft warnings", () => { assert.equal(r.soft.length, 1); assert.match(r.soft[0]!, /negation mismatch/); }); + +test("hard (Q1): the narrator is third person — a first-person sentence is refused", () => { + // The live smoke's line: no cited quote it restates. + const r = checkNarration("She talks about the contest. I've already finished mine.", input); + assert.equal(r.hard.length, 1, r.hard.join("|")); + assert.ok(r.hard[0]!.startsWith(`${THIRD_PERSON_MESSAGE} (“I've”, “mine”)`), r.hard[0]); + for (const line of ["We tried the bakery.", "That's my oven.", "The oven is ours.", "Let me be clear: the bakery stays.", "So we're done.", "It was us all along."]) { + assert.ok(checkNarration(line, input).hard.some((h) => h.startsWith(THIRD_PERSON_MESSAGE)), line); + } +}); + +test("hard (Q1): a first-person sentence that restates a cited quote names whose line it is and where", () => { + const r = checkNarration("I paid for the mixer myself.", input); + assert.equal(r.hard.length, 1, r.hard.join("|")); + assert.match(r.hard[0]!, /^the narrator is third person \(“I”, “myself”\): this is the speaker's line from c03 \(Bread day @ 0:45\), “I paid for the new mixer myself”/); + // A named speaker is named. + const named = groundingInputOf({ ...basic, citations: { ...basic.citations, c03: { ...basic.citations.c03, speaker: "the baker" } } }); + assert.match(checkNarration("I paid for the mixer myself.", named).hard[0]!, /this is the baker's line from c03/); +}); + +test("Q1: first person inside quotation marks is not the narrator's; word boundaries, not substrings", () => { + assert.deepEqual(firstPersonWords('She said "I quit" and “we are done” twice.'), []); + const quoted = checkNarration('She said "I quit" twice.', input).hard; + assert.ok(!quoted.some((h) => h.startsWith(THIRD_PERSON_MESSAGE)), quoted.join("|")); + assert.ok(quoted.includes("text in quotation marks: no quotes in narration"), "the quote itself is still refused"); + // Not first person: names and words that only contain the letters. + assert.deepEqual(firstPersonWords("Iowa's myth of the mineral museum in the US is idle."), []); + // Accepted collateral: "mine" the noun. + assert.deepEqual(firstPersonWords("The old mine shaft."), ["mine"]); + // Curly apostrophes read as straight ones. + assert.deepEqual(firstPersonWords("I’m sure."), ["I’m".replace("’", "'")]); +}); diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -9,7 +9,11 @@ // - a capitalised name the report does not have (the first word of a // sentence and the COMMON_CAPS words aside); // - text in quotation marks: a narrator does not read quotes out; -// - six or more consecutive words of a cited quote: the clip says it. +// - six or more consecutive words of a cited quote: the clip says it; +// - a first-person word (I, me, my, we, us, our, … — FIRST_PERSON_WORDS) +// outside quotation marks: the narrator is third person (release 28 Q1). +// When the sentence restates a cited quote, the reason names whose line it +// is and where it was cited. // // SOFT (a warning; the line may be used, flagged for review) — the Q0 lints, // for what the hard checks cannot see (plans/local-llm-report-media.md, Q0): @@ -80,15 +84,25 @@ export type GroundingInput = { // The evidence lines (claims and quotes) the Q0 lints compare against; // default: the quotes. evidence?: readonly string[]; + // Every cited quote with who said it and where it is cited, for the + // first-person reason (default: none — the reason names no line). + sources?: readonly QuoteSource[]; }; +export type QuoteSource = { quote: string; speaker?: string; citation?: string }; + export type GroundingResult = { hard: string[]; soft: string[] }; type ReportLike = { title?: string; summary?: string | null; sections?: readonly { title?: string; body?: string | null; claims?: readonly { text?: string; title?: string }[] | null }[]; - citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null; + citations?: + | Record< + string, + { quote?: string; label?: string; date?: string; speaker?: string; channel?: string; id?: string; start?: number } | undefined + > + | null; }; // Every text of a report a narration may draw on: title, summary, section @@ -120,8 +134,75 @@ export function reportEvidence(report: ReportLike): string[] { return [...out, ...reportQuotes(report)]; } +const mmssOf = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; + +// Each cited quote with its speaker and its citation, as the first-person +// reason names them: `c03 (Pie stream @ 0:30)`. +export function reportQuoteSources(report: ReportLike): QuoteSource[] { + const out: QuoteSource[] = []; + for (const [cid, c] of Object.entries(report.citations ?? {})) { + if (!c?.quote) continue; + const where = c.label ?? (c.channel && c.id ? `${c.channel}/${c.id}` : ""); + const at = typeof c.start === "number" ? ` @ ${mmssOf(c.start)}` : ""; + out.push({ quote: c.quote, ...(c.speaker ? { speaker: c.speaker } : {}), citation: where ? `${cid} (${where}${at})` : cid }); + } + return out; +} + export function groundingInputOf(report: ReportLike): GroundingInput { - return { reference: reportText(report), quotes: reportQuotes(report), evidence: reportEvidence(report) }; + return { + reference: reportText(report), + quotes: reportQuotes(report), + evidence: reportEvidence(report), + sources: reportQuoteSources(report), + }; +} + +// ─── the narrator is third person (release 28 Q1) ─── + +// Word-bounded and case-insensitive: "Iowa", "myth" and "mineral" are not +// hits. Two kinds of collateral are accepted: "mine" the noun (a gold mine) +// and a roman numeral I; the all-caps "US" (the country) is not a hit. +export const FIRST_PERSON_WORDS = [ + "i", "i'm", "i've", "i'd", "i'll", "me", "my", "mine", "myself", + "we", "we're", "we've", "we'd", "we'll", "us", "our", "ours", "ourselves", +] as const; + +export const THIRD_PERSON_MESSAGE = "the narrator is third person"; + +const FIRST_PERSON = new Set<string>(FIRST_PERSON_WORDS); + +// A sentence's first-person words outside quotation marks, as written. +export function firstPersonWords(sentence: string): string[] { + const outside = sentence + .replace(/[’‘ʼ]/g, "'") + .replace(/"[^"]*"|“[^”]*”/g, " "); + const out: string[] = []; + for (const m of outside.matchAll(/[A-Za-z]+(?:'[A-Za-z]+)?/g)) { + const w = m[0]; + if (w === "US") continue; + if (FIRST_PERSON.has(w.toLowerCase())) out.push(w); + } + return out; +} + +// The hard problem for each first-person sentence: the rule, and — when the +// sentence restates a cited quote — whose line it is and where it is cited. +export function firstPersonProblems(text: string, sources: readonly QuoteSource[] = []): string[] { + const out: string[] = []; + for (const sent of sentencesOf(text)) { + const words = firstPersonWords(sent); + if (!words.length) continue; + const said = [...new Set(words)].map((w) => `“${w}”`).join(", "); + const line = sources.length ? closest(strictNormalize(sent), sources.map((s) => s.quote)) : null; + const src = line === null ? undefined : sources.find((s) => s.quote === line); + out.push( + src + ? `${THIRD_PERSON_MESSAGE} (${said}): this is ${src.speaker ? `${src.speaker}'s` : "the speaker's"} line from ${src.citation ?? "a citation"}, “${src.quote.slice(0, 80)}”` + : `${THIRD_PERSON_MESSAGE} (${said}): say what the speaker said, not as the speaker`, + ); + } + return out; } const SENTENCE_SPLIT = /(?<=[.!?…])\s+/; @@ -172,6 +253,7 @@ export function checkNarration(text: string, input: GroundingInput): GroundingRe } } } + for (const p of firstPersonProblems(text, input.sources)) hard.add(p); for (const w of lintNarration(text, input.evidence ?? input.quotes)) soft.add(w); return { hard: [...hard].sort(), soft: [...soft].sort() }; } diff --git a/common/lib/report/draft/reportOps.test.ts b/common/lib/report/draft/reportOps.test.ts @@ -198,3 +198,22 @@ test("two-line findings (the claim on the bullet, its quote and link under it) a const { problems } = await sweepToReport(after, { cuesOf }); assert.deepEqual(problems, []); }); + +test("add: a fragment quote is refused, and the refusal carries the full sentence (release 28 Q2)", async () => { + const doc = parseSweep(await readSweep("basic")); + const link = momentHref("synth-kitchen", "pie-stream-02", 40); + const r = await applyReportOps( + doc, + [ + { op: "add", section: "The lease", text: "She will not discuss the lease", quote: "my lawyer told me not to", link }, + { op: "add", section: "The lease", text: "She will not discuss the lease", quote: "my lawyer told me not to talk about the lease", link }, + ], + { checkQuote: strictCheckerOver(cuesOf), origin: "https://synth.example" }, + ); + assert.equal(r.refused.length, 1); + assert.match(r.refused[0]!.why, /a fragment \(ends on “to”\).*"my lawyer told me not to talk about the lease"/); + assert.equal(r.applied.length, 1); + // The words-only checker lets it through. + const words = await strictCheckerOver(cuesOf, { fragments: false })({ channel: "synth-kitchen", id: "pie-stream-02", second: 40, quote: "my lawyer told me not to" }); + assert.deepEqual(words, { ok: true }); +}); diff --git a/common/lib/report/draft/reportOps.ts b/common/lib/report/draft/reportOps.ts @@ -28,6 +28,7 @@ // add). import { STRICT_QUOTE_WINDOW_SECONDS, strictQuoteCheck } from "../../citations/verify"; +import { fragmentHint, fragmentOf, fullSentenceFor } from "../../citations/fragment"; import { LINK_RE, QUOTE_MARK_RE, @@ -64,17 +65,23 @@ export type ReportOpsContext = { }; // The strict checker over a cue reader (testing/draft/corpus.mjs cuesOf, or -// the MCP's transcript read): every fragment verbatim within ±90 s. +// the MCP's transcript read): every fragment verbatim within ±90 s, and the +// quote not a FRAGMENT (release 28 Q2: under four words, or stopping on a +// function word) — the refusal then carries the full sentence to quote. +// `fragments: false` checks the words only. export function strictCheckerOver( cuesOf: (channel: string, id: string) => Promise<readonly { start: number; end: number; text: string }[] | null>, - opts: { windowSeconds?: number } = {}, + opts: { windowSeconds?: number; fragments?: boolean } = {}, ): (q: QuoteCheckRequest) => Promise<QuoteCheckAnswer> { const windowSeconds = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS; return async ({ channel, id, second, quote }) => { const cues = await cuesOf(channel, id); if (!cues || cues.length === 0) return { ok: false, why: `no transcript cues for ${channel}/${id}` }; const r = strictQuoteCheck(quote, cues, second, { windowSeconds }); - return r.ok ? { ok: true } : { ok: false, why: `"${r.failed}" is not there` }; + if (!r.ok) return { ok: false, why: `"${r.failed}" is not there` }; + const frag = opts.fragments === false ? null : fragmentOf(quote); + if (frag) return { ok: false, why: fragmentHint(frag, fullSentenceFor(frag.part, cues, second, { windowSeconds })) }; + return { ok: true }; }; } diff --git a/common/lib/report/draft/sweepModel.test.ts b/common/lib/report/draft/sweepModel.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, splitFinding } from "./sweepModel"; +import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, sectionsNamedBy, splitFinding, trimmedNumberedView } from "./sweepModel"; const SWEEPS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/sweeps"); @@ -86,3 +86,49 @@ test("the numbered view a model reads", async () => { const p = numberedView(parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8"))); assert.match(p, /## Coverage {2}\(coverage — keep\)/); }); + +// A synthetic report of `sections` × `per` findings with long quotes. +function bigSweep(sections: number, per: number): string { + const out = ["# Big", "", "A summary.", ""]; + let n = 0; + for (let s = 1; s <= sections; s++) { + out.push(`## Part ${s}`); + for (let k = 0; k < per; k++) { + n++; + out.push(`- Claim ${n} of part ${s}: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen" [Rec @ 0:${k}](https://synth.example/?v=ch%2Fv${n}&t=${k})`); + } + } + return out.join("\n"); +} + +test("trimmed view (Q3): the named sections first, the rest while the budget lasts; numbers the document's; the omitted said", () => { + const doc = parseSweep(bigSweep(20, 5)); + const full = numberedView(doc); + const v = trimmedNumberedView(doc, { maxChars: 2500, feedback: "Rework Part 17 and drop 3." }); + assert.ok(v.text.length <= 2500 + 400, String(v.text.length)); + assert.ok(full.length > 4 * v.text.length); + assert.deepEqual(v.named, [0, 16], "part 17 by its title; finding 3's section by its number"); + for (const n of [81, 82, 83, 84, 85, 3]) assert.ok(v.shown.includes(n), `[${n}] shown`); + assert.match(v.text, /## Part 17\n\[81\] Claim 81 of part 17/); + // Shown in document order; the left-out findings named by number. + assert.ok(v.text.indexOf("## Part 1\n") < v.text.indexOf("## Part 17")); + assert.match(v.text, /## Part 20 {2}\(findings \[96\]–\[100\] not shown\)/); + assert.equal(v.shown.length + v.omitted.length, 100); + // Quotes shortened and links reduced to their labels, in the view only. + assert.match(v.text, /\[81\] Claim 81 of part 17: "one two three four five six seven eight …" \[Rec @ 0:0\]/); + assert.ok(!v.text.includes("https://")); + assert.ok(renderSweep(doc).includes("fifteen\" [Rec @ 0:0](https://synth.example/?v=ch%2Fv81&t=0)"), "the document is untouched"); + // No feedback: document order. + const plain = trimmedNumberedView(doc, { maxChars: 2500 }); + assert.ok(plain.shown.includes(1) && !plain.shown.includes(81)); + // A budget that holds everything shows everything. + assert.equal(trimmedNumberedView(doc, { maxChars: 1e6 }).omitted.length, 0); +}); + +test("sectionsNamedBy: titles, section numbers, finding numbers", () => { + const doc = parseSweep(bigSweep(4, 2)); + assert.deepEqual([...sectionsNamedBy(doc, "In part 2, reword the claim.")], [1]); + assert.deepEqual([...sectionsNamedBy(doc, "section 4 is too long")].sort(), [3]); + assert.deepEqual([...sectionsNamedBy(doc, "merge [5] into 6")].sort(), [2]); + assert.deepEqual([...sectionsNamedBy(doc, "trim it to 30 s")], []); +}); diff --git a/common/lib/report/draft/sweepModel.ts b/common/lib/report/draft/sweepModel.ts @@ -212,3 +212,115 @@ export function numberedView(doc: SweepDoc): string { export function quotesOf(f: Finding): string[] { return [...evidenceOf(f).matchAll(new RegExp(QUOTED_RE.source, "g"))].map((m) => m[0].slice(1, -1)); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// A local model gets the numbered view in ONE prompt under the 8k cap, so the +// view is trimmed to a character budget: the sections the feedback names +// first (a section's title, "section N", or the number of a finding in it), +// then the rest in document order, finding by finding while the budget lasts. +// It is shown in document order; what is left out is said, with its numbers. +// Quotes are shortened and links reduced to their labels IN THE VIEW ONLY: an +// op still numbers against the whole document and never reaches a quote. + +export const VIEW_QUOTE_WORDS = 12; + +const normWords = (s: string) => + s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s]/gu, " ") + .replace(/\s+/g, " ") + .trim(); + +// A quoted span cut to its first words when it is long. +function shortQuote(q: string, words: number): string { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +} + +// A finding's evidence as the trimmed view shows it. +export function shortEvidence(f: Finding, quoteWords = VIEW_QUOTE_WORDS): string { + return evidenceOf(f) + .replace(new RegExp(QUOTED_RE.source, "g"), (m) => `"${shortQuote(m.slice(1, -1), quoteWords)}"`) + .replace(new RegExp(LINK_RE.source, "g"), (m) => m.slice(0, m.indexOf("](") + 1)); +} + +// The sections (their indices) the feedback names. +export function sectionsNamedBy(doc: SweepDoc, feedback: string): Set<number> { + const fb = ` ${normWords(feedback)} `; + const out = new Set<number>(); + // What is left once the titles and "section N" are taken out: its numbers + // are findings' ("drop 3", "[5]"). + let rest = ` ${normWords(feedback)} `; + doc.sections.forEach((s, i) => { + const t = normWords(s.title); + if (t.length >= 3 && fb.includes(` ${t} `)) { + out.add(i); + rest = rest.split(` ${t} `).join(" "); + } + if (new RegExp(`\\b(?:section|§)\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + rest = rest.replace(/\bsection \d+/g, " ").replace(/\b\d+ ?(?:s|sec|secs|seconds|min|minutes|percent)\b/g, " "); + const numbers = new Set([...rest.matchAll(/\b(\d{1,4})\b/g)].map((m) => Number(m[1]))); + for (const x of numberFindings(doc)) if (numbers.has(x.n)) out.add(doc.sections.indexOf(x.section)); + return out; +} + +export type TrimmedView = { text: string; shown: number[]; omitted: number[]; named: number[] }; + +export function trimmedNumberedView( + doc: SweepDoc, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): TrimmedView { + const numbered = numberFindings(doc); + const numberOf = new Map(numbered.map((x) => [x.finding, x.n])); + const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" "); + const head = [`TITLE: ${doc.title}`, `SUMMARY: ${summary.length > 600 ? `${summary.slice(0, 600)} …` : summary}`]; + const named = o.feedback ? sectionsNamedBy(doc, o.feedback) : new Set<number>(); + const order = [...doc.sections.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + let used = head.join("\n").length + doc.sections.reduce((n, s) => n + s.title.length + 40, 0); + // Which blocks of each section are shown. + const keep = new Map<number, Set<SweepBlock>>(); + for (const i of order) { + const set = new Set<SweepBlock>(); + keep.set(i, set); + for (const b of doc.sections[i]!.body) { + const line = + b.type === "finding" ? `[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}` : b.text.trim(); + if (!line) continue; + if (used + line.length + 1 > o.maxChars) continue; + used += line.length + 1; + set.add(b); + } + } + const lines = [...head]; + const shown: number[] = []; + const omitted: number[] = []; + doc.sections.forEach((s, i) => { + const set = keep.get(i)!; + const left = findingsOf(s).filter((f) => !set.has(f)).map((f) => numberOf.get(f)!); + const note = left.length ? ` (findings ${ranges(left)} not shown)` : ""; + lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}${note}`); + for (const b of s.body) { + if (!set.has(b)) continue; + if (b.type === "finding") { + lines.push(`[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}`.trimEnd()); + shown.push(numberOf.get(b)!); + } else lines.push(b.text); + } + omitted.push(...left); + }); + return { text: lines.join("\n"), shown: shown.sort((a, b) => a - b), omitted: omitted.sort((a, b) => a - b), named: [...named].sort((a, b) => a - b) }; +} + +// 1, 2, 3, 5 → "[1]–[3], [5]". +function ranges(ns: readonly number[]): string { + const out: string[] = []; + for (let i = 0; i < ns.length; ) { + let j = i; + while (j + 1 < ns.length && ns[j + 1] === ns[j]! + 1) j++; + out.push(j > i ? `[${ns[i]}]–[${ns[j]}]` : `[${ns[i]}]`); + i = j + 1; + } + return out.join(", "); +} diff --git a/common/lib/report/draft/tasks/quotes.ts b/common/lib/report/draft/tasks/quotes.ts @@ -3,7 +3,9 @@ // // The check a GENERATED quote must pass is the strict one (D3): every quoted // fragment verbatim (normalised) in the record's cues within ±90 s of its -// cited second; a post's quote in the post's text. An outside verifier (the +// cited second; a post's quote in the post's text. And it may not be a +// FRAGMENT (release 28 Q2, lib/citations/fragment.ts): the problem then +// carries the full sentence, the repair round's hint. An outside verifier (the // editor's verify-quotes over the corpus on disk, which also reads the en-orig // track) may add problems. A finding whose quote fails after the one repair // round is DROPPED, never repaired by code. @@ -12,6 +14,7 @@ import { sweepToReport } from "../../convertSweep"; import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { Report } from "../../schema"; import { strictNormalize, strictQuoteCheck, strictTextCheck, quoteFragments } from "../../../citations/verify"; +import { fragmentHint, fragmentOf, fullSentenceFor } from "../../../citations/fragment"; import { evidenceOf, findingsOf, parseSweep, quotesOf, renderSweep, LINK_RE, type SweepDoc } from "../sweepModel"; import { parseCitationHref } from "../../convertShared"; import { mmss } from "../reportOps"; @@ -26,6 +29,10 @@ export type QuoteProblem = { why: string; // The transcript ±45 s around the cited second, for a repair. near?: string; + // A FRAGMENT (release 28 Q2): the words are there, but the quote stops + // mid-thought. `sentence` is the full sentence to quote instead (the repair + // hint), null when none fits. + fragment?: { why: string; part: string; sentence: string | null }; }; export type ConvertOutcome = @@ -78,6 +85,12 @@ export async function checkQuotes( const r = strictTextCheck(quote, text); if (!r.ok) { problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: `"${r.failed}" is not the post's words`, near: text }); + continue; + } + const frag = fragmentOf(quote); + if (frag) { + const sentence = fullSentenceFor(frag.part, [{ start: 0, end: 1, text }], 0); + problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: fragmentHint(frag, sentence), fragment: { ...frag, sentence } }); } continue; } @@ -101,12 +114,20 @@ export async function checkQuotes( why: `not verbatim within 90 s of ${Math.floor(c.start)} s: "${r.failed}"`, near, }); + continue; + } + const frag = fragmentOf(quote); + if (frag) { + const sentence = fullSentenceFor(frag.part, cues, c.start); + problems.push({ citation: cid, channel: c.channel, id: c.id, second: c.start, quote, why: fragmentHint(frag, sentence), fragment: { ...frag, sentence } }); } } if (deps.verifyReport) { const seen = new Set(problems.map((p) => p.citation)); for (const p of await deps.verifyReport(report)) { - if (seen.has(p.citation) || p.status === "ok" || p.status === "inexact") continue; + // A warning (inexact, fragment) is not a problem: the strict and + // fragment checks above are this run's own. + if (seen.has(p.citation) || p.status === "ok" || p.status === "inexact" || p.status === "fragment") continue; const c = report.citations?.[p.citation] as { channel?: string; id?: string; start?: number; quote?: string } | undefined; problems.push({ citation: p.citation, diff --git a/common/lib/report/draft/tasks/research.ts b/common/lib/report/draft/tasks/research.ts @@ -184,8 +184,10 @@ async function researchBody(h: TaskHandle, input: ResearchInput): Promise<TaskOu .filter(Boolean) .join(" "); const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); + if (e.type === "turn") { + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 60 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + } else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); else if (e.type === "note") h.log(e.text); }; const run = await runAgent({ diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts @@ -8,12 +8,28 @@ // corpus (the MCP's read tools), the operator's notes, and the web for context. // Then the link backstop, convert and the quote check: a NEW finding whose // quote fails is dropped, never repaired. +// +// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound +// ask (`structuredAnswer`) for the whole ops batch, over the numbered view +// trimmed to the model's prompt cap (sweepModel trimmedNumberedView: the +// sections the feedback names first, quotes shortened in the view only). The +// ops still number against the whole document. The API path is unchanged. -import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; +import { + CHARS_PER_TOKEN, + ollamaConfigOf, + promptCapOf, + providerOf, + runAgent, + structuredAnswer, + structuredPromptEstimate, + type AgentTool, + type LlmConfig, +} from "../../../llm"; import { lineage, readIterationFile, writeIterationFile } from "../../iterations"; -import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, momentLinkRule } from "../authoringRules"; +import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule } from "../authoringRules"; import { applyReportOps, strictCheckerOver, type AppliedOp, type RefusedOp } from "../reportOps"; -import { numberedView, parseSweep, renderSweep, type SweepDoc } from "../sweepModel"; +import { numberedView, parseSweep, renderSweep, trimmedNumberedView, type SweepDoc } from "../sweepModel"; import { extractJsonObject } from "../../../parseStdoutJson"; import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes"; @@ -31,9 +47,20 @@ export const COMMON_REVISE_RULES = (what: string) => "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words. When done, stop calling tools and say in one line what you changed.", ].join(" "); -export const REPORT_OPS_TEXT = (origin: string) => +// A local revision's rules: one answer, no tools (release 28 Q3). +export const LOCAL_REVISE_RULES = (what: string) => [ - "Operations (objects for apply_ops; `n` is a finding's number as read_doc shows it — one batch numbers against the document at its start):", + `You revise one ${what} of a report built from video transcripts, following the operator's feedback.`, + UNATTENDED_RULE, + "Answer with ONE batch of edit operations, the `ops` list, that carries out the feedback: code applies it and refuses any op that breaks a rule. The view may leave some of it out (it says what); an op may still name what is not shown.", + "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words.", + ].join(" "); + +export const REPORT_OPS_TEXT = (origin: string, local = false) => + [ + local + ? "Operations (objects in the `ops` list; `n` is a finding's number as the view shows it — the batch numbers against the report as shown):" + : "Operations (objects for apply_ops; `n` is a finding's number as read_doc shows it — one batch numbers against the document at its start):", '- {"op":"drop","n":N} remove finding N', '- {"op":"claim","n":N,"text":"..."} rewrite finding N\'s claim (its quote and link stay as they are)', '- {"op":"merge","n":N,"into":M,"text":"..."} fold finding N into finding M: M keeps every quote with its own link; "text" (optional) is M\'s new claim', @@ -43,6 +70,7 @@ export const REPORT_OPS_TEXT = (origin: string) => '- {"op":"title","text":"..."} / {"op":"summary","text":"..."}', CLAIM_QUOTES_RULE, VERBATIM_QUOTES_RULE, + WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule(origin), ].join("\n"); @@ -88,6 +116,29 @@ export type ReviseReportInput = { maxTurns?: number; }; +// A local ask's user text, fitted under the model's prompt cap: `build` makes +// it at a character budget, which shrinks until the whole request — system, +// user and the ops schema, counted as ollamaChat counts them — fits. +export function fitLocalAsk(o: { + llm: LlmConfig; + model: string; + system: string; + schema: object; + build: (maxChars: number) => string; +}): { user: string; tokens: number; cap: number } { + const cap = promptCapOf(ollamaConfigOf(o.llm, o.model)); + let maxChars = Math.floor(cap * CHARS_PER_TOKEN) - o.system.length - JSON.stringify(o.schema).length; + let user = ""; + let tokens = Number.POSITIVE_INFINITY; + for (let k = 0; k < 40 && maxChars >= 400; k++) { + user = o.build(maxChars); + tokens = structuredPromptEstimate({ system: o.system, user, schema: o.schema }); + if (tokens <= cap) break; + maxChars = Math.floor(maxChars * 0.85); + } + return { user, tokens, cap }; +} + // The nearest iteration in `n`'s lineage (n excluded) with a sweep.md. export async function parentSweep(h: Pick<TaskHandle, "article" | "n" | "paths">): Promise<{ from: number; md: string } | null> { const line = await lineage(h.article, h.n, h.paths); @@ -144,7 +195,17 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis const applied: AppliedOp[] = []; const refused: RefusedOp[] = []; const added: string[] = []; - h.log(`revising the report of i${parent.from} on ${model}`); + const local = providerOf(model) === "local"; + h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}`); + const applyOps = async (ops: unknown[]) => { + const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); + doc = r.doc; + applied.push(...r.applied); + refused.push(...r.refused); + for (const a of r.applied) if (a.op.op === "add") added.push(String(a.op.quote ?? "")); + h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + return r; + }; const tools: AgentTool[] = [ ...reviseCorpusTools(deps, rewrite), @@ -160,56 +221,72 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the report after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { - const ops = Array.isArray(inp?.ops) ? inp.ops : []; - const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); - doc = r.doc; - applied.push(...r.applied); - refused.push(...r.refused); - for (const a of r.applied) if (a.op.op === "add") added.push(String(a.op.quote ?? "")); - h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + const r = await applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return `${JSON.stringify({ applied: r.applied.length, refused: r.refused.map((x) => ({ index: x.index, op: x.op.op, why: x.why })) })}\n\nNow:\n${numberedView(doc)}`; }, }, ]; - const system = `${COMMON_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin)}`; - const run = await runAgent({ - llm: deps.llm, - model, - system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}`, - tools, - meter: h.meter, - maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) gets ONE schema-bound ask for the batch; nothing at all - // after that is a failing check, not a quiet "0 applied". - if (applied.length + refused.length === 0) { - const asked = await structuredAnswer<{ ops?: unknown[] }>({ + if (local) { + await localOpsBatch(h, { + model, + system: `${LOCAL_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin, true)}`, + what: "report", + build: (maxChars) => { + const v = trimmedNumberedView(doc, { maxChars: maxChars - feedback.length - 300, feedback }); + return ( + `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW (findings numbered [n]; in this view quotes are shortened ` + + `and links cut to their labels — the report keeps them whole):\n${v.text}\n\nAnswer with the ops batch that carries out the feedback.` + ); + }, + apply: applyOps, + }); + } else { + await apiRevision(); + } + async function apiRevision() { + const system = `${COMMON_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin)}`; + const run = await runAgent({ llm: deps.llm, model, system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}\n\nAnswer with the ops batch that carries out the feedback.`, - schema: OPS_SCHEMA, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}`, + tools, meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 30, + ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type !== "turn") return; + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - if (asked && Array.isArray(asked.ops) && asked.ops.length) { - h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); - await tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + h.turns(run.transcript); + if (run.stopReason === "cancelled") return; + // A model that ends without calling apply_ops gets ONE schema-bound ask for + // the batch; nothing at all after that is a failing check, not a quiet "0 + // applied". + if (applied.length + refused.length === 0) { + const asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + model, + system, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}\n\nAnswer with the ops batch that carries out the feedback.`, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) { + h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); + await applyOps(asked.ops); + } } } + if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, @@ -241,10 +318,17 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis } await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); h.check({ name: "convert", ok: true }); + // A fragment the parent already quoted is a warning, as verify-quotes says + // of an existing report (release 28 Q2); what fails the words is a failure. + const failing = problems.filter((p) => !p.fragment); + const fragments = problems.filter((p) => p.fragment); + const warn = fragments.length ? `; ${fragments.length} fragment quote(s) from the iteration revised (a warning)` : ""; h.check({ name: "quotes", - ok: problems.length === 0, - detail: problems.length ? `${problems.length} quote(s) fail the strict check (from the iteration revised): ${problems.map((p) => p.why).slice(0, 3).join("; ")}` : "every quote verbatim (strict)", + ok: failing.length === 0, + detail: failing.length + ? `${failing.length} quote(s) fail the strict check (from the iteration revised): ${failing.map((p) => p.why).slice(0, 3).join("; ")}${warn}` + : `every quote verbatim (strict)${warn}`, }); await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths); return { @@ -253,3 +337,32 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis patch: { ops }, }; } + +// A local revision's one ops batch: the view fitted under the prompt cap, one +// structuredAnswer, the ops applied. A failed ask is logged (the ops check +// then says nothing was proposed); a cancel is rethrown. +export async function localOpsBatch( + h: TaskHandle, + o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown> }, +): Promise<void> { + const { deps } = h; + const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema: OPS_SCHEMA, build: o.build }); + h.log(`one ops batch over the ${o.what} (~${fitted.tokens} of ${fitted.cap} prompt tokens)`); + const t0 = Date.now(); + const asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + model: o.model, + system: o.system, + user: fitted.user, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + if (deps.signal?.aborted) throw e; + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + h.turns([{ kind: "model", what: "ops batch", tokens: fitted.tokens, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: asked }]); + h.progress({ metric: "turns", current: 1, total: 1 }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) await o.apply(asked.ops); +} diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts @@ -8,13 +8,18 @@ // new cut is this iteration's project, seeded from the parent's: the report // and stills copied, the voices hard-linked. A video revision has no report of // its own (its article's report stays its nearest ancestor's). +// +// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound ask +// for the ops batch over the cut trimmed to the prompt cap (videoOps +// trimmedCutView: the chapters the feedback names first, quotes shortened in +// the view only), as revise-report does. The API path is unchanged. import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; import { readIteration, type Iteration } from "../../iterations"; -import { applyVideoOps, cutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; +import { applyVideoOps, cutView, trimmedCutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; import { rewriteMomentBases, slugResolver } from "./links"; import { projectDirOf, readManifest, readProjectReport, seedProject, writeManifest } from "./project"; -import { COMMON_REVISE_RULES, OPS_SCHEMA, reviseCorpusTools } from "./revise-report"; +import { COMMON_REVISE_RULES, LOCAL_REVISE_RULES, OPS_SCHEMA, localOpsBatch, reviseCorpusTools } from "./revise-report"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; @@ -23,12 +28,17 @@ export const VIDEO_OPS_TEXT = [ '- {"op":"drop","id":"<entry id>"} remove an entry', '- {"op":"move","id":"<entry id>","after":"<entry id, or \'start\'>"} reorder', '- {"op":"heading","id":"<card id>","text":"..."} a card\'s on-screen heading', - '- {"op":"narration","id":"<card id>","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', + '- {"op":"narration","id":"<card id>","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; third person — never I, me, my, we, us or our; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', '- {"op":"trim","id":"<clip id>","start":S,"end":E} a clip\'s in/out seconds, within 3 s of its current ones', '- {"op":"add_clip","citation":"<citation id from the report>","after":"<entry id>"} a clip for a cited moment not in the cut', '- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}', ].join("\n"); +const shortQuote = (q: string, words = 12) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q; +}; + export type ReviseVideoInput = { article: string; n: number; @@ -82,6 +92,14 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< .map(([cid, c]) => `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${String(c?.quote ?? "").slice(0, 160)}"`) .join("\n"); const view = () => `${cutView(manifest)}\n\nREPORT CITATIONS (add_clip takes these ids):\n${cites}`; + const applyOps = (ops: unknown[]) => { + const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest }); + manifest = r.manifest; + applied.push(...r.applied); + refused.push(...r.refused); + h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + return r; + }; h.log(`revising the cut of i${parent.it.n} on ${model}`); const tools: AgentTool[] = [ @@ -93,11 +111,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { - const r = applyVideoOps(manifest, Array.isArray(inp?.ops) ? inp.ops : [], { report, parent: parent.manifest }); - manifest = r.manifest; - applied.push(...r.applied); - refused.push(...r.refused); - h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return ( JSON.stringify({ applied: r.applied.map((a) => ({ index: a.index, op: a.op.op, ...(a.warnings ? { warnings: a.warnings } : {}) })), @@ -107,45 +121,83 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< }, }, ]; - const system = `${COMMON_REVISE_RULES("video cut (an evidence video: cards with spoken narration between clips of what was said)")}\n\n${VIDEO_OPS_TEXT}`; - const run = await runAgent({ - llm: deps.llm, - model, - system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, - tools, - meter: h.meter, - maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) gets ONE schema-bound ask for the batch; nothing at all - // after that is a failing check, not a quiet "0 applied". - if (applied.length + refused.length === 0) { - const asked = await structuredAnswer<{ ops?: unknown[] }>({ + const what = "video cut (an evidence video: cards with spoken narration between clips of what was said)"; + if (providerOf(model) === "local") { + // Release 28 Q3: one ops batch over the cut trimmed to the prompt cap. + const citeRows = Object.entries(report.citations ?? {}).map(([cid, c]) => ({ + cid, + line: `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${shortQuote(String(c?.quote ?? ""))}"`, + })); + const named = (cid: string) => new RegExp(`\\b${cid}\\b`).test(feedback); + const citeOrder = [...citeRows].sort((a, b) => Number(named(b.cid)) - Number(named(a.cid))); + await localOpsBatch(h, { + model, + system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`, + what: "cut", + build: (maxChars) => { + const budget = maxChars - feedback.length - 400; + const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback }); + let left = budget - cut.text.length; + const shown: string[] = []; + for (const c of citeOrder) { + if (c.line.length + 1 > left) continue; + left -= c.line.length + 1; + shown.push(c.cid); + } + const lines = citeRows.filter((c) => shown.includes(c.cid)).map((c) => c.line); + const more = citeRows.length - lines.length; + return ( + `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW (quotes shortened in this view only):\n${cut.text}\n\n` + + `REPORT CITATIONS (add_clip takes these ids${more ? `; ${more} more not shown` : ""}):\n${lines.join("\n")}\n\n` + + `THE REPORT IT IS CUT FROM: ${String(report.title ?? "")}\n\nAnswer with the ops batch that carries out the feedback.` + ); + }, + apply: async (ops) => applyOps(ops), + }); + } else { + const system = `${COMMON_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT}`; + const run = await runAgent({ llm: deps.llm, model, system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`, - schema: OPS_SCHEMA, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, + tools, meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 30, + ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type !== "turn") return; + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - if (asked && Array.isArray(asked.ops) && asked.ops.length) { - h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); - await tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + h.turns(run.transcript); + if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; + // A model that ends without calling apply_ops gets ONE schema-bound ask for + // the batch; nothing at all after that is a failing check, not a quiet "0 + // applied". + if (applied.length + refused.length === 0) { + const asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + model, + system, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) { + h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); + applyOps(asked.ops); + } } } + if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -19,7 +19,7 @@ import { type IterationPatch, } from "../../iterations"; import { ArticleRegistryError } from "../../registry"; -import type { StorePaths, TaskDeps, TaskResult, TaskStatus } from "./types"; +import type { StorePaths, TaskDeps, TaskProgress, TaskResult, TaskStatus } from "./types"; export class TaskInputError extends Error {} @@ -38,6 +38,8 @@ export type TaskHandle = { deps: TaskDeps; paths: StorePaths | undefined; log(line: string): void; + // Progress for the job (deps.progress); a listener never stops the task. + progress(p: TaskProgress): void; // Turns for turns.jsonl (an agent's transcript, a pipeline's events). turns(entries: readonly unknown[]): void; check(c: IterationCheck): void; @@ -133,6 +135,13 @@ export async function runOnIteration( deps, paths, log, + progress: (p) => { + try { + deps.progress?.(p); + } catch { + // a listener never stops the task + } + }, turns: (entries) => turns.push(...entries), check: (c) => { const i = checks.findIndex((x) => x.name === c.name); diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -21,6 +21,7 @@ import { REPORT_STYLE_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, + WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule, } from "../authoringRules"; import { plainAnswer, userCharsFor } from "./llmText"; @@ -93,6 +94,7 @@ function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from `- ${ONE_QUOTE_PER_FINDING_RULE}`, `- ${CLAIM_QUOTES_RULE}`, `- ${VERBATIM_QUOTES_RULE}`, + `- ${WHOLE_SENTENCE_QUOTE_RULE}`, `- ${momentLinkRule(o.origin)}`, `- ${POST_CITATION_RULE}`, `- ${COVERAGE_RULE}`, @@ -109,7 +111,8 @@ const REPAIR_SYSTEM = [ "You repair a sweep report whose quote checks failed. You have the report tools only (read_report, edit_report, write_report); the transcript each fix needs is in the message.", `- ${VERBATIM_QUOTES_RULE}`, `- ${CLAIM_QUOTES_RULE}`, - "For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second), or remove the finding. Never invent words. Edit the report only, then stop.", + `- ${WHOLE_SENTENCE_QUOTE_RULE}`, + "For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second); a fragment's fix is the whole sentence given with it; or remove the finding. Never invent words. Edit the report only, then stop.", ].join("\n"); function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise<string>, count: { n: number }): AgentTool { @@ -197,8 +200,15 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta const web = input.web === false ? [] : (deps.web ?? []); const tools = [...corpusTools, extractTool(h, input, rewrite, extracts), ...file.tools, ...web]; const isApi = providerOf(model) === "api"; + const maxTurns = input.maxTurns ?? 150; + // The job's progress: every model turn, the repair round's included. + let turnsTaken = 0; const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + if (e.type === "turn") { + turnsTaken++; + h.progress({ metric: "turns", current: turnsTaken, total: Math.max(turnsTaken, maxTurns) }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + } else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); else if (e.type === "note") h.log(e.text); }; @@ -210,7 +220,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta tools, meter: h.meter, maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? 150, + maxTurns, ...(isApi && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 5 } } : {}), signal: deps.signal, onEvent, @@ -238,7 +248,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta system: REPAIR_SYSTEM, user: "The quote checks refused these citations — the quoted words are not, word for word, what the transcript says " + - `at that moment:\n${describeProblems(problems)}\n\nThe report now:\n\n${file.text()}`, + `at that moment, or the quote is a fragment:\n${describeProblems(problems)}\n\nThe report now:\n\n${file.text()}`, tools: file.tools, meter: h.meter, maxUsd: h.meter.usd + allowance, diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -15,6 +15,7 @@ import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; import { writeIterationFile } from "../../iterations"; import { mmss } from "../reportOps"; import { strictNormalize } from "../../../citations/verify"; +import { fragmentOf, fullSentenceFor } from "../../../citations/fragment"; import { momentHref } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; @@ -53,7 +54,7 @@ export const TERMS_SCHEMA = { export const EXTRACT_SYSTEM = "You read excerpts of an automatic transcript and pick out evidence for a research question. Rules: (1) Only use the " + "excerpt; never add facts. (2) Each quote is copied EXACTLY, character for character, from consecutive transcript " + - "lines, without the bracketed timestamps; at least 8 and at most 40 words; do not fix grammar, spelling or names. " + + "lines, without the bracketed timestamps; at least 8 and at most 40 words, a whole sentence or clause; do not fix grammar, spelling or names. " + "(3) Each claim is one plain sentence saying what the speaker says in that quote, attributed to the speaker; keep " + "every negation (not, never, no) and every hedge (maybe, I think, allegedly, if) the quote has; do not state motives " + "or feelings; do not exaggerate; paraphrase in the third person in at most 20 words, do not repeat the quote. Set " + @@ -365,6 +366,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T let nChunks = 0; let nRelevant = 0; const readIds: string[] = []; + // The job's progress: the recordings gone through, of the worklist. + let visited = 0; + h.progress({ metric: "entries", current: 0, total: todo.length }); for (let b = 0; b < todo.length; b += READ_BATCH) { deps.signal?.throwIfAborted(); const batch = todo.slice(b, b + READ_BATCH); @@ -379,6 +383,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const p = parsed.get(v.id); if (!p || !p.lines.length) { event({ kind: "unread", video: v.id, why: "no windows returned" }); + h.progress({ metric: "entries", current: ++visited, total: todo.length }); continue; } readIds.push(v.id); @@ -419,16 +424,29 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { - const quote = String(raw.quote ?? "") + let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:]+\]\s*/, ""); const claim = String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); - const wc = quote.split(" ").filter(Boolean).length; const sec = locate(quote, ch); + // A quote that stops mid-thought (Q2) becomes its whole sentence + // when the window has one: code copies the words, still verbatim. + const frag = sec === null ? null : fragmentOf(quote); + if (frag) { + const lines = win.map(([s, t], i) => ({ start: s, end: win[i + 1]?.[0] ?? s + 1, text: t })); + const whole = fullSentenceFor(quote, lines, sec!, { windowSeconds: Number.MAX_SAFE_INTEGER }); + if (whole && whole.split(" ").length <= MAX_QUOTE_WORDS) { + event({ kind: "extended", video: v.id, quote, to: whole }); + quote = whole; + } + } + const wc = quote.split(" ").filter(Boolean).length; + const stillFragment = sec === null ? null : fragmentOf(quote); let why: string | null = null; if (sec === null) why = "not verbatim in its window"; + else if (stillFragment) why = `a fragment (${stillFragment.why})`; else if (wc < MIN_QUOTE_WORDS) why = `too short (${wc} words)`; else if (wc > MAX_QUOTE_WORDS) why = `too long (${wc} words)`; else if (!claim) why = "no claim"; @@ -456,6 +474,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T } } h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); + h.progress({ metric: "entries", current: ++visited, total: todo.length }); } } if (!kept.length) { diff --git a/common/lib/report/draft/tasks/tasks.test.ts b/common/lib/report/draft/tasks/tasks.test.ts @@ -15,6 +15,8 @@ import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { cardContext, chooseDraft } from "./narrate"; import { groundingInputOf } from "../grounding"; +const DRAFT_SWEEPS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../testing/draft/sweeps"); + const stubCorpus = (slugs: Record<string, string>) => ({ calls: [] as unknown[], async call(name: string, args: Record<string, unknown> = {}) { @@ -173,6 +175,27 @@ test("quotes: the strict check over cues and posts; the failing finding dropped, assert.ok(more.length > problems.length); }); +test("quotes: a generated fragment is a failing quote whose repair hint is the full sentence (testing/draft/sweeps/fragment.md)", async () => { + const md = await readFile(path.join(DRAFT_SWEEPS, "fragment.md"), "utf8"); + const c = await convertSweepText(md, { id: "frag", cuesOf }); + assert.ok(c.ok); + if (!c.ok) return; + const problems = await checkQuotes(c.report, { cuesOf }); + assert.equal(problems.length, 3); + const by = Object.fromEntries(problems.map((p) => [p.quote, p])); + assert.equal(by["I paid for the"]!.fragment!.sentence, "I paid for the new mixer myself"); + assert.match(by["I paid for the"]!.why, /a fragment \(ends on “the”\).*quote the whole sentence: "I paid for the new mixer myself"/); + assert.equal(by["my lawyer told me not to"]!.fragment!.sentence, "my lawyer told me not to talk about the lease"); + assert.match(by["I did not"]!.why, /under 4 words.*"I did not enter the contest this year"/); + // Still a fragment after the repair round: the finding goes, the whole one stays. + const d = dropFailedFindings(md, problems); + assert.equal(d.dropped.length, 3); + assert.ok(d.md.includes('"I have never met the other finalist"')); + // A verify-quotes `fragment` is a warning, not one more problem. + const more = await checkQuotes(c.report, { cuesOf, verifyReport: async () => [{ citation: "c04", status: "fragment" }] }); + assert.equal(more.length, 3); +}); + test("narrate: a card's evidence; the better draft kept, failing sentences removed, never rewritten", async () => { const report = { title: "The baker", diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -28,6 +28,13 @@ export type CorpusToolsLike = { // the corpus on disk, which also sees the en-orig track). export type ExternalQuoteProblem = { citation: string; status: string; message?: string }; +// How far a task has got (release 28 F3): an agent's turns, a media task's +// cards, a pipeline's recordings read (or a media task's entries). `total`, +// when known, is the target (an agent's: its turn cap). The editor job maps it +// onto its JobProgress. +export type TaskProgressMetric = "turns" | "cards" | "entries"; +export type TaskProgress = { metric: TaskProgressMetric; current: number; total?: number }; + export type TaskDeps = { llm: LlmConfig; corpus: CorpusToolsLike; @@ -52,6 +59,8 @@ export type TaskDeps = { paths?: StorePaths; now?: () => Date; log?: (line: string) => void; + // Progress, as the task counts it (the editor job's setProgress). + progress?: (p: TaskProgress) => void; signal?: AbortSignal; }; diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { applyVideoOps, cutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; +import { applyVideoOps, chaptersNamedBy, chaptersOf, cutView, trimmedCutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; const DRAFT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft"); const json = async (p: string) => JSON.parse(await readFile(path.join(DRAFT, p), "utf8")); @@ -131,3 +131,19 @@ test("the cut as a model reads it", () => { assert.match(v, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUBTITLE: \n- card title \(title\) heading: /); assert.match(v, /\n- clip c01 synth-kitchen\/bread-day-01 15–19\.8 s quote: "I would never sell the bakery to a chain"/); }); + +test("trimmed cut view (Q3): the named chapter in full, every entry still listed by id", () => { + const full = cutView(manifest); + const chapters = chaptersOf(manifest); + assert.ok(chapters.length >= 3); + const last = chapters.at(-1)!; + const card = last.find((e) => e.type === "card")!; + const v = trimmedCutView(manifest, { maxChars: 600, feedback: `Rename ${card.id}.` }); + assert.deepEqual([...chaptersNamedBy(manifest, `Rename ${card.id}.`)], [chapters.length - 1]); + for (const e of last) assert.ok(v.full.includes(e.id), `${e.id} in full`); + for (const e of manifest.timeline) assert.ok(v.text.includes(` ${e.id}`), `${e.id} listed`); + assert.ok(v.short.length > 0); + assert.match(v.text, /\(not shown in full\)/); + assert.ok(v.text.length < full.length); + assert.equal(trimmedCutView(manifest, { maxChars: 1e6 }).short.length, 0); +}); diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts @@ -210,3 +210,88 @@ export function cutView(m: VideoManifest): string { } return lines.join("\n"); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// The cut in timeline order under a character budget: the chapters the +// feedback names (a card's heading or an entry's id, or "chapter N") are shown +// in full first, then the rest in order while the budget lasts; an entry left +// out is listed by its id alone, so an op may still name it. Quotes are +// shortened IN THE VIEW ONLY. + +export const CUT_VIEW_QUOTE_WORDS = 12; + +const shortQ = (q: string, words: number) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +}; + +const lowWords = (s: string) => + ` ${s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s-]/gu, " ") + .replace(/\s+/g, " ") + .trim()} `; + +export function entryLine(e: ManifestEntry, quoteWords = CUT_VIEW_QUOTE_WORDS): string { + if (e.type === "card") { + const n = e.narration?.text ?? ""; + return `- card ${e.id} (${e.style ?? ""}) heading: ${JSON.stringify(e.heading ?? "")}` + (n ? ` narration: ${JSON.stringify(n)}` : ""); + } + if (e.type === "clip") return `- clip ${e.id} ${e.channel}/${e.video} ${e.start}–${e.end} s quote: ${JSON.stringify(shortQ(e.quote ?? "", quoteWords))}`; + return `- ${e.type} ${e.id}`; +} + +// The chapters of a cut: each card starts one; entries before the first card +// are chapter 0's. +export function chaptersOf(m: VideoManifest): ManifestEntry[][] { + const out: ManifestEntry[][] = [[]]; + for (const e of m.timeline ?? []) { + if (e.type === "card" && out.at(-1)!.length) out.push([]); + out.at(-1)!.push(e); + } + return out.filter((c) => c.length); +} + +export function chaptersNamedBy(m: VideoManifest, feedback: string): Set<number> { + const fb = lowWords(feedback); + const out = new Set<number>(); + chaptersOf(m).forEach((ch, i) => { + for (const e of ch) { + if (fb.includes(lowWords(e.id))) out.add(i); + const h = lowWords(e.heading ?? "").trim(); + if (e.type === "card" && h.length >= 3 && fb.includes(` ${h} `)) out.add(i); + } + if (new RegExp(`\\bchapter\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + return out; +} + +export function trimmedCutView( + m: VideoManifest, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): { text: string; full: string[]; short: string[] } { + const head = [`TITLE: ${m.title ?? ""}`, `SUBTITLE: ${m.subtitle ?? ""}`]; + const chapters = chaptersOf(m); + const named = o.feedback ? chaptersNamedBy(m, o.feedback) : new Set<number>(); + const order = [...chapters.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + // Every entry costs at least its id line; the full line is bought from what is left. + const idLine = (e: ManifestEntry) => `- ${e.type} ${e.id} (not shown in full)`; + let used = head.join("\n").length + (m.timeline ?? []).reduce((n, e) => n + idLine(e).length + 1, 0); + const full = new Set<ManifestEntry>(); + for (const i of order) { + for (const e of chapters[i]!) { + const extra = entryLine(e, o.quoteWords).length - idLine(e).length; + if (used + extra > o.maxChars) continue; + used += extra; + full.add(e); + } + } + const lines = [...head]; + for (const e of m.timeline ?? []) lines.push(full.has(e) ? entryLine(e, o.quoteWords) : idLine(e)); + return { + text: lines.join("\n"), + full: [...full].map((e) => e.id), + short: (m.timeline ?? []).filter((e) => !full.has(e)).map((e) => e.id), + }; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -14,7 +14,7 @@ transcript, channel or person goes in these fixtures, ever. | `llm/fakeAnthropic.mjs` | A fake Messages API: scripted turns (`textTurn`, `toolTurn`, `pauseTurn`, `webSearchBlocks`, `thinkingBlock`, `errorTurn`, or a function of the request). It enforces the Sonnet 5.5 400s (temperature, forced `tool_choice`, `thinking: disabled`), signs thinking blocks so an edited history is refused, needs `x-api-key` = `FAKE_KEY`, and estimates usage, cache reads included. | | `llm/fakeOllama.mjs` | A fake ollama: `/api/chat` with `format` or tools, the 8k prompt cap and the 12k `num_ctx` cap as 400s, `stream: true` refused, `faultReply()` (`done: false`), the `keep_alive: 0` unload, `/api/tags`, `/api/ps`. | | `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. | -| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one). | +| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one), `two-line` (a finding's quote and link on the lines under its claim), `fragment` (verbatim quotes that stop mid-thought — on a function word, or under four words — and one whole sentence). | | `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. | | `web/fakeWeb.mjs` | A fake web on loopback: a DuckDuckGo-shaped HTML search (`POST /html/`, links in the `uddg` redirect, an ad), pages, plain text, a long page, redirects and a redirect loop, a PDF, a 429 that clears (`busyTimes`), a 503 that does not. `web.searchUrl` is what `webSearch` takes. | | `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. | diff --git a/common/testing/draft/derive.ts b/common/testing/draft/derive.ts @@ -10,7 +10,7 @@ import { cuesOf, ORIGIN, POSTS } from "./corpus.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); -export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact", "two-line"] as const; +export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact", "two-line", "fragment"] as const; export type SweepName = (typeof SWEEPS)[number]; // The sweeps whose report and manifest are committed. diff --git a/common/testing/draft/sweeps/fragment.md b/common/testing/draft/sweeps/fragment.md @@ -0,0 +1,11 @@ +# Fragment quotes + +Four quotes, every one verbatim: three stop mid-thought — two on a function word, one under four words — and one is a +whole sentence. + +## Findings + +- The mixer: "I paid for the" [Bread day @ 0:45](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=45) +- The lease: "my lawyer told me not to" [Pie stream @ 0:40](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=40) +- The contest: "I did not" [Pie stream @ 0:10](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=10) +- The finalist: "I have never met the other finalist" [Pie stream @ 0:30](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=30) diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -4,6 +4,11 @@ - **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`). - **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes). - **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts. +- **Generated narration that speaks as the speaker is refused.** The narrator is third person: a drafted narration sentence with I, me, my, we, us or our outside quotation marks fails its check ("the narrator is third person"), and when the sentence restates a cited quote the reason names whose line it is and its citation (`c03 (Bread day @ 0:45)`). A narration step drops such a sentence as it drops any other failing one; a video revision's narration op is refused with it. "US" in capitals and words that only contain the letters ("Iowa", "myth") are not caught; "mine" the noun is. +- **A generated quote that stops mid-sentence is refused, and the full sentence is offered.** A quote under four words, or one that ends on a word like "as", "to", "the", "and" or "my" without sentence punctuation, is a fragment. In a generated sweep it goes to the repair round with the transcript's whole sentence to quote instead (or is dropped if still a fragment); a revision's added finding is refused with the sentence; the local pipeline extends such a quote to its sentence itself. `archilyzer reports verify-quotes` reports an existing report's fragment quotes as **`fragment`**, a warning with the full sentence, after `drift`, `en-orig-drift` and `inexact`; the exit code is unchanged. Needs a restart of the editor. +- **Report and video revisions on the local model are one request.** A revision on the local model no longer runs a tool conversation: it asks once for the whole batch of edits, over the report or cut trimmed to fit the model's 8k-token prompt (the sections or chapters the feedback names first; long quotes shortened and links cut to their labels in what the model reads, never in the report). Revisions on the Claude API are unchanged. Needs a restart of the editor. +- **A sweep can name its own extractor.** `pnpm ops report-draft --json '{"task": "sweep", …, "extractorModel": "claude-haiku-5-5"}'` reads that sweep's batches with the named Claude model instead of `settings.generation.models.extractor`; the MCP's `generate` takes it too. In umtool, a sweep on a Claude model shows an **extractor** choice on `/articles/new`, beside **Copy with model**, and beside a research run's **Continue into a sweep**. A sweep on the local model has no extractor and says so. Needs a restart of the editor and umtool. +- **Report draft jobs show their progress.** A **Report draft** job's row on /jobs now shows the model turns taken against the task's turn limit (a sweep, a revision, a research run; the repair round counted on), or the recordings read of the worklist for a sweep on the local model. `pnpm ops get job <id>` carries the same as `progress`. Needs a restart of the editor. - **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan. - **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept. - **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor. diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -81,6 +81,15 @@ test("the body: each task's needs, and the refusals in words", () => { assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: " q ", channels: "x, y" }), { task: "sweep", article: "a", question: "q", channels: ["x", "y"] }); }); +test("extractorModel (release 28 F2): a sweep's, a Claude model the price table knows", () => { + const sweep = { task: "sweep", article: "a", question: "q", channels: ["x"] }; + assert.equal(parseReportDraftBody({ ...sweep, extractorModel: "claude-haiku-5-5" }).extractorModel, "claude-haiku-5-5"); + assert.equal(parseReportDraftBody({ ...sweep, extractorModel: "claude-haiku-4-5-20251001" }).extractorModel, "claude-haiku-4-5-20251001"); + assert.throws(() => parseReportDraftBody({ ...sweep, extractorModel: "qwen3:8b" }), /"extractorModel" is a Claude model id/); + assert.throws(() => parseReportDraftBody({ ...sweep, extractorModel: "claude-nonsense-9" }), /"extractorModel" is a Claude model id/); + assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f", extractorModel: "claude-haiku-5-5" }), /"extractorModel" is a sweep's/); +}); + test("refused before any iteration: a task routed to Claude Code with no model, a cap over max", async () => { const code = await enqueueReportDraft({ task: "sweep", article: "synth-refused", question: "q", channels: ["synth-kitchen"], source }, deps()); assert.equal(code.result.ok, false); @@ -115,6 +124,28 @@ test("an API sweep: a report-draft job on draft:api, the iteration done with its const jobId = out.result.jobId; assert.ok(rows.every((x) => x.jobId === jobId && x.article === "synth-api" && x.iteration === 1)); assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); + // The job's progress (release 28 F3): the agent's model turns, the runner's own count. + assert.deepEqual(job.progress, { metric: "turns", initial: 0, target: 150, current: 6 }); +}); + +test("an API sweep with its own extractorModel: the batches are read on it, its spend in the ledger", async () => { + const r = await run("sweep-agent"); + api.push(...r.turns); + const before = api.requests.length; + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-extractor", model: r.model, extractorModel: "claude-haiku-5-5", question: r.question, channels: r.channels, source }, + deps(), + ); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + const job = getRegistry().get(out.result.jobId)!; + assert.equal(done.status, "done", await readFile(job.logPath, "utf8")); + const models = api.requests.slice(before).map((q: { model: string }) => q.model); + assert.ok(models.includes("claude-haiku-5-5"), models.join(",")); + assert.ok(!models.includes("claude-haiku-4-5"), "not the settings' extractor"); + const it = (await readIteration("synth-extractor", out.iteration, paths))!; + assert.ok(it.usage["claude-haiku-5-5"]!.calls === 1); }); test("the daily cap: a job that would start past the day's total is refused, naming it", async () => { diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -7,9 +7,9 @@ import { researchEditor } from "../_researchEditor"; export const dynamic = "force-dynamic"; -// POST { task, article, iteration?, model?, feedback?, question?, channels?, -// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force?, -// autonomy? } +// POST { task, article, iteration?, model?, extractorModel?, feedback?, +// question?, channels?, from?, to?, copyOf?, maxUsd?, source?, build?, +// cards?, force?, autonomy? } // -> { ok: true, jobId, iteration, warnings? } // // A generation over an article's iteration (release 27 S6), as a @@ -28,7 +28,8 @@ export const dynamic = "force-dynamic"; // while N still waits, unless `force`); // - `copyOf` N: iteration N again on `model` (same kind and inputs). // `model` defaults to settings.generation's route for the task (a task routed -// to `code` needs one named). An API job's cap is `maxUsd`, else the task's +// to `code` needs one named). `extractorModel` is an API sweep's extractor +// (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's // default (settings.generation.caps), never above `caps.max`; a job that would // start past the day's API total (`caps.daily`) is refused, naming it. The // corpus is `source` (a handle), `build` (a composed build's id), or the newest diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx @@ -159,6 +159,9 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = { backfills: "Backfill", scans: "Metadata scan", clips: "Clip windows", + turns: "Model turns", + cards: "Cards", + entries: "Entries", }; // Per-metric glyph for the compact line ("↓ 5/10"). @@ -169,6 +172,9 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = { backfills: "\u21ba ", scans: "\u2315 ", clips: "\u2702 ", + turns: "\u21c4 ", + cards: "\u25a4 ", + entries: "\u2261 ", }; const METRIC_FILL: Record<JobProgressMetric, string> = { @@ -178,6 +184,9 @@ const METRIC_FILL: Record<JobProgressMetric, string> = { backfills: "bg-warning", scans: "bg-info/60", clips: "bg-success/60", + turns: "bg-info", + cards: "bg-success/60", + entries: "bg-success/60", }; // One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left" diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -95,6 +95,8 @@ test("a sweep draft: enqueued over ops, followed to done, its iteration read bac expect(body.iteration).toBe(1); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); + // The job's progress (release 28 F3): the agent's model turns, against its turn cap. + expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "turns", initial: 0, current: 6, target: 150 }); const it = await iterationJson("synth-e2e", 1); expect(it.status).toBe("done"); expect(it.jobId).toBe(body.jobId); diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -22,6 +22,7 @@ import { projectOf, } from "yt-dlp-transcript-common/lib/report/iterations"; import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; +import type { TaskProgress } from "yt-dlp-transcript-common/lib/report/draft/tasks/types"; import { createCorpusTools, type CorpusTools } from "./callTool"; const RUNS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft/runs"); @@ -61,8 +62,9 @@ beforeEach(async () => { const postText = async (channel: string, id: string) => POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null; -function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[] } { +function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[]; progressed: TaskProgress[] } { const lines: string[] = []; + const progressed: TaskProgress[] = []; return { llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, @@ -74,6 +76,8 @@ function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[] } { paths, log: (l) => lines.push(l), lines, + progress: (p) => progressed.push(p), + progressed, ...extra, }; } @@ -147,6 +151,9 @@ test("sweep-agent: the plan, the corpus tools, extract_batch, the report file; t const turns = (await readIterationFile("synth-contest", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); assert.ok(turns.some((t) => t.kind === "tool" && t.name === "extract_batch")); assert.ok(turns.some((t) => t.kind === "note" && t.text === "repair round")); + // The job's progress: every model turn, the repair round's counted on (release 28 F3). + assert.deepEqual(d.progressed.map((p) => p.current), [1, 2, 3, 4, 5, 6]); + assert.ok(d.progressed.every((p) => p.metric === "turns" && p.total === 150)); }); test("sweep-agent: a quote the repair round does not fix is dropped, and the iteration is still done", async () => { @@ -162,6 +169,30 @@ test("sweep-agent: a quote the repair round does not fix is dropped, and the ite assert.match(after.checks!.find((c) => c.name === "quotes")!.detail!, /1 finding\(s\) dropped/); }); +test("sweep-agent: a fragment quote goes to the repair round with its full sentence, and the fix is kept (release 28 Q2)", async () => { + const r = await run("sweep-agent"); + const turns = structuredClone(r.turns); + const write = turns[3].content[0].input; + write.markdown = write.markdown.replace("the judges were friends of mine so it felt right", "the judges were friends of"); + turns[5] = { + content: [{ type: "tool_use", id: "toolu_f04", name: "edit_report", input: { old_text: 'friends of"', new_text: 'friends of mine so it felt wrong"' } }], + stop_reason: "tool_use", + }; + api.push(...turns); + const it = await createIteration("synth-frag", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-agent", article: "synth-frag", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const first = api.requests.at(-7); + assert.match(first.system[0].text, /Quote a whole sentence or clause/); + const repair = api.requests.at(-2); + assert.match(repair.messages[0].content, /a fragment \(ends on “of”\): "the judges were friends of" — quote the whole sentence: "the judges were friends of mine so it felt wrong"/); + const md = (await readIterationFile("synth-frag", it.n, "sweep.md", paths))!; + assert.ok(md.includes('"the judges were friends of mine so it felt wrong"')); + const after = (await readIteration("synth-frag", it.n, paths))!; + assert.deepEqual(after.checks?.map((c) => [c.name, c.ok]), [["convert", true], ["quotes", true]]); +}); + test("sweep-agent: the repair round has its own small allowance", async () => { const r = await run("sweep-agent"); // The repair round's first turn costs more than the allowance: it stops there. @@ -222,6 +253,8 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d assert.ok(md.includes(`${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10`)); assert.ok(!md.includes("I entered the contest and I won"), "the invented quote never made it"); assert.match(md, /## Coverage\n\nSearched synth-kitchen for contest, judges\. 1 video\(s\) matched; 1 read/); + // The job's progress: the recordings gone through, of the worklist (release 28 F3). + assert.deepEqual(d.progressed, [{ metric: "entries", current: 0, total: 1 }, { metric: "entries", current: 1, total: 1 }]); const report = JSON.parse((await readIterationFile("synth-pipe", it.n, "report.json", paths))!); assert.equal(Object.keys(report.citations).length, 2); const turns = (await readIterationFile("synth-pipe", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); @@ -331,24 +364,95 @@ test("a task refuses an iteration that is not its own or not queued", async () = assert.ok(CHANNELS.length > 0); }); -test("revise-report on a local model that never calls apply_ops: one schema-bound ask for the batch, then the check says so", async () => { +test("revise-report on a local model: no tool loop — one schema-bound ask for the batch; nothing proposed is a failing check", async () => { await drainFake(); await doneSweep("synth-basic", "basic"); const it = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - // read_doc, then an empty answer (no tool call); then the ask answers with the batch. - ol.push(toolCallsReply([{ name: "read_doc", arguments: {} }]), reply(""), jsonReply({ ops: [{ op: "drop", n: 3 }] })); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 3 }] })); const d = deps(); const out = await runTask({ task: "revise-report", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one call"); + assert.deepEqual(d.progressed, [{ metric: "turns", current: 1, total: 1 }]); + const req = ol.requests.at(-1); + assert.ok(req.format, "schema-bound"); + assert.ok(!req.tools, "no tools"); + assert.ok(!/apply_ops|read_doc/.test(req.messages[0].content), "the local rules name no tools"); const after = (await readIteration("synth-basic", it.n, paths))!; assert.deepEqual((after.ops!.applied as { op: string }[]).map((o) => o.op), ["drop"]); assert.ok(after.checks!.some((c) => c.name === "ops" && c.ok)); assert.ok(!(await readIterationFile("synth-basic", it.n, "sweep.md", paths))!.includes("new mixer")); - // A model that proposes nothing even then: done, with a failing ops check. + // A model that proposes nothing: done, with a failing ops check. const it2 = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - ol.push(reply(""), jsonReply({ ops: [] })); + ol.push(jsonReply({ ops: [] })); await runTask({ task: "revise-report", article: "synth-basic", n: it2.n, origin: ORIGIN, maxUsd: 1 }, deps()); const after2 = (await readIteration("synth-basic", it2.n, paths))!; assert.ok(after2.checks!.some((c) => c.name === "ops" && !c.ok && /no edits/.test(String(c.detail)))); }); + +test("revise-report on a local model: a large report's view fits the 8k cap — the named section in it, one ops call, the numbers the document's", async () => { + await drainFake(); + await createIteration("synth-big", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const basic = JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")); + await writeIterationFile("synth-big", 1, "report.json", { ...basic, id: "synth-big" }, paths); + await updateIteration("synth-big", 1, { status: "done" }, paths); + // 40 sections of 6 findings over real corpus moments: ~45k characters, far past the cap. + const lines = ["# A large report", "", "The summary.", ""]; + const moments = [ + ["bread-day-01", 15, "I would never sell the bakery to a chain"], + ["bread-day-01", 45, "I paid for the new mixer myself"], + ["pie-stream-02", 10, "I did not enter the contest this year"], + ["pie-stream-02", 30, "I have never met the other finalist"], + ["pie-stream-02", 40, "my lawyer told me not to talk about the lease"], + ["bread-day-01", 30, "the oven was fine it just ran hot"], + ] as const; + let n = 0; + for (let s = 1; s <= 40; s++) { + lines.push(`## Topic ${s}`, ""); + for (const [id, t, q] of moments) { + n++; + lines.push(`- Finding number ${n} says something about topic ${s} at some length, to fill the view: "${q}" [${id} @ 0:${t}](${ORIGIN}/?v=synth-kitchen%2F${id}&t=${t})`); + } + lines.push(""); + } + const big = lines.join("\n"); + assert.ok(big.length > 40_000, String(big.length)); + await writeIterationFile("synth-big", 1, "sweep.md", big, paths); + const it = await createIteration("synth-big", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "In Topic 37, drop finding 220." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 220 }] })); + const d = deps(); + const out = await runTask({ task: "revise-report", article: "synth-big", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one ops call, sent (not refused by the cap)"); + const req = ol.requests.at(-1); + assert.ok(Math.ceil(JSON.stringify([req.messages, null, req.format]).length / 3.5) <= 8000, "under the client's 8k estimate"); + const user = req.messages[1].content as string; + assert.match(user, /## Topic 37\n\[217\] Finding number 217/, "the named section, in full"); + assert.ok(user.includes("[220] Finding number 220")); + assert.match(user, /not shown/, "what is left out is said"); + assert.ok(!user.includes(`${ORIGIN}/?v=`), "links cut to their labels in the view"); + const md = (await readIterationFile("synth-big", it.n, "sweep.md", paths))!; + assert.ok(!md.includes("Finding number 220 "), "the op numbered against the whole document"); + assert.ok(md.includes("Finding number 219 ") && md.includes("Finding number 221 ")); + assert.ok(md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=40)`), "links whole in the report"); +}); + +test("revise-video on a local model: one ops batch over the trimmed cut", async () => { + await drainFake(); + await doneSweep("synth-basic", "basic", { manifest: true }); + const it = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Rename the-bakery to About the bakery." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "heading", id: "the-bakery", text: "About the bakery" }] })); + const out = await runTask({ task: "revise-video", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps()); + assert.equal(out.status, "done", out.summary); + assert.equal(ol.requests.length - before, 1); + const req = ol.requests.at(-1); + assert.ok(req.format && !req.tools); + assert.match(req.messages[1].content, /- card the-bakery \(chapter\) heading: "The bakery"/); + assert.match(req.messages[1].content, /REPORT CITATIONS \(add_clip takes these ids\):\nc01: synth-kitchen\/bread-day-01/); + const m = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", it.n), "video.manifest.json"), "utf8")); + assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery"); +}); diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -258,6 +258,10 @@ test("generate: the arguments are checked before any request; research is a task assert.ok(GENERATE_TASKS.includes("research")); const ok = validateGenerateArgs({ task: "research", article: "synth-a", question: "what was said?", channels: ["synth-kitchen"] }); assert.equal(ok.ok, true); + // A sweep's extractor, per job (release 28 F2), passed through as the editor's key. + const ex = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], extractorModel: " claude-haiku-5-5 " }); + assert.ok(ex.ok && ex.request.kind === "start"); + if (ex.ok && ex.request.kind === "start") assert.equal(ex.request.body.extractorModel, "claude-haiku-5-5"); for (const [args, re] of [ [{ task: "teaser", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research/], [{ task: "sweep", article: "Not An Id" }, /article is an article id/], @@ -268,6 +272,8 @@ test("generate: the arguments are checked before any request; research is a task [{ task: "sweep", article: "a", via: "api", model: "x" }, /model or via, not both/], [{ task: "sweep", article: "a", wait_seconds: -2 }, /wait_seconds/], [{ job: "../etc" }, /is not a job id/], + [{ task: "revise-report", article: "a", iteration: 1, feedback: "f", extractorModel: "claude-haiku-4-5" }, /extractorModel is a sweep's/], + [{ task: "sweep", article: "a", extractorModel: "qwen3:8b" }, /extractorModel is a Claude model id/], ] as const) { const v = validateGenerateArgs(args as Record<string, unknown>); assert.equal(v.ok, false, JSON.stringify(args)); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -242,12 +242,16 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (n === null) return bad(`${k} is an iteration number (1, 2, …)`); if (n !== undefined) body[k] = n; } - for (const k of ["model", "feedback", "question", "from", "to"] as const) { + for (const k of ["model", "extractorModel", "feedback", "question", "from", "to"] as const) { if (args[k] === undefined) continue; const v = trimmed(args[k]); if (!v) return bad(`${k} is text`); body[k] = v; } + if (body.extractorModel !== undefined) { + if (task !== "sweep") return bad("extractorModel is a sweep's (the extractor an API sweep reads batches with)"); + if (!String(body.extractorModel).startsWith("claude-")) return bad("extractorModel is a Claude model id: an API sweep's extractor runs on the API"); + } for (const k of ["channels", "cards"] as const) { if (args[k] === undefined) continue; const v = args[k]; @@ -620,6 +624,10 @@ export const GENERATION_TOOLS = [ feedback: { type: "string", description: "A revision's feedback: what to change, concretely." }, copyOf: { type: "integer", minimum: 1, description: "Run this iteration again (same kind and inputs) on model or via." }, model: { type: "string", description: "The model to run on (else the route's)." }, + extractorModel: { + type: "string", + description: "sweep on the API: the Claude model its extractor reads batches with (else the settings' extractor).", + }, via: { type: "string", enum: ["api", "local"], description: "Run on this route's model instead of the policy's route — only when the operator asks." }, maxUsd: { type: "number", description: "An API job's cap in USD (else the task's default; never above the settings' max)." }, cards: { type: "array", items: { type: "string" }, description: "narrate: only these card ids." }, diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9232,3 +9232,11 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri reason }] }`; alternatives from earlier runs are carried over, newest five per field. The step is recorded in the iteration's `steps` (a done iteration's status is left). umtool reads alternatives from every `*-draft.json` beside the manifest (`lib/report/drafts.mjs` `readAlternatives`). +## Release 28 lane B: quality and progress (verified 2026-10-13, branch `r28/quality` @ `48dbc5de`) + +- **The narrator is third person** (`grounding.ts`): a first-person word outside double quotes is a HARD grounding problem whose text starts `the narrator is third person`. A media task that calls `checkNarration` refuses it with no change of its own. `GroundingInput.sources` (each quote's speaker and `c03 (label @ m:ss)`) names the line it restates; `groundingInputOf` fills it. +- **A fragment quote** (`lib/citations/fragment.ts`): `fragmentOf(quote)` → `{why, part} | null`; `fullSentenceFor(quote, cues, second)` → the cues' own words or null; `fragmentHint(f, sentence)` is the repair wording. A GENERATED fragment fails (`checkQuotes` problem with `fragment`, the add op's checker); an existing one is verify-quotes' warning `fragment`, after `drift` / `en-orig-drift` / `inexact`. +- **A local revision is one `structuredAnswer`**, never the tool loop: `localOpsBatch(h, {model, system, what, build, apply})` and `fitLocalAsk` (revise-report.ts) fit a view under the cap with `structuredPromptEstimate` (llm/structured.ts, the request localAnswer sends). `trimmedNumberedView` / `trimmedCutView` shorten quotes and links in the VIEW only. +- **`report-draft {extractorModel}`** is a sweep's, a Claude id `isKnownApiModel` accepts; it replaces `generation.models.extractor` for that job. +- **A report-draft job's progress** is the task's: `TaskDeps.progress?({metric: "turns" | "cards" | "entries", current, total?})` → `JobProgress {metric, initial: 0, target, current}`. A task calls `h.progress(...)` (TaskHandle; a throwing listener is swallowed). Media tasks report `cards` / `entries` the same way. + diff --git a/plans/release-28.md b/plans/release-28.md @@ -309,6 +309,73 @@ Left for phase 2: the media tasks themselves (M1–M6) on the scaffold; `TaskDep The served headers carry no `s-maxage`: `corpus.json` is `public, max-age=0, must-revalidate`, the tombstones are `no-store` (the `_headers` rule). Pages sends neither `cf-cache-status` nor `age`, so the live check cannot record them. The 7-day edge TTL seen in release 18 is not observed after a deploy. +### Q1, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `03ece497` | `grounding.ts`: `FIRST_PERSON_WORDS`, `firstPersonWords`, `firstPersonProblems`, `THIRD_PERSON_MESSAGE`; `GroundingInput.sources` (`QuoteSource`, `reportQuoteSources`, filled by `groundingInputOf`); `checkNarration` adds each first-person sentence to `hard`; the taste's third-person rule; revise-video's narration op names it; 3 tests | + +- A sentence with I, I'm, I've, I'd, I'll, me, my, mine, myself, we, we're, we've, we'd, we'll, us, our, ours or ourselves outside double quotation marks is a HARD problem: `the narrator is third person (“I've”, “mine”): …`. When the sentence restates a cited quote (grounding's own `closest` match: two shared content words and half the sentence's), the reason names it: `this is the speaker's line from c03 (Bread day @ 0:45), “…”` (the citation's `speaker` when it has one). +- Word-bounded and case-insensitive; curly apostrophes read as straight. Not hits: "Iowa", "myth", "mineral", the all-caps "US". Accepted collateral: "mine" the noun, a roman numeral I. +- narrate needs no change: its grounding call puts the problem in `hard`, so the re-ask, the better attempt and the failing-sentence removal refuse it. videoOps' narration op is refused with it. +- The rule is stated once, in `NARRATION_TASTE` (narrate's prompt reads it). + +Gates: in the lane's totals below. + +### Q2, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `e023db71` | `citations/fragment.ts` (`FRAGMENT_END_WORDS`, `FRAGMENT_MIN_WORDS`, `fragmentOf`, `isFragmentQuote`, `fullSentenceFor`, `fragmentHint`); `checkQuotes` and `strictCheckerOver` refuse a fragment with its sentence; the pipeline extends one in code; revise-report's parent fragments a warning; verify-quotes `fragment`; `WHOLE_SENTENCE_QUOTE_RULE`; REPORT.md; `testing/draft/sweeps/fragment.md`; 8 tests | + +- **A fragment**: fewer than 4 words in the whole quote, or an ellipsis part ending on one of `FRAGMENT_END_WORDS` (the brief's list) without sentence punctuation (. ! ? …). A part ending on punctuation is a sentence whatever its last word. +- **`fullSentenceFor(quote, cues, second, {windowSeconds?, maxWords?})`** → the cues' own words from the quote's first word to sentence punctuation, or to a cue boundary whose next cue starts with a capital (not the pronoun I); unpunctuated, the end of the quote's cue, then one more cue while still a fragment; under 4 words, widened back to the sentence's start. Cap: max(30, quote + 15) words. Null when the quote is not there verbatim or nothing whole fits. The result passes the strict check wherever the quote did. +- **Generated quotes:** `checkQuotes` gives a fragment as a problem (`fragment: {why, part, sentence}`, `why` = `a fragment (ends on “of”): "…" — quote the whole sentence: "…"`), so the sweep agent's repair round is handed the sentence; still a fragment after it, the finding is dropped. The `add` op's checker (`strictCheckerOver`, `fragments: false` turns it off) refuses one with the same words. **sweep-pipeline** replaces a fragment with its sentence from the window in code (≤ 60 words), else drops it (`a fragment (…)`). +- **revise-report:** a fragment the parent already quoted is a warning in the `quotes` check, not a failure (as verify-quotes says of existing reports); one this revision added is dropped as before. +- **verify-quotes:** `fragment` is in `QUOTE_WARNING_STATUSES`; precedence `drift` / `en-orig-drift` > `inexact` > `fragment` > `ok`; the result carries `sentence`. The summary's note names whichever warnings occur. +- A `fragment` from the editor's verify-quotes is not one more problem in `checkQuotes` (its own check is the one). + +### Q3, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `f93ac191` | `structuredPromptEstimate` (llm/structured.ts); `sweepModel` `trimmedNumberedView`, `sectionsNamedBy`, `shortEvidence`; `videoOps` `trimmedCutView`, `chaptersOf`, `chaptersNamedBy`, `entryLine`; revise-report `LOCAL_REVISE_RULES`, `fitLocalAsk`, `localOpsBatch`, `REPORT_OPS_TEXT(origin, local?)`; revise-video's local path; 5 tests | + +- On an ollama model, revise-report and revise-video make ONE `structuredAnswer` (no tools; the rules name none) and apply its ops; the API path is the tool loop and its one-ask fallback, unchanged. +- **The fit:** `fitLocalAsk` builds the user text at a character budget from the model's prompt cap (`promptCapOf` × 3.5) and shrinks it by 15% until `structuredPromptEstimate` — the very messages and format localAnswer sends, counted as `ollamaChat` counts them — is under the cap. +- **The report view:** sections the feedback names first (a title, `section N`, or a finding number in what is left once titles are taken out; seconds and percentages are not finding numbers), then the rest in document order, finding by finding while the budget lasts; shown in document order; a section's left-out findings named (`(findings [96]–[100] not shown)`). Quotes over 12 words cut to 8 and `…`, links cut to their labels — in the view only; ops number against the whole document. +- **The cut view:** every entry listed in timeline order; the chapters the feedback names (an entry id, a card heading, `chapter N`) in full first, the rest while the budget lasts, else `- clip c07 (not shown in full)`; citations the feedback names first, then the rest, with the count left out. +- Unit, against fakeOllama: a 45k-character report's view under the 8k estimate, one request, the named section in full, the op landing on finding 220 of the whole document, links whole in the report; the cut's one batch. + +### F2, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `c9e99c51` | `report-draft {extractorModel}` (`REPORT_DRAFT_BODY_KEYS`, `parseReportDraftBody`, `isKnownApiModel`); the route's comment and the ops help; COMMANDS.md; the MCP's `generate` argument; umtool `ExtractorSelect` / `extractorBody` on `/articles/new`, Copy with model and a research continuation; `DRAFT_KEYS`; editor unit 2, MCP checks, umtool `article-new.spec` | + +- `extractorModel` is a sweep's (`task: "sweep"`, a copy of one or a research continuation included) and a Claude model id the price table knows (`isKnownApiModel`: a `PRICES` key, or a dated id of one). It replaces `settings.generation.models.extractor` for that job. On a sweep whose model is local it is unused and the answer carries a warning. +- The MCP's `generate` checks it (a sweep's, `claude-…`) and passes it through. +- umtool shows the extractor only beside a sweep on a Claude model and sends it only when it is not the policy's (so the bodies its specs pin are unchanged). + +### F3, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `48dbc5de` | `JobProgressMetric` `turns` / `cards` / `entries`; `TaskProgress`, `TaskDeps.progress`, `TaskHandle.progress`; `reportDraft.ts` wires `setProgress`; sweep-agent, revise-report, revise-video and research report turns, sweep-pipeline entries; the editor's bars label them; editor unit, MCP and `report-draft.spec` assertions | + +- `TaskDeps.progress?(p: {metric: "turns" | "cards" | "entries"; current: number; total?: number})`; a task calls `h.progress`, which never throws into it. The job maps it to `{metric, initial: 0, target: max(total ?? current, current), current}` — the runner's own `current`, as fetch-windows' clips. +- Agent tasks report every model turn against their turn cap (sweep-agent 150, the repair round counted on; revisions 30; research 60); a local revision's one batch is 1/1; sweep-pipeline reports the recordings gone through of its worklist (`entries`, from 0). The media tasks (narrate, phase 2's) are not wired here. +- `common/views/jobRowView.ts` imports the union (no re-spelling to change); `JobProgressBars.tsx`'s three records gained the metrics (Model turns ⇄, Cards ▤, Entries ≡). + +**Lane B's gates** (at `48dbc5de`; counts at the branch start → the tip): +- tsc clean (all packages) before every commit. +- common 4018 (1 failed at the start, not reproduced at the tip) → 4031/4031 (13 new); mcp 343 → 346/346; editor unit 288 → 290/290; `test:scripts` 860 + 3 skipped → 860 + 3 skipped. +- `docs cli|files|env --check`, `settings example --check`: clean. +- Editor build: the e2e prebuild's capped `next build` (heavy slot, 5 GB) at `48dbc5de`, clean. +- e2e `report-draft.spec.ts` (editor suite, alone): 3 passed, 0 failed, 17.8 s wall (after 40 s in the queue). +- umtool e2e `article-new.spec.ts` + `article-iterations.spec.ts`: 7 passed, 0 failed, 44.8 s (its prebuild's capped `next build` 35 s, clean). + +Not done here: the MCP's `sweep_plan` / `ask_plan` text (Claude Code's own /sweep) does not state `WHOLE_SENTENCE_QUOTE_RULE` (`mcp/src/instructions.ts` is not this lane's; one line where the claim-quotes and verbatim rules are). ## Not in this release diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -396,8 +396,9 @@ const ACTIONS = [ "import-post", // GENERATION (release 27 S6): a sweep, a report or video revision, or a // narration step over an article's iteration ({task, article, iteration?, - // model?, feedback?, question?, channels?, copyOf?, maxUsd?, …}), as a - // report-draft job on draft:api or draft:local. `job cancel` stops it. + // model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?, + // …}), as a report-draft job on draft:api or draft:local. `job cancel` stops + // it. "report-draft", // RESEARCH RUNS (release 27 S11): a research run's acquisitions, after its // job — refreshed from their jobs, then approved (run through the editor) or @@ -1194,7 +1195,9 @@ export function usage() { ' and "channels" (and "from"/"to"): a new iteration; a revision takes', ' "iteration" (the one it revises) and "feedback": a new iteration; a', ' narration takes "iteration" (a done one; "cards"?, "force"?) and is a step', - ' on it. "copyOf" N runs iteration N again on "model". "model" defaults to', + ' on it. "copyOf" N runs iteration N again on "model". "extractorModel" is', + " an API sweep's extractor (a Claude model id; default", + ' settings.generation.models.extractor). "model" defaults to', " settings.generation's route for the task (one routed to code needs a model", ' named). A Claude model runs on draft:api, capped at "maxUsd" (default by', " task, never above caps.max), and is refused when the day's API total has", diff --git a/umtool/app/api/articles/generate/route.ts b/umtool/app/api/articles/generate/route.ts @@ -3,11 +3,13 @@ import { enqueueDraft, errorResponse } from "@/lib/articles/generation"; export const dynamic = "force-dynamic"; // START A GENERATION (release 27 S8): the body is `pnpm ops report-draft`'s — -// { task, article, iteration?, model?, feedback?, question?, channels?, from?, -// to?, copyOf?, maxUsd?, cards?, force?, autonomy? } — forwarded to the editor, which +// { task, article, iteration?, model?, extractorModel?, feedback?, question?, +// channels?, from?, to?, copyOf?, maxUsd?, cards?, force?, autonomy? } — +// forwarded to the editor, which // creates the iteration and runs the job. Answers { ok, jobId, iteration }. // -// a new article task sweep, question, channels (from, to) +// a new article task sweep, question, channels (from, to); on Claude, +// extractorModel (release 28 F2: else the settings') // a new iteration task revise-report | revise-video, iteration, feedback // copy with model the iteration's task, copyOf, model // narration task narrate, iteration, model (a step) diff --git a/umtool/components/articles/ExtractorSelect.tsx b/umtool/components/articles/ExtractorSelect.tsx @@ -0,0 +1,40 @@ +"use client"; + +// THE EXTRACTOR OF ONE SWEEP (release 28 F2): an API sweep reads its batches +// with a cheap Claude model, `settings.generation.models.extractor` unless a +// job names its own (`report-draft {extractorModel}`). Shown beside a sweep's +// model when that model is Claude's; a choice equal to the policy's sends +// nothing (the editor's default is the same model). + +const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; + +/** The body key for a sweep on `model`: `{extractorModel}` when it is not the policy's. */ +export function extractorBody(model: string, extractor: string, policyExtractor: string | undefined): { extractorModel?: string } { + return model.startsWith("claude-") && extractor && extractor !== policyExtractor ? { extractorModel: extractor } : {}; +} + +export default function ExtractorSelect({ + label, + value, + onChange, + models, +}: { + label: string; + value: string; + onChange: (v: string) => void; + /** Claude's models (an API sweep's extractor runs on the API). */ + models: string[]; +}) { + return ( + <label className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">extractor</span> + <select aria-label={label} className={`${field} font-mono`} value={value} onChange={(e) => onChange(e.target.value)}> + {[...new Set([value, ...models].filter((m) => m && m.startsWith("claude-")))].map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + ); +} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"; import { badgeVariants } from "@/components/ui/badge"; import ChainPanel from "@/components/articles/ChainPanel"; import ResearchSlot from "@/components/articles/ResearchSlot"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import DeletePlan from "@/components/DeletePlan"; import { usd, type Today } from "@/components/articles/PolicyPanel"; import type { ArticleIterations, DraftJobView, IterationRow, PolicyView } from "@/lib/articles/generation"; @@ -200,6 +201,7 @@ function IterationCard({ const g = ctx.policy?.generation; const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model); const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? "")); + const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? ""); const done = it.status === "done"; const active = it.status === "queued" || it.status === "running"; const runningStep = it.steps.find((s) => s.status === "running" && s.jobId && !s.task.startsWith("chain:")); @@ -307,6 +309,8 @@ function IterationCard({ post={ctx.post} models={ctx.allModels} sweepModel={g?.routes.sweep === "local" ? g.models.local : (g?.models.api ?? "")} + apiModels={ctx.policy?.models.api ?? []} + extractor={g?.models.extractor} /> )} @@ -324,7 +328,21 @@ function IterationCard({ {task && !active && ( <span className="flex items-center gap-1"> <ModelSelect label={`copy ${it.label} on model`} value={copyModel} onChange={setCopyModel} models={ctx.allModels} /> - <Button size="sm" onClick={() => void ctx.post({ task, article: ctx.article, copyOf: it.n, model: copyModel })}> + {task === "sweep" && copyModel.startsWith("claude-") && ( + <ExtractorSelect label={`extractor for the copy of ${it.label}`} value={copyExtractor} onChange={setCopyExtractor} models={ctx.policy?.models.api ?? []} /> + )} + <Button + size="sm" + onClick={() => + void ctx.post({ + task, + article: ctx.article, + copyOf: it.n, + model: copyModel, + ...(task === "sweep" ? extractorBody(copyModel, copyExtractor, g?.models.extractor) : {}), + }) + } + > Copy with model </Button> </span> diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // /articles/new (release 27 S8): a question over channels becomes an article's @@ -117,6 +118,7 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia : (policy?.models.local ?? []); const routeModel = begin === "research" ? researchModel : task === "agent" ? policy?.generation.models.api : policy?.generation.models.local; const [model, setModel] = useState(routeModel ?? ""); + const [extractor, setExtractor] = useState(policy?.generation.models.extractor ?? ""); // A cap is a Claude run's: the agent, or research on a Claude model. const capped = begin === "research" ? model.startsWith("claude-") : task === "agent"; const capDefault = policy?.generation.caps.sweep ?? 5; @@ -153,6 +155,7 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia question, ...(channels.length ? { channels } : {}), model, + ...(begin === "sweep" ? extractorBody(model, extractor, policy?.generation.models.extractor) : {}), ...(from ? { from } : {}), ...(to ? { to } : {}), ...(capped ? { maxUsd } : {}), @@ -264,6 +267,9 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia ))} </select> </label> + {begin === "sweep" && model.startsWith("claude-") && ( + <ExtractorSelect label="extractor for this sweep" value={extractor} onChange={setExtractor} models={policy?.models.api ?? []} /> + )} {capped && ( <label className="flex flex-col gap-1"> <span className="micro">cap $</span> diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import { badgeVariants } from "@/components/ui/badge"; import type { IterationRow } from "@/lib/articles/generation"; import type { ResearchProposal, ResearchView } from "@/lib/articles/research"; @@ -176,6 +177,8 @@ export default function ResearchSlot({ post, models, sweepModel, + apiModels = [], + extractor, }: { article: string; iteration: IterationRow; @@ -184,12 +187,16 @@ export default function ResearchSlot({ models: string[]; /** The sweep route's model, the continuation's default. */ sweepModel: string; + /** Claude's models, and the policy's extractor: a continuation on Claude may name its own (release 28 F2). */ + apiModels?: string[]; + extractor?: string; }) { const n = iteration.n; const [view, setView] = useState<ResearchView | null>(null); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [model, setModel] = useState(sweepModel); + const [extractorModel, setExtractorModel] = useState(extractor ?? ""); const active = iteration.status === "queued" || iteration.status === "running"; const load = useCallback(async () => { @@ -289,7 +296,15 @@ export default function ResearchSlot({ </option> ))} </select> - <Button size="sm" variant="primary" disabled={busy} onClick={() => void post({ task: "sweep", article, iteration: n, model })}> + {model.startsWith("claude-") && ( + <ExtractorSelect label={`continuation extractor for ${iteration.label}`} value={extractorModel} onChange={setExtractorModel} models={apiModels} /> + )} + <Button + size="sm" + variant="primary" + disabled={busy} + onClick={() => void post({ task: "sweep", article, iteration: n, model, ...extractorBody(model, extractorModel, extractor) })} + > Continue into a sweep </Button> </div> diff --git a/umtool/e2e/article-new.spec.ts b/umtool/e2e/article-new.spec.ts @@ -91,14 +91,20 @@ test("a new article: question, channels, the local pipeline — its first iterat await form.getByRole("button", { name: "Start" }).click(); await expect(form.getByRole("alert")).toContainText("at most the policy's $5"); + // The agent's extractor is the policy's unless this sweep names its own (release 28 F2). + await expect(form.getByRole("combobox", { name: "extractor for this sweep" })).toHaveValue("claude-haiku-4-5"); + await form.getByRole("combobox", { name: "extractor for this sweep" }).selectOption("claude-haiku-5-5"); + await form.getByRole("radio", { name: /pipeline/ }).check(); await expect(form.getByRole("combobox", { name: "model" })).toHaveValue("qwen3:8b"); + await expect(form.getByRole("combobox", { name: "extractor for this sweep" }), "the pipeline has no extractor").toHaveCount(0); await form.getByRole("button", { name: "Start" }).click(); await expect(page).toHaveURL(new RegExp(`/articles/${ARTICLE}\\?tab=iterations$`)); const asked = stubAsked("report-draft").at(-1)!; expect(asked).toMatchObject({ task: "sweep", article: ARTICLE, question: "What did the channel say about the vote?", channels: ["sitechan"], model: "qwen3:8b" }); expect(asked).not.toHaveProperty("maxUsd"); + expect(asked).not.toHaveProperty("extractorModel"); const first = page.locator("[data-iteration='1']"); await expect(first).toHaveAttribute("data-kind", "sweep"); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -216,7 +216,7 @@ export async function cancelDraftJob(id: string): Promise<void> { // The body umtool sends to `report-draft`: the action's own keys, nothing else // (the editor refuses an unknown key; this refuses it first, by name). -const DRAFT_KEYS = ["task", "article", "iteration", "model", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "force", "autonomy"]; +const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "force", "autonomy"]; export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> { const out: Record<string, unknown> = {};