karajan-code 1.59.0 → 2.0.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.
Files changed (115) hide show
  1. package/README.md +2 -0
  2. package/package.json +1 -1
  3. package/scripts/install.js +18 -15
  4. package/src/agents/aider-agent.js +0 -7
  5. package/src/agents/claude-agent.js +34 -6
  6. package/src/agents/codex-agent.js +2 -6
  7. package/src/agents/gemini-agent.js +0 -4
  8. package/src/agents/opencode-agent.js +0 -4
  9. package/src/{becaria → ci}/dispatch.js +13 -13
  10. package/src/{becaria → ci}/pr-diff.js +1 -1
  11. package/src/cli.js +3 -2
  12. package/src/commands/agents.js +0 -1
  13. package/src/commands/doctor.js +22 -40
  14. package/src/commands/init.js +8 -8
  15. package/src/commands/report.js +0 -13
  16. package/src/commands/review.js +17 -17
  17. package/src/commands/run.js +1 -2
  18. package/src/commands/status.js +1 -7
  19. package/src/config.js +10 -52
  20. package/src/domains/domain-loader.js +85 -4
  21. package/src/git/automation.js +9 -9
  22. package/src/guards/output-guard.js +0 -17
  23. package/src/mcp/handlers/direct-handlers.js +1 -1
  24. package/src/mcp/handlers/run-handler.js +1 -2
  25. package/src/mcp/sovereignty-guard.js +2 -2
  26. package/src/mcp/tools.js +3 -2
  27. package/src/orchestrator/brain-coordinator.js +165 -0
  28. package/src/orchestrator/ci-integration.js +139 -0
  29. package/src/orchestrator/config-init.js +435 -0
  30. package/src/orchestrator/direct-actions.js +186 -0
  31. package/src/orchestrator/feedback-enrichment.js +140 -0
  32. package/src/orchestrator/feedback-queue.js +152 -0
  33. package/src/orchestrator/flow-control.js +159 -0
  34. package/src/orchestrator/post-loop-stages.js +20 -15
  35. package/src/orchestrator/preflight-checks.js +7 -3
  36. package/src/orchestrator/role-output-compressor.js +190 -0
  37. package/src/orchestrator/session-journal.js +344 -0
  38. package/src/orchestrator/solomon-escalation.js +38 -5
  39. package/src/orchestrator/solomon-rules.js +32 -33
  40. package/src/orchestrator/stages/reviewer-stage.js +16 -5
  41. package/src/orchestrator/stages/sonar-stage.js +24 -1
  42. package/src/orchestrator/verification-gate.js +146 -0
  43. package/src/orchestrator.js +435 -661
  44. package/src/planning-game/client.js +2 -2
  45. package/src/planning-game/pipeline-adapter.js +1 -1
  46. package/src/prompts/coder.js +17 -3
  47. package/src/prompts/reviewer.js +2 -2
  48. package/src/prompts/rtk-snippet.js +3 -5
  49. package/src/review/diff-generator.js +66 -17
  50. package/src/review/snapshot-diff.js +122 -0
  51. package/src/review/tdd-policy.js +4 -2
  52. package/src/roles/agent-role.js +135 -0
  53. package/src/roles/architect-role.js +61 -108
  54. package/src/roles/audit-role.js +25 -71
  55. package/src/roles/coder-role.js +32 -57
  56. package/src/roles/discover-role.js +30 -71
  57. package/src/roles/hu-reviewer-role.js +51 -99
  58. package/src/roles/impeccable-role.js +34 -91
  59. package/src/roles/index.js +2 -0
  60. package/src/roles/karajan-brain-role.js +134 -0
  61. package/src/roles/planner-role.js +40 -75
  62. package/src/roles/refactorer-role.js +22 -64
  63. package/src/roles/researcher-role.js +52 -118
  64. package/src/roles/reviewer-role.js +69 -126
  65. package/src/roles/security-role.js +38 -102
  66. package/src/roles/solomon-role.js +71 -15
  67. package/src/roles/tester-role.js +121 -95
  68. package/src/roles/triage-role.js +50 -111
  69. package/src/session-store.js +1 -1
  70. package/src/skills/skill-detector.js +11 -0
  71. package/src/sonar/config-resolver.js +20 -1
  72. package/src/sonar/credentials.js +17 -0
  73. package/src/sonar/project-key.js +1 -1
  74. package/src/sonar/scanner.js +1 -1
  75. package/src/utils/banner.js +66 -0
  76. package/src/utils/display.js +35 -17
  77. package/src/utils/injection-guard.js +23 -8
  78. package/src/utils/logger.js +6 -1
  79. package/src/utils/process.js +3 -4
  80. package/src/utils/role-assigner.js +131 -0
  81. package/src/utils/update-check.js +5 -1
  82. package/src/utils/welcome.js +3 -8
  83. package/src/webperf/devtools-detect.js +70 -23
  84. package/templates/roles/coder.md +7 -0
  85. package/templates/roles/karajan-brain.md +95 -0
  86. package/templates/roles/solomon.md +67 -106
  87. package/templates/workflows/automerge.yml +4 -4
  88. package/templates/workflows/houston-override.yml +4 -4
  89. package/templates/workflows/{becaria-gateway.yml → kj-ci-gateway.yml} +12 -12
  90. package/src/proxy/adapters/anthropic.js +0 -131
  91. package/src/proxy/adapters/gemini.js +0 -106
  92. package/src/proxy/adapters/index.js +0 -51
  93. package/src/proxy/adapters/openai.js +0 -71
  94. package/src/proxy/compression/ai-compressor.js +0 -209
  95. package/src/proxy/compression/dedup-cache.js +0 -100
  96. package/src/proxy/compression/deterministic/bash-build.js +0 -60
  97. package/src/proxy/compression/deterministic/bash-git.js +0 -101
  98. package/src/proxy/compression/deterministic/bash-infra.js +0 -64
  99. package/src/proxy/compression/deterministic/bash-misc.js +0 -53
  100. package/src/proxy/compression/deterministic/bash-pkg.js +0 -49
  101. package/src/proxy/compression/deterministic/bash-test.js +0 -61
  102. package/src/proxy/compression/deterministic/glob.js +0 -26
  103. package/src/proxy/compression/deterministic/grep.js +0 -53
  104. package/src/proxy/compression/deterministic/index.js +0 -58
  105. package/src/proxy/compression/deterministic/read.js +0 -22
  106. package/src/proxy/compression/deterministic/utils.js +0 -33
  107. package/src/proxy/compression/pipeline.js +0 -270
  108. package/src/proxy/middleware/prompt-injector.js +0 -165
  109. package/src/proxy/middleware/response-interceptor.js +0 -223
  110. package/src/proxy/progress-monitor.js +0 -98
  111. package/src/proxy/proxy-lifecycle.js +0 -198
  112. package/src/proxy/proxy-server.js +0 -239
  113. package/src/proxy/security.js +0 -45
  114. /package/src/{becaria → ci}/index.js +0 -0
  115. /package/src/{becaria → ci}/repo.js +0 -0
@@ -1,5 +1,4 @@
1
- import { BaseRole } from "./base-role.js";
2
- import { createAgent as defaultCreateAgent } from "../agents/index.js";
1
+ import { AgentRole } from "./agent-role.js";
3
2
  import { extractFirstJson } from "../utils/json-extract.js";
4
3
 
5
4
  const SUBAGENT_PREAMBLE = [
@@ -8,118 +7,55 @@ const SUBAGENT_PREAMBLE = [
8
7
  "Do NOT use any MCP tools. Focus only on auditing code for security vulnerabilities."
9
8
  ].join(" ");
10
9
 
11
- function resolveProvider(config) {
12
- return (
13
- config?.roles?.security?.provider ||
14
- config?.roles?.coder?.provider ||
15
- "claude"
16
- );
17
- }
18
-
19
- function buildPrompt({ task, diff, instructions }) {
20
- const sections = [SUBAGENT_PREAMBLE];
21
-
22
- if (instructions) {
23
- sections.push(instructions);
10
+ export class SecurityRole extends AgentRole {
11
+ constructor(opts) {
12
+ super({ ...opts, name: "security" });
24
13
  }
25
14
 
26
- sections.push(
27
- "You are a security auditor. Analyze the code changes for vulnerabilities.",
28
- "Check for: OWASP top 10, exposed secrets/API keys, hardcoded credentials, command injection, XSS, SQL injection, path traversal, prototype pollution, insecure dependencies.",
29
- "Return a single valid JSON object with your findings and nothing else.",
30
- 'JSON schema: {"vulnerabilities":[{"severity":"critical|high|medium|low","category":string,"file":string,"line":number,"description":string,"fix_suggestion":string}],"verdict":"pass"|"fail"}',
31
- `## Task\n${task}`
32
- );
33
-
34
- if (diff) {
35
- sections.push(`## Git diff to audit\n${diff}`);
15
+ async buildPrompt({ task, diff }) {
16
+ const sections = [SUBAGENT_PREAMBLE];
17
+ if (this.instructions) sections.push(this.instructions);
18
+ sections.push(
19
+ "You are a security auditor. Analyze the code changes for vulnerabilities.",
20
+ "Check for: OWASP top 10, exposed secrets/API keys, hardcoded credentials, command injection, XSS, SQL injection, path traversal, prototype pollution, insecure dependencies.",
21
+ "Return a single valid JSON object with your findings and nothing else.",
22
+ '{"vulnerabilities":[{"severity":"critical|high|medium|low","category":string,"file":string,"line":number,"description":string,"fix_suggestion":string}],"verdict":"pass"|"fail"}',
23
+ `## Task\n${task}`
24
+ );
25
+ if (diff) sections.push(`## Git diff to audit\n${diff}`);
26
+ return { prompt: sections.join("\n\n") };
36
27
  }
37
28
 
38
- return sections.join("\n\n");
39
- }
40
-
41
- function parseSecurityOutput(raw) {
42
- return extractFirstJson(raw);
43
- }
44
-
45
- function buildSummary(parsed) {
46
- const vulns = parsed.vulnerabilities || [];
47
- if (vulns.length === 0) {
48
- return `Verdict: ${parsed.verdict || "pass"}; No vulnerabilities found`;
29
+ extractInput(input) {
30
+ if (typeof input === "string") return { task: input, diff: null };
31
+ return { task: input?.task || this.context?.task || "", diff: input?.diff || null, onOutput: input?.onOutput || null };
49
32
  }
50
33
 
51
- const bySeverity = {};
52
- for (const v of vulns) {
53
- const sev = v.severity || "unknown";
54
- bySeverity[sev] = (bySeverity[sev] || 0) + 1;
55
- }
56
-
57
- const parts = Object.entries(bySeverity)
58
- .sort(([a], [b]) => {
59
- const order = { critical: 0, high: 1, medium: 2, low: 3 };
60
- return (order[a] ?? 4) - (order[b] ?? 4);
61
- })
62
- .map(([sev, count]) => `${count} ${sev}`);
63
-
64
- return `Verdict: ${parsed.verdict || "fail"}; ${parts.join(", ")}`;
65
- }
34
+ parseOutput(raw) { return extractFirstJson(raw); }
66
35
 
67
- export class SecurityRole extends BaseRole {
68
- constructor({ config, logger, emitter = null, createAgentFn = null }) {
69
- super({ name: "security", config, logger, emitter });
70
- this._createAgent = createAgentFn || defaultCreateAgent;
36
+ isSuccessful(parsed) {
37
+ const verdict = parsed.verdict || (parsed.vulnerabilities?.length ? "fail" : "pass");
38
+ return verdict === "pass";
71
39
  }
72
40
 
73
- async execute(input) {
74
- const { task, diff } = typeof input === "string"
75
- ? { task: input, diff: null }
76
- : { task: input?.task || this.context?.task || "", diff: input?.diff || null };
77
-
78
- const provider = resolveProvider(this.config);
79
- const agent = this._createAgent(provider, this.config, this.logger);
80
-
81
- const prompt = buildPrompt({ task, diff, instructions: this.instructions });
82
- const result = await agent.runTask({ prompt, role: "security" });
41
+ buildSuccessResult(parsed, provider) {
42
+ const verdict = parsed.verdict || (parsed.vulnerabilities?.length ? "fail" : "pass");
43
+ return { vulnerabilities: parsed.vulnerabilities || [], verdict, provider };
44
+ }
83
45
 
84
- if (!result.ok) {
85
- return {
86
- ok: false,
87
- result: {
88
- error: result.error || result.output || "Security audit failed",
89
- provider
90
- },
91
- summary: `Security audit failed: ${result.error || "unknown error"}`
92
- };
93
- }
46
+ buildSummary(parsed) {
47
+ const verdict = parsed.verdict || (parsed.vulnerabilities?.length ? "fail" : "pass");
48
+ const vulns = parsed.vulnerabilities || [];
49
+ if (!vulns.length) return `Verdict: ${verdict}; No vulnerabilities found`;
94
50
 
95
- try {
96
- const parsed = parseSecurityOutput(result.output);
97
- if (!parsed) {
98
- return {
99
- ok: false,
100
- result: { error: "Failed to parse security output: no JSON found", provider },
101
- summary: "Security output parse error: no JSON found"
102
- };
103
- }
51
+ const bySeverity = {};
52
+ for (const v of vulns) bySeverity[v.severity || "unknown"] = (bySeverity[v.severity || "unknown"] || 0) + 1;
104
53
 
105
- const verdict = parsed.verdict || (parsed.vulnerabilities?.length ? "fail" : "pass");
106
- const ok = verdict === "pass";
54
+ const order = { critical: 0, high: 1, medium: 2, low: 3 };
55
+ const parts = Object.entries(bySeverity)
56
+ .sort(([a], [b]) => (order[a] ?? 4) - (order[b] ?? 4))
57
+ .map(([sev, count]) => `${count} ${sev}`);
107
58
 
108
- return {
109
- ok,
110
- result: {
111
- vulnerabilities: parsed.vulnerabilities || [],
112
- verdict,
113
- provider
114
- },
115
- summary: buildSummary({ ...parsed, verdict })
116
- };
117
- } catch (err) {
118
- return {
119
- ok: false,
120
- result: { error: `Failed to parse security output: ${err.message}`, provider },
121
- summary: `Security output parse error: ${err.message}`
122
- };
123
- }
59
+ return `Verdict: ${verdict}; ${parts.join(", ")}`;
124
60
  }
125
61
  }
@@ -1,5 +1,6 @@
1
1
  import { BaseRole } from "./base-role.js";
2
2
  import { createAgent as defaultCreateAgent } from "../agents/index.js";
3
+ import { extractFirstJson } from "../utils/json-extract.js";
3
4
 
4
5
  const SUBAGENT_PREAMBLE = [
5
6
  "IMPORTANT: You are running as a Karajan sub-agent.",
@@ -35,27 +36,51 @@ function buildPrompt({ conflict, task, instructions }) {
35
36
  }
36
37
 
37
38
  sections.push(
38
- "You are Solomon, the conflict resolver in a multi-role AI pipeline.",
39
- "You are activated when agents cannot reach agreement after their iteration limit.",
40
- "## Decision hierarchy",
39
+ "You are Solomon, the autonomous pipeline boss in a multi-agent AI coding orchestrator.",
40
+ "You are activated whenever ANYTHING deviates from normal flow: rate limits, agent failures, conflicts, max iterations, quality gate issues.",
41
+ "",
42
+ "## Core principle",
43
+ "The pipeline NEVER skips a quality stage (review, tests, sonar, security) without exhausting alternatives first.",
44
+ "NEVER approve skipping a stage as your first option. Follow the recovery hierarchy below.",
45
+ "",
46
+ "## ABSOLUTE RULE: Security issues from reviewer are NEVER overridable",
47
+ "If the reviewer's blocking_issues contain security-related issues (categories: authentication, authorization, injection, XSS, CSRF, exposed secrets/credentials, cryptography, session management, input validation), you MUST:",
48
+ "- Set ruling to \"continue\" (NOT \"approve\")",
49
+ "- Return the reviewer feedback to the coder for fixing",
50
+ "- NEVER approve or skip security issues regardless of task complexity or deadline",
51
+ "This rule overrides all other rules including the recovery hierarchy.",
52
+ "",
53
+ "## Recovery hierarchy (STRICT ORDER — follow top to bottom)",
54
+ "When a stage fails or an agent is unavailable:",
55
+ "1. **wait** — If there is a known cooldown (cooldownUntil), and it is less than 10 minutes, WAIT. Set ruling to 'approve_with_conditions' with condition 'wait for cooldown' and set waitUntil.",
56
+ "2. **retry_with_alternative** — Try the same stage with a DIFFERENT agent. The pipeline has multiple agents (claude, codex, gemini). Set ruling to 'approve_with_conditions' with condition specifying the alternative agent.",
57
+ "3. **evaluate_risk** — Only if no alternatives are available, evaluate the risk of skipping. Consider: task complexity, what the stage would catch, security implications.",
58
+ " - If risk is LOW (trivial task, no security impact, style-only review): approve with a clear justification.",
59
+ " - If risk is HIGH (complex task, security changes, new dependencies): escalate_human.",
60
+ "4. **escalate_human** — When you cannot resolve it safely. Always prefer this over blindly approving.",
61
+ "",
62
+ "## Quality hierarchy",
41
63
  "Security > Correctness > Tests > Architecture > Maintainability > Style",
42
64
  "- Green tests are sacred. Never dismiss a failing test.",
43
65
  "- Style preferences NEVER block approval.",
44
- "- Hardcoded values that will come from DB later are acceptable (contextual false positive).",
45
66
  "- Sonar INFO/MINOR issues are always dismissable.",
46
67
  "- Sonar BLOCKER/CRITICAL must be fixed unless they are proven false positives.",
68
+ "",
47
69
  "## Classification rules",
48
70
  "For each issue, classify as:",
49
71
  "1. **critical** (security, correctness, tests broken) — action: must_fix",
50
72
  "2. **important** (architecture, maintainability) — action: should_fix",
51
73
  "3. **style** (naming, formatting, preferences, false positives) — action: dismiss",
52
- "## Your decision options",
53
- '1. **approve** — All pending issues are style/false positives. Pipeline continues.',
54
- '2. **approve_with_conditions** — Important issues exist but are fixable. Give exact instructions to Coder for one more attempt.',
55
- '3. **escalate_human** — Critical issues that cannot be resolved, ambiguous requirements, architecture decisions, or business logic decisions.',
56
- '4. **create_subtask** — A prerequisite task must be completed first to resolve the conflict. The current task will pause, the subtask runs, then the current task resumes.',
74
+ "",
75
+ "## Ruling options",
76
+ '1. **approve** — FORBIDDEN when a quality stage (review, tests, sonar, security) was skipped or failed. You MUST try alternatives first (wait for cooldown, use different agent). Only allowed when all stages completed successfully and remaining issues are style/false positives.',
77
+ '2. **approve_with_conditions** — Fixable issues or recovery actions needed. Include exact conditions (wait, retry with alternative agent, specific fix instructions). Set extraIterations and/or alternativeAgent.',
78
+ '3. **escalate_human** — Cannot resolve safely. Critical issues, ambiguous requirements, architecture decisions, high-risk skip.',
79
+ '4. **create_subtask** — A prerequisite task must be completed first.',
80
+ "",
57
81
  "Return a single valid JSON object with your ruling and nothing else.",
58
- 'JSON schema: {"ruling":"approve"|"approve_with_conditions"|"escalate_human"|"create_subtask","classification":[{"issue":string,"category":"critical"|"important"|"style","action":"must_fix"|"should_fix"|"dismiss"}],"conditions":[string],"dismissed":[string],"escalate":boolean,"escalate_reason":string|null,"subtask":{"title":string,"description":string,"reason":string}|null}'
82
+ 'JSON schema: {"ruling":"approve"|"approve_with_conditions"|"escalate_human"|"create_subtask","classification":[{"issue":string,"category":"critical"|"important"|"style","action":"must_fix"|"should_fix"|"dismiss"}],"conditions":[string],"dismissed":[string],"escalate":boolean,"escalate_reason":string|null,"extraIterations":number|null,"alternativeAgent":string|null,"waitUntil":string|null,"subtask":{"title":string,"description":string,"reason":string}|null}',
83
+ "When ruling is approve_with_conditions, set extraIterations (1-5) and/or alternativeAgent (claude|codex|gemini) as appropriate."
59
84
  );
60
85
 
61
86
  const stage = conflict?.stage || "unknown";
@@ -65,14 +90,48 @@ function buildPrompt({ conflict, task, instructions }) {
65
90
  const isFirstRejection = conflict?.isFirstRejection ?? false;
66
91
  const isRepeat = conflict?.isRepeat ?? false;
67
92
 
93
+ const budgetUsd = conflict?.budget_usd;
94
+ const budgetLine = typeof budgetUsd === "number" ? `Budget spent so far: $${budgetUsd.toFixed(2)}` : "";
95
+
68
96
  sections.push(
69
97
  `## Conflict context`,
70
98
  `Stage: ${stage}`,
71
99
  `Iterations exhausted: ${iterationCount}/${maxIterations}`,
72
100
  `isFirstRejection: ${isFirstRejection}`,
73
- `isRepeat: ${isRepeat}`
101
+ `isRepeat: ${isRepeat}`,
102
+ budgetLine,
103
+ "",
104
+ "## Budget awareness",
105
+ "Consider the cost-benefit ratio when deciding. If significant budget has been spent with little progress,",
106
+ "prefer approving the current work or escalating to human. If progress is good and budget is low,",
107
+ "prefer continuing with conditions. Never waste budget on style-only iterations."
74
108
  );
75
109
 
110
+ if (conflict?.previousSolomonRulings?.length > 0) {
111
+ const rulingLines = conflict.previousSolomonRulings.map((r, idx) =>
112
+ `${idx + 1}. Stage: ${r.conflictStage}, Ruling: ${r.ruling}${r.alternativeAgent ? `, agent: ${r.alternativeAgent}` : ""}${r.error ? ` (FAILED: ${r.error})` : ""}`
113
+ ).join("\n");
114
+ sections.push(
115
+ "## Your previous rulings in this session (DO NOT repeat failed strategies)",
116
+ rulingLines,
117
+ "If a previous ruling failed (e.g., alternative agent also rate-limited), do NOT suggest the same strategy again. Escalate or try a different approach."
118
+ );
119
+ }
120
+
121
+ // Rate limit specific instruction
122
+ if (stage?.includes("rate_limit")) {
123
+ const rateLimitedAgent = conflict?.history?.[0]?.feedback?.match(/Agent "(\w+)"/)?.[1] || "unknown";
124
+ sections.push(
125
+ "## CRITICAL: Agent rate-limited",
126
+ `Agent "${rateLimitedAgent}" is rate-limited. You MUST NOT approve skipping this stage.`,
127
+ "Your ONLY valid options are:",
128
+ `1. approve_with_conditions + alternativeAgent: pick a different agent (available: claude, codex, gemini — NOT "${rateLimitedAgent}")`,
129
+ "2. approve_with_conditions + waitUntil: if cooldown is known and <10min",
130
+ "3. escalate_human: if no alternatives work",
131
+ `DO NOT set ruling to "approve". The stage MUST be completed by some agent.`
132
+ );
133
+ }
134
+
76
135
  if (conflict?.issueCategories) {
77
136
  sections.push(`## Issue categories\n${JSON.stringify(conflict.issueCategories, null, 2)}`);
78
137
  }
@@ -98,10 +157,7 @@ function buildPrompt({ conflict, task, instructions }) {
98
157
  }
99
158
 
100
159
  function parseSolomonOutput(raw) {
101
- const text = raw?.trim() || "";
102
- const jsonMatch = /\{[\s\S]*\}/.exec(text);
103
- if (!jsonMatch) return null;
104
- return JSON.parse(jsonMatch[0]);
160
+ return extractFirstJson(raw);
105
161
  }
106
162
 
107
163
  function buildSummary(parsed) {
@@ -1,6 +1,6 @@
1
- import { BaseRole } from "./base-role.js";
2
- import { createAgent as defaultCreateAgent } from "../agents/index.js";
1
+ import { AgentRole } from "./agent-role.js";
3
2
  import { extractFirstJson } from "../utils/json-extract.js";
3
+ import { detectTestFramework } from "../utils/project-detect.js";
4
4
 
5
5
  const SUBAGENT_PREAMBLE = [
6
6
  "IMPORTANT: You are running as a Karajan sub-agent.",
@@ -8,108 +8,134 @@ const SUBAGENT_PREAMBLE = [
8
8
  "Do NOT use any MCP tools. Focus only on evaluating test quality."
9
9
  ].join(" ");
10
10
 
11
- function resolveProvider(config) {
12
- return (
13
- config?.roles?.tester?.provider ||
14
- config?.roles?.coder?.provider ||
15
- "claude"
16
- );
17
- }
18
-
19
- function buildPrompt({ task, diff, sonarIssues, instructions }) {
20
- const sections = [SUBAGENT_PREAMBLE];
21
-
22
- if (instructions) {
23
- sections.push(instructions);
11
+ /**
12
+ * Map test framework to the command that runs tests with coverage.
13
+ */
14
+ const COVERAGE_COMMANDS = {
15
+ vitest: "npx vitest run --coverage --reporter=verbose 2>&1",
16
+ jest: "npx jest --coverage --verbose 2>&1",
17
+ mocha: "npx c8 mocha 2>&1",
18
+ playwright: "npx playwright test 2>&1",
19
+ pytest: "pytest --cov --tb=short 2>&1",
20
+ "go-test": "go test -cover -v ./... 2>&1",
21
+ "cargo-test": "cargo test --verbose 2>&1",
22
+ junit: "mvn test 2>&1",
23
+ rspec: "bundle exec rspec 2>&1",
24
+ phpunit: "vendor/bin/phpunit --coverage-text 2>&1",
25
+ "dotnet-test": "dotnet test --collect:\"XPlat Code Coverage\" 2>&1",
26
+ "dart-test": "dart test 2>&1"
27
+ };
28
+
29
+ const TEST_COMMANDS = {
30
+ vitest: "npx vitest run --reporter=verbose 2>&1",
31
+ jest: "npx jest --verbose 2>&1",
32
+ mocha: "npx mocha 2>&1",
33
+ playwright: "npx playwright test 2>&1",
34
+ pytest: "pytest --tb=short 2>&1",
35
+ "go-test": "go test -v ./... 2>&1",
36
+ "cargo-test": "cargo test --verbose 2>&1",
37
+ junit: "mvn test 2>&1",
38
+ rspec: "bundle exec rspec 2>&1",
39
+ phpunit: "vendor/bin/phpunit 2>&1",
40
+ "dotnet-test": "dotnet test 2>&1",
41
+ "dart-test": "dart test 2>&1"
42
+ };
43
+
44
+ export class TesterRole extends AgentRole {
45
+ constructor(opts) {
46
+ super({ ...opts, name: "tester" });
24
47
  }
25
48
 
26
- sections.push(
27
- "You are a test quality gate. You do NOT write tests — you evaluate them.",
28
- "Run the test suite, check coverage, identify missing scenarios, and evaluate assertion quality.",
29
- "Return a single valid JSON object with your findings and nothing else.",
30
- 'JSON schema: {"tests_pass":boolean,"coverage":{"overall":number,"services":number,"utilities":number},"missing_scenarios":[string],"quality_issues":[string],"verdict":"pass"|"fail"}',
31
- `## Task\n${task}`
32
- );
33
-
34
- if (diff) {
35
- sections.push(`## Git diff\n${diff}`);
49
+ extractInput(input) {
50
+ if (typeof input === "string") return { task: input, diff: null, sonarIssues: null };
51
+ return {
52
+ task: input?.task || this.context?.task || "",
53
+ diff: input?.diff || null,
54
+ sonarIssues: input?.sonarIssues || null,
55
+ onOutput: input?.onOutput || null
56
+ };
36
57
  }
37
58
 
38
- if (sonarIssues) {
39
- sections.push(`## Sonar test issues\n${sonarIssues}`);
40
- }
41
-
42
- return sections.join("\n\n");
43
- }
44
-
45
- function parseTesterOutput(raw) {
46
- return extractFirstJson(raw);
47
- }
59
+ async buildPrompt({ task, diff, sonarIssues }) {
60
+ const projectDir = this.config?.projectDir || process.cwd();
61
+ const detection = await detectTestFramework(projectDir);
62
+
63
+ const sections = [SUBAGENT_PREAMBLE];
64
+ if (this.instructions) sections.push(this.instructions);
65
+
66
+ sections.push(
67
+ "You are a test quality gate. Your job is to EXECUTE the test suite, measure REAL coverage, and evaluate quality.",
68
+ "You MUST run the actual test command — do NOT guess or estimate results."
69
+ );
70
+
71
+ if (detection.hasTests && detection.framework) {
72
+ const coverageCmd = COVERAGE_COMMANDS[detection.framework];
73
+ const testCmd = TEST_COMMANDS[detection.framework];
74
+ sections.push(
75
+ `## Detected test framework: ${detection.framework} (${detection.language})`,
76
+ "**Step 0**: If node_modules/ does not exist, run `npm install` (or `pnpm install`) first.",
77
+ `**Step 1**: Run the test suite with coverage:`,
78
+ "```bash",
79
+ coverageCmd || testCmd,
80
+ "```",
81
+ "If the coverage command fails (missing dependency), fall back to:",
82
+ "```bash",
83
+ testCmd,
84
+ "```",
85
+ "**Step 2**: Parse the output to extract: pass/fail count, coverage percentages, any failures.",
86
+ "**Step 3**: Return a single JSON object with REAL numbers from the test output."
87
+ );
88
+ } else {
89
+ sections.push(
90
+ "## No test framework detected",
91
+ "**Step 0**: If package.json exists but node_modules/ does not, run `npm install` first.",
92
+ "**Step 1**: Look at package.json or project files to find test scripts.",
93
+ "**Step 2**: Try running `npm test` or detect the framework from config files.",
94
+ "**Step 3**: If tests exist, run them. If no tests exist, report tests_pass: false with verdict: 'fail'.",
95
+ "**Step 4**: Return a JSON object with your findings."
96
+ );
97
+ }
48
98
 
49
- export class TesterRole extends BaseRole {
50
- constructor({ config, logger, emitter = null, createAgentFn = null }) {
51
- super({ name: "tester", config, logger, emitter });
52
- this._createAgent = createAgentFn || defaultCreateAgent;
99
+ sections.push(
100
+ "",
101
+ "Return ONLY a single valid JSON object:",
102
+ '{"tests_pass":boolean,"coverage":{"overall":number,"services":number,"utilities":number},"missing_scenarios":[string],"quality_issues":[string],"verdict":"pass"|"fail"}',
103
+ "",
104
+ "- coverage.overall MUST be a real number from the test runner output, NOT an estimate",
105
+ "- If coverage tool is not available, set coverage.overall to null (not 0, not a guess)",
106
+ "- tests_pass must reflect whether the actual test run succeeded",
107
+ `## Task\n${task}`
108
+ );
109
+ if (diff) sections.push(`## Git diff\n${diff}`);
110
+ if (sonarIssues) sections.push(`## Sonar test issues\n${sonarIssues}`);
111
+ return { prompt: sections.join("\n\n") };
53
112
  }
54
113
 
55
- async execute(input) {
56
- const { task, diff, sonarIssues } = typeof input === "string"
57
- ? { task: input, diff: null, sonarIssues: null }
58
- : { task: input?.task || this.context?.task || "", diff: input?.diff || null, sonarIssues: input?.sonarIssues || null };
59
-
60
- const provider = resolveProvider(this.config);
61
- const agent = this._createAgent(provider, this.config, this.logger);
62
-
63
- const prompt = buildPrompt({ task, diff, sonarIssues, instructions: this.instructions });
64
- const result = await agent.runTask({ prompt, role: "tester" });
65
-
66
- if (!result.ok) {
67
- return {
68
- ok: false,
69
- result: {
70
- error: result.error || result.output || "Tester failed",
71
- provider
72
- },
73
- summary: `Tester failed: ${result.error || "unknown error"}`
74
- };
75
- }
114
+ parseOutput(raw) { return extractFirstJson(raw); }
76
115
 
77
- try {
78
- const parsed = parseTesterOutput(result.output);
79
- if (!parsed) {
80
- return {
81
- ok: false,
82
- result: { error: "Failed to parse tester output: no JSON found", provider },
83
- summary: "Tester output parse error: no JSON found"
84
- };
85
- }
116
+ isSuccessful(parsed) {
117
+ const verdict = parsed.verdict || (parsed.tests_pass ? "pass" : "fail");
118
+ return verdict === "pass";
119
+ }
86
120
 
87
- const verdict = parsed.verdict || (parsed.tests_pass ? "pass" : "fail");
88
- const ok = verdict === "pass";
89
- const coverage = parsed.coverage || {};
121
+ buildSuccessResult(parsed, provider) {
122
+ const verdict = parsed.verdict || (parsed.tests_pass ? "pass" : "fail");
123
+ return {
124
+ tests_pass: Boolean(parsed.tests_pass),
125
+ coverage: parsed.coverage || {},
126
+ missing_scenarios: parsed.missing_scenarios || [],
127
+ quality_issues: parsed.quality_issues || [],
128
+ verdict,
129
+ provider
130
+ };
131
+ }
90
132
 
91
- return {
92
- ok,
93
- result: {
94
- tests_pass: Boolean(parsed.tests_pass),
95
- coverage,
96
- missing_scenarios: parsed.missing_scenarios || [],
97
- quality_issues: parsed.quality_issues || [],
98
- verdict,
99
- provider
100
- },
101
- summary: (() => {
102
- const missingPart = parsed.missing_scenarios?.length ? `; ${parsed.missing_scenarios.length} missing scenario(s)` : "";
103
- const qualityPart = parsed.quality_issues?.length ? `; ${parsed.quality_issues.length} quality issue(s)` : "";
104
- return `Verdict: ${verdict}; Coverage: ${coverage.overall ?? "?"}%${missingPart}${qualityPart}`;
105
- })()
106
- };
107
- } catch (err) {
108
- return {
109
- ok: false,
110
- result: { error: `Failed to parse tester output: ${err.message}`, provider },
111
- summary: `Tester output parse error: ${err.message}`
112
- };
113
- }
133
+ buildSummary(parsed) {
134
+ const verdict = parsed.verdict || (parsed.tests_pass ? "pass" : "fail");
135
+ const coverage = parsed.coverage || {};
136
+ const coverageStr = coverage.overall != null ? `${coverage.overall}%` : "not measured";
137
+ const missingPart = parsed.missing_scenarios?.length ? `; ${parsed.missing_scenarios.length} missing scenario(s)` : "";
138
+ const qualityPart = parsed.quality_issues?.length ? `; ${parsed.quality_issues.length} quality issue(s)` : "";
139
+ return `Verdict: ${verdict}; Coverage: ${coverageStr}${missingPart}${qualityPart}`;
114
140
  }
115
141
  }