@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
@@ -1,220 +1,128 @@
1
1
  /**
2
- * Claude CLI Adapter
2
+ * Claude Code adapter.
3
3
  *
4
- * Implements the ReviewerAdapter interface for Anthropic's Claude CLI.
5
- * Spawns a FRESH Claude Code instance with zero session context.
6
- * Returns raw text — CC handles interpretation.
4
+ * Spawns a separate Claude Code instance so the reviewer shares none of CC's
5
+ * conversation. Model and effort come from config (`claude.model`, default
6
+ * `fable`; `claude.effort` / `claude.consultEffort`).
7
7
  *
8
- * Read-only enforcement (defense-in-depth):
9
- * 1. --permission-mode plan (CLI-level read-only)
10
- * 2. --disallowed-tools (write tools explicitly blocked)
11
- * 3. Handoff prompt (explicit READ-ONLY instruction)
8
+ * Read-only, single-purpose run (defense in depth):
9
+ * 1. --permission-mode default Read/Grep/Glob are auto-allowed; everything
10
+ * + --permission-prompts none else that would prompt is denied outright,
11
+ * so a headless run can never hang. Plan mode
12
+ * is deliberately NOT used: it injects Claude
13
+ * Code's planning workflow (write a plan file,
14
+ * spawn Explore agents, end with ExitPlanMode)
15
+ * which fights the review brief.
16
+ * 2. --disallowed-tools write tools and agent/plan tools removed
17
+ * 3. --allowed-tools only read-only git commands may run in Bash
18
+ * 4. --strict-mcp-config none of the user's MCP servers are started
19
+ * 5. --setting-sources '' no user/project/local settings, hooks or
20
+ * plugins from settings files
21
+ * 6. the prompt itself explicit READ-ONLY ground rules
22
+ *
23
+ * Not isolated (only `--bare` removes these, and `--bare` disables the
24
+ * keychain/OAuth read, so OAuth users could not run at all): the project's
25
+ * CLAUDE.md, Claude Code's auto-memory for the working directory, and one
26
+ * built-in SessionStart hook.
12
27
  */
13
- import { spawn } from 'child_process';
14
- import { existsSync } from 'fs';
15
- import { registerAdapter, } from './base.js';
28
+ import { registerAdapter } from './base.js';
29
+ import { CliAdapter } from './cli-adapter.js';
16
30
  import { CliExecutor } from '../executor.js';
17
31
  import { ClaudeEventDecoder } from '../decoders/index.js';
18
- import { buildSimpleHandoff, buildHandoffPrompt, buildAdversarialHandoffPrompt, selectRole, } from '../handoff.js';
19
- import { buildConsultPrompt } from '../consult-prompt.js';
20
32
  import { getConfig } from '../config.js';
21
- // Write tools explicitly blocked as defense-in-depth
22
- const DISALLOWED_TOOLS = 'Edit Write NotebookEdit';
23
- // =============================================================================
24
- // CLAUDE ADAPTER
25
- // =============================================================================
26
- export class ClaudeAdapter {
33
+ /** Write tools plus the agent/plan tools a review has no business calling. */
34
+ export const DISALLOWED_TOOLS = 'Edit Write NotebookEdit Agent Task ExitPlanMode AskUserQuestion Workflow';
35
+ /** The only shell commands the reviewer may run: read-only git, as the prompt's ground rules promise. */
36
+ export const ALLOWED_TOOLS = [
37
+ 'git status', 'git diff', 'git log', 'git show', 'git blame', 'git ls-files', 'git grep', 'git rev-parse', 'git merge-base',
38
+ ].flatMap((cmd) => [`Bash(${cmd})`, `Bash(${cmd} *)`]).join(' ');
39
+ export class ClaudeAdapter extends CliAdapter {
27
40
  id = 'claude';
41
+ binary = 'claude';
42
+ installHint = 'Install Claude Code: https://docs.anthropic.com/en/docs/claude-code';
43
+ authHint = 'Run `claude auth login` (or `/login` inside claude) to authenticate';
44
+ extraAuthPatterns = ['please run /login', 'invalid api key'];
28
45
  getCapabilities() {
29
46
  return {
30
47
  name: 'Claude',
31
- description: 'Anthropic Claude (Opus) - fresh instance with clean context, excels at deep analysis across all dimensions',
32
- strengths: ['correctness', 'security', 'architecture', 'maintainability'],
33
- weaknesses: [],
34
- hasFilesystemAccess: true,
35
- supportsStructuredOutput: false,
36
- maxContextTokens: 200000,
37
- reasoningLevels: undefined,
48
+ description: 'Separate Claude Code instance, read-only tools, no MCP servers; model and effort from claude.* config',
38
49
  };
39
50
  }
40
- async isAvailable() {
41
- return new Promise((resolve) => {
42
- let settled = false;
43
- const done = (result) => { if (!settled) {
44
- settled = true;
45
- clearTimeout(timer);
46
- resolve(result);
47
- } };
48
- const proc = spawn('claude', ['--version'], {
49
- stdio: ['ignore', 'pipe', 'pipe'],
50
- });
51
- proc.on('close', (code) => done(code === 0));
52
- proc.on('error', () => done(false));
53
- const timer = setTimeout(() => { proc.kill(); done(false); }, 5000);
54
- });
55
- }
56
- async runReview(request) {
57
- const startTime = Date.now();
58
- if (!existsSync(request.workingDir)) {
59
- return {
60
- success: false,
61
- error: { type: 'cli_error', message: `Working directory does not exist: ${request.workingDir}` },
62
- suggestion: 'Check that the working directory path is correct',
63
- executionTimeMs: Date.now() - startTime,
64
- };
65
- }
66
- try {
67
- const handoff = buildSimpleHandoff(request.workingDir, request.ccOutput, request.analyzedFiles, request.focusAreas, request.customPrompt);
68
- const prompt = request.reviewMode === 'adversarial'
69
- ? buildAdversarialHandoffPrompt({ handoff })
70
- : buildHandoffPrompt({ handoff, role: selectRole(request.focusAreas) });
71
- const result = await this.runCli(prompt, request.workingDir);
72
- if (result.exitCode !== 0) {
73
- const error = this.categorizeError(result.stderr);
74
- return { success: false, error, suggestion: this.getSuggestion(error), executionTimeMs: Date.now() - startTime };
75
- }
76
- if (!result.stdout.trim()) {
77
- return {
78
- success: false,
79
- error: { type: 'cli_error', message: 'Claude returned empty response' },
80
- suggestion: 'Try again or use /multi-review instead',
81
- executionTimeMs: Date.now() - startTime,
82
- };
83
- }
84
- return { success: true, output: result.stdout, executionTimeMs: Date.now() - startTime };
85
- }
86
- catch (error) {
87
- return this.handleException(error, startTime);
88
- }
51
+ getLimits() {
52
+ const cfg = getConfig().claude;
53
+ return {
54
+ inactivityTimeoutMs: cfg.inactivityTimeoutMs,
55
+ maxTimeoutMs: cfg.maxTimeoutMs,
56
+ maxBufferSize: cfg.maxBufferSize,
57
+ };
89
58
  }
90
- async runCli(prompt, workingDir) {
59
+ /** Build the argv for a headless, read-only run. Exposed for tests. */
60
+ buildArgs(ctx) {
91
61
  const cfg = getConfig().claude;
92
- const args = [
93
- '-p', // Non-interactive, print and exit
94
- '--model', cfg.model, // Model from config (default: opus)
95
- '--setting-sources', '', // Skip hooks, plugins, CLAUDE.md (preserves OAuth auth; --bare kills keychain)
96
- '--permission-mode', 'plan', // Read-only enforcement (layer 1)
97
- '--verbose', // Required for stream-json
98
- '--output-format', 'stream-json', // Structured streaming events
99
- '--no-session-persistence', // Ephemeral — no trace
100
- '--disable-slash-commands', // No skills — minimal startup
101
- '--disallowed-tools', DISALLOWED_TOOLS, // Block write tools (layer 2)
102
- '-', // Read prompt from stdin
62
+ const effort = ctx.kind === 'consult' ? cfg.consultEffort : cfg.effort;
63
+ return [
64
+ '-p', // non-interactive: print and exit; prompt arrives on stdin
65
+ '--model', cfg.model,
66
+ ...(cfg.fallbackModel ? ['--fallback-model', cfg.fallbackModel] : []),
67
+ ...(effort ? ['--effort', effort] : []),
68
+ '--setting-sources', '', // no settings-file hooks/plugins; OAuth still works (--bare kills keychain) (layer 5)
69
+ '--strict-mcp-config', // no MCP servers (layer 4)
70
+ '--permission-mode', 'default', // auto-allow reads only (layer 1)
71
+ '--permission-prompts', 'none', // never wait on a prompt — deny instead (layer 1)
72
+ '--verbose', // required for stream-json
73
+ '--output-format', 'stream-json',
74
+ '--no-session-persistence', // ephemeral — leaves no session on disk
75
+ '--disable-slash-commands', // no skills — minimal startup
76
+ '--disallowed-tools', DISALLOWED_TOOLS, // write + agent tools removed (layer 2)
77
+ '--allowed-tools', ALLOWED_TOOLS, // read-only git in Bash (layer 3)
103
78
  ];
79
+ }
80
+ async runCli(prompt, workingDir, ctx) {
81
+ const cfg = getConfig().claude;
82
+ const limits = this.getLimits();
83
+ const args = this.buildArgs(ctx);
104
84
  const decoder = new ClaudeEventDecoder();
105
85
  const cliStartTime = Date.now();
106
- console.error('[claude] Running Opus review...');
86
+ const effort = ctx.kind === 'consult' ? cfg.consultEffort : cfg.effort;
87
+ console.error(`[claude] Running ${ctx.kind} with ${cfg.model}${effort ? ` (${effort} effort)` : ''}...`);
107
88
  decoder.onProgress = (eventType, detail) => {
108
89
  const elapsed = Math.round((Date.now() - cliStartTime) / 1000);
109
- const detailStr = detail ? ` — ${detail}` : '';
110
- console.error(`[claude] ${eventType}${detailStr} (${elapsed}s)`);
90
+ console.error(`[claude] ${eventType}${detail ? ` — ${detail}` : ''} (${elapsed}s)`);
111
91
  };
112
92
  const executor = new CliExecutor({
113
- command: 'claude',
93
+ command: this.binary,
114
94
  args,
115
95
  cwd: workingDir,
116
96
  stdin: prompt,
117
- inactivityTimeoutMs: cfg.inactivityTimeoutMs,
118
- maxTimeoutMs: cfg.maxTimeoutMs,
119
- maxBufferSize: cfg.maxBufferSize,
120
- onLine: (line) => {
121
- decoder.processLine(line);
122
- },
97
+ inactivityTimeoutMs: limits.inactivityTimeoutMs,
98
+ maxTimeoutMs: limits.maxTimeoutMs,
99
+ maxBufferSize: limits.maxBufferSize,
100
+ onLine: (line) => decoder.processLine(line),
123
101
  });
124
102
  const result = await executor.run();
125
- const elapsed = Math.round((Date.now() - cliStartTime) / 1000);
126
- console.error(`[claude] ✓ complete (${elapsed}s)`);
127
- // Prefer a completed response over a captured error: a non-fatal error event
128
- // that precedes a successful agent_message must not discard the result (same
129
- // class of bug fixed in the codex adapter). Only treat a decoder error as
130
- // fatal when no final response was produced.
103
+ console.error(`[claude] ✓ complete (${Math.round((Date.now() - cliStartTime) / 1000)}s)`);
131
104
  const finalResponse = decoder.getFinalResponse();
132
- if (finalResponse) {
133
- return {
134
- stdout: finalResponse,
135
- stderr: result.stderr,
136
- exitCode: result.exitCode,
137
- truncated: result.truncated,
138
- };
139
- }
140
105
  const decoderError = decoder.getError();
141
- if (decoderError) {
142
- const combined = result.stderr ? `${decoderError}\n\nCLI stderr: ${result.stderr}` : decoderError;
143
- return { stdout: '', stderr: combined, exitCode: 1, truncated: false };
144
- }
145
- if (decoder.hasNoOutput()) {
146
- const combined = result.stderr ? `No output from Claude\n\nCLI stderr: ${result.stderr}` : 'No output from Claude';
147
- return { stdout: '', stderr: combined, exitCode: 1, truncated: false };
148
- }
149
- const combined = result.stderr ? `No result event from Claude\n\nCLI stderr: ${result.stderr}` : 'No result event from Claude';
150
- return { stdout: '', stderr: combined, exitCode: 1, truncated: false };
151
- }
152
- handleException(error, startTime) {
153
- const err = error;
154
- if (err.code === 'ENOENT') {
155
- return { success: false, error: { type: 'cli_not_found', message: 'Claude CLI not found' },
156
- suggestion: 'Install Claude Code: https://docs.anthropic.com/en/docs/claude-code', executionTimeMs: Date.now() - startTime };
157
- }
158
- if (err.message === 'TIMEOUT') {
159
- return { success: false, error: { type: 'timeout', message: 'Claude timed out — no events received' },
160
- suggestion: 'Try a smaller scope or use /multi-review', executionTimeMs: Date.now() - startTime };
161
- }
162
- if (err.message === 'MAX_TIMEOUT') {
163
- return { success: false, error: { type: 'timeout', message: 'Task exceeded 60 minute maximum' },
164
- suggestion: 'Try a smaller scope', executionTimeMs: Date.now() - startTime };
106
+ // A non-zero exit or an `is_error` result is terminal. Claude reports
107
+ // failures that happen inside the run ("Not logged in · Please run
108
+ // /login", quota) in the result event's text, not on stderr, so that text
109
+ // must be the diagnostic that gets categorized — returning it as the
110
+ // review would either mask the failure or lose the actionable message.
111
+ if (result.exitCode !== 0 || decoder.isResultError()) {
112
+ const reason = decoderError ?? finalResponse ?? `Claude exited with code ${result.exitCode}`;
113
+ return { stdout: '', stderr: this.combineDiagnostics(reason, result.stderr), exitCode: result.exitCode || 1, truncated: false };
165
114
  }
166
- return { success: false, error: { type: 'cli_error', message: err.message }, executionTimeMs: Date.now() - startTime };
167
- }
168
- categorizeError(stderr) {
169
- const lower = stderr.toLowerCase();
170
- if (lower.includes('rate limit') || lower.includes('rate_limit') || lower.includes('quota')) {
171
- return { type: 'rate_limit', message: `Claude rate limit: ${stderr.slice(0, 500)}` };
172
- }
173
- if (lower.includes('unauthorized') || lower.includes('authentication') || lower.includes('not logged in') || lower.includes('api key') || stderr.includes('401') || stderr.includes('403')) {
174
- return { type: 'auth_error', message: `Authentication failed: ${stderr.slice(0, 500)}`, details: { stderr } };
175
- }
176
- return { type: 'cli_error', message: stderr.slice(0, 500) || 'Unknown error' };
177
- }
178
- getSuggestion(error) {
179
- switch (error.type) {
180
- case 'rate_limit': return 'Wait and retry, or use /multi-review instead';
181
- case 'auth_error': return 'Run `claude auth` to authenticate';
182
- case 'cli_not_found': return 'Install Claude Code: https://docs.anthropic.com/en/docs/claude-code';
183
- default: return 'Check the error message and try again';
115
+ // A completed response wins over a non-fatal error event that preceded it.
116
+ // `!== null` so an empty-string result reaches empty-response handling.
117
+ if (finalResponse !== null) {
118
+ return { stdout: finalResponse, stderr: result.stderr, exitCode: 0, truncated: result.truncated };
184
119
  }
185
- }
186
- async runConsult(request) {
187
- const startTime = Date.now();
188
- if (!existsSync(request.workingDir)) {
189
- return {
190
- success: false,
191
- error: { type: 'cli_error', message: `Working directory does not exist: ${request.workingDir}` },
192
- suggestion: 'Check that the working directory path is correct',
193
- executionTimeMs: Date.now() - startTime,
194
- };
195
- }
196
- try {
197
- const prompt = buildConsultPrompt(request);
198
- const result = await this.runCli(prompt, request.workingDir);
199
- if (result.exitCode !== 0) {
200
- const error = this.categorizeError(result.stderr);
201
- return { success: false, error, suggestion: this.getSuggestion(error), executionTimeMs: Date.now() - startTime };
202
- }
203
- if (!result.stdout.trim()) {
204
- return {
205
- success: false,
206
- error: { type: 'cli_error', message: 'Claude returned empty response' },
207
- suggestion: 'Try again or use /multi-review instead',
208
- executionTimeMs: Date.now() - startTime,
209
- };
210
- }
211
- return { success: true, output: result.stdout, executionTimeMs: Date.now() - startTime };
212
- }
213
- catch (error) {
214
- return this.handleException(error, startTime);
120
+ if (decoderError) {
121
+ return { stdout: '', stderr: this.combineDiagnostics(decoderError, result.stderr), exitCode: 1, truncated: false };
215
122
  }
123
+ const reason = decoder.hasNoOutput() ? 'No output from Claude' : 'No result event from Claude';
124
+ return { stdout: '', stderr: this.combineDiagnostics(reason, result.stderr), exitCode: 1, truncated: false };
216
125
  }
217
126
  }
218
- // Register the adapter
219
- registerAdapter(new ClaudeAdapter());
220
127
  export const claudeAdapter = new ClaudeAdapter();
128
+ registerAdapter(claudeAdapter);
@@ -0,0 +1,78 @@
1
+ /**
2
+ * CliAdapter — the shared implementation behind every reviewer adapter.
3
+ *
4
+ * Each concrete adapter only has to say which binary it spawns, how to build
5
+ * its argv, and how to turn the process output into text. Everything that is
6
+ * identical across CLIs lives here so it is fixed in one place:
7
+ * - availability probing (`<binary> --version`) with a short cache
8
+ * - the config `enabled` switch
9
+ * - the runReview / runConsult templates (cwd check → prompt → CLI → result)
10
+ * - error categorization, suggestions, and exception mapping
11
+ */
12
+ import { ConsultRequest, ConsultResult, ReviewerAdapter, ReviewerCapabilities, ReviewError, ReviewFailure, ReviewRequest, ReviewResult } from './base.js';
13
+ import { ReasoningEffort, ServiceTier } from '../types.js';
14
+ /** What kind of call is being made — adapters pick per-kind defaults from config. */
15
+ export interface RunContext {
16
+ kind: 'review' | 'consult';
17
+ reasoningEffort?: ReasoningEffort;
18
+ serviceTier?: ServiceTier;
19
+ }
20
+ /** Normalized outcome of one CLI run, before it is turned into a ReviewResult. */
21
+ export interface CliOutcome {
22
+ /** The model's final text ('' when none was produced). */
23
+ stdout: string;
24
+ /** Diagnostic text — CLI stderr plus any decoder-level error message. */
25
+ stderr: string;
26
+ /** 0 on success; anything else is categorized via `categorizeError`. */
27
+ exitCode: number;
28
+ truncated: boolean;
29
+ }
30
+ /** Limits in effect for a run — configure the executor and word timeout errors. */
31
+ export interface RunLimits {
32
+ inactivityTimeoutMs: number;
33
+ maxTimeoutMs: number;
34
+ maxBufferSize: number;
35
+ }
36
+ /** How long a `--version` probe result is trusted before re-probing. */
37
+ export declare const AVAILABILITY_TTL_MS = 60000;
38
+ export declare abstract class CliAdapter implements ReviewerAdapter {
39
+ abstract readonly id: string;
40
+ /** Executable spawned for probes and runs. */
41
+ protected abstract readonly binary: string;
42
+ /** Shown when the CLI is missing. */
43
+ protected abstract readonly installHint: string;
44
+ /** Shown on authentication failures. */
45
+ protected abstract readonly authHint: string;
46
+ abstract getCapabilities(): ReviewerCapabilities;
47
+ /** Timeouts/buffer for this kind of run, read from config. */
48
+ protected abstract getLimits(ctx: RunContext): RunLimits;
49
+ /** Spawn the CLI with the prompt and normalize its output. */
50
+ protected abstract runCli(prompt: string, workingDir: string, ctx: RunContext): Promise<CliOutcome>;
51
+ /** Adapter-specific stderr substrings (lower-case) that mean rate limiting. */
52
+ protected extraRateLimitPatterns: string[];
53
+ /** Adapter-specific stderr substrings (lower-case) that mean an auth failure. */
54
+ protected extraAuthPatterns: string[];
55
+ private probe;
56
+ isEnabled(): boolean;
57
+ isAvailable(options?: {
58
+ fresh?: boolean;
59
+ }): Promise<boolean>;
60
+ /** First line of `<binary> --version`, or null when the CLI is not runnable. */
61
+ getVersion(options?: {
62
+ fresh?: boolean;
63
+ }): Promise<string | null>;
64
+ private getProbe;
65
+ runReview(request: ReviewRequest): Promise<ReviewResult>;
66
+ runConsult(request: ConsultRequest): Promise<ConsultResult>;
67
+ private execute;
68
+ protected handleException(error: unknown, startTime: number, ctx: RunContext): ReviewFailure;
69
+ protected categorizeError(stderr: string): ReviewError;
70
+ protected getSuggestion(error: ReviewError): string;
71
+ /** Combine a decoder-level message with CLI stderr into one diagnostic string. */
72
+ protected combineDiagnostics(message: string, stderr: string): string;
73
+ }
74
+ /** Run `<binary> --version` with a hard timeout; never throws. */
75
+ export declare function probeVersion(binary: string): Promise<{
76
+ available: boolean;
77
+ version: string | null;
78
+ }>;
@@ -0,0 +1,220 @@
1
+ /**
2
+ * CliAdapter — the shared implementation behind every reviewer adapter.
3
+ *
4
+ * Each concrete adapter only has to say which binary it spawns, how to build
5
+ * its argv, and how to turn the process output into text. Everything that is
6
+ * identical across CLIs lives here so it is fixed in one place:
7
+ * - availability probing (`<binary> --version`) with a short cache
8
+ * - the config `enabled` switch
9
+ * - the runReview / runConsult templates (cwd check → prompt → CLI → result)
10
+ * - error categorization, suggestions, and exception mapping
11
+ */
12
+ import { spawn } from 'child_process';
13
+ import { existsSync } from 'fs';
14
+ import { isAdapterEnabledInConfig, } from './base.js';
15
+ import { buildReviewPrompt } from '../handoff.js';
16
+ import { buildConsultPrompt } from '../consult-prompt.js';
17
+ /** How long a `--version` probe result is trusted before re-probing. */
18
+ export const AVAILABILITY_TTL_MS = 60_000;
19
+ const PROBE_TIMEOUT_MS = 5_000;
20
+ const STDERR_EXCERPT = 500;
21
+ // =============================================================================
22
+ // BASE CLASS
23
+ // =============================================================================
24
+ export class CliAdapter {
25
+ /** Adapter-specific stderr substrings (lower-case) that mean rate limiting. */
26
+ extraRateLimitPatterns = [];
27
+ /** Adapter-specific stderr substrings (lower-case) that mean an auth failure. */
28
+ extraAuthPatterns = [];
29
+ probe = null;
30
+ // ---------------------------------------------------------------------------
31
+ // Availability
32
+ // ---------------------------------------------------------------------------
33
+ isEnabled() {
34
+ return isAdapterEnabledInConfig(this.id);
35
+ }
36
+ async isAvailable(options) {
37
+ return (await this.getProbe(options?.fresh === true)).available;
38
+ }
39
+ /** First line of `<binary> --version`, or null when the CLI is not runnable. */
40
+ async getVersion(options) {
41
+ return (await this.getProbe(options?.fresh === true)).version;
42
+ }
43
+ async getProbe(fresh) {
44
+ const now = Date.now();
45
+ if (!fresh && this.probe && now - this.probe.checkedAt < AVAILABILITY_TTL_MS) {
46
+ return this.probe;
47
+ }
48
+ const result = await probeVersion(this.binary);
49
+ this.probe = { ...result, checkedAt: now };
50
+ return this.probe;
51
+ }
52
+ // ---------------------------------------------------------------------------
53
+ // Review / consult templates
54
+ // ---------------------------------------------------------------------------
55
+ async runReview(request) {
56
+ return this.execute(() => buildReviewPrompt(request), request.workingDir, { kind: 'review', reasoningEffort: request.reasoningEffort, serviceTier: request.serviceTier });
57
+ }
58
+ async runConsult(request) {
59
+ return this.execute(() => buildConsultPrompt(request), request.workingDir, { kind: 'consult', reasoningEffort: request.reasoningEffort, serviceTier: request.serviceTier });
60
+ }
61
+ async execute(buildPrompt, workingDir, ctx) {
62
+ const startTime = Date.now();
63
+ const elapsed = () => Date.now() - startTime;
64
+ if (!existsSync(workingDir)) {
65
+ return {
66
+ success: false,
67
+ error: { type: 'cli_error', message: `Working directory does not exist: ${workingDir}` },
68
+ suggestion: 'Pass the absolute path of the project root as workingDir',
69
+ executionTimeMs: elapsed(),
70
+ };
71
+ }
72
+ try {
73
+ const outcome = await this.runCli(buildPrompt(), workingDir, ctx);
74
+ if (outcome.exitCode !== 0) {
75
+ const error = this.categorizeError(outcome.stderr);
76
+ return { success: false, error, suggestion: this.getSuggestion(error), executionTimeMs: elapsed() };
77
+ }
78
+ if (!outcome.stdout.trim()) {
79
+ return {
80
+ success: false,
81
+ error: { type: 'cli_error', message: `${this.getCapabilities().name} returned an empty response` },
82
+ suggestion: 'Retry; if it recurs, run the CLI by hand in the working directory to see what it prints',
83
+ executionTimeMs: elapsed(),
84
+ };
85
+ }
86
+ return { success: true, output: outcome.stdout, executionTimeMs: elapsed(), truncated: outcome.truncated || undefined };
87
+ }
88
+ catch (error) {
89
+ return this.handleException(error, startTime, ctx);
90
+ }
91
+ }
92
+ // ---------------------------------------------------------------------------
93
+ // Error handling
94
+ // ---------------------------------------------------------------------------
95
+ handleException(error, startTime, ctx) {
96
+ const err = error;
97
+ const name = this.getCapabilities().name;
98
+ const executionTimeMs = Date.now() - startTime;
99
+ if (err.code === 'ENOENT') {
100
+ this.probe = { available: false, version: null, checkedAt: Date.now() };
101
+ return {
102
+ success: false,
103
+ error: { type: 'cli_not_found', message: `${name} CLI (\`${this.binary}\`) not found on PATH` },
104
+ suggestion: this.installHint,
105
+ executionTimeMs,
106
+ };
107
+ }
108
+ if (err.message === 'TIMEOUT') {
109
+ const limits = this.getLimits(ctx);
110
+ return {
111
+ success: false,
112
+ error: {
113
+ type: 'timeout',
114
+ message: `${name} produced no output for ${Math.round(limits.inactivityTimeoutMs / 1000)}s and was stopped`,
115
+ },
116
+ suggestion: `Narrow the scope (fewer files, shorter brief) or raise ${this.id}.inactivityTimeoutMs in ~/.config/quorum/config.json`,
117
+ executionTimeMs,
118
+ };
119
+ }
120
+ if (err.message === 'MAX_TIMEOUT') {
121
+ const limits = this.getLimits(ctx);
122
+ return {
123
+ success: false,
124
+ error: {
125
+ type: 'timeout',
126
+ message: `${name} exceeded the ${Math.round(limits.maxTimeoutMs / 60_000)}-minute maximum and was stopped`,
127
+ },
128
+ suggestion: `Narrow the scope or raise ${this.id}.maxTimeoutMs in ~/.config/quorum/config.json`,
129
+ executionTimeMs,
130
+ };
131
+ }
132
+ return {
133
+ success: false,
134
+ error: { type: 'cli_error', message: err?.message || String(error) },
135
+ suggestion: 'Check the error text; run the CLI by hand to confirm it works outside quorum',
136
+ executionTimeMs,
137
+ };
138
+ }
139
+ categorizeError(stderr) {
140
+ const lower = stderr.toLowerCase();
141
+ const excerpt = stderr.slice(0, STDERR_EXCERPT);
142
+ const has = (patterns) => patterns.some((p) => lower.includes(p));
143
+ // A bare number is not a status: `file.ts:403:5` in a stack trace must not
144
+ // read as HTTP 403. Require a status-ish word within a few characters.
145
+ const httpStatus = (codes) => new RegExp(`\\b(?:http|status|code|error|response)\\b[^\\n\\d]{0,20}\\b(?:${codes})\\b`, 'i').test(stderr);
146
+ // Auth before timeout: agy reports a failed OAuth handshake as
147
+ // "authentication failed or timed out", which is a login problem, not a
148
+ // slow review, and must not be answered with "raise inactivityTimeoutMs".
149
+ const auth = [
150
+ 'unauthorized', 'forbidden', 'authentication', 'not logged in', 'not authenticated', 'invalid api key', 'invalid_api_key',
151
+ 'missing api key', 'token expired', 'please log in', 'please login', 'please run /login', ...this.extraAuthPatterns,
152
+ ];
153
+ if (has(auth) || httpStatus('401|403')) {
154
+ return { type: 'auth_error', message: `Authentication failed: ${excerpt}`, details: { stderr } };
155
+ }
156
+ if (/\btimed? ?out\b/i.test(stderr)) {
157
+ return { type: 'timeout', message: `${this.getCapabilities().name} reported a timeout: ${excerpt}` };
158
+ }
159
+ const rateLimit = [
160
+ 'rate limit', 'rate_limit', 'too many requests', 'quota exceeded', 'insufficient_quota', 'exceeded your current quota',
161
+ 'overloaded', ...this.extraRateLimitPatterns,
162
+ ];
163
+ if (has(rateLimit) || httpStatus('429')) {
164
+ return { type: 'rate_limit', message: `${this.getCapabilities().name} rate limit or quota: ${excerpt}` };
165
+ }
166
+ return { type: 'cli_error', message: excerpt || 'Unknown error' };
167
+ }
168
+ getSuggestion(error) {
169
+ switch (error.type) {
170
+ case 'rate_limit': return 'Wait a minute and retry; if it persists, check the plan limits for this CLI';
171
+ case 'auth_error': return this.authHint;
172
+ case 'cli_not_found': return this.installHint;
173
+ case 'timeout': return `Narrow the scope or raise ${this.id}.inactivityTimeoutMs in ~/.config/quorum/config.json`;
174
+ default: return `Check the error text; run \`${this.binary} --version\` to confirm the CLI works outside quorum`;
175
+ }
176
+ }
177
+ /** Combine a decoder-level message with CLI stderr into one diagnostic string. */
178
+ combineDiagnostics(message, stderr) {
179
+ return stderr.trim() ? `${message}\n\nCLI stderr: ${stderr.trim()}` : message;
180
+ }
181
+ }
182
+ // =============================================================================
183
+ // PROBE
184
+ // =============================================================================
185
+ /** Run `<binary> --version` with a hard timeout; never throws. */
186
+ export function probeVersion(binary) {
187
+ return new Promise((resolve) => {
188
+ let settled = false;
189
+ let stdout = '';
190
+ let timer;
191
+ const done = (available) => {
192
+ if (settled)
193
+ return;
194
+ settled = true;
195
+ clearTimeout(timer);
196
+ const version = available ? (stdout.trim().split('\n')[0] || null) : null;
197
+ resolve({ available, version });
198
+ };
199
+ let proc;
200
+ try {
201
+ // stderr is ignored, not piped: an undrained pipe would block a chatty
202
+ // CLI until the probe timeout and mark it unavailable for a minute.
203
+ proc = spawn(binary, ['--version'], { stdio: ['ignore', 'pipe', 'ignore'] });
204
+ }
205
+ catch {
206
+ resolve({ available: false, version: null });
207
+ return;
208
+ }
209
+ proc.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
210
+ proc.on('close', (code) => done(code === 0));
211
+ proc.on('error', () => done(false));
212
+ timer = setTimeout(() => {
213
+ try {
214
+ proc.kill('SIGKILL');
215
+ }
216
+ catch { /* ignore */ }
217
+ done(false);
218
+ }, PROBE_TIMEOUT_MS);
219
+ });
220
+ }