@workermill/agent 0.3.1 → 0.4.0
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.
- package/dist/commands/start.js +12 -3
- package/dist/config.d.ts +2 -0
- package/dist/config.js +2 -0
- package/dist/planner.d.ts +2 -0
- package/dist/planner.js +359 -129
- package/dist/spawner.js +10 -7
- package/package.json +1 -1
package/dist/commands/start.js
CHANGED
|
@@ -25,14 +25,23 @@ export async function startCommand(options) {
|
|
|
25
25
|
const failing = prereqs.filter((p) => !p.ok);
|
|
26
26
|
// Auto-pull worker image if it's the only missing prereq
|
|
27
27
|
const imageMissing = failing.find((p) => p.name === "Worker image");
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
// Claude CLI and auth are soft prerequisites — only needed for Anthropic provider.
|
|
29
|
+
// Non-Anthropic orgs can plan+execute without Claude CLI.
|
|
30
|
+
const softPrereqs = new Set(["Claude CLI", "Claude auth"]);
|
|
31
|
+
const hardFailing = failing.filter((p) => p.name !== "Worker image" && !softPrereqs.has(p.name));
|
|
32
|
+
const softFailing = failing.filter((p) => softPrereqs.has(p.name));
|
|
33
|
+
if (hardFailing.length > 0) {
|
|
30
34
|
console.log(chalk.red("Prerequisites check failed:"));
|
|
31
|
-
for (const p of
|
|
35
|
+
for (const p of hardFailing) {
|
|
32
36
|
console.log(chalk.red(` ✗ ${p.name}: ${p.detail}`));
|
|
33
37
|
}
|
|
34
38
|
process.exit(1);
|
|
35
39
|
}
|
|
40
|
+
if (softFailing.length > 0) {
|
|
41
|
+
for (const p of softFailing) {
|
|
42
|
+
console.log(chalk.yellow(` ⚠ ${p.name}: ${p.detail} (required for Anthropic provider)`));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
36
45
|
if (imageMissing) {
|
|
37
46
|
console.log(chalk.yellow(` Worker image not found locally. Pulling ${config.workerImage}...`));
|
|
38
47
|
const { spawnSync } = await import("child_process");
|
package/dist/config.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ export interface AgentConfig {
|
|
|
16
16
|
bitbucketToken: string;
|
|
17
17
|
gitlabToken: string;
|
|
18
18
|
workerImage: string;
|
|
19
|
+
teamPlanningEnabled: boolean;
|
|
19
20
|
}
|
|
20
21
|
export interface FileConfig {
|
|
21
22
|
apiUrl: string;
|
|
@@ -30,6 +31,7 @@ export interface FileConfig {
|
|
|
30
31
|
gitlab: string;
|
|
31
32
|
};
|
|
32
33
|
workerImage: string;
|
|
34
|
+
teamPlanningEnabled?: boolean;
|
|
33
35
|
setupCompletedAt: string;
|
|
34
36
|
}
|
|
35
37
|
export declare function getConfigDir(): string;
|
package/dist/config.js
CHANGED
|
@@ -75,6 +75,7 @@ export function loadConfigFromFile() {
|
|
|
75
75
|
bitbucketToken: fc.tokens?.bitbucket || "",
|
|
76
76
|
gitlabToken: fc.tokens?.gitlab || "",
|
|
77
77
|
workerImage,
|
|
78
|
+
teamPlanningEnabled: fc.teamPlanningEnabled ?? true,
|
|
78
79
|
};
|
|
79
80
|
}
|
|
80
81
|
/**
|
|
@@ -119,6 +120,7 @@ export function loadConfig() {
|
|
|
119
120
|
bitbucketToken: process.env.BITBUCKET_TOKEN || "",
|
|
120
121
|
gitlabToken: process.env.GITLAB_TOKEN || "",
|
|
121
122
|
workerImage: process.env.WORKER_IMAGE || "workermill-worker:local",
|
|
123
|
+
teamPlanningEnabled: process.env.TEAM_PLANNING_ENABLED !== "false",
|
|
122
124
|
};
|
|
123
125
|
}
|
|
124
126
|
/**
|
package/dist/planner.d.ts
CHANGED
package/dist/planner.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* sees the same planning progress as cloud mode.
|
|
16
16
|
*/
|
|
17
17
|
import chalk from "chalk";
|
|
18
|
-
import { spawn } from "child_process";
|
|
18
|
+
import { spawn, execSync } from "child_process";
|
|
19
19
|
import { findClaudePath } from "./config.js";
|
|
20
20
|
import { api } from "./api.js";
|
|
21
21
|
import { parseExecutionPlan, applyFileCap, serializePlan, runCriticValidation, formatCriticFeedback, AUTO_APPROVAL_THRESHOLD, } from "./plan-validator.js";
|
|
@@ -204,8 +204,8 @@ function runClaudeCli(claudePath, model, prompt, env, taskId, startTime) {
|
|
|
204
204
|
clearInterval(progressInterval);
|
|
205
205
|
clearInterval(sseProgressInterval);
|
|
206
206
|
proc.kill("SIGTERM");
|
|
207
|
-
reject(new Error("Claude CLI timed out after
|
|
208
|
-
},
|
|
207
|
+
reject(new Error("Claude CLI timed out after 20 minutes"));
|
|
208
|
+
}, 1_200_000);
|
|
209
209
|
proc.on("exit", (code) => {
|
|
210
210
|
clearTimeout(timeout);
|
|
211
211
|
clearInterval(progressInterval);
|
|
@@ -249,6 +249,199 @@ function resolveProviderApiKey(provider, credentials) {
|
|
|
249
249
|
return undefined;
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Build a git clone URL with authentication for the given SCM provider.
|
|
254
|
+
*/
|
|
255
|
+
function buildCloneUrl(repo, token, scmProvider) {
|
|
256
|
+
switch (scmProvider) {
|
|
257
|
+
case "bitbucket":
|
|
258
|
+
return `https://x-token-auth:${token}@bitbucket.org/${repo}.git`;
|
|
259
|
+
case "gitlab":
|
|
260
|
+
return `https://oauth2:${token}@gitlab.com/${repo}.git`;
|
|
261
|
+
case "github":
|
|
262
|
+
default:
|
|
263
|
+
return `https://x-access-token:${token}@github.com/${repo}.git`;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Clone the target repo to a temp directory for team planning analysis.
|
|
268
|
+
* Returns the path on success, or null on failure (fallback to single-agent).
|
|
269
|
+
*/
|
|
270
|
+
async function cloneTargetRepo(repo, token, scmProvider, taskId) {
|
|
271
|
+
const taskLabel = chalk.cyan(taskId.slice(0, 8));
|
|
272
|
+
const tmpDir = `/tmp/workermill-planning-${taskId.slice(0, 8)}-${Date.now()}`;
|
|
273
|
+
try {
|
|
274
|
+
const cloneUrl = buildCloneUrl(repo, token, scmProvider);
|
|
275
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim("Cloning repo for team planning...")}`);
|
|
276
|
+
execSync(`git clone --depth 1 --single-branch "${cloneUrl}" "${tmpDir}"`, {
|
|
277
|
+
stdio: "ignore",
|
|
278
|
+
timeout: 60_000,
|
|
279
|
+
});
|
|
280
|
+
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} Repo cloned to ${chalk.dim(tmpDir)}`);
|
|
281
|
+
return tmpDir;
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
285
|
+
console.error(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} Clone failed, falling back to single-agent: ${errMsg.substring(0, 100)}`);
|
|
286
|
+
// Cleanup partial clone
|
|
287
|
+
try {
|
|
288
|
+
execSync(`rm -rf "${tmpDir}"`, { stdio: "ignore" });
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
/* ignore */
|
|
292
|
+
}
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Run an analyst agent via Claude CLI with tool access to the cloned repo.
|
|
298
|
+
* Returns the analyst's report text, or an empty string on failure.
|
|
299
|
+
*/
|
|
300
|
+
function runAnalyst(claudePath, model, prompt, repoPath, env, timeoutMs = 120_000) {
|
|
301
|
+
return new Promise((resolve) => {
|
|
302
|
+
const proc = spawn(claudePath, [
|
|
303
|
+
"-p",
|
|
304
|
+
prompt,
|
|
305
|
+
"--model",
|
|
306
|
+
model,
|
|
307
|
+
"--permission-mode",
|
|
308
|
+
"bypassPermissions",
|
|
309
|
+
"--output-format",
|
|
310
|
+
"stream-json",
|
|
311
|
+
], {
|
|
312
|
+
cwd: repoPath,
|
|
313
|
+
env,
|
|
314
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
315
|
+
});
|
|
316
|
+
let resultText = "";
|
|
317
|
+
let fullText = "";
|
|
318
|
+
let lineBuffer = "";
|
|
319
|
+
proc.stdout.on("data", (data) => {
|
|
320
|
+
lineBuffer += data.toString();
|
|
321
|
+
const lines = lineBuffer.split("\n");
|
|
322
|
+
lineBuffer = lines.pop() || "";
|
|
323
|
+
for (const line of lines) {
|
|
324
|
+
const trimmed = line.trim();
|
|
325
|
+
if (!trimmed)
|
|
326
|
+
continue;
|
|
327
|
+
try {
|
|
328
|
+
const event = JSON.parse(trimmed);
|
|
329
|
+
if (event.type === "content_block_delta" && event.delta?.text) {
|
|
330
|
+
fullText += event.delta.text;
|
|
331
|
+
}
|
|
332
|
+
else if (event.type === "result" && event.result) {
|
|
333
|
+
resultText =
|
|
334
|
+
typeof event.result === "string" ? event.result : "";
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
fullText += trimmed + "\n";
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
const timeout = setTimeout(() => {
|
|
343
|
+
proc.kill("SIGTERM");
|
|
344
|
+
resolve(resultText || fullText || "");
|
|
345
|
+
}, timeoutMs);
|
|
346
|
+
proc.on("exit", () => {
|
|
347
|
+
clearTimeout(timeout);
|
|
348
|
+
resolve(resultText || fullText || "");
|
|
349
|
+
});
|
|
350
|
+
proc.on("error", () => {
|
|
351
|
+
clearTimeout(timeout);
|
|
352
|
+
resolve("");
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/** Analyst prompt templates */
|
|
357
|
+
const CODEBASE_ANALYST_PROMPT = `You are analyzing a codebase to help plan a development task.
|
|
358
|
+
Use Glob and Read to explore the repository structure.
|
|
359
|
+
Report:
|
|
360
|
+
1. Key directories and their purposes
|
|
361
|
+
2. Frameworks, languages, and patterns used
|
|
362
|
+
3. Existing test patterns and locations
|
|
363
|
+
4. CI/CD configuration
|
|
364
|
+
5. Key configuration files (.env, tsconfig, etc.)
|
|
365
|
+
Keep your report under 2000 words. Focus on facts, not opinions.`;
|
|
366
|
+
function makeRequirementsAnalystPrompt(task) {
|
|
367
|
+
return `Given this task description:
|
|
368
|
+
|
|
369
|
+
Title: ${task.summary}
|
|
370
|
+
${task.description ? `\nDescription:\n${task.description}` : ""}
|
|
371
|
+
|
|
372
|
+
Analyze the requirements and report:
|
|
373
|
+
1. Explicit acceptance criteria (what MUST be done)
|
|
374
|
+
2. Implicit requirements (what's assumed but not stated)
|
|
375
|
+
3. Ambiguities that could lead to wrong implementation
|
|
376
|
+
4. Affected components based on the requirement scope
|
|
377
|
+
5. Suggested personas for each component
|
|
378
|
+
Keep your report under 1500 words.`;
|
|
379
|
+
}
|
|
380
|
+
function makeRiskAssessorPrompt(task) {
|
|
381
|
+
return `You are assessing risks for a development task on this codebase.
|
|
382
|
+
The task: ${task.summary}
|
|
383
|
+
${task.description ? `\nDescription:\n${task.description}` : ""}
|
|
384
|
+
|
|
385
|
+
Use Grep and Read to check for potential blockers.
|
|
386
|
+
Report:
|
|
387
|
+
1. Files likely to be modified (search for relevant code)
|
|
388
|
+
2. Files that are heavily coupled (imports/dependencies)
|
|
389
|
+
3. Existing tests that may need updating
|
|
390
|
+
4. Environment/config dependencies
|
|
391
|
+
5. Migration or deployment considerations
|
|
392
|
+
Keep your report under 1500 words.`;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Run team planning: spawn 3 parallel analyst agents, then synthesize
|
|
396
|
+
* their reports into an enhanced planning prompt for the final planner.
|
|
397
|
+
*
|
|
398
|
+
* Falls back to single-agent planning if anything goes wrong.
|
|
399
|
+
*/
|
|
400
|
+
async function runTeamPlanning(task, basePrompt, claudePath, model, env, repoPath, taskId, startTime) {
|
|
401
|
+
const taskLabel = chalk.cyan(taskId.slice(0, 8));
|
|
402
|
+
console.log(`${ts()} ${taskLabel} ${chalk.magenta("◆ Team planning")} — running 3 analysts in parallel...`);
|
|
403
|
+
await postLog(taskId, `${PREFIX} Team planning: running codebase, requirements, and risk analysts in parallel...`);
|
|
404
|
+
await postProgress(taskId, "reading_repo", Math.round((Date.now() - startTime) / 1000), "Running parallel analysis agents...", 0, 0);
|
|
405
|
+
const analysisModel = model.includes("opus") ? "sonnet" : model;
|
|
406
|
+
const [codebaseResult, requirementsResult, riskResult] = await Promise.allSettled([
|
|
407
|
+
runAnalyst(claudePath, analysisModel, CODEBASE_ANALYST_PROMPT, repoPath, env),
|
|
408
|
+
runAnalyst(claudePath, analysisModel, makeRequirementsAnalystPrompt(task), repoPath, env),
|
|
409
|
+
runAnalyst(claudePath, analysisModel, makeRiskAssessorPrompt(task), repoPath, env),
|
|
410
|
+
]);
|
|
411
|
+
const codebaseReport = codebaseResult.status === "fulfilled" ? codebaseResult.value : "";
|
|
412
|
+
const requirementsReport = requirementsResult.status === "fulfilled" ? requirementsResult.value : "";
|
|
413
|
+
const riskReport = riskResult.status === "fulfilled" ? riskResult.value : "";
|
|
414
|
+
const successCount = [codebaseReport, requirementsReport, riskReport].filter((r) => r.length > 0).length;
|
|
415
|
+
const analysisElapsed = Math.round((Date.now() - startTime) / 1000);
|
|
416
|
+
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} Analysis complete: ${successCount}/3 reports (${analysisElapsed}s)`);
|
|
417
|
+
await postLog(taskId, `${PREFIX} Team analysis complete: ${successCount}/3 reports in ${formatElapsed(analysisElapsed)}. Synthesizing plan...`);
|
|
418
|
+
await postProgress(taskId, "analyzing", analysisElapsed, "Synthesizing analysis reports...", 0, 0);
|
|
419
|
+
// Build enhanced prompt with analysis reports
|
|
420
|
+
const sections = [];
|
|
421
|
+
if (codebaseReport) {
|
|
422
|
+
sections.push(`## Codebase Analysis (from automated analysis)\n\n${codebaseReport}`);
|
|
423
|
+
}
|
|
424
|
+
if (requirementsReport) {
|
|
425
|
+
sections.push(`## Requirements Analysis\n\n${requirementsReport}`);
|
|
426
|
+
}
|
|
427
|
+
if (riskReport) {
|
|
428
|
+
sections.push(`## Risk Assessment\n\n${riskReport}`);
|
|
429
|
+
}
|
|
430
|
+
if (sections.length === 0) {
|
|
431
|
+
// All analysts failed — fall through to regular planning
|
|
432
|
+
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} All analysts failed, falling back to single-agent planning`);
|
|
433
|
+
await postLog(taskId, `${PREFIX} All analysis agents failed — falling back to single-agent planning`);
|
|
434
|
+
return runClaudeCli(claudePath, model, basePrompt, env, taskId, startTime);
|
|
435
|
+
}
|
|
436
|
+
const enhancedPrompt = basePrompt +
|
|
437
|
+
"\n\n" +
|
|
438
|
+
sections.join("\n\n") +
|
|
439
|
+
"\n\n" +
|
|
440
|
+
"Use these analyses to produce a more accurate execution plan.\n" +
|
|
441
|
+
"Prefer actual file paths discovered in the codebase analysis over guessed paths.";
|
|
442
|
+
// Run the final synthesizer planner with the enhanced prompt
|
|
443
|
+
return runClaudeCli(claudePath, model, enhancedPrompt, env, taskId, startTime);
|
|
444
|
+
}
|
|
252
445
|
/**
|
|
253
446
|
* Run planning for a task with Planner-Critic validation loop.
|
|
254
447
|
*
|
|
@@ -281,6 +474,22 @@ export async function planTask(task, config, credentials) {
|
|
|
281
474
|
const startTime = Date.now();
|
|
282
475
|
// PRD for critic validation: use task description, fall back to summary
|
|
283
476
|
const prd = task.description || task.summary;
|
|
477
|
+
// Clone repo for team planning if enabled
|
|
478
|
+
let repoPath = null;
|
|
479
|
+
if (isAnthropicPlanning && config.teamPlanningEnabled && task.githubRepo) {
|
|
480
|
+
const scmProvider = task.scmProvider || "github";
|
|
481
|
+
const scmToken = scmProvider === "bitbucket"
|
|
482
|
+
? config.bitbucketToken
|
|
483
|
+
: scmProvider === "gitlab"
|
|
484
|
+
? config.gitlabToken
|
|
485
|
+
: config.githubToken;
|
|
486
|
+
if (scmToken) {
|
|
487
|
+
repoPath = await cloneTargetRepo(task.githubRepo, scmToken, scmProvider, task.id);
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} No SCM token for ${scmProvider}, skipping team planning`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
284
493
|
// 2. Planner-Critic iteration loop
|
|
285
494
|
let currentPrompt = basePrompt;
|
|
286
495
|
let bestPlan = null;
|
|
@@ -288,146 +497,167 @@ export async function planTask(task, config, credentials) {
|
|
|
288
497
|
// Track critic history across iterations for analytics
|
|
289
498
|
const criticHistory = [];
|
|
290
499
|
let totalFileCapTruncations = 0;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
else {
|
|
299
|
-
console.log(`${ts()} ${taskLabel} Running planner ${chalk.dim(`(${chalk.yellow(providerLabel)})`)}`);
|
|
300
|
-
await postLog(task.id, `${PREFIX} Starting planning agent using ${providerLabel}`);
|
|
301
|
-
}
|
|
302
|
-
// 2a. Generate plan via Claude CLI (Anthropic) or HTTP API (other providers)
|
|
303
|
-
let rawOutput;
|
|
304
|
-
try {
|
|
305
|
-
if (isAnthropicPlanning) {
|
|
306
|
-
rawOutput = await runClaudeCli(claudePath, cliModel, currentPrompt, cleanEnv, task.id, startTime);
|
|
500
|
+
try {
|
|
501
|
+
for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
|
|
502
|
+
const iterLabel = MAX_ITERATIONS > 1 ? ` (attempt ${iteration}/${MAX_ITERATIONS})` : "";
|
|
503
|
+
const providerLabel = `${provider}/${cliModel}`;
|
|
504
|
+
if (iteration > 1) {
|
|
505
|
+
console.log(`${ts()} ${taskLabel} Running planner${iterLabel} ${chalk.dim(`(${chalk.yellow(providerLabel)})`)}`);
|
|
506
|
+
await postLog(task.id, `${PREFIX} Re-planning${iterLabel} using ${providerLabel}`);
|
|
307
507
|
}
|
|
308
508
|
else {
|
|
309
|
-
|
|
310
|
-
|
|
509
|
+
console.log(`${ts()} ${taskLabel} Running planner ${chalk.dim(`(${chalk.yellow(providerLabel)})`)}`);
|
|
510
|
+
await postLog(task.id, `${PREFIX} Starting planning agent using ${providerLabel}`);
|
|
511
|
+
}
|
|
512
|
+
// 2a. Generate plan via Claude CLI (Anthropic) or HTTP API (other providers)
|
|
513
|
+
let rawOutput;
|
|
514
|
+
try {
|
|
515
|
+
if (isAnthropicPlanning && config.teamPlanningEnabled && repoPath && iteration === 1) {
|
|
516
|
+
rawOutput = await runTeamPlanning(task, currentPrompt, claudePath, cliModel, cleanEnv, repoPath, task.id, startTime);
|
|
517
|
+
}
|
|
518
|
+
else if (isAnthropicPlanning) {
|
|
519
|
+
rawOutput = await runClaudeCli(claudePath, cliModel, currentPrompt, cleanEnv, task.id, startTime);
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
if (!providerApiKey) {
|
|
523
|
+
throw new Error(`No API key available for provider "${provider}". Configure it in Settings > Integrations.`);
|
|
524
|
+
}
|
|
525
|
+
const genStart = Math.round((Date.now() - startTime) / 1000);
|
|
526
|
+
await postProgress(task.id, "generating_plan", genStart, "Generating plan via API...", 0, 0);
|
|
527
|
+
rawOutput = await generateText(provider, cliModel, currentPrompt, providerApiKey);
|
|
528
|
+
// Post "validating" phase so the dashboard progress bar transitions correctly
|
|
529
|
+
const genEnd = Math.round((Date.now() - startTime) / 1000);
|
|
530
|
+
await postProgress(task.id, "validating", genEnd, "Validating plan...", rawOutput.length, 0);
|
|
311
531
|
}
|
|
312
|
-
await postProgress(task.id, "generating_plan", 0, "Generating plan via API...", 0, 0);
|
|
313
|
-
rawOutput = await generateText(provider, cliModel, currentPrompt, providerApiKey);
|
|
314
532
|
}
|
|
315
|
-
|
|
316
|
-
|
|
533
|
+
catch (error) {
|
|
534
|
+
const elapsed = Math.round((Date.now() - startTime) / 1000);
|
|
535
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
536
|
+
console.error(`${ts()} ${taskLabel} ${chalk.red("✗")} Failed after ${elapsed}s: ${errMsg.substring(0, 100)}`);
|
|
537
|
+
await postLog(task.id, `${PREFIX} Planning failed after ${formatElapsed(elapsed)}: ${errMsg.substring(0, 200)}`, "error", "error");
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
317
540
|
const elapsed = Math.round((Date.now() - startTime) / 1000);
|
|
318
|
-
const
|
|
319
|
-
console.
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} Claude CLI done ${chalk.dim(`(${elapsed}s, ${rawOutput.length} chars)`)}`);
|
|
325
|
-
// 2b. Parse plan from raw output
|
|
326
|
-
let plan;
|
|
327
|
-
try {
|
|
328
|
-
plan = parseExecutionPlan(rawOutput);
|
|
329
|
-
}
|
|
330
|
-
catch (error) {
|
|
331
|
-
const errMsg = error instanceof Error ? error.message : String(error);
|
|
332
|
-
console.error(`${ts()} ${taskLabel} ${chalk.red("✗")} Plan parse failed: ${errMsg.substring(0, 100)}`);
|
|
333
|
-
await postLog(task.id, `${PREFIX} Failed to parse execution plan from Claude output: ${errMsg.substring(0, 200)}`, "error", "error");
|
|
334
|
-
// If we can't parse the plan, post raw output and let server-side try
|
|
335
|
-
return await postRawPlan(task.id, rawOutput, config.agentId, taskLabel, elapsed);
|
|
336
|
-
}
|
|
337
|
-
// 2c. Apply file cap (max 5 files per story)
|
|
338
|
-
const { truncatedCount, details } = applyFileCap(plan);
|
|
339
|
-
if (truncatedCount > 0) {
|
|
340
|
-
totalFileCapTruncations += truncatedCount;
|
|
341
|
-
const msg = `${PREFIX} File cap applied: ${truncatedCount} stories truncated to max 5 targetFiles`;
|
|
342
|
-
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} ${msg}`);
|
|
343
|
-
await postLog(task.id, msg);
|
|
344
|
-
for (const detail of details) {
|
|
345
|
-
console.log(`${ts()} ${taskLabel} ${chalk.dim(detail)}`);
|
|
541
|
+
const doneLabel = isAnthropicPlanning ? "Claude CLI" : `${provider} API`;
|
|
542
|
+
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} ${doneLabel} done ${chalk.dim(`(${elapsed}s, ${rawOutput.length} chars)`)}`);
|
|
543
|
+
// 2b. Parse plan from raw output
|
|
544
|
+
let plan;
|
|
545
|
+
try {
|
|
546
|
+
plan = parseExecutionPlan(rawOutput);
|
|
346
547
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
if (criticResult && criticResult.score > bestScore) {
|
|
354
|
-
bestPlan = plan;
|
|
355
|
-
bestScore = criticResult.score;
|
|
356
|
-
}
|
|
357
|
-
else if (!criticResult && !bestPlan) {
|
|
358
|
-
// Critic failed entirely — use this plan as fallback
|
|
359
|
-
bestPlan = plan;
|
|
360
|
-
}
|
|
361
|
-
// Record critic history for this iteration
|
|
362
|
-
if (criticResult) {
|
|
363
|
-
criticHistory.push({
|
|
364
|
-
iteration,
|
|
365
|
-
score: criticResult.score,
|
|
366
|
-
approved: criticResult.approved || criticResult.score >= AUTO_APPROVAL_THRESHOLD,
|
|
367
|
-
risks: criticResult.risks,
|
|
368
|
-
suggestions: criticResult.suggestions,
|
|
369
|
-
filesCapApplied: truncatedCount > 0 ? truncatedCount : undefined,
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
// 2e. Check critic result
|
|
373
|
-
if (!criticResult) {
|
|
374
|
-
// Critic failed (timeout, parse error, etc.) — post plan without critic gate
|
|
375
|
-
const msg = `${PREFIX} Critic validation failed — posting plan without critic score`;
|
|
376
|
-
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} ${msg}`);
|
|
377
|
-
await postLog(task.id, msg);
|
|
378
|
-
const planningDurationMs = Date.now() - startTime;
|
|
379
|
-
return await postValidatedPlan(task.id, plan, config.agentId, taskLabel, elapsed, undefined, undefined, criticHistory, totalFileCapTruncations, planningDurationMs, iteration);
|
|
380
|
-
}
|
|
381
|
-
if (criticResult.approved || criticResult.score >= AUTO_APPROVAL_THRESHOLD) {
|
|
382
|
-
// Approved! Post the file-capped plan
|
|
383
|
-
const msg = `${PREFIX} Critic approved (score: ${criticResult.score}/100)`;
|
|
384
|
-
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} ${msg}`);
|
|
385
|
-
await postLog(task.id, msg);
|
|
386
|
-
if (criticResult.risks.length > 0) {
|
|
387
|
-
const risksMsg = `${PREFIX} Critic risks (non-blocking): ${criticResult.risks.join("; ")}`;
|
|
388
|
-
console.log(`${ts()} ${taskLabel} ${chalk.dim(risksMsg)}`);
|
|
389
|
-
await postLog(task.id, risksMsg);
|
|
548
|
+
catch (error) {
|
|
549
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
550
|
+
console.error(`${ts()} ${taskLabel} ${chalk.red("✗")} Plan parse failed: ${errMsg.substring(0, 100)}`);
|
|
551
|
+
await postLog(task.id, `${PREFIX} Failed to parse execution plan from Claude output: ${errMsg.substring(0, 200)}`, "error", "error");
|
|
552
|
+
// If we can't parse the plan, post raw output and let server-side try
|
|
553
|
+
return await postRawPlan(task.id, rawOutput, config.agentId, taskLabel, elapsed);
|
|
390
554
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
555
|
+
// 2c. Apply file cap (max 5 files per story)
|
|
556
|
+
const { truncatedCount, details } = applyFileCap(plan);
|
|
557
|
+
if (truncatedCount > 0) {
|
|
558
|
+
totalFileCapTruncations += truncatedCount;
|
|
559
|
+
const msg = `${PREFIX} File cap applied: ${truncatedCount} stories truncated to max 5 targetFiles`;
|
|
560
|
+
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} ${msg}`);
|
|
561
|
+
await postLog(task.id, msg);
|
|
562
|
+
for (const detail of details) {
|
|
563
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim(detail)}`);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
console.log(`${ts()} ${taskLabel} Plan: ${chalk.bold(plan.stories.length)} stories`);
|
|
567
|
+
await postLog(task.id, `${PREFIX} Plan generated: ${plan.stories.length} stories (${formatElapsed(elapsed)}). Running critic validation...`);
|
|
568
|
+
// 2d. Run critic validation
|
|
569
|
+
const criticResult = await runCriticValidation(claudePath, cliModel, prd, plan, cleanEnv, taskLabel, provider, providerApiKey);
|
|
570
|
+
// Track best plan across iterations
|
|
571
|
+
if (criticResult && criticResult.score > bestScore) {
|
|
572
|
+
bestPlan = plan;
|
|
573
|
+
bestScore = criticResult.score;
|
|
574
|
+
}
|
|
575
|
+
else if (!criticResult && !bestPlan) {
|
|
576
|
+
// Critic failed entirely — use this plan as fallback
|
|
577
|
+
bestPlan = plan;
|
|
405
578
|
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
579
|
+
// Record critic history for this iteration
|
|
580
|
+
if (criticResult) {
|
|
581
|
+
criticHistory.push({
|
|
582
|
+
iteration,
|
|
583
|
+
score: criticResult.score,
|
|
584
|
+
approved: criticResult.approved || criticResult.score >= AUTO_APPROVAL_THRESHOLD,
|
|
585
|
+
risks: criticResult.risks,
|
|
586
|
+
suggestions: criticResult.suggestions,
|
|
587
|
+
filesCapApplied: truncatedCount > 0 ? truncatedCount : undefined,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
// 2e. Check critic result
|
|
591
|
+
if (!criticResult) {
|
|
592
|
+
// Critic failed (timeout, parse error, etc.) — post plan without critic gate
|
|
593
|
+
const msg = `${PREFIX} Critic validation failed — posting plan without critic score`;
|
|
594
|
+
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} ${msg}`);
|
|
595
|
+
await postLog(task.id, msg);
|
|
596
|
+
const planningDurationMs = Date.now() - startTime;
|
|
597
|
+
return await postValidatedPlan(task.id, plan, config.agentId, taskLabel, elapsed, undefined, undefined, criticHistory, totalFileCapTruncations, planningDurationMs, iteration);
|
|
598
|
+
}
|
|
599
|
+
if (criticResult.approved || criticResult.score >= AUTO_APPROVAL_THRESHOLD) {
|
|
600
|
+
// Approved! Post the file-capped plan
|
|
601
|
+
const msg = `${PREFIX} Critic approved (score: ${criticResult.score}/100)`;
|
|
602
|
+
console.log(`${ts()} ${taskLabel} ${chalk.green("✓")} ${msg}`);
|
|
603
|
+
await postLog(task.id, msg);
|
|
604
|
+
if (criticResult.risks.length > 0) {
|
|
605
|
+
const risksMsg = `${PREFIX} Critic risks (non-blocking): ${criticResult.risks.join("; ")}`;
|
|
606
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim(risksMsg)}`);
|
|
607
|
+
await postLog(task.id, risksMsg);
|
|
608
|
+
}
|
|
609
|
+
const planningDurationMs = Date.now() - startTime;
|
|
610
|
+
return await postValidatedPlan(task.id, plan, config.agentId, taskLabel, elapsed, criticResult.score, criticResult.risks, criticHistory, totalFileCapTruncations, planningDurationMs, iteration);
|
|
611
|
+
}
|
|
612
|
+
// 2f. Rejected — append critic feedback for next iteration
|
|
613
|
+
if (iteration < MAX_ITERATIONS) {
|
|
614
|
+
const feedback = formatCriticFeedback(criticResult);
|
|
615
|
+
currentPrompt = basePrompt + "\n\n" + feedback;
|
|
616
|
+
const msg = `${PREFIX} Critic rejected (score: ${criticResult.score}/100, threshold: ${AUTO_APPROVAL_THRESHOLD}). Re-planning with feedback...`;
|
|
617
|
+
console.log(`${ts()} ${taskLabel} ${chalk.yellow("⚠")} ${msg}`);
|
|
618
|
+
await postLog(task.id, msg);
|
|
619
|
+
if (criticResult.risks.length > 0) {
|
|
620
|
+
const risksMsg = `${PREFIX} Critic risks: ${criticResult.risks.join("; ")}`;
|
|
621
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim(risksMsg)}`);
|
|
622
|
+
await postLog(task.id, risksMsg);
|
|
623
|
+
}
|
|
624
|
+
if (criticResult.suggestions && criticResult.suggestions.length > 0) {
|
|
625
|
+
const sugMsg = `${PREFIX} Critic suggestions: ${criticResult.suggestions.join("; ")}`;
|
|
626
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim(sugMsg)}`);
|
|
627
|
+
await postLog(task.id, sugMsg);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
// Final iteration — rejected
|
|
632
|
+
const msg = `${PREFIX} Critic rejected after ${MAX_ITERATIONS} iterations (best score: ${bestScore}/100, threshold: ${AUTO_APPROVAL_THRESHOLD})`;
|
|
633
|
+
console.error(`${ts()} ${taskLabel} ${chalk.red("✗")} ${msg}`);
|
|
634
|
+
await postLog(task.id, msg, "error", "error");
|
|
635
|
+
if (criticResult.risks.length > 0) {
|
|
636
|
+
const risksMsg = `${PREFIX} Final risks: ${criticResult.risks.join("; ")}`;
|
|
637
|
+
console.error(`${ts()} ${taskLabel} ${risksMsg}`);
|
|
638
|
+
await postLog(task.id, risksMsg, "error", "error");
|
|
639
|
+
}
|
|
640
|
+
if (criticResult.suggestions && criticResult.suggestions.length > 0) {
|
|
641
|
+
const sugMsg = `${PREFIX} Suggestions: ${criticResult.suggestions.join("; ")}`;
|
|
642
|
+
console.error(`${ts()} ${taskLabel} ${sugMsg}`);
|
|
643
|
+
await postLog(task.id, sugMsg, "error", "error");
|
|
644
|
+
}
|
|
410
645
|
}
|
|
411
646
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
await postLog(task.id, risksMsg, "error", "error");
|
|
647
|
+
// All iterations exhausted — fail
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
finally {
|
|
651
|
+
// Cleanup temp clone
|
|
652
|
+
if (repoPath) {
|
|
653
|
+
try {
|
|
654
|
+
execSync(`rm -rf "${repoPath}"`, { stdio: "ignore" });
|
|
421
655
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
console.error(`${ts()} ${taskLabel} ${sugMsg}`);
|
|
425
|
-
await postLog(task.id, sugMsg, "error", "error");
|
|
656
|
+
catch {
|
|
657
|
+
/* ignore */
|
|
426
658
|
}
|
|
427
659
|
}
|
|
428
660
|
}
|
|
429
|
-
// All iterations exhausted — fail
|
|
430
|
-
return false;
|
|
431
661
|
}
|
|
432
662
|
/**
|
|
433
663
|
* Post a validated (file-capped) plan to the cloud API.
|
package/dist/spawner.js
CHANGED
|
@@ -132,17 +132,20 @@ export async function spawnWorker(task, config, orgConfig, credentials) {
|
|
|
132
132
|
else {
|
|
133
133
|
dockerArgs.push("--network", "host");
|
|
134
134
|
}
|
|
135
|
-
// Mount Claude credentials
|
|
135
|
+
// Mount Claude credentials (required for Anthropic workers, optional for others)
|
|
136
|
+
const workerProvider = task.workerProvider || "anthropic";
|
|
136
137
|
const claudeConfigDir = findClaudeConfigDir();
|
|
137
|
-
if (!claudeConfigDir) {
|
|
138
|
+
if (!claudeConfigDir && workerProvider === "anthropic") {
|
|
138
139
|
console.error(`${ts()} ${taskLabel} ${chalk.red("✗")} Claude credentials not found. Run 'claude' and complete the sign-in flow.`);
|
|
139
140
|
return;
|
|
140
141
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
142
|
+
if (claudeConfigDir) {
|
|
143
|
+
const dockerClaudeDir = toDockerPath(claudeConfigDir);
|
|
144
|
+
dockerArgs.push("-v", `${dockerClaudeDir}:/home/worker/.claude`);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
console.log(`${ts()} ${taskLabel} ${chalk.dim("Skipping Claude mount (non-Anthropic worker)")}`);
|
|
148
|
+
}
|
|
146
149
|
// Build environment variables — KEY DIFFERENCE: API_BASE_URL points to cloud
|
|
147
150
|
const scmProvider = (task.scmProvider || "github");
|
|
148
151
|
const scmToken = getScmToken(scmProvider, config);
|