import { RunStore, applyIssues, buildDashboardPayload, buildPrompt, checkIssueRules, deleteIssue, describeShape, detectToolchainDrift, fetchedId, fetchableSite, saveFetched, auditedRoutes, diffRuns, readingOf, loadIssues, loadTelemetry, listProjects, shapeBriefing, sweepPage, sweepBriefing, queryFindings, routesCovered, runNotCollected, sameCounts, sameRoute, issueId, issueFilePath, issuesDirFor, saveIssue, type FindingQuery, type RunSummary, // `@basementstudio/qa-engine/run`, not `@basementstudio/qa-engine`: the root barrel pulls in the browser, sharp and // lighthouse, which nothing here touches. See that barrel's header. } from '@basementstudio/qa-engine/run' /* * A subpath, not the root barrel: `@basementstudio/qa-engine` pulls the browser, sharp and lighthouse, * and this transport is a leaf that needs none of them. Same reason the imports above take `/run`. */ import { fetchResource } from '@basementstudio/qa-engine/fetch-resource' import { compareFindings, findingIdentities, Issue as IssueSchema, SCHEMA_VERSION, isDefect, SEVERITY_ORDER, tallyFindings, type FetchedResource, type Finding, type FindingKind, type Issue, type IssueCategory, type IssueOrigin, type IssueType, type PageFacts, type RunManifest, type Severity, } from '@basementstudio/qa-schema' /** * The query layer behind the MCP tools. * * Kept separate from the protocol wiring so it can be tested without standing up * a server, and so the shaping decisions — which are the interesting part — live * somewhere readable. * * The shaping matters more than it looks. These results land in a model's context * window, and a stored run holds megabytes: an 11-viewport probe sweep on a heavy * page is most of that on its own. A tool that returns a whole `facts.json` * spends the budget that was supposed to go on *fixing* things, which is the same * mistake as sending a full-page screenshot to a vision model. So findings come * back compact by default with the detail available on request, and facts are * summarised unless a specific section is named. */ export interface ToolContext { store: RunStore /** Default when a tool omits `runId`. */ defaultRunId?: string /** * The dashboard's store — the pushed snapshots — built on **first use**, not at startup. * * This is what makes *"grab the xmcp website issues from the dashboard"* a thing an agent can do * with the plugin as it ships. `plugin/.mcp.json` passes no arguments and never will, so a store * that had to be selected with a flag was a store a plugin user could not reach; every read tool * takes `dashboard: true` instead, and this is where it resolves. * * **Lazy is the whole design, not an optimisation.** Resolving a connection string can end at * `vercel env pull`, which costs ~2.3s and shells out — paying that on every session start, for * every user, to serve a store most calls do not want would be indefensible. A host that cannot * reach one at all leaves this undefined, and asking for the dashboard then fails with a message * about Vercel rather than the server refusing to start. Memoise it: several tools per turn is the * normal shape, and re-resolving per call would multiply the round trips by the ladder's cost. */ dashboard?: () => Promise /** * The connection string this server was built against, when the host knows it. * * **Only `qa_set_finished` uses it, and it exists because that tool was writing somewhere else.** * Every read tool serves whatever store the host handed over — `qa mcp --db ` serves the * preview mirror, the deployed `/mcp` route serves its own `DATABASE_URL`. `setFinished` re-resolved * a URL through the global environment ladder instead, so it could mark a run final in *production* * while the agent was reading the preview, or fail with "the usual fix is `vercel login`" from inside * a serverless function that was already holding a working connection. * * Absent for a host that has no database at all (the plain stdio server over a local `.qa`), in which * case the ladder is still the right fallback — that is the laptop case it was written for. */ databaseUrl?: string } /** Every read tool takes this, so "which store" is part of the question rather than a server mode. */ export interface StoreChoice { dashboard?: boolean } /** * The store a call should read, and the one place `dashboard: true` is honoured. * * Returns a **context**, not a store, so a tool opts in with one line at the top and every * `ctx.store` below it is already correct. Threading a store parameter through all thirty-one uses * instead would have been thirty-one chances to miss one, and a missed one reads as "this store is * empty" rather than throwing — the failure mode this file has now been bitten by twice. * * Writes deliberately do **not** take a `StoreChoice`. `qa_issue_write`, `qa_issue_delete`, * `qa_waive` always addresses the local artifact, because Postgres is a read * model that the next `qa push` overwrites. So reads may come from the dashboard while writes cannot * go there — enforced by those tools simply not having the parameter, which is stronger than a check. */ async function onStore(ctx: ToolContext, choice?: StoreChoice): Promise { if (!choice?.dashboard) return ctx if (!ctx.dashboard) { throw new Error( 'this server cannot reach the dashboard: no database was configured and no connection string ' + 'could be resolved. `qa push` and this share one resolver — the usual fix is `vercel login`, ' + 'or start the server with `--db `. The local store is still readable without `dashboard`.', ) } return { ...ctx, store: await ctx.dashboard() } } /** Compact finding shape: everything needed to triage, nothing needed twice. */ export interface FindingDigest { id: string checkId: string category: string /** * Only present for notes. A defect omits it, so its absence reads as "this is * something to fix" without the caller checking a string. */ kind?: string severity: Severity confidence: string title: string detail?: string /** * Present only when severity was overridden — what the check itself proposed, and * who moved it. Absent on an untouched finding, so it reads as signal not noise. */ reclassified?: { from: Severity; by: string } suggestion?: string route?: string selector?: string resourceUrl?: string observedAt?: string[] brokenBelow?: number values?: Record /** Which `values` fields were cut and how much of each — never a silent truncation. */ valuesTruncated?: string[] waived?: { reason: string; by: string; expiresAt?: string; active: boolean } screenshots?: string[] /** * Where in the repo this lives. * * Cheap and the most actionable field there is — `Header.tsx:42` is what replaced the * selector chain that was called "completely useless". It was missing from the digest * entirely, so the review loop could not even see a file without fetching every finding * in full. * * `snippet` is **included by default**, and that default was set by measurement rather than * by the guess that preceded it. The guess was "up to 2KB per finding, so make it opt-in"; * measured, a seven-line dedented excerpt is **192B mean / 433B p99** across 1421 windows in * a real Next+Tailwind repo, and **496B** on the fixture (whose HTML-in-a-template-literal * lines run longer than typical JSX). Only 34 of 23,777 lines in that repo exceed the 300-char * per-line cap. * * At that price, gating the single highest-leverage review input behind a flag an agent may * not think to set defeats the point of carrying it at all — the same enforcement problem * this layer keeps meeting: a CLI cannot require an agent to ask for the right thing, so the * right thing has to be the default. `includeSnippets: false` is there for a deliberately * wide sweep where even 200B × 200 findings is unwanted. */ source?: { file: string line?: number component?: string confidence: string /** * What the search matched, e.g. `class: promo-marquee-track` or `text: schedule a demo`. * * On the digest because it is the field that says how much to trust the ref, and the digest * is the path a review actually reads — carrying it only in the full object put the most * useful signal on the expensive path. A **structural** match (id, semantic class) names a * thing; **prose** found a string, and strings get reused across components. */ matchedOn?: string /** Best-guess-of-N, when the search was ambiguous. */ candidates?: number snippet?: { startLine: number; matchLine: number; text: string } } } /** * A `values` field holding a list, cut to something a reader can read. * * **A check may write an unbounded list into one evidence field, and one of them does.** Measured on * a real run: `weight.cache-lifetime-outlier` carried **55 full URLs — 9,220B — in `values.outliers`** * beside a `detail` that repeated 40 of them; `SKILL.md` records a worse one, a single finding whose * `values` was **199,651B of a 233,642B response** while the other 34 findings averaged 830B. The * digest is the path a review actually reads, so it is where the cut belongs — the stored finding is * untouched and `full: true` still returns every entry. * * Cut at whichever comes first, and **say which field was cut and how far**: a truncated list reads * as the whole list, which is how a blocker gets missed. */ const VALUE_ITEM_CAP = 12 const VALUE_CHAR_CAP = 600 function capValues(values: Record): { values: Record truncated: string[] } { const out: Record = {} const truncated: string[] = [] for (const [key, value] of Object.entries(values)) { if (typeof value !== 'string' || value.length <= VALUE_CHAR_CAP) { out[key] = value continue } /* * Newline first, then comma-space: checks use both and splitting on the wrong one yields a * single "item" that is the whole string, which caps nothing. */ const separator = value.includes('\n') ? '\n' : ', ' const items = value.split(separator) const kept: string[] = [] let chars = 0 for (const item of items) { if (kept.length >= VALUE_ITEM_CAP || chars + item.length > VALUE_CHAR_CAP) break kept.push(item) chars += item.length + separator.length } // A long single value with no separator: keep a readable head rather than nothing. if (kept.length === 0) kept.push(value.slice(0, VALUE_CHAR_CAP)) out[key] = kept.join(separator) truncated.push( items.length > 1 ? `${key}: ${kept.length} of ${items.length} entries (${value.length}B). Pass \`full: true\` for all of them.` : `${key}: first ${kept[0]?.length ?? 0}B of ${value.length}B. Pass \`full: true\` for the rest.`, ) } return { values: out, truncated } } export function digestFinding( finding: Finding, now = new Date(), opts: { includeSnippets?: boolean } = {}, ): FindingDigest { const digest: FindingDigest = { id: finding.id, checkId: finding.checkId, category: finding.category, severity: finding.severity, confidence: finding.confidence, title: finding.title, } /* * **Always stated, including for a defect.** This was set only for non-defects, on the reasoning that * absent means defect and the bytes are worth saving. A reviewer's first pass over the route list * therefore rendered seventeen lines reading `major undefined a11y.axe.list`, and nothing in * `SKILL.md` says the field is omitted — the contract talks about `kind` as though it is always there * (*"Every new check must set `kind`"*), so the reader has to infer the convention from a gap. * * ~16 bytes a finding against a whole class of misreading, in the same codebase whose recurring bug * is an absent field and an empty one being indistinguishable. */ digest.kind = finding.kind ?? 'defect' if (finding.detail) digest.detail = finding.detail if (finding.severity !== finding.defaultSeverity) { digest.reclassified = { from: finding.defaultSeverity, by: finding.severitySource } } // Only ever set by the orchestrator, so its presence marks the boundary between // fact and interpretation. if (finding.suggestion) digest.suggestion = finding.suggestion if (finding.route) digest.route = finding.route if (finding.evidence.selector) digest.selector = finding.evidence.selector if (finding.evidence.resourceUrl) digest.resourceUrl = finding.evidence.resourceUrl if (finding.observedAt.length > 0) digest.observedAt = finding.observedAt if (finding.breakRange?.brokenBelow) digest.brokenBelow = finding.breakRange.brokenBelow if (finding.evidence.values) { const { values, truncated } = capValues(finding.evidence.values) digest.values = values if (truncated.length > 0) digest.valuesTruncated = truncated } if (finding.evidence.screenshots.length > 0) digest.screenshots = finding.evidence.screenshots if (finding.source) { const candidates = finding.source.candidates ?? Number(finding.evidence.values?.sourceCandidates) const matchedOn = finding.source.matchedOn ?? finding.evidence.values?.sourceMatchedOn digest.source = { file: finding.source.file, ...(finding.source.line !== undefined ? { line: finding.source.line } : {}), ...(finding.source.component ? { component: finding.source.component } : {}), confidence: finding.source.confidence, ...(matchedOn ? { matchedOn: String(matchedOn) } : {}), ...(Number.isFinite(candidates) ? { candidates } : {}), ...(opts.includeSnippets && finding.source.snippet ? { snippet: finding.source.snippet } : {}), } } if (finding.waiver) { // `active` is computed here so the caller never has to parse a date to learn // whether an acceptance still stands. const expiry = finding.waiver.expiresAt ? Date.parse(finding.waiver.expiresAt) : undefined digest.waived = { reason: finding.waiver.reason, by: finding.waiver.by, ...(finding.waiver.expiresAt ? { expiresAt: finding.waiver.expiresAt } : {}), active: expiry === undefined ? true : !Number.isNaN(expiry) && expiry > now.getTime(), } } return digest } export async function listRuns( ctx: ToolContext, input: { limit?: number } & StoreChoice = {}, ): Promise<{ runs: RunSummary[]; storeRoot: string; toolchainNote?: string }> { ctx = await onStore(ctx, input) return { runs: await ctx.store.listRuns({ limit: input.limit ?? 20 }), storeRoot: ctx.store.storeRoot, // The orientation call, so it is where a session learns it is reading with an older server than // wrote these runs. See `run/toolchain.ts`. ...(toolchainNote() ? { toolchainNote: toolchainNote() } : {}), } } /** * One line, not the CLI's paragraph: this lands in a tool response an agent pays for by the token, * and the actionable part is which tools to call instead. */ function toolchainNote(): string | undefined { const drift = detectToolchainDrift() if (!drift) return undefined const behind = drift.unreleased.length > 0 ? `${drift.changesets} unreleased changeset(s) name ${drift.unreleased.join(', ')}` : `the plugin's pin and that checkout's packages/mcp disagree (${drift.pinnedMcp} vs ${drift.workspaceMcp})` /* * Which copy is answering decides the sentence. Told the wrong way round, this would assert that * the version answering is one it is not. */ return drift.runningFromWorkspace ? `These answers come from the checkout at ${drift.workspaceRoot}, not from the plugin's ` + `@basementstudio/qa-mcp@${drift.pinnedMcp} — ${behind}, so the registered ` + `mcp__plugin_basement-qa_qa__* tools are the older surface and may refuse an argument these accept.` : `This server is @basementstudio/qa-mcp@${drift.pinnedMcp} from npm, reading runs written by the ` + `checkout at ${drift.workspaceRoot} — ${behind}, so an argument added since the last publish is ` + `refused here by name. Reach the checkout's own tools with ` + `\`bun run packages/cli/src/index.ts mcp \`.` } /** * Runs grouped into the sites they were taken against — the same two screens the dashboard opens on. * * ## Why a flat run list was not enough * * `qa_runs` answers "what is in this store" with timestamped ids, which is fine when the store is the * `.qa` beside the project you are working in and the answer is almost always `latest`. It stops being * an answer against the **mirror**: that store holds every site anybody pushed, and "fetch the issues * for native.security" has no path through a list of ids unless you already know which id is which. * `listProjects` is what the dashboard's own first screen is built from, so this tool makes an agent * and a human name a snapshot the same way — by project, then by date. * * ## It returns ids, and deliberately adds no `project` parameter anywhere else * * The composition is `qa_projects` → pick a `runId` → every existing tool, unchanged. The alternative * — teaching `qa_issues`, `qa_findings` and the rest to accept a project and resolve its latest — was * considered and rejected: this repo has twice had an `Issue` field silently dropped by adding it * that had to be threaded through every hop, and a second way to address a run is that same shape of * change across ten tool registrations. One addressing scheme, one place it is resolved. * * ## The limit bounds runs read, not projects returned, and that is reported * * `listProjects` groups whatever `listRuns` handed it, so a limit below the store's run count drops * *snapshots* and can drop a whole project whose runs are all older than the cut. A truncated listing * reads as "that is everything", which is the silent cap this project forbids — so `runsRead` and * `capped` come back with it rather than being left for the caller to infer. */ export async function projects(ctx: ToolContext, input: { limit?: number } & StoreChoice = {}) { ctx = await onStore(ctx, input) const limit = input.limit ?? 20 const listed = await listProjects(ctx.store, { limit }) const runsRead = listed.reduce((n, p) => n + p.snapshots.length, 0) return { storeRoot: ctx.store.storeRoot, projects: listed.map((project) => ({ slug: project.slug, name: project.name, origins: project.origins, /** * False when `latest` is a fallback: nothing in this project has been finished. * * Carried because this projection is hand-built, and a field added to `ProjectSummary` and not * added here is dropped with every test still green — the hop-dropping this file has done to * an `Issue` field twice. Without it the MCP surface was the one consumer of `listProjects` that * could not tell a finished audit from a crawl still in flight. */ latestFinished: project.latestFinished, /** * Every snapshot, newest first — not just the latest. * * The whole point of asking by project is to reach a run that is *not* the newest: the newest * push is frequently the unreviewed one, because `qa run --push` mirrors measurements and the * review happens afterwards. `issues` and `draft` on each row are what let a caller pick the * snapshot that has something to say without a round trip per candidate. */ snapshots: project.snapshots.map((s) => ({ runId: s.runId, status: s.status, startedAt: s.startedAt, targetUrl: s.targetUrl, env: s.env, pages: s.pages, defectTotal: s.defectTotal, notes: s.notes, issues: s.issues, draft: s.draft, /* * Absent when nobody can say — a backend without the column, or a run written before it. Only * an explicit `false` means *still being reviewed*, so absence must not read as either answer. */ ...(project.finished[s.runId] !== undefined ? { finished: project.finished[s.runId] } : {}), ...(s.partial ? { partial: s.partial } : {}), ...(s.notMeasured.length > 0 ? { notMeasured: s.notMeasured } : {}), })), })), runsRead, limit, /* * True when the read hit the ceiling, which is the only case where something may be missing. Said * as a sentence too, because a boolean named `capped` is easy to skim past in a JSON blob. */ capped: runsRead >= limit, ...(runsRead >= limit ? { note: `read the ${limit} most recent runs and stopped — older snapshots, and any project whose runs are all older, are not in this list. Raise \`limit\` to see them.`, } : {}), } } async function resolve(ctx: ToolContext, runId?: string): Promise { return ctx.store.resolveRunId(runId ?? ctx.defaultRunId ?? 'latest') } /** * Run overview: identity, page index, counts. * * The first call an agent should make. Deliberately excludes findings — the point * is to orient and then ask for the slice that matters, not to pull everything. */ /** * The review's cost as `qa_run` reports it, or nothing at all. * * Read through `ctx.store.storage` **explicitly**, not through the default — this file omitted the * backend at six call sites once and the mirror answered *31 issues* and *0 issues* to two tools in * the same command. The seam's trailing-optional default is invisible until the backend is not the * filesystem, which is exactly the case a dashboard read is. * * A stamp with no harvest yet reports the stamp and says so, rather than reporting nothing: *"a review * started here and nobody has read its cost"* is a different and more useful answer than silence, and * it is the state every run is in between `qa brief` and `qa push`. */ async function reviewOf(ctx: ToolContext, runId: string) { const telemetry = await loadTelemetry(ctx.store.runDir(runId), ctx.store.storage).catch(() => undefined) if (!telemetry) return {} const r = telemetry.rollup if (!r) { return { review: { stampedAt: telemetry.stamp.startedAt, substrate: telemetry.stamp.substrate, mode: telemetry.stamp.mode, note: 'a review was stamped and its cost has not been harvested yet — `qa push` does that, or `qa telemetry harvest`', }, } } return { review: { mode: r.mode, substrate: r.substrate, models: r.models, efforts: r.efforts, actors: r.actors, turns: r.turns, toolCalls: r.toolCalls, tokens: r.tokens, durationMs: r.durationMs, costUsdAtSnapshot: r.costUsdAtSnapshot, rateTableVersion: r.rateTableVersion, passes: telemetry.passes.map((p) => ({ label: p.label, role: p.role, model: p.model, effort: p.effort, turns: p.turns, toolCalls: p.toolCalls, costUsdAtSnapshot: p.costUsdAtSnapshot, })), ...(telemetry.notes.length > 0 ? { notes: telemetry.notes } : {}), costNote: r.substrate === 'claude-code' ? 'Subscription credit, priced at API rates — not a bill, and NOT what the API would charge for the same review. This ran against a weekly allowance, where a full fan-out measured ~1% of one week. On this substrate the figure runs 8-14x an API call for the same work, because a subagent carries the system prompt, CLAUDE.md and the tool definitions every turn: one measured review was $22.60 here and $1.66 through the API. For that second number run `qa review --oneshot --dry-run`, which sends nothing and prices the passes the local review actually made.' : 'Anthropic API spend. Real money.', }, } } export async function describeRun(ctx: ToolContext, input: { runId?: string } & StoreChoice = {}) { ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) const manifest = await ctx.store.readManifest(id) /** * Counts recomputed from the findings on disk, not read off the manifest. * * `manifest.findingCounts` is written when the run completes, and **replaying checks over stored * facts is a designed capability** — it is what "checks are pure functions from facts to findings" * is for, and two sessions have used it to prove a fix in seconds. Nothing in that path updates the * manifest, so a replayed run ends up holding two answers. * * Measured on a real one: `run.json` reported **49 blockers / 105 findings** while its own * `global/findings.json` held **9 / 65** after the origin-level broken-link fix was replayed into * it. The report computes from findings and was right; `qa_run` read the manifest and was wrong by * a factor of five on the number a reader acts on first. * * So the findings win — they are the artifact — and a disagreement is surfaced rather than * silently resolved, because it means something wrote findings into a finished run. **`qa recheck` * is not that**: a replay is written beside the runs, so it cannot produce this state. */ let findingCounts = manifest.findingCounts let staleManifestCounts: typeof manifest.findingCounts | undefined /** * The checks that measured nothing, from the findings — **not from `manifest.ungraded` alone**. * * That field is written by the run for one case only: a page beyond the `--lighthouse-pages` cap. * Every `ungraded()` a check emits is a *finding* with `kind: 'ungraded'`, and nothing copied it * here — so this tool returned `ungraded: []` on three native.security routes that between them * held **103, 130 and 141 undetermined contrast elements**, while its own description promised the * ungraded checks. A reader trusting it reports full contrast coverage. */ const ungraded: Array<{ checkId: string; reason: string; route?: string }> = manifest.ungraded.map((u) => ({ ...u })) try { const { findings: all } = await ctx.store.readAllFindings(id) for (const finding of all) { if (finding.kind !== 'ungraded') continue if (ungraded.some((u) => u.checkId === finding.checkId && u.route === finding.route)) continue ungraded.push({ checkId: finding.checkId, // `ungraded()` writes the check's own words for what it could not establish into `detail`, // ahead of anything else the check said. reason: finding.detail ?? finding.title, ...(finding.route ? { route: finding.route } : {}), }) } const recomputed = countBy(all) /** * **Compared by value. `JSON.stringify` compares key *order* too, and these two disagree on it.** * * `countBy` returns its keys sorted blocker-first so the object reads correctly when serialised; the * manifest stores whatever order the writer happened to produce. So a fresh single-page crawl whose * counts matched exactly still reported *"checks were replayed into this run after it completed"* — * a claim about the artifact's history that cannot be true of a run created seconds earlier, on a run * where `findingCounts` and `staleManifestCounts` printed identically side by side. A warning that * fires when it cannot be true teaches a reader to ignore it, which costs the real case. */ const differs = !sameCounts(recomputed, (manifest.findingCounts ?? {}) as Record) if (differs) { staleManifestCounts = manifest.findingCounts findingCounts = recomputed } } catch { // No findings readable yet — a live run. The manifest's own counts are the best available. } /** * Where a live run currently is — the answer to "is it stuck, or is it working?" * * `status: 'running'` on its own cannot answer that: it is written per page, and with * `--lighthouse` a page is ~130s of silence, so the manifest looks identical whether the * browser is tracing or dead. Every agent that has driven this tool built its own liveness * heuristic out of side-channels — log size, artifact bytes, file activity in Chrome's temp * profile — because this number did not exist. * * `stalled` is a **hint with its threshold stated**, not a verdict. 240s is four times the * slowest legitimate step measured (a 171s Lighthouse page on native.security's WebGL * homepage), so it is deliberately generous: killing a working run is worse than waiting on a * dead one, and the caller has `ageMs` and `step` to judge for itself. */ const progress = await ctx.store.readProgress(id) return { runId: manifest.runId, status: manifest.status, startedAt: manifest.startedAt, finishedAt: manifest.finishedAt, ...(progress ? { progress: { step: progress.step, route: progress.route, page: `${progress.pageIndex}/${progress.pageCount}`, pagesDone: progress.pagesDone, elapsedMs: progress.elapsedMs, progressAgeMs: progress.ageMs, stalled: progress.ageMs > 240_000, /* * A negative age is the writer's clock running ahead of this reader's, not a fresh record — * `readProgress` no longer clamps it away. Said out loud rather than rounded to "0s ago", * because an unusable age has to read as unusable: this is the one field a caller uses to * decide whether a run is still alive. */ note: progress.ageMs < -5_000 ? `cannot tell how fresh this is: the record is stamped ${Math.round(-progress.ageMs / 1000)}s in the future, so the crawling machine's clock is ahead of this one` : progress.ageMs > 240_000 ? `nothing has moved for ${Math.round(progress.ageMs / 1000)}s, which is past 4x the slowest step measured (171s) — likely stuck` : `on ${progress.step}, last moved ${Math.round(Math.max(0, progress.ageMs) / 1000)}s ago`, }, } : {}), target: manifest.target, source: manifest.source, // Kept because timings are only comparable within a matching fingerprint; a // consumer needs it to refuse a bad comparison rather than render one. runner: { fingerprint: manifest.runner.fingerprint, os: manifest.runner.os, cpuModel: manifest.runner.cpuModel, chromeVersion: manifest.runner.chromeVersion, engineVersion: manifest.runner.engineVersion, headless: manifest.runner.headless, }, /** * **Absent unless this server is older than the checkout it is reading**, which in a dev * checkout it usually is: the plugin launches a published `@basementstudio/qa-mcp` while the * runs in front of it are written by the local engine. `engineVersion` above cannot say so — it * is the artifact contract and does not move with a release. See `run/toolchain.ts`. */ ...(toolchainNote() ? { toolchainNote: toolchainNote() } : {}), /** * What produced the **review** and what it cost — absent when nobody recorded it. * * Everything else on this object describes the crawl. This is the other half of the run, and it is * absent rather than zeroed on the two cases that both mean *nobody can say*: a run nobody stamped, * and a stamp whose transcript is no longer on the machine reading it. A review reported as 0 turns * and $0.00 would be the confident-wrong answer, so there is no default. * * The meter travels with the money. `substrate: 'claude-code'` is a subscription allowance where a * full fan-out measured ~1% of one week; `'api'` is a bill. Same number, two orders of magnitude * apart in meaning. */ ...(await reviewOf(ctx, id)), findingCounts, /** * Present only when the manifest disagrees with the findings, so its absence reads as * "these numbers came from one source". A replayed run is the case that produces it. */ ...(staleManifestCounts ? { staleManifestCounts, staleManifestNote: 'The counts above were recomputed from the findings on disk because run.json disagreed with them — checks were replayed into this run after it completed and the manifest was not rewritten. The findings are the artifact.', } : {}), /** * **Why a page's counts here can exceed what a route filter returns, when neither is wrong.** * * Measured on one run's `/customers`: 2 notes here against 1 from a route filter. This counts the * page *document* — its own findings plus the site-level ones attributed to the route, which is * what its `findings.md` shows — and site-level findings carry no `route`, so a filter over the * run's findings sees only the page-scoped ones. Two reviewers reported the pair as a bug. */ pageCountsNote: "A page's counts are its document: its own findings plus the site-level ones attributed to this" + ' route. A route filter over the run counts only page-scoped findings, so it returns fewer and' + ' both numbers are right.', pages: manifest.pages.map((p) => ({ route: p.route, slug: p.slug, status: p.status, /** Things to fix, by severity. This is the number to act on. */ defectCounts: p.defectCounts, /** Decisions, measurement notes and ungraded checks — not defects. */ noteCount: p.noteCount, scores: p.scores, error: p.error, })), errors: manifest.errors, /** * A skipped check must never read as a passing one — which is why this is the union of the * manifest's entries and every `kind: 'ungraded'` finding, deduped on (checkId, route). Reading * the manifest alone returned `[]` on runs holding hundreds of undetermined contrast elements. */ ungraded, /** * The run's own coverage bounds, in words. `sweep.notCollected` answers this per page; this is * the run-level half, which existed nowhere — the reviewer who owns *"what does this run not * cover"* was reading an absent field. */ notCollected: runNotCollected(manifest), viewports: manifest.config.viewports.map((v) => v.id), /** * **What the run found to crawl, against what it crawled** — the run-level coverage question, * which no tool could answer. * * `manifest.discovery` is read by the discovery checks and by nothing an agent can reach, so every * reviewer wanting *"how much of this site did we actually see"* had to reconstruct it from the * `discovery.section-unaudited` notes. Three did exactly that, independently, and each arrived at a * different phrasing of the same number: *"2 of 73 URLs"*, *"1 of 17 sections"*, *"under 20% of the * site"*. That is arithmetic over two arrays and it belongs here. * * Counts and a bounded sample, never the whole lists: `sitemapUrls` runs to hundreds and this * object is read on every orientation call. `qa_facts` has no section for `run.json`, so the full * arrays stay reachable only off disk — which is the right trade for something this large, and is * stated rather than left to be discovered. */ /* Absent on a run written before discovery existed, which is a different fact from an empty site. */ ...(manifest.discovery ? { discovery: { sitemapUrls: manifest.discovery!.sitemapUrls.length, crawled: manifest.pages.length, /** Declared and never loaded. The gap a reviewer keeps re-deriving. */ declaredNotCrawled: Math.max(0, manifest.discovery!.sitemapUrls.length - manifest.pages.length), fromSitemap: manifest.discovery!.fromSitemap.length, fromLinkCrawl: manifest.discovery!.fromLinkCrawl.length, fromFramework: manifest.discovery!.fromFramework.length, orphans: manifest.discovery!.orphans.length, sitemapDeadEnds: manifest.discovery!.sitemapDeadEnds.length, /** Live and linked, absent from the sitemap — the other direction from a dead end. */ missingFromSitemap: manifest.discovery!.missingFromSitemap.length, ...(manifest.discovery.robotsTxtUrl ? { robotsTxtUrl: manifest.discovery.robotsTxtUrl } : {}), sample: { sitemapUrls: manifest.discovery!.sitemapUrls.slice(0, 10), orphans: manifest.discovery!.orphans.slice(0, 10), sitemapDeadEnds: manifest.discovery!.sitemapDeadEnds.slice(0, 10), missingFromSitemap: manifest.discovery!.missingFromSitemap.slice(0, 10), }, note: 'Counts, with the first 10 of each list. The full arrays are in run.json and are deliberately' + ' not returned — sitemapUrls alone runs to hundreds on a real site and this object is read on' + ' every orientation call. A section index and its children are counted separately, so' + ' declaredNotCrawled is a floor rather than a total.', }, } : {}), /** * Which URLs collapsed into one tested representative. * * `/blog/[slug]` is crawled once, not four hundred times, and the members are recorded so a * reader knows what the representative stands for. Nothing exposed that, so a reviewer looking at * a finding on `/blog/post-1` could not learn it also describes 27 other posts — which is the * difference between a nit and a site-wide defect. */ ...(manifest.templates.length > 0 ? { templates: manifest.templates.map((t) => ({ pattern: t.pattern, representative: t.representative, memberCount: t.members.length, pinned: t.pinned, sample: t.members.slice(0, 5), })), } : {}), } } export interface FindingsToolInput extends FindingQuery, StoreChoice { runId?: string /** Return the full `Finding` objects instead of digests. Costs far more context. */ full?: boolean /** * Include each mapped finding's code excerpt. **Defaults to true** — measured at 192B mean * on a real repo, which is not worth hiding. Set `false` for a deliberately wide sweep. */ includeSnippets?: boolean /** * The run-shape prose. **Defaults to on for an unfiltered call and off for a filtered one.** * * The numbers beside it are always returned — see the note where `shape` is assembled. Only the * narration is conditional, because it is ~1,100 tokens that restate those numbers in English and * it does not change between calls. Measured across one review: nine narrow calls carried 4,600B * of briefing around 600B of payload. */ briefing?: boolean /** * The run-shape block itself. **Defaults on**, because the numbers are what the briefing narrates * and a reader who has neither has no concentration figure at all. * * Set `false` on a call that already has it. Measured on a route-filtered call returning one * finding: 1,155B of a 3,734B response — **31%**, most of it `repeated`, and identical on every * call because it describes the run rather than the filter. 892B net of the note that replaces it. */ shape?: boolean } /** * Query findings across a run. * * Sorted blockers-first because that is the order anyone wants them in, and * `truncated` is explicit: a silently-capped list reads as "that's everything", * which is how a blocker gets missed. */ /** * Does this route-less finding say it covers the given route? * * The checks that collapse across routes do not agree on how to record them — `site-meta` writes a * comma-joined string, `hygiene` joins with spaces, and one of them uses `routes` rather than * `affectedRoutes` — so reading a single field with a single separator undercounts silently, which is the * failure this whole answer exists to remove. * * **`routesCovered` is that reader, and it is shared with the report.** This used to `JSON.stringify` the * whole `values` object and run a quoted-boundary regex over it, which made any evidence value that merely * *contained* the route string count as coverage — a URL, a selector, a link target — and disagreed with * the report's own "shared, N pages" pill about the same finding. Three parsers of one fact, now one. */ export function mentionsRoute(finding: Finding, route: string): boolean { return routesCovered(finding).some((r) => sameRoute(r, route)) } /** * Every key `qa_findings` accepts, so an unrecognised one can be refused by name. * * **A dropped key answers a different question and looks like an answer.** Measured: a reviewer called * `qa_findings { checkIds: [...] }` — plural, which does not exist — and got all 93 findings back; then * `{ checks: [...] }` and got 93 again. Two wasted calls, noticed only because the response was * suspiciously large. `CLAUDE.md` records the same class twice already: `qa_facts` errors on a section * name it does not know, and `findPage` refuses a missing `page` by name. This tool never got the * treatment, and it is the most-called one in the review. */ const FINDINGS_KEYS = new Set([ 'runId', 'full', 'includeSnippets', 'route', 'siteOnly', 'severity', 'category', 'kind', 'defectsOnly', 'notesOnly', 'checkId', 'search', 'excludeWaived', 'limit', /* No `store`, for the reason `FACTS_KEYS` gives. */ 'dashboard', 'briefing', 'shape', ]) /** * Which keys narrow the result set. `runId` and the presentation flags are not filters. * * Listed rather than derived from what is on `input`, so adding a presentation flag cannot silently * start suppressing the briefing. */ const NARROWING_KEYS = [ 'route', 'siteOnly', 'severity', 'category', 'kind', 'defectsOnly', 'notesOnly', 'checkId', 'search', 'excludeWaived', ] as const export async function findings(ctx: ToolContext, input: FindingsToolInput = {}) { const unknown = Object.keys(input).filter((k) => !FINDINGS_KEYS.has(k)) if (unknown.length > 0) { throw new Error( `qa_findings does not accept ${unknown.map((k) => `\`${k}\``).join(', ')}. ` + `Accepted: ${[...FINDINGS_KEYS].sort().join(', ')}. ` + `Note the filter is \`checkId\` (singular, one id) — there is no \`checkIds\` or \`checks\`. ` + `An unrecognised key used to be ignored, which returned every finding in the run and read as an answer.`, ) } ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) const { findings: all, partial } = await ctx.store.readAllFindings(id) /** * This run's own issues, layered on at read time. * * Read time is now the *only* time — the crawl no longer applies issues, because a run has * none while it is running. So this is what makes a decision taken after the sweep visible * without re-crawling, and it is what puts a reclassification in front of the next reader. * The artifact's findings on disk stay untouched: interpretation lives beside the facts. * * No scoping filter, and that is the change. It used to read one store shared by every run of * every site, then narrow by origin — which caught cross-*site* leakage and never caught * cross-*route* leakage, so a homepage audit reclassified findings for pages it never loaded. */ const issueStore = await loadIssues(ctx.store.issuesPath(id), ctx.store.storage) const issuesApplied = applyIssues(all, issueStore) const { runId: _runId, full, limit, includeSnippets, briefing: wantBriefing, shape: wantShape, ...query } = input const matched = queryFindings(all, query).sort(compareFindings) const capped = limit !== undefined ? matched.slice(0, limit) : matched /** * The distribution, computed and put **first**. * * A run once returned 49 blocker findings for 9 unique broken URLs — the same navigation * links counted once per page — and the review read all 105 findings before noticing. Every * statement in this briefing is arithmetic, so it belongs here rather than in an instruction * asking an agent to be observant. It is stated over the *whole* run rather than the filtered * slice, because concentration is a property of the run and a filter would hide it. */ const routes = await ctx.store .readManifest(id) .then((m) => m.pages.map((p) => p.route)) .catch(() => [...new Set(all.map((f) => f.route).filter(Boolean) as string[])]) const shape = describeShape(all, routes) /** * The narration is conditional; **the numbers never are.** * * `shapeBriefing` restates `shape`'s figures in English and runs ~1,100 tokens. It is worth that * once, on the call somebody makes to orient — and on every narrow call after it, it is the same * paragraph again around a much smaller answer. So it defaults off once a filter is present. * * What must not happen is the briefing being recomputed over the filtered slice: concentration is * a property of the run, and `CLAUDE.md`'s rule is that a headline number never summarises the * active filter. Suppressing the prose keeps that intact where narrowing it would break it — and * every figure the prose is built from is still returned below. * * When it is dropped, the response says so and says how to get it back. A missing field reads as * "there was nothing to say". */ const narrowedBy = NARROWING_KEYS.filter((k) => { const value = input[k] if (value === undefined) return false // `defectsOnly: false` and `severity: []` narrow nothing. Treating an explicit no-op as a // filter would drop the briefing from a call that asked for the whole run. if (typeof value === 'boolean') return value if (Array.isArray(value)) return value.length > 0 return true }) const showBriefing = wantBriefing ?? narrowedBy.length === 0 /** * Findings that affect this route but carry no `route`, named rather than silently excluded. * * A finding collapsed across several routes keeps its members and loses its `route`, so a route * filter cannot return it — correctly, because a shared cause is the site-level slice's to write up * and four shards each citing their own instance is the duplication the grouping law forbids. * * What was wrong was saying nothing: `qa_findings { route: '/' }` returned 13 where the page's own * document listed 15, and a shard reading the smaller number concluded its page was cleaner than the * artifact said. The check ids are listed so the caller can confirm the count rather than trust it. */ const alsoAffecting = input.route ? all.filter((f) => !f.route && mentionsRoute(f, input.route as string)) : [] return { runId: id, /** * Read this before the findings. It says which of them are the same problem, and the issue * list should look more like `distinctCauses` than like `defects`. * * **Dropped only on request, and it says so when it is.** The briefing defaults off once a filter * is present because it is 1,100 tokens of prose; these numbers are 1,155B — 31% of a filtered * response — and are the thing the prose restates, so defaulting them off would leave a filtered * call with no run-level figure at all. A caller that already has them passes `shape: false`. */ ...(wantShape === false ? { shapeOmitted: 'Omitted because you passed `shape: false`. It is the run-wide distribution — defects, notes, ' + 'distinctCauses, concentration, blockingCauses, cleanRoutes, onEveryRoute, onSeveralRoutes, ' + 'repeated — and it does not change between calls. Drop the flag for it.', } : { shape: { ...(showBriefing ? { briefing: shapeBriefing(shape) } : { briefingOmitted: `Omitted because this call filters on ${narrowedBy.map((k) => `\`${k}\``).join(', ')} — it is the same ` + `run-wide paragraph every call, and you have it from an unfiltered one. Pass \`briefing: true\` for it. ` + `Every number below is still the whole run, not this filter.`, }), defects: shape.defects, notes: shape.notes, distinctCauses: shape.distinctCauses, concentration: shape.concentration, blockingCauses: shape.blockingCauses, cleanRoutes: shape.cleanRoutes, onEveryRoute: shape.onEveryRoute, /* * The shared causes that `siteOnly` cannot return, because they carry a route. Without this the * contract named an owner for something the owner had no way to find — measured twice. */ onSeveralRoutes: shape.onSeveralRoutes, repeated: shape.repeated.slice(0, 10), }, }), // True when the global document isn't written yet, i.e. the run is still // going and these findings are assembled from the per-page files. runStillInProgress: partial, /** * `total` is the whole run; `matched` is your filter. **They were reported side by side with no * statement of that**, and `total` is the name a reader anchors on — so `returned: 30` beside * `total: 85` read as truncation while `truncated: false` said it was not. A reviewer reported the * pair as two facts disagreeing. The note only appears when the two genuinely differ, because a * caveat on every response is one nobody reads. */ total: all.length, matched: matched.length, returned: capped.length, truncated: capped.length < matched.length, ...(matched.length !== all.length ? { scopeNote: `\`total\` is every finding in the run (${all.length}); \`matched\` is what your filter selected (${matched.length}). \`returned\` being below \`total\` is the filter, not truncation — \`truncated\` is the only field that reports truncation.`, } : {}), ...(alsoAffecting.length > 0 ? { alsoAffectingThisRoute: { count: alsoAffecting.length, checkIds: [...new Set(alsoAffecting.map((f) => f.checkId))], note: 'Site-level findings whose members include this route, so this page\'s own findings.md counts them' + ' and a route filter cannot. They are one shared fix each and belong to whoever owns the' + ' site-level slice — do not write them up per route.', }, } : {}), // Two separate numbers on purpose: notes must never inflate a count that reads // as "things wrong with this site". defectCounts: tallyFindings(matched).defects, noteCounts: tallyFindings(matched).notes, /** * **These are post-issue, and the manifest's are not** — the third of three note counts that share * one name. A defect a reviewer wrote up as `advice` is counted here as a note, so this number * moves as the review proceeds while `qa_run`'s stays where the crawl left it. */ countsNote: "Counted after this run's issues are applied, so a finding a reviewer reclassified is counted as" + " what the issue says rather than what the check proposed. qa_run's counts are the crawl's.", countsBySeverity: countBy(matched), // Surfaced so the caller knows some severities are overrides rather than what // the checks proposed. issuesApplied: issuesApplied.reclassified > 0 || issuesApplied.rekinded > 0 || issuesApplied.annotated > 0 ? { reclassified: issuesApplied.reclassified, rekinded: issuesApplied.rekinded, annotated: issuesApplied.annotated, } : undefined, findings: full ? capped : capped.map((f) => digestFinding(f, new Date(), { includeSnippets: includeSnippets ?? true })), } } /** * What changed between two runs. * * **The engine has had `diffRuns` for a while and no tool exposed it**, so the agent doing the * reviewing — the only party who ever asks *"did anything ship since last time"* — could not reach * it. One reviewer hand-wrote a comparison script four times in a single day, and another answered * the question by reading the previous run's `findings.md` and called that *"pure waste"*. Both are * also the carried-conclusion failure the contract forbids: a conclusion nobody re-measured. * * Nothing here is new logic. `diffRuns` matches on every identity a finding answers to, so a defect * that collapses site-wide on a six-page run and reports per route on a one-page run is one finding * in either direction; and `disappeared` is deliberately not called `fixed`. */ export async function diff( ctx: ToolContext, input: { runA: string; runB?: string } & StoreChoice, ): Promise> { ctx = await onStore(ctx, input) if (!input.runA) throw new Error('qa_diff needs `runA` — the earlier run. `runB` defaults to the latest.') // `runB` omitted goes through `resolve`, so `--run`/`defaultRunId` is honoured before `latest`. // Passing the literal `'latest'` here dropped a pinned run without saying so. const [idA, idB] = await Promise.all([resolve(ctx, input.runA), resolve(ctx, input.runB)]) if (idA === idB) { throw new Error( `\`runA\` and \`runB\` both resolve to ${idA} — a run does not differ from itself. ` + `\`qa_runs\` lists what else is stored.`, ) } const [a, b] = await Promise.all([ctx.store.readAllFindings(idA), ctx.store.readAllFindings(idB)]) /* * A run still crawling has not composed its cross-page findings, so every site-level finding would * read as appeared or disappeared purely from timing. Refused rather than annotated: the answer * would be wrong in the direction that reads as progress. */ if (a.partial || b.partial) { throw new Error( `${a.partial ? idA : idB} is still in progress — its cross-page findings are not composed yet, ` + `so a comparison would report timing as change. Wait for it to finish.`, ) } // The routes each run actually loaded. Same helper `qa diff` calls, so the two agree. const [auditedA, auditedB] = await Promise.all([ auditedRoutes(ctx.store, idA), auditedRoutes(ctx.store, idB), ]) const result = diffRuns( a.findings, b.findings, auditedA && auditedB ? { a: auditedA, b: auditedB } : undefined, ) return { runA: idA, runB: idB, ...result, /** * Stated in the payload rather than left to the caller's memory of this tool's description. * * "No longer reported" is the field a reader most wants to convert into "fixed", and the whole * reason the diff exists is that it cannot be. Built by the same function that writes the CLI's * banner, so the two surfaces cannot describe one pair of runs differently. */ reading: readingOf(result, { runA: idA, runB: idB }), } } /** * The rendered Markdown for a page, or for the whole run. * * Reading the document a human reads is often the cheapest way for an agent to * get oriented — it's already ranked, grouped and deduped. */ export async function findingsMarkdown( ctx: ToolContext, input: { runId?: string; page?: string; route?: string } & StoreChoice = {}, ): Promise<{ runId: string; scope: string; markdown: string }> { ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) /** * **`route` is accepted as well as `page`, because every sibling tool spells it `route`.** * `findPage` resolves either a route or a slug, so the two were always the same argument under two * names — and a reviewer passing `route` got the *whole run* back, silently, since an unknown key is * dropped. It reads as "this tool ignores scoping" rather than as a mistake in the call. */ const scope = input.page ?? input.route if (!scope) { return { runId: id, scope: 'run', markdown: await ctx.store.readGlobalFindingsMd(id) } } const page = await ctx.store.findPage(id, scope) return { runId: id, scope: page.route, markdown: await ctx.store.readPageFindingsMd(id, page.slug) } } /** * `qa_prompt` — a brief for whoever does the work, from a selection of this run's issues. * * ## Why an orchestrator wants this * * Not for itself. An agent that just reviewed a run already holds the issues and needs no summary of * its own conclusions. This is for **handing off**: into a session opened in the site's own repo, into * a Linear description, into a PR body, or to a developer who was not in the review. The brief carries * the reviewer's write-ups, the measurements behind them, what the run never looked at, and how to * prove a fix landed — the last of which is the loop this tool keeps failing to close by hand. * * Same builder as `qa prompt` and the dashboard's button, so the three cannot say different things * about one run. `filters` exist because the useful cut is almost always `type: ['code']`: a launch * review produces decisions, content edits and code changes in one list and only one of the three * belongs to a developer. */ export async function promptFor( ctx: ToolContext, input: { runId?: string issueIds?: string[] types?: string[] severities?: string[] workOnly?: boolean /** Include the reviewer's coverage record. Without it the handover carries work only. */ all?: boolean verifyUrl?: string } = {}, ): Promise<{ runId: string included: number work: number unknownIds: string[] markdown: string note?: string }> { const runId = await resolve(ctx, input.runId) const payload = await buildDashboardPayload(ctx.store, runId) let selected = payload.work if (input.issueIds?.length) selected = selected.filter((item) => input.issueIds!.includes(item.id)) if (input.types?.length) selected = selected.filter((item) => input.types!.includes(item.type)) if (input.severities?.length) selected = selected.filter((item) => input.severities!.includes(item.severity)) /* * **Work only by default, matching `qa brief --for-fixer`.** The two build the same document through * the same `buildPrompt`, so a different default here would make the handover depend on which door * the caller came through — and one of them is an agent that cannot see the other. * * **`issueIds` names them, so `issueIds` gets them.** The default is about a bulk handover, and the * dashboard's per-issue `Fix with Claude` is exactly one id — legitimately a transparency item. */ const NOTE_KINDS = ['advice', 'transparency', 'ungraded'] const holdNotes = !input.all && !input.issueIds?.length const notesHeld = holdNotes ? selected.filter((item) => NOTE_KINDS.includes(item.kind)).length : 0 if (holdNotes) selected = selected.filter((item) => !NOTE_KINDS.includes(item.kind)) /* * An empty selection throws rather than returning an empty document. A brief containing nothing reads * exactly like a clean run, so handing one back because a filter matched nothing would be the tool * asserting there is no work — the strongest claim it could make, on the weakest evidence. */ if (selected.length === 0) { throw new Error( payload.work.length === 0 ? `${runId} has no work items — nobody has reviewed it, so there is nothing to brief. Author issues with qa_issue_write first.` : notesHeld > 0 ? `no work items in ${runId} matched the filters (it holds ${payload.work.length}, and ${notesHeld} of those are notes this brief holds back). Pass all: true to include them, or call qa_issues to see what is there.` : `no work items in ${runId} matched the filters (it holds ${payload.work.length}). Call qa_issues to see what is there.`, ) } const result = buildPrompt(payload, { issueIds: selected.map((item) => item.id), ...(input.verifyUrl ? { verifyUrl: input.verifyUrl } : {}), }) const unreviewed = selected.filter((item) => !item.reviewed).length return { runId, included: result.included, work: result.work, unknownIds: [...result.unknownIds], markdown: result.markdown, /* * Said in the envelope as well as in the document. The caller is usually about to paste this * somewhere, and "the brief mentions it" is not the same as the caller knowing — an unreviewed * issue still carries the words a check wrote, which is not a write-up anybody can act on. */ ...(unreviewed > 0 || payload.work.length === 0 || notesHeld > 0 ? { note: [ unreviewed > 0 ? `${unreviewed} of these still carry a check's own title` : '', /* * Reported for the reason the CLI reports it: a list that does not say what it dropped * reads as the whole of it, and what is dropped here is the record of what nobody judged. */ notesHeld > 0 ? `${notesHeld} note(s) held back — advice, transparency and ungraded; pass all: true for them` : '', payload.work.length > 0 ? '' : 'this run has no issues, so nobody reasoned about it', ] .filter(Boolean) .join('; ') + '. The brief says so too, but do not hand it over without reading that part.', } : {}), } } /** Sections of a page's facts, so a caller can ask for one without the rest. */ /** One list, so the type and the error message that names the valid values cannot drift apart. */ /** * **This list is checked against a stored `facts.json`, not against the schema.** Eight keys were * collected and stored and had no name here — `consent`, `scroll`, `motion`, `copy`, `contactLinks`, * `forms`, `formControls`, `anchors` — and because an unrecognised name is refused, a caller could * not discover them by guessing either. Two reviewers reasoned a placeholder-only form out through a * contended browser while `formControls` sat on disk. */ export const FACT_SECTIONS = [ 'meta', 'probes', 'network', 'console', 'a11y', 'links', 'timings', 'interactions', 'document', 'fontUsage', 'consent', 'scroll', 'motion', 'copy', 'contactLinks', 'forms', 'formControls', 'anchors', /** * **What a collector could not do, which was written and unreachable.** * * `PageFacts.errors` is where every collector records its own failure — `lighthouse failed: …`, * `probe sweep failed: …` — and no section exposed it, so the reasons were stored on every run and * readable by nothing. Measured 2026-08-20: a run produced no Lighthouse data at all, and telling * *it threw* from *it was never attempted* was impossible through any tool while the answer sat in * this array. */ 'errors', ] as const export type FactSection = (typeof FACT_SECTIONS)[number] /** * One section's stored value. * * A `switch` rather than a lookup on `stored` so the compiler pairs each name with the field it * returns, and `fact-sections.test.ts` can assert every name in `FACT_SECTIONS` has a case. */ function sectionValue(stored: PageFacts, section: FactSection): unknown { switch (section) { case 'meta': return stored.meta case 'probes': return stored.probes case 'network': return stored.network case 'console': return stored.console case 'a11y': return stored.a11y case 'links': return stored.links case 'timings': return stored.timings case 'interactions': return stored.interactions case 'document': return stored.document case 'fontUsage': return stored.fontUsage case 'consent': return stored.consent case 'scroll': return stored.scroll case 'motion': return stored.motion case 'copy': return stored.copy case 'contactLinks': return stored.contactLinks case 'forms': return stored.forms case 'formControls': return stored.formControls case 'anchors': return stored.anchors case 'errors': return stored.errors /** * **An unrecognised section is an error, not an empty one.** It used to fall through this switch * and return the stub — `runId`, `route`, `url`, `status` and nothing else — which reads exactly * like *"that section holds no data"*. A reviewer asked for `notCollected`, which is real but lives * inside `summary`, and reported the coverage gaps as absent on a run that had them. */ default: throw new Error(unknownSectionError(String(section), stored as Record)) } } /** * Where a name lives when it is not a section itself, searched rather than listed. * * **A reviewer asked for `securityHeaders`, was told the valid sections, and concluded the field was * unreachable — it is `network.securityHeaders`.** They then rebuilt the answer from their own fetches * and reported a tool defect that does not exist. Listing the eighteen top-level names is accurate and * was not enough; the nearest real path is what the caller was actually asking for. * * Data-driven on purpose: derived from the facts in hand rather than a hand-kept table of aliases, * because a table is a second list to forget a field in. */ function nestedPathsFor(name: string, stored: Record | undefined): string[] { if (!stored) return [] const hits: string[] = [] for (const section of FACT_SECTIONS) { const value = stored[section] if (value && typeof value === 'object' && !Array.isArray(value) && name in value) { hits.push(`${section}.${name}`) } } return hits } function unknownSectionError(name: string, stored?: Record): string { const nested = nestedPathsFor(name.split('.')[0] ?? name, stored) return ( `qa_facts: no section named \`${name}\`. Valid: ${FACT_SECTIONS.join(', ')}.\n` + (nested.length > 0 ? ` It is a field inside one, so reach it with a dotted path: ${nested.map((p) => `\`${p}\``).join(' or ')}.\n` : '') + ` A dotted path projects into one — \`a11y.focusables\`, \`network.requests\`.\n` + ` Run-level facts — sweep, sweepBriefing, notCollected — are in \`summary\`, which is what` + ` you get when you pass no sections at all.` ) } /** * Walk a dotted projection, refusing by name at the first segment that does not resolve. * * The refusal names the keys that *do* exist at that point, because the reason a projection is worth * having is that a caller does not know the shape — and a typo that returned `undefined` would read * as *"that field is empty on this page"*, which is the failure this whole tool surface keeps * relearning. */ function project(root: unknown, path: readonly string[], section: string): unknown { let here: unknown = root const walked: string[] = [section] for (const key of path) { const walkedSoFar = walked.join('.') if (Array.isArray(here)) { throw new Error( `qa_facts: \`${walkedSoFar}\` is an array of ${here.length} item(s), so \`${walkedSoFar}.${key}\` selects nothing. ` + `Ask for \`${walkedSoFar}\` and read the items, or pass \`summarise: true\` for its shape and item keys.`, ) } if (here === null || typeof here !== 'object') { throw new Error(`qa_facts: \`${walkedSoFar}\` is a ${here === null ? 'null' : typeof here}, so \`${walkedSoFar}.${key}\` selects nothing.`) } const obj = here as Record if (!(key in obj)) { throw new Error( `qa_facts: \`${walkedSoFar}\` has no \`${key}\`. It holds: ${Object.keys(obj).join(', ') || '(nothing)'}.`, ) } here = obj[key] walked.push(key) } return here } /** Assign `value` at `path` inside `into`, creating the intermediate objects. */ function assignAt(into: Record, path: readonly string[], value: unknown): void { let here = into for (const key of path.slice(0, -1)) { const next = here[key] here[key] = next && typeof next === 'object' && !Array.isArray(next) ? (next as Record) : {} here = here[key] as Record } here[path[path.length - 1] as string] = value } /** * What is in a value and how much of it, without the value. * * The answer to *"is this worth fetching"*, which is the question `sections` exists to let a caller * ask — `["a11y"]` returns 73 focusables with 90-character selectors, and a reviewer who wanted the * count paid for all of it. `itemKeys` is the union over **every** item rather than a sample, so it * cannot under-report a field that only later entries carry. */ function shapeOf(value: unknown, depth = 1): unknown { if (value === undefined) return undefined if (value === null || typeof value !== 'object') { return typeof value === 'string' && value.length > 120 ? { chars: value.length } : value } const bytes = JSON.stringify(value)?.length ?? 0 if (Array.isArray(value)) { const keys = new Set() for (const item of value) { if (item && typeof item === 'object' && !Array.isArray(item)) for (const k of Object.keys(item)) keys.add(k) } return { count: value.length, bytes, ...(keys.size > 0 ? { itemKeys: [...keys] } : {}) } } const entries = Object.entries(value as Record) if (depth <= 0) return { bytes, keys: entries.map(([k]) => k) } return { bytes, keys: Object.fromEntries(entries.map(([k, v]) => [k, shapeOf(v, depth - 1)])) } } /** * Page facts, summarised by default. * * `facts.json` is the largest file in a run and returning it whole would flood a * context window with per-viewport geometry nobody asked for. The summary names * what is available and how big it is; `sections` then fetches only the part * that's actually needed. */ /** * Every key `qa_facts` accepts, so an unrecognised one can be refused by name. * * **The guard existed one level down and not here.** `sections` has always validated its *values* — * an unknown section name throws with the list — while an unknown *key* was dropped in silence. A * reviewer called `qa_facts { page, paths: ["scroll"] }`, expecting `paths` to scope the answer, and * got the entire unscoped summary back with nothing to say the parameter was not real. It read as a * successful projection. * * Same class as the `qa_findings { checkIds }` miss that cost two calls, and the same fix: a dropped * key answers a different question and looks exactly like an answer. */ /* * **No `store`.** It was listed here and in `FINDINGS_KEYS`, and `StoreChoice` is `{ dashboard }` — so * the key was advertised as accepted, taken, and discarded, and `{"store":"/not/a/store"}` answered * from the default store. `qa mcp` refuses it now and names the flag; listing it here would put the * claim back. */ const FACTS_KEYS = new Set(['runId', 'page', 'sections', 'summarise', 'dashboard']) export async function facts( ctx: ToolContext, input: { runId?: string; page: string; sections?: string[]; summarise?: boolean } & StoreChoice, ) { const unknown = Object.keys(input as unknown as Record).filter((k) => !FACTS_KEYS.has(k)) if (unknown.length > 0) { throw new Error( `qa_facts does not accept ${unknown.map((k) => '`' + k + '`').join(', ')}. Accepted: ` + `${[...FACTS_KEYS].sort().join(', ')}. To scope the answer to part of the facts the key is ` + '`sections` — `sections: ["a11y.focusables"]` projects into one. An unrecognised key used to be ' + 'ignored, which returned the whole summary and read as a successful projection.', ) } ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) const page = await ctx.store.findPage(id, input.page) const stored = await ctx.store.readPageFacts(id, page.slug) if (!input.sections || input.sections.length === 0) { return { runId: id, route: stored.route, summary: summariseFacts(stored) } } /* * Paths are validated before anything is read, so a batch naming one bad section fails on that * name rather than half-answering. Same reason `--batch` validates every entry before running any. */ const asked = input.sections.map((raw) => { const [head, ...rest] = String(raw).split('.') if (!(FACT_SECTIONS as readonly string[]).includes(head as string)) throw new Error(unknownSectionError(String(raw), stored as Record)) return { path: raw, section: head as FactSection, rest } }) // A section asked for whole outranks a projection into it: `['a11y', 'a11y.focusables']` is `a11y`. const whole = new Set(asked.filter((a) => a.rest.length === 0).map((a) => a.section)) const selected: Record = {} const shapes: Record = {} const absent: Record = {} for (const { path, section, rest } of asked) { const root = sectionValue(stored, section) /** * **Absent is stated, never left to a missing key.** `sections: ['forms']` used to answer with the * stub — `runId`, `route`, `url`, `status` — which is the same response an empty section gives and * reads as *"this page has no forms"*. Several collectors write their key only when they found * something, so absence here is genuinely two answers and the artifact does not separate them. */ if (root === undefined) { absent[section] = "not in this page's stored facts" continue } if (rest.length > 0 && whole.has(section)) continue const value = rest.length > 0 ? project(root, rest, section) : root if (input.summarise) shapes[path] = shapeOf(value) else assignAt(selected, [section, ...rest], value) } return { runId: id, route: stored.route, url: stored.url, status: stored.status, ...selected, ...(input.summarise ? { shapes, shapesNote: 'Shapes, not values: `count`/`bytes`/`itemKeys` describe what is stored without returning it. ' + 'Drop `summarise` to fetch a path for real.', } : {}), ...(Object.keys(absent).length > 0 ? { absent, absentNote: "Valid section names this page's facts do not carry. Several collectors write their key only " + 'when they found something, so absent means nothing was found OR the collector did not run — ' + 'the artifact does not distinguish those. It never means zero of something that was measured.', } : {}), } } /** * What's in this page's facts, and roughly how much of it. * * Exists so an agent can decide what to ask for rather than guessing — the whole * reason `sections` is worth having. */ /** * How useful a performance audit is to somebody asked *why* a page is slow. * * **Naming something outranks failing.** A metric audit fails hard on a slow page and blames nobody — * it is the metric restated, and the metric is already its own field. An audit with `items` is the * only kind that answers the question. Measured on fieldguide.com's homepage: four metric restatements * took four of the top five slots and displaced an audit reporting 17 seconds of render-blocking. */ function causalRank(audit: { score?: number | null; items: readonly string[] }): number { return (audit.items.length > 0 ? 2 : 0) + (typeof audit.score === 'number' ? 1 : 0) } export function summariseFacts(page: PageFacts) { const probeWidths = page.probes.map((p) => p.width) return { url: page.url, status: page.status, collectedAt: page.collectedAt, durationMs: page.durationMs, errors: page.errors, available: { meta: { title: page.meta.title, description: page.meta.description, canonical: page.meta.canonical, lang: page.meta.lang, ogTagCount: Object.keys(page.meta.og).length, twitterTagCount: Object.keys(page.meta.twitter).length, headingCount: page.meta.headings.length, /** * Both numbers, because one of them alone invites a false finding. * * `jsonLdBlocks: 0` used to be the only figure here, and it was **always** zero — the * extractor read `document.head` while the Next App Router pattern renders structured data * in the body. An agent read it and nearly filed "this site has no structured data" against * a site serving Organization, WebSite, Article, breadcrumb and FAQ blocks. `present` * distinguishes "we looked and found none" from "none parsed". */ jsonLdBlocks: page.meta.jsonLd.length, /** * **Absent when nobody counted, never `0`.** `?? 0` here was the whole bug: a run recorded * before `jsonLdScriptCount` existed reported `jsonLdBlocks: 1` next to * `jsonLdBlocksPresent: 0` — one block parsed, none present, about the same page — and the * field pair exists precisely to tell those apart. */ ...(page.meta.jsonLdScriptCount !== undefined ? { jsonLdBlocksPresent: page.meta.jsonLdScriptCount } : { jsonLdBlocksPresent: null, jsonLdBlocksPresentNote: 'not recorded on this run — count unknown, not zero' }), crawlersChecked: page.meta.crawlerViews.map((c) => c.crawler), ogImage: page.meta.ogImage ? { url: page.meta.ogImage.url, status: page.meta.ogImage.status, width: page.meta.ogImage.width, height: page.meta.ogImage.height, bytes: page.meta.ogImage.bytes, } : undefined, }, probes: { viewportCount: page.probes.length, widths: probeWidths, anyHorizontalScroll: page.probes.some((p) => p.hasHorizontalScroll), // Totals rather than the items themselves: this is the field that makes // facts.json huge, and the counts are enough to decide whether to fetch it. totals: { overflowing: sum(page.probes.map((p) => p.overflowing.length)), clippedText: sum(page.probes.map((p) => p.clippedText.length)), smallTapTargets: sum(page.probes.map((p) => p.smallTapTargets.length)), tinyText: sum(page.probes.map((p) => p.tinyText.length)), imageSizing: sum(page.probes.map((p) => p.imageSizing.length)), }, }, network: { requestCount: page.network.requests.length, redirectChain: page.network.redirectChain, securityHeaderCount: Object.keys(page.network.securityHeaders).length, mixedContentCount: page.network.mixedContent.length, }, console: { entryCount: page.console.length }, links: { count: page.links.length, external: page.links.filter((l) => l.external).length }, /** * axe results, which are populated — not `focusables`, which never are. * * This used to report `{ focusables: N }` and nothing else, and `A11yFacts.focusables` is * initialised to `[]` and never written. So the one a11y number in the summary was always * zero for a measurement nobody takes, while the twenty axe results that do exist went * unmentioned. A measurement-shaped zero is worse than an absent field; `sweep.notCollected` * now names the gap in words. */ a11y: page.a11y ? { axeResults: page.a11y.axeResults.length, axePassCount: page.a11y.axePassCount, contrastUndetermined: page.a11y.contrastUnknown.length, } : undefined, /** * ── the load numbers, and what Lighthouse blamed ────────────────────────── * * **This was `lcpMs` alone, and one number cannot be reasoned about.** An LCP of 4.1s does not * say whether the paint arrived late or the main thread was blocked, so a reviewer could see * that a page was slow and had nothing to say about *why* — the causal data was sitting in * `lighthouseAudits` behind an opt-in `sections: ['timings']` that nothing advertised. * * `slowest` is the failing **performance** audits with the savings Lighthouse attributed to * each and a couple of the offending URLs, which is the *"these three things are adding four * seconds"* sentence already computed. Capped at five and two URLs each, and the cap is stated * in `hint` rather than silently applied — a truncated list reads as the whole list. * * **Handing this over is not a licence to gate on it.** `CLAUDE.md`: nothing in timings ever * hard-fails a run, and these run under a 4× CPU throttle on whatever machine crawled, so they * are as much a fact about the runner as about the site. What they are *for* is an issue: a * check may not name a cause, and a reviewer is exactly who should. */ timings: page.timings ? { lcpMs: page.timings.lcpMs, clsScore: page.timings.clsScore, tbtMs: page.timings.tbtMs, advisoryOnly: page.timings.advisoryOnly, /* * From `performanceAudits`, **not** `lighthouseAudits` — the two are separate fields * precisely so these can never reach the findings loop. Filtering `lighthouseAudits` by * category is what the first version did, and it returned nothing on every real run: the * collector was skipping the whole performance category, so this read a list that is * always empty outside a hand-written fixture. * * **Audits that blame something come first, and that ordering is the whole value.** * Sorting on "is it failing" put the four metric audits at the top — `largest-contentful- * paint`, `speed-index`, `first-contentful-paint`, `total-blocking-time` all score 0 on a * slow page, all restate a number this object already carries as its own field, and all * name **nothing**. Measured on fieldguide.com's homepage they filled four of five slots * and pushed out `render-blocking-insight`, which reports *est. savings of 16,970 ms* and * names the two chunks responsible. An audit with `items` is a cause; an audit without one * is a restatement. * * Cap 8, not 5: that homepage has exactly 8 audits blaming something and every one is * worth reading. The metric restatements sort last and fall outside the cap on any page * that has real diagnostics, while still being there on a page where Lighthouse blamed * nothing — so the field is never empty just because it was picky. */ slowest: page.timings.performanceAudits .slice() .sort((a, b) => causalRank(b) - causalRank(a)) .slice(0, 8) .map((a) => ({ id: a.id, title: a.title, ...(a.displayValue ? { cost: a.displayValue } : {}), ...(a.items.length > 0 ? { blaming: a.items.slice(0, 2) } : {}), ...(a.itemCount !== undefined ? { itemCount: a.itemCount } : {}), })), } : undefined, interactions: { count: page.interactions.length }, }, /** * How far the page was travelled, beside what was found on it. * * Here rather than behind a `sections` name because it qualifies every other number in this * response: a page the pass stopped short on has byte totals, axe results and probe counts * that are all floors. **Absent means the page was never scrolled**, which is every run * written before the pass existed — `sweep.notCollected` says so in words. */ scroll: page.scroll, /** * What the server sent, before hydration — the one thing on this page that a live DOM read * cannot answer. **Absent means the run predates the collector**, and `notCollected` inside * it means the run has it and Chrome had already dropped the body; those are different * answers and neither is "the document was empty". * * The body itself is not stored, deliberately: measured at 15–224% of a page's `facts.json`. * `bytes` and `hash` are what a later run compares against. */ document: page.document ? { bytes: page.document.bytes, hash: page.document.hash, preloads: page.document.preloads.length, hiddenAtRest: page.document.hiddenAtRest ? { total: page.document.hiddenAtRest.total, headings: page.document.hiddenAtRest.headings, } : undefined, notCollected: page.document.notCollected, } : undefined, /** * What each font family is actually used for — the half a byte total cannot supply. * * Only families that draw text are listed, ordered by how many elements do. `unmappable` is * above zero when a stylesheet could not be read, which makes the family list a lower bound * rather than a complete answer. */ fontUsage: page.fontUsage ? { families: page.fontUsage.used.map((u) => ({ family: u.family, elements: u.elements, distinctGlyphs: u.distinctGlyphs, })), declaredFaces: page.fontUsage.faces.length, unmappable: page.fontUsage.opaqueSheets, scanCapped: page.fontUsage.capped, } : undefined, /** * The sweep the skill's step 4b asks for, computed rather than left to the reader. * * Two separate reviews wrote this same aggregation by hand within one day — weight, biggest * asset, refetches, fonts, media preload, third parties — and neither needed a judgement to do * it. Handing it over here is what makes a per-page account a sentence to write rather * than a scripting exercise, and `notCollected` is what stops silence reading as a pass. */ sweep: sweepPage(page), sweepBriefing: sweepBriefing(sweepPage(page)), hint: 'Read `sweepBriefing` before the findings — it is the arithmetic no check turned into one. Pass `sections` (meta, probes, network, console, a11y, links, timings, interactions, document, fontUsage, consent, scroll, motion, copy, contactLinks, forms, formControls, anchors, errors) to fetch a section in full. `errors` is what each collector could not do on this page, in its own words. A dotted path projects into one — `sections: ["a11y.focusables"]` returns that field alone rather than all of `a11y`, and `summarise: true` returns counts, bytes and item keys for a path instead of its contents, which is how you decide whether it is worth fetching. `formControls` carries `hasLabel` and `placeholder` for every control in or out of a `
`; `a11y.focusables` carries `tabIndex`, `tabOrderIndex` and `domOrderIndex` for every element in the tab order. `summary.document` is what the SERVER sent before any script ran, which no DOM read can tell you: `preloads` counts the preload links and `hiddenAtRest` counts elements served at inline opacity 0, with the heading levels among them. `sections: ["document"]` returns every preload with its `as` and `crossorigin`, and a sample of those elements. `summary.fontUsage` says what each family actually DRAWS, which is what makes a font byte total mean something — a 3.3MB face is one thing for body copy and another for eight icons; `unmappable` above zero means a stylesheet could not be read, so the family list is a lower bound. `timings.slowest` is the 8 most useful performance audits, ordered so the ones that NAME something come first — an audit with `blaming` is a cause, one without is the metric restated; `sections: ["timings"]` returns every audit and the scores. No check will ever report a load time as a defect — naming what made a page slow is an issue, and it is yours to write.', } } /** * A stored screenshot, as bytes plus its media type. * * Crops, not full pages. A full-page capture downscales to roughly 282×1568 on * the way into a vision model and arrives unreadable — those exist for humans * reading the HTML report. The path is validated against the run directory by * `RunStore`, since it originates from a findings file and findings files are data. */ export async function screenshot( ctx: ToolContext, input: { runId?: string; path: string } & StoreChoice, ): Promise<{ runId: string; path: string; base64: string; mimeType: string; bytes: number }> { ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) /** * Refused by name, because the obvious guess is wrong and the default error named an internal. * * A finding carries `screenshots: [...]`, so `{ findingId }` is what a reviewer reaches for * first — and it produced `The "path" property must be of type string, got undefined`, which * names a Node parameter, says nothing about what was expected, and points at neither * `qa_screenshots` nor the finding's own array. `qa_facts` was given exactly this treatment for * exactly this reason; this tool was missed. */ if (typeof input.path !== 'string' || !input.path.trim()) { throw new Error( 'qa_screenshot needs `path` — a run-relative image path, verbatim from a finding\'s ' + '`screenshots` array or from `qa_screenshots`. It is not a finding id: one finding can carry ' + 'several crops, so there is nothing to resolve. `qa_screenshots {page}` lists what this run has.', ) } const data = await ctx.store.readScreenshot(id, input.path) return { runId: id, path: input.path, base64: data.toString('base64'), mimeType: mimeFor(input.path), bytes: data.byteLength, } } export async function listScreenshots(ctx: ToolContext, input: { runId?: string; page: string } & StoreChoice) { ctx = await onStore(ctx, input) const id = await resolve(ctx, input.runId) const page = await ctx.store.findPage(id, input.page) return { runId: id, route: page.route, screenshots: await ctx.store.listScreenshots(id, page.slug) } } /** * Record a waiver against a finding id. * * The finding keeps appearing in every subsequent run — that's the contract, and * it's why this writes to the shared store rather than into a run. The reason is * required because a waiver without one is unreviewable six months later. */ export async function waive( ctx: ToolContext, input: { id: string; reason: string; by: string; expiresAt?: string; runId?: string }, ) { if (!input.reason.trim()) throw new Error('a waiver needs a reason — an unexplained waiver cannot be reviewed later') // Look the finding up so the stored entry carries its checkId and route, which // is what makes the waivers file readable by hand. let checkId: string | undefined let route: string | undefined let title: string | undefined try { const id = await resolve(ctx, input.runId) const { findings: all } = await ctx.store.readAllFindings(id) const found = all.find((f) => findingIdentities(f).includes(input.id)) if (found) { checkId = found.checkId route = found.route title = found.title } } catch { // Waiving against an id from an older run is legitimate — fingerprints are // stable across runs precisely so that works. } const entry = { id: input.id, reason: input.reason, by: input.by, at: new Date().toISOString(), ...(input.expiresAt ? { expiresAt: input.expiresAt } : {}), ...(checkId ? { checkId } : {}), ...(route ? { route } : {}), } const { replaced, waivers, path } = await ctx.store.saveWaiver(entry) return { saved: entry, replaced, waiverCount: waivers.length, // The file actually written, not the store's anchor — waivers are one file each, and reporting // a path nobody wrote is the kind of small wrong fact that sends a reader to an absent file. path, matchedFinding: title, note: 'The finding will continue to appear in future runs, marked as waived. Waivers never hide findings.', } } /** * Read the issue list. * * The counterpart to `qa_issue_write`, and the review loop cannot work without it: filling in * `related` means knowing what issues exist, and re-authoring an issue somebody already wrote * is how a work list turns into a pile of near-duplicates. * * It also answers "is this run reviewed at all?" — which is the question the DRAFT marker in * the report is built on, and the honest answer for most runs is *no*. */ /** * The small fields of an issue: enough to dedupe, rank and decide what to open, and none of the * prose. * * `where`, `route` and `cites` are in here on purpose — those are what a merge decision is made * on, so a compact mode without them would send the caller straight back for the full list. * `problem`, `fix`, `why`, `evidence`, `links` and `citedTitles` are what the size is. */ const COMPACT_FIELDS = [ 'id', 'title', 'route', 'severity', 'defaultSeverity', 'kind', 'type', 'category', 'rank', 'where', 'sharedLocation', 'cites', 'related', 'by', 'at', 'reviewed', ] as const /** Named lists are capped so one answer cannot become the whole run; the cap is reported. */ const NAMED_CAP = 20 /** Which slice of a run a set of counters was computed over. */ export type Slice = { route: string } | { siteOnly: true } const sliceLabel = (slice: Slice): string => ('siteOnly' in slice ? 'the site-level slice (findings with no route)' : slice.route) /** * The coverage counters for one slice of a run — one route, or the route-less findings. * * ## Why this is a function and not two copies * * `qa_issues { route }` computed these inline, and `qa_issue_write` returns them too, because the * numbers are a shard's stop test and the write is where a shard already is. Measured across fifteen * reviewers: **36 `qa_issues` calls whose only purpose was reading three integers**, each answered with * twelve issues, nineteen `sharedCitations` and eighteen other routes' notes. Two implementations of a * completion signal is the one place they must not drift — a shard told it is done by one surface and * not by the other has no way to decide which to believe. * * Pure over what both callers already hold: the run's findings and the run's issues. `cited` is built * from **every** issue rather than the slice's own, because a site-wide issue that cites a finding on * this route has covered it and telling a shard otherwise sends it to write a duplicate. * * The fields keep their `route` prefix on the site-level slice too. That is `qa_issues`'s existing * spelling under `siteOnly: true`, and one name a reader can look up beats two that are each right * half the time. * * Exported for the third consumer, `review-payload.ts`, which prints the same three numbers into a * shard's brief so the stop test is stated before the review starts rather than discovered at the end. */ export function sliceCoverage(findings: readonly Finding[], issues: readonly Issue[], slice: Slice) { const cited = new Set(issues.flatMap((i) => i.cites)) /* Every identity, not just `f.id` — a citation written mid-crawl names the id that existed then. */ const isCited = (f: Finding) => findingIdentities(f).some((id) => cited.has(id)) const mine = 'siteOnly' in slice ? findings.filter((f) => !f.route) : findings.filter((f) => sameRoute(f.route, slice.route)) const mineIssues = issuesOnSlice(issues, slice) const uncited = mine.filter((f) => isDefect(f) && !isCited(f)) const notesUncited = mine.filter((f) => !isDefect(f) && !isCited(f)) const checkIds = [...new Set(uncited.map((f) => f.checkId))] return { routeDefectsCited: mine.filter(isDefect).length - uncited.length, routeDefectsUncited: uncited.length, routeUncitedCheckIds: checkIds.slice(0, NAMED_CAP), routeUncitedFindingIds: uncited.slice(0, NAMED_CAP).map((f) => f.id), routeNotesUncited: notesUncited.length, routeUncitedNotes: notesUncited.slice(0, NAMED_CAP).map((f) => ({ id: f.id, checkId: f.checkId, title: f.title, ...(f.route ? { route: f.route } : {}), })), ...(checkIds.length > NAMED_CAP || uncited.length > NAMED_CAP || notesUncited.length > NAMED_CAP ? { routeNamedListsTruncated: `naming ${NAMED_CAP} of each — ${checkIds.length} check id(s), ${uncited.length} uncited defect(s), ${notesUncited.length} uncited note(s)`, } : {}), /* * The pass-3 number a shard can actually finish, over the issues it wrote rather than over * findings — the run-level one counts every other shard's looking too. */ routeFoundByLooking: mineIssues.filter((i) => i.cites.length === 0).length, } } /** The issues on one slice. `qa_issues` calls it `totalForRoute`; the write path needs the same filter. */ function issuesOnSlice(issues: readonly Issue[], slice: Slice): Issue[] { return 'siteOnly' in slice ? issues.filter((i) => !i.route) : issues.filter((i) => sameRoute(i.route, slice.route)) } export async function issues( ctx: ToolContext, input: { runId?: string unreviewedOnly?: boolean route?: string siteOnly?: boolean /** Drop the prose fields. The meta pass reads every issue, so this is the call that gets large. */ titlesOnly?: boolean /** Explicit projection, for when `titlesOnly` is the wrong subset. Unknown names are refused. */ fields?: string[] /** * Specific issues, by id. * * **The half `titlesOnly` was missing.** The documented meta-pass flow is to scan with * `titlesOnly` and then read the prose of *the few* being merged — and there was no parameter * that expressed "the few", so a reviewer needing four issues either pulled all of them at full * size, which is the 87.6KB `titlesOnly` exists to avoid, or read them off disk. It did the * second and reported it. * * An id matching nothing is reported in `idsNotFound` rather than silently dropped: an issue * that was merged away and one whose id was mistyped look identical in a shorter list. */ ids?: string[] } & StoreChoice = {}, ) { ctx = await onStore(ctx, input) /** * A run is required now, because the issues live inside one. * * This used to fall back to listing the store when no run was readable — reasonable when the * store outlived runs, and meaningless now: there is no work list independent of a run. */ const runId = await resolve(ctx, input.runId) /** * `ctx.store.storage`, not the default — and every one of the six calls in this file that reaches * an issue file needed the same correction. * * `loadIssues`/`saveIssue`/`deleteIssue` take the backend as a * trailing optional argument that **defaults to the filesystem**, so omitting it is invisible on * the only backend anybody tested against: the default and the store's own agree. Against the Neon * mirror they do not, and the failure was measured rather than reasoned — `qa_projects` reported * **31 issues** for a pushed run while `qa_issues` reported **0** for the same run in the same * command, because the first went through the seam and this one read a path that exists on nobody's * disk. `0` is not an error here; it is how the artifact says *nobody reviewed this run*. So the * tool was confidently reporting an unreviewed run over 31 authored issues. * * The writers are worse and are the reason this is a comment rather than a diff. `saveIssue` * through the default backend would have **succeeded** — writing an issue to a local directory * named after the mirror's virtual root, returning a path and a count, with nothing ever reading * it. `NeonRunStorage.writeText` throws precisely so that write is refused; a bypassed seam turns * a refusal into silent loss. */ const issueStore = await loadIssues(ctx.store.issuesPath(runId), ctx.store.storage) let findingsById = new Map() let distinct: Finding[] = [] let application: ReturnType | undefined try { const { findings: all } = await ctx.store.readAllFindings(runId) // Keyed on every identity, so a citation written against a member of a presentation // grouping resolves to the group rather than reading as "probably fixed". findingsById = new Map() for (const f of all) for (const id of findingIdentities(f)) findingsById.set(id, f) /** * **Count over this, look up in the map.** The map holds one entry *per identity* so a citation * written against a group member resolves to the group — which means iterating its values yields * the same finding once per identity, and every coverage number computed that way was inflated. * * Measured on one run: `defectsCited: 56` and `defectsUncited: 4` over a run holding **50** * findings, `notesUncited: 18` counting duplicates, and `uncitedNotes` naming a single note id * five times. Four reviewers reported the disagreement and none could tell which number to trust. */ distinct = all // Against a copy: this is a read tool and must not mutate what a later call reads. application = applyIssues( all.map((f) => ({ ...f })), issueStore, ) } catch { // A run whose findings are not written yet. The issues are still worth listing. } const unreviewedIds = new Set((application?.unreviewed ?? []).map((i) => i.id)) // No site filter: every issue in this file was authored against this run. const forThisRun = issueStore.issues /** * ── the route a shard owns, and the counters that follow it ──────────────── * * **A per-page reviewer had no number that said its route was done.** `defectsUncited` and * `notesUncited` are run-level, so under a sharded review they are dominated by other shards' work * and by the site-level slice: a shard that has cited every one of its own findings still reads * `defectsUncited: 6`, which looks like failure. Both reviewers in the first real fan-out hit this * independently and both named it the one thing to fix — they each ended up hand-diffing * `uncitedCheckIds` against their route's findings to prove pass 1 was complete. * * `qa_findings` has taken a `route` since it existed. The contract told an agent to shard by route * and then made coverage countable only for the whole run, which is the wrong unit for the job it * had just handed out. */ /** * `siteOnly` is the mirror of `route`, and it exists because the site-level slice had no number. * * Shards get `routeDefectsUncited`; the reviewer that owns everything route-less could only read the * run-level counter, **which every other concurrent writer moves** — so it could not tell whether its * own slice was covered. It reported exactly that. Same spelling as `qa_findings { siteOnly }`, for the * same reason `route: null` was never allowed to mean this. */ const scoped = input.siteOnly ? forThisRun.filter((i) => !i.route) : input.route ? forThisRun.filter((i) => sameRoute(i.route, input.route)) : forThisRun const byUnreviewed = input.unreviewedOnly ? scoped.filter((i) => unreviewedIds.has(i.id)) : scoped /* * Applied last, over the run's whole set rather than over `scoped`: asking for an id by name is * asking for that issue, and silently returning nothing because it sits on another route would * be the filter answering a question nobody asked. */ const wantedIds = input.ids?.length ? new Set(input.ids) : undefined const listed = wantedIds ? forThisRun.filter((i) => wantedIds.has(i.id)) : byUnreviewed const idsNotFound = wantedIds ? [...wantedIds].filter((id) => !forThisRun.some((i) => i.id === id)) : [] return { runId, /** * **The directory, not the anchor file.** `issueStore.path` is `/global/issues.json` — the key * every reader and writer derives `global/issues/` from — and reporting it made this tool answer * *"where do issues live"* with the pre-split layout that concurrent review is unsafe on. Five of six * reviewers in one fan-out flagged it and one said it nearly reviewed serially over it. */ path: issueStore.path ? issuesDirFor(issueStore.path) : issueStore.path, ...(issueStore.error ? { error: issueStore.error } : {}), ...(issueStore.migrated ? { migratedFromTriage: issueStore.migrated } : {}), /** * Findings cited by more than one issue — the meta pass's dedupe candidates, for free. * * **Two issues citing one finding is either a duplicate or a deliberate split, and it is never * nothing.** Unlike similarity over `where` strings this has no false positives: it is a set * overlap the server can compute in one pass. The last meta pass found exactly this by eye — * two issues about one `og:image` handler, filed by two route reviewers — and its own suggestion * was to expose it. It also explains the confusing case it hit on the way, where one issue's * `citedTitles` read as two identical strings: two different findings, one shared title. */ ...(() => { const byFinding = new Map() for (const i of forThisRun) for (const c of i.cites) byFinding.set(c, [...(byFinding.get(c) ?? []), i.id]) const shared = [...byFinding.entries()] .filter(([, ids]) => ids.length > 1) .map(([finding, issueIds]) => ({ finding, issueIds })) return shared.length > 0 ? { sharedCitations: shared.slice(0, 20), sharedCitationsNote: 'Findings cited by more than one issue. Each is a duplicate to merge or a split to justify — never nothing.', } : {} })(), total: forThisRun.length, /** * The severity spread of the issues in this run, blocker-first. **Over `total`, not over `returned`.** * * A reviewer checking its own spread had to grep the returned JSON, which is both a waste and a * different question: `returned` is a page of a list and this is a fact about the run. Same reasoning * as the summary counts elsewhere — a headline number is computed independently of the filters, or it * quietly answers "what did I ask for" instead of "what is there". * * Severity, not kind: `kind` says what response is owed and `severity` says how urgent, and it is the * urgency spread a reviewer is checking when it asks whether it has over- or under-called the run. */ bySeverity: countBy(forThisRun as unknown as Finding[]), ...(input.route ? { route: input.route, totalForRoute: scoped.length } : {}), ...(input.siteOnly ? { siteOnly: true, totalSiteLevel: scoped.length } : {}), returned: listed.length, /* Never silently short: a retracted issue and a mistyped id produce the same shorter list. */ ...(idsNotFound.length > 0 ? { idsNotFound } : {}), /** * The count that decides whether this run reads as reviewed. A CLI cannot require an * agent to think, so the artifact refuses to look finished — and this is that number. */ unreviewed: unreviewedIds.size, /** * ── the number pass 3 did not have ──────────────────────────────────────── * * Issues citing **nothing**: work found by looking at the site rather than by reading a * finding. `cites` is optional precisely so this is possible, and an uncited issue is the only * artifact-visible evidence that somebody did the half of the review no check can do. * * **Every other pass has a number that goes to zero and this one had, in the skill's own * words, "nothing. this is the job."** Anything without a counter is what gets dropped under * time pressure. Measured across two arms of one run at different effort: **16 against 5**, * while every other metric had converged — and the low arm scored `defectsUncited: 0`, a * perfect result on the measured half, next to nine missed findings that were all pass 3. * * Deliberately **not** a target to maximise. It is reported beside `total` so a reader can see * the ratio; a run whose issues are *all* uncited has stopped reading its own measurements. * * **It is only comparable within one build, and that is not a nuance.** Promoting a discovery * into a check moves that work from uncited to cited, so this number goes *down* precisely when * the tool gets better — it punishes the improvement it exists to motivate. Measured: five * checks were added from one review's uncited issues, and a re-run of that review scores lower * on this while missing nothing. Never read a trend across versions; compare arms of the same * build, on the same route set. */ foundByLooking: forThisRun.filter((i) => i.cites.length === 0).length, /** * Defects in this run that no issue cites. * * The number that says how far the review actually got. `unreviewed` catches issues * carrying a check's title; this catches the findings nobody reached at all — a run with * 24 defects and 16 issues used to be indistinguishable from one where every defect was * accounted for. Leaving a defect uncited is a legitimate call; leaving it *unstated* is * how partial coverage reads as complete. */ ...(findingsById.size > 0 ? (() => { const cited = new Set(forThisRun.flatMap((i) => i.cites)) /** * **Every identity, not just `f.id`** — the same rule `issueWrite` and `applyIssues` resolve by. * * A citation written mid-crawl names the id that existed then. The cross-page collapse mints a * new finding whose `groupedFrom` carries the old ids, so the issue still resolves while a bare * `cited.has(f.id)` stopped matching — and `markdown.ts` tells reviewers in print to work from a * page's findings *while the run is going*, which is precisely when those ids are provisional. * The counter then reported the route as uncited for ever, and that number reaching zero is the * only completion signal the sharded contract gives a reviewer. */ const isCited = (f: Finding) => findingIdentities(f).some((id) => cited.has(id)) const uncited = distinct.filter((f) => isDefect(f) && !isCited(f)) /** * The same accounting for **notes**, and this is the more important of the two. * * The skill has always said that a review has two halves — cover the findings, and * reason about what no check turned into a finding — and it diagnosed its own failure * mode exactly: *"This half has no number attached, which is exactly why it gets * skipped."* It then did not give it a number. Measured consequence: a run emitted * `discovery.sitemap.shape` reading `/solutions 8, / 1, /about 1, /blog 1` on a site * with a visible blog, the reviewer read it as inventory, and 34 undeclared content * URLs went unreported by a review that scored 0 `defectsUncited`. **A perfect score on * the measured half, next to the miss, and nothing in the artifact could tell.** * * A note is `transparency`, `policy`, `advice` or `ungraded` — every one of them is a * measurement somebody has to judge, because no rule could. Citing one from an issue is * how you record that you judged it, including when the judgement is "fine". Leaving it * uncited stays legitimate; leaving it *unstated* is what this counts. */ const notes = distinct.filter((f) => !isDefect(f)) const notesUncited = notes.filter((f) => !isCited(f)) const namedNote = (f: Finding) => ({ id: f.id, checkId: f.checkId, title: f.title, ...(f.route ? { route: f.route } : {}), }) /** * The same accounting, narrowed to one route — the number a shard can actually finish. * * Counted over findings **on that route**, cited by *any* issue rather than only by the * route's own: a site-wide issue that cites a finding on this page has covered it, and * telling a shard otherwise would send it to write a duplicate. Site-level findings carry no * route, so they are correctly outside every shard's number — they belong to the meta pass. * * **The named lists are scoped too, and they were not.** `uncitedNotes` and * `uncitedFindingIds` are run-level, so the call whose entire purpose is per-route scoping * answered with other routes' work — measured at 19 of 20 entries on one run — beside * counters that *were* scoped. A shard reading the names rather than the counts is reading * somebody else's queue. */ const scopedTo = input.siteOnly ? ({ label: 'siteOnly', slice: { siteOnly: true } } as const) : input.route ? ({ label: 'route', slice: { route: input.route } } as const) : undefined /* Shared with `qa_issue_write`, which returns the same counters — see `sliceCoverage`. */ const forRoute = scopedTo ? sliceCoverage(distinct, forThisRun, scopedTo.slice) : {} const allUncitedCheckIds = [...new Set(uncited.map((f) => f.checkId))] /** * The run-level names, dropped on a scoped call — the counts beside them are not. * * `defectsUncited` and `notesUncited` stay run-level on purpose: a headline number * summarises the run, never the active filter. What has to go is the run-level *list*, * because a name reads as *"this is yours to write up"* in a way a total does not. */ const runLevelNames = scopedTo ? { namesOmitted: `uncitedCheckIds, uncitedFindingIds and uncitedNotes are omitted because this call is scoped to ` + `${scopedTo.label === 'siteOnly' ? 'the site-level slice' : `\`${input.route}\``} — run-level, they name other ` + `slices' work. The \`route*\` fields above are the same lists for yours. Drop the scope for the run's.`, } : { uncitedCheckIds: allUncitedCheckIds.slice(0, NAMED_CAP), /** * The finding ids too, because a check id is not addressable. * * `uncitedCheckIds: ["weight.image-uncompressed"]` told the meta pass what kind of thing was * uncited and nothing it could pass to `cites`. It dumped every finding in the run and * grepped. The server already knows these — they are what the count is computed from — so * withholding them stopped one field short of being actionable. */ uncitedFindingIds: uncited.slice(0, NAMED_CAP).map((f) => f.id), /** * **The cap is stated whenever it bites.** *No silent caps* — a truncated list reads as "that * is everything", and these two are the lists a reviewer works to zero. Measured: a run with * 24 uncited notes named 20, and the reviewer only found the missing four because it happened * to hold the full findings list from elsewhere. The count beside the list was right the whole * time, which is what made the gap invisible rather than obvious. */ ...(allUncitedCheckIds.length > NAMED_CAP ? { uncitedCheckIdsTruncated: `naming ${NAMED_CAP} of ${allUncitedCheckIds.length} — ask per route to see the rest` } : {}), /** * Named, not just counted. A count says "you missed something"; the list says which * measurement nobody looked at, which is the only form of this that leads anywhere. */ uncitedNotes: notesUncited.slice(0, NAMED_CAP).map(namedNote), ...(notesUncited.length > NAMED_CAP ? { uncitedNotesTruncated: `naming ${NAMED_CAP} of ${notesUncited.length} — ask per route to see the rest` } : {}), } return { ...forRoute, defectsCited: distinct.filter(isDefect).length - uncited.length, defectsUncited: uncited.length, notesCited: notes.length - notesUncited.length, notesUncited: notesUncited.length, ...runLevelNames, } })() : {}), defects: forThisRun.filter((i) => (i.kind ?? 'defect') === 'defect').length, advice: forThisRun.filter((i) => i.kind === 'advice').length, ...shapeIssues( listed.map((issue) => ({ ...issue, reviewed: !unreviewedIds.has(issue.id), // What the checks called the findings this cites — so a reader can see at a glance // whether the write-up says anything the measurement did not. citedTitles: issue.cites.map((id) => findingsById.get(id)?.title).filter(Boolean), // Citations that match nothing in this run. Reported, never dropped: it usually means // the finding is fixed, which is the most interesting thing an issue can tell you. unresolvedCitations: issue.cites.filter((id) => findingsById.size > 0 && !findingsById.has(id)), })), input, ), } } /** One row of `qa_issues`, before any projection. */ type IssueRow = Issue & { reviewed: boolean citedTitles: (string | undefined)[] unresolvedCitations: string[] } /** * Project the issue list, and **say when it has been projected**. * * The meta pass has to read every issue in the run to dedupe and rank them, so this is the one call * that is guaranteed to be large — 35.5KB measured on a 36-issue run, and two reviewers post-processed * the response with a script rather than reading it. The prose fields are nearly all of that and none * of them are what a merge decision is made on. * * Two properties, and the second matters more than the saving: * * - **A dropped field is reported, not silently absent.** `issuesShape` names what came back. * Without it, an issue with no `problem` key is indistinguishable from an issue whose `problem` * is empty, and this codebase's recurring bug is exactly that — an omission read as data. * - **An unknown field name is refused.** Picking keys off an object means a typo yields `{}` per * issue and a caller's fallback runs on it, so `fields: ['tittle']` would report every issue as * blank rather than as an error. */ function shapeIssues( rows: IssueRow[], input: { titlesOnly?: boolean; fields?: string[] }, ): { /** * `Partial` because a projection genuinely omits fields, and that is the honest type: a consumer * indexing `problem` should be made to handle its absence rather than told it is always there. */ issues: Partial[] issuesShape?: { returnedFields: string[]; omittedFields: string[]; note: string } } { if (!input.titlesOnly && !input.fields?.length) return { issues: rows } const available = new Set(rows.flatMap((i) => Object.keys(i)).concat(COMPACT_FIELDS)) const wanted = input.fields?.length ? input.fields : [...COMPACT_FIELDS] const unknown = wanted.filter((f) => !available.has(f)) if (unknown.length > 0) { throw new Error( `qa_issues: no issue field named ${unknown.map((f) => `\`${f}\``).join(', ')}. ` + `Available: ${[...available].sort().join(', ')}.`, ) } const dropped = [...available].filter((f) => !wanted.includes(f)).sort() return { issues: rows.map((row) => { const source = row as unknown as Record const out: Record = {} for (const field of wanted) if (source[field] !== undefined) out[field] = source[field] return out as Partial }), issuesShape: { returnedFields: wanted, omittedFields: dropped, note: 'these issues are projected — ask again without `titlesOnly`/`fields` for the prose', }, } } /** * Author an issue — the unit of work. * * This is where reasoning becomes durable, and the only place a *fix* may be written: checks * never write one, enforced by test, because a fix needs the repo and the design intent that * a pure function over facts cannot have. Stored beside the facts it is about, in **this run's** * `global/issues.json`, citing fingerprints so a citation still resolves after a re-run. * * **A run is required.** It used to be optional — a missing run just meant no `target` stamp — * and that was the shape of the whole leak: an issue that belongs to no run belongs to every * run, so a homepage audit inherited work items for pages it never loaded. * * `defaultSeverity` is never overwritten, so what the check proposed and who moved it are * both always recoverable. That auditability is the condition on which overriding is allowed. * * **`cites` is optional.** An issue needs no finding behind it — "nit: this animation looks * wrong", with a Slack permalink in `links`, is a first-class issue. */ /** * The three refusals that depend on what an issue **cites**, applied to whatever record is about to be * stored. * * ## Extracted because a second write path skipped all of them * * These lived inline in the create path, so `patch` — which returns before reaching them — could store * a record none of them had seen: a severity moved with no `why`, a title `checkIssueRules` rejects, or * a title that is still the check's own, which is the one thing this layer exists to refuse. A rule that * only holds on the path it happens to be written on is not a rule, and the create path is not the only * way a stored issue comes into being. * * The presence checks on `title`, `type` and `where` stay at their call sites: they need no findings, and * refusing them before a run is resolved is what keeps a missing `type` from being reported as an * unreadable run. */ /** * Refuse a record the reader would refuse. **The write path validated nothing and the read path does.** * * `Issue` is built by hand at two sites here, saved without ever being parsed, and then parsed on the way * back out — so a field the schema rejects was accepted, written to disk, and reported as `saved` with an * id and a path, while every later read skipped it. Measured: a reviewer passed `type: "advice"` (a `kind` * value; `type` is `decision | code | content | config`) on six issues, got `11/11 succeeded`, and had 41 * files on disk against 35 issues in the tool's answer. `loadIssues` did say so — it returns * `"N of M issue files do not match the schema and were skipped"` — but a truthful error in a large payload * is not a substitute for refusing the write, and the reviewer noticed only because a coverage number * failed to move. * * Parsing the whole record rather than checking one field: this is the same hand-built-object hazard as * every other hop in this file, and the schema already knows every rule. */ function assertStorable(issue: Issue): void { const parsed = IssueSchema.safeParse(issue) if (parsed.success) return const detail = parsed.error.issues .map((i) => `\`${i.path.join('.') || '(root)'}\` ${i.message}`) .join('; ') throw new Error( `this issue would not be readable back and was not written — ${detail}. ` + 'Nothing was saved. (`type` is decision | code | content | config; `advice` is a `kind`, not a `type`.)', ) } /** * The findings a set of citations resolves to, for the run they belong to. * * A citation that resolves to nothing is **left out rather than refused** — `cites` is optional and a * run whose findings are not written yet is a real state. Callers report the unresolved ones; the rules * above only ever ask about the findings that do exist. * * `findingIdentities` rather than `f.id`, because a grouped finding answers to more than one id. */ async function citedBy(ctx: ToolContext, runId: string, cites: readonly string[]): Promise { return (await resolveCites(ctx, runId, cites)).findings } /** * The cited findings, **and the ids that named nothing**. * * The dropped ones used to be invisible: every miss was filtered out and the id stayed in `cites`, so an * issue could be stored citing evidence the run does not hold and every reader resolved it to nothing. A * measured arm wrote a blocker citing `f3D375d0e932` — a real finding's id with one character in the * wrong case — and three genuine citations beside it meant nothing looked wrong. * * `checked` is the other half and it is why this cannot simply throw. Mid-crawl a citation legitimately * names a finding not written yet, which is the case the old catch block was there for. When the * findings cannot be read there is nothing to be wrong against, so the caller must not refuse. */ async function resolveCites( ctx: ToolContext, runId: string, cites: readonly string[], ): Promise<{ findings: Finding[]; unresolved: string[]; checked: boolean }> { if (cites.length === 0) return { findings: [], unresolved: [], checked: true } let all: Finding[] try { all = (await ctx.store.readAllFindings(runId)).findings } catch { return { findings: [], unresolved: [], checked: false } } const findings: Finding[] = [] const unresolved: string[] = [] for (const findingId of cites) { const found = all.find((f) => findingIdentities(f).includes(findingId)) if (found) findings.push(found) else unresolved.push(findingId) } return { findings, unresolved, checked: all.length > 0 } } function assertIssueRulesHold(candidate: { title: string severity: Severity why?: string sharedLocation?: string /** The issue's `where`. Read only to honour an explicit "not localised" — see `declaresNoLocation`. */ where?: string cited: Finding[] /** `problem` + `why` + `fix`. Only the bundled-coverage rule reads it — see `checkIssueRules`. */ prose?: string }): void { /** * The check's own title is a placeholder, not an output. * * Refused rather than warned about. A CLI cannot make an agent think, but it can decline * to record the appearance of thinking — and an issue that merely restates the finding is * exactly the failure this layer exists to prevent. The message says what to do instead. */ const echoed = candidate.cited.find((f) => f.title.trim() === candidate.title.trim()) if (echoed) { throw new Error( `the title is still the check's own ("${echoed.title}"), which means the finding has not been ` + 'reasoned about. Say what the thing actually is — the evidence names it: read `evidence.htmlExcerpt`, ' + '`evidence.values.members` and `source.snippet`.', ) } /** * The grouping and prose rules. See `run/issue-rules.ts` for why each one exists. * * Refused together rather than one at a time: a caller fixing three problems in three * round-trips learns three unrelated lessons, and the second refusal reads as the tool moving * the goalposts. */ const violations = checkIssueRules({ title: candidate.title, cited: candidate.cited, ...(candidate.sharedLocation ? { sharedLocation: candidate.sharedLocation } : {}), // Read only to honour an explicit "not localised" — see `declaresNoLocation`. ...(candidate.where ? { where: candidate.where } : {}), ...(candidate.prose ? { prose: candidate.prose } : {}), }) /** * **Collected with the others rather than thrown after them, and that ordering was a real cost.** * * This ran as a second `throw` below the block above, so an issue breaking *both* rules only ever * heard about the first: fix the title, resend, and the severity refusal appears for the first time. * Measured while testing a one-shot repair pass — two of fourteen repaired issues came back refused * for a rule the original refusal had not mentioned, turning one repair call into two. A one-shot has * no turn to spare, and the comment below is explicit that a caller should not learn its lessons one * round trip at a time. * * `checkIssueRules` cannot own this one: it takes no severity and no `why`, and the severity a write * settles on is computed here from the cited finding's proposal. */ const proposed = candidate.cited[0]?.defaultSeverity if (proposed && candidate.severity !== proposed && !candidate.why?.trim()) { violations.push({ code: 'severity-no-why', message: `severity moves from ${proposed} to ${candidate.severity} — that needs \`why\`, or the override is ` + 'unreviewable. Say what makes this page different, or put the severity back to what the check proposed.', }) } if (violations.length > 0) { throw new Error( `this issue was not recorded — ${violations.length === 1 ? '' : `${violations.length} rules failed:\n\n`}` + violations.map((v) => `[${v.code}] ${v.message}`).join('\n\n'), ) } } export async function issueWrite( ctx: ToolContext, input: { title: string problem?: string why?: string fix?: string severity?: Severity kind?: FindingKind type?: IssueType where?: string cites?: string[] related?: string[] route?: string /** * Which report tab this belongs in. **Required when `cites` is empty and derived otherwise.** * * It was accepted by the MCP tool's schema, passed through the handler's spread, and then declared * nowhere here — so on a **create** it was dropped and on a `patch` it survived, because that path * merges whatever keys it is given. `tsc` cannot see it: an excess property arrives through a spread * and a key this interface does not name is simply not there. So the one field the schema documents * as *required when there are no citations* was silently unset on exactly the issues that need it, * and `classifyIssue` fell back to `bugs` with `classifiedBy: 'no citations and no category'` — the * same failure as the grouping field that put a site's worst blocker under "Everything else". */ category?: IssueCategory /** Reading order, higher first. Sparse — see `Issue.rank`. */ rank?: number origin?: IssueOrigin by?: string links?: { label: string; url: string }[] source?: { file: string; line?: number; component?: string; confidence?: 'certain' | 'likely' | 'needs-review' } /** * Assert that citations whose refs disagree really are one place, naming it. * * The documented escape from the grouping refusal, and deliberately **not** `where`: every * issue has a `where`, so accepting that as the override would make the refusal unreachable. * Recorded, and re-derived by `reportQuality()` so an unsupported claim is visible in the * artifact instead of being settled here. */ sharedLocation?: string runId?: string /** * Run every refusal and write nothing. * * Exists for batch authoring. A 25-issue batch executed one call at a time refused at #9, * then at #13, both for the same mistake — severity moved without `why` — which cost three * round trips for one class of error and left the store holding a partial set in between. * `qa mcp --batch` now dry-runs the whole file first and reports every refusal at once, so * the fix is one pass. * * It has to be a mode of this function rather than a copy of its rules: a validator that * duplicates the refusals is a validator that drifts out of agreement with them, and then * the batch passes and the write fails. */ dryRun?: boolean /** * Change some fields of an issue that already exists, by id, without re-sending the rest. * * **This exists because a full rewrite loses whatever the writer forgets, and the meta pass has to * rewrite issues it did not author.** `rank` is its one mandatory job and there was no way to set it * except reconstructing every field of somebody else's issue from `qa_issues` and writing it back — * five reviewers in one fan-out reported it, one lost a `sharedLocation` doing it, and it made *the * cheapest of the three meta jobs the riskiest to perform*. The same applies to `related`, which by * design can only be set after the issues it points at exist. * * Merges only the keys actually supplied, so an omitted field keeps its stored value rather than * being cleared — the opposite of the whole-record write, and the reason this is not just a * convenience. */ patch?: boolean /** The issue to patch. Required with `patch`, ignored without it — ids are derived, never chosen. */ id?: string }, ) { /** * ── patch mode ──────────────────────────────────────────────────────────────── * * Deliberately before the required-field checks: a patch supplies a delta, so demanding `title`, * `type` and `where` again would defeat the purpose. The stored record already satisfied them. */ if (input.patch) { if (!input.id?.trim()) throw new Error('patch needs the id of the issue to change') const runIdForPatch = await resolve(ctx, input.runId) const store = await loadIssues(ctx.store.issuesPath(runIdForPatch), ctx.store.storage) const existing = store.issues.find((i) => i.id === input.id) if (!existing) { throw new Error( `no issue ${input.id} in ${runIdForPatch} — patch changes an issue that exists, it does not create one`, ) } /** * **What derives the id is refused; what does not is allowed** (see `issueId`). * * `cites` and `route` always feed the id. `title` feeds it **only when `cites` is empty** — the * discriminator is the sorted citation list when there is one and `title|…` when there is not. * * Refusing `title` unconditionally was wrong in the common direction: a cited issue's id does not * move with its title, so renaming one was safe and the tool refused it anyway, on grounds that * were true for the uncited case alone. A reviewer took the refusal's own advice — write it again * under the new title, then delete the old id — and because the id had never changed, the write * replaced the record in place and the delete then removed the replacement. Success was reported * at every step and the count still looked right. */ const identity = (['cites', 'route'] as const).filter((k) => input[k] !== undefined) const titleIsIdentity = (existing.cites ?? []).length === 0 && input.title !== undefined if (identity.length > 0 || titleIsIdentity) { const fields = [...identity, ...(titleIsIdentity ? (['title'] as const) : [])] throw new Error( `patch cannot change ${fields.map((k) => `\`${k}\``).join(', ')} — ${ titleIsIdentity ? 'this issue cites nothing, so its title is what derives the id. ' : '' }they derive the id, so changing them makes a different issue. Write the new one and ` + '`qa_issue_delete` this one — in that order, because the new title mints a new id and the ' + 'delete takes the old one.', ) } const merged: Issue = { ...existing } for (const [k, v] of Object.entries(input)) { if (v === undefined) continue if (k === 'patch' || k === 'id' || k === 'runId' || k === 'dryRun' || k === 'store' || k === 'dashboard') continue ;(merged as unknown as Record)[k] = v } /** * **The merged record faces the same refusals a written one does.** * * This path returned before every one of them, so a patch was the way around the rules rather than * a lighter form of the same write: `severity` could move with no `why`, leaving an override nobody * can review, and `checkIssueRules` never saw the result. The record is judged, not the delta — * the stored fields are as much part of what gets validated as the supplied ones. * * `where` is re-checked because a patch can empty it, and "one fix, in one place" is only checkable * while that field says something. */ if (!(merged.sharedLocation ?? merged.where ?? '').trim()) { throw new Error( 'this patch would leave the issue with no `where` — the single place the change happens. An ' + 'explicit refusal in words is information; an empty field is not.', ) } assertIssueRulesHold({ title: merged.title, severity: merged.severity, cited: await citedBy(ctx, runIdForPatch, merged.cites), ...(merged.why ? { why: merged.why } : {}), ...(merged.sharedLocation ? { sharedLocation: merged.sharedLocation } : {}), ...(merged.where ? { where: merged.where } : {}), prose: [merged.problem, merged.why, merged.fix].filter(Boolean).join(' · '), }) /* Before the dry-run return, or a dry run reports "would succeed" for a record the write refuses. */ assertStorable(merged) /* * `replaced: false` on both patch branches so every shape this function returns carries it. * A patch edits a record that already exists, which is not the id collision `replaced` reports, and * a caller reading the flag off one shape and `undefined` off another would take the omission for a * `false` it never asserted — the same reasoning the coverage counters below are uniform for. */ if (input.dryRun) return { dryRun: true, patched: existing.id, would: Object.keys(input).length, replaced: false } const saved = await saveIssue(merged, ctx.store.issuesPath(runIdForPatch), ctx.store.storage) /* * The same counters a create returns. A patch can move `kind`, which moves a finding between the * defect and note halves of the stop test — and a caller reading `routeDefectsUncited` off one write * shape and `undefined` off the other would take the omission for a zero. */ return { runId: runIdForPatch, id: merged.id, patched: true, replaced: false, path: saved.path, total: saved.issues.length, ...(await coverageAfterWrite(ctx, runIdForPatch, merged, saved.issues)), } } if (!input.title?.trim()) throw new Error('an issue needs a title — it is the unit of work') /** * `type` and `where` are required here while being optional in the schema. * * The schema has to keep loading the records written before these fields existed — dropping a * recorded decision is the data loss this project treats as worse than a visible gap, and * `target` carries the same concession. But nothing *new* may arrive without them: `type` * decides who the ticket goes to, and `where` is what makes "one fix, in one place" checkable. * Defaulting either would be a guess in the one field a lead routes work by. */ if (!input.type) { throw new Error( 'an issue needs a `type` — who does the work and what kind of change it is. ' + '`decision` (a human must choose before anything can start), `code` (a developer edits a ' + 'file), `content` (an editor changes a CMS document), `config` (one line in a config, a ' + 'dashboard or an env var). This is the axis the work list is grouped by, so it cannot be ' + 'inferred from the category — contrast failing in a component is code, contrast failing ' + 'because an editor picked a pale colour is content.', ) } if (!input.where?.trim()) { throw new Error( 'an issue needs a `where` — the single place the change happens: `components/ui/book/index.tsx:174`, ' + '`Sanity → navbar → items[3]`, `next.config.ts headers()`. If you cannot name one, say so in ' + 'words here ("not localised: the six failures are in six unrelated components") — an explicit ' + 'refusal is information and an empty field is not. If naming it is hard because there are two ' + 'places, this is two issues.', ) } const cites = input.cites ?? [] /** * Which run this issue is about. Resolved first, because it decides where the issue is * stored — an unresolvable run is a refusal rather than a fallback to somewhere global. */ const runId = await resolve(ctx, input.runId) const resolved = await resolveCites(ctx, runId, cites) const citedFindings = resolved.findings /* * **Refused before anything else looks at the citations.** An id naming no finding is evidence the run * does not hold, and the rest of this function derives `category`, `severity` and the location check * from what resolved — so a silent miss quietly changes all three as well as the record. * * Only when the findings could be read and are non-empty. See `resolveCites`. */ if (resolved.checked && resolved.unresolved.length > 0) { throw new Error( `this issue was not recorded — [cites-unresolved] ${resolved.unresolved.length === 1 ? 'a citation names' : 'citations name'} ` + `no finding in this run: ${resolved.unresolved.map((id) => `\`${id}\``).join(', ')}. ` + 'Finding ids are lowercase hex and are copied, never composed — check the case and the digits ' + 'against the brief. If the evidence is real but the id is not in this run, the issue belongs to ' + 'whichever run measured it; if there is no finding behind it, write it with `cites: []`, which is ' + 'first-class and says you found it by looking.', ) } const proposed = citedFindings[0]?.defaultSeverity const severity = input.severity ?? proposed ?? 'major' /* The same gate the patch path runs — see `assertIssueRulesHold`. */ assertIssueRulesHold({ title: input.title, severity, cited: citedFindings, ...(input.why ? { why: input.why } : {}), ...(input.sharedLocation ? { sharedLocation: input.sharedLocation } : {}), ...(input.where ? { where: input.where } : {}), prose: [input.problem, input.why, input.fix].filter(Boolean).join(' · '), }) const origin = input.origin ?? 'agent' const issue: Issue = { id: issueId({ cites, title: input.title, ...(input.route ? { route: input.route } : {}) }), title: input.title.trim(), severity, kind: input.kind ?? 'defect', type: input.type, /** * `sharedLocation` wins over `where` when both are given: it is the more specific claim, and * it is the one that was checked. */ where: (input.sharedLocation ?? input.where ?? '').trim(), /* Kept as well as folded, so a read-modify-write does not lose the override — see the schema. */ ...(input.sharedLocation ? { sharedLocation: input.sharedLocation.trim() } : {}), cites, related: input.related ?? [], links: input.links ?? [], origin, by: input.by ?? (origin === 'human' ? 'human' : 'agent'), at: new Date().toISOString(), ...(input.problem ? { problem: input.problem } : {}), ...(input.why ? { why: input.why } : {}), ...(input.fix ? { fix: input.fix } : {}), ...(input.route ? { route: input.route } : {}), ...(input.category ? { category: input.category } : {}), /** * Was accepted by the MCP tool schema and then dropped here, because this object is built * The fourth field to need adding to this literal by hand, and the note above * explains why that keeps happening. `rank: 0` is a legitimate value, so this tests for * `undefined` rather than truthiness — a `?? {}` on a falsy-but-real number is the other * half of the same class of bug. */ ...(input.rank !== undefined ? { rank: input.rank } : {}), ...(input.source ? { source: { ...input.source, // An agent that read the file may claim `certain`; the heuristic mapper never can. confidence: input.source.confidence ?? ('certain' as const), }, } : {}), } /** * **The last refusal, and it has to be above the dry run rather than below it.** * * `--batch` sells "writes nothing if any one would be refused" and validates by calling this with * `dryRun: true`. With the schema check below the early return, a bad record passed the dry run and * was then refused at the write — so a 25-call batch reported five failures with twenty already * applied, which is the one outcome the guarantee exists to rule out. Measured on a real review. */ assertStorable(issue) /** * **What this write is about to overwrite, by name — because an id is derived, not chosen.** * * `issueId` hashes `cites` (sorted, joined) and `route`, falling back to the title *only* when an * issue cites nothing. So two issues citing the same finding on the same route are the **same id**, * and the second write silently replaces the first. Measured on a real meta pass: it filed a new * issue citing an existing finding and destroyed an unrelated one, noticed only because it re-read * the list afterwards and restored the victim by hand. * * `replaced: true` was already returned and was not enough — a bare boolean in a large response says * *something* was there, not *what you just deleted*. The title is what makes it recoverable, and the * dry run reports it too, which is the whole point of validating first. */ const priorTitle = (await loadIssues(ctx.store.issuesPath(runId), ctx.store.storage)).issues.find( (i) => i.id === issue.id, )?.title const collision = priorTitle && priorTitle !== issue.title ? { replacedTitle: priorTitle, replacedWarning: `This ${input.dryRun ? 'would overwrite' : 'OVERWROTE'} a different issue with the same id: "${priorTitle}". ` + 'An id is derived from its citations and route, not from its title, so two issues citing the same ' + 'finding on the same route collide. If that was not intended, re-file this one citing nothing (it ' + 'then keys on its title) and restore the other.', } : {} // Every refusal above has run by now, so this is the last point at which nothing has been // written. A dry run stops here and reports the issue it *would* have saved. if (input.dryRun) { return { saved: issue, dryRun: true, replaced: Boolean(priorTitle), ...collision, issueCount: 0, runId, // The file the write would land in, which is what the same field means on a real write. path: issueFilePath(ctx.store.issuesPath(runId), issue.id), citedTitles: [], unresolvedCitations: [], note: 'Validated only — nothing was written.', } } // Inside the run, not beside it. An issue is the output of reading this run's findings, so // it belongs to this run and to no other — see `ARTIFACT_LAYOUT.issues`. // Through the store's backend — see the note in `issues()`. The default is the filesystem, which on // a read-only mirror would write somewhere nothing reads instead of being refused at the seam. const { replaced, issues, path } = await saveIssue(issue, ctx.store.issuesPath(runId), ctx.store.storage) return { saved: issue, replaced, ...collision, /** * **Run-wide, and it says so now.** Under a fan-out this moves because *other* shards wrote, so a * caller watching it learns nothing about its own slice — the counters below are the ones that are * about the issue just written. */ issueCount: issues.length, runId, path, citedTitles: citedFindings.map((f) => f.title), unresolvedCitations: cites.filter((id) => !citedFindings.some((f) => f.id === id)), checkProposed: proposed, ...(await coverageAfterWrite(ctx, runId, issue, issues)), note: `Stored in run ${runId} and applied by qa_findings and qa report immediately. \`defaultSeverity\` is ` + 'preserved, so the override stays visible as "was X, now Y (by whom)". This issue belongs to this run: ' + 'the next run measures the site again and gets its own review. Use `qa diff` to ask what changed between them.', } } /** * The written issue's own slice, counted after the write — a shard's stop test, in the response. * * ## Why it is here and not left to `qa_issues` * * A shard's completion signal is three integers, and reading them cost a whole call: **36 of 579 tool * calls across fifteen reviewers were `qa_issues` asked for nothing else**, each answering with twelve * issues, nineteen `sharedCitations` and eighteen other routes' notes. The write is where the shard * already is and it already holds the post-write issue list, so the only thing it lacked was the * findings. * * **Counters, not the names.** `routeUncitedCheckIds` and the note list are the *next* thing a shard * wants once a counter stalls above zero, and they are also 20 entries that would land in the late * turns of all 151 writes and be re-sent on every turn after. So the numbers ride along and the names * stay one call away — which is what `stillToCover` says out loud, because a caller that does not know * the names exist will re-derive them by hand. * * **A run with nothing to count gets no numbers and a sentence saying why**, and getting that condition * right is the whole of it. `readAllFindings` does not throw on a run whose findings are not written — * it falls back to the per-page files and returns `{ findings: [], partial: true }`. So the obvious * `try`/`catch` here left a live crawl reporting `routeDefectsUncited: 0` beside *"nothing left uncited * on /about"*, which is the false *"your route is covered"* this guard exists to prevent, on the run * where it is most likely to be believed. **Zero findings is the condition, not a thrown error.** */ async function coverageAfterWrite( ctx: ToolContext, runId: string, issue: Pick, after: readonly Issue[], ) { const slice: Slice = issue.route ? { route: issue.route } : { siteOnly: true } const unavailable = (why: string) => ({ scope: sliceLabel(slice), routeCoverageUnavailable: `${why} so this run cannot yet say how much of ${sliceLabel(slice)} is covered. The issue is written. ` + 'Ask again once the crawl has passed this route — an absent number here is not a zero.', }) let read: Awaited> try { read = await ctx.store.readAllFindings(runId) } catch (e) { return unavailable(`${runId} could not be read (${e instanceof Error ? e.message : String(e)}),`) } if (read.findings.length === 0) return unavailable(`${runId} holds no findings yet,`) const { routeUncitedCheckIds, routeUncitedFindingIds, routeUncitedNotes, routeNamedListsTruncated, ...counters } = sliceCoverage(read.findings, after, slice) return { scope: sliceLabel(slice), ...counters, routeIssueCount: issuesOnSlice(after, slice).length, /** * Stated when the run is still going, because these counters are then a **floor** on a moving set. * The cross-page collapse has not run, so a finding that will become one site-level record still * counts once per route here — and the id it will collapse under does not exist yet. */ ...(read.partial ? { countersArePartial: 'This run has not finished, so these are counted over the per-page findings written so far. ' + 'The cross-page collapse happens at the end and mints new ids, so both numbers can move ' + 'without anybody reviewing anything.', } : {}), stillToCover: counters.routeDefectsUncited === 0 && counters.routeNotesUncited === 0 ? `Nothing left uncited on ${sliceLabel(slice)}. \`issueCount\` above is the whole run and moves when other reviewers write.` : `${counters.routeDefectsUncited} defect(s) and ${counters.routeNotesUncited} note(s) on ${sliceLabel(slice)} are cited by no issue. ` + '`qa_issues { runId, route }` (or `siteOnly: true`) names them — they are withheld here because 20 names ' + 'on every write is a cost paid on every later turn, and the counters are the stop test.', } } /** * The sites a run is allowed to fetch from — the one under review, and nothing else. * * ## Why this is a hard boundary and not a warning * * `qa_fetch` is the first tool in this server that reaches the network, and the URL arrives **from a * client**. That is the same class of boundary as `qa_screenshot`'s path, which `RunStore` validates * against the run directory because "findings files are data" — here the data is a URL and the risk is * the tool being pointed somewhere it has no business being. `CLAUDE.md`'s guardrail for the filesystem * is *never scan the user's filesystem; ask rather than guess*; this is its network twin. * * The target and every page's `url`, because a crawl can be seeded with more than one. Compared by * **site** rather than origin — see `fetchableSite` for the apex-versus-`www` case that forces it. */ function allowedSites(manifest: RunManifest): Set { const sites = new Set() const add = (raw: string | undefined): void => { const site = raw ? fetchableSite(raw) : undefined if (site) sites.add(site) } add(manifest.target.url) for (const page of manifest.pages) add(page.url) return sites } /** * `qa_fetch` — look at one URL, and leave the answer in the run. * * ## The number this exists to move * * **`Bash` was the largest tool category in a measured fan-out: 208 of 579 calls.** The half of it that * is genuine verification produced evidence that went nowhere — four of one reviewer's twelve issues * rest on `curl` output nobody can re-verify, and one of them asserts `max-age=0` on 3.4MB of `/public` * against a run holding no trace of it. So a reader three weeks later cannot check the claim, and * `qa diff` cannot tell them whether it was fixed. * * Three things follow from recording it instead: an issue can **cite evidence a reader can verify**; a * future check becomes a pure function over `facts.fetched` and **replays under `qa recheck`**; and it * displaces most of the 12 `chrome:evaluate_script` calls, which were mostly asking a contended shared * browser for something an HTTP response already knows. * * ## It writes, so it never takes `dashboard` * * Same rule as `qa_issue_write`: Postgres is a read model the next `qa push` overwrites, so a record * written there would be lost silently. Enforced by this function simply not having the parameter, * which is stronger than a check. * * ## `headersOnly` is the default and it is not a HEAD * * See `fetchResource`. One `GET`, stream cancelled when the body is not wanted — because a HEAD-first * strategy needs a fallback anyway (CDNs answer 405/501 while serving `GET` perfectly) and doubles the * requests. `CLAUDE.md` lists that exact design among the mechanisms this project encoded before * observing. */ export async function fetchUrl( ctx: ToolContext, input: { url: string /** Read the body too — needed for `canonical` and for real byte counts. Off by default. */ body?: boolean /** The route being reviewed, so the record is attributable and reaches that page's checks. */ route?: string by?: string runId?: string timeoutMs?: number maxBytes?: number /** Characters of the body to keep in the run. The whole text comes back either way. */ excerptChars?: number }, ) { const runId = await resolve(ctx, input.runId) const manifest = await ctx.store.readManifest(runId) const allowed = allowedSites(manifest) const want = fetchableSite(input.url) if (!want) { throw new Error( `qa_fetch needs an absolute http(s) URL and got ${JSON.stringify(input.url)}. A path alone is ` + `ambiguous and a non-http scheme is not a fetch of the site under review. This run measured ` + `${[...allowed].join(', ')}.`, ) } if (!allowed.has(want)) { /* * Refused by name, with the allowance stated. A silent refusal or an empty answer would read as * "there is nothing there", which is the failure mode this repo rates worst. */ throw new Error( `qa_fetch is scoped to the site under review: ${want} is not a site of ${runId}, which measured ` + `${[...allowed].join(', ')}. Apex, www and first-party subdomains are all allowed; a third party ` + 'is not, so a URL from somewhere else is a mistake in the call rather than a limit to work around. ' + 'If the third party genuinely matters, say so in the issue and cite what the run already holds ' + 'about it — `qa_facts` sections `network` and `console` carry every request the page made.', ) } const outcome = await fetchResource(input.url, { body: input.body ?? false, ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), ...(input.maxBytes !== undefined ? { maxBytes: input.maxBytes } : {}), ...(input.excerptChars !== undefined ? { excerptChars: input.excerptChars } : {}), }) /* * `body` is handed back and not stored; `bodyExcerpt` is what persists. Destructured here rather than * deleted afterwards so the split is visible at the one place both halves are in scope. */ const { body, ...stored } = outcome const record: FetchedResource = { ...stored, id: fetchedId({ url: input.url, bodyRead: outcome.bodyRead }), fetchedAt: new Date().toISOString(), ...(input.route ? { route: input.route } : {}), ...(input.by ? { by: input.by } : {}), } /* `store.storage` explicitly — see the note in `issues()`; the default is the filesystem. */ const saved = await saveFetched(record, ctx.store.runDir(runId), ctx.store.storage) return { runId, fetched: record, /** * The body, for the caller to work with **now** — not stored, and that is the split. * * A reviewer fetched a `.md` endpoint looking for the placeholder body four measured runs name as * their only blocker, and got a byte count with nothing to read: the tool counted 13,417 bytes and * discarded them. So this returns the text, while `fetched.bodyExcerpt` is the bounded trace that * persists for a reader to check the citation against. Absent when the body was not read, and when * the response was not textual — decoding a font into UTF-8 would return mojibake and call it * evidence. */ ...(body !== undefined ? { body } : {}), path: saved.path, replaced: saved.replaced, totalFetched: saved.total, /* * Said rather than left to be noticed. A reader seeing no `canonical` on a headers-only fetch * would otherwise have two readings — the page declares none, or nobody looked — and those are * the two this codebase keeps having to separate. */ ...(outcome.bodyRead ? /* * The cap, said out loud when it bit. `body` above is whole, so the reader is not missing * anything now — but the record they cite is shorter than what they read, and a stored excerpt * that ends mid-document reads to the next reader as a document that ends there. */ record.bodyExcerptOf !== undefined ? { bodyNote: `\`body\` above is the whole ${record.bodyExcerptOf}-character response. What was STORED is ` + `the first ${record.bodyExcerpt?.length ?? 0} characters of it, which is what a later reader ` + 'can check a citation against — quote from within that range, or re-fetch with a larger ' + '`excerptChars` if the evidence sits past it.', } : {} : { bodyNote: 'Headers only, so `bytes`, `body` and `canonical` are absent because nothing read them — not ' + 'because the response had none. `contentLength` is what the server claimed. Pass `body: true` ' + 'to read it, which is what you need to see a placeholder body or a sitemap-s entries.', }), note: `Recorded in ${runId} at global/fetched/, so an issue can cite this and the next reader can check it. ` + 'It is not part of the page facts: a fetch taken after the crawl carries its own `fetchedAt`. ' + 'A check over `facts.fetched` replays under `qa recheck`, which is what a curl in a terminal can never do.', } } /** * Retract an issue. * * `issueId` derives from `(cites, title, route)`, so **revising** a conclusion mints a new record * and leaves the old one in the store — counted, rendered, and shaping the headline. Splitting one * wrong issue into six right ones used to leave seven, and the only remedies were hand-editing a * file that is a deliverable or letting a correction sit beside the thing it contradicts. * * The reason is required, for the same purpose a waiver's is: an issue that vanished with no * account of why is indistinguishable from one nobody ever wrote. */ export async function issueDelete( ctx: ToolContext, input: { id: string; reason: string; runId?: string }, ) { if (!input.reason?.trim()) { throw new Error( 'retracting an issue needs a reason — "split into six per-component issues", "the finding was ' + 'a false positive". Without one, a retracted issue is indistinguishable from one nobody wrote.', ) } const runId = await resolve(ctx, input.runId) const { deleted, issues, path } = await deleteIssue(input.id, ctx.store.issuesPath(runId), ctx.store.storage) return { deleted: deleted ?? null, found: Boolean(deleted), reason: input.reason, issueCount: issues.length, runId, path, note: deleted ? 'Removed outright rather than flagged. A retracted-but-present issue has to be honoured by every reader — counts, tallies, report, exit code — and one missed call site turns it back into a live one.' : 'No issue with that id. Nothing changed; retracting something already gone is the state you asked for.', } } /** * `qa_set_finished` — record that the review of a run is over. * * ## The one write in this file that does not address the local artifact * * `onStore`'s note says writes never take a `StoreChoice` because Postgres is a read model the next * `qa push` overwrites, so recording a judgement there would lose it silently. That reasoning is exactly * why this one is safe to send there: **`finished` is not in the artifact and no push regenerates it.** * It exists only as a column on `run_index`, `qa push` never writes it, and this is the only thing that * sets it true. Two writers, disjoint columns — `0004_run_finished.sql` has the argument. * * The local store is still what says *which* run and *which* store label, derived exactly as `qa push` * and `qa finish` derive it, so a machine that pushes from `.qa-native` cannot finish `.qa`. * * ## Imported lazily, for the reason `mirrorStore` gives * * `database-url.ts` shells out to the Vercel CLI and `neon.ts` pulls `@neondatabase/serverless`. Neither * belongs in the import graph of a stdio server that is usually only going to read the filesystem, and * `./http` loads this module under webpack where `Bun` does not exist. */ export async function setFinished( ctx: ToolContext, input: { runId?: string; label?: string } = {}, ) { const runId = await resolve(ctx, input.runId) const { resolveDatabaseUrl, describeAttempts } = await import('@basementstudio/qa-engine/run/database-url') const { setRunFinished } = await import('@basementstudio/qa-engine/run/neon') const { defaultStoreLabel } = await import('@basementstudio/qa-engine/run') /* * **The server's own connection first.** Re-resolving through the environment ladder meant this tool * could write to a different database than every read tool on the same server was reading — see * `ToolContext.databaseUrl`. The ladder stays as the fallback for a host that never had one. */ const url = ctx.databaseUrl ?? (await resolveDatabaseUrl({}))?.url if (!url) { throw new Error( `no database, so there is nowhere to record this. every place it looked:\n${describeAttempts().join('\n')}\n` + 'the usual fix is `vercel login`.', ) } const label = input.label ?? defaultStoreLabel(ctx.store.storeRoot) const result = await setRunFinished({ url, store: label, runId }) if (!result.ok) { /* * Thrown rather than returned as `{ ok: false }`. The caller believes the run is published and * final and it is neither, and a tool result an agent has to inspect for a failure field is one it * will read as success. `qa_issue_delete` returns a soft "nothing to do" because retracting an * absent issue *is* the requested state; this is not — nothing was recorded. */ throw new Error( `${runId} has no row in ${label}, so there is nothing to mark final. Push it first: \`qa push ${runId}\`.`, ) } /** * The local marker goes too, exactly as `qa finish` does it — **the two twins must leave one state.** * * `qa finish` clears `global/in-flight` after the column write and this did not, so an agent * following `SKILL.md` (which names this the MCP twin) left the marker on disk forever: every local * `qa report` of that run kept the orange band, and `listProjects` never picked it as the project's * latest because `readFinished` kept answering `false`. Nothing else clears it. * * After the column, and swallowed: the ordering is what makes a failed column write leave the run * reading as unfinished in both places rather than in neither. */ await clearInFlightLocally(ctx, runId) return { runId, store: label, finished: true, note: 'The snapshot stops saying "still being reviewed". Push again afterwards only if you changed something — this wrote one column and uploaded nothing.', } } /** * Clear `global/in-flight` on **disk**, whatever backend this server happens to be reading through. * * ## The marker is a file, and `ctx.store` is not always a filesystem * * Under `--mirror`/`--db` the context store is `NeonRunStorage`, whose `writeText` and `remove` throw by * contract — the seam is the only thing enforcing that the mirror is a read model. So * `ctx.store.clearInFlight()` threw, the `.catch(() => {})` discarded it, and the column was recorded * while its local twin was not: `qa report` on that machine kept the *still being reviewed* band on a * run the dashboard showed as final, with nothing reporting the disagreement. `finished` is the one * thing that exists in both places, so it is the one thing that has to be written to both. * * ## The fallback is bounded by the folder actually being here * * A mirror-backed server may be running nowhere near the machine that crawled, in which case there is * no marker to clear and inventing a path to write into is the mistake `resolveStore` exists to prevent * (`neon:.qa` is a label, not a directory). So the local store is only consulted when the run's own * directory is present, and the default root is the one `qa finish` uses with no `--store`. * * Silent throughout, deliberately: the column is what a reader acts on, and a marker that could not be * cleared must not fail a recorded judgement. */ async function clearInFlightLocally(ctx: ToolContext, runId: string): Promise { /* The ordinary stdio case — the context store already addresses the run's directory. */ try { await ctx.store.clearInFlight(runId) return } catch { /* Falls through: either the seam refused the write, or the run is not under this store. */ } try { const local = new RunStore() if (await local.storage.isDirectory(local.runDir(runId))) await local.clearInFlight(runId) } catch { /* No local copy, or nothing writable. The column is recorded either way. */ } } function countBy(findings: Finding[]): Record { const counts: Record = {} for (const f of findings) counts[f.severity] = (counts[f.severity] ?? 0) + 1 // Ordered blocker-first so the object reads correctly when serialised. return Object.fromEntries( Object.entries(counts).sort( (a, b) => SEVERITY_ORDER[a[0] as Severity] - SEVERITY_ORDER[b[0] as Severity], ), ) } function sum(values: number[]): number { return values.reduce((a, b) => a + b, 0) } function mimeFor(path: string): string { if (path.endsWith('.webp')) return 'image/webp' if (path.endsWith('.png')) return 'image/png' if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg' return 'application/octet-stream' } /** * The finding and artifact contract, as data. * * Lives here rather than inline in `server.ts` so `qa mcp qa_schema` can answer the same * question as the MCP tool. A contract description that only one transport can reach is a * contract half the callers cannot read. */ export function schemaPayload() { return { schemaVersion: SCHEMA_VERSION, kind: { values: ['defect', 'policy', 'advice', 'transparency', 'ungraded'], note: 'What response is needed. **Orthogonal to `severity`, which says how urgent** — a `policy` can be a `blocker` and sorts and displays like one, because "which document is the homepage" is a decision and can be a critical one. Only `defect` counts and only `defect` gates the exit code, so a blocking decision leads the work list without turning the run red. Notes are counted separately everywhere: "17 nits" where five were "could not be checked" is worse than no count. `ungraded` alone is pinned to `info` — the measurement was never taken, so there is nothing to be urgent about yet.', defect: 'Something is wrong. The default, so an omitted kind never downgrades a real problem.', policy: 'More than one answer is valid; a human decides. Blocking or allowing AI crawlers are both defensible — not deciding is the failure.', advice: 'An opinionated recommendation where doing nothing is legitimate. The line against `policy` is obligation: `policy` means a decision is required and the site is defaulting into one, `advice` means nobody is wrong either way. Never gates. It is still **work about the site**, so it sits in the work list at its own severity rather than among the notes — the bottom tier describes nothing if the things that belong in it are filed elsewhere.', transparency: 'You checked and found nothing wrong, or you are recording how the measurement was taken so the rest can be trusted. A hidden consent overlay belongs here. **Leaves the work list on this field alone** and collapses into a `CHECKED AND CLEAN` box — nothing reads the sentence to decide that, so a coverage gap filed under this kind is rendered as a verification.', ungraded: 'Could not be evaluated. Never a pass and never a failure. **Leaves the work list on this field alone** and stays open below it, because an unmeasured thing is not a passing one — which is the opposite place from `transparency`, and the two are told apart by this field and never by their prose.', }, severity: { values: ['blocker', 'major', 'minor', 'nit'], note: 'How urgent. Ranked, never aggregated — there is no composite score and no go/no-go verdict, by explicit decision. `defaultSeverity` is what the check proposed and `severitySource` records who changed it. The four values render as four named tiers: `blocker` = BLOCKER, `major` = MAJOR, `nit` = MINOR, `info` = NIT. **`info` is the fourth tier, not a place for things nobody judged** — a measurement never taken is `kind: "ungraded"`, so every value of severity means how urgent. **The axis is truthfulness, not magnitude**: `blocker` is the site asserting something false about itself or a feature that matters being definitively non-functional; `major` is a cost you can put a number on or total failure for a small population, with nothing the site says being false; `nit` is wrong against a rule with something already absorbing it; `info` is a default nobody chose. A large number never promotes past `major`, and a dated future failure is `major` because nothing is wrong today.', }, gating: 'Exit code 3 means at least one unwaived blocking *defect*. A waived blocker does not gate, and a note never gates whatever its severity says.', confidence: { values: ['certain', 'likely', 'needs-review'], note: '`certain` is a DOM measurement or an HTTP fact. `needs-review` is a vision or inference judgement that should be confirmed before anyone files a ticket.', }, findingId: 'A stable fingerprint over checkId + route + normalised selector + a discriminator. Origin is deliberately excluded, so a waiver made against a preview still applies on production.', suggestion: 'Never written by a check. Checks report facts; reasoning needs repo and project context a pure function does not have. Filling it in is the job of the orchestrator, via qa_issue_write — it lands here as the `fix` on an issue.', issue: { what: 'A unit of work, authored by you or a human. A finding is a record of a rule firing; one issue may cite any set of findings across checks and pages, which is the real shape of "these are all one problem".', cites: 'OPTIONAL. An issue needs no finding behind it — a nit with a Slack link is first-class.', origin: 'check | agent | human | slack. `slack` is a #review comment arriving as data, with a permalink in `links`.', reviewed: 'An issue still carrying the title a check wrote has not been reviewed, and the report says so per issue. A default title is a placeholder, not an output.', scope: 'PER RUN. An issue lives in the run it was authored against and never carries into another. So every run needs its own review pass, and yesterday\'s write-ups do not come along — deliberately: a redeploy on the same commit can change env vars and fix things, so a re-stamped conclusion is an assertion nobody re-measured. Ask what changed with `qa diff`, which answers it on purpose and can say which findings are unchanged.', }, interpretation: { outputs: 'Issues are the OUTPUT of reading a run, and live inside it at global/issues/.json. Nothing merges them across runs. A pre-split global/issues.json and a pre-rename global/triage.json in the same directory are still read and converted, so no recorded decision is lost.', inputs: 'Waivers (.qa/waivers/, one file per fingerprint) and RunConfig severityOverrides/kindOverrides are INPUTS and live outside runs, because a decision to accept something has to survive a re-run. They are the only interpretation a crawl applies to itself.', precedence: 'project-config < agent < human, and slack ranks with human — a person judged it, over a different transport. Applied lowest-authority first, so someone who looked at the page outranks a model that reasoned about a selector.', note: 'defaultSeverity is never overwritten, so what the check proposed is always recoverable alongside who moved it.', kindOverrides: 'RunConfig.kindOverrides maps a checkId prefix to a kind, longest prefix wins — the same mechanism severityOverrides uses, so a whole check can move into `advice` per project.', }, facts: { sweep: 'The per-page weight sweep is at `summary.sweep`, and the prose version at `summary.sweepBriefing` — NOT at the top level of the qa_facts response. Reading the top level returns undefined, which reads as "no sweep exists" and has already sent one review off to recompute it by hand.', networkBytes: 'A request in `network.requests` carries its transfer size as **`encodedBytes`**. There is no `transferSize` and no `bytes` — reaching for either returns undefined, which arithmetic turns into 0 rather than an error, so a whole page reads as weighing nothing. Cross-check any byte total against `summary.sweep.totalBytes`.', networkFields: 'url, method, resourceType, thirdParty, host, status, mimeType, encodedBytes, contentEncoding, cacheControl, fromCache, durationMs, beforeFirstPaint, afterScroll.', scroll: 'The crawl scrolls each page to the bottom before reading it, and `summary.scroll` says how far that got. `stoppedBy` is `bottom` when the page was fully travelled and `steps`, `budget` or `stuck` when it was not — on those, every number about the page is a floor. `summary.sweep.aboveFold` is what loaded before the pass began, beside the whole-page total: two different questions, so say which one you are quoting. Both are ABSENT, never zero, on a run recorded before the pass existed — there the totals are the first screen and nothing said so. Nothing reaches content behind a click, a tab or a hover on any run.', servedDocument: 'The bytes the server sent are at `summary.document`, and they answer what a live DOM read cannot: whether markup was server-rendered or produced by hydration. The body itself is NOT stored — measured at 15–224% of a page\'s facts.json — so `bytes` and `hash` are what you compare between runs, and there is no way to read the HTML back out of the artifact. ABSENT means the run predates the collector; present with `notCollected` means Chrome had already dropped the body from its buffer. Neither is "the document was empty", and a page can be measured either way while every other fact about it is intact.', warmCache: '`fromCache: true` requests report 0 encoded bytes because nothing crossed the wire, so `font 0B` is a cache hit and not a missing font. One browser session serves every page in a run, but the HTTP cache is emptied before each navigation, so per-page totals ARE comparable and each one is what a first-time visitor downloads. A page recorded before that landed is warm from page two onwards and its totals exclude the shared bundle; `errors` carries a caveat when the reset itself failed.', }, artifactLayout: { 'run.json': 'manifest: identity, config, page list, live status', 'pages//facts.json': 'raw collected facts', 'pages//findings.json': 'page findings plus the site-level ones affecting this route', 'pages//findings.md': 'written the moment the page finishes, before the run ends', 'pages//shots/': 'full-page captures for humans, f- crops for vision', 'global/findings.{json,md}': 'the whole run, deduped with waivers applied, composed last', 'global/issues/.json': 'this run\'s work list, one file per issue, written by qa_issue_write AFTER the sweep. Empty means nobody reviewed this run. One file each so several reviewers can write concurrently without overwriting each other; a run recorded before the split has a single global/issues.json, still read and converted on the first write', }, waivers: '.qa/waivers/.json, outside runs so they survive across them — the only interpretation that does. One file each because the store is shared by every run, so concurrent waives must not overwrite one another. A waived finding is always still reported.', } }