import { causeKey, fetchedForRoute, loadFetched, loadIssues, runNotCollected, sameRoute, sweepBriefing, sweepPage, } from '@basementstudio/qa-engine/run' import { findingIdentities, isDefect, type FetchedResource, type Finding, type Issue, type PageFacts, type RunManifest, } from '@basementstudio/qa-schema' import { authoringContract } from './authoring-contract' import { mentionsRoute, sliceCoverage, summariseFacts, type ToolContext } from './tools' /** * The authoring contract, as brief lines. * * Nested at level 3 so it sits beside the brief's other `###` sections rather than reading as the * document restarting. **Not gated on `noContract`**, which exists for a caller that briefed its * reviewer about scope and batching: `issueWrite` refuses drafts on these rules, so a reviewer that * never sees them writes drafts that come back refused and learns the contract one refusal at a time. */ const AUTHORING_LINES: string[] = authoringContract({ headingLevel: 3 }).split('\n') /** * One route's review brief — everything a per-route reviewer needs, assembled once. * * ## The number this exists to move * * `qa review` already aggregated what a review starts from, and it is **249KB (~62k tokens) and * run-wide**, so no shard can be handed it: a per-route reviewer would pay for every other route's * findings. Measured across three sites × three routes × five reviewers — 1,036 turns, **$324.74** — * **cache reads were 51.8% of the bill**, because the API is stateless and every turn re-sends the * whole conversation. So the lever is not "fetch faster", it is *how many bytes sit in the transcript * from turn one*. * * **Front-loading raw facts is the wrong lever and the numbers say so.** One route's `facts.json` is * 522KB–2.1MB (~134k–537k tokens): front-loading one would cost **$0.81 per turn — $32 over 40 turns, * more than the whole agent costs today**. The same route's `findings.md` is 18–23KB (~5–6k tokens), * **25–90× smaller**, already ranked, grouped and deduped, and is what reviewers read first anyway. * Every section here was chosen from what the fifteen reviewers actually spent calls on, and the * target is **~20–25k tokens, cached once**. * * ## What it deliberately does not do * * It interprets nothing. No severity moves, nothing is ranked, no cause is named. The one thing this * module adds that is not a stored measurement is **arithmetic the reviewers were each doing by hand** — * the ownership verdict — and arithmetic belongs in the deterministic layer for the same reason * `describeShape` does. * * ## Markdown, not JSON, and that is the point of the format * * The three consumers are a shard reading it in one turn, a request body to a model API, and the cloud * box piping it to the same place. All three read prose; none of them wants to re-parse a nested object * to find a sentence. `findings.md` is already markdown, so a JSON envelope would mean escaping the * largest section of the document for nobody's benefit. `reviewPayloadJson` exists for a caller that is * scripting against the parts. */ /** * A backtick, without one ever appearing inside a template literal. * * Same reason as `run/prompt.ts`: this module emits markdown, so most of what it produces is inline * code, and an escaped backtick inside a template literal is the trap that has cost this project four * hangs — it manifests as `bun test` hanging with no output rather than as a parse error. So there are * **no template literals in this file**; prose lives in single-quoted strings, where a backtick is just * a character, and anything interpolated is concatenated. */ const code = (value: string): string => '`' + value + '`' const plural = (n: number, one: string, many: string): string => (n === 1 ? one : many) /** * The shard half of the fan-out contract — what binds a per-route reviewer, and nothing else. * * ## Why it is in the payload at all * * The claim the skill split was filed on was that every subagent pays ~22k tokens for `SKILL.md`. * Fifteen reviewers measured otherwise: **several read zero lines of it and reported needing none**. * What every one of them read in full is `references/fan-out.md` — 199 lines, of which they * consistently used 40–60 — and the reason is structural: the meta pass's rules sit in front of the * shard contract, so half the document a shard is told binds it is explicitly not theirs and it has to * read the whole thing to find that out. * * So the fix is not a smaller skill, it is **handing a shard its own half and no more**. This is that * half, and it is ~60 lines against 1,298. * * ## Two copies, and what keeps them honest * * `fan-out.md` keeps its narrative version, because the orchestrator planning a fan-out needs the * measurements and the history behind each rule and a briefed shard needs the rule. `review-payload.test.ts` * pins every rule here against a phrase in that file, so changing one without the other fails — the same * arrangement `prompt.test.ts` uses to keep `NOTE_KINDS` from drifting off `isIssueWork`. */ export const SHARD_CONTRACT: string[] = [ '### The contract you are held to', '', 'You are **one route of a fan-out**. Other reviewers are working other routes and the site-level', 'slice concurrently, and none of them will read your report back.', '', '- **Pass the run id in every call.** Every tool defaults to the newest run and the run being', ' reviewed is not always it. A reviewer that omits it reports confidently on the wrong one.', '- **Your route, and only that.** Pass 1 (every defect becomes an issue or is deliberately cleared)', ' and pass 2 (every note judged) for this page, plus this page\'s surface-level implications from', ' pass 3 (what the tool never looked at).', '- **Write with ' + code('route') + ' set, and write in batches** — flushed every ~5 issues or at a pass', ' boundary. Measured across fifteen reviewers, ' + code('qa_issue_write') + ' was **151 of 579 tool calls,', ' one per issue**, and they land in the late turns where the context being re-sent is largest. Per-issue', ' files are what make concurrent writing safe, so two reviewers physically cannot overwrite each other.', ' **Not once at the end** — the review runs for an hour and somebody is watching.', '- **Your stop test is the three counters, and every write returns them.** ' + code('routeDefectsUncited'), ' and ' + code('routeNotesUncited') + ' go to zero. For ' + code('routeFoundByLooking') + ', **the floor is', ' one**, or one line in your report saying what you examined and cleared instead. The run-level', ' ' + code('defectsUncited') + ' counts every other reviewer\'s work, so it can never reach zero for one', ' route and reads as failure.', '- **Verify with ' + code('qa_fetch') + ', not with ' + code('curl') + '.** Anything you are going to cite has', ' to be in the artifact. Measured across fifteen reviewers, ' + code('Bash') + ' was the largest tool', ' category at **208 of 579 calls**, and the half of it that was genuine verification went nowhere — four', ' of one reviewer\'s twelve issues rest on ' + code('curl') + ' output the run holds no trace of, so nobody', ' can re-check them. Set ' + code('route') + ': only route-scoped records reach your page\'s checks.', '- **A shared cause is not yours, and the rule is narrower than "fired everywhere".** One fix location', ' whose findings fired on **more than one route** — two of three is shared — belongs to the site-level', ' slice. Cite nothing for those and do not file them. The verdict above has already done this join.', '- **But if no check fired on it, file it.** An uncovered observation is visible only to whoever', ' noticed it, and the site-level slice is running concurrently and never reads your report.', ' **Prose is not a home and a concurrent reviewer is not a channel.** Write the issue, say in it that', ' the fix is shared, and let the meta pass merge. A duplicate is cheap; a lost finding is not.', '- **A note on your own route is yours even when it fired everywhere.** These two rules collide by', ' design and this is which wins: the number you are held to has to be closeable.', '- **A finding your own measurement contradicts is written up, not left uncited.** You cannot reach', ' ' + code('qa_waive') + ' — that needs a human\'s confirmation and you have no channel to one — and an', ' ' + code('advice') + ' issue is refused for "I examined this and it is fine". Write an issue that **cites', ' the finding**, ' + code('kind: transparency') + ', severity ' + code('nit') + ', saying what you measured and', ' what it contradicts. That records the contradiction beside the claim and leaves the human the one', ' decision that is theirs.', '- **Page weight splits by where the bytes come from.** An asset only this route loads is yours; a', ' bundle, font or preload every route pays for is a shared cause, even when you are the page that made', ' it visible. Say which you concluded and why — the numbers do not make that judgement for you.', '- **' + code('notCollected') + ' and run-level notes are not yours**, with one exception: how far *your*', ' route was scrolled. That differs page by page, so a route the pass stopped short on is a coverage gap', ' only you can see. Say it against your route.', '- **' + code('summary.sweep.notJudged') + ' is not ' + code('notCollected') + ' and it *is* yours.** It names', ' facts this run holds for your page that no check reads, with the path that returns each. That is pass 3', ' input on your own route. Read the list rather than a remembered version of it — it is derived per run.', /* * The three field rules that were here — `where` may not out-assert `problem`, `why` is about the * issue, a `transparency` issue stays one record — moved to `authoring-contract.ts`, which this brief * now carries as its own section. They were the only writing rules a shard ever got, and repeating * them here would put them in one document twice. */ '- **No ' + code('rank') + ', no dedupe, no cross-page anything.** Those are the meta pass\'s, and a reviewer', ' attempting them produces competing accounts of one site.', '- **Never push and never call ' + code('qa finish') + '.** Publication is the human\'s decision or the', ' orchestrator\'s, never a subagent\'s — a shard in one real fan-out took an unscoped production push', ' because nothing told it not to. ' + code('qa finish') + ' declares a review over while other reviewers are', ' still writing.', '- **One line back saying what you examined and cleared.** A route you looked at carefully and found', ' clean is a different artifact from one nobody opened, and your report is where that goes.', ] /** * What a reader with no tools is told instead of a tool list. * * **A one-shot brief used to carry the shard's tool list verbatim**, so a reader with one turn and no * tools was told to author through `qa_issue_write`, project facts with `qa_facts`, and — this is the * line that matters — *"verify a URL with this, not with `curl`"*. Both one-shot arms of the 2026-08-19 * comparison reported those exact tools back through `unused` as named-and-unreachable, and on * 2026-08-20 one of them wrote *"I fetched every sitemap-declared URL … 46 URLs"* and *"Verified by * curl"* into three issues, uncited, one of them first in the work list. Nothing was fetched: the run's * stored facts hold no such sample. * * Being told to verify, given a named way to do it, and having no way to do it is the pressure that * produces an invented verification. So the section states the constraint and gives the response that * is actually available — say what you could not settle — rather than naming instruments. */ function noToolsSection(): string[] { return [ '### You have no tools, and that changes what an issue may claim', '', 'One turn, no tool calls. Everything you need is in this document; nothing else is reachable, and', 'nothing you write is checked against the site before it is stored.', '', '- **Never describe an action you did not take.** Not fetched, opened, ran, sampled, verified or', ' ' + code('curl') + 'ed. A measurement in this brief is evidence — cite it and state it plainly — but', ' it is the run\'s, not yours, and a value this document does not contain is not available to you at', ' any confidence.', '- **The honest answer to something you cannot settle is that you could not settle it.** *"Nothing', ' under /billing was audited, and the sitemap declares 1,054 URLs there"* is a complete finding. If', ' it reads too thin to file, the thinness is the finding.', '- **A crop you were not shown is a crop you cannot judge.** Say a person needs to look.', ] } /** The tools a shard needs, named — because a deferred tool costs a lookup before it can be called. */ function toolsSection(runId: string, route: string | undefined, someRoute?: string): string[] { const withRun = (extra: string): string => code('{ runId: "' + runId + '"' + extra + ' }') /* The site slice writes issues with no route: what it owns is measured once for the origin, or spans several. */ const routeArg = route ? ', route: "' + route + '"' : '' /* A real route off this run's manifest. An invented one in a worked example is a path somebody will paste. */ const example = route ?? someRoute ?? '/' return [ '### The tools you need, by name', '', 'These are the only ones you need. **Named because they are deferred**: an agent that does not', 'know the name spends a schema lookup discovering it, and across the last fan-out that was **26 calls', 'of pure overhead**, found one refusal at a time.', '', '- ' + code('qa_issue_write') + ' — author an issue. ' + withRun(routeArg + ', title, type, where, cites'), ' Every write returns your three counters, so the stop test costs no call of its own.', ...(route ? [ '- ' + code('qa_facts') + ' — one section of this page\'s stored facts, when the digest below is not enough:', ' ' + withRun(', page: "' + route + '", sections: ["formControls"]'), ] : [ '- ' + code('qa_facts') + ' — one section of any page\'s stored facts, when you need to see how a shared', ' cause renders on a particular route: ' + withRun(', page: "' + example + '", sections: ["formControls"]'), ]), '- ' + code('qa_fetch') + ' — **verify a URL with this, not with ' + code('curl') + '.** It fetches one URL on', ' this site and writes the answer into the run, so your issue can cite evidence the next reader can', ' check: ' + withRun(routeArg + ', url: "…"') + ', plus ' + code('body: true') + ' when you need', ' the bytes or the page\'s own ' + code('rel=canonical') + '. A shell-out leaves nothing behind —', ' four of one reviewer\'s twelve issues rested on ' + code('curl') + ' output the run held no trace of, and', ' nobody can re-check those. It is scoped to this site; a third party is refused by name.', ...(route ? ['- ' + code('qa_screenshots') + ' / ' + code('qa_screenshot') + ' — the crops for this page. See the note below.'] : []), '', ...(route ? [ 'You should not need ' + code('qa_findings_md') + ' or ' + code('qa_findings') + ' for this route: the document both of', 'them would return for it is below, verbatim. You should not need ' + code('qa_issues') + ' either, unless a', 'counter stalls above zero and you want the names behind it.', ] : [ 'You should not need ' + code('qa_findings') + ' at all: every finding you own is listed below in full, by id, and', 'nothing else in this run is yours. Reaching for the run-wide document would return every route\'s', 'findings, which the route briefs already carry and their reviewers are already writing up.', ]), '', 'If the MCP tools are not registered in your session, every one is also a command:', code('qa mcp @args.json') + '. On Windows prefer the ' + code('@file') + ' form — quoting a JSON', 'argument through a nested interpreter fails on syntax that looks correct on screen.', '', 'To flush a batch of writes in one call: ' + code('qa mcp --run --batch @calls.json') + '. It validates', 'every entry before running any of them, so a batch that would be refused writes nothing.', ] } /** * Who owns each of this route's findings, joined once instead of fifteen times. * * ## Why this is the second section and not a footnote * * Every shard in the last fan-out performed the same manual join: read the site-level findings, read * `onEveryRoute` and `onSeveralRoutes`, cross-reference both against `routeUncitedCheckIds`, and work * out which of its own findings it was forbidden to write up. It is **the single most confusing part of * the contract and it is entirely mechanical** — four reviewers independently reported the version of * the rule they were given as self-contradictory, because it demanded a counter reach zero while * forbidding them from writing the remainder. * * So the payload hands over the answer rather than the inputs. Three groups, and the third is the one a * route filter cannot show you: * * - **yours** — fired on this route and no other. * - **shared** — fired here *and* on at least one other route, so one fix location serves several pages * and the site-level slice owns it. Route-scoped **notes** are excluded: a note on your own route is * yours even when it fired everywhere, because the number you are held to has to be closeable. * - **site-level** — carries no route at all but names this one among its members, so this page's own * `findings.md` counts it and `qa_findings { route }` cannot return it. That mismatch was reported as a * bug four times before the count was explained. */ /** * Which brief a finding belongs to — **computed once, and the only answer in this file.** * * ## The gap this closes * * A brief's prose and a brief's content were computed by different code paths and nothing checked they * agreed. The ownership verdict counted over *every* finding in the run; the content pasted the route's * `findings.md`. Both losses in the eleven-reviewer experiment are that gap: * * - **Told you own it, cannot see it.** The whole-run brief's ownership line said *"plus 24 routeless * findings — yours too"* into a document carrying none. A reviewer with tools called `qa_findings` and * reached 24 of 24; a reviewer with one read reached **0 of 24** and said so. * - **Can see it, told it is not yours.** Five checks fired on both of a site's routes, becoming shared * causes both shards are forbidden to file — and the slice that owns them had no brief, because there * was no `qa brief --site`. One arm lost **10 defects**, another **5**. * * So both the sentence and the section render from `owned` below. Disagreement is unrepresentable * rather than tested for, and `briefPartition` asserts the plan's briefs cover every finding once. * * ## The rules, and why notes break the pattern * * A **shared cause** is one fix location firing on two or more crawled routes — resource, then source * file, then selector, then the check id alone. **Not the check id**, which is the join that lost six * unrelated components to one slice. Shared causes belong to the site brief; so does everything with no * route, which is configured once per origin. * * **Every note on a route stays with that route**, even where the same check fired everywhere. The * number a shard is held to has to be closeable, and a note is not a fix location being shared — it is * context for reading the page. */ function briefOwnership( all: readonly Finding[], routes: string[], scope: BriefScope, route: string | undefined, ): Ownership { const routesByCause = new Map>() for (const f of all) { /* * **Counted over the routes this run crawled**, which a cause map keyed off the findings alone does * not. A findings file can carry a route the run in front of you never loaded — a replay, a re-crawl * with a shorter route set — and letting that route make a cause "shared" hands a shard's own work to * a slice that has nothing to look at. */ if (!isDefect(f) || !f.route || !routes.some((r) => sameRoute(r, f.route))) continue const key = causeKey(f) const seen = routesByCause.get(key) ?? new Set() seen.add(f.route) routesByCause.set(key, seen) } /* A one-route run has no other route for a cause to be shared with, whatever the findings say. */ const isShared = (f: Finding): boolean => routes.length > 1 && isDefect(f) && Boolean(f.route) && (routesByCause.get(causeKey(f))?.size ?? 0) > 1 const routeless = all.filter((f) => !f.route) const sharedCauses = all.filter((f) => isShared(f)) if (scope === 'site') { return { scope, owned: [...routeless, ...sharedCauses], mine: [], sharedElsewhere: [], routeless, sharedCauses } } const mine = all.filter((f) => sameRoute(f.route, route)) /* * `whole` is one reviewer with no peers, so nothing is held back and the routeless findings are theirs * — which is the correction that turned 0 of 24 into 24 of 24. The route's own shared causes stay * theirs too: there is no second shard for a fix location to be shared *with*. */ if (scope === 'whole') { return { scope, owned: [...mine, ...routeless], mine, sharedElsewhere: [], routeless, sharedCauses } } const sharedElsewhere = mine.filter((f) => isShared(f)) return { scope, owned: mine.filter((f) => !sharedElsewhere.includes(f)), mine, sharedElsewhere, routeless, sharedCauses, } } /** Which reader a brief is for. Not a flag on any command — `qa brief` picks it from what you asked for. */ export type BriefScope = 'route' | 'site' | 'whole' /** * One brief's answer to *"what is mine"*, from which both its prose and its content are rendered. * * `owned` is the field that matters and the one the guards check: the ownership sentence counts it, the * content carries it, and the union of it across the plan's briefs is every finding, exactly once. */ export interface Ownership { scope: BriefScope /** Everything this brief's reader is responsible for. */ owned: Finding[] /** Findings carrying this route, whoever owns them. Empty for the site brief. */ mine: Finding[] /** On this route and owned by the site brief instead. Empty unless `scope` is `route`. */ sharedElsewhere: Finding[] /** Findings with no route at all — configured once per origin. */ routeless: Finding[] /** Every defect whose fix location fired on two or more crawled routes, run-wide. */ sharedCauses: Finding[] } /** * Ownership for a run one reviewer owns end to end. * * The full verdict spends seven lines explaining a join across routes before reporting that nothing was * shared — and with a single reviewer it can only ever report that, because there is no second shard for * a cause to be shared *with*. The counts stay: they are the denominator the stop test is measured * against. The explanation of the join goes. */ function soloOwnership(own: Ownership, route: string): string[] { const defects = own.mine.filter((f) => isDefect(f)).length const notes = own.mine.length - defects /* Routeless findings are configured once per origin. With no site-level slice they are this reviewer's. */ const routeless = own.routeless.length return [ '### What is yours', '', '**All of it.** You are the only reviewer on this run: there is no second shard for a fix location to' + ' be shared with, and no site-level slice to hand anything to.', '', '**' + defects + ' ' + plural(defects, 'defect', 'defects') + ' and ' + notes + ' ' + plural(notes, 'note', 'notes') + '** on ' + code(route) + (routeless > 0 ? ', plus ' + routeless + ' routeless ' + plural(routeless, 'finding', 'findings') + ' — measured once for the whole origin (robots.txt, security headers) and yours too.' : '.'), ] } /** * The routeless findings, in full, for the reviewer that owns them. * * **A brief that names findings it does not carry is worse than one that omits them.** `soloOwnership` * says *"plus N routeless findings — yours too"*, and for its first day it said that into a document that * carried none: the route's `findings.md` is pasted verbatim and excludes by construction everything * without a route. A tool-using reviewer papered over it with a `qa_findings` call and reached 24 of 24. * A reviewer with one read reached **0 of 24**, and reported being told it owned findings it could not * see — which is precisely the URL box's shape. * * Rendered here rather than reusing `renderGlobalFindingsMd`, which would re-paste every route finding * this brief already carries, under a second DRAFT banner, to add the handful it is missing. */ /** * Fetches this run already made, with the bodies it already stored. * * **The brief used to ask for evidence the artifact was holding.** It told the reviewer to fetch the * alternate copy of the page `body: true` and cite what came back — an instruction a one-shot cannot * act on at all, and one that costs a fan-out reviewer a tool call to rediscover. Measured on one run: * `/index.md` was stored with a 2,135-character `bodyExcerpt`, and the reviewer filed *"the * machine-readable copy was never opened"* about a file inside the run it was reviewing. That body * carried one authored description repeated **four times** and one quote attributed to two different * people — two real content defects that two reviewers with tools found and the one-shot could not. * * So the rule this follows: **the payload carries facts the run already has, and only ever asks for * what it does not.** */ function fetchedSection(records: readonly FetchedResource[]): string[] { const out: string[] = ["## What this run already fetched", ""] if (records.length === 0) { out.push( "Nothing was fetched beyond the pages themselves, so there is no stored response body here to read.", ) return out } out.push( "Responses this run requested and stored. These are **already measured** — do not ask for them again,", "and cite them by URL when an issue rests on one.", "", ) /* * A cap that bounds coverage has to be reported, so the count of what was trimmed is printed rather * than the list quietly ending. Bodies are the only unbounded part; the metadata line is tiny. */ let budget = BODY_BUDGET let trimmed = 0 /* * **Prose first, or the budget goes on the wrong bodies.** Records arrive in store order, and on a * real run `robots.txt`, `sitemap.xml` and `feed.xml` come before the alternate copy of the page — * so a shared budget spent in that order starves the one body carrying authored copy. Those three * are already digested by `meta.crawler.*` and `discovery.sitemap.*` checks; the markdown view is * read by nothing, which is exactly why it belongs here. Ordering, not filtering, so nothing is * dropped on a guess about content type. */ const prose = (r: FetchedResource): number => /markdown/i.test(r.contentType ?? '') ? 0 : /html/i.test(r.contentType ?? '') ? 1 : 2 const ordered = [...records].sort((a, b) => prose(a) - prose(b)) for (const r of ordered) { const head = "- " + code(r.url) + " — HTTP " + String(r.status ?? "no status") + (r.contentType ? " · " + r.contentType : "") + (typeof r.bytes === "number" ? " · " + r.bytes.toLocaleString() + "B" : "") out.push(head) const body = (r.bodyExcerpt ?? "").trim() if (!body) { if (r.bodyRead === false) out.push(" (headers only — the body was not read)") continue } if (budget <= 0) { trimmed++ continue } const slice = body.length > budget ? body.slice(0, budget) : body budget -= slice.length if (slice.length < body.length) trimmed++ out.push("", "```", ...slice.split(/\r?\n/), "```", "") } if (trimmed > 0) { out.push( "", "**" + trimmed + " stored " + plural(trimmed, "body", "bodies") + " " + (trimmed === 1 ? "was" : "were") + " truncated or omitted here against a " + BODY_BUDGET.toLocaleString() + "-character budget.** Read them with `qa_fetch` if an issue turns on one.", ) } return out } /** Characters of stored response body the brief will carry. 3,000 covers the 2,135-character alternate copy that motivated this with headroom. */ const BODY_BUDGET = 3_000 function routelessSection(routeless: readonly Finding[]): string[] { if (routeless.length === 0) { return [ '### Findings with no route', '', 'This run recorded none. robots.txt, the security headers, the sitemap and the crawler policy were' + ' all measured and none of them produced a finding.', ] } const ORDER = ['blocker', 'major', 'minor', 'nit'] as const const lines = [ '### Findings with no route — yours, because nobody else is reviewing this run', '', 'Measured once for the whole origin rather than per page: robots.txt, the security headers, the' + ' sitemap, the AI-crawler policy, origin caching. Each is **one fix in one place**, so name that' + ' place — ' + code('next.config.ts headers()') + ', ' + code('public/robots.txt') + ', the CDN — rather than "not localised". Cite them by id exactly like a route finding.', '', ] for (const severity of ORDER) { const group = routeless.filter((f) => f.severity === severity) if (group.length === 0) continue lines.push('**' + severity.toUpperCase() + '** (' + group.length + ')') lines.push('') for (const f of group) { const note = f.kind === 'defect' ? '' : ' _[' + f.kind + ']_' lines.push('- ' + code(f.id) + ' **' + f.title + '**' + note) if (f.detail?.trim()) lines.push(' ' + f.detail.trim()) const resource = f.evidence.resourceUrl if (resource) lines.push(' → ' + resource) lines.push(' ' + code(f.checkId)) } lines.push('') } return lines } function ownershipVerdict( own: Ownership, issues: readonly Issue[], route: string, routes: string[], ): string[] { const cited = new Set(issues.flatMap((i) => i.cites)) const isCited = (f: Finding) => findingIdentities(f).some((id) => cited.has(id)) /** * **Shared is a fix location on more than one route, not a check id on more than one route.** * * The join lives in `briefOwnership` now, and is the same one the site brief's content is built from, * so the sentence below cannot describe a split the documents do not make. It joined on `checkId` once * and lost work: `layout.small-tap-target-group` fired on two routes as six findings with six different * selectors — a navbar stage list, three separate carousel dots, a step control — and the verdict handed * all six to the site-level slice as one shared cause. The reviewer obeyed, filed none, and with no * site-level reviewer in that configuration they went nowhere. */ const shared = own.sharedElsewhere const yoursDefects = own.owned.filter((f) => isDefect(f)) const yoursNotes = own.owned.filter((f) => !isDefect(f)) const siteLevel = own.routeless.filter((f) => mentionsRoute(f, route)) /** * Findings and causes counted separately, and never in one word. * * The first version of this sentence read *"29 shared causes"* for 29 findings resolving to 9 check * ids, which is the mislabel `describeShape` exists to prevent: `distinctCauses` is a defined quantity * in this codebase and 29 is not it. A count that names the wrong unit looks exactly like a count that * names the right one. */ const causes = (findings: readonly Finding[]): string[] => [...new Set(findings.map((f) => f.checkId))].sort() /** * A check id that is shared on *some* of its findings and not others, which is the case the check-id * join could not see. Named, because a reader who sees the id in the not-yours list and also sees it on * a finding of their own would otherwise conclude the verdict is wrong. */ const splitIds = causes(shared).filter((id) => yoursDefects.some((f) => f.checkId === id)) const lines = [ '### What is yours, and what is not', '', 'The join every reviewer in the last fan-out did by hand. Nothing here is a judgement — it is', 'arithmetic over which routes each **fix location** fired on: a resource, a source file or a selector,', 'and the check id only where a finding carries none of those. **Not the check id**, which is why a', 'check that fired on two routes as six unrelated components stays yours rather than becoming one', 'shared cause you are forbidden to file.', '', '**Yours — ' + yoursDefects.length + ' ' + plural(yoursDefects.length, 'defect', 'defects') + ' and ' + yoursNotes.length + ' ' + plural(yoursNotes.length, 'note', 'notes') + '.** ' + plural(yoursDefects.length, 'That defect fired', 'Those defects fired') + ' on this route and on no other. **Every note on this route is yours** even where the same check' + ' fired everywhere — a note on your own route beats the shared-cause rule, because the number you' + ' are held to has to be closeable.', ] if (shared.length > 0) { const ids = causes(shared) lines.push('') lines.push( '**Not yours — ' + shared.length + ' ' + plural(shared.length, 'defect', 'defects') + ' on this route, from ' + ids.length + ' shared ' + plural(ids.length, 'cause', 'causes') + '.** Each resolves to one fix location that fired here *and* on at least one other route, so it' + ' serves several pages and the site-level slice owns it. Do not cite them and do not file them.' + ' By check id: ' + ids.map(code).join(', ') + '.' + (splitIds.length > 0 ? ' **' + splitIds.map(code).join(', ') + (splitIds.length === 1 ? ' also has' : ' also have') + ' findings that are yours** — the same check fired on this route at a different place, and' + ' that instance is not shared. The counts above already separate them.' : ''), ) } else { lines.push('') lines.push( '**No shared causes on this route.** Every check that fired here fired only here' + (routes.length > 1 ? ' across the ' + routes.length + ' routes this run crawled' : '') + ', so nothing is being held back from you on those grounds.', ) } if (siteLevel.length > 0) { const ids = causes(siteLevel) lines.push('') lines.push( '**Not yours — ' + siteLevel.length + ' site-level ' + plural(siteLevel.length, 'finding', 'findings') + '** carrying no route at all but naming this one among ' + plural(siteLevel.length, 'its', 'their') + ' members, from ' + ids.length + ' ' + plural(ids.length, 'check', 'checks') + ': ' + ids.map(code).join(', ') + '. This page\'s ' + code('findings.md') + ' below counts ' + plural(siteLevel.length, 'it', 'them') + ', which is why its total can exceed the number of findings attributed to the' + ' route — that mismatch was reported as a bug four times before it was explained. A check id may' + ' appear in both lists: some of its findings collapsed site-wide and some stayed on a route.', ) } /** * The line the whole section is for: how the stop test's number splits. * * `routeDefectsUncited` counts every uncited defect on the route, shared ones included — so a shard * that has written up all of its own work still reads a number above zero and cannot tell whether it * is finished. Four reviewers independently reported the contract as self-contradictory for exactly * this reason: it demanded zero *and* forbade filing the remainder. Both halves were right; the split * was simply never computed for them. */ const uncitedYours = yoursDefects.filter((f) => !isCited(f)) const uncitedShared = shared.filter((f) => !isCited(f)) lines.push('') lines.push( 'So, in the one number your stop test reports: of the ' + (uncitedYours.length + uncitedShared.length) + ' ' + plural(uncitedYours.length + uncitedShared.length, 'defect', 'defects') + ' on this route that no issue cites yet, **' + uncitedYours.length + ' ' + plural(uncitedYours.length, 'is yours', 'are yours') + ' and ' + uncitedShared.length + ' ' + plural(uncitedShared.length, 'is a shared cause', 'are shared causes') + '**. ' + code('routeDefectsUncited') + ' counts both, so it bottoms out at ' + uncitedShared.length + ' rather than at zero and that is the correct end state — say so in your report back rather than' + ' filing the remainder to close the number.', ) return lines } /** * Ownership for the site-level slice — **the only reviewer whose whole job is the join.** * * Its brief was hand-written, because there was no `qa brief --site`. That is not a small gap: the * fan-out contract says the slice owns *"every shared cause"* and an orchestrator briefing it from * memory named some of them. One arm lost **10 defects** that way and another lost **5**, on a run where * every route brief correctly told its shard those defects were not theirs. Nobody was wrong; the * document that would have caught it did not exist. */ function siteOwnership(own: Ownership, routes: string[]): string[] { const defects = own.owned.filter((f) => isDefect(f)).length const notes = own.owned.length - defects const causes = [...new Set(own.sharedCauses.map((f) => f.checkId))].sort() const lines = [ '### What is yours', '', 'Everything **no single route owns** — and this is the other half of the split every route brief in', 'this run has already been told about. A shard reading its own brief has been shown these findings and', 'instructed not to file them, so if you do not file them nobody does.', '', '**' + defects + ' ' + plural(defects, 'defect', 'defects') + ' and ' + notes + ' ' + plural(notes, 'note', 'notes') + '**, in two groups:', '', '1. **' + own.routeless.length + ' ' + plural(own.routeless.length, 'finding', 'findings') + ' with no route** — measured once for the whole origin: robots.txt, the security headers, the' + ' sitemap, the AI-crawler policy, origin caching.', '2. **' + own.sharedCauses.length + ' ' + plural(own.sharedCauses.length, 'finding', 'findings') + ' from ' + causes.length + ' shared ' + plural(causes.length, 'cause', 'causes') + '** — one fix location that fired on two or more of the ' + routes.length + ' routes this run crawled' + (causes.length > 0 ? ', by check id: ' + causes.map(code).join(', ') : '') + '.', ] if (own.sharedCauses.length > 0) { lines.push('') lines.push( '**A shared cause is one issue, not one per route.** Nine nav 404s from one CMS document are one' + ' issue; the same check firing on six unrelated components is six. Cite every finding the fix' + ' closes — the ids below are all of them — and name the single file, document or config in' + ' ' + code('where') + '.', ) } return lines } /** * The findings the site slice owns, in full — routeless and shared, in one list. * * Rendered here rather than reusing `renderGlobalFindingsMd`, which would paste every route finding this * brief does not own, under a second DRAFT banner, to add the ones it does. **The reader is told it owns * these, so it has to be able to see them**: the failure this whole item exists for is a brief naming * findings it does not carry. */ function siteFindingsSection(own: Ownership): string[] { if (own.owned.length === 0) { return [ '### Your findings', '', 'This run recorded none. Nothing was measured once for the origin and nothing fired on more than' + ' one route, so every finding in this run belongs to exactly one route brief. **That is an' + ' answer, not an empty document** — say so and stop.', ] } const ORDER = ['blocker', 'major', 'minor', 'nit'] as const const lines: string[] = [] const group = (title: string, blurb: string, findings: readonly Finding[]): void => { if (findings.length === 0) return lines.push('### ' + title) lines.push('') lines.push(blurb) lines.push('') for (const severity of ORDER) { const bucket = findings.filter((f) => f.severity === severity) if (bucket.length === 0) continue lines.push('**' + severity.toUpperCase() + '** (' + bucket.length + ')') lines.push('') for (const f of bucket) { const note = f.kind === 'defect' ? '' : ' _[' + f.kind + ']_' const where = f.route ? ' — on ' + code(f.route) : '' lines.push('- ' + code(f.id) + ' **' + f.title + '**' + note + where) if (f.detail?.trim()) lines.push(' ' + f.detail.trim()) const resource = f.evidence.resourceUrl if (resource) lines.push(' → ' + resource) lines.push(' ' + code(f.checkId)) } lines.push('') } } group( 'Findings with no route', 'Each is **one fix in one place**, so name that place — ' + code('next.config.ts headers()') + ', ' + code('public/robots.txt') + ', the CDN — rather than "not localised".', own.routeless, ) group( 'Shared causes — the same fix location on several routes', 'Grouped by check id below only for reading; **the unit of work is the fix location**. Two findings' + ' under one check id can still be two issues if they resolve to two different places, and the' + ' route each one fired on is named so you can tell.', own.sharedCauses, ) return lines } /** The run's own identity and bounds — the constants a brief has to restate, because a subagent inherits none. */ function runConstants(manifest: RunManifest, storeRoot: string, page: { route: string; url: string }): string[] { const lines = [ '### This run', '', '- **run id** ' + code(manifest.runId) + ' — pass it in every call.', '- **store** ' + code(storeRoot), '- **your route** ' + code(page.route) + ' — ' + page.url, '- **target** ' + manifest.target.url + ' · ' + manifest.target.env + (manifest.target.isDevServer ? ' · **dev server, so every timing is meaningless**' : ''), '- **routes crawled** ' + manifest.pages.map((p) => p.route).join(', '), '- **viewports** ' + manifest.config.viewports.map((v) => v.id).join(', '), ] /** * Whether the run had a repo, said plainly. * * A reviewer reported that nothing told them, and **it changed the `where` field of all eight issues * they wrote** — a linked repo means a finding can name a file, and no repo means the * only honest answer is the CMS document or the config surface. `source.linked` is the field that * carries it: absent means the git fields describe whatever checkout the crawl was invoked from, which * is a different claim and usually a wrong one. */ if (manifest.source.linked) { const at = [manifest.source.repoSlug ?? manifest.source.repoPath, manifest.source.commit?.slice(0, 8)] .filter(Boolean) .join(' @ ') lines.push( '- **repo** linked — ' + at + (manifest.source.dirty ? ' (dirty: uncommitted changes, so a finding may not match any commit)' : '') + '. Findings carry heuristic source refs, so ' + code('where') + ' may name a file. Read it before you assert one.', ) } else { /* * **An address ladder, not an exit.** The previous wording ended "or say in words that you could * not localise it", and reviewers took the third option: measured over 24 tool-free reviews on * 2026-08-19, between 13% and 73% of issues per run opened `where` with "not localised" — many of * them naming the exact component in the same sentence, inside the disclaimer. A reviewer with * tools over the same facts ran 0-28%, and it had no repo either, so the ceiling here is not * source mapping. "No repo" bounds what `where` may claim; it does not stop it having a value. */ lines.push( '- **repo** NOT linked, so ' + code('where') + ' must not name a file path — but it still names a place. Take the first of these that fits:' + ' the component, identified by the selector or class the finding already carries; the CMS' + ' document; the config surface (a header rule, a robots route, an env var). **A component named' + ' by its own selector is localised** — do not open with "not localised" because you could not' + ' add a path to it. Reserve that opening for an issue with genuinely no single place, such as a' + ' bundle of unaudited sections, and say there what the places are. Do not guess a path.', ) } const bounds = runNotCollected(manifest) if (bounds.length > 0) { lines.push('') lines.push( '**What this run did not cover** (run-level, so the site-level slice owns all of it except your own' + ' scroll bound below):', ) lines.push('') for (const bound of bounds) lines.push('- ' + bound) } return lines } /** * The same constants for the site slice, whose "your route" is every route and none of them. * * Built off `runConstants` rather than beside it: the repo line changed the `where` field of all eight * of one reviewer's issues, and the site slice writes the issues most likely to name a config surface — * `next.config.ts headers()`, `public/robots.txt`, the CDN. It needs that line more than a shard does. */ function siteRunConstants(manifest: RunManifest, storeRoot: string, routes: string[]): string[] { const first = manifest.pages[0] const lines = runConstants(manifest, storeRoot, { route: 'site', url: first?.url ?? manifest.target.url }) return lines.map((line) => line.startsWith('- **your route**') ? '- **your slice** everything no single route owns, across the ' + routes.length + ' ' + plural(routes.length, 'route', 'routes') + ' crawled. You write issues with **no** ' + code('route') + ' unless the fix genuinely lives on one.' : line, ) } /** * The site slice's stop test — the same shape as a shard's, over a different denominator. * * A shard's `routeDefectsUncited` bottoms out above zero by design, because the shared causes on its * route are not its to file. **This is the reviewer for whom that remainder is the whole job**, so its * number is the uncited half of `owned` and it really does go to zero. */ function siteStopTest(own: Ownership, issues: readonly Issue[], routeCount: number): string[] { const cited = new Set(issues.flatMap((i) => i.cites)) const isCited = (f: Finding) => findingIdentities(f).some((id) => cited.has(id)) const defects = own.owned.filter((f) => isDefect(f)) const notes = own.owned.filter((f) => !isDefect(f)) const defectsUncited = defects.filter((f) => !isCited(f)).length const notesUncited = notes.filter((f) => !isCited(f)).length return [ '### Where this slice stands right now', '', '| | total | not yet cited |', '| --- | --- | --- |', '| defects you own | ' + defects.length + ' | **' + defectsUncited + '** |', '| notes you own | ' + notes.length + ' | **' + notesUncited + '** |', '', '**Both go to zero, and unlike a shard\'s they really can.** A route reviewer\'s counter bottoms out' + ' above zero because its shared causes are yours; nothing is held back from you. If a number will' + ' not close, say which findings are left and why in your report rather than filing to close it.', '', 'Counted over the ' + routeCount + ' ' + plural(routeCount, 'route', 'routes') + ' this run crawled. A cause that fired on one of them is a route reviewer\'s, however many routes' + ' the site has — this run cannot see the pages it did not load.', ] } /** * The site slice's half of the fan-out contract. * * A shard's contract is `SHARD_CONTRACT` and half of what it says does not apply here: this reviewer has * no route, no crops, and no shared causes to hold back. Handing it the shard's half is what `fan-out.md` * used to do, and the reason the slice's brief was hand-written instead. */ export const SITE_CONTRACT: string[] = [ '### The contract you are held to', '', 'You are the **site-level slice** of a fan-out. Other reviewers are working the individual routes', 'concurrently, none of them will read your report back, and **every one of them has been shown the', 'findings below and told not to file them.** If you do not file them, nobody does.', '', '- **Pass the run id in every call.** Every tool defaults to the newest run and the run being', ' reviewed is not always it.', '- **Write with no ' + code('route') + '** unless a fix genuinely lives on one page. What you own is either', ' measured once for the origin or serves several pages; a route on the issue sends it to a report', ' section where the reader will read it as that page\'s problem.', '- **A shared cause is one issue, not one per route.** Nine nav 404s from one CMS document are one', ' issue and ' + code('where') + ' is that document. But the same check firing on six unrelated components', ' is **six** issues — the test is whether you can name the single file, document or config where the', ' change happens. ' + code('run/issue-rules.ts') + ' refuses a multi-cite issue whose citations resolve to', ' two or more places, so this is enforced rather than trusted.', '- **`where` may not assert more than `problem` does.** They are read together and by the same person,', ' so a `where` naming a cause the evidence does not establish sends somebody to change the wrong', ' thing. Measured: an issue titled *"absent from the server response"* whose `problem` said the run', ' could not tell client-side injection from a UA-conditional response, and whose `where` said the', ' tags **are** injected client-side. If the mechanism is unsettled, `where` names the surface —', ' *"whatever selects the variant served by user agent"* — and stops there.', '- **`why` is about the issue, never about reading the list.** It answers *why does this matter to', ' whoever fixes it*. Orientation for the report — which items are cheap, what the top of the list has', ' in common — is the meta pass\'s prose and belongs nowhere near a work item.', '- **A `transparency` issue is a record, so keep it one.** It exists so a gap is not read as a clean', ' bill of health, and a reader meets it in the same list as the work. If yours runs past a screen it', ' has become a report section: state the bound and the count, name what to do about it, and stop.', '- **Cite every finding the fix closes.** A shared cause has one finding per route it fired on and they', ' are all listed below by id. Citing one of three leaves two reading as unreviewed for ever.', '- **Write in batches**, flushed every ~5 issues or at a pass boundary — not once at the end. The', ' review runs for an hour and somebody is watching.', '- **Verify with ' + code('qa_fetch') + ', not with ' + code('curl') + '.** Anything you cite has to be in the', ' artifact, or a reader three weeks later cannot check it and ' + code('qa diff') + ' cannot say whether it', ' was fixed.', '- **The run-level bounds above are yours.** What the crawl never covered — routes nobody loaded, a', ' stage that did not run — is a site-level fact, and saying so is part of this slice\'s job. Nobody', ' else in the fan-out is positioned to.', '- **If no check fired on it, file it anyway.** An uncovered observation is visible only to whoever', ' noticed it. Prose is not a home.', ] /** * The stop test, with today's values in it. * * `settled` is false while the run is still going, and it gates the *"already closed"* sentence rather * than the table. Mid-crawl a route with no findings written yet counts zero uncited, which reads as * *"covered"* — the same false claim `coverageAfterWrite` withholds its numbers for, and the reason that * guard turns on an empty finding set rather than on a thrown read. */ function stopTest(coverage: ReturnType, route: string, settled: boolean): string[] { const done = settled && coverage.routeDefectsUncited === 0 && coverage.routeNotesUncited === 0 return [ '### Where this route stands right now', '', '| counter | now | done when |', '| --- | --- | --- |', '| ' + code('routeDefectsUncited') + ' | ' + coverage.routeDefectsUncited + ' | zero, or the remainder are shared causes |', '| ' + code('routeNotesUncited') + ' | ' + coverage.routeNotesUncited + ' | zero |', '| ' + code('routeFoundByLooking') + ' | ' + coverage.routeFoundByLooking + ' | at least one, or a line saying what you cleared |', '', 'Every ' + code('qa_issue_write') + ' returns these three for ' + code(route) + ', so you never need a call to read them.' + (done ? ' All three measured halves are already closed on this route — check that against the findings below rather than trusting it.' : ''), ] } /** * The facts nobody turned into a finding, for this page. * * `summariseFacts` minus its `hint`: that string is ~2.5KB of instruction about how to call `qa_facts`, * which is the right thing for a caller of that tool and pure weight here — the section above already * names the call, and the payload is a document rather than a tool response. */ /** * How far this page was travelled, in one sentence, whichever way it went. * * Every branch has to say something: *"reached the bottom"* is the answer that makes the totals below * complete, and it is the one `sweepBriefing` is silent about. **No indefinite article sits in front of * an interpolation here** — it cannot agree with a number the sentence has not seen, which is how * *"a 8px box"* shipped, so the pixel figures are phrased without one. */ function scrollBound(facts: PageFacts): string { const s = facts.scroll if (!s) { return ( 'this run has no scroll pass at all, so nothing below the first screen was measured — the byte' + ' totals, the layout probes, axe, the link graph and the crops are all first-screen-only, and that' + ' gap is unbounded rather than merely large.' ) } const settle = s.settled === false ? ' Requests were still arriving when the pass ran out of time, so the byte totals are a floor either way.' : '' if (s.stoppedBy === 'stuck') { return ( 'the document did not move when scrolled — ' + s.documentHeightPx + 'px of content in a viewport ' + s.viewportHeightPx + 'px tall — so only the first screen was measured and every total below is a floor. Say that against' + ' your route; no other reviewer can see it.' + settle ) } if (!s.reachedBottom) { const bound = s.stoppedBy === 'steps' ? s.steps + ' ' + plural(s.steps, 'screen', 'screens') : s.durationMs + 'ms' return ( 'the pass stopped after ' + bound + ', at ' + s.reachedPx + 'px of ' + s.documentHeightPx + 'px, so the rest of the page was not measured and every total below is a floor. Say that against your' + ' route; no other reviewer can see it.' + settle ) } return ( 'the pass reached the bottom in ' + s.steps + ' ' + plural(s.steps, 'screen', 'screens') + ' of ' + s.documentHeightPx + 'px' + (s.grew ? ', and the document grew while scrolling — infinite scroll or content injected on intersection' : '') + ', so nothing below the fold is missing from the totals below.' + settle ) } /** * Drop the ``(`qa_facts` sections: [...])`` pointers from stored sweep prose. * * Anchored on the whole parenthetical including the space before it, so removing one leaves a sentence * that still ends in its own full stop — the pointers are appended after the period in some branches and * before it in others, which is why the trailing punctuation is not assumed. */ export function withoutFactPointers(prose: string): string { return prose.replace(/\s*\(`qa_facts` sections: \[[^\]]*\]\)/g, '') } function factsDigest(facts: PageFacts, inlineUnjudged = false): string[] { const { hint: _hint, ...summary } = summariseFacts(facts) return [ '### What this page measures, that no check judged', '', /* * One producer of this prose. `sweepBriefing` already ends with the two sentences a shard is told to * read — *Not measured:* (which carries how far the page was scrolled) and *Measured and judged by no * check* — so re-listing either here would be a second answer to one question in the one document * where bytes are the whole point. */ /* * **The `qa_facts` pointers come out for a reader that cannot call it.** * * `sweep.ts` ends several of these sentences with *(`qa_facts` sections: ["formControls"])*, which is * the right next step for a shard and an instruction a one-shot cannot follow — it has one turn and * no tools. Both one-shot arms of the 2026-08-19 comparison reported those exact sections back * through `unused` as named-and-unreachable, and `inlineUnjudged` already means the sections a shard * would fetch are inlined here instead, so the pointer is not merely unfollowable, it is redundant. * * Stripped at render rather than in `sweep.ts`, because the fact is stored at crawl time and the * advice is correct for every other reader — and because this way it fixes runs already on disk. */ inlineUnjudged ? withoutFactPointers(sweepBriefing(sweepPage(facts))) : sweepBriefing(sweepPage(facts)), '', 'Two sentences above are yours specifically. **Measured and judged by no check** is pass 3 input on your', 'own route — read that list rather than a remembered version of it, because it is derived per run and', 'three of the fields it used to name became checks. **Not measured** is the run\'s coverage bound and', 'belongs to the site-level slice, with one exception, below.', '', /* * The positive case, stated. `sweepBriefing` names the scroll bound only when the pass stopped short, * which is right for a paragraph about what is wrong and wrong for the one coverage question the * contract makes a shard's own: silence would leave *reached the bottom* and *the field is not in * this run* looking identical, and one of those makes every total below a floor. */ '**How far your route was travelled** is the exception, because it differs page by page: ' + scrollBound(facts), '', /** * ── the assigned work goes **before** the bulk digest ───────────────── * * Inlining these was supposed to make them reachable and instead moved them out of reach a second * way. Measured: on a 170-focusable page the brief reached **2,017 lines**, the reader got through * **700**, and the three things it was assigned — the tab sequence at line 934, the stored bodies at * 1903, the crops at 2006 — were all past that. Its own words: *"I cleared nothing by looking, * because the material to look at was past the point I could reach."* `routeFoundByLooking` stayed * at zero. * * A reader that runs out of budget reads the top, so what it is answerable for belongs at the top. * The `summary` digest is a reference to consult and goes last; the sections a shard would have * *fetched deliberately* go first. Same bytes, and the ordering is the whole fix. */ ...(inlineUnjudged ? [ 'The sections this run assigns to you are inlined **first**, because you have no second turn to', 'ask for them. The ' + code('summary') + ' digest follows as reference — read it if you have room.', ...unjudgedSections(facts), '', '#### The digest — the same object ' + code('qa_facts') + ' returns as ' + code('summary'), ] : [ 'The digest below is the same object ' + code('qa_facts') + ' returns as ' + code('summary') + '. Ask for a', code('sections') + ' path when you need more than it carries.', ]), '', '```json', /* * The digest carries the same pointers the prose above does — in `notJudged` entries and in * `sweepBriefing` — so stripping one and not the other left the instruction reachable in the * document it was removed from. Measured: two occurrences survived the prose fix. */ inlineUnjudged ? withoutFactPointers(JSON.stringify(summary, null, 2)) : JSON.stringify(summary, null, 2), '```', ] } /** * The fact sections a brief calls *yours to read*, inlined for the reader that cannot go and read them. * * ## The gap this closes, measured * * `notJudgedFor` ends each entry with the call that fetches it — *"(`qa_facts` sections: * ["a11y.focusables"])"* — which is correct advice for a shard and impossible advice for a one-shot. * Both one-shot arms of the 2026-08-19 comparison reported exactly these three sections back through * `unused`: the 76-element tab sequence, the one form control's label text, and the canvas probes. Their * verdicts said tab order and form labelling were **unexamined rather than cleared** — the brief had * assigned work it also made unreachable. * * So `scope: 'whole'` gets the data instead of the instruction. Nothing else changes: the same sections, * the same shape `qa_facts` would have returned, and no judgement applied to any of it. * * ## Bounded, because a one-shot has no way to ask for less * * A page with 300 focusables would otherwise push the brief past what the turn can carry, and a * one-shot cannot say *"just the first twenty"*. Each section is capped and **says so when it truncates** * — a silent cut here would read as a complete tab order and be worse than the instruction it replaced. */ function unjudgedSections(facts: PageFacts): string[] { /* Measured: 76 focusables rendered ~8KB. 120 keeps a heavy page inside the turn and covers the corpus. */ const CAP = 120 const out: string[] = [] const focusables = facts.a11y?.focusables ?? [] if (focusables.length > 0) { const shown = focusables.slice(0, CAP) out.push( '', '#### Tab sequence — `a11y.focusables`, judged by no check', '', ...(focusables.length > shown.length ? ['**' + shown.length + ' of ' + focusables.length + ' shown.** The rest are in the artifact and not here.', ''] : []), '```json', JSON.stringify(shown, null, 2), '```', ) } const controls = facts.formControls ?? [] if (controls.length > 0) { out.push( '', '#### Form controls — `formControls`, judged by no check', '', '```json', JSON.stringify(controls.slice(0, CAP), null, 2), '```', ) } return out } /** * The crops, and why they are not here. * * **A gate can make a section silent, and silence reads as "there was nothing".** Item 25 collects * per-viewport tiles and they are deferred behind item 28, so this payload cannot carry them yet — and a * payload that simply omitted any mention would be telling a reviewer this run has no screenshots. So the * bound is stated and the call that reaches them is named, which is the same rule `notCollected` follows. */ function cropsSection(runId: string, route: string, screenshots: number, inlined?: boolean): string[] { if (screenshots === 0) { return [ '### Screenshots', '', 'This run stored none for ' + code(route) + '. Nothing visual is available to you here.', ] } /* * **The transport decides what this section may claim.** `reviewOneshot` attaches every `cropRef` as * a base64 image block by default, so for that caller the paragraph below was false twice over: it * said the crops were not inlined while they were arriving in the same message, and it told a reader * with no tools to fetch them with two it does not have. Measured 2026-08-19: an arm deferred a * contrast judgement to "a person must look at the crops" while obeying this text. */ if (inlined) { /* * No count here, deliberately. This section is built before `gatherCrops` runs, and that step caps * at 40 and drops any crop it cannot read — so a number taken from the stored total can overstate * what actually arrives, which is the same class of wrong information this branch exists to remove. * Each image is labelled with its finding id, so the reader can see exactly what it has. */ return [ '### Screenshots', '', 'The crops for ' + code(route) + ' are **attached to this message**, each labelled with the id of the finding it is evidence', 'for. Look at them: a crop settles what a selector cannot, and several checks report a', 'measurement they could not take because the answer is only visible.', '', 'Crops, not full pages: a full-page capture downscales to roughly 282x1568 on the way into a', 'vision model and arrives unreadable, so what you have is the element and its surroundings.', ] } return [ '### Screenshots', '', 'This run stored ' + screenshots + ' ' + plural(screenshots, 'crop', 'crops') + ' for ' + code(route) + '. They are **not inlined in this payload**: the per-viewport tiles that would make a chosen crop', 'worth the bytes are not built yet, so listing them here would be a guess at which ones matter. Ask for', 'them by name when a finding needs a look:', '', '- ' + code('qa_screenshots { runId: "' + runId + '", page: "' + route + '" }') + ' — what exists.', '- ' + code('qa_screenshot { runId: "' + runId + '", path: "" }') + ' — the bytes.', '', 'Crops, not full pages: a full-page capture downscales to roughly 282x1568 on the way into a vision', 'model and arrives unreadable.', ] } export interface ReviewPayloadInput { runId?: string /** * The route this brief is for. A slug works too — `findPage` resolves either. * * Required for every scope but `site`, which has no route by definition: it is the brief for what no * single route owns. */ route?: string /** * Which reader this brief is for. Defaults to `route`. * * **Never a flag on any command.** `--solo` was three unrelated changes behind one word — * presentation (drop the contract), semantics (change the ownership computation) and content (add the * routeless findings) — which is exactly why it was the flag that lost 24 findings. `qa brief` picks * this from what you asked for: `--route` is `route`, `--site` is `site`, and a one-shot is `whole` * because it is the only reader that run will get. */ scope?: BriefScope /** Drop the shard contract, for a caller that has already briefed its reviewer. */ noContract?: boolean /** * The caller will attach the crops as images, so the Screenshots section may say so. * * Set by `qa review --oneshot`, which inlines every `cropRef` unless `--no-crops`. Without it the * section tells the reader the crops are elsewhere and names two tools to fetch them with, which is * wrong information for a reader holding the images and impossible advice for one with no tools. */ cropsInlined?: boolean } /** One crop, and the finding it is evidence for. Resolved here so a caller never re-derives the join. */ export interface CropRef { findingId: string checkId: string route: string | undefined path: string } export interface ReviewPayload { runId: string /** The route this brief covers. `site` for the site-level slice, which covers no single one. */ route: string scope: BriefScope /** * The ids this brief's reader is responsible for. * * The **containment guard** reads this: every one of them must appear in `markdown`, which is what * stops a brief claiming findings it does not carry. The **partition guard** reads it across the * plan's briefs: every finding in the run in exactly one, none in zero and none in two. */ ownedIds: string[] markdown: string /** What the document is made of, in order, so a caller can see a section was dropped rather than empty. */ sections: string[] bytes: number /** Bytes / 4. A rough count, stated as rough — a tokeniser is not worth a dependency here. */ tokensApprox: number /** * The crops for this route's findings, by path — **not** their bytes. * * The markdown deliberately tells a *tool-using* reader to fetch crops by name. A one-shot has no * turn 2 in which to ask, so the transport needs the finding→crop join to inline them, and this is * the only place that already holds both halves. Paths only: a brief that carried base64 could not * be printed, diffed or cached, and most callers never look at an image. */ cropRefs: CropRef[] } /** * Assemble one route's brief. * * **Nothing here touches the network and nothing re-crawls** — every section is a projection over the * stored artifact, which is the same property that lets `qa recheck` replay a new check over stored * facts. A payload that fetched anything would be a payload that could disagree with the run it claims * to describe. */ export async function reviewPayload(ctx: ToolContext, input: ReviewPayloadInput): Promise { const scope: BriefScope = input.scope ?? 'route' const runId = input.runId ? await ctx.store.resolveRunId(input.runId) : await ctx.store.resolveRunId('latest') const manifest = await ctx.store.readManifest(runId) if (scope === 'site') return siteReviewPayload(ctx, runId, manifest) if (!input.route) throw new Error('a ' + scope + ' brief needs a route — the site brief is the one that has none') const page = await ctx.store.findPage(runId, input.route) const { findings: all, partial } = await ctx.store.readAllFindings(runId) const issueStore = await loadIssues(ctx.store.issuesPath(runId), ctx.store.storage) const routes = manifest.pages.map((p) => p.route) const coverage = sliceCoverage(all, issueStore.issues, { route: page.route }) const own = briefOwnership(all, routes, scope, page.route) const sections: string[] = [] const lines: string[] = [] const add = (name: string, body: string[]): void => { sections.push(name) lines.push(...body, '') } lines.push('# Review brief — ' + page.route) lines.push('') lines.push( 'One route of a qa run, for one reviewer. Everything below is this run\'s **stored measurements** —' + ' nothing here re-crawls, and no check in it proposes a fix. Checks report facts; naming a cause and' + ' saying what to change is your job, recorded as an **issue**.', ) lines.push('') /** * A brief built mid-crawl, and the one section of it that is not merely incomplete but *provisional*. * * The cross-page collapse runs when the crawl finishes: a finding that repeats across routes becomes * one site-level finding under a **new id**. Before that happens every instance still carries its own * route, so the ownership join below sees no shared causes and would tell a shard that all of them are * its own — the exact opposite of the answer, and the one that produces duplicates. `findings.md` * already warns that ids are provisional; nothing warned that the *verdict* is. */ if (partial) { sections.push('provisional') lines.push( '> **This run has not finished, so the verdict below is provisional.** The cross-page collapse' + ' happens when the crawl ends: findings that repeat across routes become one site-level finding' + ' under a *new* id. Until then every instance still carries its own route, so **the ownership' + ' section cannot yet see a shared cause** and will read everything on this route as yours. Issues' + ' you write still resolve — citations are matched on every identity a finding answers to — but' + ' re-read this brief once the run completes before concluding that nothing here is shared.', ) lines.push('') } add('run', runConstants(manifest, ctx.store.storeRoot, page)) add('stopTest', stopTest(coverage, page.route, !partial)) add( scope === 'whole' ? 'ownershipSolo' : 'ownership', scope === 'whole' ? soloOwnership(own, page.route) : ownershipVerdict(own, issueStore.issues, page.route, routes), ) /* * `whole` is set only by `--mode oneshot`, and a one-shot has one turn and no tools — so naming five * of them is five instructions it cannot follow. See `noToolsSection`. */ add('tools', scope === 'whole' ? noToolsSection() : toolsSection(runId, page.route)) /** * The route's own document, verbatim. * * Reviewer consensus called it "the best thing in this toolkit" and it is what they read first, so it * is pasted rather than summarised: it is already ranked, grouped and deduped with evidence and HTML * excerpts inline, and any second rendering of it here would be a second answer to one question. */ let findingsMd = '' try { findingsMd = await ctx.store.readPageFindingsMd(runId, page.slug) } catch { findingsMd = '' } if (findingsMd.trim()) { sections.push('findings') lines.push('---') lines.push('') lines.push('## Your route\'s findings, as the report renders them') lines.push('') lines.push(findingsMd.trim()) lines.push('') } else { /* Said, not skipped: an absent findings document and a clean page are not the same artifact. */ sections.push('findingsMissing') lines.push( '## Your route\'s findings — NOT AVAILABLE. ' + 'This run has no findings document for ' + code(page.route) + ', which means the page has not finished collecting or the write failed. It does **not** mean the' + ' page is clean. Call ' + code('qa_findings { runId, route }') + ' and say in your report that the document was missing.', ) lines.push('') } lines.push('---') lines.push('') /* * Only in solo. In a fan-out these belong to the site-level slice, and handing the same routeless * findings to every shard is how one fix becomes N competing issues — the duplication the split * exists to prevent. */ if (scope === 'whole') add('routeless', routelessSection(own.routeless)) let facts: PageFacts | undefined try { facts = await ctx.store.readPageFacts(runId, page.slug) } catch { facts = undefined } if (facts) add('facts', factsDigest(facts, scope === 'whole')) else { add('factsMissing', [ '### What this page measures, that no check judged — NOT AVAILABLE', '', 'This run holds no readable facts for ' + code(page.route) + '. The sweep, the byte totals and the not-judged list are all unavailable, so pass 2 on this route' + ' cannot be completed from the artifact. Say so rather than reporting the page as measured.', ]) } /* * Scope decides the slice, the same way it decides `routeless`: a route reviewer gets this route's * fetches, and the reviewer with no peers gets all of them because nobody else will read them. */ const fetchedStore = await loadFetched(ctx.store.runDir(runId), ctx.store.storage).catch(() => ({ fetched: [] as FetchedResource[], dir: '', })) add('fetched', fetchedSection(scope === 'whole' ? fetchedStore.fetched : fetchedForRoute(fetchedStore.fetched, page.route))) const screenshots = await ctx.store.listScreenshots(runId, page.slug).catch(() => [] as string[]) add('crops', cropsSection(runId, page.route, screenshots.length, input.cropsInlined)) /* * The finding→crop join, from the findings this route already carries. `listScreenshots` above knows * which files exist but not what any of them is evidence *for*, and an unlabelled image is evidence * for nothing in particular. */ const cropRefs: CropRef[] = [] for (const f of all) { if (!sameRoute(f.route, page.route)) continue for (const path of f.evidence.screenshots) { cropRefs.push({ findingId: f.id, checkId: f.checkId, route: f.route, path }) } } if (!input.noContract && scope === 'route') add('contract', SHARD_CONTRACT) if (scope === 'route') add('authoring', AUTHORING_LINES) const markdown = lines.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n' return { runId, route: page.route, scope, ownedIds: own.owned.map((f) => f.id), markdown, sections, bytes: Buffer.byteLength(markdown, 'utf8'), tokensApprox: Math.round(Buffer.byteLength(markdown, 'utf8') / 4), cropRefs, } } /** * The site-level slice's brief — routeless findings and every shared cause, computed by the same join * `--route` already runs. * * **The only reviewer whose entire job is that join was the only one briefed by hand**, and it cost 10 * defects on one arm of the experiment and 5 on another. Nothing here is new capability: the ownership * verdict in every route brief had already computed exactly this set in order to tell each shard what * was *not* theirs. It simply had nowhere to send it. * * No `findings.md` to paste and no crops: a shared cause spans routes, so there is no one page document * that holds them, and the evidence for "this fired on three routes" is the list of routes rather than * an image. `siteFindingsSection` renders `owned` directly, which is what makes containment hold. */ async function siteReviewPayload(ctx: ToolContext, runId: string, manifest: RunManifest): Promise { const { findings: all, partial } = await ctx.store.readAllFindings(runId) const issueStore = await loadIssues(ctx.store.issuesPath(runId), ctx.store.storage) const routes = manifest.pages.map((p) => p.route) const own = briefOwnership(all, routes, 'site', undefined) const sections: string[] = [] const lines: string[] = [] const add = (name: string, body: string[]): void => { sections.push(name) lines.push(...body, '') } lines.push('# Review brief — the site-level slice') lines.push('') lines.push( 'The findings **no single route owns**: measured once for the origin, or firing on several routes' + ' from one fix location. Everything below is this run\'s **stored measurements** — nothing here' + ' re-crawls, and no check in it proposes a fix. Naming a cause and saying what to change is your' + ' job, recorded as an **issue**.', ) lines.push('') if (partial) { sections.push('provisional') lines.push( '> **This run has not finished, so this brief is provisional — and it is the brief that suffers' + ' most.** The cross-page collapse happens when the crawl ends: findings that repeat across routes' + ' become one site-level finding under a *new* id. Until then every instance still carries its own' + ' route, so **the shared causes below are undercounted** and some of what you will eventually own' + ' still reads as a route\'s. Re-read this once the run completes.', ) lines.push('') } add('run', siteRunConstants(manifest, ctx.store.storeRoot, routes)) add('stopTest', siteStopTest(own, issueStore.issues, routes.length)) add('ownership', siteOwnership(own, routes)) add('tools', toolsSection(runId, undefined, routes[0])) lines.push('---') lines.push('') sections.push('findings') lines.push(...siteFindingsSection(own), '') add('contract', SITE_CONTRACT) add('authoring', AUTHORING_LINES) const markdown = lines.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n' return { runId, route: 'site', scope: 'site', ownedIds: own.owned.map((f) => f.id), markdown, sections, bytes: Buffer.byteLength(markdown, 'utf8'), tokensApprox: Math.round(Buffer.byteLength(markdown, 'utf8') / 4), cropRefs: [], } } /** * The exact set of briefs a run needs — **uniform, and computed rather than remembered.** * * ## Why this is a command and not a paragraph in a document * * The roster used to be hand-written. `fan-out.md` says the site-level slice owns *"every shared * cause"*, an orchestrator planning a fan-out read that, briefed three reviewers from memory, and the * slice's brief named some of the shared causes rather than all of them. **One arm lost 10 defects that * way and another lost 5** — on a run where every route brief had correctly told its shard those * defects were not theirs. Nobody misread anything; the roster was simply a thing a person typed. * * ## N route briefs + 1 site brief, always * * **No special case at one route.** A single-page run still gets a site brief, because robots.txt, the * security headers and the crawler policy are still measured once for the origin and still belong to * nobody in particular — and a rule with an exception at N=1 is a rule somebody has to remember. * * **Route count is a property of the run, never a mode.** The crawl already decided it. What a caller * chooses is how many readers these briefs get — one agent per brief, or one agent reading all of them — * and that lives in `references/modes.md`, not on a command line. */ export interface BriefPlanEntry { scope: BriefScope /** The route, or `site` for the slice that owns what no route does. */ route: string /** The command that prints this brief. */ command: string /** How many findings this brief's reader is responsible for. */ owns: number ownsDefects: number } export interface BriefPlan { runId: string entries: BriefPlanEntry[] /** Every finding in the run, for the partition guard's denominator. */ findingCount: number } export async function briefPlan(ctx: ToolContext, input: { runId?: string }): Promise { const runId = await ctx.store.resolveRunId(input.runId ?? 'latest') const manifest = await ctx.store.readManifest(runId) const { findings: all } = await ctx.store.readAllFindings(runId) const routes = manifest.pages.map((p) => p.route) const entries: BriefPlanEntry[] = routes.map((route) => { const own = briefOwnership(all, routes, 'route', route) return { scope: 'route' as const, route, command: 'qa brief ' + runId + ' --route ' + route, owns: own.owned.length, ownsDefects: own.owned.filter((f) => isDefect(f)).length, } }) const site = briefOwnership(all, routes, 'site', undefined) entries.push({ scope: 'site', route: 'site', command: 'qa brief ' + runId + ' --site', owns: site.owned.length, ownsDefects: site.owned.filter((f) => isDefect(f)).length, }) return { runId, entries, findingCount: all.length } } /** * The **partition guard**: the plan's briefs cover every finding exactly once. * * None in zero — the failure that lost 10 defects, where five shared causes were owned by a brief * nobody was given. None in two — the failure the shared-cause rule exists to prevent, where one fix * becomes N competing issues from N shards. * * Exported because it is worth running against a real run and not only a fixture: it is arithmetic over * stored findings, so `qa brief --check` can assert it on any run in the store for the cost of a read. */ export interface BriefPartition { ok: boolean /** Findings no brief in the plan owns. Each one is work nobody will be asked to do. */ orphaned: string[] /** Findings more than one brief owns, with the briefs that claim them. */ contested: Array<{ id: string; briefs: string[] }> } export async function briefPartition(ctx: ToolContext, input: { runId?: string }): Promise { const runId = await ctx.store.resolveRunId(input.runId ?? 'latest') const manifest = await ctx.store.readManifest(runId) const { findings: all } = await ctx.store.readAllFindings(runId) const routes = manifest.pages.map((p) => p.route) const owners = new Map() const claim = (label: string, own: Ownership): void => { for (const f of own.owned) owners.set(f.id, [...(owners.get(f.id) ?? []), label]) } for (const route of routes) claim(route, briefOwnership(all, routes, 'route', route)) claim('site', briefOwnership(all, routes, 'site', undefined)) const orphaned = all.filter((f) => !owners.has(f.id)).map((f) => f.id) const contested = [...owners.entries()] .filter(([, briefs]) => briefs.length > 1) .map(([id, briefs]) => ({ id, briefs })) return { ok: orphaned.length === 0 && contested.length === 0, orphaned, contested } }