@howlil/ez-agents 3.4.2 → 4.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 (365) hide show
  1. package/README.md +735 -462
  2. package/agents/ez-architect-agent.md +267 -0
  3. package/agents/ez-backend-agent.md +303 -0
  4. package/agents/ez-chief-strategist.md +271 -0
  5. package/agents/ez-codebase-mapper.md +770 -770
  6. package/agents/ez-context-manager.md +319 -0
  7. package/agents/ez-debugger.md +1255 -1255
  8. package/agents/ez-design-expert.md +347 -0
  9. package/agents/ez-devops-agent.md +331 -0
  10. package/agents/ez-executor.md +487 -487
  11. package/agents/ez-frontend-agent.md +322 -0
  12. package/agents/ez-phase-researcher.md +553 -553
  13. package/agents/ez-planner.md +1307 -1307
  14. package/agents/ez-product-engineer.md +435 -0
  15. package/agents/ez-project-researcher.md +629 -629
  16. package/agents/ez-qa-agent.md +320 -0
  17. package/agents/ez-release-agent.md +333 -0
  18. package/agents/ez-requirements-agent.md +377 -0
  19. package/agents/ez-roadmapper.md +650 -650
  20. package/agents/ez-technical-writer.md +551 -0
  21. package/agents/ez-ux-expert.md +393 -0
  22. package/agents/ez-verifier.md +579 -579
  23. package/bin/guards/autonomy-guard.cjs +346 -0
  24. package/bin/guards/context-budget-guard.cjs +278 -0
  25. package/bin/guards/hallucination-guard.cjs +380 -0
  26. package/bin/guards/hidden-state-guard.cjs +182 -0
  27. package/bin/guards/team-overhead-guard.cjs +266 -0
  28. package/bin/guards/tool-sprawl-guard.cjs +271 -0
  29. package/bin/install.js +3221 -3272
  30. package/bin/lib/analytics/analytics-collector.cjs +86 -0
  31. package/bin/lib/analytics/analytics-reporter.cjs +130 -0
  32. package/bin/lib/analytics/cohort-analyzer.cjs +138 -0
  33. package/bin/lib/analytics/funnel-analyzer.cjs +147 -0
  34. package/bin/lib/analytics/nps-tracker.cjs +147 -0
  35. package/bin/lib/archetype-detector.cjs +289 -0
  36. package/bin/lib/assistant-adapter.cjs +361 -0
  37. package/bin/lib/audit-exec.cjs +175 -0
  38. package/bin/lib/auth.cjs +176 -0
  39. package/bin/lib/backup-service.cjs +422 -0
  40. package/bin/lib/bdd-validator.cjs +622 -0
  41. package/bin/lib/business-flow-mapper.cjs +429 -0
  42. package/bin/lib/circuit-breaker.cjs +276 -0
  43. package/bin/lib/code-complexity-analyzer.cjs +360 -0
  44. package/bin/lib/codebase-analyzer.cjs +241 -0
  45. package/bin/lib/commands.cjs +691 -0
  46. package/bin/lib/config.cjs +236 -0
  47. package/bin/lib/constraint-extractor.cjs +526 -0
  48. package/bin/lib/content-scanner.cjs +238 -0
  49. package/bin/lib/context-cache.cjs +154 -0
  50. package/bin/lib/context-compressor.cjs +102 -0
  51. package/bin/lib/context-deduplicator.cjs +105 -0
  52. package/bin/lib/context-errors.cjs +78 -0
  53. package/bin/lib/context-manager.cjs +338 -0
  54. package/bin/lib/context-metadata-tracker.cjs +140 -0
  55. package/bin/lib/context-relevance-scorer.cjs +99 -0
  56. package/bin/lib/core.cjs +507 -0
  57. package/bin/lib/cost-alerts.cjs +174 -0
  58. package/bin/lib/cost-tracker.cjs +275 -0
  59. package/bin/lib/crash-recovery.cjs +220 -0
  60. package/bin/lib/dependency-graph.cjs +319 -0
  61. package/bin/lib/deploy/deploy-audit-log.cjs +76 -0
  62. package/bin/lib/deploy/deploy-detector.cjs +69 -0
  63. package/bin/lib/deploy/deploy-env-manager.cjs +109 -0
  64. package/bin/lib/deploy/deploy-health-check.cjs +88 -0
  65. package/bin/lib/deploy/deploy-pre-flight.cjs +57 -0
  66. package/bin/lib/deploy/deploy-rollback.cjs +72 -0
  67. package/bin/lib/deploy/deploy-runner.cjs +97 -0
  68. package/bin/lib/deploy/deploy-status.cjs +74 -0
  69. package/bin/lib/discussion-synthesizer.cjs +439 -0
  70. package/bin/lib/error-cache.cjs +114 -0
  71. package/bin/lib/error-registry.cjs +177 -0
  72. package/bin/lib/file-access.cjs +207 -0
  73. package/bin/lib/file-lock.cjs +236 -0
  74. package/bin/lib/finops/budget-enforcer.cjs +126 -0
  75. package/bin/lib/finops/cost-reporter.cjs +132 -0
  76. package/bin/lib/finops/finops-analyzer.cjs +112 -0
  77. package/bin/lib/finops/spot-manager.cjs +118 -0
  78. package/bin/lib/framework-detector.cjs +396 -0
  79. package/bin/lib/frontmatter.cjs +313 -0
  80. package/bin/lib/fs-utils.cjs +153 -0
  81. package/bin/lib/gate-executor.cjs +272 -0
  82. package/bin/lib/gates/README.md +374 -0
  83. package/bin/lib/gates/gate-01-requirement.cjs +303 -0
  84. package/bin/lib/gates/gate-02-architecture.cjs +555 -0
  85. package/bin/lib/gates/gate-03-code.cjs +635 -0
  86. package/bin/lib/gates/gate-04-security.cjs +829 -0
  87. package/bin/lib/git-errors.cjs +83 -0
  88. package/bin/lib/git-utils.cjs +321 -0
  89. package/bin/lib/git-workflow-engine.cjs +1157 -0
  90. package/bin/lib/health-check.cjs +227 -0
  91. package/bin/lib/index.cjs +279 -0
  92. package/bin/lib/init.cjs +725 -0
  93. package/bin/lib/lock-logger.cjs +194 -0
  94. package/bin/lib/lock-state.cjs +263 -0
  95. package/bin/lib/lockfile-validator.cjs +227 -0
  96. package/bin/lib/log-rotation.cjs +71 -0
  97. package/bin/lib/logger.cjs +125 -0
  98. package/bin/lib/memory-compression.cjs +256 -0
  99. package/bin/lib/milestone.cjs +247 -0
  100. package/bin/lib/model-provider.cjs +241 -0
  101. package/bin/lib/package-manager-detector.cjs +203 -0
  102. package/bin/lib/package-manager-executor.cjs +385 -0
  103. package/bin/lib/package-manager-service.cjs +216 -0
  104. package/bin/lib/perf/api-monitor.cjs +88 -0
  105. package/bin/lib/perf/db-optimizer.cjs +78 -0
  106. package/bin/lib/perf/frontend-performance.cjs +56 -0
  107. package/bin/lib/perf/perf-analyzer.cjs +77 -0
  108. package/bin/lib/perf/perf-baseline.cjs +102 -0
  109. package/bin/lib/perf/perf-reporter.cjs +117 -0
  110. package/bin/lib/perf/regression-detector.cjs +92 -0
  111. package/bin/lib/phase.cjs +963 -0
  112. package/bin/lib/planning-write.cjs +123 -0
  113. package/bin/lib/project-reporter.cjs +565 -0
  114. package/bin/lib/quality-gate.cjs +332 -0
  115. package/bin/lib/quality-metrics.cjs +324 -0
  116. package/bin/lib/recovery-manager.cjs +98 -0
  117. package/bin/lib/release-validator.cjs +617 -0
  118. package/bin/lib/retry.cjs +119 -0
  119. package/bin/lib/roadmap.cjs +309 -0
  120. package/bin/lib/safe-exec.cjs +173 -0
  121. package/bin/lib/safe-path.cjs +130 -0
  122. package/bin/lib/security-errors.cjs +62 -0
  123. package/bin/lib/session-chain.cjs +304 -0
  124. package/bin/lib/session-errors.cjs +81 -0
  125. package/bin/lib/session-export.cjs +251 -0
  126. package/bin/lib/session-import.cjs +262 -0
  127. package/bin/lib/session-manager.cjs +280 -0
  128. package/bin/lib/skill-context.cjs +148 -0
  129. package/bin/lib/skill-matcher.cjs +236 -0
  130. package/bin/lib/skill-registry.cjs +360 -0
  131. package/bin/lib/skill-resolver.cjs +449 -0
  132. package/bin/lib/skill-triggers.cjs +90 -0
  133. package/bin/lib/skill-validator.cjs +270 -0
  134. package/bin/lib/skill-versioning.cjs +355 -0
  135. package/bin/lib/stack-detector.cjs +399 -0
  136. package/bin/lib/state.cjs +736 -0
  137. package/bin/lib/tech-debt-analyzer.cjs +309 -0
  138. package/bin/lib/temp-file.cjs +239 -0
  139. package/bin/lib/template.cjs +223 -0
  140. package/bin/lib/test-file-lock.cjs +112 -0
  141. package/bin/lib/test-graceful.cjs +93 -0
  142. package/bin/lib/test-logger.cjs +60 -0
  143. package/bin/lib/test-safe-exec.cjs +38 -0
  144. package/bin/lib/test-safe-path.cjs +33 -0
  145. package/bin/lib/test-temp-file.cjs +125 -0
  146. package/bin/lib/tier-manager.cjs +428 -0
  147. package/bin/lib/timeout-exec.cjs +63 -0
  148. package/bin/lib/tradeoff-analyzer.cjs +284 -0
  149. package/bin/lib/url-fetch.cjs +170 -0
  150. package/bin/lib/verify.cjs +863 -0
  151. package/bin/update.js +217 -214
  152. package/commands/deploy.cjs +53 -0
  153. package/commands/ez/add-tests.md +41 -41
  154. package/commands/ez/audit-milestone.md +36 -36
  155. package/commands/ez/complete-milestone.md +136 -136
  156. package/commands/ez/discuss-phase.md +90 -90
  157. package/commands/ez/execute-phase.md +52 -41
  158. package/commands/ez/help.md +22 -22
  159. package/commands/ez/map-codebase.md +71 -71
  160. package/commands/ez/new-milestone.md +44 -44
  161. package/commands/ez/new-project.md +51 -42
  162. package/commands/ez/plan-phase.md +53 -45
  163. package/commands/ez/progress.md +36 -24
  164. package/commands/ez/quick.md +45 -45
  165. package/commands/ez/resume-work.md +40 -40
  166. package/commands/ez/run-phase.md +580 -0
  167. package/commands/ez/settings.md +36 -36
  168. package/commands/ez/update.md +37 -37
  169. package/commands/ez/verify-work.md +402 -38
  170. package/commands/health-check.cjs +44 -0
  171. package/commands/rollback.cjs +47 -0
  172. package/ez-agents/bin/ez-tools.cjs +1692 -716
  173. package/ez-agents/bin/guards/autonomy-guard.cjs +346 -0
  174. package/ez-agents/bin/guards/context-budget-guard.cjs +247 -0
  175. package/ez-agents/bin/guards/hallucination-guard.cjs +271 -0
  176. package/ez-agents/bin/guards/hidden-state-guard.cjs +182 -0
  177. package/ez-agents/bin/guards/team-overhead-guard.cjs +266 -0
  178. package/ez-agents/bin/guards/tool-sprawl-guard.cjs +271 -0
  179. package/ez-agents/bin/lib/analytics/analytics-collector.cjs +86 -0
  180. package/ez-agents/bin/lib/analytics/analytics-reporter.cjs +130 -0
  181. package/ez-agents/bin/lib/analytics/cohort-analyzer.cjs +138 -0
  182. package/ez-agents/bin/lib/analytics/funnel-analyzer.cjs +147 -0
  183. package/ez-agents/bin/lib/analytics/nps-tracker.cjs +147 -0
  184. package/ez-agents/bin/lib/archetype-detector.cjs +289 -0
  185. package/ez-agents/bin/lib/audit-exec.cjs +166 -167
  186. package/ez-agents/bin/lib/auth.cjs +176 -176
  187. package/ez-agents/bin/lib/backup-service.cjs +422 -0
  188. package/ez-agents/bin/lib/bdd-validator.cjs +622 -0
  189. package/ez-agents/bin/lib/business-flow-mapper.cjs +429 -0
  190. package/ez-agents/bin/lib/code-complexity-analyzer.cjs +360 -0
  191. package/ez-agents/bin/lib/codebase-analyzer.cjs +241 -0
  192. package/ez-agents/bin/lib/commands.cjs +685 -685
  193. package/ez-agents/bin/lib/config.cjs +41 -1
  194. package/ez-agents/bin/lib/constraint-extractor.cjs +526 -0
  195. package/ez-agents/bin/lib/content-scanner.cjs +238 -0
  196. package/ez-agents/bin/lib/context-cache.cjs +154 -0
  197. package/ez-agents/bin/lib/context-errors.cjs +71 -0
  198. package/ez-agents/bin/lib/context-manager.cjs +220 -0
  199. package/ez-agents/bin/lib/core.cjs +507 -512
  200. package/ez-agents/bin/lib/cost-tracker.cjs +243 -0
  201. package/ez-agents/bin/lib/crash-recovery.cjs +172 -0
  202. package/ez-agents/bin/lib/dependency-graph.cjs +319 -0
  203. package/ez-agents/bin/lib/deploy/deploy-audit-log.cjs +76 -0
  204. package/ez-agents/bin/lib/deploy/deploy-detector.cjs +69 -0
  205. package/ez-agents/bin/lib/deploy/deploy-env-manager.cjs +109 -0
  206. package/ez-agents/bin/lib/deploy/deploy-health-check.cjs +88 -0
  207. package/ez-agents/bin/lib/deploy/deploy-pre-flight.cjs +57 -0
  208. package/ez-agents/bin/lib/deploy/deploy-rollback.cjs +72 -0
  209. package/ez-agents/bin/lib/deploy/deploy-runner.cjs +97 -0
  210. package/ez-agents/bin/lib/deploy/deploy-status.cjs +74 -0
  211. package/ez-agents/bin/lib/discussion-synthesizer.cjs +458 -0
  212. package/ez-agents/bin/lib/file-access.cjs +207 -0
  213. package/ez-agents/bin/lib/finops/budget-enforcer.cjs +126 -0
  214. package/ez-agents/bin/lib/finops/cost-reporter.cjs +132 -0
  215. package/ez-agents/bin/lib/finops/finops-analyzer.cjs +112 -0
  216. package/ez-agents/bin/lib/finops/spot-manager.cjs +118 -0
  217. package/ez-agents/bin/lib/framework-detector.cjs +396 -0
  218. package/ez-agents/bin/lib/frontmatter.cjs +3 -1
  219. package/ez-agents/bin/lib/gates/README.md +374 -0
  220. package/ez-agents/bin/lib/gates/gate-01-requirement.cjs +303 -0
  221. package/ez-agents/bin/lib/gates/gate-02-architecture.cjs +555 -0
  222. package/ez-agents/bin/lib/gates/gate-03-code.cjs +635 -0
  223. package/ez-agents/bin/lib/gates/gate-04-security.cjs +829 -0
  224. package/ez-agents/bin/lib/git-errors.cjs +83 -0
  225. package/ez-agents/bin/lib/git-utils.cjs +118 -0
  226. package/ez-agents/bin/lib/git-workflow-engine.cjs +1157 -0
  227. package/ez-agents/bin/lib/health-check.cjs +162 -162
  228. package/ez-agents/bin/lib/index.cjs +40 -2
  229. package/ez-agents/bin/lib/init.cjs +0 -2
  230. package/ez-agents/bin/lib/lockfile-validator.cjs +227 -0
  231. package/ez-agents/bin/lib/log-rotation.cjs +71 -0
  232. package/ez-agents/bin/lib/logger.cjs +99 -154
  233. package/ez-agents/bin/lib/memory-compression.cjs +256 -0
  234. package/ez-agents/bin/lib/package-manager-detector.cjs +203 -0
  235. package/ez-agents/bin/lib/package-manager-executor.cjs +385 -0
  236. package/ez-agents/bin/lib/package-manager-service.cjs +216 -0
  237. package/ez-agents/bin/lib/perf/api-monitor.cjs +88 -0
  238. package/ez-agents/bin/lib/perf/db-optimizer.cjs +78 -0
  239. package/ez-agents/bin/lib/perf/frontend-performance.cjs +56 -0
  240. package/ez-agents/bin/lib/perf/perf-analyzer.cjs +77 -0
  241. package/ez-agents/bin/lib/perf/perf-baseline.cjs +102 -0
  242. package/ez-agents/bin/lib/perf/perf-reporter.cjs +117 -0
  243. package/ez-agents/bin/lib/perf/regression-detector.cjs +92 -0
  244. package/ez-agents/bin/lib/project-reporter.cjs +502 -0
  245. package/ez-agents/bin/lib/quality-gate.cjs +332 -0
  246. package/ez-agents/bin/lib/recovery-manager.cjs +98 -0
  247. package/ez-agents/bin/lib/release-validator.cjs +617 -0
  248. package/ez-agents/bin/lib/safe-exec.cjs +128 -214
  249. package/ez-agents/bin/lib/security-errors.cjs +62 -0
  250. package/ez-agents/bin/lib/session-chain.cjs +304 -0
  251. package/ez-agents/bin/lib/session-errors.cjs +81 -0
  252. package/ez-agents/bin/lib/session-export.cjs +251 -0
  253. package/ez-agents/bin/lib/session-import.cjs +262 -0
  254. package/ez-agents/bin/lib/session-manager.cjs +280 -0
  255. package/ez-agents/bin/lib/skill-context.cjs +148 -0
  256. package/ez-agents/bin/lib/skill-matcher.cjs +236 -0
  257. package/ez-agents/bin/lib/skill-registry.cjs +341 -0
  258. package/ez-agents/bin/lib/skill-resolver.cjs +449 -0
  259. package/ez-agents/bin/lib/skill-triggers.cjs +90 -0
  260. package/ez-agents/bin/lib/skill-validator.cjs +270 -0
  261. package/ez-agents/bin/lib/skill-versioning.cjs +355 -0
  262. package/ez-agents/bin/lib/stack-detector.cjs +399 -0
  263. package/ez-agents/bin/lib/tech-debt-analyzer.cjs +309 -0
  264. package/ez-agents/bin/lib/tier-manager.cjs +428 -0
  265. package/ez-agents/bin/lib/tradeoff-analyzer.cjs +284 -0
  266. package/ez-agents/bin/lib/url-fetch.cjs +170 -0
  267. package/ez-agents/bin/lib/verify.cjs +863 -863
  268. package/ez-agents/references/decimal-phase-calculation.md +65 -65
  269. package/ez-agents/references/git-integration.md +248 -248
  270. package/ez-agents/references/git-planning-commit.md +38 -38
  271. package/ez-agents/references/metrics-schema.md +118 -0
  272. package/ez-agents/references/model-profile-resolution.md +34 -34
  273. package/ez-agents/references/model-profiles.md +93 -93
  274. package/ez-agents/references/phase-argument-parsing.md +61 -61
  275. package/ez-agents/references/planning-config.md +340 -200
  276. package/ez-agents/references/tier-strategy.md +103 -0
  277. package/ez-agents/references/ui-brand.md +160 -160
  278. package/ez-agents/references/verification-patterns.md +612 -612
  279. package/ez-agents/templates/DEBUG.md +164 -164
  280. package/ez-agents/templates/UAT.md +247 -247
  281. package/ez-agents/templates/agent-output-format.md +404 -0
  282. package/ez-agents/templates/bdd-feature.md +173 -0
  283. package/ez-agents/templates/codebase/architecture.md +255 -255
  284. package/ez-agents/templates/codebase/structure.md +285 -285
  285. package/ez-agents/templates/copilot-instructions.md +7 -7
  286. package/ez-agents/templates/debug-subagent-prompt.md +91 -91
  287. package/ez-agents/templates/discovery.md +146 -146
  288. package/ez-agents/templates/discussion.md +68 -0
  289. package/ez-agents/templates/handoff-protocol.md +294 -0
  290. package/ez-agents/templates/incident-runbook.md +205 -0
  291. package/ez-agents/templates/mode-workflow-templates.md +301 -0
  292. package/ez-agents/templates/phase-prompt.md +610 -610
  293. package/ez-agents/templates/planner-subagent-prompt.md +117 -117
  294. package/ez-agents/templates/project.md +184 -184
  295. package/ez-agents/templates/release-checklist.md +136 -0
  296. package/ez-agents/templates/research.md +552 -552
  297. package/ez-agents/templates/rollback-plan.md +201 -0
  298. package/ez-agents/templates/security-user-setup.md +244 -0
  299. package/ez-agents/templates/skill-validation-rules.md +476 -0
  300. package/ez-agents/templates/state.md +180 -176
  301. package/ez-agents/templates/summary-complex.md +59 -59
  302. package/ez-agents/tests/gates/gate-01-02.test.cjs +812 -0
  303. package/ez-agents/tests/gates/gate-03-04.test.cjs +762 -0
  304. package/ez-agents/tests/gates/gate-05-validator.test.cjs +145 -0
  305. package/ez-agents/tests/gates/gate-06-docs-validator.test.cjs +244 -0
  306. package/ez-agents/tests/gates/gate-07-release-validator.test.cjs +219 -0
  307. package/ez-agents/tests/guards/context-budget-guard.test.cjs +145 -0
  308. package/ez-agents/tests/guards/edge-case-guards.test.cjs +238 -0
  309. package/ez-agents/tests/guards/hallucination-guard.test.cjs +124 -0
  310. package/ez-agents/workflows/audit-milestone.md +1 -1
  311. package/ez-agents/workflows/autonomous.md +131 -30
  312. package/ez-agents/workflows/complete-milestone.md +1 -1
  313. package/ez-agents/workflows/discuss-phase.md +1 -1
  314. package/ez-agents/workflows/execute-phase.md +169 -3
  315. package/ez-agents/workflows/help.md +86 -133
  316. package/ez-agents/workflows/hotfix.md +291 -0
  317. package/ez-agents/workflows/new-milestone.md +340 -11
  318. package/ez-agents/workflows/new-project.md +294 -318
  319. package/ez-agents/workflows/plan-phase.md +22 -40
  320. package/ez-agents/workflows/progress.md +15 -25
  321. package/ez-agents/workflows/release.md +253 -0
  322. package/ez-agents/workflows/resume-session.md +215 -0
  323. package/ez-agents/workflows/run-phase.md +531 -0
  324. package/ez-agents/workflows/settings.md +2 -35
  325. package/hooks/dist/ez-check-update.js +81 -81
  326. package/hooks/dist/ez-context-monitor.js +148 -141
  327. package/hooks/dist/ez-statusline.js +115 -115
  328. package/package.json +78 -64
  329. package/scripts/fix-qwen-installation.js +144 -144
  330. package/agents/ez-integration-checker.md +0 -443
  331. package/agents/ez-nyquist-auditor.md +0 -176
  332. package/agents/ez-plan-checker.md +0 -706
  333. package/agents/ez-research-synthesizer.md +0 -247
  334. package/agents/ez-ui-auditor.md +0 -439
  335. package/agents/ez-ui-checker.md +0 -300
  336. package/agents/ez-ui-researcher.md +0 -353
  337. package/commands/ez/add-phase.md +0 -43
  338. package/commands/ez/add-todo.md +0 -47
  339. package/commands/ez/auth.md +0 -87
  340. package/commands/ez/autonomous.md +0 -41
  341. package/commands/ez/check-todos.md +0 -45
  342. package/commands/ez/cleanup.md +0 -18
  343. package/commands/ez/debug.md +0 -168
  344. package/commands/ez/health.md +0 -22
  345. package/commands/ez/insert-phase.md +0 -32
  346. package/commands/ez/join-discord.md +0 -18
  347. package/commands/ez/list-phase-assumptions.md +0 -46
  348. package/commands/ez/pause-work.md +0 -38
  349. package/commands/ez/plan-milestone-gaps.md +0 -34
  350. package/commands/ez/reapply-patches.md +0 -124
  351. package/commands/ez/remove-phase.md +0 -31
  352. package/commands/ez/research-phase.md +0 -190
  353. package/commands/ez/set-profile.md +0 -34
  354. package/commands/ez/stats.md +0 -18
  355. package/commands/ez/ui-phase.md +0 -34
  356. package/commands/ez/ui-review.md +0 -32
  357. package/commands/ez/validate-phase.md +0 -35
  358. package/ez-agents/templates/UI-SPEC.md +0 -100
  359. package/ez-agents/templates/VALIDATION.md +0 -76
  360. package/ez-agents/templates/context.md +0 -352
  361. package/ez-agents/templates/verification-report.md +0 -322
  362. package/ez-agents/workflows/research-phase.md +0 -74
  363. package/ez-agents/workflows/ui-phase.md +0 -290
  364. package/ez-agents/workflows/ui-review.md +0 -157
  365. package/ez-agents/workflows/validate-phase.md +0 -167
@@ -0,0 +1,963 @@
1
+ /**
2
+ * Phase — Phase CRUD, query, and lifecycle operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, toPosixPath, output, error } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+ const { writeStateMd } = require('./state.cjs');
10
+ const { safePlanningWriteSync } = require('./planning-write.cjs');
11
+ const { defaultLogger: logger } = require('./logger.cjs');
12
+ const { TaskGraph } = require('./task-graph.cjs');
13
+
14
+ function cmdPhasesList(cwd, options, raw) {
15
+ const phasesDir = path.join(cwd, '.planning', 'phases');
16
+ const { type, phase, includeArchived } = options;
17
+
18
+ // If no phases directory, return empty
19
+ if (!fs.existsSync(phasesDir)) {
20
+ if (type) {
21
+ output({ files: [], count: 0 }, raw, '');
22
+ } else {
23
+ output({ directories: [], count: 0 }, raw, '');
24
+ }
25
+ return;
26
+ }
27
+
28
+ try {
29
+ // Get all phase directories
30
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
31
+ let dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
32
+
33
+ // Include archived phases if requested
34
+ if (includeArchived) {
35
+ const archived = getArchivedPhaseDirs(cwd);
36
+ for (const a of archived) {
37
+ dirs.push(`${a.name} [${a.milestone}]`);
38
+ }
39
+ }
40
+
41
+ // Sort numerically (handles integers, decimals, letter-suffix, hybrids)
42
+ dirs.sort((a, b) => comparePhaseNum(a, b));
43
+
44
+ // If filtering by phase number
45
+ if (phase) {
46
+ const normalized = normalizePhaseName(phase);
47
+ const match = dirs.find(d => d.startsWith(normalized));
48
+ if (!match) {
49
+ output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
50
+ return;
51
+ }
52
+ dirs = [match];
53
+ }
54
+
55
+ // If listing files of a specific type
56
+ if (type) {
57
+ const files = [];
58
+ for (const dir of dirs) {
59
+ const dirPath = path.join(phasesDir, dir);
60
+ const dirFiles = fs.readdirSync(dirPath);
61
+
62
+ let filtered;
63
+ if (type === 'plans') {
64
+ filtered = dirFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
65
+ } else if (type === 'summaries') {
66
+ filtered = dirFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
67
+ } else {
68
+ filtered = dirFiles;
69
+ }
70
+
71
+ files.push(...filtered.sort());
72
+ }
73
+
74
+ const result = {
75
+ files,
76
+ count: files.length,
77
+ phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
78
+ };
79
+ output(result, raw, files.join('\n'));
80
+ return;
81
+ }
82
+
83
+ // Default: list directories
84
+ output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
85
+ } catch (err) {
86
+ logger.error('Failed to list phases in cmdPhasesList', { error: err.message });
87
+ error('Failed to list phases: ' + err.message);
88
+ }
89
+ }
90
+
91
+ function cmdPhaseNextDecimal(cwd, basePhase, raw) {
92
+ const phasesDir = path.join(cwd, '.planning', 'phases');
93
+ const normalized = normalizePhaseName(basePhase);
94
+
95
+ // Check if phases directory exists
96
+ if (!fs.existsSync(phasesDir)) {
97
+ output(
98
+ {
99
+ found: false,
100
+ base_phase: normalized,
101
+ next: `${normalized}.1`,
102
+ existing: [],
103
+ },
104
+ raw,
105
+ `${normalized}.1`
106
+ );
107
+ return;
108
+ }
109
+
110
+ try {
111
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
112
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
113
+
114
+ // Check if base phase exists
115
+ const baseExists = dirs.some(d => d.startsWith(normalized + '-') || d === normalized);
116
+
117
+ // Find existing decimal phases for this base
118
+ const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
119
+ const existingDecimals = [];
120
+
121
+ for (const dir of dirs) {
122
+ const match = dir.match(decimalPattern);
123
+ if (match) {
124
+ existingDecimals.push(`${normalized}.${match[1]}`);
125
+ }
126
+ }
127
+
128
+ // Sort numerically
129
+ existingDecimals.sort((a, b) => comparePhaseNum(a, b));
130
+
131
+ // Calculate next decimal
132
+ let nextDecimal;
133
+ if (existingDecimals.length === 0) {
134
+ nextDecimal = `${normalized}.1`;
135
+ } else {
136
+ const lastDecimal = existingDecimals[existingDecimals.length - 1];
137
+ const lastNum = parseInt(lastDecimal.split('.')[1], 10);
138
+ nextDecimal = `${normalized}.${lastNum + 1}`;
139
+ }
140
+
141
+ output(
142
+ {
143
+ found: baseExists,
144
+ base_phase: normalized,
145
+ next: nextDecimal,
146
+ existing: existingDecimals,
147
+ },
148
+ raw,
149
+ nextDecimal
150
+ );
151
+ } catch (err) {
152
+ logger.error('Failed to calculate next decimal phase in cmdPhaseNextDecimal', { basePhase, error: err.message });
153
+ error('Failed to calculate next decimal phase: ' + err.message);
154
+ }
155
+ }
156
+
157
+ function cmdFindPhase(cwd, phase, raw) {
158
+ if (!phase) {
159
+ error('phase identifier required');
160
+ }
161
+
162
+ const phasesDir = path.join(cwd, '.planning', 'phases');
163
+ const normalized = normalizePhaseName(phase);
164
+
165
+ const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
166
+
167
+ try {
168
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
169
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
170
+
171
+ const match = dirs.find(d => d.startsWith(normalized));
172
+ if (!match) {
173
+ output(notFound, raw, '');
174
+ return;
175
+ }
176
+
177
+ const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
178
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
179
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
180
+
181
+ const phaseDir = path.join(phasesDir, match);
182
+ const phaseFiles = fs.readdirSync(phaseDir);
183
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
184
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
185
+
186
+ const result = {
187
+ found: true,
188
+ directory: toPosixPath(path.join('.planning', 'phases', match)),
189
+ phase_number: phaseNumber,
190
+ phase_name: phaseName,
191
+ plans,
192
+ summaries,
193
+ };
194
+
195
+ output(result, raw, result.directory);
196
+ } catch (err) {
197
+ logger.warn('Failed to read phases directory in cmdFindPhase', { phasesDir, error: err.message });
198
+ output(notFound, raw, '');
199
+ }
200
+ }
201
+
202
+ function extractObjective(content) {
203
+ const m = content.match(/<objective>\s*\n?\s*(.+)/);
204
+ return m ? m[1].trim() : null;
205
+ }
206
+
207
+ function cmdPhasePlanIndex(cwd, phase, raw) {
208
+ if (!phase) {
209
+ error('phase required for phase-plan-index');
210
+ }
211
+
212
+ const phasesDir = path.join(cwd, '.planning', 'phases');
213
+ const normalized = normalizePhaseName(phase);
214
+
215
+ // Find phase directory
216
+ let phaseDir = null;
217
+ let phaseDirName = null;
218
+ try {
219
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
220
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
221
+ const match = dirs.find(d => d.startsWith(normalized));
222
+ if (match) {
223
+ phaseDir = path.join(phasesDir, match);
224
+ phaseDirName = match;
225
+ }
226
+ } catch (err) {
227
+ logger.warn('Failed to enumerate phase directories in cmdPhasePlanIndex', { phasesDir, error: err.message });
228
+ }
229
+
230
+ if (!phaseDir) {
231
+ output({ phase: normalized, error: 'Phase not found', plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
232
+ return;
233
+ }
234
+
235
+ // Get all files in phase directory
236
+ const phaseFiles = fs.readdirSync(phaseDir);
237
+ const planFiles = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
238
+ const summaryFiles = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
239
+
240
+ // Build set of plan IDs with summaries
241
+ const completedPlanIds = new Set(
242
+ summaryFiles.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
243
+ );
244
+
245
+ const plans = [];
246
+ const waves = {};
247
+ const incomplete = [];
248
+ let hasCheckpoints = false;
249
+
250
+ // First pass: collect all plans with their dependencies
251
+ const planDataMap = new Map(); // Map planId to { fm, content, planFile }
252
+ for (const planFile of planFiles) {
253
+ const planId = planFile.replace('-PLAN.md', '').replace('PLAN.md', '');
254
+ const planPath = path.join(phaseDir, planFile);
255
+ const content = fs.readFileSync(planPath, 'utf-8');
256
+ const fm = extractFrontmatter(content);
257
+ planDataMap.set(planId, { fm, content, planFile, planPath });
258
+ }
259
+
260
+ // Build task array for TaskGraph with dependencies
261
+ const tasks = [];
262
+ for (const [planId, data] of planDataMap) {
263
+ const deps = data.fm.depends_on || [];
264
+ tasks.push({ id: planId, dependencies: Array.isArray(deps) ? deps : (deps ? [deps] : []) });
265
+ }
266
+
267
+ // Compute waves dynamically using TaskGraph
268
+ let waveAssignments;
269
+ try {
270
+ const taskGraph = new TaskGraph();
271
+ taskGraph.buildDAG(tasks);
272
+ waveAssignments = taskGraph.computeWaves();
273
+ } catch (err) {
274
+ logger.warn('Failed to compute waves, using static wave=1 for all plans', { error: err.message });
275
+ waveAssignments = [tasks.map(t => t.id)]; // Fallback: all plans in wave 1
276
+ }
277
+
278
+ // Build wave-to-planId map from computed waves
279
+ const waveToPlanIds = {};
280
+ const planToWave = {};
281
+ for (let i = 0; i < waveAssignments.length; i++) {
282
+ const waveNum = i + 1; // 1-indexed waves
283
+ waveToPlanIds[String(waveNum)] = waveAssignments[i];
284
+ for (const planId of waveAssignments[i]) {
285
+ planToWave[planId] = waveNum;
286
+ }
287
+ }
288
+
289
+ // Second pass: build plan objects with computed wave
290
+ for (const [planId, data] of planDataMap) {
291
+ const { fm, content } = data;
292
+
293
+ // Count tasks: XML <task> tags (canonical) or ## Task N markdown (legacy)
294
+ const xmlTasks = content.match(/<task[\s>]/gi) || [];
295
+ const mdTasks = content.match(/##\s*Task\s*\d+/gi) || [];
296
+ const taskCount = xmlTasks.length || mdTasks.length;
297
+
298
+ // Use dynamically computed wave
299
+ const wave = planToWave[planId] || 1;
300
+
301
+ // Parse autonomous (default true if not specified)
302
+ let autonomous = true;
303
+ if (fm.autonomous !== undefined) {
304
+ autonomous = fm.autonomous === 'true' || fm.autonomous === true;
305
+ }
306
+
307
+ if (!autonomous) {
308
+ hasCheckpoints = true;
309
+ }
310
+
311
+ // Parse files_modified (underscore is canonical; also accept hyphenated for compat)
312
+ let filesModified = [];
313
+ const fmFiles = fm['files_modified'] || fm['files-modified'];
314
+ if (fmFiles) {
315
+ filesModified = Array.isArray(fmFiles) ? fmFiles : [fmFiles];
316
+ }
317
+
318
+ const hasSummary = completedPlanIds.has(planId);
319
+ if (!hasSummary) {
320
+ incomplete.push(planId);
321
+ }
322
+
323
+ const plan = {
324
+ id: planId,
325
+ wave,
326
+ autonomous,
327
+ objective: extractObjective(content) || fm.objective || null,
328
+ files_modified: filesModified,
329
+ task_count: taskCount,
330
+ has_summary: hasSummary,
331
+ };
332
+
333
+ plans.push(plan);
334
+
335
+ // Group by wave
336
+ const waveKey = String(wave);
337
+ if (!waves[waveKey]) {
338
+ waves[waveKey] = [];
339
+ }
340
+ waves[waveKey].push(planId);
341
+ }
342
+
343
+ const result = {
344
+ phase: normalized,
345
+ plans,
346
+ waves,
347
+ incomplete,
348
+ has_checkpoints: hasCheckpoints,
349
+ };
350
+
351
+ output(result, raw);
352
+ }
353
+
354
+ function cmdPhaseAdd(cwd, description, raw) {
355
+ if (!description) {
356
+ error('description required for phase add');
357
+ }
358
+
359
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
360
+ if (!fs.existsSync(roadmapPath)) {
361
+ error('ROADMAP.md not found');
362
+ }
363
+
364
+ const content = fs.readFileSync(roadmapPath, 'utf-8');
365
+ const slug = generateSlugInternal(description);
366
+
367
+ // Find highest integer phase number
368
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
369
+ let maxPhase = 0;
370
+ let m;
371
+ while ((m = phasePattern.exec(content)) !== null) {
372
+ const num = parseInt(m[1], 10);
373
+ if (num > maxPhase) maxPhase = num;
374
+ }
375
+
376
+ const newPhaseNum = maxPhase + 1;
377
+ const paddedNum = String(newPhaseNum).padStart(2, '0');
378
+ const dirName = `${paddedNum}-${slug}`;
379
+ const dirPath = path.join(cwd, '.planning', 'phases', dirName);
380
+
381
+ // Create directory with .gitkeep so git tracks empty folders
382
+ fs.mkdirSync(dirPath, { recursive: true });
383
+ safePlanningWriteSync(path.join(dirPath, '.gitkeep'), '');
384
+
385
+ // Build phase entry
386
+ const phaseEntry = `\n### Phase ${newPhaseNum}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${maxPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /ez-plan-phase ${newPhaseNum} to break down)\n`;
387
+
388
+ // Find insertion point: before last "---" or at end
389
+ let updatedContent;
390
+ const lastSeparator = content.lastIndexOf('\n---');
391
+ if (lastSeparator > 0) {
392
+ updatedContent = content.slice(0, lastSeparator) + phaseEntry + content.slice(lastSeparator);
393
+ } else {
394
+ updatedContent = content + phaseEntry;
395
+ }
396
+
397
+ safePlanningWriteSync(roadmapPath, updatedContent);
398
+
399
+ const result = {
400
+ phase_number: newPhaseNum,
401
+ padded: paddedNum,
402
+ name: description,
403
+ slug,
404
+ directory: `.planning/phases/${dirName}`,
405
+ };
406
+
407
+ output(result, raw, paddedNum);
408
+ }
409
+
410
+ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
411
+ if (!afterPhase || !description) {
412
+ error('after-phase and description required for phase insert');
413
+ }
414
+
415
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
416
+ if (!fs.existsSync(roadmapPath)) {
417
+ error('ROADMAP.md not found');
418
+ }
419
+
420
+ const content = fs.readFileSync(roadmapPath, 'utf-8');
421
+ const slug = generateSlugInternal(description);
422
+
423
+ // Normalize input then strip leading zeros for flexible matching
424
+ const normalizedAfter = normalizePhaseName(afterPhase);
425
+ const unpadded = normalizedAfter.replace(/^0+/, '');
426
+ const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
427
+ const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
428
+ if (!targetPattern.test(content)) {
429
+ error(`Phase ${afterPhase} not found in ROADMAP.md`);
430
+ }
431
+
432
+ // Calculate next decimal using existing logic
433
+ const phasesDir = path.join(cwd, '.planning', 'phases');
434
+ const normalizedBase = normalizePhaseName(afterPhase);
435
+ let existingDecimals = [];
436
+
437
+ try {
438
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
439
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
440
+ const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
441
+ for (const dir of dirs) {
442
+ const dm = dir.match(decimalPattern);
443
+ if (dm) existingDecimals.push(parseInt(dm[1], 10));
444
+ }
445
+ } catch (err) {
446
+ logger.warn('Failed to enumerate decimal siblings in cmdPhaseInsert', { phasesDir, normalizedBase, error: err.message });
447
+ }
448
+
449
+ const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
450
+ const decimalPhase = `${normalizedBase}.${nextDecimal}`;
451
+ const dirName = `${decimalPhase}-${slug}`;
452
+ const dirPath = path.join(cwd, '.planning', 'phases', dirName);
453
+
454
+ // Create directory with .gitkeep so git tracks empty folders
455
+ fs.mkdirSync(dirPath, { recursive: true });
456
+ safePlanningWriteSync(path.join(dirPath, '.gitkeep'), '');
457
+
458
+ // Build phase entry
459
+ const phaseEntry = `\n### Phase ${decimalPhase}: ${description} (INSERTED)\n\n**Goal:** [Urgent work - to be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${afterPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /ez-plan-phase ${decimalPhase} to break down)\n`;
460
+
461
+ // Insert after the target phase section
462
+ const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
463
+ const headerMatch = content.match(headerPattern);
464
+ if (!headerMatch) {
465
+ error(`Could not find Phase ${afterPhase} header`);
466
+ }
467
+
468
+ const headerIdx = content.indexOf(headerMatch[0]);
469
+ const afterHeader = content.slice(headerIdx + headerMatch[0].length);
470
+ const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
471
+
472
+ let insertIdx;
473
+ if (nextPhaseMatch) {
474
+ insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
475
+ } else {
476
+ insertIdx = content.length;
477
+ }
478
+
479
+ const updatedContent = content.slice(0, insertIdx) + phaseEntry + content.slice(insertIdx);
480
+ safePlanningWriteSync(roadmapPath, updatedContent);
481
+
482
+ const result = {
483
+ phase_number: decimalPhase,
484
+ after_phase: afterPhase,
485
+ name: description,
486
+ slug,
487
+ directory: `.planning/phases/${dirName}`,
488
+ };
489
+
490
+ output(result, raw, decimalPhase);
491
+ }
492
+
493
+ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
494
+ if (!targetPhase) {
495
+ error('phase number required for phase remove');
496
+ }
497
+
498
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
499
+ const phasesDir = path.join(cwd, '.planning', 'phases');
500
+ const force = options.force || false;
501
+
502
+ if (!fs.existsSync(roadmapPath)) {
503
+ error('ROADMAP.md not found');
504
+ }
505
+
506
+ // Normalize the target
507
+ const normalized = normalizePhaseName(targetPhase);
508
+ const isDecimal = targetPhase.includes('.');
509
+
510
+ // Find and validate target directory
511
+ let targetDir = null;
512
+ try {
513
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
514
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
515
+ targetDir = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
516
+ } catch (err) {
517
+ logger.warn('Failed to locate target phase directory in cmdPhaseRemove', { phasesDir, normalized, error: err.message });
518
+ }
519
+
520
+ // Check for executed work (SUMMARY.md files)
521
+ if (targetDir && !force) {
522
+ const targetPath = path.join(phasesDir, targetDir);
523
+ const files = fs.readdirSync(targetPath);
524
+ const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
525
+ if (summaries.length > 0) {
526
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
527
+ }
528
+ }
529
+
530
+ // Delete target directory
531
+ if (targetDir) {
532
+ fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
533
+ }
534
+
535
+ // Renumber subsequent phases
536
+ const renamedDirs = [];
537
+ const renamedFiles = [];
538
+
539
+ if (isDecimal) {
540
+ // Decimal removal: renumber sibling decimals (e.g., removing 06.2 → 06.3 becomes 06.2)
541
+ const baseParts = normalized.split('.');
542
+ const baseInt = baseParts[0];
543
+ const removedDecimal = parseInt(baseParts[1], 10);
544
+
545
+ try {
546
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
547
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
548
+
549
+ // Find sibling decimals with higher numbers
550
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
551
+ const toRename = [];
552
+ for (const dir of dirs) {
553
+ const dm = dir.match(decPattern);
554
+ if (dm && parseInt(dm[1], 10) > removedDecimal) {
555
+ toRename.push({ dir, oldDecimal: parseInt(dm[1], 10), slug: dm[2] });
556
+ }
557
+ }
558
+
559
+ // Sort descending to avoid conflicts
560
+ toRename.sort((a, b) => b.oldDecimal - a.oldDecimal);
561
+
562
+ for (const item of toRename) {
563
+ const newDecimal = item.oldDecimal - 1;
564
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
565
+ const newPhaseId = `${baseInt}.${newDecimal}`;
566
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
567
+
568
+ // Rename directory
569
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
570
+ renamedDirs.push({ from: item.dir, to: newDirName });
571
+
572
+ // Rename files inside
573
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
574
+ for (const f of dirFiles) {
575
+ // Files may have phase prefix like "06.2-01-PLAN.md"
576
+ if (f.includes(oldPhaseId)) {
577
+ const newFileName = f.replace(oldPhaseId, newPhaseId);
578
+ fs.renameSync(
579
+ path.join(phasesDir, newDirName, f),
580
+ path.join(phasesDir, newDirName, newFileName)
581
+ );
582
+ renamedFiles.push({ from: f, to: newFileName });
583
+ }
584
+ }
585
+ }
586
+ } catch (err) {
587
+ logger.warn('Failed to renumber decimal phase directories in cmdPhaseRemove', { normalized, error: err.message });
588
+ }
589
+
590
+ } else {
591
+ // Integer removal: renumber all subsequent integer phases
592
+ const removedInt = parseInt(normalized, 10);
593
+
594
+ try {
595
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
596
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
597
+
598
+ // Collect directories that need renumbering (integer phases > removed, and their decimals/letters)
599
+ const toRename = [];
600
+ for (const dir of dirs) {
601
+ const dm = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
602
+ if (!dm) continue;
603
+ const dirInt = parseInt(dm[1], 10);
604
+ if (dirInt > removedInt) {
605
+ toRename.push({
606
+ dir,
607
+ oldInt: dirInt,
608
+ letter: dm[2] ? dm[2].toUpperCase() : '',
609
+ decimal: dm[3] ? parseInt(dm[3], 10) : null,
610
+ slug: dm[4],
611
+ });
612
+ }
613
+ }
614
+
615
+ // Sort descending to avoid conflicts
616
+ toRename.sort((a, b) => {
617
+ if (a.oldInt !== b.oldInt) return b.oldInt - a.oldInt;
618
+ return (b.decimal || 0) - (a.decimal || 0);
619
+ });
620
+
621
+ for (const item of toRename) {
622
+ const newInt = item.oldInt - 1;
623
+ const newPadded = String(newInt).padStart(2, '0');
624
+ const oldPadded = String(item.oldInt).padStart(2, '0');
625
+ const letterSuffix = item.letter || '';
626
+ const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
627
+ const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
628
+ const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
629
+ const newDirName = `${newPrefix}-${item.slug}`;
630
+
631
+ // Rename directory
632
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
633
+ renamedDirs.push({ from: item.dir, to: newDirName });
634
+
635
+ // Rename files inside
636
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
637
+ for (const f of dirFiles) {
638
+ if (f.startsWith(oldPrefix)) {
639
+ const newFileName = newPrefix + f.slice(oldPrefix.length);
640
+ fs.renameSync(
641
+ path.join(phasesDir, newDirName, f),
642
+ path.join(phasesDir, newDirName, newFileName)
643
+ );
644
+ renamedFiles.push({ from: f, to: newFileName });
645
+ }
646
+ }
647
+ }
648
+ } catch (err) {
649
+ logger.warn('Failed to renumber integer phase directories in cmdPhaseRemove', { normalized, error: err.message });
650
+ }
651
+ }
652
+
653
+ // Update ROADMAP.md
654
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
655
+
656
+ // Remove the target phase section
657
+ const targetEscaped = escapeRegex(targetPhase);
658
+ const sectionPattern = new RegExp(
659
+ `\\n?#{2,4}\\s*Phase\\s+${targetEscaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`,
660
+ 'i'
661
+ );
662
+ roadmapContent = roadmapContent.replace(sectionPattern, '');
663
+
664
+ // Remove from phase list (checkbox)
665
+ const checkboxPattern = new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${targetEscaped}[:\\s][^\\n]*`, 'gi');
666
+ roadmapContent = roadmapContent.replace(checkboxPattern, '');
667
+
668
+ // Remove from progress table
669
+ const tableRowPattern = new RegExp(`\\n?\\|\\s*${targetEscaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi');
670
+ roadmapContent = roadmapContent.replace(tableRowPattern, '');
671
+
672
+ // Renumber references in ROADMAP for subsequent phases
673
+ if (!isDecimal) {
674
+ const removedInt = parseInt(normalized, 10);
675
+
676
+ // Collect all integer phases > removedInt
677
+ const maxPhase = 99; // reasonable upper bound
678
+ for (let oldNum = maxPhase; oldNum > removedInt; oldNum--) {
679
+ const newNum = oldNum - 1;
680
+ const oldStr = String(oldNum);
681
+ const newStr = String(newNum);
682
+ const oldPad = oldStr.padStart(2, '0');
683
+ const newPad = newStr.padStart(2, '0');
684
+
685
+ // Phase headings: ## Phase 18: or ### Phase 18: → ## Phase 17: or ### Phase 17:
686
+ roadmapContent = roadmapContent.replace(
687
+ new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'),
688
+ `$1${newStr}$2`
689
+ );
690
+
691
+ // Checkbox items: - [ ] **Phase 18:** → - [ ] **Phase 17:**
692
+ roadmapContent = roadmapContent.replace(
693
+ new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'),
694
+ `$1${newStr}$2`
695
+ );
696
+
697
+ // Plan references: 18-01 → 17-01
698
+ roadmapContent = roadmapContent.replace(
699
+ new RegExp(`${oldPad}-(\\d{2})`, 'g'),
700
+ `${newPad}-$1`
701
+ );
702
+
703
+ // Table rows: | 18. → | 17.
704
+ roadmapContent = roadmapContent.replace(
705
+ new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'),
706
+ `$1${newStr}. `
707
+ );
708
+
709
+ // Depends on references
710
+ roadmapContent = roadmapContent.replace(
711
+ new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'),
712
+ `$1${newStr}`
713
+ );
714
+ }
715
+ }
716
+
717
+ safePlanningWriteSync(roadmapPath, roadmapContent);
718
+
719
+ // Update STATE.md phase count
720
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
721
+ if (fs.existsSync(statePath)) {
722
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
723
+ // Update "Total Phases" field
724
+ const totalPattern = /(\*\*Total Phases:\*\*\s*)(\d+)/;
725
+ const totalMatch = stateContent.match(totalPattern);
726
+ if (totalMatch) {
727
+ const oldTotal = parseInt(totalMatch[2], 10);
728
+ stateContent = stateContent.replace(totalPattern, `$1${oldTotal - 1}`);
729
+ }
730
+ // Update "Phase: X of Y" pattern
731
+ const ofPattern = /(\bof\s+)(\d+)(\s*(?:\(|phases?))/i;
732
+ const ofMatch = stateContent.match(ofPattern);
733
+ if (ofMatch) {
734
+ const oldTotal = parseInt(ofMatch[2], 10);
735
+ stateContent = stateContent.replace(ofPattern, `$1${oldTotal - 1}$3`);
736
+ }
737
+ writeStateMd(statePath, stateContent, cwd);
738
+ }
739
+
740
+ const result = {
741
+ removed: targetPhase,
742
+ directory_deleted: targetDir || null,
743
+ renamed_directories: renamedDirs,
744
+ renamed_files: renamedFiles,
745
+ roadmap_updated: true,
746
+ state_updated: fs.existsSync(statePath),
747
+ };
748
+
749
+ output(result, raw);
750
+ }
751
+
752
+ function cmdPhaseComplete(cwd, phaseNum, raw) {
753
+ if (!phaseNum) {
754
+ error('phase number required for phase complete');
755
+ }
756
+
757
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
758
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
759
+ const phasesDir = path.join(cwd, '.planning', 'phases');
760
+ const normalized = normalizePhaseName(phaseNum);
761
+ const today = new Date().toISOString().split('T')[0];
762
+
763
+ // Verify phase info
764
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
765
+ if (!phaseInfo) {
766
+ error(`Phase ${phaseNum} not found`);
767
+ }
768
+
769
+ const planCount = phaseInfo.plans.length;
770
+ const summaryCount = phaseInfo.summaries.length;
771
+ let requirementsUpdated = false;
772
+
773
+ // Update ROADMAP.md: mark phase complete
774
+ if (fs.existsSync(roadmapPath)) {
775
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
776
+
777
+ // Checkbox: - [ ] Phase N: → - [x] Phase N: (...completed DATE)
778
+ const checkboxPattern = new RegExp(
779
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
780
+ 'i'
781
+ );
782
+ roadmapContent = roadmapContent.replace(checkboxPattern, `$1x$2 (completed ${today})`);
783
+
784
+ // Progress table: update Status to Complete, add date
785
+ const phaseEscaped = escapeRegex(phaseNum);
786
+ const tablePattern = new RegExp(
787
+ `(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|[^|]*\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
788
+ 'i'
789
+ );
790
+ roadmapContent = roadmapContent.replace(
791
+ tablePattern,
792
+ `$1 Complete $2 ${today} $3`
793
+ );
794
+
795
+ // Update plan count in phase section
796
+ const planCountPattern = new RegExp(
797
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
798
+ 'i'
799
+ );
800
+ roadmapContent = roadmapContent.replace(
801
+ planCountPattern,
802
+ `$1${summaryCount}/${planCount} plans complete`
803
+ );
804
+
805
+ safePlanningWriteSync(roadmapPath, roadmapContent);
806
+
807
+ // Update REQUIREMENTS.md traceability for this phase's requirements
808
+ const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
809
+ if (fs.existsSync(reqPath)) {
810
+ // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
811
+ const phaseEsc = escapeRegex(phaseNum);
812
+ const phaseSectionMatch = roadmapContent.match(
813
+ new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
814
+ );
815
+
816
+ const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
817
+ const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
818
+
819
+ if (reqMatch) {
820
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
821
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
822
+
823
+ for (const reqId of reqIds) {
824
+ const reqEscaped = escapeRegex(reqId);
825
+ // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
826
+ reqContent = reqContent.replace(
827
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
828
+ '$1x$2'
829
+ );
830
+ // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | → | REQ-ID | Phase N | Complete |
831
+ reqContent = reqContent.replace(
832
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
833
+ '$1 Complete $2'
834
+ );
835
+ }
836
+
837
+ safePlanningWriteSync(reqPath, reqContent);
838
+ requirementsUpdated = true;
839
+ }
840
+ }
841
+ }
842
+
843
+ // Find next phase — check both filesystem AND roadmap
844
+ // Phases may be defined in ROADMAP.md but not yet scaffolded to disk,
845
+ // so a filesystem-only scan would incorrectly report is_last_phase:true
846
+ let nextPhaseNum = null;
847
+ let nextPhaseName = null;
848
+ let isLastPhase = true;
849
+
850
+ try {
851
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
852
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
853
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
854
+ .filter(isDirInMilestone)
855
+ .sort((a, b) => comparePhaseNum(a, b));
856
+
857
+ // Find the next phase directory after current
858
+ for (const dir of dirs) {
859
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
860
+ if (dm) {
861
+ if (comparePhaseNum(dm[1], phaseNum) > 0) {
862
+ nextPhaseNum = dm[1];
863
+ nextPhaseName = dm[2] || null;
864
+ isLastPhase = false;
865
+ break;
866
+ }
867
+ }
868
+ }
869
+ } catch (err) {
870
+ logger.warn('Failed to locate next phase from disk in cmdPhaseComplete', { phasesDir, phaseNum, error: err.message });
871
+ }
872
+
873
+ // Fallback: if filesystem found no next phase, check ROADMAP.md
874
+ // for phases that are defined but not yet planned (no directory on disk)
875
+ if (isLastPhase && fs.existsSync(roadmapPath)) {
876
+ try {
877
+ const roadmapForPhases = fs.readFileSync(roadmapPath, 'utf-8');
878
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
879
+ let pm;
880
+ while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
881
+ if (comparePhaseNum(pm[1], phaseNum) > 0) {
882
+ nextPhaseNum = pm[1];
883
+ nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
884
+ isLastPhase = false;
885
+ break;
886
+ }
887
+ }
888
+ } catch (err) {
889
+ logger.warn('Failed to locate next phase from ROADMAP fallback in cmdPhaseComplete', { roadmapPath, phaseNum, error: err.message });
890
+ }
891
+ }
892
+
893
+ // Update STATE.md
894
+ if (fs.existsSync(statePath)) {
895
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
896
+
897
+ // Update Current Phase
898
+ stateContent = stateContent.replace(
899
+ /(\*\*Current Phase:\*\*\s*).*/,
900
+ `$1${nextPhaseNum || phaseNum}`
901
+ );
902
+
903
+ // Update Current Phase Name
904
+ if (nextPhaseName) {
905
+ stateContent = stateContent.replace(
906
+ /(\*\*Current Phase Name:\*\*\s*).*/,
907
+ `$1${nextPhaseName.replace(/-/g, ' ')}`
908
+ );
909
+ }
910
+
911
+ // Update Status
912
+ stateContent = stateContent.replace(
913
+ /(\*\*Status:\*\*\s*).*/,
914
+ `$1${isLastPhase ? 'Milestone complete' : 'Ready to plan'}`
915
+ );
916
+
917
+ // Update Current Plan
918
+ stateContent = stateContent.replace(
919
+ /(\*\*Current Plan:\*\*\s*).*/,
920
+ `$1Not started`
921
+ );
922
+
923
+ // Update Last Activity
924
+ stateContent = stateContent.replace(
925
+ /(\*\*Last Activity:\*\*\s*).*/,
926
+ `$1${today}`
927
+ );
928
+
929
+ // Update Last Activity Description
930
+ stateContent = stateContent.replace(
931
+ /(\*\*Last Activity Description:\*\*\s*).*/,
932
+ `$1Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`
933
+ );
934
+
935
+ writeStateMd(statePath, stateContent, cwd);
936
+ }
937
+
938
+ const result = {
939
+ completed_phase: phaseNum,
940
+ phase_name: phaseInfo.phase_name,
941
+ plans_executed: `${summaryCount}/${planCount}`,
942
+ next_phase: nextPhaseNum,
943
+ next_phase_name: nextPhaseName,
944
+ is_last_phase: isLastPhase,
945
+ date: today,
946
+ roadmap_updated: fs.existsSync(roadmapPath),
947
+ state_updated: fs.existsSync(statePath),
948
+ requirements_updated: requirementsUpdated,
949
+ };
950
+
951
+ output(result, raw);
952
+ }
953
+
954
+ module.exports = {
955
+ cmdPhasesList,
956
+ cmdPhaseNextDecimal,
957
+ cmdFindPhase,
958
+ cmdPhasePlanIndex,
959
+ cmdPhaseAdd,
960
+ cmdPhaseInsert,
961
+ cmdPhaseRemove,
962
+ cmdPhaseComplete,
963
+ };