karajan-code 4.70.4 → 5.0.1

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 (390) hide show
  1. package/README.md +2 -2
  2. package/package.json +6 -14
  3. package/packages/hu-board/package.json +1 -1
  4. package/packages/hu-board/public/app.js +4 -18
  5. package/packages/hu-board/public/index.html +5 -2
  6. package/packages/hu-board/public/styles.css +26 -0
  7. package/packages/hu-board/public/utils/api.js +0 -74
  8. package/packages/hu-board/public/utils/board-tour.js +62 -0
  9. package/packages/hu-board/public/utils/board-view.js +49 -144
  10. package/packages/hu-board/public/utils/command-launcher.js +8 -70
  11. package/packages/hu-board/public/utils/formatters.js +10 -0
  12. package/packages/hu-board/public/utils/governance-view.js +13 -1
  13. package/packages/hu-board/public/utils/hu-actions.js +17 -68
  14. package/packages/hu-board/public/utils/init-listeners.js +7 -8
  15. package/packages/hu-board/public/utils/log-panel.js +3 -16
  16. package/packages/hu-board/public/utils/maggle-mode.js +2 -12
  17. package/packages/hu-board/public/utils/modals.js +7 -0
  18. package/packages/hu-board/public/utils/project-picker-view.js +1 -1
  19. package/packages/hu-board/public/utils/server-push.js +3 -22
  20. package/packages/hu-board/public/utils/shared-board-notice.js +33 -0
  21. package/packages/hu-board/public/utils/story-detail-view.js +5 -19
  22. package/packages/hu-board/src/cleanup-zombies.js +0 -1
  23. package/packages/hu-board/src/command-runner.js +36 -25
  24. package/packages/hu-board/src/db-connection.js +282 -0
  25. package/packages/hu-board/src/db-paths.js +113 -0
  26. package/packages/hu-board/src/db-queries.js +188 -0
  27. package/packages/hu-board/src/db-tombstones.js +51 -0
  28. package/packages/hu-board/src/db.js +28 -619
  29. package/packages/hu-board/src/ephemeral-cleaner.js +2 -3
  30. package/packages/hu-board/src/hu-zombie-reaper.js +5 -1
  31. package/packages/hu-board/src/plan-mutations.js +3 -153
  32. package/packages/hu-board/src/plans-service.js +55 -0
  33. package/packages/hu-board/src/routes/api/commands.js +122 -0
  34. package/packages/hu-board/src/routes/api/plans.js +55 -0
  35. package/packages/hu-board/src/routes/api/projects.js +267 -0
  36. package/packages/hu-board/src/routes/api/prompts.js +135 -0
  37. package/packages/hu-board/src/routes/api/sessions.js +95 -0
  38. package/packages/hu-board/src/routes/api/stories.js +183 -0
  39. package/packages/hu-board/src/routes/api/system.js +241 -0
  40. package/packages/hu-board/src/routes/api/tombstones.js +38 -0
  41. package/packages/hu-board/src/routes/api.js +24 -1371
  42. package/packages/hu-board/src/routes/governance.js +23 -1
  43. package/packages/hu-board/src/routes/lanes.js +40 -0
  44. package/packages/hu-board/src/routes/rag.js +4 -3
  45. package/packages/hu-board/src/server.js +20 -34
  46. package/packages/hu-board/src/sync-files.js +318 -0
  47. package/packages/hu-board/src/sync-project.js +99 -0
  48. package/packages/hu-board/src/sync.js +22 -566
  49. package/packages/hu-board/src/zombie-reaper.js +1 -1
  50. package/scripts/dual-publish.mjs +19 -3
  51. package/scripts/postinstall.js +15 -2
  52. package/scripts/verify-pack-mcp.mjs +11 -7
  53. package/scripts/verify-pack.mjs +4 -4
  54. package/src/audit/audit-history.js +3 -2
  55. package/src/audit/dead-exports.js +68 -59
  56. package/src/audit/deterministic-summary.js +33 -13
  57. package/src/audit/npm-signatures.js +41 -0
  58. package/src/audit/sbom.js +35 -0
  59. package/src/checks/agent-token.js +112 -0
  60. package/src/checks/dir-setup.js +34 -1
  61. package/src/checks/native-build.js +21 -39
  62. package/src/checks/runner.js +128 -142
  63. package/src/cli/advanced-commands.js +6 -6
  64. package/src/cli/register-meta.js +42 -82
  65. package/src/cli/register-pipeline.js +8 -143
  66. package/src/cli/register-plan.js +9 -100
  67. package/src/cli/register-roles-skills.js +1 -1
  68. package/src/cli/retired-commands.js +49 -0
  69. package/src/cli.js +18 -5
  70. package/src/commands/agent-run.js +40 -26
  71. package/src/commands/audit.js +127 -124
  72. package/src/commands/board.js +5 -9
  73. package/src/commands/check.js +29 -16
  74. package/src/commands/doctor.js +2 -0
  75. package/src/commands/env.js +176 -150
  76. package/src/commands/go.js +71 -53
  77. package/src/commands/harden.js +90 -81
  78. package/src/commands/hu-start.js +52 -0
  79. package/src/commands/hu.js +288 -221
  80. package/src/commands/identity.js +111 -78
  81. package/src/commands/init-atril.js +47 -0
  82. package/src/commands/init.js +11 -40
  83. package/src/commands/install-tools.js +70 -85
  84. package/src/commands/main-guard.js +78 -0
  85. package/src/commands/policy.js +226 -184
  86. package/src/commands/qmd.js +27 -21
  87. package/src/commands/rag.js +121 -55
  88. package/src/commands/review-gate.js +421 -341
  89. package/src/commands/skills.js +4 -1
  90. package/src/commands/start.js +4 -5
  91. package/src/commands/steward.js +96 -47
  92. package/src/commands/tournament.js +46 -37
  93. package/src/commands/worktree.js +107 -26
  94. package/src/config/defaults.js +1 -0
  95. package/src/config/loader.js +34 -17
  96. package/src/config/role-resolver.js +1 -0
  97. package/src/config/schema.js +1 -0
  98. package/src/config/secrets.js +36 -0
  99. package/src/config.js +1 -0
  100. package/src/environment/adr.js +16 -2
  101. package/src/git/karajan-label.js +20 -8
  102. package/src/guards/main-guard.js +54 -0
  103. package/src/harden/hook-templates.js +16 -1
  104. package/src/harden/sentinel/posttooluse.mjs +18 -6
  105. package/src/harden/sentinel/pretooluse-sentinel.mjs +64 -36
  106. package/src/harden/sentinel/sentinel-lib.mjs +129 -26
  107. package/src/harden/sentinel/sentinel-shell.mjs +5 -16
  108. package/src/harden/sentinel/sessionstart.mjs +3 -2
  109. package/src/harden/sentinel/stop.mjs +5 -4
  110. package/src/harden/workflow-templates.js +1 -1
  111. package/src/hu/board-lookup.js +29 -0
  112. package/src/hu/gh-identity.js +23 -0
  113. package/src/hu/github-board.js +4 -2
  114. package/src/hu/lane-prune.js +83 -13
  115. package/src/hu/lane-setup.js +65 -0
  116. package/src/hu/lanes.js +66 -0
  117. package/src/hu/team-board-mirror.js +3 -2
  118. package/src/infrastructure/command-runner.js +1 -1
  119. package/src/infrastructure/file-system-service.js +1 -1
  120. package/src/mcp/handlers/direct-handlers.js +2 -292
  121. package/src/mcp/handlers/hu-handlers.js +1 -35
  122. package/src/mcp/handlers/management-handlers.js +2 -42
  123. package/src/mcp/handlers/rag-handler.js +9 -1
  124. package/src/mcp/server-handlers.js +16 -22
  125. package/src/mcp/tools.js +1 -196
  126. package/src/plan/lane-plans.js +54 -0
  127. package/src/plan/plan-store.js +7 -4
  128. package/src/policy/add.js +26 -12
  129. package/src/policy/adr-number-check.js +31 -0
  130. package/src/prompts/audit.js +299 -339
  131. package/src/prompts/card-context.js +10 -5
  132. package/src/prompts/reviewer.js +5 -2
  133. package/src/rag/auto-update.js +71 -44
  134. package/src/rag/bootstrap-index.js +46 -54
  135. package/src/rag/indexer.js +9 -4
  136. package/src/rag/migrate.js +1 -1
  137. package/src/rag/onnx-fallback.js +2 -2
  138. package/src/rag/pid-lease.js +181 -0
  139. package/src/rag/project-store.js +2 -12
  140. package/src/review/card-first.js +57 -46
  141. package/src/review/gate-gitignore.js +23 -4
  142. package/src/review/gate-hook.js +12 -4
  143. package/src/review/one-shot-review.js +45 -35
  144. package/src/review/publish-pr.js +14 -2
  145. package/src/review/repo-docs.js +73 -0
  146. package/src/review/repo-stack.js +59 -0
  147. package/src/review/reviewer-fallback.js +19 -4
  148. package/src/review/seal-commit.js +29 -0
  149. package/src/review/sonar-pregate.js +59 -44
  150. package/src/review/third-party-review.js +90 -16
  151. package/src/review/third-party-size.js +43 -0
  152. package/src/review/third-party-skills.js +54 -0
  153. package/src/review/verify-pr.js +1 -24
  154. package/src/roles/audit-role.js +106 -125
  155. package/src/skills/atril-cli.js +19 -1
  156. package/src/skills/atril-skills.js +5 -4
  157. package/src/skills/skills-search.js +72 -0
  158. package/src/skills/translate.js +62 -0
  159. package/src/sonar/scanner.js +116 -101
  160. package/src/steward/invariants.js +5 -4
  161. package/src/steward/phantom-sweep.js +66 -0
  162. package/src/tournament/judge.js +60 -53
  163. package/src/utils/gh-account.js +37 -0
  164. package/src/utils/git.js +0 -13
  165. package/src/utils/home-migration.js +7 -1
  166. package/src/utils/main-checkout.js +53 -0
  167. package/src/utils/qmd-collection.js +3 -1
  168. package/src/utils/welcome.js +3 -3
  169. package/templates/{skills → atril/commands}/kj-architect.md +5 -0
  170. package/templates/{skills → atril/commands}/kj-audit.md +5 -0
  171. package/templates/{skills → atril/commands}/kj-board.md +5 -0
  172. package/templates/{skills → atril/commands}/kj-code.md +5 -0
  173. package/templates/{skills → atril/commands}/kj-csv-transform.md +5 -0
  174. package/templates/{skills → atril/commands}/kj-data-report.md +5 -0
  175. package/templates/{skills → atril/commands}/kj-discover.md +5 -0
  176. package/templates/{skills → atril/commands}/kj-rag-query.md +5 -0
  177. package/templates/{skills → atril/commands}/kj-review.md +5 -0
  178. package/templates/{skills → atril/commands}/kj-security.md +5 -0
  179. package/templates/{skills → atril/commands}/kj-sonar.md +5 -0
  180. package/templates/{skills → atril/commands}/kj-sql-analysis.md +5 -0
  181. package/templates/{skills → atril/commands}/kj-test.md +5 -0
  182. package/packages/hu-board/public/utils/run-launcher.js +0 -169
  183. package/packages/hu-board/src/run-tracker.js +0 -121
  184. package/src/activity-log.js +0 -59
  185. package/src/agents/host-agent.js +0 -38
  186. package/src/agents/model-registry.js +0 -142
  187. package/src/audit/plan-adherence.js +0 -224
  188. package/src/autonomy/arbiter-role.js +0 -71
  189. package/src/autonomy/arbiter.js +0 -22
  190. package/src/autonomy/decider.js +0 -18
  191. package/src/autonomy/decision-resolver.js +0 -58
  192. package/src/autonomy/outcome-report.js +0 -55
  193. package/src/autonomy/stage-ask.js +0 -30
  194. package/src/brain/decision-tracker.js +0 -125
  195. package/src/brain/decisor.js +0 -243
  196. package/src/brain/solomon-consult.js +0 -171
  197. package/src/brain/standby-scheduler.js +0 -8
  198. package/src/budget/comparison.js +0 -96
  199. package/src/canvas/parse-md.js +0 -238
  200. package/src/canvas/schema.js +0 -101
  201. package/src/canvas/to-flat.js +0 -85
  202. package/src/canvas/validate.js +0 -163
  203. package/src/ci/dispatch.js +0 -99
  204. package/src/ci/index.js +0 -3
  205. package/src/ci/pr-diff.js +0 -26
  206. package/src/cli/register-standby.js +0 -26
  207. package/src/commands/architect.js +0 -111
  208. package/src/commands/autorun.js +0 -49
  209. package/src/commands/researcher.js +0 -54
  210. package/src/commands/resume.js +0 -72
  211. package/src/commands/review.js +0 -89
  212. package/src/commands/run.js +0 -185
  213. package/src/commands/standby.js +0 -117
  214. package/src/commands/status.js +0 -36
  215. package/src/commands/triage.js +0 -78
  216. package/src/commands/undo.js +0 -62
  217. package/src/domains/domain-loader.js +0 -245
  218. package/src/domains/domain-registry.js +0 -140
  219. package/src/domains/domain-synthesizer.js +0 -129
  220. package/src/git/automation.js +0 -433
  221. package/src/git/coder-commit-guard.js +0 -40
  222. package/src/git/hu-automation.js +0 -243
  223. package/src/git/hu-snapshot.js +0 -10
  224. package/src/git/symlink-targets.js +0 -57
  225. package/src/golden/asserter.js +0 -92
  226. package/src/golden/loader.js +0 -52
  227. package/src/golden/runner.js +0 -92
  228. package/src/golden/schema.js +0 -41
  229. package/src/guards/duplicate-members.js +0 -86
  230. package/src/guards/intent-guard.js +0 -161
  231. package/src/guards/perf-guard.js +0 -126
  232. package/src/guards/policy-guard.js +0 -90
  233. package/src/guards/policy-resolver.js +0 -85
  234. package/src/guards/secret-redactor.js +0 -71
  235. package/src/hu/acceptance-runner.js +0 -138
  236. package/src/hu/lazy-planner.js +0 -109
  237. package/src/hu/parallel-executor.js +0 -94
  238. package/src/hu/routing-metrics.js +0 -17
  239. package/src/hu/split-validator.js +0 -143
  240. package/src/hu/splitting-detector.js +0 -158
  241. package/src/hu/splitting-generator.js +0 -175
  242. package/src/hu/store.js +0 -394
  243. package/src/infrastructure/mocks.js +0 -182
  244. package/src/mcp/handlers/run-handler.js +0 -318
  245. package/src/mcp/sovereignty-guard.js +0 -113
  246. package/src/mcp/tool-arg-normalizers.js +0 -16
  247. package/src/mutate/reviewer-signal.js +0 -76
  248. package/src/orchestrator/agent-fallback.js +0 -81
  249. package/src/orchestrator/brain-coordinator.js +0 -186
  250. package/src/orchestrator/ci-integration.js +0 -139
  251. package/src/orchestrator/config-init.js +0 -426
  252. package/src/orchestrator/direct-actions.js +0 -217
  253. package/src/orchestrator/drivers/error-recovery.js +0 -287
  254. package/src/orchestrator/drivers/init-context.js +0 -238
  255. package/src/orchestrator/drivers/iteration-loop.js +0 -382
  256. package/src/orchestrator/drivers/iteration-phases/coder-and-refactorer.js +0 -69
  257. package/src/orchestrator/drivers/iteration-phases/guards.js +0 -91
  258. package/src/orchestrator/drivers/iteration-phases/handle-approved.js +0 -29
  259. package/src/orchestrator/drivers/iteration-phases/quality-gates.js +0 -125
  260. package/src/orchestrator/drivers/iteration-phases/reviewer-gate.js +0 -62
  261. package/src/orchestrator/drivers/post-loop.js +0 -404
  262. package/src/orchestrator/drivers/pre-loop-phases/auto-hu-batch.js +0 -137
  263. package/src/orchestrator/drivers/pre-loop-phases/config-deprecations.js +0 -47
  264. package/src/orchestrator/drivers/pre-loop-phases/ensure-addyosmani-skills.js +0 -84
  265. package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +0 -393
  266. package/src/orchestrator/drivers/pre-loop.js +0 -524
  267. package/src/orchestrator/drivers/run-hu-batch.js +0 -468
  268. package/src/orchestrator/feedback-enrichment.js +0 -140
  269. package/src/orchestrator/feedback-queue.js +0 -151
  270. package/src/orchestrator/flow-control.js +0 -170
  271. package/src/orchestrator/flow-runner.js +0 -365
  272. package/src/orchestrator/fs-leak-detector.js +0 -228
  273. package/src/orchestrator/hu-scheduler.js +0 -114
  274. package/src/orchestrator/hu-sub-pipeline.js +0 -642
  275. package/src/orchestrator/iteration-gate.js +0 -73
  276. package/src/orchestrator/iteration-stages.js +0 -9
  277. package/src/orchestrator/parallel-limiter.js +0 -74
  278. package/src/orchestrator/pipeline-context.js +0 -72
  279. package/src/orchestrator/post-loop-stages.js +0 -468
  280. package/src/orchestrator/pre-loop-stages.js +0 -11
  281. package/src/orchestrator/preflight-checks.js +0 -487
  282. package/src/orchestrator/repair/repair-detector.js +0 -117
  283. package/src/orchestrator/repair/repair-runner.js +0 -142
  284. package/src/orchestrator/reviewer-fallback.js +0 -45
  285. package/src/orchestrator/role-output-compressor.js +0 -189
  286. package/src/orchestrator/session-journal.js +0 -308
  287. package/src/orchestrator/solomon-escalation.js +0 -331
  288. package/src/orchestrator/solomon-rules.js +0 -212
  289. package/src/orchestrator/stages/acceptance-coverage-stage.js +0 -47
  290. package/src/orchestrator/stages/architect-stage.js +0 -172
  291. package/src/orchestrator/stages/coder-stage.js +0 -506
  292. package/src/orchestrator/stages/domain-curator-stage.js +0 -82
  293. package/src/orchestrator/stages/format-stage.js +0 -61
  294. package/src/orchestrator/stages/hu-reviewer-phases/detect-and-apply-splits.js +0 -127
  295. package/src/orchestrator/stages/hu-reviewer-stage.js +0 -419
  296. package/src/orchestrator/stages/perf-stage.js +0 -140
  297. package/src/orchestrator/stages/planner-stage.js +0 -85
  298. package/src/orchestrator/stages/rag-context-stage.js +0 -80
  299. package/src/orchestrator/stages/rag-preload-decisor.js +0 -58
  300. package/src/orchestrator/stages/research-stage.js +0 -69
  301. package/src/orchestrator/stages/reviewer-stage.js +0 -431
  302. package/src/orchestrator/stages/sonar-stage.js +0 -439
  303. package/src/orchestrator/stages/stage-classes.js +0 -84
  304. package/src/orchestrator/stages/stage-executor.js +0 -155
  305. package/src/orchestrator/stages/suite-green-stage.js +0 -62
  306. package/src/orchestrator/stages/tdd-discipline-stage.js +0 -56
  307. package/src/orchestrator/stages/tool-judge-stage.js +0 -53
  308. package/src/orchestrator/stages/triage-stage.js +0 -172
  309. package/src/orchestrator/standby.js +0 -71
  310. package/src/orchestrator/verification-gate.js +0 -183
  311. package/src/orchestrator.js +0 -22
  312. package/src/plan/adr-generator.js +0 -170
  313. package/src/plan/adr-loader.js +0 -60
  314. package/src/plan/plan-executor.js +0 -100
  315. package/src/plan/plan-validation.js +0 -4
  316. package/src/prompts/acceptance-coverage.js +0 -32
  317. package/src/prompts/arbiter.js +0 -38
  318. package/src/prompts/architect.js +0 -103
  319. package/src/prompts/hu-reviewer.js +0 -244
  320. package/src/prompts/tool-correctness-judge.js +0 -31
  321. package/src/prompts/triage.js +0 -57
  322. package/src/rag/embedder.js +0 -2
  323. package/src/rag/embedders/_cloud-base.js +0 -2
  324. package/src/rag/embedders/cohere.js +0 -2
  325. package/src/rag/embedders/mistral.js +0 -2
  326. package/src/rag/embedders/onnx.js +0 -2
  327. package/src/rag/embedders/openai.js +0 -2
  328. package/src/rag/embedders/voyage.js +0 -2
  329. package/src/rag/rerank.js +0 -4
  330. package/src/rag/where-parser.js +0 -4
  331. package/src/repeat-detector.js +0 -88
  332. package/src/review/diff-generator.js +0 -112
  333. package/src/review/git-stash-helper.js +0 -104
  334. package/src/review/schema.js +0 -31
  335. package/src/review/scope-filter.js +0 -152
  336. package/src/review/snapshot-diff.js +0 -122
  337. package/src/review/tdd-discipline.js +0 -90
  338. package/src/review/tdd-policy.js +0 -69
  339. package/src/roles/acceptance-coverage-role.js +0 -78
  340. package/src/roles/architect-role.js +0 -77
  341. package/src/roles/coder-role.js +0 -113
  342. package/src/roles/commiter-role.js +0 -113
  343. package/src/roles/domain-curator-role.js +0 -134
  344. package/src/roles/hu-reviewer-role.js +0 -64
  345. package/src/roles/impeccable-role.js +0 -85
  346. package/src/roles/index.js +0 -18
  347. package/src/roles/karajan-brain-role.js +0 -134
  348. package/src/roles/perf-role.js +0 -122
  349. package/src/roles/planner-role.js +0 -151
  350. package/src/roles/refactorer-role.js +0 -30
  351. package/src/roles/repairer-role.js +0 -181
  352. package/src/roles/researcher-role.js +0 -70
  353. package/src/roles/reviewer-role.js +0 -115
  354. package/src/roles/security-role.js +0 -73
  355. package/src/roles/solomon-role.js +0 -271
  356. package/src/roles/sonar-role.js +0 -72
  357. package/src/roles/tester-role.js +0 -235
  358. package/src/roles/tool-correctness-judge-role.js +0 -78
  359. package/src/roles/triage-role.js +0 -99
  360. package/src/session/journal/decisions-writer.js +0 -200
  361. package/src/session/journal/iteration-logger.js +0 -194
  362. package/src/session/journal/summary-writer.js +0 -320
  363. package/src/session/journal/tree-writer.js +0 -164
  364. package/src/session/journal/write-all.js +0 -89
  365. package/src/session-cleanup.js +0 -116
  366. package/src/skills/semantic-detector.js +0 -167
  367. package/src/skills/skill-detector.js +0 -385
  368. package/src/sonar/cloud-scanner.js +0 -78
  369. package/src/tracker-bootstrap.js +0 -44
  370. package/src/types/index.js +0 -38
  371. package/src/types/policy.js +0 -43
  372. package/src/types/solomon.js +0 -87
  373. package/src/utils/async-lock.js +0 -31
  374. package/src/utils/budget.js +0 -229
  375. package/src/utils/cwd-confirm.js +0 -39
  376. package/src/utils/display/event-handlers.js +0 -403
  377. package/src/utils/display/formatters.js +0 -132
  378. package/src/utils/display/header.js +0 -47
  379. package/src/utils/display/session-summary.js +0 -118
  380. package/src/utils/display/solomon.js +0 -42
  381. package/src/utils/pricing.js +0 -29
  382. package/src/utils/quota-simulator.js +0 -56
  383. package/src/utils/role-assigner.js +0 -137
  384. package/src/utils/rtk-wrapper.js +0 -87
  385. package/src/utils/run-registry.js +0 -9
  386. package/src/utils/status-dashboard.js +0 -254
  387. package/src/utils/tool-call-extractor.js +0 -56
  388. package/src/webperf/devtools-detect.js +0 -112
  389. package/src/webperf/webperf-role-integration.js +0 -66
  390. package/templates/skills/kj-run.md +0 -73
@@ -1,151 +0,0 @@
1
- // Structured feedback queue for inter-role communication.
2
- // Replaces the flat session.last_reviewer_feedback string with typed messages.
3
-
4
- /**
5
- * @typedef {Object} FeedbackEntry
6
- * @property {string} source - "reviewer" | "tester" | "security" | "sonar" | "audit" | "brain"
7
- * @property {string} severity - "critical" | "high" | "medium" | "low"
8
- * @property {string} category - "security" | "correctness" | "tests" | "style" | "performance" | "other"
9
- * @property {string} description
10
- * @property {string} [file]
11
- * @property {number} [line]
12
- * @property {string} [suggestedFix]
13
- * @property {string} [id]
14
- * @property {number} [iteration] - when this feedback was added
15
- */
16
-
17
- const SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
18
- const CATEGORY_ORDER = { security: 0, correctness: 1, tests: 2, performance: 3, style: 4, other: 5 };
19
-
20
- /**
21
- * Create a new empty feedback queue.
22
- */
23
- export function createQueue() {
24
- return { entries: [] };
25
- }
26
-
27
- /**
28
- * Add a feedback entry to the queue.
29
- */
30
- export function addEntry(queue, entry) {
31
- if (!entry || !entry.description) return queue;
32
- const normalized = {
33
- source: entry.source || "unknown",
34
- severity: entry.severity || "medium",
35
- category: entry.category || "other",
36
- description: entry.description,
37
- file: entry.file || null,
38
- line: entry.line || null,
39
- suggestedFix: entry.suggestedFix || null,
40
- id: entry.id || null,
41
- iteration: entry.iteration || 0
42
- };
43
- queue.entries.push(normalized);
44
- return queue;
45
- }
46
-
47
- /**
48
- * Add multiple entries at once.
49
- */
50
- export function addEntries(queue, entries) {
51
- for (const e of entries || []) addEntry(queue, e);
52
- return queue;
53
- }
54
-
55
- /**
56
- * Deduplicate entries with the same description + source (keep the most severe).
57
- */
58
- export function deduplicate(queue) {
59
- const seen = new Map();
60
- for (const e of queue.entries) {
61
- const key = `${e.source}::${e.description}`;
62
- const existing = seen.get(key);
63
- if (!existing || SEVERITY_ORDER[e.severity] < SEVERITY_ORDER[existing.severity]) {
64
- seen.set(key, e);
65
- }
66
- }
67
- queue.entries = [...seen.values()];
68
- return queue;
69
- }
70
-
71
- /**
72
- * Sort entries by priority: category first (security > correctness > ...), then severity.
73
- */
74
- export function prioritize(queue) {
75
- queue.entries.sort((a, b) => {
76
- const catDiff = (CATEGORY_ORDER[a.category] ?? 5) - (CATEGORY_ORDER[b.category] ?? 5);
77
- if (catDiff !== 0) return catDiff;
78
- return (SEVERITY_ORDER[a.severity] ?? 2) - (SEVERITY_ORDER[b.severity] ?? 2);
79
- });
80
- return queue;
81
- }
82
-
83
- /**
84
- * Format queue as a numbered list for the coder prompt.
85
- */
86
- export function formatForCoder(queue) {
87
- if (!queue.entries.length) return "";
88
-
89
- const lines = [];
90
- queue.entries.forEach((e, i) => {
91
- const loc = e.file ? ` (${e.file}${e.line ? `:${e.line}` : ""})` : "";
92
- const tag = `[${e.source}:${e.severity}:${e.category}]`;
93
- lines.push(`${i + 1}. ${tag}${loc} ${e.description}`);
94
- if (e.suggestedFix) lines.push(` Fix: ${e.suggestedFix}`);
95
- });
96
- return lines.join("\n");
97
- }
98
-
99
- /**
100
- * Filter entries by category.
101
- */
102
- export function filterByCategory(queue, category) {
103
- return { entries: queue.entries.filter(e => e.category === category) };
104
- }
105
-
106
- /**
107
- * Check if queue has any critical/high severity entries.
108
- */
109
- export function hasBlockingIssues(queue) {
110
- return queue.entries.some(e => e.severity === "critical" || e.severity === "high");
111
- }
112
-
113
- /**
114
- * Get count of entries by category.
115
- */
116
- export function countByCategory(queue) {
117
- const counts = {};
118
- for (const e of queue.entries) {
119
- counts[e.category] = (counts[e.category] || 0) + 1;
120
- }
121
- return counts;
122
- }
123
-
124
- /**
125
- * Clear the queue (after coder addresses the feedback).
126
- */
127
- export function clear(queue) {
128
- queue.entries = [];
129
- return queue;
130
- }
131
-
132
- /**
133
- * Serialize queue for persistence in session.
134
- */
135
- export function serialize(queue) {
136
- return JSON.stringify(queue);
137
- }
138
-
139
- /**
140
- * Deserialize queue from session.
141
- */
142
- export function deserialize(str) {
143
- if (!str) return createQueue();
144
- try {
145
- const parsed = JSON.parse(str);
146
- return { entries: Array.isArray(parsed.entries) ? parsed.entries : [] };
147
- } catch {
148
- return createQueue();
149
- }
150
- }
151
-
@@ -1,170 +0,0 @@
1
- /**
2
- * Session flow control — checkpoints, timeouts, budget checks.
3
- * Extracted from orchestrator.js — session management, not orchestration.
4
- */
5
- import { markSessionStatus, addCheckpoint } from "../session/store.js";
6
- import { setRetryCount } from "../session/mutators.js";
7
- import { emitProgress, makeEvent } from "../utils/events.js";
8
- import { msg, getLang } from "../utils/messages.js";
9
-
10
- function detectCheckpointProgress(session, lastCheckpointSnapshot) {
11
- if (!lastCheckpointSnapshot) return true; // First checkpoint — assume progress
12
- const currentIteration = session.reviewer_retry_count ?? 0;
13
- const currentStages = Object.keys(session.resolved_policies || {}).length;
14
- const currentCheckpoints = (session.checkpoints || []).length;
15
-
16
- const iterationAdvanced = currentIteration !== lastCheckpointSnapshot.iteration;
17
- const stagesChanged = currentStages !== lastCheckpointSnapshot.stagesCount;
18
- const checkpointsChanged = currentCheckpoints !== lastCheckpointSnapshot.checkpointsCount;
19
-
20
- return iterationAdvanced || stagesChanged || checkpointsChanged;
21
- }
22
-
23
- export function takeCheckpointSnapshot(session) {
24
- return {
25
- iteration: session.reviewer_retry_count ?? 0,
26
- stagesCount: Object.keys(session.resolved_policies || {}).length,
27
- checkpointsCount: (session.checkpoints || []).length
28
- };
29
- }
30
-
31
- /**
32
- * Determine if checkpoint should auto-continue without asking the user.
33
- * Exported for testing.
34
- */
35
- export function shouldAutoContinueCheckpoint(session, hasProgress) {
36
- if (hasProgress) {
37
- setRetryCount(session, "checkpoint_stall", 0);
38
- return { autoContinue: true, reason: "progress_detected" };
39
- }
40
- const wasRateLimited = (session.standby_retry_count || 0) > 0;
41
- const consecutiveStalls = (session._checkpoint_stall_count || 0) + 1;
42
- setRetryCount(session, "checkpoint_stall", consecutiveStalls);
43
- if (wasRateLimited && consecutiveStalls < 3) {
44
- return { autoContinue: true, reason: "recoverable_stall" };
45
- }
46
- return { autoContinue: false, reason: consecutiveStalls >= 3 ? "max_stalls_reached" : "no_progress" };
47
- }
48
-
49
- export async function handleCheckpoint({ checkpointDisabled, askQuestion, lastCheckpointAt, checkpointIntervalMs, elapsedMinutes, i, config, budgetTracker, stageResults, emitter, eventBase, session, budgetSummary, lastCheckpointSnapshot }) {
50
- if (checkpointDisabled || !askQuestion || (Date.now() - lastCheckpointAt) < checkpointIntervalMs) {
51
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt, lastCheckpointSnapshot };
52
- }
53
-
54
- const elapsedStr = elapsedMinutes.toFixed(1);
55
- const stagesCompleted = Object.keys(stageResults).join(", ") || "none";
56
-
57
- const hasProgress = detectCheckpointProgress(session, lastCheckpointSnapshot);
58
- const newSnapshot = takeCheckpointSnapshot(session);
59
- const decision = shouldAutoContinueCheckpoint(session, hasProgress);
60
-
61
- if (decision.autoContinue) {
62
- emitProgress(
63
- emitter,
64
- makeEvent("session:checkpoint", { ...eventBase, iteration: i, stage: "checkpoint" }, {
65
- message: `Checkpoint: ${decision.reason === "progress_detected" ? "progress detected" : "stall caused by rate limit/cooldown"}, auto-continuing (${elapsedStr} min elapsed)`,
66
- detail: { elapsed_minutes: Number(elapsedStr), iterations_done: i - 1, stages: stagesCompleted, auto_continued: true, reason: decision.reason }
67
- })
68
- );
69
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now(), lastCheckpointSnapshot: newSnapshot };
70
- }
71
-
72
- const iterInfo = `${i - 1}/${config.max_iterations} iterations completed`;
73
- const budgetInfo = budgetTracker.total().cost_usd > 0 ? ` | Budget: $${budgetTracker.total().cost_usd.toFixed(2)}` : "";
74
- const checkpointMsg = `Checkpoint — ${elapsedStr} min elapsed | ${iterInfo}${budgetInfo} | Stages completed: ${stagesCompleted}. No progress since last checkpoint. What would you like to do?`;
75
-
76
- emitProgress(
77
- emitter,
78
- makeEvent("session:checkpoint", { ...eventBase, iteration: i, stage: "checkpoint" }, {
79
- message: `Interactive checkpoint at ${elapsedStr} min (stalled)`,
80
- detail: { elapsed_minutes: Number(elapsedStr), iterations_done: i - 1, stages: stagesCompleted, auto_continued: false }
81
- })
82
- );
83
-
84
- const lang = getLang(config);
85
- const answer = await askQuestion(
86
- `${checkpointMsg}\n\n${msg("checkpoint_options", lang)}`
87
- );
88
-
89
- await addCheckpoint(session, { stage: "interactive-checkpoint", elapsed_minutes: Number(elapsedStr), answer });
90
-
91
- const trimmedAnswer = (answer || "").trim();
92
- const isExplicitStop = trimmedAnswer === "4" || trimmedAnswer.toLowerCase().startsWith("stop");
93
-
94
- if (isExplicitStop) {
95
- await markSessionStatus(session, "stopped");
96
- emitProgress(
97
- emitter,
98
- makeEvent("session:end", { ...eventBase, iteration: i, stage: "user-stop" }, {
99
- status: "stopped",
100
- message: "Session stopped by user at checkpoint",
101
- detail: { approved: false, reason: "user_stopped", elapsed_minutes: Number(elapsedStr), budget: budgetSummary() }
102
- })
103
- );
104
- return { action: "stop", result: { approved: false, sessionId: session.id, reason: "user_stopped", elapsed_minutes: Number(elapsedStr) } };
105
- }
106
-
107
- const parsed = parseCheckpointAnswer({ trimmedAnswer, checkpointDisabled, config });
108
- parsed.lastCheckpointSnapshot = newSnapshot;
109
- return parsed;
110
- }
111
-
112
- export function parseCheckpointAnswer({ trimmedAnswer, checkpointDisabled, config }) {
113
- if (!trimmedAnswer) {
114
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
115
- }
116
- if (trimmedAnswer === "2" || trimmedAnswer.toLowerCase().startsWith("continue until")) {
117
- return { action: "continue_loop", checkpointDisabled: true, lastCheckpointAt: Date.now() };
118
- }
119
- if (trimmedAnswer === "1" || trimmedAnswer.toLowerCase().includes("5 m")) {
120
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
121
- }
122
- const customMinutes = Number.parseInt(trimmedAnswer.replaceAll(/\D/g, ""), 10);
123
- if (customMinutes > 0) {
124
- config.session.checkpoint_interval_minutes = customMinutes;
125
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
126
- }
127
- return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
128
- }
129
-
130
- export async function checkSessionTimeout({ askQuestion, elapsedMinutes, config, session, emitter, eventBase, i, budgetSummary }) {
131
- // Enforce the wall-clock when no human is watching the checkpoint: either a
132
- // non-interactive run (no askQuestion) OR an autonomous one — where askQuestion
133
- // is the auto-continue wrapper (truthy) but nobody is there to stop a runaway.
134
- // Interactive runs keep skipping it (the human decides at the checkpoint).
135
- // KJC-TSK-0575 (AUTO-D): without this, autonomous runs had NO wall-clock cap.
136
- const unattended = !askQuestion || askQuestion.unattended === true;
137
- if (!unattended || elapsedMinutes <= config.session.max_total_minutes) return;
138
-
139
- await markSessionStatus(session, "failed");
140
- emitProgress(
141
- emitter,
142
- makeEvent("session:end", { ...eventBase, iteration: i, stage: "timeout" }, {
143
- status: "fail",
144
- message: "Session timed out",
145
- detail: { approved: false, reason: "timeout", budget: budgetSummary() }
146
- })
147
- );
148
- throw new Error("Session timed out");
149
- }
150
-
151
- export async function checkBudgetExceeded({ budgetTracker, config, session, emitter, eventBase, i, budgetLimit, budgetSummary }) {
152
- if (!budgetTracker.isOverBudget(config?.max_budget_usd)) return;
153
-
154
- await markSessionStatus(session, "failed");
155
- const totalCost = budgetTracker.total().cost_usd;
156
- const limit = Number(budgetLimit ?? config?.max_budget_usd);
157
- const message =
158
- `Budget exceeded: $${totalCost.toFixed(2)} > $${limit.toFixed(2)}. ` +
159
- `Continue consciously with \`kj resume ${session.id}\`, or raise the cap ` +
160
- `(max_budget_usd in .karajan/kj.config.yml; null removes it).`;
161
- emitProgress(
162
- emitter,
163
- makeEvent("session:end", { ...eventBase, iteration: i, stage: "budget" }, {
164
- status: "fail",
165
- message,
166
- detail: { approved: false, reason: "budget_exceeded", budget: budgetSummary(), max_budget_usd: budgetLimit }
167
- })
168
- );
169
- throw new Error(message);
170
- }
@@ -1,365 +0,0 @@
1
- // Post-TSK-0335 flow-runner.js is a thin orchestrator: runFlow + resumeFlow.
2
- // Heavy lifting lives under src/orchestrator/drivers/. Imports here reflect
3
- // only what the two top-level entry points still need directly:
4
- // • session/store.js — load/save/resume/checkpoint for resumeFlow
5
- // • utils/events.js — session:start / session:end / init_error events
6
- // • solomon-escalation.js — init-error fallback (pre-loop failures)
7
- // • hu-sub-pipeline.js — branch: if HU batch → sub-pipeline, else loop
8
- // • config-init.js — dry-run handling, pipeline flag resolution,
9
- // product-context loader
10
- // • config/test-harness.js — defensive testHarness resolution for callers
11
- // that bypass loadConfig (orchestrator tests)
12
- // • skills/skill-detector.js — cleanupAutoInstalledSkills on session end
13
- // • drivers/* — the extracted pipeline phases
14
- import {
15
- loadSession,
16
- markSessionStatus,
17
- resumeSessionWithAnswer,
18
- saveSession,
19
- } from "../session/store.js";
20
- // TSK-0337: session mutations go through the mutators module. Every
21
- // `session.x = y` outside src/session/ should route through one of these
22
- // so grepping the mutator name locates every writer in seconds. See
23
- // tests/architecture/session-write-boundary.test.js for the invariant.
24
- import {
25
- setStatus, setReviewerFeedback, resetAllRetryCounters,
26
- setSonarIssueSignature, setReviewerIssueSignature,
27
- setSonarRepeatCount, setReviewerRepeatCount,
28
- setBudget,
29
- } from "../session/mutators.js";
30
- import { emitProgress, makeEvent } from "../utils/events.js";
31
- import {
32
- resolvePipelineFlags, handleDryRun,
33
- } from "./config-init.js";
34
- import { resolveTestHarness } from "../config/test-harness.js";
35
- import { cleanupAutoInstalledSkills } from "../skills/skill-detector.js";
36
- import { withRunContext } from "../utils/run-context.js";
37
- import { ensureTrackerRegistered } from "../tracker-bootstrap.js";
38
-
39
- // Drivers extracted from this god-module in TSK-0335 (Oleada 3 of the v2.7.4
40
- // audit refactor). Each driver covers one phase of the pipeline; flow-runner
41
- // keeps only the top-level runFlow/resumeFlow orchestration.
42
- // • drivers/init-context.js — build the PipelineContext (pre-loop setup)
43
- // • drivers/iteration-loop.js — the coder→reviewer iteration body
44
- // • drivers/post-loop.js — writeHistoryRecord called from resumeFlow
45
- import { initFlowContext } from "./drivers/init-context.js";
46
- import { runIterationLoop } from "./drivers/iteration-loop.js";
47
- import { writeHistoryRecord } from "./drivers/post-loop.js";
48
- import { runHuBatch } from "./drivers/run-hu-batch.js";
49
- // Analysis-only path (taskType=audit/doc/infra) skips coder iterations
50
- // and runs security + audit directly. These three were called without
51
- // imports until ESLint surfaced it — same class of latent bug as the
52
- // `saveSession` ReferenceError that took the demo down on 2026-04-27.
53
- import { generateDiff } from "../review/diff-generator.js";
54
- import { runSecurityStage, runFinalAuditStage } from "./post-loop-stages.js";
55
-
56
- // Public re-exports (loadProductContext, shouldAutoContinueCheckpoint,
57
- // parseCheckpointAnswer) live in src/orchestrator.js (the barrel).
58
-
59
-
60
- // PG card "In Progress" logic moved to src/planning-game/pipeline-adapter.js → initPgAdapter()
61
-
62
-
63
- /**
64
- * Boundary guard: make sure the session's terminal status reflects what
65
- * actually happened, even if some inner exit path forgot to call
66
- * `markSessionStatus`. KJC-BUG-0037 (N1 dogfooding 2026-05-07): runs
67
- * that took the Brain "max_iterations approved" / "Solomon-after-error
68
- * approved" / "Brain solomon-approved" exits returned `{approved:true}`
69
- * upstream but left `session.status = "running"` on disk indefinitely.
70
- * `kj status` then showed "Pipeline RUNNING" forever and the HU Board
71
- * carried a perma-zombie.
72
- *
73
- * Maps the result shape to a terminal status:
74
- * approved → "approved"
75
- * paused → "paused"
76
- * cancelled → "cancelled"
77
- * hibernated → "hibernated"
78
- * anything else → "failed"
79
- *
80
- * Idempotent: only writes when the current status is still "running"
81
- * (or unset). If an inner path already sealed it correctly, this is a
82
- * no-op.
83
- *
84
- * Safe-by-default: never throws. A failure here must not block the
85
- * top-level result from being returned to the caller.
86
- *
87
- * @param {object} session
88
- * @param {object} [result]
89
- */
90
- export async function sealSessionStatusIfStillRunning(session, result) {
91
- try {
92
- if (!session) return;
93
- const current = session.status;
94
- if (current && current !== "running") return;
95
- let target = "failed";
96
- if (result?.approved === true) target = "approved";
97
- else if (result?.paused === true) target = "paused";
98
- else if (result?.cancelled === true) target = "cancelled";
99
- // A run hibernated on a provider quota cap is NOT a failure — it is
100
- // suspended and resumable via `kj standby resume`. Sealing it as
101
- // `failed` would let the HU-zombie reaper treat it as dead work.
102
- else if (result?.hibernated === true) target = "hibernated";
103
- await markSessionStatus(session, target);
104
- } catch { /* non-blocking */ }
105
- }
106
-
107
- export async function runFlow(opts) {
108
- // TSK-0338: isolate per-run state (git/diff runner, projectDir, snapshot)
109
- // inside an AsyncLocalStorage scope. Two concurrent `runFlow` invocations
110
- // (MCP multi-client) no longer contaminate each other's module state.
111
- // initFlowContext writes into this store (see drivers/init-context.js).
112
- return withRunContext({}, () => _runFlowInner(opts));
113
- }
114
-
115
- async function _runFlowInner({ task, config, logger, flags = {}, emitter = null, askQuestion = null, pgTaskId = null, pgProject = null, preexisting = null }) {
116
- // Defensive test-harness resolution for callers that bypass loadConfig()
117
- // (orchestrator unit tests that build raw config objects). Production
118
- // callers go through src/config/loader.js → loadConfig which already
119
- // runs resolveTestHarness() once. When config.testHarness is missing we
120
- // resolve it here using the same contract: explicit field → globalThis →
121
- // prod defaults. Idempotent — no-op when already present.
122
- if (config && !config.testHarness) {
123
- config.testHarness = resolveTestHarness(config.testHarness);
124
- }
125
-
126
- // TSK-0339: delegate tracker registration to the neutral bootstrap
127
- // module so `src/orchestrator/` never imports a tracker directly.
128
- // Idempotent — no-op if the adapter is already registered (which is the
129
- // steady state once the real `src/bootstrap.js::ensureBootstrap` has
130
- // run; orchestrator unit tests that skip bootstrap benefit from this
131
- // lazy fallback).
132
- await ensureTrackerRegistered(config);
133
-
134
- // Auto-GC: prune orphan plans and old finalised state so `~/.kj/` and
135
- // `~/.karajan/` don't accumulate forever. Silent unless something was
136
- // removed; stderr one-liner on cleanup. Skipped in test env.
137
- if (!process.env.VITEST && process.env.NODE_ENV !== "test") {
138
- try {
139
- const { runAutoGC, summarizeGC } = await import("../utils/garbage-collector.js");
140
- const gcResult = await runAutoGC();
141
- const summary = summarizeGC(gcResult);
142
- if (summary) process.stderr.write(`${summary}\n`);
143
- } catch (err) {
144
- logger?.warn?.(`Auto-GC failed (non-blocking): ${err.message}`);
145
- }
146
- }
147
-
148
- const pipelineFlags = resolvePipelineFlags(config);
149
-
150
- if (flags.dryRun) {
151
- return handleDryRun({ task, config, flags, emitter, pipelineFlags });
152
- }
153
-
154
- let ctx;
155
- try {
156
- ctx = await initFlowContext({ task, config, logger, emitter, askQuestion, pgTaskId, pgProject, flags, preexisting });
157
- } catch (initError) {
158
- // Pre-loop / preflight failures are CONFIG problems, not pipeline
159
- // disputes. Pre-v2.7.5 we escalated them to Solomon, which:
160
- // 1. Spent tokens on something an LLM can't actually fix (e.g.
161
- // "port 9000 occupied", "docker not installed", "node version
162
- // too old"). Solomon's job is to mediate between coder and
163
- // reviewer, not to rewrite the user's environment.
164
- // 2. Often failed to parse its own output ("Failed to parse
165
- // Solomon output: no JSON found") and then asked the user a
166
- // garbled multi-line "Conflict: init_error" prompt — useless
167
- // when the run was launched by the board's ▶ Run plan with
168
- // stdio=ignore, since there's nobody to answer it.
169
- //
170
- // New behaviour: print the error verbatim with the actionable fix
171
- // (the preflight check already attached one), emit init_error
172
- // through the event channel for tooling, and bail with a non-zero
173
- // exit. The user gets one clear message and a fix; nothing tries to
174
- // be cleverer than that.
175
- logger.error(`Initialization failed: ${initError.message}`);
176
- if (initError.fix) logger.error(` Fix: ${initError.fix}`);
177
- emitProgress(emitter, makeEvent("init:failed", {
178
- sessionId: "init-error", iteration: 0, stage: "init", startedAt: Date.now()
179
- }, {
180
- status: "fail",
181
- message: `Initialization failed: ${initError.message}`,
182
- detail: { error: initError.message, fix: initError.fix || null }
183
- }));
184
- throw initError;
185
- }
186
-
187
- try {
188
- // --- Analysis-only flow: skip coder/reviewer when coderRequired === false ---
189
- if (ctx.pipelineFlags.coderRequired === false) {
190
- logger.info("Analysis-only task — skipping coder/reviewer iteration loop");
191
- emitProgress(emitter, makeEvent("pipeline:analysis-only", { ...ctx.eventBase, stage: "analysis" }, {
192
- message: "Analysis-only task — running security and audit stages only",
193
- detail: { taskType: ctx.session.resolved_policies?.taskType, coderRequired: false }
194
- }));
195
-
196
- const analysisStageResults = ctx.stageResults;
197
- const postLoopDiff = await generateDiff({ baseRef: ctx.session.session_start_sha });
198
-
199
- if (ctx.pipelineFlags.securityEnabled) {
200
- const securityResult = await runSecurityStage({
201
- config: ctx.config, logger, emitter, eventBase: ctx.eventBase, session: ctx.session,
202
- coderRole: ctx.coderRole, trackBudget: ctx.trackBudget,
203
- iteration: 1, task: ctx.plannedTask, diff: postLoopDiff, askQuestion, brainCtx: ctx.brainCtx
204
- });
205
- if (securityResult.stageResult) analysisStageResults.security = securityResult.stageResult;
206
- }
207
-
208
- const auditResult = await runFinalAuditStage({
209
- config: ctx.config, logger, emitter, eventBase: ctx.eventBase, session: ctx.session,
210
- coderRole: ctx.coderRole, trackBudget: ctx.trackBudget,
211
- iteration: 1, task: ctx.plannedTask, diff: postLoopDiff
212
- });
213
- if (auditResult.stageResult) analysisStageResults.audit = auditResult.stageResult;
214
-
215
- setBudget(ctx.session, ctx.budgetSummary());
216
- await markSessionStatus(ctx.session, "approved");
217
-
218
- const analysisResult = {
219
- approved: true,
220
- sessionId: ctx.session.id,
221
- analysisOnly: true,
222
- stages: analysisStageResults,
223
- budget: ctx.budgetSummary()
224
- };
225
- await writeHistoryRecord({ sessionId: ctx.session.id, task, result: analysisResult, logger });
226
-
227
- emitProgress(emitter, makeEvent("session:end", { ...ctx.eventBase, stage: "done" }, {
228
- message: "Analysis-only session completed",
229
- detail: analysisResult
230
- }));
231
-
232
- return analysisResult;
233
- }
234
-
235
- // --- HU Sub-Pipeline: extracted to drivers/run-hu-batch.js (PR-L) ---
236
- // 244 LOC of needsSubPipeline check + per-HU iteration with
237
- // policies + acceptance-tests gate + Sonar + tester translation.
238
- const huBatch = await runHuBatch({ ctx, task, askQuestion, emitter, logger });
239
- if (huBatch.handled) {
240
- await sealSessionStatusIfStillRunning(ctx.session, huBatch.result);
241
- return huBatch.result;
242
- }
243
-
244
- // --- Standard single-task pipeline (1 HU or no HU reviewer) ---
245
- const result = await runIterationLoop(ctx, { task: ctx.plannedTask, askQuestion, emitter, logger });
246
- await writeHistoryRecord({ sessionId: ctx.session.id, task, result, logger });
247
- await sealSessionStatusIfStillRunning(ctx.session, result);
248
- return result;
249
- } finally {
250
- // --- Journal: best-effort write for non-approved endings (KJC-BUG-0084) ---
251
- // finalizeApprovedSession writes the journal on the happy path and sets
252
- // session._journalWritten. Every other terminal ending (sonar_repeat
253
- // stall, stage_error, thrown stage, budget exceeded) used to leave only
254
- // triage.md behind — losing the Cache hits table, budget breakdown and
255
- // commits exactly on the runs where the post-mortem matters most.
256
- // Paused sessions are skipped: they resume later and the eventual
257
- // finalize overwrites the journal with the real outcome.
258
- try {
259
- const s = ctx.session;
260
- if (s && s._journalDir && !s._journalWritten && s.status !== "paused") {
261
- const { writeSessionJournal } = await import("../session/journal/write-all.js");
262
- const badge = s.status && s.status !== "running" ? s.status.toUpperCase() : "FAILED";
263
- await writeSessionJournal({
264
- session: s, logger,
265
- result: badge,
266
- iterations: s._journalIterations?.length || 0,
267
- budget: typeof ctx.budgetSummary === "function" ? ctx.budgetSummary() : null,
268
- stages: ctx.stageResults || {},
269
- });
270
- }
271
- } catch (err) {
272
- logger.warn(`Final journal write failed (non-blocking): ${err.message}`);
273
- }
274
-
275
- // --- Cleanup auto-installed skills ---
276
- const autoSkills = ctx.session?.autoInstalledSkills;
277
- if (autoSkills && autoSkills.length > 0) {
278
- const cleanProjectDir = ctx.config?.projectDir || process.cwd();
279
- try {
280
- const cleanupResult = await cleanupAutoInstalledSkills(autoSkills, cleanProjectDir);
281
- if (cleanupResult.removed.length > 0) {
282
- logger.info(`Cleaned up ${cleanupResult.removed.length} auto-installed skill(s): ${cleanupResult.removed.join(", ")}`);
283
- }
284
- } catch (err) {
285
- logger.warn(`Skill cleanup failed (non-blocking): ${err.message}`);
286
- }
287
- }
288
-
289
- // --- Telemetry: anonymous pipeline_complete event (non-blocking) ---
290
- try {
291
- const { sendTelemetryEvent, computeCachedPct } = await import("../utils/telemetry.js");
292
- const durationS = Math.round((Date.now() - ctx.startedAt) / 1000);
293
- const sessionStatus = ctx.session?.status || "unknown";
294
- // Φ0-H (KJC-TSK-0526): aggregate cache-hit ratios per role so we
295
- // can see on the fleet how much each provider's cache is buying.
296
- let cachedPct = { cached_pct_coder: null, cached_pct_reviewer: null, cached_pct_total: null };
297
- try {
298
- const budgetSummary = ctx.budgetTracker?.summary?.();
299
- if (budgetSummary) cachedPct = computeCachedPct(budgetSummary);
300
- } catch { /* non-blocking — telemetry must never break runs */ }
301
- sendTelemetryEvent("pipeline_complete", {
302
- mode: config.review_mode,
303
- agent: ctx.coderRole?.provider || config.coder,
304
- duration_s: durationS,
305
- success: sessionStatus === "approved",
306
- taskType: ctx.session?.resolved_policies?.taskType || null,
307
- ...cachedPct
308
- }, config).catch(() => {});
309
- } catch { /* non-blocking */ }
310
- }
311
- }
312
-
313
- export async function resumeFlow({ sessionId, answer, config, logger, flags = {}, emitter = null, askQuestion = null }) {
314
- const session = answer
315
- ? await resumeSessionWithAnswer(sessionId, answer)
316
- : await loadSession(sessionId);
317
-
318
- if (session.status === "paused" && !answer) {
319
- logger.info(`Session ${sessionId} is paused. Provide --answer to resume.`);
320
- return session;
321
- }
322
-
323
- // Allow resuming "stopped" sessions (checkpoint stop) and "failed" sessions
324
- const resumableStatuses = new Set(["running", "stopped", "failed"]);
325
- if (!resumableStatuses.has(session.status)) {
326
- logger.info(`Session ${sessionId} has status ${session.status} — not resumable`);
327
- return session;
328
- }
329
-
330
- // Mark as running again for stopped/failed sessions
331
- if (session.status !== "running") {
332
- logger.info(`Resuming ${session.status} session ${sessionId}`);
333
- setStatus(session, "running");
334
- await saveSession(session);
335
- }
336
-
337
- // Session was paused and now resumed with answer - re-run the flow
338
- const task = session.task;
339
- const sessionConfig = config || session.config_snapshot;
340
- if (!sessionConfig) {
341
- throw new Error("No config available to resume session");
342
- }
343
-
344
- logger.info(`Resuming session ${sessionId} with answer: ${answer}`);
345
-
346
- // Inject the answer as additional feedback for the coder
347
- if (session.paused_state?.context?.lastFeedback) {
348
- setReviewerFeedback(session, `Previous feedback: ${session.paused_state.context.lastFeedback}\nUser guidance: ${answer}`);
349
- }
350
- resetAllRetryCounters(session);
351
- setSonarIssueSignature(session, null);
352
- setSonarRepeatCount(session, 0);
353
- setReviewerIssueSignature(session, null);
354
- setReviewerRepeatCount(session, 0);
355
- await saveSession(session);
356
-
357
- // Re-run the flow with the existing session context
358
- try {
359
- // KJC-BUG-0412: what was pending is what was pending when THIS session started.
360
- return await runFlow({ task, config: sessionConfig, logger, flags, emitter, askQuestion, preexisting: session.git_preexisting ?? null });
361
- } catch (err) {
362
- await markSessionStatus(session, "failed");
363
- throw err;
364
- }
365
- }