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,485 @@
1
+ import type { SkillFrontmatter } from './skills.js';
2
+
3
+ /**
4
+ * Multi-pass review config resolution.
5
+ *
6
+ * Each skill carries an effective `{ count, mode }` pair that drives how many
7
+ * AI calls the reviewer makes for that skill and how the orchestrator
8
+ * aggregates findings.
9
+ *
10
+ * Resolution precedence (highest → lowest):
11
+ * 1. `.clud-bug.json` `reviewPasses.perSkill[<slug>]` — per-skill consumer override
12
+ * 2. SKILL.md frontmatter `review_passes` (parsed from base ref) — skill author intent
13
+ * 3. `.clud-bug.json` `reviewPasses.default` / top-level fields — repo default
14
+ * 4. Hard-coded built-in `{ count: 1, mode: "cross-check" }` — D.2.5 baseline
15
+ *
16
+ * Hard cap: `count` is clamped to `MAX_PASSES = 3`. The plan calls this a
17
+ * brick wall — there is no escape hatch via config. Anything above gets
18
+ * silently clamped + logged. Three Claude calls per skill per review is the
19
+ * outer envelope before cost becomes user-hostile.
20
+ *
21
+ * The orchestrator uses the resolved entry to:
22
+ * - decide how many passes to run per skill (or per shared-skill bundle when
23
+ * `applyTo === "shared-only"`)
24
+ * - pass the right role / model to `runStructuredReview`
25
+ * - hand the aggregator the right mode
26
+ *
27
+ * SKILL.md frontmatter is read by the App's skills loader. We don't bake the
28
+ * parsing into the loader to keep that module simple — instead, the loader
29
+ * surfaces `frontmatter.review_passes` as opaque and we coerce it here. The
30
+ * loader is unchanged for D.2.5 — it just preserves any `review_passes` block
31
+ * verbatim through `stripFrontmatter` → body, which we never need to touch.
32
+ *
33
+ * NOTE: The loader currently only validates well-known fields. SKILL.md
34
+ * `review_passes` arrives via a NEW frontmatter pass we expose here as
35
+ * `extractSkillReviewPassesOverride` — the loader's `parseFrontmatter` doesn't
36
+ * preserve unknown top-level keys, but this helper re-parses the raw
37
+ * frontmatter on the side, so D.2.5 is additive (no breaking change to
38
+ * D.2.0 callers / tests).
39
+ *
40
+ * Decoupled from the App's `LoadedSkill` on the port to `clud-bug/core`:
41
+ * `resolveReviewPasses` accepts the minimal `{ slug, frontmatter }` shape
42
+ * (where `frontmatter` is the core `SkillFrontmatter`) so the engine has no
43
+ * dependency on the App's skills loader.
44
+ */
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Public types
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /** The three review modes. See module doc for semantics. */
51
+ export type ReviewPassMode = 'cross-check' | 'consensus' | 'independent';
52
+
53
+ export const REVIEW_PASS_MODES: readonly ReviewPassMode[] = [
54
+ 'cross-check',
55
+ 'consensus',
56
+ 'independent',
57
+ ] as const;
58
+
59
+ /** Apply scope. `shared-only` restricts multi-pass to shared (default) skills. */
60
+ export type ApplyTo = 'all' | 'shared-only';
61
+
62
+ /** The smallest config unit per skill. */
63
+ export interface ReviewPassesEntry {
64
+ /** Number of independent passes (1..MAX_PASSES). Always positive. */
65
+ count: number;
66
+ /** Aggregation mode. Only meaningful when count >= 2. */
67
+ mode: ReviewPassMode;
68
+ }
69
+
70
+ /**
71
+ * Reviewer-role tier abstraction. The orchestrator keys on the tier (not the
72
+ * display `name`) when it needs to reason about reviewer strength
73
+ * independent of the human-facing label:
74
+ * - `beetle` → fast first-pass reviewer (Sonnet-class).
75
+ * - `wasp` → deeper cross-check / consensus reviewer (Opus-class).
76
+ * - `mantis` → arbiter / third-pass reviewer (Opus-class).
77
+ *
78
+ * `name` + `model` stay for back-compat (inline attribution + AI-Gateway
79
+ * routing); `tier` is additive and optional so config-supplied roles that
80
+ * omit it still validate.
81
+ */
82
+ export type ReviewRoleTier = 'beetle' | 'wasp' | 'mantis';
83
+
84
+ /** One role definition; pairs a label ("Beetle") with a model slug. */
85
+ export interface ReviewRole {
86
+ /** Display name. Surfaced inline in the comment per the spec. */
87
+ name: string;
88
+ /** AI Gateway model slug, e.g. `anthropic/claude-sonnet-4.6`. */
89
+ model: string;
90
+ /** Optional reviewer tier. See ReviewRoleTier. */
91
+ tier?: ReviewRoleTier;
92
+ }
93
+
94
+ /** Full resolved per-skill config exposed to the orchestrator. */
95
+ export interface ResolvedReviewPasses {
96
+ /** The skill slug this entry applies to. */
97
+ slug: string;
98
+ /** Number of passes to run for this skill. Always >= 1. */
99
+ count: number;
100
+ /** Aggregation mode. */
101
+ mode: ReviewPassMode;
102
+ /** Roles, in pass order. May have fewer entries than `count`; we recycle. */
103
+ roles: ReviewRole[];
104
+ /**
105
+ * Provenance — which precedence layer produced the chosen count.
106
+ * Useful in tests + logs to verify the precedence chain.
107
+ */
108
+ source:
109
+ | 'perSkill'
110
+ | 'frontmatter'
111
+ | 'repoDefault'
112
+ | 'builtin';
113
+ }
114
+
115
+ /**
116
+ * Shape of `reviewPasses` in `.clud-bug.json`.
117
+ *
118
+ * We accept two layouts (per the plan):
119
+ *
120
+ * // (A) flat — repo-wide single setting
121
+ * "reviewPasses": {
122
+ * "count": 2,
123
+ * "mode": "cross-check",
124
+ * "applyTo": "all",
125
+ * "roles": [{ "name": "Beetle", "model": "..." }]
126
+ * }
127
+ *
128
+ * // (B) split — default + perSkill overrides
129
+ * "reviewPasses": {
130
+ * "default": { "count": 1, "mode": "cross-check" },
131
+ * "perSkill": { "security-audit": { "count": 3 } },
132
+ * "roles": [...]
133
+ * }
134
+ *
135
+ * (B) supersedes (A) when both are present; the flat keys are read as the
136
+ * `default` block. Roles are read from the outer object regardless.
137
+ */
138
+ export interface ReviewPassesConfig {
139
+ count?: number;
140
+ mode?: ReviewPassMode;
141
+ applyTo?: ApplyTo;
142
+ roles?: ReviewRole[];
143
+ default?: Partial<ReviewPassesEntry>;
144
+ perSkill?: Record<string, Partial<ReviewPassesEntry>>;
145
+ }
146
+
147
+ /** Frontmatter shape (subset) — only the bit D.2.5 cares about. */
148
+ export interface SkillReviewPassesFrontmatter {
149
+ count?: number;
150
+ mode?: ReviewPassMode;
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Constants
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /** Hard cap, enforced silently. Plan: count > 3 is brand-damaging cost. */
158
+ export const MAX_PASSES = 3;
159
+
160
+ /** Floor, enforced silently. Negative / zero / non-integer collapses to 1. */
161
+ export const MIN_PASSES = 1;
162
+
163
+ /** Built-in defaults — pre-config bottom of the precedence stack. */
164
+ export const BUILTIN_DEFAULT: ReviewPassesEntry = {
165
+ count: 1,
166
+ mode: 'cross-check',
167
+ };
168
+
169
+ /** Built-in roles, in order. Used when config omits the `roles` array. */
170
+ export const BUILTIN_ROLES: ReviewRole[] = [
171
+ { name: 'Beetle', model: 'anthropic/claude-sonnet-4.6', tier: 'beetle' },
172
+ { name: 'Wasp', model: 'anthropic/claude-opus-4.7', tier: 'wasp' },
173
+ { name: 'Mantis', model: 'anthropic/claude-opus-4.7', tier: 'mantis' },
174
+ ];
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // Helpers
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /** Clamp a `count` to `[MIN_PASSES, MAX_PASSES]`. NaN / negative → MIN. */
181
+ function clampCount(raw: unknown): number {
182
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return MIN_PASSES;
183
+ const truncated = Math.trunc(raw);
184
+ if (truncated < MIN_PASSES) return MIN_PASSES;
185
+ if (truncated > MAX_PASSES) return MAX_PASSES;
186
+ return truncated;
187
+ }
188
+
189
+ /** Returns the input mode if valid, else undefined. */
190
+ function asMode(raw: unknown): ReviewPassMode | undefined {
191
+ if (typeof raw !== 'string') return undefined;
192
+ return (REVIEW_PASS_MODES as readonly string[]).includes(raw)
193
+ ? (raw as ReviewPassMode)
194
+ : undefined;
195
+ }
196
+
197
+ /**
198
+ * Coerces an arbitrary fragment into a partial entry. Unknown fields and
199
+ * invalid types collapse to `undefined` so downstream merging is honest about
200
+ * which fields the layer actually supplied.
201
+ */
202
+ function coerceEntry(raw: unknown): Partial<ReviewPassesEntry> {
203
+ if (!raw || typeof raw !== 'object') return {};
204
+ const r = raw as Record<string, unknown>;
205
+ const out: Partial<ReviewPassesEntry> = {};
206
+ if (typeof r.count === 'number') {
207
+ out.count = clampCount(r.count);
208
+ }
209
+ const mode = asMode(r.mode);
210
+ if (mode) out.mode = mode;
211
+ return out;
212
+ }
213
+
214
+ /**
215
+ * Reads top-level `reviewPasses` from a parsed `.clud-bug.json` object.
216
+ * Tolerates absence + invalid types.
217
+ */
218
+ export function readReviewPassesConfig(
219
+ parsedJson: unknown,
220
+ ): ReviewPassesConfig | null {
221
+ if (!parsedJson || typeof parsedJson !== 'object') return null;
222
+ const root = parsedJson as Record<string, unknown>;
223
+ const raw = root.reviewPasses;
224
+ if (!raw || typeof raw !== 'object') return null;
225
+
226
+ const obj = raw as Record<string, unknown>;
227
+ const cfg: ReviewPassesConfig = {};
228
+
229
+ if (typeof obj.count === 'number') cfg.count = clampCount(obj.count);
230
+ const flatMode = asMode(obj.mode);
231
+ if (flatMode) cfg.mode = flatMode;
232
+
233
+ if (obj.applyTo === 'all' || obj.applyTo === 'shared-only') {
234
+ cfg.applyTo = obj.applyTo;
235
+ }
236
+
237
+ if (Array.isArray(obj.roles)) {
238
+ cfg.roles = obj.roles
239
+ .map((entry) => coerceRole(entry))
240
+ .filter((r): r is ReviewRole => r !== null);
241
+ }
242
+
243
+ if (obj.default && typeof obj.default === 'object') {
244
+ cfg.default = coerceEntry(obj.default);
245
+ }
246
+
247
+ if (obj.perSkill && typeof obj.perSkill === 'object') {
248
+ const out: Record<string, Partial<ReviewPassesEntry>> = {};
249
+ for (const [slug, value] of Object.entries(
250
+ obj.perSkill as Record<string, unknown>,
251
+ )) {
252
+ out[slug] = coerceEntry(value);
253
+ }
254
+ cfg.perSkill = out;
255
+ }
256
+
257
+ return cfg;
258
+ }
259
+
260
+ function coerceRole(raw: unknown): ReviewRole | null {
261
+ if (!raw || typeof raw !== 'object') return null;
262
+ const r = raw as Record<string, unknown>;
263
+ if (typeof r.name !== 'string' || typeof r.model !== 'string') return null;
264
+ if (!r.name.trim() || !r.model.trim()) return null;
265
+ return { name: r.name.trim(), model: r.model.trim() };
266
+ }
267
+
268
+ /**
269
+ * Re-parses raw SKILL.md frontmatter to extract the (optional)
270
+ * `review_passes` block. Returns null when the block is absent / malformed.
271
+ *
272
+ * We can't reuse the App skills-loader's `parseFrontmatter` — it strips
273
+ * unknown nested keys for security/forward-compat. This helper is scoped to
274
+ * one block: it tolerates `count` + `mode` inline scalars and nothing else.
275
+ *
276
+ * Raw frontmatter is whatever sits between the leading `---\n` and the
277
+ * matching `---\n` in the SKILL.md file. The caller (orchestrator) already
278
+ * has the parsed `body`/frontmatter from the skills loader; what we need here
279
+ * is the RAW source so we can pluck `review_passes` out.
280
+ */
281
+ export function extractSkillReviewPassesOverride(
282
+ rawSkillMd: string,
283
+ ): SkillReviewPassesFrontmatter | null {
284
+ const trimmed = rawSkillMd.replace(/^/, '');
285
+ const match = trimmed.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
286
+ if (!match) return null;
287
+ const block = match[1] ?? '';
288
+ // We want the `review_passes:` top-level key + its indented children
289
+ // (count, mode). Anything outside this block is ignored.
290
+ const lines = block.split(/\r?\n/);
291
+ let inBlock = false;
292
+ const out: SkillReviewPassesFrontmatter = {};
293
+ for (const line of lines) {
294
+ if (!inBlock) {
295
+ // Top-level key match: `review_passes:` with no value (block start).
296
+ if (/^review_passes\s*:\s*$/.test(line)) {
297
+ inBlock = true;
298
+ }
299
+ continue;
300
+ }
301
+ // Inside the block: keep going while the line is indented OR blank.
302
+ if (line.trim() === '') continue;
303
+ if (!/^\s/.test(line)) {
304
+ // De-dent → block ended.
305
+ break;
306
+ }
307
+ const inner = line.trim();
308
+ const colon = inner.indexOf(':');
309
+ if (colon === -1) continue;
310
+ const key = inner.slice(0, colon).trim();
311
+ const value = inner.slice(colon + 1).trim();
312
+ if (key === 'count') {
313
+ const n = Number(value);
314
+ if (Number.isFinite(n)) out.count = clampCount(n);
315
+ } else if (key === 'mode') {
316
+ // Strip surrounding quotes.
317
+ const m = asMode(value.replace(/^['"]|['"]$/g, ''));
318
+ if (m) out.mode = m;
319
+ }
320
+ }
321
+ // Return null when neither field landed — keeps the precedence resolver's
322
+ // "frontmatter layer supplied nothing" branch honest.
323
+ if (out.count === undefined && out.mode === undefined) return null;
324
+ return out;
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // Resolver
329
+ // ---------------------------------------------------------------------------
330
+
331
+ /** Minimal skill shape the resolver needs — decoupled from the App loader. */
332
+ export interface ReviewPlanSkill {
333
+ /** Skill slug (catalog identity). */
334
+ slug: string;
335
+ /** Parsed SKILL.md frontmatter (core shape). Only `review_mode` is read. */
336
+ frontmatter: SkillFrontmatter;
337
+ }
338
+
339
+ export interface ResolveReviewPassesInput {
340
+ /** Loaded skills, in catalog order. */
341
+ skills: ReviewPlanSkill[];
342
+ /**
343
+ * Raw SKILL.md text per slug (for the frontmatter `review_passes` block).
344
+ * Optional — when omitted, frontmatter override is treated as absent.
345
+ * Map key = slug; value = raw SKILL.md including the leading `---` block.
346
+ */
347
+ rawSkillMd?: Record<string, string>;
348
+ /** Parsed `.clud-bug.json` `reviewPasses` block. May be null/empty. */
349
+ config: ReviewPassesConfig | null;
350
+ }
351
+
352
+ export interface ResolveReviewPassesResult {
353
+ /** Resolved entry per skill, in input order. */
354
+ perSkill: ResolvedReviewPasses[];
355
+ /**
356
+ * Effective roles list — falls back to BUILTIN_ROLES when config omits.
357
+ * The aggregator + writeback use this for inline attribution.
358
+ */
359
+ roles: ReviewRole[];
360
+ /**
361
+ * `applyTo` scope. When `shared-only`, the orchestrator only multi-passes
362
+ * skills with `review_mode === 'shared'`. Defaults to `all`.
363
+ */
364
+ applyTo: ApplyTo;
365
+ }
366
+
367
+ /**
368
+ * Walks the precedence stack and produces an effective `{ count, mode }` per
369
+ * skill plus the resolved roles + apply scope.
370
+ *
371
+ * Pure function; no I/O. The orchestrator handles the actual fetch ordering
372
+ * upstream (config from the skills loader, raw SKILL.md from a separate fetch
373
+ * in D.2.5 — the loader returns `body` with frontmatter stripped, so the
374
+ * orchestrator passes the un-stripped source on the side).
375
+ */
376
+ export function resolveReviewPasses(
377
+ input: ResolveReviewPassesInput,
378
+ ): ResolveReviewPassesResult {
379
+ const { skills, rawSkillMd = {}, config } = input;
380
+
381
+ // 1. Repo-level default — collapses the two .clud-bug.json layouts.
382
+ const repoDefault: Partial<ReviewPassesEntry> = (() => {
383
+ if (!config) return {};
384
+ const flat: Partial<ReviewPassesEntry> = {};
385
+ if (config.count !== undefined) flat.count = clampCount(config.count);
386
+ if (config.mode) flat.mode = config.mode;
387
+ const explicit = config.default ?? {};
388
+ // `default` wins over flat — explicit always beats inferred.
389
+ return { ...flat, ...explicit };
390
+ })();
391
+
392
+ // 2. Roles + applyTo carry over uniformly.
393
+ const roles =
394
+ config?.roles && config.roles.length > 0 ? config.roles : BUILTIN_ROLES;
395
+ const applyTo: ApplyTo = config?.applyTo === 'shared-only' ? 'shared-only' : 'all';
396
+
397
+ const perSkill: ResolvedReviewPasses[] = skills.map((skill) => {
398
+ const fromPerSkill = config?.perSkill?.[skill.slug] ?? {};
399
+ const fromFrontmatter =
400
+ rawSkillMd[skill.slug] !== undefined
401
+ ? extractSkillReviewPassesOverride(rawSkillMd[skill.slug] ?? '') ?? {}
402
+ : {};
403
+
404
+ // 3. shared-only scope clamps non-shared skills to count = 1.
405
+ // Apply BEFORE precedence merging so even a perSkill override can't
406
+ // re-enable multi-pass for a dedicated skill in shared-only mode.
407
+ const sharedOnlyClamp: { count?: number } =
408
+ applyTo === 'shared-only' && skill.frontmatter.review_mode !== 'shared'
409
+ ? { count: 1 }
410
+ : {};
411
+
412
+ // Precedence: perSkill → frontmatter → repoDefault → builtin
413
+ const merged: ReviewPassesEntry = {
414
+ count:
415
+ sharedOnlyClamp.count ??
416
+ fromPerSkill.count ??
417
+ fromFrontmatter.count ??
418
+ repoDefault.count ??
419
+ BUILTIN_DEFAULT.count,
420
+ mode:
421
+ fromPerSkill.mode ??
422
+ fromFrontmatter.mode ??
423
+ repoDefault.mode ??
424
+ BUILTIN_DEFAULT.mode,
425
+ };
426
+
427
+ // Provenance — which precedence layer SUPPLIED count.
428
+ const source: ResolvedReviewPasses['source'] =
429
+ sharedOnlyClamp.count !== undefined
430
+ ? 'repoDefault' // applyTo lives at the repo layer
431
+ : fromPerSkill.count !== undefined
432
+ ? 'perSkill'
433
+ : fromFrontmatter.count !== undefined
434
+ ? 'frontmatter'
435
+ : repoDefault.count !== undefined
436
+ ? 'repoDefault'
437
+ : 'builtin';
438
+
439
+ return {
440
+ slug: skill.slug,
441
+ count: clampCount(merged.count),
442
+ mode: merged.mode,
443
+ roles,
444
+ source,
445
+ };
446
+ });
447
+
448
+ return { perSkill, roles, applyTo };
449
+ }
450
+
451
+ /**
452
+ * Returns the role for a given pass index, recycling when `roles.length` is
453
+ * smaller than the pass count. Pass 1 → roles[0], pass 2 → roles[1], etc.
454
+ * Empty roles array → synthesized `Pass N` / requested model fallback.
455
+ *
456
+ * The orchestrator calls this for every (skill, passIndex) combination.
457
+ */
458
+ export function roleForPass(
459
+ roles: ReviewRole[],
460
+ passIndex: number,
461
+ fallbackModel: string,
462
+ ): ReviewRole {
463
+ if (roles.length === 0) {
464
+ return { name: `Pass ${passIndex + 1}`, model: fallbackModel };
465
+ }
466
+ const i = passIndex % roles.length;
467
+ return roles[i] as ReviewRole;
468
+ }
469
+
470
+ /**
471
+ * Truthy when ANY resolved skill needs more than one pass. Used by the
472
+ * orchestrator to decide whether to invoke the aggregator at all (single-pass
473
+ * results render via the D.2.0 path verbatim).
474
+ */
475
+ export function anyMultiPass(resolved: ResolvedReviewPasses[]): boolean {
476
+ return resolved.some((r) => r.count > 1);
477
+ }
478
+
479
+ /**
480
+ * Total pass count across every skill — the cost-gate input. Used by
481
+ * `./budget-plan.ts`'s Layer-1 estimator.
482
+ */
483
+ export function totalPassCount(resolved: ResolvedReviewPasses[]): number {
484
+ return resolved.reduce((sum, r) => sum + r.count, 0);
485
+ }