@jphutchins/code-review 0.1.0-alpha.7 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cost.ts","../src/patch.ts","../src/surface.ts","../src/render.ts","../src/diff.ts","../src/inline.ts","../src/schema.ts","../src/validate.ts","../src/format.ts","../src/registry.ts","../src/gh.ts","../src/pr.ts","../src/post.ts","../src/gather.ts","../src/extract.ts","../src/adapt.ts","../src/stop-gate.ts","../src/index.ts"],"names":["Eta","key","resolvePath","resolve","readFileSync","reviewUrl","execFile","t2","scanLine","t3","writeFileSync"],"mappings":";;;;;;;;;;;;AA0BA,IAAM,WAAA,GAAoB,CAAC,OAAA,KAAY;AACrC,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,OAAO;AAAA,CAAI,CAAA;AACrC,CAAA;AAEA,IAAM,gBAAA,GAAmB,CAAC,KAAA,EAAwB,MAAA,EAAkB,IAAA,KAAyB;AAC3F,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA;AACnC,EAAA,MAAM,SAAA,GAAY,MAAM,iBAAA,IAAqB,CAAA;AAC7C,EAAA,MAAM,UAAA,GAAa,MAAM,kBAAA,IAAsB,CAAA;AAC/C,EAAA,IAAI,CAAC,CAAA,EAAG;AACN,IAAA,IAAA;AAAA,MACE,CAAA,iCAAA,EAAoC,MAAM,KAAK,CAAA,6DAAA;AAAA,KACjD;AACA,IAAA,OAAO;AAAA,MACL,OAAO,KAAA,CAAM,KAAA;AAAA,MACb,aAAa,KAAA,CAAM,YAAA;AAAA,MACnB,cAAc,KAAA,CAAM,aAAA;AAAA,MACpB,eAAA,EAAiB,SAAA;AAAA,MACjB,gBAAA,EAAkB,UAAA;AAAA,MAClB,OAAA,EAAS;AAAA,KACX;AAAA,EACF;AACA,EA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AAA;AAAA,MAC/C,kBAAA,EAAoB,yBAAA,CAA0B,IAAA,CAAK,iBAAiB,CAAC,CAAA;AAAA,MACrE,OAAO,IAAA,CAAK,KAAA;AAAA,MACZ,UAAA,EAAY,KAAK,aAAa,CAAA;AAAA,MAC9B,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,cAAA,EAAgB,KAAK,aAAa,CAAA;AAAA,MAClC,MAAA,EAAQ,KAAK,SAAS,CAAA;AAAA,MACtB,OAAA,EAAS,KAAK,UAAU;AAAA,KACzB,CAAA;AAAA,EACH;AACF,CAAC,CAAA;AAEM,IAAM,OAAO,aAAA,CAAc;AAAA,EAChC,IAAA,EAAM;AAAA,IACJ,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS,cAAA;AAAA,IACT,WAAA,EACE;AAAA,GACJ;AAAA,EACA,WAAA,EAAa;AAAA,IACX,MAAA,EAAQ,SAAA;AAAA,IACR,MAAA,EAAQ,SAAA;AAAA,IACR,MAAA,EAAQ,SAAA;AAAA,IACR,IAAA,EAAM,OAAA;AAAA,IACN,IAAA,EAAM,OAAA;AAAA,IACN,QAAA,EAAU,WAAA;AAAA,IACV,KAAA,EAAO,QAAA;AAAA,IACP,OAAA,EAAS,UAAA;AAAA,IACT,kBAAA,EAAoB,kBAAA;AAAA,IACpB,cAAA,EAAgB,cAAA;AAAA,IAChB,WAAA,EAAa;AAAA;AAEjB,CAAC;AAGD,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC1B,EAAA,MAAM,QAAQ,IAAI,CAAA;AACpB","file":"index.js","sourcesContent":["// Pure cost computation from the abstract envelope's `models` array + price map.\n// Recomputes USD because the CLI's vendor_cost_usd is vendor-priced (SPEC §6.2).\n// Pure core: side effects (unknown-model warnings) are threaded via a `warn` callback.\n\nimport type { PriceMap, ModelUsageEntry } from \"./schema.js\";\n\nexport interface CostLine {\n readonly model: string;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly cacheReadTokens: number;\n readonly cacheWriteTokens: number;\n readonly costUSD: number;\n}\n\nexport interface CostReport {\n readonly lines: readonly CostLine[];\n readonly totalInputTokens: number;\n readonly totalOutputTokens: number;\n readonly totalCacheReadTokens: number;\n readonly totalCacheWriteTokens: number;\n readonly totalCostUSD: number;\n}\n\nexport type Warn = (message: string) => void;\n\nconst defaultWarn: Warn = (message) => {\n process.stderr.write(`${message}\\n`);\n};\n\nconst computeModelCost = (entry: ModelUsageEntry, prices: PriceMap, warn: Warn): CostLine => {\n const p = prices.models[entry.model];\n const cacheRead = entry.cache_read_tokens ?? 0;\n const cacheWrite = entry.cache_write_tokens ?? 0;\n if (!p) {\n warn(\n `code-review cost: unknown model \"${entry.model}\" — no entry in price map; cost for this model set to $0`,\n );\n return {\n model: entry.model,\n inputTokens: entry.input_tokens,\n outputTokens: entry.output_tokens,\n cacheReadTokens: cacheRead,\n cacheWriteTokens: cacheWrite,\n costUSD: 0,\n };\n }\n const costUSD =\n (entry.input_tokens * p.in +\n entry.output_tokens * p.out +\n cacheRead * p.cache_read +\n cacheWrite * p.cache_write) /\n 1_000_000;\n return {\n model: entry.model,\n inputTokens: entry.input_tokens,\n outputTokens: entry.output_tokens,\n cacheReadTokens: cacheRead,\n cacheWriteTokens: cacheWrite,\n costUSD,\n };\n};\n\n/** Recompute cost from the envelope's `models` array against a price map. Pure given a `warn` sink. */\nexport const computeCost = (\n models: readonly ModelUsageEntry[],\n prices: PriceMap,\n warn: Warn = defaultWarn,\n): CostReport => {\n const lines = models.map((entry) => computeModelCost(entry, prices, warn));\n\n return {\n lines,\n totalInputTokens: lines.reduce((s, l) => s + l.inputTokens, 0),\n totalOutputTokens: lines.reduce((s, l) => s + l.outputTokens, 0),\n totalCacheReadTokens: lines.reduce((s, l) => s + l.cacheReadTokens, 0),\n totalCacheWriteTokens: lines.reduce((s, l) => s + l.cacheWriteTokens, 0),\n totalCostUSD: lines.reduce((s, l) => s + l.costUSD, 0),\n };\n};\n","// Pure patch helpers (issue #10): a review agent's own unified-diff patch of an edit it actually\n// made is either validated against the real PR-head file (to align a finding's range and confirm it\n// still applies) or projected into a GitHub suggestion's replacement text — two concerns split into\n// two pure functions over one shared hunk parser (SSOT). Eliminates the bad-suggestion bug class\n// caused by hand-authored suggestions with wrong indentation or too-wide ranges. Assumes LF line\n// endings (the review runs on Linux); CRLF handling is out of scope.\n\n/** The file-anchored range a patch's removed lines occupy — what a suggestion replaces. */\nexport type ValidateResult =\n | { readonly startLine: number; readonly endLine: number }\n | { readonly kind: \"drop\"; readonly reason: string };\n\n/** The replacement text a patch's added lines carry — a suggestion's body. */\nexport type SuggestionResult = string | { readonly kind: \"drop\"; readonly reason: string };\n\ntype BodyLine =\n | { readonly kind: \"context\"; readonly text: string }\n | { readonly kind: \"removed\"; readonly text: string }\n | { readonly kind: \"added\"; readonly text: string };\n\nconst HUNK_HEADER_RE = /^@@ -(\\d+)(?:,\\d+)? \\+\\d+(?:,\\d+)? @@/;\n\n/** The hunk's `-a` value when `line` is a hunk header, else null. */\nconst hunkOldStart = (line: string): number | null => {\n const raw = HUNK_HEADER_RE.exec(line)?.[1];\n return raw !== undefined ? Number(raw) : null;\n};\n\n/** Classify one hunk-body line by its leading marker char, stripping it; null when the line\n * carries none of the three markers (malformed). */\nconst classifyBodyLine = (line: string): BodyLine | null => {\n if (line.startsWith(\" \")) return { kind: \"context\", text: line.slice(1) };\n if (line.startsWith(\"-\")) return { kind: \"removed\", text: line.slice(1) };\n if (line.startsWith(\"+\")) return { kind: \"added\", text: line.slice(1) };\n return null;\n};\n\n/** The maximal run of non-context lines in the middle of `body`, once leading and trailing context\n * is trimmed — empty when `body` is all context (no change at all). */\nconst trimmedMiddle = (body: readonly BodyLine[]): readonly BodyLine[] => {\n const first = body.findIndex((l) => l.kind !== \"context\");\n if (first === -1) return [];\n const last = body.findLastIndex((l) => l.kind !== \"context\");\n return body.slice(first, last + 1);\n};\n\n/** True when `middle` (already trimmed of outer context) is zero-or-more removed lines followed by\n * zero-or-more added lines, with no context and no interleaving between them. */\nconst isContiguousChange = (middle: readonly BodyLine[]): boolean => {\n if (middle.some((l) => l.kind === \"context\")) return false;\n const firstAdded = middle.findIndex((l) => l.kind === \"added\");\n if (firstAdded === -1) return true;\n return (\n middle.slice(0, firstAdded).every((l) => l.kind === \"removed\") &&\n middle.slice(firstAdded).every((l) => l.kind === \"added\")\n );\n};\n\ninterface RemovedRange {\n readonly lineNumber: number;\n readonly firstRemoved: number | null;\n readonly lastRemoved: number | null;\n}\n\n/** Fold over the hunk body tracking the old-side line number (advanced by context and removed\n * lines, not by added lines), recording the first and last removed line's number. */\nconst removedRange = (body: readonly BodyLine[], oldStart: number): RemovedRange =>\n body.reduce<RemovedRange>(\n (acc, line) =>\n line.kind === \"added\"\n ? acc\n : {\n lineNumber: acc.lineNumber + 1,\n firstRemoved:\n line.kind === \"removed\" && acc.firstRemoved === null\n ? acc.lineNumber\n : acc.firstRemoved,\n lastRemoved: line.kind === \"removed\" ? acc.lineNumber : acc.lastRemoved,\n },\n { lineNumber: oldStart, firstRemoved: null, lastRemoved: null },\n );\n\nconst drop = (reason: string): { readonly kind: \"drop\"; readonly reason: string } => ({\n kind: \"drop\",\n reason,\n});\n\ntype ParsedHunk =\n | { readonly kind: \"ok\"; readonly oldStart: number; readonly body: readonly BodyLine[] }\n | { readonly kind: \"drop\"; readonly reason: string };\n\n/** Parse a single-hunk unified diff into its old-side start line + classified body — the SSOT both\n * `validatePatch` and `patchToSuggestion` share. Drops on !=1 hunk or a malformed body line. */\nconst parseHunk = (patch: string): ParsedHunk => {\n const rawLines = patch.split(\"\\n\");\n // A trailing newline in the patch text splits into a trailing \"\" element — not a line of content.\n const lines =\n rawLines.length > 0 && rawLines[rawLines.length - 1] === \"\" ? rawLines.slice(0, -1) : rawLines;\n\n const headerHits = lines.reduce<readonly { readonly index: number; readonly oldStart: number }[]>(\n (acc, line, index) => {\n const oldStart = hunkOldStart(line);\n return oldStart !== null ? [...acc, { index, oldStart }] : acc;\n },\n [],\n );\n if (headerHits.length !== 1) {\n return drop(`expected exactly one hunk, got ${String(headerHits.length)}`);\n }\n const hit = headerHits[0];\n if (hit === undefined) return drop(\"malformed hunk header\");\n\n // Header-preceding lines (diff --git/index/---/+++) are never examined — the hunk body starts\n // right after the header; a trailing \"\\" marker carries no content.\n const bodyRaw = lines.slice(hit.index + 1).filter((line) => !line.startsWith(\"\\\\\"));\n const classified = bodyRaw.map(classifyBodyLine);\n if (classified.some((line) => line === null)) return drop(\"malformed hunk body line\");\n const body = classified.filter((line): line is BodyLine => line !== null);\n\n return { kind: \"ok\", oldStart: hit.oldStart, body };\n};\n\n/** The issue-#10 guard: confirm a single-hunk unified diff still applies to the PR-head file\n * (`fileLines`, 0-indexed lines WITHOUT trailing newlines) and return the exact\n * `start_line..end_line` its removed lines occupy — for aligning the finding's range. Drops on a\n * context mismatch, a non-contiguous change, or a change with no removed lines to anchor. Pure. */\nexport const validatePatch = (patch: string, fileLines: readonly string[]): ValidateResult => {\n const parsed = parseHunk(patch);\n if (parsed.kind === \"drop\") return parsed;\n const { oldStart, body } = parsed;\n\n const oldSideTexts = body.filter((l) => l.kind !== \"added\").map((l) => l.text);\n const expected = fileLines.slice(oldStart - 1, oldStart - 1 + oldSideTexts.length);\n const oldSideMatches =\n expected.length === oldSideTexts.length &&\n expected.every((line, i) => line === oldSideTexts[i]);\n if (!oldSideMatches) {\n return drop(\n `patch context does not match the file at lines ${String(oldStart)}..${String(oldStart + oldSideTexts.length - 1)}`,\n );\n }\n\n if (!isContiguousChange(trimmedMiddle(body))) {\n return drop(\"change is not a single contiguous block\");\n }\n\n const removedCount = body.filter((l) => l.kind === \"removed\").length;\n const addedCount = body.filter((l) => l.kind === \"added\").length;\n if (removedCount === 0 && addedCount === 0) return drop(\"hunk contains no changes\");\n if (removedCount === 0) return drop(\"pure insertion has no range to anchor a suggestion\");\n\n const { firstRemoved, lastRemoved } = removedRange(body, oldStart);\n if (firstRemoved === null || lastRemoved === null) return drop(\"malformed hunk body\");\n\n return { startLine: firstRemoved, endLine: lastRemoved };\n};\n\n/** Project a single-hunk unified diff into a GitHub suggestion's replacement text (the added lines\n * alone) — no file needed. Drops a multi-hunk/malformed patch, a non-contiguous change, or a pure\n * insertion (nothing to replace). An all-deletion hunk yields \"\" (delete the range). Pure. */\nexport const patchToSuggestion = (patch: string): SuggestionResult => {\n const parsed = parseHunk(patch);\n if (parsed.kind === \"drop\") return parsed;\n const { body } = parsed;\n\n if (!isContiguousChange(trimmedMiddle(body))) {\n return drop(\"change is not a single contiguous block\");\n }\n\n const removedCount = body.filter((l) => l.kind === \"removed\").length;\n const addedLines = body.filter((l) => l.kind === \"added\");\n if (removedCount === 0 && addedLines.length === 0) return drop(\"hunk contains no changes\");\n if (removedCount === 0) return drop(\"pure insertion can't be expressed as a suggestion\");\n\n return addedLines.map((l) => l.text).join(\"\\n\");\n};\n","// Shared render-surface primitives — the single source of truth for the bits every render surface\n// (sticky, inline comment, review body) must agree on: the severity→emoji mapping, the\n// machine-readable findings-json pointer (issue #19), and the patch→suggestion projection. Pure.\n\nimport type { Findings } from \"./schema.js\";\nimport { patchToSuggestion } from \"./patch.js\";\n\n/** Severity → emoji, used by every render surface (sticky, inline, strays). */\nexport const severityEmoji = (s: string): string => {\n switch (s) {\n case \"critical\":\n return \"🔴\";\n case \"major\":\n return \"🟠\";\n case \"minor\":\n return \"🔵\";\n case \"nit\":\n return \"⚪\";\n default:\n return \"❓\";\n }\n};\n\n/** Base64 chars (~30KB JSON); keeps a comment well under GitHub's 65536-char comment limit. */\nconst EMBED_LIMIT = 40000;\n\n/** The directive that makes the marker below self-describing to a reviewing agent — travels with\n * the marker on every surface so a reader who only sees one comment still knows to decode it. */\nconst AGENTS_STOP_DIRECTIVE =\n \"<!-- AGENTS: STOP — do not parse the prose below; decode this findings JSON and read schema_version first. -->\";\n\n/** The machine-readable findings-json marker (issue #19), identical on every surface: embeds\n * `findings` as base64 when it fits under `limit`, falls back to a `jsonUrl` link marker, or\n * omits the marker entirely when neither is available. */\nexport const findingsPointer = (\n findings: Findings,\n jsonUrl: string | undefined,\n limit = EMBED_LIMIT,\n): string => {\n const b64 = Buffer.from(JSON.stringify(findings), \"utf-8\").toString(\"base64\");\n const marker =\n b64.length <= limit\n ? `<!-- code-review:findings-json;base64 ${b64} -->`\n : jsonUrl\n ? `<!-- code-review:findings-json ${jsonUrl} -->`\n : \"\";\n return marker ? `${AGENTS_STOP_DIRECTIVE}\\n${marker}` : \"\";\n};\n\n/** Escape triple-backtick sequences so fenced content can't break out of its block. */\nconst escapeFence = (text: string): string => text.replace(/```/g, \"`` ` ``\");\n\n/** How a finding's `patch` renders on a surface (JP's core design): a GitHub ```suggestion when the\n * patch lowers to replacement text (anchored at the finding's already-aligned range), a raw\n * ```patch fallback when it can't lower (non-lossy — the diff still reaches the reader), or nothing\n * when the finding carries no patch. Fenced content is backtick-escaped against breakout. */\nexport type PatchProjection =\n | { readonly kind: \"suggestion\"; readonly text: string }\n | { readonly kind: \"patch\"; readonly raw: string }\n | { readonly kind: \"none\" };\n\n/** Project a finding's `patch` into a template-ready {@link PatchProjection}. Pure. */\nexport const projectPatch = (patch: string | null | undefined): PatchProjection => {\n if (patch === null || patch === undefined) return { kind: \"none\" };\n const lowered = patchToSuggestion(patch);\n return typeof lowered === \"string\"\n ? { kind: \"suggestion\", text: escapeFence(lowered) }\n : { kind: \"patch\", raw: escapeFence(patch) };\n};\n","// Deterministic comment renderer. Takes findings + envelope + prices → comment markdown.\n// Uses Eta templates; pure data-in, string-out — no side effects, no model invocation.\n\nimport { Eta } from \"eta\";\nimport type { Finding, Severity } from \"./schema.js\";\nimport type { RenderInput, SeverityCounts } from \"./types.js\";\nimport { computeCost } from \"./cost.js\";\nimport { severityEmoji, findingsPointer, projectPatch } from \"./surface.js\";\nimport type { PatchProjection } from \"./surface.js\";\n\n/** Escape pipe characters so they don't break markdown table columns. */\nconst escapePipes = (text: string): string => text.replace(/\\|/g, \"\\\\|\");\n\n/** Replace backticks so they don't break inline code spans. */\nconst escapeCodeBackticks = (text: string): string => text.replace(/`/g, \"-\");\n\n/** A stray finding with its sanitized fields plus its projected patch block for the strays list. */\ntype StrayView = Finding & { readonly patchProjection: PatchProjection };\n\n/** Sanitize a stray finding's fields and attach its patch projection for the strays section. */\nconst sanitizeFinding = (f: Finding): StrayView => ({\n ...f,\n title: escapePipes(f.title),\n path: escapeCodeBackticks(f.path),\n patchProjection: projectPatch(f.patch),\n});\n\nconst emptySeverityCounts = (): Record<Severity, number> => ({\n critical: 0,\n major: 0,\n minor: 0,\n nit: 0,\n});\n\n/** Tally findings by severity for the summary counts line. Ignores out-of-domain severities. */\nexport const computeSeverityCounts = (findings: readonly Finding[]): SeverityCounts =>\n findings.reduce<Record<Severity, number>>(\n (acc, f) => (f.severity in acc ? { ...acc, [f.severity]: acc[f.severity] + 1 } : acc),\n emptySeverityCounts(),\n );\n\n/** Render a code-review comment from findings, envelope, and prices. Pure. */\nexport const render = (input: RenderInput): string => {\n const eta = new Eta({ autoTrim: false });\n const usageAvailable = input.envelope !== null;\n const costReport = input.envelope ? computeCost(input.envelope.models, input.prices) : null;\n const pricesProvided = input.pricesProvided ?? true;\n const route = input.route ?? input.envelope?.route ?? null;\n const effort = input.effort ?? input.envelope?.effort ?? null;\n const modelNames = input.envelope ? input.envelope.models.map((m) => m.model).join(\", \") : \"\";\n\n return eta.renderString(input.template, {\n findings: input.findings,\n envelope: input.envelope,\n usageAvailable,\n costReport,\n pricesProvided,\n route,\n effort,\n modelNames,\n testReport: input.testReport ?? null,\n reviewedSha: input.reviewedSha ?? \"0000000000000000000000000000000000000000\",\n severityCounts: input.severityCounts ?? computeSeverityCounts(input.findings.findings),\n strays: (input.strays ?? []).map(sanitizeFinding),\n inlineDisposition: input.inlineDisposition ?? null,\n runUrl: input.runUrl ?? null,\n jsonUrl: input.jsonUrl ?? null,\n findingsPointer: input.findingsPointer ?? findingsPointer(input.findings, input.jsonUrl),\n reviewUrl: input.reviewUrl ?? null,\n formatTokens: (n: number): string =>\n Number.isFinite(n) && n >= 0 ? n.toLocaleString(\"en-US\") : \"—\",\n // Cost cells render N/A (never a false $0.00) when no real price map was provided — there are\n // real tokens spent, we simply have no rates to price them (SPEC §6.2).\n formatCost: (n: number): string =>\n !pricesProvided\n ? \"N/A\"\n : Number.isFinite(n)\n ? n > 0 && n.toFixed(2) === \"0.00\"\n ? \"<$0.01\"\n : `$${n.toFixed(2)}`\n : \"—\",\n formatDuration: (ms: number): string => {\n if (!Number.isFinite(ms) || ms < 0) return \"—\";\n const s = Math.round(ms / 1000);\n return s >= 60 ? `${String(Math.floor(s / 60))}m ${String(s % 60)}s` : `${String(s)}s`;\n },\n verdictBadge: (v: string): string => {\n switch (v) {\n case \"approve\":\n return \"✅ approved\";\n case \"comment\":\n return \"💬 comment\";\n case \"changes\":\n return \"🔧 changes requested\";\n default:\n return `❓ ${v}`;\n }\n },\n severityEmoji,\n });\n};\n","// Pure functions for unified-diff parsing and line-in-diff validation.\n// Uses parse-diff for parsing; exports only clean functional interfaces.\n\nimport parseDiff from \"parse-diff\";\nimport type { Finding, Side } from \"./schema.js\";\n\n// A set of \"path:line\" keys present in the diff hunks (additions/changes).\n// Used to validate findings before posting inline comments.\nexport type DiffLineIndex = ReadonlySet<string>;\n\nconst key = (path: string, line: number): string => `${path}:${String(line)}`;\n\n/** Index a set of changes under a given file path. */\nconst indexChanges = (\n keys: Set<string>,\n fpath: string,\n changes: ReadonlyArray<{\n readonly type: \"normal\" | \"add\" | \"del\";\n readonly ln1?: number;\n readonly ln2?: number;\n readonly ln?: number;\n }>,\n): void => {\n for (const change of changes) {\n if (change.type === \"normal\") {\n if (change.ln1 !== undefined) keys.add(key(fpath, change.ln1));\n if (change.ln2 !== undefined) keys.add(key(fpath, change.ln2));\n } else if (change.ln !== undefined) {\n keys.add(key(fpath, change.ln));\n }\n }\n};\n\n/** Parse a unified diff string into a set of \"path:line\" keys for every line in the diff.\n * For renamed files, both old and new paths are indexed so findings on either path match. */\nexport const indexDiff = (diff: string): DiffLineIndex => {\n const files = parseDiff(diff);\n if (!Array.isArray(files)) return new Set();\n\n const keys = new Set<string>();\n for (const file of files) {\n // Deleted: file.to is /dev/null, use file.from\n // New: file.from is undefined, use file.to\n // Modified: both set and equal\n // Renamed: both set and differ → index both paths\n const primary = file.from ?? file.to;\n if (!primary) continue;\n\n indexChanges(\n keys,\n primary,\n file.chunks.flatMap((c) => c.changes),\n );\n\n // Also index under file.to for renames (when both paths exist and differ)\n if (file.to && file.to !== \"/dev/null\" && file.to !== primary) {\n indexChanges(\n keys,\n file.to,\n file.chunks.flatMap((c) => c.changes),\n );\n }\n }\n return keys;\n};\n\n/** Check whether a finding's anchor line appears in the diff. */\nexport const isInDiff = (index: DiffLineIndex, path: string, line: number): boolean =>\n index.has(key(path, line));\n\n/** True for a diff with no content or no hunks — nothing to review or anchor inline comments to. */\nexport const isEmptyDiff = (diff: string): boolean => {\n if (diff.trim().length === 0) return true;\n const files = parseDiff(diff);\n return !Array.isArray(files) || files.length === 0 || files.every((f) => f.chunks.length === 0);\n};\n\n/** Default side for inline comments: RIGHT for additions, LEFT for deletions. */\nexport const defaultSide = (side: string | undefined): Side => (side === \"LEFT\" ? \"LEFT\" : \"RIGHT\");\n\n/** Partition findings into in-diff and out-of-diff (strays). Strays get demoted to the summary. */\nexport const partitionFindings = (\n findings: readonly Finding[],\n index: DiffLineIndex,\n): {\n readonly inDiff: readonly Finding[];\n readonly strays: readonly Finding[];\n} => {\n const inDiff: Finding[] = [];\n const strays: Finding[] = [];\n for (const f of findings) {\n if (isInDiff(index, f.path, f.start_line) && isInDiff(index, f.path, f.end_line)) {\n inDiff.push(f);\n } else {\n strays.push(f);\n }\n }\n return { inDiff, strays };\n};\n","// Inline review payload builder. Validates findings against the diff,\n// builds the GitHub reviews API comments[] array, and demotes strays.\n\nimport { Eta } from \"eta\";\nimport { partitionFindings, indexDiff, defaultSide } from \"./diff.js\";\nimport { severityEmoji, findingsPointer, projectPatch } from \"./surface.js\";\nimport type { Finding, Findings } from \"./schema.js\";\nimport type { InlineComment, InlineResult } from \"./types.js\";\n\n/** Backtick-wrapped, `/`-joined model names for the disclosure line (issue #16), falling back to\n * a plain phrase when no models are known. */\nconst formatModels = (models: readonly string[]): string =>\n models.length > 0 ? models.map((m) => `\\`${m}\\``).join(\"/\") : \"an AI model\";\n\n/** Render a finding's inline comment body via the inline Eta template (bundled by default — see\n * resolveInlineTemplatePath, index.ts). The template is the SSOT for all body text — severity\n * header, description, recommendation, the projected patch block, and the [!TIP] disclosure fold;\n * TS supplies only data. The patch is projected here (never a `suggestion` field — that field is\n * gone as of schema 0.4). */\nconst renderCommentBody = (\n f: Finding,\n eta: Eta,\n template: string,\n modelsText: string,\n jsonUrl: string | undefined,\n pointer: string,\n): string =>\n // Eta.renderString returns string | Promise<string>; with autoTrim:false it's always sync.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n eta.renderString(template, {\n ...f,\n patchProjection: projectPatch(f.patch),\n severityEmoji,\n modelsText,\n jsonUrl: jsonUrl ?? null,\n findingsPointer: pointer,\n }) as string;\n\n/** Extra context threaded into each inline comment beyond the finding itself. */\nexport interface InlineContext {\n /** Eta template for each comment's body — bundled by default (index.ts's\n * resolveInlineTemplatePath), overridable via --inline-template. */\n readonly inlineTemplate: string;\n /** Model name(s) that produced the review, for the template's disclosure line (issue #16). */\n readonly models?: readonly string[];\n /** Findings-json artifact URL — the marker's fallback when the embedded form is too large (#19). */\n readonly jsonUrl?: string;\n /** The full findings document, embedded (or pointed at) via the shared marker (#19); omitted\n * when the caller has no whole document to embed (the marker is then omitted too). */\n readonly findings?: Findings;\n /** Precomputed findings-json marker (#19) — when set, used verbatim instead of recomputing from\n * `findings`/`jsonUrl`, so `post()` base64-encodes the findings once and reuses it here. */\n readonly findingsPointer?: string;\n}\n\n/** Build the GitHub reviews API comments[] array from in-diff findings. Strays are demoted. */\nexport const buildInlineComments = (\n findings: readonly Finding[],\n diff: string,\n context: InlineContext,\n): InlineResult => {\n const { inlineTemplate, models = [], jsonUrl, findings: fullFindings } = context;\n const index = indexDiff(diff);\n const { inDiff, strays } = partitionFindings(findings, index);\n const eta = new Eta({ autoTrim: false });\n const modelsText = formatModels(models);\n const pointer =\n context.findingsPointer ?? (fullFindings ? findingsPointer(fullFindings, jsonUrl) : \"\");\n\n const comments: InlineComment[] = inDiff.map((f) => {\n const comment: InlineComment = {\n path: f.path,\n line: f.end_line,\n side: defaultSide(f.side),\n body: renderCommentBody(f, eta, inlineTemplate, modelsText, jsonUrl, pointer),\n };\n if (f.start_line < f.end_line) {\n return {\n ...comment,\n start_line: f.start_line,\n start_side: defaultSide(f.side),\n };\n }\n return comment;\n });\n\n return { comments, strays };\n};\n\n/** Render the demoted (stray) findings as a markdown section for the summary. */\nexport const renderStraysSection = (strays: readonly Finding[]): string => {\n if (strays.length === 0) return \"\";\n\n const items = strays.map(\n (f) => `- **${f.severity}** · \\`${f.path}:${String(f.start_line)}\\` — ${f.title}`,\n );\n\n return [\n \"\",\n \"---\",\n \"\",\n \"#### ⚠️ Findings on lines not in the diff (demoted to summary)\",\n \"\",\n ...items,\n ].join(\"\\n\");\n};\n","// io-ts codecs for de/serialization at the boundary.\n// These ARE the source of truth for the data shapes — types are materialized via t.TypeOf<>.\n// No hand-written DTO types exist elsewhere; import types from here.\n\nimport * as t from \"io-ts\";\n\nconst SeverityCodec = t.union([\n t.literal(\"critical\"),\n t.literal(\"major\"),\n t.literal(\"minor\"),\n t.literal(\"nit\"),\n]);\n\nconst SideCodec = t.union([t.literal(\"RIGHT\"), t.literal(\"LEFT\")]);\n\nconst VerdictCodec = t.union([t.literal(\"approve\"), t.literal(\"comment\"), t.literal(\"changes\")]);\n\nconst LineNumber = t.refinement(\n t.number,\n (n): n is number => Number.isInteger(n) && n >= 1,\n \"LineNumber\",\n);\n\nconst Confidence = t.refinement(t.number, (n): n is number => n >= 0 && n <= 1, \"Confidence\");\n\n// Mirrors findings.schema.json's `schema_version.pattern` exactly, so `resolve()` (registry.ts,\n// consumed by post.ts's §5.5 malformed-doc path) never accepts a value that ajv (validate.ts, the\n// extraction ladder's candidate gate) would reject — e.g. a truncated \"0.2\" or an over-long \"0.2.0.0\".\nconst SCHEMA_VERSION_RE =\n /^(0|[1-9]\\d*)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nconst SchemaVersion = t.refinement(\n t.string,\n (s): s is string => SCHEMA_VERSION_RE.test(s),\n \"SchemaVersion\",\n);\n\nconst FindingShape = t.intersection([\n t.type({\n path: t.string,\n start_line: LineNumber,\n end_line: LineNumber,\n severity: SeverityCodec,\n title: t.string,\n description: t.string,\n reasoning: t.string,\n confidence: Confidence,\n }),\n t.partial({\n side: SideCodec,\n code: t.string,\n code_url: t.string,\n recommendation: t.string,\n patch: t.union([t.string, t.null]),\n }),\n]);\n\nconst EndGeStart = t.refinement(\n FindingShape,\n (f): f is t.TypeOf<typeof FindingShape> => f.end_line >= f.start_line,\n \"EndGeStart\",\n);\n\nexport const FindingCodec = t.exact(EndGeStart);\n\nexport const FindingsCodec = t.exact(\n t.type({\n schema_version: SchemaVersion,\n summary: t.string,\n verdict: VerdictCodec,\n findings: t.array(FindingCodec),\n }),\n);\n\nexport const TriageCodec = t.type({\n safe: t.boolean,\n reasons: t.string,\n});\n\n// Abstract, vendor-neutral result envelope (SPEC §6.1) — not any adapter's native shape.\nconst TokenCount = t.refinement(\n t.number,\n (n): n is number => Number.isInteger(n) && n >= 0,\n \"TokenCount\",\n);\n\nexport const ModelUsageEntryCodec = t.intersection([\n t.type({\n model: t.string,\n input_tokens: TokenCount,\n output_tokens: TokenCount,\n }),\n t.partial({\n cache_read_tokens: TokenCount,\n cache_write_tokens: TokenCount,\n }),\n]);\n\nexport const ResultEnvelopeCodec = t.intersection([\n t.type({\n schema_version: t.string,\n findings: FindingsCodec,\n models: t.array(ModelUsageEntryCodec),\n turns: TokenCount,\n duration_ms: TokenCount,\n }),\n t.partial({\n vendor_cost_usd: t.union([t.number, t.null]),\n route: t.string,\n effort: t.string,\n }),\n]);\n\nexport const ModelPricesCodec = t.type({\n in: t.number,\n out: t.number,\n cache_read: t.number,\n cache_write: t.number,\n});\n\nexport const PriceMapCodec = t.type({\n _updated: t.string,\n _unit: t.string,\n models: t.record(t.string, ModelPricesCodec),\n});\n\n// Format-agnostic test summary (SPEC §5.1 item 4, REQ-CO-9) — any conforming test report shape.\nexport const TestFailureCodec = t.intersection([\n t.type({ name: t.string }),\n t.partial({ message: t.string }),\n]);\n\nexport const TestSummaryCodec = t.intersection([\n t.type({\n passed: t.number,\n failed: t.number,\n total: t.number,\n }),\n t.partial({\n failures: t.array(TestFailureCodec),\n }),\n]);\n\n// The supported-minor allowlist and version dispatch live in the registry (src/registry.ts),\n// which sources its findings entry's defaultVersion from this constant.\n/** Full semver used when an adapter's native output omits `schema_version` (SPEC §6.1). */\nexport const DEFAULT_SCHEMA_VERSION = \"0.4.0\";\n\nexport type Finding = t.TypeOf<typeof FindingCodec>;\nexport type Findings = t.TypeOf<typeof FindingsCodec>;\n\n/** A valid, empty-findings document carrying `summary` as its only content — the single shape used\n * for a sticky-only notice (post.ts, SPEC §5.5) and a \"did not complete\" degraded envelope\n * (adapt.ts, issue #18). Callers supply the fully-formatted markdown summary. */\nexport const noticeFindings = (summary: string): Findings => ({\n schema_version: DEFAULT_SCHEMA_VERSION,\n summary,\n verdict: \"comment\",\n findings: [],\n});\nexport type Triage = t.TypeOf<typeof TriageCodec>;\nexport type Severity = t.TypeOf<typeof SeverityCodec>;\nexport type Side = t.TypeOf<typeof SideCodec>;\nexport type Verdict = t.TypeOf<typeof VerdictCodec>;\nexport type ModelUsageEntry = t.TypeOf<typeof ModelUsageEntryCodec>;\nexport type ResultEnvelope = t.TypeOf<typeof ResultEnvelopeCodec>;\nexport type ModelPrices = t.TypeOf<typeof ModelPricesCodec>;\nexport type PriceMap = t.TypeOf<typeof PriceMapCodec>;\nexport type TestFailure = t.TypeOf<typeof TestFailureCodec>;\nexport type TestSummary = t.TypeOf<typeof TestSummaryCodec>;\n","// Schema validation wrapper. Validates findings JSON against the published schema.\n// Minor command — defense-in-depth; the CLI enforces the schema on the agent side already.\n\nimport { Ajv2020 } from \"ajv/dist/2020.js\";\nimport type { ValidateFunction as AjvValidateFunction } from \"ajv/dist/2020.js\";\nimport _addFormats from \"ajv-formats\";\nimport { readFileSync } from \"node:fs\";\nimport type { Either } from \"fp-ts/Either\";\nimport { FindingsCodec } from \"./schema.js\";\nimport type { Findings } from \"./schema.js\";\n\nconst addFormats = _addFormats as unknown as (ajv: Ajv2020) => void;\n\n/** Module-level cache of compiled validators keyed by schema path. */\nconst validatorCache = new Map<string, AjvValidateFunction>();\n\n/** Compile a JSON Schema validator from the given file path (cached). */\nconst compileSchema = (schemaPath: string): AjvValidateFunction => {\n const cached = validatorCache.get(schemaPath);\n if (cached) return cached;\n\n let schemaJson: string;\n try {\n schemaJson = readFileSync(schemaPath, \"utf-8\");\n } catch {\n throw new Error(`Cannot read schema file: ${schemaPath}`);\n }\n let schema: unknown;\n try {\n schema = JSON.parse(schemaJson);\n } catch {\n throw new Error(`Invalid JSON in schema file: ${schemaPath}`);\n }\n const ajv = new Ajv2020({ allErrors: true, strict: true });\n addFormats(ajv);\n const validator = ajv.compile(schema as Record<string, unknown>);\n validatorCache.set(schemaPath, validator);\n return validator;\n};\n\nexport interface ValidateResult {\n readonly valid: boolean;\n readonly errors: readonly string[];\n}\n\nexport const validateAgainstSchema = (findings: unknown, schemaPath: string): ValidateResult => {\n const validator = compileSchema(schemaPath);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- ajv returns boolean | Promise<unknown>\n const valid = validator(findings) as boolean;\n const errors: readonly string[] =\n valid || !validator.errors\n ? []\n : validator.errors.map((e) => `${e.instancePath} ${e.message ?? \"unknown error\"}`);\n return { valid, errors };\n};\n\n/** Extract the right value from an io-ts Either, or throw. */\nexport const unsafeUnwrap = <A>(decoded: Either<unknown, A>): A => {\n if (decoded._tag === \"Right\") return decoded.right;\n throw new Error(\"io-ts decode failed — data does not match expected shape\");\n};\n\n/** Decode findings, throwing on failure. */\nexport const decodeFindings = (data: unknown): Findings => unsafeUnwrap(FindingsCodec.decode(data));\n","// Conservative markdown formatting pass applied just before a comment/review body is posted.\n// Pure string transform: never reflows content, never touches fenced code blocks (a `suggestion`\n// block's blank lines and trailing whitespace are significant and must survive verbatim).\n\ninterface ScanState {\n readonly lines: readonly string[];\n readonly inFence: boolean;\n readonly blankRun: number;\n}\n\nconst FENCE_RE = /^\\s*```/;\n\nconst scanLine = (state: ScanState, line: string): ScanState => {\n if (FENCE_RE.test(line)) {\n return { lines: [...state.lines, line], inFence: !state.inFence, blankRun: 0 };\n }\n if (state.inFence) {\n return { lines: [...state.lines, line], inFence: true, blankRun: 0 };\n }\n const trimmed = line.replace(/[ \\t]+$/, \"\");\n if (trimmed !== \"\") {\n return { lines: [...state.lines, trimmed], inFence: false, blankRun: 0 };\n }\n const blankRun = state.blankRun + 1;\n return blankRun === 1\n ? { lines: [...state.lines, \"\"], inFence: false, blankRun }\n : { ...state, blankRun };\n};\n\n/** Trim trailing whitespace and collapse runs of 2+ blank lines to one — never to zero — leaving\n * exactly one trailing newline. Fenced (```) content passes through untouched. */\nexport const formatMarkdown = (md: string): string => {\n const { lines } = md\n .split(\"\\n\")\n .reduce<ScanState>(scanLine, { lines: [], inFence: false, blankRun: 0 });\n return `${lines.join(\"\\n\").replace(/\\n+$/, \"\")}\\n`;\n};\n","// Version-aware schema registry: maps each schema kind's supported major.minor(s) to a bundled\n// schema file, io-ts codec, and upcast normalizer (identity for every entry today). Findings is a\n// single current minor (0.4): the 0.4 shape REQUIRES `reasoning`/`confidence`, which cannot be\n// honestly upcast from a 0.2/0.3 document (a confidence score cannot be fabricated), so those older\n// minors are dropped from the table and now degrade to the §5.5 unsupported-version notice.\n// `resolve` is pure (no IO); `schemaPathFor` only computes a path string from the tables below.\n//\n// This module imports from schema.ts (codecs, DEFAULT_SCHEMA_VERSION), never the reverse — schema.ts\n// stays a dependency-free leaf so the registry can compose it without an import cycle.\n//\n// Bundled schema files resolve relative to the installed package exactly like index.ts's\n// bundledPath: tsup bundles this module into the same dist/index.js as index.ts, so\n// import.meta.dirname here resolves identically at runtime, in dev, and from the published package.\n\nimport { resolve as resolvePath } from \"node:path\";\nimport type { Decoder, Encoder, Errors, ValidationError } from \"io-ts\";\nimport { FindingsCodec, TriageCodec, PriceMapCodec, DEFAULT_SCHEMA_VERSION } from \"./schema.js\";\nimport type { Findings, Triage, PriceMap } from \"./schema.js\";\n\nexport type SchemaKind = \"findings\" | \"triage\" | \"prices\";\n\nexport interface DecodedFor {\n readonly findings: Findings;\n readonly triage: Triage;\n readonly prices: PriceMap;\n}\n\ninterface VersionEntry<K extends SchemaKind, A> {\n /** major.minor of `schema_version` this entry dispatches on; patch is ignored. */\n readonly minor: string;\n /** full semver stamped when a document omits `schema_version` (findings) or reported as the\n * resolved version for kinds with no in-data signal (triage, prices). */\n readonly defaultVersion: string;\n /** path relative to schema/: flat name for the latest entry, \"v<minor>/…\" once frozen. */\n readonly schemaFile: string;\n readonly codec: Decoder<unknown, A> & Encoder<A, unknown>;\n /** upcast to the latest shape for this kind; identity when the codec already accepts both\n * shapes (e.g. an additive minor whose new field is optional). */\n readonly normalize: (decoded: A) => DecodedFor[K];\n readonly latest: boolean;\n}\n\nexport type Resolution<K extends SchemaKind> =\n | { readonly kind: \"ok\"; readonly version: string; readonly value: DecodedFor[K] }\n | {\n readonly kind: \"unsupported-version\";\n readonly version: string;\n readonly supported: readonly string[];\n }\n | { readonly kind: \"invalid-shape\"; readonly errors: readonly string[] }\n | { readonly kind: \"missing-version\" }; // findings only; triage/prices never return this\n\nconst identity = <A>(decoded: A): A => decoded;\n\nconst findingsTable: readonly VersionEntry<\"findings\", Findings>[] = [\n {\n minor: \"0.4\",\n defaultVersion: DEFAULT_SCHEMA_VERSION,\n schemaFile: \"findings.schema.json\",\n codec: FindingsCodec,\n normalize: identity,\n latest: true,\n },\n];\n\nconst triageTable: readonly VersionEntry<\"triage\", Triage>[] = [\n {\n minor: \"0.1\",\n defaultVersion: \"0.1.0\",\n schemaFile: \"triage.schema.json\",\n codec: TriageCodec,\n normalize: identity,\n latest: true,\n },\n];\n\nconst pricesTable: readonly VersionEntry<\"prices\", PriceMap>[] = [\n {\n minor: \"0.1\",\n defaultVersion: \"0.1.0\",\n schemaFile: \"prices.schema.json\",\n codec: PriceMapCodec,\n normalize: identity,\n latest: true,\n },\n];\n\ntype Table<K extends SchemaKind> = readonly VersionEntry<K, DecodedFor[K]>[];\n\nconst tables: { readonly [K in SchemaKind]: Table<K> } = {\n findings: findingsTable,\n triage: triageTable,\n prices: pricesTable,\n};\n\nconst tableFor = <K extends SchemaKind>(kind: K): Table<K> => tables[kind];\n\n/** major.minor of a semver-ish string; dispatch ignores patch and any prerelease/build suffix. */\nconst majorMinor = (version: string): string => version.split(\".\").slice(0, 2).join(\".\");\n\nconst describeValidationError = (e: ValidationError): string => {\n const path = e.context\n .map((entry) => entry.key)\n .filter((key) => key.length > 0)\n .join(\".\");\n return e.message ?? `${path || \"(root)\"}: invalid value ${JSON.stringify(e.value)}`;\n};\n\nconst formatErrors = (errors: Errors): readonly string[] => errors.map(describeValidationError);\n\n/** The declared `schema_version` of a raw document, when present as a string. */\nexport const declaredVersion = (raw: unknown): string | undefined =>\n typeof raw === \"object\" && raw !== null && \"schema_version\" in raw\n ? typeof raw.schema_version === \"string\"\n ? raw.schema_version\n : undefined\n : undefined;\n\nexport const supportedVersions = (kind: SchemaKind): readonly string[] =>\n tableFor(kind).map((entry) => entry.minor);\n\nexport const defaultVersion = (kind: SchemaKind): string => {\n const latest = tableFor(kind).find((entry) => entry.latest);\n if (!latest) throw new Error(`Registry invariant violated — no latest entry for \"${kind}\"`);\n return latest.defaultVersion;\n};\n\nconst bundledSchemaPath = (relativePath: string): string =>\n resolvePath(import.meta.dirname, \"..\", \"schema\", relativePath);\n\n/** Resolve the bundled schema path for a kind + optional version; no version → flat latest file. */\nexport const schemaPathFor = (kind: SchemaKind, version?: string): string => {\n const table = tableFor(kind);\n const entry =\n version === undefined\n ? table.find((v) => v.latest)\n : table.find((v) => v.minor === majorMinor(version));\n if (!entry) {\n throw new Error(\n `Unsupported ${kind} schema version \"${version ?? \"\"}\" — supported: ${supportedVersions(kind).join(\", \")}`,\n );\n }\n return bundledSchemaPath(entry.schemaFile);\n};\n\nconst resolveFindings = (raw: unknown): Resolution<\"findings\"> => {\n const version = declaredVersion(raw);\n if (version === undefined) return { kind: \"missing-version\" };\n const entry = findingsTable.find((v) => v.minor === majorMinor(version));\n if (!entry) {\n return { kind: \"unsupported-version\", version, supported: supportedVersions(\"findings\") };\n }\n const decoded = entry.codec.decode(raw);\n return decoded._tag === \"Left\"\n ? { kind: \"invalid-shape\", errors: formatErrors(decoded.left) }\n : { kind: \"ok\", version, value: entry.normalize(decoded.right) };\n};\n\n/** Resolve a kind with no in-data version signal — a single bundled entry, never \"missing-version\". */\nconst resolveSingleVersion = <K extends \"triage\" | \"prices\">(\n kind: K,\n raw: unknown,\n): Resolution<K> => {\n const entry = tableFor(kind)[0];\n if (!entry) throw new Error(`Registry invariant violated — no entry for \"${kind}\"`);\n const decoded = entry.codec.decode(raw);\n return decoded._tag === \"Left\"\n ? { kind: \"invalid-shape\", errors: formatErrors(decoded.left) }\n : { kind: \"ok\", version: entry.defaultVersion, value: entry.normalize(decoded.right) };\n};\n\nconst resolvers: { readonly [K in SchemaKind]: (raw: unknown) => Resolution<K> } = {\n findings: resolveFindings,\n triage: (raw) => resolveSingleVersion(\"triage\", raw),\n prices: (raw) => resolveSingleVersion(\"prices\", raw),\n};\n\n/** Decode + version-dispatch a raw document for a schema kind. Pure — no IO. */\nexport const resolve = <K extends SchemaKind>(kind: K, raw: unknown): Resolution<K> =>\n resolvers[kind](raw);\n","// The `gh api` effect: the single shell boundary for GitHub API calls. Pure callers inject a\n// fake; the default implementation shells out to the `gh` CLI (auth via GH_TOKEN in the env).\n\nimport { execFile } from \"node:child_process\";\n\n/** Signature of the `gh api` effect. Default implementation shells out to the `gh` CLI. */\nexport type GhApi = (\n args: readonly string[],\n stdin?: string,\n env?: Readonly<Record<string, string>>,\n) => Promise<string>;\n\n/** Default effect: execFile gh. Extra `env` merges over process.env for this call only —\n * used to pass untrusted values (bot login, marker) to jq via `env.NAME`, never interpolated\n * into the filter text (SPEC §5.4). */\nexport const runGhApi: GhApi = (args, stdin, env) =>\n new Promise<string>((resolve, reject) => {\n const child = execFile(\n \"gh\",\n [\"api\", ...args],\n { env: { ...process.env, ...env }, encoding: \"utf-8\", maxBuffer: 100 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n const stderrStr = typeof stderr === \"string\" && stderr.trim() ? stderr.trim() : \"\";\n const errStr = err instanceof Error ? err.message : \"unknown error\";\n reject(new Error(`gh api failed: ${stderrStr || errStr}`));\n } else {\n resolve(stdout);\n }\n },\n );\n if (stdin !== undefined) {\n child.stdin?.end(stdin);\n }\n });\n","// PR resolution + diff fetch, shared by `post` (comment job) and `gather` (review job). Both jobs\n// resolve independently (separate runners), but from the SAME pure logic, so they never disagree on\n// which PR (SPEC §8.3 — avoid split-brain). PR resolution is a single read, never jq-interpolated.\n\nimport type { GhApi } from \"./gh.js\";\n\ninterface PrCandidate {\n readonly number: number;\n readonly state: string;\n readonly headRef: string;\n}\n\nexport const fetchPrCandidates = async (\n repo: string,\n headSha: string,\n ghApi: GhApi,\n): Promise<readonly PrCandidate[]> => {\n const stdout = await ghApi([\n `repos/${repo}/commits/${headSha}/pulls`,\n \"--jq\",\n \".[] | {number: .number, state: .state, headRef: .head.ref}\",\n ]);\n return stdout\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as PrCandidate);\n};\n\nexport type PrResolution =\n | { readonly kind: \"none\" }\n | { readonly kind: \"not-open\"; readonly prNumber: number; readonly state: string }\n | { readonly kind: \"open\"; readonly prNumber: number };\n\n/** Resolve which PR to act on. Disambiguates by head branch (pure); never shells out. */\nexport const resolvePr = (\n candidates: readonly PrCandidate[],\n headBranch: string | undefined,\n): PrResolution => {\n if (candidates.length === 0) return { kind: \"none\" };\n const scoped =\n candidates.length > 1 && headBranch\n ? candidates.filter((c) => c.headRef === headBranch)\n : candidates;\n const chosen = scoped[0] ?? candidates[0];\n if (chosen === undefined) return { kind: \"none\" };\n return chosen.state === \"open\"\n ? { kind: \"open\", prNumber: chosen.number }\n : { kind: \"not-open\", prNumber: chosen.number, state: chosen.state };\n};\n\nexport const fetchDiff = async (repo: string, prNumber: number, ghApi: GhApi): Promise<string> =>\n ghApi([\n `repos/${repo}/pulls/${String(prNumber)}`,\n \"-H\",\n \"Accept: application/vnd.github.v3.diff\",\n ]);\n","// Deterministic GH posting: resolve PR, fetch diff, run inline, post inline review,\n// render summary, upsert sticky comment. Pure core with a thin gh-api effect.\n//\n// Ordering (CO-R3): all reads, decodes, diff validation, and rendering complete before\n// the first API write; then the sticky is posted, and the inline review second. A posting\n// failure propagates and exits the process non-zero (never partially posts).\n\nimport { readFileSync } from \"node:fs\";\nimport type { InlineComment, InlineDisposition, RenderInput } from \"./types.js\";\nimport { buildInlineComments } from \"./inline.js\";\nimport { isEmptyDiff } from \"./diff.js\";\nimport { render, computeSeverityCounts } from \"./render.js\";\nimport { formatMarkdown } from \"./format.js\";\nimport { findingsPointer } from \"./surface.js\";\nimport { ResultEnvelopeCodec, PriceMapCodec, TestSummaryCodec, noticeFindings } from \"./schema.js\";\nimport type { Findings, ResultEnvelope, TestSummary } from \"./schema.js\";\nimport { resolve, supportedVersions } from \"./registry.js\";\nimport type { GhApi } from \"./gh.js\";\nimport { runGhApi } from \"./gh.js\";\nexport type { GhApi } from \"./gh.js\";\nimport { fetchDiff, fetchPrCandidates, resolvePr } from \"./pr.js\";\n\nexport interface PostInput {\n readonly repo: string;\n readonly headSha: string;\n readonly botLogin: string;\n readonly findingsPath: string;\n readonly envelopePath: string;\n readonly pricesPath: string;\n /** Whether `pricesPath` is a real caller-supplied price map or the bundled all-zero example\n * standing in for an absent one — threaded to the render layer so cost shows N/A, not a false\n * $0.00, when absent (SPEC §6.2). */\n readonly pricesProvided: boolean;\n readonly templatePath: string;\n readonly inlineTemplatePath: string;\n /** Overrides the envelope's route (SPEC §6.1) when set; otherwise the envelope is the source. */\n readonly route?: string;\n readonly headBranch?: string;\n readonly testReportPath?: string;\n readonly effort?: string;\n /** Workflow run URL, threaded into the sticky's LLM Disclosure aside (SPEC §5.1 item 6). */\n readonly runUrl?: string;\n /** Findings-json artifact URL — the marker's fallback on every surface (sticky, each inline\n * comment, and the review body itself) when the embedded form is too large (SPEC §5.1 item 7,\n * §5.2, issue #19). */\n readonly jsonUrl?: string;\n}\n\nconst DEFAULT_MARKER = \"<!-- code-review -->\";\nconst MAX_SUGGESTION_LINES = 10;\n\n/** Count lines in a suggestion string (empty suggestion \"\" = 1 line — delete range). */\nconst countSuggestionLines = (text: string): number => text.split(\"\\n\").length;\n\n/** Extract and check suggestion blocks in a comment body, stripping those that are too long. */\nconst checkLongSuggestions = (\n comments: readonly InlineComment[],\n): { readonly comments: readonly InlineComment[]; readonly longFiles: readonly string[] } => {\n const longFiles: string[] = [];\n const adjusted = comments.map((c) => {\n const match = /```suggestion\\n([\\s\\S]*?)\\n```/.exec(c.body);\n if (match?.[1] && countSuggestionLines(match[1]) > MAX_SUGGESTION_LINES) {\n longFiles.push(`${c.path}:${String(c.line)}`);\n return {\n ...c,\n body: c.body.replace(\n /```suggestion\\n[\\s\\S]*?\\n```/,\n \"*(suggestion omitted — exceeds GitHub's ~10-line suggestion limit; see summary)*\",\n ),\n };\n }\n return c;\n });\n return { comments: adjusted, longFiles };\n};\n\n// Loaders below never throw on untrusted artifacts (SPEC §5.5) — malformed input degrades to a\n// tagged result the caller renders as a notice, rather than crashing the post.\ntype FindingsLoadResult =\n | { readonly kind: \"ok\"; readonly findings: Findings }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"invalid-shape\" }\n | { readonly kind: \"unsupported-schema-version\"; readonly version: string };\n\nconst loadFindings = (path: string): FindingsLoadResult => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch {\n return { kind: \"corrupt\" };\n }\n const resolution = resolve(\"findings\", raw);\n switch (resolution.kind) {\n case \"ok\":\n return { kind: \"ok\", findings: resolution.value };\n case \"unsupported-version\":\n return { kind: \"unsupported-schema-version\", version: resolution.version };\n case \"invalid-shape\":\n case \"missing-version\":\n return { kind: \"invalid-shape\" };\n }\n};\n\nconst noticeMessageFor = (result: Exclude<FindingsLoadResult, { kind: \"ok\" }>): string => {\n switch (result.kind) {\n case \"corrupt\":\n return \"Review output was missing or malformed — the review did not complete. See the workflow run for logs.\";\n case \"invalid-shape\":\n return \"Review output was malformed — it did not conform to the findings schema. See the workflow run for logs.\";\n case \"unsupported-schema-version\": {\n const supported = supportedVersions(\"findings\")\n .map((minor) => `${minor}.x`)\n .join(\", \");\n return `Review output declares schema_version \"${result.version}\", which this commenter does not support (supported: ${supported}). See the workflow run for logs.`;\n }\n }\n};\n\n/** Load the result envelope; null on any read/decode failure (SPEC §5.5 — degrade, never crash). */\nconst loadEnvelope = (path: string): ResultEnvelope | null => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch {\n return null;\n }\n const decoded = ResultEnvelopeCodec.decode(raw);\n return decoded._tag === \"Right\" ? decoded.right : null;\n};\n\n/** Load an optional test report; undefined (and a warning) on any read/decode failure — REQ-CO-9\n * enrichment is optional and MUST degrade gracefully, never abort the post. */\nconst loadTestReport = (path: string): TestSummary | undefined => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch (err) {\n process.stderr.write(\n `Warning: could not read test report at ${path}: ${err instanceof Error ? err.message : String(err)} — omitting test panel\\n`,\n );\n return undefined;\n }\n const decoded = TestSummaryCodec.decode(raw);\n if (decoded._tag === \"Left\") {\n process.stderr.write(\n `Warning: test report at ${path} does not match the expected shape — omitting test panel\\n`,\n );\n return undefined;\n }\n return decoded.right;\n};\n\n/** Parse an `html_url` field out of a `gh api` JSON response; a malformed or unexpected response\n * degrades to undefined rather than throwing — a missing link must never fail the post (§5.5). */\nconst parseHtmlUrl = (raw: string): string | undefined => {\n try {\n const parsed = JSON.parse(raw) as { html_url?: unknown };\n return typeof parsed.html_url === \"string\" ? parsed.html_url : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** Post the inline review, pointing its body at the sticky (issue #11) when the sticky's URL is\n * known, and prepending the precomputed findings-json marker (issue #19) so the review body\n * carries it too. Returns the review's own `html_url` (undefined on a malformed response) so the\n * caller can link the sticky back to it. */\nconst postInlineReview = async (\n repo: string,\n prNumber: number,\n headSha: string,\n comments: readonly InlineComment[],\n stickyUrl: string | undefined,\n marker: string,\n ghApi: GhApi,\n): Promise<string | undefined> => {\n const sha7 = headSha.slice(0, 7);\n const linkLine = stickyUrl\n ? `🤖 Automated code review for \\`${sha7}\\` — see the [summary comment](${stickyUrl}) for the verdict, walkthrough, and cost.`\n : `🤖 Automated code review for \\`${sha7}\\` — see the summary comment for the verdict, walkthrough, and cost.`;\n const pointer = marker ? `${marker}\\n\\n${linkLine}` : linkLine;\n const body = JSON.stringify({\n body: pointer,\n commit_id: headSha,\n event: \"COMMENT\",\n comments: comments.map((c) => ({\n path: c.path,\n line: c.line,\n side: c.side,\n ...(c.start_line !== undefined && c.start_side !== undefined\n ? { start_line: c.start_line, start_side: c.start_side }\n : {}),\n body: formatMarkdown(c.body),\n })),\n });\n const stdout = await ghApi(\n [`repos/${repo}/pulls/${String(prNumber)}/reviews`, \"--input\", \"-\"],\n body,\n );\n return parseHtmlUrl(stdout);\n};\n\nconst findBotComment = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n marker: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly body: string } | null> => {\n const stdout = await ghApi(\n [\n `repos/${repo}/issues/${String(prNumber)}/comments`,\n \"--paginate\",\n \"--jq\",\n \".[] | select(.user.login == env.CODE_REVIEW_BOT_LOGIN and (.body | startswith(env.CODE_REVIEW_MARKER))) | {id: .id, body: .body}\",\n ],\n undefined,\n { CODE_REVIEW_BOT_LOGIN: botLogin, CODE_REVIEW_MARKER: marker },\n );\n const lines = stdout.trim().split(\"\\n\").filter(Boolean);\n if (lines.length === 0) return null;\n const last = lines[lines.length - 1] ?? null;\n if (last === null) return null;\n const parsed = JSON.parse(last) as { id: number; body: string };\n return { id: parsed.id, body: parsed.body };\n};\n\n/** Parse an issue-comment create/patch response for `id`/`html_url`; malformed responses degrade\n * to null rather than throwing (§5.5, issue #11 ROBUSTNESS — a missing link must never fail the\n * post). */\nconst parseCommentRef = (\n raw: string,\n): { readonly id: number; readonly html_url: string } | null => {\n try {\n const parsed = JSON.parse(raw) as { id?: unknown; html_url?: unknown };\n return typeof parsed.id === \"number\" && typeof parsed.html_url === \"string\"\n ? { id: parsed.id, html_url: parsed.html_url }\n : null;\n } catch {\n return null;\n }\n};\n\nconst patchComment = async (\n repo: string,\n commentId: number,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly html_url: string } | null> => {\n const stdout = await ghApi(\n [`repos/${repo}/issues/comments/${String(commentId)}`, \"--input\", \"-\"],\n JSON.stringify({ body }),\n );\n // Only `html_url` is needed here — the id is already known by the caller — so this doesn't\n // require `id` in the response the way parseCommentRef (used for a brand-new comment) does.\n const htmlUrl = parseHtmlUrl(stdout);\n return htmlUrl !== undefined ? { html_url: htmlUrl } : null;\n};\n\nconst postComment = async (\n repo: string,\n prNumber: number,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly html_url: string } | null> => {\n const stdout = await ghApi(\n [`repos/${repo}/issues/${String(prNumber)}/comments`, \"--input\", \"-\"],\n JSON.stringify({ body }),\n );\n return parseCommentRef(stdout);\n};\n\n/** Upsert the sticky summary — trust by author identity (bot login), not marker alone (§5.3).\n * Returns the sticky's id + `html_url` (url undefined on a malformed response) so the caller can\n * re-patch it with a link to the review once posted (issue #11). Returns null only when a *new*\n * comment's response couldn't be parsed at all — there is then no id to re-patch with. */\nconst upsertSticky = async (\n repo: string,\n prNumber: number,\n existing: { readonly id: number; readonly body: string } | null,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly url: string | undefined } | null> => {\n if (existing !== null) {\n const patched = await patchComment(repo, existing.id, body, ghApi);\n process.stderr.write(\n `Updated sticky comment #${String(existing.id)} on PR #${String(prNumber)}\\n`,\n );\n return { id: existing.id, url: patched?.html_url };\n }\n const posted = await postComment(repo, prNumber, body, ghApi);\n process.stderr.write(`Posted new sticky comment on PR #${String(prNumber)}\\n`);\n return posted ? { id: posted.id, url: posted.html_url } : null;\n};\n\n/** A non-dismissed bot-authored review, carrying the commit it reviewed (SPEC §5.2.6 — review\n * identity is the reviews API `commit_id`, not the sticky's `reviewed-sha` marker). */\ninterface BotReviewRef {\n readonly id: number;\n readonly commitId: string;\n}\n\nconst isBotReview = (\n r: unknown,\n): r is { id: number; user: { login: string }; state: string; commit_id?: unknown } =>\n typeof r === \"object\" &&\n r !== null &&\n typeof (r as { id?: unknown }).id === \"number\" &&\n typeof (r as { state?: unknown }).state === \"string\" &&\n typeof (r as { user?: { login?: unknown } }).user?.login === \"string\";\n\n/** List the PR's non-dismissed bot-authored reviews with the SHA each one reviewed. */\nconst fetchBotReviews = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n ghApi: GhApi,\n): Promise<readonly BotReviewRef[]> => {\n const stdout = await ghApi([`repos/${repo}/pulls/${String(prNumber)}/reviews`, \"--paginate\"]);\n let reviews: unknown;\n try {\n reviews = JSON.parse(stdout || \"[]\");\n } catch {\n return [];\n }\n if (!Array.isArray(reviews)) return [];\n return reviews\n .filter(isBotReview)\n .filter((r) => r.user.login === botLogin && r.state !== \"DISMISSED\")\n .map((r) => ({\n id: r.id,\n commitId: typeof r.commit_id === \"string\" ? r.commit_id : \"\",\n }));\n};\n\n/** Dismiss superseded bot-authored reviews (REC-CO-2). Failures are logged, never fail the job. */\nconst dismissReviews = async (\n repo: string,\n prNumber: number,\n ids: readonly number[],\n ghApi: GhApi,\n): Promise<void> => {\n for (const id of ids) {\n try {\n await ghApi(\n [\n `repos/${repo}/pulls/${String(prNumber)}/reviews/${String(id)}/dismissals`,\n \"-X\",\n \"PUT\",\n \"--input\",\n \"-\",\n ],\n JSON.stringify({ message: \"Superseded by a new review for an updated commit.\" }),\n );\n } catch (err) {\n process.stderr.write(\n `Warning: failed to dismiss prior review #${String(id)} on PR #${String(prNumber)}: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n};\n\nexport const post = async (input: PostInput, ghApi: GhApi = runGhApi): Promise<void> => {\n // Phase 1 (CO-R3): reads, decodes, diff validation, rendering — no writes yet.\n const candidates = await fetchPrCandidates(input.repo, input.headSha, ghApi);\n const resolution = resolvePr(candidates, input.headBranch);\n if (resolution.kind === \"none\") {\n process.stderr.write(`No open PR for ${input.headSha} — nothing to post\\n`);\n process.exit(0);\n }\n if (resolution.kind === \"not-open\") {\n process.stderr.write(\n `PR #${String(resolution.prNumber)} for ${input.headSha} is not open (state: ${resolution.state}) — nothing to post\\n`,\n );\n process.exit(0);\n }\n const prNumber = resolution.prNumber;\n\n const diff = await fetchDiff(input.repo, prNumber, ghApi);\n const existingSticky = await findBotComment(\n input.repo,\n prNumber,\n input.botLogin,\n DEFAULT_MARKER,\n ghApi,\n );\n\n const prices = JSON.parse(readFileSync(input.pricesPath, \"utf-8\")) as unknown;\n const decodedPrices = PriceMapCodec.decode(prices);\n if (decodedPrices._tag === \"Left\") {\n throw new Error(`Price map at ${input.pricesPath} does not match the expected shape`);\n }\n const template = readFileSync(input.templatePath, \"utf-8\");\n const inlineTemplate = readFileSync(input.inlineTemplatePath, \"utf-8\");\n\n const renderNotice = (message: string): string =>\n formatMarkdown(\n render({\n findings: noticeFindings(`### ⚠️ ${message}`),\n envelope: null,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n }),\n );\n\n if (isEmptyDiff(diff)) {\n await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderNotice(\"The diff for this PR is empty — nothing to review.\"),\n ghApi,\n );\n process.exit(0);\n }\n\n const findingsResult = loadFindings(input.findingsPath);\n if (findingsResult.kind !== \"ok\") {\n await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderNotice(noticeMessageFor(findingsResult)),\n ghApi,\n );\n process.exit(0);\n }\n const findings = findingsResult.findings;\n\n const envelope = loadEnvelope(input.envelopePath);\n const testReport = input.testReportPath ? loadTestReport(input.testReportPath) : undefined;\n\n if (envelope === null) {\n const body = formatMarkdown(\n render({\n findings,\n envelope: null,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n testReport,\n inlineDisposition: { kind: \"no-envelope\" },\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n }),\n );\n await upsertSticky(input.repo, prNumber, existingSticky, body, ghApi);\n process.stderr.write(\n \"Result envelope missing or malformed — posted sticky summary without usage/cost data; no inline review\\n\",\n );\n process.exit(0);\n }\n\n // Issue #19 + review fix #5: base64-encode the findings ONCE and reuse the marker across every\n // surface (both sticky renders, each inline comment, the review body) instead of recomputing it.\n const findingsMarker = findingsPointer(findings, input.jsonUrl);\n\n const { comments: rawComments, strays } = buildInlineComments(findings.findings, diff, {\n inlineTemplate,\n models: envelope.models.map((m) => m.model),\n findingsPointer: findingsMarker,\n });\n const { comments, longFiles } = checkLongSuggestions(rawComments);\n for (const wf of longFiles) {\n process.stderr.write(\n `Warning: suggestion in ${wf} exceeds ${String(MAX_SUGGESTION_LINES)} lines — omitted from inline to avoid 422\\n`,\n );\n }\n\n // Fix #5 (SPEC §5.2.6): suppression turns on whether a COMPLETED bot review already exists for\n // this head SHA — review identity via the reviews API `commit_id` — not on the sticky's marker\n // (a placeholder/degraded sticky must not claim the SHA). Only relevant when there is an inline\n // review to post at all.\n const botReviews =\n comments.length > 0 ? await fetchBotReviews(input.repo, prNumber, input.botLogin, ghApi) : [];\n const alreadyReviewedThisSha = botReviews.some((r) => r.commitId === input.headSha);\n\n // Issue #21: the \"posted — see the review\" disposition is constructed ONLY from the actual\n // postInlineReview result below, never optimistically — a review that doesn't yet exist (or\n // never will, if this process dies before posting it) must never be claimed. Everything knowable\n // from reads alone (suppression, no-in-diff-findings) is truthful up front and stays as-is.\n const initialDisposition: InlineDisposition | undefined =\n comments.length > 0\n ? alreadyReviewedThisSha\n ? { kind: \"suppressed-existing-review\", sha: input.headSha }\n : undefined\n : strays.length > 0\n ? { kind: \"none-in-diff\" }\n : undefined;\n\n const commonRenderInput: Omit<RenderInput, \"inlineDisposition\" | \"reviewUrl\"> = {\n findings,\n envelope,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n testReport,\n severityCounts: computeSeverityCounts(findings.findings),\n strays,\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n findingsPointer: findingsMarker,\n };\n const longFilesNote =\n longFiles.length > 0\n ? `\\n\\n---\\n\\n> **Note:** ${String(longFiles.length)} suggestion(s) exceeded GitHub's ~10-line inline suggestion limit and were omitted from the inline comments; the affected findings remain in the review.\\n`\n : \"\";\n // Renders the sticky body; called twice (issue #11) — once before the review exists (no\n // disposition claim beyond what reads already confirmed), once after (with the confirmed\n // disposition + reviewUrl) to report the truth and link the sticky back to the review.\n const renderBody = (\n inlineDisposition: InlineDisposition | undefined,\n reviewUrl?: string,\n ): string =>\n formatMarkdown(render({ ...commonRenderInput, inlineDisposition, reviewUrl }) + longFilesNote);\n\n // Phase 2 (CO-R3): writes — sticky first, inline second; failure exits non-zero.\n const stickyRef = await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderBody(initialDisposition),\n ghApi,\n );\n\n if (comments.length === 0) return;\n\n if (alreadyReviewedThisSha) {\n process.stderr.write(\n `A completed bot review already exists for ${input.headSha} — updated sticky only, no new inline review\\n`,\n );\n return;\n }\n\n // REC-CO-2: supersede prior bot reviews left on OTHER commits before posting the fresh one.\n const stalePriorReviewIds = botReviews\n .filter((r) => r.commitId !== input.headSha)\n .map((r) => r.id);\n if (stalePriorReviewIds.length > 0) {\n await dismissReviews(input.repo, prNumber, stalePriorReviewIds, ghApi);\n }\n\n const reviewUrl = await postInlineReview(\n input.repo,\n prNumber,\n input.headSha,\n comments,\n stickyRef?.url,\n findingsMarker,\n ghApi,\n );\n process.stderr.write(\n `Posted ${String(comments.length)} inline comments on PR #${String(prNumber)}\\n`,\n );\n\n // Issue #11/#21: now that postInlineReview has actually resolved, the sticky can truthfully\n // report the review — with a link when reviewUrl parsed, as plain text otherwise (still true:\n // the review was posted; only its URL is unknown). Best-effort — the sticky and review are\n // already posted, so a failure here (a bad response, a network hiccup) must never fail the job.\n if (stickyRef !== null) {\n const confirmedDisposition: InlineDisposition = {\n kind: \"posted\",\n count: comments.length,\n sha: input.headSha,\n };\n try {\n await patchComment(\n input.repo,\n stickyRef.id,\n renderBody(confirmedDisposition, reviewUrl),\n ghApi,\n );\n process.stderr.write(`Linked sticky comment #${String(stickyRef.id)} to the review\\n`);\n } catch (err) {\n process.stderr.write(\n `Warning: failed to link the sticky summary to the review: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n};\n","// Gather review inputs (SPEC §8.2): resolve the PR from the trusted head SHA, fetch the diff (with\n// a non-truncating git-diff fallback), the PR context, the prior bot review, and — when CI\n// failed — the failing-job logs. Mirrors the bash \"Gather review inputs\" step 1:1, but as\n// vitest-tested TypeScript, sharing `post`'s PR resolution so the two jobs never split-brain.\n\nimport { execFile } from \"node:child_process\";\nimport { writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as t from \"io-ts\";\nimport type { GhApi } from \"./gh.js\";\nimport { runGhApi } from \"./gh.js\";\nimport { fetchDiff, fetchPrCandidates, resolvePr } from \"./pr.js\";\n\nexport interface GatherInput {\n readonly repo: string;\n readonly headSha: string;\n readonly headBranch?: string;\n readonly runId: string;\n readonly conclusion: string;\n readonly botLogin: string;\n readonly outDir: string;\n}\n\nexport type GatherResult =\n | { readonly kind: \"skip\" }\n | {\n readonly kind: \"gathered\";\n readonly pr: number;\n readonly conclusion: string;\n readonly diffSize: number;\n };\n\n/** The GitHub-outputs lines the step appends to $GITHUB_OUTPUT. CI-agnostic + directly testable. */\nexport const renderOutputs = (result: GatherResult): string => {\n switch (result.kind) {\n case \"skip\":\n return \"skip=true\\n\";\n case \"gathered\":\n return `pr=${String(result.pr)}\\nconclusion=${result.conclusion}\\ndiff_size=${String(result.diffSize)}\\n`;\n }\n};\n\nexport type GitRun = (args: readonly string[]) => Promise<string>;\n\nexport const runGit: GitRun = (args) =>\n new Promise<string>((resolve, reject) => {\n execFile(\n \"git\",\n [...args],\n { encoding: \"utf-8\", maxBuffer: 100 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n const stderrStr = typeof stderr === \"string\" && stderr.trim() ? stderr.trim() : \"\";\n const errStr = err instanceof Error ? err.message : \"unknown error\";\n reject(new Error(`git ${args.join(\" \")} failed: ${stderrStr || errStr}`));\n } else {\n resolve(stdout);\n }\n },\n );\n });\n\nconst PrMetaCodec = t.type({\n changed_files: t.number,\n base_sha: t.string,\n title: t.string,\n body: t.union([t.string, t.null]),\n});\ntype PrMeta = t.TypeOf<typeof PrMetaCodec>;\n\nconst IssueCommentCodec = t.type({\n id: t.number,\n body: t.union([t.string, t.null]),\n user: t.type({ login: t.string }),\n});\nconst IssueCommentsCodec = t.array(IssueCommentCodec);\n\nconst JobCodec = t.type({ id: t.number, conclusion: t.union([t.string, t.null]) });\nconst JobsResponseCodec = t.type({ jobs: t.array(JobCodec) });\n\nconst fetchPrMeta = async (repo: string, prNumber: number, ghApi: GhApi): Promise<PrMeta> => {\n const stdout = await ghApi([\n `repos/${repo}/pulls/${String(prNumber)}`,\n \"--jq\",\n \"{changed_files: .changed_files, base_sha: .base.sha, title: .title, body: .body}\",\n ]);\n const decoded = PrMetaCodec.decode(JSON.parse(stdout) as unknown);\n if (decoded._tag === \"Left\") {\n throw new Error(`PR metadata for #${String(prNumber)} did not match the expected shape`);\n }\n return decoded.right;\n};\n\n/** Fetch the diff via the API; null on failure (drives the git fallback). */\nconst fetchApiDiff = async (\n repo: string,\n prNumber: number,\n ghApi: GhApi,\n): Promise<string | null> => {\n try {\n return await fetchDiff(repo, prNumber, ghApi);\n } catch {\n return null;\n }\n};\n\n/** Last comment authored by botLogin, or null. Degrades to null on ANY failure (bash `|| echo null`). */\nconst fetchPriorReview = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly body: string | null } | null> => {\n try {\n const stdout = await ghApi([`repos/${repo}/issues/${String(prNumber)}/comments`, \"--paginate\"]);\n const decoded = IssueCommentsCodec.decode(JSON.parse(stdout || \"[]\") as unknown);\n if (decoded._tag === \"Left\") return null;\n const byBot = decoded.right.filter((c) => c.user.login === botLogin);\n const last = byBot[byBot.length - 1];\n return last ? { id: last.id, body: last.body } : null;\n } catch {\n return null;\n }\n};\n\n/** Download each failing job's logs → <outDir>/job_<id>.log. Jobs-list failure is fatal; a\n * per-log download failure degrades (warns to stderr, keeps whatever logs were retrieved) —\n * logs are advisory input, and partial logs plus the diff beat a dead review. */\nconst downloadFailingJobLogs = async (\n repo: string,\n runId: string,\n outDir: string,\n ghApi: GhApi,\n): Promise<void> => {\n const stdout = await ghApi([`repos/${repo}/actions/runs/${runId}/jobs`]);\n const decoded = JobsResponseCodec.decode(JSON.parse(stdout) as unknown);\n if (decoded._tag === \"Left\") {\n throw new Error(`Jobs list for run ${runId} did not match the expected shape`);\n }\n for (const job of decoded.right.jobs.filter((j) => j.conclusion === \"failure\")) {\n try {\n const log = await ghApi([`repos/${repo}/actions/jobs/${String(job.id)}/logs`]);\n writeFileSync(join(outDir, `job_${String(job.id)}.log`), log);\n } catch (err) {\n process.stderr.write(\n `Warning: failed to download logs for job ${String(job.id)}: ${err instanceof Error ? err.message : String(err)} — continuing with the logs retrieved so far\\n`,\n );\n }\n }\n};\n\nexport const gather = async (\n input: GatherInput,\n ghApi: GhApi = runGhApi,\n gitRun: GitRun = runGit,\n): Promise<GatherResult> => {\n const candidates = await fetchPrCandidates(input.repo, input.headSha, ghApi);\n const resolution = resolvePr(candidates, input.headBranch);\n if (resolution.kind === \"none\") {\n process.stderr.write(`No open PR for ${input.headSha} — nothing to review\\n`);\n return { kind: \"skip\" };\n }\n if (resolution.kind === \"not-open\") {\n process.stderr.write(\n `PR #${String(resolution.prNumber)} for ${input.headSha} is not open (state: ${resolution.state}) — nothing to review\\n`,\n );\n return { kind: \"skip\" };\n }\n const prNumber = resolution.prNumber;\n\n const meta = await fetchPrMeta(input.repo, prNumber, ghApi);\n\n const apiDiff = await fetchApiDiff(input.repo, prNumber, ghApi);\n const diff =\n apiDiff !== null && !(apiDiff.length === 0 && meta.changed_files > 0)\n ? apiDiff\n : await (async () => {\n process.stderr.write(\n `PR diff fetch failed or was empty for ${String(meta.changed_files)} changed files — falling back to git diff\\n`,\n );\n await gitRun([\"fetch\", \"origin\", input.headSha]);\n return gitRun([\"diff\", meta.base_sha, input.headSha]);\n })();\n\n writeFileSync(join(input.outDir, \"pr.diff\"), diff);\n writeFileSync(\n join(input.outDir, \"pr_context.json\"),\n JSON.stringify({ title: meta.title, body: meta.body }),\n );\n\n const prior = await fetchPriorReview(input.repo, prNumber, input.botLogin, ghApi);\n writeFileSync(\n join(input.outDir, \"prior_review.json\"),\n prior === null ? \"null\" : JSON.stringify(prior),\n );\n\n if (input.conclusion === \"failure\") {\n await downloadFailingJobLogs(input.repo, input.runId, input.outDir, ghApi);\n }\n\n return {\n kind: \"gathered\",\n pr: prNumber,\n conclusion: input.conclusion,\n diffSize: Buffer.byteLength(diff, \"utf8\"),\n };\n};\n","// Extraction ladder: recovers a schema-conforming candidate (findings or triage) from a native\n// agent-CLI result envelope when structured-output enforcement is imperfect or absent. Rung order\n// is a fixed priority: --agent-file > structured_output > pure-JSON result > fenced code blocks.\n// The first rung producing exactly one distinct schema-validating candidate wins (fenced-block\n// candidates are deduplicated by canonical value first — an exact duplicate is not a conflict); an\n// error envelope (the agent run did not complete) short-circuits before any rung runs. See\n// docs/adapters.md \"Extraction ladder\" for the security rationale (exactly-one-distinct-validating\n// defeats block-injection).\n//\n// Candidate gate: ajv (via validateAgainstSchema, additionalProperties:false) rejects shape and\n// injection attempts; the registry's io-ts codec (via resolve) then materializes the value,\n// additionally enforcing invariants ajv cannot express (e.g. end_line >= start_line). A candidate\n// must pass both to count as \"validating\".\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve, schemaPathFor, defaultVersion } from \"./registry.js\";\nimport { validateAgainstSchema } from \"./validate.js\";\n\nexport type ExtractKind = \"findings\" | \"triage\";\n\nexport interface ExtractInput {\n readonly kind: ExtractKind;\n readonly native: unknown;\n /** Path to a file the agent was told to write its own validated JSON to (findings only — a\n * documented no-op for triage, per the rung order's \"agent-file wins\" test). */\n readonly agentFilePath?: string;\n}\n\nexport type LadderOutcome =\n | { readonly kind: \"ok\"; readonly version: string; readonly candidate: unknown }\n | { readonly kind: \"error-envelope\"; readonly detail: string }\n | { readonly kind: \"none\"; readonly detail: string }\n | { readonly kind: \"ambiguous\"; readonly detail: string };\n\ninterface NativeForExtraction {\n readonly result: unknown;\n readonly structuredOutput: unknown;\n readonly isError: unknown;\n readonly subtype: unknown;\n readonly apiErrorStatus: unknown;\n}\n\nconst fieldOf = (raw: unknown, key: string): unknown =>\n typeof raw === \"object\" && raw !== null && key in raw\n ? (raw as Record<string, unknown>)[key]\n : undefined;\n\nconst parseNativeForExtraction = (raw: unknown): NativeForExtraction => ({\n result: fieldOf(raw, \"result\"),\n structuredOutput: fieldOf(raw, \"structured_output\"),\n isError: fieldOf(raw, \"is_error\"),\n subtype: fieldOf(raw, \"subtype\"),\n apiErrorStatus: fieldOf(raw, \"api_error_status\"),\n});\n\nconst isNullish = (value: unknown): boolean => value === null || value === undefined;\n\n/** is_error===true OR (subtype not null/undefined and != \"success\") OR api_error_status not null/undefined. */\nconst isErrorEnvelope = (native: NativeForExtraction): boolean =>\n native.isError === true ||\n (!isNullish(native.subtype) && native.subtype !== \"success\") ||\n !isNullish(native.apiErrorStatus);\n\nconst describeErrorEnvelope = (native: NativeForExtraction): string => {\n const parts: readonly string[] = [\n ...(native.isError === true ? [\"is_error=true\"] : []),\n ...(!isNullish(native.subtype) && native.subtype !== \"success\"\n ? [`subtype=${JSON.stringify(native.subtype)}`]\n : []),\n ...(!isNullish(native.apiErrorStatus)\n ? [`api_error_status=${JSON.stringify(native.apiErrorStatus)}`]\n : []),\n ];\n return `agent run did not complete successfully (${parts.join(\", \")})`;\n};\n\n/** Default `schema_version` onto a findings candidate when the agent omitted it; identity for triage. */\nexport const withDefaultSchemaVersion = (candidate: unknown): unknown =>\n typeof candidate === \"object\" &&\n candidate !== null &&\n !Array.isArray(candidate) &&\n !(\"schema_version\" in candidate)\n ? { ...candidate, schema_version: defaultVersion(\"findings\") }\n : candidate;\n\nconst normalizeCandidate = (kind: ExtractKind, candidate: unknown): unknown =>\n kind === \"findings\" ? withDefaultSchemaVersion(candidate) : candidate;\n\nconst candidateVersion = (kind: ExtractKind, candidate: unknown): string | undefined => {\n if (kind !== \"findings\") return undefined;\n const version = fieldOf(candidate, \"schema_version\");\n return typeof version === \"string\" ? version : undefined;\n};\n\nconst safeSchemaPathFor = (kind: ExtractKind, version: string | undefined): string | null => {\n try {\n return schemaPathFor(kind, version);\n } catch {\n return null;\n }\n};\n\ninterface GatedCandidate {\n readonly version: string;\n /** The survivor after `schema_version` injection, pre-registry-normalize (identical for alpha) —\n * what the extract CLI prints, per the registry seam ruling. */\n readonly candidate: unknown;\n}\n\n/** Recursively sort object keys so two values that differ only in key order canonicalize equal. */\nconst canonicalize = (value: unknown): unknown =>\n Array.isArray(value)\n ? value.map(canonicalize)\n : value !== null && typeof value === \"object\"\n ? Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => [k, canonicalize(v)]),\n )\n : value;\n\n/** Collapse gated candidates that are exact duplicates once canonicalized — a model re-emitting its\n * answer verbatim is a plausible benign case, not a conflict. Two candidates that differ in any\n * value still remain distinct, so the injection defense (refusing to pick a survivor among\n * disagreeing candidates) is unweakened. */\nconst dedupCandidates = (candidates: readonly GatedCandidate[]): readonly GatedCandidate[] => {\n const seen = new Set<string>();\n return candidates.filter((c) => {\n const key = JSON.stringify(canonicalize(c.candidate));\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n};\n\n/** Gate a raw candidate through ajv (shape + injection defense) then the registry's io-ts codec\n * (materialization + cross-field invariants); null when either gate rejects it. */\nconst gateCandidate = (kind: ExtractKind, rawCandidate: unknown): GatedCandidate | null => {\n const candidate = normalizeCandidate(kind, rawCandidate);\n const schemaPath = safeSchemaPathFor(kind, candidateVersion(kind, candidate));\n if (schemaPath === null) return null;\n if (!validateAgainstSchema(candidate, schemaPath).valid) return null;\n const resolution = resolve(kind, candidate);\n return resolution.kind === \"ok\" ? { version: resolution.version, candidate } : null;\n};\n\ntype ParseResult = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\nconst tryParseJson = (text: string): ParseResult => {\n try {\n return { ok: true, value: JSON.parse(text) as unknown };\n } catch {\n return { ok: false };\n }\n};\n\nconst readFileOrNull = (path: string): string | null => {\n try {\n return readFileSync(path, \"utf-8\");\n } catch {\n return null;\n }\n};\n\nconst candidateFromJsonText = (kind: ExtractKind, text: string | null): GatedCandidate | null => {\n if (text === null) return null;\n const parsed = tryParseJson(text);\n return parsed.ok ? gateCandidate(kind, parsed.value) : null;\n};\n\ninterface FenceScanState {\n readonly blocks: readonly string[];\n readonly openLength: number | null;\n readonly buffer: readonly string[];\n}\n\nconst FENCE_OPEN = /^\\s*(`{3,})/;\nconst FENCE_MARKER_ONLY = /^`+$/;\n\n/** Fold one line into the fence-scan state. Opens on a line whose first non-whitespace run is\n * >=3 backticks (the rest of the line — an info string like \"json\" — is ignored); closes on the\n * next line that, trimmed, is only backticks of length >= the opening fence. Line-based by\n * design — no regex spans more than one line, so there is no catastrophic-backtracking surface. */\nconst scanLine = (state: FenceScanState, line: string): FenceScanState => {\n if (state.openLength === null) {\n const opened = FENCE_OPEN.exec(line)?.[1]?.length;\n return opened !== undefined ? { blocks: state.blocks, openLength: opened, buffer: [] } : state;\n }\n const trimmed = line.trim();\n const closes = FENCE_MARKER_ONLY.test(trimmed) && trimmed.length >= state.openLength;\n return closes\n ? { blocks: [...state.blocks, state.buffer.join(\"\\n\")], openLength: null, buffer: [] }\n : { ...state, buffer: [...state.buffer, line] };\n};\n\n/** Extract fenced code-block contents from `text` (both ` ```json ` and bare ` ``` `); text before,\n * between, and after fences (and an unterminated trailing fence) is discarded. */\nexport const scanFencedBlocks = (text: string): readonly string[] =>\n text.split(\"\\n\").reduce(scanLine, { blocks: [], openLength: null, buffer: [] }).blocks;\n\n/** Operator-facing breakdown of what each rung actually saw when recovery fails — for stderr/logs,\n * never for the fail-closed reasons (which stay generic). Turns an opaque \"no candidate\" into an\n * actionable trace: a null structured_output points at a CLI not enforcing `--json-schema`. */\nexport const ladderFailureDiagnostics = (input: ExtractInput): string => {\n const native = parseNativeForExtraction(input.native);\n const preview = (s: string): string => {\n const flat = s.replace(/\\s+/g, \" \").trim();\n return flat.length > 200 ? `${flat.slice(0, 200)}…` : flat;\n };\n const lines: string[] = [];\n if (input.kind === \"findings\") {\n lines.push(\n input.agentFilePath === undefined\n ? \"agent-file rung: no --agent-file given\"\n : `agent-file rung: ${input.agentFilePath} did not validate (or was unreadable)`,\n );\n }\n lines.push(\n isNullish(native.structuredOutput)\n ? \"structured_output rung: absent (null) — the CLI's --json-schema likely did not enforce\"\n : \"structured_output rung: present but did not validate against the schema\",\n );\n lines.push(\n typeof native.result === \"string\"\n ? `result rung: ${String(native.result.length)} chars, ${String(scanFencedBlocks(native.result).length)} fenced JSON block(s), none validated; preview: ${preview(native.result)}`\n : \"result rung: absent or not a string\",\n );\n return lines.join(\"\\n\");\n};\n\n/** Render a non-\"ok\" ladder outcome as a single human-readable message. */\nexport const describeLadderFailure = (outcome: Exclude<LadderOutcome, { kind: \"ok\" }>): string => {\n switch (outcome.kind) {\n case \"error-envelope\":\n return `review did not complete: ${outcome.detail}`;\n case \"none\":\n return `could not recover a validating candidate: ${outcome.detail}`;\n case \"ambiguous\":\n return `ambiguous candidates: ${outcome.detail}`;\n }\n};\n\nconst okOutcome = (gated: GatedCandidate): LadderOutcome => ({\n kind: \"ok\",\n version: gated.version,\n candidate: gated.candidate,\n});\n\n/** Run the extraction ladder. Pure aside from an optional `--agent-file` read. */\nexport const extractStructured = (input: ExtractInput): LadderOutcome => {\n const native = parseNativeForExtraction(input.native);\n\n if (isErrorEnvelope(native)) {\n return { kind: \"error-envelope\", detail: describeErrorEnvelope(native) };\n }\n\n if (input.kind === \"findings\" && input.agentFilePath !== undefined) {\n const fromFile = candidateFromJsonText(input.kind, readFileOrNull(input.agentFilePath));\n if (fromFile) return okOutcome(fromFile);\n }\n\n if (native.structuredOutput !== undefined) {\n const fromStructured = gateCandidate(input.kind, native.structuredOutput);\n if (fromStructured) return okOutcome(fromStructured);\n }\n\n if (typeof native.result === \"string\") {\n const fromResult = candidateFromJsonText(input.kind, native.result.trim());\n if (fromResult) return okOutcome(fromResult);\n\n const fencedCandidates = dedupCandidates(\n scanFencedBlocks(native.result)\n .map((block) => candidateFromJsonText(input.kind, block))\n .filter((gated): gated is GatedCandidate => gated !== null),\n );\n\n const [survivor, ...rest] = fencedCandidates;\n if (survivor !== undefined && rest.length === 0) return okOutcome(survivor);\n if (survivor !== undefined) {\n return {\n kind: \"ambiguous\",\n detail: `${String(fencedCandidates.length)} distinct fenced JSON blocks each validate against the ${input.kind} schema — refusing to pick one`,\n };\n }\n }\n\n return {\n kind: \"none\",\n detail: `no --agent-file, structured_output, JSON result, or fenced block validated against the ${input.kind} schema`,\n };\n};\n","// Adapter: maps a coding-agent CLI's native result envelope onto the abstract\n// result envelope (SPEC §6.1). Claude Code is the reference adapter — see docs/adapters.md.\n// Pure mapping; a decode failure surfaces as a Left, never a throw.\n\nimport * as t from \"io-ts\";\nimport type { Either } from \"fp-ts/Either\";\nimport { resolve } from \"./registry.js\";\nimport { extractStructured, describeLadderFailure } from \"./extract.js\";\nimport { DEFAULT_SCHEMA_VERSION, noticeFindings } from \"./schema.js\";\nimport type { Findings, ModelUsageEntry, ResultEnvelope } from \"./schema.js\";\n\n// No value-level import from fp-ts (a bare \"fp-ts/Either\" subpath import breaks under strict\n// Node ESM — see fp-ts's lack of a package.json \"exports\" map). Either values are constructed\n// as plain tagged literals and consumed via ._tag, matching this codebase's existing convention\n// (validate.ts, index.ts) of importing only the Either *type*.\nconst left = <A>(message: string): Either<string, A> => ({ _tag: \"Left\", left: message });\nconst right = <A>(value: A): Either<string, A> => ({ _tag: \"Right\", right: value });\n\nexport type AdapterName = \"claude-code\";\n\nexport const isAdapterName = (name: string): name is AdapterName => name === \"claude-code\";\n\nconst ClaudeCodeModelUsageEntryCodec = t.intersection([\n t.type({\n inputTokens: t.number,\n outputTokens: t.number,\n }),\n t.partial({\n cacheReadInputTokens: t.number,\n cacheCreationInputTokens: t.number,\n costUSD: t.number,\n }),\n]);\n\nexport const ClaudeCodeEnvelopeCodec = t.intersection([\n t.type({\n modelUsage: t.record(t.string, ClaudeCodeModelUsageEntryCodec),\n num_turns: t.number,\n duration_ms: t.number,\n }),\n t.partial({\n total_cost_usd: t.union([t.number, t.null]),\n structured_output: t.unknown,\n }),\n]);\n\ntype ClaudeCodeEnvelope = t.TypeOf<typeof ClaudeCodeEnvelopeCodec>;\n\nconst mapModelUsage = (modelUsage: ClaudeCodeEnvelope[\"modelUsage\"]): ModelUsageEntry[] =>\n Object.entries(modelUsage).map(([model, entry]) => ({\n model,\n input_tokens: entry.inputTokens,\n output_tokens: entry.outputTokens,\n ...(entry.cacheReadInputTokens !== undefined\n ? { cache_read_tokens: entry.cacheReadInputTokens }\n : {}),\n ...(entry.cacheCreationInputTokens !== undefined\n ? { cache_write_tokens: entry.cacheCreationInputTokens }\n : {}),\n }));\n\n/** Route/effort the review ran under (SPEC §6.1 envelope fields). */\nexport interface RunMeta {\n readonly route?: string;\n readonly effort?: string;\n}\n\n/** The extraction ladder's outcome, reduced to what adaptClaudeCode needs: either a materialized\n * findings document, or a reason findings are unavailable. Never a reason to drop telemetry\n * (issue #18) — every ladder outcome maps onto a *findings* result, not a fatal one. */\ntype FindingsOutcome =\n | { readonly kind: \"ok\"; readonly version: string; readonly findings: Findings }\n | { readonly kind: \"telemetry-only\"; readonly reason: string };\n\nconst findingsOutcome = (\n native: ClaudeCodeEnvelope,\n agentFilePath: string | undefined,\n): FindingsOutcome => {\n const ladder = extractStructured({ kind: \"findings\", native, agentFilePath });\n if (ladder.kind !== \"ok\")\n return { kind: \"telemetry-only\", reason: describeLadderFailure(ladder) };\n // The ladder already confirmed this candidate resolves via the registry; re-resolving here just\n // materializes the typed, normalized value it deliberately didn't keep (see extract.ts).\n const resolution = resolve(\"findings\", ladder.candidate);\n return resolution.kind === \"ok\"\n ? { kind: \"ok\", version: resolution.version, findings: resolution.value }\n : {\n kind: \"telemetry-only\",\n reason:\n \"internal error: the extraction ladder validated a candidate the registry then rejected\",\n };\n};\n\n/** Map Claude Code's native `--output-format json` envelope onto the abstract envelope (SPEC §6.1).\n * `findings` and `schema_version` come from the extraction ladder when it recovers a candidate;\n * every other envelope field (models, turns, duration, vendor cost) always comes from the native\n * envelope itself, UNCONDITIONALLY — a findings-ladder miss never discards real telemetry. */\nconst adaptClaudeCode = (\n native: ClaudeCodeEnvelope,\n agentFilePath: string | undefined,\n meta: RunMeta,\n): Either<string, ResultEnvelope> => {\n const telemetry = {\n models: mapModelUsage(native.modelUsage),\n turns: native.num_turns,\n duration_ms: native.duration_ms,\n vendor_cost_usd: native.total_cost_usd ?? null,\n ...(meta.route ? { route: meta.route } : {}),\n ...(meta.effort ? { effort: meta.effort } : {}),\n };\n const outcome = findingsOutcome(native, agentFilePath);\n switch (outcome.kind) {\n case \"ok\":\n return right({\n schema_version: outcome.version,\n findings: outcome.findings,\n ...telemetry,\n });\n case \"telemetry-only\":\n return right({\n schema_version: DEFAULT_SCHEMA_VERSION,\n findings: noticeFindings(`### ⚠️ Review did not complete\\n\\n${outcome.reason}`),\n ...telemetry,\n });\n }\n};\n\n/** Map a native agent-CLI result envelope onto the abstract envelope (SPEC §6.1). `agentFilePath`\n * is meaningful only for the findings recovery (a documented no-op otherwise). */\nexport const adapt = (\n adapterName: AdapterName,\n native: unknown,\n agentFilePath?: string,\n meta: RunMeta = {},\n): Either<string, ResultEnvelope> => {\n switch (adapterName) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- exhaustive by design; AdapterName grows (e.g. \"opencode\") without collapsing this switch to an if\n case \"claude-code\": {\n const decoded = ClaudeCodeEnvelopeCodec.decode(native);\n if (decoded._tag === \"Left\") {\n return left(\"native envelope does not match the Claude Code output shape\");\n }\n return adaptClaudeCode(decoded.right, agentFilePath, meta);\n }\n }\n};\n","// Stop-hook deliverable gate. A Claude Code `Stop` hook that refuses to let the review agent end\n// its turn until it has written a findings document that validates against the schema — turning\n// the \"write your draft and validate before stopping\" instruction from a hope into an invariant.\n// The check is the same validation `code-review validate` performs.\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { validateAgainstSchema } from \"./validate.js\";\n\n/** Validation state of the agent's draft deliverable at the moment it tries to stop. A sum type so\n * `decideGate` can reprompt precisely per case — critically, distinguishing an UNREADABLE file\n * (EACCES/EISDIR) from an INVALID one, since \"does not validate against the schema\" is a lie when\n * the file could not even be read. */\nexport type DraftState =\n | { readonly kind: \"missing\" }\n | { readonly kind: \"unreadable\"; readonly error: string }\n | { readonly kind: \"invalid\"; readonly errors: readonly string[] }\n | { readonly kind: \"valid\" };\n\n/** A Stop-hook outcome: `block` feeds `reason` back to the agent so it keeps working; `allow`\n * lets the turn end. */\nexport type GateDecision =\n { readonly kind: \"allow\" } | { readonly kind: \"block\"; readonly reason: string };\n\n/** The precise \"what's wrong\" clause per non-valid draft state — honest about unreadable vs invalid. */\nconst whatsWrong = (\n state: Exclude<DraftState, { kind: \"valid\" }>,\n draftPath: string,\n kind: string,\n): string => {\n switch (state.kind) {\n case \"missing\":\n return `${draftPath} does not exist yet`;\n case \"unreadable\":\n return `${draftPath} could not be read: ${state.error}`;\n case \"invalid\":\n return `${draftPath} does not validate against the ${kind} schema:\\n${state.errors\n .map((e) => ` - ${e}`)\n .join(\"\\n\")}`;\n }\n};\n\n/** The settings shape Claude Code reads from a `--settings` file to wire a Stop hook command. */\nexport interface StopHookSettings {\n readonly hooks: {\n readonly Stop: readonly {\n readonly hooks: readonly { readonly type: \"command\"; readonly command: string }[];\n }[];\n };\n}\n\n/** Allow when the draft validates or the nudge budget is spent; otherwise block with a reason\n * that names what is wrong and reprompts the agent about the ONLY deliverable — a document\n * validating against `kind`'s schema — so it can fix it. */\nexport const decideGate = (\n state: DraftState,\n nudges: number,\n maxNudges: number,\n draftPath: string,\n kind: string,\n): GateDecision => {\n if (state.kind === \"valid\") return { kind: \"allow\" };\n if (nudges >= maxNudges) return { kind: \"allow\" };\n return {\n kind: \"block\",\n reason: [\n `This review is not complete — ${whatsWrong(state, draftPath, kind)}`,\n `The only deliverable is a ${kind} document that validates against the ${kind} schema — run \"code-review print-schema ${kind}\" to see the exact shape.`,\n `Write it to ${draftPath}, then run \"code-review validate ${draftPath} --kind ${kind}\" until it exits 0 before ending your turn.`,\n ].join(\"\\n\"),\n };\n};\n\n/** Read and validate the draft, resolving the schema from the parsed document when needed. Never\n * throws — every failure mode (missing file, unreadable file, invalid JSON, an unresolvable or\n * crashing schema lookup, a validator crash) degrades to a `DraftState` the gate can act on,\n * rather than crashing the hook and letting the agent stop by default. */\nexport const draftState = (\n draftPath: string,\n resolveSchema: (parsed: unknown) => string,\n): DraftState => {\n let raw: string;\n try {\n raw = readFileSync(draftPath, \"utf-8\");\n } catch (err) {\n if (err instanceof Error && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { kind: \"missing\" };\n }\n return { kind: \"unreadable\", error: err instanceof Error ? err.message : String(err) };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n kind: \"invalid\",\n errors: [`not valid JSON: ${err instanceof Error ? err.message : String(err)}`],\n };\n }\n let schemaPath: string;\n try {\n schemaPath = resolveSchema(parsed);\n } catch (err) {\n return { kind: \"invalid\", errors: [err instanceof Error ? err.message : String(err)] };\n }\n try {\n const { valid, errors } = validateAgainstSchema(parsed, schemaPath);\n return valid ? { kind: \"valid\" } : { kind: \"invalid\", errors };\n } catch (err) {\n return { kind: \"invalid\", errors: [err instanceof Error ? err.message : String(err)] };\n }\n};\n\n/** Nudge count persisted beside the draft across hook invocations within one review. Absent or\n * unparseable counts read as 0, so a fresh review starts with a full budget. */\nexport const readNudges = (counterPath: string): number => {\n try {\n const n = Number.parseInt(readFileSync(counterPath, \"utf-8\").trim(), 10);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n } catch {\n return 0;\n }\n};\n\n/** Persist the incremented nudge count (`current + 1`). The caller reads `current` immediately\n * prior (via `readNudges`) and passes it here, so there is no second read to go stale. May throw\n * on a write failure — the caller decides how to handle that (index.ts allows the stop rather than\n * emit an unbounded block). */\nexport const bumpNudges = (counterPath: string, current: number): void => {\n writeFileSync(counterPath, `${String(current + 1)}\\n`);\n};\n\n/** POSIX single-quote a string for safe embedding in a hook command line. */\nexport const shellQuote = (s: string): string => `'${s.replace(/'/g, `'\\\\''`)}'`;\n\n/** The default hook command: this CLI re-invoked as the gate, carrying the same schema/budget\n * flags so the hook validates exactly as the caller intended. */\nexport const defaultHookCommand = (\n draftPath: string,\n opts: {\n readonly kind?: string;\n readonly schema?: string;\n readonly schemaVersion?: string;\n readonly maxNudges?: string;\n readonly counter?: string;\n },\n): string =>\n [\n \"code-review stop-gate --draft\",\n shellQuote(draftPath),\n ...(opts.kind ? [\"--kind\", shellQuote(opts.kind)] : []),\n ...(opts.schema ? [\"--schema\", shellQuote(opts.schema)] : []),\n ...(opts.schemaVersion ? [\"--schema-version\", shellQuote(opts.schemaVersion)] : []),\n ...(opts.maxNudges ? [\"--max-nudges\", shellQuote(opts.maxNudges)] : []),\n ...(opts.counter ? [\"--counter\", shellQuote(opts.counter)] : []),\n ].join(\" \");\n\n/** The settings object that wires `command` as a Stop hook. */\nexport const stopHookSettings = (command: string): StopHookSettings => ({\n hooks: { Stop: [{ hooks: [{ type: \"command\", command }] }] },\n});\n","#!/usr/bin/env node\n// CLI entry point — citty subcommands for render, inline, post, cost, validate, adapt, extract,\n// validate-patches, print-schema, stop-gate.\n\n/* eslint-disable @typescript-eslint/require-await */\n// citty requires async run() even when the body has no explicit await\n\nimport { defineCommand, runMain } from \"citty\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Either } from \"fp-ts/Either\";\nimport { render } from \"./render.js\";\nimport { buildInlineComments, renderStraysSection } from \"./inline.js\";\nimport { computeCost } from \"./cost.js\";\nimport { validateAgainstSchema, unsafeUnwrap } from \"./validate.js\";\nimport { ResultEnvelopeCodec, FindingsCodec, PriceMapCodec, TestSummaryCodec } from \"./schema.js\";\nimport type { Triage, Finding } from \"./schema.js\";\nimport { post } from \"./post.js\";\nimport { gather, renderOutputs } from \"./gather.js\";\nimport { adapt, isAdapterName } from \"./adapt.js\";\nimport type { AdapterName } from \"./adapt.js\";\nimport { extractStructured, describeLadderFailure, ladderFailureDiagnostics } from \"./extract.js\";\nimport type { ExtractKind, LadderOutcome } from \"./extract.js\";\nimport { schemaPathFor, declaredVersion } from \"./registry.js\";\nimport type { SchemaKind } from \"./registry.js\";\nimport { validatePatch } from \"./patch.js\";\nimport {\n decideGate,\n draftState,\n readNudges,\n bumpNudges,\n defaultHookCommand,\n stopHookSettings,\n} from \"./stop-gate.js\";\n\nconst readJSON = (path: string): unknown => {\n try {\n return JSON.parse(readFileSync(resolve(path), \"utf-8\")) as unknown;\n } catch (err) {\n fail(`Cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`);\n throw new Error(\"unreachable\", { cause: err }); // fail() always exits\n }\n};\n\nconst fail = (msg: string): never => {\n process.stderr.write(`${msg}\\n`);\n process.exit(1);\n};\n\nconst decode = <A>(either: Either<unknown, A>, label: string): A => {\n try {\n return unsafeUnwrap(either);\n } catch {\n fail(`${label} does not match expected shape`);\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Unwrap an adapter's Either, surfacing its own message rather than a generic one. */\nconst unwrapAdapt = <A>(either: Either<string, A>): A => {\n try {\n if (either._tag === \"Left\") throw new Error(either.left);\n return either.right;\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Resolve a path bundled with the package (schema/, templates/) — same pattern as validate's default schema. */\nconst bundledPath = (...segments: string[]): string =>\n resolve(import.meta.dirname, \"..\", ...segments);\n\nconst packageVersion = (\n JSON.parse(readFileSync(bundledPath(\"package.json\"), \"utf-8\")) as { version: string }\n).version;\n\n/** `--template` defaults to the bundled comment template when omitted. */\nconst resolveTemplatePath = (templateArg: string | undefined): string =>\n templateArg ? resolve(templateArg) : bundledPath(\"templates\", \"comment.eta\");\n\n/** `--inline-template` defaults to the bundled inline template when omitted (inline.eta is the\n * per-surface SSOT — issue #22 — mirroring resolveTemplatePath's sticky default). */\nconst resolveInlineTemplatePath = (templateArg: string | undefined): string =>\n templateArg ? resolve(templateArg) : bundledPath(\"templates\", \"inline.eta\");\n\n/** Price-map resolution with explicit provenance: `provided` is a real caller-supplied map,\n * `absent` is the bundled all-zero example standing in for one (loaded only to satisfy the codec /\n * computeCost shape). The render layer is TOLD which, so it reports cost as N/A rather than a false\n * $0.00 when absent (SPEC §6.2) — never inferring it from the path. */\ntype PriceResolution =\n | { readonly kind: \"provided\"; readonly path: string }\n | { readonly kind: \"absent\"; readonly path: string };\n\n/** `--prices` defaults to the bundled (all-zero) example prices when omitted, with a warning. */\nconst resolvePrices = (pricesArg: string | undefined): PriceResolution => {\n if (pricesArg) return { kind: \"provided\", path: resolve(pricesArg) };\n process.stderr.write(\n \"code-review: no --prices given — cost will be reported as N/A (no price map to recompute from)\\n\",\n );\n return { kind: \"absent\", path: bundledPath(\"schema\", \"prices.example.json\") };\n};\n\nconst TEST_REPORT_DESCRIPTION =\n 'Path to a JSON test summary: {\"passed\": number, \"failed\": number, \"total\": number, \"failures\"?: [{\"name\": string, \"message\"?: string}]}';\n\nconst renderCmd = defineCommand({\n meta: {\n name: \"render\",\n description: \"Render a code-review comment from findings + usage + prices\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n template: {\n type: \"string\",\n description: \"Path to Eta template file (default: bundled templates/comment.eta)\",\n },\n usage: {\n type: \"string\",\n description: \"Path to result envelope JSON (from agent CLI)\",\n required: true,\n },\n prices: {\n type: \"string\",\n description:\n \"Path to price map JSON (default: bundled schema/prices.example.json — all zero)\",\n },\n \"reviewed-sha\": {\n type: \"string\",\n description: \"SHA of the last reviewed commit\",\n },\n route: {\n type: \"string\",\n description:\n \"Review route label; overrides the envelope's route when set (default: read from the envelope)\",\n },\n effort: {\n type: \"string\",\n description:\n \"Effort label; overrides the envelope's effort when set (default: read from the envelope)\",\n },\n \"test-report\": {\n type: \"string\",\n description: TEST_REPORT_DESCRIPTION,\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const envelope = decode(ResultEnvelopeCodec.decode(readJSON(args.usage)), \"envelope\");\n const templatePath = resolveTemplatePath(args.template);\n const priceResolution = resolvePrices(args.prices);\n const prices = decode(PriceMapCodec.decode(readJSON(priceResolution.path)), \"prices\");\n const template = readFileSync(templatePath, \"utf-8\");\n const testReport = args[\"test-report\"]\n ? decode(TestSummaryCodec.decode(readJSON(args[\"test-report\"])), \"test report\")\n : undefined;\n const output = render({\n findings,\n envelope,\n prices,\n pricesProvided: priceResolution.kind === \"provided\",\n template,\n reviewedSha: args[\"reviewed-sha\"],\n route: args.route,\n effort: args.effort,\n testReport,\n });\n process.stdout.write(output);\n },\n});\n\nconst inlineCmd = defineCommand({\n meta: {\n name: \"inline\",\n description: \"Build GitHub reviews comments[] payload from findings + diff\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n diff: {\n type: \"string\",\n description: \"Path to PR diff file\",\n required: true,\n },\n template: {\n type: \"string\",\n description: \"Path to inline comment Eta template (default: bundled templates/inline.eta)\",\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const diff = readFileSync(resolve(args.diff), \"utf-8\");\n const inlineTemplate = readFileSync(resolveInlineTemplatePath(args.template), \"utf-8\");\n const { comments, strays } = buildInlineComments(findings.findings, diff, {\n inlineTemplate,\n findings,\n });\n process.stdout.write(\n JSON.stringify({ comments, strays, stray_markdown: renderStraysSection(strays) }, null, 2),\n );\n },\n});\n\nconst costCmd = defineCommand({\n meta: {\n name: \"cost\",\n description: \"Recompute USD cost from the envelope's models array + price map\",\n },\n args: {\n envelope: {\n type: \"positional\",\n description: \"Path to result envelope JSON\",\n required: true,\n },\n prices: {\n type: \"string\",\n description: \"Path to price map JSON\",\n required: true,\n },\n },\n run: async ({ args }) => {\n const envelope = decode(ResultEnvelopeCodec.decode(readJSON(args.envelope)), \"envelope\");\n const prices = decode(PriceMapCodec.decode(readJSON(args.prices)), \"prices\");\n const report = computeCost(envelope.models, prices);\n process.stdout.write(JSON.stringify(report, null, 2));\n },\n});\n\n/** The version to derive when neither --schema nor --schema-version is given: findings carries its\n * version in-data; triage/prices have no in-data signal (see registry.ts), so undefined selects the\n * registry default (latest) for the kind. */\nconst derivedSchemaVersion = (kind: SchemaKind, raw: unknown): string | undefined =>\n kind === \"findings\" ? declaredVersion(raw) : undefined;\n\nconst validateCmd = defineCommand({\n meta: {\n name: \"validate\",\n description: \"Validate a findings/triage/prices JSON document against the canonical schema\",\n },\n args: {\n document: {\n type: \"positional\",\n description: \"Path to the JSON document to validate (of the given --kind)\",\n required: true,\n },\n kind: {\n type: \"string\",\n description:\n \"Schema kind to validate against: findings | triage | prices (default: findings)\",\n },\n schema: {\n type: \"string\",\n description:\n \"Path to a schema file (wins over --kind; default: the bundled schema derived from --kind, --schema-version, the document's declared schema_version, or the bundled latest)\",\n },\n \"schema-version\": {\n type: \"string\",\n description:\n \"Schema major.minor version to validate against (default: the document's declared schema_version for findings, or the kind's latest)\",\n },\n },\n run: async ({ args }) => {\n const kind = requireSchemaKind(args.kind || \"findings\");\n const documentRaw = readJSON(args.document);\n const schemaPath = args.schema\n ? resolve(args.schema)\n : requireSchemaPath(kind, args[\"schema-version\"] || derivedSchemaVersion(kind, documentRaw));\n const { valid, errors } = validateAgainstSchema(documentRaw, schemaPath);\n if (valid) {\n process.stdout.write(\"✅ valid\\n\");\n } else {\n process.stderr.write(\"❌ invalid\\n\");\n for (const e of errors) process.stderr.write(` - ${e}\\n`);\n process.exit(1);\n }\n },\n});\n\nconst adaptCmd = defineCommand({\n meta: {\n name: \"adapt\",\n description: \"Map a native agent-CLI result envelope onto the abstract SPEC §6.1 envelope\",\n },\n args: {\n native: {\n type: \"positional\",\n description: \"Path to the native result envelope JSON (from the agent CLI)\",\n required: true,\n },\n adapter: {\n type: \"string\",\n description: 'Adapter to use (currently: \"claude-code\")',\n required: true,\n },\n \"agent-file\": {\n type: \"string\",\n description:\n \"Path to a file the agent was told to write its own validated findings JSON to (wins over the native envelope's structured_output/result when it validates)\",\n },\n route: {\n type: \"string\",\n description:\n 'Review route label to stamp into the envelope (e.g. \"full review\" or \"mechanic\")',\n },\n effort: {\n type: \"string\",\n description: 'Effort label to stamp into the envelope (e.g. \"max\" or \"low\")',\n },\n },\n run: async ({ args }) => {\n const envelope = unwrapAdapt(\n adapt(requireAdapterName(args.adapter), readJSON(args.native), args[\"agent-file\"], {\n route: args.route,\n effort: args.effort,\n }),\n );\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n },\n});\n\nconst isExtractSchemaKind = (s: string): s is ExtractKind => s === \"findings\" || s === \"triage\";\n\n/** Narrow to a schema kind the extraction ladder supports (no \"prices\" — unlike print-schema's),\n * or fail with a clear message (never falls through). */\nconst requireExtractSchemaKind = (name: string): ExtractKind => {\n if (isExtractSchemaKind(name)) return name;\n fail(`Unknown kind \"${name}\" for extract — expected one of: findings, triage`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Fail-closed triage synthesized when the ladder can't recover a validated triage verdict — never\n * defaults to safe (§7.3). */\nconst failClosedTriage = (outcome: Exclude<LadderOutcome, { kind: \"ok\" }>): Triage => ({\n safe: false,\n reasons: describeLadderFailure(outcome),\n});\n\nconst extractCmd = defineCommand({\n meta: {\n name: \"extract\",\n description:\n \"Recover findings/triage JSON from a native agent-CLI result envelope via the deterministic extraction ladder\",\n },\n args: {\n native: {\n type: \"positional\",\n description: \"Path to the native result envelope JSON (from the agent CLI)\",\n required: true,\n },\n adapter: {\n type: \"string\",\n description: 'Adapter whose native envelope shape to extract from (currently: \"claude-code\")',\n required: true,\n },\n kind: {\n type: \"string\",\n description: \"Schema kind to extract: findings | triage\",\n required: true,\n },\n \"agent-file\": {\n type: \"string\",\n description:\n \"Path to a file the agent was told to write its own validated JSON to (findings only — a documented no-op for triage)\",\n },\n },\n run: async ({ args }) => {\n requireAdapterName(args.adapter);\n const kind = requireExtractSchemaKind(args.kind);\n const input = { kind, native: readJSON(args.native), agentFilePath: args[\"agent-file\"] };\n const outcome = extractStructured(input);\n\n if (outcome.kind === \"ok\") {\n process.stdout.write(`${JSON.stringify(outcome.candidate, null, 2)}\\n`);\n return;\n }\n // A recovery miss is otherwise opaque (only the generic reason reaches the comment); trace what\n // each rung saw to stderr so the CI log alone explains the failure — no local repro needed.\n if (outcome.kind === \"none\" || outcome.kind === \"ambiguous\") {\n process.stderr.write(`extract: recovery failed —\\n${ladderFailureDiagnostics(input)}\\n`);\n }\n if (kind === \"triage\") {\n process.stdout.write(`${JSON.stringify(failClosedTriage(outcome), null, 2)}\\n`);\n return;\n }\n fail(describeLadderFailure(outcome));\n },\n});\n\n/** `finding` with its `patch` field removed — a fresh shallow copy, `finding` itself untouched. */\nconst withoutPatch = (finding: Finding): Finding => {\n const copy = { ...finding };\n delete copy.patch;\n return copy;\n};\n\n/** A file's lines, LF-split and without a trailing-newline artifact entry; null when unreadable. */\nconst readFileLines = (path: string): readonly string[] | null => {\n try {\n const rawLines = readFileSync(path, \"utf-8\").split(\"\\n\");\n return rawLines.length > 0 && rawLines[rawLines.length - 1] === \"\"\n ? rawLines.slice(0, -1)\n : rawLines;\n } catch {\n return null;\n }\n};\n\n/** Validate one finding's `patch` (when present) against the real file at `<repoRoot>/<finding.path>`,\n * aligning the finding's `start_line`/`end_line` to the patch's removed range and KEEPING the patch\n * for the renderer to project. Drop the patch (logging why to stderr) when the file can't be read\n * or the patch doesn't apply cleanly — the finding survives without it, never writing a suggestion.\n * A finding with no patch passes through untouched. Never throws. */\nconst validateFinding = (finding: Finding, repoRoot: string): Finding => {\n if (finding.patch === undefined || finding.patch === null) return finding;\n const lines = readFileLines(resolve(repoRoot, finding.path));\n if (lines === null) {\n process.stderr.write(\n `validate-patches: ${finding.path}: could not read file at \"${repoRoot}\" — dropping patch\\n`,\n );\n return withoutPatch(finding);\n }\n const result = validatePatch(finding.patch, lines);\n if (\"kind\" in result) {\n process.stderr.write(\n `validate-patches: ${finding.path}:${String(finding.start_line)}: ${result.reason} — dropping patch\\n`,\n );\n return withoutPatch(finding);\n }\n return { ...finding, start_line: result.startLine, end_line: result.endLine };\n};\n\nconst validatePatchesCmd = defineCommand({\n meta: {\n name: \"validate-patches\",\n description:\n \"Validate each finding's patch against the real PR-head tree, aligning the finding's range to it and keeping the patch, or dropping the patch (issue #10)\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n \"repo-root\": {\n type: \"string\",\n description:\n \"Directory to resolve each finding's path against — the review job's checked-out, clean PR-head tree (default: .)\",\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const repoRoot = args[\"repo-root\"] ? resolve(args[\"repo-root\"]) : process.cwd();\n const validated = {\n ...findings,\n findings: findings.findings.map((f) => validateFinding(f, repoRoot)),\n };\n process.stdout.write(`${JSON.stringify(validated, null, 2)}\\n`);\n },\n});\n\n/** Narrow to a known adapter name, or fail with a clear message (never falls through). */\nconst requireAdapterName = (name: string): AdapterName => {\n if (isAdapterName(name)) return name;\n fail(`Unknown adapter \"${name}\" — supported: claude-code`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\nconst isSchemaKind = (s: string): s is SchemaKind =>\n s === \"findings\" || s === \"triage\" || s === \"prices\";\n\n/** Narrow to a known schema kind, or fail with a clear message (never falls through). */\nconst requireSchemaKind = (name: string): SchemaKind => {\n if (isSchemaKind(name)) return name;\n fail(`Unknown schema \"${name}\" — expected one of: findings, triage, prices`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Resolve a bundled schema path via the registry, or fail listing what's supported. */\nconst requireSchemaPath = (kind: SchemaKind, version: string | undefined): string => {\n try {\n return schemaPathFor(kind, version);\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\nconst printSchemaCmd = defineCommand({\n meta: {\n name: \"print-schema\",\n description:\n \"Print a bundled schema JSON, ready to hand to a CLI's --json-schema (the $schema draft declaration is stripped)\",\n },\n args: {\n name: {\n type: \"positional\",\n description: \"Schema to print: findings | triage | prices\",\n required: true,\n },\n \"schema-version\": {\n type: \"string\",\n description: \"Schema major.minor version to print (default: latest)\",\n },\n },\n run: async ({ args }) => {\n const schemaKind = requireSchemaKind(args.name);\n const schemaPath = requireSchemaPath(schemaKind, args[\"schema-version\"]);\n const schema = JSON.parse(readFileSync(schemaPath, \"utf-8\")) as Record<string, unknown>;\n // `claude -p --json-schema` silently disables structured-output enforcement when the schema\n // carries a top-level `$schema` draft declaration — `structured_output` comes back null and the\n // model guesses field names. The canonical file keeps `$schema` for validators; the form handed\n // to a CLI must omit it. `$id`/`title` are tolerated and kept.\n const enforcementSchema = Object.fromEntries(\n Object.entries(schema).filter(([key]) => key !== \"$schema\"),\n );\n process.stdout.write(`${JSON.stringify(enforcementSchema, null, 2)}\\n`);\n },\n});\n\nconst MAX_NUDGES_DEFAULT = 5;\n\n/** Drain the Stop-hook payload delivered on stdin so the caller never sees EPIPE; its content is\n * not needed — the decision comes from the draft on disk. Skips draining on a TTY (an interactive,\n * manual run with nothing piped in) since readFileSync(0) would otherwise block forever waiting\n * for EOF that never comes; absent/empty piped stdin otherwise is fine.\n * DEFERRED (known low-risk edge): a pipe held open without data + EOF could still block here, but\n * the real Stop hook writes its payload then closes (EOF), and the TTY case is guarded above, so\n * the held-open-forever case isn't the production path. Revisit only if hangs are observed. */\nconst drainStdin = (): void => {\n if (process.stdin.isTTY) return;\n try {\n readFileSync(0);\n } catch {\n // no stdin\n }\n};\n\n/** Parse `--max-nudges`: a strict positive integer (`>= 1`). A loose `Number.parseInt` accepts\n * `\"5abc\"`/`\"0x5\"` and `0 >= 0` allows on the first call — both silently DISABLE the gate. Reject\n * anything not matching `^\\d+$`, and reject `< 1`, loudly: a gate that never blocks must be an\n * explicit choice (omit the hook), never a typo. */\nconst requireMaxNudges = (raw: string | undefined): number => {\n if (raw === undefined) return MAX_NUDGES_DEFAULT;\n if (!/^\\d+$/.test(raw)) {\n fail(`--max-nudges must be a non-negative integer; got \"${raw}\"`);\n }\n const n = Number.parseInt(raw, 10);\n if (n < 1) {\n fail(`--max-nudges must be >= 1 — a gate that never blocks must be omitted, not set to ${raw}`);\n }\n return n;\n};\n\nconst stopGateCmd = defineCommand({\n meta: {\n name: \"stop-gate\",\n description:\n \"Claude Code Stop-hook gate: refuse to let the agent end its turn until --draft validates against the schema (bounded by --max-nudges). With --print-settings, emit the --settings JSON that wires this as the Stop hook.\",\n },\n args: {\n draft: {\n type: \"string\",\n description: \"Path to the findings document the agent must produce and keep valid\",\n required: true,\n },\n kind: {\n type: \"string\",\n description:\n \"Schema kind to validate against: findings | triage | prices (default: findings)\",\n },\n schema: { type: \"string\", description: \"Path to a schema file (wins over --kind)\" },\n \"schema-version\": {\n type: \"string\",\n description: \"Schema major.minor to validate against (default: the draft's declared version)\",\n },\n \"max-nudges\": {\n type: \"string\",\n description: `Times to block before relenting so the step fails downstream as before (default: ${String(MAX_NUDGES_DEFAULT)})`,\n },\n counter: {\n type: \"string\",\n description: \"Path for the nudge counter (default: <draft>.nudges)\",\n },\n \"print-settings\": {\n type: \"boolean\",\n description: \"Print the Stop-hook settings JSON that wires this gate, then exit\",\n },\n },\n run: async ({ args }) => {\n const draftPath = resolve(args.draft);\n\n if (args[\"print-settings\"]) {\n const command = defaultHookCommand(draftPath, {\n kind: args.kind,\n schema: args.schema,\n schemaVersion: args[\"schema-version\"],\n maxNudges: args[\"max-nudges\"],\n counter: args.counter,\n });\n process.stdout.write(`${JSON.stringify(stopHookSettings(command))}\\n`);\n return;\n }\n\n drainStdin();\n\n const kind = requireSchemaKind(args.kind || \"findings\");\n const maxNudges = requireMaxNudges(args[\"max-nudges\"]);\n const counterPath = args.counter ? resolve(args.counter) : `${draftPath}.nudges`;\n\n // schemaPathFor throws (rather than the process-exiting requireSchemaPath) so that a draft\n // declaring an unsupported schema_version is caught by draftState and treated as invalid —\n // i.e. a block with a helpful message — instead of crashing the hook and letting the agent stop.\n const state = draftState(draftPath, (parsed) =>\n args.schema\n ? resolve(args.schema)\n : schemaPathFor(kind, args[\"schema-version\"] || derivedSchemaVersion(kind, parsed)),\n );\n\n const nudges = readNudges(counterPath);\n const decision = decideGate(state, nudges, maxNudges, draftPath, kind);\n if (decision.kind === \"block\") {\n // CRITICAL ordering: bump the counter FIRST, and emit the block ONLY after the increment is\n // durably persisted. If the write fails, do NOT block — a block we can't bound loops forever\n // (the counter never advances → `nudges >= maxNudges` is never reached). Allow the stop and\n // log: a missed nudge is far less bad than an unbounded block loop.\n try {\n bumpNudges(counterPath, nudges);\n } catch (err) {\n process.stderr.write(\n `stop-gate: cannot persist nudge counter at ${counterPath} → allowing to avoid an unbounded block loop: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return;\n }\n process.stdout.write(`${JSON.stringify({ decision: \"block\", reason: decision.reason })}\\n`);\n }\n },\n});\n\nconst gatherCmd = defineCommand({\n meta: {\n name: \"gather\",\n description:\n \"Resolve the PR from the CI head SHA and gather review inputs (diff with git-diff fallback, PR context, prior bot review, failing-job logs) as files for the review agent\",\n },\n args: {\n repo: { type: \"string\", description: \"Repository (owner/name)\", required: true },\n \"head-sha\": {\n type: \"string\",\n description: \"Trusted head SHA to resolve the PR (from workflow_run.head_sha)\",\n required: true,\n },\n \"head-branch\": {\n type: \"string\",\n description: \"Head branch to disambiguate the PR when multiple share a commit\",\n },\n \"run-id\": {\n type: \"string\",\n description:\n \"CI run id (from workflow_run.id); its failing jobs' logs are downloaded on failure\",\n required: true,\n },\n conclusion: {\n type: \"string\",\n description:\n \"CI conclusion (e.g. success | failure); failure triggers failing-job log download\",\n required: true,\n },\n \"bot-login\": {\n type: \"string\",\n description:\n \"Bot login whose last PR comment is captured as prior review (default: github-actions[bot])\",\n },\n \"out-dir\": {\n type: \"string\",\n description: \"Directory to write gathered files into (default: current directory)\",\n },\n },\n run: async ({ args }) => {\n const result = await gather({\n repo: args.repo,\n headSha: args[\"head-sha\"],\n headBranch: args[\"head-branch\"],\n runId: args[\"run-id\"],\n conclusion: args.conclusion,\n botLogin: args[\"bot-login\"] || \"github-actions[bot]\",\n outDir: args[\"out-dir\"] ? resolve(args[\"out-dir\"]) : process.cwd(),\n });\n process.stdout.write(renderOutputs(result));\n },\n});\n\nconst postCmd = defineCommand({\n meta: {\n name: \"post\",\n description:\n \"Post a complete review (inline comments + sticky summary) from findings + envelope + diff\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n \"head-sha\": {\n type: \"string\",\n description: \"Trusted head SHA to resolve the PR (from workflow_run.head_sha)\",\n required: true,\n },\n repo: {\n type: \"string\",\n description: \"Repository (owner/name)\",\n required: true,\n },\n usage: {\n type: \"string\",\n description: \"Path to result envelope JSON (from agent CLI)\",\n required: true,\n },\n prices: {\n type: \"string\",\n description:\n \"Path to price map JSON (default: bundled schema/prices.example.json — all zero)\",\n },\n template: {\n type: \"string\",\n description:\n \"Path to Eta template file for the summary comment (default: bundled templates/comment.eta)\",\n },\n \"inline-template\": {\n type: \"string\",\n description: \"Path to inline comment Eta template (default: bundled templates/inline.eta)\",\n },\n route: {\n type: \"string\",\n description:\n \"Review route label; overrides the envelope's route when set (default: read from the envelope)\",\n },\n \"bot-login\": {\n type: \"string\",\n description: \"Bot login to trust for sticky comment upsert (default: github-actions[bot])\",\n },\n \"head-branch\": {\n type: \"string\",\n description: \"Head branch to disambiguate PR when multiple share a commit\",\n },\n effort: {\n type: \"string\",\n description:\n \"Effort label; overrides the envelope's effort when set (default: read from the envelope)\",\n },\n \"test-report\": {\n type: \"string\",\n description: TEST_REPORT_DESCRIPTION,\n },\n \"run-url\": {\n type: \"string\",\n description:\n \"Workflow run URL (transcript/traces), rendered as a link in the LLM Disclosure aside\",\n },\n \"json-url\": {\n type: \"string\",\n description:\n \"URL to the machine-readable findings JSON artifact, pointed at from the sticky and each inline comment\",\n },\n },\n run: async ({ args }) => {\n const priceResolution = resolvePrices(args.prices);\n await post({\n repo: args.repo,\n headSha: args[\"head-sha\"],\n botLogin: args[\"bot-login\"] || \"github-actions[bot]\",\n findingsPath: args.findings,\n envelopePath: args.usage,\n pricesPath: priceResolution.path,\n pricesProvided: priceResolution.kind === \"provided\",\n templatePath: resolveTemplatePath(args.template),\n inlineTemplatePath: resolveInlineTemplatePath(args[\"inline-template\"]),\n route: args.route,\n headBranch: args[\"head-branch\"],\n effort: args.effort,\n testReportPath: args[\"test-report\"],\n runUrl: args[\"run-url\"],\n jsonUrl: args[\"json-url\"],\n });\n },\n});\n\nexport const main = defineCommand({\n meta: {\n name: \"code-review\",\n version: packageVersion,\n description:\n \"Deterministic commenter for agentic PR review — gather, render, inline, post, adapt, extract, validate-patches, cost, validate, and stop-gate findings JSON\",\n },\n subCommands: {\n gather: gatherCmd,\n render: renderCmd,\n inline: inlineCmd,\n post: postCmd,\n cost: costCmd,\n validate: validateCmd,\n adapt: adaptCmd,\n extract: extractCmd,\n \"validate-patches\": validatePatchesCmd,\n \"print-schema\": printSchemaCmd,\n \"stop-gate\": stopGateCmd,\n },\n});\n\n// Skip auto-invocation under the test runner — tests drive `main` directly via citty's runCommand.\nif (!process.env[\"VITEST\"]) {\n await runMain(main);\n}\n"]}
1
+ {"version":3,"sources":["../src/cost.ts","../src/patch.ts","../src/surface.ts","../src/render.ts","../src/diff.ts","../src/inline.ts","../src/schema.ts","../src/validate.ts","../src/format.ts","../src/registry.ts","../src/gh.ts","../src/pr.ts","../src/post.ts","../src/gather.ts","../src/extract.ts","../src/adapt.ts","../src/stop-gate.ts","../src/index.ts"],"names":["Eta","key","resolvePath","resolve","readFileSync","reviewUrl","execFile","t2","scanLine","t3","writeFileSync"],"mappings":";;;;;;;;;;;;AA0BA,IAAM,WAAA,GAAoB,CAAC,OAAA,KAAY;AACrC,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,OAAO;AAAA,CAAI,CAAA;AACrC,CAAA;AAEA,IAAM,gBAAA,GAAmB,CAAC,KAAA,EAAwB,MAAA,EAAkB,IAAA,KAAyB;AAC3F,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA;AACnC,EAAA,MAAM,SAAA,GAAY,MAAM,iBAAA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mBAAA,CAAoB,IAAA,CAAK,QAAQ,CAAA;AAAA,MAC/C,kBAAA,EAAoB,yBAAA,CAA0B,IAAA,CAAK,iBAAiB,CAAC,CAAA;AAAA,MACrE,OAAO,IAAA,CAAK,KAAA;AAAA,MACZ,UAAA,EAAY,KAAK,aAAa,CAAA;AAAA,MAC9B,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,cAAA,EAAgB,KAAK,aAAa,CAAA;AAAA,MAClC,MAAA,EAAQ,KAAK,SAAS,CAAA;AAAA,MACtB,OAAA,EAAS,KAAK,UAAU,CAAA;AAAA,MACxB,QAAA,EAAU,SAAA,iBAAU,IAAI,IAAA,EAAM;AAAA,KAC/B,CAAA;AAAA,EACH;AACF,CAAC,CAAA;AAEM,IAAM,OAAO,aAAA,CAAc;AAAA,EAChC,IAAA,EAAM;AAAA,IACJ,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS,cAAA;AAAA,IACT,WAAA,EACE;AAAA,GACJ;AAAA,EACA,WAAA,EAAa;AAAA,IACX,MAAA,EAAQ,SAAA;AAAA,IACR,MAAA,EAAQ,SAAA;AAAA,IACR,MAAA,EAAQ,SAAA;AAAA,IACR,IAAA,EAAM,OAAA;AAAA,IACN,IAAA,EAAM,OAAA;AAAA,IACN,QAAA,EAAU,WAAA;AAAA,IACV,KAAA,EAAO,QAAA;AAAA,IACP,OAAA,EAAS,UAAA;AAAA,IACT,kBAAA,EAAoB,kBAAA;AAAA,IACpB,cAAA,EAAgB,cAAA;AAAA,IAChB,WAAA,EAAa;AAAA;AAEjB,CAAC;AAGD,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC1B,EAAA,MAAM,QAAQ,IAAI,CAAA;AACpB","file":"index.js","sourcesContent":["// Pure cost computation from the abstract envelope's `models` array + price map.\n// Recomputes USD because the CLI's vendor_cost_usd is vendor-priced (SPEC §6.2).\n// Pure core: side effects (unknown-model warnings) are threaded via a `warn` callback.\n\nimport type { PriceMap, ModelUsageEntry } from \"./schema.js\";\n\nexport interface CostLine {\n readonly model: string;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly cacheReadTokens: number;\n readonly cacheWriteTokens: number;\n readonly costUSD: number;\n}\n\nexport interface CostReport {\n readonly lines: readonly CostLine[];\n readonly totalInputTokens: number;\n readonly totalOutputTokens: number;\n readonly totalCacheReadTokens: number;\n readonly totalCacheWriteTokens: number;\n readonly totalCostUSD: number;\n}\n\nexport type Warn = (message: string) => void;\n\nconst defaultWarn: Warn = (message) => {\n process.stderr.write(`${message}\\n`);\n};\n\nconst computeModelCost = (entry: ModelUsageEntry, prices: PriceMap, warn: Warn): CostLine => {\n const p = prices.models[entry.model];\n const cacheRead = entry.cache_read_tokens ?? 0;\n const cacheWrite = entry.cache_write_tokens ?? 0;\n if (!p) {\n warn(\n `code-review cost: unknown model \"${entry.model}\" — no entry in price map; cost for this model set to $0`,\n );\n return {\n model: entry.model,\n inputTokens: entry.input_tokens,\n outputTokens: entry.output_tokens,\n cacheReadTokens: cacheRead,\n cacheWriteTokens: cacheWrite,\n costUSD: 0,\n };\n }\n const costUSD =\n (entry.input_tokens * p.in +\n entry.output_tokens * p.out +\n cacheRead * p.cache_read +\n cacheWrite * p.cache_write) /\n 1_000_000;\n return {\n model: entry.model,\n inputTokens: entry.input_tokens,\n outputTokens: entry.output_tokens,\n cacheReadTokens: cacheRead,\n cacheWriteTokens: cacheWrite,\n costUSD,\n };\n};\n\n/** Recompute cost from the envelope's `models` array against a price map. Pure given a `warn` sink. */\nexport const computeCost = (\n models: readonly ModelUsageEntry[],\n prices: PriceMap,\n warn: Warn = defaultWarn,\n): CostReport => {\n const lines = models.map((entry) => computeModelCost(entry, prices, warn));\n\n return {\n lines,\n totalInputTokens: lines.reduce((s, l) => s + l.inputTokens, 0),\n totalOutputTokens: lines.reduce((s, l) => s + l.outputTokens, 0),\n totalCacheReadTokens: lines.reduce((s, l) => s + l.cacheReadTokens, 0),\n totalCacheWriteTokens: lines.reduce((s, l) => s + l.cacheWriteTokens, 0),\n totalCostUSD: lines.reduce((s, l) => s + l.costUSD, 0),\n };\n};\n","// Pure patch helpers (issue #10): a review agent's own unified-diff patch of an edit it actually\n// made is either validated against the real PR-head file (to align a finding's range and confirm it\n// still applies) or projected into a GitHub suggestion's replacement text — two concerns split into\n// two pure functions over one shared hunk parser (SSOT). Eliminates the bad-suggestion bug class\n// caused by hand-authored suggestions with wrong indentation or too-wide ranges. Assumes LF line\n// endings (the review runs on Linux); CRLF handling is out of scope.\n\n/** The file-anchored range a patch's removed lines occupy — what a suggestion replaces. */\nexport type ValidateResult =\n | { readonly startLine: number; readonly endLine: number }\n | { readonly kind: \"drop\"; readonly reason: string };\n\n/** The replacement text a patch's added lines carry — a suggestion's body. */\nexport type SuggestionResult = string | { readonly kind: \"drop\"; readonly reason: string };\n\ntype BodyLine =\n | { readonly kind: \"context\"; readonly text: string }\n | { readonly kind: \"removed\"; readonly text: string }\n | { readonly kind: \"added\"; readonly text: string };\n\nconst HUNK_HEADER_RE = /^@@ -(\\d+)(?:,\\d+)? \\+\\d+(?:,\\d+)? @@/;\n\n/** The hunk's `-a` value when `line` is a hunk header, else null. */\nconst hunkOldStart = (line: string): number | null => {\n const raw = HUNK_HEADER_RE.exec(line)?.[1];\n return raw !== undefined ? Number(raw) : null;\n};\n\n/** Classify one hunk-body line by its leading marker char, stripping it; null when the line\n * carries none of the three markers (malformed). */\nconst classifyBodyLine = (line: string): BodyLine | null => {\n if (line.startsWith(\" \")) return { kind: \"context\", text: line.slice(1) };\n if (line.startsWith(\"-\")) return { kind: \"removed\", text: line.slice(1) };\n if (line.startsWith(\"+\")) return { kind: \"added\", text: line.slice(1) };\n return null;\n};\n\n/** The maximal run of non-context lines in the middle of `body`, once leading and trailing context\n * is trimmed — empty when `body` is all context (no change at all). */\nconst trimmedMiddle = (body: readonly BodyLine[]): readonly BodyLine[] => {\n const first = body.findIndex((l) => l.kind !== \"context\");\n if (first === -1) return [];\n const last = body.findLastIndex((l) => l.kind !== \"context\");\n return body.slice(first, last + 1);\n};\n\n/** True when `middle` (already trimmed of outer context) is zero-or-more removed lines followed by\n * zero-or-more added lines, with no context and no interleaving between them. */\nconst isContiguousChange = (middle: readonly BodyLine[]): boolean => {\n if (middle.some((l) => l.kind === \"context\")) return false;\n const firstAdded = middle.findIndex((l) => l.kind === \"added\");\n if (firstAdded === -1) return true;\n return (\n middle.slice(0, firstAdded).every((l) => l.kind === \"removed\") &&\n middle.slice(firstAdded).every((l) => l.kind === \"added\")\n );\n};\n\ninterface RemovedRange {\n readonly lineNumber: number;\n readonly firstRemoved: number | null;\n readonly lastRemoved: number | null;\n}\n\n/** Fold over the hunk body tracking the old-side line number (advanced by context and removed\n * lines, not by added lines), recording the first and last removed line's number. */\nconst removedRange = (body: readonly BodyLine[], oldStart: number): RemovedRange =>\n body.reduce<RemovedRange>(\n (acc, line) =>\n line.kind === \"added\"\n ? acc\n : {\n lineNumber: acc.lineNumber + 1,\n firstRemoved:\n line.kind === \"removed\" && acc.firstRemoved === null\n ? acc.lineNumber\n : acc.firstRemoved,\n lastRemoved: line.kind === \"removed\" ? acc.lineNumber : acc.lastRemoved,\n },\n { lineNumber: oldStart, firstRemoved: null, lastRemoved: null },\n );\n\nconst drop = (reason: string): { readonly kind: \"drop\"; readonly reason: string } => ({\n kind: \"drop\",\n reason,\n});\n\ntype ParsedHunk =\n | { readonly kind: \"ok\"; readonly oldStart: number; readonly body: readonly BodyLine[] }\n | { readonly kind: \"drop\"; readonly reason: string };\n\n/** Parse a single-hunk unified diff into its old-side start line + classified body — the SSOT both\n * `validatePatch` and `patchToSuggestion` share. Drops on !=1 hunk or a malformed body line. */\nconst parseHunk = (patch: string): ParsedHunk => {\n const rawLines = patch.split(\"\\n\");\n // A trailing newline in the patch text splits into a trailing \"\" element — not a line of content.\n const lines =\n rawLines.length > 0 && rawLines[rawLines.length - 1] === \"\" ? rawLines.slice(0, -1) : rawLines;\n\n const headerHits = lines.reduce<readonly { readonly index: number; readonly oldStart: number }[]>(\n (acc, line, index) => {\n const oldStart = hunkOldStart(line);\n return oldStart !== null ? [...acc, { index, oldStart }] : acc;\n },\n [],\n );\n if (headerHits.length !== 1) {\n return drop(`expected exactly one hunk, got ${String(headerHits.length)}`);\n }\n const hit = headerHits[0];\n if (hit === undefined) return drop(\"malformed hunk header\");\n\n // Header-preceding lines (diff --git/index/---/+++) are never examined — the hunk body starts\n // right after the header; a trailing \"\\" marker carries no content.\n const bodyRaw = lines.slice(hit.index + 1).filter((line) => !line.startsWith(\"\\\\\"));\n const classified = bodyRaw.map(classifyBodyLine);\n if (classified.some((line) => line === null)) return drop(\"malformed hunk body line\");\n const body = classified.filter((line): line is BodyLine => line !== null);\n\n return { kind: \"ok\", oldStart: hit.oldStart, body };\n};\n\n/** The issue-#10 guard: confirm a single-hunk unified diff still applies to the PR-head file\n * (`fileLines`, 0-indexed lines WITHOUT trailing newlines) and return the exact\n * `start_line..end_line` its removed lines occupy — for aligning the finding's range. Drops on a\n * context mismatch, a non-contiguous change, or a change with no removed lines to anchor. Pure. */\nexport const validatePatch = (patch: string, fileLines: readonly string[]): ValidateResult => {\n const parsed = parseHunk(patch);\n if (parsed.kind === \"drop\") return parsed;\n const { oldStart, body } = parsed;\n\n const oldSideTexts = body.filter((l) => l.kind !== \"added\").map((l) => l.text);\n const expected = fileLines.slice(oldStart - 1, oldStart - 1 + oldSideTexts.length);\n const oldSideMatches =\n expected.length === oldSideTexts.length &&\n expected.every((line, i) => line === oldSideTexts[i]);\n if (!oldSideMatches) {\n return drop(\n `patch context does not match the file at lines ${String(oldStart)}..${String(oldStart + oldSideTexts.length - 1)}`,\n );\n }\n\n if (!isContiguousChange(trimmedMiddle(body))) {\n return drop(\"change is not a single contiguous block\");\n }\n\n const removedCount = body.filter((l) => l.kind === \"removed\").length;\n const addedCount = body.filter((l) => l.kind === \"added\").length;\n if (removedCount === 0 && addedCount === 0) return drop(\"hunk contains no changes\");\n if (removedCount === 0) return drop(\"pure insertion has no range to anchor a suggestion\");\n\n const { firstRemoved, lastRemoved } = removedRange(body, oldStart);\n if (firstRemoved === null || lastRemoved === null) return drop(\"malformed hunk body\");\n\n return { startLine: firstRemoved, endLine: lastRemoved };\n};\n\n/** Project a single-hunk unified diff into a GitHub suggestion's replacement text (the added lines\n * alone) — no file needed. Drops a multi-hunk/malformed patch, a non-contiguous change, or a pure\n * insertion (nothing to replace). An all-deletion hunk yields \"\" (delete the range). Pure. */\nexport const patchToSuggestion = (patch: string): SuggestionResult => {\n const parsed = parseHunk(patch);\n if (parsed.kind === \"drop\") return parsed;\n const { body } = parsed;\n\n if (!isContiguousChange(trimmedMiddle(body))) {\n return drop(\"change is not a single contiguous block\");\n }\n\n const removedCount = body.filter((l) => l.kind === \"removed\").length;\n const addedLines = body.filter((l) => l.kind === \"added\");\n if (removedCount === 0 && addedLines.length === 0) return drop(\"hunk contains no changes\");\n if (removedCount === 0) return drop(\"pure insertion can't be expressed as a suggestion\");\n\n return addedLines.map((l) => l.text).join(\"\\n\");\n};\n","// Shared render-surface primitives — the single source of truth for the bits every render surface\n// (sticky, inline comment, review body) must agree on: the severity→emoji mapping, the\n// machine-readable findings-json pointer (issue #19), and the patch→suggestion projection. Pure.\n\nimport type { Findings } from \"./schema.js\";\nimport { patchToSuggestion } from \"./patch.js\";\n\n/** Severity → emoji, used by every render surface (sticky, inline, strays). */\nexport const severityEmoji = (s: string): string => {\n switch (s) {\n case \"critical\":\n return \"🔴\";\n case \"major\":\n return \"🟠\";\n case \"minor\":\n return \"🔵\";\n case \"nit\":\n return \"⚪\";\n default:\n return \"❓\";\n }\n};\n\n/** Base64 chars (~30KB JSON); keeps a comment well under GitHub's 65536-char comment limit. */\nconst EMBED_LIMIT = 40000;\n\n/** The directive that makes the marker below self-describing to a reviewing agent — travels with\n * the marker on every surface so a reader who only sees one comment still knows to decode it. */\nconst AGENTS_STOP_DIRECTIVE =\n \"<!-- AGENTS: STOP — do not parse the prose below; decode this findings JSON and read schema_version first. -->\";\n\n/** The machine-readable findings-json marker (issue #19), identical on every surface: embeds\n * `findings` as base64 when it fits under `limit`, falls back to a `jsonUrl` link marker, or\n * omits the marker entirely when neither is available. */\nexport const findingsPointer = (\n findings: Findings,\n jsonUrl: string | undefined,\n limit = EMBED_LIMIT,\n): string => {\n const b64 = Buffer.from(JSON.stringify(findings), \"utf-8\").toString(\"base64\");\n const marker =\n b64.length <= limit\n ? `<!-- code-review:findings-json;base64 ${b64} -->`\n : jsonUrl\n ? `<!-- code-review:findings-json ${jsonUrl} -->`\n : \"\";\n return marker ? `${AGENTS_STOP_DIRECTIVE}\\n${marker}` : \"\";\n};\n\n/** Escape triple-backtick sequences so fenced content can't break out of its block. */\nconst escapeFence = (text: string): string => text.replace(/```/g, \"`` ` ``\");\n\n/** How a finding's `patch` renders on a surface (JP's core design): a GitHub ```suggestion when the\n * patch lowers to replacement text (anchored at the finding's already-aligned range), a raw\n * ```patch fallback when it can't lower (non-lossy — the diff still reaches the reader), or nothing\n * when the finding carries no patch. Fenced content is backtick-escaped against breakout. */\nexport type PatchProjection =\n | { readonly kind: \"suggestion\"; readonly text: string }\n | { readonly kind: \"patch\"; readonly raw: string }\n | { readonly kind: \"none\" };\n\n/** Project a finding's `patch` into a template-ready {@link PatchProjection}. Pure. */\nexport const projectPatch = (patch: string | undefined): PatchProjection => {\n if (patch === undefined) return { kind: \"none\" };\n const lowered = patchToSuggestion(patch);\n return typeof lowered === \"string\"\n ? { kind: \"suggestion\", text: escapeFence(lowered) }\n : { kind: \"patch\", raw: escapeFence(patch) };\n};\n\n/** Confidence, always at 2 decimal places (issue #26 — `1` renders `1.00`, `0.6` renders `0.60`). */\nexport const formatConfidence = (n: number): string => n.toFixed(2);\n\n/** The review-object body: the shared findings-json marker (when present) followed by a one-line\n * pointer to the sticky summary, linking to it when its URL is known. The single source of truth\n * for this body, shared by the commenter (post.ts) and the `preview` command. Pure. */\nexport const reviewBodyPointer = (\n headSha: string,\n stickyUrl: string | undefined,\n marker: string,\n): string => {\n const sha7 = headSha.slice(0, 7);\n const linkLine = stickyUrl\n ? `🤖 Automated code review for \\`${sha7}\\` — see the [summary comment](${stickyUrl}) for the verdict, walkthrough, and cost.`\n : `🤖 Automated code review for \\`${sha7}\\` — see the summary comment for the verdict, walkthrough, and cost.`;\n return marker ? `${marker}\\n\\n${linkLine}` : linkLine;\n};\n","// Deterministic comment renderer. Takes findings + envelope + prices → comment markdown.\n// Uses Eta templates; pure data-in, string-out — no side effects, no model invocation.\n\nimport { Eta } from \"eta\";\nimport type { Finding, Severity } from \"./schema.js\";\nimport type { RenderInput, SeverityCounts } from \"./types.js\";\nimport { computeCost } from \"./cost.js\";\nimport { severityEmoji, findingsPointer, projectPatch, formatConfidence } from \"./surface.js\";\nimport type { PatchProjection } from \"./surface.js\";\n\n/** Escape pipe characters so they don't break markdown table columns. */\nconst escapePipes = (text: string): string => text.replace(/\\|/g, \"\\\\|\");\n\n/** Replace backticks so they don't break inline code spans. */\nconst escapeCodeBackticks = (text: string): string => text.replace(/`/g, \"-\");\n\n/** A stray finding with its sanitized fields plus its projected patch block for the strays list. */\ntype StrayView = Finding & { readonly patchProjection: PatchProjection };\n\n/** Sanitize a stray finding's fields and attach its patch projection for the strays section. */\nconst sanitizeFinding = (f: Finding): StrayView => ({\n ...f,\n title: escapePipes(f.title),\n path: escapeCodeBackticks(f.path),\n patchProjection: projectPatch(f.patch),\n});\n\nconst emptySeverityCounts = (): Record<Severity, number> => ({\n critical: 0,\n major: 0,\n minor: 0,\n nit: 0,\n});\n\n/** Tally findings by severity for the summary counts line. Ignores out-of-domain severities. */\nexport const computeSeverityCounts = (findings: readonly Finding[]): SeverityCounts =>\n findings.reduce<Record<Severity, number>>(\n (acc, f) => (f.severity in acc ? { ...acc, [f.severity]: acc[f.severity] + 1 } : acc),\n emptySeverityCounts(),\n );\n\n/** Render a code-review comment from findings, envelope, and prices. Pure. */\nexport const render = (input: RenderInput): string => {\n const eta = new Eta({ autoTrim: false });\n const usageAvailable = input.envelope !== null;\n const costReport = input.envelope ? computeCost(input.envelope.models, input.prices) : null;\n const pricesProvided = input.pricesProvided ?? true;\n const route = input.route ?? input.envelope?.route ?? null;\n const effort = input.effort ?? input.envelope?.effort ?? null;\n const modelNames = input.envelope ? input.envelope.models.map((m) => m.model).join(\", \") : \"\";\n\n return eta.renderString(input.template, {\n findings: input.findings,\n envelope: input.envelope,\n usageAvailable,\n costReport,\n pricesProvided,\n route,\n effort,\n modelNames,\n testReport: input.testReport ?? null,\n reviewedSha: input.reviewedSha ?? \"0000000000000000000000000000000000000000\",\n postedAt: input.postedAt ?? \"\",\n severityCounts: input.severityCounts ?? computeSeverityCounts(input.findings.findings),\n strays: (input.strays ?? []).map(sanitizeFinding),\n inlineDisposition: input.inlineDisposition ?? null,\n runUrl: input.runUrl ?? null,\n jsonUrl: input.jsonUrl ?? null,\n findingsPointer: input.findingsPointer ?? findingsPointer(input.findings, input.jsonUrl),\n reviewUrl: input.reviewUrl ?? null,\n formatTokens: (n: number): string =>\n Number.isFinite(n) && n >= 0 ? n.toLocaleString(\"en-US\") : \"—\",\n // Cost cells render N/A (never a false $0.00) when no real price map was provided — there are\n // real tokens spent, we simply have no rates to price them (SPEC §6.2).\n formatCost: (n: number): string =>\n !pricesProvided\n ? \"N/A\"\n : Number.isFinite(n)\n ? n > 0 && n.toFixed(2) === \"0.00\"\n ? \"<$0.01\"\n : `$${n.toFixed(2)}`\n : \"—\",\n formatDuration: (ms: number): string => {\n if (!Number.isFinite(ms) || ms < 0) return \"—\";\n const s = Math.round(ms / 1000);\n return s >= 60 ? `${String(Math.floor(s / 60))}m ${String(s % 60)}s` : `${String(s)}s`;\n },\n verdictBadge: (v: string): string => {\n switch (v) {\n case \"approve\":\n return \"✅ approved\";\n case \"comment\":\n return \"💬 comment\";\n case \"changes\":\n return \"🔧 changes requested\";\n default:\n return `❓ ${v}`;\n }\n },\n severityEmoji,\n formatConfidence,\n });\n};\n","// Pure functions for unified-diff parsing and line-in-diff validation.\n// Uses parse-diff for parsing; exports only clean functional interfaces.\n\nimport parseDiff from \"parse-diff\";\nimport type { Finding, Side } from \"./schema.js\";\n\n// A set of \"path:line\" keys present in the diff hunks (additions/changes).\n// Used to validate findings before posting inline comments.\nexport type DiffLineIndex = ReadonlySet<string>;\n\nconst key = (path: string, line: number): string => `${path}:${String(line)}`;\n\n/** Index a set of changes under a given file path. */\nconst indexChanges = (\n keys: Set<string>,\n fpath: string,\n changes: ReadonlyArray<{\n readonly type: \"normal\" | \"add\" | \"del\";\n readonly ln1?: number;\n readonly ln2?: number;\n readonly ln?: number;\n }>,\n): void => {\n for (const change of changes) {\n if (change.type === \"normal\") {\n if (change.ln1 !== undefined) keys.add(key(fpath, change.ln1));\n if (change.ln2 !== undefined) keys.add(key(fpath, change.ln2));\n } else if (change.ln !== undefined) {\n keys.add(key(fpath, change.ln));\n }\n }\n};\n\n/** Parse a unified diff string into a set of \"path:line\" keys for every line in the diff.\n * For renamed files, both old and new paths are indexed so findings on either path match. */\nexport const indexDiff = (diff: string): DiffLineIndex => {\n const files = parseDiff(diff);\n if (!Array.isArray(files)) return new Set();\n\n const keys = new Set<string>();\n for (const file of files) {\n // Deleted: file.to is /dev/null, use file.from\n // New: file.from is undefined, use file.to\n // Modified: both set and equal\n // Renamed: both set and differ → index both paths\n const primary = file.from ?? file.to;\n if (!primary) continue;\n\n indexChanges(\n keys,\n primary,\n file.chunks.flatMap((c) => c.changes),\n );\n\n // Also index under file.to for renames (when both paths exist and differ)\n if (file.to && file.to !== \"/dev/null\" && file.to !== primary) {\n indexChanges(\n keys,\n file.to,\n file.chunks.flatMap((c) => c.changes),\n );\n }\n }\n return keys;\n};\n\n/** Check whether a finding's anchor line appears in the diff. */\nexport const isInDiff = (index: DiffLineIndex, path: string, line: number): boolean =>\n index.has(key(path, line));\n\n/** True for a diff with no content or no hunks — nothing to review or anchor inline comments to. */\nexport const isEmptyDiff = (diff: string): boolean => {\n if (diff.trim().length === 0) return true;\n const files = parseDiff(diff);\n return !Array.isArray(files) || files.length === 0 || files.every((f) => f.chunks.length === 0);\n};\n\n/** Default side for inline comments: RIGHT for additions, LEFT for deletions. */\nexport const defaultSide = (side: string | undefined): Side => (side === \"LEFT\" ? \"LEFT\" : \"RIGHT\");\n\n/** Partition findings into in-diff and out-of-diff (strays). Strays get demoted to the summary. */\nexport const partitionFindings = (\n findings: readonly Finding[],\n index: DiffLineIndex,\n): {\n readonly inDiff: readonly Finding[];\n readonly strays: readonly Finding[];\n} => {\n const inDiff: Finding[] = [];\n const strays: Finding[] = [];\n for (const f of findings) {\n if (isInDiff(index, f.path, f.start_line) && isInDiff(index, f.path, f.end_line)) {\n inDiff.push(f);\n } else {\n strays.push(f);\n }\n }\n return { inDiff, strays };\n};\n","// Inline review payload builder. Validates findings against the diff,\n// builds the GitHub reviews API comments[] array, and demotes strays.\n\nimport { Eta } from \"eta\";\nimport { partitionFindings, indexDiff, defaultSide } from \"./diff.js\";\nimport { severityEmoji, findingsPointer, projectPatch, formatConfidence } from \"./surface.js\";\nimport type { Finding, Findings } from \"./schema.js\";\nimport type { InlineComment, InlineResult } from \"./types.js\";\n\n/** Backtick-wrapped, `/`-joined model names for the disclosure line (issue #16), falling back to\n * a plain phrase when no models are known. */\nconst formatModels = (models: readonly string[]): string =>\n models.length > 0 ? models.map((m) => `\\`${m}\\``).join(\"/\") : \"an AI model\";\n\n/** Render a finding's inline comment body via the inline Eta template (bundled by default — see\n * resolveInlineTemplatePath, index.ts). The template is the SSOT for all body text — severity\n * header, description, recommendation, the projected patch block, and the [!TIP] disclosure fold;\n * TS supplies only data. The patch is projected here (never a `suggestion` field — that field is\n * gone as of schema 0.4). */\nconst renderCommentBody = (\n f: Finding,\n eta: Eta,\n template: string,\n modelsText: string,\n jsonUrl: string | undefined,\n pointer: string,\n): string =>\n // Eta.renderString returns string | Promise<string>; with autoTrim:false it's always sync.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n eta.renderString(template, {\n ...f,\n patchProjection: projectPatch(f.patch),\n severityEmoji,\n formatConfidence,\n modelsText,\n jsonUrl: jsonUrl ?? null,\n findingsPointer: pointer,\n }) as string;\n\n/** Extra context threaded into each inline comment beyond the finding itself. */\nexport interface InlineContext {\n /** Eta template for each comment's body — bundled by default (index.ts's\n * resolveInlineTemplatePath), overridable via --inline-template. */\n readonly inlineTemplate: string;\n /** Model name(s) that produced the review, for the template's disclosure line (issue #16). */\n readonly models?: readonly string[];\n /** Findings-json artifact URL — the marker's fallback when the embedded form is too large (#19). */\n readonly jsonUrl?: string;\n /** The full findings document, embedded (or pointed at) via the shared marker (#19); omitted\n * when the caller has no whole document to embed (the marker is then omitted too). */\n readonly findings?: Findings;\n /** Precomputed findings-json marker (#19) — when set, used verbatim instead of recomputing from\n * `findings`/`jsonUrl`, so `post()` base64-encodes the findings once and reuses it here. */\n readonly findingsPointer?: string;\n}\n\n/** Build the GitHub reviews API comments[] array from in-diff findings. Strays are demoted. */\nexport const buildInlineComments = (\n findings: readonly Finding[],\n diff: string,\n context: InlineContext,\n): InlineResult => {\n const { inlineTemplate, models = [], jsonUrl, findings: fullFindings } = context;\n const index = indexDiff(diff);\n const { inDiff, strays } = partitionFindings(findings, index);\n const eta = new Eta({ autoTrim: false });\n const modelsText = formatModels(models);\n const pointer =\n context.findingsPointer ?? (fullFindings ? findingsPointer(fullFindings, jsonUrl) : \"\");\n\n const comments: InlineComment[] = inDiff.map((f) => {\n const comment: InlineComment = {\n path: f.path,\n line: f.end_line,\n side: defaultSide(f.side),\n body: renderCommentBody(f, eta, inlineTemplate, modelsText, jsonUrl, pointer),\n };\n if (f.start_line < f.end_line) {\n return {\n ...comment,\n start_line: f.start_line,\n start_side: defaultSide(f.side),\n };\n }\n return comment;\n });\n\n return { comments, strays };\n};\n\n/** Render the demoted (stray) findings as a markdown section for the summary. */\nexport const renderStraysSection = (strays: readonly Finding[]): string => {\n if (strays.length === 0) return \"\";\n\n const items = strays.map(\n (f) => `- **${f.severity}** · \\`${f.path}:${String(f.start_line)}\\` — ${f.title}`,\n );\n\n return [\n \"\",\n \"---\",\n \"\",\n \"#### ⚠️ Findings on lines not in the diff (demoted to summary)\",\n \"\",\n ...items,\n ].join(\"\\n\");\n};\n","// io-ts codecs for de/serialization at the boundary.\n// These ARE the source of truth for the data shapes — types are materialized via t.TypeOf<>.\n// No hand-written DTO types exist elsewhere; import types from here.\n\nimport * as t from \"io-ts\";\n\nconst SeverityCodec = t.union([\n t.literal(\"critical\"),\n t.literal(\"major\"),\n t.literal(\"minor\"),\n t.literal(\"nit\"),\n]);\n\nconst SideCodec = t.union([t.literal(\"RIGHT\"), t.literal(\"LEFT\")]);\n\nconst VerdictCodec = t.union([t.literal(\"approve\"), t.literal(\"comment\"), t.literal(\"changes\")]);\n\nconst LineNumber = t.refinement(\n t.number,\n (n): n is number => Number.isInteger(n) && n >= 1,\n \"LineNumber\",\n);\n\nconst Confidence = t.refinement(t.number, (n): n is number => n >= 0 && n <= 1, \"Confidence\");\n\n// Mirrors findings.schema.json's `schema_version.pattern` exactly, so `resolve()` (registry.ts,\n// consumed by post.ts's §5.5 malformed-doc path) never accepts a value that ajv (validate.ts, the\n// extraction ladder's candidate gate) would reject — e.g. a truncated \"0.2\" or an over-long \"0.2.0.0\".\nconst SCHEMA_VERSION_RE =\n /^(0|[1-9]\\d*)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nconst SchemaVersion = t.refinement(\n t.string,\n (s): s is string => SCHEMA_VERSION_RE.test(s),\n \"SchemaVersion\",\n);\n\nconst FindingShape = t.intersection([\n t.type({\n path: t.string,\n start_line: LineNumber,\n end_line: LineNumber,\n severity: SeverityCodec,\n title: t.string,\n description: t.string,\n reasoning: t.string,\n confidence: Confidence,\n }),\n t.partial({\n side: SideCodec,\n code: t.string,\n code_url: t.string,\n recommendation: t.string,\n patch: t.string,\n }),\n]);\n\nconst EndGeStart = t.refinement(\n FindingShape,\n (f): f is t.TypeOf<typeof FindingShape> => f.end_line >= f.start_line,\n \"EndGeStart\",\n);\n\nexport const FindingCodec = t.exact(EndGeStart);\n\nexport const FindingsCodec = t.exact(\n t.type({\n schema_version: SchemaVersion,\n summary: t.string,\n verdict: VerdictCodec,\n findings: t.array(FindingCodec),\n }),\n);\n\nexport const TriageCodec = t.type({\n safe: t.boolean,\n reasons: t.string,\n});\n\n// Abstract, vendor-neutral result envelope (SPEC §6.1) — not any adapter's native shape.\nconst TokenCount = t.refinement(\n t.number,\n (n): n is number => Number.isInteger(n) && n >= 0,\n \"TokenCount\",\n);\n\nexport const ModelUsageEntryCodec = t.intersection([\n t.type({\n model: t.string,\n input_tokens: TokenCount,\n output_tokens: TokenCount,\n }),\n t.partial({\n cache_read_tokens: TokenCount,\n cache_write_tokens: TokenCount,\n }),\n]);\n\nexport const ResultEnvelopeCodec = t.intersection([\n t.type({\n schema_version: t.string,\n findings: FindingsCodec,\n models: t.array(ModelUsageEntryCodec),\n turns: TokenCount,\n duration_ms: TokenCount,\n }),\n t.partial({\n vendor_cost_usd: t.union([t.number, t.null]),\n route: t.string,\n effort: t.string,\n }),\n]);\n\nexport const ModelPricesCodec = t.type({\n in: t.number,\n out: t.number,\n cache_read: t.number,\n cache_write: t.number,\n});\n\nexport const PriceMapCodec = t.type({\n _updated: t.string,\n _unit: t.string,\n models: t.record(t.string, ModelPricesCodec),\n});\n\n// Format-agnostic test summary (SPEC §5.1 item 4, REQ-CO-9) — any conforming test report shape.\nexport const TestFailureCodec = t.intersection([\n t.type({ name: t.string }),\n t.partial({ message: t.string }),\n]);\n\nexport const TestSummaryCodec = t.intersection([\n t.type({\n passed: t.number,\n failed: t.number,\n total: t.number,\n }),\n t.partial({\n failures: t.array(TestFailureCodec),\n }),\n]);\n\n// The supported-minor allowlist and version dispatch live in the registry (src/registry.ts),\n// which sources its findings entry's defaultVersion from this constant.\n/** Full semver used when an adapter's native output omits `schema_version` (SPEC §6.1). */\nexport const DEFAULT_SCHEMA_VERSION = \"0.4.0\";\n\nexport type Finding = t.TypeOf<typeof FindingCodec>;\nexport type Findings = t.TypeOf<typeof FindingsCodec>;\n\n/** A valid, empty-findings document carrying `summary` as its only content — the single shape used\n * for a sticky-only notice (post.ts, SPEC §5.5) and a \"did not complete\" degraded envelope\n * (adapt.ts, issue #18). Callers supply the fully-formatted markdown summary. */\nexport const noticeFindings = (summary: string): Findings => ({\n schema_version: DEFAULT_SCHEMA_VERSION,\n summary,\n verdict: \"comment\",\n findings: [],\n});\nexport type Triage = t.TypeOf<typeof TriageCodec>;\nexport type Severity = t.TypeOf<typeof SeverityCodec>;\nexport type Side = t.TypeOf<typeof SideCodec>;\nexport type Verdict = t.TypeOf<typeof VerdictCodec>;\nexport type ModelUsageEntry = t.TypeOf<typeof ModelUsageEntryCodec>;\nexport type ResultEnvelope = t.TypeOf<typeof ResultEnvelopeCodec>;\nexport type ModelPrices = t.TypeOf<typeof ModelPricesCodec>;\nexport type PriceMap = t.TypeOf<typeof PriceMapCodec>;\nexport type TestFailure = t.TypeOf<typeof TestFailureCodec>;\nexport type TestSummary = t.TypeOf<typeof TestSummaryCodec>;\n","// Schema validation wrapper. Validates findings JSON against the published schema.\n// Minor command — defense-in-depth; the CLI enforces the schema on the agent side already.\n\nimport { Ajv2020 } from \"ajv/dist/2020.js\";\nimport type { ValidateFunction as AjvValidateFunction } from \"ajv/dist/2020.js\";\nimport _addFormats from \"ajv-formats\";\nimport { readFileSync } from \"node:fs\";\nimport type { Either } from \"fp-ts/Either\";\nimport { FindingsCodec } from \"./schema.js\";\nimport type { Findings } from \"./schema.js\";\n\nconst addFormats = _addFormats as unknown as (ajv: Ajv2020) => void;\n\n/** Module-level cache of compiled validators keyed by schema path. */\nconst validatorCache = new Map<string, AjvValidateFunction>();\n\n/** Compile a JSON Schema validator from the given file path (cached). */\nconst compileSchema = (schemaPath: string): AjvValidateFunction => {\n const cached = validatorCache.get(schemaPath);\n if (cached) return cached;\n\n let schemaJson: string;\n try {\n schemaJson = readFileSync(schemaPath, \"utf-8\");\n } catch {\n throw new Error(`Cannot read schema file: ${schemaPath}`);\n }\n let schema: unknown;\n try {\n schema = JSON.parse(schemaJson);\n } catch {\n throw new Error(`Invalid JSON in schema file: ${schemaPath}`);\n }\n const ajv = new Ajv2020({ allErrors: true, strict: true });\n addFormats(ajv);\n const validator = ajv.compile(schema as Record<string, unknown>);\n validatorCache.set(schemaPath, validator);\n return validator;\n};\n\nexport interface ValidateResult {\n readonly valid: boolean;\n readonly errors: readonly string[];\n}\n\nexport const validateAgainstSchema = (findings: unknown, schemaPath: string): ValidateResult => {\n const validator = compileSchema(schemaPath);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- ajv returns boolean | Promise<unknown>\n const valid = validator(findings) as boolean;\n const errors: readonly string[] =\n valid || !validator.errors\n ? []\n : validator.errors.map((e) => `${e.instancePath} ${e.message ?? \"unknown error\"}`);\n return { valid, errors };\n};\n\n/** Extract the right value from an io-ts Either, or throw. */\nexport const unsafeUnwrap = <A>(decoded: Either<unknown, A>): A => {\n if (decoded._tag === \"Right\") return decoded.right;\n throw new Error(\"io-ts decode failed — data does not match expected shape\");\n};\n\n/** Decode findings, throwing on failure. */\nexport const decodeFindings = (data: unknown): Findings => unsafeUnwrap(FindingsCodec.decode(data));\n","// Conservative markdown formatting pass applied just before a comment/review body is posted, plus\n// small pure formatting helpers for the IO boundary (e.g. the sticky's posted-at timestamp).\n// Pure string transform: never reflows content, never touches fenced code blocks (a `suggestion`\n// block's blank lines and trailing whitespace are significant and must survive verbatim).\n\ninterface ScanState {\n readonly lines: readonly string[];\n readonly inFence: boolean;\n readonly blankRun: number;\n}\n\nconst FENCE_RE = /^\\s*```/;\n\nconst scanLine = (state: ScanState, line: string): ScanState => {\n if (FENCE_RE.test(line)) {\n return { lines: [...state.lines, line], inFence: !state.inFence, blankRun: 0 };\n }\n if (state.inFence) {\n return { lines: [...state.lines, line], inFence: true, blankRun: 0 };\n }\n const trimmed = line.replace(/[ \\t]+$/, \"\");\n if (trimmed !== \"\") {\n return { lines: [...state.lines, trimmed], inFence: false, blankRun: 0 };\n }\n const blankRun = state.blankRun + 1;\n return blankRun === 1\n ? { lines: [...state.lines, \"\"], inFence: false, blankRun }\n : { ...state, blankRun };\n};\n\n/** Trim trailing whitespace and collapse runs of 2+ blank lines to one — never to zero — leaving\n * exactly one trailing newline. Fenced (```) content passes through untouched. */\nexport const formatMarkdown = (md: string): string => {\n const { lines } = md\n .split(\"\\n\")\n .reduce<ScanState>(scanLine, { lines: [], inFence: false, blankRun: 0 });\n return `${lines.join(\"\\n\").replace(/\\n+$/, \"\")}\\n`;\n};\n\nconst pad2 = (n: number): string => String(n).padStart(2, \"0\");\n\n/** Format a Date as UTC `YYYY-MM-DD HH:MM UTC`, for the sticky's \"Reviewed `<sha>` · <postedAt>\"\n * line (issue #28). Computed at the IO boundary (index.ts's post/render commands) — `render()`\n * itself stays pure/clockless and just receives the formatted string. */\nexport const formatUtc = (d: Date): string =>\n `${String(d.getUTCFullYear())}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())} ${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())} UTC`;\n","// Version-aware schema registry: maps each schema kind's supported major.minor(s) to a bundled\n// schema file, io-ts codec, and upcast normalizer (identity for every entry today). Findings is a\n// single current minor (0.4): the 0.4 shape REQUIRES `reasoning`/`confidence`, which cannot be\n// honestly upcast from a 0.2/0.3 document (a confidence score cannot be fabricated), so those older\n// minors are dropped from the table and now degrade to the §5.5 unsupported-version notice.\n// `resolve` is pure (no IO); `schemaPathFor` only computes a path string from the tables below.\n//\n// This module imports from schema.ts (codecs, DEFAULT_SCHEMA_VERSION), never the reverse — schema.ts\n// stays a dependency-free leaf so the registry can compose it without an import cycle.\n//\n// Bundled schema files resolve relative to the installed package exactly like index.ts's\n// bundledPath: tsup bundles this module into the same dist/index.js as index.ts, so\n// import.meta.dirname here resolves identically at runtime, in dev, and from the published package.\n\nimport { resolve as resolvePath } from \"node:path\";\nimport type { Decoder, Encoder, Errors, ValidationError } from \"io-ts\";\nimport { FindingsCodec, TriageCodec, PriceMapCodec, DEFAULT_SCHEMA_VERSION } from \"./schema.js\";\nimport type { Findings, Triage, PriceMap } from \"./schema.js\";\n\nexport type SchemaKind = \"findings\" | \"triage\" | \"prices\";\n\nexport interface DecodedFor {\n readonly findings: Findings;\n readonly triage: Triage;\n readonly prices: PriceMap;\n}\n\ninterface VersionEntry<K extends SchemaKind, A> {\n /** major.minor of `schema_version` this entry dispatches on; patch is ignored. */\n readonly minor: string;\n /** full semver stamped when a document omits `schema_version` (findings) or reported as the\n * resolved version for kinds with no in-data signal (triage, prices). */\n readonly defaultVersion: string;\n /** path relative to schema/: flat name for the latest entry, \"v<minor>/…\" once frozen. */\n readonly schemaFile: string;\n readonly codec: Decoder<unknown, A> & Encoder<A, unknown>;\n /** upcast to the latest shape for this kind; identity when the codec already accepts both\n * shapes (e.g. an additive minor whose new field is optional). */\n readonly normalize: (decoded: A) => DecodedFor[K];\n readonly latest: boolean;\n}\n\nexport type Resolution<K extends SchemaKind> =\n | { readonly kind: \"ok\"; readonly version: string; readonly value: DecodedFor[K] }\n | {\n readonly kind: \"unsupported-version\";\n readonly version: string;\n readonly supported: readonly string[];\n }\n | { readonly kind: \"invalid-shape\"; readonly errors: readonly string[] }\n | { readonly kind: \"missing-version\" }; // findings only; triage/prices never return this\n\nconst identity = <A>(decoded: A): A => decoded;\n\nconst findingsTable: readonly VersionEntry<\"findings\", Findings>[] = [\n {\n minor: \"0.4\",\n defaultVersion: DEFAULT_SCHEMA_VERSION,\n schemaFile: \"findings.schema.json\",\n codec: FindingsCodec,\n normalize: identity,\n latest: true,\n },\n];\n\nconst triageTable: readonly VersionEntry<\"triage\", Triage>[] = [\n {\n minor: \"0.1\",\n defaultVersion: \"0.1.0\",\n schemaFile: \"triage.schema.json\",\n codec: TriageCodec,\n normalize: identity,\n latest: true,\n },\n];\n\nconst pricesTable: readonly VersionEntry<\"prices\", PriceMap>[] = [\n {\n minor: \"0.1\",\n defaultVersion: \"0.1.0\",\n schemaFile: \"prices.schema.json\",\n codec: PriceMapCodec,\n normalize: identity,\n latest: true,\n },\n];\n\ntype Table<K extends SchemaKind> = readonly VersionEntry<K, DecodedFor[K]>[];\n\nconst tables: { readonly [K in SchemaKind]: Table<K> } = {\n findings: findingsTable,\n triage: triageTable,\n prices: pricesTable,\n};\n\nconst tableFor = <K extends SchemaKind>(kind: K): Table<K> => tables[kind];\n\n/** major.minor of a semver-ish string; dispatch ignores patch and any prerelease/build suffix. */\nconst majorMinor = (version: string): string => version.split(\".\").slice(0, 2).join(\".\");\n\nconst describeValidationError = (e: ValidationError): string => {\n const path = e.context\n .map((entry) => entry.key)\n .filter((key) => key.length > 0)\n .join(\".\");\n return e.message ?? `${path || \"(root)\"}: invalid value ${JSON.stringify(e.value)}`;\n};\n\nconst formatErrors = (errors: Errors): readonly string[] => errors.map(describeValidationError);\n\n/** The declared `schema_version` of a raw document, when present as a string. */\nexport const declaredVersion = (raw: unknown): string | undefined =>\n typeof raw === \"object\" && raw !== null && \"schema_version\" in raw\n ? typeof raw.schema_version === \"string\"\n ? raw.schema_version\n : undefined\n : undefined;\n\nexport const supportedVersions = (kind: SchemaKind): readonly string[] =>\n tableFor(kind).map((entry) => entry.minor);\n\nexport const defaultVersion = (kind: SchemaKind): string => {\n const latest = tableFor(kind).find((entry) => entry.latest);\n if (!latest) throw new Error(`Registry invariant violated — no latest entry for \"${kind}\"`);\n return latest.defaultVersion;\n};\n\nconst bundledSchemaPath = (relativePath: string): string =>\n resolvePath(import.meta.dirname, \"..\", \"schema\", relativePath);\n\n/** Resolve the bundled schema path for a kind + optional version; no version → flat latest file. */\nexport const schemaPathFor = (kind: SchemaKind, version?: string): string => {\n const table = tableFor(kind);\n const entry =\n version === undefined\n ? table.find((v) => v.latest)\n : table.find((v) => v.minor === majorMinor(version));\n if (!entry) {\n throw new Error(\n `Unsupported ${kind} schema version \"${version ?? \"\"}\" — supported: ${supportedVersions(kind).join(\", \")}`,\n );\n }\n return bundledSchemaPath(entry.schemaFile);\n};\n\nconst resolveFindings = (raw: unknown): Resolution<\"findings\"> => {\n const version = declaredVersion(raw);\n if (version === undefined) return { kind: \"missing-version\" };\n const entry = findingsTable.find((v) => v.minor === majorMinor(version));\n if (!entry) {\n return { kind: \"unsupported-version\", version, supported: supportedVersions(\"findings\") };\n }\n const decoded = entry.codec.decode(raw);\n return decoded._tag === \"Left\"\n ? { kind: \"invalid-shape\", errors: formatErrors(decoded.left) }\n : { kind: \"ok\", version, value: entry.normalize(decoded.right) };\n};\n\n/** Resolve a kind with no in-data version signal — a single bundled entry, never \"missing-version\". */\nconst resolveSingleVersion = <K extends \"triage\" | \"prices\">(\n kind: K,\n raw: unknown,\n): Resolution<K> => {\n const entry = tableFor(kind)[0];\n if (!entry) throw new Error(`Registry invariant violated — no entry for \"${kind}\"`);\n const decoded = entry.codec.decode(raw);\n return decoded._tag === \"Left\"\n ? { kind: \"invalid-shape\", errors: formatErrors(decoded.left) }\n : { kind: \"ok\", version: entry.defaultVersion, value: entry.normalize(decoded.right) };\n};\n\nconst resolvers: { readonly [K in SchemaKind]: (raw: unknown) => Resolution<K> } = {\n findings: resolveFindings,\n triage: (raw) => resolveSingleVersion(\"triage\", raw),\n prices: (raw) => resolveSingleVersion(\"prices\", raw),\n};\n\n/** Decode + version-dispatch a raw document for a schema kind. Pure — no IO. */\nexport const resolve = <K extends SchemaKind>(kind: K, raw: unknown): Resolution<K> =>\n resolvers[kind](raw);\n","// The `gh api` effect: the single shell boundary for GitHub API calls. Pure callers inject a\n// fake; the default implementation shells out to the `gh` CLI (auth via GH_TOKEN in the env).\n\nimport { execFile } from \"node:child_process\";\n\n/** Signature of the `gh api` effect. Default implementation shells out to the `gh` CLI. */\nexport type GhApi = (\n args: readonly string[],\n stdin?: string,\n env?: Readonly<Record<string, string>>,\n) => Promise<string>;\n\n/** Default effect: execFile gh. Extra `env` merges over process.env for this call only —\n * used to pass untrusted values (bot login, marker) to jq via `env.NAME`, never interpolated\n * into the filter text (SPEC §5.4). */\nexport const runGhApi: GhApi = (args, stdin, env) =>\n new Promise<string>((resolve, reject) => {\n const child = execFile(\n \"gh\",\n [\"api\", ...args],\n { env: { ...process.env, ...env }, encoding: \"utf-8\", maxBuffer: 100 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n const stderrStr = typeof stderr === \"string\" && stderr.trim() ? stderr.trim() : \"\";\n const errStr = err instanceof Error ? err.message : \"unknown error\";\n reject(new Error(`gh api failed: ${stderrStr || errStr}`));\n } else {\n resolve(stdout);\n }\n },\n );\n if (stdin !== undefined) {\n child.stdin?.end(stdin);\n }\n });\n","// PR resolution + diff fetch, shared by `post` (comment job) and `gather` (review job). Both jobs\n// resolve independently (separate runners), but from the SAME pure logic, so they never disagree on\n// which PR (SPEC §8.3 — avoid split-brain). PR resolution is a single read, never jq-interpolated.\n\nimport type { GhApi } from \"./gh.js\";\n\ninterface PrCandidate {\n readonly number: number;\n readonly state: string;\n readonly headRef: string;\n}\n\nexport const fetchPrCandidates = async (\n repo: string,\n headSha: string,\n ghApi: GhApi,\n): Promise<readonly PrCandidate[]> => {\n const stdout = await ghApi([\n `repos/${repo}/commits/${headSha}/pulls`,\n \"--jq\",\n \".[] | {number: .number, state: .state, headRef: .head.ref}\",\n ]);\n return stdout\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as PrCandidate);\n};\n\nexport type PrResolution =\n | { readonly kind: \"none\" }\n | { readonly kind: \"not-open\"; readonly prNumber: number; readonly state: string }\n | { readonly kind: \"open\"; readonly prNumber: number };\n\n/** Resolve which PR to act on. Disambiguates by head branch (pure); never shells out. */\nexport const resolvePr = (\n candidates: readonly PrCandidate[],\n headBranch: string | undefined,\n): PrResolution => {\n if (candidates.length === 0) return { kind: \"none\" };\n const scoped =\n candidates.length > 1 && headBranch\n ? candidates.filter((c) => c.headRef === headBranch)\n : candidates;\n const chosen = scoped[0] ?? candidates[0];\n if (chosen === undefined) return { kind: \"none\" };\n return chosen.state === \"open\"\n ? { kind: \"open\", prNumber: chosen.number }\n : { kind: \"not-open\", prNumber: chosen.number, state: chosen.state };\n};\n\nexport const fetchDiff = async (repo: string, prNumber: number, ghApi: GhApi): Promise<string> =>\n ghApi([\n `repos/${repo}/pulls/${String(prNumber)}`,\n \"-H\",\n \"Accept: application/vnd.github.v3.diff\",\n ]);\n","// Deterministic GH posting: resolve PR, fetch diff, run inline, post inline review,\n// render summary, upsert sticky comment. Pure core with a thin gh-api effect.\n//\n// Ordering (CO-R3): all reads, decodes, diff validation, and rendering complete before\n// the first API write; then the sticky is posted, and the inline review second. A posting\n// failure propagates and exits the process non-zero (never partially posts).\n\nimport { readFileSync } from \"node:fs\";\nimport type { InlineComment, InlineDisposition, RenderInput } from \"./types.js\";\nimport { buildInlineComments } from \"./inline.js\";\nimport { isEmptyDiff } from \"./diff.js\";\nimport { render, computeSeverityCounts } from \"./render.js\";\nimport { formatMarkdown } from \"./format.js\";\nimport { findingsPointer, reviewBodyPointer } from \"./surface.js\";\nimport { ResultEnvelopeCodec, PriceMapCodec, TestSummaryCodec, noticeFindings } from \"./schema.js\";\nimport type { Findings, ResultEnvelope, TestSummary } from \"./schema.js\";\nimport { resolve, supportedVersions } from \"./registry.js\";\nimport type { GhApi } from \"./gh.js\";\nimport { runGhApi } from \"./gh.js\";\nexport type { GhApi } from \"./gh.js\";\nimport { fetchDiff, fetchPrCandidates, resolvePr } from \"./pr.js\";\n\nexport interface PostInput {\n readonly repo: string;\n readonly headSha: string;\n readonly botLogin: string;\n readonly findingsPath: string;\n readonly envelopePath: string;\n readonly pricesPath: string;\n /** Whether `pricesPath` is a real caller-supplied price map or the bundled all-zero example\n * standing in for an absent one — threaded to the render layer so cost shows N/A, not a false\n * $0.00, when absent (SPEC §6.2). */\n readonly pricesProvided: boolean;\n readonly templatePath: string;\n readonly inlineTemplatePath: string;\n /** Overrides the envelope's route (SPEC §6.1) when set; otherwise the envelope is the source. */\n readonly route?: string;\n readonly headBranch?: string;\n readonly testReportPath?: string;\n readonly effort?: string;\n /** Workflow run URL, threaded into the sticky's LLM Disclosure aside (SPEC §5.1 item 6). */\n readonly runUrl?: string;\n /** Findings-json artifact URL — the marker's fallback on every surface (sticky, each inline\n * comment, and the review body itself) when the embedded form is too large (SPEC §5.1 item 7,\n * §5.2, issue #19). */\n readonly jsonUrl?: string;\n /** Preformatted UTC post time, rendered on the sticky's dedicated \"Reviewed `<sha>` · <postedAt>\"\n * line (issue #28) — computed by the caller (index.ts's post command) via `formatUtc`, not here,\n * so `post()` stays a thin, testable pass-through of the timestamp into `render()`. */\n readonly postedAt?: string;\n}\n\nconst DEFAULT_MARKER = \"<!-- code-review -->\";\nconst MAX_SUGGESTION_LINES = 10;\n\n/** Count lines in a suggestion string (empty suggestion \"\" = 1 line — delete range). */\nconst countSuggestionLines = (text: string): number => text.split(\"\\n\").length;\n\n/** Extract and check suggestion blocks in a comment body, stripping those that are too long. */\nconst checkLongSuggestions = (\n comments: readonly InlineComment[],\n): { readonly comments: readonly InlineComment[]; readonly longFiles: readonly string[] } => {\n const longFiles: string[] = [];\n const adjusted = comments.map((c) => {\n const match = /```suggestion\\n([\\s\\S]*?)\\n```/.exec(c.body);\n if (match?.[1] && countSuggestionLines(match[1]) > MAX_SUGGESTION_LINES) {\n longFiles.push(`${c.path}:${String(c.line)}`);\n return {\n ...c,\n body: c.body.replace(\n /```suggestion\\n[\\s\\S]*?\\n```/,\n \"*(suggestion omitted — exceeds GitHub's ~10-line suggestion limit; see summary)*\",\n ),\n };\n }\n return c;\n });\n return { comments: adjusted, longFiles };\n};\n\n// Loaders below never throw on untrusted artifacts (SPEC §5.5) — malformed input degrades to a\n// tagged result the caller renders as a notice, rather than crashing the post.\ntype FindingsLoadResult =\n | { readonly kind: \"ok\"; readonly findings: Findings }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"invalid-shape\" }\n | { readonly kind: \"unsupported-schema-version\"; readonly version: string };\n\nconst loadFindings = (path: string): FindingsLoadResult => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch {\n return { kind: \"corrupt\" };\n }\n const resolution = resolve(\"findings\", raw);\n switch (resolution.kind) {\n case \"ok\":\n return { kind: \"ok\", findings: resolution.value };\n case \"unsupported-version\":\n return { kind: \"unsupported-schema-version\", version: resolution.version };\n case \"invalid-shape\":\n case \"missing-version\":\n return { kind: \"invalid-shape\" };\n }\n};\n\nconst noticeMessageFor = (result: Exclude<FindingsLoadResult, { kind: \"ok\" }>): string => {\n switch (result.kind) {\n case \"corrupt\":\n return \"Review output was missing or malformed — the review did not complete. See the workflow run for logs.\";\n case \"invalid-shape\":\n return \"Review output was malformed — it did not conform to the findings schema. See the workflow run for logs.\";\n case \"unsupported-schema-version\": {\n const supported = supportedVersions(\"findings\")\n .map((minor) => `${minor}.x`)\n .join(\", \");\n return `Review output declares schema_version \"${result.version}\", which this commenter does not support (supported: ${supported}). See the workflow run for logs.`;\n }\n }\n};\n\n/** Load the result envelope; null on any read/decode failure (SPEC §5.5 — degrade, never crash). */\nconst loadEnvelope = (path: string): ResultEnvelope | null => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch {\n return null;\n }\n const decoded = ResultEnvelopeCodec.decode(raw);\n return decoded._tag === \"Right\" ? decoded.right : null;\n};\n\n/** Load an optional test report; undefined (and a warning) on any read/decode failure — REQ-CO-9\n * enrichment is optional and MUST degrade gracefully, never abort the post. */\nconst loadTestReport = (path: string): TestSummary | undefined => {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n } catch (err) {\n process.stderr.write(\n `Warning: could not read test report at ${path}: ${err instanceof Error ? err.message : String(err)} — omitting test panel\\n`,\n );\n return undefined;\n }\n const decoded = TestSummaryCodec.decode(raw);\n if (decoded._tag === \"Left\") {\n process.stderr.write(\n `Warning: test report at ${path} does not match the expected shape — omitting test panel\\n`,\n );\n return undefined;\n }\n return decoded.right;\n};\n\n/** Parse an `html_url` field out of a `gh api` JSON response; a malformed or unexpected response\n * degrades to undefined rather than throwing — a missing link must never fail the post (§5.5). */\nconst parseHtmlUrl = (raw: string): string | undefined => {\n try {\n const parsed = JSON.parse(raw) as { html_url?: unknown };\n return typeof parsed.html_url === \"string\" ? parsed.html_url : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** Post the inline review, pointing its body at the sticky (issue #11) when the sticky's URL is\n * known, and prepending the precomputed findings-json marker (issue #19) so the review body\n * carries it too. Returns the review's own `html_url` (undefined on a malformed response) so the\n * caller can link the sticky back to it. */\nconst postInlineReview = async (\n repo: string,\n prNumber: number,\n headSha: string,\n comments: readonly InlineComment[],\n stickyUrl: string | undefined,\n marker: string,\n ghApi: GhApi,\n): Promise<string | undefined> => {\n const pointer = reviewBodyPointer(headSha, stickyUrl, marker);\n const body = JSON.stringify({\n body: pointer,\n commit_id: headSha,\n event: \"COMMENT\",\n comments: comments.map((c) => ({\n path: c.path,\n line: c.line,\n side: c.side,\n ...(c.start_line !== undefined && c.start_side !== undefined\n ? { start_line: c.start_line, start_side: c.start_side }\n : {}),\n body: formatMarkdown(c.body),\n })),\n });\n const stdout = await ghApi(\n [`repos/${repo}/pulls/${String(prNumber)}/reviews`, \"--input\", \"-\"],\n body,\n );\n return parseHtmlUrl(stdout);\n};\n\nconst findBotComment = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n marker: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly body: string } | null> => {\n const stdout = await ghApi(\n [\n `repos/${repo}/issues/${String(prNumber)}/comments`,\n \"--paginate\",\n \"--jq\",\n \".[] | select(.user.login == env.CODE_REVIEW_BOT_LOGIN and (.body | startswith(env.CODE_REVIEW_MARKER))) | {id: .id, body: .body}\",\n ],\n undefined,\n { CODE_REVIEW_BOT_LOGIN: botLogin, CODE_REVIEW_MARKER: marker },\n );\n const lines = stdout.trim().split(\"\\n\").filter(Boolean);\n if (lines.length === 0) return null;\n const last = lines[lines.length - 1] ?? null;\n if (last === null) return null;\n const parsed = JSON.parse(last) as { id: number; body: string };\n return { id: parsed.id, body: parsed.body };\n};\n\n/** Parse an issue-comment create/patch response for `id`/`html_url`; malformed responses degrade\n * to null rather than throwing (§5.5, issue #11 ROBUSTNESS — a missing link must never fail the\n * post). */\nconst parseCommentRef = (\n raw: string,\n): { readonly id: number; readonly html_url: string } | null => {\n try {\n const parsed = JSON.parse(raw) as { id?: unknown; html_url?: unknown };\n return typeof parsed.id === \"number\" && typeof parsed.html_url === \"string\"\n ? { id: parsed.id, html_url: parsed.html_url }\n : null;\n } catch {\n return null;\n }\n};\n\nconst patchComment = async (\n repo: string,\n commentId: number,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly html_url: string } | null> => {\n const stdout = await ghApi(\n [`repos/${repo}/issues/comments/${String(commentId)}`, \"--input\", \"-\"],\n JSON.stringify({ body }),\n );\n // Only `html_url` is needed here — the id is already known by the caller — so this doesn't\n // require `id` in the response the way parseCommentRef (used for a brand-new comment) does.\n const htmlUrl = parseHtmlUrl(stdout);\n return htmlUrl !== undefined ? { html_url: htmlUrl } : null;\n};\n\nconst postComment = async (\n repo: string,\n prNumber: number,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly html_url: string } | null> => {\n const stdout = await ghApi(\n [`repos/${repo}/issues/${String(prNumber)}/comments`, \"--input\", \"-\"],\n JSON.stringify({ body }),\n );\n return parseCommentRef(stdout);\n};\n\n/** Upsert the sticky summary — trust by author identity (bot login), not marker alone (§5.3).\n * Returns the sticky's id + `html_url` (url undefined on a malformed response) so the caller can\n * re-patch it with a link to the review once posted (issue #11). Returns null only when a *new*\n * comment's response couldn't be parsed at all — there is then no id to re-patch with. */\nconst upsertSticky = async (\n repo: string,\n prNumber: number,\n existing: { readonly id: number; readonly body: string } | null,\n body: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly url: string | undefined } | null> => {\n if (existing !== null) {\n const patched = await patchComment(repo, existing.id, body, ghApi);\n process.stderr.write(\n `Updated sticky comment #${String(existing.id)} on PR #${String(prNumber)}\\n`,\n );\n return { id: existing.id, url: patched?.html_url };\n }\n const posted = await postComment(repo, prNumber, body, ghApi);\n process.stderr.write(`Posted new sticky comment on PR #${String(prNumber)}\\n`);\n return posted ? { id: posted.id, url: posted.html_url } : null;\n};\n\n/** A non-dismissed bot-authored review, carrying the commit it reviewed (SPEC §5.2.6 — review\n * identity is the reviews API `commit_id`, not the sticky's `reviewed-sha` marker). */\ninterface BotReviewRef {\n readonly id: number;\n readonly commitId: string;\n}\n\nconst isBotReview = (\n r: unknown,\n): r is { id: number; user: { login: string }; state: string; commit_id?: unknown } =>\n typeof r === \"object\" &&\n r !== null &&\n typeof (r as { id?: unknown }).id === \"number\" &&\n typeof (r as { state?: unknown }).state === \"string\" &&\n typeof (r as { user?: { login?: unknown } }).user?.login === \"string\";\n\n/** List the PR's non-dismissed bot-authored reviews with the SHA each one reviewed. */\nconst fetchBotReviews = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n ghApi: GhApi,\n): Promise<readonly BotReviewRef[]> => {\n const stdout = await ghApi([`repos/${repo}/pulls/${String(prNumber)}/reviews`, \"--paginate\"]);\n let reviews: unknown;\n try {\n reviews = JSON.parse(stdout || \"[]\");\n } catch {\n return [];\n }\n if (!Array.isArray(reviews)) return [];\n return reviews\n .filter(isBotReview)\n .filter((r) => r.user.login === botLogin && r.state !== \"DISMISSED\")\n .map((r) => ({\n id: r.id,\n commitId: typeof r.commit_id === \"string\" ? r.commit_id : \"\",\n }));\n};\n\n/** Dismiss superseded bot-authored reviews (REC-CO-2). Failures are logged, never fail the job. */\nconst dismissReviews = async (\n repo: string,\n prNumber: number,\n ids: readonly number[],\n ghApi: GhApi,\n): Promise<void> => {\n for (const id of ids) {\n try {\n await ghApi(\n [\n `repos/${repo}/pulls/${String(prNumber)}/reviews/${String(id)}/dismissals`,\n \"-X\",\n \"PUT\",\n \"--input\",\n \"-\",\n ],\n JSON.stringify({ message: \"Superseded by a new review for an updated commit.\" }),\n );\n } catch (err) {\n process.stderr.write(\n `Warning: failed to dismiss prior review #${String(id)} on PR #${String(prNumber)}: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n};\n\nexport const post = async (input: PostInput, ghApi: GhApi = runGhApi): Promise<void> => {\n // Phase 1 (CO-R3): reads, decodes, diff validation, rendering — no writes yet.\n const candidates = await fetchPrCandidates(input.repo, input.headSha, ghApi);\n const resolution = resolvePr(candidates, input.headBranch);\n if (resolution.kind === \"none\") {\n process.stderr.write(`No open PR for ${input.headSha} — nothing to post\\n`);\n process.exit(0);\n }\n if (resolution.kind === \"not-open\") {\n process.stderr.write(\n `PR #${String(resolution.prNumber)} for ${input.headSha} is not open (state: ${resolution.state}) — nothing to post\\n`,\n );\n process.exit(0);\n }\n const prNumber = resolution.prNumber;\n\n const diff = await fetchDiff(input.repo, prNumber, ghApi);\n const existingSticky = await findBotComment(\n input.repo,\n prNumber,\n input.botLogin,\n DEFAULT_MARKER,\n ghApi,\n );\n\n const prices = JSON.parse(readFileSync(input.pricesPath, \"utf-8\")) as unknown;\n const decodedPrices = PriceMapCodec.decode(prices);\n if (decodedPrices._tag === \"Left\") {\n throw new Error(`Price map at ${input.pricesPath} does not match the expected shape`);\n }\n const template = readFileSync(input.templatePath, \"utf-8\");\n const inlineTemplate = readFileSync(input.inlineTemplatePath, \"utf-8\");\n\n const renderNotice = (message: string): string =>\n formatMarkdown(\n render({\n findings: noticeFindings(`### ⚠️ ${message}`),\n envelope: null,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n postedAt: input.postedAt,\n }),\n );\n\n if (isEmptyDiff(diff)) {\n await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderNotice(\"The diff for this PR is empty — nothing to review.\"),\n ghApi,\n );\n process.exit(0);\n }\n\n const findingsResult = loadFindings(input.findingsPath);\n if (findingsResult.kind !== \"ok\") {\n await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderNotice(noticeMessageFor(findingsResult)),\n ghApi,\n );\n process.exit(0);\n }\n const findings = findingsResult.findings;\n\n const envelope = loadEnvelope(input.envelopePath);\n const testReport = input.testReportPath ? loadTestReport(input.testReportPath) : undefined;\n\n if (envelope === null) {\n const body = formatMarkdown(\n render({\n findings,\n envelope: null,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n testReport,\n inlineDisposition: { kind: \"no-envelope\" },\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n postedAt: input.postedAt,\n }),\n );\n await upsertSticky(input.repo, prNumber, existingSticky, body, ghApi);\n process.stderr.write(\n \"Result envelope missing or malformed — posted sticky summary without usage/cost data; no inline review\\n\",\n );\n process.exit(0);\n }\n\n // Issue #19 + review fix #5: base64-encode the findings ONCE and reuse the marker across every\n // surface (both sticky renders, each inline comment, the review body) instead of recomputing it.\n const findingsMarker = findingsPointer(findings, input.jsonUrl);\n\n const { comments: rawComments, strays } = buildInlineComments(findings.findings, diff, {\n inlineTemplate,\n models: envelope.models.map((m) => m.model),\n findingsPointer: findingsMarker,\n });\n const { comments, longFiles } = checkLongSuggestions(rawComments);\n for (const wf of longFiles) {\n process.stderr.write(\n `Warning: suggestion in ${wf} exceeds ${String(MAX_SUGGESTION_LINES)} lines — omitted from inline to avoid 422\\n`,\n );\n }\n\n // Fix #5 (SPEC §5.2.6): suppression turns on whether a COMPLETED bot review already exists for\n // this head SHA — review identity via the reviews API `commit_id` — not on the sticky's marker\n // (a placeholder/degraded sticky must not claim the SHA). Only relevant when there is an inline\n // review to post at all.\n const botReviews =\n comments.length > 0 ? await fetchBotReviews(input.repo, prNumber, input.botLogin, ghApi) : [];\n const alreadyReviewedThisSha = botReviews.some((r) => r.commitId === input.headSha);\n\n // Issue #21: the \"posted — see the review\" disposition is constructed ONLY from the actual\n // postInlineReview result below, never optimistically — a review that doesn't yet exist (or\n // never will, if this process dies before posting it) must never be claimed. Everything knowable\n // from reads alone (suppression, no-in-diff-findings) is truthful up front and stays as-is.\n const initialDisposition: InlineDisposition | undefined =\n comments.length > 0\n ? alreadyReviewedThisSha\n ? { kind: \"suppressed-existing-review\", sha: input.headSha }\n : undefined\n : strays.length > 0\n ? { kind: \"none-in-diff\" }\n : undefined;\n\n const commonRenderInput: Omit<RenderInput, \"inlineDisposition\" | \"reviewUrl\"> = {\n findings,\n envelope,\n prices: decodedPrices.right,\n pricesProvided: input.pricesProvided,\n template,\n route: input.route,\n reviewedSha: input.headSha,\n effort: input.effort,\n testReport,\n severityCounts: computeSeverityCounts(findings.findings),\n strays,\n runUrl: input.runUrl,\n jsonUrl: input.jsonUrl,\n findingsPointer: findingsMarker,\n postedAt: input.postedAt,\n };\n const longFilesNote =\n longFiles.length > 0\n ? `\\n\\n---\\n\\n> **Note:** ${String(longFiles.length)} suggestion(s) exceeded GitHub's ~10-line inline suggestion limit and were omitted from the inline comments; the affected findings remain in the review.\\n`\n : \"\";\n // Renders the sticky body; called twice (issue #11) — once before the review exists (no\n // disposition claim beyond what reads already confirmed), once after (with the confirmed\n // disposition + reviewUrl) to report the truth and link the sticky back to the review.\n const renderBody = (\n inlineDisposition: InlineDisposition | undefined,\n reviewUrl?: string,\n ): string =>\n formatMarkdown(render({ ...commonRenderInput, inlineDisposition, reviewUrl }) + longFilesNote);\n\n // Phase 2 (CO-R3): writes — sticky first, inline second; failure exits non-zero.\n const stickyRef = await upsertSticky(\n input.repo,\n prNumber,\n existingSticky,\n renderBody(initialDisposition),\n ghApi,\n );\n\n if (comments.length === 0) return;\n\n if (alreadyReviewedThisSha) {\n process.stderr.write(\n `A completed bot review already exists for ${input.headSha} — updated sticky only, no new inline review\\n`,\n );\n return;\n }\n\n // REC-CO-2: supersede prior bot reviews left on OTHER commits before posting the fresh one.\n const stalePriorReviewIds = botReviews\n .filter((r) => r.commitId !== input.headSha)\n .map((r) => r.id);\n if (stalePriorReviewIds.length > 0) {\n await dismissReviews(input.repo, prNumber, stalePriorReviewIds, ghApi);\n }\n\n const reviewUrl = await postInlineReview(\n input.repo,\n prNumber,\n input.headSha,\n comments,\n stickyRef?.url,\n findingsMarker,\n ghApi,\n );\n process.stderr.write(\n `Posted ${String(comments.length)} inline comments on PR #${String(prNumber)}\\n`,\n );\n\n // Issue #11/#21: now that postInlineReview has actually resolved, the sticky can truthfully\n // report the review — with a link when reviewUrl parsed, as plain text otherwise (still true:\n // the review was posted; only its URL is unknown). Best-effort — the sticky and review are\n // already posted, so a failure here (a bad response, a network hiccup) must never fail the job.\n if (stickyRef !== null) {\n const confirmedDisposition: InlineDisposition = {\n kind: \"posted\",\n count: comments.length,\n sha: input.headSha,\n };\n try {\n await patchComment(\n input.repo,\n stickyRef.id,\n renderBody(confirmedDisposition, reviewUrl),\n ghApi,\n );\n process.stderr.write(`Linked sticky comment #${String(stickyRef.id)} to the review\\n`);\n } catch (err) {\n process.stderr.write(\n `Warning: failed to link the sticky summary to the review: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n};\n","// Gather review inputs (SPEC §8.2): resolve the PR from the trusted head SHA, fetch the diff (with\n// a non-truncating git-diff fallback), the PR context, the prior bot review, and — when CI\n// failed — the failing-job logs. Mirrors the bash \"Gather review inputs\" step 1:1, but as\n// vitest-tested TypeScript, sharing `post`'s PR resolution so the two jobs never split-brain.\n\nimport { execFile } from \"node:child_process\";\nimport { writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as t from \"io-ts\";\nimport type { GhApi } from \"./gh.js\";\nimport { runGhApi } from \"./gh.js\";\nimport { fetchDiff, fetchPrCandidates, resolvePr } from \"./pr.js\";\n\nexport interface GatherInput {\n readonly repo: string;\n readonly headSha: string;\n readonly headBranch?: string;\n readonly runId: string;\n readonly conclusion: string;\n readonly botLogin: string;\n readonly outDir: string;\n}\n\nexport type GatherResult =\n | { readonly kind: \"skip\" }\n | {\n readonly kind: \"gathered\";\n readonly pr: number;\n readonly conclusion: string;\n readonly diffSize: number;\n };\n\n/** The GitHub-outputs lines the step appends to $GITHUB_OUTPUT. CI-agnostic + directly testable. */\nexport const renderOutputs = (result: GatherResult): string => {\n switch (result.kind) {\n case \"skip\":\n return \"skip=true\\n\";\n case \"gathered\":\n return `pr=${String(result.pr)}\\nconclusion=${result.conclusion}\\ndiff_size=${String(result.diffSize)}\\n`;\n }\n};\n\nexport type GitRun = (args: readonly string[]) => Promise<string>;\n\nexport const runGit: GitRun = (args) =>\n new Promise<string>((resolve, reject) => {\n execFile(\n \"git\",\n [...args],\n { encoding: \"utf-8\", maxBuffer: 100 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n const stderrStr = typeof stderr === \"string\" && stderr.trim() ? stderr.trim() : \"\";\n const errStr = err instanceof Error ? err.message : \"unknown error\";\n reject(new Error(`git ${args.join(\" \")} failed: ${stderrStr || errStr}`));\n } else {\n resolve(stdout);\n }\n },\n );\n });\n\nconst PrMetaCodec = t.type({\n changed_files: t.number,\n base_sha: t.string,\n title: t.string,\n body: t.union([t.string, t.null]),\n});\ntype PrMeta = t.TypeOf<typeof PrMetaCodec>;\n\nconst IssueCommentCodec = t.type({\n id: t.number,\n body: t.union([t.string, t.null]),\n user: t.type({ login: t.string }),\n});\nconst IssueCommentsCodec = t.array(IssueCommentCodec);\n\nconst JobCodec = t.type({ id: t.number, conclusion: t.union([t.string, t.null]) });\nconst JobsResponseCodec = t.type({ jobs: t.array(JobCodec) });\n\nconst fetchPrMeta = async (repo: string, prNumber: number, ghApi: GhApi): Promise<PrMeta> => {\n const stdout = await ghApi([\n `repos/${repo}/pulls/${String(prNumber)}`,\n \"--jq\",\n \"{changed_files: .changed_files, base_sha: .base.sha, title: .title, body: .body}\",\n ]);\n const decoded = PrMetaCodec.decode(JSON.parse(stdout) as unknown);\n if (decoded._tag === \"Left\") {\n throw new Error(`PR metadata for #${String(prNumber)} did not match the expected shape`);\n }\n return decoded.right;\n};\n\n/** Fetch the diff via the API; null on failure (drives the git fallback). */\nconst fetchApiDiff = async (\n repo: string,\n prNumber: number,\n ghApi: GhApi,\n): Promise<string | null> => {\n try {\n return await fetchDiff(repo, prNumber, ghApi);\n } catch {\n return null;\n }\n};\n\n/** Last comment authored by botLogin, or null. Degrades to null on ANY failure (bash `|| echo null`). */\nconst fetchPriorReview = async (\n repo: string,\n prNumber: number,\n botLogin: string,\n ghApi: GhApi,\n): Promise<{ readonly id: number; readonly body: string | null } | null> => {\n try {\n const stdout = await ghApi([`repos/${repo}/issues/${String(prNumber)}/comments`, \"--paginate\"]);\n const decoded = IssueCommentsCodec.decode(JSON.parse(stdout || \"[]\") as unknown);\n if (decoded._tag === \"Left\") return null;\n const byBot = decoded.right.filter((c) => c.user.login === botLogin);\n const last = byBot[byBot.length - 1];\n return last ? { id: last.id, body: last.body } : null;\n } catch {\n return null;\n }\n};\n\n/** Download each failing job's logs → <outDir>/job_<id>.log. Jobs-list failure is fatal; a\n * per-log download failure degrades (warns to stderr, keeps whatever logs were retrieved) —\n * logs are advisory input, and partial logs plus the diff beat a dead review. */\nconst downloadFailingJobLogs = async (\n repo: string,\n runId: string,\n outDir: string,\n ghApi: GhApi,\n): Promise<void> => {\n const stdout = await ghApi([`repos/${repo}/actions/runs/${runId}/jobs`]);\n const decoded = JobsResponseCodec.decode(JSON.parse(stdout) as unknown);\n if (decoded._tag === \"Left\") {\n throw new Error(`Jobs list for run ${runId} did not match the expected shape`);\n }\n for (const job of decoded.right.jobs.filter((j) => j.conclusion === \"failure\")) {\n try {\n const log = await ghApi([`repos/${repo}/actions/jobs/${String(job.id)}/logs`]);\n writeFileSync(join(outDir, `job_${String(job.id)}.log`), log);\n } catch (err) {\n process.stderr.write(\n `Warning: failed to download logs for job ${String(job.id)}: ${err instanceof Error ? err.message : String(err)} — continuing with the logs retrieved so far\\n`,\n );\n }\n }\n};\n\nexport const gather = async (\n input: GatherInput,\n ghApi: GhApi = runGhApi,\n gitRun: GitRun = runGit,\n): Promise<GatherResult> => {\n const candidates = await fetchPrCandidates(input.repo, input.headSha, ghApi);\n const resolution = resolvePr(candidates, input.headBranch);\n if (resolution.kind === \"none\") {\n process.stderr.write(`No open PR for ${input.headSha} — nothing to review\\n`);\n return { kind: \"skip\" };\n }\n if (resolution.kind === \"not-open\") {\n process.stderr.write(\n `PR #${String(resolution.prNumber)} for ${input.headSha} is not open (state: ${resolution.state}) — nothing to review\\n`,\n );\n return { kind: \"skip\" };\n }\n const prNumber = resolution.prNumber;\n\n const meta = await fetchPrMeta(input.repo, prNumber, ghApi);\n\n const apiDiff = await fetchApiDiff(input.repo, prNumber, ghApi);\n const diff =\n apiDiff !== null && !(apiDiff.length === 0 && meta.changed_files > 0)\n ? apiDiff\n : await (async () => {\n process.stderr.write(\n `PR diff fetch failed or was empty for ${String(meta.changed_files)} changed files — falling back to git diff\\n`,\n );\n await gitRun([\"fetch\", \"origin\", input.headSha]);\n return gitRun([\"diff\", meta.base_sha, input.headSha]);\n })();\n\n writeFileSync(join(input.outDir, \"pr.diff\"), diff);\n writeFileSync(\n join(input.outDir, \"pr_context.json\"),\n JSON.stringify({ title: meta.title, body: meta.body }),\n );\n\n const prior = await fetchPriorReview(input.repo, prNumber, input.botLogin, ghApi);\n writeFileSync(\n join(input.outDir, \"prior_review.json\"),\n prior === null ? \"null\" : JSON.stringify(prior),\n );\n\n if (input.conclusion === \"failure\") {\n await downloadFailingJobLogs(input.repo, input.runId, input.outDir, ghApi);\n }\n\n return {\n kind: \"gathered\",\n pr: prNumber,\n conclusion: input.conclusion,\n diffSize: Buffer.byteLength(diff, \"utf8\"),\n };\n};\n","// Extraction ladder: recovers a schema-conforming candidate (findings or triage) from a native\n// agent-CLI result envelope when structured-output enforcement is imperfect or absent. Rung order\n// is a fixed priority: --agent-file > structured_output > pure-JSON result > fenced code blocks.\n// The first rung producing exactly one distinct schema-validating candidate wins (fenced-block\n// candidates are deduplicated by canonical value first — an exact duplicate is not a conflict); an\n// error envelope (the agent run did not complete) short-circuits before any rung runs. See\n// docs/adapters.md \"Extraction ladder\" for the security rationale (exactly-one-distinct-validating\n// defeats block-injection).\n//\n// Candidate gate: ajv (via validateAgainstSchema, additionalProperties:false) rejects shape and\n// injection attempts; the registry's io-ts codec (via resolve) then materializes the value,\n// additionally enforcing invariants ajv cannot express (e.g. end_line >= start_line). A candidate\n// must pass both to count as \"validating\".\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve, schemaPathFor, defaultVersion } from \"./registry.js\";\nimport { validateAgainstSchema } from \"./validate.js\";\n\nexport type ExtractKind = \"findings\" | \"triage\";\n\nexport interface ExtractInput {\n readonly kind: ExtractKind;\n readonly native: unknown;\n /** Path to a file the agent was told to write its own validated JSON to (findings only — a\n * documented no-op for triage, per the rung order's \"agent-file wins\" test). */\n readonly agentFilePath?: string;\n}\n\nexport type LadderOutcome =\n | { readonly kind: \"ok\"; readonly version: string; readonly candidate: unknown }\n | { readonly kind: \"error-envelope\"; readonly detail: string }\n | { readonly kind: \"none\"; readonly detail: string }\n | { readonly kind: \"ambiguous\"; readonly detail: string };\n\ninterface NativeForExtraction {\n readonly result: unknown;\n readonly structuredOutput: unknown;\n readonly isError: unknown;\n readonly subtype: unknown;\n readonly apiErrorStatus: unknown;\n}\n\nconst fieldOf = (raw: unknown, key: string): unknown =>\n typeof raw === \"object\" && raw !== null && key in raw\n ? (raw as Record<string, unknown>)[key]\n : undefined;\n\nconst parseNativeForExtraction = (raw: unknown): NativeForExtraction => ({\n result: fieldOf(raw, \"result\"),\n structuredOutput: fieldOf(raw, \"structured_output\"),\n isError: fieldOf(raw, \"is_error\"),\n subtype: fieldOf(raw, \"subtype\"),\n apiErrorStatus: fieldOf(raw, \"api_error_status\"),\n});\n\nconst isNullish = (value: unknown): boolean => value === null || value === undefined;\n\n/** is_error===true OR (subtype not null/undefined and != \"success\") OR api_error_status not null/undefined. */\nconst isErrorEnvelope = (native: NativeForExtraction): boolean =>\n native.isError === true ||\n (!isNullish(native.subtype) && native.subtype !== \"success\") ||\n !isNullish(native.apiErrorStatus);\n\nconst describeErrorEnvelope = (native: NativeForExtraction): string => {\n const parts: readonly string[] = [\n ...(native.isError === true ? [\"is_error=true\"] : []),\n ...(!isNullish(native.subtype) && native.subtype !== \"success\"\n ? [`subtype=${JSON.stringify(native.subtype)}`]\n : []),\n ...(!isNullish(native.apiErrorStatus)\n ? [`api_error_status=${JSON.stringify(native.apiErrorStatus)}`]\n : []),\n ];\n return `agent run did not complete successfully (${parts.join(\", \")})`;\n};\n\n/** Default `schema_version` onto a findings candidate when the agent omitted it; identity for triage. */\nexport const withDefaultSchemaVersion = (candidate: unknown): unknown =>\n typeof candidate === \"object\" &&\n candidate !== null &&\n !Array.isArray(candidate) &&\n !(\"schema_version\" in candidate)\n ? { ...candidate, schema_version: defaultVersion(\"findings\") }\n : candidate;\n\nconst normalizeCandidate = (kind: ExtractKind, candidate: unknown): unknown =>\n kind === \"findings\" ? withDefaultSchemaVersion(candidate) : candidate;\n\nconst candidateVersion = (kind: ExtractKind, candidate: unknown): string | undefined => {\n if (kind !== \"findings\") return undefined;\n const version = fieldOf(candidate, \"schema_version\");\n return typeof version === \"string\" ? version : undefined;\n};\n\nconst safeSchemaPathFor = (kind: ExtractKind, version: string | undefined): string | null => {\n try {\n return schemaPathFor(kind, version);\n } catch {\n return null;\n }\n};\n\ninterface GatedCandidate {\n readonly version: string;\n /** The survivor after `schema_version` injection, pre-registry-normalize (identical for alpha) —\n * what the extract CLI prints, per the registry seam ruling. */\n readonly candidate: unknown;\n}\n\n/** Recursively sort object keys so two values that differ only in key order canonicalize equal. */\nconst canonicalize = (value: unknown): unknown =>\n Array.isArray(value)\n ? value.map(canonicalize)\n : value !== null && typeof value === \"object\"\n ? Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => [k, canonicalize(v)]),\n )\n : value;\n\n/** Collapse gated candidates that are exact duplicates once canonicalized — a model re-emitting its\n * answer verbatim is a plausible benign case, not a conflict. Two candidates that differ in any\n * value still remain distinct, so the injection defense (refusing to pick a survivor among\n * disagreeing candidates) is unweakened. */\nconst dedupCandidates = (candidates: readonly GatedCandidate[]): readonly GatedCandidate[] => {\n const seen = new Set<string>();\n return candidates.filter((c) => {\n const key = JSON.stringify(canonicalize(c.candidate));\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n};\n\n/** Gate a raw candidate through ajv (shape + injection defense) then the registry's io-ts codec\n * (materialization + cross-field invariants); null when either gate rejects it. */\nconst gateCandidate = (kind: ExtractKind, rawCandidate: unknown): GatedCandidate | null => {\n const candidate = normalizeCandidate(kind, rawCandidate);\n const schemaPath = safeSchemaPathFor(kind, candidateVersion(kind, candidate));\n if (schemaPath === null) return null;\n if (!validateAgainstSchema(candidate, schemaPath).valid) return null;\n const resolution = resolve(kind, candidate);\n return resolution.kind === \"ok\" ? { version: resolution.version, candidate } : null;\n};\n\ntype ParseResult = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\nconst tryParseJson = (text: string): ParseResult => {\n try {\n return { ok: true, value: JSON.parse(text) as unknown };\n } catch {\n return { ok: false };\n }\n};\n\nconst readFileOrNull = (path: string): string | null => {\n try {\n return readFileSync(path, \"utf-8\");\n } catch {\n return null;\n }\n};\n\nconst candidateFromJsonText = (kind: ExtractKind, text: string | null): GatedCandidate | null => {\n if (text === null) return null;\n const parsed = tryParseJson(text);\n return parsed.ok ? gateCandidate(kind, parsed.value) : null;\n};\n\ninterface FenceScanState {\n readonly blocks: readonly string[];\n readonly openLength: number | null;\n readonly buffer: readonly string[];\n}\n\nconst FENCE_OPEN = /^\\s*(`{3,})/;\nconst FENCE_MARKER_ONLY = /^`+$/;\n\n/** Fold one line into the fence-scan state. Opens on a line whose first non-whitespace run is\n * >=3 backticks (the rest of the line — an info string like \"json\" — is ignored); closes on the\n * next line that, trimmed, is only backticks of length >= the opening fence. Line-based by\n * design — no regex spans more than one line, so there is no catastrophic-backtracking surface. */\nconst scanLine = (state: FenceScanState, line: string): FenceScanState => {\n if (state.openLength === null) {\n const opened = FENCE_OPEN.exec(line)?.[1]?.length;\n return opened !== undefined ? { blocks: state.blocks, openLength: opened, buffer: [] } : state;\n }\n const trimmed = line.trim();\n const closes = FENCE_MARKER_ONLY.test(trimmed) && trimmed.length >= state.openLength;\n return closes\n ? { blocks: [...state.blocks, state.buffer.join(\"\\n\")], openLength: null, buffer: [] }\n : { ...state, buffer: [...state.buffer, line] };\n};\n\n/** Extract fenced code-block contents from `text` (both ` ```json ` and bare ` ``` `); text before,\n * between, and after fences (and an unterminated trailing fence) is discarded. */\nexport const scanFencedBlocks = (text: string): readonly string[] =>\n text.split(\"\\n\").reduce(scanLine, { blocks: [], openLength: null, buffer: [] }).blocks;\n\n/** Operator-facing breakdown of what each rung actually saw when recovery fails — for stderr/logs,\n * never for the fail-closed reasons (which stay generic). Turns an opaque \"no candidate\" into an\n * actionable trace: a null structured_output points at a CLI not enforcing `--json-schema`. */\nexport const ladderFailureDiagnostics = (input: ExtractInput): string => {\n const native = parseNativeForExtraction(input.native);\n const preview = (s: string): string => {\n const flat = s.replace(/\\s+/g, \" \").trim();\n return flat.length > 200 ? `${flat.slice(0, 200)}…` : flat;\n };\n const lines: string[] = [];\n if (input.kind === \"findings\") {\n lines.push(\n input.agentFilePath === undefined\n ? \"agent-file rung: no --agent-file given\"\n : `agent-file rung: ${input.agentFilePath} did not validate (or was unreadable)`,\n );\n }\n lines.push(\n isNullish(native.structuredOutput)\n ? \"structured_output rung: absent (null) — the CLI's --json-schema likely did not enforce\"\n : \"structured_output rung: present but did not validate against the schema\",\n );\n lines.push(\n typeof native.result === \"string\"\n ? `result rung: ${String(native.result.length)} chars, ${String(scanFencedBlocks(native.result).length)} fenced JSON block(s), none validated; preview: ${preview(native.result)}`\n : \"result rung: absent or not a string\",\n );\n return lines.join(\"\\n\");\n};\n\n/** Render a non-\"ok\" ladder outcome as a single human-readable message. */\nexport const describeLadderFailure = (outcome: Exclude<LadderOutcome, { kind: \"ok\" }>): string => {\n switch (outcome.kind) {\n case \"error-envelope\":\n return `review did not complete: ${outcome.detail}`;\n case \"none\":\n return `could not recover a validating candidate: ${outcome.detail}`;\n case \"ambiguous\":\n return `ambiguous candidates: ${outcome.detail}`;\n }\n};\n\nconst okOutcome = (gated: GatedCandidate): LadderOutcome => ({\n kind: \"ok\",\n version: gated.version,\n candidate: gated.candidate,\n});\n\n/** Run the extraction ladder. Pure aside from an optional `--agent-file` read. */\nexport const extractStructured = (input: ExtractInput): LadderOutcome => {\n const native = parseNativeForExtraction(input.native);\n\n if (isErrorEnvelope(native)) {\n return { kind: \"error-envelope\", detail: describeErrorEnvelope(native) };\n }\n\n if (input.kind === \"findings\" && input.agentFilePath !== undefined) {\n const fromFile = candidateFromJsonText(input.kind, readFileOrNull(input.agentFilePath));\n if (fromFile) return okOutcome(fromFile);\n }\n\n if (native.structuredOutput !== undefined) {\n const fromStructured = gateCandidate(input.kind, native.structuredOutput);\n if (fromStructured) return okOutcome(fromStructured);\n }\n\n if (typeof native.result === \"string\") {\n const fromResult = candidateFromJsonText(input.kind, native.result.trim());\n if (fromResult) return okOutcome(fromResult);\n\n const fencedCandidates = dedupCandidates(\n scanFencedBlocks(native.result)\n .map((block) => candidateFromJsonText(input.kind, block))\n .filter((gated): gated is GatedCandidate => gated !== null),\n );\n\n const [survivor, ...rest] = fencedCandidates;\n if (survivor !== undefined && rest.length === 0) return okOutcome(survivor);\n if (survivor !== undefined) {\n return {\n kind: \"ambiguous\",\n detail: `${String(fencedCandidates.length)} distinct fenced JSON blocks each validate against the ${input.kind} schema — refusing to pick one`,\n };\n }\n }\n\n return {\n kind: \"none\",\n detail: `no --agent-file, structured_output, JSON result, or fenced block validated against the ${input.kind} schema`,\n };\n};\n","// Adapter: maps a coding-agent CLI's native result envelope onto the abstract\n// result envelope (SPEC §6.1). Claude Code is the reference adapter — see docs/adapters.md.\n// Pure mapping; a decode failure surfaces as a Left, never a throw.\n\nimport * as t from \"io-ts\";\nimport type { Either } from \"fp-ts/Either\";\nimport { resolve } from \"./registry.js\";\nimport { extractStructured, describeLadderFailure } from \"./extract.js\";\nimport { DEFAULT_SCHEMA_VERSION, noticeFindings } from \"./schema.js\";\nimport type { Findings, ModelUsageEntry, ResultEnvelope } from \"./schema.js\";\n\n// No value-level import from fp-ts (a bare \"fp-ts/Either\" subpath import breaks under strict\n// Node ESM — see fp-ts's lack of a package.json \"exports\" map). Either values are constructed\n// as plain tagged literals and consumed via ._tag, matching this codebase's existing convention\n// (validate.ts, index.ts) of importing only the Either *type*.\nconst left = <A>(message: string): Either<string, A> => ({ _tag: \"Left\", left: message });\nconst right = <A>(value: A): Either<string, A> => ({ _tag: \"Right\", right: value });\n\nexport type AdapterName = \"claude-code\";\n\nexport const isAdapterName = (name: string): name is AdapterName => name === \"claude-code\";\n\nconst ClaudeCodeModelUsageEntryCodec = t.intersection([\n t.type({\n inputTokens: t.number,\n outputTokens: t.number,\n }),\n t.partial({\n cacheReadInputTokens: t.number,\n cacheCreationInputTokens: t.number,\n costUSD: t.number,\n }),\n]);\n\nexport const ClaudeCodeEnvelopeCodec = t.intersection([\n t.type({\n modelUsage: t.record(t.string, ClaudeCodeModelUsageEntryCodec),\n num_turns: t.number,\n duration_ms: t.number,\n }),\n t.partial({\n total_cost_usd: t.union([t.number, t.null]),\n structured_output: t.unknown,\n }),\n]);\n\ntype ClaudeCodeEnvelope = t.TypeOf<typeof ClaudeCodeEnvelopeCodec>;\n\nconst mapModelUsage = (modelUsage: ClaudeCodeEnvelope[\"modelUsage\"]): ModelUsageEntry[] =>\n Object.entries(modelUsage).map(([model, entry]) => ({\n model,\n input_tokens: entry.inputTokens,\n output_tokens: entry.outputTokens,\n ...(entry.cacheReadInputTokens !== undefined\n ? { cache_read_tokens: entry.cacheReadInputTokens }\n : {}),\n ...(entry.cacheCreationInputTokens !== undefined\n ? { cache_write_tokens: entry.cacheCreationInputTokens }\n : {}),\n }));\n\n/** Route/effort the review ran under (SPEC §6.1 envelope fields). */\nexport interface RunMeta {\n readonly route?: string;\n readonly effort?: string;\n}\n\n/** The extraction ladder's outcome, reduced to what adaptClaudeCode needs: either a materialized\n * findings document, or a reason findings are unavailable. Never a reason to drop telemetry\n * (issue #18) — every ladder outcome maps onto a *findings* result, not a fatal one. */\ntype FindingsOutcome =\n | { readonly kind: \"ok\"; readonly version: string; readonly findings: Findings }\n | { readonly kind: \"telemetry-only\"; readonly reason: string };\n\nconst findingsOutcome = (\n native: ClaudeCodeEnvelope,\n agentFilePath: string | undefined,\n): FindingsOutcome => {\n const ladder = extractStructured({ kind: \"findings\", native, agentFilePath });\n if (ladder.kind !== \"ok\")\n return { kind: \"telemetry-only\", reason: describeLadderFailure(ladder) };\n // The ladder already confirmed this candidate resolves via the registry; re-resolving here just\n // materializes the typed, normalized value it deliberately didn't keep (see extract.ts).\n const resolution = resolve(\"findings\", ladder.candidate);\n return resolution.kind === \"ok\"\n ? { kind: \"ok\", version: resolution.version, findings: resolution.value }\n : {\n kind: \"telemetry-only\",\n reason:\n \"internal error: the extraction ladder validated a candidate the registry then rejected\",\n };\n};\n\n/** Map Claude Code's native `--output-format json` envelope onto the abstract envelope (SPEC §6.1).\n * `findings` and `schema_version` come from the extraction ladder when it recovers a candidate;\n * every other envelope field (models, turns, duration, vendor cost) always comes from the native\n * envelope itself, UNCONDITIONALLY — a findings-ladder miss never discards real telemetry. */\nconst adaptClaudeCode = (\n native: ClaudeCodeEnvelope,\n agentFilePath: string | undefined,\n meta: RunMeta,\n): Either<string, ResultEnvelope> => {\n const telemetry = {\n models: mapModelUsage(native.modelUsage),\n turns: native.num_turns,\n duration_ms: native.duration_ms,\n vendor_cost_usd: native.total_cost_usd ?? null,\n ...(meta.route ? { route: meta.route } : {}),\n ...(meta.effort ? { effort: meta.effort } : {}),\n };\n const outcome = findingsOutcome(native, agentFilePath);\n switch (outcome.kind) {\n case \"ok\":\n return right({\n schema_version: outcome.version,\n findings: outcome.findings,\n ...telemetry,\n });\n case \"telemetry-only\":\n return right({\n schema_version: DEFAULT_SCHEMA_VERSION,\n findings: noticeFindings(`### ⚠️ Review did not complete\\n\\n${outcome.reason}`),\n ...telemetry,\n });\n }\n};\n\n/** Map a native agent-CLI result envelope onto the abstract envelope (SPEC §6.1). `agentFilePath`\n * is meaningful only for the findings recovery (a documented no-op otherwise). */\nexport const adapt = (\n adapterName: AdapterName,\n native: unknown,\n agentFilePath?: string,\n meta: RunMeta = {},\n): Either<string, ResultEnvelope> => {\n switch (adapterName) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- exhaustive by design; AdapterName grows (e.g. \"opencode\") without collapsing this switch to an if\n case \"claude-code\": {\n const decoded = ClaudeCodeEnvelopeCodec.decode(native);\n if (decoded._tag === \"Left\") {\n return left(\"native envelope does not match the Claude Code output shape\");\n }\n return adaptClaudeCode(decoded.right, agentFilePath, meta);\n }\n }\n};\n","// Stop-hook deliverable gate. A Claude Code `Stop` hook that refuses to let the review agent end\n// its turn until it has written a findings document that validates against the schema — turning\n// the \"write your draft and validate before stopping\" instruction from a hope into an invariant.\n// The check is the same validation `code-review validate` performs.\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { validateAgainstSchema } from \"./validate.js\";\n\n/** Validation state of the agent's draft deliverable at the moment it tries to stop. A sum type so\n * `decideGate` can reprompt precisely per case — critically, distinguishing an UNREADABLE file\n * (EACCES/EISDIR) from an INVALID one, since \"does not validate against the schema\" is a lie when\n * the file could not even be read. */\nexport type DraftState =\n | { readonly kind: \"missing\" }\n | { readonly kind: \"unreadable\"; readonly error: string }\n | { readonly kind: \"invalid\"; readonly errors: readonly string[] }\n | { readonly kind: \"valid\" };\n\n/** A Stop-hook outcome: `block` feeds `reason` back to the agent so it keeps working; `allow`\n * lets the turn end. */\nexport type GateDecision =\n { readonly kind: \"allow\" } | { readonly kind: \"block\"; readonly reason: string };\n\n/** The precise \"what's wrong\" clause per non-valid draft state — honest about unreadable vs invalid. */\nconst whatsWrong = (\n state: Exclude<DraftState, { kind: \"valid\" }>,\n draftPath: string,\n kind: string,\n): string => {\n switch (state.kind) {\n case \"missing\":\n return `${draftPath} does not exist yet`;\n case \"unreadable\":\n return `${draftPath} could not be read: ${state.error}`;\n case \"invalid\":\n return `${draftPath} does not validate against the ${kind} schema:\\n${state.errors\n .map((e) => ` - ${e}`)\n .join(\"\\n\")}`;\n }\n};\n\n/** The settings shape Claude Code reads from a `--settings` file to wire a Stop hook command. */\nexport interface StopHookSettings {\n readonly hooks: {\n readonly Stop: readonly {\n readonly hooks: readonly { readonly type: \"command\"; readonly command: string }[];\n }[];\n };\n}\n\n/** Allow when the draft validates or the nudge budget is spent; otherwise block with a reason\n * that names what is wrong and reprompts the agent about the ONLY deliverable — a document\n * validating against `kind`'s schema — so it can fix it. */\nexport const decideGate = (\n state: DraftState,\n nudges: number,\n maxNudges: number,\n draftPath: string,\n kind: string,\n): GateDecision => {\n if (state.kind === \"valid\") return { kind: \"allow\" };\n if (nudges >= maxNudges) return { kind: \"allow\" };\n return {\n kind: \"block\",\n reason: [\n `This review is not complete — ${whatsWrong(state, draftPath, kind)}`,\n `The only deliverable is a ${kind} document that validates against the ${kind} schema — run \"code-review print-schema ${kind}\" to see the exact shape.`,\n `Write it to ${draftPath}, then run \"code-review validate ${draftPath} --kind ${kind}\" until it exits 0 before ending your turn.`,\n ].join(\"\\n\"),\n };\n};\n\n/** Read and validate the draft, resolving the schema from the parsed document when needed. Never\n * throws — every failure mode (missing file, unreadable file, invalid JSON, an unresolvable or\n * crashing schema lookup, a validator crash) degrades to a `DraftState` the gate can act on,\n * rather than crashing the hook and letting the agent stop by default. */\nexport const draftState = (\n draftPath: string,\n resolveSchema: (parsed: unknown) => string,\n): DraftState => {\n let raw: string;\n try {\n raw = readFileSync(draftPath, \"utf-8\");\n } catch (err) {\n if (err instanceof Error && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { kind: \"missing\" };\n }\n return { kind: \"unreadable\", error: err instanceof Error ? err.message : String(err) };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n kind: \"invalid\",\n errors: [`not valid JSON: ${err instanceof Error ? err.message : String(err)}`],\n };\n }\n let schemaPath: string;\n try {\n schemaPath = resolveSchema(parsed);\n } catch (err) {\n return { kind: \"invalid\", errors: [err instanceof Error ? err.message : String(err)] };\n }\n try {\n const { valid, errors } = validateAgainstSchema(parsed, schemaPath);\n return valid ? { kind: \"valid\" } : { kind: \"invalid\", errors };\n } catch (err) {\n return { kind: \"invalid\", errors: [err instanceof Error ? err.message : String(err)] };\n }\n};\n\n/** Nudge count persisted beside the draft across hook invocations within one review. Absent or\n * unparseable counts read as 0, so a fresh review starts with a full budget. */\nexport const readNudges = (counterPath: string): number => {\n try {\n const n = Number.parseInt(readFileSync(counterPath, \"utf-8\").trim(), 10);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n } catch {\n return 0;\n }\n};\n\n/** Persist the incremented nudge count (`current + 1`). The caller reads `current` immediately\n * prior (via `readNudges`) and passes it here, so there is no second read to go stale. May throw\n * on a write failure — the caller decides how to handle that (index.ts allows the stop rather than\n * emit an unbounded block). */\nexport const bumpNudges = (counterPath: string, current: number): void => {\n writeFileSync(counterPath, `${String(current + 1)}\\n`);\n};\n\n/** POSIX single-quote a string for safe embedding in a hook command line. */\nexport const shellQuote = (s: string): string => `'${s.replace(/'/g, `'\\\\''`)}'`;\n\n/** The default hook command: this CLI re-invoked as the gate, carrying the same schema/budget\n * flags so the hook validates exactly as the caller intended. */\nexport const defaultHookCommand = (\n draftPath: string,\n opts: {\n readonly kind?: string;\n readonly schema?: string;\n readonly schemaVersion?: string;\n readonly maxNudges?: string;\n readonly counter?: string;\n },\n): string =>\n [\n \"code-review stop-gate --draft\",\n shellQuote(draftPath),\n ...(opts.kind ? [\"--kind\", shellQuote(opts.kind)] : []),\n ...(opts.schema ? [\"--schema\", shellQuote(opts.schema)] : []),\n ...(opts.schemaVersion ? [\"--schema-version\", shellQuote(opts.schemaVersion)] : []),\n ...(opts.maxNudges ? [\"--max-nudges\", shellQuote(opts.maxNudges)] : []),\n ...(opts.counter ? [\"--counter\", shellQuote(opts.counter)] : []),\n ].join(\" \");\n\n/** The settings object that wires `command` as a Stop hook. */\nexport const stopHookSettings = (command: string): StopHookSettings => ({\n hooks: { Stop: [{ hooks: [{ type: \"command\", command }] }] },\n});\n","#!/usr/bin/env node\n// CLI entry point — citty subcommands for render, inline, post, cost, validate, adapt, extract,\n// validate-patches, print-schema, stop-gate.\n\n/* eslint-disable @typescript-eslint/require-await */\n// citty requires async run() even when the body has no explicit await\n\nimport { defineCommand, runMain } from \"citty\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Either } from \"fp-ts/Either\";\nimport { render } from \"./render.js\";\nimport { buildInlineComments, renderStraysSection } from \"./inline.js\";\nimport { computeCost } from \"./cost.js\";\nimport { validateAgainstSchema, unsafeUnwrap } from \"./validate.js\";\nimport { formatUtc } from \"./format.js\";\nimport { ResultEnvelopeCodec, FindingsCodec, PriceMapCodec, TestSummaryCodec } from \"./schema.js\";\nimport type { Triage, Finding } from \"./schema.js\";\nimport { post } from \"./post.js\";\nimport { gather, renderOutputs } from \"./gather.js\";\nimport { adapt, isAdapterName } from \"./adapt.js\";\nimport type { AdapterName } from \"./adapt.js\";\nimport { extractStructured, describeLadderFailure, ladderFailureDiagnostics } from \"./extract.js\";\nimport type { ExtractKind, LadderOutcome } from \"./extract.js\";\nimport { schemaPathFor, declaredVersion } from \"./registry.js\";\nimport type { SchemaKind } from \"./registry.js\";\nimport { validatePatch } from \"./patch.js\";\nimport {\n decideGate,\n draftState,\n readNudges,\n bumpNudges,\n defaultHookCommand,\n stopHookSettings,\n} from \"./stop-gate.js\";\n\nconst readJSON = (path: string): unknown => {\n try {\n return JSON.parse(readFileSync(resolve(path), \"utf-8\")) as unknown;\n } catch (err) {\n fail(`Cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`);\n throw new Error(\"unreachable\", { cause: err }); // fail() always exits\n }\n};\n\nconst fail = (msg: string): never => {\n process.stderr.write(`${msg}\\n`);\n process.exit(1);\n};\n\nconst decode = <A>(either: Either<unknown, A>, label: string): A => {\n try {\n return unsafeUnwrap(either);\n } catch {\n fail(`${label} does not match expected shape`);\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Unwrap an adapter's Either, surfacing its own message rather than a generic one. */\nconst unwrapAdapt = <A>(either: Either<string, A>): A => {\n try {\n if (either._tag === \"Left\") throw new Error(either.left);\n return either.right;\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Resolve a path bundled with the package (schema/, templates/) — same pattern as validate's default schema. */\nconst bundledPath = (...segments: string[]): string =>\n resolve(import.meta.dirname, \"..\", ...segments);\n\nconst packageVersion = (\n JSON.parse(readFileSync(bundledPath(\"package.json\"), \"utf-8\")) as { version: string }\n).version;\n\n/** `--template` defaults to the bundled comment template when omitted. */\nconst resolveTemplatePath = (templateArg: string | undefined): string =>\n templateArg ? resolve(templateArg) : bundledPath(\"templates\", \"comment.eta\");\n\n/** `--inline-template` defaults to the bundled inline template when omitted (inline.eta is the\n * per-surface SSOT — issue #22 — mirroring resolveTemplatePath's sticky default). */\nconst resolveInlineTemplatePath = (templateArg: string | undefined): string =>\n templateArg ? resolve(templateArg) : bundledPath(\"templates\", \"inline.eta\");\n\n/** Price-map resolution with explicit provenance: `provided` is a real caller-supplied map,\n * `absent` is the bundled all-zero example standing in for one (loaded only to satisfy the codec /\n * computeCost shape). The render layer is TOLD which, so it reports cost as N/A rather than a false\n * $0.00 when absent (SPEC §6.2) — never inferring it from the path. */\ntype PriceResolution =\n | { readonly kind: \"provided\"; readonly path: string }\n | { readonly kind: \"absent\"; readonly path: string };\n\n/** `--prices` defaults to the bundled (all-zero) example prices when omitted, with a warning. */\nconst resolvePrices = (pricesArg: string | undefined): PriceResolution => {\n if (pricesArg) return { kind: \"provided\", path: resolve(pricesArg) };\n process.stderr.write(\n \"code-review: no --prices given — cost will be reported as N/A (no price map to recompute from)\\n\",\n );\n return { kind: \"absent\", path: bundledPath(\"schema\", \"prices.example.json\") };\n};\n\nconst TEST_REPORT_DESCRIPTION =\n 'Path to a JSON test summary: {\"passed\": number, \"failed\": number, \"total\": number, \"failures\"?: [{\"name\": string, \"message\"?: string}]}';\n\nconst renderCmd = defineCommand({\n meta: {\n name: \"render\",\n description: \"Render a code-review comment from findings + usage + prices\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n template: {\n type: \"string\",\n description: \"Path to Eta template file (default: bundled templates/comment.eta)\",\n },\n usage: {\n type: \"string\",\n description: \"Path to result envelope JSON (from agent CLI)\",\n required: true,\n },\n prices: {\n type: \"string\",\n description:\n \"Path to price map JSON (default: bundled schema/prices.example.json — all zero)\",\n },\n \"reviewed-sha\": {\n type: \"string\",\n description: \"SHA of the last reviewed commit\",\n },\n route: {\n type: \"string\",\n description:\n \"Review route label; overrides the envelope's route when set (default: read from the envelope)\",\n },\n effort: {\n type: \"string\",\n description:\n \"Effort label; overrides the envelope's effort when set (default: read from the envelope)\",\n },\n \"test-report\": {\n type: \"string\",\n description: TEST_REPORT_DESCRIPTION,\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const envelope = decode(ResultEnvelopeCodec.decode(readJSON(args.usage)), \"envelope\");\n const templatePath = resolveTemplatePath(args.template);\n const priceResolution = resolvePrices(args.prices);\n const prices = decode(PriceMapCodec.decode(readJSON(priceResolution.path)), \"prices\");\n const template = readFileSync(templatePath, \"utf-8\");\n const testReport = args[\"test-report\"]\n ? decode(TestSummaryCodec.decode(readJSON(args[\"test-report\"])), \"test report\")\n : undefined;\n const output = render({\n findings,\n envelope,\n prices,\n pricesProvided: priceResolution.kind === \"provided\",\n template,\n reviewedSha: args[\"reviewed-sha\"],\n route: args.route,\n effort: args.effort,\n testReport,\n postedAt: formatUtc(new Date()),\n });\n process.stdout.write(output);\n },\n});\n\nconst inlineCmd = defineCommand({\n meta: {\n name: \"inline\",\n description: \"Build GitHub reviews comments[] payload from findings + diff\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n diff: {\n type: \"string\",\n description: \"Path to PR diff file\",\n required: true,\n },\n template: {\n type: \"string\",\n description: \"Path to inline comment Eta template (default: bundled templates/inline.eta)\",\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const diff = readFileSync(resolve(args.diff), \"utf-8\");\n const inlineTemplate = readFileSync(resolveInlineTemplatePath(args.template), \"utf-8\");\n const { comments, strays } = buildInlineComments(findings.findings, diff, {\n inlineTemplate,\n findings,\n });\n process.stdout.write(\n JSON.stringify({ comments, strays, stray_markdown: renderStraysSection(strays) }, null, 2),\n );\n },\n});\n\nconst costCmd = defineCommand({\n meta: {\n name: \"cost\",\n description: \"Recompute USD cost from the envelope's models array + price map\",\n },\n args: {\n envelope: {\n type: \"positional\",\n description: \"Path to result envelope JSON\",\n required: true,\n },\n prices: {\n type: \"string\",\n description: \"Path to price map JSON\",\n required: true,\n },\n },\n run: async ({ args }) => {\n const envelope = decode(ResultEnvelopeCodec.decode(readJSON(args.envelope)), \"envelope\");\n const prices = decode(PriceMapCodec.decode(readJSON(args.prices)), \"prices\");\n const report = computeCost(envelope.models, prices);\n process.stdout.write(JSON.stringify(report, null, 2));\n },\n});\n\n/** The version to derive when neither --schema nor --schema-version is given: findings carries its\n * version in-data; triage/prices have no in-data signal (see registry.ts), so undefined selects the\n * registry default (latest) for the kind. */\nconst derivedSchemaVersion = (kind: SchemaKind, raw: unknown): string | undefined =>\n kind === \"findings\" ? declaredVersion(raw) : undefined;\n\nconst validateCmd = defineCommand({\n meta: {\n name: \"validate\",\n description: \"Validate a findings/triage/prices JSON document against the canonical schema\",\n },\n args: {\n document: {\n type: \"positional\",\n description: \"Path to the JSON document to validate (of the given --kind)\",\n required: true,\n },\n kind: {\n type: \"string\",\n description:\n \"Schema kind to validate against: findings | triage | prices (default: findings)\",\n },\n schema: {\n type: \"string\",\n description:\n \"Path to a schema file (wins over --kind; default: the bundled schema derived from --kind, --schema-version, the document's declared schema_version, or the bundled latest)\",\n },\n \"schema-version\": {\n type: \"string\",\n description:\n \"Schema major.minor version to validate against (default: the document's declared schema_version for findings, or the kind's latest)\",\n },\n },\n run: async ({ args }) => {\n const kind = requireSchemaKind(args.kind || \"findings\");\n const documentRaw = readJSON(args.document);\n const schemaPath = args.schema\n ? resolve(args.schema)\n : requireSchemaPath(kind, args[\"schema-version\"] || derivedSchemaVersion(kind, documentRaw));\n const { valid, errors } = validateAgainstSchema(documentRaw, schemaPath);\n if (valid) {\n process.stdout.write(\"✅ valid\\n\");\n } else {\n process.stderr.write(\"❌ invalid\\n\");\n for (const e of errors) process.stderr.write(` - ${e}\\n`);\n process.exit(1);\n }\n },\n});\n\nconst adaptCmd = defineCommand({\n meta: {\n name: \"adapt\",\n description: \"Map a native agent-CLI result envelope onto the abstract SPEC §6.1 envelope\",\n },\n args: {\n native: {\n type: \"positional\",\n description: \"Path to the native result envelope JSON (from the agent CLI)\",\n required: true,\n },\n adapter: {\n type: \"string\",\n description: 'Adapter to use (currently: \"claude-code\")',\n required: true,\n },\n \"agent-file\": {\n type: \"string\",\n description:\n \"Path to a file the agent was told to write its own validated findings JSON to (wins over the native envelope's structured_output/result when it validates)\",\n },\n route: {\n type: \"string\",\n description:\n 'Review route label to stamp into the envelope (e.g. \"full review\" or \"mechanic\")',\n },\n effort: {\n type: \"string\",\n description: 'Effort label to stamp into the envelope (e.g. \"max\" or \"low\")',\n },\n },\n run: async ({ args }) => {\n const envelope = unwrapAdapt(\n adapt(requireAdapterName(args.adapter), readJSON(args.native), args[\"agent-file\"], {\n route: args.route,\n effort: args.effort,\n }),\n );\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n },\n});\n\nconst isExtractSchemaKind = (s: string): s is ExtractKind => s === \"findings\" || s === \"triage\";\n\n/** Narrow to a schema kind the extraction ladder supports (no \"prices\" — unlike print-schema's),\n * or fail with a clear message (never falls through). */\nconst requireExtractSchemaKind = (name: string): ExtractKind => {\n if (isExtractSchemaKind(name)) return name;\n fail(`Unknown kind \"${name}\" for extract — expected one of: findings, triage`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Fail-closed triage synthesized when the ladder can't recover a validated triage verdict — never\n * defaults to safe (§7.3). */\nconst failClosedTriage = (outcome: Exclude<LadderOutcome, { kind: \"ok\" }>): Triage => ({\n safe: false,\n reasons: describeLadderFailure(outcome),\n});\n\nconst extractCmd = defineCommand({\n meta: {\n name: \"extract\",\n description:\n \"Recover findings/triage JSON from a native agent-CLI result envelope via the deterministic extraction ladder\",\n },\n args: {\n native: {\n type: \"positional\",\n description: \"Path to the native result envelope JSON (from the agent CLI)\",\n required: true,\n },\n adapter: {\n type: \"string\",\n description: 'Adapter whose native envelope shape to extract from (currently: \"claude-code\")',\n required: true,\n },\n kind: {\n type: \"string\",\n description: \"Schema kind to extract: findings | triage\",\n required: true,\n },\n \"agent-file\": {\n type: \"string\",\n description:\n \"Path to a file the agent was told to write its own validated JSON to (findings only — a documented no-op for triage)\",\n },\n },\n run: async ({ args }) => {\n requireAdapterName(args.adapter);\n const kind = requireExtractSchemaKind(args.kind);\n const input = { kind, native: readJSON(args.native), agentFilePath: args[\"agent-file\"] };\n const outcome = extractStructured(input);\n\n if (outcome.kind === \"ok\") {\n process.stdout.write(`${JSON.stringify(outcome.candidate, null, 2)}\\n`);\n return;\n }\n // A recovery miss is otherwise opaque (only the generic reason reaches the comment); trace what\n // each rung saw to stderr so the CI log alone explains the failure — no local repro needed.\n if (outcome.kind === \"none\" || outcome.kind === \"ambiguous\") {\n process.stderr.write(`extract: recovery failed —\\n${ladderFailureDiagnostics(input)}\\n`);\n }\n if (kind === \"triage\") {\n process.stdout.write(`${JSON.stringify(failClosedTriage(outcome), null, 2)}\\n`);\n return;\n }\n fail(describeLadderFailure(outcome));\n },\n});\n\n/** `finding` with its `patch` field removed — a fresh shallow copy, `finding` itself untouched. */\nconst withoutPatch = (finding: Finding): Finding => {\n const copy = { ...finding };\n delete copy.patch;\n return copy;\n};\n\n/** A file's lines, LF-split and without a trailing-newline artifact entry; null when unreadable. */\nconst readFileLines = (path: string): readonly string[] | null => {\n try {\n const rawLines = readFileSync(path, \"utf-8\").split(\"\\n\");\n return rawLines.length > 0 && rawLines[rawLines.length - 1] === \"\"\n ? rawLines.slice(0, -1)\n : rawLines;\n } catch {\n return null;\n }\n};\n\n/** Validate one finding's `patch` (when present) against the real file at `<repoRoot>/<finding.path>`,\n * aligning the finding's `start_line`/`end_line` to the patch's removed range and KEEPING the patch\n * for the renderer to project. Drop the patch (logging why to stderr) when the file can't be read\n * or the patch doesn't apply cleanly — the finding survives without it, never writing a suggestion.\n * A finding with no patch passes through untouched. Never throws. */\nconst validateFinding = (finding: Finding, repoRoot: string): Finding => {\n if (finding.patch === undefined) return finding;\n const lines = readFileLines(resolve(repoRoot, finding.path));\n if (lines === null) {\n process.stderr.write(\n `validate-patches: ${finding.path}: could not read file at \"${repoRoot}\" — dropping patch\\n`,\n );\n return withoutPatch(finding);\n }\n const result = validatePatch(finding.patch, lines);\n if (\"kind\" in result) {\n process.stderr.write(\n `validate-patches: ${finding.path}:${String(finding.start_line)}: ${result.reason} — dropping patch\\n`,\n );\n return withoutPatch(finding);\n }\n return { ...finding, start_line: result.startLine, end_line: result.endLine };\n};\n\nconst validatePatchesCmd = defineCommand({\n meta: {\n name: \"validate-patches\",\n description:\n \"Validate each finding's patch against the real PR-head tree, aligning the finding's range to it and keeping the patch, or dropping the patch (issue #10)\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n \"repo-root\": {\n type: \"string\",\n description:\n \"Directory to resolve each finding's path against — the review job's checked-out, clean PR-head tree (default: .)\",\n },\n },\n run: async ({ args }) => {\n const findings = decode(FindingsCodec.decode(readJSON(args.findings)), \"findings\");\n const repoRoot = args[\"repo-root\"] ? resolve(args[\"repo-root\"]) : process.cwd();\n const validated = {\n ...findings,\n findings: findings.findings.map((f) => validateFinding(f, repoRoot)),\n };\n process.stdout.write(`${JSON.stringify(validated, null, 2)}\\n`);\n },\n});\n\n/** Narrow to a known adapter name, or fail with a clear message (never falls through). */\nconst requireAdapterName = (name: string): AdapterName => {\n if (isAdapterName(name)) return name;\n fail(`Unknown adapter \"${name}\" — supported: claude-code`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\nconst isSchemaKind = (s: string): s is SchemaKind =>\n s === \"findings\" || s === \"triage\" || s === \"prices\";\n\n/** Narrow to a known schema kind, or fail with a clear message (never falls through). */\nconst requireSchemaKind = (name: string): SchemaKind => {\n if (isSchemaKind(name)) return name;\n fail(`Unknown schema \"${name}\" — expected one of: findings, triage, prices`);\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\n/** Resolve a bundled schema path via the registry, or fail listing what's supported. */\nconst requireSchemaPath = (kind: SchemaKind, version: string | undefined): string => {\n try {\n return schemaPathFor(kind, version);\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n }\n throw new Error(\"unreachable\"); // fail() always exits\n};\n\nconst printSchemaCmd = defineCommand({\n meta: {\n name: \"print-schema\",\n description:\n \"Print a bundled schema JSON, ready to hand to a CLI's --json-schema (the $schema draft declaration is stripped)\",\n },\n args: {\n name: {\n type: \"positional\",\n description: \"Schema to print: findings | triage | prices\",\n required: true,\n },\n \"schema-version\": {\n type: \"string\",\n description: \"Schema major.minor version to print (default: latest)\",\n },\n },\n run: async ({ args }) => {\n const schemaKind = requireSchemaKind(args.name);\n const schemaPath = requireSchemaPath(schemaKind, args[\"schema-version\"]);\n const schema = JSON.parse(readFileSync(schemaPath, \"utf-8\")) as Record<string, unknown>;\n // `claude -p --json-schema` silently disables structured-output enforcement when the schema\n // carries a top-level `$schema` draft declaration — `structured_output` comes back null and the\n // model guesses field names. The canonical file keeps `$schema` for validators; the form handed\n // to a CLI must omit it. `$id`/`title` are tolerated and kept.\n const enforcementSchema = Object.fromEntries(\n Object.entries(schema).filter(([key]) => key !== \"$schema\"),\n );\n process.stdout.write(`${JSON.stringify(enforcementSchema, null, 2)}\\n`);\n },\n});\n\nconst MAX_NUDGES_DEFAULT = 5;\n\n/** Drain the Stop-hook payload delivered on stdin so the caller never sees EPIPE; its content is\n * not needed — the decision comes from the draft on disk. Skips draining on a TTY (an interactive,\n * manual run with nothing piped in) since readFileSync(0) would otherwise block forever waiting\n * for EOF that never comes; absent/empty piped stdin otherwise is fine.\n * DEFERRED (known low-risk edge): a pipe held open without data + EOF could still block here, but\n * the real Stop hook writes its payload then closes (EOF), and the TTY case is guarded above, so\n * the held-open-forever case isn't the production path. Revisit only if hangs are observed. */\nconst drainStdin = (): void => {\n if (process.stdin.isTTY) return;\n try {\n readFileSync(0);\n } catch {\n // no stdin\n }\n};\n\n/** Parse `--max-nudges`: a strict positive integer (`>= 1`). A loose `Number.parseInt` accepts\n * `\"5abc\"`/`\"0x5\"` and `0 >= 0` allows on the first call — both silently DISABLE the gate. Reject\n * anything not matching `^\\d+$`, and reject `< 1`, loudly: a gate that never blocks must be an\n * explicit choice (omit the hook), never a typo. */\nconst requireMaxNudges = (raw: string | undefined): number => {\n if (raw === undefined) return MAX_NUDGES_DEFAULT;\n if (!/^\\d+$/.test(raw)) {\n fail(`--max-nudges must be a non-negative integer; got \"${raw}\"`);\n }\n const n = Number.parseInt(raw, 10);\n if (n < 1) {\n fail(`--max-nudges must be >= 1 — a gate that never blocks must be omitted, not set to ${raw}`);\n }\n return n;\n};\n\nconst stopGateCmd = defineCommand({\n meta: {\n name: \"stop-gate\",\n description:\n \"Claude Code Stop-hook gate: refuse to let the agent end its turn until --draft validates against the schema (bounded by --max-nudges). With --print-settings, emit the --settings JSON that wires this as the Stop hook.\",\n },\n args: {\n draft: {\n type: \"string\",\n description: \"Path to the findings document the agent must produce and keep valid\",\n required: true,\n },\n kind: {\n type: \"string\",\n description:\n \"Schema kind to validate against: findings | triage | prices (default: findings)\",\n },\n schema: { type: \"string\", description: \"Path to a schema file (wins over --kind)\" },\n \"schema-version\": {\n type: \"string\",\n description: \"Schema major.minor to validate against (default: the draft's declared version)\",\n },\n \"max-nudges\": {\n type: \"string\",\n description: `Times to block before relenting so the step fails downstream as before (default: ${String(MAX_NUDGES_DEFAULT)})`,\n },\n counter: {\n type: \"string\",\n description: \"Path for the nudge counter (default: <draft>.nudges)\",\n },\n \"print-settings\": {\n type: \"boolean\",\n description: \"Print the Stop-hook settings JSON that wires this gate, then exit\",\n },\n },\n run: async ({ args }) => {\n const draftPath = resolve(args.draft);\n\n if (args[\"print-settings\"]) {\n const command = defaultHookCommand(draftPath, {\n kind: args.kind,\n schema: args.schema,\n schemaVersion: args[\"schema-version\"],\n maxNudges: args[\"max-nudges\"],\n counter: args.counter,\n });\n process.stdout.write(`${JSON.stringify(stopHookSettings(command))}\\n`);\n return;\n }\n\n drainStdin();\n\n const kind = requireSchemaKind(args.kind || \"findings\");\n const maxNudges = requireMaxNudges(args[\"max-nudges\"]);\n const counterPath = args.counter ? resolve(args.counter) : `${draftPath}.nudges`;\n\n // schemaPathFor throws (rather than the process-exiting requireSchemaPath) so that a draft\n // declaring an unsupported schema_version is caught by draftState and treated as invalid —\n // i.e. a block with a helpful message — instead of crashing the hook and letting the agent stop.\n const state = draftState(draftPath, (parsed) =>\n args.schema\n ? resolve(args.schema)\n : schemaPathFor(kind, args[\"schema-version\"] || derivedSchemaVersion(kind, parsed)),\n );\n\n const nudges = readNudges(counterPath);\n const decision = decideGate(state, nudges, maxNudges, draftPath, kind);\n if (decision.kind === \"block\") {\n // CRITICAL ordering: bump the counter FIRST, and emit the block ONLY after the increment is\n // durably persisted. If the write fails, do NOT block — a block we can't bound loops forever\n // (the counter never advances → `nudges >= maxNudges` is never reached). Allow the stop and\n // log: a missed nudge is far less bad than an unbounded block loop.\n try {\n bumpNudges(counterPath, nudges);\n } catch (err) {\n process.stderr.write(\n `stop-gate: cannot persist nudge counter at ${counterPath} → allowing to avoid an unbounded block loop: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return;\n }\n process.stdout.write(`${JSON.stringify({ decision: \"block\", reason: decision.reason })}\\n`);\n }\n },\n});\n\nconst gatherCmd = defineCommand({\n meta: {\n name: \"gather\",\n description:\n \"Resolve the PR from the CI head SHA and gather review inputs (diff with git-diff fallback, PR context, prior bot review, failing-job logs) as files for the review agent\",\n },\n args: {\n repo: { type: \"string\", description: \"Repository (owner/name)\", required: true },\n \"head-sha\": {\n type: \"string\",\n description: \"Trusted head SHA to resolve the PR (from workflow_run.head_sha)\",\n required: true,\n },\n \"head-branch\": {\n type: \"string\",\n description: \"Head branch to disambiguate the PR when multiple share a commit\",\n },\n \"run-id\": {\n type: \"string\",\n description:\n \"CI run id (from workflow_run.id); its failing jobs' logs are downloaded on failure\",\n required: true,\n },\n conclusion: {\n type: \"string\",\n description:\n \"CI conclusion (e.g. success | failure); failure triggers failing-job log download\",\n required: true,\n },\n \"bot-login\": {\n type: \"string\",\n description:\n \"Bot login whose last PR comment is captured as prior review (default: github-actions[bot])\",\n },\n \"out-dir\": {\n type: \"string\",\n description: \"Directory to write gathered files into (default: current directory)\",\n },\n },\n run: async ({ args }) => {\n const result = await gather({\n repo: args.repo,\n headSha: args[\"head-sha\"],\n headBranch: args[\"head-branch\"],\n runId: args[\"run-id\"],\n conclusion: args.conclusion,\n botLogin: args[\"bot-login\"] || \"github-actions[bot]\",\n outDir: args[\"out-dir\"] ? resolve(args[\"out-dir\"]) : process.cwd(),\n });\n process.stdout.write(renderOutputs(result));\n },\n});\n\nconst postCmd = defineCommand({\n meta: {\n name: \"post\",\n description:\n \"Post a complete review (inline comments + sticky summary) from findings + envelope + diff\",\n },\n args: {\n findings: {\n type: \"positional\",\n description: \"Path to findings JSON\",\n required: true,\n },\n \"head-sha\": {\n type: \"string\",\n description: \"Trusted head SHA to resolve the PR (from workflow_run.head_sha)\",\n required: true,\n },\n repo: {\n type: \"string\",\n description: \"Repository (owner/name)\",\n required: true,\n },\n usage: {\n type: \"string\",\n description: \"Path to result envelope JSON (from agent CLI)\",\n required: true,\n },\n prices: {\n type: \"string\",\n description:\n \"Path to price map JSON (default: bundled schema/prices.example.json — all zero)\",\n },\n template: {\n type: \"string\",\n description:\n \"Path to Eta template file for the summary comment (default: bundled templates/comment.eta)\",\n },\n \"inline-template\": {\n type: \"string\",\n description: \"Path to inline comment Eta template (default: bundled templates/inline.eta)\",\n },\n route: {\n type: \"string\",\n description:\n \"Review route label; overrides the envelope's route when set (default: read from the envelope)\",\n },\n \"bot-login\": {\n type: \"string\",\n description: \"Bot login to trust for sticky comment upsert (default: github-actions[bot])\",\n },\n \"head-branch\": {\n type: \"string\",\n description: \"Head branch to disambiguate PR when multiple share a commit\",\n },\n effort: {\n type: \"string\",\n description:\n \"Effort label; overrides the envelope's effort when set (default: read from the envelope)\",\n },\n \"test-report\": {\n type: \"string\",\n description: TEST_REPORT_DESCRIPTION,\n },\n \"run-url\": {\n type: \"string\",\n description:\n \"Workflow run URL (transcript/traces), rendered as a link in the LLM Disclosure aside\",\n },\n \"json-url\": {\n type: \"string\",\n description:\n \"URL to the machine-readable findings JSON artifact, pointed at from the sticky and each inline comment\",\n },\n },\n run: async ({ args }) => {\n const priceResolution = resolvePrices(args.prices);\n await post({\n repo: args.repo,\n headSha: args[\"head-sha\"],\n botLogin: args[\"bot-login\"] || \"github-actions[bot]\",\n findingsPath: args.findings,\n envelopePath: args.usage,\n pricesPath: priceResolution.path,\n pricesProvided: priceResolution.kind === \"provided\",\n templatePath: resolveTemplatePath(args.template),\n inlineTemplatePath: resolveInlineTemplatePath(args[\"inline-template\"]),\n route: args.route,\n headBranch: args[\"head-branch\"],\n effort: args.effort,\n testReportPath: args[\"test-report\"],\n runUrl: args[\"run-url\"],\n jsonUrl: args[\"json-url\"],\n postedAt: formatUtc(new Date()),\n });\n },\n});\n\nexport const main = defineCommand({\n meta: {\n name: \"code-review\",\n version: packageVersion,\n description:\n \"Deterministic commenter for agentic PR review — gather, render, inline, post, adapt, extract, validate-patches, cost, validate, and stop-gate findings JSON\",\n },\n subCommands: {\n gather: gatherCmd,\n render: renderCmd,\n inline: inlineCmd,\n post: postCmd,\n cost: costCmd,\n validate: validateCmd,\n adapt: adaptCmd,\n extract: extractCmd,\n \"validate-patches\": validatePatchesCmd,\n \"print-schema\": printSchemaCmd,\n \"stop-gate\": stopGateCmd,\n },\n});\n\n// Skip auto-invocation under the test runner — tests drive `main` directly via citty's runCommand.\nif (!process.env[\"VITEST\"]) {\n await runMain(main);\n}\n"]}