claude-flow 3.10.4 → 3.10.5

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 (58) hide show
  1. package/package.json +1 -1
  2. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +18 -0
  3. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.js +253 -0
  4. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.d.ts +198 -0
  5. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.js +651 -0
  6. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.d.ts +133 -0
  7. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.js +281 -0
  8. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +22 -0
  9. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.js +300 -0
  10. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.d.ts +138 -0
  11. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.js +260 -0
  12. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.d.ts +19 -0
  13. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.js +246 -0
  14. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.d.ts +123 -0
  15. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +312 -0
  16. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.d.ts +21 -0
  17. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.js +327 -0
  18. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.d.ts +125 -0
  19. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.js +350 -0
  20. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +21 -0
  21. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.js +228 -0
  22. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.d.ts +27 -0
  23. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.js +136 -0
  24. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.d.ts +45 -0
  25. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.js +242 -0
  26. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.d.ts +46 -0
  27. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.js +170 -0
  28. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.d.ts +105 -0
  29. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.js +260 -0
  30. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +20 -0
  31. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +235 -0
  32. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +51 -0
  33. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.js +179 -0
  34. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.d.ts +88 -0
  35. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.js +437 -0
  36. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.d.ts +87 -0
  37. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.js +326 -0
  38. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.d.ts +35 -0
  39. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.js +403 -0
  40. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +126 -0
  41. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.js +225 -0
  42. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.d.ts +32 -0
  43. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.js +36 -0
  44. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.d.ts +62 -0
  45. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.js +12 -0
  46. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.d.ts +30 -0
  47. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.js +210 -0
  48. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.d.ts +88 -0
  49. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.js +297 -0
  50. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.d.ts +20 -0
  51. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.js +332 -0
  52. package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.d.ts +40 -0
  53. package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.js +597 -0
  54. package/v3/@claude-flow/cli/dist/src/commands/index.js +2 -0
  55. package/v3/@claude-flow/cli/dist/src/commands/init.js +41 -4
  56. package/v3/@claude-flow/cli/dist/src/init/executor.js +25 -6
  57. package/v3/@claude-flow/cli/dist/src/init/mcp-generator.js +9 -4
  58. package/v3/@claude-flow/cli/package.json +1 -1
@@ -0,0 +1,312 @@
1
+ /**
2
+ * GAIA Adversarial Critic — ADR-135 Track D
3
+ *
4
+ * After the main agent produces a candidate answer, a Sonnet pass reviews it.
5
+ * If the critic verdict is "fail", the orchestrator re-runs the agent with the
6
+ * critique injected as additional context.
7
+ *
8
+ * Motivation (iter 29 finding): tool quality is the bottleneck on L1 (~20.8%).
9
+ * The critic catches wrong-because-of-bad-tool-result answers BEFORE submission,
10
+ * without requiring better search backends. Expected L1 lift: +3-5pp.
11
+ *
12
+ * Design:
13
+ * - NEW file only; NOT wired into gaia-bench.ts yet to avoid merge conflicts
14
+ * with in-flight iter 29/31/34 branches. Wiring is a small follow-up PR.
15
+ * - `criticReview()` — single Sonnet call, returns structured verdict.
16
+ * - `runGaiaAgentWithCritic()` — orchestration wrapper: runs agent, calls
17
+ * critic, retries once on "fail". "uncertain" is treated as "pass" (don't
18
+ * burn retries on borderline cases).
19
+ * - API errors and malformed JSON from the critic are caught; original
20
+ * candidate is returned with an error-flagged verdict.
21
+ * - Default opt-in: enableCritic=false. Set true via RunWithCriticOptions.
22
+ *
23
+ * Cost discipline:
24
+ * - Critic uses claude-sonnet-4-6 (separate from the agent's default Haiku).
25
+ * - One critic call + one optional retry = max 2 extra Sonnet calls per Q.
26
+ * - Approximate extra cost per question: ~$0.003-0.005 (well within budget).
27
+ *
28
+ * Plugin sync TODO (follow-up PR after gaia-bench wiring):
29
+ * - Update plugins/ruflo-workflows/commands/gaia-run.md with --enable-critic flag.
30
+ * - Update plugins/ruflo-workflows/skills/gaia-debugging/SKILL.md: add critic
31
+ * as a recommended diagnostic step for wrong-answer analysis.
32
+ *
33
+ * Refs: ADR-135, ADR-133, iter 29 finding, #2156
34
+ */
35
+ import { execSync } from 'node:child_process';
36
+ import { runGaiaAgent, } from './gaia-agent.js';
37
+ // ---------------------------------------------------------------------------
38
+ // Constants
39
+ // ---------------------------------------------------------------------------
40
+ const ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';
41
+ const ANTHROPIC_API_VERSION = '2023-06-01';
42
+ /** Default model for the critic — Sonnet for higher reasoning quality. */
43
+ const DEFAULT_CRITIC_MODEL = 'claude-sonnet-4-6';
44
+ /** Max tokens for the critic response (verdict JSON is short). */
45
+ const CRITIC_MAX_TOKENS = 512;
46
+ /** Sonnet pricing (input/output per million tokens, 2026-05-27).
47
+ * Used only for cost estimation in CriticVerdict. */
48
+ const SONNET_INPUT_COST_PER_M = 3.0;
49
+ const SONNET_OUTPUT_COST_PER_M = 15.0;
50
+ // ---------------------------------------------------------------------------
51
+ // Internal helpers
52
+ // ---------------------------------------------------------------------------
53
+ /** Resolve Anthropic API key using the same precedence as gaia-agent.ts. */
54
+ function resolveApiKey(override) {
55
+ if (override)
56
+ return override;
57
+ const fromEnv = process.env['ANTHROPIC_API_KEY'];
58
+ if (fromEnv)
59
+ return fromEnv;
60
+ try {
61
+ return execSync('gcloud secrets versions access latest --secret=ANTHROPIC_API_KEY', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
62
+ }
63
+ catch {
64
+ throw new Error('ANTHROPIC_API_KEY not set and gcloud fallback failed. ' +
65
+ 'Set ANTHROPIC_API_KEY env var or ensure gcloud access.');
66
+ }
67
+ }
68
+ /**
69
+ * Build the critic system prompt.
70
+ * Instructs Sonnet to act as an adversarial reviewer and respond in JSON.
71
+ */
72
+ function buildCriticSystemPrompt() {
73
+ return `You are an adversarial reviewer of agent answers on the GAIA benchmark. \
74
+ Your job is to find flaws in candidate answers before they are submitted.
75
+
76
+ Given a question, a candidate answer, and a summary of the agent's reasoning \
77
+ trajectory, you must decide whether the candidate answer is correct.
78
+
79
+ Evaluation criteria:
80
+ 1. Does the answer directly address what the question asks?
81
+ 2. Is there evidence in the trajectory that supports the answer?
82
+ 3. Are there obvious flaws (wrong unit, wrong format, missed constraint, \
83
+ fabricated source, off-by-one error, truncation)?
84
+ 4. For numeric answers: is the magnitude and unit plausible?
85
+ 5. For list answers: are all required items present and correctly ordered?
86
+
87
+ Respond ONLY with a JSON object — no markdown, no prose outside the JSON:
88
+ {"verdict":"pass"|"fail"|"uncertain","reasoning":"<1-3 sentences>","suggestedRevision":"<corrected answer or empty string>"}
89
+
90
+ Use "uncertain" only when you genuinely cannot determine correctness from the \
91
+ available information. Never use "uncertain" to avoid making a decision when \
92
+ evidence is available.`;
93
+ }
94
+ /**
95
+ * Build the critic user message combining the question, candidate answer,
96
+ * and a compressed view of the agent trajectory.
97
+ */
98
+ function buildCriticUserMessage(question, candidateAnswer, trajectory) {
99
+ // Summarise trajectory: first 2 + last 2 steps to keep tokens bounded.
100
+ const steps = trajectory.steps ?? [];
101
+ const summarised = steps.length <= 4
102
+ ? steps
103
+ : [...steps.slice(0, 2), ...steps.slice(-2)];
104
+ const trajectoryText = summarised.length === 0
105
+ ? '(no tool calls recorded)'
106
+ : summarised.map((s, i) => {
107
+ const label = s.tool ? `Step ${i + 1} [${s.tool}]` : `Step ${i + 1}`;
108
+ const result = s.result ? ` → ${s.result.slice(0, 200)}` : '';
109
+ return `${label}${result}`;
110
+ }).join('\n');
111
+ return `QUESTION: ${question.question}
112
+
113
+ CANDIDATE ANSWER: ${candidateAnswer}
114
+
115
+ AGENT TRAJECTORY (${trajectory.turns} turns, summarised):
116
+ ${trajectoryText}`;
117
+ }
118
+ /**
119
+ * Attempt to extract a verdict from a potentially malformed JSON string.
120
+ * Falls back gracefully to "uncertain" with the raw text preserved.
121
+ */
122
+ function parseVerdictFallback(raw) {
123
+ // Try standard JSON parse first.
124
+ try {
125
+ const parsed = JSON.parse(raw);
126
+ const verdict = parsed['verdict'];
127
+ if (verdict === 'pass' || verdict === 'fail' || verdict === 'uncertain') {
128
+ return {
129
+ verdict,
130
+ reasoning: parsed['reasoning'] ?? '',
131
+ suggestedRevision: parsed['suggestedRevision'] ?? '',
132
+ };
133
+ }
134
+ }
135
+ catch {
136
+ // Fall through to regex extraction.
137
+ }
138
+ // Regex extraction for embedded JSON in prose.
139
+ const jsonMatch = raw.match(/\{[\s\S]*?"verdict"\s*:\s*"(pass|fail|uncertain)"[\s\S]*?\}/);
140
+ if (jsonMatch) {
141
+ try {
142
+ const parsed = JSON.parse(jsonMatch[0]);
143
+ return {
144
+ verdict: parsed['verdict'],
145
+ reasoning: parsed['reasoning'] ?? '',
146
+ suggestedRevision: parsed['suggestedRevision'] ?? '',
147
+ };
148
+ }
149
+ catch {
150
+ // Fall through.
151
+ }
152
+ }
153
+ // Last resort: extract verdict keyword from raw text.
154
+ const verdictMatch = raw.match(/\b(pass|fail|uncertain)\b/i);
155
+ return {
156
+ verdict: verdictMatch
157
+ ? verdictMatch[1].toLowerCase()
158
+ : 'uncertain',
159
+ reasoning: `Critic returned malformed JSON; extracted verdict heuristically.`,
160
+ suggestedRevision: '',
161
+ rawResponse: raw.slice(0, 500),
162
+ };
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Core critic function
166
+ // ---------------------------------------------------------------------------
167
+ /**
168
+ * Run the adversarial critic against a candidate answer.
169
+ *
170
+ * @param question - The GAIA question being evaluated.
171
+ * @param candidateAnswer - The agent's proposed final answer.
172
+ * @param trajectory - Lightweight trajectory summary from the agent run.
173
+ * @param options - Critic configuration (model, apiKey).
174
+ * @returns CriticVerdict with verdict, reasoning, cost.
175
+ */
176
+ export async function criticReview(question, candidateAnswer, trajectory, options) {
177
+ const model = options?.model ?? DEFAULT_CRITIC_MODEL;
178
+ const apiKey = resolveApiKey(options?.apiKey);
179
+ const t0 = Date.now();
180
+ const requestBody = {
181
+ model,
182
+ max_tokens: CRITIC_MAX_TOKENS,
183
+ system: buildCriticSystemPrompt(),
184
+ messages: [
185
+ {
186
+ role: 'user',
187
+ content: buildCriticUserMessage(question, candidateAnswer, trajectory),
188
+ },
189
+ ],
190
+ };
191
+ let rawResponseText = '';
192
+ try {
193
+ const response = await fetch(ANTHROPIC_API_URL, {
194
+ method: 'POST',
195
+ headers: {
196
+ 'Content-Type': 'application/json',
197
+ 'x-api-key': apiKey,
198
+ 'anthropic-version': ANTHROPIC_API_VERSION,
199
+ },
200
+ body: JSON.stringify(requestBody),
201
+ });
202
+ if (!response.ok) {
203
+ const errText = await response.text().catch(() => '');
204
+ throw new Error(`Anthropic API error ${response.status}: ${errText.slice(0, 200)}`);
205
+ }
206
+ const data = await response.json();
207
+ const inputTokens = data.usage?.input_tokens ?? 0;
208
+ const outputTokens = data.usage?.output_tokens ?? 0;
209
+ const costUsd = (inputTokens / 1_000_000) * SONNET_INPUT_COST_PER_M +
210
+ (outputTokens / 1_000_000) * SONNET_OUTPUT_COST_PER_M;
211
+ rawResponseText = data.content
212
+ .filter(b => b.type === 'text')
213
+ .map(b => b.text ?? '')
214
+ .join('');
215
+ const parsed = parseVerdictFallback(rawResponseText);
216
+ return {
217
+ verdict: parsed.verdict ?? 'uncertain',
218
+ reasoning: parsed.reasoning ?? '',
219
+ suggestedRevision: parsed.suggestedRevision ?? '',
220
+ costUsd,
221
+ ...(parsed.rawResponse ? { rawResponse: parsed.rawResponse } : {}),
222
+ };
223
+ }
224
+ catch (err) {
225
+ const wallMs = Date.now() - t0;
226
+ const errMsg = err instanceof Error ? err.message : String(err);
227
+ // Graceful fallback: treat critic error as "uncertain" so agent result
228
+ // is still returned rather than throwing.
229
+ return {
230
+ verdict: 'uncertain',
231
+ reasoning: `Critic call failed after ${wallMs}ms: ${errMsg.slice(0, 200)}`,
232
+ suggestedRevision: '',
233
+ costUsd: 0,
234
+ error: true,
235
+ rawResponse: rawResponseText.slice(0, 200) || undefined,
236
+ };
237
+ }
238
+ }
239
+ // ---------------------------------------------------------------------------
240
+ // Orchestration wrapper
241
+ // ---------------------------------------------------------------------------
242
+ /**
243
+ * Run the GAIA agent with an optional adversarial critic pass.
244
+ *
245
+ * When enableCritic=false (default), this is a thin pass-through to
246
+ * runGaiaAgent with an empty criticVerdicts array.
247
+ *
248
+ * When enableCritic=true:
249
+ * 1. Run runGaiaAgent normally.
250
+ * 2. If the agent produced a finalAnswer, call criticReview.
251
+ * 3. If verdict is "fail" and retriesAttempted < maxRetries:
252
+ * a. Re-run the agent with the critique injected as additional context.
253
+ * b. Call criticReview again on the new answer.
254
+ * 4. Return the final result with all critic verdicts attached.
255
+ *
256
+ * Note on "uncertain": treated as "pass" (no retry triggered).
257
+ */
258
+ export async function runGaiaAgentWithCritic(question, options = {}) {
259
+ const { enableCritic = false, criticOptions, ...agentOptions } = options;
260
+ // Fast path: critic disabled.
261
+ if (!enableCritic) {
262
+ const result = await runGaiaAgent(question, agentOptions);
263
+ return { ...result, criticVerdicts: [], retriesAttempted: 0 };
264
+ }
265
+ const maxRetries = criticOptions?.maxRetries ?? 1;
266
+ const criticVerdicts = [];
267
+ let retriesAttempted = 0;
268
+ // First agent run.
269
+ let agentResult = await runGaiaAgent(question, agentOptions);
270
+ // If agent timed out or errored with no answer, skip critic.
271
+ if (agentResult.finalAnswer == null) {
272
+ return { ...agentResult, criticVerdicts, retriesAttempted };
273
+ }
274
+ // Build a lightweight trajectory summary from the agent result.
275
+ // gaia-agent.ts doesn't expose step-level detail in GaiaAgentResult, so we
276
+ // synthesise from the available fields (tool call counts, turn count).
277
+ const makeTrajectory = (result) => ({
278
+ turns: result.turns,
279
+ steps: Object.entries(result.toolCallsByName).map(([tool, count]) => ({
280
+ tool,
281
+ result: `called ${count} time(s)`,
282
+ })),
283
+ });
284
+ // First critic pass.
285
+ let verdict = await criticReview(question, agentResult.finalAnswer, makeTrajectory(agentResult), criticOptions);
286
+ criticVerdicts.push(verdict);
287
+ // Retry loop on "fail".
288
+ while (verdict.verdict === 'fail' && retriesAttempted < maxRetries) {
289
+ retriesAttempted += 1;
290
+ // Inject critique as additional context via the system prompt append.
291
+ // We pass it through GaiaAgentOptions.criticFeedback — gaia-agent.ts does
292
+ // NOT yet read this field (wiring is follow-up PR), but storing it here
293
+ // makes the contract explicit and harmless (unknown options are ignored).
294
+ const retryOptions = {
295
+ ...agentOptions,
296
+ criticFeedback: `Previous answer "${agentResult.finalAnswer}" was flagged by adversarial review: ` +
297
+ `${verdict.reasoning}` +
298
+ (verdict.suggestedRevision
299
+ ? ` Suggested revision: ${verdict.suggestedRevision}`
300
+ : ''),
301
+ };
302
+ agentResult = await runGaiaAgent(question, retryOptions);
303
+ if (agentResult.finalAnswer == null) {
304
+ // Retry yielded no answer; stop retrying.
305
+ break;
306
+ }
307
+ verdict = await criticReview(question, agentResult.finalAnswer, makeTrajectory(agentResult), criticOptions);
308
+ criticVerdicts.push(verdict);
309
+ }
310
+ return { ...agentResult, criticVerdicts, retriesAttempted };
311
+ }
312
+ //# sourceMappingURL=gaia-critic.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * GAIA Critic Smoke Tests — ADR-135 Track D
3
+ *
4
+ * Tests for the adversarial critic agent in gaia-critic.ts.
5
+ * All tests use mocked responses — NO live API calls.
6
+ *
7
+ * Test coverage:
8
+ * 1. Critic returns "pass" → no retry, immediately returns candidate
9
+ * 2. Critic returns "fail" with suggestedRevision → triggers one retry
10
+ * 3. Critic returns "fail" twice → retries exhausted, returns last candidate
11
+ * 4. Critic returns "uncertain" → treated as "pass", no retry
12
+ * 5. API error in critic → graceful fallback, returns candidate as-is
13
+ * 6. Malformed JSON from critic → fallback parser extracts verdict
14
+ *
15
+ * Usage (no API key required):
16
+ * npx tsx src/benchmarks/gaia-critic.smoke.ts
17
+ *
18
+ * Refs: ADR-135, #2156
19
+ */
20
+ export {};
21
+ //# sourceMappingURL=gaia-critic.smoke.d.ts.map
@@ -0,0 +1,327 @@
1
+ /**
2
+ * GAIA Critic Smoke Tests — ADR-135 Track D
3
+ *
4
+ * Tests for the adversarial critic agent in gaia-critic.ts.
5
+ * All tests use mocked responses — NO live API calls.
6
+ *
7
+ * Test coverage:
8
+ * 1. Critic returns "pass" → no retry, immediately returns candidate
9
+ * 2. Critic returns "fail" with suggestedRevision → triggers one retry
10
+ * 3. Critic returns "fail" twice → retries exhausted, returns last candidate
11
+ * 4. Critic returns "uncertain" → treated as "pass", no retry
12
+ * 5. API error in critic → graceful fallback, returns candidate as-is
13
+ * 6. Malformed JSON from critic → fallback parser extracts verdict
14
+ *
15
+ * Usage (no API key required):
16
+ * npx tsx src/benchmarks/gaia-critic.smoke.ts
17
+ *
18
+ * Refs: ADR-135, #2156
19
+ */
20
+ import { criticReview, runGaiaAgentWithCritic, } from './gaia-critic.js';
21
+ // ---------------------------------------------------------------------------
22
+ // Test helpers
23
+ // ---------------------------------------------------------------------------
24
+ let passed = 0;
25
+ let failed = 0;
26
+ function assert(condition, message) {
27
+ if (condition) {
28
+ console.log(` PASS ${message}`);
29
+ passed++;
30
+ }
31
+ else {
32
+ console.error(` FAIL ${message}`);
33
+ failed++;
34
+ }
35
+ }
36
+ function assertEqual(actual, expected, message) {
37
+ assert(actual === expected, `${message} (expected ${String(expected)}, got ${String(actual)})`);
38
+ }
39
+ /** A minimal GaiaQuestion fixture. */
40
+ const FIXTURE_QUESTION = {
41
+ task_id: 'smoke-001',
42
+ level: 1,
43
+ question: 'What is the capital of France?',
44
+ final_answer: 'Paris',
45
+ file_name: null,
46
+ file_path: null,
47
+ };
48
+ /** Minimal GaiaAgentResult with a given finalAnswer. */
49
+ function makeAgentResult(finalAnswer, turns = 2) {
50
+ return {
51
+ questionId: FIXTURE_QUESTION.task_id,
52
+ finalAnswer,
53
+ turns,
54
+ toolCallsByName: { web_search: 1 },
55
+ totalInputTokens: 100,
56
+ totalOutputTokens: 50,
57
+ wallMs: 1200,
58
+ };
59
+ }
60
+ function installFetchMock(responses) {
61
+ let callIndex = 0;
62
+ const original = globalThis.fetch;
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ globalThis.fetch = async (_url, _init) => {
65
+ const resp = responses[Math.min(callIndex, responses.length - 1)];
66
+ callIndex++;
67
+ if (!resp.ok) {
68
+ return {
69
+ ok: false,
70
+ status: resp.status ?? 500,
71
+ text: async () => resp.text ?? 'Internal error',
72
+ json: async () => { throw new Error('not ok'); },
73
+ };
74
+ }
75
+ return {
76
+ ok: true,
77
+ status: 200,
78
+ json: async () => resp.body ?? {},
79
+ text: async () => JSON.stringify(resp.body ?? {}),
80
+ };
81
+ };
82
+ return () => { globalThis.fetch = original; };
83
+ }
84
+ /**
85
+ * Build a mock Anthropic response body containing a critic verdict JSON.
86
+ */
87
+ function mockCriticResponse(verdict, reasoning, suggestedRevision = '') {
88
+ const content = JSON.stringify({ verdict, reasoning, suggestedRevision });
89
+ return {
90
+ content: [{ type: 'text', text: content }],
91
+ usage: { input_tokens: 200, output_tokens: 40 },
92
+ };
93
+ }
94
+ /**
95
+ * Mock for runGaiaAgent that immediately returns a fixed result.
96
+ * We monkey-patch the module-level import by wrapping runGaiaAgentWithCritic
97
+ * via its options.catalogue approach — but since gaia-agent's runGaiaAgent is
98
+ * imported directly, we mock at the fetch level instead (the agent also calls
99
+ * the Anthropic API, so we intercept there).
100
+ *
101
+ * For the smoke tests we only exercise criticReview directly in Tests 1-6, and
102
+ * use a simplified version of runGaiaAgentWithCritic that pre-supplies a
103
+ * mocked agent result rather than actually calling the API for the agent run.
104
+ *
105
+ * This avoids needing to rewrite the import mechanism just for smoke tests.
106
+ */
107
+ // ---------------------------------------------------------------------------
108
+ // Test 1: critic returns "pass" → no retry
109
+ // ---------------------------------------------------------------------------
110
+ async function test1_criticPass() {
111
+ console.log('\nTest 1: critic returns "pass" → no retry');
112
+ const restore = installFetchMock([
113
+ { ok: true, body: mockCriticResponse('pass', 'Answer is correct.') },
114
+ ]);
115
+ try {
116
+ const verdict = await criticReview(FIXTURE_QUESTION, 'Paris', { steps: [{ tool: 'web_search', result: 'Paris is the capital' }], turns: 2 }, { model: 'claude-sonnet-4-6', apiKey: 'test-key' });
117
+ assertEqual(verdict.verdict, 'pass', 'verdict is "pass"');
118
+ assert(verdict.reasoning.length > 0, 'reasoning is non-empty');
119
+ assert(verdict.costUsd >= 0, 'costUsd is non-negative');
120
+ assert(!verdict.error, 'no error flag');
121
+ }
122
+ finally {
123
+ restore();
124
+ }
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // Test 2: critic returns "fail" with suggestedRevision
128
+ // ---------------------------------------------------------------------------
129
+ async function test2_criticFail() {
130
+ console.log('\nTest 2: critic returns "fail" with suggestedRevision');
131
+ const restore = installFetchMock([
132
+ {
133
+ ok: true,
134
+ body: mockCriticResponse('fail', 'The answer is the wrong city.', 'Paris'),
135
+ },
136
+ ]);
137
+ try {
138
+ const verdict = await criticReview(FIXTURE_QUESTION, 'Lyon', { steps: [{ tool: 'web_search', result: 'Lyon is in France' }], turns: 1 }, { model: 'claude-sonnet-4-6', apiKey: 'test-key' });
139
+ assertEqual(verdict.verdict, 'fail', 'verdict is "fail"');
140
+ assert((verdict.suggestedRevision ?? '').length > 0, 'suggestedRevision is non-empty');
141
+ assertEqual(verdict.suggestedRevision, 'Paris', 'suggestedRevision is "Paris"');
142
+ }
143
+ finally {
144
+ restore();
145
+ }
146
+ }
147
+ // ---------------------------------------------------------------------------
148
+ // Test 3: critic returns "fail" twice → retries exhausted
149
+ // ---------------------------------------------------------------------------
150
+ async function test3_retriesExhausted() {
151
+ console.log('\nTest 3: critic fails twice → retries exhausted, returns last candidate');
152
+ // We test this at the runGaiaAgentWithCritic level.
153
+ // We need to mock BOTH the critic fetch calls AND the agent API calls.
154
+ // Strategy: sequence the mock responses in the order they will be called.
155
+ //
156
+ // Call sequence (with enableCritic=true, maxRetries=1):
157
+ // 1. runGaiaAgent attempt 1 → agent Anthropic API call (returns answer "Lyon")
158
+ // 2. criticReview attempt 1 → critic API call (returns "fail")
159
+ // 3. runGaiaAgent attempt 2 → agent Anthropic API call (returns answer "Marseille")
160
+ // 4. criticReview attempt 2 → critic API call (returns "fail")
161
+ //
162
+ // For simplicity we make the agent calls also return valid Anthropic responses
163
+ // that produce a FINAL_ANSWER (the agent code parses stop_reason=end_turn).
164
+ const agentResponseLyon = {
165
+ id: 'msg_01',
166
+ type: 'message',
167
+ role: 'assistant',
168
+ stop_reason: 'end_turn',
169
+ content: [{ type: 'text', text: 'FINAL_ANSWER: Lyon' }],
170
+ usage: { input_tokens: 150, output_tokens: 20 },
171
+ model: 'claude-haiku-4-5',
172
+ };
173
+ const agentResponseMarseille = {
174
+ id: 'msg_02',
175
+ type: 'message',
176
+ role: 'assistant',
177
+ stop_reason: 'end_turn',
178
+ content: [{ type: 'text', text: 'FINAL_ANSWER: Marseille' }],
179
+ usage: { input_tokens: 150, output_tokens: 20 },
180
+ model: 'claude-haiku-4-5',
181
+ };
182
+ const restore = installFetchMock([
183
+ { ok: true, body: agentResponseLyon }, // agent call 1
184
+ { ok: true, body: mockCriticResponse('fail', 'Wrong city.', 'Paris') }, // critic 1
185
+ { ok: true, body: agentResponseMarseille }, // agent call 2 (retry)
186
+ { ok: true, body: mockCriticResponse('fail', 'Still wrong.', 'Paris') }, // critic 2
187
+ ]);
188
+ try {
189
+ const result = await runGaiaAgentWithCritic(FIXTURE_QUESTION, {
190
+ enableCritic: true,
191
+ apiKey: 'test-key',
192
+ criticOptions: { apiKey: 'test-key', maxRetries: 1 },
193
+ });
194
+ assertEqual(result.retriesAttempted, 1, 'retriesAttempted is 1');
195
+ assertEqual(result.criticVerdicts.length, 2, 'two critic verdicts collected');
196
+ assertEqual(result.criticVerdicts[0].verdict, 'fail', 'first verdict is fail');
197
+ assertEqual(result.criticVerdicts[1].verdict, 'fail', 'second verdict is fail');
198
+ // Last candidate is returned regardless.
199
+ assert(result.finalAnswer !== null, 'finalAnswer is non-null (last candidate returned)');
200
+ }
201
+ finally {
202
+ restore();
203
+ }
204
+ }
205
+ // ---------------------------------------------------------------------------
206
+ // Test 4: critic returns "uncertain" → treated as "pass", no retry
207
+ // ---------------------------------------------------------------------------
208
+ async function test4_uncertainAsPass() {
209
+ console.log('\nTest 4: critic returns "uncertain" → treated as pass, no retry');
210
+ const restore = installFetchMock([
211
+ {
212
+ ok: true,
213
+ body: mockCriticResponse('uncertain', 'Cannot verify without more context.'),
214
+ },
215
+ ]);
216
+ try {
217
+ const verdict = await criticReview(FIXTURE_QUESTION, 'Paris', { steps: [], turns: 1 }, { model: 'claude-sonnet-4-6', apiKey: 'test-key' });
218
+ assertEqual(verdict.verdict, 'uncertain', 'verdict is "uncertain"');
219
+ // Verify orchestrator treats uncertain as pass (no retry fired).
220
+ // We simulate by checking the logic directly: uncertain !== 'fail', so loop
221
+ // body is skipped. We test it via runGaiaAgentWithCritic with a minimal
222
+ // agent mock that returns a final answer.
223
+ const agentResponseParis = {
224
+ id: 'msg_03',
225
+ type: 'message',
226
+ role: 'assistant',
227
+ stop_reason: 'end_turn',
228
+ content: [{ type: 'text', text: 'FINAL_ANSWER: Paris' }],
229
+ usage: { input_tokens: 100, output_tokens: 15 },
230
+ model: 'claude-haiku-4-5',
231
+ };
232
+ const restore2 = installFetchMock([
233
+ { ok: true, body: agentResponseParis }, // agent call
234
+ { ok: true, body: mockCriticResponse('uncertain', 'Cannot verify.') }, // critic
235
+ ]);
236
+ try {
237
+ const result = await runGaiaAgentWithCritic(FIXTURE_QUESTION, {
238
+ enableCritic: true,
239
+ apiKey: 'test-key',
240
+ criticOptions: { apiKey: 'test-key', maxRetries: 1 },
241
+ });
242
+ assertEqual(result.retriesAttempted, 0, 'no retries for uncertain verdict');
243
+ assertEqual(result.criticVerdicts.length, 1, 'one critic verdict collected');
244
+ assertEqual(result.criticVerdicts[0].verdict, 'uncertain', 'verdict is uncertain');
245
+ }
246
+ finally {
247
+ restore2();
248
+ }
249
+ }
250
+ finally {
251
+ restore();
252
+ }
253
+ }
254
+ // ---------------------------------------------------------------------------
255
+ // Test 5: API error in critic → graceful fallback
256
+ // ---------------------------------------------------------------------------
257
+ async function test5_apiErrorFallback() {
258
+ console.log('\nTest 5: API error in critic → graceful fallback, original candidate returned');
259
+ const restore = installFetchMock([
260
+ { ok: false, status: 529, text: 'Overloaded' },
261
+ ]);
262
+ try {
263
+ const verdict = await criticReview(FIXTURE_QUESTION, 'Paris', { steps: [], turns: 1 }, { model: 'claude-sonnet-4-6', apiKey: 'test-key' });
264
+ // On API error, critic returns uncertain with error flag — does not throw.
265
+ assertEqual(verdict.verdict, 'uncertain', 'verdict is "uncertain" on API error');
266
+ assert(verdict.error === true, 'error flag is set');
267
+ assert(verdict.costUsd === 0, 'costUsd is 0 on error');
268
+ assert(verdict.reasoning.includes('failed'), 'reasoning mentions failure');
269
+ }
270
+ finally {
271
+ restore();
272
+ }
273
+ }
274
+ // ---------------------------------------------------------------------------
275
+ // Test 6: malformed JSON from critic → fallback parser
276
+ // ---------------------------------------------------------------------------
277
+ async function test6_malformedJson() {
278
+ console.log('\nTest 6: malformed JSON from critic → fallback parser extracts verdict');
279
+ // Simulate Sonnet returning prose with embedded JSON fragment.
280
+ const malformedBody = {
281
+ content: [{
282
+ type: 'text',
283
+ text: 'After careful review, I believe the answer is wrong. {"verdict":"fail","reasoning":"Incorrect city","suggestedRevision":"Paris"} The agent should try again.',
284
+ }],
285
+ usage: { input_tokens: 180, output_tokens: 60 },
286
+ };
287
+ const restore = installFetchMock([
288
+ { ok: true, body: malformedBody },
289
+ ]);
290
+ try {
291
+ const verdict = await criticReview(FIXTURE_QUESTION, 'Lyon', { steps: [], turns: 1 }, { model: 'claude-sonnet-4-6', apiKey: 'test-key' });
292
+ // Fallback parser should extract "fail" from the embedded JSON.
293
+ assertEqual(verdict.verdict, 'fail', 'fallback parser extracts "fail" verdict');
294
+ assert(!verdict.error, 'no error flag for recoverable parse');
295
+ }
296
+ finally {
297
+ restore();
298
+ }
299
+ }
300
+ // ---------------------------------------------------------------------------
301
+ // Run all tests
302
+ // ---------------------------------------------------------------------------
303
+ async function main() {
304
+ console.log('=== GAIA Critic Smoke Tests (ADR-135 Track D) ===');
305
+ console.log('All tests use mocked responses — no live API calls.\n');
306
+ try {
307
+ await test1_criticPass();
308
+ await test2_criticFail();
309
+ await test3_retriesExhausted();
310
+ await test4_uncertainAsPass();
311
+ await test5_apiErrorFallback();
312
+ await test6_malformedJson();
313
+ }
314
+ catch (err) {
315
+ console.error('\nUnexpected test runner error:', err);
316
+ process.exit(1);
317
+ }
318
+ console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
319
+ if (failed > 0) {
320
+ process.exit(1);
321
+ }
322
+ }
323
+ main().catch(err => {
324
+ console.error(err);
325
+ process.exit(1);
326
+ });
327
+ //# sourceMappingURL=gaia-critic.smoke.js.map