@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.
Files changed (52) hide show
  1. package/README.md +11 -204
  2. package/dist/index.d.mts +92 -914
  3. package/dist/index.mjs +176 -71
  4. package/dist/index.mjs.map +1 -1
  5. package/package.json +3 -18
  6. package/src/index.ts +1 -25
  7. package/src/review.ts +244 -0
  8. package/dist/action.d.mts +0 -215
  9. package/dist/action.mjs +0 -505
  10. package/dist/action.mjs.map +0 -1
  11. package/dist/cli.d.mts +0 -1
  12. package/dist/cli.mjs +0 -106
  13. package/dist/cli.mjs.map +0 -1
  14. package/dist/fan-out-C3yG1cx3.d.mts +0 -1526
  15. package/dist/github-CCuLgyqb.mjs +0 -3437
  16. package/dist/github-CCuLgyqb.mjs.map +0 -1
  17. package/dist/logging-Q4j0oub-.mjs +0 -75
  18. package/dist/logging-Q4j0oub-.mjs.map +0 -1
  19. package/dist/providers-Br9FRn7j.mjs +0 -1349
  20. package/dist/providers-Br9FRn7j.mjs.map +0 -1
  21. package/dist/testing.d.mts +0 -86
  22. package/dist/testing.mjs +0 -184
  23. package/dist/testing.mjs.map +0 -1
  24. package/src/action.ts +0 -906
  25. package/src/cli.ts +0 -235
  26. package/src/internal/action-entry.ts +0 -45
  27. package/src/internal/adjudication.ts +0 -415
  28. package/src/internal/anchors.ts +0 -20
  29. package/src/internal/coverage.ts +0 -357
  30. package/src/internal/diff.ts +0 -193
  31. package/src/internal/effort.ts +0 -86
  32. package/src/internal/factory.ts +0 -357
  33. package/src/internal/fan-out-scripted.ts +0 -77
  34. package/src/internal/fan-out.ts +0 -1148
  35. package/src/internal/fingerprint.ts +0 -89
  36. package/src/internal/fixtures.ts +0 -148
  37. package/src/internal/github-env.ts +0 -164
  38. package/src/internal/github.ts +0 -1218
  39. package/src/internal/ignore.ts +0 -88
  40. package/src/internal/logging.ts +0 -124
  41. package/src/internal/profiles.ts +0 -91
  42. package/src/internal/progress.ts +0 -433
  43. package/src/internal/providers.ts +0 -133
  44. package/src/internal/render.ts +0 -819
  45. package/src/internal/retirement.ts +0 -337
  46. package/src/internal/review-agent.ts +0 -543
  47. package/src/internal/review-state.ts +0 -782
  48. package/src/internal/review-units.ts +0 -493
  49. package/src/internal/run.ts +0 -611
  50. package/src/internal/scripted.ts +0 -108
  51. package/src/internal/source.ts +0 -110
  52. package/src/testing.ts +0 -8
@@ -1,3437 +0,0 @@
1
- import { Context, Crypto, DateTime, Effect, Encoding, Layer, Option, Redacted, Result, Schema } from "effect";
2
- import { Agent, AgentPolicy, AgentRuntime, ToolExecutionClass, ToolResultBounds } from "effect-agent";
3
- import { Tool, Toolkit } from "effect/unstable/ai";
4
- import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
5
- //#region src/internal/diff.ts
6
- /** A repository-relative file path as transported values carry it. */
7
- const ChangedPath = Schema.NonEmptyString.check(Schema.isMaxLength(512));
8
- /** GitHub's changed-file status vocabulary, kept verbatim. */
9
- const ChangedFileStatus = Schema.Literals([
10
- "added",
11
- "removed",
12
- "modified",
13
- "renamed",
14
- "copied",
15
- "changed",
16
- "unchanged"
17
- ]);
18
- /** One file changed by the pull request, with its optional textual patch. */
19
- var ChangedFile = class extends Schema.Class("@effect-agent/pr-review/ChangedFile")({
20
- path: ChangedPath,
21
- status: ChangedFileStatus,
22
- additions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
23
- deletions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
24
- /** Present for renames/copies: the path the file previously had. */
25
- previousPath: Schema.optionalKey(ChangedPath),
26
- /** Unified-diff hunks; absent for binary or oversized files. */
27
- patch: Schema.optionalKey(Schema.String),
28
- /**
29
- * Bounded UTF-8 content used only when the provider omitted `patch`.
30
- * Modified files require both sides; additions require head content and
31
- * deletions require base content. These values are review evidence, never
32
- * GitHub inline-comment anchors.
33
- */
34
- reviewBaseContent: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2e5))),
35
- reviewHeadContent: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2e5)))
36
- }) {};
37
- /** Complete rendered fallback evidence must fit one ordinary model context. */
38
- const MAX_REVIEW_CONTENT_CHARS = 22e4;
39
- /**
40
- * Render complete patchless evidence, or refuse it when a required side is
41
- * absent or B/H annotation would exceed the model-facing bound. Callers use
42
- * this same value for planning and tool output so truncated fallback evidence
43
- * can never count as complete coverage.
44
- */
45
- const renderReviewContent = (file) => {
46
- if (file.patch !== void 0) return void 0;
47
- const includeBase = file.status !== "added";
48
- const includeHead = file.status !== "removed";
49
- const sections = ["[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.]"];
50
- let renderedLength = sections[0]?.length ?? 0;
51
- const append = (part) => {
52
- const nextLength = renderedLength + 1 + part.length;
53
- if (nextLength > 22e4) return false;
54
- sections.push(part);
55
- renderedLength = nextLength;
56
- return true;
57
- };
58
- const appendSide = (side, header, content) => {
59
- if (!append(header)) return false;
60
- const lines = content.split("\n");
61
- for (let index = 0; index < lines.length; index += 1) if (!append(`${side}${index + 1} ${lines[index] ?? ""}`)) return false;
62
- return true;
63
- };
64
- if (includeBase) {
65
- if (file.reviewBaseContent === void 0) return void 0;
66
- if (!appendSide("B", "[BASE VERSION]", file.reviewBaseContent)) return void 0;
67
- }
68
- if (includeHead) {
69
- if (file.reviewHeadContent === void 0) return void 0;
70
- if (!appendSide("H", "[HEAD VERSION]", file.reviewHeadContent)) return void 0;
71
- }
72
- return sections.join("\n");
73
- };
74
- /** Whether complete patchless evidence fits the model-facing review bound. */
75
- const hasReviewableContent = (file) => renderReviewContent(file) !== void 0;
76
- /** Whether the reviewer has either a real patch or bounded textual fallback evidence. */
77
- const isReviewableFile = (file) => file.patch !== void 0 || hasReviewableContent(file);
78
- const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
79
- /**
80
- * Parse unified-diff hunk text into coordinate-tagged lines. Lines outside a
81
- * recognized hunk header are ignored rather than guessed at.
82
- */
83
- const parsePatch = (patch) => {
84
- const lines = [];
85
- let oldLine = 0;
86
- let newLine = 0;
87
- let inHunk = false;
88
- for (const raw of patch.split("\n")) {
89
- const header = HUNK_HEADER.exec(raw);
90
- if (header !== null) {
91
- oldLine = Number(header[1]);
92
- newLine = Number(header[2]);
93
- inHunk = true;
94
- continue;
95
- }
96
- if (!inHunk) continue;
97
- if (raw.startsWith("+")) {
98
- lines.push({
99
- kind: "add",
100
- oldLine: void 0,
101
- newLine,
102
- text: raw.slice(1)
103
- });
104
- newLine += 1;
105
- } else if (raw.startsWith("-")) {
106
- lines.push({
107
- kind: "del",
108
- oldLine,
109
- newLine: void 0,
110
- text: raw.slice(1)
111
- });
112
- oldLine += 1;
113
- } else if (raw.startsWith(" ") || raw === "") {
114
- lines.push({
115
- kind: "context",
116
- oldLine,
117
- newLine,
118
- text: raw.slice(1)
119
- });
120
- oldLine += 1;
121
- newLine += 1;
122
- } else if (raw.startsWith("\\")) {} else inHunk = false;
123
- }
124
- return lines;
125
- };
126
- /**
127
- * The new-file line numbers a GitHub review comment may anchor to on the
128
- * RIGHT side: every added or context line that appears in the diff.
129
- */
130
- const commentableLines = (patch) => {
131
- const lines = /* @__PURE__ */ new Set();
132
- for (const line of parsePatch(patch)) if (line.newLine !== void 0) lines.add(line.newLine);
133
- return lines;
134
- };
135
- /**
136
- * Render a patch with explicit RIGHT-side line numbers so the model can
137
- * anchor findings without arithmetic. `R<n>` marks a line that exists in the
138
- * new version of the file (`+` added, blank context); deleted lines keep a
139
- * bare `-` marker and no number.
140
- */
141
- const annotatePatch = (patch) => {
142
- const output = [];
143
- let oldLine = 0;
144
- let newLine = 0;
145
- let inHunk = false;
146
- for (const raw of patch.split("\n")) {
147
- const header = HUNK_HEADER.exec(raw);
148
- if (header !== null) {
149
- oldLine = Number(header[1]);
150
- newLine = Number(header[2]);
151
- inHunk = true;
152
- output.push(raw);
153
- continue;
154
- }
155
- if (!inHunk) continue;
156
- if (raw.startsWith("+")) {
157
- output.push(`R${newLine} + ${raw.slice(1)}`);
158
- newLine += 1;
159
- } else if (raw.startsWith("-")) {
160
- output.push(` - ${raw.slice(1)}`);
161
- oldLine += 1;
162
- } else if (raw.startsWith(" ") || raw === "") {
163
- output.push(`R${newLine} ${raw.slice(1)}`);
164
- oldLine += 1;
165
- newLine += 1;
166
- } else if (raw.startsWith("\\")) output.push(` ${raw}`);
167
- else inHunk = false;
168
- }
169
- return output.join("\n");
170
- };
171
- //#endregion
172
- //#region src/internal/source.ts
173
- /** Reading a file head version larger than this is refused, never truncated silently. */
174
- const MAX_FILE_CHARS = 2e5;
175
- /** The changeset surface is bounded; larger pull requests fail typed. */
176
- const MAX_CHANGED_FILES = 300;
177
- /** Pull-request identity and framing shown to the agent as its mission. */
178
- var PullRequestMetadata = class extends Schema.Class("@effect-agent/pr-review/PullRequestMetadata")({
179
- /** `owner/name`, exactly as GitHub renders it. */
180
- repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),
181
- number: Schema.Int.check(Schema.isGreaterThan(0)),
182
- title: Schema.String.check(Schema.isMaxLength(400)),
183
- /** Author-provided description; empty when the author left none. */
184
- body: Schema.String.check(Schema.isMaxLength(2e4)),
185
- baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
186
- /** Exact base commit used to validate persisted incremental-review lineage. */
187
- baseSha: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(64))),
188
- headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
189
- headSha: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
190
- /** GitHub's own changed-file total; may exceed what `changedFiles` returns. */
191
- totalChangedFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
192
- }) {};
193
- /** The upstream source failed: API error, network fault, or malformed payload. */
194
- var PullRequestSourceFailure = class extends Schema.TaggedError()("PullRequestSourceFailure", {
195
- operation: Schema.String,
196
- reason: Schema.String
197
- }) {
198
- get message() {
199
- return `Pull-request source operation '${this.operation}' failed: ${this.reason}`;
200
- }
201
- };
202
- /** A model-supplied path or range was invalid; always fail-closed (SEC-007). */
203
- var ReviewInputViolation = class extends Schema.TaggedError()("ReviewInputViolation", {
204
- input: Schema.String,
205
- reason: Schema.String
206
- }) {
207
- get message() {
208
- return `Rejected review input '${this.input}': ${this.reason}`;
209
- }
210
- };
211
- const BACKSLASH = String.fromCharCode(92);
212
- /**
213
- * Normalize and validate one model-supplied repository-relative path.
214
- * Absolute paths, drive letters, backslashes, empty segments, `.` and `..`
215
- * segments are all violations — never silently fixed. The changeset list is
216
- * the real allowlist; this check is defense in depth for URL construction.
217
- */
218
- const normalizeRepoRelativePath = (path) => {
219
- const fail = (reason) => Effect.fail(ReviewInputViolation.make({
220
- input: path,
221
- reason
222
- }));
223
- if (path.length === 0 || path.length > 512) return fail("Path length is out of bounds.");
224
- if (path.includes(BACKSLASH)) return fail("Path contains a forbidden backslash.");
225
- if (path.startsWith("/") || /^[A-Za-z]:/.test(path)) return fail("Path must be repository-relative, not absolute.");
226
- const segments = path.split("/");
227
- for (const segment of segments) if (segment === "" || segment === "." || segment === "..") return fail("Path segments must not be empty, '.', or '..'.");
228
- return Effect.succeed(segments.join("/"));
229
- };
230
- /** Read-only view of one pull request; the only repository access tools get. */
231
- var PullRequestSource = class extends Context.Service()("@effect-agent/pr-review/PullRequestSource") {};
232
- //#endregion
233
- //#region src/internal/review-agent.ts
234
- /** The hard findings bound carried by the CodeReview schema. */
235
- const MAX_FINDINGS = 20;
236
- /** The hard non-anchored-concerns bound carried by the CodeReview schema. */
237
- const MAX_CONCERNS = 10;
238
- /** Maximum characters in one deterministic model-visible evidence chunk. */
239
- const MAX_PATCH_CHARS = 6e4;
240
- /** The encoded Tool result must retain one complete bounded content fallback. */
241
- const REVIEW_TOOL_RESULT_MAX_BYTES = 2 * 1024 * 1024;
242
- /** One `read_file` slice never exceeds this many lines. */
243
- const MAX_SLICE_LINES = 1e3;
244
- const DEFAULT_SLICE_LINES = 400;
245
- var ChangedFileSummary = class extends Schema.Class("@effect-agent/pr-review/ChangedFileSummary")({
246
- path: ChangedPath,
247
- status: ChangedFileStatus,
248
- additions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
249
- deletions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
250
- hasTextualDiff: Schema.Boolean,
251
- /** True when a missing patch was recovered as bounded UTF-8 base/head content. */
252
- hasReviewableContent: Schema.Boolean
253
- }) {};
254
- var ChangedFilesView = class extends Schema.Class("@effect-agent/pr-review/ChangedFilesView")({
255
- totalFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
256
- /** True when the pull request has more changed files than are listed here. */
257
- truncated: Schema.Boolean,
258
- files: Schema.Array(ChangedFileSummary).check(Schema.isMaxLength(300))
259
- }) {};
260
- var ListChangedFilesQuery = class extends Schema.Class("@effect-agent/pr-review/ListChangedFilesQuery")({
261
- /** Explicit constant keeps the zero-choice operation compatible with strict provider schemas. */
262
- scope: Schema.Literal("all") }) {};
263
- const ListChangedFiles = Tool.make("list_changed_files", {
264
- description: "List every file changed by this pull request with its status, line counts, and whether a textual diff is available.",
265
- parameters: ListChangedFilesQuery,
266
- success: ChangedFilesView,
267
- failure: PullRequestSourceFailure,
268
- failureMode: "error",
269
- dependencies: [PullRequestSource]
270
- }).annotate(ToolExecutionClass, "readonly");
271
- var FileDiffQuery = class extends Schema.Class("@effect-agent/pr-review/FileDiffQuery")({ path: ChangedPath }) {};
272
- var FileDiffView = class extends Schema.Class("@effect-agent/pr-review/FileDiffView")({
273
- path: ChangedPath,
274
- status: ChangedFileStatus,
275
- reviewMode: Schema.Literals([
276
- "diff",
277
- "content",
278
- "unavailable"
279
- ]),
280
- /**
281
- * The unified diff with explicit RIGHT-side line numbers: `R<n>` marks a
282
- * line present in the new file version (only those may anchor findings);
283
- * `-` marks removed lines. For content fallback, `B<n>` and `H<n>`
284
- * identify base/head lines for reading only; they are never valid anchors.
285
- * Empty only when neither a patch nor bounded textual content exists.
286
- */
287
- annotatedPatch: Schema.String,
288
- truncated: Schema.Boolean
289
- }) {};
290
- /**
291
- * Split complete model-visible evidence at deterministic line boundaries.
292
- * A pathological single line is hard-sliced so every character is still
293
- * assigned and every chunk remains within the provider-independent bound.
294
- */
295
- const boundedEvidenceChunks = (evidence) => {
296
- if (evidence.length <= 6e4) return [evidence];
297
- const chunks = [];
298
- let offset = 0;
299
- while (offset < evidence.length) {
300
- let end = Math.min(offset + MAX_PATCH_CHARS, evidence.length);
301
- if (end < evidence.length) {
302
- const boundary = evidence.lastIndexOf("\n", end - 1);
303
- if (boundary >= offset) end = boundary + 1;
304
- }
305
- if (end === offset) end = Math.min(offset + MAX_PATCH_CHARS, evidence.length);
306
- chunks.push(evidence.slice(offset, end));
307
- offset = end;
308
- }
309
- return chunks;
310
- };
311
- /** Complete bounded evidence chunks used by deterministic fan-out planning. */
312
- const fileReviewEvidenceChunks = (file) => {
313
- const contentEvidence = renderReviewContent(file);
314
- const reviewMode = file.patch !== void 0 ? "diff" : contentEvidence !== void 0 ? "content" : "unavailable";
315
- const annotated = file.patch === void 0 ? contentEvidence ?? "" : annotatePatch(file.patch);
316
- return boundedEvidenceChunks(annotated).map((annotatedPatch) => ({
317
- reviewMode,
318
- annotatedPatch
319
- }));
320
- };
321
- /** Host-owned rendering of one changed file's bounded review evidence. */
322
- const fileDiffView = (file) => {
323
- const chunks = fileReviewEvidenceChunks(file);
324
- const first = chunks[0] ?? {
325
- reviewMode: "unavailable",
326
- annotatedPatch: ""
327
- };
328
- const truncated = first.reviewMode === "diff" && chunks.length > 1;
329
- return FileDiffView.make({
330
- path: file.path,
331
- status: file.status,
332
- reviewMode: first.reviewMode,
333
- annotatedPatch: truncated ? `${first.annotatedPatch}\n[diff truncated]` : first.annotatedPatch,
334
- truncated
335
- });
336
- };
337
- const ReadFileDiff = Tool.make("read_file_diff", {
338
- description: "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.",
339
- parameters: FileDiffQuery,
340
- success: FileDiffView,
341
- failure: Schema.Union([PullRequestSourceFailure, ReviewInputViolation]),
342
- failureMode: "return",
343
- dependencies: [PullRequestSource]
344
- }).annotate(ToolExecutionClass, "readonly");
345
- var FileSliceQuery = class extends Schema.Class("@effect-agent/pr-review/FileSliceQuery")({
346
- path: ChangedPath,
347
- /** 1-based first line to read; defaults to 1. */
348
- startLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
349
- /** Number of lines to read; defaults to 400, capped at 1000. */
350
- maxLines: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThanOrEqualTo(MAX_SLICE_LINES)))
351
- }) {};
352
- var FileSlice = class extends Schema.Class("@effect-agent/pr-review/FileSlice")({
353
- path: ChangedPath,
354
- startLine: Schema.Int.check(Schema.isGreaterThan(0)),
355
- endLine: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
356
- totalLines: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
357
- /** Slice content with each line prefixed by its 1-based line number. */
358
- content: Schema.String
359
- }) {};
360
- const ReadFile = Tool.make("read_file", {
361
- description: "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.",
362
- parameters: FileSliceQuery,
363
- success: FileSlice,
364
- failure: Schema.Union([PullRequestSourceFailure, ReviewInputViolation]),
365
- failureMode: "return",
366
- dependencies: [PullRequestSource]
367
- }).annotate(ToolExecutionClass, "readonly");
368
- const ReviewToolkit = Toolkit.make(ListChangedFiles, ReadFileDiff, ReadFile);
369
- /**
370
- * The `list_changed_files` handler, shared by the flat reviewer's toolkit and
371
- * any extended toolkit built by the configuration factory.
372
- */
373
- const listChangedFilesHandler = (_query) => Effect.gen(function* () {
374
- const source = yield* PullRequestSource;
375
- const files = yield* source.changedFiles;
376
- const metadata = yield* source.metadata;
377
- return ChangedFilesView.make({
378
- totalFiles: metadata.totalChangedFiles,
379
- truncated: files.length < metadata.totalChangedFiles,
380
- files: files.map((file) => ChangedFileSummary.make({
381
- path: file.path,
382
- status: file.status,
383
- additions: file.additions,
384
- deletions: file.deletions,
385
- hasTextualDiff: file.patch !== void 0,
386
- hasReviewableContent: hasReviewableContent(file)
387
- }))
388
- });
389
- });
390
- /**
391
- * The `read_file_diff` handler, shared verbatim by the flat reviewer's
392
- * toolkit and the fan-out child's toolkit (fan-out.ts).
393
- */
394
- const readFileDiffHandler = (query) => Effect.gen(function* () {
395
- const source = yield* PullRequestSource;
396
- const relative = yield* normalizeRepoRelativePath(query.path);
397
- const file = (yield* source.changedFiles).find((candidate) => candidate.path === relative);
398
- if (file === void 0) return yield* ReviewInputViolation.make({
399
- input: relative,
400
- reason: "Path is not part of this pull request's changeset."
401
- });
402
- return fileDiffView(file);
403
- });
404
- /**
405
- * The `read_file` handler, shared verbatim by the flat reviewer's toolkit
406
- * and the fan-out child's toolkit (fan-out.ts).
407
- */
408
- const readFileHandler = (query) => Effect.gen(function* () {
409
- const source = yield* PullRequestSource;
410
- const relative = yield* normalizeRepoRelativePath(query.path);
411
- const lines = (yield* source.readFile(relative)).split("\n");
412
- const startLine = query.startLine ?? 1;
413
- const maxLines = query.maxLines ?? DEFAULT_SLICE_LINES;
414
- if (startLine > lines.length) return yield* ReviewInputViolation.make({
415
- input: `${relative}:${startLine}`,
416
- reason: `startLine is beyond the end of the file (${lines.length} lines).`
417
- });
418
- const slice = lines.slice(startLine - 1, startLine - 1 + maxLines);
419
- const endLine = startLine + slice.length - 1;
420
- return FileSlice.make({
421
- path: relative,
422
- startLine,
423
- endLine,
424
- totalLines: lines.length,
425
- content: slice.map((text, index) => `${String(startLine + index).padStart(5)} ${text}`).join("\n")
426
- });
427
- });
428
- const ReviewToolkitLayer = ReviewToolkit.toLayer({
429
- list_changed_files: listChangedFilesHandler,
430
- read_file_diff: readFileDiffHandler,
431
- read_file: readFileHandler
432
- });
433
- /** Bounded prior-review context lines injected into reviewer instructions. */
434
- const ReviewContextLines = Schema.Array(Schema.String.check(Schema.isMaxLength(1200))).check(Schema.isMaxLength(20));
435
- var ReviewMission = class extends Schema.Class("@effect-agent/pr-review/ReviewMission")({
436
- repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),
437
- number: Schema.Int.check(Schema.isGreaterThan(0)),
438
- title: Schema.String.check(Schema.isMaxLength(400)),
439
- body: Schema.String.check(Schema.isMaxLength(2e4)),
440
- baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
441
- headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
442
- changedFileCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
443
- /**
444
- * Maintainer-adjudicated identities rendered as bounded context lines; the
445
- * reviewer must not re-raise them without materially new evidence. Absent
446
- * from fingerprint missions so an adjudication never invalidates the
447
- * skip-unchanged authority.
448
- */
449
- adjudicatedContext: Schema.optionalKey(ReviewContextLines),
450
- /**
451
- * Prior-round findings on re-reviewed scope, rendered as bounded context
452
- * lines; each must be confirmed, declared fixed, or explicitly withdrawn.
453
- */
454
- priorFindingContext: Schema.optionalKey(ReviewContextLines)
455
- }) {};
456
- const FindingSeverity = Schema.Literals([
457
- "blocking",
458
- "important",
459
- "nit"
460
- ]);
461
- /**
462
- * What kind of problem a finding names. Model-claimed like severity — it is a
463
- * label for scanning a busy review, never an input to the check conclusion.
464
- */
465
- const FindingCategory = Schema.Literals([
466
- "correctness",
467
- "security",
468
- "concurrency",
469
- "performance",
470
- "resources",
471
- "error-handling",
472
- "testing",
473
- "maintainability",
474
- "style",
475
- "docs"
476
- ]);
477
- var ReviewFinding = class extends Schema.Class("@effect-agent/pr-review/ReviewFinding")({
478
- path: ChangedPath,
479
- /** 1-based line numbers in the NEW file version; must appear in the diff. */
480
- startLine: Schema.Int.check(Schema.isGreaterThan(0)),
481
- endLine: Schema.Int.check(Schema.isGreaterThan(0)),
482
- severity: FindingSeverity,
483
- /** Optional problem-kind label rendered next to the severity. */
484
- category: Schema.optionalKey(FindingCategory),
485
- title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),
486
- body: Schema.NonEmptyString.check(Schema.isMaxLength(2e3)),
487
- /** Replacement for exactly lines startLine..endLine; omit when unsure. */
488
- suggestion: Schema.optionalKey(Schema.String.annotate({ description: "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." }).check(Schema.isMaxLength(2e3)))
489
- }) {};
490
- const ReviewVerdict = Schema.Literals([
491
- "approve",
492
- "comment",
493
- "request-changes"
494
- ]);
495
- /**
496
- * A concern with no diff line to anchor to: a missing deletion or cleanup,
497
- * rollout or migration sequencing, a coverage gap the diff implies but does
498
- * not add, or a scope question only the author can answer. Rendered as a
499
- * review-body section instead of an inline comment. `evidencePaths` binds the
500
- * concern to changed files so a later incremental review can invalidate and
501
- * recheck it when any supporting path changes. It remains optional only for
502
- * decoding review output and continuity state written before path binding was
503
- * introduced; a pathless concern cannot authorize incremental continuity.
504
- */
505
- var ReviewConcern = class extends Schema.Class("@effect-agent/pr-review/ReviewConcern")({
506
- evidencePaths: Schema.optionalKey(Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3))),
507
- severity: FindingSeverity,
508
- title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),
509
- body: Schema.NonEmptyString.check(Schema.isMaxLength(2e3))
510
- }) {};
511
- /** The per-entry walkthrough summary bound, and the entries bound (the changeset cap). */
512
- const MAX_WALKTHROUGH_SUMMARY_CHARS = 240;
513
- const MAX_WALKTHROUGH_ENTRIES = 300;
514
- /**
515
- * One reviewed file's one-sentence change summary. Rendered only when the
516
- * path is actually part of the changeset — like finding anchors, walkthrough
517
- * paths are validated host-side and invented ones are dropped.
518
- */
519
- var WalkthroughEntry = class extends Schema.Class("@effect-agent/pr-review/WalkthroughEntry")({
520
- path: ChangedPath,
521
- summary: Schema.NonEmptyString.check(Schema.isMaxLength(240))
522
- }) {};
523
- var CodeReview = class extends Schema.Class("@effect-agent/pr-review/CodeReview")({
524
- summary: Schema.NonEmptyString.check(Schema.isMaxLength(4e3)),
525
- verdict: ReviewVerdict,
526
- findings: Schema.Array(ReviewFinding).check(Schema.isMaxLength(20)),
527
- /** Non-anchorable concerns; absent when the review raises none. */
528
- concerns: Schema.optionalKey(Schema.Array(ReviewConcern).check(Schema.isMaxLength(10))),
529
- /** Per-file change summaries; absent when the model provides none. */
530
- walkthrough: Schema.optionalKey(Schema.Array(WalkthroughEntry).check(Schema.isMaxLength(300)))
531
- }) {};
532
- const resolveGuidance = (guidance, mission) => {
533
- if (guidance === void 0) return [];
534
- const value = typeof guidance === "function" ? guidance(mission) : guidance;
535
- return (typeof value === "string" ? [value] : value).filter((line) => line.length > 0);
536
- };
537
- /** Clamp a configured findings bound into the schema-supported range. */
538
- const clampMaxFindings = (maxFindings) => maxFindings === void 0 ? 20 : Math.min(20, Math.max(1, Math.trunc(maxFindings)));
539
- /** Build the flat reviewer's instructions with optional consumer guidance. */
540
- const makeReviewInstructions = (options = {}) => (mission) => {
541
- const maxFindings = clampMaxFindings(options.maxFindings);
542
- return [
543
- `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).`,
544
- mission.body.length > 0 ? `Author description:\n${mission.body}` : "The author provided no description.",
545
- ...resolveGuidance(options.guidance, mission),
546
- ...mission.adjudicatedContext === void 0 || mission.adjudicatedContext.length === 0 ? [] : ["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:", ...mission.adjudicatedContext.map((line) => `- ${line}`)],
547
- ...mission.priorFindingContext === void 0 || mission.priorFindingContext.length === 0 ? [] : ["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:", ...mission.priorFindingContext.map((line) => `- ${line}`)],
548
- "Work in this order:",
549
- "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.",
550
- "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.",
551
- "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.",
552
- "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.",
553
- "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.",
554
- "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.",
555
- "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.",
556
- "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.",
557
- `6. Write a walkthrough: for every file whose evidence you examined, one factual sentence (<= 240 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.`,
558
- "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>}.",
559
- `Report at most ${maxFindings} findings and at most 10 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.`,
560
- "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."
561
- ].join("\n");
562
- };
563
- /** The default flat-reviewer instructions: no guidance, schema-cap findings. */
564
- const reviewInstructions = makeReviewInstructions();
565
- /** The default flat-reviewer execution bounds. */
566
- const defaultReviewPolicy = AgentPolicy.make({
567
- maxTurns: 12,
568
- maxToolCalls: 24,
569
- maxDuration: "8 minutes",
570
- toolConcurrency: 2,
571
- repeatedFailureLimit: 12,
572
- tokenBudget: 3e5,
573
- contextTokenLimit: 15e4,
574
- toolResultBounds: ToolResultBounds.make({ maxBytes: REVIEW_TOOL_RESULT_MAX_BYTES }),
575
- onExhaustion: "final-answer"
576
- });
577
- const PullRequestReviewer = Agent.define("pr-reviewer", {
578
- input: ReviewMission,
579
- output: CodeReview,
580
- instructions: reviewInstructions,
581
- toolkit: ReviewToolkit,
582
- policy: defaultReviewPolicy,
583
- description: "Review one pull request read-only: list the changeset, read annotated diffs and head-file context, and return a structured, line-anchored code review.",
584
- metadata: {
585
- deploymentClass: "E",
586
- surface: "read-only"
587
- }
588
- });
589
- //#endregion
590
- //#region src/internal/review-state.ts
591
- const ReviewMode = Schema.Literals(["incremental", "final"]);
592
- const ReviewScopeMode = Schema.Literals(["incremental", "full"]);
593
- const GitCommitSha = Schema.NonEmptyString.check(Schema.isMaxLength(64), Schema.isPattern(/^[0-9a-f]{40,64}$/));
594
- const Fingerprint = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/));
595
- const StoredText = Schema.NonEmptyString.check(Schema.isMaxLength(800));
596
- /** A compact unresolved finding suitable for the bounded review-body marker. */
597
- var StoredReviewFinding = class extends Schema.Class("@effect-agent/pr-review/StoredReviewFinding")({
598
- path: ChangedPath,
599
- startLine: Schema.Int.check(Schema.isGreaterThan(0)),
600
- endLine: Schema.Int.check(Schema.isGreaterThan(0)),
601
- severity: FindingSeverity,
602
- title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),
603
- body: StoredText
604
- }) {};
605
- /** A compact unresolved non-anchored concern with its invalidation paths. */
606
- var StoredReviewConcern = class extends Schema.Class("@effect-agent/pr-review/StoredReviewConcern")({
607
- /** Absent only on legacy state written before concern path binding. */
608
- evidencePaths: Schema.optionalKey(Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3))),
609
- severity: FindingSeverity,
610
- title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),
611
- body: StoredText
612
- }) {};
613
- /** How a maintainer settled a previously raised finding or concern. */
614
- const AdjudicationDisposition = Schema.Literals([
615
- "accepted-risk",
616
- "refuted",
617
- "obsolete"
618
- ]);
619
- /** The adjudications bound carried by the ReviewState schema. */
620
- const MAX_STORED_ADJUDICATIONS = 20;
621
- /**
622
- * One maintainer adjudication of a finding or concern identity. Anchored
623
- * findings carry their full location identity; unanchored concerns are
624
- * identified by title alone, so the location fields stay absent.
625
- */
626
- const StoredAdjudicationFields = Schema.Struct({
627
- path: Schema.optionalKey(ChangedPath),
628
- startLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
629
- endLine: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
630
- title: Schema.NonEmptyString.check(Schema.isMaxLength(120)),
631
- disposition: AdjudicationDisposition,
632
- reason: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(300))),
633
- /** GitHub login of the maintainer whose comment adjudicated the identity. */
634
- actor: Schema.NonEmptyString.check(Schema.isMaxLength(100))
635
- }).check(Schema.makeFilter((adjudication) => {
636
- const locationParts = [
637
- adjudication.path,
638
- adjudication.startLine,
639
- adjudication.endLine
640
- ].filter((part) => part !== void 0).length;
641
- return locationParts === 0 || locationParts === 3 ? void 0 : "path, startLine, and endLine must be either all present or all absent";
642
- }, { title: "adjudication locations are complete or unanchored" }));
643
- var StoredAdjudication = class extends Schema.Class("@effect-agent/pr-review/StoredAdjudication")(StoredAdjudicationFields) {};
644
- /**
645
- * The one finding-identity composition shared by retirement, adjudication,
646
- * and settlement. A tagged JSON tuple keeps anchored findings in a namespace
647
- * disjoint from title-only concerns and remains unambiguous even when
648
- * untrusted path or title text contains delimiter characters.
649
- */
650
- const findingIdentity = (finding) => JSON.stringify([
651
- "finding",
652
- finding.path,
653
- finding.startLine,
654
- finding.endLine,
655
- finding.title
656
- ]);
657
- /** The disjoint title-only identity namespace for unanchored concerns. */
658
- const concernIdentity = (concern) => JSON.stringify(["concern", concern.title]);
659
- /**
660
- * An adjudication's identity: the shared finding identity when anchored, the
661
- * disjoint concern identity when unanchored.
662
- */
663
- const adjudicationIdentity = (adjudication) => adjudication.path !== void 0 && adjudication.startLine !== void 0 && adjudication.endLine !== void 0 ? findingIdentity({
664
- path: adjudication.path,
665
- startLine: adjudication.startLine,
666
- endLine: adjudication.endLine,
667
- title: adjudication.title
668
- }) : concernIdentity(adjudication);
669
- /** The carried-scope bound; a run that cannot fit its leftovers publishes no state. */
670
- const MAX_STORED_UNREVIEWED_PATHS = 100;
671
- /** Failed-pass records stored beside the leftover paths; one per unit stage. */
672
- const MAX_STORED_UNREVIEWED_PASSES = 24;
673
- /** Stages a leftover path may need retried on the next incremental run. */
674
- const UnreviewedStage = Schema.Literals([
675
- "discovery",
676
- "specialist",
677
- "verification"
678
- ]);
679
- /** One failed fan-out pass whose stage remains attached to its exact paths. */
680
- var StoredUnreviewedPass = class extends Schema.Class("@effect-agent/pr-review/StoredUnreviewedPass")({
681
- stage: UnreviewedStage,
682
- paths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12))
683
- }) {};
684
- /**
685
- * Versioned state embedded after EVERY completed run that can be signed. The
686
- * head plus full-scope fingerprint forms an incremental baseline; an absent
687
- * unresolved item never means the path is defect-free. `unreviewedPaths`
688
- * carries retryable review gaps (failed passes) forward so the next
689
- * incremental run re-reviews exactly them plus the new delta — the baseline
690
- * advances monotonically instead of freezing on one flaky pass and reopening
691
- * the whole post-baseline scope. Storing hundreds of path strings separately
692
- * would not fit GitHub's bounded review body in the worst case.
693
- */
694
- var ReviewState = class extends Schema.Class("@effect-agent/pr-review/ReviewState")({
695
- version: Schema.Literal(1),
696
- repository: Schema.NonEmptyString.check(Schema.isMaxLength(200)),
697
- pullRequestNumber: Schema.Int.check(Schema.isGreaterThan(0)),
698
- baseRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
699
- baseSha: GitCommitSha,
700
- headRef: Schema.NonEmptyString.check(Schema.isMaxLength(300)),
701
- reviewedHeadSha: GitCommitSha,
702
- profileFingerprint: Fingerprint,
703
- settledScopeFingerprint: Fingerprint,
704
- reviewedPathCount: Schema.Int.check(Schema.isBetween({
705
- minimum: 0,
706
- maximum: 300
707
- })),
708
- unresolvedFindings: Schema.Array(StoredReviewFinding).check(Schema.isMaxLength(20)),
709
- unresolvedConcerns: Schema.Array(StoredReviewConcern).check(Schema.isMaxLength(10)),
710
- /** Retryable review gaps carried into the next incremental run's scope. */
711
- unreviewedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(100)),
712
- /** Which failed pass produced those leftovers. */
713
- unreviewedPasses: Schema.Array(StoredUnreviewedPass).check(Schema.isMaxLength(24)),
714
- /**
715
- * True only when the producing run had complete input coverage, no
716
- * unsettled pass, and nothing carried. Skip-unchanged authority: an
717
- * unchanged patch may skip re-review only over a settled state.
718
- */
719
- settled: Schema.Boolean,
720
- lastReviewMode: ReviewScopeMode,
721
- /**
722
- * Maintainer adjudications standing against this pull request. optionalKey
723
- * so state markers signed before the field existed still decode.
724
- */
725
- adjudications: Schema.optionalKey(Schema.Array(StoredAdjudication).check(Schema.isMaxLength(20)))
726
- }) {};
727
- const toStoredFinding = (finding) => StoredReviewFinding.make({
728
- path: finding.path,
729
- startLine: finding.startLine,
730
- endLine: finding.endLine,
731
- severity: finding.severity,
732
- title: finding.title,
733
- body: finding.body.slice(0, 800)
734
- });
735
- const fromStoredFinding = (finding) => ReviewFinding.make({
736
- path: finding.path,
737
- startLine: finding.startLine,
738
- endLine: finding.endLine,
739
- severity: finding.severity,
740
- title: finding.title,
741
- body: finding.body
742
- });
743
- const toStoredConcern = (concern) => StoredReviewConcern.make({
744
- ...concern.evidencePaths === void 0 ? {} : { evidencePaths: concern.evidencePaths },
745
- severity: concern.severity,
746
- title: concern.title,
747
- body: concern.body.slice(0, 800)
748
- });
749
- const fromStoredConcern = (concern) => ReviewConcern.make({
750
- ...concern.evidencePaths === void 0 ? {} : { evidencePaths: concern.evidencePaths },
751
- severity: concern.severity,
752
- title: concern.title,
753
- body: concern.body
754
- });
755
- const STATE_MARKER_PREFIX = "<!-- effect-agent-pr-review state-v1:";
756
- const STATE_MARKER_SUFFIX = " -->";
757
- const STATE_MARKER_PATTERN = /(?:^|\n)<!-- effect-agent-pr-review state-v1:([A-Za-z0-9+/]+={0,2})\.([0-9a-f]{64}) -->$/;
758
- const STATE_SIGNATURE_DOMAIN = "effect-agent-pr-review/state-v1\0";
759
- const MAX_REVIEW_STATE_MARKER_CHARS = 24e3;
760
- const ReviewStateMarker = Schema.NonEmptyString.check(Schema.isMaxLength(MAX_REVIEW_STATE_MARKER_CHARS), Schema.isPattern(/^<!-- effect-agent-pr-review state-v1:[A-Za-z0-9+/]+={0,2}\.[0-9a-f]{64} -->$/)).pipe(Schema.brand("@effect-agent/pr-review/ReviewStateMarker"));
761
- var ReviewStateAuthenticationFailure = class extends Schema.TaggedError()("ReviewStateAuthenticationFailure", {
762
- operation: Schema.Literals(["sign", "verify"]),
763
- reason: Schema.NonEmptyString.check(Schema.isMaxLength(2048))
764
- }) {};
765
- var ReviewStateMarkerTooLarge = class extends Schema.TaggedError()("ReviewStateMarkerTooLarge", {
766
- observedChars: Schema.Int.check(Schema.isGreaterThan(0)),
767
- maximumChars: Schema.Int.check(Schema.isGreaterThan(0))
768
- }) {};
769
- var ReviewStateAuthenticator = class extends Context.Service()("@effect-agent/pr-review/ReviewStateAuthenticator") {};
770
- const authenticationFailure = (operation, cause) => ReviewStateAuthenticationFailure.make({
771
- operation,
772
- reason: String(cause).slice(0, 2048)
773
- });
774
- const hmacKey = (secret, operation) => Effect.tryPromise({
775
- try: () => globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(Redacted.value(secret)), {
776
- name: "HMAC",
777
- hash: "SHA-256"
778
- }, false, ["sign", "verify"]),
779
- catch: (cause) => authenticationFailure(operation, cause)
780
- });
781
- const signatureBytes = (signature) => {
782
- const pairs = signature.match(/../g) ?? [];
783
- const buffer = new ArrayBuffer(pairs.length);
784
- const bytes = new Uint8Array(buffer);
785
- for (let index = 0; index < pairs.length; index += 1) bytes[index] = Number.parseInt(pairs[index] ?? "", 16);
786
- return buffer;
787
- };
788
- /** Validated WebCrypto adapter selected at the Action composition root. */
789
- const webCryptoReviewStateAuthenticatorLayer = (secret) => Layer.succeed(ReviewStateAuthenticator)(ReviewStateAuthenticator.of({
790
- status: "available",
791
- unavailableReason: void 0,
792
- render: (state) => Effect.gen(function* () {
793
- const json = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(ReviewState))(state).pipe(Effect.mapError((cause) => authenticationFailure("sign", cause)));
794
- const payload = Encoding.encodeBase64(json);
795
- const message = new TextEncoder().encode(`${STATE_SIGNATURE_DOMAIN}${payload}`);
796
- const key = yield* hmacKey(secret, "sign");
797
- const signature = yield* Effect.tryPromise({
798
- try: () => globalThis.crypto.subtle.sign("HMAC", key, message),
799
- catch: (cause) => authenticationFailure("sign", cause)
800
- });
801
- const hex = Array.from(new Uint8Array(signature)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
802
- const marker = `${STATE_MARKER_PREFIX}${payload}.${hex}${STATE_MARKER_SUFFIX}`;
803
- if (marker.length > 24e3) return yield* ReviewStateMarkerTooLarge.make({
804
- observedChars: marker.length,
805
- maximumChars: MAX_REVIEW_STATE_MARKER_CHARS
806
- });
807
- return yield* Schema.decodeUnknownEffect(ReviewStateMarker)(marker).pipe(Effect.mapError((cause) => authenticationFailure("sign", cause)));
808
- }),
809
- extract: (body) => {
810
- if (body.length > 6e4) return Effect.succeed(Option.none());
811
- const match = STATE_MARKER_PATTERN.exec(body);
812
- const payload = match?.[1];
813
- const signature = match?.[2];
814
- if (payload === void 0 || signature === void 0) return Effect.succeed(Option.none());
815
- const marker = `${STATE_MARKER_PREFIX}${payload}.${signature}${STATE_MARKER_SUFFIX}`;
816
- if (!Schema.is(ReviewStateMarker)(marker)) return Effect.succeed(Option.none());
817
- const json = Result.getOrUndefined(Encoding.decodeBase64String(payload));
818
- if (json === void 0) return Effect.succeed(Option.none());
819
- const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(ReviewState))(json);
820
- if (Option.isNone(decoded)) return Effect.succeed(Option.none());
821
- const message = new TextEncoder().encode(`${STATE_SIGNATURE_DOMAIN}${payload}`);
822
- return Effect.gen(function* () {
823
- const key = yield* hmacKey(secret, "verify");
824
- return (yield* Effect.tryPromise({
825
- try: () => globalThis.crypto.subtle.verify("HMAC", key, signatureBytes(signature), message),
826
- catch: (cause) => authenticationFailure("verify", cause)
827
- })) ? Option.some(decoded.value) : Option.none();
828
- });
829
- }
830
- }));
831
- /** Explicit no-state implementation for hosts without a stable authentication secret. */
832
- const unavailableReviewStateAuthenticatorLayer = (reason) => {
833
- const safeReason = reason === "" ? "review-state authentication is unavailable" : reason;
834
- return Layer.succeed(ReviewStateAuthenticator)(ReviewStateAuthenticator.of({
835
- status: "unavailable",
836
- unavailableReason: safeReason.slice(0, 1e3),
837
- render: () => Effect.fail(ReviewStateAuthenticationFailure.make({
838
- operation: "sign",
839
- reason: safeReason.slice(0, 2048)
840
- })),
841
- extract: () => Effect.succeed(Option.none())
842
- }));
843
- };
844
- /** The bounded result of GitHub's previous-head...current-head comparison. */
845
- var ReviewHeadComparison = class extends Schema.Class("@effect-agent/pr-review/ReviewHeadComparison")({
846
- status: Schema.Literals([
847
- "ahead",
848
- "behind",
849
- "diverged",
850
- "identical"
851
- ]),
852
- baseSha: GitCommitSha,
853
- headSha: GitCommitSha,
854
- mergeBaseSha: GitCommitSha,
855
- files: Schema.Array(ChangedFile).check(Schema.isMaxLength(300)),
856
- /** GitHub caps compare-file payloads at 300; equality is conservatively truncated. */
857
- truncated: Schema.Boolean
858
- }) {};
859
- /**
860
- * Current and previous paths for 300 PR files plus bounded stored continuity
861
- * paths. The live adapter refuses a larger snapshot-comparison request.
862
- */
863
- const MAX_TREE_COMPARISON_PATHS = 750;
864
- /** A direct comparison of two complete commit tree snapshots. */
865
- var ReviewTreeComparison = class extends Schema.Class("@effect-agent/pr-review/ReviewTreeComparison")({
866
- baseSha: GitCommitSha,
867
- headSha: GitCommitSha,
868
- changedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(750)),
869
- /** True when GitHub returned either recursive tree incompletely. */
870
- truncated: Schema.Boolean
871
- }) {};
872
- const fullReviewSelection = (input) => ({
873
- mode: "full",
874
- reason: input.reason,
875
- files: input.files,
876
- affectedPaths: input.files.flatMap((file) => file.previousPath === void 0 ? [file.path] : [file.path, file.previousPath]),
877
- retryPasses: [],
878
- retryPaths: [],
879
- retryStages: [],
880
- totalFiles: input.totalFiles,
881
- baselineSha: void 0,
882
- priorState: void 0,
883
- profileFingerprint: input.profileFingerprint
884
- });
885
- /** Three-dot lineage from the reviewed head to the current head is usable. */
886
- const isLineageAncestor = (comparison, priorState, currentHeadSha) => comparison.baseSha === priorState.reviewedHeadSha && comparison.headSha === currentHeadSha && comparison.mergeBaseSha === priorState.reviewedHeadSha && !comparison.truncated && (comparison.status === "ahead" || comparison.status === "identical");
887
- /**
888
- * Validate that persisted state belongs to this exact PR/base lineage and the
889
- * same review profile. A mismatch is a full-review reason, never an error that
890
- * silently suppresses review work.
891
- */
892
- const validateReviewState = (state, current, profileFingerprint) => {
893
- if (state.repository !== current.repository || state.pullRequestNumber !== current.number) return "stored state belongs to a different pull request";
894
- if (current.baseSha === void 0) return "the current base commit is unavailable";
895
- if (state.baseRef !== current.baseRef) return "the pull request base ref changed";
896
- if (state.headRef !== current.headRef) return "the pull request head ref changed";
897
- if (state.profileFingerprint !== profileFingerprint) return "the reviewer profile or model configuration changed";
898
- if (state.unresolvedConcerns.some((concern) => concern.evidencePaths === void 0)) return "stored concerns predate affected-path tracking";
899
- };
900
- const filePaths = (file) => file.previousPath === void 0 ? [file.path] : [file.path, file.previousPath];
901
- const incrementalFromDelta = (input) => {
902
- const currentPaths = new Set(input.fullFiles.flatMap(filePaths));
903
- const affectedPaths = /* @__PURE__ */ new Set([...input.deltaPaths, ...input.extraAffectedPaths ?? []]);
904
- const initialAffectedCount = affectedPaths.size;
905
- let expanded = true;
906
- while (expanded) {
907
- expanded = false;
908
- for (const concern of input.priorState.unresolvedConcerns) {
909
- const paths = concern.evidencePaths ?? [];
910
- if (!paths.some((path) => affectedPaths.has(path))) continue;
911
- for (const path of paths) if (!affectedPaths.has(path)) {
912
- affectedPaths.add(path);
913
- expanded = true;
914
- }
915
- }
916
- }
917
- const selectedByPath = /* @__PURE__ */ new Map();
918
- const carriedPaths = input.priorState.unreviewedPaths.filter((path) => currentPaths.has(path));
919
- const retryOnly = /* @__PURE__ */ new Set();
920
- for (const path of carriedPaths) {
921
- if (affectedPaths.has(path)) continue;
922
- retryOnly.add(path);
923
- }
924
- const retryPathsByStage = /* @__PURE__ */ new Map();
925
- const representedRetryPaths = /* @__PURE__ */ new Set();
926
- for (const pass of input.priorState.unreviewedPasses) for (const path of pass.paths) {
927
- if (!retryOnly.has(path)) continue;
928
- const paths = retryPathsByStage.get(pass.stage) ?? /* @__PURE__ */ new Set();
929
- paths.add(path);
930
- retryPathsByStage.set(pass.stage, paths);
931
- representedRetryPaths.add(path);
932
- }
933
- for (const path of retryOnly) {
934
- if (representedRetryPaths.has(path)) continue;
935
- retryOnly.delete(path);
936
- affectedPaths.add(path);
937
- }
938
- const retryPasses = [
939
- "discovery",
940
- "specialist",
941
- "verification"
942
- ].flatMap((stage) => {
943
- const paths = [...retryPathsByStage.get(stage) ?? []].filter((path) => retryOnly.has(path)).sort();
944
- return Array.from({ length: Math.ceil(paths.length / 12) }, (_, index) => StoredUnreviewedPass.make({
945
- stage,
946
- paths: paths.slice(index * 12, (index + 1) * 12)
947
- }));
948
- });
949
- const retryPaths = [...retryOnly].sort();
950
- const retryStages = [...new Set(retryPasses.map((pass) => pass.stage))];
951
- for (const file of input.fullFiles) if (affectedPaths.has(file.path) || file.previousPath !== void 0 && affectedPaths.has(file.previousPath) || retryOnly.has(file.path) || file.previousPath !== void 0 && retryOnly.has(file.previousPath)) selectedByPath.set(file.path, file);
952
- const selectedFiles = [...selectedByPath.values()].sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
953
- const leftoverCount = retryPaths.length;
954
- const carriedReason = leftoverCount > 0 ? `; retrying ${leftoverCount} unchanged leftover path(s) by recorded failed stage` : carriedPaths.length > 0 ? `; retrying ${carriedPaths.length} carried unreviewed path(s)` : "";
955
- const concernPathCount = affectedPaths.size - initialAffectedCount;
956
- const concernReason = concernPathCount === 0 ? "" : `; reopening ${concernPathCount} related concern path(s) for context`;
957
- return {
958
- mode: "incremental",
959
- reason: `${input.reason}${carriedReason}${concernReason}`,
960
- files: selectedFiles,
961
- affectedPaths: [...affectedPaths].sort(),
962
- retryPasses,
963
- retryPaths,
964
- retryStages,
965
- totalFiles: selectedFiles.length,
966
- baselineSha: input.priorState.reviewedHeadSha,
967
- priorState: input.priorState,
968
- profileFingerprint: input.profileFingerprint
969
- };
970
- };
971
- /** Pure, deterministic range selection with conservative full-review fallbacks. */
972
- const selectReviewRange = (input) => {
973
- const full = (reason) => fullReviewSelection({
974
- reason,
975
- files: input.fullFiles,
976
- totalFiles: input.current.totalChangedFiles,
977
- profileFingerprint: input.profileFingerprint
978
- });
979
- if (input.requestedMode === "final") return full("explicit final full-diff audit requested");
980
- if (input.lookupFailure !== void 0) return full(`stored review state could not be recovered: ${input.lookupFailure}`);
981
- if (input.priorState === void 0) return full("no compatible stored review state was found");
982
- const invalid = validateReviewState(input.priorState, input.current, input.profileFingerprint);
983
- if (invalid !== void 0) return full(invalid);
984
- const comparison = input.comparison;
985
- if (comparison !== void 0 && isLineageAncestor(comparison, input.priorState, input.current.headSha)) {
986
- const extraAffected = [];
987
- let baseReason = "";
988
- if (input.priorState.baseSha !== input.current.baseSha) {
989
- const baseComparison = input.baseComparison;
990
- if (baseComparison === void 0) return full("the pull request base changed and its lineage comparison was unavailable");
991
- if (baseComparison.baseSha !== input.priorState.baseSha || baseComparison.headSha !== input.current.baseSha || baseComparison.mergeBaseSha !== input.priorState.baseSha || baseComparison.status !== "ahead" && baseComparison.status !== "identical" || baseComparison.truncated) return full("the pull request base changed materially or exceeded the comparison bound");
992
- for (const file of baseComparison.files) extraAffected.push(...filePaths(file));
993
- baseReason = `; base advanced from ${input.priorState.baseSha.slice(0, 7)} and overlapping PR paths were included`;
994
- }
995
- return incrementalFromDelta({
996
- fullFiles: input.fullFiles,
997
- profileFingerprint: input.profileFingerprint,
998
- priorState: input.priorState,
999
- deltaPaths: comparison.files.flatMap(filePaths),
1000
- extraAffectedPaths: extraAffected,
1001
- reason: `changes since reviewed head ${input.priorState.reviewedHeadSha.slice(0, 7)}${baseReason}`
1002
- });
1003
- }
1004
- const contentComparison = input.contentComparison;
1005
- if (contentComparison !== void 0) {
1006
- if (contentComparison.baseSha !== input.priorState.reviewedHeadSha || contentComparison.headSha !== input.current.headSha) return full("the rewritten-head tree snapshot comparison did not match the requested heads");
1007
- if (contentComparison.truncated) return full("the rewritten-head tree snapshot comparison was truncated");
1008
- return incrementalFromDelta({
1009
- fullFiles: input.fullFiles,
1010
- profileFingerprint: input.profileFingerprint,
1011
- priorState: input.priorState,
1012
- deltaPaths: contentComparison.changedPaths,
1013
- reason: `rewritten history; contents changed since reviewed head ${input.priorState.reviewedHeadSha.slice(0, 7)}`
1014
- });
1015
- }
1016
- if (input.contentComparisonFailure !== void 0) return full(`the rewritten-head tree snapshot comparison failed: ${input.contentComparisonFailure.slice(0, 2048)}`);
1017
- if (comparison === void 0) return full("the incremental head comparison was unavailable");
1018
- if (comparison.truncated) return full("the incremental comparison exceeded GitHub's file bound");
1019
- return full("the prior reviewed head is not an ancestor of the current head");
1020
- };
1021
- /** Per-run context consumed by orchestration and publication, not by the model. */
1022
- var ReviewExecutionContext = class extends Context.Service()("@effect-agent/pr-review/ReviewExecutionContext") {};
1023
- /**
1024
- * Explicit direct-run adapter for callers that intentionally review the full
1025
- * source without authenticated incremental continuity.
1026
- */
1027
- const fullReviewExecutionContextLayer = (reason) => Layer.effect(ReviewExecutionContext, Effect.gen(function* () {
1028
- const source = yield* PullRequestSource;
1029
- const [metadata, files] = yield* Effect.all([source.metadata, source.changedFiles]);
1030
- return fullReviewSelection({
1031
- reason,
1032
- files,
1033
- totalFiles: metadata.totalChangedFiles
1034
- });
1035
- }));
1036
- /**
1037
- * Decorate the full source with the selected review range. Full anchor files
1038
- * remain available to host-side publication validation; model tools see only
1039
- * the selected delta and may read head context only for that delta's paths.
1040
- */
1041
- const selectedPullRequestSourceLayer = (selection) => Layer.effect(PullRequestSource)(Effect.gen(function* () {
1042
- const source = yield* PullRequestSource;
1043
- const selectedPaths = new Set(selection.files.map((file) => file.path));
1044
- const selectedFiles = source.changedFiles.pipe(Effect.map((fullFiles) => {
1045
- const fullByPath = new Map(fullFiles.map((file) => [file.path, file]));
1046
- return selection.files.map((file) => {
1047
- if (file.patch !== void 0) return file;
1048
- const full = fullByPath.get(file.path);
1049
- return full === void 0 ? file : ChangedFile.make({
1050
- ...file,
1051
- ...full.reviewBaseContent === void 0 ? {} : { reviewBaseContent: full.reviewBaseContent },
1052
- ...full.reviewHeadContent === void 0 ? {} : { reviewHeadContent: full.reviewHeadContent }
1053
- });
1054
- });
1055
- }));
1056
- return PullRequestSource.of({
1057
- metadata: source.metadata,
1058
- changedFiles: selectedFiles,
1059
- anchorFiles: source.anchorFiles,
1060
- readFile: (path) => selectedPaths.has(path) ? source.readFile(path) : Effect.fail(ReviewInputViolation.make({
1061
- input: path,
1062
- reason: "Path is outside this incremental review range."
1063
- }))
1064
- });
1065
- }));
1066
- /** Build the full-surface mission used only to resolve profile guidance. */
1067
- const buildProfileMission = (metadata, files) => ReviewMission.make({
1068
- repository: metadata.repository,
1069
- number: metadata.number,
1070
- title: metadata.title,
1071
- body: metadata.body,
1072
- baseRef: metadata.baseRef,
1073
- headRef: metadata.headRef,
1074
- changedFileCount: files.length
1075
- });
1076
- //#endregion
1077
- //#region src/internal/retirement.ts
1078
- const PositiveLine$1 = Schema.Int.check(Schema.isGreaterThan(0));
1079
- /** One previously posted review as observed through the retirement host. */
1080
- var RetirableReview = class extends Schema.Class("@effect-agent/pr-review/RetirableReview")({
1081
- reviewId: Schema.Int.check(Schema.isGreaterThan(0)),
1082
- body: Schema.String.check(Schema.isMaxLength(6e4)),
1083
- commitSha: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
1084
- authorNodeId: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(200))),
1085
- submittedAt: Schema.NullOr(Schema.DateTimeUtc)
1086
- }) {};
1087
- /** One inline comment attached to a previously posted review. */
1088
- var RetirableReviewComment = class extends Schema.Class("@effect-agent/pr-review/RetirableReviewComment")({
1089
- nodeId: Schema.NonEmptyString.check(Schema.isMaxLength(200)),
1090
- path: Schema.NonEmptyString.check(Schema.isMaxLength(500)),
1091
- startLine: Schema.NullOr(PositiveLine$1),
1092
- endLine: Schema.NullOr(PositiveLine$1),
1093
- body: Schema.String.check(Schema.isMaxLength(65536))
1094
- }) {};
1095
- /** A GitHub retirement read or mutation failed. */
1096
- var ReviewRetirementFailure = class extends Schema.TaggedError()("ReviewRetirementFailure", {
1097
- operation: Schema.String,
1098
- reason: Schema.String
1099
- }) {
1100
- get message() {
1101
- return `Review retirement operation '${this.operation}' failed: ${this.reason}`;
1102
- }
1103
- };
1104
- /**
1105
- * Host-side GitHub operations used by retirement. Domain code never reaches
1106
- * into REST or GraphQL directly, and deterministic tests substitute this port.
1107
- */
1108
- var ReviewRetirementHost = class extends Context.Service()("@effect-agent/pr-review/ReviewRetirementHost") {};
1109
- /** Observable cosmetic work completed by one fail-open retirement pass. */
1110
- var ReviewRetirementReport = class extends Schema.Class("@effect-agent/pr-review/ReviewRetirementReport")({
1111
- reviewsRetired: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1112
- findingsResolved: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1113
- commentsMinimized: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1114
- failures: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
1115
- }) {};
1116
- const REVIEW_METADATA_PATTERN = /<!-- effect-agent-pr-review metadata\n[\s\S]*?\n-->/g;
1117
- const FINGERPRINT_PATTERN = /<!-- effect-agent-pr-review fingerprint=sha256:[0-9a-f]{64} -->/g;
1118
- const STATE_PATTERN = /<!-- effect-agent-pr-review state-v1:[A-Za-z0-9+/]+={0,2}\.[0-9a-f]{64} -->/g;
1119
- const RETIRED_ORIGINAL_PATTERN = /<!-- effect-agent-pr-review retired-original:start -->\n([\s\S]*?)\n<!-- effect-agent-pr-review retired-original:end -->/;
1120
- const MACHINE_COMMENT_PATTERN = new RegExp(`${REVIEW_METADATA_PATTERN.source}|${FINGERPRINT_PATTERN.source}|${STATE_PATTERN.source}`, "g");
1121
- const VERDICT_CALLOUT_PATTERN = /^(?:> \[!(?:CAUTION|IMPORTANT)\]\n> [^\n]*(?:\n> [^\n]*)*|> (?:ℹ️|✅)[^\n]*)\n*/;
1122
- /**
1123
- * The first line of every inline finding comment this package posts. Shared
1124
- * with adjudication so both parse the identical title shape.
1125
- */
1126
- const INLINE_FINDING_TITLE_PATTERN = /^\*\*\[(?:🛑 blocking|⚠️ important|💅 nit) · [a-z-]+\] ([^\n]+)\*\*$/;
1127
- const MAX_REVIEW_BODY_CHARS = 6e4;
1128
- /** The host-authored metadata marker is the authority gate for any edit. */
1129
- const hasReviewMetadataMarker = (body) => /<!-- effect-agent-pr-review metadata\n/.test(body);
1130
- const machineComments = (body) => Array.from(body.matchAll(MACHINE_COMMENT_PATTERN), (match) => match[0]);
1131
- const originalVisibleBody = (body) => {
1132
- const retired = RETIRED_ORIGINAL_PATTERN.exec(body)?.[1];
1133
- if (retired !== void 0) return retired;
1134
- return body.replace(MACHINE_COMMENT_PATTERN, "").trim().replace(VERDICT_CALLOUT_PATTERN, "");
1135
- };
1136
- const findingLocation = (finding) => `${finding.path}:${finding.startLine}${finding.endLine === finding.startLine ? "" : `-${finding.endLine}`}`;
1137
- const renderRetiredBody = (input) => {
1138
- const shortSha = input.currentState.reviewedHeadSha.slice(0, 7);
1139
- const comments = machineComments(input.priorBody);
1140
- const original = originalVisibleBody(input.priorBody);
1141
- const resolved = input.resolvedFindings.length === 0 ? [] : [
1142
- "### Findings resolved by later review",
1143
- "",
1144
- ...input.resolvedFindings.map((finding) => `- \`${findingLocation(finding)}\` ~~${finding.title}~~ · resolved at \`${shortSha}\``),
1145
- ""
1146
- ];
1147
- const prefix = [
1148
- `> ℹ️ Superseded — ${input.resolvedFindings.length} of ${input.priorState.unresolvedFindings.length} findings resolved at \`${shortSha}\`; see [the latest review](${input.currentReviewUrl}).`,
1149
- "",
1150
- "<details>",
1151
- "<summary>Previous review details</summary>",
1152
- "",
1153
- ...resolved,
1154
- "<!-- effect-agent-pr-review retired-original:start -->"
1155
- ];
1156
- const suffix = [
1157
- "<!-- effect-agent-pr-review retired-original:end -->",
1158
- "",
1159
- "</details>",
1160
- ...comments.length === 0 ? [] : ["", ...comments]
1161
- ];
1162
- const render = (visible) => [
1163
- ...prefix,
1164
- visible,
1165
- ...suffix
1166
- ].join("\n");
1167
- if (render(original).length <= MAX_REVIEW_BODY_CHARS) return render(original);
1168
- const truncationNotice = "\n\n_Original review content truncated during retirement._";
1169
- const budget = Math.max(0, MAX_REVIEW_BODY_CHARS - render(truncationNotice).length);
1170
- return render(`${original.slice(0, budget)}${truncationNotice}`);
1171
- };
1172
- /** Compute one prior review's resolved subset and deterministic retired body. */
1173
- const decideReviewRetirement = (input) => {
1174
- const current = new Set(input.currentState.unresolvedFindings.map(findingIdentity));
1175
- const adjudicated = new Set((input.currentState.adjudications ?? []).map((entry) => adjudicationIdentity(entry)));
1176
- const resolvedFindings = input.priorState.unresolvedFindings.filter((finding) => !current.has(findingIdentity(finding)) && !adjudicated.has(findingIdentity(finding)));
1177
- return {
1178
- body: renderRetiredBody({
1179
- ...input,
1180
- resolvedFindings
1181
- }),
1182
- resolvedFindings,
1183
- priorFindingCount: input.priorState.unresolvedFindings.length
1184
- };
1185
- };
1186
- const inlineCommentIdentity = (comment) => {
1187
- if (comment.startLine === null || comment.endLine === null) return void 0;
1188
- const firstLine = comment.body.split("\n", 1)[0] ?? "";
1189
- const title = INLINE_FINDING_TITLE_PATTERN.exec(firstLine)?.[1];
1190
- return title === void 0 ? void 0 : findingIdentity({
1191
- path: comment.path,
1192
- startLine: comment.startLine,
1193
- endLine: comment.endLine,
1194
- title
1195
- });
1196
- };
1197
- const failOpen = (effect, fallback, message) => effect.pipe(Effect.catch((error) => Effect.logWarning(`${message}: ${String(error)}`).pipe(Effect.as(fallback))));
1198
- const isStrictlyOlderReview = (review, input) => {
1199
- if (review.submittedAt === null) return false;
1200
- const submittedAt = DateTime.toEpochMillis(review.submittedAt);
1201
- const currentSubmittedAt = DateTime.toEpochMillis(input.currentSubmittedAt);
1202
- return submittedAt < currentSubmittedAt || submittedAt === currentSubmittedAt && review.reviewId < input.currentReviewId;
1203
- };
1204
- /**
1205
- * Retire every marker-bearing prior review against the newest posted state.
1206
- * Every lookup, edit, and minimization is isolated: retirement is cosmetic
1207
- * and can never change the run or check outcome.
1208
- */
1209
- const retireStaleReviews = Effect.fn("retireStaleReviews")(function* (input) {
1210
- const host = yield* ReviewRetirementHost;
1211
- const authenticator = yield* ReviewStateAuthenticator;
1212
- if (authenticator.status !== "available") {
1213
- yield* Effect.logWarning("Skipping stale-review retirement because authenticated review state is unavailable.");
1214
- return ReviewRetirementReport.make({
1215
- reviewsRetired: 0,
1216
- findingsResolved: 0,
1217
- commentsMinimized: 0,
1218
- failures: 0
1219
- });
1220
- }
1221
- let failures = 0;
1222
- let reviewsRetired = 0;
1223
- let findingsResolved = 0;
1224
- let commentsMinimized = 0;
1225
- const reviews = yield* failOpen(host.listReviews, void 0, "Could not list prior reviews");
1226
- if (reviews === void 0) return ReviewRetirementReport.make({
1227
- reviewsRetired,
1228
- findingsResolved,
1229
- commentsMinimized,
1230
- failures: 1
1231
- });
1232
- for (const review of reviews) {
1233
- if (review.authorNodeId !== input.currentAuthorNodeId || !isStrictlyOlderReview(review, input) || !hasReviewMetadataMarker(review.body)) continue;
1234
- const priorState = yield* failOpen(authenticator.extract(review.body), Option.none(), `Could not authenticate prior review ${review.reviewId}`);
1235
- if (Option.isNone(priorState)) continue;
1236
- const decision = decideReviewRetirement({
1237
- priorBody: review.body,
1238
- priorState: priorState.value,
1239
- currentState: input.currentState,
1240
- currentReviewUrl: input.currentReviewUrl
1241
- });
1242
- if (yield* failOpen(host.updateBody(review.reviewId, decision.body).pipe(Effect.as(true)), false, `Could not retire prior review ${review.reviewId}`)) {
1243
- reviewsRetired += 1;
1244
- findingsResolved += decision.resolvedFindings.length;
1245
- } else failures += 1;
1246
- if (decision.resolvedFindings.length === 0) continue;
1247
- const comments = yield* failOpen(host.listComments(review.reviewId), void 0, `Could not list inline comments for prior review ${review.reviewId}`);
1248
- if (comments === void 0) {
1249
- failures += 1;
1250
- continue;
1251
- }
1252
- const resolved = new Set(decision.resolvedFindings.map(findingIdentity));
1253
- for (const comment of comments) {
1254
- const identity = inlineCommentIdentity(comment);
1255
- if (identity === void 0 || !resolved.has(identity)) continue;
1256
- if (yield* failOpen(host.minimizeComment(comment.nodeId).pipe(Effect.as(true)), false, `Could not minimize resolved inline comment ${comment.nodeId}`)) commentsMinimized += 1;
1257
- else failures += 1;
1258
- }
1259
- }
1260
- return ReviewRetirementReport.make({
1261
- reviewsRetired,
1262
- findingsResolved,
1263
- commentsMinimized,
1264
- failures
1265
- });
1266
- });
1267
- //#endregion
1268
- //#region src/internal/adjudication.ts
1269
- const PositiveLine = Schema.Int.check(Schema.isGreaterThan(0));
1270
- /** Maximum authorized command candidates retained for one inline thread. */
1271
- const MAX_THREAD_ADJUDICATION_COMMANDS = 100;
1272
- /** One reply or top-level comment observed through the adjudication host. */
1273
- var AdjudicationComment = class extends Schema.Class("@effect-agent/pr-review/AdjudicationComment")({
1274
- body: Schema.String.check(Schema.isMaxLength(65536)),
1275
- /** GitHub's author_association for the comment author, verbatim. */
1276
- authorAssociation: Schema.String.check(Schema.isMaxLength(40)),
1277
- authorLogin: Schema.NonEmptyString.check(Schema.isMaxLength(100)),
1278
- /** Creation time; a comment without one loses every later-wins tie. */
1279
- createdAt: Schema.NullOr(Schema.DateTimeUtc),
1280
- /** Stable zero-based order in the source listing, before thread grouping. */
1281
- sourceOrder: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
1282
- }) {};
1283
- /** One of the action's own inline finding threads, replies in creation order. */
1284
- var AdjudicableThread = class extends Schema.Class("@effect-agent/pr-review/AdjudicableThread")({
1285
- path: Schema.NonEmptyString.check(Schema.isMaxLength(500)),
1286
- startLine: Schema.NullOr(PositiveLine),
1287
- endLine: Schema.NullOr(PositiveLine),
1288
- /** The root comment's body; its first line carries the finding title. */
1289
- rootBody: Schema.String.check(Schema.isMaxLength(65536)),
1290
- replies: Schema.Array(AdjudicationComment).check(Schema.isMaxLength(100))
1291
- }) {};
1292
- /** A GitHub adjudication read failed. */
1293
- var ReviewAdjudicationFailure = class extends Schema.TaggedError()("ReviewAdjudicationFailure", {
1294
- operation: Schema.String,
1295
- reason: Schema.String
1296
- }) {
1297
- get message() {
1298
- return `Review adjudication operation '${this.operation}' failed: ${this.reason}`;
1299
- }
1300
- };
1301
- /**
1302
- * Host-side GitHub reads used by adjudication. Domain code never reaches into
1303
- * REST directly, and deterministic tests substitute this port. Both listings
1304
- * return comments in creation order.
1305
- */
1306
- var ReviewAdjudicationHost = class extends Context.Service()("@effect-agent/pr-review/ReviewAdjudicationHost") {};
1307
- /** Explicit program-edge adapter for runs that intentionally perform no host reads. */
1308
- const noReviewAdjudicationHost = ReviewAdjudicationHost.of({
1309
- listFindingThreads: Effect.succeed([]),
1310
- listIssueComments: Effect.succeed([])
1311
- });
1312
- /** Layer form of {@link noReviewAdjudicationHost}. */
1313
- const noReviewAdjudicationHostLayer = Layer.succeed(ReviewAdjudicationHost)(noReviewAdjudicationHost);
1314
- /** author_associations allowed to adjudicate; everything else is ignored. */
1315
- const AUTHORIZED_ADJUDICATION_ASSOCIATIONS = /* @__PURE__ */ new Set([
1316
- "OWNER",
1317
- "MEMBER",
1318
- "COLLABORATOR"
1319
- ]);
1320
- const AdjudicationDispositionSchema = Schema.Literals([
1321
- "accepted-risk",
1322
- "refuted",
1323
- "obsolete"
1324
- ]);
1325
- const THREAD_COMMAND_PATTERN = /^\/adjudicate[ \t]+([a-z-]+)[ \t]*(?::[ \t]*(.*\S))?[ \t]*$/;
1326
- const ISSUE_COMMAND_PATTERN = /^\/adjudicate[ \t]+([a-z-]+)[ \t]+"([^"\n]+)"[ \t]*(?::[ \t]*(.*\S))?[ \t]*$/;
1327
- const firstLine = (body) => (body.split("\n", 1)[0] ?? "").trim();
1328
- const boundedReason = (raw) => {
1329
- if (raw === void 0) return void 0;
1330
- const trimmed = raw.trim().slice(0, 300);
1331
- return trimmed.length === 0 ? void 0 : trimmed;
1332
- };
1333
- /**
1334
- * Parse one inline-thread reply: `/adjudicate <disposition>(: <reason>)?`.
1335
- * The thread itself names the target identity. Returns undefined for a
1336
- * non-command body and "malformed" for a command that fails the grammar.
1337
- */
1338
- const parseThreadAdjudication = (body) => {
1339
- const line = firstLine(body);
1340
- if (!line.startsWith("/adjudicate")) return void 0;
1341
- const match = THREAD_COMMAND_PATTERN.exec(line);
1342
- const disposition = match?.[1];
1343
- if (disposition === void 0 || !Schema.is(AdjudicationDispositionSchema)(disposition)) return "malformed";
1344
- return {
1345
- disposition,
1346
- reason: boundedReason(match?.[2])
1347
- };
1348
- };
1349
- /**
1350
- * Parse one top-level PR comment:
1351
- * `/adjudicate <disposition> "<exact title>"(: <reason>)?`. The quoted title
1352
- * is required because the conversation names no finding thread; it targets
1353
- * the title-alone identity of an unanchored concern.
1354
- */
1355
- const parseIssueAdjudication = (body) => {
1356
- const line = firstLine(body);
1357
- if (!line.startsWith("/adjudicate")) return void 0;
1358
- const match = ISSUE_COMMAND_PATTERN.exec(line);
1359
- const disposition = match?.[1];
1360
- const title = match?.[2];
1361
- if (disposition === void 0 || !Schema.is(AdjudicationDispositionSchema)(disposition) || title === void 0 || title.length > 120) return "malformed";
1362
- return {
1363
- disposition,
1364
- title,
1365
- reason: boundedReason(match?.[3])
1366
- };
1367
- };
1368
- /** The finding identity an inline thread names, or undefined when unparsable. */
1369
- const threadFindingTarget = (thread) => {
1370
- if (thread.startLine === null || thread.endLine === null) return void 0;
1371
- const title = INLINE_FINDING_TITLE_PATTERN.exec(firstLine(thread.rootBody))?.[1];
1372
- if (title === void 0 || title.length > 120) return void 0;
1373
- return {
1374
- path: thread.path,
1375
- startLine: thread.startLine,
1376
- endLine: thread.endLine,
1377
- title
1378
- };
1379
- };
1380
- /**
1381
- * Derive the standing adjudications from the host's listings. Every command
1382
- * is screened fail-closed (authorization, grammar, a parsable target); later
1383
- * adjudications of the same identity win by comment creation order; the
1384
- * result is capped at the ReviewState bound dropping the oldest winners.
1385
- */
1386
- const deriveAdjudications = (input) => {
1387
- const candidates = [];
1388
- const ignored = [];
1389
- const admit = (comment, command, target) => {
1390
- candidates.push({
1391
- adjudication: StoredAdjudication.make({
1392
- ...target.path === void 0 ? {} : { path: target.path },
1393
- ...target.startLine === void 0 ? {} : { startLine: target.startLine },
1394
- ...target.endLine === void 0 ? {} : { endLine: target.endLine },
1395
- title: target.title,
1396
- disposition: command.disposition,
1397
- ...command.reason === void 0 ? {} : { reason: command.reason },
1398
- actor: comment.authorLogin
1399
- }),
1400
- epochMillis: comment.createdAt === null ? -1 : DateTime.toEpochMillis(comment.createdAt),
1401
- sourceOrder: comment.sourceOrder
1402
- });
1403
- };
1404
- const authorized = (comment, surface) => {
1405
- if (AUTHORIZED_ADJUDICATION_ASSOCIATIONS.has(comment.authorAssociation)) return true;
1406
- ignored.push(`${surface}: unauthorized /adjudicate from @${comment.authorLogin} (${comment.authorAssociation})`);
1407
- return false;
1408
- };
1409
- for (const thread of input.threads) {
1410
- const target = threadFindingTarget(thread);
1411
- for (const reply of thread.replies) {
1412
- const command = parseThreadAdjudication(reply.body);
1413
- if (command === void 0) continue;
1414
- const surface = `inline thread ${thread.path}`;
1415
- if (command === "malformed") {
1416
- ignored.push(`${surface}: malformed /adjudicate command from @${reply.authorLogin}`);
1417
- continue;
1418
- }
1419
- if (!authorized(reply, surface)) continue;
1420
- if (target === void 0) {
1421
- ignored.push(`${surface}: thread root names no parsable finding title`);
1422
- continue;
1423
- }
1424
- admit(reply, command, target);
1425
- }
1426
- }
1427
- for (const comment of input.issueComments) {
1428
- const command = parseIssueAdjudication(comment.body);
1429
- if (command === void 0) continue;
1430
- const surface = "pull-request conversation";
1431
- if (command === "malformed") {
1432
- ignored.push(`${surface}: malformed /adjudicate command from @${comment.authorLogin}`);
1433
- continue;
1434
- }
1435
- if (!authorized(comment, surface)) continue;
1436
- if (command.title === void 0) {
1437
- ignored.push(`${surface}: /adjudicate without a quoted target title`);
1438
- continue;
1439
- }
1440
- admit(comment, command, { title: command.title });
1441
- }
1442
- const byIdentity = /* @__PURE__ */ new Map();
1443
- const ordered = [...candidates].sort((left, right) => left.epochMillis - right.epochMillis || left.sourceOrder - right.sourceOrder);
1444
- for (const candidate of ordered) {
1445
- const identity = adjudicationIdentity(candidate.adjudication);
1446
- byIdentity.delete(identity);
1447
- byIdentity.set(identity, candidate);
1448
- }
1449
- const winners = [...byIdentity.values()];
1450
- const droppedOldest = Math.max(0, winners.length - 20);
1451
- return {
1452
- adjudications: winners.slice(droppedOldest).map((candidate) => candidate.adjudication),
1453
- ignored,
1454
- droppedOldest
1455
- };
1456
- };
1457
- /** Later-wins merge of stored prior adjudications with freshly derived ones. */
1458
- const mergeAdjudications = (prior, fresh) => {
1459
- const byIdentity = /* @__PURE__ */ new Map();
1460
- for (const adjudication of [...prior, ...fresh]) {
1461
- const identity = adjudicationIdentity(adjudication);
1462
- byIdentity.delete(identity);
1463
- byIdentity.set(identity, adjudication);
1464
- }
1465
- const merged = [...byIdentity.values()];
1466
- return merged.slice(Math.max(0, merged.length - 20));
1467
- };
1468
- /**
1469
- * Collect the standing maintainer adjudications: freshly derived through the
1470
- * host, merged later-wins over the prior state's stored set. The host is a
1471
- * visible Effect requirement; program edges that intentionally perform no
1472
- * reads provide {@link noReviewAdjudicationHost}. Fail-open — any listing
1473
- * fault keeps the complete prior set and never fails the review, because NOT
1474
- * suppressing a finding is the conservative direction.
1475
- */
1476
- const collectReviewAdjudications = Effect.fn("collectReviewAdjudications")(function* (prior) {
1477
- const host = yield* ReviewAdjudicationHost;
1478
- const listings = yield* Effect.all({
1479
- threads: host.listFindingThreads,
1480
- issueComments: host.listIssueComments
1481
- }).pipe(Effect.catch((error) => Effect.logWarning(`Could not collect adjudications from '${error.operation}': ${error.reason}; retaining stored adjudications unchanged.`).pipe(Effect.as(void 0))));
1482
- if (listings === void 0) return prior;
1483
- const derived = deriveAdjudications({
1484
- threads: listings.threads,
1485
- issueComments: listings.issueComments
1486
- });
1487
- for (const note of derived.ignored) yield* Effect.logDebug(`Ignored adjudication command — ${note}`);
1488
- if (derived.droppedOldest > 0) yield* Effect.logWarning(`Dropped ${derived.droppedOldest} oldest adjudication(s) over the 20-entry bound.`);
1489
- return mergeAdjudications(prior, derived.adjudications);
1490
- });
1491
- const lineRange = (startLine, endLine) => `${startLine}${endLine === startLine ? "" : `-${endLine}`}`;
1492
- /** One adjudication as a bounded reviewer-prompt context line. */
1493
- const renderAdjudicationContextLine = (adjudication) => {
1494
- const location = adjudication.path !== void 0 && adjudication.startLine !== void 0 && adjudication.endLine !== void 0 ? `${adjudication.path}:${lineRange(adjudication.startLine, adjudication.endLine)}` : "(unanchored)";
1495
- const reason = adjudication.reason === void 0 ? "" : `: ${adjudication.reason}`;
1496
- return `${location} "${adjudication.title}" — ${adjudication.disposition} by @${adjudication.actor}${reason}`;
1497
- };
1498
- /** One prior-round finding as a bounded reviewer-prompt context line. */
1499
- const renderPriorFindingContextLine = (finding) => `${finding.path}:${lineRange(finding.startLine, finding.endLine)} [${finding.severity}] "${finding.title}" — ${finding.body.slice(0, 400)}`;
1500
- /** Build the fan-out prior-review context from the resolved continuity data. */
1501
- const buildPriorReviewContext = (adjudications, priorFindingsOnScope) => ({
1502
- adjudicated: adjudications.map((adjudication) => ({
1503
- path: adjudication.path,
1504
- line: renderAdjudicationContextLine(adjudication)
1505
- })),
1506
- priorFindings: priorFindingsOnScope.map((finding) => ({
1507
- path: finding.path,
1508
- line: renderPriorFindingContextLine(finding)
1509
- }))
1510
- });
1511
- //#endregion
1512
- //#region src/internal/anchors.ts
1513
- /** Why a finding cannot anchor to the current new-version diff, if any. */
1514
- const anchorViolation = (finding, files) => {
1515
- const file = files.find((candidate) => candidate.path === finding.path);
1516
- if (file === void 0) return "path is not part of the changeset";
1517
- if (file.patch === void 0) return "file has no anchorable textual diff";
1518
- if (finding.endLine < finding.startLine) return "endLine precedes startLine";
1519
- if (finding.endLine - finding.startLine + 1 > 100) return "range is implausibly large";
1520
- const anchors = commentableLines(file.patch);
1521
- for (let line = finding.startLine; line <= finding.endLine; line += 1) if (!anchors.has(line)) return `line ${line} is not part of the diff`;
1522
- };
1523
- //#endregion
1524
- //#region src/internal/coverage.ts
1525
- var ReviewInputCoverage = class extends Schema.Class("@effect-agent/pr-review/ReviewInputCoverage")({
1526
- status: Schema.Literals(["complete", "incomplete"]),
1527
- requiredPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(Schema.isMaxLength(300)),
1528
- assignedPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(Schema.isMaxLength(300)),
1529
- /** Assigned paths whose model-visible diff was truncated by the evidence bound. */
1530
- partialPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(Schema.isMaxLength(300)),
1531
- unassignedPaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(Schema.isMaxLength(300)),
1532
- /**
1533
- * Paths with neither a textual diff nor bounded base/head text (binaries,
1534
- * oversized files). Fail-closed: they keep the status incomplete for as
1535
- * long as they are part of the pull request — an unreviewable change must
1536
- * never authorize a green check. Exclude them deliberately with ignore
1537
- * globs when that is intended.
1538
- */
1539
- undiffablePaths: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(512))).check(Schema.isMaxLength(300)),
1540
- reasons: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(1e3))).check(Schema.isMaxLength(20))
1541
- }) {};
1542
- var FailedReviewPass = class extends Schema.Class("@effect-agent/pr-review/FailedReviewPass")({
1543
- workId: Schema.NonEmptyString.check(Schema.isMaxLength(96)),
1544
- stage: Schema.Literals([
1545
- "discovery",
1546
- "specialist",
1547
- "verification"
1548
- ]),
1549
- errorTag: Schema.NonEmptyString.check(Schema.isMaxLength(256))
1550
- }) {};
1551
- /**
1552
- * Settlement of scheduled review work. `incomplete` means reviewer-side work
1553
- * failed after its bounded retry — a machinery gap that is carried forward and
1554
- * retried on the next run, never a statement about the code under review.
1555
- * `unverified` is the flat reviewer's honest constant: one pass with no
1556
- * independent verifier is neither settled assurance nor a failure.
1557
- */
1558
- var ReviewAssurance = class extends Schema.Class("@effect-agent/pr-review/ReviewAssurance")({
1559
- status: Schema.Literals([
1560
- "settled",
1561
- "incomplete",
1562
- "unverified"
1563
- ]),
1564
- requiredGeneralDiscoveryPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1565
- completedGeneralDiscoveryPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1566
- requiredSpecialistPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1567
- completedSpecialistPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1568
- requiredVerificationPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1569
- completedVerificationPasses: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1570
- discoveredCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1571
- confirmedCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1572
- rejectedCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1573
- unsettledCandidates: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1574
- /** Discovery claims discarded for anchors/paths outside their assigned evidence. */
1575
- discardedInvalidFindings: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1576
- failedPasses: Schema.Array(FailedReviewPass).check(Schema.isMaxLength(64)),
1577
- reasons: Schema.Array(Schema.NonEmptyString.check(Schema.isMaxLength(1e3))).check(Schema.isMaxLength(32))
1578
- }) {};
1579
- const toolTrace = (events) => {
1580
- const declared = /* @__PURE__ */ new Map();
1581
- const succeeded = /* @__PURE__ */ new Map();
1582
- const failed = /* @__PURE__ */ new Map();
1583
- for (const event of events) {
1584
- if (event._tag === "ToolCallDeclared") declared.set(event.toolCallId, event);
1585
- if (event._tag === "ToolCallSucceeded") succeeded.set(event.toolCallId, event);
1586
- if (event._tag === "ToolCallFailed") failed.set(event.toolCallId, event);
1587
- }
1588
- return {
1589
- declared,
1590
- succeeded,
1591
- failed
1592
- };
1593
- };
1594
- const sortedUnique = (values) => [...new Set(values)].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
1595
- /** Render a bounded, deterministic "label (n): a, b, … (+k more)" reason line. */
1596
- const boundedListReason = (label, values) => {
1597
- const items = sortedUnique(values);
1598
- let rendered = `${label} (${items.length}): `;
1599
- for (let index = 0; index < items.length; index += 1) {
1600
- const item = items[index] ?? "";
1601
- const separator = index === 0 ? "" : ", ";
1602
- const omitted = items.length - index - 1;
1603
- const suffix = omitted === 0 ? "" : ` … (+${omitted} more)`;
1604
- if (`${rendered}${separator}${item}${suffix}`.length > 1e3) {
1605
- const omission = `… (+${items.length - index} more)`;
1606
- return `${rendered.slice(0, 1e3 - omission.length)}${omission}`;
1607
- }
1608
- rendered = `${rendered}${separator}${item}`;
1609
- }
1610
- return rendered;
1611
- };
1612
- /**
1613
- * Split carried scope into paths a retry can settle and paths it never can.
1614
- * Undiffable files are a property of the pull request, not a transient
1615
- * reviewer-side failure: gate reasons and rendered callouts must never promise
1616
- * they are "retried automatically" — the honest instruction is to remove them
1617
- * from the pull request or exclude them with ignore globs.
1618
- */
1619
- const splitCarriedScope = (input) => {
1620
- const undiffable = new Set(input.inputCoverage?.undiffablePaths ?? []);
1621
- const retryablePaths = (input.unreviewedPaths ?? []).filter((path) => !undiffable.has(path));
1622
- const undiffablePaths = sortedUnique(undiffable);
1623
- const coverageGapBeyondUndiffable = input.inputCoverage?.status === "incomplete" && input.inputCoverage.reasons.length > (undiffablePaths.length > 0 ? 1 : 0);
1624
- return {
1625
- retryablePaths,
1626
- undiffablePaths,
1627
- retryableGap: input.assurance?.status === "incomplete" || retryablePaths.length > 0 || coverageGapBeyondUndiffable
1628
- };
1629
- };
1630
- const anchorSurfaceAdjusted = (inputCoverage, anchorFiles, totalAnchorFiles) => anchorFiles.length >= totalAnchorFiles ? inputCoverage : ReviewInputCoverage.make({
1631
- ...inputCoverage,
1632
- status: "incomplete",
1633
- reasons: [...inputCoverage.reasons, `full pull-request anchor surface exposed ${anchorFiles.length} of ${totalAnchorFiles} required files`]
1634
- });
1635
- /** The flat reviewer's honest constant assurance: one pass, no verifier. */
1636
- const flatAssurance = () => ReviewAssurance.make({
1637
- status: "unverified",
1638
- requiredGeneralDiscoveryPasses: 1,
1639
- completedGeneralDiscoveryPasses: 1,
1640
- requiredSpecialistPasses: 0,
1641
- completedSpecialistPasses: 0,
1642
- requiredVerificationPasses: 0,
1643
- completedVerificationPasses: 0,
1644
- discoveredCandidates: 0,
1645
- confirmedCandidates: 0,
1646
- rejectedCandidates: 0,
1647
- unsettledCandidates: 0,
1648
- discardedInvalidFindings: 0,
1649
- failedPasses: [],
1650
- reasons: ["flat review has no independent candidate-verification pass; use the fan-out pipeline for a settled assurance result"]
1651
- });
1652
- /**
1653
- * Assess one settled flat run from its Run event trace: which required paths
1654
- * received successful bounded diff evidence. This observes tool INPUT
1655
- * assignment only — the host cannot know which evidence the model weighed.
1656
- */
1657
- const assessFlatReview = (input) => {
1658
- const trace = toolTrace(input.events);
1659
- const requiredPaths = sortedUnique(input.files.map((file) => file.path));
1660
- const assigned = /* @__PURE__ */ new Set();
1661
- const partial = /* @__PURE__ */ new Set();
1662
- const failedPaths = /* @__PURE__ */ new Set();
1663
- for (const [toolCallId, declaration] of trace.declared) {
1664
- if (declaration.toolName !== "read_file_diff") continue;
1665
- const query = Schema.decodeUnknownOption(FileDiffQuery)(declaration.parameters);
1666
- if (Option.isNone(query)) continue;
1667
- const success = trace.succeeded.get(toolCallId);
1668
- if (success !== void 0) {
1669
- assigned.add(query.value.path);
1670
- const view = Schema.decodeUnknownOption(FileDiffView)(success.result);
1671
- if (Option.isSome(view) && view.value.truncated) partial.add(query.value.path);
1672
- }
1673
- if (trace.failed.has(toolCallId)) failedPaths.add(query.value.path);
1674
- }
1675
- const undiffable = new Set(input.files.filter((file) => !isReviewableFile(file)).map((file) => file.path));
1676
- const unassigned = requiredPaths.filter((path) => !undiffable.has(path) && (!assigned.has(path) || failedPaths.has(path)));
1677
- const reasons = [];
1678
- if (input.files.length < input.totalFiles) reasons.push(`review range exposed ${input.files.length} of ${input.totalFiles} required files`);
1679
- if (undiffable.size > 0) reasons.push(boundedListReason("required paths have no reviewable diff or bounded text", undiffable));
1680
- if (failedPaths.size > 0) reasons.push(boundedListReason("diff reads failed", failedPaths));
1681
- if (partial.size > 0) reasons.push(boundedListReason("model-visible diff evidence was truncated", partial));
1682
- if (unassigned.length > 0) reasons.push(boundedListReason("required paths received no successful diff input", unassigned));
1683
- return {
1684
- inputCoverage: anchorSurfaceAdjusted(ReviewInputCoverage.make({
1685
- status: reasons.length === 0 ? "complete" : "incomplete",
1686
- requiredPaths,
1687
- assignedPaths: sortedUnique(assigned),
1688
- partialPaths: sortedUnique(partial),
1689
- unassignedPaths: sortedUnique(unassigned),
1690
- undiffablePaths: sortedUnique(undiffable),
1691
- reasons
1692
- }), input.anchorFiles, input.totalAnchorFiles),
1693
- assurance: flatAssurance(),
1694
- unreviewedPaths: sortedUnique([...unassigned, ...undiffable])
1695
- };
1696
- };
1697
- /**
1698
- * Input coverage of one host-scheduled fan-out plan: which required paths the
1699
- * bounded plan actually assigned complete evidence for. Capacity overflow and
1700
- * undiffable paths are both real gaps; the pipeline carries them so the check
1701
- * stays fail-closed until they are reviewed, removed, or explicitly ignored.
1702
- */
1703
- const fanOutInputCoverage = (input) => {
1704
- const plan = input.plan;
1705
- const assignedPaths = sortedUnique(plan.units.flatMap((unit) => unit.paths));
1706
- const unassignedPaths = sortedUnique(plan.unassignedPaths);
1707
- const reasons = [];
1708
- if (plan.truncated) reasons.push(`review range exposed ${input.files.length} of ${input.totalFiles} required files`);
1709
- if (plan.undiffablePaths.length > 0) reasons.push(boundedListReason("required paths have no reviewable diff or bounded text", plan.undiffablePaths));
1710
- if (plan.partialEvidencePaths.length > 0) reasons.push(boundedListReason("fan-out capacity left some deterministic evidence shards unassigned", plan.partialEvidencePaths));
1711
- if (plan.unassignedEvidenceShardCount > 0) {
1712
- reasons.push(`${plan.unassignedEvidenceShardCount} deterministic evidence shard(s) exceeded fan-out capacity`);
1713
- reasons.push(boundedListReason(`unassigned evidence shard identifier sample (${plan.unassignedEvidenceShardIds.length} of ${plan.unassignedEvidenceShardCount})`, plan.unassignedEvidenceShardIds));
1714
- }
1715
- if (plan.unassignedPaths.length > 0) reasons.push(boundedListReason("fan-out capacity left paths unassigned", plan.unassignedPaths));
1716
- return anchorSurfaceAdjusted(ReviewInputCoverage.make({
1717
- status: reasons.length === 0 ? "complete" : "incomplete",
1718
- requiredPaths: sortedUnique(input.files.map((file) => file.path)),
1719
- assignedPaths,
1720
- partialPaths: plan.partialEvidencePaths,
1721
- unassignedPaths,
1722
- undiffablePaths: sortedUnique(plan.undiffablePaths),
1723
- reasons
1724
- }), input.anchorFiles, input.totalAnchorFiles);
1725
- };
1726
- //#endregion
1727
- //#region src/internal/review-units.ts
1728
- /** The delegation fan-out bound: one parent Run spawns at most this many children. */
1729
- const MAX_REVIEW_UNITS = 8;
1730
- /** A unit never carries more files than this, regardless of their size. */
1731
- const MAX_UNIT_FILES = 12;
1732
- /**
1733
- * Bound the complete model-visible evidence assigned to one child. This is a
1734
- * character bound rather than a token estimate because it is deterministic,
1735
- * provider-independent, and enforced before any model call.
1736
- */
1737
- const UNIT_EVIDENCE_CHAR_BUDGET = 24e4;
1738
- /** Maximum complete evidence shards placed in one child brief. */
1739
- const MAX_UNIT_EVIDENCE_SHARDS = 12;
1740
- /**
1741
- * Keep overflow diagnostics bounded to one plan's total assignment capacity.
1742
- * The plan separately records the exact overflow count and every affected
1743
- * path, so identifiers are a deterministic diagnostic sample rather than the
1744
- * authority for whether input coverage is complete.
1745
- */
1746
- const MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS = 96;
1747
- /** The merged review never exceeds the `CodeReview` findings bound. */
1748
- const MAX_MERGED_FINDINGS = 20;
1749
- const ReviewUnitId = Schema.NonEmptyString.check(Schema.isMaxLength(32));
1750
- /** High-risk surfaces that receive an explicit specialist focus label. */
1751
- const ReviewRiskCategory = Schema.Literals([
1752
- "authentication-authorization",
1753
- "security-boundary",
1754
- "persistence-durability",
1755
- "concurrency",
1756
- "credential-handling",
1757
- "external-side-effects"
1758
- ]);
1759
- const ReviewDiscoveryPerspective = Schema.Literals(["general", "risk-specialist"]);
1760
- const ReviewPassId = Schema.NonEmptyString.check(Schema.isMaxLength(64));
1761
- const ReviewEvidenceShardId = Schema.NonEmptyString.check(Schema.isMaxLength(32));
1762
- /** One complete bounded slice of a changed path's model-visible evidence. */
1763
- var ReviewEvidenceShard = class extends Schema.Class("@effect-agent/pr-review/ReviewEvidenceShard")({
1764
- shardId: ReviewEvidenceShardId,
1765
- path: ChangedPath,
1766
- ordinal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
1767
- total: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
1768
- evidenceChars: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(MAX_PATCH_CHARS))
1769
- }) {};
1770
- const EvidenceShardIds$1 = Schema.Array(ReviewEvidenceShardId).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12));
1771
- /** One required, independently scoped discovery attempt. */
1772
- var ReviewDiscoveryPass = class extends Schema.Class("@effect-agent/pr-review/ReviewDiscoveryPass")({
1773
- passId: ReviewPassId,
1774
- unitId: ReviewUnitId,
1775
- paths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12)),
1776
- evidenceShardIds: EvidenceShardIds$1,
1777
- perspective: ReviewDiscoveryPerspective,
1778
- /** Empty for the general pass; explicit deterministic focus for specialists. */
1779
- riskCategories: Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6))
1780
- }) {};
1781
- /** One bounded slice of the changeset delegated to one child reviewer. */
1782
- var ReviewUnit = class extends Schema.Class("@effect-agent/pr-review/ReviewUnit")({
1783
- unitId: ReviewUnitId,
1784
- paths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12)),
1785
- evidenceShards: Schema.Array(ReviewEvidenceShard).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12)),
1786
- /** additions + deletions across the unit's files, for honest sizing. */
1787
- changedLines: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1788
- /** Complete model-visible diff/content evidence assigned to each child. */
1789
- evidenceChars: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(UNIT_EVIDENCE_CHAR_BUDGET)),
1790
- /** Host-classified focus labels for the unit's redundant specialist pass. */
1791
- riskCategories: Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6))
1792
- }) {};
1793
- /** The complete deterministic fan-out plan over one changeset. */
1794
- var ReviewUnitPlan = class extends Schema.Class("@effect-agent/pr-review/ReviewUnitPlan")({
1795
- totalFiles: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1796
- /** True when the source returned fewer files than the pull request has. */
1797
- truncated: Schema.Boolean,
1798
- units: Schema.Array(ReviewUnit).check(Schema.isMaxLength(8)),
1799
- /** Exact discovery calls the coordinator must make. */
1800
- discoveryPasses: Schema.Array(ReviewDiscoveryPass).check(Schema.isMaxLength(16)),
1801
- /** Changed files with neither a textual diff nor bounded base/head text. */
1802
- undiffablePaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300)),
1803
- /** Assigned paths with one or more evidence shards beyond plan capacity. */
1804
- partialEvidencePaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300)),
1805
- /** Exact number of shards beyond the bounded unit capacity. */
1806
- unassignedEvidenceShardCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1807
- /** Bounded deterministic prefix of the unassigned shard identifiers. */
1808
- unassignedEvidenceShardIds: Schema.Array(ReviewEvidenceShardId).check(Schema.isMaxLength(96)),
1809
- /**
1810
- * Diffable files beyond the fan-out capacity (MAX_REVIEW_UNITS units of
1811
- * MAX_UNIT_FILES files). Never silently dropped: the coordinator must name
1812
- * them as unreviewed in its summary.
1813
- */
1814
- unassignedPaths: Schema.Array(ChangedPath).check(Schema.isMaxLength(300))
1815
- }) {};
1816
- const riskRules = [
1817
- {
1818
- category: "authentication-authorization",
1819
- patterns: [
1820
- /auth/,
1821
- /authoriz/,
1822
- /permission/,
1823
- /principal/,
1824
- /access[-_ ]?control/,
1825
- /role\b/
1826
- ]
1827
- },
1828
- {
1829
- category: "security-boundary",
1830
- patterns: [
1831
- /security/,
1832
- /sandbox/,
1833
- /untrusted/,
1834
- /schema\.decode/,
1835
- /validation/,
1836
- /injection/,
1837
- /csrf/,
1838
- /xss/,
1839
- /path traversal/
1840
- ]
1841
- },
1842
- {
1843
- category: "persistence-durability",
1844
- patterns: [
1845
- /durab/,
1846
- /persist/,
1847
- /storage/,
1848
- /database/,
1849
- /\bsql\b/,
1850
- /journal/,
1851
- /ledger/,
1852
- /checkpoint/,
1853
- /migration/,
1854
- /transaction/
1855
- ]
1856
- },
1857
- {
1858
- category: "concurrency",
1859
- patterns: [
1860
- /concurr/,
1861
- /semaphore/,
1862
- /\bfiber/,
1863
- /race/,
1864
- /mutex/,
1865
- /\block\b/,
1866
- /queue/,
1867
- /parallel/,
1868
- /interrupt/
1869
- ]
1870
- },
1871
- {
1872
- category: "credential-handling",
1873
- patterns: [
1874
- /credential/,
1875
- /secret/,
1876
- /password/,
1877
- /api[-_ ]?key/,
1878
- /bearer/,
1879
- /hmac/,
1880
- /signature/
1881
- ]
1882
- },
1883
- {
1884
- category: "external-side-effects",
1885
- patterns: [
1886
- /publish/,
1887
- /webhook/,
1888
- /github/,
1889
- /fetch\(/,
1890
- /http/,
1891
- /send[-_ ]?(email|message)/,
1892
- /write[-_ ]?(file|record)/,
1893
- /delete/,
1894
- /mutation/,
1895
- /side[-_ ]?effect/,
1896
- /spawn/,
1897
- /exec/
1898
- ]
1899
- }
1900
- ];
1901
- /**
1902
- * Deterministic host policy for specialist assignment. It intentionally
1903
- * favors false positives: an extra bounded pass costs work, while a missed
1904
- * high-risk classification removes redundancy. This is not a claim that the
1905
- * keyword policy recognizes every semantically risky change.
1906
- */
1907
- const classifyReviewRisks = (file) => {
1908
- const text = [
1909
- file.path,
1910
- file.previousPath ?? "",
1911
- file.patch ?? "",
1912
- file.reviewBaseContent ?? "",
1913
- file.reviewHeadContent ?? ""
1914
- ].join("\n").toLowerCase();
1915
- return riskRules.filter((rule) => rule.patterns.some((pattern) => pattern.test(text))).map((rule) => rule.category);
1916
- };
1917
- /**
1918
- * Whether every claimed finding anchor was present in the exact bounded
1919
- * evidence shards assigned to one unit. This is stricter than checking the
1920
- * full pull-request diff when an oversized path spans multiple units.
1921
- */
1922
- const findingAnchorInUnitEvidence = (finding, unit, files) => {
1923
- const file = files.find((candidate) => candidate.path === finding.path);
1924
- if (file?.patch === void 0 || finding.endLine < finding.startLine) return false;
1925
- const assignedOrdinals = new Set(unit.evidenceShards.filter((shard) => shard.path === finding.path).map((shard) => shard.ordinal));
1926
- const visibleLines = /* @__PURE__ */ new Set();
1927
- const chunks = fileReviewEvidenceChunks(file);
1928
- for (let index = 0; index < chunks.length; index += 1) {
1929
- if (!assignedOrdinals.has(index + 1)) continue;
1930
- for (const line of chunks[index]?.annotatedPatch.split("\n") ?? []) {
1931
- const match = /^R(\d+) /.exec(line);
1932
- if (match?.[1] !== void 0) visibleLines.add(Number(match[1]));
1933
- }
1934
- }
1935
- for (let line = finding.startLine; line <= finding.endLine; line += 1) if (!visibleLines.has(line)) return false;
1936
- return true;
1937
- };
1938
- const uniquePaths = (shards) => [...new Set(shards.map(({ shard }) => shard.path))];
1939
- const plannedEvidenceShards = (files) => {
1940
- const planned = [];
1941
- let shardIndex = 0;
1942
- for (const file of files) {
1943
- const chunks = fileReviewEvidenceChunks(file);
1944
- for (let index = 0; index < chunks.length; index += 1) {
1945
- const chunk = chunks[index];
1946
- if (chunk === void 0) continue;
1947
- shardIndex += 1;
1948
- planned.push({
1949
- shard: ReviewEvidenceShard.make({
1950
- shardId: `shard-${String(shardIndex).padStart(4, "0")}`,
1951
- path: file.path,
1952
- ordinal: index + 1,
1953
- total: chunks.length,
1954
- evidenceChars: chunk.annotatedPatch.length
1955
- }),
1956
- file,
1957
- changedLines: index === 0 ? file.additions + file.deletions : 0
1958
- });
1959
- }
1960
- }
1961
- return planned;
1962
- };
1963
- const unitOf = (index, shards) => ReviewUnit.make({
1964
- unitId: `unit-${String(index + 1).padStart(3, "0")}`,
1965
- paths: uniquePaths(shards),
1966
- evidenceShards: shards.map(({ shard }) => shard),
1967
- changedLines: shards.reduce((total, shard) => total + shard.changedLines, 0),
1968
- evidenceChars: shards.reduce((total, { shard }) => total + shard.evidenceChars, 0),
1969
- riskCategories: [...new Set(shards.flatMap(({ file }) => classifyReviewRisks(file)))]
1970
- });
1971
- const discoveryPassesFor = (units) => units.flatMap((unit) => [ReviewDiscoveryPass.make({
1972
- passId: `${unit.unitId}-general`,
1973
- unitId: unit.unitId,
1974
- paths: unit.paths,
1975
- evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),
1976
- perspective: "general",
1977
- riskCategories: []
1978
- }), ReviewDiscoveryPass.make({
1979
- passId: `${unit.unitId}-specialist`,
1980
- unitId: unit.unitId,
1981
- paths: unit.paths,
1982
- evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),
1983
- perspective: "risk-specialist",
1984
- riskCategories: unit.riskCategories
1985
- })]);
1986
- /**
1987
- * Group the changeset into at most `MAX_REVIEW_UNITS` review units.
1988
- *
1989
- * Deterministic by construction: files are ordered by path (so files sharing
1990
- * a directory become neighbors — directory affinity without a heuristic),
1991
- * then split into complete line-bounded evidence shards and packed greedily
1992
- * under the hard evidence and per-unit shard bounds. Capacity is finite and
1993
- * explicit:
1994
- *
1995
- * - files without a textual diff are still delegated when the source
1996
- * recovered complete bounded UTF-8 base/head content. Findings from that
1997
- * evidence cannot anchor inline and are reported as concerns;
1998
- * - files with neither form of textual evidence surface in
1999
- * `undiffablePaths` instead of laundering missing coverage;
2000
- * - an oversized path spans as many deterministic shards and units as needed;
2001
- * - shards beyond `MAX_REVIEW_UNITS` full units surface explicitly, so a path
2002
- * is partial only when finite plan capacity is genuinely exhausted.
2003
- */
2004
- const planReviewUnits = (files, options) => {
2005
- const ordered = [...files].sort((left, right) => left.path < right.path ? -1 : 1);
2006
- const reviewable = ordered.filter(isReviewableFile);
2007
- const undiffable = ordered.filter((file) => !isReviewableFile(file));
2008
- const shards = plannedEvidenceShards(reviewable);
2009
- const groups = [];
2010
- const unassigned = [];
2011
- let current = [];
2012
- let currentEvidenceChars = 0;
2013
- for (const shard of shards) {
2014
- const nextPaths = /* @__PURE__ */ new Set([...uniquePaths(current), shard.shard.path]);
2015
- if (current.length >= 12 || nextPaths.size > 12 || current.length > 0 && currentEvidenceChars + shard.shard.evidenceChars > 24e4) {
2016
- groups.push(current);
2017
- current = [];
2018
- currentEvidenceChars = 0;
2019
- }
2020
- if (groups.length >= 8) {
2021
- unassigned.push(shard);
2022
- continue;
2023
- }
2024
- current.push(shard);
2025
- currentEvidenceChars += shard.shard.evidenceChars;
2026
- }
2027
- if (current.length > 0 && groups.length < 8) groups.push(current);
2028
- const units = groups.map((group, index) => unitOf(index, group));
2029
- const assignedShardIds = new Set(units.flatMap((unit) => unit.evidenceShards.map((shard) => shard.shardId)));
2030
- const assignedPaths = new Set(shards.filter(({ shard }) => assignedShardIds.has(shard.shardId)).map(({ shard }) => shard.path));
2031
- const unassignedPathsWithEvidence = new Set(unassigned.map(({ shard }) => shard.path));
2032
- return ReviewUnitPlan.make({
2033
- totalFiles: files.length,
2034
- truncated: files.length < options.totalChangedFiles,
2035
- units,
2036
- discoveryPasses: discoveryPassesFor(units),
2037
- undiffablePaths: undiffable.map((file) => file.path),
2038
- partialEvidencePaths: [...unassignedPathsWithEvidence].filter((path) => assignedPaths.has(path)),
2039
- unassignedEvidenceShardCount: unassigned.length,
2040
- unassignedEvidenceShardIds: unassigned.slice(0, 96).map(({ shard }) => shard.shardId),
2041
- unassignedPaths: [...unassignedPathsWithEvidence].filter((path) => !assignedPaths.has(path))
2042
- });
2043
- };
2044
- const severityRank = {
2045
- blocking: 0,
2046
- important: 1,
2047
- nit: 2
2048
- };
2049
- const anchorKey = (finding) => `${finding.path} ${finding.startLine} ${finding.endLine}`;
2050
- /**
2051
- * Merge the children's findings into one bounded, deterministic list: dedupe
2052
- * findings sharing an anchor (path + line range) keeping the most severe —
2053
- * and, at equal severity, the first in declaration order — then rank by
2054
- * severity, path, and line, and cap at the `CodeReview` findings bound.
2055
- * This is the merge policy the coordinator's instructions state in prose;
2056
- * pinning it here keeps the policy itself deterministic and testable.
2057
- */
2058
- const rankAndDedupeFindings = (findings) => {
2059
- const byAnchor = /* @__PURE__ */ new Map();
2060
- for (const finding of findings) {
2061
- const key = anchorKey(finding);
2062
- const existing = byAnchor.get(key);
2063
- if (existing === void 0 || severityRank[finding.severity] < severityRank[existing.severity]) byAnchor.set(key, finding);
2064
- }
2065
- return [...byAnchor.values()].sort((left, right) => {
2066
- const bySeverity = severityRank[left.severity] - severityRank[right.severity];
2067
- if (bySeverity !== 0) return bySeverity;
2068
- if (left.path !== right.path) return left.path < right.path ? -1 : 1;
2069
- return left.startLine - right.startLine;
2070
- }).slice(0, 20);
2071
- };
2072
- /**
2073
- * Stable identity for one concern. The paths are part of the claim: identical
2074
- * prose about two independent files must not collapse into one item.
2075
- */
2076
- const reviewConcernKey = (concern) => `${(concern.evidencePaths ?? []).join("\0")}\u0001${concern.title}\u0000${concern.body}`;
2077
- /**
2078
- * The concern analogue of `rankAndDedupeFindings`: dedupe by exact scoped
2079
- * content keeping the most severe duplicate, rank by severity, and cap at the
2080
- * `CodeReview` concerns bound.
2081
- */
2082
- const rankAndDedupeConcerns = (concerns) => {
2083
- const byContent = /* @__PURE__ */ new Map();
2084
- for (const concern of concerns) {
2085
- const key = reviewConcernKey(concern);
2086
- const previous = byContent.get(key);
2087
- if (previous === void 0 || severityRank[concern.severity] < severityRank[previous.severity]) byContent.set(key, concern);
2088
- }
2089
- return [...byContent.values()].sort((left, right) => severityRank[left.severity] - severityRank[right.severity]).slice(0, 10);
2090
- };
2091
- //#endregion
2092
- //#region src/internal/fan-out.ts
2093
- /** One discovery pass returns at most this many anchored candidates. */
2094
- const MAX_CHILD_FINDINGS = 6;
2095
- /** One discovery pass returns at most this many non-anchored candidates. */
2096
- const MAX_CHILD_CONCERNS = 3;
2097
- /** Every unit receives independent general and specialist discovery passes. */
2098
- const MAX_UNIT_CANDIDATES = 18;
2099
- /**
2100
- * General + specialist discovery for every unit, then one verifier per unit.
2101
- * The one-retry budget doubles the worst-case child Run count, but the
2102
- * schedule itself never exceeds this bound.
2103
- */
2104
- const MAX_REVIEW_CHILDREN = 24;
2105
- /** Bounded structured concurrency across units; passes inside a unit are sequential. */
2106
- const REVIEW_UNIT_CONCURRENCY = 4;
2107
- /** Structural minimum for a child that exposes no tools. */
2108
- const MAX_FILE_REVIEW_TOOL_CALLS = 1;
2109
- const ReviewWorkPhase = Schema.Literals(["discovery", "verification"]);
2110
- const ReviewWorkPerspective = Schema.Literals([
2111
- "general",
2112
- "risk-specialist",
2113
- "candidate-verification"
2114
- ]);
2115
- const ReviewCandidateId = Schema.NonEmptyString.check(Schema.isMaxLength(96));
2116
- var FindingCandidate = class extends Schema.TaggedClass()("FindingCandidate", {
2117
- candidateId: ReviewCandidateId,
2118
- workId: ReviewPassId,
2119
- unitId: ReviewUnitId,
2120
- finding: ReviewFinding,
2121
- evidencePaths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(1))
2122
- }) {};
2123
- var ConcernCandidate = class extends Schema.TaggedClass()("ConcernCandidate", {
2124
- candidateId: ReviewCandidateId,
2125
- workId: ReviewPassId,
2126
- unitId: ReviewUnitId,
2127
- concern: ReviewConcern,
2128
- evidencePaths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3))
2129
- }) {};
2130
- const ReviewCandidate = Schema.Union([FindingCandidate, ConcernCandidate]);
2131
- /** Deterministic host equivalence for claims repeated across discovery passes. */
2132
- const reviewCandidateSubjectKey = (candidate) => candidate._tag === "FindingCandidate" ? `finding:${JSON.stringify(Schema.encodeSync(ReviewFinding)(candidate.finding))}` : `concern:${JSON.stringify(Schema.encodeSync(ReviewConcern)(candidate.concern))}`;
2133
- var CandidateAssessment = class extends Schema.Class("@effect-agent/pr-review/CandidateAssessment")({
2134
- candidateId: ReviewCandidateId,
2135
- disposition: Schema.Literals(["confirmed", "rejected"]),
2136
- /**
2137
- * Exact suggestion settlement: required when the candidate finding carries
2138
- * a suggestion, forbidden otherwise. Untrusted child output cannot publish
2139
- * a GitHub replacement block by prompt compliance alone — the host keeps a
2140
- * confirmed finding's suggestion only on an exact "committable" settlement.
2141
- */
2142
- suggestion: Schema.optionalKey(Schema.Literals(["committable", "not-committable"]).annotate({ description: "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." })),
2143
- rationale: Schema.NonEmptyString.check(Schema.isMaxLength(600))
2144
- }) {};
2145
- /**
2146
- * Exact suggestion settlement shape: a carried suggestion must be settled and
2147
- * nothing else may be. A verification report that violates it is treated as a
2148
- * misbehaving pass and retried within the pass budget.
2149
- */
2150
- const assessmentSettlesSuggestionExactly = (assessment, candidate) => candidate._tag === "FindingCandidate" && candidate.finding.suggestion !== void 0 ? assessment.suggestion !== void 0 : assessment.suggestion === void 0;
2151
- /**
2152
- * Fail-closed publication of a confirmed finding: only an exact "committable"
2153
- * settlement keeps the suggestion; anything else publishes the finding with
2154
- * the suggestion stripped so unverified text can never become a one-click
2155
- * GitHub replacement block.
2156
- */
2157
- const confirmedFindingForPublication = (assessment, candidate) => {
2158
- if (candidate.finding.suggestion === void 0 || assessment.suggestion === "committable") return candidate.finding;
2159
- const { suggestion: _stripped, ...finding } = candidate.finding;
2160
- return ReviewFinding.make(finding);
2161
- };
2162
- /**
2163
- * Concern candidates need explicit paths internally to bind the claim to
2164
- * scheduled evidence. The verifier receives the complete bounded unit so it
2165
- * can use neighboring evidence to falsify the claim. The host copies these
2166
- * validated paths onto a confirmed public concern for incremental continuity.
2167
- */
2168
- var DiscoveredConcern = class extends Schema.Class("@effect-agent/pr-review/DiscoveredConcern")({
2169
- concern: ReviewConcern,
2170
- evidencePaths: Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(3))
2171
- }) {};
2172
- const UnitPaths = Schema.Array(ChangedPath).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12));
2173
- /** Bounded prior-review context lines injected into discovery instructions. */
2174
- const UnitContextLines = Schema.Array(Schema.String.check(Schema.isMaxLength(1200))).check(Schema.isMaxLength(20));
2175
- const RiskCategories = Schema.Array(ReviewRiskCategory).check(Schema.isMaxLength(6));
2176
- const Candidates = Schema.Array(ReviewCandidate).check(Schema.isMaxLength(18));
2177
- const EvidenceShardIds = Schema.Array(ReviewEvidenceShardId).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12));
2178
- /** One complete host-selected evidence shard supplied to a review child. */
2179
- var FileReviewEvidence = class extends Schema.Class("@effect-agent/pr-review/FileReviewEvidence")({
2180
- shardId: ReviewEvidenceShardId,
2181
- path: ChangedPath,
2182
- status: ChangedFileStatus,
2183
- reviewMode: Schema.Literals([
2184
- "diff",
2185
- "content",
2186
- "unavailable"
2187
- ]),
2188
- ordinal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
2189
- total: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
2190
- annotatedPatch: Schema.String.check(Schema.isMaxLength(MAX_PATCH_CHARS))
2191
- }) {};
2192
- /** Host-prepared child input with complete bounded diff/content evidence. */
2193
- var FileReviewBrief = class extends Schema.Class("@effect-agent/pr-review/FileReviewBrief")({
2194
- phase: ReviewWorkPhase,
2195
- workId: ReviewPassId,
2196
- unitId: ReviewUnitId,
2197
- paths: UnitPaths,
2198
- evidenceShardIds: EvidenceShardIds,
2199
- perspective: ReviewWorkPerspective,
2200
- riskCategories: RiskCategories,
2201
- /** Empty for discovery; the exact discovered set for unit verification. */
2202
- candidates: Candidates,
2203
- evidence: Schema.Array(FileReviewEvidence).check(Schema.isMinLength(1)).check(Schema.isMaxLength(12)),
2204
- /** Maintainer-adjudicated identities on this unit; do not re-raise. */
2205
- adjudicatedContext: Schema.optionalKey(UnitContextLines),
2206
- /** Prior-round findings on this unit's re-reviewed paths. */
2207
- priorFindingContext: Schema.optionalKey(UnitContextLines)
2208
- }) {};
2209
- /** Child output; phase-inapplicable collections must be empty. */
2210
- var FileReviewReport = class extends Schema.Class("@effect-agent/pr-review/FileReviewReport")({
2211
- phase: ReviewWorkPhase,
2212
- workId: ReviewPassId,
2213
- unitId: ReviewUnitId,
2214
- findings: Schema.Array(ReviewFinding).check(Schema.isMaxLength(6)),
2215
- concerns: Schema.Array(DiscoveredConcern).check(Schema.isMaxLength(3)),
2216
- fileSummaries: Schema.Array(WalkthroughEntry).check(Schema.isMaxLength(12)),
2217
- assessments: Schema.Array(CandidateAssessment).check(Schema.isMaxLength(18))
2218
- }) {};
2219
- /**
2220
- * A structurally valid child report that does not answer the scheduled pass:
2221
- * wrong identity, phase-inapplicable fields, or an inexact assessment set.
2222
- * Retried once like any other pass fault, because it is model misbehavior,
2223
- * not evidence about the code under review.
2224
- */
2225
- var ReviewPassMisbehaved = class extends Schema.TaggedError()("ReviewPassMisbehaved", {
2226
- workId: ReviewPassId,
2227
- reason: Schema.NonEmptyString.check(Schema.isMaxLength(600))
2228
- }) {};
2229
- const staticGuidanceLines = (guidance) => {
2230
- if (guidance === void 0) return [];
2231
- return (typeof guidance === "string" ? [guidance] : guidance).filter((line) => line.length > 0);
2232
- };
2233
- const evidenceInstructions = [
2234
- "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.",
2235
- "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.",
2236
- "A diff marks new-version anchors as R<number>; only those lines may anchor findings. B/H content evidence is non-anchorable."
2237
- ];
2238
- /** Discovery and verification instructions share one child definition. */
2239
- const makeFileReviewerInstructions = (options = {}) => (brief) => {
2240
- const common = [
2241
- `You are an attached review worker for ${brief.workId} in host-planned unit ${brief.unitId}: ${brief.paths.join(", ")}.`,
2242
- ...staticGuidanceLines(options.guidance),
2243
- ...evidenceInstructions
2244
- ];
2245
- if (brief.phase === "verification") return [
2246
- ...common,
2247
- "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.",
2248
- "The evidence array contains the complete bounded unit, including neighboring changed code that may confirm or falsify a locally plausible claim.",
2249
- "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.",
2250
- "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.",
2251
- "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."
2252
- ].join("\n");
2253
- const focus = brief.perspective === "risk-specialist" ? brief.riskCategories.length > 0 ? `This is a fresh specialist discovery pass. Concentrate on these host-classified risks without relying on another pass: ${brief.riskCategories.join(", ")}.` : "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." : "This is the general discovery pass. Review broadly for correctness, security, concurrency, resource, API, and error-handling defects.";
2254
- const adjudicated = brief.adjudicatedContext ?? [];
2255
- const priorFindings = brief.priorFindingContext ?? [];
2256
- return [
2257
- ...common,
2258
- focus,
2259
- ...adjudicated.length === 0 ? [] : ["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:", ...adjudicated.map((line) => `- ${line}`)],
2260
- ...priorFindings.length === 0 ? [] : ["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:", ...priorFindings.map((line) => `- ${line}`)],
2261
- "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.",
2262
- "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.",
2263
- `Return ONLY JSON with phase "discovery", the exact workId/unitId, up to 6 findings, up to 3 concerns shaped as {concern, evidencePaths}, one factual file summary per path (<= 240 chars), and an empty assessments array. Empty candidate arrays are valid; do not invent defects.`,
2264
- "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>}.",
2265
- "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\"."
2266
- ].join("\n");
2267
- };
2268
- const fileReviewerInstructions = makeFileReviewerInstructions();
2269
- const FileReviewToolkit = Toolkit.empty;
2270
- const defaultFileReviewerPolicy = AgentPolicy.make({
2271
- maxTurns: 6,
2272
- maxToolCalls: 1,
2273
- maxDuration: "6 minutes",
2274
- toolConcurrency: 2,
2275
- repeatedFailureLimit: 6,
2276
- tokenBudget: 2e5,
2277
- contextTokenLimit: 15e4,
2278
- toolResultBounds: ToolResultBounds.make({ maxBytes: REVIEW_TOOL_RESULT_MAX_BYTES }),
2279
- onExhaustion: "fail"
2280
- });
2281
- const makeFileReviewerDefinition = (options = {}) => Agent.define("pr-review-worker", {
2282
- input: FileReviewBrief,
2283
- output: FileReviewReport,
2284
- instructions: makeFileReviewerInstructions(options),
2285
- toolkit: FileReviewToolkit,
2286
- policy: defaultFileReviewerPolicy,
2287
- description: "Perform one bounded discovery or independent candidate-verification pass over host-supplied pull-request evidence.",
2288
- metadata: {
2289
- deploymentClass: "E",
2290
- surface: "read-only",
2291
- stage: "discovery-verification"
2292
- }
2293
- });
2294
- const FileReviewer = makeFileReviewerDefinition();
2295
- const candidateOrdinal = (index) => String(index + 1).padStart(3, "0");
2296
- /** Rebuild one unit's complete evidence from the same snapshot the plan used. */
2297
- const unitEvidence = (unit, files) => Effect.gen(function* () {
2298
- const byPath = new Map(files.map((file) => [file.path, file]));
2299
- const evidence = [];
2300
- for (const shard of unit.evidenceShards) {
2301
- const file = byPath.get(shard.path);
2302
- const chunk = file === void 0 ? void 0 : fileReviewEvidenceChunks(file)[shard.ordinal - 1];
2303
- if (file === void 0 || chunk === void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`planned evidence shard has no source: ${shard.shardId} (${shard.path})`));
2304
- evidence.push(FileReviewEvidence.make({
2305
- shardId: shard.shardId,
2306
- path: shard.path,
2307
- status: file.status,
2308
- reviewMode: chunk.reviewMode,
2309
- ordinal: shard.ordinal,
2310
- total: shard.total,
2311
- annotatedPatch: chunk.annotatedPatch
2312
- }));
2313
- }
2314
- return evidence;
2315
- });
2316
- const misbehaved = (workId, reason) => ReviewPassMisbehaved.make({
2317
- workId,
2318
- reason: reason.slice(0, 600)
2319
- });
2320
- /** Validate that a verification report assesses exactly the scheduled candidates. */
2321
- const validateVerificationReport = (brief, report) => {
2322
- if (report.findings.length > 0 || report.concerns.length > 0 || report.fileSummaries.length > 0) return misbehaved(brief.workId, "verification output contained discovery-only fields");
2323
- const expectedById = new Map(brief.candidates.map((candidate) => [candidate.candidateId, candidate]));
2324
- const assessedIds = /* @__PURE__ */ new Set();
2325
- for (const assessment of report.assessments) {
2326
- const candidate = expectedById.get(assessment.candidateId);
2327
- if (candidate === void 0 || assessedIds.has(assessment.candidateId)) return misbehaved(brief.workId, "verification output did not assess the exact candidate set");
2328
- if (!assessmentSettlesSuggestionExactly(assessment, candidate)) return misbehaved(brief.workId, "verification output did not settle suggestion publication exactly");
2329
- assessedIds.add(assessment.candidateId);
2330
- }
2331
- if (assessedIds.size !== expectedById.size) return misbehaved(brief.workId, "verification output did not assess the exact candidate set");
2332
- };
2333
- /**
2334
- * Run one scheduled pass: execute the child, decode its report, and enforce
2335
- * the pass contract. Any typed fault — child failure, malformed or misdirected
2336
- * output — is retried once; budget exhaustion is terminal because a retry
2337
- * would fail the same way. The settled outcome is a value either way, so one
2338
- * flaky pass can never fail the whole pipeline.
2339
- */
2340
- const runReviewPass = (binding, brief, budget) => Effect.gen(function* () {
2341
- const result = yield* AgentRuntime.run(binding, brief, {
2342
- ...budget === void 0 ? {} : { budget },
2343
- estimateCostMicrousd: () => Effect.succeed(500)
2344
- });
2345
- const report = yield* Schema.decodeUnknownEffect(FileReviewReport)(result.output).pipe(Effect.mapError((error) => misbehaved(brief.workId, `child report failed to decode: ${error.message}`)));
2346
- if (report.phase !== brief.phase || report.workId !== brief.workId || report.unitId !== brief.unitId) return yield* misbehaved(brief.workId, "child report identity does not match the scheduled pass");
2347
- if (brief.phase === "verification") {
2348
- const violation = validateVerificationReport(brief, report);
2349
- if (violation !== void 0) return yield* violation;
2350
- } else if (report.assessments.length > 0) return yield* misbehaved(brief.workId, "discovery output contained verification-only assessments");
2351
- return {
2352
- report,
2353
- turns: result.turns
2354
- };
2355
- }).pipe(Effect.scoped, Effect.retry({
2356
- times: 1,
2357
- while: (error) => error._tag !== "BudgetExceeded"
2358
- }), Effect.map((settled) => ({
2359
- _tag: "settled",
2360
- ...settled
2361
- })), Effect.catch((error) => Effect.succeed({
2362
- _tag: "failed",
2363
- errorTag: String(error._tag).slice(0, 256)
2364
- })));
2365
- /**
2366
- * Keep only findings anchored inside the pass's exact assigned evidence and
2367
- * concerns bound to unit paths. Everything else is discarded and counted —
2368
- * an invalid anchor invalidates one claim, never the pass that produced it.
2369
- */
2370
- const harvestDiscovery = (pass, unit, files, anchorFiles, report) => {
2371
- const allowed = new Set(pass.paths);
2372
- let discarded = 0;
2373
- const keptFindings = [];
2374
- for (const finding of report.findings) {
2375
- if (!allowed.has(finding.path) || anchorViolation(finding, anchorFiles) !== void 0 || !findingAnchorInUnitEvidence(finding, unit, files)) {
2376
- discarded += 1;
2377
- continue;
2378
- }
2379
- keptFindings.push(finding);
2380
- }
2381
- const keptConcerns = [];
2382
- for (const candidate of report.concerns) {
2383
- if (candidate.evidencePaths.some((path) => !allowed.has(path))) {
2384
- discarded += 1;
2385
- continue;
2386
- }
2387
- keptConcerns.push(candidate);
2388
- }
2389
- return {
2390
- candidates: [...keptFindings.map((finding, index) => FindingCandidate.make({
2391
- candidateId: `${pass.passId}:finding:${candidateOrdinal(index)}`,
2392
- workId: pass.passId,
2393
- unitId: pass.unitId,
2394
- finding,
2395
- evidencePaths: [finding.path]
2396
- })), ...keptConcerns.map((candidate, index) => ConcernCandidate.make({
2397
- candidateId: `${pass.passId}:concern:${candidateOrdinal(index)}`,
2398
- workId: pass.passId,
2399
- unitId: pass.unitId,
2400
- concern: candidate.concern,
2401
- evidencePaths: candidate.evidencePaths
2402
- }))],
2403
- fileSummaries: report.fileSummaries.filter((entry) => allowed.has(entry.path)),
2404
- discarded
2405
- };
2406
- };
2407
- const reviewUnit = (binding, unit, passes, input) => Effect.gen(function* () {
2408
- const evidence = yield* unitEvidence(unit, input.files);
2409
- const failedPasses = [];
2410
- const candidates = [];
2411
- const subjects = /* @__PURE__ */ new Set();
2412
- const walkthrough = [];
2413
- let discardedFindings = 0;
2414
- let turns = 0;
2415
- let completedGeneralPasses = 0;
2416
- let completedSpecialistPasses = 0;
2417
- const unitPaths = new Set(unit.paths);
2418
- const adjudicatedContext = (input.priorContext?.adjudicated ?? []).filter((entry) => entry.path === void 0 || unitPaths.has(entry.path)).map((entry) => entry.line).slice(0, 20);
2419
- const priorFindingContext = (input.priorContext?.priorFindings ?? []).filter((entry) => unitPaths.has(entry.path)).map((entry) => entry.line).slice(0, 20);
2420
- for (const pass of passes) {
2421
- const stage = pass.perspective === "risk-specialist" ? "specialist" : "discovery";
2422
- const brief = FileReviewBrief.make({
2423
- phase: "discovery",
2424
- workId: pass.passId,
2425
- unitId: pass.unitId,
2426
- paths: pass.paths,
2427
- evidenceShardIds: pass.evidenceShardIds,
2428
- perspective: pass.perspective,
2429
- riskCategories: pass.riskCategories,
2430
- candidates: [],
2431
- evidence,
2432
- ...adjudicatedContext.length === 0 ? {} : { adjudicatedContext },
2433
- ...priorFindingContext.length === 0 ? {} : { priorFindingContext }
2434
- });
2435
- const outcome = yield* runReviewPass(binding, brief, input.budget);
2436
- if (outcome._tag === "failed") {
2437
- failedPasses.push(FailedReviewPass.make({
2438
- workId: pass.passId,
2439
- stage,
2440
- errorTag: outcome.errorTag
2441
- }));
2442
- continue;
2443
- }
2444
- turns += outcome.turns;
2445
- if (stage === "specialist") completedSpecialistPasses += 1;
2446
- else completedGeneralPasses += 1;
2447
- const harvest = harvestDiscovery(pass, unit, input.files, input.anchorFiles, outcome.report);
2448
- discardedFindings += harvest.discarded;
2449
- if (pass.perspective === "general") walkthrough.push(...harvest.fileSummaries);
2450
- for (const candidate of harvest.candidates) {
2451
- const subject = reviewCandidateSubjectKey(candidate);
2452
- if (subjects.has(subject)) continue;
2453
- subjects.add(subject);
2454
- candidates.push(candidate);
2455
- }
2456
- }
2457
- const confirmed = [];
2458
- let rejectedCandidates = 0;
2459
- let unsettledCandidates = 0;
2460
- let completedVerificationPasses = 0;
2461
- const requiredVerificationPasses = candidates.length > 0 ? 1 : 0;
2462
- if (candidates.length > 0) {
2463
- const workId = `${unit.unitId}-verification`;
2464
- const brief = FileReviewBrief.make({
2465
- phase: "verification",
2466
- workId,
2467
- unitId: unit.unitId,
2468
- paths: unit.paths,
2469
- evidenceShardIds: unit.evidenceShards.map((shard) => shard.shardId),
2470
- perspective: "candidate-verification",
2471
- riskCategories: unit.riskCategories,
2472
- candidates,
2473
- evidence
2474
- });
2475
- const outcome = yield* runReviewPass(binding, brief, input.budget);
2476
- if (outcome._tag === "failed") {
2477
- unsettledCandidates = candidates.length;
2478
- failedPasses.push(FailedReviewPass.make({
2479
- workId,
2480
- stage: "verification",
2481
- errorTag: outcome.errorTag
2482
- }));
2483
- } else {
2484
- turns += outcome.turns;
2485
- completedVerificationPasses = 1;
2486
- const byId = new Map(candidates.map((candidate) => [candidate.candidateId, candidate]));
2487
- for (const assessment of outcome.report.assessments) {
2488
- const candidate = byId.get(assessment.candidateId);
2489
- if (candidate === void 0) continue;
2490
- if (assessment.disposition === "confirmed") confirmed.push({
2491
- assessment,
2492
- candidate
2493
- });
2494
- else rejectedCandidates += 1;
2495
- }
2496
- }
2497
- }
2498
- return {
2499
- failedPasses,
2500
- discoveredCandidates: candidates.length,
2501
- confirmed,
2502
- rejectedCandidates,
2503
- unsettledCandidates,
2504
- discardedFindings,
2505
- walkthrough,
2506
- turns,
2507
- completedGeneralPasses,
2508
- completedSpecialistPasses,
2509
- requiredVerificationPasses,
2510
- completedVerificationPasses,
2511
- unreviewedPaths: failedPasses.length > 0 ? unit.paths : [],
2512
- unreviewedPasses: failedPasses.map((pass) => ({
2513
- stage: pass.stage,
2514
- paths: unit.paths
2515
- }))
2516
- };
2517
- });
2518
- const countNoun = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
2519
- const composeSummary = (plan, assurance) => {
2520
- const requiredDiscovery = assurance.requiredGeneralDiscoveryPasses + assurance.requiredSpecialistPasses;
2521
- const completedDiscovery = assurance.completedGeneralDiscoveryPasses + assurance.completedSpecialistPasses;
2522
- const parts = [`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.`];
2523
- if (assurance.failedPasses.length > 0) parts.push(`${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.`);
2524
- if (assurance.discardedInvalidFindings > 0) parts.push(`${countNoun(assurance.discardedInvalidFindings, "candidate")} discarded for anchors or paths outside the assigned evidence.`);
2525
- if (plan.undiffablePaths.length > 0) parts.push(`${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.`);
2526
- if (plan.unassignedPaths.length > 0 || plan.unassignedEvidenceShardCount > 0) parts.push("The changeset exceeded the bounded fan-out capacity; unassigned scope is reported under input coverage.");
2527
- parts.push("No configured pipeline can prove absence of defects; this describes settled work only.");
2528
- return parts.join(" ").slice(0, 4e3);
2529
- };
2530
- const remapPlanUnitIds = (plan, offset) => {
2531
- if (offset === 0) return plan;
2532
- const units = plan.units.map((unit, index) => ReviewUnit.make({
2533
- ...unit,
2534
- unitId: `unit-${String(offset + index + 1).padStart(3, "0")}`
2535
- }));
2536
- const mappedIds = /* @__PURE__ */ new Map();
2537
- for (const [index, unit] of plan.units.entries()) {
2538
- const remapped = units[index];
2539
- if (remapped !== void 0) mappedIds.set(unit.unitId, remapped.unitId);
2540
- }
2541
- return ReviewUnitPlan.make({
2542
- ...plan,
2543
- units,
2544
- discoveryPasses: plan.discoveryPasses.map((pass) => {
2545
- const unitId = mappedIds.get(pass.unitId) ?? pass.unitId;
2546
- return ReviewDiscoveryPass.make({
2547
- ...pass,
2548
- unitId,
2549
- passId: `${unitId}${pass.passId.slice(pass.unitId.length)}`
2550
- });
2551
- })
2552
- });
2553
- };
2554
- const scheduleFanOutWork = (input) => {
2555
- const requestedRetryPasses = input.retry?.passes ?? input.retry?.stages?.map((stage) => ({
2556
- stage,
2557
- paths: input.retry?.paths ?? []
2558
- })) ?? [];
2559
- const requestedStagesByPath = /* @__PURE__ */ new Map();
2560
- for (const pass of requestedRetryPasses) for (const path of pass.paths) {
2561
- const stages = requestedStagesByPath.get(path) ?? /* @__PURE__ */ new Set();
2562
- stages.add(pass.stage);
2563
- requestedStagesByPath.set(path, stages);
2564
- }
2565
- const canonicalPathByKnownPath = /* @__PURE__ */ new Map();
2566
- const retryStagesByPath = /* @__PURE__ */ new Map();
2567
- for (const file of input.files) {
2568
- canonicalPathByKnownPath.set(file.path, file.path);
2569
- if (file.previousPath !== void 0) canonicalPathByKnownPath.set(file.previousPath, file.path);
2570
- const requested = [requestedStagesByPath.get(file.path), ...file.previousPath === void 0 ? [] : [requestedStagesByPath.get(file.previousPath)]];
2571
- const stages = new Set(requested.flatMap((entry) => [...entry ?? []]));
2572
- if (stages.size > 0) retryStagesByPath.set(file.path, stages);
2573
- }
2574
- if (retryStagesByPath.size === 0) {
2575
- const plan = planReviewUnits(input.files, { totalChangedFiles: input.totalChangedFiles });
2576
- const passesByUnit = /* @__PURE__ */ new Map();
2577
- for (const pass of plan.discoveryPasses) {
2578
- const passes = passesByUnit.get(pass.unitId) ?? [];
2579
- passes.push(pass);
2580
- passesByUnit.set(pass.unitId, passes);
2581
- }
2582
- return {
2583
- plan,
2584
- passesByUnit,
2585
- overflowRetryPasses: []
2586
- };
2587
- }
2588
- const discoveryStagesFor = (stages) => {
2589
- if (stages.has("verification")) return ["discovery", "specialist"];
2590
- return [...stages.has("discovery") ? ["discovery"] : [], ...stages.has("specialist") ? ["specialist"] : []];
2591
- };
2592
- const freshFiles = input.files.filter((file) => !retryStagesByPath.has(file.path));
2593
- const retryGroups = /* @__PURE__ */ new Map();
2594
- for (const file of input.files) {
2595
- const retryStages = retryStagesByPath.get(file.path);
2596
- if (retryStages === void 0) continue;
2597
- const stages = discoveryStagesFor(retryStages);
2598
- const key = stages.join("|");
2599
- const group = retryGroups.get(key) ?? {
2600
- stages,
2601
- files: []
2602
- };
2603
- group.files.push(file);
2604
- retryGroups.set(key, group);
2605
- }
2606
- const batches = [...freshFiles.length === 0 ? [] : [{
2607
- stages: ["discovery", "specialist"],
2608
- files: freshFiles
2609
- }], ...[...retryGroups.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, group]) => group)];
2610
- const subplans = [];
2611
- const acceptedUnits = [];
2612
- const rejectedUnits = [];
2613
- const discoveryPasses = [];
2614
- for (const batch of batches) {
2615
- const batchPlan = remapPlanUnitIds(planReviewUnits(batch.files, { totalChangedFiles: batch.files.length }), acceptedUnits.length);
2616
- subplans.push(batchPlan);
2617
- const accepted = batchPlan.units.slice(0, Math.max(0, 8 - acceptedUnits.length));
2618
- acceptedUnits.push(...accepted);
2619
- rejectedUnits.push(...batchPlan.units.slice(accepted.length));
2620
- const acceptedIds = new Set(accepted.map((unit) => unit.unitId));
2621
- discoveryPasses.push(...batchPlan.discoveryPasses.filter((pass) => {
2622
- const stage = pass.perspective === "risk-specialist" ? "specialist" : "discovery";
2623
- return acceptedIds.has(pass.unitId) && batch.stages.includes(stage);
2624
- }));
2625
- }
2626
- const acceptedPaths = new Set(acceptedUnits.flatMap((unit) => unit.paths));
2627
- const incompletePlannedPaths = /* @__PURE__ */ new Set([
2628
- ...subplans.flatMap((plan) => plan.partialEvidencePaths),
2629
- ...subplans.flatMap((plan) => plan.unassignedPaths),
2630
- ...rejectedUnits.flatMap((unit) => unit.paths)
2631
- ]);
2632
- const partialEvidencePaths = [...incompletePlannedPaths].filter((path) => acceptedPaths.has(path)).sort();
2633
- const unassignedPaths = [...incompletePlannedPaths].filter((path) => !acceptedPaths.has(path)).sort();
2634
- const rejectedEvidenceShards = rejectedUnits.flatMap((unit) => unit.evidenceShards);
2635
- const undiffablePaths = [...new Set(subplans.flatMap((plan) => plan.undiffablePaths))].sort();
2636
- const plan = ReviewUnitPlan.make({
2637
- totalFiles: input.files.length,
2638
- truncated: input.files.length < input.totalChangedFiles,
2639
- units: acceptedUnits,
2640
- discoveryPasses,
2641
- undiffablePaths,
2642
- partialEvidencePaths,
2643
- unassignedEvidenceShardCount: subplans.reduce((total, item) => total + item.unassignedEvidenceShardCount, 0) + rejectedEvidenceShards.length,
2644
- unassignedEvidenceShardIds: [...subplans.flatMap((item) => item.unassignedEvidenceShardIds), ...rejectedEvidenceShards.map((shard) => shard.shardId)].slice(0, 96),
2645
- unassignedPaths
2646
- });
2647
- const passesByUnit = /* @__PURE__ */ new Map();
2648
- for (const pass of discoveryPasses) {
2649
- const passes = passesByUnit.get(pass.unitId) ?? [];
2650
- passes.push(pass);
2651
- passesByUnit.set(pass.unitId, passes);
2652
- }
2653
- const incompletePaths = /* @__PURE__ */ new Set([
2654
- ...partialEvidencePaths,
2655
- ...unassignedPaths,
2656
- ...undiffablePaths
2657
- ]);
2658
- const overflowRetryPathsByStage = /* @__PURE__ */ new Map();
2659
- for (const pass of requestedRetryPasses) for (const path of pass.paths) {
2660
- const canonicalPath = canonicalPathByKnownPath.get(path);
2661
- if (canonicalPath === void 0 || !incompletePaths.has(canonicalPath)) continue;
2662
- const paths = overflowRetryPathsByStage.get(pass.stage) ?? /* @__PURE__ */ new Set();
2663
- paths.add(canonicalPath);
2664
- overflowRetryPathsByStage.set(pass.stage, paths);
2665
- }
2666
- return {
2667
- plan,
2668
- passesByUnit,
2669
- overflowRetryPasses: [
2670
- "discovery",
2671
- "specialist",
2672
- "verification"
2673
- ].flatMap((stage) => {
2674
- const paths = [...overflowRetryPathsByStage.get(stage) ?? []].sort();
2675
- return Array.from({ length: Math.ceil(paths.length / 12) }, (_, index) => ({
2676
- stage,
2677
- paths: paths.slice(index * 12, (index + 1) * 12)
2678
- }));
2679
- })
2680
- };
2681
- };
2682
- /**
2683
- * Run the complete host-scheduled fan-out pipeline over one selected
2684
- * changeset snapshot: plan, independent discovery, exact verification, and a
2685
- * deterministic host-composed CodeReview from verifier-confirmed candidates
2686
- * only. The verdict is derived from confirmed severities, never model prose.
2687
- */
2688
- const runFanOutReview = (binding, input) => Effect.gen(function* () {
2689
- const { plan, passesByUnit, overflowRetryPasses } = scheduleFanOutWork(input);
2690
- const outcomes = yield* Effect.forEach(plan.units, (unit) => reviewUnit(binding, unit, passesByUnit.get(unit.unitId) ?? [], input), { concurrency: 4 });
2691
- const failedPasses = outcomes.flatMap((outcome) => outcome.failedPasses);
2692
- const unsettledCandidates = outcomes.reduce((total, outcome) => total + outcome.unsettledCandidates, 0);
2693
- const reasons = [];
2694
- if (failedPasses.length > 0) reasons.push(boundedListReason("configured review passes did not settle", failedPasses.map((pass) => `${pass.workId} (${pass.errorTag})`)));
2695
- if (unsettledCandidates > 0) reasons.push(`${unsettledCandidates} discovered candidate(s) did not receive exact verification`);
2696
- const requiredSpecialistPasses = plan.discoveryPasses.filter((pass) => pass.perspective === "risk-specialist").length;
2697
- const confirmed = outcomes.flatMap((outcome) => outcome.confirmed);
2698
- const assurance = ReviewAssurance.make({
2699
- status: reasons.length === 0 ? "settled" : "incomplete",
2700
- requiredGeneralDiscoveryPasses: plan.discoveryPasses.length - requiredSpecialistPasses,
2701
- completedGeneralDiscoveryPasses: outcomes.reduce((total, outcome) => total + outcome.completedGeneralPasses, 0),
2702
- requiredSpecialistPasses,
2703
- completedSpecialistPasses: outcomes.reduce((total, outcome) => total + outcome.completedSpecialistPasses, 0),
2704
- requiredVerificationPasses: outcomes.reduce((total, outcome) => total + outcome.requiredVerificationPasses, 0),
2705
- completedVerificationPasses: outcomes.reduce((total, outcome) => total + outcome.completedVerificationPasses, 0),
2706
- discoveredCandidates: outcomes.reduce((total, outcome) => total + outcome.discoveredCandidates, 0),
2707
- confirmedCandidates: confirmed.length,
2708
- rejectedCandidates: outcomes.reduce((total, outcome) => total + outcome.rejectedCandidates, 0),
2709
- unsettledCandidates,
2710
- discardedInvalidFindings: outcomes.reduce((total, outcome) => total + outcome.discardedFindings, 0),
2711
- failedPasses,
2712
- reasons
2713
- });
2714
- const findings = rankAndDedupeFindings(confirmed.flatMap(({ assessment, candidate }) => candidate._tag === "FindingCandidate" ? [confirmedFindingForPublication(assessment, candidate)] : []));
2715
- const concerns = rankAndDedupeConcerns(confirmed.flatMap(({ candidate }) => candidate._tag === "ConcernCandidate" ? [ReviewConcern.make({
2716
- ...candidate.concern,
2717
- evidencePaths: [...new Set(candidate.evidencePaths)].sort()
2718
- })] : []));
2719
- const walkthrough = outcomes.flatMap((outcome) => outcome.walkthrough);
2720
- const blocking = findings.some((finding) => finding.severity === "blocking") || concerns.some((concern) => concern.severity === "blocking");
2721
- return {
2722
- review: CodeReview.make({
2723
- summary: composeSummary(plan, assurance),
2724
- verdict: blocking ? "request-changes" : findings.length > 0 || concerns.length > 0 ? "comment" : "approve",
2725
- findings,
2726
- ...concerns.length === 0 ? {} : { concerns },
2727
- ...walkthrough.length === 0 ? {} : { walkthrough }
2728
- }),
2729
- assurance,
2730
- plan,
2731
- unreviewedPaths: [.../* @__PURE__ */ new Set([
2732
- ...outcomes.flatMap((outcome) => outcome.unreviewedPaths),
2733
- ...plan.unassignedPaths,
2734
- ...plan.partialEvidencePaths,
2735
- ...plan.undiffablePaths
2736
- ])].sort(),
2737
- unreviewedPasses: [...outcomes.flatMap((outcome) => outcome.unreviewedPasses), ...overflowRetryPasses],
2738
- turns: outcomes.reduce((total, outcome) => total + outcome.turns, 0)
2739
- };
2740
- });
2741
- //#endregion
2742
- //#region src/internal/fingerprint.ts
2743
- const MARKER_PREFIX = "<!-- effect-agent-pr-review fingerprint=sha256:";
2744
- const MARKER_SUFFIX = " -->";
2745
- const MARKER_PATTERN = /<!-- effect-agent-pr-review fingerprint=sha256:([0-9a-f]{64}) -->/g;
2746
- /** Render the invisible review-body marker for one fingerprint. */
2747
- const renderFingerprintMarker = (fingerprint) => `${MARKER_PREFIX}${fingerprint}${MARKER_SUFFIX}`;
2748
- /** The rendered marker length is fixed; publication reserves room for it. */
2749
- const FINGERPRINT_MARKER_LENGTH = renderFingerprintMarker("0".repeat(64)).length;
2750
- /** Extract the last fingerprint marker in one review body, if any. */
2751
- const extractFingerprint = (body) => {
2752
- let last;
2753
- for (const match of body.matchAll(MARKER_PATTERN)) last = match[1];
2754
- return last;
2755
- };
2756
- /** SHA-256 via `Crypto.Crypto`; unavailable crypto is a defect, not an expected failure. */
2757
- const sha256Hex = Effect.fn("sha256Hex")(function* (text) {
2758
- const digest = yield* (yield* Crypto.Crypto).digest("SHA-256", new TextEncoder().encode(text)).pipe(Effect.orDie);
2759
- return Encoding.encodeHex(digest);
2760
- });
2761
- const FIELD = "\0";
2762
- const RECORD = "";
2763
- const SECTION = "";
2764
- /**
2765
- * Unified-diff hunk coordinates describe where a patch applies, not what it
2766
- * changes. A content-equivalent rebase can shift both coordinates while
2767
- * leaving every context/addition/deletion line unchanged, so exclude only
2768
- * those coordinates from the canonical patch representation.
2769
- */
2770
- const canonicalPatch = (patch) => patch.replace(/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/gm, "@@ -_ +_ @@");
2771
- /**
2772
- * Canonical changeset encoding: sorted by path so provider ordering never
2773
- * matters, with every review-relevant field of every file.
2774
- */
2775
- const canonicalChangeset = (files) => files.map((file) => `${file.path}${FIELD}${file.status}${FIELD}${String(file.additions)}${FIELD}${String(file.deletions)}${FIELD}${file.patch === void 0 ? "" : canonicalPatch(file.patch)}${FIELD}${file.reviewBaseContent ?? ""}${FIELD}${file.reviewHeadContent ?? ""}`).sort().join(RECORD);
2776
- /**
2777
- * Fingerprint one review's complete input surface: the (already
2778
- * ignore-filtered) changeset plus the caller's prompt signature — the
2779
- * rendered instructions and any review-shaping options the instructions do
2780
- * not carry.
2781
- */
2782
- const computeChangesetFingerprint = (files, signature) => sha256Hex(`${canonicalChangeset(files)}${SECTION}${signature}`);
2783
- /** Profile fingerprints are SHA-256 over configuration-only signatures. */
2784
- const computeProfileFingerprint = (signature) => sha256Hex(signature);
2785
- //#endregion
2786
- //#region src/internal/github.ts
2787
- const defaultGraphqlUrl = (apiUrl) => apiUrl === "https://api.github.com" ? "https://api.github.com/graphql" : apiUrl.replace(/\/api\/v3$/, "/api/graphql");
2788
- /** Which pull request to review and how to reach the API. */
2789
- const DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN = "github-actions[bot]";
2790
- var GitHubReviewTarget = class GitHubReviewTarget extends Context.Service()("@effect-agent/pr-review/GitHubReviewTarget") {
2791
- static layer(config) {
2792
- return Layer.succeed(this, GitHubReviewTarget.of({
2793
- ...config,
2794
- graphqlUrl: config.graphqlUrl ?? defaultGraphqlUrl(config.apiUrl),
2795
- reviewAuthorLogin: config.reviewAuthorLogin ?? "github-actions[bot]"
2796
- }));
2797
- }
2798
- };
2799
- /** A GitHub API call failed: transport, status, or payload decode. */
2800
- var GitHubApiFailure = class extends Schema.TaggedError()("GitHubApiFailure", {
2801
- operation: Schema.String,
2802
- reason: Schema.String
2803
- }) {
2804
- get message() {
2805
- return `GitHub API operation '${this.operation}' failed: ${this.reason}`;
2806
- }
2807
- };
2808
- const GitHubPullRequestWire = Schema.Struct({
2809
- number: Schema.Int,
2810
- title: Schema.String,
2811
- body: Schema.NullOr(Schema.String),
2812
- changed_files: Schema.Int,
2813
- base: Schema.Struct({
2814
- ref: Schema.String,
2815
- sha: Schema.String
2816
- }),
2817
- head: Schema.Struct({
2818
- ref: Schema.String,
2819
- sha: Schema.String
2820
- })
2821
- });
2822
- const GitHubFileWire = Schema.Struct({
2823
- filename: Schema.String,
2824
- status: Schema.String,
2825
- additions: Schema.Int,
2826
- deletions: Schema.Int,
2827
- patch: Schema.optionalKey(Schema.String),
2828
- previous_filename: Schema.optionalKey(Schema.String)
2829
- });
2830
- const GitHubFilesPageWire = Schema.Array(GitHubFileWire);
2831
- const GitHubActorWire = Schema.Struct({ node_id: Schema.String });
2832
- const GitHubReviewWire = Schema.Struct({
2833
- id: Schema.Int,
2834
- html_url: Schema.String,
2835
- user: Schema.NullOr(GitHubActorWire),
2836
- submitted_at: Schema.NullOr(Schema.String)
2837
- });
2838
- const GitHubRetirableReviewWire = Schema.Struct({
2839
- id: Schema.Int,
2840
- body: Schema.NullOr(Schema.String),
2841
- commit_id: Schema.String,
2842
- user: Schema.NullOr(GitHubActorWire),
2843
- submitted_at: Schema.NullOr(Schema.String)
2844
- });
2845
- const GitHubRetirableReviewsPageWire = Schema.Array(GitHubRetirableReviewWire);
2846
- const GitHubReviewCommentWire = Schema.Struct({
2847
- node_id: Schema.String,
2848
- path: Schema.String,
2849
- body: Schema.String,
2850
- line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
2851
- original_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
2852
- start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
2853
- original_start_line: Schema.optionalKey(Schema.NullOr(Schema.Int))
2854
- });
2855
- const GitHubReviewCommentsPageWire = Schema.Array(GitHubReviewCommentWire);
2856
- const GitHubMinimizeCommentWire = Schema.Struct({
2857
- data: Schema.optionalKey(Schema.NullOr(Schema.Struct({ minimizeComment: Schema.NullOr(Schema.Struct({ minimizedComment: Schema.NullOr(Schema.Struct({ isMinimized: Schema.Boolean })) })) }))),
2858
- errors: Schema.optionalKey(Schema.Array(Schema.Struct({ message: Schema.String })))
2859
- });
2860
- /** Decode GitHub's external timestamp before it participates in mutation ordering. */
2861
- const parseGitHubSubmittedAt = (value) => value === null ? null : Option.getOrNull(DateTime.make(value));
2862
- /** The publication receipt callers report back to the operator. */
2863
- var PublishedReview = class extends Schema.Class("@effect-agent/pr-review/PublishedReview")({
2864
- reviewId: Schema.Int,
2865
- url: Schema.String,
2866
- event: Schema.String,
2867
- inlineComments: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
2868
- /** Actor and ordering boundary returned by the create-review response. */
2869
- authorNodeId: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(200))),
2870
- submittedAt: Schema.NullOr(Schema.DateTimeUtc)
2871
- }) {};
2872
- /** Posts one planned review; the ONLY mutating operation in this package. */
2873
- var ReviewPublisher = class extends Context.Service()("@effect-agent/pr-review/ReviewPublisher") {};
2874
- const FILE_STATUSES = /* @__PURE__ */ new Set([
2875
- "added",
2876
- "removed",
2877
- "modified",
2878
- "renamed",
2879
- "copied",
2880
- "changed",
2881
- "unchanged"
2882
- ]);
2883
- const withCommonHeaders = (request, token) => {
2884
- const base = request.pipe(HttpClientRequest.setHeaders({
2885
- "X-GitHub-Api-Version": "2022-11-28",
2886
- "User-Agent": "effect-agent-pr-review"
2887
- }));
2888
- return Option.isSome(token) ? base.pipe(HttpClientRequest.bearerToken(token.value)) : base;
2889
- };
2890
- const failWith = (operation) => (error) => PullRequestSourceFailure.make({
2891
- operation,
2892
- reason: `${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048)
2893
- });
2894
- const decodeJsonBody = (schema, operation) => {
2895
- const decode = Schema.decodeUnknownEffect(schema);
2896
- return (response) => response.json.pipe(Effect.mapError(failWith(operation)), Effect.flatMap((body) => decode(body).pipe(Effect.mapError(failWith(operation)))));
2897
- };
2898
- const executeOk = (operation, request) => HttpClient.execute(request).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(failWith(operation)));
2899
- const toChangedFile = (wire) => ChangedFile.make({
2900
- path: wire.filename,
2901
- status: FILE_STATUSES.has(wire.status) ? wire.status : "changed",
2902
- additions: wire.additions,
2903
- deletions: wire.deletions,
2904
- ...wire.previous_filename !== void 0 ? { previousPath: wire.previous_filename } : {},
2905
- ...wire.patch !== void 0 ? { patch: wire.patch } : {}
2906
- });
2907
- /**
2908
- * GitHub-backed PullRequestSource. Metadata and the changeset are fetched
2909
- * once per Layer build and cached: the pull request is reviewed as one
2910
- * consistent snapshot even if the branch moves mid-run.
2911
- */
2912
- const gitHubPullRequestSourceLayer = Layer.effect(PullRequestSource)(Effect.gen(function* () {
2913
- const target = yield* GitHubReviewTarget;
2914
- const client = yield* HttpClient.HttpClient;
2915
- const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;
2916
- const fetchMetadata = executeOk("getPullRequest", withCommonHeaders(HttpClientRequest.get(prefix).pipe(HttpClientRequest.acceptJson), target.token)).pipe(Effect.flatMap(decodeJsonBody(GitHubPullRequestWire, "getPullRequest")), Effect.map((wire) => PullRequestMetadata.make({
2917
- repository: target.repository,
2918
- number: wire.number,
2919
- title: wire.title.slice(0, 400),
2920
- body: (wire.body ?? "").slice(0, 2e4),
2921
- baseRef: wire.base.ref,
2922
- baseSha: wire.base.sha,
2923
- headRef: wire.head.ref,
2924
- headSha: wire.head.sha,
2925
- totalChangedFiles: wire.changed_files
2926
- })));
2927
- const fetchFiles = Effect.gen(function* () {
2928
- const perPage = 100;
2929
- const all = [];
2930
- for (let page = 1; page <= 300 / perPage; page += 1) {
2931
- const response = yield* executeOk("listChangedFiles", withCommonHeaders(HttpClientRequest.get(`${prefix}/files`).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setUrlParams({
2932
- per_page: String(perPage),
2933
- page: String(page)
2934
- })), target.token));
2935
- const wires = yield* decodeJsonBody(GitHubFilesPageWire, "listChangedFiles")(response);
2936
- all.push(...wires.map(toChangedFile));
2937
- if (wires.length < perPage) break;
2938
- }
2939
- return all;
2940
- });
2941
- const metadata = yield* Effect.cached(fetchMetadata.pipe(Effect.provideService(HttpClient.HttpClient, client)));
2942
- const rawFiles = yield* Effect.cached(fetchFiles.pipe(Effect.provideService(HttpClient.HttpClient, client)));
2943
- const readRepositoryFile = (path, ref) => Effect.gen(function* () {
2944
- const relative = yield* normalizeRepoRelativePath(path);
2945
- const encodedPath = relative.split("/").map(encodeURIComponent).join("/");
2946
- const buffer = yield* (yield* executeOk("readFile", withCommonHeaders(HttpClientRequest.get(`${target.apiUrl}/repos/${target.repository}/contents/${encodedPath}`).pipe(HttpClientRequest.accept("application/vnd.github.raw+json"), HttpClientRequest.setUrlParams({ ref })), target.token)).pipe(Effect.provideService(HttpClient.HttpClient, client))).arrayBuffer.pipe(Effect.mapError(failWith("readFile")));
2947
- if (buffer.byteLength > 2e5) return yield* ReviewInputViolation.make({
2948
- input: relative,
2949
- reason: `File is larger than the ${MAX_FILE_CHARS}-byte read bound.`
2950
- });
2951
- const text = yield* Effect.try({
2952
- try: () => new TextDecoder("utf-8", { fatal: true }).decode(buffer),
2953
- catch: () => ReviewInputViolation.make({
2954
- input: relative,
2955
- reason: "File is not valid UTF-8 text."
2956
- })
2957
- });
2958
- if (text.includes("\0")) return yield* ReviewInputViolation.make({
2959
- input: relative,
2960
- reason: "File contains binary NUL bytes."
2961
- });
2962
- if (text.length > 2e5) return yield* ReviewInputViolation.make({
2963
- input: relative,
2964
- reason: `File is larger than the ${MAX_FILE_CHARS}-character read bound.`
2965
- });
2966
- return text;
2967
- });
2968
- const changedFiles = yield* Effect.cached(Effect.gen(function* () {
2969
- const [files, pullRequest] = yield* Effect.all([rawFiles, metadata]);
2970
- return yield* Effect.forEach(files, (file) => {
2971
- if (file.patch !== void 0) return Effect.succeed(file);
2972
- const basePath = file.previousPath ?? file.path;
2973
- const base = file.status === "added" ? Effect.succeed(Option.none()) : readRepositoryFile(basePath, pullRequest.baseSha ?? pullRequest.baseRef).pipe(Effect.option);
2974
- const head = file.status === "removed" ? Effect.succeed(Option.none()) : readRepositoryFile(file.path, pullRequest.headSha).pipe(Effect.option);
2975
- return Effect.all({
2976
- base,
2977
- head
2978
- }).pipe(Effect.map(({ base, head }) => ChangedFile.make({
2979
- ...file,
2980
- ...Option.isSome(base) ? { reviewBaseContent: base.value } : {},
2981
- ...Option.isSome(head) ? { reviewHeadContent: head.value } : {}
2982
- })));
2983
- }, { concurrency: 4 });
2984
- }));
2985
- const readFile = (path) => Effect.gen(function* () {
2986
- const relative = yield* normalizeRepoRelativePath(path);
2987
- const file = (yield* changedFiles).find((candidate) => candidate.path === relative);
2988
- if (file === void 0) return yield* ReviewInputViolation.make({
2989
- input: relative,
2990
- reason: "Path is not part of this pull request's changeset."
2991
- });
2992
- if (file.reviewHeadContent !== void 0) return file.reviewHeadContent;
2993
- const head = yield* metadata;
2994
- return yield* readRepositoryFile(relative, head.headSha);
2995
- });
2996
- return PullRequestSource.of({
2997
- metadata,
2998
- changedFiles,
2999
- anchorFiles: changedFiles,
3000
- readFile
3001
- });
3002
- }));
3003
- /** GitHub-backed publisher: one POST to the pull-request reviews endpoint. */
3004
- const gitHubReviewPublisherLayer = Layer.effect(ReviewPublisher)(Effect.gen(function* () {
3005
- const target = yield* GitHubReviewTarget;
3006
- const client = yield* HttpClient.HttpClient;
3007
- return ReviewPublisher.of({ publish: (plan) => Effect.gen(function* () {
3008
- const payload = {
3009
- event: plan.event,
3010
- body: plan.body,
3011
- commit_id: plan.commitSha,
3012
- comments: plan.comments.map((comment) => ({
3013
- path: comment.path,
3014
- line: comment.line,
3015
- side: "RIGHT",
3016
- ...comment.startLine !== void 0 ? {
3017
- start_line: comment.startLine,
3018
- start_side: "RIGHT"
3019
- } : {},
3020
- body: comment.body
3021
- }))
3022
- };
3023
- const request = withCommonHeaders(HttpClientRequest.post(`${target.apiUrl}/repos/${target.repository}/pulls/${target.number}/reviews`).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bodyJsonUnsafe(payload)), target.token);
3024
- const wire = yield* HttpClient.execute(request).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap((response) => response.json.pipe(Effect.flatMap(Schema.decodeUnknownEffect(GitHubReviewWire)))), Effect.mapError((error) => GitHubApiFailure.make({
3025
- operation: "createReview",
3026
- reason: `${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048)
3027
- })), Effect.provideService(HttpClient.HttpClient, client));
3028
- return PublishedReview.make({
3029
- reviewId: wire.id,
3030
- url: wire.html_url,
3031
- event: plan.event,
3032
- inlineComments: plan.comments.length,
3033
- authorNodeId: wire.user?.node_id ?? null,
3034
- submittedAt: parseGitHubSubmittedAt(wire.submitted_at)
3035
- });
3036
- }) });
3037
- }));
3038
- const MAX_RETIREMENT_PAGES = 5;
3039
- const MINIMIZE_REVIEW_COMMENT_MUTATION = `mutation MinimizeReviewComment($subjectId: ID!) {
3040
- minimizeComment(input: { subjectId: $subjectId, classifier: OUTDATED }) {
3041
- minimizedComment { isMinimized }
3042
- }
3043
- }`;
3044
- /** GitHub-backed host operations for cosmetic retirement after publication. */
3045
- const gitHubReviewRetirementHostLayer = Layer.effect(ReviewRetirementHost)(Effect.gen(function* () {
3046
- const target = yield* GitHubReviewTarget;
3047
- const client = yield* HttpClient.HttpClient;
3048
- const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;
3049
- const asRetirementFailure = (operation) => (error) => ReviewRetirementFailure.make({
3050
- operation,
3051
- reason: `${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048)
3052
- });
3053
- const executeRetirement = (operation, request) => HttpClient.execute(request).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asRetirementFailure(operation)), Effect.provideService(HttpClient.HttpClient, client));
3054
- const decodeRetirement = (schema, operation) => {
3055
- const decode = Schema.decodeUnknownEffect(schema);
3056
- return (response) => response.json.pipe(Effect.mapError(asRetirementFailure(operation)), Effect.flatMap((body) => decode(body).pipe(Effect.mapError(asRetirementFailure(operation)))));
3057
- };
3058
- const listPaged = (input) => Effect.gen(function* () {
3059
- const values = [];
3060
- const perPage = 100;
3061
- for (let page = 1; page <= MAX_RETIREMENT_PAGES; page += 1) {
3062
- const response = yield* executeRetirement(input.operation, withCommonHeaders(HttpClientRequest.get(input.url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setUrlParams({
3063
- per_page: String(perPage),
3064
- page: String(page)
3065
- })), target.token));
3066
- const pageValues = yield* input.decode(response);
3067
- values.push(...pageValues);
3068
- if (pageValues.length < perPage) return values;
3069
- }
3070
- return yield* ReviewRetirementFailure.make({
3071
- operation: input.operation,
3072
- reason: `history exceeds the bounded ${MAX_RETIREMENT_PAGES * 100}-item lookup`
3073
- });
3074
- });
3075
- return ReviewRetirementHost.of({
3076
- listReviews: listPaged({
3077
- operation: "listReviewsForRetirement",
3078
- url: `${prefix}/reviews`,
3079
- decode: decodeRetirement(GitHubRetirableReviewsPageWire, "listReviewsForRetirement")
3080
- }).pipe(Effect.map((reviews) => reviews.map((review) => RetirableReview.make({
3081
- reviewId: review.id,
3082
- body: review.body ?? "",
3083
- commitSha: review.commit_id,
3084
- authorNodeId: review.user?.node_id ?? null,
3085
- submittedAt: parseGitHubSubmittedAt(review.submitted_at)
3086
- })))),
3087
- listComments: (reviewId) => listPaged({
3088
- operation: "listReviewCommentsForRetirement",
3089
- url: `${prefix}/reviews/${reviewId}/comments`,
3090
- decode: decodeRetirement(GitHubReviewCommentsPageWire, "listReviewCommentsForRetirement")
3091
- }).pipe(Effect.map((comments) => comments.map((comment) => {
3092
- const positiveLine = (value) => value !== void 0 && value !== null && value > 0 ? value : null;
3093
- const endLine = positiveLine(comment.line ?? comment.original_line);
3094
- const startLine = positiveLine(comment.start_line ?? comment.original_start_line) ?? endLine;
3095
- return RetirableReviewComment.make({
3096
- nodeId: comment.node_id,
3097
- path: comment.path,
3098
- startLine,
3099
- endLine,
3100
- body: comment.body
3101
- });
3102
- }))),
3103
- updateBody: (reviewId, body) => executeRetirement("updateReview", withCommonHeaders(HttpClientRequest.put(`${prefix}/reviews/${reviewId}`).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bodyJsonUnsafe({ body })), target.token)).pipe(Effect.asVoid),
3104
- minimizeComment: (nodeId) => Effect.gen(function* () {
3105
- const response = yield* executeRetirement("minimizeComment", withCommonHeaders(HttpClientRequest.post(target.graphqlUrl).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bodyJsonUnsafe({
3106
- query: MINIMIZE_REVIEW_COMMENT_MUTATION,
3107
- variables: { subjectId: nodeId }
3108
- })), target.token));
3109
- const wire = yield* decodeRetirement(GitHubMinimizeCommentWire, "minimizeComment")(response);
3110
- if ((wire.errors?.length ?? 0) > 0 || wire.data?.minimizeComment?.minimizedComment?.isMinimized !== true) return yield* ReviewRetirementFailure.make({
3111
- operation: "minimizeComment",
3112
- reason: wire.errors?.map((error) => error.message).join("; ").slice(0, 2048) ?? "GitHub did not confirm comment minimization"
3113
- });
3114
- })
3115
- });
3116
- }));
3117
- const MAX_ADJUDICATION_PAGES = 5;
3118
- const GitHubThreadCommentWire = Schema.Struct({
3119
- id: Schema.Int,
3120
- in_reply_to_id: Schema.optionalKey(Schema.NullOr(Schema.Int)),
3121
- path: Schema.String,
3122
- body: Schema.String,
3123
- author_association: Schema.optionalKey(Schema.NullOr(Schema.String)),
3124
- user: Schema.NullOr(Schema.Struct({ login: Schema.String })),
3125
- created_at: Schema.optionalKey(Schema.NullOr(Schema.String)),
3126
- line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
3127
- original_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
3128
- start_line: Schema.optionalKey(Schema.NullOr(Schema.Int)),
3129
- original_start_line: Schema.optionalKey(Schema.NullOr(Schema.Int))
3130
- });
3131
- const GitHubThreadCommentsPageWire = Schema.Array(GitHubThreadCommentWire);
3132
- const GitHubIssueCommentWire = Schema.Struct({
3133
- body: Schema.optionalKey(Schema.NullOr(Schema.String)),
3134
- author_association: Schema.optionalKey(Schema.NullOr(Schema.String)),
3135
- user: Schema.NullOr(Schema.Struct({ login: Schema.String })),
3136
- created_at: Schema.optionalKey(Schema.NullOr(Schema.String))
3137
- });
3138
- const GitHubIssueCommentsPageWire = Schema.Array(GitHubIssueCommentWire);
3139
- const toAdjudicationComment = (wire, sourceOrder) => {
3140
- const login = wire.user?.login;
3141
- if (login === void 0 || login.length === 0) return void 0;
3142
- return AdjudicationComment.make({
3143
- body: (wire.body ?? "").slice(0, 65536),
3144
- authorAssociation: (wire.author_association ?? "NONE").slice(0, 40),
3145
- authorLogin: login.slice(0, 100),
3146
- createdAt: parseGitHubSubmittedAt(wire.created_at ?? null),
3147
- sourceOrder
3148
- });
3149
- };
3150
- /**
3151
- * GitHub-backed host reads for maintainer adjudication, installed by
3152
- * `gitHubReviewLayers` in `github-env.ts` at the public composition root: this action's own
3153
- * inline finding threads (roots authored by the configured review author)
3154
- * with their replies, and the pull request's top-level conversation comments.
3155
- * Both listings are creation-ordered.
3156
- */
3157
- const gitHubReviewAdjudicationHostLayer = Layer.effect(ReviewAdjudicationHost)(Effect.gen(function* () {
3158
- const target = yield* GitHubReviewTarget;
3159
- const client = yield* HttpClient.HttpClient;
3160
- const reviewAuthorLogin = (target.reviewAuthorLogin ?? "github-actions[bot]").toLowerCase();
3161
- const asAdjudicationFailure = (operation) => (error) => ReviewAdjudicationFailure.make({
3162
- operation,
3163
- reason: `${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048)
3164
- });
3165
- const decodeAdjudication = (schema, operation) => {
3166
- const decode = Schema.decodeUnknownEffect(schema);
3167
- return (response) => response.json.pipe(Effect.mapError(asAdjudicationFailure(operation)), Effect.flatMap((body) => decode(body).pipe(Effect.mapError(asAdjudicationFailure(operation)))));
3168
- };
3169
- const listPaged = (input) => Effect.gen(function* () {
3170
- const values = [];
3171
- const perPage = 100;
3172
- for (let page = 1; page <= MAX_ADJUDICATION_PAGES; page += 1) {
3173
- const response = yield* client.execute(withCommonHeaders(HttpClientRequest.get(input.url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setUrlParams({
3174
- per_page: String(perPage),
3175
- page: String(page),
3176
- sort: "created",
3177
- direction: "asc"
3178
- })), target.token)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asAdjudicationFailure(input.operation)));
3179
- const pageValues = yield* input.decode(response);
3180
- values.push(...pageValues);
3181
- if (pageValues.length < perPage) return values;
3182
- }
3183
- return yield* ReviewAdjudicationFailure.make({
3184
- operation: input.operation,
3185
- reason: `history exceeds the bounded ${MAX_ADJUDICATION_PAGES * 100}-item lookup`
3186
- });
3187
- });
3188
- const listFindingThreads = Effect.gen(function* () {
3189
- const wires = yield* listPaged({
3190
- operation: "listReviewCommentsForAdjudication",
3191
- url: `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}/comments`,
3192
- decode: decodeAdjudication(GitHubThreadCommentsPageWire, "listReviewCommentsForAdjudication")
3193
- });
3194
- const positiveLine = (value) => value !== void 0 && value !== null && value > 0 ? value : null;
3195
- const threads = /* @__PURE__ */ new Map();
3196
- for (const wire of wires) {
3197
- if (wire.in_reply_to_id !== void 0 && wire.in_reply_to_id !== null) continue;
3198
- if (wire.user?.login.toLowerCase() !== reviewAuthorLogin) continue;
3199
- threads.set(wire.id, {
3200
- root: wire,
3201
- replies: []
3202
- });
3203
- }
3204
- for (const [sourceOrder, wire] of wires.entries()) {
3205
- if (wire.in_reply_to_id === void 0 || wire.in_reply_to_id === null) continue;
3206
- const thread = threads.get(wire.in_reply_to_id);
3207
- if (thread === void 0) continue;
3208
- const reply = toAdjudicationComment(wire, sourceOrder);
3209
- if (reply === void 0) continue;
3210
- if (parseThreadAdjudication(reply.body) === void 0) continue;
3211
- if (!AUTHORIZED_ADJUDICATION_ASSOCIATIONS.has(reply.authorAssociation)) {
3212
- yield* Effect.logDebug(`Ignored inline adjudication command from @${reply.authorLogin} (${reply.authorAssociation}).`);
3213
- continue;
3214
- }
3215
- if (thread.replies.length >= 100) return yield* ReviewAdjudicationFailure.make({
3216
- operation: "listReviewCommentsForAdjudication",
3217
- reason: `inline thread ${wire.in_reply_to_id} exceeds the bounded 100-command adjudication lookup`
3218
- });
3219
- thread.replies.push(reply);
3220
- }
3221
- return [...threads.values()].filter((thread) => thread.root.path.length > 0 && thread.root.path.length <= 500).map(({ root, replies }) => {
3222
- const endLine = positiveLine(root.line ?? root.original_line);
3223
- const startLine = positiveLine(root.start_line ?? root.original_start_line) ?? endLine;
3224
- return AdjudicableThread.make({
3225
- path: root.path,
3226
- startLine,
3227
- endLine,
3228
- rootBody: root.body.slice(0, 65536),
3229
- replies
3230
- });
3231
- });
3232
- });
3233
- const listIssueComments = Effect.gen(function* () {
3234
- return (yield* listPaged({
3235
- operation: "listIssueCommentsForAdjudication",
3236
- url: `${target.apiUrl}/repos/${target.repository}/issues/${target.number}/comments`,
3237
- decode: decodeAdjudication(GitHubIssueCommentsPageWire, "listIssueCommentsForAdjudication")
3238
- })).flatMap((wire, sourceOrder) => {
3239
- const comment = toAdjudicationComment(wire, sourceOrder);
3240
- return comment === void 0 ? [] : [comment];
3241
- });
3242
- });
3243
- return ReviewAdjudicationHost.of({
3244
- listFindingThreads,
3245
- listIssueComments
3246
- });
3247
- }));
3248
- /** Reading the pull request's previously posted reviews failed. */
3249
- var PriorReviewLookupFailure = class extends Schema.TaggedError()("PriorReviewLookupFailure", { reason: Schema.String }) {
3250
- get message() {
3251
- return `Prior-review lookup failed: ${this.reason}`;
3252
- }
3253
- };
3254
- /**
3255
- * Read-only view of this package's previously posted reviews on the target
3256
- * pull request — the deduplication state for unchanged-changeset skipping.
3257
- */
3258
- var PriorReviews = class extends Context.Service()("@effect-agent/pr-review/PriorReviews") {};
3259
- const GitHubPriorReviewWire = Schema.Struct({
3260
- body: Schema.NullOr(Schema.String),
3261
- commit_id: Schema.String,
3262
- user: Schema.optionalKey(Schema.NullOr(Schema.Struct({
3263
- login: Schema.String,
3264
- type: Schema.String
3265
- })))
3266
- });
3267
- const GitHubPriorReviewsPageWire = Schema.Array(GitHubPriorReviewWire);
3268
- const GitHubCompareWire = Schema.Struct({
3269
- status: Schema.Literals([
3270
- "ahead",
3271
- "behind",
3272
- "diverged",
3273
- "identical"
3274
- ]),
3275
- base_commit: Schema.Struct({ sha: Schema.String }),
3276
- merge_base_commit: Schema.Struct({ sha: Schema.String }),
3277
- files: GitHubFilesPageWire
3278
- });
3279
- const GitHubGitCommitWire = Schema.Struct({
3280
- sha: GitCommitSha,
3281
- tree: Schema.Struct({ sha: GitCommitSha })
3282
- });
3283
- const GitHubTreeEntryFields = {
3284
- path: Schema.String.check(Schema.isMaxLength(4096)),
3285
- sha: GitCommitSha
3286
- };
3287
- const GitHubTreeEntryWire = Schema.Union([
3288
- Schema.Struct({
3289
- ...GitHubTreeEntryFields,
3290
- mode: Schema.Literals([
3291
- "100644",
3292
- "100755",
3293
- "120000"
3294
- ]),
3295
- type: Schema.Literal("blob")
3296
- }),
3297
- Schema.Struct({
3298
- ...GitHubTreeEntryFields,
3299
- mode: Schema.Literal("040000"),
3300
- type: Schema.Literal("tree")
3301
- }),
3302
- Schema.Struct({
3303
- ...GitHubTreeEntryFields,
3304
- mode: Schema.Literal("160000"),
3305
- type: Schema.Literal("commit")
3306
- })
3307
- ]);
3308
- const GitHubTreeWire = Schema.Struct({
3309
- sha: GitCommitSha,
3310
- tree: Schema.Array(GitHubTreeEntryWire).check(Schema.isMaxLength(1e5)),
3311
- truncated: Schema.Boolean
3312
- });
3313
- const TreeComparisonPaths = Schema.Array(ChangedPath).check(Schema.isMaxLength(750));
3314
- /** Reviews are paged chronologically; scanning stays bounded. */
3315
- const MAX_PRIOR_REVIEW_PAGES = 5;
3316
- /** GitHub-backed PriorReviews over the pull-request reviews endpoint. */
3317
- const gitHubPriorReviewsLayer = Layer.effect(PriorReviews)(Effect.gen(function* () {
3318
- const target = yield* GitHubReviewTarget;
3319
- const client = yield* HttpClient.HttpClient;
3320
- const prefix = `${target.apiUrl}/repos/${target.repository}/pulls/${target.number}`;
3321
- const reviewAuthorLogin = target.reviewAuthorLogin ?? "github-actions[bot]";
3322
- const decodePage = Schema.decodeUnknownEffect(GitHubPriorReviewsPageWire);
3323
- const asLookupFailure = (error) => PriorReviewLookupFailure.make({ reason: `${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048) });
3324
- const asTreeLookupFailure = (operation) => (error) => PriorReviewLookupFailure.make({ reason: `${operation}: ${error._tag}: ${error.message ?? "request failed"}`.slice(0, 2048) });
3325
- const decodeLookupJson = (schema, operation) => {
3326
- const decode = Schema.decodeUnknownEffect(schema);
3327
- return (response) => response.json.pipe(Effect.mapError(asTreeLookupFailure(operation)), Effect.flatMap((body) => decode(body).pipe(Effect.mapError(asTreeLookupFailure(operation)))));
3328
- };
3329
- const readMarkers = (authenticator) => Effect.gen(function* () {
3330
- const perPage = 100;
3331
- let latest = Option.none();
3332
- let latestState = Option.none();
3333
- for (let page = 1; page <= MAX_PRIOR_REVIEW_PAGES; page += 1) {
3334
- const wires = yield* (yield* HttpClient.execute(withCommonHeaders(HttpClientRequest.get(`${prefix}/reviews`).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setUrlParams({
3335
- per_page: String(perPage),
3336
- page: String(page)
3337
- })), target.token)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asLookupFailure))).json.pipe(Effect.mapError(asLookupFailure), Effect.flatMap((body) => decodePage(body).pipe(Effect.mapError(asLookupFailure))));
3338
- for (const wire of wires) {
3339
- if (wire.user?.login.toLowerCase() !== reviewAuthorLogin.toLowerCase() || wire.user.type !== "Bot") continue;
3340
- const fingerprint = extractFingerprint(wire.body ?? "");
3341
- if (fingerprint !== void 0) latest = Option.some(fingerprint);
3342
- if (Option.isSome(authenticator)) {
3343
- const state = yield* authenticator.value.extract(wire.body ?? "").pipe(Effect.mapError((error) => PriorReviewLookupFailure.make({ reason: `${error._tag}: ${error.reason}`.slice(0, 2048) })));
3344
- if (Option.isSome(state) && state.value.reviewedHeadSha === wire.commit_id) latestState = state;
3345
- }
3346
- }
3347
- if (wires.length < perPage) break;
3348
- if (page === MAX_PRIOR_REVIEW_PAGES) return yield* PriorReviewLookupFailure.make({ reason: `review history exceeds the bounded ${MAX_PRIOR_REVIEW_PAGES * perPage}-review lookup` });
3349
- }
3350
- return {
3351
- latestFingerprint: latest,
3352
- latestState
3353
- };
3354
- }).pipe(Effect.provideService(HttpClient.HttpClient, client));
3355
- const compareCommits = (baseSha, headSha) => Effect.gen(function* () {
3356
- const wire = yield* (yield* HttpClient.execute(withCommonHeaders(HttpClientRequest.get(`${target.apiUrl}/repos/${target.repository}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}`).pipe(HttpClientRequest.acceptJson), target.token)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asLookupFailure))).json.pipe(Effect.mapError(asLookupFailure), Effect.flatMap((body) => Schema.decodeUnknownEffect(GitHubCompareWire)(body).pipe(Effect.mapError(asLookupFailure))));
3357
- const files = wire.files.map(toChangedFile);
3358
- return ReviewHeadComparison.make({
3359
- status: wire.status,
3360
- baseSha: wire.base_commit.sha,
3361
- headSha,
3362
- mergeBaseSha: wire.merge_base_commit.sha,
3363
- files,
3364
- truncated: files.length >= 300
3365
- });
3366
- }).pipe(Effect.provideService(HttpClient.HttpClient, client));
3367
- const readTreeSnapshot = Effect.fn("PriorReviews.readTreeSnapshot")(function* (commitSha) {
3368
- const commitResponse = yield* client.execute(withCommonHeaders(HttpClientRequest.get(`${target.apiUrl}/repos/${target.repository}/git/commits/${encodeURIComponent(commitSha)}`).pipe(HttpClientRequest.acceptJson), target.token)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asTreeLookupFailure("get Git commit")));
3369
- const commit = yield* decodeLookupJson(GitHubGitCommitWire, "decode Git commit")(commitResponse);
3370
- if (commit.sha !== commitSha) return yield* PriorReviewLookupFailure.make({ reason: `GitHub returned commit ${commit.sha} for requested snapshot ${commitSha}` });
3371
- const treeResponse = yield* client.execute(withCommonHeaders(HttpClientRequest.get(`${target.apiUrl}/repos/${target.repository}/git/trees/${encodeURIComponent(commit.tree.sha)}`).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setUrlParams({ recursive: "1" })), target.token)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError(asTreeLookupFailure("get recursive Git tree")));
3372
- const tree = yield* decodeLookupJson(GitHubTreeWire, "decode recursive Git tree")(treeResponse);
3373
- if (tree.sha !== commit.tree.sha) return yield* PriorReviewLookupFailure.make({ reason: `GitHub returned tree ${tree.sha} for requested tree ${commit.tree.sha}` });
3374
- const entries = /* @__PURE__ */ new Map();
3375
- for (const entry of tree.tree) {
3376
- if (entries.has(entry.path)) return yield* PriorReviewLookupFailure.make({ reason: `GitHub returned duplicate path '${entry.path}' in tree ${tree.sha}` });
3377
- entries.set(entry.path, entry);
3378
- }
3379
- return {
3380
- entries,
3381
- truncated: tree.truncated
3382
- };
3383
- });
3384
- const compareTrees = Effect.fn("PriorReviews.compareTrees")(function* (baseSha, headSha, paths) {
3385
- const decodeSha = Schema.decodeUnknownEffect(GitCommitSha);
3386
- const [validatedBaseSha, validatedHeadSha, validatedPaths] = yield* Effect.all([
3387
- decodeSha(baseSha),
3388
- decodeSha(headSha),
3389
- Schema.decodeUnknownEffect(TreeComparisonPaths)(paths)
3390
- ]).pipe(Effect.mapError(asTreeLookupFailure("validate tree comparison request")));
3391
- const uniquePaths = [...new Set(validatedPaths)].sort();
3392
- const { base, head } = yield* Effect.all({
3393
- base: readTreeSnapshot(validatedBaseSha),
3394
- head: readTreeSnapshot(validatedHeadSha)
3395
- }, { concurrency: 2 });
3396
- if (base.truncated || head.truncated) return ReviewTreeComparison.make({
3397
- baseSha: validatedBaseSha,
3398
- headSha: validatedHeadSha,
3399
- changedPaths: [],
3400
- truncated: true
3401
- });
3402
- const changedPaths = uniquePaths.filter((path) => {
3403
- const before = base.entries.get(path);
3404
- const after = head.entries.get(path);
3405
- if (before === void 0 || after === void 0) return before !== after;
3406
- return before.sha !== after.sha || before.mode !== after.mode || before.type !== after.type;
3407
- });
3408
- return ReviewTreeComparison.make({
3409
- baseSha: validatedBaseSha,
3410
- headSha: validatedHeadSha,
3411
- changedPaths,
3412
- truncated: false
3413
- });
3414
- });
3415
- return PriorReviews.of({
3416
- latestFingerprint: readMarkers(Option.none()).pipe(Effect.map((markers) => markers.latestFingerprint)),
3417
- latestState: Effect.gen(function* () {
3418
- const authenticator = yield* ReviewStateAuthenticator;
3419
- return yield* readMarkers(Option.some(authenticator)).pipe(Effect.map((markers) => markers.latestState));
3420
- }),
3421
- compareHeads: compareCommits,
3422
- compareTrees
3423
- });
3424
- }));
3425
- /**
3426
- * Whether the current fingerprint matches the most recent posted review.
3427
- * Fails OPEN: a lookup fault means "not unchanged" — the review proceeds,
3428
- * which is the safe direction for a deduplication optimization.
3429
- */
3430
- const fingerprintUnchanged = (current) => Effect.gen(function* () {
3431
- const latest = yield* (yield* PriorReviews).latestFingerprint.pipe(Effect.orElseSucceed(() => Option.none()));
3432
- return Option.isSome(latest) && latest.value === current;
3433
- });
3434
- //#endregion
3435
- export { ReviewDiscoveryPass as $, ReadFileDiff as $n, MAX_STORED_ADJUDICATIONS as $t, MAX_CHILD_FINDINGS as A, toStoredFinding as An, hasReviewableContent as Ar, buildPriorReviewContext as At, assessmentSettlesSuggestionExactly as B, FileSliceQuery as Bn, threadFindingTarget as Bt, FileReviewBrief as C, fromStoredFinding as Cn, normalizeRepoRelativePath as Cr, anchorViolation as Ct, FileReviewer as D, selectReviewRange as Dn, MAX_REVIEW_CONTENT_CHARS as Dr, MAX_THREAD_ADJUDICATION_COMMANDS as Dt, FileReviewToolkit as E, isLineageAncestor as En, ChangedPath as Er, AdjudicationComment as Et, ReviewCandidate as F, ChangedFilesView as Fn, noReviewAdjudicationHostLayer as Ft, makeFileReviewerInstructions as G, MAX_CONCERNS as Gn, ReviewRetirementHost as Gt, defaultFileReviewerPolicy as H, FindingSeverity as Hn, RetirableReview as Ht, ReviewCandidateId as I, CodeReview as In, parseIssueAdjudication as It, MAX_MERGED_FINDINGS as J, MAX_WALKTHROUGH_ENTRIES as Jn, hasReviewMetadataMarker as Jt, reviewCandidateSubjectKey as K, MAX_FINDINGS as Kn, ReviewRetirementReport as Kt, ReviewPassMisbehaved as L, FileDiffQuery as Ln, parseThreadAdjudication as Lt, MAX_REVIEW_CHILDREN as M, validateReviewState as Mn, parsePatch as Mr, deriveAdjudications as Mt, MAX_UNIT_CANDIDATES as N, webCryptoReviewStateAuthenticatorLayer as Nn, renderReviewContent as Nr, mergeAdjudications as Nt, FindingCandidate as O, selectedPullRequestSourceLayer as On, annotatePatch as Or, ReviewAdjudicationFailure as Ot, REVIEW_UNIT_CONCURRENCY as P, ChangedFileSummary as Pn, noReviewAdjudicationHost as Pt, MAX_UNIT_FILES as Q, ReadFile as Qn, MAX_REVIEW_STATE_MARKER_CHARS as Qt, ReviewWorkPerspective as R, FileDiffView as Rn, renderAdjudicationContextLine as Rt, DiscoveredConcern as S, fromStoredConcern as Sn, ReviewInputViolation as Sr, splitCarriedScope as St, FileReviewReport as T, fullReviewSelection as Tn, ChangedFileStatus as Tr, AdjudicableThread as Tt, fileReviewerInstructions as U, ListChangedFiles as Un, RetirableReviewComment as Ut, confirmedFindingForPublication as V, FindingCategory as Vn, INLINE_FINDING_TITLE_PATTERN as Vt, makeFileReviewerDefinition as W, ListChangedFilesQuery as Wn, ReviewRetirementFailure as Wt, MAX_REVIEW_UNITS as X, PullRequestReviewer as Xn, AdjudicationDisposition as Xt, MAX_REPORTED_UNASSIGNED_EVIDENCE_SHARDS as Y, MAX_WALKTHROUGH_SUMMARY_CHARS as Yn, retireStaleReviews as Yt, MAX_UNIT_EVIDENCE_SHARDS as Z, REVIEW_TOOL_RESULT_MAX_BYTES as Zn, GitCommitSha as Zt, computeProfileFingerprint as _, UnreviewedStage as _n, MAX_CHANGED_FILES as _r, ReviewInputCoverage as _t, PriorReviews as a, ReviewMode as an, ReviewVerdict as ar, ReviewUnit as at, CandidateAssessment as b, concernIdentity as bn, PullRequestSource as br, fanOutInputCoverage as bt, fingerprintUnchanged as c, ReviewStateAuthenticationFailure as cn, defaultReviewPolicy as cr, UNIT_EVIDENCE_CHAR_BUDGET as ct, gitHubReviewAdjudicationHostLayer as d, ReviewStateMarkerTooLarge as dn, listChangedFilesHandler as dr, planReviewUnits as dt, MAX_STORED_UNREVIEWED_PASSES as en, ReviewConcern as er, ReviewDiscoveryPerspective as et, gitHubReviewPublisherLayer as f, ReviewTreeComparison as fn, makeReviewInstructions as fr, rankAndDedupeConcerns as ft, computeChangesetFingerprint as g, StoredUnreviewedPass as gn, reviewInstructions as gr, ReviewAssurance as gt, FINGERPRINT_MARKER_LENGTH as h, StoredReviewFinding as hn, resolveGuidance as hr, FailedReviewPass as ht, PriorReviewLookupFailure as i, ReviewHeadComparison as in, ReviewToolkitLayer as ir, ReviewRiskCategory as it, MAX_FILE_REVIEW_TOOL_CALLS as j, unavailableReviewStateAuthenticatorLayer as jn, isReviewableFile as jr, collectReviewAdjudications as jt, MAX_CHILD_CONCERNS as k, toStoredConcern as kn, commentableLines as kr, ReviewAdjudicationHost as kt, gitHubPriorReviewsLayer as l, ReviewStateAuthenticator as ln, fileDiffView as lr, classifyReviewRisks as lt, parseGitHubSubmittedAt as m, StoredReviewConcern as mn, readFileHandler as mr, reviewConcernKey as mt, GitHubApiFailure as n, MAX_TREE_COMPARISON_PATHS as nn, ReviewMission as nr, ReviewEvidenceShardId as nt, PublishedReview as o, ReviewScopeMode as on, WalkthroughEntry as or, ReviewUnitId as ot, gitHubReviewRetirementHostLayer as p, StoredAdjudication as pn, readFileDiffHandler as pr, rankAndDedupeFindings as pt, runFanOutReview as q, MAX_PATCH_CHARS as qn, decideReviewRetirement as qt, GitHubReviewTarget as r, ReviewExecutionContext as rn, ReviewToolkit as rr, ReviewPassId as rt, ReviewPublisher as s, ReviewState as sn, clampMaxFindings as sr, ReviewUnitPlan as st, DEFAULT_GITHUB_REVIEW_AUTHOR_LOGIN as t, MAX_STORED_UNREVIEWED_PATHS as tn, ReviewFinding as tr, ReviewEvidenceShard as tt, gitHubPullRequestSourceLayer as u, ReviewStateMarker as un, fileReviewEvidenceChunks as ur, findingAnchorInUnitEvidence as ut, extractFingerprint as v, adjudicationIdentity as vn, MAX_FILE_CHARS as vr, assessFlatReview as vt, FileReviewEvidence as w, fullReviewExecutionContextLayer as wn, ChangedFile as wr, AUTHORIZED_ADJUDICATION_ASSOCIATIONS as wt, ConcernCandidate as x, findingIdentity as xn, PullRequestSourceFailure as xr, flatAssurance as xt, renderFingerprintMarker as y, buildProfileMission as yn, PullRequestMetadata as yr, boundedListReason as yt, ReviewWorkPhase as z, FileSlice as zn, renderPriorFindingContextLine as zt };
3436
-
3437
- //# sourceMappingURL=github-CCuLgyqb.mjs.map