@simonren/quorum 0.9.1 → 0.11.1

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 (68) hide show
  1. package/README.md +91 -48
  2. package/commands/multi-consult.md +47 -72
  3. package/commands/multi-review.md +68 -99
  4. package/dist/adapters/base.d.ts +53 -70
  5. package/dist/adapters/base.js +21 -79
  6. package/dist/adapters/claude.d.ts +38 -17
  7. package/dist/adapters/claude.js +93 -185
  8. package/dist/adapters/cli-adapter.d.ts +78 -0
  9. package/dist/adapters/cli-adapter.js +220 -0
  10. package/dist/adapters/codex.d.ts +18 -13
  11. package/dist/adapters/codex.js +64 -200
  12. package/dist/adapters/gemini.d.ts +45 -21
  13. package/dist/adapters/gemini.js +81 -152
  14. package/dist/adapters/index.d.ts +8 -5
  15. package/dist/adapters/index.js +7 -8
  16. package/dist/config.d.ts +98 -28
  17. package/dist/config.js +44 -25
  18. package/dist/consult-prompt.d.ts +6 -5
  19. package/dist/consult-prompt.js +48 -23
  20. package/dist/decoders/claude.d.ts +6 -0
  21. package/dist/decoders/claude.js +10 -1
  22. package/dist/doctor.d.ts +20 -0
  23. package/dist/doctor.js +91 -0
  24. package/dist/executor.d.ts +58 -46
  25. package/dist/executor.js +218 -129
  26. package/dist/guards.d.ts +29 -0
  27. package/dist/guards.js +72 -0
  28. package/dist/handoff.d.ts +79 -229
  29. package/dist/handoff.js +411 -402
  30. package/dist/index.d.ts +8 -12
  31. package/dist/index.js +81 -106
  32. package/dist/integrity.d.ts +16 -0
  33. package/dist/integrity.js +49 -0
  34. package/dist/sections.d.ts +22 -0
  35. package/dist/sections.js +31 -0
  36. package/dist/server.d.ts +9 -0
  37. package/dist/server.js +36 -0
  38. package/dist/tools/consult.d.ts +17 -76
  39. package/dist/tools/consult.js +72 -188
  40. package/dist/tools/format.d.ts +35 -0
  41. package/dist/tools/format.js +85 -0
  42. package/dist/tools/review.d.ts +55 -0
  43. package/dist/tools/review.js +120 -0
  44. package/dist/types.d.ts +20 -103
  45. package/dist/types.js +18 -29
  46. package/package.json +7 -4
  47. package/dist/cli/check.d.ts +0 -20
  48. package/dist/cli/check.js +0 -78
  49. package/dist/cli/codex.d.ts +0 -11
  50. package/dist/cli/codex.js +0 -255
  51. package/dist/cli/gemini.d.ts +0 -12
  52. package/dist/cli/gemini.js +0 -253
  53. package/dist/context.d.ts +0 -1538
  54. package/dist/context.js +0 -383
  55. package/dist/decoders/gemini.d.ts +0 -33
  56. package/dist/decoders/gemini.js +0 -58
  57. package/dist/errors.d.ts +0 -46
  58. package/dist/errors.js +0 -198
  59. package/dist/pipeline.d.ts +0 -135
  60. package/dist/pipeline.js +0 -462
  61. package/dist/prompt-v2.d.ts +0 -38
  62. package/dist/prompt-v2.js +0 -391
  63. package/dist/prompt.d.ts +0 -71
  64. package/dist/prompt.js +0 -309
  65. package/dist/schema.d.ts +0 -660
  66. package/dist/schema.js +0 -536
  67. package/dist/tools/feedback.d.ts +0 -91
  68. package/dist/tools/feedback.js +0 -117
package/dist/handoff.js CHANGED
@@ -1,106 +1,47 @@
1
1
  /**
2
- * Review Handoff Protocol
3
- *
4
- * Defines the minimal, targeted information that should flow from CC to reviewers.
2
+ * Review handoff protocol — what flows from Claude Code (CC) to a reviewer,
3
+ * and the prompts built from it.
5
4
  *
6
5
  * Philosophy:
7
- * - Reviewers have filesystem access - don't duplicate what they can discover
8
- * - Pass ONLY what CC uniquely knows: uncertainties, decisions, questions
9
- * - Let reviewer use their tools (file reading) for actual code
10
- * - Do NOT assume git — working directory may not be a git repo
11
- */
12
- import { z } from 'zod';
13
- // =============================================================================
14
- // HANDOFF SCHEMA - What CC Passes to Reviewer
15
- // =============================================================================
16
- /**
17
- * Uncertainty that CC has - things the reviewer should verify
18
- */
19
- export const UncertaintySchema = z.object({
20
- topic: z.string().describe('What CC is uncertain about'),
21
- question: z.string().describe('The specific question'),
22
- ccAssumption: z.string().optional().describe("What CC assumed/did - reviewer should verify"),
23
- relevantFiles: z.array(z.string()).optional().describe('Files related to this uncertainty'),
24
- severity: z.enum(['critical', 'important', 'minor']).optional(),
25
- });
26
- /**
27
- * Decision CC made - for reviewer to evaluate
28
- */
29
- export const DecisionSchema = z.object({
30
- decision: z.string().describe('What CC decided'),
31
- rationale: z.string().describe('Why CC chose this'),
32
- alternatives: z.array(z.string()).optional().describe('Other options considered'),
33
- tradeoffs: z.string().optional().describe('Known tradeoffs of this choice'),
34
- });
35
- /**
36
- * Question CC wants the reviewer to answer
37
- */
38
- export const QuestionSchema = z.object({
39
- question: z.string(),
40
- context: z.string().optional(),
41
- ccGuess: z.string().optional().describe("CC's best guess - for comparison"),
42
- });
43
- /**
44
- * The complete handoff from CC to reviewer
45
- * Intentionally minimal - only what CC uniquely knows
46
- */
47
- export const HandoffSchema = z.object({
48
- // Working directory (required for filesystem access)
49
- workingDir: z.string(),
50
- // Brief summary of what CC did (1-3 sentences)
51
- summary: z.string().describe('Brief: what CC did and why'),
52
- // CC's uncertainties - things reviewer should verify
53
- uncertainties: z.array(UncertaintySchema).optional(),
54
- // Key decisions CC made - for reviewer to evaluate
55
- decisions: z.array(DecisionSchema).optional(),
56
- // Specific questions CC wants answered
57
- questions: z.array(QuestionSchema).optional(),
58
- // Files to prioritize (if CC knows which are most important)
59
- priorityFiles: z.array(z.string()).optional(),
60
- // Focus areas (security, performance, etc.)
61
- focusAreas: z.array(z.string()).optional(),
62
- // Overall confidence (0-1)
63
- confidence: z.number().min(0).max(1).optional(),
64
- // Custom instructions from user
65
- customInstructions: z.string().optional(),
66
- });
67
- /**
68
- * Strong generic role - when no specific focus is given
69
- * This is NOT a weak fallback - it's a comprehensive reviewer
6
+ * - Reviewers have the filesystem; CC has the conversation. The brief carries
7
+ * only what CC uniquely knows: what it did, the bar it must clear, its
8
+ * uncertainties, questions, decisions, and acknowledged gaps.
9
+ * - Reviewers verify against the code, they do not trust the brief.
10
+ * - Reviewer output goes back to CC for verification and synthesis, so it is
11
+ * asked for in a fixed markdown structure that CC can cross-reference across
12
+ * models and passes.
70
13
  */
14
+ import { OUTPUT_TYPES } from './types.js';
15
+ /** Strong generic role when no focus is given — a comprehensive reviewer, not a weak fallback. */
71
16
  export const COMPREHENSIVE_REVIEWER = {
72
17
  id: 'comprehensive',
73
18
  name: 'Comprehensive Code Reviewer',
74
19
  description: 'Systematic review across all dimensions, prioritizing high-impact issues',
75
20
  isGeneric: true,
76
21
  applicableFocusAreas: [],
77
- systemPrompt: `Senior staff engineer. Be skeptical — catch mistakes, don't rubber-stamp.
78
- Priority: correctness > security > performance > maintainability.
79
- Only report real issues with evidence.`,
22
+ systemPrompt: `Senior staff engineer doing the review a careful human would do before merging.
23
+ Priority: correctness > security and data integrity > behaviour under failure (retries, partial writes, concurrency) > performance > maintainability.
24
+ Skeptical by default: the brief describes what CC believes it did — verify against the code before agreeing with any of it.
25
+ Report only real issues with evidence. Do not rubber-stamp; do not pad.`,
80
26
  };
81
- /**
82
- * Change-focused reviewer - specifically for reviewing diffs
83
- */
27
+ /** Change-focused reviewer — used when the requested focus areas map to no specialist. */
84
28
  export const CHANGE_FOCUSED_REVIEWER = {
85
29
  id: 'change_focused',
86
30
  name: 'Change Reviewer',
87
- description: 'Focused on reviewing the delta - what changed and its implications',
31
+ description: 'Focused on the delta — what changed and its implications',
88
32
  isGeneric: true,
89
33
  applicableFocusAreas: [],
90
- systemPrompt: `Change reviewer. Focus on: goal achievement, regressions, edge cases, side effects.
34
+ systemPrompt: `Change reviewer. Does the change achieve its stated goal, what does it regress, which edge cases and side effects are unhandled.
91
35
  Reference specific lines in the source files.`,
92
36
  };
93
- /**
94
- * Specialized roles - when specific focus is requested
95
- */
96
37
  export const SECURITY_REVIEWER = {
97
38
  id: 'security',
98
39
  name: 'Security Auditor',
99
40
  description: 'Deep security analysis with OWASP/CWE focus',
100
41
  isGeneric: false,
101
42
  applicableFocusAreas: ['security'],
102
- systemPrompt: `Security auditor. Focus on injection, auth bypass, data exposure, input validation.
103
- Rate by exploitability + impact.`,
43
+ systemPrompt: `Security auditor. Injection, auth/authz bypass, trust-boundary and tenant-isolation gaps, secrets and data exposure, input validation, path traversal, SSRF, unsafe deserialization.
44
+ Rate by exploitability and impact; give the attack scenario, not just the pattern.`,
104
45
  };
105
46
  export const PERFORMANCE_REVIEWER = {
106
47
  id: 'performance',
@@ -108,17 +49,17 @@ export const PERFORMANCE_REVIEWER = {
108
49
  description: 'Performance and efficiency analysis',
109
50
  isGeneric: false,
110
51
  applicableFocusAreas: ['performance', 'scalability'],
111
- systemPrompt: `Performance engineer. Focus on complexity (Big-O), N+1 queries, memory, blocking I/O.
112
- Provide complexity analysis and specific optimizations.`,
52
+ systemPrompt: `Performance engineer. Algorithmic complexity (state the Big-O), N+1 and unindexed queries, blocking I/O on hot or async paths, unbounded memory growth, missing caching.
53
+ Quantify the impact and name the concrete optimization.`,
113
54
  };
114
55
  export const ARCHITECTURE_REVIEWER = {
115
56
  id: 'architecture',
116
57
  name: 'Software Architect',
117
- description: 'Design patterns, structure, and maintainability',
58
+ description: 'Design, structure, and maintainability',
118
59
  isGeneric: false,
119
60
  applicableFocusAreas: ['architecture', 'maintainability'],
120
- systemPrompt: `Software architect. Focus on SOLID, coupling/cohesion, abstractions, patterns.
121
- Suggest refactorings with specific patterns.`,
61
+ systemPrompt: `Software architect. Coupling and cohesion, layering and dependency direction, leaky abstractions, misused or missing patterns, changes that make the next change harder.
62
+ Name the principle violated and the refactoring that fixes it.`,
122
63
  };
123
64
  export const CORRECTNESS_REVIEWER = {
124
65
  id: 'correctness',
@@ -126,11 +67,17 @@ export const CORRECTNESS_REVIEWER = {
126
67
  description: 'Logic errors, edge cases, and bug detection',
127
68
  isGeneric: false,
128
69
  applicableFocusAreas: ['correctness', 'testing'],
129
- systemPrompt: `Correctness analyst. Focus on logic errors, edge cases, race conditions, error handling.
130
- Provide triggering inputs and expected vs actual behavior.
131
- For significant bugs, suggest a concrete regression test (name, inputs, expected output).`,
70
+ systemPrompt: `Correctness analyst. Logic errors, off-by-ones, null/empty/boundary handling, ordering and race conditions, error propagation and silent failures.
71
+ Give the triggering input and expected vs actual behaviour. For significant bugs, sketch a regression test (name, inputs, expected output).`,
72
+ };
73
+ export const ADVERSARIAL_REVIEWER = {
74
+ id: 'adversarial',
75
+ name: 'Adversarial Reviewer',
76
+ description: 'Actively tries to break confidence in the change — challenges assumptions and decisions, not just bugs',
77
+ isGeneric: false,
78
+ applicableFocusAreas: [],
79
+ systemPrompt: `Senior staff engineer performing an adversarial review. Your job is to break confidence in the change, not to validate it. A standard reviewer is looking for bugs in parallel; you look for the assumptions, decisions, and failure paths a bug hunt would miss.`,
132
80
  };
133
- // All roles indexed by ID
134
81
  export const ROLES = {
135
82
  comprehensive: COMPREHENSIVE_REVIEWER,
136
83
  change_focused: CHANGE_FOCUSED_REVIEWER,
@@ -140,16 +87,12 @@ export const ROLES = {
140
87
  correctness: CORRECTNESS_REVIEWER,
141
88
  };
142
89
  /**
143
- * Select and compose roles based on focus areas.
144
- *
145
- * When multiple focus areas map to different roles (e.g. security + performance),
146
- * composes them into a single role with merged prompts instead of picking one winner.
90
+ * Select and compose roles from focus areas. Multiple areas mapping to
91
+ * different specialists compose into one role with merged prompts.
147
92
  */
148
93
  export function selectRole(focusAreas) {
149
- if (!focusAreas || focusAreas.length === 0) {
94
+ if (!focusAreas || focusAreas.length === 0)
150
95
  return COMPREHENSIVE_REVIEWER;
151
- }
152
- // Collect all unique matching roles (preserving insertion order)
153
96
  const matched = new Map();
154
97
  for (const focus of focusAreas) {
155
98
  for (const role of Object.values(ROLES)) {
@@ -162,46 +105,266 @@ export function selectRole(focusAreas) {
162
105
  return CHANGE_FOCUSED_REVIEWER;
163
106
  if (matched.size === 1)
164
107
  return [...matched.values()][0];
165
- // Compose multiple roles into one
166
108
  const roles = [...matched.values()];
167
109
  return {
168
- id: roles.map(r => r.id).join('+'),
169
- name: roles.map(r => r.name).join(' + '),
170
- description: roles.map(r => r.description).join('; '),
110
+ id: roles.map((r) => r.id).join('+'),
111
+ name: roles.map((r) => r.name).join(' + '),
112
+ description: roles.map((r) => r.description).join('; '),
171
113
  isGeneric: false,
172
114
  applicableFocusAreas: focusAreas,
173
- systemPrompt: roles.map(r => `**As ${r.name}:** ${r.systemPrompt}`).join('\n'),
115
+ systemPrompt: roles.map((r) => `**As ${r.name}:** ${r.systemPrompt}`).join('\n'),
174
116
  };
175
117
  }
176
118
  // =============================================================================
177
- // ADVERSARIAL REVIEWER — Challenge mode for multi_review
119
+ // FOCUS-AREA CHECKLISTS
178
120
  // =============================================================================
179
- export const ADVERSARIAL_REVIEWER = {
180
- id: 'adversarial',
181
- name: 'Adversarial Reviewer',
182
- description: 'Actively tries to break confidence in the change — challenges assumptions, not just bugs',
183
- isGeneric: false,
184
- applicableFocusAreas: [],
185
- systemPrompt: `Senior staff engineer performing an adversarial review. Your job is to break confidence in the change, not to validate it.`,
121
+ const FOCUS_CHECKLISTS = {
122
+ security: `Check for:
123
+ - Injection vulnerabilities (SQL, NoSQL, command, template, XSS)
124
+ - Auth/authorization bypass, session and token handling flaws, missing tenant isolation
125
+ - Sensitive data exposure, secrets in code or logs, missing encryption
126
+ - Input validation gaps (type, range, format, size)
127
+ - Path traversal, SSRF, unsafe deserialization
128
+ For each: CWE ID if applicable, attack scenario, severity by impact and exploitability.`,
129
+ performance: `Check for:
130
+ - Algorithmic complexity (provide Big-O notation)
131
+ - N+1 queries, missing indexes, unbounded result sets
132
+ - Blocking I/O in async contexts, synchronous work on hot paths
133
+ - Memory leaks, unbounded allocations, large object retention
134
+ - Missing caching/memoization, repeated expensive operations
135
+ For each: Big-O analysis, estimated impact, concrete optimization.`,
136
+ architecture: `Check for:
137
+ - SOLID violations, high coupling between modules, low cohesion within them
138
+ - Layering violations, circular dependencies, wrong dependency direction
139
+ - Anti-patterns (god classes, deep nesting, magic numbers, leaky abstractions)
140
+ - Missing or misused design patterns
141
+ For each: the principle violated, the refactoring, the maintainability impact.`,
142
+ correctness: `Check for:
143
+ - Off-by-one errors, incorrect conditionals, wrong operators
144
+ - Null/undefined handling, empty collections, boundary conditions
145
+ - Race conditions, ordering assumptions, deadlock potential, state inconsistency
146
+ - Uncaught exceptions, silent failures, incorrect error propagation
147
+ For each: triggering input, expected vs actual behaviour.
148
+ For significant bugs: suggest a concrete regression test.`,
149
+ testing: `Check for:
150
+ - Missing test coverage for changed code paths
151
+ - Tests that pass for the wrong reason (tautologies, mocked-away logic)
152
+ - Non-deterministic tests (timing, ordering, randomness)
153
+ - Missing edge-case tests (null, empty, boundary, error paths)
154
+ For significant gaps: suggest a concrete test (name, inputs, expected output).`,
155
+ scalability: `Check for:
156
+ - Algorithmic complexity that degrades at scale (provide Big-O)
157
+ - Unbounded growth (queues, caches, in-memory collections)
158
+ - Missing pagination, rate limiting, or backpressure
159
+ - Single points of contention (locks, shared state, single-threaded bottlenecks)
160
+ For each: estimated impact at 10x/100x current load.`,
161
+ maintainability: `Check for:
162
+ - God classes, deep nesting (>3 levels), magic numbers
163
+ - Tight coupling between modules, leaky abstractions
164
+ - Duplication that should be extracted
165
+ - Missing or misleading comments on non-obvious logic
166
+ For each: specific refactoring suggestion with rationale.`,
167
+ documentation: `Check for:
168
+ - Public API functions missing doc comments
169
+ - Outdated or misleading comments that contradict the code
170
+ - Missing README updates for changed behaviour
171
+ - Undocumented configuration, environment variables, or flags
172
+ For each: what specifically should be documented and where.`,
173
+ };
174
+ // =============================================================================
175
+ // PROMPT SECTIONS SHARED BY BOTH PASSES
176
+ // =============================================================================
177
+ const TASK_BY_OUTPUT_TYPE = {
178
+ implementation: 'Code changes CC made in the working directory. Locate the change (git diff if the directory is a repository, otherwise PRIORITY FILES), read it in full, then judge it against the acceptance bar.',
179
+ plan: 'A plan CC wrote before implementing. Nothing has changed on disk yet. Judge whether the plan is complete, correct against the code as it exists today, and safe to execute; point at existing code that contradicts it.',
180
+ findings: 'Findings CC produced from analysis (an audit, a bug investigation, a root-cause claim). Verify each finding against the code: confirm it, refute it, or add what CC missed.',
181
+ analysis: 'An analysis CC wrote up. Check its reasoning and evidence against the code and flag conclusions the code does not support.',
182
+ proposal: 'A design proposal. Judge feasibility against the existing code, the alternatives it dismisses, and the risks it does not mention.',
186
183
  };
184
+ const DEFAULT_BAR = 'None stated — judge against: correct, safe to merge, no regressions.';
185
+ /** Section headers the reviewer must emit, in order. */
186
+ export const REVIEW_RESPONSE_SECTIONS = ['Verdict', 'Findings', 'Answers', 'Decisions'];
187
+ /** The subset whose absence marks a response as drifted. */
188
+ export const REQUIRED_REVIEW_SECTIONS = ['Verdict', 'Findings'];
189
+ function renderTask(handoff) {
190
+ const kind = TASK_BY_OUTPUT_TYPE[handoff.outputType ?? 'implementation'];
191
+ const base = handoff.baseRef
192
+ ? `\n\nThe working tree is clean; the change is \`git diff ${handoff.baseRef}...HEAD\` (\`--stat\` first, then the files).`
193
+ : '';
194
+ return `## WHAT YOU ARE REVIEWING
195
+
196
+ ${kind}${base}
197
+
198
+ ## THE BRIEF FROM CC
199
+
200
+ Working directory: \`${handoff.workingDir}\`
201
+
202
+ **Summary:** ${handoff.summary}
203
+
204
+ **Acceptance bar:** ${handoff.bar ?? DEFAULT_BAR}`;
205
+ }
206
+ function renderGroundRules() {
207
+ return `## GROUND RULES
208
+
209
+ - Read-only. Do not create, modify, or delete files. Do not run anything that changes state: no git commit/checkout/stash/reset/push, no installs, no formatters, no test runs that write.
210
+ - If the directory is a git repository, \`git status\`, \`git diff\`, \`git diff --cached\` and \`git log -3 --stat\` are the fastest way to find the change; when the brief names a base ref, \`git diff <base>...HEAD\` is the change. If it is not a repository, or the tree is clean and no base ref is given, work from PRIORITY FILES and the brief.
211
+ - Verify before you report. Open the file, quote the line. A finding without a location and evidence is not a finding.
212
+ - Stay in scope: the change and the code it touches. Report a pre-existing problem elsewhere only if the change activates it or the bar depends on it, and label it "pre-existing".
213
+ - Do not restate the brief, do not praise, no preamble. Your reader is CC, which will verify every claim against the code and synthesize a verdict across several reviewers.`;
214
+ }
215
+ function renderUncertainties(handoff) {
216
+ if (!handoff.uncertainties || handoff.uncertainties.length === 0)
217
+ return null;
218
+ const items = handoff.uncertainties.map((u, i) => {
219
+ const tag = u.weight ? ` [${u.weight}]` : '';
220
+ // When the topic is just the question minus its punctuation, one line is enough.
221
+ const topicIsQuestion = u.question.startsWith(u.topic) && u.question.length - u.topic.length <= 1;
222
+ const lines = topicIsQuestion
223
+ ? [`### ${i + 1}. ${u.question}${tag}`]
224
+ : [`### ${i + 1}. ${u.topic}${tag}`, `- Question: ${u.question}`];
225
+ if (u.ccAssumption)
226
+ lines.push(`- CC assumed: ${u.ccAssumption}`);
227
+ if (u.relevantFiles && u.relevantFiles.length > 0)
228
+ lines.push(`- Files: ${u.relevantFiles.join(', ')}`);
229
+ return lines.join('\n');
230
+ });
231
+ return `## CC'S UNCERTAINTIES — verify these first
232
+
233
+ Load-bearing items decide the verdict; incidental items are worth a look but do not block.
234
+
235
+ ${items.join('\n\n')}`;
236
+ }
237
+ function renderQuestions(handoff) {
238
+ if (!handoff.questions || handoff.questions.length === 0)
239
+ return null;
240
+ const items = handoff.questions.map((q, i) => {
241
+ const lines = [`${i + 1}. **${q.question}**`];
242
+ if (q.context)
243
+ lines.push(` Context: ${q.context}`);
244
+ if (q.ccGuess)
245
+ lines.push(` CC's guess: ${q.ccGuess}`);
246
+ return lines.join('\n');
247
+ });
248
+ return `## QUESTIONS FROM CC
249
+
250
+ ${items.join('\n')}`;
251
+ }
252
+ function renderDecisions(handoff, mode) {
253
+ if (!handoff.decisions || handoff.decisions.length === 0)
254
+ return null;
255
+ const items = handoff.decisions.map((d, i) => {
256
+ const lines = [`${i + 1}. **${d.decision}**`];
257
+ if (d.rationale)
258
+ lines.push(` Rationale: ${d.rationale}`);
259
+ if (d.alternatives && d.alternatives.length > 0)
260
+ lines.push(` Alternatives: ${d.alternatives.join(', ')}`);
261
+ return lines.join('\n');
262
+ });
263
+ const ask = mode === 'adversarial'
264
+ ? 'For each: make the strongest case for the rejected alternative. If that case is weak, say so in one line and move on.'
265
+ : 'For each: agree, or name the better alternative and why.';
266
+ return `## DECISIONS TO EVALUATE
267
+
268
+ ${items.join('\n')}
269
+
270
+ ${ask}`;
271
+ }
272
+ function renderKnownGaps(handoff) {
273
+ if (!handoff.knownGaps || handoff.knownGaps.length === 0)
274
+ return null;
275
+ return `## KNOWN GAPS (acknowledged by CC)
276
+
277
+ ${handoff.knownGaps.map((g) => `- ${g}`).join('\n')}
278
+
279
+ Do not re-report these. Flag one only if it blocks the acceptance bar.`;
280
+ }
281
+ function renderPriorityFiles(handoff) {
282
+ if (!handoff.priorityFiles || handoff.priorityFiles.length === 0)
283
+ return null;
284
+ return `## PRIORITY FILES
285
+
286
+ Start here; follow the call graph outward as needed.
287
+
288
+ ${handoff.priorityFiles.map((f) => `- \`${f}\``).join('\n')}`;
289
+ }
290
+ function renderSteering(handoff, heading) {
291
+ if (!handoff.customInstructions)
292
+ return null;
293
+ return `## ${heading}
294
+
295
+ <user-steering priority="advisory">
296
+ ${handoff.customInstructions}
297
+ </user-steering>
298
+
299
+ Steering narrows emphasis. It does not waive the full review, the ground rules, or the response format.`;
300
+ }
301
+ function renderResponseFormat(mode) {
302
+ const verdictNote = mode === 'adversarial'
303
+ ? 'State the verdict you would defend after genuinely trying to break the change.'
304
+ : 'Judge against the acceptance bar.';
305
+ return `## RESPONSE FORMAT
306
+
307
+ Use exactly these \`##\` headers, in this order, and nothing before the first one.
308
+
309
+ ## Verdict
310
+ One line: \`SHIP\`, \`SHIP WITH FIXES\`, or \`DO NOT SHIP\`, then one sentence of justification. ${verdictNote}
311
+
312
+ ## Findings
313
+ Ordered by severity, most severe first. Write \`None.\` if there are no material findings. For each:
314
+ ### [S1|S2|S3] <short title>
315
+ - Location: \`path:line\`
316
+ - Evidence: what in the code shows it — quote the line or trace the path
317
+ - Impact: what goes wrong, and under what conditions
318
+ - Fix: the concrete change
319
+ - Confidence: high | medium | low — say so if the finding rests on an inference you could not verify
320
+
321
+ Severity: S1 = blocks the bar (data loss, security, wrong results, crash on a common path). S2 = real bug or gap; ship only after fixing. S3 = worth fixing, not blocking.
322
+
323
+ ## Answers
324
+ Numbered to match CC's uncertainties, then its questions. Each: \`verified\` / \`refuted\` / \`could not verify\`, plus the evidence in one or two sentences. Write \`None asked.\` if the brief had neither.
325
+
326
+ ## Decisions
327
+ One line per decision in the brief: \`agree\`, or \`disagree — <better alternative and why>\`. Write \`None listed.\` if the brief listed none.`;
328
+ }
329
+ function joinSections(sections) {
330
+ return sections.filter((s) => typeof s === 'string' && s.length > 0).join('\n\n');
331
+ }
332
+ /** Standard review pass: find bugs and gaps, judge against the bar. */
333
+ export function buildHandoffPrompt(options) {
334
+ const { handoff } = options;
335
+ const role = options.role ?? selectRole(handoff.focusAreas);
336
+ let checklist = null;
337
+ if (handoff.focusAreas && handoff.focusAreas.length > 0) {
338
+ const lists = handoff.focusAreas.map((f) => FOCUS_CHECKLISTS[f]).filter((c) => !!c);
339
+ if (lists.length > 0)
340
+ checklist = `## REVIEW CHECKLIST\n\n${lists.join('\n\n')}`;
341
+ }
342
+ return joinSections([
343
+ `# ROLE: ${role.name}\n\n${role.systemPrompt}`,
344
+ checklist,
345
+ renderTask(handoff),
346
+ renderGroundRules(),
347
+ renderUncertainties(handoff),
348
+ renderQuestions(handoff),
349
+ renderDecisions(handoff, 'standard'),
350
+ renderKnownGaps(handoff),
351
+ renderPriorityFiles(handoff),
352
+ renderSteering(handoff, 'USER STEERING'),
353
+ renderResponseFormat('standard'),
354
+ ]);
355
+ }
187
356
  /**
188
- * Build an adversarial handoff prompt with challenge-mode stance sections.
357
+ * Adversarial pass: break confidence in the change.
189
358
  *
190
- * Block structure ported from openai/codex-plugin-cc's adversarial-review
191
- * prompt: tagged XML blocks (operating_stance, attack_surface, review_method,
192
- * finding_bar, calibration_rules, grounding_rules, final_check) so the prompt
193
- * has stable internal structure the reviewer can lean on. CC's handoff
194
- * sections (uncertainties / decisions / questions / focus / files / focus
195
- * instructions) are layered on after as our differentiator.
359
+ * The tagged blocks (operating_stance, attack_surface, review_method,
360
+ * finding_bar, calibration_rules, grounding_rules, final_check) are ported
361
+ * from openai/codex-plugin-cc's adversarial-review prompt so the reviewer has
362
+ * a stable operating contract; CC's brief is layered on after.
196
363
  */
197
364
  export function buildAdversarialHandoffPrompt(options) {
198
365
  const { handoff } = options;
199
366
  const role = ADVERSARIAL_REVIEWER;
200
- const sections = [];
201
- // SECTION 1: ROLE
202
- sections.push(`# ROLE: ${role.name}\n\n${role.systemPrompt}`);
203
- // SECTION 2: ADVERSARIAL STANCE — tagged blocks form the operating contract
204
- sections.push(`<operating_stance>
367
+ const stance = `<operating_stance>
205
368
  Default to skepticism.
206
369
  Assume the change can fail in subtle, high-cost, or user-visible ways until the evidence says otherwise.
207
370
  Do not give credit for good intent, partial fixes, or likely follow-up work.
@@ -217,23 +380,26 @@ Prioritize the kinds of failures that are expensive, dangerous, or hard to detec
217
380
  - empty-state, null, timeout, and degraded dependency behavior
218
381
  - version skew, schema drift, migration hazards, and compatibility regressions
219
382
  - observability gaps that would hide failure or make recovery harder
383
+ - the acceptance bar itself: is it the right bar, and what does it leave out?
384
+ - the decisions in the brief: the strongest case for each rejected alternative
220
385
  </attack_surface>
221
386
 
222
387
  <review_method>
223
388
  Actively try to disprove the change.
224
389
  Look for violated invariants, missing guards, unhandled failure paths, and assumptions that stop being true under stress.
225
390
  Trace how bad inputs, retries, concurrent actions, or partially completed operations move through the code.
391
+ Treat every claim in the brief as a hypothesis: find the code that would make it false.
226
392
  If the user supplied a focus area, weight it heavily, but still report any other material issue you can defend.
227
393
  </review_method>
228
394
 
229
395
  <finding_bar>
230
396
  Report only material findings.
231
397
  Do not include style feedback, naming feedback, low-value cleanup, or speculative concerns without evidence.
232
- Each finding must answer:
233
- 1. What can go wrong?
234
- 2. Why is this code path vulnerable?
235
- 3. What is the likely impact?
236
- 4. What concrete change would reduce the risk?
398
+ Each finding must answer, in the response format below:
399
+ 1. What can go wrong? (Impact)
400
+ 2. Why is this code path exposed? (Evidence)
401
+ 3. How likely and how bad is it? (Impact, Confidence)
402
+ 4. What concrete change would reduce the risk? (Fix)
237
403
  </finding_bar>
238
404
 
239
405
  <calibration_rules>
@@ -255,298 +421,158 @@ Before finalizing, check that each finding is:
255
421
  - tied to a concrete code location
256
422
  - plausible under a real failure scenario
257
423
  - actionable for an engineer fixing the issue
258
- </final_check>`);
259
- // SECTION 3: TASK (same as standard)
260
- sections.push(`## YOUR TASK
261
-
262
- Review code in \`${handoff.workingDir}\`.
263
-
264
- **Summary:** ${handoff.summary}${handoff.confidence !== undefined && handoff.confidence < 0.9 ? `\n**CC Confidence:** ${Math.round(handoff.confidence * 100)}% — verify weak areas` : ''}
265
-
266
- **IMPORTANT:**
267
- - This is a READ-ONLY review. Do NOT create, modify, or delete any files. Only read files to verify claims.
268
- - Do NOT assume a git repository exists. Do NOT run git commands. Read files directly from the filesystem.`);
269
- // SECTION 4: CC'S UNCERTAINTIES
270
- if (handoff.uncertainties && handoff.uncertainties.length > 0) {
271
- sections.push(`## CC'S UNCERTAINTIES
272
-
273
- ${handoff.uncertainties.map((u, i) => `### ${i + 1}. ${u.topic} ${u.severity === 'critical' ? '⚠️' : ''}
274
- - **Question:** ${u.question}
275
- ${u.ccAssumption ? `- **CC assumed:** ${u.ccAssumption}` : ''}
276
- ${u.relevantFiles ? `- **Files:** ${u.relevantFiles.join(', ')}` : ''}`).join('\n\n')}`);
277
- }
278
- // SECTION 5: SPECIFIC QUESTIONS
279
- if (handoff.questions && handoff.questions.length > 0) {
280
- sections.push(`## QUESTIONS FROM CC
281
-
282
- ${handoff.questions.map((q, i) => `${i + 1}. **${q.question}**
283
- ${q.context ? `Context: ${q.context}` : ''}
284
- ${q.ccGuess ? `CC Guess: ${q.ccGuess}` : ''}`).join('\n')}`);
285
- }
286
- // SECTION 6: DECISIONS TO EVALUATE
287
- if (handoff.decisions && handoff.decisions.length > 0) {
288
- sections.push(`## DECISIONS TO EVALUATE
289
-
290
- ${handoff.decisions.map((d, i) => `${i + 1}. **${d.decision}**${d.rationale ? `\n Rationale: ${d.rationale}` : ''}${d.alternatives ? `\n Alternatives: ${d.alternatives.join(', ')}` : ''}`).join('\n')}`);
291
- }
292
- // SECTION 7: FOCUS AREAS
293
- if (handoff.focusAreas && handoff.focusAreas.length > 0) {
294
- sections.push(`## FOCUS AREAS\n\nWeight these areas heavily in your adversarial analysis:\n${handoff.focusAreas.map(f => `- **${f}**`).join('\n')}`);
295
- }
296
- // SECTION 8: PRIORITY FILES
297
- if (handoff.priorityFiles && handoff.priorityFiles.length > 0) {
298
- sections.push(`## PRIORITY FILES\n\n${handoff.priorityFiles.map(f => `- \`${f}\``).join('\n')}`);
299
- }
300
- // SECTION 9: ADVERSARIAL FOCUS (customInstructions steers the challenge)
301
- if (handoff.customInstructions) {
302
- sections.push(`## ADVERSARIAL FOCUS\n\n${handoff.customInstructions}`);
303
- }
304
- return sections.join('\n\n');
424
+ </final_check>`;
425
+ const focus = handoff.focusAreas && handoff.focusAreas.length > 0
426
+ ? `## FOCUS AREAS\n\nWeight these areas heavily in your adversarial analysis:\n${handoff.focusAreas.map((f) => `- **${f}**`).join('\n')}`
427
+ : null;
428
+ return joinSections([
429
+ `# ROLE: ${role.name}\n\n${role.systemPrompt}`,
430
+ stance,
431
+ renderTask(handoff),
432
+ renderGroundRules(),
433
+ renderUncertainties(handoff),
434
+ renderQuestions(handoff),
435
+ renderDecisions(handoff, 'adversarial'),
436
+ renderKnownGaps(handoff),
437
+ focus,
438
+ renderPriorityFiles(handoff),
439
+ renderSteering(handoff, 'ADVERSARIAL FOCUS'),
440
+ renderResponseFormat('adversarial'),
441
+ ]);
305
442
  }
306
- // =============================================================================
307
- // FOCUS-AREA CHECKLISTS — Specific patterns to look for (ported from prompt-v2)
308
- // =============================================================================
309
- const FOCUS_CHECKLISTS = {
310
- security: `Check for:
311
- - Injection vulnerabilities (SQL, NoSQL, Command, XSS)
312
- - Auth/authorization bypass, session management flaws
313
- - Sensitive data exposure, insecure storage, missing encryption
314
- - Input validation gaps (type, range, format)
315
- - Path traversal, SSRF, unsafe deserialization
316
- For each: CWE ID if applicable, attack scenario, severity by impact + exploitability.`,
317
- performance: `Check for:
318
- - Algorithmic complexity (provide Big-O notation)
319
- - N+1 queries, missing indexes, unoptimized queries
320
- - Blocking I/O in async contexts
321
- - Memory leaks, unbounded allocations, large object retention
322
- - Missing caching/memoization, repeated expensive operations
323
- For each: Big-O analysis, estimated impact, concrete optimization.`,
324
- architecture: `Check for:
325
- - SOLID violations (SRP, OCP, LSP, ISP, DIP)
326
- - High coupling between modules, low cohesion within
327
- - Layering violations, circular dependencies
328
- - Anti-patterns (god classes, deep nesting, magic numbers, leaky abstractions)
329
- - Missing or misused design patterns
330
- For each: specific principle violated, refactoring suggestion, maintainability impact.`,
331
- correctness: `Check for:
332
- - Off-by-one errors, incorrect conditionals, wrong operators
333
- - Null/undefined handling, empty collections, boundary conditions
334
- - Race conditions, deadlock potential, state inconsistency
335
- - Uncaught exceptions, silent failures, incorrect error propagation
336
- For each: triggering input, expected vs actual behavior.
337
- For significant bugs: suggest a concrete regression test.`,
338
- testing: `Check for:
339
- - Missing test coverage for changed code paths
340
- - Tests that pass for wrong reasons (tautologies, mocked-away logic)
341
- - Non-deterministic tests (timing, ordering, randomness)
342
- - Missing edge case tests (null, empty, boundary, error paths)
343
- For significant gaps: suggest a concrete test (name, inputs, expected output).`,
344
- scalability: `Check for:
345
- - Algorithmic complexity that degrades at scale (provide Big-O)
346
- - Unbounded growth (queues, caches, in-memory collections)
347
- - Missing pagination, rate limiting, or backpressure
348
- - Single points of contention (locks, shared state, single-threaded bottlenecks)
349
- For each: estimated impact at 10x/100x current load.`,
350
- maintainability: `Check for:
351
- - God classes, deep nesting (>3 levels), magic numbers
352
- - Tight coupling between modules, leaky abstractions
353
- - Code duplication that should be extracted
354
- - Missing or misleading comments on non-obvious logic
355
- For each: specific refactoring suggestion with rationale.`,
356
- documentation: `Check for:
357
- - Public API functions missing doc comments
358
- - Outdated or misleading comments that contradict the code
359
- - Missing README updates for changed behavior
360
- - Undocumented configuration, environment variables, or flags
361
- For each: what specifically should be documented and where.`,
362
- };
363
- /**
364
- * Build the review prompt using minimal, targeted context.
365
- * No output format constraints — reviewer responds naturally, CC interprets.
366
- */
367
- export function buildHandoffPrompt(options) {
368
- const { handoff } = options;
369
- const role = options.role || selectRole(handoff.focusAreas);
370
- const sections = [];
371
- // SECTION 1: ROLE
372
- sections.push(`# ROLE: ${role.name}\n\n${role.systemPrompt}`);
373
- // SECTION 2: REVIEW CHECKLIST (focus-area-specific patterns to look for)
374
- const focusAreas = handoff.focusAreas;
375
- if (focusAreas && focusAreas.length > 0) {
376
- const checklists = focusAreas
377
- .map(f => FOCUS_CHECKLISTS[f])
378
- .filter((c) => !!c);
379
- if (checklists.length > 0) {
380
- sections.push(`## REVIEW CHECKLIST\n\n${checklists.join('\n\n')}`);
381
- }
382
- }
383
- // SECTION 3: TASK
384
- sections.push(`## YOUR TASK
385
-
386
- Review code in \`${handoff.workingDir}\`.
387
-
388
- **Summary:** ${handoff.summary}${handoff.confidence !== undefined && handoff.confidence < 0.9 ? `\n**CC Confidence:** ${Math.round(handoff.confidence * 100)}% — verify weak areas` : ''}
389
-
390
- **IMPORTANT:**
391
- - This is a READ-ONLY review. Do NOT create, modify, or delete any files. Only read files to verify claims.
392
- - Do NOT assume a git repository exists. Do NOT run git commands. Read files directly from the filesystem.`);
393
- // SECTION 4: CC'S UNCERTAINTIES
394
- if (handoff.uncertainties && handoff.uncertainties.length > 0) {
395
- sections.push(`## CC'S UNCERTAINTIES
396
-
397
- ${handoff.uncertainties.map((u, i) => `### ${i + 1}. ${u.topic} ${u.severity === 'critical' ? '⚠️' : ''}
398
- - **Question:** ${u.question}
399
- ${u.ccAssumption ? `- **CC assumed:** ${u.ccAssumption}` : ''}
400
- ${u.relevantFiles ? `- **Files:** ${u.relevantFiles.join(', ')}` : ''}`).join('\n\n')}`);
401
- }
402
- // SECTION 5: SPECIFIC QUESTIONS
403
- if (handoff.questions && handoff.questions.length > 0) {
404
- sections.push(`## QUESTIONS FROM CC
405
-
406
- ${handoff.questions.map((q, i) => `${i + 1}. **${q.question}**
407
- ${q.context ? `Context: ${q.context}` : ''}
408
- ${q.ccGuess ? `CC Guess: ${q.ccGuess}` : ''}`).join('\n')}`);
409
- }
410
- // SECTION 6: DECISIONS TO EVALUATE
411
- if (handoff.decisions && handoff.decisions.length > 0) {
412
- sections.push(`## DECISIONS TO EVALUATE
413
-
414
- ${handoff.decisions.map((d, i) => `${i + 1}. **${d.decision}**${d.rationale ? `\n Rationale: ${d.rationale}` : ''}${d.alternatives ? `\n Alternatives: ${d.alternatives.join(', ')}` : ''}`).join('\n')}`);
415
- }
416
- // SECTION 7: PRIORITY FILES
417
- if (handoff.priorityFiles && handoff.priorityFiles.length > 0) {
418
- sections.push(`## PRIORITY FILES\n\n${handoff.priorityFiles.map(f => `- \`${f}\``).join('\n')}`);
419
- }
420
- // SECTION 8: CUSTOM INSTRUCTIONS
421
- if (handoff.customInstructions) {
422
- sections.push(`## ADDITIONAL INSTRUCTIONS\n\n${handoff.customInstructions}`);
423
- }
424
- return sections.join('\n\n');
443
+ /** Build the prompt for a ReviewRequest, selecting the pass from `reviewMode`. */
444
+ export function buildReviewPrompt(request) {
445
+ const handoff = buildSimpleHandoff(request.workingDir, request.ccOutput, request.analyzedFiles, request.focusAreas, request.customPrompt, request.outputType, request.baseRef);
446
+ return request.reviewMode === 'adversarial'
447
+ ? buildAdversarialHandoffPrompt({ handoff })
448
+ : buildHandoffPrompt({ handoff, role: selectRole(request.focusAreas) });
425
449
  }
426
450
  // =============================================================================
427
451
  // STRUCTURED ccOutput PARSER
428
452
  // =============================================================================
453
+ const KNOWN_HEADERS = ['SUMMARY', 'UNCERTAINTIES', 'QUESTIONS', 'DECISIONS', 'KNOWN GAPS', 'PRIORITY FILES'];
429
454
  /**
430
- * Parse structured ccOutput into Handoff fields.
431
- *
432
- * The slash commands tell CC to format its output as:
433
- * SUMMARY:
434
- * <text>
435
- *
436
- * UNCERTAINTIES (verify these):
437
- * 1. <text>
455
+ * Parse CC's structured brief into Handoff fields.
438
456
  *
439
- * QUESTIONS:
440
- * 1. <text>
441
- *
442
- * PRIORITY FILES:
443
- * - <file>
444
- *
445
- * If no sections detected, returns { summary: ccOutput } (graceful fallback).
457
+ * The slash command tells CC to format its output as ALL-CAPS section headers
458
+ * (`SUMMARY:`, `UNCERTAINTIES (verify these):`, ...). Headers are matched
459
+ * case-sensitively at the start of a line so prose such as "Questions: none"
460
+ * inside a section cannot open a new one. Unstructured input falls back to
461
+ * `{ summary: ccOutput }`.
446
462
  */
447
463
  export function parseStructuredCcOutput(ccOutput) {
448
- // Quick check: does it look structured? Case-SENSITIVE to avoid matching
449
- // prose like "Summary: I think..." — slash commands produce ALL-CAPS headers.
450
464
  if (!/^SUMMARY[^:\n]*:/m.test(ccOutput)) {
451
465
  return { summary: ccOutput };
452
466
  }
453
- // Known section headers — case-SENSITIVE (ALL-CAPS only) to prevent
454
- // header injection from natural prose starting with "Questions:" etc.
455
- const KNOWN_HEADERS = ['SUMMARY', 'UNCERTAINTIES', 'QUESTIONS', 'PRIORITY FILES', 'DECISIONS'];
456
- const headerPattern = new RegExp(`^(${KNOWN_HEADERS.join('|')})[^:\\n]*:`, 'gm' // no 'i' flag — case-sensitive
457
- );
458
- // Find all header positions
459
- const headers = [];
467
+ const headerPattern = new RegExp(`^(${KNOWN_HEADERS.join('|')})[^:\\n]*:[ \\t]*`, 'gm');
468
+ const found = [];
460
469
  let match;
461
470
  while ((match = headerPattern.exec(ccOutput)) !== null) {
462
- const raw = match[1].trim();
463
- const name = KNOWN_HEADERS.find(h => raw.startsWith(h)) || raw;
464
- headers.push({ name, contentStart: match.index + match[0].length });
471
+ found.push({ name: match[1], start: match.index, contentStart: match.index + match[0].length });
465
472
  }
466
- if (headers.length === 0) {
473
+ if (found.length === 0)
467
474
  return { summary: ccOutput };
468
- }
469
- // Extract content between headers
470
475
  const sections = new Map();
471
- for (let i = 0; i < headers.length; i++) {
472
- const start = headers[i].contentStart;
473
- const end = i + 1 < headers.length
474
- ? ccOutput.lastIndexOf('\n', headers[i + 1].contentStart - headers[i + 1].name.length - 1)
475
- : ccOutput.length;
476
- sections.set(headers[i].name, ccOutput.slice(start, end).trim());
476
+ for (let i = 0; i < found.length; i++) {
477
+ const end = i + 1 < found.length ? found[i + 1].start : ccOutput.length;
478
+ const body = ccOutput.slice(found[i].contentStart, end).trim();
479
+ // First occurrence wins so a duplicated header cannot overwrite content.
480
+ if (!sections.has(found[i].name))
481
+ sections.set(found[i].name, body);
477
482
  }
483
+ const result = { summary: ccOutput };
478
484
  const rawSummary = sections.get('SUMMARY');
479
- const result = {
480
- summary: rawSummary && rawSummary.length > 0 ? rawSummary : ccOutput,
481
- };
482
- // Parse uncertainties (numbered or bulleted list)
483
- const uncertText = sections.get('UNCERTAINTIES');
484
- if (uncertText) {
485
- const items = parseListItems(uncertText);
486
- if (items.length > 0) {
487
- result.uncertainties = items.map(item => ({
488
- topic: extractTopic(item),
489
- question: item,
490
- }));
491
- }
485
+ if (rawSummary && rawSummary.length > 0) {
486
+ const { summary, bar } = splitBar(rawSummary);
487
+ result.summary = summary.length > 0 ? summary : ccOutput;
488
+ if (bar)
489
+ result.bar = bar;
492
490
  }
493
- // Parse questions (numbered or bulleted list)
494
- const questionsText = sections.get('QUESTIONS');
495
- if (questionsText) {
496
- const items = parseListItems(questionsText);
497
- if (items.length > 0) {
498
- result.questions = items.map(item => ({ question: item }));
499
- }
491
+ const uncertainties = parseListItems(sections.get('UNCERTAINTIES') ?? '');
492
+ if (uncertainties.length > 0) {
493
+ result.uncertainties = uncertainties.map((item) => {
494
+ const { weight, text } = splitWeightTag(item);
495
+ return { topic: extractTopic(text), question: text, weight };
496
+ });
500
497
  }
501
- // Parse priority files (bullet or numbered list)
502
- const filesText = sections.get('PRIORITY FILES');
503
- if (filesText) {
504
- const items = parseListItems(filesText);
505
- if (items.length > 0) {
506
- result.priorityFiles = items;
507
- }
498
+ const questions = parseListItems(sections.get('QUESTIONS') ?? '');
499
+ if (questions.length > 0) {
500
+ result.questions = questions.map((question) => ({ question }));
508
501
  }
509
- // Parse decisions (numbered or bulleted list)
510
- const decisionsText = sections.get('DECISIONS');
511
- if (decisionsText) {
512
- const items = parseListItems(decisionsText);
513
- if (items.length > 0) {
514
- result.decisions = items.map(item => ({ decision: item, rationale: '' }));
515
- }
502
+ const decisions = parseListItems(sections.get('DECISIONS') ?? '');
503
+ if (decisions.length > 0) {
504
+ result.decisions = decisions.map((item) => splitRationale(item));
516
505
  }
506
+ const gaps = parseListItems(sections.get('KNOWN GAPS') ?? '');
507
+ if (gaps.length > 0)
508
+ result.knownGaps = gaps;
509
+ const files = parseListItems(sections.get('PRIORITY FILES') ?? '').map(stripBackticks);
510
+ if (files.length > 0)
511
+ result.priorityFiles = files;
517
512
  return result;
518
513
  }
514
+ /** Pull a `Bar: ...` line out of the summary body. */
515
+ function splitBar(summary) {
516
+ const lines = summary.split('\n');
517
+ const idx = lines.findIndex((l) => /^\s*\**\s*Bar\**\s*:/i.test(l));
518
+ if (idx === -1)
519
+ return { summary };
520
+ const barLines = [lines[idx].replace(/^\s*\**\s*Bar\**\s*:\s*/i, '')];
521
+ // Continuation lines belong to the bar until a blank line.
522
+ let j = idx + 1;
523
+ while (j < lines.length && lines[j].trim().length > 0) {
524
+ barLines.push(lines[j].trim());
525
+ j++;
526
+ }
527
+ const rest = [...lines.slice(0, idx), ...lines.slice(j)].join('\n').trim();
528
+ return { summary: rest, bar: barLines.join(' ').trim() };
529
+ }
530
+ function splitWeightTag(item) {
531
+ const m = item.match(/^\[\s*(load[- ]bearing|incidental)\s*\]\s*/i);
532
+ if (!m)
533
+ return { text: item };
534
+ const weight = m[1].toLowerCase().startsWith('load') ? 'load-bearing' : 'incidental';
535
+ return { weight, text: item.slice(m[0].length).trim() };
536
+ }
537
+ function splitRationale(item) {
538
+ const m = item.match(/\s*\**\s*Rationale\**\s*:\s*/i);
539
+ if (!m || m.index === undefined)
540
+ return { decision: item };
541
+ const decision = item.slice(0, m.index).replace(/[.\s]+$/, '').trim();
542
+ const rationale = item.slice(m.index + m[0].length).trim();
543
+ return rationale.length > 0 ? { decision: decision || item, rationale } : { decision: decision || item };
544
+ }
545
+ function stripBackticks(s) {
546
+ return s.replace(/^`+|`+$/g, '').trim();
547
+ }
519
548
  /**
520
- * Extract a short topic from an item — uses first sentence/clause up to 60 chars.
521
- * Avoids redundant rendering where topic === question.
549
+ * Short topic from an item — the first clause, up to 60 chars. Clause
550
+ * boundaries are punctuation followed by whitespace (or a trailing `?`/`.`),
551
+ * so hyphenated words such as "race-free" stay intact.
522
552
  */
523
553
  function extractTopic(item) {
524
- // Try first clause (up to first comma, period, dash, or question mark)
525
- const clauseMatch = item.match(/^(.+?)[,.\-?]/);
526
- const clause = clauseMatch ? clauseMatch[1].trim() : item;
554
+ const clauseMatch = item.match(/^(.+?)(?:[,.;:?]\s|\s[-—–]\s|[?.]$)/);
555
+ const clause = clauseMatch ? clauseMatch[1].trim() : item.trim();
527
556
  if (clause.length <= 60)
528
557
  return clause;
529
558
  return clause.slice(0, 57) + '...';
530
559
  }
531
560
  /**
532
- * Parse a list section that may use numbered ("1. foo") or bulleted ("- foo") format.
533
- * Supports multi-line continuation for both styles.
561
+ * Parse a list that may use numbered ("1. foo", "2) bar") or bulleted
562
+ * ("- foo", "* bar") items, with multi-line continuation for both styles.
534
563
  */
535
564
  function parseListItems(text) {
536
565
  const items = [];
537
566
  let current = '';
538
567
  for (const line of text.split('\n')) {
539
- // Match numbered: "1. foo", "2) bar"
540
- const numbered = line.match(/^\d+[.)]\s+(.+)/);
541
- // Match bulleted: "- foo", "* bar"
542
- const bulleted = line.match(/^[-*]\s+(.+)/);
568
+ const numbered = line.match(/^\s*\d+[.)]\s+(.+)/);
569
+ const bulleted = line.match(/^\s*[-*•]\s+(.+)/);
543
570
  if (numbered || bulleted) {
544
571
  if (current)
545
572
  items.push(current.trim());
546
573
  current = (numbered || bulleted)[1];
547
574
  }
548
575
  else if (current && line.trim()) {
549
- // Continuation line for multi-line items
550
576
  current += ' ' + line.trim();
551
577
  }
552
578
  }
@@ -555,45 +581,28 @@ function parseListItems(text) {
555
581
  return items;
556
582
  }
557
583
  // =============================================================================
558
- // HELPER: Build handoff from simple inputs
584
+ // HANDOFF FROM TOOL INPUTS
559
585
  // =============================================================================
560
586
  /**
561
- * Build a handoff from MCP tool inputs.
562
- *
563
- * Parses structured sections (SUMMARY, UNCERTAINTIES, QUESTIONS, PRIORITY FILES)
564
- * from ccOutput when present, populating typed Handoff fields so reviewers
565
- * receive machine-usable context instead of a single summary blob.
587
+ * Build a handoff from MCP tool inputs. Structured sections in ccOutput are
588
+ * parsed into typed fields; `analyzedFiles` are merged into priorityFiles.
566
589
  */
567
- export function buildSimpleHandoff(workingDir, ccOutput, analyzedFiles, focusAreas, customPrompt) {
590
+ export function buildSimpleHandoff(workingDir, ccOutput, analyzedFiles, focusAreas, customPrompt, outputType, baseRef) {
568
591
  const parsed = parseStructuredCcOutput(ccOutput);
569
- // Merge analyzedFiles with any priority files parsed from ccOutput (dedup)
570
- const mergedFiles = dedupStrings([
571
- ...(parsed.priorityFiles || []),
572
- ...(analyzedFiles || []),
573
- ]);
592
+ const mergedFiles = [...new Set([...(parsed.priorityFiles ?? []), ...(analyzedFiles ?? [])])];
593
+ const resolvedType = outputType && OUTPUT_TYPES.includes(outputType) ? outputType : undefined;
574
594
  return {
575
595
  workingDir,
596
+ outputType: resolvedType,
597
+ baseRef: baseRef && baseRef.trim().length > 0 ? baseRef.trim() : undefined,
576
598
  summary: parsed.summary,
599
+ bar: parsed.bar,
577
600
  uncertainties: parsed.uncertainties,
578
601
  questions: parsed.questions,
579
602
  decisions: parsed.decisions,
603
+ knownGaps: parsed.knownGaps,
580
604
  priorityFiles: mergedFiles.length > 0 ? mergedFiles : undefined,
581
- focusAreas,
582
- customInstructions: customPrompt,
583
- };
584
- }
585
- function dedupStrings(arr) {
586
- return [...new Set(arr)];
587
- }
588
- /**
589
- * Enhance a simple handoff with uncertainties/questions
590
- * CC should call this to add its specific concerns
591
- */
592
- export function enhanceHandoff(handoff, uncertainties, questions, decisions) {
593
- return {
594
- ...handoff,
595
- uncertainties: uncertainties || handoff.uncertainties,
596
- questions: questions || handoff.questions,
597
- decisions: decisions || handoff.decisions,
605
+ focusAreas: focusAreas && focusAreas.length > 0 ? focusAreas : undefined,
606
+ customInstructions: customPrompt && customPrompt.trim().length > 0 ? customPrompt : undefined,
598
607
  };
599
608
  }