clud-bug 0.7.0-rc.2 → 0.7.0-rc.21

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 (147) hide show
  1. package/README.md +20 -0
  2. package/data/canonical-v1.json +37 -0
  3. package/dist/cli/configure-github.d.ts +58 -0
  4. package/dist/cli/configure-github.d.ts.map +1 -0
  5. package/dist/cli/configure-github.js +242 -0
  6. package/dist/cli/configure-github.js.map +1 -0
  7. package/dist/cli/hooks.d.ts +51 -0
  8. package/dist/cli/hooks.d.ts.map +1 -0
  9. package/dist/cli/hooks.js +138 -0
  10. package/dist/cli/hooks.js.map +1 -0
  11. package/dist/cli/index.d.ts +1 -0
  12. package/dist/cli/index.d.ts.map +1 -1
  13. package/dist/cli/index.js +1 -0
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cli/main.d.ts.map +1 -1
  16. package/dist/cli/main.js +949 -35
  17. package/dist/cli/main.js.map +1 -1
  18. package/dist/cli/post-check-run.d.ts +16 -0
  19. package/dist/cli/post-check-run.d.ts.map +1 -0
  20. package/dist/cli/post-check-run.js +93 -0
  21. package/dist/cli/post-check-run.js.map +1 -0
  22. package/dist/cli/review-prompt.d.ts +43 -0
  23. package/dist/cli/review-prompt.d.ts.map +1 -0
  24. package/dist/cli/review-prompt.js +287 -0
  25. package/dist/cli/review-prompt.js.map +1 -0
  26. package/dist/cli/skills.d.ts +7 -0
  27. package/dist/cli/skills.d.ts.map +1 -1
  28. package/dist/cli/skills.js +42 -2
  29. package/dist/cli/skills.js.map +1 -1
  30. package/dist/cli/update-notifier.d.ts +17 -0
  31. package/dist/cli/update-notifier.d.ts.map +1 -0
  32. package/dist/cli/update-notifier.js +88 -0
  33. package/dist/cli/update-notifier.js.map +1 -0
  34. package/dist/cli/update.d.ts.map +1 -1
  35. package/dist/cli/update.js +60 -11
  36. package/dist/cli/update.js.map +1 -1
  37. package/dist/core/auto-resolve.d.ts +235 -0
  38. package/dist/core/auto-resolve.d.ts.map +1 -0
  39. package/dist/core/auto-resolve.js +293 -0
  40. package/dist/core/auto-resolve.js.map +1 -0
  41. package/dist/core/budget-plan.d.ts +125 -0
  42. package/dist/core/budget-plan.d.ts.map +1 -0
  43. package/dist/core/budget-plan.js +211 -0
  44. package/dist/core/budget-plan.js.map +1 -0
  45. package/dist/core/check-verdict.d.ts +31 -0
  46. package/dist/core/check-verdict.d.ts.map +1 -0
  47. package/dist/core/check-verdict.js +66 -0
  48. package/dist/core/check-verdict.js.map +1 -0
  49. package/dist/core/configure-github.d.ts +179 -0
  50. package/dist/core/configure-github.d.ts.map +1 -0
  51. package/dist/core/configure-github.js +289 -0
  52. package/dist/core/configure-github.js.map +1 -0
  53. package/dist/core/design.d.ts +37 -0
  54. package/dist/core/design.d.ts.map +1 -0
  55. package/dist/core/design.js +47 -0
  56. package/dist/core/design.js.map +1 -0
  57. package/dist/core/diff-findings.d.ts +96 -0
  58. package/dist/core/diff-findings.d.ts.map +1 -0
  59. package/dist/core/diff-findings.js +261 -0
  60. package/dist/core/diff-findings.js.map +1 -0
  61. package/dist/core/formal-review.d.ts +79 -0
  62. package/dist/core/formal-review.d.ts.map +1 -0
  63. package/dist/core/formal-review.js +71 -0
  64. package/dist/core/formal-review.js.map +1 -0
  65. package/dist/core/index.d.ts +15 -2
  66. package/dist/core/index.d.ts.map +1 -1
  67. package/dist/core/index.js +53 -1
  68. package/dist/core/index.js.map +1 -1
  69. package/dist/core/inline-threads.d.ts +160 -0
  70. package/dist/core/inline-threads.d.ts.map +1 -0
  71. package/dist/core/inline-threads.js +369 -0
  72. package/dist/core/inline-threads.js.map +1 -0
  73. package/dist/core/multi-pass-aggregate.d.ts +161 -0
  74. package/dist/core/multi-pass-aggregate.d.ts.map +1 -0
  75. package/dist/core/multi-pass-aggregate.js +457 -0
  76. package/dist/core/multi-pass-aggregate.js.map +1 -0
  77. package/dist/core/plan-review.d.ts +57 -0
  78. package/dist/core/plan-review.d.ts.map +1 -0
  79. package/dist/core/plan-review.js +77 -0
  80. package/dist/core/plan-review.js.map +1 -0
  81. package/dist/core/prompt-builder.d.ts +18 -0
  82. package/dist/core/prompt-builder.d.ts.map +1 -1
  83. package/dist/core/prompt-builder.js +24 -2
  84. package/dist/core/prompt-builder.js.map +1 -1
  85. package/dist/core/render.d.ts.map +1 -1
  86. package/dist/core/render.js +1 -19
  87. package/dist/core/render.js.map +1 -1
  88. package/dist/core/resolve-verifier.d.ts +53 -0
  89. package/dist/core/resolve-verifier.d.ts.map +1 -0
  90. package/dist/core/resolve-verifier.js +204 -0
  91. package/dist/core/resolve-verifier.js.map +1 -0
  92. package/dist/core/review-context.d.ts +39 -0
  93. package/dist/core/review-context.d.ts.map +1 -0
  94. package/dist/core/review-context.js +99 -0
  95. package/dist/core/review-context.js.map +1 -0
  96. package/dist/core/review-plan.d.ts +219 -0
  97. package/dist/core/review-plan.d.ts.map +1 -0
  98. package/dist/core/review-plan.js +274 -0
  99. package/dist/core/review-plan.js.map +1 -0
  100. package/dist/core/review-writeback.d.ts +74 -0
  101. package/dist/core/review-writeback.d.ts.map +1 -1
  102. package/dist/core/review-writeback.js +71 -4
  103. package/dist/core/review-writeback.js.map +1 -1
  104. package/dist/core/skills.d.ts +25 -0
  105. package/dist/core/skills.d.ts.map +1 -1
  106. package/dist/core/skills.js +100 -4
  107. package/dist/core/skills.js.map +1 -1
  108. package/dist/core/version.d.ts +2 -0
  109. package/dist/core/version.d.ts.map +1 -0
  110. package/dist/core/version.js +4 -0
  111. package/dist/core/version.js.map +1 -0
  112. package/package.json +11 -5
  113. package/src/cli/configure-github.ts +329 -0
  114. package/src/cli/hooks.ts +155 -0
  115. package/src/cli/index.ts +6 -0
  116. package/src/cli/main.ts +1031 -37
  117. package/src/cli/post-check-run.ts +115 -0
  118. package/src/cli/review-prompt.ts +355 -0
  119. package/src/cli/skills.ts +42 -2
  120. package/src/cli/update-notifier.ts +100 -0
  121. package/src/cli/update.ts +60 -11
  122. package/src/core/auto-resolve.ts +488 -0
  123. package/src/core/budget-plan.ts +324 -0
  124. package/src/core/check-verdict.ts +93 -0
  125. package/src/core/configure-github.ts +497 -0
  126. package/src/core/design.ts +73 -0
  127. package/src/core/diff-findings.ts +323 -0
  128. package/src/core/formal-review.ts +168 -0
  129. package/src/core/index.ts +188 -0
  130. package/src/core/inline-threads.ts +471 -0
  131. package/src/core/multi-pass-aggregate.ts +591 -0
  132. package/src/core/plan-review.ts +136 -0
  133. package/src/core/prompt-builder.ts +44 -2
  134. package/src/core/render.ts +10 -16
  135. package/src/core/resolve-verifier.ts +254 -0
  136. package/src/core/review-context.ts +106 -0
  137. package/src/core/review-plan.ts +485 -0
  138. package/src/core/review-writeback.ts +161 -4
  139. package/src/core/skills.ts +128 -5
  140. package/src/core/version.ts +3 -0
  141. package/templates/clud-bug-review.md.tmpl +115 -0
  142. package/templates/skills/design/design-system-consistency.md +41 -0
  143. package/templates/skills/design/frontend-a11y.md +41 -0
  144. package/templates/skills/design/visual-polish.md +41 -0
  145. package/templates/workflow-py.yml.tmpl +92 -2
  146. package/templates/workflow-ts.yml.tmpl +92 -2
  147. package/templates/workflow.yml.tmpl +173 -2
@@ -0,0 +1,591 @@
1
+ import type { ReviewRole } from './review-plan.js';
2
+ import {
3
+ flattenFindings,
4
+ type Finding,
5
+ type Review,
6
+ type Severity,
7
+ } from './review-schema-zod.js';
8
+ import type {
9
+ Consensus,
10
+ MultiPassReview,
11
+ PassAttribution,
12
+ PassSource,
13
+ ReviewPassMode,
14
+ UnifiedFinding,
15
+ } from './review-writeback.js';
16
+
17
+ /**
18
+ * Multi-pass aggregator.
19
+ *
20
+ * Takes N passes' review outputs + the active mode + the role definitions
21
+ * and produces a single unified `MultiPassReview` payload the renderer can
22
+ * format with per-pass attribution inline.
23
+ *
24
+ * The three modes are NOT interchangeable in their output shape — see the
25
+ * per-mode comments below.
26
+ *
27
+ * Design discipline:
28
+ * - Pure function. No I/O, no AI calls. Input = N validated reviews +
29
+ * metadata; output = aggregated findings list.
30
+ * - Order-stable. The renderer needs a deterministic finding order so the
31
+ * comment is stable across re-reviews (matters for thread continuity in
32
+ * D.2.6). We preserve Pass 1's order, then append later-pass findings.
33
+ * - Match semantics live here. Two findings are "the same" if their
34
+ * (file, line, skill) tuple matches. Summaries diverge stylistically
35
+ * between passes; key matching on summary is too brittle.
36
+ * - Resolution rules:
37
+ * cross-check → Pass 2 explicitly classified Pass-1 findings as
38
+ * agreed/disagreed via the cross-check schema; we use
39
+ * its verdict verbatim.
40
+ * consensus → Pass 2 ran independent. Same-tuple findings across
41
+ * passes are marked `agreed`; tuple-unique findings are
42
+ * attributed to their pass with provenance.
43
+ * independent → No merging. We emit a flat list with one entry per
44
+ * (pass, finding) — the renderer formats them as a
45
+ * side-by-side review block.
46
+ *
47
+ * The orchestrator owns the AI call orchestration upstream. This module just
48
+ * deals with shapes — call it once per skill (or once per shared bundle).
49
+ *
50
+ * Ported from clud-bug-app/lib/multi-pass-aggregator.ts. The result types
51
+ * (`MultiPassReview`, `UnifiedFinding`, `PassAttribution`, `PassSource`,
52
+ * `ReviewPassMode`) live in `./review-writeback.ts` and are imported here so
53
+ * core has a single declaration for each. The aggregator-internal contracts
54
+ * (`PassSource` is shared; `Consensus`, `CrossCheckVerdict`,
55
+ * `CrossCheckPassResult`, `AggregateInput`) are defined below.
56
+ */
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // Public types
60
+ // ---------------------------------------------------------------------------
61
+
62
+ // `Consensus` (the SPEC §6.10.1 marker) is defined in `./review-writeback.ts`
63
+ // alongside `UnifiedFinding` and imported above — core keeps a single
64
+ // declaration so it rides on `MultiPassReview.findings[].consensus`.
65
+
66
+ /**
67
+ * Derive the SPEC §6.10.1 consensus marker from a finding's per-pass
68
+ * attribution list. Mapping rules:
69
+ *
70
+ * - any source === 'agreed' → '2-of-2' (consensus reached)
71
+ * - any source === 'disagreed' → 'arbitrated' (cross-check produced
72
+ * active dissent; the finding still made it through, which is the
73
+ * arbitration outcome we model today — see Consensus type doc)
74
+ * - otherwise (just 'first' / 'independent') → '1-of-N' (single-pass)
75
+ *
76
+ * Priority order: agreed > disagreed > default. If a finding has BOTH
77
+ * an `agreed` and a `disagreed` attribution (e.g., 3-pass setup with
78
+ * Pass 2 agreed + Pass 3 disagreed), `agreed` wins — at least one pass
79
+ * cross-validated the finding, so the gate has consensus.
80
+ */
81
+ export function deriveConsensus(attributions: PassAttribution[]): Consensus {
82
+ let sawDisagreed = false;
83
+ for (const a of attributions) {
84
+ if (a.source === 'agreed') return '2-of-2';
85
+ if (a.source === 'disagreed') sawDisagreed = true;
86
+ }
87
+ return sawDisagreed ? 'arbitrated' : '1-of-N';
88
+ }
89
+
90
+ // (Removed `UnifiedFindingWithConsensus`: core's `UnifiedFinding` now carries
91
+ // the optional `consensus` field directly — see `./review-writeback.ts` — so
92
+ // `finalize()` returns `UnifiedFinding[]` and `aggregatePasses(...).findings[i]
93
+ // .consensus` is on the PUBLIC return type, not erased at the boundary.)
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Cross-check schema (what Pass 2 returns under mode: cross-check)
97
+ // ---------------------------------------------------------------------------
98
+
99
+ /**
100
+ * The cross-check pass returns:
101
+ * - One verdict per Pass-1 finding (agreed / disagreed + rationale).
102
+ * - A list of independently-discovered findings (same shape as Finding).
103
+ *
104
+ * We define the response shape here (not in review-schema-zod.ts) because
105
+ * it's an aggregator-internal contract. The orchestrator uses
106
+ * `crossCheckSchema` (from review-schema-zod) for the AI call output type.
107
+ */
108
+ export interface CrossCheckVerdict {
109
+ /** 0-indexed reference to the Pass-1 finding being judged. */
110
+ pass1Index: number;
111
+ /** Pass 2's verdict. */
112
+ verdict: 'agreed' | 'disagreed';
113
+ /** One-line rationale shown inline. Optional but recommended. */
114
+ rationale?: string;
115
+ }
116
+
117
+ export interface CrossCheckPassResult {
118
+ /** Per-Pass-1-finding judgements. */
119
+ verdicts: CrossCheckVerdict[];
120
+ /** Newly-discovered findings, independent of Pass 1's list. */
121
+ independentFindings: Finding[];
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // Aggregation entry point
126
+ // ---------------------------------------------------------------------------
127
+
128
+ export interface AggregateInput {
129
+ /** Mode driving the merge. */
130
+ mode: ReviewPassMode;
131
+ /** Pass 1's review. Required — at minimum we need one pass. */
132
+ firstPass: Review;
133
+ /**
134
+ * Subsequent passes. Shape depends on mode:
135
+ * - cross-check: each entry has `crossCheck` populated; `review` may be
136
+ * omitted (the cross-check pass doesn't produce a full review object).
137
+ * - consensus / independent: each entry has `review` populated; the
138
+ * `crossCheck` field is ignored.
139
+ */
140
+ subsequentPasses: Array<{
141
+ /** 1-indexed pass number, starting at 2. */
142
+ passNumber: number;
143
+ /** Role label + model used. */
144
+ role: ReviewRole;
145
+ /** Cross-check response (only valid when mode === 'cross-check'). */
146
+ crossCheck?: CrossCheckPassResult;
147
+ /** Full review (for consensus / independent modes). */
148
+ review?: Review;
149
+ }>;
150
+ /** Role assigned to Pass 1 — needed for attribution headers. */
151
+ firstPassRole: ReviewRole;
152
+ }
153
+
154
+ /**
155
+ * Merges the per-pass results into a single MultiPassReview.
156
+ */
157
+ export function aggregatePasses(input: AggregateInput): MultiPassReview {
158
+ switch (input.mode) {
159
+ case 'cross-check':
160
+ return aggregateCrossCheck(input);
161
+ case 'consensus':
162
+ return aggregateConsensus(input);
163
+ case 'independent':
164
+ return aggregateIndependent(input);
165
+ }
166
+ }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // 6c — conditional Mantis-arbiter escalation
170
+ // ---------------------------------------------------------------------------
171
+
172
+ export interface EscalationInput {
173
+ /** Active aggregation mode — escalation only applies to cross-check. */
174
+ mode: ReviewPassMode;
175
+ /** Resolved pass count — escalation only when the plan ran exactly 2. */
176
+ passCount: number;
177
+ /** Pass 1's review; its findings are indexed by the cross-check verdicts. */
178
+ firstPass: Review;
179
+ /** Subsequent passes — the cross-check verdicts live here. */
180
+ subsequentPasses: AggregateInput['subsequentPasses'];
181
+ }
182
+
183
+ /**
184
+ * 6c arbiter gate (SPEC §6.10.1 `arbitrated`). Returns true when a 2-pass
185
+ * cross-check disagreed on a gate-relevant (`critical` | `minor`) Pass-1
186
+ * finding — the only case worth spending a 3rd Mantis arbiter pass on. Pure:
187
+ * it reads the verdicts Pass 2 already produced; no I/O, no AI call.
188
+ *
189
+ * Scope rationale:
190
+ * - cross-check only — `consensus` already runs Mantis as its final pass and
191
+ * `independent` has no arbiter; both return false.
192
+ * - `passCount === 2` (not `>= 2`) — a statically-configured 3-pass
193
+ * cross-check already runs Mantis as pass 3 via the loop, so escalating
194
+ * there would stack a redundant 4th pass past MAX_PASSES.
195
+ * - severity `critical | minor` — a `preexisting` dispute can never flip the
196
+ * merge gate, so it doesn't earn an Opus-class arbiter.
197
+ *
198
+ * Authority is marker-only: the arbiter's verdict sets the disputed finding's
199
+ * consensus marker + rationale; it does not change which findings gate the
200
+ * merge (that stays `resolveVerdict`'s job).
201
+ */
202
+ export function shouldEscalate(input: EscalationInput): boolean {
203
+ if (input.mode !== 'cross-check' || input.passCount !== 2) return false;
204
+ const pass1 = flattenFindings(input.firstPass);
205
+ return input.subsequentPasses.some((pass) =>
206
+ (pass.crossCheck?.verdicts ?? []).some((v) => {
207
+ if (v.verdict !== 'disagreed') return false;
208
+ const severity = pass1[v.pass1Index]?.severity;
209
+ return severity === 'critical' || severity === 'minor';
210
+ }),
211
+ );
212
+ }
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // Mode: cross-check
216
+ // ---------------------------------------------------------------------------
217
+
218
+ /**
219
+ * Cross-check: Pass 2 saw Pass 1's findings + the diff. Each Pass-1 finding
220
+ * gets a per-pass-2 verdict; Pass 2's independent findings are appended.
221
+ *
222
+ * Output order:
223
+ * 1. Pass-1 findings in original order, each with their pass-2 verdict
224
+ * attribution attached (one PassAttribution for Pass 1, one for Pass 2
225
+ * if applicable, etc.).
226
+ * 2. Pass-2 (and beyond) independent findings, in pass order.
227
+ */
228
+ function aggregateCrossCheck(input: AggregateInput): MultiPassReview {
229
+ const findings: UnifiedFinding[] = [];
230
+ const firstRoleAttribution = (
231
+ _f: Finding,
232
+ source: PassSource = 'first',
233
+ ): PassAttribution => ({
234
+ passNumber: 1,
235
+ roleName: input.firstPassRole.name,
236
+ model: input.firstPassRole.model,
237
+ source,
238
+ });
239
+
240
+ // Initialize the unified list with Pass 1's findings. Wire-shape Review
241
+ // splits findings across 3 severity arrays; flatten to internal Finding[].
242
+ for (const f of flattenFindings(input.firstPass)) {
243
+ findings.push({
244
+ ...f,
245
+ attributions: [firstRoleAttribution(f)],
246
+ });
247
+ }
248
+
249
+ // Layer in each subsequent pass's verdicts + independent findings.
250
+ for (const pass of input.subsequentPasses) {
251
+ if (!pass.crossCheck) continue; // mis-configured input; skip cleanly
252
+ // 1. Verdicts on Pass-1 findings — attach a PassAttribution per verdict.
253
+ for (const v of pass.crossCheck.verdicts) {
254
+ const target = findings[v.pass1Index];
255
+ if (!target) continue; // out-of-range index — ignore
256
+ target.attributions.push({
257
+ passNumber: pass.passNumber,
258
+ roleName: pass.role.name,
259
+ model: pass.role.model,
260
+ source: v.verdict,
261
+ // exactOptionalPropertyTypes: omit `note` entirely when the pass
262
+ // supplied no rationale (vs. setting it to `undefined`). Behavior is
263
+ // identical for every consumer (renderer/tests read `note` only when
264
+ // present); the App relied on a looser tsconfig where `note:
265
+ // undefined` was allowed.
266
+ ...(v.rationale !== undefined ? { note: v.rationale } : {}),
267
+ });
268
+ }
269
+ // 2. Independent findings — append with provenance.
270
+ for (const f of pass.crossCheck.independentFindings) {
271
+ findings.push({
272
+ ...f,
273
+ attributions: [
274
+ {
275
+ passNumber: pass.passNumber,
276
+ roleName: pass.role.name,
277
+ model: pass.role.model,
278
+ source: 'independent',
279
+ },
280
+ ],
281
+ });
282
+ }
283
+ }
284
+
285
+ return finalize({
286
+ mode: 'cross-check',
287
+ findings,
288
+ firstPassRole: input.firstPassRole,
289
+ subsequentPasses: input.subsequentPasses,
290
+ });
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Mode: consensus
295
+ // ---------------------------------------------------------------------------
296
+
297
+ /**
298
+ * Consensus: every pass ran fully independent of the others. We diff the
299
+ * passes pairwise and label same-tuple findings as `agreed` (intersection)
300
+ * and tuple-unique findings as `first` / `independent` per pass.
301
+ *
302
+ * Output order:
303
+ * 1. Pass 1's findings in original order (each enriched with `agreed`
304
+ * attributions if other passes also raised the same tuple).
305
+ * 2. Tuple-unique findings from later passes, in pass-number order.
306
+ */
307
+ function aggregateConsensus(input: AggregateInput): MultiPassReview {
308
+ const findings: UnifiedFinding[] = [];
309
+
310
+ // Index Pass 1's findings by tuple → list index.
311
+ const tupleToIndex = new Map<string, number>();
312
+ flattenFindings(input.firstPass).forEach((f, i) => {
313
+ findings.push({
314
+ ...f,
315
+ attributions: [
316
+ {
317
+ passNumber: 1,
318
+ roleName: input.firstPassRole.name,
319
+ model: input.firstPassRole.model,
320
+ source: 'first',
321
+ },
322
+ ],
323
+ });
324
+ tupleToIndex.set(tupleKey(f), i);
325
+ });
326
+
327
+ for (const pass of input.subsequentPasses) {
328
+ if (!pass.review) continue;
329
+ for (const f of flattenFindings(pass.review)) {
330
+ const key = tupleKey(f);
331
+ const existingIndex = tupleToIndex.get(key);
332
+ if (existingIndex !== undefined) {
333
+ // Same-tuple match → consensus. Append an "agreed" attribution.
334
+ const target = findings[existingIndex];
335
+ if (!target) continue;
336
+ target.attributions.push({
337
+ passNumber: pass.passNumber,
338
+ roleName: pass.role.name,
339
+ model: pass.role.model,
340
+ source: 'agreed',
341
+ });
342
+ // Promote severity if this pass flagged it higher (e.g. Pass 1 minor,
343
+ // Pass 2 critical — we keep the more conservative critical).
344
+ if (severityRank(f.severity) > severityRank(target.severity)) {
345
+ target.severity = f.severity;
346
+ }
347
+ } else {
348
+ // New tuple — append + index for future passes.
349
+ const newIdx = findings.length;
350
+ findings.push({
351
+ ...f,
352
+ attributions: [
353
+ {
354
+ passNumber: pass.passNumber,
355
+ roleName: pass.role.name,
356
+ model: pass.role.model,
357
+ source: 'independent',
358
+ },
359
+ ],
360
+ });
361
+ tupleToIndex.set(key, newIdx);
362
+ }
363
+ }
364
+ }
365
+
366
+ return finalize({
367
+ mode: 'consensus',
368
+ findings,
369
+ firstPassRole: input.firstPassRole,
370
+ subsequentPasses: input.subsequentPasses,
371
+ });
372
+ }
373
+
374
+ // ---------------------------------------------------------------------------
375
+ // Mode: independent
376
+ // ---------------------------------------------------------------------------
377
+
378
+ /**
379
+ * Independent: no merging. Every finding from every pass is emitted with
380
+ * `source: 'first'` (Pass 1) or `source: 'independent'` (Pass N > 1). The
381
+ * renderer is responsible for formatting as side-by-side blocks.
382
+ *
383
+ * Output order: Pass 1's findings, then Pass 2's, then Pass 3's — preserving
384
+ * each pass's internal order.
385
+ */
386
+ function aggregateIndependent(input: AggregateInput): MultiPassReview {
387
+ const findings: UnifiedFinding[] = [];
388
+ for (const f of flattenFindings(input.firstPass)) {
389
+ findings.push({
390
+ ...f,
391
+ attributions: [
392
+ {
393
+ passNumber: 1,
394
+ roleName: input.firstPassRole.name,
395
+ model: input.firstPassRole.model,
396
+ source: 'first',
397
+ },
398
+ ],
399
+ });
400
+ }
401
+ for (const pass of input.subsequentPasses) {
402
+ if (!pass.review) continue;
403
+ for (const f of flattenFindings(pass.review)) {
404
+ findings.push({
405
+ ...f,
406
+ attributions: [
407
+ {
408
+ passNumber: pass.passNumber,
409
+ roleName: pass.role.name,
410
+ model: pass.role.model,
411
+ source: 'independent',
412
+ },
413
+ ],
414
+ });
415
+ }
416
+ }
417
+ return finalize({
418
+ mode: 'independent',
419
+ findings,
420
+ firstPassRole: input.firstPassRole,
421
+ subsequentPasses: input.subsequentPasses,
422
+ });
423
+ }
424
+
425
+ // ---------------------------------------------------------------------------
426
+ // Internal helpers
427
+ // ---------------------------------------------------------------------------
428
+
429
+ /**
430
+ * Tuple-key used to detect "same finding" across passes.
431
+ *
432
+ * We key on (file, line, skill) instead of summary because:
433
+ * - Summaries vary stylistically between passes (Sonnet vs Opus phrasing).
434
+ * - File + line + cited skill is the SPEC §1.8.1 minimum identity unit.
435
+ * - File-level findings (no line) collapse to the same tuple regardless of
436
+ * phrasing, which is the desired consensus semantic.
437
+ */
438
+ function tupleKey(f: Finding): string {
439
+ return `${f.file}::${f.line ?? '*'}::${f.skill}`;
440
+ }
441
+
442
+ function severityRank(s: Severity): number {
443
+ switch (s) {
444
+ case 'critical':
445
+ return 3;
446
+ case 'minor':
447
+ return 2;
448
+ case 'preexisting':
449
+ return 1;
450
+ }
451
+ }
452
+
453
+ interface FinalizeInput {
454
+ mode: ReviewPassMode;
455
+ /**
456
+ * Pre-consensus shape — aggregators build these without populating
457
+ * the `consensus` field; `finalize()` is the single derivation point
458
+ * via `deriveConsensus(attributions)`. Keeping aggregators free of
459
+ * the consensus concern avoids drift between cross-check / consensus
460
+ * / independent paths (one mapping rule, three call sites).
461
+ */
462
+ findings: UnifiedFinding[];
463
+ firstPassRole: ReviewRole;
464
+ subsequentPasses: AggregateInput['subsequentPasses'];
465
+ }
466
+
467
+ function finalize(input: FinalizeInput): MultiPassReview {
468
+ const passCount = 1 + input.subsequentPasses.length;
469
+ const roles = [
470
+ {
471
+ passNumber: 1,
472
+ roleName: input.firstPassRole.name,
473
+ model: input.firstPassRole.model,
474
+ },
475
+ ...input.subsequentPasses.map((p) => ({
476
+ passNumber: p.passNumber,
477
+ roleName: p.role.name,
478
+ model: p.role.model,
479
+ })),
480
+ ];
481
+
482
+ // SPEC §6.10.1 consensus marker — single derivation point.
483
+ // Aggregators emit findings without `consensus`; this map adds it
484
+ // from the accumulated per-pass attributions. Renderer + auto-fix
485
+ // gate both consume `finding.consensus` downstream.
486
+ const findingsWithConsensus: UnifiedFinding[] = input.findings.map(
487
+ (f) => ({
488
+ ...f,
489
+ consensus: deriveConsensus(f.attributions),
490
+ }),
491
+ );
492
+
493
+ // Derive summary counts + skills_referenced from the aggregated list.
494
+ const counts = {
495
+ critical: findingsWithConsensus.filter((f) => f.severity === 'critical').length,
496
+ minor: findingsWithConsensus.filter((f) => f.severity === 'minor').length,
497
+ preexisting: findingsWithConsensus.filter((f) => f.severity === 'preexisting')
498
+ .length,
499
+ resolved_from_prior: 0,
500
+ still_open: 0,
501
+ };
502
+ const skillsReferenced = uniqInOrder(findingsWithConsensus.map((f) => f.skill));
503
+
504
+ // Status header logic:
505
+ // - empty → "clean"
506
+ // - any critical → "critical findings"
507
+ // - else → "clean" (minor + preexisting alone don't headline as critical)
508
+ const status_header =
509
+ counts.critical > 0
510
+ ? ('critical findings' as const)
511
+ : ('clean' as const);
512
+
513
+ // Verdict resolution — see resolveVerdict for the per-mode rules.
514
+ const verdict = resolveVerdict(input.mode, findingsWithConsensus, passCount);
515
+
516
+ return {
517
+ status_header,
518
+ summary_counts: counts,
519
+ skills_referenced: skillsReferenced,
520
+ findings: findingsWithConsensus,
521
+ mode: input.mode,
522
+ passCount,
523
+ roles,
524
+ verdict,
525
+ };
526
+ }
527
+
528
+ function uniqInOrder(items: string[]): string[] {
529
+ const seen = new Set<string>();
530
+ const out: string[] = [];
531
+ for (const it of items) {
532
+ if (seen.has(it)) continue;
533
+ seen.add(it);
534
+ out.push(it);
535
+ }
536
+ return out;
537
+ }
538
+
539
+ // ---------------------------------------------------------------------------
540
+ // Verdict resolution
541
+ // ---------------------------------------------------------------------------
542
+
543
+ /**
544
+ * Resolves the APPROVE / REQUEST_CHANGES verdict per the SPEC §1.8.5 table:
545
+ *
546
+ * mode | request_changes when…
547
+ * --------------+------------------------------------------------------
548
+ * strict (=cross-check default) | ANY pass flagged critical
549
+ * consensus | ≥2 passes flagged the same critical tuple
550
+ * independent | findings side-by-side — human decides per finding.
551
+ * | For automation purposes we treat ANY critical as
552
+ * | request_changes (safer default; humans can downgrade).
553
+ *
554
+ * We expose this both as a return field on `MultiPassReview.verdict` and
555
+ * separately (for tests + future D.2 wiring) as `resolveVerdict`.
556
+ *
557
+ * NOTE: The broader D.2 phase wires APPROVE/REQUEST_CHANGES into actual
558
+ * PR check states. D.2.5 only computes the verdict — surfacing it is left
559
+ * to the renderer (which prefixes the header line with the verdict label).
560
+ */
561
+ export function resolveVerdict(
562
+ mode: ReviewPassMode,
563
+ findings: UnifiedFinding[],
564
+ passCount: number,
565
+ ): MultiPassReview['verdict'] {
566
+ if (findings.length === 0) return 'clean';
567
+ const criticals = findings.filter((f) => f.severity === 'critical');
568
+ if (criticals.length === 0) return 'review_only';
569
+
570
+ switch (mode) {
571
+ case 'cross-check':
572
+ case 'independent':
573
+ // Strict: any critical → request_changes.
574
+ return 'request_changes';
575
+ case 'consensus':
576
+ // ≥2 passes must agree on the same critical tuple.
577
+ // Single-pass consensus is degenerate but valid — any critical fires.
578
+ if (passCount < 2) return 'request_changes';
579
+ for (const f of criticals) {
580
+ // Spec: "≥2 passes flagged the same critical tuple."
581
+ // Each attribution represents exactly one pass, so the correct
582
+ // count is f.attributions.length. The earlier filter on
583
+ // `source === 'first' | 'agreed'` silently dropped findings
584
+ // raised by Pass 2 + confirmed by Pass 3 but missed by Pass 1
585
+ // (attributions = [independent, agreed], neither matches → the
586
+ // consensus gate never fired).
587
+ if (f.attributions.length >= 2) return 'request_changes';
588
+ }
589
+ return 'review_only';
590
+ }
591
+ }