karajan-code 4.70.3 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (388) 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/ai-surface.js +9 -7
  61. package/src/checks/config-files.js +8 -7
  62. package/src/checks/dir-setup.js +34 -1
  63. package/src/checks/native-build.js +21 -39
  64. package/src/checks/runner.js +128 -142
  65. package/src/cli/advanced-commands.js +6 -6
  66. package/src/cli/register-meta.js +42 -82
  67. package/src/cli/register-pipeline.js +8 -140
  68. package/src/cli/register-plan.js +9 -100
  69. package/src/cli/retired-commands.js +49 -0
  70. package/src/cli.js +18 -5
  71. package/src/commands/agent-run.js +40 -26
  72. package/src/commands/audit.js +127 -124
  73. package/src/commands/board.js +5 -9
  74. package/src/commands/check.js +29 -16
  75. package/src/commands/doctor.js +2 -0
  76. package/src/commands/env.js +176 -148
  77. package/src/commands/go.js +76 -55
  78. package/src/commands/harden.js +105 -86
  79. package/src/commands/hu-start.js +52 -0
  80. package/src/commands/hu.js +288 -221
  81. package/src/commands/identity.js +111 -78
  82. package/src/commands/init-atril.js +47 -0
  83. package/src/commands/init.js +11 -40
  84. package/src/commands/install-tools.js +70 -85
  85. package/src/commands/main-guard.js +78 -0
  86. package/src/commands/policy.js +226 -184
  87. package/src/commands/qmd.js +27 -21
  88. package/src/commands/rag.js +75 -48
  89. package/src/commands/review-gate.js +422 -339
  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 +94 -25
  94. package/src/config/loader.js +34 -17
  95. package/src/config/overrides.js +2 -1
  96. package/src/config/secrets.js +36 -0
  97. package/src/config.js +1 -0
  98. package/src/environment/adr.js +16 -2
  99. package/src/environment/board-access.js +11 -9
  100. package/src/git/karajan-label.js +20 -8
  101. package/src/guards/main-guard.js +54 -0
  102. package/src/harden/branch-protection.js +36 -3
  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 +81 -35
  106. package/src/harden/sentinel/sentinel-lib.mjs +149 -23
  107. package/src/harden/sentinel/sentinel-shell.mjs +64 -0
  108. package/src/harden/sentinel/sessionstart.mjs +3 -2
  109. package/src/harden/sentinel/stop.mjs +5 -4
  110. package/src/harden/workflow-engine.js +12 -1
  111. package/src/harden/workflow-templates.js +1 -1
  112. package/src/hu/board-lookup.js +29 -0
  113. package/src/hu/gh-identity.js +23 -0
  114. package/src/hu/github-board.js +4 -2
  115. package/src/hu/lane-prune.js +15 -7
  116. package/src/hu/lane-setup.js +65 -0
  117. package/src/hu/lanes.js +66 -0
  118. package/src/hu/team-board-mirror.js +3 -2
  119. package/src/infrastructure/command-runner.js +1 -1
  120. package/src/infrastructure/file-system-service.js +1 -1
  121. package/src/mcp/handlers/direct-handlers.js +2 -292
  122. package/src/mcp/handlers/hu-handlers.js +44 -55
  123. package/src/mcp/handlers/management-handlers.js +2 -42
  124. package/src/mcp/server-handlers.js +16 -22
  125. package/src/mcp/tools.js +5 -200
  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 +56 -43
  134. package/src/rag/bootstrap-index.js +28 -54
  135. package/src/rag/migrate.js +1 -1
  136. package/src/rag/onnx-fallback.js +2 -2
  137. package/src/rag/pid-lease.js +70 -0
  138. package/src/rag/project-store.js +2 -12
  139. package/src/review/card-first.js +57 -46
  140. package/src/review/dual-review.js +5 -4
  141. package/src/review/gate-gitignore.js +23 -4
  142. package/src/review/gate-hook.js +47 -0
  143. package/src/review/one-shot-review.js +51 -37
  144. package/src/review/publish-pr.js +18 -3
  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 +34 -3
  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 +2 -26
  154. package/src/roles/audit-role.js +106 -125
  155. package/src/skills/atril-skills.js +5 -4
  156. package/src/sonar/scanner.js +116 -101
  157. package/src/steward/invariants.js +5 -4
  158. package/src/steward/phantom-sweep.js +66 -0
  159. package/src/tournament/judge.js +60 -53
  160. package/src/utils/agent-home.js +33 -0
  161. package/src/utils/gh-account.js +37 -0
  162. package/src/utils/git.js +0 -13
  163. package/src/utils/home-migration.js +7 -1
  164. package/src/utils/main-checkout.js +53 -0
  165. package/src/utils/qmd-collection.js +3 -1
  166. package/src/utils/welcome.js +3 -3
  167. package/templates/{skills → atril/commands}/kj-architect.md +5 -0
  168. package/templates/{skills → atril/commands}/kj-audit.md +5 -0
  169. package/templates/{skills → atril/commands}/kj-board.md +5 -0
  170. package/templates/{skills → atril/commands}/kj-code.md +5 -0
  171. package/templates/{skills → atril/commands}/kj-csv-transform.md +5 -0
  172. package/templates/{skills → atril/commands}/kj-data-report.md +5 -0
  173. package/templates/{skills → atril/commands}/kj-discover.md +5 -0
  174. package/templates/{skills → atril/commands}/kj-rag-query.md +5 -0
  175. package/templates/{skills → atril/commands}/kj-review.md +5 -0
  176. package/templates/{skills → atril/commands}/kj-security.md +5 -0
  177. package/templates/{skills → atril/commands}/kj-sonar.md +5 -0
  178. package/templates/{skills → atril/commands}/kj-sql-analysis.md +5 -0
  179. package/templates/{skills → atril/commands}/kj-test.md +5 -0
  180. package/packages/hu-board/public/utils/run-launcher.js +0 -169
  181. package/packages/hu-board/src/run-tracker.js +0 -121
  182. package/src/activity-log.js +0 -59
  183. package/src/agents/host-agent.js +0 -38
  184. package/src/agents/model-registry.js +0 -142
  185. package/src/audit/plan-adherence.js +0 -224
  186. package/src/autonomy/arbiter-role.js +0 -71
  187. package/src/autonomy/arbiter.js +0 -22
  188. package/src/autonomy/decider.js +0 -18
  189. package/src/autonomy/decision-resolver.js +0 -58
  190. package/src/autonomy/outcome-report.js +0 -55
  191. package/src/autonomy/stage-ask.js +0 -30
  192. package/src/brain/decision-tracker.js +0 -125
  193. package/src/brain/decisor.js +0 -243
  194. package/src/brain/solomon-consult.js +0 -171
  195. package/src/brain/standby-scheduler.js +0 -8
  196. package/src/budget/comparison.js +0 -96
  197. package/src/canvas/parse-md.js +0 -238
  198. package/src/canvas/schema.js +0 -101
  199. package/src/canvas/to-flat.js +0 -85
  200. package/src/canvas/validate.js +0 -163
  201. package/src/ci/dispatch.js +0 -99
  202. package/src/ci/index.js +0 -3
  203. package/src/ci/pr-diff.js +0 -26
  204. package/src/cli/register-standby.js +0 -26
  205. package/src/commands/architect.js +0 -111
  206. package/src/commands/autorun.js +0 -49
  207. package/src/commands/researcher.js +0 -54
  208. package/src/commands/resume.js +0 -72
  209. package/src/commands/review.js +0 -89
  210. package/src/commands/run.js +0 -185
  211. package/src/commands/standby.js +0 -117
  212. package/src/commands/status.js +0 -36
  213. package/src/commands/triage.js +0 -78
  214. package/src/commands/undo.js +0 -62
  215. package/src/domains/domain-loader.js +0 -245
  216. package/src/domains/domain-registry.js +0 -140
  217. package/src/domains/domain-synthesizer.js +0 -129
  218. package/src/git/automation.js +0 -433
  219. package/src/git/coder-commit-guard.js +0 -40
  220. package/src/git/hu-automation.js +0 -243
  221. package/src/git/hu-snapshot.js +0 -10
  222. package/src/git/symlink-targets.js +0 -57
  223. package/src/golden/asserter.js +0 -92
  224. package/src/golden/loader.js +0 -52
  225. package/src/golden/runner.js +0 -92
  226. package/src/golden/schema.js +0 -41
  227. package/src/guards/duplicate-members.js +0 -86
  228. package/src/guards/intent-guard.js +0 -161
  229. package/src/guards/perf-guard.js +0 -126
  230. package/src/guards/policy-guard.js +0 -90
  231. package/src/guards/policy-resolver.js +0 -85
  232. package/src/guards/secret-redactor.js +0 -71
  233. package/src/hu/acceptance-runner.js +0 -138
  234. package/src/hu/lazy-planner.js +0 -109
  235. package/src/hu/parallel-executor.js +0 -94
  236. package/src/hu/routing-metrics.js +0 -17
  237. package/src/hu/split-validator.js +0 -143
  238. package/src/hu/splitting-detector.js +0 -158
  239. package/src/hu/splitting-generator.js +0 -175
  240. package/src/hu/store.js +0 -394
  241. package/src/infrastructure/mocks.js +0 -182
  242. package/src/mcp/handlers/run-handler.js +0 -318
  243. package/src/mcp/sovereignty-guard.js +0 -113
  244. package/src/mcp/tool-arg-normalizers.js +0 -16
  245. package/src/mutate/reviewer-signal.js +0 -76
  246. package/src/orchestrator/agent-fallback.js +0 -81
  247. package/src/orchestrator/brain-coordinator.js +0 -186
  248. package/src/orchestrator/ci-integration.js +0 -139
  249. package/src/orchestrator/config-init.js +0 -426
  250. package/src/orchestrator/direct-actions.js +0 -217
  251. package/src/orchestrator/drivers/error-recovery.js +0 -287
  252. package/src/orchestrator/drivers/init-context.js +0 -238
  253. package/src/orchestrator/drivers/iteration-loop.js +0 -382
  254. package/src/orchestrator/drivers/iteration-phases/coder-and-refactorer.js +0 -69
  255. package/src/orchestrator/drivers/iteration-phases/guards.js +0 -91
  256. package/src/orchestrator/drivers/iteration-phases/handle-approved.js +0 -29
  257. package/src/orchestrator/drivers/iteration-phases/quality-gates.js +0 -125
  258. package/src/orchestrator/drivers/iteration-phases/reviewer-gate.js +0 -62
  259. package/src/orchestrator/drivers/post-loop.js +0 -404
  260. package/src/orchestrator/drivers/pre-loop-phases/auto-hu-batch.js +0 -137
  261. package/src/orchestrator/drivers/pre-loop-phases/config-deprecations.js +0 -47
  262. package/src/orchestrator/drivers/pre-loop-phases/ensure-addyosmani-skills.js +0 -84
  263. package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +0 -393
  264. package/src/orchestrator/drivers/pre-loop.js +0 -524
  265. package/src/orchestrator/drivers/run-hu-batch.js +0 -468
  266. package/src/orchestrator/feedback-enrichment.js +0 -140
  267. package/src/orchestrator/feedback-queue.js +0 -151
  268. package/src/orchestrator/flow-control.js +0 -170
  269. package/src/orchestrator/flow-runner.js +0 -365
  270. package/src/orchestrator/fs-leak-detector.js +0 -228
  271. package/src/orchestrator/hu-scheduler.js +0 -114
  272. package/src/orchestrator/hu-sub-pipeline.js +0 -642
  273. package/src/orchestrator/iteration-gate.js +0 -73
  274. package/src/orchestrator/iteration-stages.js +0 -9
  275. package/src/orchestrator/parallel-limiter.js +0 -74
  276. package/src/orchestrator/pipeline-context.js +0 -72
  277. package/src/orchestrator/post-loop-stages.js +0 -468
  278. package/src/orchestrator/pre-loop-stages.js +0 -11
  279. package/src/orchestrator/preflight-checks.js +0 -487
  280. package/src/orchestrator/repair/repair-detector.js +0 -117
  281. package/src/orchestrator/repair/repair-runner.js +0 -142
  282. package/src/orchestrator/reviewer-fallback.js +0 -45
  283. package/src/orchestrator/role-output-compressor.js +0 -189
  284. package/src/orchestrator/session-journal.js +0 -308
  285. package/src/orchestrator/solomon-escalation.js +0 -331
  286. package/src/orchestrator/solomon-rules.js +0 -212
  287. package/src/orchestrator/stages/acceptance-coverage-stage.js +0 -47
  288. package/src/orchestrator/stages/architect-stage.js +0 -172
  289. package/src/orchestrator/stages/coder-stage.js +0 -506
  290. package/src/orchestrator/stages/domain-curator-stage.js +0 -82
  291. package/src/orchestrator/stages/format-stage.js +0 -61
  292. package/src/orchestrator/stages/hu-reviewer-phases/detect-and-apply-splits.js +0 -127
  293. package/src/orchestrator/stages/hu-reviewer-stage.js +0 -419
  294. package/src/orchestrator/stages/perf-stage.js +0 -140
  295. package/src/orchestrator/stages/planner-stage.js +0 -85
  296. package/src/orchestrator/stages/rag-context-stage.js +0 -80
  297. package/src/orchestrator/stages/rag-preload-decisor.js +0 -58
  298. package/src/orchestrator/stages/research-stage.js +0 -69
  299. package/src/orchestrator/stages/reviewer-stage.js +0 -431
  300. package/src/orchestrator/stages/sonar-stage.js +0 -439
  301. package/src/orchestrator/stages/stage-classes.js +0 -84
  302. package/src/orchestrator/stages/stage-executor.js +0 -155
  303. package/src/orchestrator/stages/suite-green-stage.js +0 -62
  304. package/src/orchestrator/stages/tdd-discipline-stage.js +0 -56
  305. package/src/orchestrator/stages/tool-judge-stage.js +0 -53
  306. package/src/orchestrator/stages/triage-stage.js +0 -172
  307. package/src/orchestrator/standby.js +0 -71
  308. package/src/orchestrator/verification-gate.js +0 -183
  309. package/src/orchestrator.js +0 -22
  310. package/src/plan/adr-generator.js +0 -170
  311. package/src/plan/adr-loader.js +0 -60
  312. package/src/plan/plan-executor.js +0 -100
  313. package/src/plan/plan-validation.js +0 -4
  314. package/src/prompts/acceptance-coverage.js +0 -32
  315. package/src/prompts/arbiter.js +0 -38
  316. package/src/prompts/architect.js +0 -103
  317. package/src/prompts/hu-reviewer.js +0 -244
  318. package/src/prompts/tool-correctness-judge.js +0 -31
  319. package/src/prompts/triage.js +0 -57
  320. package/src/rag/embedder.js +0 -2
  321. package/src/rag/embedders/_cloud-base.js +0 -2
  322. package/src/rag/embedders/cohere.js +0 -2
  323. package/src/rag/embedders/mistral.js +0 -2
  324. package/src/rag/embedders/onnx.js +0 -2
  325. package/src/rag/embedders/openai.js +0 -2
  326. package/src/rag/embedders/voyage.js +0 -2
  327. package/src/rag/rerank.js +0 -4
  328. package/src/rag/where-parser.js +0 -4
  329. package/src/repeat-detector.js +0 -88
  330. package/src/review/diff-generator.js +0 -112
  331. package/src/review/git-stash-helper.js +0 -104
  332. package/src/review/schema.js +0 -31
  333. package/src/review/scope-filter.js +0 -152
  334. package/src/review/snapshot-diff.js +0 -122
  335. package/src/review/tdd-discipline.js +0 -90
  336. package/src/review/tdd-policy.js +0 -69
  337. package/src/roles/acceptance-coverage-role.js +0 -78
  338. package/src/roles/architect-role.js +0 -77
  339. package/src/roles/coder-role.js +0 -113
  340. package/src/roles/commiter-role.js +0 -113
  341. package/src/roles/domain-curator-role.js +0 -134
  342. package/src/roles/hu-reviewer-role.js +0 -64
  343. package/src/roles/impeccable-role.js +0 -85
  344. package/src/roles/index.js +0 -18
  345. package/src/roles/karajan-brain-role.js +0 -134
  346. package/src/roles/perf-role.js +0 -122
  347. package/src/roles/planner-role.js +0 -151
  348. package/src/roles/refactorer-role.js +0 -30
  349. package/src/roles/repairer-role.js +0 -181
  350. package/src/roles/researcher-role.js +0 -70
  351. package/src/roles/reviewer-role.js +0 -115
  352. package/src/roles/security-role.js +0 -73
  353. package/src/roles/solomon-role.js +0 -271
  354. package/src/roles/sonar-role.js +0 -72
  355. package/src/roles/tester-role.js +0 -235
  356. package/src/roles/tool-correctness-judge-role.js +0 -78
  357. package/src/roles/triage-role.js +0 -99
  358. package/src/session/journal/decisions-writer.js +0 -200
  359. package/src/session/journal/iteration-logger.js +0 -194
  360. package/src/session/journal/summary-writer.js +0 -320
  361. package/src/session/journal/tree-writer.js +0 -164
  362. package/src/session/journal/write-all.js +0 -89
  363. package/src/session-cleanup.js +0 -116
  364. package/src/skills/semantic-detector.js +0 -167
  365. package/src/skills/skill-detector.js +0 -385
  366. package/src/sonar/cloud-scanner.js +0 -78
  367. package/src/tracker-bootstrap.js +0 -44
  368. package/src/types/index.js +0 -38
  369. package/src/types/policy.js +0 -43
  370. package/src/types/solomon.js +0 -87
  371. package/src/utils/async-lock.js +0 -31
  372. package/src/utils/budget.js +0 -229
  373. package/src/utils/cwd-confirm.js +0 -39
  374. package/src/utils/display/event-handlers.js +0 -403
  375. package/src/utils/display/formatters.js +0 -132
  376. package/src/utils/display/header.js +0 -47
  377. package/src/utils/display/session-summary.js +0 -118
  378. package/src/utils/display/solomon.js +0 -42
  379. package/src/utils/pricing.js +0 -29
  380. package/src/utils/quota-simulator.js +0 -56
  381. package/src/utils/role-assigner.js +0 -137
  382. package/src/utils/rtk-wrapper.js +0 -87
  383. package/src/utils/run-registry.js +0 -9
  384. package/src/utils/status-dashboard.js +0 -254
  385. package/src/utils/tool-call-extractor.js +0 -56
  386. package/src/webperf/devtools-detect.js +0 -112
  387. package/src/webperf/webperf-role-integration.js +0 -66
  388. 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
- }