// THE SWEEP.MD MODEL — a /sweep report as a document a revision can edit // with checked operations (./reportOps.ts), and write back unchanged where it // was not edited. // // The shape (what /sweep writes and convertSweep reads, // lib/report/convertSweep.ts): // // # // <preamble: the summary, any lines before the first section> // ## <section> // - <claim>: "<quoted words>" [<label>](<link>) ← a FINDING // <paragraphs, sub-headings, blank lines> ← kept, in body order // // A FINDING is a list item (`- ` or `* `) inside a section that carries at // least one citing link. It is split at its FIRST quoted span before the // first link (or at the link when nothing is quoted): the CLAIM before it, // the separator, and the REST — the quotes and links — kept verbatim. That // cut is the rule convertSweep imposes: every quoted span between the // previous link and a link becomes that link's quote, so no quoted word may // sit in the editable claim, and nothing an op does touches a quote. // // `parseSweep` → `renderSweep` is BYTE-IDENTICAL for any input (every line, // blank lines and the final newline included; a test holds it over every // fixture sweep). Ops change the parts they name and nothing else. export type Finding = { type: "finding"; // The list marker as written (`- `, `* `, with any indent). bullet: string; claim: string; // What sat between the claim and the first quote (`: `, ` — `, ` `); may // be empty. sep: string; // From the first quote (or link) to the end of the line, verbatim. rest: string; // Indented lines that continue the item, verbatim. continued: string[]; // Set by the `add` op: a finding this revision wrote (its quote is checked // again after convert, and dropped — never repaired — if it fails). added?: true; }; export type SweepLine = { type: "line"; text: string }; export type SweepBlock = Finding | SweepLine; export type SweepSection = { title: string; // The heading line as written, when it is not exactly `## <title>`. rawHeading?: string; body: SweepBlock[]; }; export type SweepDoc = { // Lines before the `# ` title (normally none). lead: string[]; // The title, without `# `; empty when the document has no `# ` line. title: string; hasTitle: boolean; rawTitle?: string; // Every line between the title and the first section, verbatim. preamble: string[]; sections: SweepSection[]; }; // A quoted span: straight or curly double quotes. export const QUOTED_RE = /"[^"\n]*"|“[^”\n]*”/g; // A citing link: a markdown link to an http(s) URL. export const LINK_RE = /\[[^\]\n]*\]\(https?:\/\/[^)\s]+\)/g; // Any quotation mark a claim may not carry. export const QUOTE_MARK_RE = /["“”]/; const BULLET_RE = /^(\s{0,3}[-*] )(.*)$/; const CONTINUED_RE = /^\s{2,}\S/; function firstMatch(re: RegExp, text: string, from = 0, to = text.length): RegExpExecArray | null { const r = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`); r.lastIndex = from; const m = r.exec(text); return m && m.index < to ? m : null; } export function hasLink(text: string): boolean { return firstMatch(LINK_RE, text) !== null; } // A finding's text split at its first quote before its first link (the // stopgap's split_item): the claim (trailing ` :—-` moved into the // separator), the separator, and the rest. export function splitFinding(text: string): { claim: string; sep: string; rest: string } { const link = firstMatch(LINK_RE, text); const quote = link ? firstMatch(QUOTED_RE, text, 0, link.index) : null; const cut = quote ? quote.index : link ? link.index : text.length; const head = text.slice(0, cut); const claim = head.replace(/[ :—-]+$/u, ""); return { claim, sep: head.slice(claim.length), rest: text.slice(cut) }; } export function parseSweep(md: string): SweepDoc { const lines = md.split("\n"); const doc: SweepDoc = { lead: [], title: "", hasTitle: false, preamble: [], sections: [] }; let section: SweepSection | null = null; let last: Finding | null = null; for (let i = 0; i < lines.length; i++) { const line = lines[i]!; if (section === null && !doc.hasTitle && line.startsWith("# ")) { doc.hasTitle = true; doc.title = line.slice(2).trim(); if (line !== `# ${doc.title}`) doc.rawTitle = line; continue; } if (line.startsWith("## ")) { const title = line.slice(3).trim(); section = { title, body: [], ...(line !== `## ${title}` ? { rawHeading: line } : {}) }; doc.sections.push(section); last = null; continue; } if (section === null) { (doc.hasTitle ? doc.preamble : doc.lead).push(line); continue; } if (last && CONTINUED_RE.test(line)) { last.continued.push(line); continue; } const b = BULLET_RE.exec(line); if (b && hasLink(b[2]!)) { last = { type: "finding", bullet: b[1]!, ...splitFinding(b[2]!), continued: [] }; section.body.push(last); continue; } // A TWO-LINE finding: the claim on the bullet, its quote and link on the // indented line(s) under it (the shape a sweep agent often writes, and // convertSweep reads as one claim). The claim is the whole bullet line. if (b) { let j = i + 1; while (j < lines.length && CONTINUED_RE.test(lines[j]!)) j++; const cont = lines.slice(i + 1, j); if (cont.some(hasLink)) { last = { type: "finding", bullet: b[1]!, claim: b[2]!, sep: "", rest: "", continued: cont }; section.body.push(last); i = j - 1; continue; } } last = null; section.body.push({ type: "line", text: line }); } return doc; } // A finding's evidence — its quotes and links — wherever they sit: after the // claim on the bullet line, or on the indented lines under it. export function evidenceOf(f: Finding): string { return [f.rest, ...f.continued.map((l) => l.trim())].filter((x) => x.trim()).join(" "); } export function findingLines(f: Finding): string[] { return [`${f.bullet}${f.claim}${f.sep}${f.rest}`, ...f.continued]; } export function renderSweep(doc: SweepDoc): string { const out: string[] = [...doc.lead]; if (doc.hasTitle) { out.push(doc.rawTitle !== undefined && doc.rawTitle.slice(2).trim() === doc.title ? doc.rawTitle : `# ${doc.title}`); } out.push(...doc.preamble); for (const s of doc.sections) { out.push(s.rawHeading !== undefined && s.rawHeading.slice(3).trim() === s.title ? s.rawHeading : `## ${s.title}`); for (const b of s.body) { if (b.type === "line") out.push(b.text); else out.push(...findingLines(b)); } } return out.join("\n"); } export function findingsOf(section: SweepSection): Finding[] { return section.body.filter((b): b is Finding => b.type === "finding"); } // Every finding in document order, numbered from 1 — the numbering an op // batch is written against. export function numberFindings(doc: SweepDoc): { n: number; section: SweepSection; finding: Finding }[] { const out: { n: number; section: SweepSection; finding: Finding }[] = []; for (const section of doc.sections) { for (const finding of findingsOf(section)) out.push({ n: out.length + 1, section, finding }); } return out; } export const isCoverage = (s: SweepSection) => s.title.trim().toLowerCase() === "coverage"; // The document as a model reads it: the title, the summary, each section // and each finding numbered `[n]` (the numbers an op batch uses). export function numberedView(doc: SweepDoc): string { const numbers = new Map(numberFindings(doc).map((x) => [x.finding, x.n])); const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" "); const lines = [`TITLE: ${doc.title}`, `SUMMARY: ${summary}`]; for (const s of doc.sections) { lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}`); for (const b of s.body) { if (b.type === "finding") lines.push(`[${numbers.get(b)}] ${b.claim}${b.sep || " "}${evidenceOf(b)}`.trimEnd()); else if (b.text.trim()) lines.push(b.text); } } return lines.join("\n"); } // The quoted spans of a finding's evidence, in order (without their marks). 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(", "); }