clud-bug 0.7.0-rc.11 → 0.7.0-rc.13

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 (55) hide show
  1. package/dist/cli/hooks.d.ts +40 -0
  2. package/dist/cli/hooks.d.ts.map +1 -0
  3. package/dist/cli/hooks.js +105 -0
  4. package/dist/cli/hooks.js.map +1 -0
  5. package/dist/cli/main.d.ts.map +1 -1
  6. package/dist/cli/main.js +61 -0
  7. package/dist/cli/main.js.map +1 -1
  8. package/dist/cli/review-prompt.d.ts +28 -0
  9. package/dist/cli/review-prompt.d.ts.map +1 -0
  10. package/dist/cli/review-prompt.js +169 -0
  11. package/dist/cli/review-prompt.js.map +1 -0
  12. package/dist/cli/update.d.ts.map +1 -1
  13. package/dist/cli/update.js +22 -0
  14. package/dist/cli/update.js.map +1 -1
  15. package/dist/core/budget-plan.d.ts +125 -0
  16. package/dist/core/budget-plan.d.ts.map +1 -0
  17. package/dist/core/budget-plan.js +211 -0
  18. package/dist/core/budget-plan.js.map +1 -0
  19. package/dist/core/index.d.ts +5 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/index.js +14 -0
  22. package/dist/core/index.js.map +1 -1
  23. package/dist/core/multi-pass-aggregate.d.ts +131 -0
  24. package/dist/core/multi-pass-aggregate.d.ts.map +1 -0
  25. package/dist/core/multi-pass-aggregate.js +427 -0
  26. package/dist/core/multi-pass-aggregate.js.map +1 -0
  27. package/dist/core/plan-review.d.ts +57 -0
  28. package/dist/core/plan-review.d.ts.map +1 -0
  29. package/dist/core/plan-review.js +77 -0
  30. package/dist/core/plan-review.js.map +1 -0
  31. package/dist/core/review-plan.d.ts +219 -0
  32. package/dist/core/review-plan.d.ts.map +1 -0
  33. package/dist/core/review-plan.js +274 -0
  34. package/dist/core/review-plan.js.map +1 -0
  35. package/dist/core/review-writeback.d.ts +20 -0
  36. package/dist/core/review-writeback.d.ts.map +1 -1
  37. package/dist/core/review-writeback.js +16 -0
  38. package/dist/core/review-writeback.js.map +1 -1
  39. package/dist/core/version.d.ts +1 -1
  40. package/dist/core/version.js +1 -1
  41. package/package.json +1 -1
  42. package/src/cli/hooks.ts +122 -0
  43. package/src/cli/main.ts +56 -0
  44. package/src/cli/review-prompt.ts +206 -0
  45. package/src/cli/update.ts +22 -0
  46. package/src/core/budget-plan.ts +324 -0
  47. package/src/core/index.ts +64 -0
  48. package/src/core/multi-pass-aggregate.ts +545 -0
  49. package/src/core/plan-review.ts +136 -0
  50. package/src/core/review-plan.ts +485 -0
  51. package/src/core/review-writeback.ts +38 -0
  52. package/src/core/version.ts +1 -1
  53. package/templates/workflow-py.yml.tmpl +1 -1
  54. package/templates/workflow-ts.yml.tmpl +1 -1
  55. package/templates/workflow.yml.tmpl +1 -1
@@ -0,0 +1,545 @@
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
+ // Mode: cross-check
170
+ // ---------------------------------------------------------------------------
171
+
172
+ /**
173
+ * Cross-check: Pass 2 saw Pass 1's findings + the diff. Each Pass-1 finding
174
+ * gets a per-pass-2 verdict; Pass 2's independent findings are appended.
175
+ *
176
+ * Output order:
177
+ * 1. Pass-1 findings in original order, each with their pass-2 verdict
178
+ * attribution attached (one PassAttribution for Pass 1, one for Pass 2
179
+ * if applicable, etc.).
180
+ * 2. Pass-2 (and beyond) independent findings, in pass order.
181
+ */
182
+ function aggregateCrossCheck(input: AggregateInput): MultiPassReview {
183
+ const findings: UnifiedFinding[] = [];
184
+ const firstRoleAttribution = (
185
+ _f: Finding,
186
+ source: PassSource = 'first',
187
+ ): PassAttribution => ({
188
+ passNumber: 1,
189
+ roleName: input.firstPassRole.name,
190
+ model: input.firstPassRole.model,
191
+ source,
192
+ });
193
+
194
+ // Initialize the unified list with Pass 1's findings. Wire-shape Review
195
+ // splits findings across 3 severity arrays; flatten to internal Finding[].
196
+ for (const f of flattenFindings(input.firstPass)) {
197
+ findings.push({
198
+ ...f,
199
+ attributions: [firstRoleAttribution(f)],
200
+ });
201
+ }
202
+
203
+ // Layer in each subsequent pass's verdicts + independent findings.
204
+ for (const pass of input.subsequentPasses) {
205
+ if (!pass.crossCheck) continue; // mis-configured input; skip cleanly
206
+ // 1. Verdicts on Pass-1 findings — attach a PassAttribution per verdict.
207
+ for (const v of pass.crossCheck.verdicts) {
208
+ const target = findings[v.pass1Index];
209
+ if (!target) continue; // out-of-range index — ignore
210
+ target.attributions.push({
211
+ passNumber: pass.passNumber,
212
+ roleName: pass.role.name,
213
+ model: pass.role.model,
214
+ source: v.verdict,
215
+ // exactOptionalPropertyTypes: omit `note` entirely when the pass
216
+ // supplied no rationale (vs. setting it to `undefined`). Behavior is
217
+ // identical for every consumer (renderer/tests read `note` only when
218
+ // present); the App relied on a looser tsconfig where `note:
219
+ // undefined` was allowed.
220
+ ...(v.rationale !== undefined ? { note: v.rationale } : {}),
221
+ });
222
+ }
223
+ // 2. Independent findings — append with provenance.
224
+ for (const f of pass.crossCheck.independentFindings) {
225
+ findings.push({
226
+ ...f,
227
+ attributions: [
228
+ {
229
+ passNumber: pass.passNumber,
230
+ roleName: pass.role.name,
231
+ model: pass.role.model,
232
+ source: 'independent',
233
+ },
234
+ ],
235
+ });
236
+ }
237
+ }
238
+
239
+ return finalize({
240
+ mode: 'cross-check',
241
+ findings,
242
+ firstPassRole: input.firstPassRole,
243
+ subsequentPasses: input.subsequentPasses,
244
+ });
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // Mode: consensus
249
+ // ---------------------------------------------------------------------------
250
+
251
+ /**
252
+ * Consensus: every pass ran fully independent of the others. We diff the
253
+ * passes pairwise and label same-tuple findings as `agreed` (intersection)
254
+ * and tuple-unique findings as `first` / `independent` per pass.
255
+ *
256
+ * Output order:
257
+ * 1. Pass 1's findings in original order (each enriched with `agreed`
258
+ * attributions if other passes also raised the same tuple).
259
+ * 2. Tuple-unique findings from later passes, in pass-number order.
260
+ */
261
+ function aggregateConsensus(input: AggregateInput): MultiPassReview {
262
+ const findings: UnifiedFinding[] = [];
263
+
264
+ // Index Pass 1's findings by tuple → list index.
265
+ const tupleToIndex = new Map<string, number>();
266
+ flattenFindings(input.firstPass).forEach((f, i) => {
267
+ findings.push({
268
+ ...f,
269
+ attributions: [
270
+ {
271
+ passNumber: 1,
272
+ roleName: input.firstPassRole.name,
273
+ model: input.firstPassRole.model,
274
+ source: 'first',
275
+ },
276
+ ],
277
+ });
278
+ tupleToIndex.set(tupleKey(f), i);
279
+ });
280
+
281
+ for (const pass of input.subsequentPasses) {
282
+ if (!pass.review) continue;
283
+ for (const f of flattenFindings(pass.review)) {
284
+ const key = tupleKey(f);
285
+ const existingIndex = tupleToIndex.get(key);
286
+ if (existingIndex !== undefined) {
287
+ // Same-tuple match → consensus. Append an "agreed" attribution.
288
+ const target = findings[existingIndex];
289
+ if (!target) continue;
290
+ target.attributions.push({
291
+ passNumber: pass.passNumber,
292
+ roleName: pass.role.name,
293
+ model: pass.role.model,
294
+ source: 'agreed',
295
+ });
296
+ // Promote severity if this pass flagged it higher (e.g. Pass 1 minor,
297
+ // Pass 2 critical — we keep the more conservative critical).
298
+ if (severityRank(f.severity) > severityRank(target.severity)) {
299
+ target.severity = f.severity;
300
+ }
301
+ } else {
302
+ // New tuple — append + index for future passes.
303
+ const newIdx = findings.length;
304
+ findings.push({
305
+ ...f,
306
+ attributions: [
307
+ {
308
+ passNumber: pass.passNumber,
309
+ roleName: pass.role.name,
310
+ model: pass.role.model,
311
+ source: 'independent',
312
+ },
313
+ ],
314
+ });
315
+ tupleToIndex.set(key, newIdx);
316
+ }
317
+ }
318
+ }
319
+
320
+ return finalize({
321
+ mode: 'consensus',
322
+ findings,
323
+ firstPassRole: input.firstPassRole,
324
+ subsequentPasses: input.subsequentPasses,
325
+ });
326
+ }
327
+
328
+ // ---------------------------------------------------------------------------
329
+ // Mode: independent
330
+ // ---------------------------------------------------------------------------
331
+
332
+ /**
333
+ * Independent: no merging. Every finding from every pass is emitted with
334
+ * `source: 'first'` (Pass 1) or `source: 'independent'` (Pass N > 1). The
335
+ * renderer is responsible for formatting as side-by-side blocks.
336
+ *
337
+ * Output order: Pass 1's findings, then Pass 2's, then Pass 3's — preserving
338
+ * each pass's internal order.
339
+ */
340
+ function aggregateIndependent(input: AggregateInput): MultiPassReview {
341
+ const findings: UnifiedFinding[] = [];
342
+ for (const f of flattenFindings(input.firstPass)) {
343
+ findings.push({
344
+ ...f,
345
+ attributions: [
346
+ {
347
+ passNumber: 1,
348
+ roleName: input.firstPassRole.name,
349
+ model: input.firstPassRole.model,
350
+ source: 'first',
351
+ },
352
+ ],
353
+ });
354
+ }
355
+ for (const pass of input.subsequentPasses) {
356
+ if (!pass.review) continue;
357
+ for (const f of flattenFindings(pass.review)) {
358
+ findings.push({
359
+ ...f,
360
+ attributions: [
361
+ {
362
+ passNumber: pass.passNumber,
363
+ roleName: pass.role.name,
364
+ model: pass.role.model,
365
+ source: 'independent',
366
+ },
367
+ ],
368
+ });
369
+ }
370
+ }
371
+ return finalize({
372
+ mode: 'independent',
373
+ findings,
374
+ firstPassRole: input.firstPassRole,
375
+ subsequentPasses: input.subsequentPasses,
376
+ });
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // Internal helpers
381
+ // ---------------------------------------------------------------------------
382
+
383
+ /**
384
+ * Tuple-key used to detect "same finding" across passes.
385
+ *
386
+ * We key on (file, line, skill) instead of summary because:
387
+ * - Summaries vary stylistically between passes (Sonnet vs Opus phrasing).
388
+ * - File + line + cited skill is the SPEC §1.8.1 minimum identity unit.
389
+ * - File-level findings (no line) collapse to the same tuple regardless of
390
+ * phrasing, which is the desired consensus semantic.
391
+ */
392
+ function tupleKey(f: Finding): string {
393
+ return `${f.file}::${f.line ?? '*'}::${f.skill}`;
394
+ }
395
+
396
+ function severityRank(s: Severity): number {
397
+ switch (s) {
398
+ case 'critical':
399
+ return 3;
400
+ case 'minor':
401
+ return 2;
402
+ case 'preexisting':
403
+ return 1;
404
+ }
405
+ }
406
+
407
+ interface FinalizeInput {
408
+ mode: ReviewPassMode;
409
+ /**
410
+ * Pre-consensus shape — aggregators build these without populating
411
+ * the `consensus` field; `finalize()` is the single derivation point
412
+ * via `deriveConsensus(attributions)`. Keeping aggregators free of
413
+ * the consensus concern avoids drift between cross-check / consensus
414
+ * / independent paths (one mapping rule, three call sites).
415
+ */
416
+ findings: UnifiedFinding[];
417
+ firstPassRole: ReviewRole;
418
+ subsequentPasses: AggregateInput['subsequentPasses'];
419
+ }
420
+
421
+ function finalize(input: FinalizeInput): MultiPassReview {
422
+ const passCount = 1 + input.subsequentPasses.length;
423
+ const roles = [
424
+ {
425
+ passNumber: 1,
426
+ roleName: input.firstPassRole.name,
427
+ model: input.firstPassRole.model,
428
+ },
429
+ ...input.subsequentPasses.map((p) => ({
430
+ passNumber: p.passNumber,
431
+ roleName: p.role.name,
432
+ model: p.role.model,
433
+ })),
434
+ ];
435
+
436
+ // SPEC §6.10.1 consensus marker — single derivation point.
437
+ // Aggregators emit findings without `consensus`; this map adds it
438
+ // from the accumulated per-pass attributions. Renderer + auto-fix
439
+ // gate both consume `finding.consensus` downstream.
440
+ const findingsWithConsensus: UnifiedFinding[] = input.findings.map(
441
+ (f) => ({
442
+ ...f,
443
+ consensus: deriveConsensus(f.attributions),
444
+ }),
445
+ );
446
+
447
+ // Derive summary counts + skills_referenced from the aggregated list.
448
+ const counts = {
449
+ critical: findingsWithConsensus.filter((f) => f.severity === 'critical').length,
450
+ minor: findingsWithConsensus.filter((f) => f.severity === 'minor').length,
451
+ preexisting: findingsWithConsensus.filter((f) => f.severity === 'preexisting')
452
+ .length,
453
+ resolved_from_prior: 0,
454
+ still_open: 0,
455
+ };
456
+ const skillsReferenced = uniqInOrder(findingsWithConsensus.map((f) => f.skill));
457
+
458
+ // Status header logic:
459
+ // - empty → "clean"
460
+ // - any critical → "critical findings"
461
+ // - else → "clean" (minor + preexisting alone don't headline as critical)
462
+ const status_header =
463
+ counts.critical > 0
464
+ ? ('critical findings' as const)
465
+ : ('clean' as const);
466
+
467
+ // Verdict resolution — see resolveVerdict for the per-mode rules.
468
+ const verdict = resolveVerdict(input.mode, findingsWithConsensus, passCount);
469
+
470
+ return {
471
+ status_header,
472
+ summary_counts: counts,
473
+ skills_referenced: skillsReferenced,
474
+ findings: findingsWithConsensus,
475
+ mode: input.mode,
476
+ passCount,
477
+ roles,
478
+ verdict,
479
+ };
480
+ }
481
+
482
+ function uniqInOrder(items: string[]): string[] {
483
+ const seen = new Set<string>();
484
+ const out: string[] = [];
485
+ for (const it of items) {
486
+ if (seen.has(it)) continue;
487
+ seen.add(it);
488
+ out.push(it);
489
+ }
490
+ return out;
491
+ }
492
+
493
+ // ---------------------------------------------------------------------------
494
+ // Verdict resolution
495
+ // ---------------------------------------------------------------------------
496
+
497
+ /**
498
+ * Resolves the APPROVE / REQUEST_CHANGES verdict per the SPEC §1.8.5 table:
499
+ *
500
+ * mode | request_changes when…
501
+ * --------------+------------------------------------------------------
502
+ * strict (=cross-check default) | ANY pass flagged critical
503
+ * consensus | ≥2 passes flagged the same critical tuple
504
+ * independent | findings side-by-side — human decides per finding.
505
+ * | For automation purposes we treat ANY critical as
506
+ * | request_changes (safer default; humans can downgrade).
507
+ *
508
+ * We expose this both as a return field on `MultiPassReview.verdict` and
509
+ * separately (for tests + future D.2 wiring) as `resolveVerdict`.
510
+ *
511
+ * NOTE: The broader D.2 phase wires APPROVE/REQUEST_CHANGES into actual
512
+ * PR check states. D.2.5 only computes the verdict — surfacing it is left
513
+ * to the renderer (which prefixes the header line with the verdict label).
514
+ */
515
+ export function resolveVerdict(
516
+ mode: ReviewPassMode,
517
+ findings: UnifiedFinding[],
518
+ passCount: number,
519
+ ): MultiPassReview['verdict'] {
520
+ if (findings.length === 0) return 'clean';
521
+ const criticals = findings.filter((f) => f.severity === 'critical');
522
+ if (criticals.length === 0) return 'review_only';
523
+
524
+ switch (mode) {
525
+ case 'cross-check':
526
+ case 'independent':
527
+ // Strict: any critical → request_changes.
528
+ return 'request_changes';
529
+ case 'consensus':
530
+ // ≥2 passes must agree on the same critical tuple.
531
+ // Single-pass consensus is degenerate but valid — any critical fires.
532
+ if (passCount < 2) return 'request_changes';
533
+ for (const f of criticals) {
534
+ // Spec: "≥2 passes flagged the same critical tuple."
535
+ // Each attribution represents exactly one pass, so the correct
536
+ // count is f.attributions.length. The earlier filter on
537
+ // `source === 'first' | 'agreed'` silently dropped findings
538
+ // raised by Pass 2 + confirmed by Pass 3 but missed by Pass 1
539
+ // (attributions = [independent, agreed], neither matches → the
540
+ // consensus gate never fired).
541
+ if (f.attributions.length >= 2) return 'request_changes';
542
+ }
543
+ return 'review_only';
544
+ }
545
+ }
@@ -0,0 +1,136 @@
1
+ // The single shared review planner (SPEC §11.5). Composes the per-skill pass
2
+ // resolver (`review-plan.ts`) and the Layer-1 budget gate (`budget-plan.ts`),
3
+ // then applies trigger / diff-size tiering. Every consumer — the hosted bot,
4
+ // the npm workflow, and local mode — runs THIS function so they plan
5
+ // identically; only the tier → concrete-model binding differs per consumer.
6
+ //
7
+ // Lives in its own module (not in `review-plan.ts`) because it imports
8
+ // `estimateBudget`, and `budget-plan.ts` already imports from `review-plan.ts`
9
+ // — keeping `planReview` here avoids a review-plan ↔ budget-plan cycle.
10
+
11
+ import {
12
+ resolveReviewPasses,
13
+ type ReviewPlanSkill,
14
+ type ReviewPassesConfig,
15
+ type ResolvedReviewPasses,
16
+ type ReviewRole,
17
+ type ApplyTo,
18
+ } from './review-plan.js';
19
+ import { estimateBudget, type BudgetVerdict } from './budget-plan.js';
20
+
21
+ /** Trigger context that selects plan depth (SPEC §11.5). */
22
+ export type ReviewTrigger = 'commit' | 'push' | 'pr';
23
+
24
+ /** Why a plan was tiered down from its fully-resolved passes. */
25
+ export type TierDownReason = 'commit' | 'large-diff';
26
+
27
+ /**
28
+ * Diff size (bytes) at/above which the planner auto-tiers down to a single
29
+ * fast pass to protect cost + latency. A very large diff rarely benefits from
30
+ * multi-pass depth as much as it costs.
31
+ */
32
+ export const LARGE_DIFF_THRESHOLD_BYTES = 50_000;
33
+
34
+ export interface PlanReviewInput {
35
+ /** Loaded skills — the caller does the consumer-specific I/O to load them. */
36
+ skills: ReviewPlanSkill[];
37
+ /** Parsed `.clud-bug.json` `reviewPasses` block (may be null). */
38
+ config: ReviewPassesConfig | null;
39
+ /** Raw SKILL.md text per slug, for the frontmatter `review_passes` override. */
40
+ rawSkillMd?: Record<string, string>;
41
+ /** Trigger context. Defaults to `pr` (the full plan). */
42
+ trigger?: ReviewTrigger;
43
+ /** Diff size under review, in bytes — enables large-diff auto-tiering. */
44
+ diffSizeBytes?: number;
45
+ /** Optional per-PR USD cap forwarded to the budget gate. */
46
+ perPrCapUsd?: number;
47
+ /** Billing-exempt installs bypass the budget cap. */
48
+ billingExempt?: boolean;
49
+ }
50
+
51
+ export interface ReviewPlan {
52
+ /** Effective per-skill passes (after any tier-down). */
53
+ perSkill: ResolvedReviewPasses[];
54
+ /** Role tiers in pass order — the consumer binds each tier → a concrete model. */
55
+ roles: ReviewRole[];
56
+ /** Multi-pass apply scope. */
57
+ applyTo: ApplyTo;
58
+ /** Layer-1 budget verdict over the effective (post-tiering) plan. */
59
+ budget: BudgetVerdict;
60
+ /** The trigger this plan was computed for. */
61
+ trigger: ReviewTrigger;
62
+ /** Present when the resolved passes were tiered down, with the reason. */
63
+ tieredDown?: TierDownReason;
64
+ /** One-line human summary. */
65
+ summary: string;
66
+ }
67
+
68
+ /**
69
+ * Plan a review. Tiering (a commit-time review runs on every commit, and a very
70
+ * large diff shouldn't pay for full multi-pass depth):
71
+ * - `trigger: 'commit'` → a single fast pass per skill.
72
+ * - `diffSizeBytes` >= `LARGE_DIFF_THRESHOLD_BYTES` → a single fast pass per skill.
73
+ * - otherwise (push/pr, normal diff) → the fully-resolved plan.
74
+ * `commit` takes precedence over diff size.
75
+ *
76
+ * Tiering to one pass means pass 1 / role[0] (the `beetle` fast tier) runs — so
77
+ * "fast model for commits" falls out of the tier system, never hand-picked.
78
+ */
79
+ export function planReview(input: PlanReviewInput): ReviewPlan {
80
+ const trigger: ReviewTrigger = input.trigger ?? 'pr';
81
+
82
+ const resolved = resolveReviewPasses({
83
+ skills: input.skills,
84
+ config: input.config,
85
+ ...(input.rawSkillMd !== undefined ? { rawSkillMd: input.rawSkillMd } : {}),
86
+ });
87
+
88
+ let tieredDown: TierDownReason | undefined;
89
+ if (trigger === 'commit') {
90
+ tieredDown = 'commit';
91
+ } else if (
92
+ input.diffSizeBytes !== undefined &&
93
+ input.diffSizeBytes >= LARGE_DIFF_THRESHOLD_BYTES
94
+ ) {
95
+ tieredDown = 'large-diff';
96
+ }
97
+
98
+ const perSkill: ResolvedReviewPasses[] = tieredDown
99
+ ? resolved.perSkill.map((p) => ({ ...p, count: 1 }))
100
+ : resolved.perSkill;
101
+
102
+ // Cost only the passes that actually run: a tiered plan runs a single
103
+ // (role[0] / beetle) pass, so don't bill the skipped deeper tiers.
104
+ const roleModels = (tieredDown ? resolved.roles.slice(0, 1) : resolved.roles).map(
105
+ (r) => r.model,
106
+ );
107
+ const budget = estimateBudget({
108
+ resolved: perSkill,
109
+ roleModels,
110
+ ...(input.perPrCapUsd !== undefined ? { perPrCapUsd: input.perPrCapUsd } : {}),
111
+ ...(input.billingExempt !== undefined ? { billingExempt: input.billingExempt } : {}),
112
+ });
113
+
114
+ // Report the per-skill pass DEPTH (max), not the summed call count — the
115
+ // recipe branches on this same depth, so "1-pass" here agrees with "single
116
+ // pass" there. (Total call count drives the budget below, not the summary.)
117
+ const passesPerSkill = perSkill.length
118
+ ? Math.max(...perSkill.map((p) => p.count))
119
+ : 0;
120
+ const tierNote = tieredDown ? `, tiered down (${tieredDown})` : '';
121
+ const budgetNote =
122
+ budget.verdict === 'deny'
123
+ ? `; budget exceeded ($${budget.estimate.estimatedCostUsd.toFixed(2)} > $${budget.estimate.capUsd.toFixed(2)})`
124
+ : `; est $${budget.estimate.estimatedCostUsd.toFixed(2)}`;
125
+ const summary = `${passesPerSkill}-pass review across ${perSkill.length} skill(s) [${trigger}]${tierNote}${budgetNote}`;
126
+
127
+ return {
128
+ perSkill,
129
+ roles: resolved.roles,
130
+ applyTo: resolved.applyTo,
131
+ budget,
132
+ trigger,
133
+ ...(tieredDown !== undefined ? { tieredDown } : {}),
134
+ summary,
135
+ };
136
+ }