@effect-agent/pr-review 0.1.0-beta.28 → 0.1.0-beta.30
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/README.md +11 -204
- package/dist/index.d.mts +92 -914
- package/dist/index.mjs +176 -71
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -18
- package/src/index.ts +1 -25
- package/src/review.ts +244 -0
- package/dist/action.d.mts +0 -215
- package/dist/action.mjs +0 -505
- package/dist/action.mjs.map +0 -1
- package/dist/cli.d.mts +0 -1
- package/dist/cli.mjs +0 -106
- package/dist/cli.mjs.map +0 -1
- package/dist/fan-out-C3yG1cx3.d.mts +0 -1526
- package/dist/github-CCuLgyqb.mjs +0 -3437
- package/dist/github-CCuLgyqb.mjs.map +0 -1
- package/dist/logging-Q4j0oub-.mjs +0 -75
- package/dist/logging-Q4j0oub-.mjs.map +0 -1
- package/dist/providers-Br9FRn7j.mjs +0 -1349
- package/dist/providers-Br9FRn7j.mjs.map +0 -1
- package/dist/testing.d.mts +0 -86
- package/dist/testing.mjs +0 -184
- package/dist/testing.mjs.map +0 -1
- package/src/action.ts +0 -906
- package/src/cli.ts +0 -235
- package/src/internal/action-entry.ts +0 -45
- package/src/internal/adjudication.ts +0 -415
- package/src/internal/anchors.ts +0 -20
- package/src/internal/coverage.ts +0 -357
- package/src/internal/diff.ts +0 -193
- package/src/internal/effort.ts +0 -86
- package/src/internal/factory.ts +0 -357
- package/src/internal/fan-out-scripted.ts +0 -77
- package/src/internal/fan-out.ts +0 -1148
- package/src/internal/fingerprint.ts +0 -89
- package/src/internal/fixtures.ts +0 -148
- package/src/internal/github-env.ts +0 -164
- package/src/internal/github.ts +0 -1218
- package/src/internal/ignore.ts +0 -88
- package/src/internal/logging.ts +0 -124
- package/src/internal/profiles.ts +0 -91
- package/src/internal/progress.ts +0 -433
- package/src/internal/providers.ts +0 -133
- package/src/internal/render.ts +0 -819
- package/src/internal/retirement.ts +0 -337
- package/src/internal/review-agent.ts +0 -543
- package/src/internal/review-state.ts +0 -782
- package/src/internal/review-units.ts +0 -493
- package/src/internal/run.ts +0 -611
- package/src/internal/scripted.ts +0 -108
- package/src/internal/source.ts +0 -110
- package/src/testing.ts +0 -8
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-CCuLgyqb.mjs","names":["PositiveLine","EvidenceShardIds"],"sources":["../src/internal/diff.ts","../src/internal/source.ts","../src/internal/review-agent.ts","../src/internal/review-state.ts","../src/internal/retirement.ts","../src/internal/adjudication.ts","../src/internal/anchors.ts","../src/internal/coverage.ts","../src/internal/review-units.ts","../src/internal/fan-out.ts","../src/internal/fingerprint.ts","../src/internal/github.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\n// ---------------------------------------------------------------------------\n// Changed-file and unified-diff primitives shared by the tool surface, the\n// publication planner, and the GitHub adapter. The parser is deterministic\n// and bounded; it never throws on malformed hunks — unparseable patch text\n// simply yields no commentable lines, which fails findings closed.\n// ---------------------------------------------------------------------------\n\n/** A repository-relative file path as transported values carry it. */\nexport const ChangedPath = Schema.NonEmptyString.check(Schema.isMaxLength(512));\n\n/** GitHub's changed-file status vocabulary, kept verbatim. */\nexport const ChangedFileStatus = Schema.Literals([\n \"added\",\n \"removed\",\n \"modified\",\n \"renamed\",\n \"copied\",\n \"changed\",\n \"unchanged\",\n]);\n\n/** One file changed by the pull request, with its optional textual patch. */\nexport class ChangedFile extends Schema.Class<ChangedFile>(\"@effect-agent/pr-review/ChangedFile\")({\n path: ChangedPath,\n status: ChangedFileStatus,\n additions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n deletions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Present for renames/copies: the path the file previously had. */\n previousPath: Schema.optionalKey(ChangedPath),\n /** Unified-diff hunks; absent for binary or oversized files. */\n patch: Schema.optionalKey(Schema.String),\n /**\n * Bounded UTF-8 content used only when the provider omitted `patch`.\n * Modified files require both sides; additions require head content and\n * deletions require base content. These values are review evidence, never\n * GitHub inline-comment anchors.\n */\n reviewBaseContent: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200_000))),\n reviewHeadContent: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200_000))),\n}) {}\n\n/** Complete rendered fallback evidence must fit one ordinary model context. */\nexport const MAX_REVIEW_CONTENT_CHARS = 220_000;\n\n/**\n * Render complete patchless evidence, or refuse it when a required side is\n * absent or B/H annotation would exceed the model-facing bound. Callers use\n * this same value for planning and tool output so truncated fallback evidence\n * can never count as complete coverage.\n */\nexport const renderReviewContent = (file: ChangedFile): string | undefined => {\n if (file.patch !== undefined) return undefined;\n const includeBase = file.status !== \"added\";\n const includeHead = file.status !== \"removed\";\n const sections: Array<string> = [\n \"[GitHub omitted the unified diff. B/H lines below are bounded full-file review content, not valid inline-comment anchors. Report defects from this evidence as non-anchored concerns.]\",\n ];\n let renderedLength = sections[0]?.length ?? 0;\n const append = (part: string): boolean => {\n const nextLength = renderedLength + 1 + part.length;\n if (nextLength > MAX_REVIEW_CONTENT_CHARS) return false;\n sections.push(part);\n renderedLength = nextLength;\n return true;\n };\n const appendSide = (side: \"B\" | \"H\", header: string, content: string): boolean => {\n if (!append(header)) return false;\n const lines = content.split(\"\\n\");\n for (let index = 0; index < lines.length; index += 1) {\n if (!append(`${side}${index + 1} ${lines[index] ?? \"\"}`)) return false;\n }\n return true;\n };\n if (includeBase) {\n if (file.reviewBaseContent === undefined) return undefined;\n if (!appendSide(\"B\", \"[BASE VERSION]\", file.reviewBaseContent)) return undefined;\n }\n if (includeHead) {\n if (file.reviewHeadContent === undefined) return undefined;\n if (!appendSide(\"H\", \"[HEAD VERSION]\", file.reviewHeadContent)) return undefined;\n }\n return sections.join(\"\\n\");\n};\n\n/** Whether complete patchless evidence fits the model-facing review bound. */\nexport const hasReviewableContent = (file: ChangedFile): boolean =>\n renderReviewContent(file) !== undefined;\n\n/** Whether the reviewer has either a real patch or bounded textual fallback evidence. */\nexport const isReviewableFile = (file: ChangedFile): boolean =>\n file.patch !== undefined || hasReviewableContent(file);\n\n/** One parsed line of a unified diff, with both coordinate systems. */\nexport interface PatchLine {\n readonly kind: \"context\" | \"add\" | \"del\";\n readonly oldLine: number | undefined;\n readonly newLine: number | undefined;\n readonly text: string;\n}\n\nconst HUNK_HEADER = /^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/;\n\n/**\n * Parse unified-diff hunk text into coordinate-tagged lines. Lines outside a\n * recognized hunk header are ignored rather than guessed at.\n */\nexport const parsePatch = (patch: string): ReadonlyArray<PatchLine> => {\n const lines: Array<PatchLine> = [];\n let oldLine = 0;\n let newLine = 0;\n let inHunk = false;\n for (const raw of patch.split(\"\\n\")) {\n const header = HUNK_HEADER.exec(raw);\n if (header !== null) {\n oldLine = Number(header[1]);\n newLine = Number(header[2]);\n inHunk = true;\n continue;\n }\n if (!inHunk) continue;\n if (raw.startsWith(\"+\")) {\n lines.push({ kind: \"add\", oldLine: undefined, newLine, text: raw.slice(1) });\n newLine += 1;\n } else if (raw.startsWith(\"-\")) {\n lines.push({ kind: \"del\", oldLine, newLine: undefined, text: raw.slice(1) });\n oldLine += 1;\n } else if (raw.startsWith(\" \") || raw === \"\") {\n lines.push({ kind: \"context\", oldLine, newLine, text: raw.slice(1) });\n oldLine += 1;\n newLine += 1;\n } else if (raw.startsWith(\"\\\\\")) {\n // \"\\" — metadata, not a diff line.\n } else {\n // Unrecognized content ends the current hunk conservatively.\n inHunk = false;\n }\n }\n return lines;\n};\n\n/**\n * The new-file line numbers a GitHub review comment may anchor to on the\n * RIGHT side: every added or context line that appears in the diff.\n */\nexport const commentableLines = (patch: string): ReadonlySet<number> => {\n const lines = new Set<number>();\n for (const line of parsePatch(patch)) {\n if (line.newLine !== undefined) lines.add(line.newLine);\n }\n return lines;\n};\n\n/**\n * Render a patch with explicit RIGHT-side line numbers so the model can\n * anchor findings without arithmetic. `R<n>` marks a line that exists in the\n * new version of the file (`+` added, blank context); deleted lines keep a\n * bare `-` marker and no number.\n */\nexport const annotatePatch = (patch: string): string => {\n const output: Array<string> = [];\n let oldLine = 0;\n let newLine = 0;\n let inHunk = false;\n for (const raw of patch.split(\"\\n\")) {\n const header = HUNK_HEADER.exec(raw);\n if (header !== null) {\n oldLine = Number(header[1]);\n newLine = Number(header[2]);\n inHunk = true;\n output.push(raw);\n continue;\n }\n if (!inHunk) continue;\n if (raw.startsWith(\"+\")) {\n output.push(`R${newLine} + ${raw.slice(1)}`);\n newLine += 1;\n } else if (raw.startsWith(\"-\")) {\n output.push(` - ${raw.slice(1)}`);\n oldLine += 1;\n } else if (raw.startsWith(\" \") || raw === \"\") {\n output.push(`R${newLine} ${raw.slice(1)}`);\n oldLine += 1;\n newLine += 1;\n } else if (raw.startsWith(\"\\\\\")) {\n output.push(` ${raw}`);\n } else {\n inHunk = false;\n }\n }\n return output.join(\"\\n\");\n};\n","import { Context, Effect, Schema } from \"effect\";\n\nimport type { ChangedFile } from \"./diff.ts\";\n\n// ---------------------------------------------------------------------------\n// The pull-request source port: everything the review tools may observe about\n// one pull request. The live adapter speaks the GitHub REST API; the fixture\n// adapter (testing entry) serves an in-memory pull request so ordinary gates\n// and dry runs need no network or credential.\n// ---------------------------------------------------------------------------\n\n/** Reading a file head version larger than this is refused, never truncated silently. */\nexport const MAX_FILE_CHARS = 200_000;\n\n/** The changeset surface is bounded; larger pull requests fail typed. */\nexport const MAX_CHANGED_FILES = 300;\n\n/** Pull-request identity and framing shown to the agent as its mission. */\nexport class PullRequestMetadata extends Schema.Class<PullRequestMetadata>(\n \"@effect-agent/pr-review/PullRequestMetadata\",\n)({\n /** `owner/name`, exactly as GitHub renders it. */\n repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),\n number: Schema.Int.check(Schema.isGreaterThan(0)),\n title: Schema.String.check(Schema.isMaxLength(400)),\n /** Author-provided description; empty when the author left none. */\n body: Schema.String.check(Schema.isMaxLength(20_000)),\n baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n /** Exact base commit used to validate persisted incremental-review lineage. */\n baseSha: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(64))),\n headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n headSha: Schema.NonEmptyString.check(Schema.isMaxLength(64)),\n /** GitHub's own changed-file total; may exceed what `changedFiles` returns. */\n totalChangedFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** The upstream source failed: API error, network fault, or malformed payload. */\nexport class PullRequestSourceFailure extends Schema.TaggedError<PullRequestSourceFailure>()(\n \"PullRequestSourceFailure\",\n {\n operation: Schema.String,\n reason: Schema.String,\n },\n) {\n override get message() {\n return `Pull-request source operation '${this.operation}' failed: ${this.reason}`;\n }\n}\n\n/** A model-supplied path or range was invalid; always fail-closed (SEC-007). */\nexport class ReviewInputViolation extends Schema.TaggedError<ReviewInputViolation>()(\n \"ReviewInputViolation\",\n {\n input: Schema.String,\n reason: Schema.String,\n },\n) {\n override get message() {\n return `Rejected review input '${this.input}': ${this.reason}`;\n }\n}\n\nconst BACKSLASH = String.fromCharCode(92);\n\n/**\n * Normalize and validate one model-supplied repository-relative path.\n * Absolute paths, drive letters, backslashes, empty segments, `.` and `..`\n * segments are all violations — never silently fixed. The changeset list is\n * the real allowlist; this check is defense in depth for URL construction.\n */\nexport const normalizeRepoRelativePath = (\n path: string,\n): Effect.Effect<string, ReviewInputViolation> => {\n const fail = (reason: string) => Effect.fail(ReviewInputViolation.make({ input: path, reason }));\n if (path.length === 0 || path.length > 512) {\n return fail(\"Path length is out of bounds.\");\n }\n if (path.includes(BACKSLASH)) {\n return fail(\"Path contains a forbidden backslash.\");\n }\n if (path.startsWith(\"/\") || /^[A-Za-z]:/.test(path)) {\n return fail(\"Path must be repository-relative, not absolute.\");\n }\n const segments = path.split(\"/\");\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\" || segment === \"..\") {\n return fail(\"Path segments must not be empty, '.', or '..'.\");\n }\n }\n return Effect.succeed(segments.join(\"/\"));\n};\n\n/** Read-only view of one pull request; the only repository access tools get. */\nexport class PullRequestSource extends Context.Service<\n PullRequestSource,\n {\n readonly metadata: Effect.Effect<PullRequestMetadata, PullRequestSourceFailure>;\n /** Files exposed to the model for this run (full PR or selected delta). */\n readonly changedFiles: Effect.Effect<ReadonlyArray<ChangedFile>, PullRequestSourceFailure>;\n /** Full current PR diff used only for host-side anchor/state validation. */\n readonly anchorFiles: Effect.Effect<ReadonlyArray<ChangedFile>, PullRequestSourceFailure>;\n /**\n * The head-version content of one CHANGED file. Paths outside the\n * changeset are violations: the reviewer reads the change, not the tree.\n */\n readonly readFile: (\n path: string,\n ) => Effect.Effect<string, PullRequestSourceFailure | ReviewInputViolation>;\n }\n>()(\"@effect-agent/pr-review/PullRequestSource\") {}\n","import { Effect, Schema } from \"effect\";\nimport { Agent, AgentPolicy, ToolExecutionClass, ToolResultBounds } from \"effect-agent\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n annotatePatch,\n ChangedFileStatus,\n ChangedPath,\n hasReviewableContent,\n renderReviewContent,\n} from \"./diff.ts\";\nimport type { ChangedFile } from \"./diff.ts\";\nimport {\n normalizeRepoRelativePath,\n PullRequestSource,\n PullRequestSourceFailure,\n ReviewInputViolation,\n} from \"./source.ts\";\n\n// ---------------------------------------------------------------------------\n// The pull-request reviewer: a bounded, read-only agent. Every tool observes\n// the pull request through the PullRequestSource port; nothing the model can\n// call mutates anything. Publishing the review happens OUTSIDE the agent\n// loop, after the finding anchors have been validated against the real diff\n// (model output is untrusted input, AGENTS.md rule 11).\n// ---------------------------------------------------------------------------\n\n/** The hard findings bound carried by the CodeReview schema. */\nexport const MAX_FINDINGS = 20;\n\n/** The hard non-anchored-concerns bound carried by the CodeReview schema. */\nexport const MAX_CONCERNS = 10;\n\n/** Maximum characters in one deterministic model-visible evidence chunk. */\nexport const MAX_PATCH_CHARS = 60_000;\n\n/** The encoded Tool result must retain one complete bounded content fallback. */\nexport const REVIEW_TOOL_RESULT_MAX_BYTES = 2 * 1024 * 1024;\n\n/** One `read_file` slice never exceeds this many lines. */\nconst MAX_SLICE_LINES = 1_000;\nconst DEFAULT_SLICE_LINES = 400;\n\n// ---------------------------------------------------------------------------\n// Tool surface.\n// ---------------------------------------------------------------------------\n\nexport class ChangedFileSummary extends Schema.Class<ChangedFileSummary>(\n \"@effect-agent/pr-review/ChangedFileSummary\",\n)({\n path: ChangedPath,\n status: ChangedFileStatus,\n additions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n deletions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n hasTextualDiff: Schema.Boolean,\n /** True when a missing patch was recovered as bounded UTF-8 base/head content. */\n hasReviewableContent: Schema.Boolean,\n}) {}\n\nexport class ChangedFilesView extends Schema.Class<ChangedFilesView>(\n \"@effect-agent/pr-review/ChangedFilesView\",\n)({\n totalFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** True when the pull request has more changed files than are listed here. */\n truncated: Schema.Boolean,\n files: Schema.Array(ChangedFileSummary).check(Schema.isMaxLength(300)),\n}) {}\n\nexport class ListChangedFilesQuery extends Schema.Class<ListChangedFilesQuery>(\n \"@effect-agent/pr-review/ListChangedFilesQuery\",\n)({\n /** Explicit constant keeps the zero-choice operation compatible with strict provider schemas. */\n scope: Schema.Literal(\"all\"),\n}) {}\n\nexport const ListChangedFiles = Tool.make(\"list_changed_files\", {\n description:\n \"List every file changed by this pull request with its status, line counts, and whether a textual diff is available.\",\n parameters: ListChangedFilesQuery,\n success: ChangedFilesView,\n failure: PullRequestSourceFailure,\n failureMode: \"error\",\n dependencies: [PullRequestSource],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport class FileDiffQuery extends Schema.Class<FileDiffQuery>(\n \"@effect-agent/pr-review/FileDiffQuery\",\n)({\n path: ChangedPath,\n}) {}\n\nexport class FileDiffView extends Schema.Class<FileDiffView>(\n \"@effect-agent/pr-review/FileDiffView\",\n)({\n path: ChangedPath,\n status: ChangedFileStatus,\n reviewMode: Schema.Literals([\"diff\", \"content\", \"unavailable\"]),\n /**\n * The unified diff with explicit RIGHT-side line numbers: `R<n>` marks a\n * line present in the new file version (only those may anchor findings);\n * `-` marks removed lines. For content fallback, `B<n>` and `H<n>`\n * identify base/head lines for reading only; they are never valid anchors.\n * Empty only when neither a patch nor bounded textual content exists.\n */\n annotatedPatch: Schema.String,\n truncated: Schema.Boolean,\n}) {}\n\nexport interface FileReviewEvidenceChunk {\n readonly reviewMode: \"diff\" | \"content\" | \"unavailable\";\n readonly annotatedPatch: string;\n}\n\n/**\n * Split complete model-visible evidence at deterministic line boundaries.\n * A pathological single line is hard-sliced so every character is still\n * assigned and every chunk remains within the provider-independent bound.\n */\nconst boundedEvidenceChunks = (evidence: string): ReadonlyArray<string> => {\n if (evidence.length <= MAX_PATCH_CHARS) return [evidence];\n const chunks: Array<string> = [];\n let offset = 0;\n while (offset < evidence.length) {\n let end = Math.min(offset + MAX_PATCH_CHARS, evidence.length);\n if (end < evidence.length) {\n const boundary = evidence.lastIndexOf(\"\\n\", end - 1);\n if (boundary >= offset) end = boundary + 1;\n }\n // No newline exists inside the bound: preserve complete input with a\n // deterministic hard slice instead of silently truncating the line.\n if (end === offset) end = Math.min(offset + MAX_PATCH_CHARS, evidence.length);\n chunks.push(evidence.slice(offset, end));\n offset = end;\n }\n return chunks;\n};\n\n/** Complete bounded evidence chunks used by deterministic fan-out planning. */\nexport const fileReviewEvidenceChunks = (\n file: ChangedFile,\n): ReadonlyArray<FileReviewEvidenceChunk> => {\n const contentEvidence = renderReviewContent(file);\n const reviewMode =\n file.patch !== undefined\n ? (\"diff\" as const)\n : contentEvidence !== undefined\n ? (\"content\" as const)\n : (\"unavailable\" as const);\n const annotated = file.patch === undefined ? (contentEvidence ?? \"\") : annotatePatch(file.patch);\n return boundedEvidenceChunks(annotated).map((annotatedPatch) => ({\n reviewMode,\n annotatedPatch,\n }));\n};\n\n/** Host-owned rendering of one changed file's bounded review evidence. */\nexport const fileDiffView = (file: ChangedFile): FileDiffView => {\n const chunks = fileReviewEvidenceChunks(file);\n const first = chunks[0] ?? { reviewMode: \"unavailable\" as const, annotatedPatch: \"\" };\n const truncated = first.reviewMode === \"diff\" && chunks.length > 1;\n return FileDiffView.make({\n path: file.path,\n status: file.status,\n reviewMode: first.reviewMode,\n annotatedPatch: truncated ? `${first.annotatedPatch}\\n[diff truncated]` : first.annotatedPatch,\n truncated,\n });\n};\n\n// Read failures stay model-visible results (\"return\"), never run-killers:\n// a model asking for an out-of-changeset path is expected untrusted-input\n// behavior, and the fail-closed answer is a typed refusal it can correct —\n// aborting the whole review on one bad path guess would be fragility, not\n// security (the run stays bounded by AgentPolicy regardless).\nexport const ReadFileDiff = Tool.make(\"read_file_diff\", {\n description:\n \"Read one changed file's review evidence. A normal unified diff marks valid anchors as R<number>. When GitHub omitted the diff, bounded base/head content is returned with B/H line labels for review but no valid inline anchors.\",\n parameters: FileDiffQuery,\n success: FileDiffView,\n failure: Schema.Union([PullRequestSourceFailure, ReviewInputViolation]),\n failureMode: \"return\",\n dependencies: [PullRequestSource],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport class FileSliceQuery extends Schema.Class<FileSliceQuery>(\n \"@effect-agent/pr-review/FileSliceQuery\",\n)({\n path: ChangedPath,\n /** 1-based first line to read; defaults to 1. */\n startLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n /** Number of lines to read; defaults to 400, capped at 1000. */\n maxLines: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThanOrEqualTo(MAX_SLICE_LINES)),\n ),\n}) {}\n\nexport class FileSlice extends Schema.Class<FileSlice>(\"@effect-agent/pr-review/FileSlice\")({\n path: ChangedPath,\n startLine: Schema.Int.check(Schema.isGreaterThan(0)),\n endLine: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n totalLines: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Slice content with each line prefixed by its 1-based line number. */\n content: Schema.String,\n}) {}\n\nexport const ReadFile = Tool.make(\"read_file\", {\n description:\n \"Read a numbered slice of the NEW (head) version of one changed file, for context around the diff. Only files in the changeset are readable.\",\n parameters: FileSliceQuery,\n success: FileSlice,\n failure: Schema.Union([PullRequestSourceFailure, ReviewInputViolation]),\n failureMode: \"return\",\n dependencies: [PullRequestSource],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const ReviewToolkit = Toolkit.make(ListChangedFiles, ReadFileDiff, ReadFile);\n\n/**\n * The `list_changed_files` handler, shared by the flat reviewer's toolkit and\n * any extended toolkit built by the configuration factory.\n */\nexport const listChangedFilesHandler = (_query: ListChangedFilesQuery) =>\n Effect.gen(function* () {\n const source = yield* PullRequestSource;\n const files = yield* source.changedFiles;\n const metadata = yield* source.metadata;\n return ChangedFilesView.make({\n totalFiles: metadata.totalChangedFiles,\n truncated: files.length < metadata.totalChangedFiles,\n files: files.map((file) =>\n ChangedFileSummary.make({\n path: file.path,\n status: file.status,\n additions: file.additions,\n deletions: file.deletions,\n hasTextualDiff: file.patch !== undefined,\n hasReviewableContent: hasReviewableContent(file),\n }),\n ),\n });\n });\n\n/**\n * The `read_file_diff` handler, shared verbatim by the flat reviewer's\n * toolkit and the fan-out child's toolkit (fan-out.ts).\n */\nexport const readFileDiffHandler = (query: FileDiffQuery) =>\n Effect.gen(function* () {\n const source = yield* PullRequestSource;\n const relative = yield* normalizeRepoRelativePath(query.path);\n const files = yield* source.changedFiles;\n const file = files.find((candidate) => candidate.path === relative);\n if (file === undefined) {\n return yield* ReviewInputViolation.make({\n input: relative,\n reason: \"Path is not part of this pull request's changeset.\",\n });\n }\n return fileDiffView(file);\n });\n\n/**\n * The `read_file` handler, shared verbatim by the flat reviewer's toolkit\n * and the fan-out child's toolkit (fan-out.ts).\n */\nexport const readFileHandler = (query: FileSliceQuery) =>\n Effect.gen(function* () {\n const source = yield* PullRequestSource;\n const relative = yield* normalizeRepoRelativePath(query.path);\n const content = yield* source.readFile(relative);\n const lines = content.split(\"\\n\");\n const startLine = query.startLine ?? 1;\n const maxLines = query.maxLines ?? DEFAULT_SLICE_LINES;\n if (startLine > lines.length) {\n return yield* ReviewInputViolation.make({\n input: `${relative}:${startLine}`,\n reason: `startLine is beyond the end of the file (${lines.length} lines).`,\n });\n }\n const slice = lines.slice(startLine - 1, startLine - 1 + maxLines);\n const endLine = startLine + slice.length - 1;\n return FileSlice.make({\n path: relative,\n startLine,\n endLine,\n totalLines: lines.length,\n content: slice\n .map((text, index) => `${String(startLine + index).padStart(5)} ${text}`)\n .join(\"\\n\"),\n });\n });\n\nexport const ReviewToolkitLayer = ReviewToolkit.toLayer({\n list_changed_files: listChangedFilesHandler,\n read_file_diff: readFileDiffHandler,\n read_file: readFileHandler,\n});\n\n// ---------------------------------------------------------------------------\n// Mission input and review output contracts.\n// ---------------------------------------------------------------------------\n\n/** Bounded prior-review context lines injected into reviewer instructions. */\nconst ReviewContextLines = Schema.Array(Schema.String.check(Schema.isMaxLength(1_200))).check(\n Schema.isMaxLength(20),\n);\n\nexport class ReviewMission extends Schema.Class<ReviewMission>(\n \"@effect-agent/pr-review/ReviewMission\",\n)({\n repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),\n number: Schema.Int.check(Schema.isGreaterThan(0)),\n title: Schema.String.check(Schema.isMaxLength(400)),\n body: Schema.String.check(Schema.isMaxLength(20_000)),\n baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n changedFileCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /**\n * Maintainer-adjudicated identities rendered as bounded context lines; the\n * reviewer must not re-raise them without materially new evidence. Absent\n * from fingerprint missions so an adjudication never invalidates the\n * skip-unchanged authority.\n */\n adjudicatedContext: Schema.optionalKey(ReviewContextLines),\n /**\n * Prior-round findings on re-reviewed scope, rendered as bounded context\n * lines; each must be confirmed, declared fixed, or explicitly withdrawn.\n */\n priorFindingContext: Schema.optionalKey(ReviewContextLines),\n}) {}\n\nexport const FindingSeverity = Schema.Literals([\"blocking\", \"important\", \"nit\"]);\nexport type FindingSeverity = typeof FindingSeverity.Type;\n\n/**\n * What kind of problem a finding names. Model-claimed like severity — it is a\n * label for scanning a busy review, never an input to the check conclusion.\n */\nexport const FindingCategory = Schema.Literals([\n \"correctness\",\n \"security\",\n \"concurrency\",\n \"performance\",\n \"resources\",\n \"error-handling\",\n \"testing\",\n \"maintainability\",\n \"style\",\n \"docs\",\n]);\nexport type FindingCategory = typeof FindingCategory.Type;\n\nexport class ReviewFinding extends Schema.Class<ReviewFinding>(\n \"@effect-agent/pr-review/ReviewFinding\",\n)({\n path: ChangedPath,\n /** 1-based line numbers in the NEW file version; must appear in the diff. */\n startLine: Schema.Int.check(Schema.isGreaterThan(0)),\n endLine: Schema.Int.check(Schema.isGreaterThan(0)),\n severity: FindingSeverity,\n /** Optional problem-kind label rendered next to the severity. */\n category: Schema.optionalKey(FindingCategory),\n title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),\n body: Schema.NonEmptyString.check(Schema.isMaxLength(2_000)),\n /** Replacement for exactly lines startLine..endLine; omit when unsure. */\n suggestion: Schema.optionalKey(\n Schema.String.annotate({\n description:\n \"Committable replacement source code for exactly lines startLine..endLine: the full replacement for every line in the range and nothing else — never prose describing the change, which belongs in body.\",\n }).check(Schema.isMaxLength(2_000)),\n ),\n}) {}\n\nexport const ReviewVerdict = Schema.Literals([\"approve\", \"comment\", \"request-changes\"]);\nexport type ReviewVerdict = typeof ReviewVerdict.Type;\n\n/**\n * A concern with no diff line to anchor to: a missing deletion or cleanup,\n * rollout or migration sequencing, a coverage gap the diff implies but does\n * not add, or a scope question only the author can answer. Rendered as a\n * review-body section instead of an inline comment. `evidencePaths` binds the\n * concern to changed files so a later incremental review can invalidate and\n * recheck it when any supporting path changes. It remains optional only for\n * decoding review output and continuity state written before path binding was\n * introduced; a pathless concern cannot authorize incremental continuity.\n */\nexport class ReviewConcern extends Schema.Class<ReviewConcern>(\n \"@effect-agent/pr-review/ReviewConcern\",\n)({\n evidencePaths: Schema.optionalKey(\n Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3)),\n ),\n severity: FindingSeverity,\n title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),\n body: Schema.NonEmptyString.check(Schema.isMaxLength(2_000)),\n}) {}\n\n/** The per-entry walkthrough summary bound, and the entries bound (the changeset cap). */\nexport const MAX_WALKTHROUGH_SUMMARY_CHARS = 240;\nexport const MAX_WALKTHROUGH_ENTRIES = 300;\n\n/**\n * One reviewed file's one-sentence change summary. Rendered only when the\n * path is actually part of the changeset — like finding anchors, walkthrough\n * paths are validated host-side and invented ones are dropped.\n */\nexport class WalkthroughEntry extends Schema.Class<WalkthroughEntry>(\n \"@effect-agent/pr-review/WalkthroughEntry\",\n)({\n path: ChangedPath,\n summary: Schema.NonEmptyString.check(Schema.isMaxLength(MAX_WALKTHROUGH_SUMMARY_CHARS)),\n}) {}\n\nexport class CodeReview extends Schema.Class<CodeReview>(\"@effect-agent/pr-review/CodeReview\")({\n summary: Schema.NonEmptyString.check(Schema.isMaxLength(4_000)),\n verdict: ReviewVerdict,\n findings: Schema.Array(ReviewFinding).check(Schema.isMaxLength(MAX_FINDINGS)),\n /** Non-anchorable concerns; absent when the review raises none. */\n concerns: Schema.optionalKey(Schema.Array(ReviewConcern).check(Schema.isMaxLength(MAX_CONCERNS))),\n /** Per-file change summaries; absent when the model provides none. */\n walkthrough: Schema.optionalKey(\n Schema.Array(WalkthroughEntry).check(Schema.isMaxLength(MAX_WALKTHROUGH_ENTRIES)),\n ),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Instructions. Live models diverge wherever the contract is implicit, so the\n// exact JSON shape, the anchor rule, and the suggestion rule are all spelled\n// out with types. Consumer guidance is injected BETWEEN the mission framing\n// and the procedure — it can widen what the reviewer pays attention to, but\n// the machine contract (anchor rule, JSON shape, bounds) is always appended\n// by this builder and cannot be edited out.\n// ---------------------------------------------------------------------------\n\n/** Consumer-supplied domain guidance: static lines or a function of the mission. */\nexport type ReviewGuidance =\n | string\n | ReadonlyArray<string>\n | ((mission: ReviewMission) => string | ReadonlyArray<string>);\n\nexport const resolveGuidance = (\n guidance: ReviewGuidance | undefined,\n mission: ReviewMission,\n): ReadonlyArray<string> => {\n if (guidance === undefined) return [];\n const value = typeof guidance === \"function\" ? guidance(mission) : guidance;\n const lines = typeof value === \"string\" ? [value] : value;\n return lines.filter((line) => line.length > 0);\n};\n\nexport interface ReviewInstructionOptions {\n readonly guidance?: ReviewGuidance | undefined;\n /** Advertised findings bound; clamped to the CodeReview schema cap. */\n readonly maxFindings?: number | undefined;\n}\n\n/** Clamp a configured findings bound into the schema-supported range. */\nexport const clampMaxFindings = (maxFindings: number | undefined): number =>\n maxFindings === undefined\n ? MAX_FINDINGS\n : Math.min(MAX_FINDINGS, Math.max(1, Math.trunc(maxFindings)));\n\n/** Build the flat reviewer's instructions with optional consumer guidance. */\nexport const makeReviewInstructions =\n (options: ReviewInstructionOptions = {}) =>\n (mission: ReviewMission): string => {\n const maxFindings = clampMaxFindings(options.maxFindings);\n return [\n `You are a senior code reviewer for pull request #${mission.number} (\"${mission.title}\") in ${mission.repository}, merging ${mission.headRef} into ${mission.baseRef}. It changes ${mission.changedFileCount} file(s).`,\n mission.body.length > 0\n ? `Author description:\\n${mission.body}`\n : \"The author provided no description.\",\n ...resolveGuidance(options.guidance, mission),\n ...(mission.adjudicatedContext === undefined || mission.adjudicatedContext.length === 0\n ? []\n : [\n \"A maintainer has adjudicated these previously raised review items (disposition, reason). Do not re-raise them unless you have materially new evidence, and if you do, say explicitly what changed since the adjudication:\",\n ...mission.adjudicatedContext.map((line) => `- ${line}`),\n ]),\n ...(mission.priorFindingContext === undefined || mission.priorFindingContext.length === 0\n ? []\n : [\n \"Your previous review raised these findings on the scope you are re-reviewing. For each, either confirm it still holds, state that it is fixed, or withdraw it; do not demand the opposite of your own prior guidance without explicitly acknowledging the reversal:\",\n ...mission.priorFindingContext.map((line) => `- ${line}`),\n ]),\n \"Work in this order:\",\n \"1. Call list_changed_files once to see the selected input scope. In incremental reviews it is deliberately a subset of the pull request's full diff (totalFiles counts the whole pull request); omitted paths belong to settled prior scope or explicit host exclusions, not to this run.\",\n \"2. Call read_file_diff for every listed file. A normal diff marks new-version anchors as R<number>; only those numbers are valid startLine/endLine values. When GitHub omitted a diff, the tool may return bounded base/head content marked B/H instead. Review that content, but report its defects as non-anchored concerns because B/H lines cannot anchor GitHub comments. Never anchor a finding to a removed (-), B, or H line.\",\n \"3. Call read_file when you need surrounding context the diff does not show. ONLY listed files are readable — read_file_diff and read_file both return a failed result for any other path (an import, a neighbor, a file named in the description). Do not request or retry unlisted paths; reason from the visible diffs instead and note the gap honestly in your summary when it matters.\",\n \"4. Review for real defects first: correctness, security, concurrency, resource leaks, error handling, API misuse. Style nits are least important. Do not praise; do not restate the diff.\",\n \"When the diff adds or changes a test, check that it can actually fail: a test that would still pass with the bug present is theatre, not coverage. The usual tell is a loose assertion standing where an exact one belongs — >= or a truthiness check over an expected value, or a snapshot that absorbs whatever it is handed.\",\n \"Go shallow only when the diff has no behavioral surface at all: doc typos, formatting, lockfile or generated-code regeneration, a mechanical rename. Line count is not the signal — a one-line change to auth, money, SQL, a comparison operator, or a config default is not trivial.\",\n \"Drop bloat-shaped findings before reporting: defensive checks for cases that cannot happen, abstractions used once, comments restating obvious code, tests asserting tautologies, just-in-case guards. A finding must be sound, correct, and worth acting on; prefer an explicit keep over an invented finding.\",\n '5. After collecting anchored findings, deliberately scan for concerns with NO line to point at: deletion or cleanup plans for code the diff replaces, rollout or migration sequencing, coverage gaps the diff implies but does not add, scope questions only the author can answer. Report each as a \"concern\", never as a finding with an invented anchor. Every concern must list 1-3 exact changed evidencePaths that support it so later incremental reviews can recheck it when those files change. Report none when none exist, and never split one root concern into differently worded restatements.',\n `6. Write a walkthrough: for every file whose evidence you examined, one factual sentence (<= ${MAX_WALKTHROUGH_SUMMARY_CHARS} chars) describing what changed in that file — written for a reader scanning the pull request, never restating the diff line by line. Use only paths from list_changed_files; invented paths are dropped.`,\n '7. Then return ONLY a JSON object — no Markdown fences, no prose before or after — exactly this shape: {\"summary\": <string, 1-3 paragraphs of overall assessment>, \"verdict\": <\"approve\" | \"comment\" | \"request-changes\">, \"findings\": [{\"path\": <string, a changed file path>, \"startLine\": <integer, an R-marked new-file line>, \"endLine\": <integer, >= startLine, same file, R-marked>, \"severity\": <\"blocking\" | \"important\" | \"nit\">, \"category\": <OPTIONAL: \"correctness\" | \"security\" | \"concurrency\" | \"performance\" | \"resources\" | \"error-handling\" | \"testing\" | \"maintainability\" | \"style\" | \"docs\">, \"title\": <string, <= 120 chars>, \"body\": <string, why it matters and what to do>, \"suggestion\": <string, OPTIONAL: replacement text for exactly lines startLine..endLine, ready to commit>}], \"concerns\": <array, OPTIONAL: [{\"evidencePaths\": <array of 1-3 exact changed file paths>, \"severity\": <\"blocking\" | \"important\" | \"nit\">, \"title\": <string, <= 120 chars>, \"body\": <string>}], only for step-5 concerns with no valid anchor — never duplicate a finding here>, \"walkthrough\": <array, OPTIONAL: [{\"path\": <string, a changed file path>, \"summary\": <string, the step-6 sentence>}], one entry per reviewed file>}.',\n `Report at most ${maxFindings} findings and at most ${MAX_CONCERNS} concerns; prefer the most important ones. An empty findings array with verdict \"approve\" is a valid review. Include \"suggestion\" only when you are confident the replacement compiles and preserves intent; its text must contain the full replacement for every line in the range and nothing else.`,\n 'Use verdict \"request-changes\" only when at least one finding or concern is \"blocking\". Line anchors you invent will be discarded, so copy R-numbers from read_file_diff output.',\n ].join(\"\\n\");\n };\n\n/** The default flat-reviewer instructions: no guidance, schema-cap findings. */\nexport const reviewInstructions = makeReviewInstructions();\n\n/** The default flat-reviewer execution bounds. */\nexport const defaultReviewPolicy = AgentPolicy.make({\n maxTurns: 12,\n maxToolCalls: 24,\n maxDuration: \"8 minutes\",\n toolConcurrency: 2,\n // The read tools return refusals as model-visible results (failureMode\n // \"return\"), and a model may probe several out-of-scope paths in ONE\n // parallel batch — e.g. files the PR description names outside an\n // incremental delta — before it has seen a single refusal. The engine's\n // default limit of 3 made that exploration fatal; half the tool-call\n // budget keeps the genuinely-stuck brake while maxToolCalls and\n // maxDuration bound the run regardless.\n repeatedFailureLimit: 12,\n tokenBudget: 300_000,\n // Keep enough output/summary headroom for the 200k-class provider window;\n // tool-heavy histories prune before the engine spends a summarization call.\n contextTokenLimit: 150_000,\n toolResultBounds: ToolResultBounds.make({ maxBytes: REVIEW_TOOL_RESULT_MAX_BYTES }),\n // Budget soft landing (RUN-018): an exhausted reviewer returns its partial\n // review on one final tool-free turn instead of failing the whole run.\n onExhaustion: \"final-answer\",\n});\n\n// ---------------------------------------------------------------------------\n// Agent Definition: model-agnostic (D-027); bindings are created by callers\n// or by the configuration factory.\n// ---------------------------------------------------------------------------\n\nexport const PullRequestReviewer = Agent.define(\"pr-reviewer\", {\n input: ReviewMission,\n output: CodeReview,\n instructions: reviewInstructions,\n toolkit: ReviewToolkit,\n policy: defaultReviewPolicy,\n description:\n \"Review one pull request read-only: list the changeset, read annotated diffs and head-file context, and return a structured, line-anchored code review.\",\n metadata: { deploymentClass: \"E\", surface: \"read-only\" },\n});\n","import { Context, Effect, Encoding, Layer, Option, Redacted, Result, Schema } from \"effect\";\n\nimport { ChangedFile, ChangedPath } from \"./diff.ts\";\nimport { FindingSeverity, ReviewConcern, ReviewFinding, ReviewMission } from \"./review-agent.ts\";\nimport { PullRequestSource, ReviewInputViolation, type PullRequestMetadata } from \"./source.ts\";\n\n// ---------------------------------------------------------------------------\n// Bounded review continuity. The Action is still deployment class E, but every\n// completed review can publish authenticated state inside its GitHub review body.\n// A later Action run validates the state against the live PR/base lineage and\n// uses a head-to-head comparison to select only newly affected scope.\n// ---------------------------------------------------------------------------\n\nexport const ReviewMode = Schema.Literals([\"incremental\", \"final\"]);\nexport type ReviewMode = typeof ReviewMode.Type;\n\nexport const ReviewScopeMode = Schema.Literals([\"incremental\", \"full\"]);\nexport type ReviewScopeMode = typeof ReviewScopeMode.Type;\n\nexport const GitCommitSha = Schema.NonEmptyString.check(\n Schema.isMaxLength(64),\n Schema.isPattern(/^[0-9a-f]{40,64}$/),\n);\n\nconst Fingerprint = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/));\nconst StoredText = Schema.NonEmptyString.check(Schema.isMaxLength(800));\n\n/** A compact unresolved finding suitable for the bounded review-body marker. */\nexport class StoredReviewFinding extends Schema.Class<StoredReviewFinding>(\n \"@effect-agent/pr-review/StoredReviewFinding\",\n)({\n path: ChangedPath,\n startLine: Schema.Int.check(Schema.isGreaterThan(0)),\n endLine: Schema.Int.check(Schema.isGreaterThan(0)),\n severity: FindingSeverity,\n title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),\n body: StoredText,\n}) {}\n\n/** A compact unresolved non-anchored concern with its invalidation paths. */\nexport class StoredReviewConcern extends Schema.Class<StoredReviewConcern>(\n \"@effect-agent/pr-review/StoredReviewConcern\",\n)({\n /** Absent only on legacy state written before concern path binding. */\n evidencePaths: Schema.optionalKey(\n Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3)),\n ),\n severity: FindingSeverity,\n title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),\n body: StoredText,\n}) {}\n\n/** How a maintainer settled a previously raised finding or concern. */\nexport const AdjudicationDisposition = Schema.Literals([\"accepted-risk\", \"refuted\", \"obsolete\"]);\nexport type AdjudicationDisposition = typeof AdjudicationDisposition.Type;\n\n/** The adjudications bound carried by the ReviewState schema. */\nexport const MAX_STORED_ADJUDICATIONS = 20;\n\n/**\n * One maintainer adjudication of a finding or concern identity. Anchored\n * findings carry their full location identity; unanchored concerns are\n * identified by title alone, so the location fields stay absent.\n */\nconst StoredAdjudicationFields = Schema.Struct({\n path: Schema.optionalKey(ChangedPath),\n startLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n endLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),\n disposition: AdjudicationDisposition,\n reason: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(300))),\n /** GitHub login of the maintainer whose comment adjudicated the identity. */\n actor: Schema.NonEmptyString.check(Schema.isMaxLength(100)),\n}).check(\n Schema.makeFilter(\n (adjudication) => {\n const locationParts = [\n adjudication.path,\n adjudication.startLine,\n adjudication.endLine,\n ].filter((part) => part !== undefined).length;\n return locationParts === 0 || locationParts === 3\n ? undefined\n : \"path, startLine, and endLine must be either all present or all absent\";\n },\n { title: \"adjudication locations are complete or unanchored\" },\n ),\n);\n\nexport class StoredAdjudication extends Schema.Class<StoredAdjudication>(\n \"@effect-agent/pr-review/StoredAdjudication\",\n)(StoredAdjudicationFields) {}\n\n/**\n * The one finding-identity composition shared by retirement, adjudication,\n * and settlement. A tagged JSON tuple keeps anchored findings in a namespace\n * disjoint from title-only concerns and remains unambiguous even when\n * untrusted path or title text contains delimiter characters.\n */\nexport const findingIdentity = (finding: {\n readonly path: string;\n readonly startLine: number;\n readonly endLine: number;\n readonly title: string;\n}): string =>\n JSON.stringify([\"finding\", finding.path, finding.startLine, finding.endLine, finding.title]);\n\n/** The disjoint title-only identity namespace for unanchored concerns. */\nexport const concernIdentity = (concern: { readonly title: string }): string =>\n JSON.stringify([\"concern\", concern.title]);\n\n/**\n * An adjudication's identity: the shared finding identity when anchored, the\n * disjoint concern identity when unanchored.\n */\nexport const adjudicationIdentity = (adjudication: StoredAdjudication): string =>\n adjudication.path !== undefined &&\n adjudication.startLine !== undefined &&\n adjudication.endLine !== undefined\n ? findingIdentity({\n path: adjudication.path,\n startLine: adjudication.startLine,\n endLine: adjudication.endLine,\n title: adjudication.title,\n })\n : concernIdentity(adjudication);\n\n/** The carried-scope bound; a run that cannot fit its leftovers publishes no state. */\nexport const MAX_STORED_UNREVIEWED_PATHS = 100;\n\n/** Failed-pass records stored beside the leftover paths; one per unit stage. */\nexport const MAX_STORED_UNREVIEWED_PASSES = 24;\n\n/** Stages a leftover path may need retried on the next incremental run. */\nexport const UnreviewedStage = Schema.Literals([\"discovery\", \"specialist\", \"verification\"]);\nexport type UnreviewedStage = typeof UnreviewedStage.Type;\n\n/** One failed fan-out pass whose stage remains attached to its exact paths. */\nexport class StoredUnreviewedPass extends Schema.Class<StoredUnreviewedPass>(\n \"@effect-agent/pr-review/StoredUnreviewedPass\",\n)({\n stage: UnreviewedStage,\n paths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12)),\n}) {}\n\n/**\n * Versioned state embedded after EVERY completed run that can be signed. The\n * head plus full-scope fingerprint forms an incremental baseline; an absent\n * unresolved item never means the path is defect-free. `unreviewedPaths`\n * carries retryable review gaps (failed passes) forward so the next\n * incremental run re-reviews exactly them plus the new delta — the baseline\n * advances monotonically instead of freezing on one flaky pass and reopening\n * the whole post-baseline scope. Storing hundreds of path strings separately\n * would not fit GitHub's bounded review body in the worst case.\n */\nexport class ReviewState extends Schema.Class<ReviewState>(\"@effect-agent/pr-review/ReviewState\")({\n version: Schema.Literal(1),\n repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),\n pullRequestNumber: Schema.Int.check(Schema.isGreaterThan(0)),\n baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n baseSha: GitCommitSha,\n headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),\n reviewedHeadSha: GitCommitSha,\n profileFingerprint: Fingerprint,\n settledScopeFingerprint: Fingerprint,\n reviewedPathCount: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 300 })),\n unresolvedFindings: Schema.Array(StoredReviewFinding).check(Schema.isMaxLength(20)),\n unresolvedConcerns: Schema.Array(StoredReviewConcern).check(Schema.isMaxLength(10)),\n /** Retryable review gaps carried into the next incremental run's scope. */\n unreviewedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(MAX_STORED_UNREVIEWED_PATHS)),\n /** Which failed pass produced those leftovers. */\n unreviewedPasses: Schema.Array(StoredUnreviewedPass).check(\n Schema.isMaxLength(MAX_STORED_UNREVIEWED_PASSES),\n ),\n /**\n * True only when the producing run had complete input coverage, no\n * unsettled pass, and nothing carried. Skip-unchanged authority: an\n * unchanged patch may skip re-review only over a settled state.\n */\n settled: Schema.Boolean,\n lastReviewMode: ReviewScopeMode,\n /**\n * Maintainer adjudications standing against this pull request. optionalKey\n * so state markers signed before the field existed still decode.\n */\n adjudications: Schema.optionalKey(\n Schema.Array(StoredAdjudication).check(Schema.isMaxLength(MAX_STORED_ADJUDICATIONS)),\n ),\n}) {}\n\nexport const toStoredFinding = (finding: ReviewFinding): StoredReviewFinding =>\n StoredReviewFinding.make({\n path: finding.path,\n startLine: finding.startLine,\n endLine: finding.endLine,\n severity: finding.severity,\n title: finding.title,\n body: finding.body.slice(0, 800),\n });\n\nexport const fromStoredFinding = (finding: StoredReviewFinding): ReviewFinding =>\n ReviewFinding.make({\n path: finding.path,\n startLine: finding.startLine,\n endLine: finding.endLine,\n severity: finding.severity,\n title: finding.title,\n body: finding.body,\n });\n\nexport const toStoredConcern = (concern: ReviewConcern): StoredReviewConcern =>\n StoredReviewConcern.make({\n ...(concern.evidencePaths === undefined ? {} : { evidencePaths: concern.evidencePaths }),\n severity: concern.severity,\n title: concern.title,\n body: concern.body.slice(0, 800),\n });\n\nexport const fromStoredConcern = (concern: StoredReviewConcern): ReviewConcern =>\n ReviewConcern.make({\n ...(concern.evidencePaths === undefined ? {} : { evidencePaths: concern.evidencePaths }),\n severity: concern.severity,\n title: concern.title,\n body: concern.body,\n });\n\nconst STATE_MARKER_PREFIX = \"<!-- effect-agent-pr-review state-v1:\";\nconst STATE_MARKER_SUFFIX = \" -->\";\nconst STATE_MARKER_PATTERN =\n /(?:^|\\n)<!-- effect-agent-pr-review state-v1:([A-Za-z0-9+/]+={0,2})\\.([0-9a-f]{64}) -->$/;\nconst STATE_SIGNATURE_DOMAIN = \"effect-agent-pr-review/state-v1\\u0000\";\nexport const MAX_REVIEW_STATE_MARKER_CHARS = 24_000;\nexport const ReviewStateMarker = Schema.NonEmptyString.check(\n Schema.isMaxLength(MAX_REVIEW_STATE_MARKER_CHARS),\n Schema.isPattern(/^<!-- effect-agent-pr-review state-v1:[A-Za-z0-9+/]+={0,2}\\.[0-9a-f]{64} -->$/),\n).pipe(Schema.brand(\"@effect-agent/pr-review/ReviewStateMarker\"));\nexport type ReviewStateMarker = typeof ReviewStateMarker.Type;\n\nexport class ReviewStateAuthenticationFailure extends Schema.TaggedError<ReviewStateAuthenticationFailure>()(\n \"ReviewStateAuthenticationFailure\",\n {\n operation: Schema.Literals([\"sign\", \"verify\"]),\n reason: Schema.NonEmptyString.check(Schema.isMaxLength(2_048)),\n },\n) {}\n\nexport class ReviewStateMarkerTooLarge extends Schema.TaggedError<ReviewStateMarkerTooLarge>()(\n \"ReviewStateMarkerTooLarge\",\n {\n observedChars: Schema.Int.check(Schema.isGreaterThan(0)),\n maximumChars: Schema.Int.check(Schema.isGreaterThan(0)),\n },\n) {}\n\nexport class ReviewStateAuthenticator extends Context.Service<\n ReviewStateAuthenticator,\n {\n readonly status: \"available\" | \"unavailable\";\n readonly unavailableReason: string | undefined;\n readonly render: (\n state: ReviewState,\n ) => Effect.Effect<\n ReviewStateMarker,\n ReviewStateAuthenticationFailure | ReviewStateMarkerTooLarge\n >;\n readonly extract: (\n body: string,\n ) => Effect.Effect<Option.Option<ReviewState>, ReviewStateAuthenticationFailure>;\n }\n>()(\"@effect-agent/pr-review/ReviewStateAuthenticator\") {}\n\nconst authenticationFailure = (\n operation: \"sign\" | \"verify\",\n cause: unknown,\n): ReviewStateAuthenticationFailure =>\n ReviewStateAuthenticationFailure.make({\n operation,\n reason: String(cause).slice(0, 2_048),\n });\n\nconst hmacKey = (secret: Redacted.Redacted<string>, operation: \"sign\" | \"verify\") =>\n Effect.tryPromise({\n try: () =>\n globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(Redacted.value(secret)),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"],\n ),\n catch: (cause) => authenticationFailure(operation, cause),\n });\n\nconst signatureBytes = (signature: string): ArrayBuffer => {\n const pairs = signature.match(/../g) ?? [];\n const buffer = new ArrayBuffer(pairs.length);\n const bytes = new Uint8Array(buffer);\n for (let index = 0; index < pairs.length; index += 1) {\n bytes[index] = Number.parseInt(pairs[index] ?? \"\", 16);\n }\n return buffer;\n};\n\n/** Validated WebCrypto adapter selected at the Action composition root. */\nexport const webCryptoReviewStateAuthenticatorLayer = (\n secret: Redacted.Redacted<string>,\n): Layer.Layer<ReviewStateAuthenticator> =>\n Layer.succeed(ReviewStateAuthenticator)(\n ReviewStateAuthenticator.of({\n status: \"available\",\n unavailableReason: undefined,\n render: (state) =>\n Effect.gen(function* () {\n const json = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(ReviewState))(\n state,\n ).pipe(Effect.mapError((cause) => authenticationFailure(\"sign\", cause)));\n const payload = Encoding.encodeBase64(json);\n const message = new TextEncoder().encode(`${STATE_SIGNATURE_DOMAIN}${payload}`);\n const key = yield* hmacKey(secret, \"sign\");\n const signature = yield* Effect.tryPromise({\n try: () => globalThis.crypto.subtle.sign(\"HMAC\", key, message),\n catch: (cause) => authenticationFailure(\"sign\", cause),\n });\n const hex = Array.from(new Uint8Array(signature))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n const marker = `${STATE_MARKER_PREFIX}${payload}.${hex}${STATE_MARKER_SUFFIX}`;\n if (marker.length > MAX_REVIEW_STATE_MARKER_CHARS) {\n return yield* ReviewStateMarkerTooLarge.make({\n observedChars: marker.length,\n maximumChars: MAX_REVIEW_STATE_MARKER_CHARS,\n });\n }\n return yield* Schema.decodeUnknownEffect(ReviewStateMarker)(marker).pipe(\n Effect.mapError((cause) => authenticationFailure(\"sign\", cause)),\n );\n }),\n extract: (body) => {\n if (body.length > 60_000) return Effect.succeed(Option.none());\n const match = STATE_MARKER_PATTERN.exec(body);\n const payload = match?.[1];\n const signature = match?.[2];\n if (payload === undefined || signature === undefined) return Effect.succeed(Option.none());\n const marker = `${STATE_MARKER_PREFIX}${payload}.${signature}${STATE_MARKER_SUFFIX}`;\n if (!Schema.is(ReviewStateMarker)(marker)) return Effect.succeed(Option.none());\n const json = Result.getOrUndefined(Encoding.decodeBase64String(payload));\n if (json === undefined) return Effect.succeed(Option.none());\n const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(ReviewState))(json);\n if (Option.isNone(decoded)) return Effect.succeed(Option.none());\n const message = new TextEncoder().encode(`${STATE_SIGNATURE_DOMAIN}${payload}`);\n return Effect.gen(function* () {\n const key = yield* hmacKey(secret, \"verify\");\n const valid = yield* Effect.tryPromise({\n try: () =>\n globalThis.crypto.subtle.verify(\"HMAC\", key, signatureBytes(signature), message),\n catch: (cause) => authenticationFailure(\"verify\", cause),\n });\n return valid ? Option.some(decoded.value) : Option.none();\n });\n },\n }),\n );\n\n/** Explicit no-state implementation for hosts without a stable authentication secret. */\nexport const unavailableReviewStateAuthenticatorLayer = (\n reason: string,\n): Layer.Layer<ReviewStateAuthenticator> => {\n const safeReason = reason === \"\" ? \"review-state authentication is unavailable\" : reason;\n return Layer.succeed(ReviewStateAuthenticator)(\n ReviewStateAuthenticator.of({\n status: \"unavailable\",\n unavailableReason: safeReason.slice(0, 1_000),\n render: () =>\n Effect.fail(\n ReviewStateAuthenticationFailure.make({\n operation: \"sign\",\n reason: safeReason.slice(0, 2_048),\n }),\n ),\n extract: () => Effect.succeed(Option.none()),\n }),\n );\n};\n\n/** The bounded result of GitHub's previous-head...current-head comparison. */\nexport class ReviewHeadComparison extends Schema.Class<ReviewHeadComparison>(\n \"@effect-agent/pr-review/ReviewHeadComparison\",\n)({\n status: Schema.Literals([\"ahead\", \"behind\", \"diverged\", \"identical\"]),\n baseSha: GitCommitSha,\n headSha: GitCommitSha,\n mergeBaseSha: GitCommitSha,\n files: Schema.Array(ChangedFile).check(Schema.isMaxLength(300)),\n /** GitHub caps compare-file payloads at 300; equality is conservatively truncated. */\n truncated: Schema.Boolean,\n}) {}\n\n/**\n * Current and previous paths for 300 PR files plus bounded stored continuity\n * paths. The live adapter refuses a larger snapshot-comparison request.\n */\nexport const MAX_TREE_COMPARISON_PATHS = 750;\n\n/** A direct comparison of two complete commit tree snapshots. */\nexport class ReviewTreeComparison extends Schema.Class<ReviewTreeComparison>(\n \"@effect-agent/pr-review/ReviewTreeComparison\",\n)({\n baseSha: GitCommitSha,\n headSha: GitCommitSha,\n changedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(MAX_TREE_COMPARISON_PATHS)),\n /** True when GitHub returned either recursive tree incompletely. */\n truncated: Schema.Boolean,\n}) {}\n\n/** Internal review selection applied as a decorator over the full PR source. */\nexport interface ReviewSelection {\n readonly mode: ReviewScopeMode;\n readonly reason: string;\n readonly files: ReadonlyArray<ChangedFile>;\n /** Paths whose changes invalidate prior findings, including paths reverted out of the PR. */\n readonly affectedPaths: ReadonlyArray<string>;\n /**\n * Failed stages attached to the unchanged paths that own them. Verification\n * retries reopen discovery for only their paths because candidates are not\n * persisted in review state.\n */\n readonly retryPasses?: ReadonlyArray<StoredUnreviewedPass>;\n /** Flattened summaries retained for diagnostics and compatibility. */\n readonly retryPaths: ReadonlyArray<string>;\n readonly retryStages: ReadonlyArray<UnreviewedStage>;\n readonly totalFiles: number;\n readonly baselineSha: string | undefined;\n readonly priorState: ReviewState | undefined;\n /** Absent only for an explicit full review with no continuity profile. */\n readonly profileFingerprint: string | undefined;\n /** Action-owned authentication capability, constructed at the composition root. */\n readonly stateAuthenticator?: ReviewStateAuthenticator[\"Service\"] | undefined;\n}\n\nexport const fullReviewSelection = (input: {\n readonly reason: string;\n readonly files: ReadonlyArray<ChangedFile>;\n readonly totalFiles: number;\n readonly profileFingerprint?: string | undefined;\n}): ReviewSelection => ({\n mode: \"full\",\n reason: input.reason,\n files: input.files,\n affectedPaths: input.files.flatMap((file) =>\n file.previousPath === undefined ? [file.path] : [file.path, file.previousPath],\n ),\n retryPasses: [],\n retryPaths: [],\n retryStages: [],\n totalFiles: input.totalFiles,\n baselineSha: undefined,\n priorState: undefined,\n profileFingerprint: input.profileFingerprint,\n});\n\n/** Three-dot lineage from the reviewed head to the current head is usable. */\nexport const isLineageAncestor = (\n comparison: ReviewHeadComparison,\n priorState: ReviewState,\n currentHeadSha: string,\n): boolean =>\n comparison.baseSha === priorState.reviewedHeadSha &&\n comparison.headSha === currentHeadSha &&\n comparison.mergeBaseSha === priorState.reviewedHeadSha &&\n !comparison.truncated &&\n (comparison.status === \"ahead\" || comparison.status === \"identical\");\n\n/**\n * Validate that persisted state belongs to this exact PR/base lineage and the\n * same review profile. A mismatch is a full-review reason, never an error that\n * silently suppresses review work.\n */\nexport const validateReviewState = (\n state: ReviewState,\n current: PullRequestMetadata,\n profileFingerprint: string,\n): string | undefined => {\n if (state.repository !== current.repository || state.pullRequestNumber !== current.number) {\n return \"stored state belongs to a different pull request\";\n }\n if (current.baseSha === undefined) return \"the current base commit is unavailable\";\n if (state.baseRef !== current.baseRef) return \"the pull request base ref changed\";\n if (state.headRef !== current.headRef) return \"the pull request head ref changed\";\n if (state.profileFingerprint !== profileFingerprint) {\n return \"the reviewer profile or model configuration changed\";\n }\n if (state.unresolvedConcerns.some((concern) => concern.evidencePaths === undefined)) {\n return \"stored concerns predate affected-path tracking\";\n }\n return undefined;\n};\n\nconst filePaths = (file: ChangedFile): ReadonlyArray<string> =>\n file.previousPath === undefined ? [file.path] : [file.path, file.previousPath];\n\nconst incrementalFromDelta = (input: {\n readonly fullFiles: ReadonlyArray<ChangedFile>;\n readonly profileFingerprint: string;\n readonly priorState: ReviewState;\n readonly deltaPaths: ReadonlyArray<string>;\n readonly extraAffectedPaths?: ReadonlyArray<string> | undefined;\n readonly reason: string;\n}): ReviewSelection => {\n const currentPaths = new Set(input.fullFiles.flatMap(filePaths));\n const affectedPaths = new Set([...input.deltaPaths, ...(input.extraAffectedPaths ?? [])]);\n const initialAffectedCount = affectedPaths.size;\n // Reopen every current path needed to reassess a concern touched by this\n // delta. Repeat to a fixed point because two concerns may overlap on a path.\n let expanded = true;\n while (expanded) {\n expanded = false;\n for (const concern of input.priorState.unresolvedConcerns) {\n const paths = concern.evidencePaths ?? [];\n if (!paths.some((path) => affectedPaths.has(path))) continue;\n for (const path of paths) {\n if (!affectedPaths.has(path)) {\n affectedPaths.add(path);\n expanded = true;\n }\n }\n }\n }\n const selectedByPath = new Map<string, ChangedFile>();\n const carriedPaths = input.priorState.unreviewedPaths.filter((path) => currentPaths.has(path));\n const retryOnly = new Set<string>();\n for (const path of carriedPaths) {\n if (affectedPaths.has(path)) continue;\n retryOnly.add(path);\n }\n\n const retryPathsByStage = new Map<UnreviewedStage, Set<string>>();\n const representedRetryPaths = new Set<string>();\n for (const pass of input.priorState.unreviewedPasses) {\n for (const path of pass.paths) {\n if (!retryOnly.has(path)) continue;\n const paths = retryPathsByStage.get(pass.stage) ?? new Set<string>();\n paths.add(path);\n retryPathsByStage.set(pass.stage, paths);\n representedRetryPaths.add(path);\n }\n }\n // Some continuity gaps (capacity overflow, partial evidence, legacy state)\n // have no failed-pass record. They conservatively re-enter fresh discovery\n // instead of inheriting another path's unrelated failed stage.\n for (const path of retryOnly) {\n if (representedRetryPaths.has(path)) continue;\n retryOnly.delete(path);\n affectedPaths.add(path);\n }\n const retryPasses = ([\"discovery\", \"specialist\", \"verification\"] as const).flatMap((stage) => {\n const paths = [...(retryPathsByStage.get(stage) ?? [])]\n .filter((path) => retryOnly.has(path))\n .sort();\n return Array.from({ length: Math.ceil(paths.length / 12) }, (_, index) =>\n StoredUnreviewedPass.make({\n stage,\n paths: paths.slice(index * 12, (index + 1) * 12),\n }),\n );\n });\n const retryPaths = [...retryOnly].sort();\n const retryStages = [...new Set(retryPasses.map((pass) => pass.stage))];\n for (const file of input.fullFiles) {\n const needed =\n affectedPaths.has(file.path) ||\n (file.previousPath !== undefined && affectedPaths.has(file.previousPath)) ||\n retryOnly.has(file.path) ||\n (file.previousPath !== undefined && retryOnly.has(file.previousPath));\n if (needed) selectedByPath.set(file.path, file);\n }\n const selectedFiles = [...selectedByPath.values()].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const leftoverCount = retryPaths.length;\n const carriedReason =\n leftoverCount > 0\n ? `; retrying ${leftoverCount} unchanged leftover path(s) by recorded failed stage`\n : carriedPaths.length > 0\n ? `; retrying ${carriedPaths.length} carried unreviewed path(s)`\n : \"\";\n const concernPathCount = affectedPaths.size - initialAffectedCount;\n const concernReason =\n concernPathCount === 0\n ? \"\"\n : `; reopening ${concernPathCount} related concern path(s) for context`;\n return {\n mode: \"incremental\",\n reason: `${input.reason}${carriedReason}${concernReason}`,\n files: selectedFiles,\n affectedPaths: [...affectedPaths].sort(),\n retryPasses,\n retryPaths,\n retryStages,\n totalFiles: selectedFiles.length,\n baselineSha: input.priorState.reviewedHeadSha,\n priorState: input.priorState,\n profileFingerprint: input.profileFingerprint,\n };\n};\n\n/** Pure, deterministic range selection with conservative full-review fallbacks. */\nexport const selectReviewRange = (input: {\n readonly requestedMode: ReviewMode;\n readonly current: PullRequestMetadata;\n readonly fullFiles: ReadonlyArray<ChangedFile>;\n readonly profileFingerprint: string;\n readonly priorState: ReviewState | undefined;\n readonly comparison: ReviewHeadComparison | undefined;\n readonly baseComparison?: ReviewHeadComparison | undefined;\n /**\n * Direct commit-tree snapshot comparison used when the reviewed head is not\n * a git ancestor. Selection hydrates these paths from the current PR files.\n */\n readonly contentComparison?: ReviewTreeComparison | undefined;\n /** Why the direct snapshot comparison could not produce complete evidence. */\n readonly contentComparisonFailure?: string | undefined;\n readonly lookupFailure?: string | undefined;\n}): ReviewSelection => {\n const full = (reason: string) =>\n fullReviewSelection({\n reason,\n files: input.fullFiles,\n totalFiles: input.current.totalChangedFiles,\n profileFingerprint: input.profileFingerprint,\n });\n if (input.requestedMode === \"final\") return full(\"explicit final full-diff audit requested\");\n if (input.lookupFailure !== undefined) {\n return full(`stored review state could not be recovered: ${input.lookupFailure}`);\n }\n if (input.priorState === undefined) return full(\"no compatible stored review state was found\");\n const invalid = validateReviewState(input.priorState, input.current, input.profileFingerprint);\n if (invalid !== undefined) return full(invalid);\n const comparison = input.comparison;\n if (\n comparison !== undefined &&\n isLineageAncestor(comparison, input.priorState, input.current.headSha)\n ) {\n const extraAffected: Array<string> = [];\n let baseReason = \"\";\n if (input.priorState.baseSha !== input.current.baseSha) {\n const baseComparison = input.baseComparison;\n if (baseComparison === undefined) {\n return full(\"the pull request base changed and its lineage comparison was unavailable\");\n }\n if (\n baseComparison.baseSha !== input.priorState.baseSha ||\n baseComparison.headSha !== input.current.baseSha ||\n baseComparison.mergeBaseSha !== input.priorState.baseSha ||\n (baseComparison.status !== \"ahead\" && baseComparison.status !== \"identical\") ||\n baseComparison.truncated\n ) {\n return full(\"the pull request base changed materially or exceeded the comparison bound\");\n }\n for (const file of baseComparison.files) extraAffected.push(...filePaths(file));\n baseReason = `; base advanced from ${input.priorState.baseSha.slice(0, 7)} and overlapping PR paths were included`;\n }\n return incrementalFromDelta({\n fullFiles: input.fullFiles,\n profileFingerprint: input.profileFingerprint,\n priorState: input.priorState,\n deltaPaths: comparison.files.flatMap(filePaths),\n extraAffectedPaths: extraAffected,\n reason: `changes since reviewed head ${input.priorState.reviewedHeadSha.slice(0, 7)}${baseReason}`,\n });\n }\n const contentComparison = input.contentComparison;\n if (contentComparison !== undefined) {\n if (\n contentComparison.baseSha !== input.priorState.reviewedHeadSha ||\n contentComparison.headSha !== input.current.headSha\n ) {\n return full(\"the rewritten-head tree snapshot comparison did not match the requested heads\");\n }\n if (contentComparison.truncated) {\n return full(\"the rewritten-head tree snapshot comparison was truncated\");\n }\n return incrementalFromDelta({\n fullFiles: input.fullFiles,\n profileFingerprint: input.profileFingerprint,\n priorState: input.priorState,\n deltaPaths: contentComparison.changedPaths,\n reason: `rewritten history; contents changed since reviewed head ${input.priorState.reviewedHeadSha.slice(0, 7)}`,\n });\n }\n if (input.contentComparisonFailure !== undefined) {\n return full(\n `the rewritten-head tree snapshot comparison failed: ${input.contentComparisonFailure.slice(0, 2_048)}`,\n );\n }\n if (comparison === undefined) return full(\"the incremental head comparison was unavailable\");\n if (comparison.truncated) return full(\"the incremental comparison exceeded GitHub's file bound\");\n return full(\"the prior reviewed head is not an ancestor of the current head\");\n};\n\n/** Per-run context consumed by orchestration and publication, not by the model. */\nexport class ReviewExecutionContext extends Context.Service<\n ReviewExecutionContext,\n ReviewSelection\n>()(\"@effect-agent/pr-review/ReviewExecutionContext\") {}\n\n/**\n * Explicit direct-run adapter for callers that intentionally review the full\n * source without authenticated incremental continuity.\n */\nexport const fullReviewExecutionContextLayer = (reason: string) =>\n Layer.effect(\n ReviewExecutionContext,\n Effect.gen(function* () {\n const source = yield* PullRequestSource;\n const [metadata, files] = yield* Effect.all([source.metadata, source.changedFiles]);\n return fullReviewSelection({ reason, files, totalFiles: metadata.totalChangedFiles });\n }),\n );\n\n/**\n * Decorate the full source with the selected review range. Full anchor files\n * remain available to host-side publication validation; model tools see only\n * the selected delta and may read head context only for that delta's paths.\n */\nexport const selectedPullRequestSourceLayer = (\n selection: ReviewSelection,\n): Layer.Layer<PullRequestSource, never, PullRequestSource> =>\n Layer.effect(PullRequestSource)(\n Effect.gen(function* () {\n const source = yield* PullRequestSource;\n const selectedPaths = new Set(selection.files.map((file) => file.path));\n const selectedFiles = source.changedFiles.pipe(\n Effect.map((fullFiles) => {\n const fullByPath = new Map(fullFiles.map((file) => [file.path, file] as const));\n return selection.files.map((file) => {\n if (file.patch !== undefined) return file;\n const full = fullByPath.get(file.path);\n return full === undefined\n ? file\n : ChangedFile.make({\n ...file,\n ...(full.reviewBaseContent === undefined\n ? {}\n : { reviewBaseContent: full.reviewBaseContent }),\n ...(full.reviewHeadContent === undefined\n ? {}\n : { reviewHeadContent: full.reviewHeadContent }),\n });\n });\n }),\n );\n return PullRequestSource.of({\n metadata: source.metadata,\n changedFiles: selectedFiles,\n anchorFiles: source.anchorFiles,\n readFile: (path) =>\n selectedPaths.has(path)\n ? source.readFile(path)\n : Effect.fail(\n ReviewInputViolation.make({\n input: path,\n reason: \"Path is outside this incremental review range.\",\n }),\n ),\n });\n }),\n );\n\n/** Build the full-surface mission used only to resolve profile guidance. */\nexport const buildProfileMission = (\n metadata: PullRequestMetadata,\n files: ReadonlyArray<ChangedFile>,\n): ReviewMission =>\n ReviewMission.make({\n repository: metadata.repository,\n number: metadata.number,\n title: metadata.title,\n body: metadata.body,\n baseRef: metadata.baseRef,\n headRef: metadata.headRef,\n changedFileCount: files.length,\n });\n","import { Context, DateTime, Effect, Option, Schema } from \"effect\";\n\nimport {\n adjudicationIdentity,\n findingIdentity,\n ReviewStateAuthenticator,\n type ReviewState,\n type StoredReviewFinding,\n} from \"./review-state.ts\";\n\n// ---------------------------------------------------------------------------\n// Review retirement. GitHub mutations stay behind ReviewRetirementHost; this\n// module owns only deterministic identity matching, body rewriting, and the\n// fail-open orchestration that turns stale reviews into quiet history.\n// ---------------------------------------------------------------------------\n\nconst PositiveLine = Schema.Int.check(Schema.isGreaterThan(0));\n\n/** One previously posted review as observed through the retirement host. */\nexport class RetirableReview extends Schema.Class<RetirableReview>(\n \"@effect-agent/pr-review/RetirableReview\",\n)({\n reviewId: Schema.Int.check(Schema.isGreaterThan(0)),\n body: Schema.String.check(Schema.isMaxLength(60_000)),\n commitSha: Schema.NonEmptyString.check(Schema.isMaxLength(64)),\n authorNodeId: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(200))),\n submittedAt: Schema.NullOr(Schema.DateTimeUtc),\n}) {}\n\n/** One inline comment attached to a previously posted review. */\nexport class RetirableReviewComment extends Schema.Class<RetirableReviewComment>(\n \"@effect-agent/pr-review/RetirableReviewComment\",\n)({\n nodeId: Schema.NonEmptyString.check(Schema.isMaxLength(200)),\n path: Schema.NonEmptyString.check(Schema.isMaxLength(500)),\n startLine: Schema.NullOr(PositiveLine),\n endLine: Schema.NullOr(PositiveLine),\n body: Schema.String.check(Schema.isMaxLength(65_536)),\n}) {}\n\n/** A GitHub retirement read or mutation failed. */\nexport class ReviewRetirementFailure extends Schema.TaggedError<ReviewRetirementFailure>()(\n \"ReviewRetirementFailure\",\n {\n operation: Schema.String,\n reason: Schema.String,\n },\n) {\n override get message() {\n return `Review retirement operation '${this.operation}' failed: ${this.reason}`;\n }\n}\n\n/**\n * Host-side GitHub operations used by retirement. Domain code never reaches\n * into REST or GraphQL directly, and deterministic tests substitute this port.\n */\nexport class ReviewRetirementHost extends Context.Service<\n ReviewRetirementHost,\n {\n readonly listReviews: Effect.Effect<ReadonlyArray<RetirableReview>, ReviewRetirementFailure>;\n readonly listComments: (\n reviewId: number,\n ) => Effect.Effect<ReadonlyArray<RetirableReviewComment>, ReviewRetirementFailure>;\n readonly updateBody: (\n reviewId: number,\n body: string,\n ) => Effect.Effect<void, ReviewRetirementFailure>;\n readonly minimizeComment: (nodeId: string) => Effect.Effect<void, ReviewRetirementFailure>;\n }\n>()(\"@effect-agent/pr-review/ReviewRetirementHost\") {}\n\n/** Observable cosmetic work completed by one fail-open retirement pass. */\nexport class ReviewRetirementReport extends Schema.Class<ReviewRetirementReport>(\n \"@effect-agent/pr-review/ReviewRetirementReport\",\n)({\n reviewsRetired: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n findingsResolved: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n commentsMinimized: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n failures: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nexport interface ReviewRetirementInput {\n readonly currentReviewId: number;\n readonly currentReviewUrl: string;\n readonly currentAuthorNodeId: string;\n readonly currentSubmittedAt: DateTime.Utc;\n readonly currentState: ReviewState;\n}\n\nexport interface ReviewRetirementDecision {\n readonly body: string;\n readonly resolvedFindings: ReadonlyArray<StoredReviewFinding>;\n readonly priorFindingCount: number;\n}\n\nconst REVIEW_METADATA_PATTERN = /<!-- effect-agent-pr-review metadata\\n[\\s\\S]*?\\n-->/g;\nconst FINGERPRINT_PATTERN = /<!-- effect-agent-pr-review fingerprint=sha256:[0-9a-f]{64} -->/g;\nconst STATE_PATTERN =\n /<!-- effect-agent-pr-review state-v1:[A-Za-z0-9+/]+={0,2}\\.[0-9a-f]{64} -->/g;\nconst RETIRED_ORIGINAL_PATTERN =\n /<!-- effect-agent-pr-review retired-original:start -->\\n([\\s\\S]*?)\\n<!-- effect-agent-pr-review retired-original:end -->/;\nconst MACHINE_COMMENT_PATTERN = new RegExp(\n `${REVIEW_METADATA_PATTERN.source}|${FINGERPRINT_PATTERN.source}|${STATE_PATTERN.source}`,\n \"g\",\n);\nconst VERDICT_CALLOUT_PATTERN =\n /^(?:> \\[!(?:CAUTION|IMPORTANT)\\]\\n> [^\\n]*(?:\\n> [^\\n]*)*|> (?:ℹ️|✅)[^\\n]*)\\n*/;\n/**\n * The first line of every inline finding comment this package posts. Shared\n * with adjudication so both parse the identical title shape.\n */\nexport const INLINE_FINDING_TITLE_PATTERN =\n /^\\*\\*\\[(?:🛑 blocking|⚠️ important|💅 nit) · [a-z-]+\\] ([^\\n]+)\\*\\*$/;\nconst MAX_REVIEW_BODY_CHARS = 60_000;\n\n/** The host-authored metadata marker is the authority gate for any edit. */\nexport const hasReviewMetadataMarker = (body: string): boolean =>\n /<!-- effect-agent-pr-review metadata\\n/.test(body);\n\nconst machineComments = (body: string): ReadonlyArray<string> =>\n Array.from(body.matchAll(MACHINE_COMMENT_PATTERN), (match) => match[0]);\n\nconst originalVisibleBody = (body: string): string => {\n const retired = RETIRED_ORIGINAL_PATTERN.exec(body)?.[1];\n if (retired !== undefined) return retired;\n return body.replace(MACHINE_COMMENT_PATTERN, \"\").trim().replace(VERDICT_CALLOUT_PATTERN, \"\");\n};\n\nconst findingLocation = (finding: StoredReviewFinding): string =>\n `${finding.path}:${finding.startLine}${\n finding.endLine === finding.startLine ? \"\" : `-${finding.endLine}`\n }`;\n\nconst renderRetiredBody = (input: {\n readonly priorBody: string;\n readonly priorState: ReviewState;\n readonly currentState: ReviewState;\n readonly currentReviewUrl: string;\n readonly resolvedFindings: ReadonlyArray<StoredReviewFinding>;\n}): string => {\n const shortSha = input.currentState.reviewedHeadSha.slice(0, 7);\n const comments = machineComments(input.priorBody);\n const original = originalVisibleBody(input.priorBody);\n const resolved =\n input.resolvedFindings.length === 0\n ? []\n : [\n \"### Findings resolved by later review\",\n \"\",\n ...input.resolvedFindings.map(\n (finding) =>\n `- \\`${findingLocation(finding)}\\` ~~${finding.title}~~ · resolved at \\`${shortSha}\\``,\n ),\n \"\",\n ];\n const prefix = [\n `> ℹ️ Superseded — ${input.resolvedFindings.length} of ${input.priorState.unresolvedFindings.length} findings resolved at \\`${shortSha}\\`; see [the latest review](${input.currentReviewUrl}).`,\n \"\",\n \"<details>\",\n \"<summary>Previous review details</summary>\",\n \"\",\n ...resolved,\n \"<!-- effect-agent-pr-review retired-original:start -->\",\n ];\n const suffix = [\n \"<!-- effect-agent-pr-review retired-original:end -->\",\n \"\",\n \"</details>\",\n ...(comments.length === 0 ? [] : [\"\", ...comments]),\n ];\n const render = (visible: string) => [...prefix, visible, ...suffix].join(\"\\n\");\n if (render(original).length <= MAX_REVIEW_BODY_CHARS) return render(original);\n const truncationNotice = \"\\n\\n_Original review content truncated during retirement._\";\n const budget = Math.max(0, MAX_REVIEW_BODY_CHARS - render(truncationNotice).length);\n return render(`${original.slice(0, budget)}${truncationNotice}`);\n};\n\n/** Compute one prior review's resolved subset and deterministic retired body. */\nexport const decideReviewRetirement = (input: {\n readonly priorBody: string;\n readonly priorState: ReviewState;\n readonly currentState: ReviewState;\n readonly currentReviewUrl: string;\n}): ReviewRetirementDecision => {\n const current = new Set(input.currentState.unresolvedFindings.map(findingIdentity));\n // Adjudicated identities are distinct from resolved: a maintainer verdict\n // is not a fix, so retirement neither strikes nor minimizes them.\n const adjudicated = new Set(\n (input.currentState.adjudications ?? []).map((entry) => adjudicationIdentity(entry)),\n );\n const resolvedFindings = input.priorState.unresolvedFindings.filter(\n (finding) =>\n !current.has(findingIdentity(finding)) && !adjudicated.has(findingIdentity(finding)),\n );\n return {\n body: renderRetiredBody({ ...input, resolvedFindings }),\n resolvedFindings,\n priorFindingCount: input.priorState.unresolvedFindings.length,\n };\n};\n\nconst inlineCommentIdentity = (comment: RetirableReviewComment): string | undefined => {\n if (comment.startLine === null || comment.endLine === null) return undefined;\n const firstLine = comment.body.split(\"\\n\", 1)[0] ?? \"\";\n const title = INLINE_FINDING_TITLE_PATTERN.exec(firstLine)?.[1];\n return title === undefined\n ? undefined\n : findingIdentity({\n path: comment.path,\n startLine: comment.startLine,\n endLine: comment.endLine,\n title,\n });\n};\n\nconst failOpen = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n fallback: A,\n message: string,\n): Effect.Effect<A, never, R> =>\n effect.pipe(\n Effect.catch((error) =>\n Effect.logWarning(`${message}: ${String(error)}`).pipe(Effect.as(fallback)),\n ),\n );\n\nconst isStrictlyOlderReview = (review: RetirableReview, input: ReviewRetirementInput): boolean => {\n if (review.submittedAt === null) return false;\n const submittedAt = DateTime.toEpochMillis(review.submittedAt);\n const currentSubmittedAt = DateTime.toEpochMillis(input.currentSubmittedAt);\n return (\n submittedAt < currentSubmittedAt ||\n (submittedAt === currentSubmittedAt && review.reviewId < input.currentReviewId)\n );\n};\n\n/**\n * Retire every marker-bearing prior review against the newest posted state.\n * Every lookup, edit, and minimization is isolated: retirement is cosmetic\n * and can never change the run or check outcome.\n */\nexport const retireStaleReviews = Effect.fn(\"retireStaleReviews\")(function* (\n input: ReviewRetirementInput,\n) {\n const host = yield* ReviewRetirementHost;\n const authenticator = yield* ReviewStateAuthenticator;\n if (authenticator.status !== \"available\") {\n yield* Effect.logWarning(\n \"Skipping stale-review retirement because authenticated review state is unavailable.\",\n );\n return ReviewRetirementReport.make({\n reviewsRetired: 0,\n findingsResolved: 0,\n commentsMinimized: 0,\n failures: 0,\n });\n }\n\n let failures = 0;\n let reviewsRetired = 0;\n let findingsResolved = 0;\n let commentsMinimized = 0;\n const reviews = yield* failOpen(host.listReviews, undefined, \"Could not list prior reviews\");\n if (reviews === undefined) {\n return ReviewRetirementReport.make({\n reviewsRetired,\n findingsResolved,\n commentsMinimized,\n failures: 1,\n });\n }\n\n for (const review of reviews) {\n if (\n review.authorNodeId !== input.currentAuthorNodeId ||\n !isStrictlyOlderReview(review, input) ||\n !hasReviewMetadataMarker(review.body)\n ) {\n continue;\n }\n const priorState = yield* failOpen(\n authenticator.extract(review.body),\n Option.none<ReviewState>(),\n `Could not authenticate prior review ${review.reviewId}`,\n );\n if (Option.isNone(priorState)) continue;\n\n const decision = decideReviewRetirement({\n priorBody: review.body,\n priorState: priorState.value,\n currentState: input.currentState,\n currentReviewUrl: input.currentReviewUrl,\n });\n const updated = yield* failOpen(\n host.updateBody(review.reviewId, decision.body).pipe(Effect.as(true)),\n false,\n `Could not retire prior review ${review.reviewId}`,\n );\n if (updated) {\n reviewsRetired += 1;\n findingsResolved += decision.resolvedFindings.length;\n } else {\n failures += 1;\n }\n\n if (decision.resolvedFindings.length === 0) continue;\n const comments = yield* failOpen(\n host.listComments(review.reviewId),\n undefined,\n `Could not list inline comments for prior review ${review.reviewId}`,\n );\n if (comments === undefined) {\n failures += 1;\n continue;\n }\n const resolved = new Set(decision.resolvedFindings.map(findingIdentity));\n for (const comment of comments) {\n const identity = inlineCommentIdentity(comment);\n if (identity === undefined || !resolved.has(identity)) continue;\n const minimized = yield* failOpen(\n host.minimizeComment(comment.nodeId).pipe(Effect.as(true)),\n false,\n `Could not minimize resolved inline comment ${comment.nodeId}`,\n );\n if (minimized) commentsMinimized += 1;\n else failures += 1;\n }\n }\n\n return ReviewRetirementReport.make({\n reviewsRetired,\n findingsResolved,\n commentsMinimized,\n failures,\n });\n});\n","import { Context, DateTime, Effect, Layer, Schema } from \"effect\";\n\nimport { INLINE_FINDING_TITLE_PATTERN } from \"./retirement.ts\";\nimport {\n adjudicationIdentity,\n MAX_STORED_ADJUDICATIONS,\n StoredAdjudication,\n type AdjudicationDisposition,\n type StoredReviewFinding,\n} from \"./review-state.ts\";\n\n// ---------------------------------------------------------------------------\n// Maintainer adjudication. GitHub reads stay behind ReviewAdjudicationHost;\n// this module owns only the deterministic verb grammar, fail-closed\n// authorization, later-wins resolution, and prompt-context rendering. Only an\n// explicit, authorized `/adjudicate` verb adjudicates — free-text rebuttals\n// are deliberately never parsed, because only an explicit verb is auditable\n// and fail-closed (model output and third-party comments are untrusted\n// input, AGENTS.md rule 11).\n// ---------------------------------------------------------------------------\n\nconst PositiveLine = Schema.Int.check(Schema.isGreaterThan(0));\n\n/** Maximum authorized command candidates retained for one inline thread. */\nexport const MAX_THREAD_ADJUDICATION_COMMANDS = 100;\n\n/** One reply or top-level comment observed through the adjudication host. */\nexport class AdjudicationComment extends Schema.Class<AdjudicationComment>(\n \"@effect-agent/pr-review/AdjudicationComment\",\n)({\n body: Schema.String.check(Schema.isMaxLength(65_536)),\n /** GitHub's author_association for the comment author, verbatim. */\n authorAssociation: Schema.String.check(Schema.isMaxLength(40)),\n authorLogin: Schema.NonEmptyString.check(Schema.isMaxLength(100)),\n /** Creation time; a comment without one loses every later-wins tie. */\n createdAt: Schema.NullOr(Schema.DateTimeUtc),\n /** Stable zero-based order in the source listing, before thread grouping. */\n sourceOrder: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** One of the action's own inline finding threads, replies in creation order. */\nexport class AdjudicableThread extends Schema.Class<AdjudicableThread>(\n \"@effect-agent/pr-review/AdjudicableThread\",\n)({\n path: Schema.NonEmptyString.check(Schema.isMaxLength(500)),\n startLine: Schema.NullOr(PositiveLine),\n endLine: Schema.NullOr(PositiveLine),\n /** The root comment's body; its first line carries the finding title. */\n rootBody: Schema.String.check(Schema.isMaxLength(65_536)),\n replies: Schema.Array(AdjudicationComment).check(\n Schema.isMaxLength(MAX_THREAD_ADJUDICATION_COMMANDS),\n ),\n}) {}\n\n/** A GitHub adjudication read failed. */\nexport class ReviewAdjudicationFailure extends Schema.TaggedError<ReviewAdjudicationFailure>()(\n \"ReviewAdjudicationFailure\",\n {\n operation: Schema.String,\n reason: Schema.String,\n },\n) {\n override get message() {\n return `Review adjudication operation '${this.operation}' failed: ${this.reason}`;\n }\n}\n\n/**\n * Host-side GitHub reads used by adjudication. Domain code never reaches into\n * REST directly, and deterministic tests substitute this port. Both listings\n * return comments in creation order.\n */\nexport class ReviewAdjudicationHost extends Context.Service<\n ReviewAdjudicationHost,\n {\n /** This action's own inline finding threads with their replies. */\n readonly listFindingThreads: Effect.Effect<\n ReadonlyArray<AdjudicableThread>,\n ReviewAdjudicationFailure\n >;\n /** Top-level pull-request conversation comments. */\n readonly listIssueComments: Effect.Effect<\n ReadonlyArray<AdjudicationComment>,\n ReviewAdjudicationFailure\n >;\n }\n>()(\"@effect-agent/pr-review/ReviewAdjudicationHost\") {}\n\n/** Explicit program-edge adapter for runs that intentionally perform no host reads. */\nexport const noReviewAdjudicationHost = ReviewAdjudicationHost.of({\n listFindingThreads: Effect.succeed([]),\n listIssueComments: Effect.succeed([]),\n});\n\n/** Layer form of {@link noReviewAdjudicationHost}. */\nexport const noReviewAdjudicationHostLayer =\n Layer.succeed(ReviewAdjudicationHost)(noReviewAdjudicationHost);\n\n// ---------------------------------------------------------------------------\n// Verb grammar. A body whose first line starts with `/adjudicate` is a\n// command; a command that fails the grammar is malformed and ignored rather\n// than guessed at. Fail-closed authorization: only OWNER, MEMBER, and\n// COLLABORATOR authors may adjudicate.\n// ---------------------------------------------------------------------------\n\n/** author_associations allowed to adjudicate; everything else is ignored. */\nexport const AUTHORIZED_ADJUDICATION_ASSOCIATIONS: ReadonlySet<string> = new Set([\n \"OWNER\",\n \"MEMBER\",\n \"COLLABORATOR\",\n]);\n\nconst AdjudicationDispositionSchema = Schema.Literals([\"accepted-risk\", \"refuted\", \"obsolete\"]);\n\nconst THREAD_COMMAND_PATTERN = /^\\/adjudicate[ \\t]+([a-z-]+)[ \\t]*(?::[ \\t]*(.*\\S))?[ \\t]*$/;\nconst ISSUE_COMMAND_PATTERN =\n /^\\/adjudicate[ \\t]+([a-z-]+)[ \\t]+\"([^\"\\n]+)\"[ \\t]*(?::[ \\t]*(.*\\S))?[ \\t]*$/;\n\nexport interface ParsedAdjudicationCommand {\n readonly disposition: AdjudicationDisposition;\n /** Present only for the issue-comment grammar's quoted target title. */\n readonly title?: string | undefined;\n readonly reason?: string | undefined;\n}\n\nconst firstLine = (body: string): string => (body.split(\"\\n\", 1)[0] ?? \"\").trim();\n\nconst boundedReason = (raw: string | undefined): string | undefined => {\n if (raw === undefined) return undefined;\n const trimmed = raw.trim().slice(0, 300);\n return trimmed.length === 0 ? undefined : trimmed;\n};\n\n/**\n * Parse one inline-thread reply: `/adjudicate <disposition>(: <reason>)?`.\n * The thread itself names the target identity. Returns undefined for a\n * non-command body and \"malformed\" for a command that fails the grammar.\n */\nexport const parseThreadAdjudication = (\n body: string,\n): ParsedAdjudicationCommand | \"malformed\" | undefined => {\n const line = firstLine(body);\n if (!line.startsWith(\"/adjudicate\")) return undefined;\n const match = THREAD_COMMAND_PATTERN.exec(line);\n const disposition = match?.[1];\n if (disposition === undefined || !Schema.is(AdjudicationDispositionSchema)(disposition)) {\n return \"malformed\";\n }\n return { disposition, reason: boundedReason(match?.[2]) };\n};\n\n/**\n * Parse one top-level PR comment:\n * `/adjudicate <disposition> \"<exact title>\"(: <reason>)?`. The quoted title\n * is required because the conversation names no finding thread; it targets\n * the title-alone identity of an unanchored concern.\n */\nexport const parseIssueAdjudication = (\n body: string,\n): ParsedAdjudicationCommand | \"malformed\" | undefined => {\n const line = firstLine(body);\n if (!line.startsWith(\"/adjudicate\")) return undefined;\n const match = ISSUE_COMMAND_PATTERN.exec(line);\n const disposition = match?.[1];\n const title = match?.[2];\n if (\n disposition === undefined ||\n !Schema.is(AdjudicationDispositionSchema)(disposition) ||\n title === undefined ||\n title.length > 120\n ) {\n return \"malformed\";\n }\n return { disposition, title, reason: boundedReason(match?.[3]) };\n};\n\n/** The finding identity an inline thread names, or undefined when unparsable. */\nexport const threadFindingTarget = (\n thread: AdjudicableThread,\n):\n | {\n readonly path: string;\n readonly startLine: number;\n readonly endLine: number;\n readonly title: string;\n }\n | undefined => {\n if (thread.startLine === null || thread.endLine === null) return undefined;\n const title = INLINE_FINDING_TITLE_PATTERN.exec(firstLine(thread.rootBody))?.[1];\n if (title === undefined || title.length > 120) return undefined;\n return {\n path: thread.path,\n startLine: thread.startLine,\n endLine: thread.endLine,\n title,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Deterministic derivation: authorization, later-wins, bounded storage.\n// ---------------------------------------------------------------------------\n\ninterface AdjudicationCandidate {\n readonly adjudication: StoredAdjudication;\n readonly epochMillis: number;\n readonly sourceOrder: number;\n}\n\nexport interface DerivedAdjudications {\n readonly adjudications: ReadonlyArray<StoredAdjudication>;\n /** Commands ignored fail-closed: unauthorized authors and malformed bodies. */\n readonly ignored: ReadonlyArray<string>;\n /** Later-wins winners dropped oldest-first at the storage bound. */\n readonly droppedOldest: number;\n}\n\n/**\n * Derive the standing adjudications from the host's listings. Every command\n * is screened fail-closed (authorization, grammar, a parsable target); later\n * adjudications of the same identity win by comment creation order; the\n * result is capped at the ReviewState bound dropping the oldest winners.\n */\nexport const deriveAdjudications = (input: {\n readonly threads: ReadonlyArray<AdjudicableThread>;\n readonly issueComments: ReadonlyArray<AdjudicationComment>;\n}): DerivedAdjudications => {\n const candidates: Array<AdjudicationCandidate> = [];\n const ignored: Array<string> = [];\n const admit = (\n comment: AdjudicationComment,\n command: ParsedAdjudicationCommand,\n target: {\n readonly path?: string | undefined;\n readonly startLine?: number | undefined;\n readonly endLine?: number | undefined;\n readonly title: string;\n },\n ): void => {\n candidates.push({\n adjudication: StoredAdjudication.make({\n ...(target.path === undefined ? {} : { path: target.path }),\n ...(target.startLine === undefined ? {} : { startLine: target.startLine }),\n ...(target.endLine === undefined ? {} : { endLine: target.endLine }),\n title: target.title,\n disposition: command.disposition,\n ...(command.reason === undefined ? {} : { reason: command.reason }),\n actor: comment.authorLogin,\n }),\n epochMillis: comment.createdAt === null ? -1 : DateTime.toEpochMillis(comment.createdAt),\n sourceOrder: comment.sourceOrder,\n });\n };\n const authorized = (comment: AdjudicationComment, surface: string): boolean => {\n if (AUTHORIZED_ADJUDICATION_ASSOCIATIONS.has(comment.authorAssociation)) return true;\n ignored.push(\n `${surface}: unauthorized /adjudicate from @${comment.authorLogin} (${comment.authorAssociation})`,\n );\n return false;\n };\n\n for (const thread of input.threads) {\n const target = threadFindingTarget(thread);\n for (const reply of thread.replies) {\n const command = parseThreadAdjudication(reply.body);\n if (command === undefined) continue;\n const surface = `inline thread ${thread.path}`;\n if (command === \"malformed\") {\n ignored.push(`${surface}: malformed /adjudicate command from @${reply.authorLogin}`);\n continue;\n }\n if (!authorized(reply, surface)) continue;\n if (target === undefined) {\n ignored.push(`${surface}: thread root names no parsable finding title`);\n continue;\n }\n admit(reply, command, target);\n }\n }\n for (const comment of input.issueComments) {\n const command = parseIssueAdjudication(comment.body);\n if (command === undefined) continue;\n const surface = \"pull-request conversation\";\n if (command === \"malformed\") {\n ignored.push(`${surface}: malformed /adjudicate command from @${comment.authorLogin}`);\n continue;\n }\n if (!authorized(comment, surface)) continue;\n if (command.title === undefined) {\n ignored.push(`${surface}: /adjudicate without a quoted target title`);\n continue;\n }\n admit(comment, command, { title: command.title });\n }\n\n const byIdentity = new Map<string, AdjudicationCandidate>();\n const ordered = [...candidates].sort(\n (left, right) => left.epochMillis - right.epochMillis || left.sourceOrder - right.sourceOrder,\n );\n for (const candidate of ordered) {\n const identity = adjudicationIdentity(candidate.adjudication);\n // Delete-then-set so a later adjudication also refreshes its recency for\n // the oldest-first drop below.\n byIdentity.delete(identity);\n byIdentity.set(identity, candidate);\n }\n const winners = [...byIdentity.values()];\n const droppedOldest = Math.max(0, winners.length - MAX_STORED_ADJUDICATIONS);\n return {\n adjudications: winners.slice(droppedOldest).map((candidate) => candidate.adjudication),\n ignored,\n droppedOldest,\n };\n};\n\n/** Later-wins merge of stored prior adjudications with freshly derived ones. */\nexport const mergeAdjudications = (\n prior: ReadonlyArray<StoredAdjudication>,\n fresh: ReadonlyArray<StoredAdjudication>,\n): ReadonlyArray<StoredAdjudication> => {\n const byIdentity = new Map<string, StoredAdjudication>();\n for (const adjudication of [...prior, ...fresh]) {\n const identity = adjudicationIdentity(adjudication);\n byIdentity.delete(identity);\n byIdentity.set(identity, adjudication);\n }\n const merged = [...byIdentity.values()];\n return merged.slice(Math.max(0, merged.length - MAX_STORED_ADJUDICATIONS));\n};\n\n/**\n * Collect the standing maintainer adjudications: freshly derived through the\n * host, merged later-wins over the prior state's stored set. The host is a\n * visible Effect requirement; program edges that intentionally perform no\n * reads provide {@link noReviewAdjudicationHost}. Fail-open — any listing\n * fault keeps the complete prior set and never fails the review, because NOT\n * suppressing a finding is the conservative direction.\n */\nexport const collectReviewAdjudications = Effect.fn(\"collectReviewAdjudications\")(function* (\n prior: ReadonlyArray<StoredAdjudication>,\n) {\n const host = yield* ReviewAdjudicationHost;\n const listings = yield* Effect.all({\n threads: host.listFindingThreads,\n issueComments: host.listIssueComments,\n }).pipe(\n Effect.catch((error) =>\n Effect.logWarning(\n `Could not collect adjudications from '${error.operation}': ${error.reason}; retaining stored adjudications unchanged.`,\n ).pipe(Effect.as(undefined)),\n ),\n );\n if (listings === undefined) return prior;\n const derived = deriveAdjudications({\n threads: listings.threads,\n issueComments: listings.issueComments,\n });\n for (const note of derived.ignored) {\n yield* Effect.logDebug(`Ignored adjudication command — ${note}`);\n }\n if (derived.droppedOldest > 0) {\n yield* Effect.logWarning(\n `Dropped ${derived.droppedOldest} oldest adjudication(s) over the ${MAX_STORED_ADJUDICATIONS}-entry bound.`,\n );\n }\n return mergeAdjudications(prior, derived.adjudications);\n});\n\n// ---------------------------------------------------------------------------\n// Prompt-context rendering: deterministic bounded lines the reviewer sees.\n// ---------------------------------------------------------------------------\n\nconst lineRange = (startLine: number, endLine: number): string =>\n `${startLine}${endLine === startLine ? \"\" : `-${endLine}`}`;\n\n/** One adjudication as a bounded reviewer-prompt context line. */\nexport const renderAdjudicationContextLine = (adjudication: StoredAdjudication): string => {\n const location =\n adjudication.path !== undefined &&\n adjudication.startLine !== undefined &&\n adjudication.endLine !== undefined\n ? `${adjudication.path}:${lineRange(adjudication.startLine, adjudication.endLine)}`\n : \"(unanchored)\";\n const reason = adjudication.reason === undefined ? \"\" : `: ${adjudication.reason}`;\n return `${location} \"${adjudication.title}\" — ${adjudication.disposition} by @${adjudication.actor}${reason}`;\n};\n\n/** One prior-round finding as a bounded reviewer-prompt context line. */\nexport const renderPriorFindingContextLine = (finding: StoredReviewFinding): string =>\n `${finding.path}:${lineRange(finding.startLine, finding.endLine)} [${finding.severity}] \"${finding.title}\" — ${finding.body.slice(0, 400)}`;\n\n/** Prior-review context threaded into fan-out discovery briefs, per path. */\nexport interface PriorReviewContext {\n /** Adjudicated identities; path-free entries apply to every unit. */\n readonly adjudicated: ReadonlyArray<{\n readonly path: string | undefined;\n readonly line: string;\n }>;\n /** Prior-round findings whose paths are being re-reviewed. */\n readonly priorFindings: ReadonlyArray<{ readonly path: string; readonly line: string }>;\n}\n\n/** Build the fan-out prior-review context from the resolved continuity data. */\nexport const buildPriorReviewContext = (\n adjudications: ReadonlyArray<StoredAdjudication>,\n priorFindingsOnScope: ReadonlyArray<StoredReviewFinding>,\n): PriorReviewContext => ({\n adjudicated: adjudications.map((adjudication) => ({\n path: adjudication.path,\n line: renderAdjudicationContextLine(adjudication),\n })),\n priorFindings: priorFindingsOnScope.map((finding) => ({\n path: finding.path,\n line: renderPriorFindingContextLine(finding),\n })),\n});\n","import { commentableLines } from \"./diff.ts\";\nimport type { ChangedFile } from \"./diff.ts\";\nimport type { ReviewFinding } from \"./review-agent.ts\";\n\n/** Why a finding cannot anchor to the current new-version diff, if any. */\nexport const anchorViolation = (\n finding: ReviewFinding,\n files: ReadonlyArray<ChangedFile>,\n): string | undefined => {\n const file = files.find((candidate) => candidate.path === finding.path);\n if (file === undefined) return \"path is not part of the changeset\";\n if (file.patch === undefined) return \"file has no anchorable textual diff\";\n if (finding.endLine < finding.startLine) return \"endLine precedes startLine\";\n if (finding.endLine - finding.startLine + 1 > 100) return \"range is implausibly large\";\n const anchors = commentableLines(file.patch);\n for (let line = finding.startLine; line <= finding.endLine; line += 1) {\n if (!anchors.has(line)) return `line ${line} is not part of the diff`;\n }\n return undefined;\n};\n","import { Option, Schema } from \"effect\";\nimport type { RunEvent } from \"effect-agent\";\n\nimport type { ChangedFile } from \"./diff.ts\";\nimport { isReviewableFile } from \"./diff.ts\";\nimport { FileDiffView, FileDiffQuery } from \"./review-agent.ts\";\nimport type { ReviewUnitPlan } from \"./review-units.ts\";\n\n// ---------------------------------------------------------------------------\n// Two different claims are deliberately modeled:\n//\n// - input coverage: every required path was assigned bounded evidence or was\n// explicitly reported outside the pipeline's capacity;\n// - review assurance: every scheduled discovery/specialist pass and every\n// candidate-verification pass settled.\n//\n// Neither claims that the model found every defect. The fan-out pipeline is\n// host-scheduled (fan-out.ts), so its assurance is computed from direct pass\n// results; only the flat reviewer is assessed from its Run event trace here.\n// ---------------------------------------------------------------------------\n\nexport class ReviewInputCoverage extends Schema.Class<ReviewInputCoverage>(\n \"@effect-agent/pr-review/ReviewInputCoverage\",\n)({\n status: Schema.Literals([\"complete\", \"incomplete\"]),\n requiredPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(\n Schema.isMaxLength(300),\n ),\n assignedPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(\n Schema.isMaxLength(300),\n ),\n /** Assigned paths whose model-visible diff was truncated by the evidence bound. */\n partialPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(\n Schema.isMaxLength(300),\n ),\n unassignedPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(\n Schema.isMaxLength(300),\n ),\n /**\n * Paths with neither a textual diff nor bounded base/head text (binaries,\n * oversized files). Fail-closed: they keep the status incomplete for as\n * long as they are part of the pull request — an unreviewable change must\n * never authorize a green check. Exclude them deliberately with ignore\n * globs when that is intended.\n */\n undiffablePaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(\n Schema.isMaxLength(300),\n ),\n reasons: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(1_000))).check(\n Schema.isMaxLength(20),\n ),\n}) {}\n\nexport class FailedReviewPass extends Schema.Class<FailedReviewPass>(\n \"@effect-agent/pr-review/FailedReviewPass\",\n)({\n workId: Schema.NonEmptyString.check(Schema.isMaxLength(96)),\n stage: Schema.Literals([\"discovery\", \"specialist\", \"verification\"]),\n errorTag: Schema.NonEmptyString.check(Schema.isMaxLength(256)),\n}) {}\n\n/**\n * Settlement of scheduled review work. `incomplete` means reviewer-side work\n * failed after its bounded retry — a machinery gap that is carried forward and\n * retried on the next run, never a statement about the code under review.\n * `unverified` is the flat reviewer's honest constant: one pass with no\n * independent verifier is neither settled assurance nor a failure.\n */\nexport class ReviewAssurance extends Schema.Class<ReviewAssurance>(\n \"@effect-agent/pr-review/ReviewAssurance\",\n)({\n status: Schema.Literals([\"settled\", \"incomplete\", \"unverified\"]),\n requiredGeneralDiscoveryPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n completedGeneralDiscoveryPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n requiredSpecialistPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n completedSpecialistPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n requiredVerificationPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n completedVerificationPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n discoveredCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n confirmedCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n rejectedCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n unsettledCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Discovery claims discarded for anchors/paths outside their assigned evidence. */\n discardedInvalidFindings: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n failedPasses: Schema.Array(FailedReviewPass).check(Schema.isMaxLength(64)),\n reasons: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(1_000))).check(\n Schema.isMaxLength(32),\n ),\n}) {}\n\ninterface ToolTrace {\n readonly declared: Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallDeclared\" }>>;\n readonly succeeded: Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallSucceeded\" }>>;\n readonly failed: Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallFailed\" }>>;\n}\n\nconst toolTrace = (events: ReadonlyArray<RunEvent>): ToolTrace => {\n const declared = new Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallDeclared\" }>>();\n const succeeded = new Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallSucceeded\" }>>();\n const failed = new Map<string, Extract<RunEvent, { readonly _tag: \"ToolCallFailed\" }>>();\n for (const event of events) {\n if (event._tag === \"ToolCallDeclared\") declared.set(event.toolCallId, event);\n if (event._tag === \"ToolCallSucceeded\") succeeded.set(event.toolCallId, event);\n if (event._tag === \"ToolCallFailed\") failed.set(event.toolCallId, event);\n }\n return { declared, succeeded, failed };\n};\n\nconst sortedUnique = (values: Iterable<string>): ReadonlyArray<string> =>\n [...new Set(values)].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));\n\n/** Render a bounded, deterministic \"label (n): a, b, … (+k more)\" reason line. */\nexport const boundedListReason = (label: string, values: Iterable<string>): string => {\n const items = sortedUnique(values);\n const prefix = `${label} (${items.length}): `;\n let rendered = prefix;\n for (let index = 0; index < items.length; index += 1) {\n const item = items[index] ?? \"\";\n const separator = index === 0 ? \"\" : \", \";\n const omitted = items.length - index - 1;\n const suffix = omitted === 0 ? \"\" : ` … (+${omitted} more)`;\n if (`${rendered}${separator}${item}${suffix}`.length > 1_000) {\n const omission = `… (+${items.length - index} more)`;\n return `${rendered.slice(0, 1_000 - omission.length)}${omission}`;\n }\n rendered = `${rendered}${separator}${item}`;\n }\n return rendered;\n};\n\nexport interface CarriedScope {\n /** Carried paths a retry can actually settle (failed passes, overflow). */\n readonly retryablePaths: ReadonlyArray<string>;\n /** Carried paths no retry can settle (binaries, oversized files). */\n readonly undiffablePaths: ReadonlyArray<string>;\n /** Whether any incompleteness beyond the undiffable files exists. */\n readonly retryableGap: boolean;\n}\n\n/**\n * Split carried scope into paths a retry can settle and paths it never can.\n * Undiffable files are a property of the pull request, not a transient\n * reviewer-side failure: gate reasons and rendered callouts must never promise\n * they are \"retried automatically\" — the honest instruction is to remove them\n * from the pull request or exclude them with ignore globs.\n */\nexport const splitCarriedScope = (input: {\n readonly inputCoverage?: ReviewInputCoverage | undefined;\n readonly assurance?: ReviewAssurance | undefined;\n readonly unreviewedPaths?: ReadonlyArray<string> | undefined;\n}): CarriedScope => {\n const undiffable = new Set(input.inputCoverage?.undiffablePaths ?? []);\n const retryablePaths = (input.unreviewedPaths ?? []).filter((path) => !undiffable.has(path));\n const undiffablePaths = sortedUnique(undiffable);\n // Every non-undiffable coverage gap (range truncation, capacity overflow,\n // truncated or missing evidence, anchor surface) contributes its own reason\n // line, so a lone reason alongside undiffable paths means the undiffable\n // files are the entire gap.\n const coverageGapBeyondUndiffable =\n input.inputCoverage?.status === \"incomplete\" &&\n input.inputCoverage.reasons.length > (undiffablePaths.length > 0 ? 1 : 0);\n return {\n retryablePaths,\n undiffablePaths,\n retryableGap:\n input.assurance?.status === \"incomplete\" ||\n retryablePaths.length > 0 ||\n coverageGapBeyondUndiffable,\n };\n};\n\nconst anchorSurfaceAdjusted = (\n inputCoverage: ReviewInputCoverage,\n anchorFiles: ReadonlyArray<ChangedFile>,\n totalAnchorFiles: number,\n): ReviewInputCoverage =>\n anchorFiles.length >= totalAnchorFiles\n ? inputCoverage\n : ReviewInputCoverage.make({\n ...inputCoverage,\n status: \"incomplete\",\n reasons: [\n ...inputCoverage.reasons,\n `full pull-request anchor surface exposed ${anchorFiles.length} of ${totalAnchorFiles} required files`,\n ],\n });\n\n/** The flat reviewer's honest constant assurance: one pass, no verifier. */\nexport const flatAssurance = (): ReviewAssurance =>\n ReviewAssurance.make({\n status: \"unverified\",\n requiredGeneralDiscoveryPasses: 1,\n completedGeneralDiscoveryPasses: 1,\n requiredSpecialistPasses: 0,\n completedSpecialistPasses: 0,\n requiredVerificationPasses: 0,\n completedVerificationPasses: 0,\n discoveredCandidates: 0,\n confirmedCandidates: 0,\n rejectedCandidates: 0,\n unsettledCandidates: 0,\n discardedInvalidFindings: 0,\n failedPasses: [],\n reasons: [\n \"flat review has no independent candidate-verification pass; use the fan-out pipeline for a settled assurance result\",\n ],\n });\n\nexport interface FlatReviewAssessment {\n readonly inputCoverage: ReviewInputCoverage;\n readonly assurance: ReviewAssurance;\n /** Retryable evidence gaps (failed or missing diff reads), never undiffable paths. */\n readonly unreviewedPaths: ReadonlyArray<string>;\n}\n\n/**\n * Assess one settled flat run from its Run event trace: which required paths\n * received successful bounded diff evidence. This observes tool INPUT\n * assignment only — the host cannot know which evidence the model weighed.\n */\nexport const assessFlatReview = (input: {\n readonly files: ReadonlyArray<ChangedFile>;\n readonly totalFiles: number;\n readonly anchorFiles: ReadonlyArray<ChangedFile>;\n readonly totalAnchorFiles: number;\n readonly events: ReadonlyArray<RunEvent>;\n}): FlatReviewAssessment => {\n const trace = toolTrace(input.events);\n const requiredPaths = sortedUnique(input.files.map((file) => file.path));\n const assigned = new Set<string>();\n const partial = new Set<string>();\n const failedPaths = new Set<string>();\n for (const [toolCallId, declaration] of trace.declared) {\n if (declaration.toolName !== \"read_file_diff\") continue;\n const query = Schema.decodeUnknownOption(FileDiffQuery)(declaration.parameters);\n if (Option.isNone(query)) continue;\n const success = trace.succeeded.get(toolCallId);\n if (success !== undefined) {\n assigned.add(query.value.path);\n const view = Schema.decodeUnknownOption(FileDiffView)(success.result);\n if (Option.isSome(view) && view.value.truncated) partial.add(query.value.path);\n }\n if (trace.failed.has(toolCallId)) failedPaths.add(query.value.path);\n }\n const undiffable = new Set(\n input.files.filter((file) => !isReviewableFile(file)).map((file) => file.path),\n );\n const unassigned = requiredPaths.filter(\n (path) => !undiffable.has(path) && (!assigned.has(path) || failedPaths.has(path)),\n );\n const reasons: Array<string> = [];\n if (input.files.length < input.totalFiles) {\n reasons.push(\n `review range exposed ${input.files.length} of ${input.totalFiles} required files`,\n );\n }\n if (undiffable.size > 0) {\n reasons.push(\n boundedListReason(\"required paths have no reviewable diff or bounded text\", undiffable),\n );\n }\n if (failedPaths.size > 0) reasons.push(boundedListReason(\"diff reads failed\", failedPaths));\n if (partial.size > 0) {\n reasons.push(boundedListReason(\"model-visible diff evidence was truncated\", partial));\n }\n if (unassigned.length > 0) {\n reasons.push(boundedListReason(\"required paths received no successful diff input\", unassigned));\n }\n const inputCoverage = anchorSurfaceAdjusted(\n ReviewInputCoverage.make({\n status: reasons.length === 0 ? \"complete\" : \"incomplete\",\n requiredPaths,\n assignedPaths: sortedUnique(assigned),\n partialPaths: sortedUnique(partial),\n unassignedPaths: sortedUnique(unassigned),\n undiffablePaths: sortedUnique(undiffable),\n reasons,\n }),\n input.anchorFiles,\n input.totalAnchorFiles,\n );\n return {\n inputCoverage,\n assurance: flatAssurance(),\n // Everything still unreviewed and still part of the pull request carries\n // forward — undiffable paths included, so the check stays fail-closed\n // even after they leave the incremental delta.\n unreviewedPaths: sortedUnique([...unassigned, ...undiffable]),\n };\n};\n\n/**\n * Input coverage of one host-scheduled fan-out plan: which required paths the\n * bounded plan actually assigned complete evidence for. Capacity overflow and\n * undiffable paths are both real gaps; the pipeline carries them so the check\n * stays fail-closed until they are reviewed, removed, or explicitly ignored.\n */\nexport const fanOutInputCoverage = (input: {\n readonly plan: ReviewUnitPlan;\n readonly files: ReadonlyArray<ChangedFile>;\n readonly totalFiles: number;\n readonly anchorFiles: ReadonlyArray<ChangedFile>;\n readonly totalAnchorFiles: number;\n}): ReviewInputCoverage => {\n const plan = input.plan;\n const assignedPaths = sortedUnique(plan.units.flatMap((unit) => unit.paths));\n const unassignedPaths = sortedUnique(plan.unassignedPaths);\n const reasons: Array<string> = [];\n if (plan.truncated) {\n reasons.push(\n `review range exposed ${input.files.length} of ${input.totalFiles} required files`,\n );\n }\n if (plan.undiffablePaths.length > 0) {\n reasons.push(\n boundedListReason(\n \"required paths have no reviewable diff or bounded text\",\n plan.undiffablePaths,\n ),\n );\n }\n if (plan.partialEvidencePaths.length > 0) {\n reasons.push(\n boundedListReason(\n \"fan-out capacity left some deterministic evidence shards unassigned\",\n plan.partialEvidencePaths,\n ),\n );\n }\n if (plan.unassignedEvidenceShardCount > 0) {\n reasons.push(\n `${plan.unassignedEvidenceShardCount} deterministic evidence shard(s) exceeded fan-out capacity`,\n );\n reasons.push(\n boundedListReason(\n `unassigned evidence shard identifier sample (${plan.unassignedEvidenceShardIds.length} of ${plan.unassignedEvidenceShardCount})`,\n plan.unassignedEvidenceShardIds,\n ),\n );\n }\n if (plan.unassignedPaths.length > 0) {\n reasons.push(boundedListReason(\"fan-out capacity left paths unassigned\", plan.unassignedPaths));\n }\n return anchorSurfaceAdjusted(\n ReviewInputCoverage.make({\n status: reasons.length === 0 ? \"complete\" : \"incomplete\",\n requiredPaths: sortedUnique(input.files.map((file) => file.path)),\n assignedPaths,\n partialPaths: plan.partialEvidencePaths,\n unassignedPaths,\n undiffablePaths: sortedUnique(plan.undiffablePaths),\n reasons,\n }),\n input.anchorFiles,\n input.totalAnchorFiles,\n );\n};\n","import { Schema } from \"effect\";\n\nimport type { ChangedFile } from \"./diff.ts\";\nimport { ChangedPath, isReviewableFile } from \"./diff.ts\";\nimport {\n fileReviewEvidenceChunks,\n type FindingSeverity,\n MAX_PATCH_CHARS,\n type ReviewConcern,\n type ReviewFinding,\n} from \"./review-agent.ts\";\n\n// ---------------------------------------------------------------------------\n// Pure, deterministic planning for the fan-out reviewer: group the changeset\n// into bounded review units (the work one delegated child reviews) and merge\n// the children's findings back into one bounded review. Both operations are\n// plain functions so tests pin them directly and the coordinator's tool\n// surface stays deterministic — grouping is an algorithm, not model prose.\n// ---------------------------------------------------------------------------\n\n/** The delegation fan-out bound: one parent Run spawns at most this many children. */\nexport const MAX_REVIEW_UNITS = 8;\n\n/** A unit never carries more files than this, regardless of their size. */\nexport const MAX_UNIT_FILES = 12;\n\n/**\n * Bound the complete model-visible evidence assigned to one child. This is a\n * character bound rather than a token estimate because it is deterministic,\n * provider-independent, and enforced before any model call.\n */\nexport const UNIT_EVIDENCE_CHAR_BUDGET = 240_000;\n\n/** Maximum complete evidence shards placed in one child brief. */\nexport const MAX_UNIT_EVIDENCE_SHARDS = 12;\n\n/**\n * Keep overflow diagnostics bounded to one plan's total assignment capacity.\n * The plan separately records the exact overflow count and every affected\n * path, so identifiers are a deterministic diagnostic sample rather than the\n * authority for whether input coverage is complete.\n */\nexport const MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS = MAX_REVIEW_UNITS * MAX_UNIT_EVIDENCE_SHARDS;\n\n/** The merged review never exceeds the `CodeReview` findings bound. */\nexport const MAX_MERGED_FINDINGS = 20;\n\nexport const ReviewUnitId = Schema.NonEmptyString.check(Schema.isMaxLength(32));\n\n/** High-risk surfaces that receive an explicit specialist focus label. */\nexport const ReviewRiskCategory = Schema.Literals([\n \"authentication-authorization\",\n \"security-boundary\",\n \"persistence-durability\",\n \"concurrency\",\n \"credential-handling\",\n \"external-side-effects\",\n]);\nexport type ReviewRiskCategory = typeof ReviewRiskCategory.Type;\n\nexport const ReviewDiscoveryPerspective = Schema.Literals([\"general\", \"risk-specialist\"]);\nexport type ReviewDiscoveryPerspective = typeof ReviewDiscoveryPerspective.Type;\n\nexport const ReviewPassId = Schema.NonEmptyString.check(Schema.isMaxLength(64));\nexport const ReviewEvidenceShardId = Schema.NonEmptyString.check(Schema.isMaxLength(32));\n\n/** One complete bounded slice of a changed path's model-visible evidence. */\nexport class ReviewEvidenceShard extends Schema.Class<ReviewEvidenceShard>(\n \"@effect-agent/pr-review/ReviewEvidenceShard\",\n)({\n shardId: ReviewEvidenceShardId,\n path: ChangedPath,\n ordinal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n total: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n evidenceChars: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).check(\n Schema.isLessThanOrEqualTo(MAX_PATCH_CHARS),\n ),\n}) {}\n\nconst EvidenceShardIds = Schema.Array(ReviewEvidenceShardId)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_EVIDENCE_SHARDS));\n\n/** One required, independently scoped discovery attempt. */\nexport class ReviewDiscoveryPass extends Schema.Class<ReviewDiscoveryPass>(\n \"@effect-agent/pr-review/ReviewDiscoveryPass\",\n)({\n passId: ReviewPassId,\n unitId: ReviewUnitId,\n paths: Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_FILES)),\n evidenceShardIds: EvidenceShardIds,\n perspective: ReviewDiscoveryPerspective,\n /** Empty for the general pass; explicit deterministic focus for specialists. */\n riskCategories: Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6)),\n}) {}\n\n/** One bounded slice of the changeset delegated to one child reviewer. */\nexport class ReviewUnit extends Schema.Class<ReviewUnit>(\"@effect-agent/pr-review/ReviewUnit\")({\n unitId: ReviewUnitId,\n paths: Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_FILES)),\n evidenceShards: Schema.Array(ReviewEvidenceShard)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_EVIDENCE_SHARDS)),\n /** additions + deletions across the unit's files, for honest sizing. */\n changedLines: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Complete model-visible diff/content evidence assigned to each child. */\n evidenceChars: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).check(\n Schema.isLessThanOrEqualTo(UNIT_EVIDENCE_CHAR_BUDGET),\n ),\n /** Host-classified focus labels for the unit's redundant specialist pass. */\n riskCategories: Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6)),\n}) {}\n\n/** The complete deterministic fan-out plan over one changeset. */\nexport class ReviewUnitPlan extends Schema.Class<ReviewUnitPlan>(\n \"@effect-agent/pr-review/ReviewUnitPlan\",\n)({\n totalFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** True when the source returned fewer files than the pull request has. */\n truncated: Schema.Boolean,\n units: Schema.Array(ReviewUnit).check(Schema.isMaxLength(MAX_REVIEW_UNITS)),\n /** Exact discovery calls the coordinator must make. */\n discoveryPasses: Schema.Array(ReviewDiscoveryPass).check(\n Schema.isMaxLength(MAX_REVIEW_UNITS * 2),\n ),\n /** Changed files with neither a textual diff nor bounded base/head text. */\n undiffablePaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300)),\n /** Assigned paths with one or more evidence shards beyond plan capacity. */\n partialEvidencePaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300)),\n /** Exact number of shards beyond the bounded unit capacity. */\n unassignedEvidenceShardCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Bounded deterministic prefix of the unassigned shard identifiers. */\n unassignedEvidenceShardIds: Schema.Array(ReviewEvidenceShardId).check(\n Schema.isMaxLength(MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS),\n ),\n /**\n * Diffable files beyond the fan-out capacity (MAX_REVIEW_UNITS units of\n * MAX_UNIT_FILES files). Never silently dropped: the coordinator must name\n * them as unreviewed in its summary.\n */\n unassignedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300)),\n}) {}\n\nconst riskRules: ReadonlyArray<{\n readonly category: ReviewRiskCategory;\n readonly patterns: ReadonlyArray<RegExp>;\n}> = [\n {\n category: \"authentication-authorization\",\n patterns: [/auth/, /authoriz/, /permission/, /principal/, /access[-_ ]?control/, /role\\b/],\n },\n {\n category: \"security-boundary\",\n patterns: [\n /security/,\n /sandbox/,\n /untrusted/,\n /schema\\.decode/,\n /validation/,\n /injection/,\n /csrf/,\n /xss/,\n /path traversal/,\n ],\n },\n {\n category: \"persistence-durability\",\n patterns: [\n /durab/,\n /persist/,\n /storage/,\n /database/,\n /\\bsql\\b/,\n /journal/,\n /ledger/,\n /checkpoint/,\n /migration/,\n /transaction/,\n ],\n },\n {\n category: \"concurrency\",\n patterns: [\n /concurr/,\n /semaphore/,\n /\\bfiber/,\n /race/,\n /mutex/,\n /\\block\\b/,\n /queue/,\n /parallel/,\n /interrupt/,\n ],\n },\n {\n category: \"credential-handling\",\n patterns: [/credential/, /secret/, /password/, /api[-_ ]?key/, /bearer/, /hmac/, /signature/],\n },\n {\n category: \"external-side-effects\",\n patterns: [\n /publish/,\n /webhook/,\n /github/,\n /fetch\\(/,\n /http/,\n /send[-_ ]?(email|message)/,\n /write[-_ ]?(file|record)/,\n /delete/,\n /mutation/,\n /side[-_ ]?effect/,\n /spawn/,\n /exec/,\n ],\n },\n];\n\n/**\n * Deterministic host policy for specialist assignment. It intentionally\n * favors false positives: an extra bounded pass costs work, while a missed\n * high-risk classification removes redundancy. This is not a claim that the\n * keyword policy recognizes every semantically risky change.\n */\nexport const classifyReviewRisks = (file: ChangedFile): ReadonlyArray<ReviewRiskCategory> => {\n const text = [\n file.path,\n file.previousPath ?? \"\",\n file.patch ?? \"\",\n file.reviewBaseContent ?? \"\",\n file.reviewHeadContent ?? \"\",\n ]\n .join(\"\\n\")\n .toLowerCase();\n return riskRules\n .filter((rule) => rule.patterns.some((pattern) => pattern.test(text)))\n .map((rule) => rule.category);\n};\n\n/**\n * Whether every claimed finding anchor was present in the exact bounded\n * evidence shards assigned to one unit. This is stricter than checking the\n * full pull-request diff when an oversized path spans multiple units.\n */\nexport const findingAnchorInUnitEvidence = (\n finding: ReviewFinding,\n unit: ReviewUnit,\n files: ReadonlyArray<ChangedFile>,\n): boolean => {\n const file = files.find((candidate) => candidate.path === finding.path);\n if (file?.patch === undefined || finding.endLine < finding.startLine) return false;\n const assignedOrdinals = new Set(\n unit.evidenceShards\n .filter((shard) => shard.path === finding.path)\n .map((shard) => shard.ordinal),\n );\n const visibleLines = new Set<number>();\n const chunks = fileReviewEvidenceChunks(file);\n for (let index = 0; index < chunks.length; index += 1) {\n if (!assignedOrdinals.has(index + 1)) continue;\n for (const line of chunks[index]?.annotatedPatch.split(\"\\n\") ?? []) {\n const match = /^R(\\d+) /.exec(line);\n if (match?.[1] !== undefined) visibleLines.add(Number(match[1]));\n }\n }\n for (let line = finding.startLine; line <= finding.endLine; line += 1) {\n if (!visibleLines.has(line)) return false;\n }\n return true;\n};\n\ninterface PlannedEvidenceShard {\n readonly shard: ReviewEvidenceShard;\n readonly file: ChangedFile;\n readonly changedLines: number;\n}\n\nconst uniquePaths = (shards: ReadonlyArray<PlannedEvidenceShard>): ReadonlyArray<string> => [\n ...new Set(shards.map(({ shard }) => shard.path)),\n];\n\nconst plannedEvidenceShards = (\n files: ReadonlyArray<ChangedFile>,\n): ReadonlyArray<PlannedEvidenceShard> => {\n const planned: Array<PlannedEvidenceShard> = [];\n let shardIndex = 0;\n for (const file of files) {\n const chunks = fileReviewEvidenceChunks(file);\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n if (chunk === undefined) continue;\n shardIndex += 1;\n planned.push({\n shard: ReviewEvidenceShard.make({\n shardId: `shard-${String(shardIndex).padStart(4, \"0\")}`,\n path: file.path,\n ordinal: index + 1,\n total: chunks.length,\n evidenceChars: chunk.annotatedPatch.length,\n }),\n file,\n changedLines: index === 0 ? file.additions + file.deletions : 0,\n });\n }\n }\n return planned;\n};\n\nconst unitOf = (index: number, shards: ReadonlyArray<PlannedEvidenceShard>): ReviewUnit =>\n ReviewUnit.make({\n unitId: `unit-${String(index + 1).padStart(3, \"0\")}`,\n paths: uniquePaths(shards),\n evidenceShards: shards.map(({ shard }) => shard),\n changedLines: shards.reduce((total, shard) => total + shard.changedLines, 0),\n evidenceChars: shards.reduce((total, { shard }) => total + shard.evidenceChars, 0),\n riskCategories: [...new Set(shards.flatMap(({ file }) => classifyReviewRisks(file)))],\n });\n\nconst discoveryPassesFor = (units: ReadonlyArray<ReviewUnit>): ReadonlyArray<ReviewDiscoveryPass> =>\n units.flatMap((unit) => [\n ReviewDiscoveryPass.make({\n passId: `${unit.unitId}-general`,\n unitId: unit.unitId,\n paths: unit.paths,\n evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),\n perspective: \"general\",\n riskCategories: [],\n }),\n ReviewDiscoveryPass.make({\n passId: `${unit.unitId}-specialist`,\n unitId: unit.unitId,\n paths: unit.paths,\n evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),\n perspective: \"risk-specialist\",\n riskCategories: unit.riskCategories,\n }),\n ]);\n\n/**\n * Group the changeset into at most `MAX_REVIEW_UNITS` review units.\n *\n * Deterministic by construction: files are ordered by path (so files sharing\n * a directory become neighbors — directory affinity without a heuristic),\n * then split into complete line-bounded evidence shards and packed greedily\n * under the hard evidence and per-unit shard bounds. Capacity is finite and\n * explicit:\n *\n * - files without a textual diff are still delegated when the source\n * recovered complete bounded UTF-8 base/head content. Findings from that\n * evidence cannot anchor inline and are reported as concerns;\n * - files with neither form of textual evidence surface in\n * `undiffablePaths` instead of laundering missing coverage;\n * - an oversized path spans as many deterministic shards and units as needed;\n * - shards beyond `MAX_REVIEW_UNITS` full units surface explicitly, so a path\n * is partial only when finite plan capacity is genuinely exhausted.\n */\nexport const planReviewUnits = (\n files: ReadonlyArray<ChangedFile>,\n options: { readonly totalChangedFiles: number },\n): ReviewUnitPlan => {\n const ordered = [...files].sort((left, right) => (left.path < right.path ? -1 : 1));\n const reviewable = ordered.filter(isReviewableFile);\n const undiffable = ordered.filter((file) => !isReviewableFile(file));\n\n const shards = plannedEvidenceShards(reviewable);\n const groups: Array<Array<PlannedEvidenceShard>> = [];\n const unassigned: Array<PlannedEvidenceShard> = [];\n let current: Array<PlannedEvidenceShard> = [];\n let currentEvidenceChars = 0;\n for (const shard of shards) {\n const nextPaths = new Set([...uniquePaths(current), shard.shard.path]);\n const wouldOverflow =\n current.length >= MAX_UNIT_EVIDENCE_SHARDS ||\n nextPaths.size > MAX_UNIT_FILES ||\n (current.length > 0 &&\n currentEvidenceChars + shard.shard.evidenceChars > UNIT_EVIDENCE_CHAR_BUDGET);\n if (wouldOverflow) {\n groups.push(current);\n current = [];\n currentEvidenceChars = 0;\n }\n if (groups.length >= MAX_REVIEW_UNITS) {\n unassigned.push(shard);\n continue;\n }\n current.push(shard);\n currentEvidenceChars += shard.shard.evidenceChars;\n }\n if (current.length > 0 && groups.length < MAX_REVIEW_UNITS) {\n groups.push(current);\n }\n\n const units = groups.map((group, index) => unitOf(index, group));\n const assignedShardIds = new Set(\n units.flatMap((unit) => unit.evidenceShards.map((shard) => shard.shardId)),\n );\n const assignedPaths = new Set(\n shards\n .filter(({ shard }) => assignedShardIds.has(shard.shardId))\n .map(({ shard }) => shard.path),\n );\n const unassignedPathsWithEvidence = new Set(unassigned.map(({ shard }) => shard.path));\n return ReviewUnitPlan.make({\n totalFiles: files.length,\n truncated: files.length < options.totalChangedFiles,\n units,\n discoveryPasses: discoveryPassesFor(units),\n undiffablePaths: undiffable.map((file) => file.path),\n partialEvidencePaths: [...unassignedPathsWithEvidence].filter((path) =>\n assignedPaths.has(path),\n ),\n unassignedEvidenceShardCount: unassigned.length,\n unassignedEvidenceShardIds: unassigned\n .slice(0, MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS)\n .map(({ shard }) => shard.shardId),\n unassignedPaths: [...unassignedPathsWithEvidence].filter((path) => !assignedPaths.has(path)),\n });\n};\n\nconst severityRank: Record<FindingSeverity, number> = {\n blocking: 0,\n important: 1,\n nit: 2,\n};\n\nconst anchorKey = (finding: ReviewFinding): string =>\n `${finding.path} ${finding.startLine} ${finding.endLine}`;\n\n/**\n * Merge the children's findings into one bounded, deterministic list: dedupe\n * findings sharing an anchor (path + line range) keeping the most severe —\n * and, at equal severity, the first in declaration order — then rank by\n * severity, path, and line, and cap at the `CodeReview` findings bound.\n * This is the merge policy the coordinator's instructions state in prose;\n * pinning it here keeps the policy itself deterministic and testable.\n */\nexport const rankAndDedupeFindings = (\n findings: ReadonlyArray<ReviewFinding>,\n): ReadonlyArray<ReviewFinding> => {\n const byAnchor = new Map<string, ReviewFinding>();\n for (const finding of findings) {\n const key = anchorKey(finding);\n const existing = byAnchor.get(key);\n if (\n existing === undefined ||\n severityRank[finding.severity] < severityRank[existing.severity]\n ) {\n byAnchor.set(key, finding);\n }\n }\n return [...byAnchor.values()]\n .sort((left, right) => {\n const bySeverity = severityRank[left.severity] - severityRank[right.severity];\n if (bySeverity !== 0) return bySeverity;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return left.startLine - right.startLine;\n })\n .slice(0, MAX_MERGED_FINDINGS);\n};\n\n/**\n * Stable identity for one concern. The paths are part of the claim: identical\n * prose about two independent files must not collapse into one item.\n */\nexport const reviewConcernKey = (concern: ReviewConcern): string =>\n `${(concern.evidencePaths ?? []).join(\"\\u0000\")}\\u0001${concern.title}\\u0000${concern.body}`;\n\n/**\n * The concern analogue of `rankAndDedupeFindings`: dedupe by exact scoped\n * content keeping the most severe duplicate, rank by severity, and cap at the\n * `CodeReview` concerns bound.\n */\nexport const rankAndDedupeConcerns = (\n concerns: ReadonlyArray<ReviewConcern>,\n): ReadonlyArray<ReviewConcern> => {\n const byContent = new Map<string, ReviewConcern>();\n for (const concern of concerns) {\n const key = reviewConcernKey(concern);\n const previous = byContent.get(key);\n if (\n previous === undefined ||\n severityRank[concern.severity] < severityRank[previous.severity]\n ) {\n byContent.set(key, concern);\n }\n }\n return [...byContent.values()]\n .sort((left, right) => severityRank[left.severity] - severityRank[right.severity])\n .slice(0, 10);\n};\n","import { Effect, Schema } from \"effect\";\nimport {\n Agent,\n AgentPolicy,\n AgentRuntime,\n ToolResultBounds,\n type BudgetAdapterError,\n type BudgetExceeded,\n type RunBudgetHook,\n type RuntimeBinding,\n} from \"effect-agent\";\nimport { Toolkit } from \"effect/unstable/ai\";\n\nimport type { PriorReviewContext } from \"./adjudication.ts\";\nimport { anchorViolation } from \"./anchors.ts\";\nimport { boundedListReason, FailedReviewPass, ReviewAssurance } from \"./coverage.ts\";\nimport { ChangedFileStatus, ChangedPath, type ChangedFile } from \"./diff.ts\";\nimport {\n CodeReview,\n fileReviewEvidenceChunks,\n MAX_PATCH_CHARS,\n MAX_WALKTHROUGH_SUMMARY_CHARS,\n REVIEW_TOOL_RESULT_MAX_BYTES,\n ReviewConcern,\n ReviewFinding,\n WalkthroughEntry,\n} from \"./review-agent.ts\";\nimport {\n MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS,\n MAX_REVIEW_UNITS,\n MAX_UNIT_EVIDENCE_SHARDS,\n MAX_UNIT_FILES,\n findingAnchorInUnitEvidence,\n planReviewUnits,\n rankAndDedupeConcerns,\n rankAndDedupeFindings,\n ReviewDiscoveryPass,\n ReviewEvidenceShardId,\n ReviewPassId,\n ReviewRiskCategory,\n ReviewUnit,\n ReviewUnitId,\n ReviewUnitPlan,\n} from \"./review-units.ts\";\n\n// ---------------------------------------------------------------------------\n// The assured fan-out reviewer is a bounded, deterministic three-stage\n// pipeline scheduled ENTIRELY by host code:\n//\n// host plan -> independent discovery passes -> independent verification\n//\n// `planReviewUnits` is a pure function, so dispatch is plain Effect structured\n// concurrency over its exact work list — there is no coordinator model, no\n// delegation tool, and therefore no prompt-compliance failure mode. A pass\n// that fails (child fault, malformed output) is retried once; a pass that\n// still fails is recorded and its unit's paths are carried forward as\n// retryable unreviewed scope instead of freezing the run's continuity\n// baseline. A finding whose anchor is invalid is discarded and counted —\n// never a reason to reject the whole pass.\n// ---------------------------------------------------------------------------\n\n/** One discovery pass returns at most this many anchored candidates. */\nexport const MAX_CHILD_FINDINGS = 6;\n\n/** One discovery pass returns at most this many non-anchored candidates. */\nexport const MAX_CHILD_CONCERNS = 3;\n\n/** Every unit receives independent general and specialist discovery passes. */\nexport const MAX_UNIT_CANDIDATES = (MAX_CHILD_FINDINGS + MAX_CHILD_CONCERNS) * 2;\n\n/**\n * General + specialist discovery for every unit, then one verifier per unit.\n * The one-retry budget doubles the worst-case child Run count, but the\n * schedule itself never exceeds this bound.\n */\nexport const MAX_REVIEW_CHILDREN = MAX_REVIEW_UNITS * 3;\n\n/** Bounded structured concurrency across units; passes inside a unit are sequential. */\nexport const REVIEW_UNIT_CONCURRENCY = 4;\n\n/** Structural minimum for a child that exposes no tools. */\nexport const MAX_FILE_REVIEW_TOOL_CALLS = 1;\n\nexport const ReviewWorkPhase = Schema.Literals([\"discovery\", \"verification\"]);\nexport type ReviewWorkPhase = typeof ReviewWorkPhase.Type;\n\nexport const ReviewWorkPerspective = Schema.Literals([\n \"general\",\n \"risk-specialist\",\n \"candidate-verification\",\n]);\nexport type ReviewWorkPerspective = typeof ReviewWorkPerspective.Type;\n\nexport const ReviewCandidateId = Schema.NonEmptyString.check(Schema.isMaxLength(96));\n\nexport class FindingCandidate extends Schema.TaggedClass<FindingCandidate>()(\"FindingCandidate\", {\n candidateId: ReviewCandidateId,\n workId: ReviewPassId,\n unitId: ReviewUnitId,\n finding: ReviewFinding,\n evidencePaths: Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(1)),\n}) {}\n\nexport class ConcernCandidate extends Schema.TaggedClass<ConcernCandidate>()(\"ConcernCandidate\", {\n candidateId: ReviewCandidateId,\n workId: ReviewPassId,\n unitId: ReviewUnitId,\n concern: ReviewConcern,\n evidencePaths: Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(3)),\n}) {}\n\nexport const ReviewCandidate = Schema.Union([FindingCandidate, ConcernCandidate]);\nexport type ReviewCandidate = typeof ReviewCandidate.Type;\n\n/** Deterministic host equivalence for claims repeated across discovery passes. */\nexport const reviewCandidateSubjectKey = (candidate: ReviewCandidate): string =>\n candidate._tag === \"FindingCandidate\"\n ? `finding:${JSON.stringify(Schema.encodeSync(ReviewFinding)(candidate.finding))}`\n : `concern:${JSON.stringify(Schema.encodeSync(ReviewConcern)(candidate.concern))}`;\n\nexport class CandidateAssessment extends Schema.Class<CandidateAssessment>(\n \"@effect-agent/pr-review/CandidateAssessment\",\n)({\n candidateId: ReviewCandidateId,\n disposition: Schema.Literals([\"confirmed\", \"rejected\"]),\n /**\n * Exact suggestion settlement: required when the candidate finding carries\n * a suggestion, forbidden otherwise. Untrusted child output cannot publish\n * a GitHub replacement block by prompt compliance alone — the host keeps a\n * confirmed finding's suggestion only on an exact \"committable\" settlement.\n */\n suggestion: Schema.optionalKey(\n Schema.Literals([\"committable\", \"not-committable\"]).annotate({\n description:\n 'Required exactly when the candidate finding carries a suggestion: \"committable\" only when its text is the full replacement source for exactly lines startLine..endLine and nothing else. Forbidden for candidates without a suggestion.',\n }),\n ),\n rationale: Schema.NonEmptyString.check(Schema.isMaxLength(600)),\n}) {}\n\n/**\n * Exact suggestion settlement shape: a carried suggestion must be settled and\n * nothing else may be. A verification report that violates it is treated as a\n * misbehaving pass and retried within the pass budget.\n */\nexport const assessmentSettlesSuggestionExactly = (\n assessment: CandidateAssessment,\n candidate: ReviewCandidate,\n): boolean =>\n candidate._tag === \"FindingCandidate\" && candidate.finding.suggestion !== undefined\n ? assessment.suggestion !== undefined\n : assessment.suggestion === undefined;\n\n/**\n * Fail-closed publication of a confirmed finding: only an exact \"committable\"\n * settlement keeps the suggestion; anything else publishes the finding with\n * the suggestion stripped so unverified text can never become a one-click\n * GitHub replacement block.\n */\nexport const confirmedFindingForPublication = (\n assessment: CandidateAssessment,\n candidate: FindingCandidate,\n): ReviewFinding => {\n if (candidate.finding.suggestion === undefined || assessment.suggestion === \"committable\") {\n return candidate.finding;\n }\n const { suggestion: _stripped, ...finding } = candidate.finding;\n return ReviewFinding.make(finding);\n};\n\n/**\n * Concern candidates need explicit paths internally to bind the claim to\n * scheduled evidence. The verifier receives the complete bounded unit so it\n * can use neighboring evidence to falsify the claim. The host copies these\n * validated paths onto a confirmed public concern for incremental continuity.\n */\nexport class DiscoveredConcern extends Schema.Class<DiscoveredConcern>(\n \"@effect-agent/pr-review/DiscoveredConcern\",\n)({\n concern: ReviewConcern,\n evidencePaths: Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(3)),\n}) {}\n\nconst UnitPaths = Schema.Array(ChangedPath)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_FILES));\n\n/** Bounded prior-review context lines injected into discovery instructions. */\nconst UnitContextLines = Schema.Array(Schema.String.check(Schema.isMaxLength(1_200))).check(\n Schema.isMaxLength(20),\n);\n\nconst RiskCategories = Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6));\nconst Candidates = Schema.Array(ReviewCandidate).check(Schema.isMaxLength(MAX_UNIT_CANDIDATES));\nconst EvidenceShardIds = Schema.Array(ReviewEvidenceShardId)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_EVIDENCE_SHARDS));\n\n/** One complete host-selected evidence shard supplied to a review child. */\nexport class FileReviewEvidence extends Schema.Class<FileReviewEvidence>(\n \"@effect-agent/pr-review/FileReviewEvidence\",\n)({\n shardId: ReviewEvidenceShardId,\n path: ChangedPath,\n status: ChangedFileStatus,\n reviewMode: Schema.Literals([\"diff\", \"content\", \"unavailable\"]),\n ordinal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n total: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n annotatedPatch: Schema.String.check(Schema.isMaxLength(MAX_PATCH_CHARS)),\n}) {}\n\n/** Host-prepared child input with complete bounded diff/content evidence. */\nexport class FileReviewBrief extends Schema.Class<FileReviewBrief>(\n \"@effect-agent/pr-review/FileReviewBrief\",\n)({\n phase: ReviewWorkPhase,\n workId: ReviewPassId,\n unitId: ReviewUnitId,\n paths: UnitPaths,\n evidenceShardIds: EvidenceShardIds,\n perspective: ReviewWorkPerspective,\n riskCategories: RiskCategories,\n /** Empty for discovery; the exact discovered set for unit verification. */\n candidates: Candidates,\n evidence: Schema.Array(FileReviewEvidence)\n .check(Schema.isMinLength(1))\n .check(Schema.isMaxLength(MAX_UNIT_EVIDENCE_SHARDS)),\n /** Maintainer-adjudicated identities on this unit; do not re-raise. */\n adjudicatedContext: Schema.optionalKey(UnitContextLines),\n /** Prior-round findings on this unit's re-reviewed paths. */\n priorFindingContext: Schema.optionalKey(UnitContextLines),\n}) {}\n\n/** Child output; phase-inapplicable collections must be empty. */\nexport class FileReviewReport extends Schema.Class<FileReviewReport>(\n \"@effect-agent/pr-review/FileReviewReport\",\n)({\n phase: ReviewWorkPhase,\n workId: ReviewPassId,\n unitId: ReviewUnitId,\n findings: Schema.Array(ReviewFinding).check(Schema.isMaxLength(MAX_CHILD_FINDINGS)),\n concerns: Schema.Array(DiscoveredConcern).check(Schema.isMaxLength(MAX_CHILD_CONCERNS)),\n fileSummaries: Schema.Array(WalkthroughEntry).check(Schema.isMaxLength(MAX_UNIT_FILES)),\n assessments: Schema.Array(CandidateAssessment).check(Schema.isMaxLength(MAX_UNIT_CANDIDATES)),\n}) {}\n\n/**\n * A structurally valid child report that does not answer the scheduled pass:\n * wrong identity, phase-inapplicable fields, or an inexact assessment set.\n * Retried once like any other pass fault, because it is model misbehavior,\n * not evidence about the code under review.\n */\nexport class ReviewPassMisbehaved extends Schema.TaggedError<ReviewPassMisbehaved>()(\n \"ReviewPassMisbehaved\",\n {\n workId: ReviewPassId,\n reason: Schema.NonEmptyString.check(Schema.isMaxLength(600)),\n },\n) {}\n\nexport interface FanOutInstructionOptions {\n readonly guidance?: string | ReadonlyArray<string> | undefined;\n}\n\nconst staticGuidanceLines = (\n guidance: string | ReadonlyArray<string> | undefined,\n): ReadonlyArray<string> => {\n if (guidance === undefined) return [];\n const lines = typeof guidance === \"string\" ? [guidance] : guidance;\n return lines.filter((line) => line.length > 0);\n};\n\nconst evidenceInstructions = [\n \"The host placed complete bounded review evidence shards in the input evidence array. Treat every shard as required input; ordinal/total identifies multi-shard paths.\",\n \"You have no tools and cannot roam outside this evidence. If it is insufficient for a candidate, reject or omit that candidate rather than guessing.\",\n \"A diff marks new-version anchors as R<number>; only those lines may anchor findings. B/H content evidence is non-anchorable.\",\n];\n\n/** Discovery and verification instructions share one child definition. */\nexport const makeFileReviewerInstructions =\n (options: FanOutInstructionOptions = {}) =>\n (brief: FileReviewBrief): string => {\n const common = [\n `You are an attached review worker for ${brief.workId} in host-planned unit ${brief.unitId}: ${brief.paths.join(\", \")}.`,\n ...staticGuidanceLines(options.guidance),\n ...evidenceInstructions,\n ];\n if (brief.phase === \"verification\") {\n return [\n ...common,\n \"Independently verify every candidate in the input. You did not receive another reviewer's transcript or reasoning; use only the candidate claim and bounded evidence.\",\n \"The evidence array contains the complete bounded unit, including neighboring changed code that may confirm or falsify a locally plausible claim.\",\n \"For each candidate, try to falsify it first. Confirm only when the cited behavior is supported and actionable. Reject unsupported, speculative, duplicate, or non-actionable candidates.\",\n 'Return ONLY JSON with phase \"verification\", the exact workId/unitId, empty findings/concerns/fileSummaries arrays, and exactly one assessment per candidateId. Each assessment is {\"candidateId\": <exact id>, \"disposition\": <\"confirmed\" | \"rejected\">, \"suggestion\": <\"committable\" | \"not-committable\", present exactly when the candidate finding carries a suggestion>, \"rationale\": <bounded evidence-based reason>}. Never add or omit an id.',\n 'Settle every carried suggestion independently of the claim: answer \"committable\" only when its text is the full replacement source for exactly lines startLine..endLine and nothing else — it compiles in context and preserves the finding\\'s intent, never prose describing a change. Otherwise answer \"not-committable\"; the host then publishes the confirmed finding without its suggestion. Omit the assessment \"suggestion\" field for candidates without one.',\n ].join(\"\\n\");\n }\n const focus =\n brief.perspective === \"risk-specialist\"\n ? brief.riskCategories.length > 0\n ? `This is a fresh specialist discovery pass. Concentrate on these host-classified risks without relying on another pass: ${brief.riskCategories.join(\", \")}.`\n : \"This is a fresh specialist discovery pass. The host found no keyword-classified category, so independently scrutinize authentication/authorization, security boundaries, durability, concurrency, credentials, and external side effects rather than treating classification silence as low risk.\"\n : \"This is the general discovery pass. Review broadly for correctness, security, concurrency, resource, API, and error-handling defects.\";\n const adjudicated = brief.adjudicatedContext ?? [];\n const priorFindings = brief.priorFindingContext ?? [];\n return [\n ...common,\n focus,\n ...(adjudicated.length === 0\n ? []\n : [\n \"A maintainer has adjudicated these previously raised items on this unit (disposition, reason). Do not re-raise them unless you have materially new evidence, and if you do, say explicitly what changed since the adjudication:\",\n ...adjudicated.map((line) => `- ${line}`),\n ]),\n ...(priorFindings.length === 0\n ? []\n : [\n \"A previous review round raised these findings on this unit's paths. For each, either confirm it still holds, state that it is fixed, or withdraw it; do not demand the opposite of that prior guidance without explicitly acknowledging the reversal:\",\n ...priorFindings.map((line) => `- ${line}`),\n ]),\n \"The discovery evidence array contains every complete shard in the unit. Review every entry and every shard of a multi-shard path. A later independent verifier, not you, decides which candidates publish.\",\n \"Every non-anchored concern must list 1-3 exact evidencePaths to bind the claim to scheduled evidence. Report one root concern once; never split it into differently worded restatements.\",\n `Return ONLY JSON with phase \"discovery\", the exact workId/unitId, up to ${MAX_CHILD_FINDINGS} findings, up to ${MAX_CHILD_CONCERNS} concerns shaped as {concern, evidencePaths}, one factual file summary per path (<= ${MAX_WALKTHROUGH_SUMMARY_CHARS} chars), and an empty assessments array. Empty candidate arrays are valid; do not invent defects.`,\n 'Each finding is {\"path\": <a unit file path>, \"startLine\": <integer, an R-marked new-file line>, \"endLine\": <integer, >= startLine, same file, R-marked>, \"severity\": <\"blocking\" | \"important\" | \"nit\">, \"category\": <OPTIONAL problem-kind label>, \"title\": <string, <= 120 chars>, \"body\": <string, why it matters and what to do>, \"suggestion\": <string, OPTIONAL: replacement source code for exactly lines startLine..endLine, ready to commit>}.',\n 'Include \"suggestion\" only when you are confident the replacement compiles and preserves intent; its text must contain the full replacement source for every line in the range and nothing else — never prose describing the change, which belongs in \"body\".',\n ].join(\"\\n\");\n };\n\nexport const fileReviewerInstructions = makeFileReviewerInstructions();\n\nexport const FileReviewToolkit = Toolkit.empty;\n\nexport const defaultFileReviewerPolicy = AgentPolicy.make({\n maxTurns: 6,\n maxToolCalls: MAX_FILE_REVIEW_TOOL_CALLS,\n maxDuration: \"6 minutes\",\n toolConcurrency: 2,\n repeatedFailureLimit: 6,\n tokenBudget: 200_000,\n contextTokenLimit: 150_000,\n toolResultBounds: ToolResultBounds.make({ maxBytes: REVIEW_TOOL_RESULT_MAX_BYTES }),\n // Discovery or verification that exhausts is unsettled work, never a\n // schema-valid partial that can contribute to a green assurance claim.\n onExhaustion: \"fail\",\n});\n\nexport const makeFileReviewerDefinition = (options: FanOutInstructionOptions = {}) =>\n Agent.define(\"pr-review-worker\", {\n input: FileReviewBrief,\n output: FileReviewReport,\n instructions: makeFileReviewerInstructions(options),\n toolkit: FileReviewToolkit,\n policy: defaultFileReviewerPolicy,\n description:\n \"Perform one bounded discovery or independent candidate-verification pass over host-supplied pull-request evidence.\",\n metadata: { deploymentClass: \"E\", surface: \"read-only\", stage: \"discovery-verification\" },\n });\n\nexport const FileReviewer = makeFileReviewerDefinition();\n\n/** The exact child binding shape the host pipeline schedules. */\nexport type FileReviewerBinding<Provider, ModelProvides, ModelRequires> = RuntimeBinding<\n typeof FileReviewBrief,\n typeof FileReviewReport,\n ReturnType<typeof makeFileReviewerInstructions>,\n Toolkit.Tools<typeof FileReviewToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n>;\n\n// ---------------------------------------------------------------------------\n// Host pipeline.\n// ---------------------------------------------------------------------------\n\n/** Everything one settled fan-out pipeline run produced, before publication. */\nexport interface FanOutPipelineOutcome {\n readonly review: CodeReview;\n readonly assurance: ReviewAssurance;\n readonly plan: ReviewUnitPlan;\n /** Paths of units with an unsettled pass — retryable scope for the next run. */\n readonly unreviewedPaths: ReadonlyArray<string>;\n /** Failed stages paired with the leftover paths they still own. */\n readonly unreviewedPasses: ReadonlyArray<{\n readonly stage: FailedReviewPass[\"stage\"];\n readonly paths: ReadonlyArray<string>;\n }>;\n /** Total settled child turns across every scheduled pass. */\n readonly turns: number;\n}\n\nexport interface FanOutPipelineInput {\n readonly files: ReadonlyArray<ChangedFile>;\n readonly anchorFiles: ReadonlyArray<ChangedFile>;\n readonly totalChangedFiles: number;\n readonly maxFindings?: number | undefined;\n /** Shared run budget observed by every child pass. */\n readonly budget?: RunBudgetHook<BudgetExceeded | BudgetAdapterError> | undefined;\n /**\n * Unchanged leftovers from prior failed passes. Every stage stays attached\n * to its own paths; failed verification reopens both discovery perspectives\n * for only those paths because candidate payloads are not persisted.\n */\n readonly retry?:\n | {\n readonly passes?: ReadonlyArray<{\n readonly stage: FailedReviewPass[\"stage\"];\n readonly paths: ReadonlyArray<string>;\n }>;\n /** @deprecated Pass path-bound `passes`; this flat form cannot preserve ownership. */\n readonly paths?: ReadonlyArray<string>;\n /** @deprecated Pass path-bound `passes`; this flat form cannot preserve ownership. */\n readonly stages?: ReadonlyArray<FailedReviewPass[\"stage\"]>;\n }\n | undefined;\n /**\n * Adjudicated identities and prior-round findings injected as discovery\n * context on the units whose paths they touch. Context only — they never\n * enter candidates or publication.\n */\n readonly priorContext?: PriorReviewContext | undefined;\n}\n\nconst candidateOrdinal = (index: number): string => String(index + 1).padStart(3, \"0\");\n\n/** Rebuild one unit's complete evidence from the same snapshot the plan used. */\nconst unitEvidence = (\n unit: ReviewUnit,\n files: ReadonlyArray<ChangedFile>,\n): Effect.Effect<ReadonlyArray<FileReviewEvidence>> =>\n Effect.gen(function* () {\n const byPath = new Map(files.map((file) => [file.path, file] as const));\n const evidence: Array<FileReviewEvidence> = [];\n for (const shard of unit.evidenceShards) {\n const file = byPath.get(shard.path);\n const chunk =\n file === undefined ? undefined : fileReviewEvidenceChunks(file)[shard.ordinal - 1];\n if (file === undefined || chunk === undefined) {\n // The plan and this evidence derive from the same immutable snapshot\n // via the same pure function; a mismatch is a host defect, not input.\n return yield* Effect.die(\n new Error(`planned evidence shard has no source: ${shard.shardId} (${shard.path})`),\n );\n }\n evidence.push(\n FileReviewEvidence.make({\n shardId: shard.shardId,\n path: shard.path,\n status: file.status,\n reviewMode: chunk.reviewMode,\n ordinal: shard.ordinal,\n total: shard.total,\n annotatedPatch: chunk.annotatedPatch,\n }),\n );\n }\n return evidence;\n });\n\ninterface SettledPass {\n readonly report: FileReviewReport;\n readonly turns: number;\n}\n\ntype PassOutcome =\n | ({ readonly _tag: \"settled\" } & SettledPass)\n | { readonly _tag: \"failed\"; readonly errorTag: string };\n\nconst misbehaved = (workId: string, reason: string) =>\n ReviewPassMisbehaved.make({ workId, reason: reason.slice(0, 600) });\n\n/** Validate that a verification report assesses exactly the scheduled candidates. */\nconst validateVerificationReport = (\n brief: FileReviewBrief,\n report: FileReviewReport,\n): ReviewPassMisbehaved | undefined => {\n if (report.findings.length > 0 || report.concerns.length > 0 || report.fileSummaries.length > 0) {\n return misbehaved(brief.workId, \"verification output contained discovery-only fields\");\n }\n const expectedById = new Map(\n brief.candidates.map((candidate) => [candidate.candidateId, candidate] as const),\n );\n const assessedIds = new Set<string>();\n for (const assessment of report.assessments) {\n const candidate = expectedById.get(assessment.candidateId);\n if (candidate === undefined || assessedIds.has(assessment.candidateId)) {\n return misbehaved(brief.workId, \"verification output did not assess the exact candidate set\");\n }\n if (!assessmentSettlesSuggestionExactly(assessment, candidate)) {\n return misbehaved(\n brief.workId,\n \"verification output did not settle suggestion publication exactly\",\n );\n }\n assessedIds.add(assessment.candidateId);\n }\n if (assessedIds.size !== expectedById.size) {\n return misbehaved(brief.workId, \"verification output did not assess the exact candidate set\");\n }\n return undefined;\n};\n\n/**\n * Run one scheduled pass: execute the child, decode its report, and enforce\n * the pass contract. Any typed fault — child failure, malformed or misdirected\n * output — is retried once; budget exhaustion is terminal because a retry\n * would fail the same way. The settled outcome is a value either way, so one\n * flaky pass can never fail the whole pipeline.\n */\nconst runReviewPass = <Provider, ModelProvides, ModelRequires>(\n binding: FileReviewerBinding<Provider, ModelProvides, ModelRequires>,\n brief: FileReviewBrief,\n budget: RunBudgetHook<BudgetExceeded | BudgetAdapterError> | undefined,\n) =>\n Effect.gen(function* () {\n const result = yield* AgentRuntime.run(binding, brief, {\n ...(budget === undefined ? {} : { budget }),\n estimateCostMicrousd: () => Effect.succeed(500),\n });\n const report = yield* Schema.decodeUnknownEffect(FileReviewReport)(result.output).pipe(\n Effect.mapError((error) =>\n misbehaved(brief.workId, `child report failed to decode: ${error.message}`),\n ),\n );\n if (\n report.phase !== brief.phase ||\n report.workId !== brief.workId ||\n report.unitId !== brief.unitId\n ) {\n return yield* misbehaved(\n brief.workId,\n \"child report identity does not match the scheduled pass\",\n );\n }\n if (brief.phase === \"verification\") {\n const violation = validateVerificationReport(brief, report);\n if (violation !== undefined) return yield* violation;\n } else if (report.assessments.length > 0) {\n return yield* misbehaved(\n brief.workId,\n \"discovery output contained verification-only assessments\",\n );\n }\n return { report, turns: result.turns } satisfies SettledPass;\n }).pipe(\n Effect.scoped,\n Effect.retry({ times: 1, while: (error) => error._tag !== \"BudgetExceeded\" }),\n Effect.map((settled): PassOutcome => ({ _tag: \"settled\", ...settled })),\n Effect.catch((error) =>\n Effect.succeed<PassOutcome>({ _tag: \"failed\", errorTag: String(error._tag).slice(0, 256) }),\n ),\n );\n\ninterface DiscoveryHarvest {\n readonly candidates: ReadonlyArray<ReviewCandidate>;\n readonly fileSummaries: ReadonlyArray<WalkthroughEntry>;\n readonly discarded: number;\n}\n\n/**\n * Keep only findings anchored inside the pass's exact assigned evidence and\n * concerns bound to unit paths. Everything else is discarded and counted —\n * an invalid anchor invalidates one claim, never the pass that produced it.\n */\nconst harvestDiscovery = (\n pass: ReviewDiscoveryPass,\n unit: ReviewUnit,\n files: ReadonlyArray<ChangedFile>,\n anchorFiles: ReadonlyArray<ChangedFile>,\n report: FileReviewReport,\n): DiscoveryHarvest => {\n const allowed = new Set(pass.paths);\n let discarded = 0;\n const keptFindings: Array<ReviewFinding> = [];\n for (const finding of report.findings) {\n if (\n !allowed.has(finding.path) ||\n anchorViolation(finding, anchorFiles) !== undefined ||\n !findingAnchorInUnitEvidence(finding, unit, files)\n ) {\n discarded += 1;\n continue;\n }\n keptFindings.push(finding);\n }\n const keptConcerns: Array<DiscoveredConcern> = [];\n for (const candidate of report.concerns) {\n if (candidate.evidencePaths.some((path) => !allowed.has(path))) {\n discarded += 1;\n continue;\n }\n keptConcerns.push(candidate);\n }\n return {\n candidates: [\n ...keptFindings.map((finding, index) =>\n FindingCandidate.make({\n candidateId: `${pass.passId}:finding:${candidateOrdinal(index)}`,\n workId: pass.passId,\n unitId: pass.unitId,\n finding,\n evidencePaths: [finding.path],\n }),\n ),\n ...keptConcerns.map((candidate, index) =>\n ConcernCandidate.make({\n candidateId: `${pass.passId}:concern:${candidateOrdinal(index)}`,\n workId: pass.passId,\n unitId: pass.unitId,\n concern: candidate.concern,\n evidencePaths: candidate.evidencePaths,\n }),\n ),\n ],\n fileSummaries: report.fileSummaries.filter((entry) => allowed.has(entry.path)),\n discarded,\n };\n};\n\ninterface UnitReviewOutcome {\n readonly failedPasses: ReadonlyArray<FailedReviewPass>;\n readonly discoveredCandidates: number;\n readonly confirmed: ReadonlyArray<{\n readonly assessment: CandidateAssessment;\n readonly candidate: ReviewCandidate;\n }>;\n readonly rejectedCandidates: number;\n readonly unsettledCandidates: number;\n readonly discardedFindings: number;\n readonly walkthrough: ReadonlyArray<WalkthroughEntry>;\n readonly turns: number;\n readonly completedGeneralPasses: number;\n readonly completedSpecialistPasses: number;\n readonly requiredVerificationPasses: number;\n readonly completedVerificationPasses: number;\n readonly unreviewedPaths: ReadonlyArray<string>;\n readonly unreviewedPasses: ReadonlyArray<{\n readonly stage: FailedReviewPass[\"stage\"];\n readonly paths: ReadonlyArray<string>;\n }>;\n}\n\nconst reviewUnit = <Provider, ModelProvides, ModelRequires>(\n binding: FileReviewerBinding<Provider, ModelProvides, ModelRequires>,\n unit: ReviewUnit,\n passes: ReadonlyArray<ReviewDiscoveryPass>,\n input: FanOutPipelineInput,\n) =>\n Effect.gen(function* () {\n const evidence = yield* unitEvidence(unit, input.files);\n const failedPasses: Array<FailedReviewPass> = [];\n const candidates: Array<ReviewCandidate> = [];\n const subjects = new Set<string>();\n const walkthrough: Array<WalkthroughEntry> = [];\n let discardedFindings = 0;\n let turns = 0;\n let completedGeneralPasses = 0;\n let completedSpecialistPasses = 0;\n // Discovery-only context: adjudicated identities (path-free entries apply\n // to every unit) and prior-round findings on this unit's paths. The\n // verifier stays unbiased — it judges only the candidate claims and the\n // bounded evidence.\n const unitPaths = new Set(unit.paths);\n const adjudicatedContext = (input.priorContext?.adjudicated ?? [])\n .filter((entry) => entry.path === undefined || unitPaths.has(entry.path))\n .map((entry) => entry.line)\n .slice(0, 20);\n const priorFindingContext = (input.priorContext?.priorFindings ?? [])\n .filter((entry) => unitPaths.has(entry.path))\n .map((entry) => entry.line)\n .slice(0, 20);\n for (const pass of passes) {\n const stage = pass.perspective === \"risk-specialist\" ? \"specialist\" : \"discovery\";\n const brief = FileReviewBrief.make({\n phase: \"discovery\",\n workId: pass.passId,\n unitId: pass.unitId,\n paths: pass.paths,\n evidenceShardIds: pass.evidenceShardIds,\n perspective: pass.perspective,\n riskCategories: pass.riskCategories,\n candidates: [],\n evidence,\n ...(adjudicatedContext.length === 0 ? {} : { adjudicatedContext }),\n ...(priorFindingContext.length === 0 ? {} : { priorFindingContext }),\n });\n const outcome = yield* runReviewPass(binding, brief, input.budget);\n if (outcome._tag === \"failed\") {\n failedPasses.push(\n FailedReviewPass.make({ workId: pass.passId, stage, errorTag: outcome.errorTag }),\n );\n continue;\n }\n turns += outcome.turns;\n if (stage === \"specialist\") {\n completedSpecialistPasses += 1;\n } else {\n completedGeneralPasses += 1;\n }\n const harvest = harvestDiscovery(pass, unit, input.files, input.anchorFiles, outcome.report);\n discardedFindings += harvest.discarded;\n if (pass.perspective === \"general\") walkthrough.push(...harvest.fileSummaries);\n for (const candidate of harvest.candidates) {\n const subject = reviewCandidateSubjectKey(candidate);\n if (subjects.has(subject)) continue;\n subjects.add(subject);\n candidates.push(candidate);\n }\n }\n const confirmed: Array<{\n readonly assessment: CandidateAssessment;\n readonly candidate: ReviewCandidate;\n }> = [];\n let rejectedCandidates = 0;\n let unsettledCandidates = 0;\n let completedVerificationPasses = 0;\n const requiredVerificationPasses = candidates.length > 0 ? 1 : 0;\n if (candidates.length > 0) {\n const workId = `${unit.unitId}-verification`;\n const brief = FileReviewBrief.make({\n phase: \"verification\",\n workId,\n unitId: unit.unitId,\n paths: unit.paths,\n evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),\n perspective: \"candidate-verification\",\n riskCategories: unit.riskCategories,\n candidates,\n evidence,\n });\n const outcome = yield* runReviewPass(binding, brief, input.budget);\n if (outcome._tag === \"failed\") {\n unsettledCandidates = candidates.length;\n failedPasses.push(\n FailedReviewPass.make({ workId, stage: \"verification\", errorTag: outcome.errorTag }),\n );\n } else {\n turns += outcome.turns;\n completedVerificationPasses = 1;\n const byId = new Map(candidates.map((candidate) => [candidate.candidateId, candidate]));\n for (const assessment of outcome.report.assessments) {\n const candidate = byId.get(assessment.candidateId);\n if (candidate === undefined) continue;\n if (assessment.disposition === \"confirmed\") {\n confirmed.push({ assessment, candidate });\n } else {\n rejectedCandidates += 1;\n }\n }\n }\n }\n return {\n failedPasses,\n discoveredCandidates: candidates.length,\n confirmed,\n rejectedCandidates,\n unsettledCandidates,\n discardedFindings,\n walkthrough,\n turns,\n completedGeneralPasses,\n completedSpecialistPasses,\n requiredVerificationPasses,\n completedVerificationPasses,\n unreviewedPaths: failedPasses.length > 0 ? unit.paths : [],\n unreviewedPasses: failedPasses.map((pass) => ({\n stage: pass.stage,\n paths: unit.paths,\n })),\n } satisfies UnitReviewOutcome;\n });\n\nconst countNoun = (count: number, noun: string): string =>\n `${count} ${noun}${count === 1 ? \"\" : \"s\"}`;\n\nconst composeSummary = (plan: ReviewUnitPlan, assurance: ReviewAssurance): string => {\n const requiredDiscovery =\n assurance.requiredGeneralDiscoveryPasses + assurance.requiredSpecialistPasses;\n const completedDiscovery =\n assurance.completedGeneralDiscoveryPasses + assurance.completedSpecialistPasses;\n const parts = [\n `Reviewed ${countNoun(plan.totalFiles, \"changed file\")} across ${countNoun(plan.units.length, \"bounded unit\")}: ${completedDiscovery}/${requiredDiscovery} discovery and ${assurance.completedVerificationPasses}/${assurance.requiredVerificationPasses} verification pass(es) settled; ${assurance.confirmedCandidates} of ${countNoun(assurance.discoveredCandidates, \"discovered candidate\")} confirmed by independent verification.`,\n ];\n if (assurance.failedPasses.length > 0) {\n parts.push(\n `${countNoun(assurance.failedPasses.length, \"pass\")} did not settle; the affected paths are carried forward and retried on the next run. This is a reviewer-side gap, not a code defect.`,\n );\n }\n if (assurance.discardedInvalidFindings > 0) {\n parts.push(\n `${countNoun(assurance.discardedInvalidFindings, \"candidate\")} discarded for anchors or paths outside the assigned evidence.`,\n );\n }\n if (plan.undiffablePaths.length > 0) {\n parts.push(\n `${countNoun(plan.undiffablePaths.length, \"path\")} had no reviewable textual evidence and keep input coverage incomplete; exclude such paths with ignore globs when that is intended.`,\n );\n }\n if (plan.unassignedPaths.length > 0 || plan.unassignedEvidenceShardCount > 0) {\n parts.push(\n \"The changeset exceeded the bounded fan-out capacity; unassigned scope is reported under input coverage.\",\n );\n }\n parts.push(\n \"No configured pipeline can prove absence of defects; this describes settled work only.\",\n );\n return parts.join(\" \").slice(0, 4_000);\n};\n\nconst remapPlanUnitIds = (plan: ReviewUnitPlan, offset: number): ReviewUnitPlan => {\n if (offset === 0) return plan;\n const units = plan.units.map((unit, index) =>\n ReviewUnit.make({\n ...unit,\n unitId: `unit-${String(offset + index + 1).padStart(3, \"0\")}`,\n }),\n );\n const mappedIds = new Map<string, string>();\n for (const [index, unit] of plan.units.entries()) {\n const remapped = units[index];\n if (remapped !== undefined) {\n mappedIds.set(unit.unitId, remapped.unitId);\n }\n }\n return ReviewUnitPlan.make({\n ...plan,\n units,\n discoveryPasses: plan.discoveryPasses.map((pass) => {\n const unitId = mappedIds.get(pass.unitId) ?? pass.unitId;\n return ReviewDiscoveryPass.make({\n ...pass,\n unitId,\n passId: `${unitId}${pass.passId.slice(pass.unitId.length)}`,\n });\n }),\n });\n};\n\nconst scheduleFanOutWork = (\n input: FanOutPipelineInput,\n): {\n readonly plan: ReviewUnitPlan;\n readonly passesByUnit: Map<string, ReadonlyArray<ReviewDiscoveryPass>>;\n readonly overflowRetryPasses: ReadonlyArray<{\n readonly stage: FailedReviewPass[\"stage\"];\n readonly paths: ReadonlyArray<string>;\n }>;\n} => {\n const requestedRetryPasses =\n input.retry?.passes ??\n input.retry?.stages?.map((stage) => ({ stage, paths: input.retry?.paths ?? [] })) ??\n [];\n const requestedStagesByPath = new Map<string, Set<FailedReviewPass[\"stage\"]>>();\n for (const pass of requestedRetryPasses) {\n for (const path of pass.paths) {\n const stages = requestedStagesByPath.get(path) ?? new Set<FailedReviewPass[\"stage\"]>();\n stages.add(pass.stage);\n requestedStagesByPath.set(path, stages);\n }\n }\n const canonicalPathByKnownPath = new Map<string, string>();\n const retryStagesByPath = new Map<string, Set<FailedReviewPass[\"stage\"]>>();\n for (const file of input.files) {\n canonicalPathByKnownPath.set(file.path, file.path);\n if (file.previousPath !== undefined) {\n canonicalPathByKnownPath.set(file.previousPath, file.path);\n }\n const requested = [\n requestedStagesByPath.get(file.path),\n ...(file.previousPath === undefined ? [] : [requestedStagesByPath.get(file.previousPath)]),\n ];\n const stages = new Set(requested.flatMap((entry) => [...(entry ?? [])]));\n if (stages.size > 0) retryStagesByPath.set(file.path, stages);\n }\n if (retryStagesByPath.size === 0) {\n const plan = planReviewUnits(input.files, { totalChangedFiles: input.totalChangedFiles });\n const passesByUnit = new Map<string, Array<ReviewDiscoveryPass>>();\n for (const pass of plan.discoveryPasses) {\n const passes = passesByUnit.get(pass.unitId) ?? [];\n passes.push(pass);\n passesByUnit.set(pass.unitId, passes);\n }\n return { plan, passesByUnit, overflowRetryPasses: [] };\n }\n\n type DiscoveryStage = \"discovery\" | \"specialist\";\n const discoveryStagesFor = (\n stages: ReadonlySet<FailedReviewPass[\"stage\"]>,\n ): ReadonlyArray<DiscoveryStage> => {\n if (stages.has(\"verification\")) return [\"discovery\", \"specialist\"];\n return [\n ...(stages.has(\"discovery\") ? ([\"discovery\"] as const) : []),\n ...(stages.has(\"specialist\") ? ([\"specialist\"] as const) : []),\n ];\n };\n const freshFiles = input.files.filter((file) => !retryStagesByPath.has(file.path));\n const retryGroups = new Map<\n string,\n { readonly stages: ReadonlyArray<DiscoveryStage>; readonly files: Array<ChangedFile> }\n >();\n for (const file of input.files) {\n const retryStages = retryStagesByPath.get(file.path);\n if (retryStages === undefined) continue;\n const stages = discoveryStagesFor(retryStages);\n const key = stages.join(\"|\");\n const group = retryGroups.get(key) ?? { stages, files: [] };\n group.files.push(file);\n retryGroups.set(key, group);\n }\n\n const batches: ReadonlyArray<{\n readonly stages: ReadonlyArray<DiscoveryStage>;\n readonly files: ReadonlyArray<ChangedFile>;\n }> = [\n ...(freshFiles.length === 0\n ? []\n : [{ stages: [\"discovery\", \"specialist\"] as const, files: freshFiles }]),\n ...[...retryGroups.entries()]\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([, group]) => group),\n ];\n const subplans: Array<ReviewUnitPlan> = [];\n const acceptedUnits: Array<ReviewUnit> = [];\n const rejectedUnits: Array<ReviewUnit> = [];\n const discoveryPasses: Array<ReviewDiscoveryPass> = [];\n for (const batch of batches) {\n const batchPlan = remapPlanUnitIds(\n planReviewUnits(batch.files, { totalChangedFiles: batch.files.length }),\n acceptedUnits.length,\n );\n subplans.push(batchPlan);\n const accepted = batchPlan.units.slice(0, Math.max(0, MAX_REVIEW_UNITS - acceptedUnits.length));\n acceptedUnits.push(...accepted);\n rejectedUnits.push(...batchPlan.units.slice(accepted.length));\n const acceptedIds = new Set(accepted.map((unit) => unit.unitId));\n discoveryPasses.push(\n ...batchPlan.discoveryPasses.filter((pass) => {\n const stage = pass.perspective === \"risk-specialist\" ? \"specialist\" : \"discovery\";\n return acceptedIds.has(pass.unitId) && batch.stages.includes(stage);\n }),\n );\n }\n\n const acceptedPaths = new Set(acceptedUnits.flatMap((unit) => unit.paths));\n const incompletePlannedPaths = new Set([\n ...subplans.flatMap((plan) => plan.partialEvidencePaths),\n ...subplans.flatMap((plan) => plan.unassignedPaths),\n ...rejectedUnits.flatMap((unit) => unit.paths),\n ]);\n const partialEvidencePaths = [...incompletePlannedPaths]\n .filter((path) => acceptedPaths.has(path))\n .sort();\n const unassignedPaths = [...incompletePlannedPaths]\n .filter((path) => !acceptedPaths.has(path))\n .sort();\n const rejectedEvidenceShards = rejectedUnits.flatMap((unit) => unit.evidenceShards);\n const undiffablePaths = [...new Set(subplans.flatMap((plan) => plan.undiffablePaths))].sort();\n const plan = ReviewUnitPlan.make({\n totalFiles: input.files.length,\n truncated: input.files.length < input.totalChangedFiles,\n units: acceptedUnits,\n discoveryPasses,\n undiffablePaths,\n partialEvidencePaths,\n unassignedEvidenceShardCount:\n subplans.reduce((total, item) => total + item.unassignedEvidenceShardCount, 0) +\n rejectedEvidenceShards.length,\n unassignedEvidenceShardIds: [\n ...subplans.flatMap((item) => item.unassignedEvidenceShardIds),\n ...rejectedEvidenceShards.map((shard) => shard.shardId),\n ].slice(0, MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS),\n unassignedPaths,\n });\n const passesByUnit = new Map<string, Array<ReviewDiscoveryPass>>();\n for (const pass of discoveryPasses) {\n const passes = passesByUnit.get(pass.unitId) ?? [];\n passes.push(pass);\n passesByUnit.set(pass.unitId, passes);\n }\n const incompletePaths = new Set([\n ...partialEvidencePaths,\n ...unassignedPaths,\n ...undiffablePaths,\n ]);\n const overflowRetryPathsByStage = new Map<FailedReviewPass[\"stage\"], Set<string>>();\n for (const pass of requestedRetryPasses) {\n for (const path of pass.paths) {\n const canonicalPath = canonicalPathByKnownPath.get(path);\n if (canonicalPath === undefined || !incompletePaths.has(canonicalPath)) continue;\n const paths = overflowRetryPathsByStage.get(pass.stage) ?? new Set<string>();\n paths.add(canonicalPath);\n overflowRetryPathsByStage.set(pass.stage, paths);\n }\n }\n const overflowRetryPasses = ([\"discovery\", \"specialist\", \"verification\"] as const).flatMap(\n (stage) => {\n const paths = [...(overflowRetryPathsByStage.get(stage) ?? [])].sort();\n return Array.from({ length: Math.ceil(paths.length / MAX_UNIT_FILES) }, (_, index) => ({\n stage,\n paths: paths.slice(index * MAX_UNIT_FILES, (index + 1) * MAX_UNIT_FILES),\n }));\n },\n );\n return { plan, passesByUnit, overflowRetryPasses };\n};\n\n/**\n * Run the complete host-scheduled fan-out pipeline over one selected\n * changeset snapshot: plan, independent discovery, exact verification, and a\n * deterministic host-composed CodeReview from verifier-confirmed candidates\n * only. The verdict is derived from confirmed severities, never model prose.\n */\nexport const runFanOutReview = <Provider, ModelProvides, ModelRequires>(\n binding: FileReviewerBinding<Provider, ModelProvides, ModelRequires>,\n input: FanOutPipelineInput,\n) =>\n Effect.gen(function* () {\n const { plan, passesByUnit, overflowRetryPasses } = scheduleFanOutWork(input);\n const outcomes = yield* Effect.forEach(\n plan.units,\n (unit) => reviewUnit(binding, unit, passesByUnit.get(unit.unitId) ?? [], input),\n { concurrency: REVIEW_UNIT_CONCURRENCY },\n );\n const failedPasses = outcomes.flatMap((outcome) => outcome.failedPasses);\n const unsettledCandidates = outcomes.reduce(\n (total, outcome) => total + outcome.unsettledCandidates,\n 0,\n );\n const reasons: Array<string> = [];\n if (failedPasses.length > 0) {\n reasons.push(\n boundedListReason(\n \"configured review passes did not settle\",\n failedPasses.map((pass) => `${pass.workId} (${pass.errorTag})`),\n ),\n );\n }\n if (unsettledCandidates > 0) {\n reasons.push(\n `${unsettledCandidates} discovered candidate(s) did not receive exact verification`,\n );\n }\n const requiredSpecialistPasses = plan.discoveryPasses.filter(\n (pass) => pass.perspective === \"risk-specialist\",\n ).length;\n const confirmed = outcomes.flatMap((outcome) => outcome.confirmed);\n const assurance = ReviewAssurance.make({\n status: reasons.length === 0 ? \"settled\" : \"incomplete\",\n requiredGeneralDiscoveryPasses: plan.discoveryPasses.length - requiredSpecialistPasses,\n completedGeneralDiscoveryPasses: outcomes.reduce(\n (total, outcome) => total + outcome.completedGeneralPasses,\n 0,\n ),\n requiredSpecialistPasses,\n completedSpecialistPasses: outcomes.reduce(\n (total, outcome) => total + outcome.completedSpecialistPasses,\n 0,\n ),\n requiredVerificationPasses: outcomes.reduce(\n (total, outcome) => total + outcome.requiredVerificationPasses,\n 0,\n ),\n completedVerificationPasses: outcomes.reduce(\n (total, outcome) => total + outcome.completedVerificationPasses,\n 0,\n ),\n discoveredCandidates: outcomes.reduce(\n (total, outcome) => total + outcome.discoveredCandidates,\n 0,\n ),\n confirmedCandidates: confirmed.length,\n rejectedCandidates: outcomes.reduce(\n (total, outcome) => total + outcome.rejectedCandidates,\n 0,\n ),\n unsettledCandidates,\n discardedInvalidFindings: outcomes.reduce(\n (total, outcome) => total + outcome.discardedFindings,\n 0,\n ),\n failedPasses,\n reasons,\n });\n const findings = rankAndDedupeFindings(\n confirmed.flatMap(({ assessment, candidate }) =>\n candidate._tag === \"FindingCandidate\"\n ? [confirmedFindingForPublication(assessment, candidate)]\n : [],\n ),\n );\n const concerns = rankAndDedupeConcerns(\n confirmed.flatMap(({ candidate }) =>\n candidate._tag === \"ConcernCandidate\"\n ? [\n ReviewConcern.make({\n ...candidate.concern,\n evidencePaths: [...new Set(candidate.evidencePaths)].sort(),\n }),\n ]\n : [],\n ),\n );\n const walkthrough = outcomes.flatMap((outcome) => outcome.walkthrough);\n const blocking =\n findings.some((finding) => finding.severity === \"blocking\") ||\n concerns.some((concern) => concern.severity === \"blocking\");\n const review = CodeReview.make({\n summary: composeSummary(plan, assurance),\n verdict: blocking\n ? \"request-changes\"\n : findings.length > 0 || concerns.length > 0\n ? \"comment\"\n : \"approve\",\n findings,\n ...(concerns.length === 0 ? {} : { concerns }),\n ...(walkthrough.length === 0 ? {} : { walkthrough }),\n });\n return {\n review,\n assurance,\n plan,\n // Everything not fully reviewed this run and still part of the pull\n // request carries forward, so the baseline can advance without ever\n // moving unreviewed scope behind a green check: failed units retry,\n // whole overflow files review in later installments, and partial or\n // undiffable files keep the check fail-closed until they are reviewed,\n // removed, or explicitly ignored.\n unreviewedPaths: [\n ...new Set([\n ...outcomes.flatMap((outcome) => outcome.unreviewedPaths),\n ...plan.unassignedPaths,\n ...plan.partialEvidencePaths,\n ...plan.undiffablePaths,\n ]),\n ].sort(),\n unreviewedPasses: [\n ...outcomes.flatMap((outcome) => outcome.unreviewedPasses),\n ...overflowRetryPasses,\n ],\n turns: outcomes.reduce((total, outcome) => total + outcome.turns, 0),\n } satisfies FanOutPipelineOutcome;\n });\n","import { Crypto, Effect, Encoding } from \"effect\";\n\nimport type { ChangedFile } from \"./diff.ts\";\n\n// ---------------------------------------------------------------------------\n// Changeset fingerprinting: dedupe re-reviews of an UNCHANGED effective diff.\n// Repositories that auto-merge the base branch into open pull requests fire\n// `synchronize` on every base update; the head SHA moves but the three-dot\n// changeset the reviewer reads is byte-identical. The fingerprint hashes the\n// (ignore-filtered) changeset together with a prompt signature — everything\n// that shapes the review — so a rebase with no content change skips, while a\n// real change, a conflict resolution, or a guidance change reviews again.\n//\n// The reviewer is deployment class E and owns no storage: the fingerprint is\n// embedded in the posted review body as an invisible HTML comment, so the\n// published review itself is the deduplication state.\n// ---------------------------------------------------------------------------\n\nconst MARKER_PREFIX = \"<!-- effect-agent-pr-review fingerprint=sha256:\";\nconst MARKER_SUFFIX = \" -->\";\nconst MARKER_PATTERN = /<!-- effect-agent-pr-review fingerprint=sha256:([0-9a-f]{64}) -->/g;\n\n/** Render the invisible review-body marker for one fingerprint. */\nexport const renderFingerprintMarker = (fingerprint: string): string =>\n `${MARKER_PREFIX}${fingerprint}${MARKER_SUFFIX}`;\n\n/** The rendered marker length is fixed; publication reserves room for it. */\nexport const FINGERPRINT_MARKER_LENGTH = renderFingerprintMarker(\"0\".repeat(64)).length;\n\n/** Extract the last fingerprint marker in one review body, if any. */\nexport const extractFingerprint = (body: string): string | undefined => {\n let last: string | undefined;\n for (const match of body.matchAll(MARKER_PATTERN)) {\n last = match[1];\n }\n return last;\n};\n\n/** SHA-256 via `Crypto.Crypto`; unavailable crypto is a defect, not an expected failure. */\nconst sha256Hex = Effect.fn(\"sha256Hex\")(function* (\n text: string,\n): Effect.fn.Return<string, never, Crypto.Crypto> {\n const crypto = yield* Crypto.Crypto;\n const digest = yield* crypto.digest(\"SHA-256\", new TextEncoder().encode(text)).pipe(Effect.orDie);\n return Encoding.encodeHex(digest);\n});\n\nconst FIELD = \"\\u0000\";\nconst RECORD = \"\\u0001\";\nconst SECTION = \"\\u0002\";\n\n/**\n * Unified-diff hunk coordinates describe where a patch applies, not what it\n * changes. A content-equivalent rebase can shift both coordinates while\n * leaving every context/addition/deletion line unchanged, so exclude only\n * those coordinates from the canonical patch representation.\n */\nconst canonicalPatch = (patch: string): string =>\n patch.replace(/^@@ -\\d+(?:,\\d+)? \\+\\d+(?:,\\d+)? @@/gm, \"@@ -_ +_ @@\");\n\n/**\n * Canonical changeset encoding: sorted by path so provider ordering never\n * matters, with every review-relevant field of every file.\n */\nconst canonicalChangeset = (files: ReadonlyArray<ChangedFile>): string =>\n files\n .map(\n (file) =>\n `${file.path}${FIELD}${file.status}${FIELD}${String(file.additions)}${FIELD}${String(file.deletions)}${FIELD}${file.patch === undefined ? \"\" : canonicalPatch(file.patch)}${FIELD}${file.reviewBaseContent ?? \"\"}${FIELD}${file.reviewHeadContent ?? \"\"}`,\n )\n .sort()\n .join(RECORD);\n\n/**\n * Fingerprint one review's complete input surface: the (already\n * ignore-filtered) changeset plus the caller's prompt signature — the\n * rendered instructions and any review-shaping options the instructions do\n * not carry.\n */\nexport const computeChangesetFingerprint = (\n files: ReadonlyArray<ChangedFile>,\n signature: string,\n): Effect.Effect<string, never, Crypto.Crypto> =>\n sha256Hex(`${canonicalChangeset(files)}${SECTION}${signature}`);\n\n/** Profile fingerprints are SHA-256 over configuration-only signatures. */\nexport const computeProfileFingerprint = (\n signature: string,\n): Effect.Effect<string, never, Crypto.Crypto> => sha256Hex(signature);\n","import type { Redacted } from \"effect\";\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\";\n\nimport {\n AdjudicableThread,\n AdjudicationComment,\n AUTHORIZED_ADJUDICATION_ASSOCIATIONS,\n MAX_THREAD_ADJUDICATION_COMMANDS,\n parseThreadAdjudication,\n ReviewAdjudicationFailure,\n ReviewAdjudicationHost,\n} from \"./adjudication.ts\";\nimport { ChangedFile, ChangedPath } from \"./diff.ts\";\nimport { extractFingerprint } from \"./fingerprint.ts\";\nimport type { ReviewPublicationPlan } from \"./render.ts\";\nimport {\n RetirableReview,\n RetirableReviewComment,\n ReviewRetirementFailure,\n ReviewRetirementHost,\n} from \"./retirement.ts\";\nimport {\n GitCommitSha,\n MAX_TREE_COMPARISON_PATHS,\n ReviewHeadComparison,\n ReviewStateAuthenticator,\n ReviewTreeComparison,\n type ReviewState,\n} from \"./review-state.ts\";\nimport {\n MAX_CHANGED_FILES,\n MAX_FILE_CHARS,\n normalizeRepoRelativePath,\n PullRequestMetadata,\n PullRequestSource,\n PullRequestSourceFailure,\n ReviewInputViolation,\n} from \"./source.ts\";\n\n// ---------------------------------------------------------------------------\n// GitHub REST adapters for the PullRequestSource port and the ReviewPublisher.\n// Wire payloads are decoded through minimal Schemas — never asserted — and\n// every upstream fault becomes the typed PullRequestSourceFailure /\n// GitHubApiFailure instead of an untyped defect.\n// ---------------------------------------------------------------------------\n\nconst defaultGraphqlUrl = (apiUrl: string): string =>\n apiUrl === \"https://api.github.com\"\n ? \"https://api.github.com/graphql\"\n : apiUrl.replace(/\\/api\\/v3$/, \"/api/graphql\");\n\n/** Which pull request to review and how to reach the API. */\nexport const DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN = \"github-actions[bot]\";\n\nexport class GitHubReviewTarget extends Context.Service<\n GitHubReviewTarget,\n {\n /** API root, e.g. `https://api.github.com` (no trailing slash). */\n readonly apiUrl: string;\n /** GraphQL root, e.g. `https://api.github.com/graphql`. */\n readonly graphqlUrl: string;\n /** `owner/name`. */\n readonly repository: string;\n readonly number: number;\n /** Absent token means unauthenticated reads (public repositories only). */\n readonly token: Option.Option<Redacted.Redacted<string>>;\n /** Bot login expected to author reviews posted with this target's token. */\n readonly reviewAuthorLogin?: string | undefined;\n }\n>()(\"@effect-agent/pr-review/GitHubReviewTarget\") {\n static layer(config: {\n readonly apiUrl: string;\n readonly graphqlUrl?: string | undefined;\n readonly repository: string;\n readonly number: number;\n readonly token: Option.Option<Redacted.Redacted<string>>;\n readonly reviewAuthorLogin?: string | undefined;\n }): Layer.Layer<GitHubReviewTarget> {\n return Layer.succeed(\n this,\n GitHubReviewTarget.of({\n ...config,\n graphqlUrl: config.graphqlUrl ?? defaultGraphqlUrl(config.apiUrl),\n reviewAuthorLogin: config.reviewAuthorLogin ?? DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN,\n }),\n );\n }\n}\n\n/** A GitHub API call failed: transport, status, or payload decode. */\nexport class GitHubApiFailure extends Schema.TaggedError<GitHubApiFailure>()(\"GitHubApiFailure\", {\n operation: Schema.String,\n reason: Schema.String,\n}) {\n override get message() {\n return `GitHub API operation '${this.operation}' failed: ${this.reason}`;\n }\n}\n\n// --- Wire schemas (decode-only, minimal fields) ------------------------------\n\nconst GitHubPullRequestWire = Schema.Struct({\n number: Schema.Int,\n title: Schema.String,\n body: Schema.NullOr(Schema.String),\n changed_files: Schema.Int,\n base: Schema.Struct({ ref: Schema.String, sha: Schema.String }),\n head: Schema.Struct({ ref: Schema.String, sha: Schema.String }),\n});\n\nconst GitHubFileWire = Schema.Struct({\n filename: Schema.String,\n status: Schema.String,\n additions: Schema.Int,\n deletions: Schema.Int,\n patch: Schema.optionalKey(Schema.String),\n previous_filename: Schema.optionalKey(Schema.String),\n});\n\nconst GitHubFilesPageWire = Schema.Array(GitHubFileWire);\n\nconst GitHubActorWire = Schema.Struct({ node_id: Schema.String });\n\nconst GitHubReviewWire = Schema.Struct({\n id: Schema.Int,\n html_url: Schema.String,\n user: Schema.NullOr(GitHubActorWire),\n submitted_at: Schema.NullOr(Schema.String),\n});\n\nconst GitHubRetirableReviewWire = Schema.Struct({\n id: Schema.Int,\n body: Schema.NullOr(Schema.String),\n commit_id: Schema.String,\n user: Schema.NullOr(GitHubActorWire),\n submitted_at: Schema.NullOr(Schema.String),\n});\nconst GitHubRetirableReviewsPageWire = Schema.Array(GitHubRetirableReviewWire);\n\nconst GitHubReviewCommentWire = Schema.Struct({\n node_id: Schema.String,\n path: Schema.String,\n body: Schema.String,\n // Outdated comments omit `line` entirely instead of sending null.\n line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n original_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n original_start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n});\nconst GitHubReviewCommentsPageWire = Schema.Array(GitHubReviewCommentWire);\n\nconst GitHubMinimizeCommentWire = Schema.Struct({\n data: Schema.optionalKey(\n Schema.NullOr(\n Schema.Struct({\n minimizeComment: Schema.NullOr(\n Schema.Struct({\n minimizedComment: Schema.NullOr(Schema.Struct({ isMinimized: Schema.Boolean })),\n }),\n ),\n }),\n ),\n ),\n errors: Schema.optionalKey(Schema.Array(Schema.Struct({ message: Schema.String }))),\n});\n\n/** Decode GitHub's external timestamp before it participates in mutation ordering. */\nexport const parseGitHubSubmittedAt = (value: string | null): DateTime.Utc | null =>\n value === null ? null : Option.getOrNull(DateTime.make(value));\n\n/** The publication receipt callers report back to the operator. */\nexport class PublishedReview extends Schema.Class<PublishedReview>(\n \"@effect-agent/pr-review/PublishedReview\",\n)({\n reviewId: Schema.Int,\n url: Schema.String,\n event: Schema.String,\n inlineComments: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Actor and ordering boundary returned by the create-review response. */\n authorNodeId: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(200))),\n submittedAt: Schema.NullOr(Schema.DateTimeUtc),\n}) {}\n\n/** Posts one planned review; the ONLY mutating operation in this package. */\nexport class ReviewPublisher extends Context.Service<\n ReviewPublisher,\n {\n readonly publish: (\n plan: ReviewPublicationPlan,\n ) => Effect.Effect<PublishedReview, GitHubApiFailure>;\n }\n>()(\"@effect-agent/pr-review/ReviewPublisher\") {}\n\n// --- Shared request plumbing -------------------------------------------------\n\nconst FILE_STATUSES = new Set([\n \"added\",\n \"removed\",\n \"modified\",\n \"renamed\",\n \"copied\",\n \"changed\",\n \"unchanged\",\n]);\n\nconst withCommonHeaders = (\n request: HttpClientRequest.HttpClientRequest,\n token: Option.Option<Redacted.Redacted<string>>,\n): HttpClientRequest.HttpClientRequest => {\n const base = request.pipe(\n HttpClientRequest.setHeaders({\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n \"User-Agent\": \"effect-agent-pr-review\",\n }),\n );\n return Option.isSome(token) ? base.pipe(HttpClientRequest.bearerToken(token.value)) : base;\n};\n\nconst failWith =\n (operation: string) =>\n (error: { readonly _tag: string; readonly message?: string }): PullRequestSourceFailure =>\n PullRequestSourceFailure.make({\n operation,\n reason: `${error._tag}: ${error.message ?? \"request failed\"}`.slice(0, 2_048),\n });\n\nconst decodeJsonBody = <S extends Schema.Top>(schema: S, operation: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return (\n response: HttpClientResponse.HttpClientResponse,\n ): Effect.Effect<S[\"Type\"], PullRequestSourceFailure, S[\"DecodingServices\"]> =>\n response.json.pipe(\n Effect.mapError(failWith(operation)),\n Effect.flatMap((body) => decode(body).pipe(Effect.mapError(failWith(operation)))),\n );\n};\n\nconst executeOk = (\n operation: string,\n request: HttpClientRequest.HttpClientRequest,\n): Effect.Effect<\n HttpClientResponse.HttpClientResponse,\n PullRequestSourceFailure,\n HttpClient.HttpClient\n> =>\n HttpClient.execute(request).pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(failWith(operation)),\n );\n\nconst toChangedFile = (wire: typeof GitHubFileWire.Type): ChangedFile =>\n ChangedFile.make({\n path: wire.filename,\n status: FILE_STATUSES.has(wire.status) ? (wire.status as ChangedFile[\"status\"]) : \"changed\",\n additions: wire.additions,\n deletions: wire.deletions,\n ...(wire.previous_filename !== undefined ? { previousPath: wire.previous_filename } : {}),\n ...(wire.patch !== undefined ? { patch: wire.patch } : {}),\n });\n\n// --- Live PullRequestSource --------------------------------------------------\n\n/**\n * GitHub-backed PullRequestSource. Metadata and the changeset are fetched\n * once per Layer build and cached: the pull request is reviewed as one\n * consistent snapshot even if the branch moves mid-run.\n */\nexport const gitHubPullRequestSourceLayer: Layer.Layer<\n PullRequestSource,\n never,\n GitHubReviewTarget | HttpClient.HttpClient\n> = Layer.effect(PullRequestSource)(\n Effect.gen(function* () {\n const target = yield* GitHubReviewTarget;\n const client = yield* HttpClient.HttpClient;\n const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;\n\n const fetchMetadata = executeOk(\n \"getPullRequest\",\n withCommonHeaders(\n HttpClientRequest.get(prefix).pipe(HttpClientRequest.acceptJson),\n target.token,\n ),\n ).pipe(\n Effect.flatMap(decodeJsonBody(GitHubPullRequestWire, \"getPullRequest\")),\n Effect.map((wire) =>\n PullRequestMetadata.make({\n repository: target.repository,\n number: wire.number,\n title: wire.title.slice(0, 400),\n body: (wire.body ?? \"\").slice(0, 20_000),\n baseRef: wire.base.ref,\n baseSha: wire.base.sha,\n headRef: wire.head.ref,\n headSha: wire.head.sha,\n totalChangedFiles: wire.changed_files,\n }),\n ),\n );\n\n const fetchFiles = Effect.gen(function* () {\n const perPage = 100;\n const all: Array<ChangedFile> = [];\n for (let page = 1; page <= MAX_CHANGED_FILES / perPage; page += 1) {\n const response = yield* executeOk(\n \"listChangedFiles\",\n withCommonHeaders(\n HttpClientRequest.get(`${prefix}/files`).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.setUrlParams({\n per_page: String(perPage),\n page: String(page),\n }),\n ),\n target.token,\n ),\n );\n const wires = yield* decodeJsonBody(GitHubFilesPageWire, \"listChangedFiles\")(response);\n all.push(...wires.map(toChangedFile));\n if (wires.length < perPage) break;\n }\n return all as ReadonlyArray<ChangedFile>;\n });\n\n const metadata = yield* Effect.cached(\n fetchMetadata.pipe(Effect.provideService(HttpClient.HttpClient, client)),\n );\n const rawFiles = yield* Effect.cached(\n fetchFiles.pipe(Effect.provideService(HttpClient.HttpClient, client)),\n );\n\n const readRepositoryFile = (path: string, ref: string) =>\n Effect.gen(function* () {\n const relative = yield* normalizeRepoRelativePath(path);\n const encodedPath = relative.split(\"/\").map(encodeURIComponent).join(\"/\");\n const response = yield* executeOk(\n \"readFile\",\n withCommonHeaders(\n HttpClientRequest.get(\n `${target.apiUrl}/repos/${target.repository}/contents/${encodedPath}`,\n ).pipe(\n HttpClientRequest.accept(\"application/vnd.github.raw+json\"),\n HttpClientRequest.setUrlParams({ ref }),\n ),\n target.token,\n ),\n ).pipe(Effect.provideService(HttpClient.HttpClient, client));\n const buffer = yield* response.arrayBuffer.pipe(Effect.mapError(failWith(\"readFile\")));\n if (buffer.byteLength > MAX_FILE_CHARS) {\n return yield* ReviewInputViolation.make({\n input: relative,\n reason: `File is larger than the ${MAX_FILE_CHARS}-byte read bound.`,\n });\n }\n const text = yield* Effect.try({\n try: () => new TextDecoder(\"utf-8\", { fatal: true }).decode(buffer),\n catch: () =>\n ReviewInputViolation.make({\n input: relative,\n reason: \"File is not valid UTF-8 text.\",\n }),\n });\n if (text.includes(\"\\u0000\")) {\n return yield* ReviewInputViolation.make({\n input: relative,\n reason: \"File contains binary NUL bytes.\",\n });\n }\n if (text.length > MAX_FILE_CHARS) {\n return yield* ReviewInputViolation.make({\n input: relative,\n reason: `File is larger than the ${MAX_FILE_CHARS}-character read bound.`,\n });\n }\n return text;\n });\n\n const changedFiles = yield* Effect.cached(\n Effect.gen(function* () {\n const [files, pullRequest] = yield* Effect.all([rawFiles, metadata]);\n return yield* Effect.forEach(\n files,\n (file) => {\n if (file.patch !== undefined) return Effect.succeed(file);\n const basePath = file.previousPath ?? file.path;\n const base =\n file.status === \"added\"\n ? Effect.succeed(Option.none<string>())\n : readRepositoryFile(basePath, pullRequest.baseSha ?? pullRequest.baseRef).pipe(\n Effect.option,\n );\n const head =\n file.status === \"removed\"\n ? Effect.succeed(Option.none<string>())\n : readRepositoryFile(file.path, pullRequest.headSha).pipe(Effect.option);\n return Effect.all({ base, head }).pipe(\n Effect.map(({ base, head }) =>\n ChangedFile.make({\n ...file,\n ...(Option.isSome(base) ? { reviewBaseContent: base.value } : {}),\n ...(Option.isSome(head) ? { reviewHeadContent: head.value } : {}),\n }),\n ),\n );\n },\n { concurrency: 4 },\n );\n }),\n );\n\n const readFile = (path: string) =>\n Effect.gen(function* () {\n const relative = yield* normalizeRepoRelativePath(path);\n const files = yield* changedFiles;\n const file = files.find((candidate) => candidate.path === relative);\n if (file === undefined) {\n return yield* ReviewInputViolation.make({\n input: relative,\n reason: \"Path is not part of this pull request's changeset.\",\n });\n }\n if (file.reviewHeadContent !== undefined) return file.reviewHeadContent;\n const head = yield* metadata;\n return yield* readRepositoryFile(relative, head.headSha);\n });\n\n return PullRequestSource.of({ metadata, changedFiles, anchorFiles: changedFiles, readFile });\n }),\n);\n\n// --- Live ReviewPublisher ------------------------------------------------------\n\n/** GitHub-backed publisher: one POST to the pull-request reviews endpoint. */\nexport const gitHubReviewPublisherLayer: Layer.Layer<\n ReviewPublisher,\n never,\n GitHubReviewTarget | HttpClient.HttpClient\n> = Layer.effect(ReviewPublisher)(\n Effect.gen(function* () {\n const target = yield* GitHubReviewTarget;\n const client = yield* HttpClient.HttpClient;\n return ReviewPublisher.of({\n publish: (plan) =>\n Effect.gen(function* () {\n const payload = {\n event: plan.event,\n body: plan.body,\n commit_id: plan.commitSha,\n comments: plan.comments.map((comment) => ({\n path: comment.path,\n line: comment.line,\n side: \"RIGHT\",\n ...(comment.startLine !== undefined\n ? { start_line: comment.startLine, start_side: \"RIGHT\" }\n : {}),\n body: comment.body,\n })),\n };\n const request = withCommonHeaders(\n HttpClientRequest.post(\n `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}/reviews`,\n ).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bodyJsonUnsafe(payload)),\n target.token,\n );\n const wire = yield* HttpClient.execute(request).pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.flatMap((response) =>\n response.json.pipe(Effect.flatMap(Schema.decodeUnknownEffect(GitHubReviewWire))),\n ),\n Effect.mapError((error) =>\n GitHubApiFailure.make({\n operation: \"createReview\",\n reason: `${error._tag}: ${error.message ?? \"request failed\"}`.slice(0, 2_048),\n }),\n ),\n Effect.provideService(HttpClient.HttpClient, client),\n );\n return PublishedReview.make({\n reviewId: wire.id,\n url: wire.html_url,\n event: plan.event,\n inlineComments: plan.comments.length,\n authorNodeId: wire.user?.node_id ?? null,\n submittedAt: parseGitHubSubmittedAt(wire.submitted_at),\n });\n }),\n });\n }),\n);\n\n// --- Live ReviewRetirementHost ----------------------------------------------\n\nconst MAX_RETIREMENT_PAGES = 5;\nconst MINIMIZE_REVIEW_COMMENT_MUTATION = `mutation MinimizeReviewComment($subjectId: ID!) {\n minimizeComment(input: { subjectId: $subjectId, classifier: OUTDATED }) {\n minimizedComment { isMinimized }\n }\n}`;\n\n/** GitHub-backed host operations for cosmetic retirement after publication. */\nexport const gitHubReviewRetirementHostLayer: Layer.Layer<\n ReviewRetirementHost,\n never,\n GitHubReviewTarget | HttpClient.HttpClient\n> = Layer.effect(ReviewRetirementHost)(\n Effect.gen(function* () {\n const target = yield* GitHubReviewTarget;\n const client = yield* HttpClient.HttpClient;\n const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;\n const asRetirementFailure =\n (operation: string) =>\n (error: { readonly _tag: string; readonly message?: string }): ReviewRetirementFailure =>\n ReviewRetirementFailure.make({\n operation,\n reason: `${error._tag}: ${error.message ?? \"request failed\"}`.slice(0, 2_048),\n });\n const executeRetirement = (operation: string, request: HttpClientRequest.HttpClientRequest) =>\n HttpClient.execute(request).pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(asRetirementFailure(operation)),\n Effect.provideService(HttpClient.HttpClient, client),\n );\n const decodeRetirement = <S extends Schema.Top>(schema: S, operation: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return (response: HttpClientResponse.HttpClientResponse) =>\n response.json.pipe(\n Effect.mapError(asRetirementFailure(operation)),\n Effect.flatMap((body) =>\n decode(body).pipe(Effect.mapError(asRetirementFailure(operation))),\n ),\n );\n };\n const listPaged = <A>(input: {\n readonly operation: string;\n readonly url: string;\n readonly decode: (\n response: HttpClientResponse.HttpClientResponse,\n ) => Effect.Effect<ReadonlyArray<A>, ReviewRetirementFailure>;\n }) =>\n Effect.gen(function* () {\n const values: Array<A> = [];\n const perPage = 100;\n for (let page = 1; page <= MAX_RETIREMENT_PAGES; page += 1) {\n const response = yield* executeRetirement(\n input.operation,\n withCommonHeaders(\n HttpClientRequest.get(input.url).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.setUrlParams({\n per_page: String(perPage),\n page: String(page),\n }),\n ),\n target.token,\n ),\n );\n const pageValues = yield* input.decode(response);\n values.push(...pageValues);\n if (pageValues.length < perPage) return values;\n }\n return yield* ReviewRetirementFailure.make({\n operation: input.operation,\n reason: `history exceeds the bounded ${MAX_RETIREMENT_PAGES * 100}-item lookup`,\n });\n });\n\n return ReviewRetirementHost.of({\n listReviews: listPaged({\n operation: \"listReviewsForRetirement\",\n url: `${prefix}/reviews`,\n decode: decodeRetirement(GitHubRetirableReviewsPageWire, \"listReviewsForRetirement\"),\n }).pipe(\n Effect.map((reviews) =>\n reviews.map((review) =>\n RetirableReview.make({\n reviewId: review.id,\n body: review.body ?? \"\",\n commitSha: review.commit_id,\n authorNodeId: review.user?.node_id ?? null,\n submittedAt: parseGitHubSubmittedAt(review.submitted_at),\n }),\n ),\n ),\n ),\n listComments: (reviewId) =>\n listPaged({\n operation: \"listReviewCommentsForRetirement\",\n url: `${prefix}/reviews/${reviewId}/comments`,\n decode: decodeRetirement(GitHubReviewCommentsPageWire, \"listReviewCommentsForRetirement\"),\n }).pipe(\n Effect.map((comments) =>\n comments.map((comment) => {\n const positiveLine = (value: number | null | undefined): number | null =>\n value !== undefined && value !== null && value > 0 ? value : null;\n const endLine = positiveLine(comment.line ?? comment.original_line);\n const startLine =\n positiveLine(comment.start_line ?? comment.original_start_line) ?? endLine;\n return RetirableReviewComment.make({\n nodeId: comment.node_id,\n path: comment.path,\n startLine,\n endLine,\n body: comment.body,\n });\n }),\n ),\n ),\n updateBody: (reviewId, body) =>\n executeRetirement(\n \"updateReview\",\n withCommonHeaders(\n HttpClientRequest.put(`${prefix}/reviews/${reviewId}`).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.bodyJsonUnsafe({ body }),\n ),\n target.token,\n ),\n ).pipe(Effect.asVoid),\n minimizeComment: (nodeId) =>\n Effect.gen(function* () {\n const response = yield* executeRetirement(\n \"minimizeComment\",\n withCommonHeaders(\n HttpClientRequest.post(target.graphqlUrl).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.bodyJsonUnsafe({\n query: MINIMIZE_REVIEW_COMMENT_MUTATION,\n variables: { subjectId: nodeId },\n }),\n ),\n target.token,\n ),\n );\n const wire = yield* decodeRetirement(\n GitHubMinimizeCommentWire,\n \"minimizeComment\",\n )(response);\n if (\n (wire.errors?.length ?? 0) > 0 ||\n wire.data?.minimizeComment?.minimizedComment?.isMinimized !== true\n ) {\n return yield* ReviewRetirementFailure.make({\n operation: \"minimizeComment\",\n reason:\n wire.errors\n ?.map((error) => error.message)\n .join(\"; \")\n .slice(0, 2_048) ?? \"GitHub did not confirm comment minimization\",\n });\n }\n }),\n });\n }),\n);\n\n// --- Live ReviewAdjudicationHost ----------------------------------------------\n\nconst MAX_ADJUDICATION_PAGES = 5;\n\nconst GitHubThreadCommentWire = Schema.Struct({\n id: Schema.Int,\n in_reply_to_id: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n path: Schema.String,\n body: Schema.String,\n author_association: Schema.optionalKey(Schema.NullOr(Schema.String)),\n user: Schema.NullOr(Schema.Struct({ login: Schema.String })),\n created_at: Schema.optionalKey(Schema.NullOr(Schema.String)),\n line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n original_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n original_start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n});\nconst GitHubThreadCommentsPageWire = Schema.Array(GitHubThreadCommentWire);\n\nconst GitHubIssueCommentWire = Schema.Struct({\n body: Schema.optionalKey(Schema.NullOr(Schema.String)),\n author_association: Schema.optionalKey(Schema.NullOr(Schema.String)),\n user: Schema.NullOr(Schema.Struct({ login: Schema.String })),\n created_at: Schema.optionalKey(Schema.NullOr(Schema.String)),\n});\nconst GitHubIssueCommentsPageWire = Schema.Array(GitHubIssueCommentWire);\n\nconst toAdjudicationComment = (\n wire: {\n readonly body?: string | null | undefined;\n readonly author_association?: string | null | undefined;\n readonly user: { readonly login: string } | null;\n readonly created_at?: string | null | undefined;\n },\n sourceOrder: number,\n): AdjudicationComment | undefined => {\n // A comment without an attributable author cannot authorize anything —\n // skip it fail-closed rather than inventing an actor.\n const login = wire.user?.login;\n if (login === undefined || login.length === 0) return undefined;\n return AdjudicationComment.make({\n body: (wire.body ?? \"\").slice(0, 65_536),\n authorAssociation: (wire.author_association ?? \"NONE\").slice(0, 40),\n authorLogin: login.slice(0, 100),\n createdAt: parseGitHubSubmittedAt(wire.created_at ?? null),\n sourceOrder,\n });\n};\n\n/**\n * GitHub-backed host reads for maintainer adjudication, installed by\n * `gitHubReviewLayers` in `github-env.ts` at the public composition root: this action's own\n * inline finding threads (roots authored by the configured review author)\n * with their replies, and the pull request's top-level conversation comments.\n * Both listings are creation-ordered.\n */\nexport const gitHubReviewAdjudicationHostLayer: Layer.Layer<\n ReviewAdjudicationHost,\n never,\n GitHubReviewTarget | HttpClient.HttpClient\n> = Layer.effect(ReviewAdjudicationHost)(\n Effect.gen(function* () {\n const target = yield* GitHubReviewTarget;\n const client = yield* HttpClient.HttpClient;\n const reviewAuthorLogin = (\n target.reviewAuthorLogin ?? DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN\n ).toLowerCase();\n const asAdjudicationFailure =\n (operation: string) =>\n (error: { readonly _tag: string; readonly message?: string }): ReviewAdjudicationFailure =>\n ReviewAdjudicationFailure.make({\n operation,\n reason: `${error._tag}: ${error.message ?? \"request failed\"}`.slice(0, 2_048),\n });\n const decodeAdjudication = <S extends Schema.Top>(schema: S, operation: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return (response: HttpClientResponse.HttpClientResponse) =>\n response.json.pipe(\n Effect.mapError(asAdjudicationFailure(operation)),\n Effect.flatMap((body) =>\n decode(body).pipe(Effect.mapError(asAdjudicationFailure(operation))),\n ),\n );\n };\n const listPaged = <A>(input: {\n readonly operation: string;\n readonly url: string;\n readonly decode: (\n response: HttpClientResponse.HttpClientResponse,\n ) => Effect.Effect<ReadonlyArray<A>, ReviewAdjudicationFailure>;\n }) =>\n Effect.gen(function* () {\n const values: Array<A> = [];\n const perPage = 100;\n for (let page = 1; page <= MAX_ADJUDICATION_PAGES; page += 1) {\n const response = yield* client\n .execute(\n withCommonHeaders(\n HttpClientRequest.get(input.url).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.setUrlParams({\n per_page: String(perPage),\n page: String(page),\n sort: \"created\",\n direction: \"asc\",\n }),\n ),\n target.token,\n ),\n )\n .pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(asAdjudicationFailure(input.operation)),\n );\n const pageValues = yield* input.decode(response);\n values.push(...pageValues);\n if (pageValues.length < perPage) return values;\n }\n return yield* ReviewAdjudicationFailure.make({\n operation: input.operation,\n reason: `history exceeds the bounded ${MAX_ADJUDICATION_PAGES * 100}-item lookup`,\n });\n });\n\n const listFindingThreads = Effect.gen(function* () {\n const wires = yield* listPaged({\n operation: \"listReviewCommentsForAdjudication\",\n url: `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}/comments`,\n decode: decodeAdjudication(\n GitHubThreadCommentsPageWire,\n \"listReviewCommentsForAdjudication\",\n ),\n });\n const positiveLine = (value: number | null | undefined): number | null =>\n value !== undefined && value !== null && value > 0 ? value : null;\n const threads = new Map<\n number,\n { readonly root: (typeof wires)[number]; readonly replies: Array<AdjudicationComment> }\n >();\n for (const wire of wires) {\n if (wire.in_reply_to_id !== undefined && wire.in_reply_to_id !== null) continue;\n // Only this action's own finding threads can be adjudicated inline.\n if (wire.user?.login.toLowerCase() !== reviewAuthorLogin) continue;\n threads.set(wire.id, { root: wire, replies: [] });\n }\n for (const [sourceOrder, wire] of wires.entries()) {\n if (wire.in_reply_to_id === undefined || wire.in_reply_to_id === null) continue;\n const thread = threads.get(wire.in_reply_to_id);\n if (thread === undefined) continue;\n const reply = toAdjudicationComment(wire, sourceOrder);\n if (reply === undefined) continue;\n const command = parseThreadAdjudication(reply.body);\n if (command === undefined) continue;\n if (!AUTHORIZED_ADJUDICATION_ASSOCIATIONS.has(reply.authorAssociation)) {\n yield* Effect.logDebug(\n `Ignored inline adjudication command from @${reply.authorLogin} (${reply.authorAssociation}).`,\n );\n continue;\n }\n if (thread.replies.length >= MAX_THREAD_ADJUDICATION_COMMANDS) {\n return yield* ReviewAdjudicationFailure.make({\n operation: \"listReviewCommentsForAdjudication\",\n reason: `inline thread ${wire.in_reply_to_id} exceeds the bounded ${MAX_THREAD_ADJUDICATION_COMMANDS}-command adjudication lookup`,\n });\n }\n thread.replies.push(reply);\n }\n return [...threads.values()]\n .filter((thread) => thread.root.path.length > 0 && thread.root.path.length <= 500)\n .map(({ root, replies }) => {\n const endLine = positiveLine(root.line ?? root.original_line);\n const startLine = positiveLine(root.start_line ?? root.original_start_line) ?? endLine;\n return AdjudicableThread.make({\n path: root.path,\n startLine,\n endLine,\n rootBody: root.body.slice(0, 65_536),\n replies,\n });\n });\n });\n\n const listIssueComments = Effect.gen(function* () {\n const wires = yield* listPaged({\n operation: \"listIssueCommentsForAdjudication\",\n url: `${target.apiUrl}/repos/${target.repository}/issues/${target.number}/comments`,\n decode: decodeAdjudication(GitHubIssueCommentsPageWire, \"listIssueCommentsForAdjudication\"),\n });\n return wires.flatMap((wire, sourceOrder) => {\n const comment = toAdjudicationComment(wire, sourceOrder);\n return comment === undefined ? [] : [comment];\n });\n });\n\n return ReviewAdjudicationHost.of({ listFindingThreads, listIssueComments });\n }),\n);\n\n// --- Prior reviews (fingerprint deduplication) ---------------------------------\n\n/** Reading the pull request's previously posted reviews failed. */\nexport class PriorReviewLookupFailure extends Schema.TaggedError<PriorReviewLookupFailure>()(\n \"PriorReviewLookupFailure\",\n {\n reason: Schema.String,\n },\n) {\n override get message() {\n return `Prior-review lookup failed: ${this.reason}`;\n }\n}\n\n/**\n * Read-only view of this package's previously posted reviews on the target\n * pull request — the deduplication state for unchanged-changeset skipping.\n */\nexport class PriorReviews extends Context.Service<\n PriorReviews,\n {\n /** The fingerprint embedded in the most recent marker-bearing review. */\n readonly latestFingerprint: Effect.Effect<Option.Option<string>, PriorReviewLookupFailure>;\n /** The latest authenticated, successfully covered review state marker. */\n readonly latestState: Effect.Effect<\n Option.Option<ReviewState>,\n PriorReviewLookupFailure,\n ReviewStateAuthenticator\n >;\n /** Compare a previously reviewed head to the live current head. */\n readonly compareHeads: (\n baseSha: string,\n headSha: string,\n ) => Effect.Effect<ReviewHeadComparison, PriorReviewLookupFailure>;\n /**\n * Compare complete commit tree snapshots for a bounded path allowlist.\n * Used when the reviewed head is not a git ancestor after a rebase,\n * amend, or force-push.\n */\n readonly compareTrees: (\n baseSha: string,\n headSha: string,\n paths: ReadonlyArray<string>,\n ) => Effect.Effect<ReviewTreeComparison, PriorReviewLookupFailure>;\n }\n>()(\"@effect-agent/pr-review/PriorReviews\") {}\n\nconst GitHubPriorReviewWire = Schema.Struct({\n body: Schema.NullOr(Schema.String),\n commit_id: Schema.String,\n user: Schema.optionalKey(\n Schema.NullOr(\n Schema.Struct({\n login: Schema.String,\n type: Schema.String,\n }),\n ),\n ),\n});\nconst GitHubPriorReviewsPageWire = Schema.Array(GitHubPriorReviewWire);\n\nconst GitHubCompareWire = Schema.Struct({\n status: Schema.Literals([\"ahead\", \"behind\", \"diverged\", \"identical\"]),\n base_commit: Schema.Struct({ sha: Schema.String }),\n merge_base_commit: Schema.Struct({ sha: Schema.String }),\n files: GitHubFilesPageWire,\n});\n\nconst GitHubGitCommitWire = Schema.Struct({\n sha: GitCommitSha,\n tree: Schema.Struct({ sha: GitCommitSha }),\n});\n\nconst GitHubTreeEntryFields = {\n path: Schema.String.check(Schema.isMaxLength(4_096)),\n sha: GitCommitSha,\n} as const;\n\nconst GitHubTreeEntryWire = Schema.Union([\n Schema.Struct({\n ...GitHubTreeEntryFields,\n mode: Schema.Literals([\"100644\", \"100755\", \"120000\"]),\n type: Schema.Literal(\"blob\"),\n }),\n Schema.Struct({\n ...GitHubTreeEntryFields,\n mode: Schema.Literal(\"040000\"),\n type: Schema.Literal(\"tree\"),\n }),\n Schema.Struct({\n ...GitHubTreeEntryFields,\n mode: Schema.Literal(\"160000\"),\n type: Schema.Literal(\"commit\"),\n }),\n]);\n\nconst MAX_RECURSIVE_TREE_ENTRIES = 100_000;\nconst GitHubTreeWire = Schema.Struct({\n sha: GitCommitSha,\n tree: Schema.Array(GitHubTreeEntryWire).check(Schema.isMaxLength(MAX_RECURSIVE_TREE_ENTRIES)),\n truncated: Schema.Boolean,\n});\n\nconst TreeComparisonPaths = Schema.Array(ChangedPath).check(\n Schema.isMaxLength(MAX_TREE_COMPARISON_PATHS),\n);\n\n/** Reviews are paged chronologically; scanning stays bounded. */\nconst MAX_PRIOR_REVIEW_PAGES = 5;\n\n/** GitHub-backed PriorReviews over the pull-request reviews endpoint. */\nexport const gitHubPriorReviewsLayer: Layer.Layer<\n PriorReviews,\n never,\n GitHubReviewTarget | HttpClient.HttpClient\n> = Layer.effect(PriorReviews)(\n Effect.gen(function* () {\n const target = yield* GitHubReviewTarget;\n const client = yield* HttpClient.HttpClient;\n const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;\n const reviewAuthorLogin = target.reviewAuthorLogin ?? DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN;\n const decodePage = Schema.decodeUnknownEffect(GitHubPriorReviewsPageWire);\n const asLookupFailure = (error: { readonly _tag: string; readonly message?: string }) =>\n PriorReviewLookupFailure.make({\n reason: `${error._tag}: ${error.message ?? \"request failed\"}`.slice(0, 2_048),\n });\n const asTreeLookupFailure =\n (operation: string) => (error: { readonly _tag: string; readonly message?: string }) =>\n PriorReviewLookupFailure.make({\n reason: `${operation}: ${error._tag}: ${error.message ?? \"request failed\"}`.slice(\n 0,\n 2_048,\n ),\n });\n const decodeLookupJson = <S extends Schema.Top>(schema: S, operation: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return (response: HttpClientResponse.HttpClientResponse) =>\n response.json.pipe(\n Effect.mapError(asTreeLookupFailure(operation)),\n Effect.flatMap((body) =>\n decode(body).pipe(Effect.mapError(asTreeLookupFailure(operation))),\n ),\n );\n };\n const readMarkers = (authenticator: Option.Option<ReviewStateAuthenticator[\"Service\"]>) =>\n Effect.gen(function* () {\n const perPage = 100;\n let latest = Option.none<string>();\n let latestState = Option.none<ReviewState>();\n for (let page = 1; page <= MAX_PRIOR_REVIEW_PAGES; page += 1) {\n const response = yield* HttpClient.execute(\n withCommonHeaders(\n HttpClientRequest.get(`${prefix}/reviews`).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.setUrlParams({\n per_page: String(perPage),\n page: String(page),\n }),\n ),\n target.token,\n ),\n ).pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(asLookupFailure),\n );\n const wires = yield* response.json.pipe(\n Effect.mapError(asLookupFailure),\n Effect.flatMap((body) => decodePage(body).pipe(Effect.mapError(asLookupFailure))),\n );\n for (const wire of wires) {\n // State controls what required scope may be omitted. Match the bot\n // identity that posts with this target's token; the terminal marker\n // is additionally HMAC authenticated so another workflow or model\n // text cannot forge it.\n if (\n wire.user?.login.toLowerCase() !== reviewAuthorLogin.toLowerCase() ||\n wire.user.type !== \"Bot\"\n ) {\n continue;\n }\n const fingerprint = extractFingerprint(wire.body ?? \"\");\n if (fingerprint !== undefined) latest = Option.some(fingerprint);\n if (Option.isSome(authenticator)) {\n const state = yield* authenticator.value.extract(wire.body ?? \"\").pipe(\n Effect.mapError((error) =>\n PriorReviewLookupFailure.make({\n reason: `${error._tag}: ${error.reason}`.slice(0, 2_048),\n }),\n ),\n );\n if (Option.isSome(state) && state.value.reviewedHeadSha === wire.commit_id) {\n latestState = state;\n }\n }\n }\n if (wires.length < perPage) break;\n if (page === MAX_PRIOR_REVIEW_PAGES) {\n return yield* PriorReviewLookupFailure.make({\n reason: `review history exceeds the bounded ${MAX_PRIOR_REVIEW_PAGES * perPage}-review lookup`,\n });\n }\n }\n return { latestFingerprint: latest, latestState };\n }).pipe(Effect.provideService(HttpClient.HttpClient, client));\n const compareCommits = (baseSha: string, headSha: string) =>\n Effect.gen(function* () {\n const response = yield* HttpClient.execute(\n withCommonHeaders(\n HttpClientRequest.get(\n `${target.apiUrl}/repos/${target.repository}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}`,\n ).pipe(HttpClientRequest.acceptJson),\n target.token,\n ),\n ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asLookupFailure));\n const wire = yield* response.json.pipe(\n Effect.mapError(asLookupFailure),\n Effect.flatMap((body) =>\n Schema.decodeUnknownEffect(GitHubCompareWire)(body).pipe(\n Effect.mapError(asLookupFailure),\n ),\n ),\n );\n const files = wire.files.map(toChangedFile);\n return ReviewHeadComparison.make({\n status: wire.status,\n baseSha: wire.base_commit.sha,\n headSha,\n mergeBaseSha: wire.merge_base_commit.sha,\n files,\n truncated: files.length >= MAX_CHANGED_FILES,\n });\n }).pipe(Effect.provideService(HttpClient.HttpClient, client));\n const readTreeSnapshot = Effect.fn(\"PriorReviews.readTreeSnapshot\")(function* (\n commitSha: string,\n ) {\n const commitResponse = yield* client\n .execute(\n withCommonHeaders(\n HttpClientRequest.get(\n `${target.apiUrl}/repos/${target.repository}/git/commits/${encodeURIComponent(commitSha)}`,\n ).pipe(HttpClientRequest.acceptJson),\n target.token,\n ),\n )\n .pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(asTreeLookupFailure(\"get Git commit\")),\n );\n const commit = yield* decodeLookupJson(\n GitHubGitCommitWire,\n \"decode Git commit\",\n )(commitResponse);\n if (commit.sha !== commitSha) {\n return yield* PriorReviewLookupFailure.make({\n reason: `GitHub returned commit ${commit.sha} for requested snapshot ${commitSha}`,\n });\n }\n const treeResponse = yield* client\n .execute(\n withCommonHeaders(\n HttpClientRequest.get(\n `${target.apiUrl}/repos/${target.repository}/git/trees/${encodeURIComponent(commit.tree.sha)}`,\n ).pipe(\n HttpClientRequest.acceptJson,\n HttpClientRequest.setUrlParams({ recursive: \"1\" }),\n ),\n target.token,\n ),\n )\n .pipe(\n Effect.flatMap(HttpClientResponse.filterStatusOk),\n Effect.mapError(asTreeLookupFailure(\"get recursive Git tree\")),\n );\n const tree = yield* decodeLookupJson(\n GitHubTreeWire,\n \"decode recursive Git tree\",\n )(treeResponse);\n if (tree.sha !== commit.tree.sha) {\n return yield* PriorReviewLookupFailure.make({\n reason: `GitHub returned tree ${tree.sha} for requested tree ${commit.tree.sha}`,\n });\n }\n const entries = new Map<string, typeof GitHubTreeEntryWire.Type>();\n for (const entry of tree.tree) {\n if (entries.has(entry.path)) {\n return yield* PriorReviewLookupFailure.make({\n reason: `GitHub returned duplicate path '${entry.path}' in tree ${tree.sha}`,\n });\n }\n entries.set(entry.path, entry);\n }\n return { entries, truncated: tree.truncated } as const;\n });\n const compareTrees = Effect.fn(\"PriorReviews.compareTrees\")(function* (\n baseSha: string,\n headSha: string,\n paths: ReadonlyArray<string>,\n ) {\n const decodeSha = Schema.decodeUnknownEffect(GitCommitSha);\n const [validatedBaseSha, validatedHeadSha, validatedPaths] = yield* Effect.all([\n decodeSha(baseSha),\n decodeSha(headSha),\n Schema.decodeUnknownEffect(TreeComparisonPaths)(paths),\n ]).pipe(Effect.mapError(asTreeLookupFailure(\"validate tree comparison request\")));\n const uniquePaths = [...new Set(validatedPaths)].sort();\n const { base, head } = yield* Effect.all(\n {\n base: readTreeSnapshot(validatedBaseSha),\n head: readTreeSnapshot(validatedHeadSha),\n },\n { concurrency: 2 },\n );\n if (base.truncated || head.truncated) {\n return ReviewTreeComparison.make({\n baseSha: validatedBaseSha,\n headSha: validatedHeadSha,\n changedPaths: [],\n truncated: true,\n });\n }\n const changedPaths = uniquePaths.filter((path) => {\n const before = base.entries.get(path);\n const after = head.entries.get(path);\n if (before === undefined || after === undefined) return before !== after;\n return before.sha !== after.sha || before.mode !== after.mode || before.type !== after.type;\n });\n return ReviewTreeComparison.make({\n baseSha: validatedBaseSha,\n headSha: validatedHeadSha,\n changedPaths,\n truncated: false,\n });\n });\n return PriorReviews.of({\n latestFingerprint: readMarkers(Option.none()).pipe(\n Effect.map((markers) => markers.latestFingerprint),\n ),\n latestState: Effect.gen(function* () {\n const authenticator = yield* ReviewStateAuthenticator;\n return yield* readMarkers(Option.some(authenticator)).pipe(\n Effect.map((markers) => markers.latestState),\n );\n }),\n compareHeads: compareCommits,\n compareTrees,\n });\n }),\n);\n\n/**\n * Whether the current fingerprint matches the most recent posted review.\n * Fails OPEN: a lookup fault means \"not unchanged\" — the review proceeds,\n * which is the safe direction for a deduplication optimization.\n */\nexport const fingerprintUnchanged = (\n current: string,\n): Effect.Effect<boolean, never, PriorReviews> =>\n Effect.gen(function* () {\n const priorReviews = yield* PriorReviews;\n const latest = yield* priorReviews.latestFingerprint.pipe(\n Effect.orElseSucceed(() => Option.none<string>()),\n );\n return Option.isSome(latest) && latest.value === current;\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