karajan-code 4.70.4 → 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 (380) 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/retired-commands.js +49 -0
  68. package/src/cli.js +18 -5
  69. package/src/commands/agent-run.js +40 -26
  70. package/src/commands/audit.js +127 -124
  71. package/src/commands/board.js +5 -9
  72. package/src/commands/check.js +29 -16
  73. package/src/commands/doctor.js +2 -0
  74. package/src/commands/env.js +176 -150
  75. package/src/commands/go.js +71 -53
  76. package/src/commands/harden.js +90 -81
  77. package/src/commands/hu-start.js +52 -0
  78. package/src/commands/hu.js +288 -221
  79. package/src/commands/identity.js +111 -78
  80. package/src/commands/init-atril.js +47 -0
  81. package/src/commands/init.js +11 -40
  82. package/src/commands/install-tools.js +70 -85
  83. package/src/commands/main-guard.js +78 -0
  84. package/src/commands/policy.js +226 -184
  85. package/src/commands/qmd.js +27 -21
  86. package/src/commands/rag.js +75 -48
  87. package/src/commands/review-gate.js +421 -341
  88. package/src/commands/start.js +4 -5
  89. package/src/commands/steward.js +96 -47
  90. package/src/commands/tournament.js +46 -37
  91. package/src/commands/worktree.js +94 -25
  92. package/src/config/loader.js +34 -17
  93. package/src/config/secrets.js +36 -0
  94. package/src/config.js +1 -0
  95. package/src/environment/adr.js +16 -2
  96. package/src/git/karajan-label.js +20 -8
  97. package/src/guards/main-guard.js +54 -0
  98. package/src/harden/hook-templates.js +16 -1
  99. package/src/harden/sentinel/posttooluse.mjs +18 -6
  100. package/src/harden/sentinel/pretooluse-sentinel.mjs +64 -36
  101. package/src/harden/sentinel/sentinel-lib.mjs +129 -26
  102. package/src/harden/sentinel/sentinel-shell.mjs +5 -16
  103. package/src/harden/sentinel/sessionstart.mjs +3 -2
  104. package/src/harden/sentinel/stop.mjs +5 -4
  105. package/src/harden/workflow-templates.js +1 -1
  106. package/src/hu/board-lookup.js +29 -0
  107. package/src/hu/gh-identity.js +23 -0
  108. package/src/hu/github-board.js +4 -2
  109. package/src/hu/lane-prune.js +15 -7
  110. package/src/hu/lane-setup.js +65 -0
  111. package/src/hu/lanes.js +66 -0
  112. package/src/hu/team-board-mirror.js +3 -2
  113. package/src/infrastructure/command-runner.js +1 -1
  114. package/src/infrastructure/file-system-service.js +1 -1
  115. package/src/mcp/handlers/direct-handlers.js +2 -292
  116. package/src/mcp/handlers/hu-handlers.js +1 -35
  117. package/src/mcp/handlers/management-handlers.js +2 -42
  118. package/src/mcp/server-handlers.js +16 -22
  119. package/src/mcp/tools.js +1 -196
  120. package/src/plan/lane-plans.js +54 -0
  121. package/src/plan/plan-store.js +7 -4
  122. package/src/policy/add.js +26 -12
  123. package/src/policy/adr-number-check.js +31 -0
  124. package/src/prompts/audit.js +299 -339
  125. package/src/prompts/card-context.js +10 -5
  126. package/src/prompts/reviewer.js +5 -2
  127. package/src/rag/auto-update.js +56 -43
  128. package/src/rag/bootstrap-index.js +28 -54
  129. package/src/rag/migrate.js +1 -1
  130. package/src/rag/onnx-fallback.js +2 -2
  131. package/src/rag/pid-lease.js +70 -0
  132. package/src/rag/project-store.js +2 -12
  133. package/src/review/card-first.js +57 -46
  134. package/src/review/gate-gitignore.js +23 -4
  135. package/src/review/gate-hook.js +12 -4
  136. package/src/review/one-shot-review.js +45 -35
  137. package/src/review/publish-pr.js +14 -2
  138. package/src/review/repo-docs.js +73 -0
  139. package/src/review/repo-stack.js +59 -0
  140. package/src/review/reviewer-fallback.js +19 -4
  141. package/src/review/seal-commit.js +29 -0
  142. package/src/review/sonar-pregate.js +59 -44
  143. package/src/review/third-party-review.js +90 -16
  144. package/src/review/third-party-size.js +43 -0
  145. package/src/review/third-party-skills.js +54 -0
  146. package/src/review/verify-pr.js +1 -24
  147. package/src/roles/audit-role.js +106 -125
  148. package/src/skills/atril-skills.js +5 -4
  149. package/src/sonar/scanner.js +116 -101
  150. package/src/steward/invariants.js +5 -4
  151. package/src/steward/phantom-sweep.js +66 -0
  152. package/src/tournament/judge.js +60 -53
  153. package/src/utils/gh-account.js +37 -0
  154. package/src/utils/git.js +0 -13
  155. package/src/utils/home-migration.js +7 -1
  156. package/src/utils/main-checkout.js +53 -0
  157. package/src/utils/qmd-collection.js +3 -1
  158. package/src/utils/welcome.js +3 -3
  159. package/templates/{skills → atril/commands}/kj-architect.md +5 -0
  160. package/templates/{skills → atril/commands}/kj-audit.md +5 -0
  161. package/templates/{skills → atril/commands}/kj-board.md +5 -0
  162. package/templates/{skills → atril/commands}/kj-code.md +5 -0
  163. package/templates/{skills → atril/commands}/kj-csv-transform.md +5 -0
  164. package/templates/{skills → atril/commands}/kj-data-report.md +5 -0
  165. package/templates/{skills → atril/commands}/kj-discover.md +5 -0
  166. package/templates/{skills → atril/commands}/kj-rag-query.md +5 -0
  167. package/templates/{skills → atril/commands}/kj-review.md +5 -0
  168. package/templates/{skills → atril/commands}/kj-security.md +5 -0
  169. package/templates/{skills → atril/commands}/kj-sonar.md +5 -0
  170. package/templates/{skills → atril/commands}/kj-sql-analysis.md +5 -0
  171. package/templates/{skills → atril/commands}/kj-test.md +5 -0
  172. package/packages/hu-board/public/utils/run-launcher.js +0 -169
  173. package/packages/hu-board/src/run-tracker.js +0 -121
  174. package/src/activity-log.js +0 -59
  175. package/src/agents/host-agent.js +0 -38
  176. package/src/agents/model-registry.js +0 -142
  177. package/src/audit/plan-adherence.js +0 -224
  178. package/src/autonomy/arbiter-role.js +0 -71
  179. package/src/autonomy/arbiter.js +0 -22
  180. package/src/autonomy/decider.js +0 -18
  181. package/src/autonomy/decision-resolver.js +0 -58
  182. package/src/autonomy/outcome-report.js +0 -55
  183. package/src/autonomy/stage-ask.js +0 -30
  184. package/src/brain/decision-tracker.js +0 -125
  185. package/src/brain/decisor.js +0 -243
  186. package/src/brain/solomon-consult.js +0 -171
  187. package/src/brain/standby-scheduler.js +0 -8
  188. package/src/budget/comparison.js +0 -96
  189. package/src/canvas/parse-md.js +0 -238
  190. package/src/canvas/schema.js +0 -101
  191. package/src/canvas/to-flat.js +0 -85
  192. package/src/canvas/validate.js +0 -163
  193. package/src/ci/dispatch.js +0 -99
  194. package/src/ci/index.js +0 -3
  195. package/src/ci/pr-diff.js +0 -26
  196. package/src/cli/register-standby.js +0 -26
  197. package/src/commands/architect.js +0 -111
  198. package/src/commands/autorun.js +0 -49
  199. package/src/commands/researcher.js +0 -54
  200. package/src/commands/resume.js +0 -72
  201. package/src/commands/review.js +0 -89
  202. package/src/commands/run.js +0 -185
  203. package/src/commands/standby.js +0 -117
  204. package/src/commands/status.js +0 -36
  205. package/src/commands/triage.js +0 -78
  206. package/src/commands/undo.js +0 -62
  207. package/src/domains/domain-loader.js +0 -245
  208. package/src/domains/domain-registry.js +0 -140
  209. package/src/domains/domain-synthesizer.js +0 -129
  210. package/src/git/automation.js +0 -433
  211. package/src/git/coder-commit-guard.js +0 -40
  212. package/src/git/hu-automation.js +0 -243
  213. package/src/git/hu-snapshot.js +0 -10
  214. package/src/git/symlink-targets.js +0 -57
  215. package/src/golden/asserter.js +0 -92
  216. package/src/golden/loader.js +0 -52
  217. package/src/golden/runner.js +0 -92
  218. package/src/golden/schema.js +0 -41
  219. package/src/guards/duplicate-members.js +0 -86
  220. package/src/guards/intent-guard.js +0 -161
  221. package/src/guards/perf-guard.js +0 -126
  222. package/src/guards/policy-guard.js +0 -90
  223. package/src/guards/policy-resolver.js +0 -85
  224. package/src/guards/secret-redactor.js +0 -71
  225. package/src/hu/acceptance-runner.js +0 -138
  226. package/src/hu/lazy-planner.js +0 -109
  227. package/src/hu/parallel-executor.js +0 -94
  228. package/src/hu/routing-metrics.js +0 -17
  229. package/src/hu/split-validator.js +0 -143
  230. package/src/hu/splitting-detector.js +0 -158
  231. package/src/hu/splitting-generator.js +0 -175
  232. package/src/hu/store.js +0 -394
  233. package/src/infrastructure/mocks.js +0 -182
  234. package/src/mcp/handlers/run-handler.js +0 -318
  235. package/src/mcp/sovereignty-guard.js +0 -113
  236. package/src/mcp/tool-arg-normalizers.js +0 -16
  237. package/src/mutate/reviewer-signal.js +0 -76
  238. package/src/orchestrator/agent-fallback.js +0 -81
  239. package/src/orchestrator/brain-coordinator.js +0 -186
  240. package/src/orchestrator/ci-integration.js +0 -139
  241. package/src/orchestrator/config-init.js +0 -426
  242. package/src/orchestrator/direct-actions.js +0 -217
  243. package/src/orchestrator/drivers/error-recovery.js +0 -287
  244. package/src/orchestrator/drivers/init-context.js +0 -238
  245. package/src/orchestrator/drivers/iteration-loop.js +0 -382
  246. package/src/orchestrator/drivers/iteration-phases/coder-and-refactorer.js +0 -69
  247. package/src/orchestrator/drivers/iteration-phases/guards.js +0 -91
  248. package/src/orchestrator/drivers/iteration-phases/handle-approved.js +0 -29
  249. package/src/orchestrator/drivers/iteration-phases/quality-gates.js +0 -125
  250. package/src/orchestrator/drivers/iteration-phases/reviewer-gate.js +0 -62
  251. package/src/orchestrator/drivers/post-loop.js +0 -404
  252. package/src/orchestrator/drivers/pre-loop-phases/auto-hu-batch.js +0 -137
  253. package/src/orchestrator/drivers/pre-loop-phases/config-deprecations.js +0 -47
  254. package/src/orchestrator/drivers/pre-loop-phases/ensure-addyosmani-skills.js +0 -84
  255. package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +0 -393
  256. package/src/orchestrator/drivers/pre-loop.js +0 -524
  257. package/src/orchestrator/drivers/run-hu-batch.js +0 -468
  258. package/src/orchestrator/feedback-enrichment.js +0 -140
  259. package/src/orchestrator/feedback-queue.js +0 -151
  260. package/src/orchestrator/flow-control.js +0 -170
  261. package/src/orchestrator/flow-runner.js +0 -365
  262. package/src/orchestrator/fs-leak-detector.js +0 -228
  263. package/src/orchestrator/hu-scheduler.js +0 -114
  264. package/src/orchestrator/hu-sub-pipeline.js +0 -642
  265. package/src/orchestrator/iteration-gate.js +0 -73
  266. package/src/orchestrator/iteration-stages.js +0 -9
  267. package/src/orchestrator/parallel-limiter.js +0 -74
  268. package/src/orchestrator/pipeline-context.js +0 -72
  269. package/src/orchestrator/post-loop-stages.js +0 -468
  270. package/src/orchestrator/pre-loop-stages.js +0 -11
  271. package/src/orchestrator/preflight-checks.js +0 -487
  272. package/src/orchestrator/repair/repair-detector.js +0 -117
  273. package/src/orchestrator/repair/repair-runner.js +0 -142
  274. package/src/orchestrator/reviewer-fallback.js +0 -45
  275. package/src/orchestrator/role-output-compressor.js +0 -189
  276. package/src/orchestrator/session-journal.js +0 -308
  277. package/src/orchestrator/solomon-escalation.js +0 -331
  278. package/src/orchestrator/solomon-rules.js +0 -212
  279. package/src/orchestrator/stages/acceptance-coverage-stage.js +0 -47
  280. package/src/orchestrator/stages/architect-stage.js +0 -172
  281. package/src/orchestrator/stages/coder-stage.js +0 -506
  282. package/src/orchestrator/stages/domain-curator-stage.js +0 -82
  283. package/src/orchestrator/stages/format-stage.js +0 -61
  284. package/src/orchestrator/stages/hu-reviewer-phases/detect-and-apply-splits.js +0 -127
  285. package/src/orchestrator/stages/hu-reviewer-stage.js +0 -419
  286. package/src/orchestrator/stages/perf-stage.js +0 -140
  287. package/src/orchestrator/stages/planner-stage.js +0 -85
  288. package/src/orchestrator/stages/rag-context-stage.js +0 -80
  289. package/src/orchestrator/stages/rag-preload-decisor.js +0 -58
  290. package/src/orchestrator/stages/research-stage.js +0 -69
  291. package/src/orchestrator/stages/reviewer-stage.js +0 -431
  292. package/src/orchestrator/stages/sonar-stage.js +0 -439
  293. package/src/orchestrator/stages/stage-classes.js +0 -84
  294. package/src/orchestrator/stages/stage-executor.js +0 -155
  295. package/src/orchestrator/stages/suite-green-stage.js +0 -62
  296. package/src/orchestrator/stages/tdd-discipline-stage.js +0 -56
  297. package/src/orchestrator/stages/tool-judge-stage.js +0 -53
  298. package/src/orchestrator/stages/triage-stage.js +0 -172
  299. package/src/orchestrator/standby.js +0 -71
  300. package/src/orchestrator/verification-gate.js +0 -183
  301. package/src/orchestrator.js +0 -22
  302. package/src/plan/adr-generator.js +0 -170
  303. package/src/plan/adr-loader.js +0 -60
  304. package/src/plan/plan-executor.js +0 -100
  305. package/src/plan/plan-validation.js +0 -4
  306. package/src/prompts/acceptance-coverage.js +0 -32
  307. package/src/prompts/arbiter.js +0 -38
  308. package/src/prompts/architect.js +0 -103
  309. package/src/prompts/hu-reviewer.js +0 -244
  310. package/src/prompts/tool-correctness-judge.js +0 -31
  311. package/src/prompts/triage.js +0 -57
  312. package/src/rag/embedder.js +0 -2
  313. package/src/rag/embedders/_cloud-base.js +0 -2
  314. package/src/rag/embedders/cohere.js +0 -2
  315. package/src/rag/embedders/mistral.js +0 -2
  316. package/src/rag/embedders/onnx.js +0 -2
  317. package/src/rag/embedders/openai.js +0 -2
  318. package/src/rag/embedders/voyage.js +0 -2
  319. package/src/rag/rerank.js +0 -4
  320. package/src/rag/where-parser.js +0 -4
  321. package/src/repeat-detector.js +0 -88
  322. package/src/review/diff-generator.js +0 -112
  323. package/src/review/git-stash-helper.js +0 -104
  324. package/src/review/schema.js +0 -31
  325. package/src/review/scope-filter.js +0 -152
  326. package/src/review/snapshot-diff.js +0 -122
  327. package/src/review/tdd-discipline.js +0 -90
  328. package/src/review/tdd-policy.js +0 -69
  329. package/src/roles/acceptance-coverage-role.js +0 -78
  330. package/src/roles/architect-role.js +0 -77
  331. package/src/roles/coder-role.js +0 -113
  332. package/src/roles/commiter-role.js +0 -113
  333. package/src/roles/domain-curator-role.js +0 -134
  334. package/src/roles/hu-reviewer-role.js +0 -64
  335. package/src/roles/impeccable-role.js +0 -85
  336. package/src/roles/index.js +0 -18
  337. package/src/roles/karajan-brain-role.js +0 -134
  338. package/src/roles/perf-role.js +0 -122
  339. package/src/roles/planner-role.js +0 -151
  340. package/src/roles/refactorer-role.js +0 -30
  341. package/src/roles/repairer-role.js +0 -181
  342. package/src/roles/researcher-role.js +0 -70
  343. package/src/roles/reviewer-role.js +0 -115
  344. package/src/roles/security-role.js +0 -73
  345. package/src/roles/solomon-role.js +0 -271
  346. package/src/roles/sonar-role.js +0 -72
  347. package/src/roles/tester-role.js +0 -235
  348. package/src/roles/tool-correctness-judge-role.js +0 -78
  349. package/src/roles/triage-role.js +0 -99
  350. package/src/session/journal/decisions-writer.js +0 -200
  351. package/src/session/journal/iteration-logger.js +0 -194
  352. package/src/session/journal/summary-writer.js +0 -320
  353. package/src/session/journal/tree-writer.js +0 -164
  354. package/src/session/journal/write-all.js +0 -89
  355. package/src/session-cleanup.js +0 -116
  356. package/src/skills/semantic-detector.js +0 -167
  357. package/src/skills/skill-detector.js +0 -385
  358. package/src/sonar/cloud-scanner.js +0 -78
  359. package/src/tracker-bootstrap.js +0 -44
  360. package/src/types/index.js +0 -38
  361. package/src/types/policy.js +0 -43
  362. package/src/types/solomon.js +0 -87
  363. package/src/utils/async-lock.js +0 -31
  364. package/src/utils/budget.js +0 -229
  365. package/src/utils/cwd-confirm.js +0 -39
  366. package/src/utils/display/event-handlers.js +0 -403
  367. package/src/utils/display/formatters.js +0 -132
  368. package/src/utils/display/header.js +0 -47
  369. package/src/utils/display/session-summary.js +0 -118
  370. package/src/utils/display/solomon.js +0 -42
  371. package/src/utils/pricing.js +0 -29
  372. package/src/utils/quota-simulator.js +0 -56
  373. package/src/utils/role-assigner.js +0 -137
  374. package/src/utils/rtk-wrapper.js +0 -87
  375. package/src/utils/run-registry.js +0 -9
  376. package/src/utils/status-dashboard.js +0 -254
  377. package/src/utils/tool-call-extractor.js +0 -56
  378. package/src/webperf/devtools-detect.js +0 -112
  379. package/src/webperf/webperf-role-integration.js +0 -66
  380. package/templates/skills/kj-run.md +0 -73
@@ -1,194 +0,0 @@
1
- /**
2
- * Per-iteration journal entries for `.reviews/{sessionId}/iterations.md`.
3
- *
4
- * The orchestrator calls `recordIteration(session, data)` after every
5
- * iteration of the coder/reviewer loop completes. Entries are appended to
6
- * `session._journalIterations` and rendered as Markdown at session end.
7
- *
8
- * Acceptance criterion (KJC-TSK-0287):
9
- * - Given a kj run with multiple iterations → iterations.md exists with
10
- * one section per iteration containing: number, coder summary, reviewer
11
- * blocking issues, sonar issues (if any), Solomon ruling (if any),
12
- * duration.
13
- */
14
-
15
- /**
16
- * @typedef {Object} IterationData
17
- * @property {number} iteration - 1-based index
18
- * @property {number} durationMs
19
- * @property {string} [coderSummary]
20
- * @property {string} [reviewerSummary]
21
- * @property {Array<{id?:string, severity?:string, file?:string, line?:number, description?:string}>} [blockingIssues]
22
- * @property {string} [sonarSummary]
23
- * @property {number} [sonarIssuesFound]
24
- * @property {number} [sonarIssuesResolved]
25
- * @property {string} [testerSummary]
26
- * @property {string} [securitySummary]
27
- * @property {{ ruling?:string, reasoning?:string }} [solomon] - only present when Solomon ran in this iteration
28
- */
29
-
30
- function esc(text) {
31
- return String(text ?? "").replaceAll(/\|/g, "\\|");
32
- }
33
-
34
- function formatDuration(ms) {
35
- if (!Number.isFinite(ms) || ms < 0) return "—";
36
- if (ms < 1000) return `${ms}ms`;
37
- const s = Math.round(ms / 1000);
38
- if (s < 60) return `${s}s`;
39
- const m = Math.floor(s / 60);
40
- const rs = s % 60;
41
- return `${m}m ${rs}s`;
42
- }
43
-
44
- function formatBlockingIssues(issues) {
45
- if (!Array.isArray(issues) || issues.length === 0) return null;
46
- const lines = ["**Blocking issues**:"];
47
- for (const issue of issues) {
48
- const sev = issue.severity ? `[${issue.severity}] ` : "";
49
- const loc = issue.file ? ` — \`${esc(issue.file)}${issue.line ? `:${issue.line}` : ""}\`` : "";
50
- const id = issue.id ? `${issue.id}: ` : "";
51
- const desc = esc(issue.description || issue.message || "(no description)");
52
- lines.push(`- ${sev}${id}${desc}${loc}`);
53
- }
54
- return lines.join("\n");
55
- }
56
-
57
- function formatSonarBlock(data) {
58
- const parts = [];
59
- if (data.sonarSummary) parts.push(esc(data.sonarSummary));
60
- if (Number.isFinite(data.sonarIssuesFound)) {
61
- const resolved = Number.isFinite(data.sonarIssuesResolved) ? ` (${data.sonarIssuesResolved} resolved)` : "";
62
- parts.push(`Issues: ${data.sonarIssuesFound}${resolved}`);
63
- }
64
- return parts.length > 0 ? parts.join(" · ") : null;
65
- }
66
-
67
- function formatSolomonBlock(solomon) {
68
- if (!solomon || !solomon.ruling) return null;
69
- const lines = [`**Ruling**: \`${esc(solomon.ruling)}\``];
70
- if (solomon.reasoning) lines.push(`**Reasoning**: ${esc(solomon.reasoning)}`);
71
- return lines.join(" \n");
72
- }
73
-
74
- /**
75
- * Render a single iteration as a Markdown section.
76
- *
77
- * @param {IterationData} data
78
- * @returns {string}
79
- */
80
- export function renderIterationEntry(data) {
81
- const lines = [`## Iteration ${data.iteration}`, ""];
82
- lines.push(`**Duration**: ${formatDuration(data.durationMs)}`);
83
-
84
- if (data.coderSummary) {
85
- lines.push("", "### Coder", data.coderSummary);
86
- }
87
-
88
- if (data.reviewerSummary || (data.blockingIssues && data.blockingIssues.length > 0)) {
89
- lines.push("", "### Reviewer");
90
- if (data.reviewerSummary) lines.push(data.reviewerSummary);
91
- const blocks = formatBlockingIssues(data.blockingIssues);
92
- if (blocks) {
93
- lines.push("", blocks);
94
- }
95
- }
96
-
97
- const sonarLine = formatSonarBlock(data);
98
- if (sonarLine) {
99
- lines.push("", "### Sonar", sonarLine);
100
- }
101
-
102
- if (data.testerSummary) lines.push("", "### Tester", data.testerSummary);
103
- if (data.securitySummary) lines.push("", "### Security", data.securitySummary);
104
-
105
- const solomonBlock = formatSolomonBlock(data.solomon);
106
- if (solomonBlock) {
107
- lines.push("", "### Solomon", solomonBlock);
108
- }
109
-
110
- lines.push("");
111
- return lines.join("\n");
112
- }
113
-
114
- /**
115
- * Append an iteration record to session._journalIterations.
116
- * Creates the array if absent. Callers pass structured IterationData.
117
- *
118
- * @param {Object} session
119
- * @param {IterationData} data
120
- */
121
- export function recordIteration(session, data) {
122
- if (!session || !data) return;
123
- if (!Array.isArray(session._journalIterations)) session._journalIterations = [];
124
- session._journalIterations.push(renderIterationEntry(data));
125
- }
126
-
127
- /**
128
- * Build the full iterations.md content from recorded entries.
129
- * Returns null when there are no iterations to render.
130
- *
131
- * @param {Object} session
132
- * @returns {string|null}
133
- */
134
- export function buildIterationsMarkdown(session) {
135
- const entries = Array.isArray(session?._journalIterations) ? session._journalIterations : [];
136
- if (entries.length === 0) return null;
137
- const header = [
138
- `# Session iterations — ${session.id || "(unknown)"}`,
139
- "",
140
- `_Generated at ${new Date().toISOString()}._`,
141
- "",
142
- `Total iterations: **${entries.length}**`,
143
- "",
144
- "---",
145
- "",
146
- ].join("\n");
147
- return header + entries.join("---\n\n") + "\n";
148
- }
149
-
150
- /**
151
- * Extract structured iteration data from a stageResults bundle + session state.
152
- * The orchestrator produces stage results per role; this helper pulls the
153
- * relevant fields into a single object suitable for recordIteration().
154
- *
155
- * @param {Object} args
156
- * @param {number} args.iteration
157
- * @param {number} args.durationMs
158
- * @param {Object} args.stageResults
159
- * @param {Object} [args.session]
160
- * @returns {IterationData}
161
- */
162
- export function extractIterationData({ iteration, durationMs, stageResults = {}, session = {} }) {
163
- const coderSummary = stageResults.coder?.summary || stageResults.coder?.result?.summary;
164
- const reviewerSummary = stageResults.reviewer?.summary;
165
- const blockingIssues = stageResults.reviewer?.result?.blocking_issues
166
- || stageResults.reviewer?.blocking_issues
167
- || [];
168
- const testerSummary = stageResults.tester?.summary;
169
- const securitySummary = stageResults.security?.summary;
170
- const sonarSummary = stageResults.sonar?.summary
171
- || (stageResults.sonar?.openIssues != null ? `${stageResults.sonar.openIssues} open issue(s)` : undefined);
172
- const sonarIssuesFound = stageResults.sonar?.issuesInitial ?? stageResults.sonar?.issuesFound;
173
- const sonarIssuesResolved = stageResults.sonar?.issuesResolved;
174
-
175
- // Solomon ruling for THIS iteration: match by iteration if the session
176
- // tracks it; otherwise just take the latest ruling.
177
- const rulings = Array.isArray(session.solomonRulings) ? session.solomonRulings : [];
178
- const solomonRecord = rulings.find((r) => r.iteration === iteration) || rulings.at(-1);
179
- const solomon = solomonRecord ? { ruling: solomonRecord.ruling, reasoning: solomonRecord.reasoning } : undefined;
180
-
181
- return {
182
- iteration,
183
- durationMs,
184
- coderSummary,
185
- reviewerSummary,
186
- blockingIssues,
187
- sonarSummary,
188
- sonarIssuesFound,
189
- sonarIssuesResolved,
190
- testerSummary,
191
- securitySummary,
192
- solomon,
193
- };
194
- }
@@ -1,320 +0,0 @@
1
- /**
2
- * Executive session summary (`summary.md`) — the entry point to the journal
3
- * directory. Pulls together every useful signal from the session into a
4
- * single scannable Markdown page with links to the rest of the journal.
5
- *
6
- * Acceptance criterion (KJC-TSK-0289):
7
- * summary.md contains: task, result (approved/rejected/paused), iterations,
8
- * duration, budget, stages + status, list of journal files, commits.
9
- */
10
-
11
- import fs from "node:fs/promises";
12
- import path from "node:path";
13
-
14
- /**
15
- * @typedef {Object} SummaryInput
16
- * @property {string} sessionId
17
- * @property {string} task
18
- * @property {"APPROVED"|"REJECTED"|"PAUSED"|"FAILED"|string} result
19
- * @property {number} iterations
20
- * @property {number} durationMs
21
- * @property {{ total_cost_usd?: number, total_tokens?: number, total_cached_tokens?: number, breakdown_by_role?: Object }} [budget]
22
- * @property {Record<string, { ok?: boolean, summary?: string }>} [stages]
23
- * @property {Array<{ hash?: string, message?: string, date?: string, author?: string }>} [commits]
24
- * @property {string[]} [files] - names of other journal files in the same dir
25
- * @property {string} [startedAt] - ISO timestamp (optional, auto-derived if absent)
26
- * @property {string} [finishedAt] - ISO timestamp (optional)
27
- * @property {number} [solomonInvocations]
28
- * @property {number} [brainDecisions]
29
- * @property {Object} [skills] - skill sources used this session (KJC-TSK-0327)
30
- * @property {Object} [skills.addyosmani] - { available, action, resolvedSlugs, reason }
31
- * @property {string[]} [skills.installed] - OpenSkills installed this run (session.autoInstalledSkills)
32
- * @property {string[]} [skills.recommended] - wouldHaveUsed when OpenSkills CLI missing
33
- */
34
-
35
- function esc(text) {
36
- return String(text ?? "").replaceAll(/\|/g, "\\|");
37
- }
38
-
39
- function formatDuration(ms) {
40
- if (!Number.isFinite(ms) || ms < 0) return "—";
41
- if (ms < 1000) return `${ms}ms`;
42
- const s = Math.round(ms / 1000);
43
- if (s < 60) return `${s}s`;
44
- const m = Math.floor(s / 60);
45
- const rs = s % 60;
46
- if (m < 60) return `${m}m ${rs}s`;
47
- const h = Math.floor(m / 60);
48
- const rm = m % 60;
49
- return `${h}h ${rm}m ${rs}s`;
50
- }
51
-
52
- function formatBudget(budget) {
53
- if (!budget) return "—";
54
- const cost = Number(budget.total_cost_usd ?? 0);
55
- const tokens = Number(budget.total_tokens ?? 0);
56
- const costStr = `$${cost.toFixed(2)}`;
57
- const tokStr = tokens > 0 ? `${tokens.toLocaleString("en-US")} tokens` : "—";
58
- return `${costStr} · ${tokStr}`;
59
- }
60
-
61
- function resultBadge(result) {
62
- const r = String(result || "").toUpperCase();
63
- const map = {
64
- APPROVED: "✅ APPROVED",
65
- REJECTED: "❌ REJECTED",
66
- PAUSED: "⏸ PAUSED",
67
- FAILED: "❌ FAILED",
68
- };
69
- return map[r] || r;
70
- }
71
-
72
- function renderStagesTable(stages) {
73
- if (!stages || Object.keys(stages).length === 0) return "_No stages recorded._";
74
- const header = "| Stage | Status | Summary |\n|---|---|---|";
75
- const rows = Object.entries(stages).map(([name, stageResult]) => {
76
- const ok = stageResult?.ok !== false;
77
- const status = ok ? "✅ pass" : "❌ fail";
78
- const summary = esc(stageResult?.summary || "").slice(0, 120);
79
- return `| \`${esc(name)}\` | ${status} | ${summary} |`;
80
- });
81
- return [header, ...rows].join("\n");
82
- }
83
-
84
- function renderCommits(commits) {
85
- if (!Array.isArray(commits) || commits.length === 0) return "_No commits in this session._";
86
- return commits
87
- .map((c) => {
88
- const hash = (c.hash || "").slice(0, 7) || "?";
89
- return `- \`${hash}\` ${esc(c.message || "(no message)")}`;
90
- })
91
- .join("\n");
92
- }
93
-
94
- function renderBreakdownByRole(breakdown) {
95
- if (!breakdown || typeof breakdown !== "object") return null;
96
- const entries = Object.entries(breakdown)
97
- .map(([role, m]) => ({
98
- role,
99
- tokens: Number(m?.total_tokens || 0),
100
- cost: Number(m?.total_cost_usd || 0),
101
- }))
102
- .filter((e) => e.tokens > 0 || e.cost > 0);
103
- if (entries.length === 0) return null;
104
- const rows = entries
105
- .sort((a, b) => b.cost - a.cost)
106
- .map((e) => `| \`${esc(e.role)}\` | ${e.tokens.toLocaleString("en-US")} | $${e.cost.toFixed(4)} |`);
107
- return ["| Role | Tokens | Cost |", "|---|---|---|", ...rows].join("\n");
108
- }
109
-
110
- /**
111
- * Render the Cache hits section (Φ0-F, KJC-TSK-0524). Shows how many input
112
- * tokens were served from provider-side prompt caches, per role, plus a
113
- * conservative dollar savings estimate.
114
- *
115
- * Savings formula: cached tokens are billed at ~10% of the input rate (the
116
- * Anthropic/OpenAI convention). Per role:
117
- * savings_usd ≈ cost_usd * (cached_tokens / tokens_in) * 0.9
118
- * The estimate is approximate (output tokens also contribute to cost_usd)
119
- * and labelled with `~$` so users don't read it as exact.
120
- *
121
- * Returns:
122
- * - null when no budget data is available
123
- * - "cold run" placeholder when cached == 0 across all roles
124
- * - Markdown table sorted by cached tokens desc when there is cache activity
125
- */
126
- function renderCacheHits(budget) {
127
- if (!budget) return null;
128
- const totalCached = Number(budget.total_cached_tokens ?? 0);
129
- const breakdown = budget.breakdown_by_role || {};
130
- const entries = Object.entries(breakdown)
131
- .map(([role, m]) => ({
132
- role,
133
- cached: Number(m?.cached_tokens || 0),
134
- tokens_in: Number(m?.tokens_in || 0),
135
- cost: Number(m?.total_cost_usd || 0),
136
- }))
137
- .filter((e) => e.cached > 0);
138
-
139
- if (totalCached === 0 && entries.length === 0) {
140
- return "_Cache hits: 0 tokens (cold run)._";
141
- }
142
-
143
- const rows = entries
144
- .sort((a, b) => b.cached - a.cached)
145
- .map((e) => {
146
- const ratio = e.tokens_in > 0 ? (e.cached / e.tokens_in) * 100 : 0;
147
- const savings = e.tokens_in > 0 ? e.cost * (e.cached / e.tokens_in) * 0.9 : 0;
148
- return `| \`${esc(e.role)}\` | ${e.cached.toLocaleString("en-US")} | ${ratio.toFixed(1)}% | ~$${savings.toFixed(4)} |`;
149
- });
150
- const header = "| Role | Cached tokens | Ratio (cached/in) | Est. savings |\n|---|---|---|---|";
151
- return [
152
- `**Total cached**: ${totalCached.toLocaleString("en-US")} tokens`,
153
- "",
154
- header,
155
- ...rows,
156
- ].join("\n");
157
- }
158
-
159
- /**
160
- * Render the Skills section: which process skills (addyosmani) were resolved
161
- * for the task, which OpenSkills were installed, and which skills would have
162
- * helped but couldn't be installed (graceful-degradation path).
163
- *
164
- * Returns null when no skill activity happened (no addyosmani, no installs,
165
- * no recommendations) so the section is elided.
166
- */
167
- function renderSkills(skills) {
168
- if (!skills || typeof skills !== "object") return null;
169
- const addy = skills.addyosmani;
170
- const installed = Array.isArray(skills.installed) ? skills.installed : [];
171
- const recommended = Array.isArray(skills.recommended) ? skills.recommended : [];
172
-
173
- const hasAddy = addy && (addy.available === true || addy.available === false);
174
- if (!hasAddy && installed.length === 0 && recommended.length === 0) return null;
175
-
176
- const lines = [];
177
-
178
- if (hasAddy) {
179
- if (addy.available) {
180
- const action = addy.action || "ready";
181
- const slugs = Array.isArray(addy.resolvedSlugs) ? addy.resolvedSlugs : [];
182
- lines.push(`- **addyosmani/agent-skills** (process, 1st source): ${esc(action)}` +
183
- (slugs.length > 0 ? ` — resolved slugs: ${slugs.map((s) => `\`${esc(s)}\``).join(", ")}` : " — no role/task-specific slugs resolved"));
184
- } else {
185
- const reason = addy.reason ? ` — ${esc(addy.reason)}` : "";
186
- lines.push(`- **addyosmani/agent-skills**: unavailable${reason}`);
187
- }
188
- }
189
-
190
- if (installed.length > 0) {
191
- lines.push(`- **OpenSkills installed**: ${installed.map((s) => `\`${esc(s)}\``).join(", ")}`);
192
- }
193
-
194
- if (recommended.length > 0) {
195
- lines.push(`- **OpenSkills recommended** (CLI missing, would-have-used): ${recommended.map((s) => `\`${esc(s)}\``).join(", ")}`);
196
- }
197
-
198
- return lines.join("\n");
199
- }
200
-
201
- function renderJournalLinks(files) {
202
- if (!Array.isArray(files) || files.length === 0) return "_No additional journal files._";
203
- return files.map((f) => `- [${esc(f)}](./${f})`).join("\n");
204
- }
205
-
206
- /**
207
- * Build the summary.md content.
208
- *
209
- * @param {SummaryInput} input
210
- * @returns {string}
211
- */
212
- export function buildSummaryMarkdown(input) {
213
- const sessionId = input.sessionId || "(unknown)";
214
- const result = resultBadge(input.result);
215
- const startedAt = input.startedAt || "(unknown)";
216
- const finishedAt = input.finishedAt || new Date().toISOString();
217
-
218
- const sections = [
219
- `# Session summary — ${sessionId}`,
220
- "",
221
- `- **Result**: ${result}`,
222
- `- **Task**: ${esc(input.task || "(no task)")}`,
223
- `- **Iterations**: ${input.iterations ?? 0}`,
224
- `- **Duration**: ${formatDuration(input.durationMs)}`,
225
- `- **Budget**: ${formatBudget(input.budget)}`,
226
- `- **Started**: ${startedAt}`,
227
- `- **Finished**: ${finishedAt}`,
228
- ];
229
-
230
- if (Number.isFinite(input.brainDecisions) && input.brainDecisions > 0) {
231
- sections.push(`- **Brain decisions**: ${input.brainDecisions}`);
232
- }
233
- if (Number.isFinite(input.solomonInvocations) && input.solomonInvocations > 0) {
234
- sections.push(`- **Solomon invocations**: ${input.solomonInvocations}`);
235
- }
236
-
237
- sections.push("", "---", "", "## Stages", "", renderStagesTable(input.stages));
238
-
239
- const breakdown = renderBreakdownByRole(input.budget?.breakdown_by_role);
240
- if (breakdown) {
241
- sections.push("", "## Budget breakdown (by role)", "", breakdown);
242
- }
243
-
244
- const cacheHitsSection = renderCacheHits(input.budget);
245
- if (cacheHitsSection) {
246
- sections.push("", "## Cache hits", "", cacheHitsSection);
247
- }
248
-
249
- const skillsSection = renderSkills(input.skills);
250
- if (skillsSection) {
251
- sections.push("", "## Skills Used", "", skillsSection);
252
- }
253
-
254
- sections.push("", "## Commits", "", renderCommits(input.commits));
255
-
256
- // KJC-TSK-0376 — plan adherence metric (deepeval-inspired). Only
257
- // rendered when the run executed against a known plan and the
258
- // calculation produced a non-null score (a run with no commits or
259
- // no files changed yields nulls everywhere → omit the section).
260
- const planAdherenceSection = renderPlanAdherence(input.planAdherence);
261
- if (planAdherenceSection) {
262
- sections.push("", "## Plan adherence", "", planAdherenceSection);
263
- }
264
-
265
- sections.push("", "## Journal files", "", renderJournalLinks(input.files));
266
-
267
- return sections.join("\n") + "\n";
268
- }
269
-
270
- function renderPlanAdherence(planAdherence) {
271
- if (!planAdherence || typeof planAdherence !== "object") return "";
272
- if (planAdherence.score === null || planAdherence.score === undefined) return "";
273
- const lines = [`**Score**: ${planAdherence.score}/100`, ""];
274
- const breakdown = planAdherence.breakdown || {};
275
- lines.push("| Component | Score | Weight |");
276
- lines.push("| --- | --- | --- |");
277
- const rows = [
278
- ["Commit attribution", breakdown.commit_attribution, "40%"],
279
- ["Acceptance tests", breakdown.acceptance_tests, "30%"],
280
- ["Scope discipline", breakdown.scope_discipline, "20%"],
281
- ["Dependency order", breakdown.dependency_order, "10%"],
282
- ];
283
- for (const [label, value, weight] of rows) {
284
- const cell = value === null || value === undefined ? "n/a" : `${value}/100`;
285
- lines.push(`| ${label} | ${cell} | ${weight} |`);
286
- }
287
- const huScores = Array.isArray(planAdherence.hu_scores) ? planAdherence.hu_scores : [];
288
- if (huScores.length > 0) {
289
- const unattributed = huScores.filter((h) => !h.attributed);
290
- if (unattributed.length > 0) {
291
- lines.push("", `_${unattributed.length} HU(s) without an attributed commit:_`);
292
- for (const h of unattributed) {
293
- lines.push(`- \`${h.huId}\``);
294
- }
295
- }
296
- }
297
- return lines.join("\n");
298
- }
299
-
300
- /**
301
- * Write summary.md to the given journal directory. Always writes (the file
302
- * is the entry point; even a barebones session should have one).
303
- *
304
- * @param {string} journalDir
305
- * @param {SummaryInput} input
306
- * @param {{ logger?: Object }} [options]
307
- * @returns {Promise<{ written: boolean, path: string|null }>}
308
- */
309
- export async function writeSummaryJournal(journalDir, input, options = {}) {
310
- const filePath = path.join(journalDir, "summary.md");
311
- try {
312
- await fs.mkdir(journalDir, { recursive: true });
313
- await fs.writeFile(filePath, buildSummaryMarkdown(input), "utf8");
314
- options.logger?.info?.(`Wrote session summary: ${filePath}`);
315
- return { written: true, path: filePath };
316
- } catch (err) {
317
- options.logger?.warn?.(`Failed to write session summary (non-blocking): ${err.message}`);
318
- return { written: false, path: null };
319
- }
320
- }
@@ -1,164 +0,0 @@
1
- /**
2
- * Build a directory-grouped tree view of files affected during the session,
3
- * rendered as `.reviews/{sessionId}/tree.txt`.
4
- *
5
- * Acceptance criterion (KJC-TSK-0288):
6
- * - Given a kj run that modifies files, when the session finishes, then
7
- * tree.txt contains the tree of affected files (modified/added/deleted)
8
- * grouped by directory, generated from `git diff --name-status` against
9
- * the base ref.
10
- */
11
-
12
- import fs from "node:fs/promises";
13
- import path from "node:path";
14
- import { runCommand } from "../../utils/process.js";
15
-
16
- const STATUS_LABELS = {
17
- M: "modified",
18
- A: "added",
19
- D: "deleted",
20
- R: "renamed",
21
- C: "copied",
22
- T: "typechange",
23
- U: "unmerged",
24
- };
25
-
26
- /**
27
- * @typedef {Object} DiffEntry
28
- * @property {string} file - path relative to repo root
29
- * @property {string} status - "modified" | "added" | "deleted" | ...
30
- */
31
-
32
- /**
33
- * Parse `git diff --name-status` output into structured entries.
34
- *
35
- * @param {string} rawDiff
36
- * @returns {DiffEntry[]}
37
- */
38
- export function parseNameStatus(rawDiff) {
39
- if (!rawDiff || !rawDiff.trim()) return [];
40
- const entries = [];
41
- for (const line of rawDiff.split("\n")) {
42
- if (!line.trim()) continue;
43
- const parts = line.split("\t");
44
- const status = parts[0];
45
- // Renames and copies report "R<score>\told\tnew". Take the new path.
46
- const file = parts.length >= 3 ? parts[2] : parts[1];
47
- if (!status || !file) continue;
48
- const key = status[0];
49
- const label = STATUS_LABELS[key] || "other";
50
- entries.push({ file, status: label });
51
- }
52
- return entries;
53
- }
54
-
55
- /**
56
- * Group entries into a nested directory tree.
57
- * Each node is { name, children: Map<string, node>, entries: DiffEntry[] }.
58
- *
59
- * @param {DiffEntry[]} entries
60
- * @returns {{name:string, children:Map<string, any>, files:DiffEntry[]}}
61
- */
62
- export function buildTree(entries) {
63
- const root = { name: "", children: new Map(), files: [] };
64
- for (const entry of entries) {
65
- const parts = entry.file.split("/");
66
- let node = root;
67
- for (let i = 0; i < parts.length - 1; i++) {
68
- const dir = parts[i];
69
- if (!node.children.has(dir)) {
70
- node.children.set(dir, { name: dir, children: new Map(), files: [] });
71
- }
72
- node = node.children.get(dir);
73
- }
74
- node.files.push({ file: parts.at(-1), status: entry.status });
75
- }
76
- return root;
77
- }
78
-
79
- /**
80
- * Render a tree node as indented text. Directories come before files at each
81
- * level; both are sorted alphabetically (case-insensitive).
82
- */
83
- function renderNode(node, depth, lines) {
84
- const indent = " ".repeat(depth);
85
- const dirs = Array.from(node.children.values()).sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
86
- for (const dir of dirs) {
87
- lines.push(`${indent}${dir.name}/`);
88
- renderNode(dir, depth + 1, lines);
89
- }
90
- const files = [...node.files].sort((a, b) => a.file.localeCompare(b.file, undefined, { sensitivity: "base" }));
91
- for (const f of files) {
92
- lines.push(`${indent}${f.file} [${f.status}]`);
93
- }
94
- }
95
-
96
- /**
97
- * Render the tree as a self-describing text document.
98
- * Returns null when there are no entries.
99
- *
100
- * @param {DiffEntry[]} entries
101
- * @returns {string|null}
102
- */
103
- export function renderTree(entries) {
104
- if (!entries || entries.length === 0) return null;
105
- const tree = buildTree(entries);
106
- const lines = ["# Affected files (grouped by directory)", ""];
107
- renderNode(tree, 0, lines);
108
- lines.push("");
109
-
110
- // Summary counts at the bottom for quick scanning.
111
- const counts = entries.reduce((acc, e) => {
112
- acc[e.status] = (acc[e.status] || 0) + 1;
113
- return acc;
114
- }, {});
115
- const summary = Object.entries(counts)
116
- .sort(([a], [b]) => a.localeCompare(b))
117
- .map(([status, n]) => `${n} ${status}`)
118
- .join(", ");
119
- lines.push(`Total: ${entries.length} file${entries.length === 1 ? "" : "s"} — ${summary}`);
120
- return lines.join("\n");
121
- }
122
-
123
- /**
124
- * Run `git diff --name-status <baseRef>...HEAD` and return structured entries.
125
- * Returns [] if git exits with an error or produces no output.
126
- *
127
- * @param {string} baseRef
128
- * @returns {Promise<DiffEntry[]>}
129
- */
130
- export async function collectAffectedFiles(baseRef) {
131
- if (!baseRef) return [];
132
- try {
133
- const result = await runCommand("git", ["diff", "--name-status", `${baseRef}...HEAD`]);
134
- if (result.exitCode !== 0) return [];
135
- return parseNameStatus(result.stdout || "");
136
- } catch {
137
- return [];
138
- }
139
- }
140
-
141
- /**
142
- * High-level: generate the tree content and persist it to `tree.txt` under
143
- * the given journal directory. Returns `{ written, path }`.
144
- *
145
- * @param {string} journalDir
146
- * @param {string} baseRef
147
- * @param {{ logger?: Object }} [options]
148
- * @returns {Promise<{ written: boolean, path: string|null }>}
149
- */
150
- export async function writeTreeJournal(journalDir, baseRef, options = {}) {
151
- const entries = await collectAffectedFiles(baseRef);
152
- const content = renderTree(entries);
153
- if (!content) return { written: false, path: null };
154
- const filePath = path.join(journalDir, "tree.txt");
155
- try {
156
- await fs.mkdir(journalDir, { recursive: true });
157
- await fs.writeFile(filePath, content + "\n", "utf8");
158
- options.logger?.info?.(`Wrote file tree journal: ${filePath}`);
159
- return { written: true, path: filePath };
160
- } catch (err) {
161
- options.logger?.warn?.(`Failed to write tree journal (non-blocking): ${err.message}`);
162
- return { written: false, path: null };
163
- }
164
- }