karajan-code 2.7.3 → 2.8.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 (167) hide show
  1. package/README.md +4 -4
  2. package/package.json +24 -4
  3. package/scripts/diet-baseline.mjs +170 -0
  4. package/scripts/regen-arch-stats.sh +71 -0
  5. package/src/agents/availability.js +15 -9
  6. package/src/agents/claude-agent.js +143 -45
  7. package/src/agents/model-registry.js +1 -1
  8. package/src/audit/agent-readiness.js +240 -0
  9. package/src/bootstrap.js +26 -1
  10. package/src/brain/decision-tracker.js +3 -1
  11. package/src/brain/decisor.js +1 -1
  12. package/src/canvas/parse-md.js +238 -0
  13. package/src/canvas/schema.js +101 -0
  14. package/src/canvas/to-flat.js +85 -0
  15. package/src/canvas/validate.js +163 -0
  16. package/src/checks/binaries.js +1 -1
  17. package/src/checks/ports.js +97 -27
  18. package/src/checks/runner.js +26 -10
  19. package/src/checks/sonar.js +1 -1
  20. package/src/checks/system.js +1 -1
  21. package/src/checks/tokens.js +77 -24
  22. package/src/cli/_shared.js +30 -0
  23. package/src/cli/register-meta.js +204 -0
  24. package/src/cli/register-pipeline.js +212 -0
  25. package/src/cli/register-plan.js +152 -0
  26. package/src/cli/register-roles-skills.js +38 -0
  27. package/src/cli/register-sonar.js +28 -0
  28. package/src/cli.js +83 -468
  29. package/src/commands/agents.js +18 -6
  30. package/src/commands/architect.js +29 -2
  31. package/src/commands/audit.js +27 -3
  32. package/src/commands/board.js +160 -30
  33. package/src/commands/clean.js +83 -0
  34. package/src/commands/code.js +7 -2
  35. package/src/commands/discover.js +7 -2
  36. package/src/commands/init.js +2 -2
  37. package/src/commands/plan/_shared.js +40 -0
  38. package/src/commands/plan/add-hu.js +21 -0
  39. package/src/commands/plan/delete.js +9 -0
  40. package/src/commands/plan/generate.js +284 -0
  41. package/src/commands/plan/index.js +14 -0
  42. package/src/commands/plan/list.js +21 -0
  43. package/src/commands/plan/ready.js +46 -0
  44. package/src/commands/plan/remove-hu.js +17 -0
  45. package/src/commands/plan/show.js +81 -0
  46. package/src/commands/plan/validate.js +20 -0
  47. package/src/commands/plan.js +14 -291
  48. package/src/commands/researcher.js +7 -2
  49. package/src/commands/resume.js +24 -1
  50. package/src/commands/review.js +7 -2
  51. package/src/commands/run.js +52 -1
  52. package/src/commands/status.js +1 -1
  53. package/src/commands/sync.js +75 -0
  54. package/src/commands/triage.js +7 -2
  55. package/src/commands/undo.js +1 -1
  56. package/src/config/defaults.js +213 -0
  57. package/src/config/loader.js +137 -0
  58. package/src/config/overrides.js +199 -0
  59. package/src/config/role-resolver.js +159 -0
  60. package/src/config/test-harness.js +79 -0
  61. package/src/config.js +30 -609
  62. package/src/git/automation.js +2 -2
  63. package/src/guards/output-guard.js +0 -2
  64. package/src/hu/acceptance-runner.js +52 -10
  65. package/src/hu/store.js +11 -0
  66. package/src/mcp/handlers/direct-handlers.js +2 -5
  67. package/src/mcp/handlers/management-handlers.js +48 -4
  68. package/src/mcp/handlers/run-handler.js +9 -8
  69. package/src/mcp/preflight.js +32 -13
  70. package/src/mcp/server-handlers.js +4 -3
  71. package/src/mcp/suggest-handler.js +3 -2
  72. package/src/mcp/tools.js +15 -0
  73. package/src/orchestrator/agent-fallback.js +1 -1
  74. package/src/orchestrator/ci-integration.js +10 -10
  75. package/src/orchestrator/config-init.js +25 -7
  76. package/src/orchestrator/direct-actions.js +6 -2
  77. package/src/orchestrator/drivers/error-recovery.js +287 -0
  78. package/src/orchestrator/drivers/init-context.js +222 -0
  79. package/src/orchestrator/drivers/iteration-loop.js +311 -0
  80. package/src/orchestrator/drivers/iteration-phases/coder-and-refactorer.js +48 -0
  81. package/src/orchestrator/drivers/iteration-phases/guards.js +84 -0
  82. package/src/orchestrator/drivers/iteration-phases/handle-approved.js +29 -0
  83. package/src/orchestrator/drivers/iteration-phases/quality-gates.js +76 -0
  84. package/src/orchestrator/drivers/iteration-phases/reviewer-gate.js +60 -0
  85. package/src/orchestrator/drivers/post-loop.js +370 -0
  86. package/src/orchestrator/drivers/pre-loop-phases/auto-hu-batch.js +116 -0
  87. package/src/orchestrator/drivers/pre-loop-phases/config-deprecations.js +47 -0
  88. package/src/orchestrator/drivers/pre-loop-phases/ensure-addyosmani-skills.js +84 -0
  89. package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +268 -0
  90. package/src/orchestrator/drivers/pre-loop.js +434 -0
  91. package/src/orchestrator/drivers/run-hu-batch.js +367 -0
  92. package/src/orchestrator/flow-control.js +4 -3
  93. package/src/orchestrator/flow-runner.js +121 -2019
  94. package/src/orchestrator/fs-leak-detector.js +156 -0
  95. package/src/orchestrator/hu-sub-pipeline.js +197 -9
  96. package/src/orchestrator/integrations.js +88 -0
  97. package/src/orchestrator/post-loop-stages.js +35 -8
  98. package/src/orchestrator/preflight-checks.js +30 -3
  99. package/src/orchestrator/repair/repair-detector.js +117 -0
  100. package/src/orchestrator/repair/repair-runner.js +142 -0
  101. package/src/orchestrator/reviewer-fallback.js +1 -1
  102. package/src/orchestrator/solomon-escalation.js +3 -2
  103. package/src/orchestrator/solomon-rules.js +7 -3
  104. package/src/orchestrator/stages/architect-stage.js +12 -11
  105. package/src/orchestrator/stages/coder-stage.js +56 -7
  106. package/src/orchestrator/stages/hu-reviewer-phases/detect-and-apply-splits.js +127 -0
  107. package/src/orchestrator/stages/hu-reviewer-stage.js +6 -79
  108. package/src/orchestrator/stages/planner-stage.js +1 -1
  109. package/src/orchestrator/stages/research-stage.js +1 -1
  110. package/src/orchestrator/stages/reviewer-stage.js +7 -7
  111. package/src/orchestrator/stages/sonar-stage.js +94 -10
  112. package/src/orchestrator/stages/stage-classes.js +86 -0
  113. package/src/orchestrator/stages/stage-executor.js +1 -1
  114. package/src/orchestrator/stages/triage-stage.js +1 -1
  115. package/src/orchestrator/standby.js +3 -2
  116. package/src/orchestrator/verification-gate.js +20 -12
  117. package/src/plan/adr-generator.js +170 -0
  118. package/src/plan/adr-loader.js +60 -0
  119. package/src/plan/plan-executor.js +19 -1
  120. package/src/plan/plan-hu-ops.js +170 -1
  121. package/src/plan/plan-reviewer.js +199 -0
  122. package/src/plan/plan-schema.js +69 -1
  123. package/src/plan/plan-store.js +40 -3
  124. package/src/plan/spec-detector.js +61 -0
  125. package/src/plan/tests-synthesizer.js +116 -0
  126. package/src/planning-game/client.js +3 -14
  127. package/src/planning-game/decomposition.js +1 -1
  128. package/src/planning-game/pipeline-adapter.js +36 -5
  129. package/src/prompts/coder.js +172 -1
  130. package/src/prompts/hu-reviewer.js +0 -1
  131. package/src/prompts/planner.js +81 -4
  132. package/src/review/diff-generator.js +35 -22
  133. package/src/review/snapshot-diff.js +1 -1
  134. package/src/roles/coder-role.js +25 -3
  135. package/src/roles/planner-role.js +42 -1
  136. package/src/roles/repairer-role.js +181 -0
  137. package/src/roles/tester-role.js +70 -4
  138. package/src/session/mutators.js +304 -0
  139. package/src/session/runtime-overrides.js +59 -0
  140. package/src/{session-store.js → session/store.js} +8 -2
  141. package/src/skills/semantic-detector.js +10 -5
  142. package/src/skills/skill-detector.js +1 -1
  143. package/src/sonar/cloud-scanner.js +0 -1
  144. package/src/sonar/credentials.js +14 -6
  145. package/src/sonar/discovery.js +123 -0
  146. package/src/sonar/manager.js +18 -0
  147. package/src/sync/detect-drift.js +113 -0
  148. package/src/tracker-bootstrap.js +44 -0
  149. package/src/utils/agent-detect.js +15 -11
  150. package/src/utils/board-prompt-bridge.js +109 -0
  151. package/src/utils/cli-progress.js +161 -0
  152. package/src/utils/cwd-confirm.js +39 -0
  153. package/src/utils/derive-project-name-from-cwd.js +119 -0
  154. package/src/utils/garbage-collector.js +396 -0
  155. package/src/utils/git.js +16 -4
  156. package/src/utils/locale.js +1 -1
  157. package/src/utils/paths.js +21 -1
  158. package/src/utils/process.js +1 -1
  159. package/src/utils/prompt-project-name.js +35 -0
  160. package/src/utils/run-context.js +75 -0
  161. package/src/utils/run-log.js +12 -0
  162. package/src/utils/task-file.js +1 -1
  163. package/src/utils/telemetry.js +13 -1
  164. package/src/webperf/devtools-detect.js +1 -1
  165. package/templates/coder-rules.md +13 -0
  166. package/templates/roles/coder.md +34 -0
  167. package/templates/roles/repairer.md +94 -0
@@ -0,0 +1,127 @@
1
+ /**
2
+ * HU Reviewer phase: detect splittable HUs and apply the split.
3
+ *
4
+ * Extracted from `runHuReviewerStage` in PR-M (audit follow-up,
5
+ * KJC-PCS-0033). Was 78 LOC inlined inside the 311-LOC parent
6
+ * function — moving it brings the stage closer to a clean
7
+ * load → split → evaluate → return shape.
8
+ *
9
+ * For each pending HU in the batch:
10
+ *
11
+ * 1. Run the deterministic indicator detector
12
+ * (src/hu/splitting-detector.js). If no indicators, skip.
13
+ * 2. Pick the first heuristic that matches; ask the LLM for a
14
+ * split proposal. Retry with other heuristics on failure.
15
+ * 3. In autonomous mode (askQuestion=null) the proposal is
16
+ * auto-accepted. In interactive mode the FDE confirms.
17
+ * 4. Replace the original story with the proposed sub-HUs in
18
+ * the batch and persist.
19
+ *
20
+ * Behaviour identical to the inlined version — only the container
21
+ * changes. The closure variables (batch, askQuestion, config,
22
+ * logger, emitter, eventBase, batchSessionId) become explicit
23
+ * function parameters.
24
+ */
25
+
26
+ import { saveHuBatch, updateStoryStatus } from "#hu/store.js";
27
+ import { emitProgress, makeEvent } from "#utils/events.js";
28
+ import { detectIndicators, selectHeuristic } from "#hu/splitting-detector.js";
29
+ import { generateSplitProposal, formatSplitProposalForFDE, buildSplitDependencies } from "#hu/splitting-generator.js";
30
+
31
+ /**
32
+ * Build a fresh sub-HU story object from a proposal entry. Same
33
+ * shape the inlined code produced; centralised to avoid the
34
+ * autonomous + interactive paths drifting apart.
35
+ */
36
+ function buildSubHuStory(sub) {
37
+ const text = `${sub.title}\n\n${sub.text}\n\nAcceptance Criteria:\n${(sub.acceptanceCriteria || []).map((ac) => `- ${ac}`).join("\n")}`;
38
+ const now = new Date().toISOString();
39
+ return {
40
+ id: sub.id,
41
+ status: "pending",
42
+ original: { text },
43
+ blocked_by: sub.blocked_by || [],
44
+ certified: null,
45
+ quality: null,
46
+ context_requests: [],
47
+ created_at: now,
48
+ updated_at: now,
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Replace `story` in `batch.stories` with the expanded sub-HUs and
54
+ * emit the `hu-reviewer:split-accepted` event.
55
+ */
56
+ function applySplit({ batch, story, proposal, heuristic, source, eventBase, emitter }) {
57
+ const updatedSubHUs = buildSplitDependencies(proposal.subHUs, story);
58
+ const storyIndex = batch.stories.findIndex((s) => s.id === story.id);
59
+ const newStories = updatedSubHUs.map(buildSubHuStory);
60
+ batch.stories.splice(storyIndex, 1, ...newStories);
61
+ emitProgress(emitter, makeEvent("hu-reviewer:split-accepted", { ...eventBase, stage: "hu-reviewer" }, {
62
+ message: `${source} accepted split of ${story.id} into ${updatedSubHUs.length} sub-HUs`,
63
+ detail: { originalId: story.id, subHUs: updatedSubHUs.map((s) => s.id), heuristic }
64
+ }));
65
+ }
66
+
67
+ /**
68
+ * @param {object} args
69
+ * @param {object} args.batch — HU batch (mutated in place)
70
+ * @param {string} args.batchSessionId — for saveHuBatch persistence
71
+ * @param {Function|null} args.askQuestion — interactive prompt (null = auto-accept)
72
+ * @param {object} args.config
73
+ * @param {object} args.logger
74
+ * @param {object} args.emitter
75
+ * @param {object} args.eventBase
76
+ */
77
+ export async function detectAndApplySplits({ batch, batchSessionId, askQuestion, config, logger, emitter, eventBase }) {
78
+ const storiesToSplit = [...batch.stories].filter((s) => s.status === "pending");
79
+ for (const story of storiesToSplit) {
80
+ const indicators = detectIndicators(story.original.text);
81
+ if (indicators.length === 0) continue;
82
+
83
+ let heuristic = selectHeuristic(indicators);
84
+ if (!heuristic) continue;
85
+
86
+ const triedHeuristics = [];
87
+
88
+ while (heuristic) {
89
+ const proposal = await generateSplitProposal(
90
+ { id: story.id, text: story.original.text },
91
+ heuristic, config, logger
92
+ );
93
+
94
+ if (!proposal) {
95
+ triedHeuristics.push(heuristic);
96
+ heuristic = selectHeuristic(indicators, triedHeuristics);
97
+ continue;
98
+ }
99
+
100
+ if (!askQuestion) {
101
+ // Autonomous mode: auto-accept the split.
102
+ applySplit({ batch, story, proposal, heuristic, source: "Auto", eventBase, emitter });
103
+ } else {
104
+ // Interactive mode: ask FDE for confirmation.
105
+ const formatted = formatSplitProposalForFDE(proposal);
106
+ const question = `Split proposed for ${story.id}:\n${formatted}\nAccept? (yes/no/try another)`;
107
+ emitProgress(emitter, makeEvent("hu-reviewer:split-proposal", { ...eventBase, stage: "hu-reviewer" }, {
108
+ message: `Split proposal for ${story.id} using heuristic: ${heuristic}`,
109
+ detail: { originalId: story.id, heuristic, subHUCount: proposal.subHUs.length }
110
+ }));
111
+ const answer = await askQuestion(question, { iteration: 0, stage: "hu-reviewer" });
112
+ if (!answer || answer.toLowerCase().startsWith("yes")) {
113
+ applySplit({ batch, story, proposal, heuristic, source: "FDE", eventBase, emitter });
114
+ } else if (answer.toLowerCase().includes("try") || answer.toLowerCase().startsWith("no")) {
115
+ triedHeuristics.push(heuristic);
116
+ heuristic = selectHeuristic(indicators, triedHeuristics);
117
+ if (!heuristic) {
118
+ updateStoryStatus(batch, story.id, "needs_context");
119
+ }
120
+ continue;
121
+ }
122
+ }
123
+ break;
124
+ }
125
+ await saveHuBatch(batchSessionId, batch);
126
+ }
127
+ }
@@ -6,14 +6,13 @@
6
6
  import { DiscoverRole } from "../../roles/discover-role.js";
7
7
  import { HuReviewerRole } from "../../roles/hu-reviewer-role.js";
8
8
  import { createAgent } from "../../agents/index.js";
9
- import { addCheckpoint } from "../../session-store.js";
9
+ import { addCheckpoint } from "../../session/store.js";
10
10
  import { emitProgress, makeEvent } from "../../utils/events.js";
11
11
  import { buildDecompositionPrompt, parseDecompositionOutput } from "../../prompts/hu-reviewer.js";
12
12
  import { createStallDetector } from "../../utils/stall-detector.js";
13
13
  import { createHuBatch, loadHuBatch, saveHuBatch, updateStoryStatus, updateStoryQuality, updateStoryCertified, addContextRequest, answerContextRequest } from "../../hu/store.js";
14
14
  import { topologicalSort } from "../../hu/graph.js";
15
- import { detectIndicators, selectHeuristic } from "../../hu/splitting-detector.js";
16
- import { generateSplitProposal, formatSplitProposalForFDE, buildSplitDependencies } from "../../hu/splitting-generator.js";
15
+ import { detectAndApplySplits } from "./hu-reviewer-phases/detect-and-apply-splits.js";
17
16
 
18
17
  /**
19
18
  * Use an AI agent to decompose a complex task into multiple formal HUs.
@@ -239,83 +238,11 @@ export async function runHuReviewerStage({ config, logger, emitter, eventBase, s
239
238
  batch = await createHuBatch(batchSessionId, stories);
240
239
  }
241
240
 
242
- // --- Splitting detection: check each pending HU for split indicators before 6D evaluation ---
243
- const storiesToSplit = [...batch.stories].filter(s => s.status === "pending");
244
- for (const story of storiesToSplit) {
245
- const indicators = detectIndicators(story.original.text);
246
- if (indicators.length === 0) continue;
247
-
248
- let heuristic = selectHeuristic(indicators);
249
- if (!heuristic) continue;
250
-
251
- const triedHeuristics = [];
252
- let splitAccepted = false;
253
-
254
- while (heuristic && !splitAccepted) {
255
- const proposal = await generateSplitProposal(
256
- { id: story.id, text: story.original.text },
257
- heuristic, config, logger
258
- );
259
-
260
- if (!proposal) {
261
- triedHeuristics.push(heuristic);
262
- heuristic = selectHeuristic(indicators, triedHeuristics);
263
- continue;
264
- }
241
+ // --- Splitting detection: extracted to hu-reviewer-phases/detect-and-apply-splits.js (PR-M) ---
242
+ await detectAndApplySplits({
243
+ batch, batchSessionId, askQuestion, config, logger, emitter, eventBase,
244
+ });
265
245
 
266
- if (!askQuestion) {
267
- // Autonomous mode: auto-accept the split
268
- const updatedSubHUs = buildSplitDependencies(proposal.subHUs, story);
269
- const storyIndex = batch.stories.findIndex(s => s.id === story.id);
270
- const newStories = updatedSubHUs.map(sub => ({
271
- id: sub.id, status: "pending",
272
- original: { text: `${sub.title}\n\n${sub.text}\n\nAcceptance Criteria:\n${(sub.acceptanceCriteria || []).map(ac => `- ${ac}`).join("\n")}` },
273
- blocked_by: sub.blocked_by || [], certified: null, quality: null,
274
- context_requests: [], created_at: new Date().toISOString(), updated_at: new Date().toISOString()
275
- }));
276
- batch.stories.splice(storyIndex, 1, ...newStories);
277
- splitAccepted = true;
278
- emitProgress(emitter, makeEvent("hu-reviewer:split-accepted", { ...eventBase, stage: "hu-reviewer" }, {
279
- message: `Auto-accepted split of ${story.id} into ${updatedSubHUs.length} sub-HUs`,
280
- detail: { originalId: story.id, subHUs: updatedSubHUs.map(s => s.id), heuristic }
281
- }));
282
- } else {
283
- // Interactive mode: ask FDE for confirmation
284
- const formatted = formatSplitProposalForFDE(proposal);
285
- const question = `Split proposed for ${story.id}:\n${formatted}\nAccept? (yes/no/try another)`;
286
- emitProgress(emitter, makeEvent("hu-reviewer:split-proposal", { ...eventBase, stage: "hu-reviewer" }, {
287
- message: `Split proposal for ${story.id} using heuristic: ${heuristic}`,
288
- detail: { originalId: story.id, heuristic, subHUCount: proposal.subHUs.length }
289
- }));
290
- const answer = await askQuestion(question, { iteration: 0, stage: "hu-reviewer" });
291
- if (!answer || answer.toLowerCase().startsWith("yes")) {
292
- const updatedSubHUs = buildSplitDependencies(proposal.subHUs, story);
293
- const storyIndex = batch.stories.findIndex(s => s.id === story.id);
294
- const newStories = updatedSubHUs.map(sub => ({
295
- id: sub.id, status: "pending",
296
- original: { text: `${sub.title}\n\n${sub.text}\n\nAcceptance Criteria:\n${(sub.acceptanceCriteria || []).map(ac => `- ${ac}`).join("\n")}` },
297
- blocked_by: sub.blocked_by || [], certified: null, quality: null,
298
- context_requests: [], created_at: new Date().toISOString(), updated_at: new Date().toISOString()
299
- }));
300
- batch.stories.splice(storyIndex, 1, ...newStories);
301
- splitAccepted = true;
302
- emitProgress(emitter, makeEvent("hu-reviewer:split-accepted", { ...eventBase, stage: "hu-reviewer" }, {
303
- message: `FDE accepted split of ${story.id} into ${updatedSubHUs.length} sub-HUs`,
304
- detail: { originalId: story.id, subHUs: updatedSubHUs.map(s => s.id), heuristic }
305
- }));
306
- } else if (answer.toLowerCase().includes("try") || answer.toLowerCase().startsWith("no")) {
307
- triedHeuristics.push(heuristic);
308
- heuristic = selectHeuristic(indicators, triedHeuristics);
309
- if (!heuristic) {
310
- updateStoryStatus(batch, story.id, "needs_context");
311
- }
312
- continue;
313
- }
314
- }
315
- break;
316
- }
317
- await saveHuBatch(batchSessionId, batch);
318
- }
319
246
 
320
247
  // --- Evaluate loop (re-evaluate entire batch until all certified or needs_context with no askQuestion) ---
321
248
  const huReviewerOnOutput = ({ stream, line }) => {
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { PlannerRole } from "../../roles/planner-role.js";
7
7
  import { createAgent } from "../../agents/index.js";
8
- import { addCheckpoint, markSessionStatus } from "../../session-store.js";
8
+ import { addCheckpoint, markSessionStatus } from "../../session/store.js";
9
9
  import { emitProgress, makeEvent, emitAgentOutput } from "../../utils/events.js";
10
10
  import { parsePlannerOutput } from "../../prompts/planner.js";
11
11
  import { createStallDetector } from "../../utils/stall-detector.js";
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { ResearcherRole } from "../../roles/researcher-role.js";
7
- import { addCheckpoint } from "../../session-store.js";
7
+ import { addCheckpoint } from "../../session/store.js";
8
8
  import { emitProgress, makeEvent, emitAgentOutput } from "../../utils/events.js";
9
9
  import { createStallDetector } from "../../utils/stall-detector.js";
10
10
 
@@ -3,10 +3,11 @@
3
3
  * Extracted from iteration-stages.js for maintainability.
4
4
  */
5
5
 
6
- import { addCheckpoint, markSessionStatus, saveSession } from "../../session-store.js";
6
+ import { addCheckpoint, markSessionStatus, saveSession } from "../../session/store.js";
7
+ import { setReviewerFeedback, setDeferredIssues } from "../../session/mutators.js";
7
8
  import { generateDiff } from "../../review/diff-generator.js";
8
9
  import { validateReviewResult } from "../../review/schema.js";
9
- import { filterReviewScope, buildDeferredContext } from "../../review/scope-filter.js";
10
+ import { filterReviewScope } from "../../review/scope-filter.js";
10
11
  import { emitProgress, makeEvent, emitAgentOutput } from "../../utils/events.js";
11
12
  import { runReviewerWithFallback } from "../reviewer-fallback.js";
12
13
  import { invokeSolomon } from "../solomon-escalation.js";
@@ -110,7 +111,7 @@ async function handleReviewerStalledSolomon({ review, repeatCounts, repeatState,
110
111
  if (solomonResult.action === "continue") {
111
112
  repeatDetector.reviewer = { lastHash: null, repeatCount: 0 };
112
113
  if (solomonResult.humanGuidance) {
113
- session.last_reviewer_feedback = `Solomon/user guidance: ${solomonResult.humanGuidance}`;
114
+ setReviewerFeedback(session, `Solomon/user guidance: ${solomonResult.humanGuidance}`);
114
115
  await saveSession(session);
115
116
  }
116
117
  return { review };
@@ -144,7 +145,6 @@ async function handleReviewerRejection({ review, repeatDetector, config, logger,
144
145
  if (brainCtx?.enabled && config.brain?.bypass_solomon_on_correctness !== false) {
145
146
  const cats = categorizeIssues(review.blocking_issues);
146
147
  const nonStyleIssues = cats.security + cats.correctness + cats.tests;
147
- const styleIssues = cats.style;
148
148
  // Only bypass if there ARE non-style issues (correctness, tests, security, or "other" is correctness)
149
149
  // If it's style-only, let Solomon evaluate whether to override
150
150
  if (nonStyleIssues > 0 || cats.other > 0) {
@@ -156,9 +156,9 @@ async function handleReviewerRejection({ review, repeatDetector, config, logger,
156
156
  detail: { categories: cats, queueSize: brainCtx.feedbackQueue.entries.length }
157
157
  }));
158
158
  // Persist flat feedback for compat with non-Brain flow
159
- session.last_reviewer_feedback = review.blocking_issues
159
+ setReviewerFeedback(session, review.blocking_issues
160
160
  .map((x, idx) => `R-${idx + 1} [${x.severity || "medium"}]: ${x.description}`)
161
- .join("\n");
161
+ .join("\n"));
162
162
  await saveSession(session);
163
163
  return null; // null = continue to next iteration (coder fixes)
164
164
  }
@@ -339,7 +339,7 @@ export async function runReviewerStage({ reviewerRole, config, logger, emitter,
339
339
  logger.info(`Scope filter: deferred ${demoted.length} out-of-scope issue(s)${allDemoted ? " — auto-approved" : ""}`);
340
340
 
341
341
  // Accumulate deferred issues in session for tracking
342
- if (!session.deferred_issues) session.deferred_issues = [];
342
+ if (!session.deferred_issues) setDeferredIssues(session, []);
343
343
  session.deferred_issues.push(...deferred);
344
344
  await saveSession(session);
345
345
 
@@ -4,10 +4,57 @@
4
4
  */
5
5
 
6
6
  import { SonarRole } from "../../roles/sonar-role.js";
7
- import { addCheckpoint, markSessionStatus, saveSession } from "../../session-store.js";
7
+ import { addCheckpoint, markSessionStatus, saveSession } from "../../session/store.js";
8
+ import {
9
+ setReviewerFeedback, setSonarSummary, resetRetryCount, incrementRetryCount,
10
+ } from "../../session/mutators.js";
8
11
  import { emitProgress, makeEvent } from "../../utils/events.js";
9
12
  import { invokeSolomon } from "../solomon-escalation.js";
10
13
  import { sonarUp, isSonarReachable } from "../../sonar/manager.js";
14
+ import { addEntries } from "../feedback-queue.js";
15
+
16
+ /**
17
+ * Detect sonar errors that are caused by a malformed `sonar-project.properties`
18
+ * (or equivalent CLI args) — i.e. the scanner refused to start at all because
19
+ * a path is wrong, a key is missing, or a value is invalid. These are NOT
20
+ * findings about user code; they're the coder's own configuration mistake.
21
+ *
22
+ * When this fires, the right move is to send a precise diagnostic to the
23
+ * coder so it fixes the config in the next iteration. Bypassing with the
24
+ * Brain (or Solomon) on a config error means iterating 5 times against the
25
+ * same wall — Sonar can't possibly succeed until the config is fixed.
26
+ *
27
+ * Returns a string with actionable guidance, or null when the error is a
28
+ * different category (auth, network, scanner crash) that the coder can't
29
+ * resolve from inside the codebase.
30
+ */
31
+ function detectSonarConfigError(rawError) {
32
+ if (!rawError || typeof rawError !== "string") return null;
33
+
34
+ // "Invalid value of sonar.tests for X — The folder 'tests' does not exist"
35
+ // (and its sonar.sources / sonar.exclusions / sonar.coverage.* siblings).
36
+ const invalidPath = rawError.match(/Invalid value of (sonar\.\w[\w.]*) for [^\n]+\nERROR The folder '([^']+)' does not exist/);
37
+ if (invalidPath) {
38
+ const [, key, dir] = invalidPath;
39
+ return [
40
+ `The Sonar property \`${key}=${dir}\` in sonar-project.properties points to a directory that doesn't exist.`,
41
+ `Fix one of these in the SAME iteration:`,
42
+ ` - Create the \`${dir}/\` directory in the project root, or`,
43
+ ` - Edit sonar-project.properties so \`${key}\` points to an existing directory, or`,
44
+ ` - Remove the \`${key}\` line entirely if the project legitimately has no such folder.`,
45
+ `Without this fix, Sonar will refuse to scan and the run will burn every remaining iteration on the same error.`,
46
+ ].join("\n");
47
+ }
48
+
49
+ // Fallback patterns for other config-shaped failures.
50
+ if (/Invalid value of sonar\./i.test(rawError)) {
51
+ return `Sonar refused to start because of an invalid value in sonar-project.properties. Read the scanner's error above and fix the offending key in this iteration: ${rawError.slice(0, 300)}`;
52
+ }
53
+ if (/sonar-project\.properties.*not found/i.test(rawError) || /No project key/i.test(rawError)) {
54
+ return `Sonar can't find a usable sonar-project.properties. Generate one at the project root with at minimum: sonar.projectKey, sonar.projectName, sonar.sources=src, and sonar.tests pointing to an EXISTING directory (or omit it).`;
55
+ }
56
+ return null;
57
+ }
11
58
 
12
59
  async function handleSonarStalled({ repeatDetector, logger, emitter, eventBase, session, budgetSummary }) {
13
60
  const repeatCounts = repeatDetector.getRepeatCounts();
@@ -34,7 +81,7 @@ async function handleSonarRetryLimit({ config, logger, emitter, eventBase, sessi
34
81
  message: `Sonar sub-loop limit reached (${session.sonar_retry_count}/${maxSonarRetries}) — Brain handling`,
35
82
  detail: { subloop: "sonar", retryCount: session.sonar_retry_count, limit: maxSonarRetries, gateStatus: sonarResult.gateStatus }
36
83
  }));
37
- session.sonar_retry_count = 0;
84
+ resetRetryCount(session, "sonar");
38
85
  await saveSession(session);
39
86
  return { action: "continue" };
40
87
  }
@@ -66,9 +113,9 @@ async function handleSonarRetryLimit({ config, logger, emitter, eventBase, sessi
66
113
  }
67
114
  if (solomonResult.action === "continue") {
68
115
  if (solomonResult.humanGuidance) {
69
- session.last_reviewer_feedback += `\nUser guidance: ${solomonResult.humanGuidance}`;
116
+ setReviewerFeedback(session, `${session.last_reviewer_feedback}\nUser guidance: ${solomonResult.humanGuidance}`);
70
117
  }
71
- session.sonar_retry_count = 0;
118
+ resetRetryCount(session, "sonar");
72
119
  await saveSession(session);
73
120
  return { action: "continue" };
74
121
  }
@@ -89,7 +136,7 @@ async function handleSonarBlocking({ sonarResult, config, logger, emitter, event
89
136
  status: "warn",
90
137
  message: "Quality gate: coverage below threshold (advisory — code quality is clean)"
91
138
  }));
92
- session.last_reviewer_feedback = null;
139
+ setReviewerFeedback(session, null);
93
140
  return { action: "ok", stageResult: { gateStatus: "WARN_COVERAGE", advisory: true } };
94
141
  }
95
142
  }
@@ -101,13 +148,13 @@ async function handleSonarBlocking({ sonarResult, config, logger, emitter, event
101
148
  }
102
149
 
103
150
  const summary = `Sonar gate blocking (${sonarResult.gateStatus}). Resolve critical findings first.`;
104
- session.last_reviewer_feedback = summary;
151
+ setReviewerFeedback(session, summary);
105
152
  // Brain: push sonar feedback into queue when enabled
106
153
  if (brainCtx?.enabled) {
107
154
  const { processRoleOutput } = await import("../brain-coordinator.js");
108
155
  processRoleOutput(brainCtx, { roleName: "sonar", output: { verdict: "fail", summary }, iteration });
109
156
  }
110
- session.sonar_retry_count = (session.sonar_retry_count || 0) + 1;
157
+ incrementRetryCount(session, "sonar");
111
158
  await saveSession(session);
112
159
  const maxSonarRetries = config.session.max_sonar_retries ?? config.session.fail_fast_repeats;
113
160
 
@@ -120,6 +167,20 @@ async function handleSonarBlocking({ sonarResult, config, logger, emitter, event
120
167
  }
121
168
 
122
169
  export async function runSonarStage({ config, logger, emitter, eventBase, session, trackBudget, iteration, repeatDetector, budgetSummary, sonarState, askQuestion, task, brainCtx }) {
170
+ // Required-input guards. Without these, the bug class that broke the
171
+ // FASE-2 run on 2026-04-29 (run-hu-batch.js called runSonarStage
172
+ // without sonarState) is silent: the stage threw `Cannot read
173
+ // properties of undefined (reading 'issuesInitial')` later, the HU
174
+ // sub-pipeline's catch swallowed it as "non-blocking", and the
175
+ // Sonar gate effectively never ran. Failing fast here surfaces the
176
+ // missing wiring at the first iteration so any new caller fixes it
177
+ // before burning budget.
178
+ if (!sonarState || typeof sonarState !== "object") {
179
+ throw new Error("runSonarStage: `sonarState` is required (object with issuesInitial/issuesFinal slots — usually ctx.sonarState).");
180
+ }
181
+ if (!session) {
182
+ throw new Error("runSonarStage: `session` is required.");
183
+ }
123
184
  logger.setContext({ iteration, stage: "sonar" });
124
185
  emitProgress(
125
186
  emitter,
@@ -188,8 +249,31 @@ export async function runSonarStage({ config, logger, emitter, eventBase, sessio
188
249
  })
189
250
  );
190
251
 
191
- // Brain: when enabled, skip Solomon for sonar errors — Brain handles via max_iterations
252
+ // Brain: when enabled, skip Solomon for sonar errors — Brain handles via max_iterations.
192
253
  if (brainCtx?.enabled) {
254
+ // BUT: if the error is a *configuration* mistake (sonar.tests pointing to a
255
+ // missing folder, etc.), iterating won't help — Sonar will refuse to scan
256
+ // again and again. Push a typed feedback entry into the brain queue so the
257
+ // next coder iteration sees a concrete fix-this-config diagnostic AND so
258
+ // handleMaxIterations doesn't auto-finalize as approved (config is a
259
+ // "correctness" category — pending entries block approval).
260
+ const configHint = detectSonarConfigError(sonarResult.error);
261
+ if (configHint) {
262
+ addEntries(brainCtx.feedbackQueue, [{
263
+ source: "sonar",
264
+ severity: "high",
265
+ category: "correctness",
266
+ description: configHint,
267
+ iteration
268
+ }]);
269
+ setReviewerFeedback(session, configHint);
270
+ logger.info("Brain: sonar config error detected — feeding fix-this-config diagnostic to coder");
271
+ emitProgress(emitter, makeEvent("brain:sonar-config-error", { ...eventBase, stage: "sonar" }, {
272
+ message: "Sonar refused to scan — config error fed back to coder",
273
+ detail: { hint: configHint.slice(0, 240) }
274
+ }));
275
+ return { action: "continue" };
276
+ }
193
277
  logger.info("Brain: sonar error — Brain will handle (Solomon bypassed)");
194
278
  emitProgress(emitter, makeEvent("brain:sonar-error", { ...eventBase, stage: "sonar" }, {
195
279
  message: `Sonar error — Brain handling: ${errorMessage.slice(0, 200)}`,
@@ -224,7 +308,7 @@ export async function runSonarStage({ config, logger, emitter, eventBase, sessio
224
308
  throw new Error(errorMessage);
225
309
  }
226
310
 
227
- session.last_sonar_summary = sonarOutput.summary;
311
+ setSonarSummary(session, sonarOutput.summary);
228
312
  if (typeof sonarResult.openIssuesTotal === "number") {
229
313
  if (sonarState.issuesInitial === null) {
230
314
  sonarState.issuesInitial = sonarResult.openIssuesTotal;
@@ -255,7 +339,7 @@ export async function runSonarStage({ config, logger, emitter, eventBase, sessio
255
339
  }
256
340
 
257
341
  // Sonar passed — reset retry counter
258
- session.sonar_retry_count = 0;
342
+ resetRetryCount(session, "sonar");
259
343
  const issuesInitial = sonarState.issuesInitial ?? sonarResult.openIssuesTotal ?? 0;
260
344
  const issuesFinal = sonarState.issuesFinal ?? sonarResult.openIssuesTotal ?? 0;
261
345
  const stageResult = {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * StageExecutor class wrappers for the first 3 pipeline stages adopted
3
+ * under KJC-TSK-0328 (triage, coder, reviewer).
4
+ *
5
+ * Why these 3:
6
+ * - Triage is the first stage a pipeline runs — proves the registry is
7
+ * consulted before any execution.
8
+ * - Coder runs inside the iteration loop — proves the contract works
9
+ * for stages that run N times per pipeline.
10
+ * - Reviewer has the most complex signature (fetchReviewDiff + handle
11
+ * rejection + Solomon escalation path) — proves the contract does not
12
+ * artificially limit stage complexity.
13
+ *
14
+ * Contract: each class extends StageExecutor and delegates `execute(ctx)`
15
+ * to the existing `run{Stage}Stage` function. This keeps back-compat:
16
+ * flow-runner can still call the function directly during the transition,
17
+ * while the registry path is available for future iterations (and for
18
+ * anyone writing a new stage).
19
+ *
20
+ * A shared `stageRegistry` singleton is exported with the 3 stages
21
+ * pre-registered so callers do `stageRegistry.get("coder")` without
22
+ * rebuilding the registry.
23
+ *
24
+ * Future Oleada 3 will finish the migration by having flow-runner ONLY
25
+ * use the registry path, deleting the direct function imports.
26
+ */
27
+
28
+ import { StageExecutor, StageRegistry } from "./stage-executor.js";
29
+
30
+ // TSK-0336: stage subclasses use DYNAMIC imports inside execute() so that
31
+ // loading this module does not pull in the whole roles/ + agents/ graph.
32
+ // Orchestrator tests mock role/agent modules partially — eagerly importing
33
+ // triage-stage / coder-stage / reviewer-stage here would cascade through
34
+ // agent-role.js → BaseRole and crash those partial mocks. Deferring the
35
+ // import keeps canRun/construction cheap and the test surface unchanged.
36
+ export class TriageStage extends StageExecutor {
37
+ constructor() { super("triage"); }
38
+ canRun(ctx) {
39
+ // Triage runs when the triage pipeline flag is on (default: true for
40
+ // kj_run; tests may flip it off via config.pipeline.triage.enabled).
41
+ return ctx?.pipelineFlags?.triageEnabled !== false;
42
+ }
43
+ async execute(ctx) {
44
+ // Import via the pre-loop-stages barrel so test mocks that target
45
+ // `src/orchestrator/pre-loop-stages.js` (the historical surface) still
46
+ // apply when a stage is invoked via the registry.
47
+ const { runTriageStage } = await import("../pre-loop-stages.js");
48
+ return runTriageStage(ctx);
49
+ }
50
+ }
51
+
52
+ export class CoderStage extends StageExecutor {
53
+ constructor() { super("coder"); }
54
+ canRun(ctx) {
55
+ // Coder always runs unless the analysis-only path disables it.
56
+ return ctx?.pipelineFlags?.coderRequired !== false;
57
+ }
58
+ async execute(ctx) {
59
+ // Import via iteration-stages barrel for the same reason as TriageStage —
60
+ // preserve the existing mock surface used by orchestrator unit tests.
61
+ const { runCoderStage } = await import("../iteration-stages.js");
62
+ return runCoderStage(ctx);
63
+ }
64
+ }
65
+
66
+ export class ReviewerStage extends StageExecutor {
67
+ constructor() { super("reviewer"); }
68
+ canRun(ctx) {
69
+ return ctx?.pipelineFlags?.reviewerEnabled !== false;
70
+ }
71
+ async execute(ctx) {
72
+ const { runReviewerStage } = await import("../iteration-stages.js");
73
+ return runReviewerStage(ctx);
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Shared registry singleton with the 3 pre-registered stages. New stages
79
+ * should be added here as they migrate to the StageExecutor contract.
80
+ */
81
+ export const stageRegistry = new StageRegistry();
82
+ stageRegistry.register(new TriageStage());
83
+ stageRegistry.register(new CoderStage());
84
+ stageRegistry.register(new ReviewerStage());
85
+
86
+ export { StageExecutor, StageRegistry };
@@ -71,7 +71,7 @@ export class StageExecutor {
71
71
  * @param {StageContext} _ctx
72
72
  * @returns {Promise<StageOutcome | void>}
73
73
  */
74
- // eslint-disable-next-line no-unused-vars
74
+
75
75
  async onFailure(err, _ctx) {
76
76
  throw err;
77
77
  }
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { TriageRole } from "../../roles/triage-role.js";
7
- import { addCheckpoint } from "../../session-store.js";
7
+ import { addCheckpoint } from "../../session/store.js";
8
8
  import { emitProgress, makeEvent, emitAgentOutput } from "../../utils/events.js";
9
9
  import { selectModelsForRoles } from "../../utils/model-selector.js";
10
10
  import { createStallDetector } from "../../utils/stall-detector.js";
@@ -1,4 +1,5 @@
1
1
  import { emitProgress, makeEvent } from "../utils/events.js";
2
+ import { setStatus } from "../session/mutators.js";
2
3
 
3
4
  const DEFAULT_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes
4
5
  const MAX_COOLDOWN_MS = 30 * 60 * 1000; // 30 minutes
@@ -37,7 +38,7 @@ export async function waitForCooldown({ cooldownMs, cooldownUntil, agent, retryC
37
38
  }));
38
39
 
39
40
  // Update session status
40
- session.status = "standby";
41
+ setStatus(session, "standby");
41
42
 
42
43
  // Wait with periodic heartbeats
43
44
  const startTime = Date.now();
@@ -64,7 +65,7 @@ export async function waitForCooldown({ cooldownMs, cooldownUntil, agent, retryC
64
65
  detail: { agent, retryCount: retryCount + 1 }
65
66
  }));
66
67
 
67
- session.status = "running";
68
+ setStatus(session, "running");
68
69
  }
69
70
 
70
71
  export { DEFAULT_COOLDOWN_MS, MAX_COOLDOWN_MS, MAX_STANDBY_RETRIES, HEARTBEAT_INTERVAL_MS };