karajan-code 1.49.0 → 1.50.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/package.json +1 -1
- package/src/mcp/handlers/direct-handlers.js +393 -0
- package/src/mcp/handlers/hu-handlers.js +93 -0
- package/src/mcp/handlers/management-handlers.js +182 -0
- package/src/mcp/handlers/run-handler.js +283 -0
- package/src/mcp/server-handlers.js +40 -870
- package/src/orchestrator/iteration-stages.js +9 -890
- package/src/orchestrator/pre-loop-stages.js +8 -906
- package/src/orchestrator/stages/architect-stage.js +176 -0
- package/src/orchestrator/stages/coder-stage.js +307 -0
- package/src/orchestrator/stages/hu-reviewer-stage.js +467 -0
- package/src/orchestrator/stages/planner-stage.js +90 -0
- package/src/orchestrator/stages/research-stage.js +74 -0
- package/src/orchestrator/stages/reviewer-stage.js +350 -0
- package/src/orchestrator/stages/sonar-stage.js +267 -0
- package/src/orchestrator/stages/triage-stage.js +137 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run and Resume handler logic.
|
|
3
|
+
* Extracted from server-handlers.js for maintainability.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { EventEmitter } from "node:events";
|
|
7
|
+
import { runFlow, resumeFlow } from "../../orchestrator.js";
|
|
8
|
+
import { loadConfig, applyRunOverrides, validateConfig, resolveRole } from "../../config.js";
|
|
9
|
+
import { createLogger } from "../../utils/logger.js";
|
|
10
|
+
import { assertAgentsAvailable } from "../../agents/availability.js";
|
|
11
|
+
import { createRunLog } from "../../utils/run-log.js";
|
|
12
|
+
import { buildProgressHandler, buildProgressNotifier, buildPipelineTracker } from "../progress.js";
|
|
13
|
+
import { isPreflightAcked, ackPreflight, getSessionOverrides } from "../preflight.js";
|
|
14
|
+
import { ensureBootstrap } from "../../bootstrap.js";
|
|
15
|
+
import { validateSovereignty } from "../sovereignty-guard.js";
|
|
16
|
+
import {
|
|
17
|
+
resolveProjectDir,
|
|
18
|
+
failPayload,
|
|
19
|
+
classifyError,
|
|
20
|
+
assertNotOnBaseBranch,
|
|
21
|
+
buildConfig,
|
|
22
|
+
buildAskQuestion,
|
|
23
|
+
enrichedFailPayload,
|
|
24
|
+
} from "../server-handlers.js";
|
|
25
|
+
|
|
26
|
+
const MAX_AUTO_RESUMES = 2;
|
|
27
|
+
const NON_RECOVERABLE_CATEGORIES = new Set([
|
|
28
|
+
"config_error", "auth_error", "agent_missing", "branch_error", "git_error", "bootstrap_error"
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
async function attemptAutoResume({ err, config, logger, emitter, askQuestion, runLog }) {
|
|
32
|
+
const { category } = classifyError(err);
|
|
33
|
+
if (NON_RECOVERABLE_CATEGORIES.has(category)) return null;
|
|
34
|
+
|
|
35
|
+
// Find session ID from most recent session file
|
|
36
|
+
const { loadMostRecentSession } = await import("../../session-store.js");
|
|
37
|
+
let session;
|
|
38
|
+
try {
|
|
39
|
+
session = await loadMostRecentSession();
|
|
40
|
+
} catch { /* no session store or read error */
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
if (!session || !["failed", "stopped"].includes(session.status)) return null;
|
|
44
|
+
|
|
45
|
+
const maxRetries = config.session?.max_auto_resumes ?? MAX_AUTO_RESUMES;
|
|
46
|
+
const autoResumeCount = session.auto_resume_count || 0;
|
|
47
|
+
if (autoResumeCount >= maxRetries) {
|
|
48
|
+
runLog.logText(`[resilient] auto-resume limit reached (${maxRetries}), giving up`);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
runLog.logText(`[resilient] run failed (${category}), auto-resuming (${autoResumeCount + 1}/${maxRetries})...`);
|
|
53
|
+
emitter.emit("progress", {
|
|
54
|
+
type: "resilient:auto_resume",
|
|
55
|
+
attempt: autoResumeCount + 1,
|
|
56
|
+
maxRetries,
|
|
57
|
+
errorCategory: category,
|
|
58
|
+
sessionId: session.id
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Increment counter and save before resuming
|
|
62
|
+
const { saveSession } = await import("../../session-store.js");
|
|
63
|
+
session.auto_resume_count = autoResumeCount + 1;
|
|
64
|
+
await saveSession(session);
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
const result = await resumeFlow({
|
|
68
|
+
sessionId: session.id,
|
|
69
|
+
config,
|
|
70
|
+
logger,
|
|
71
|
+
flags: {},
|
|
72
|
+
emitter,
|
|
73
|
+
askQuestion
|
|
74
|
+
});
|
|
75
|
+
const ok = !result.paused && (result.approved !== false);
|
|
76
|
+
runLog.logText(`[resilient] auto-resume ${ok ? "succeeded" : "finished"} — ok=${ok}`);
|
|
77
|
+
return { ok, ...result, autoResumed: true, autoResumeAttempt: autoResumeCount + 1 };
|
|
78
|
+
} catch (error) {
|
|
79
|
+
// Recursive: try again if still within limits
|
|
80
|
+
const nestedResult = await attemptAutoResume({
|
|
81
|
+
err: error, config, logger, emitter, askQuestion, runLog
|
|
82
|
+
});
|
|
83
|
+
if (nestedResult) return nestedResult;
|
|
84
|
+
runLog.logText(`[resilient] auto-resume failed: ${error.message}`);
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const PIPELINE_PROVIDER_ROLES = [
|
|
90
|
+
["triage", true],
|
|
91
|
+
["planner", true],
|
|
92
|
+
["refactorer", true],
|
|
93
|
+
["researcher", true],
|
|
94
|
+
["tester", true],
|
|
95
|
+
["security", true]
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
function collectRequiredProviders(config) {
|
|
99
|
+
const providers = [
|
|
100
|
+
resolveRole(config, "coder").provider,
|
|
101
|
+
config.reviewer_options?.fallback_reviewer
|
|
102
|
+
];
|
|
103
|
+
if (config.pipeline?.reviewer?.enabled !== false) {
|
|
104
|
+
providers.push(resolveRole(config, "reviewer").provider);
|
|
105
|
+
}
|
|
106
|
+
for (const [role, requireEnabled] of PIPELINE_PROVIDER_ROLES) {
|
|
107
|
+
if (requireEnabled && config.pipeline?.[role]?.enabled) {
|
|
108
|
+
providers.push(resolveRole(config, role).provider);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return providers;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function handleRunDirect(a, server, extra) {
|
|
115
|
+
const config = await buildConfig(a);
|
|
116
|
+
await assertNotOnBaseBranch(config);
|
|
117
|
+
const logger = createLogger(config.output.log_level, "mcp");
|
|
118
|
+
|
|
119
|
+
// Best-effort session cleanup before starting
|
|
120
|
+
try {
|
|
121
|
+
const { cleanupExpiredSessions } = await import("../../session-cleanup.js");
|
|
122
|
+
await cleanupExpiredSessions({ logger });
|
|
123
|
+
} catch { /* non-blocking */ }
|
|
124
|
+
|
|
125
|
+
await assertAgentsAvailable(collectRequiredProviders(config));
|
|
126
|
+
|
|
127
|
+
const projectDir = await resolveProjectDir(server, a.projectDir);
|
|
128
|
+
const runLog = createRunLog(projectDir);
|
|
129
|
+
runLog.logText(`[kj_run] started — task="${a.task.slice(0, 80)}..."`);
|
|
130
|
+
|
|
131
|
+
const emitter = new EventEmitter();
|
|
132
|
+
emitter.on("progress", buildProgressHandler(server));
|
|
133
|
+
emitter.on("progress", (event) => runLog.logEvent(event));
|
|
134
|
+
const progressNotifier = buildProgressNotifier(extra);
|
|
135
|
+
if (progressNotifier) emitter.on("progress", progressNotifier);
|
|
136
|
+
buildPipelineTracker(config, emitter);
|
|
137
|
+
|
|
138
|
+
const askQuestion = buildAskQuestion(server);
|
|
139
|
+
const pgTaskId = a.pgTask || null;
|
|
140
|
+
const pgProject = a.pgProject || config.planning_game?.project_id || null;
|
|
141
|
+
try {
|
|
142
|
+
const result = await runFlow({ task: a.task, config, logger, flags: a, emitter, askQuestion, pgTaskId, pgProject });
|
|
143
|
+
runLog.logText(`[kj_run] finished — ok=${!result.paused && (result.approved !== false)}`);
|
|
144
|
+
return { ok: !result.paused && (result.approved !== false), ...result };
|
|
145
|
+
} catch (err) {
|
|
146
|
+
const autoResumeResult = await attemptAutoResume({
|
|
147
|
+
err, config, logger, emitter, askQuestion, runLog, progressNotifier, extra
|
|
148
|
+
});
|
|
149
|
+
if (autoResumeResult) return autoResumeResult;
|
|
150
|
+
throw err;
|
|
151
|
+
} finally {
|
|
152
|
+
runLog.close();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function handleResumeDirect(a, server, extra) {
|
|
157
|
+
const config = await buildConfig(a);
|
|
158
|
+
const logger = createLogger(config.output.log_level, "mcp");
|
|
159
|
+
|
|
160
|
+
const projectDir = await resolveProjectDir(server, a.projectDir);
|
|
161
|
+
const runLog = createRunLog(projectDir);
|
|
162
|
+
runLog.logText(`[kj_resume] started — session="${a.sessionId}"`);
|
|
163
|
+
|
|
164
|
+
const emitter = new EventEmitter();
|
|
165
|
+
emitter.on("progress", buildProgressHandler(server));
|
|
166
|
+
emitter.on("progress", (event) => runLog.logEvent(event));
|
|
167
|
+
const progressNotifier = buildProgressNotifier(extra);
|
|
168
|
+
if (progressNotifier) emitter.on("progress", progressNotifier);
|
|
169
|
+
|
|
170
|
+
const askQuestion = buildAskQuestion(server);
|
|
171
|
+
try {
|
|
172
|
+
const result = await resumeFlow({
|
|
173
|
+
sessionId: a.sessionId,
|
|
174
|
+
answer: a.answer || null,
|
|
175
|
+
config,
|
|
176
|
+
logger,
|
|
177
|
+
flags: a,
|
|
178
|
+
emitter,
|
|
179
|
+
askQuestion
|
|
180
|
+
});
|
|
181
|
+
const ok = !result.paused && (result.approved !== false);
|
|
182
|
+
runLog.logText(`[kj_resume] finished — ok=${ok}`);
|
|
183
|
+
return { ok, ...result };
|
|
184
|
+
} catch (err) {
|
|
185
|
+
runLog.logText(`[kj_resume] failed: ${err.message}`);
|
|
186
|
+
throw err;
|
|
187
|
+
} finally {
|
|
188
|
+
runLog.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const RESUME_MAX_ANSWER_LENGTH = 500;
|
|
193
|
+
const RESUME_INJECTION_PATTERNS = [
|
|
194
|
+
/ignore\s+(previous|all|above)\s+(instructions|rules|prompts)/i,
|
|
195
|
+
/you\s+are\s+now/i,
|
|
196
|
+
/new\s+instructions?:/i,
|
|
197
|
+
/override\s+(all|security|guardrails|rules)/i,
|
|
198
|
+
/skip\s+(all\s+)?(review|test|sonar|security|solomon|guard)s?\b/i,
|
|
199
|
+
/disable\s+(tdd|review|test|sonar|security)\b/i,
|
|
200
|
+
/set\s+(status|approved|verdict)\s*(=|to|:)/i,
|
|
201
|
+
/force\s+(approve|merge|push|commit)\b/i,
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
export function validateResumeAnswer(answer) {
|
|
205
|
+
if (answer == null || answer === "") return { valid: true, sanitized: answer ?? null };
|
|
206
|
+
if (typeof answer !== "string") return { valid: true, sanitized: String(answer) };
|
|
207
|
+
if (answer.length > RESUME_MAX_ANSWER_LENGTH) {
|
|
208
|
+
return { valid: false, reason: `Answer too long (${answer.length} chars, max ${RESUME_MAX_ANSWER_LENGTH})` };
|
|
209
|
+
}
|
|
210
|
+
for (const pattern of RESUME_INJECTION_PATTERNS) {
|
|
211
|
+
if (pattern.test(answer)) {
|
|
212
|
+
return { valid: false, reason: "Answer rejected: matches guardrail bypass pattern" };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { valid: true, sanitized: answer.trim() };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Run bootstrap gate: validate all environment prerequisites before execution.
|
|
220
|
+
* Throws if any prerequisite fails.
|
|
221
|
+
*/
|
|
222
|
+
async function runBootstrapGate(server, a) {
|
|
223
|
+
const projectDir = await resolveProjectDir(server, a.projectDir);
|
|
224
|
+
const { config } = await loadConfig(projectDir);
|
|
225
|
+
await ensureBootstrap(projectDir, config);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function applySessionOverrides(a, roleKeys) {
|
|
229
|
+
const sessionOvr = getSessionOverrides();
|
|
230
|
+
for (const key of roleKeys) {
|
|
231
|
+
if (sessionOvr[key] !== undefined) { a[key] = sessionOvr[key]; }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export async function handleResume(a, server, extra) {
|
|
236
|
+
if (!a.sessionId) {
|
|
237
|
+
return failPayload("Missing required field: sessionId");
|
|
238
|
+
}
|
|
239
|
+
await runBootstrapGate(server, a);
|
|
240
|
+
if (a.answer) {
|
|
241
|
+
const validation = validateResumeAnswer(a.answer);
|
|
242
|
+
if (!validation.valid) {
|
|
243
|
+
return failPayload(`Resume answer rejected: ${validation.reason}`);
|
|
244
|
+
}
|
|
245
|
+
a.answer = validation.sanitized;
|
|
246
|
+
}
|
|
247
|
+
applySessionOverrides(a, ["coder", "reviewer", "tester", "security", "solomon", "enableTester", "enableSecurity", "enableImpeccable"]);
|
|
248
|
+
return handleResumeDirect(a, server, extra);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function handleRun(a, server, extra) {
|
|
252
|
+
if (!a.task) {
|
|
253
|
+
return failPayload("Missing required field: task");
|
|
254
|
+
}
|
|
255
|
+
if (a.taskType) {
|
|
256
|
+
const validTypes = new Set(["sw", "infra", "doc", "add-tests", "refactor"]);
|
|
257
|
+
if (!validTypes.has(a.taskType)) {
|
|
258
|
+
return failPayload(`Invalid taskType "${a.taskType}". Valid values: ${[...validTypes].join(", ")}`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Sovereignty guard: sanitise params and check for active sessions
|
|
263
|
+
const projectDir = await resolveProjectDir(server, a.projectDir);
|
|
264
|
+
const sovereignty = validateSovereignty(a, { projectDir });
|
|
265
|
+
if (sovereignty.error) {
|
|
266
|
+
return failPayload(sovereignty.error);
|
|
267
|
+
}
|
|
268
|
+
if (sovereignty.warnings.length > 0) {
|
|
269
|
+
const logger = createLogger("info", "mcp");
|
|
270
|
+
for (const w of sovereignty.warnings) logger.warn(`[sovereignty] ${w}`);
|
|
271
|
+
}
|
|
272
|
+
Object.assign(a, sovereignty.params);
|
|
273
|
+
|
|
274
|
+
await runBootstrapGate(server, a);
|
|
275
|
+
if (!isPreflightAcked()) {
|
|
276
|
+
// Auto-acknowledge with defaults for autonomous operation
|
|
277
|
+
ackPreflight({});
|
|
278
|
+
const logger = createLogger("info", "mcp");
|
|
279
|
+
logger.info("Preflight auto-acknowledged with default agent config");
|
|
280
|
+
}
|
|
281
|
+
applySessionOverrides(a, ["coder", "reviewer", "tester", "security", "solomon", "enableTester", "enableSecurity", "enableImpeccable"]);
|
|
282
|
+
return handleRunDirect(a, server, extra);
|
|
283
|
+
}
|