drt-method 1.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 (299) hide show
  1. package/AGENTS.md +45 -0
  2. package/GETTING-STARTED.md +269 -0
  3. package/README.md +233 -0
  4. package/drt-method-1.0.0.tgz +0 -0
  5. package/drt-modules.yaml +1 -0
  6. package/package.json +51 -0
  7. package/scripts/install-from-github.ps1 +22 -0
  8. package/scripts/install-from-github.sh +17 -0
  9. package/src/core-skills/drt-advanced-elicitation/SKILL.md +142 -0
  10. package/src/core-skills/drt-advanced-elicitation/methods.csv +72 -0
  11. package/src/core-skills/drt-brainstorming/SKILL.md +80 -0
  12. package/src/core-skills/drt-brainstorming/assets/brain-icons.json +166 -0
  13. package/src/core-skills/drt-brainstorming/assets/brain-methods.csv +109 -0
  14. package/src/core-skills/drt-brainstorming/assets/brain-selector.html +326 -0
  15. package/src/core-skills/drt-brainstorming/customize.toml +84 -0
  16. package/src/core-skills/drt-brainstorming/references/converge.md +24 -0
  17. package/src/core-skills/drt-brainstorming/references/finalize.md +26 -0
  18. package/src/core-skills/drt-brainstorming/references/headless.md +54 -0
  19. package/src/core-skills/drt-brainstorming/references/in-chat-techniques.md +18 -0
  20. package/src/core-skills/drt-brainstorming/references/mode-autonomous.md +10 -0
  21. package/src/core-skills/drt-brainstorming/references/mode-facilitator.md +11 -0
  22. package/src/core-skills/drt-brainstorming/references/mode-partner.md +16 -0
  23. package/src/core-skills/drt-brainstorming/references/resume.md +5 -0
  24. package/src/core-skills/drt-brainstorming/scripts/brain.py +740 -0
  25. package/src/core-skills/drt-customize/SKILL.md +111 -0
  26. package/src/core-skills/drt-customize/scripts/list_customizable_skills.py +231 -0
  27. package/src/core-skills/drt-editorial-review-prose/SKILL.md +86 -0
  28. package/src/core-skills/drt-editorial-review-structure/SKILL.md +179 -0
  29. package/src/core-skills/drt-forge-idea/SKILL.md +107 -0
  30. package/src/core-skills/drt-forge-idea/customize.toml +42 -0
  31. package/src/core-skills/drt-forge-idea/scripts/resolve_personas.py +270 -0
  32. package/src/core-skills/drt-help/SKILL.md +75 -0
  33. package/src/core-skills/drt-index-docs/SKILL.md +66 -0
  34. package/src/core-skills/drt-party-mode/SKILL.md +60 -0
  35. package/src/core-skills/drt-party-mode/customize.toml +211 -0
  36. package/src/core-skills/drt-party-mode/references/create-party.md +70 -0
  37. package/src/core-skills/drt-party-mode/references/mode-agent-team.md +13 -0
  38. package/src/core-skills/drt-party-mode/references/mode-auto.md +13 -0
  39. package/src/core-skills/drt-party-mode/references/mode-subagent.md +31 -0
  40. package/src/core-skills/drt-party-mode/references/party-memory.md +51 -0
  41. package/src/core-skills/drt-party-mode/scripts/resolve_party.py +272 -0
  42. package/src/core-skills/drt-review-adversarial-general/SKILL.md +37 -0
  43. package/src/core-skills/drt-review-edge-case-hunter/SKILL.md +73 -0
  44. package/src/core-skills/drt-review-edge-case-hunter/references/deletion-check.md +14 -0
  45. package/src/core-skills/drt-review-verification-gap/SKILL.md +106 -0
  46. package/src/core-skills/drt-shard-doc/SKILL.md +105 -0
  47. package/src/core-skills/drt-spec/SKILL.md +160 -0
  48. package/src/core-skills/drt-spec/assets/headless-schemas.md +33 -0
  49. package/src/core-skills/drt-spec/assets/spec-template.md +49 -0
  50. package/src/core-skills/drt-spec/assets/stories-schema.md +44 -0
  51. package/src/core-skills/drt-spec/customize.toml +53 -0
  52. package/src/core-skills/module-help.csv +14 -0
  53. package/src/core-skills/module.yaml +33 -0
  54. package/src/drt-skills/1-analysis/drt-agent-analyst/SKILL.md +76 -0
  55. package/src/drt-skills/1-analysis/drt-agent-analyst/customize.toml +90 -0
  56. package/src/drt-skills/1-analysis/drt-agent-tech-writer/SKILL.md +76 -0
  57. package/src/drt-skills/1-analysis/drt-agent-tech-writer/customize.toml +81 -0
  58. package/src/drt-skills/1-analysis/drt-agent-tech-writer/explain-concept.md +20 -0
  59. package/src/drt-skills/1-analysis/drt-agent-tech-writer/mermaid-gen.md +20 -0
  60. package/src/drt-skills/1-analysis/drt-agent-tech-writer/validate-doc.md +19 -0
  61. package/src/drt-skills/1-analysis/drt-agent-tech-writer/write-document.md +20 -0
  62. package/src/drt-skills/1-analysis/drt-document-project/SKILL.md +62 -0
  63. package/src/drt-skills/1-analysis/drt-document-project/checklist.md +245 -0
  64. package/src/drt-skills/1-analysis/drt-document-project/customize.toml +41 -0
  65. package/src/drt-skills/1-analysis/drt-document-project/documentation-requirements.csv +12 -0
  66. package/src/drt-skills/1-analysis/drt-document-project/instructions.md +128 -0
  67. package/src/drt-skills/1-analysis/drt-document-project/templates/deep-dive-template.md +345 -0
  68. package/src/drt-skills/1-analysis/drt-document-project/templates/index-template.md +169 -0
  69. package/src/drt-skills/1-analysis/drt-document-project/templates/project-overview-template.md +103 -0
  70. package/src/drt-skills/1-analysis/drt-document-project/templates/project-scan-report-schema.json +160 -0
  71. package/src/drt-skills/1-analysis/drt-document-project/templates/source-tree-template.md +135 -0
  72. package/src/drt-skills/1-analysis/drt-document-project/workflows/deep-dive-instructions.md +300 -0
  73. package/src/drt-skills/1-analysis/drt-document-project/workflows/deep-dive-workflow.md +34 -0
  74. package/src/drt-skills/1-analysis/drt-document-project/workflows/full-scan-instructions.md +1111 -0
  75. package/src/drt-skills/1-analysis/drt-document-project/workflows/full-scan-workflow.md +34 -0
  76. package/src/drt-skills/1-analysis/drt-prfaq/SKILL.md +135 -0
  77. package/src/drt-skills/1-analysis/drt-prfaq/agents/artifact-analyzer.md +60 -0
  78. package/src/drt-skills/1-analysis/drt-prfaq/agents/web-researcher.md +49 -0
  79. package/src/drt-skills/1-analysis/drt-prfaq/assets/prfaq-template.md +62 -0
  80. package/src/drt-skills/1-analysis/drt-prfaq/bmad-manifest.json +16 -0
  81. package/src/drt-skills/1-analysis/drt-prfaq/customize.toml +41 -0
  82. package/src/drt-skills/1-analysis/drt-prfaq/references/customer-faq.md +55 -0
  83. package/src/drt-skills/1-analysis/drt-prfaq/references/internal-faq.md +51 -0
  84. package/src/drt-skills/1-analysis/drt-prfaq/references/press-release.md +60 -0
  85. package/src/drt-skills/1-analysis/drt-prfaq/references/verdict.md +83 -0
  86. package/src/drt-skills/1-analysis/drt-product-brief/SKILL.md +91 -0
  87. package/src/drt-skills/1-analysis/drt-product-brief/assets/brief-template.md +41 -0
  88. package/src/drt-skills/1-analysis/drt-product-brief/customize.toml +99 -0
  89. package/src/drt-skills/1-analysis/research/drt-domain-research/SKILL.md +96 -0
  90. package/src/drt-skills/1-analysis/research/drt-domain-research/customize.toml +41 -0
  91. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-01-init.md +137 -0
  92. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-02-domain-analysis.md +229 -0
  93. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-03-competitive-landscape.md +238 -0
  94. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-04-regulatory-focus.md +206 -0
  95. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-05-technical-trends.md +234 -0
  96. package/src/drt-skills/1-analysis/research/drt-domain-research/domain-steps/step-06-research-synthesis.md +450 -0
  97. package/src/drt-skills/1-analysis/research/drt-domain-research/research.template.md +29 -0
  98. package/src/drt-skills/1-analysis/research/drt-market-research/SKILL.md +96 -0
  99. package/src/drt-skills/1-analysis/research/drt-market-research/customize.toml +41 -0
  100. package/src/drt-skills/1-analysis/research/drt-market-research/research.template.md +29 -0
  101. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-01-init.md +184 -0
  102. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-02-customer-behavior.md +239 -0
  103. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-03-customer-pain-points.md +251 -0
  104. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-04-customer-decisions.md +261 -0
  105. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-05-competitive-analysis.md +173 -0
  106. package/src/drt-skills/1-analysis/research/drt-market-research/steps/step-06-research-completion.md +484 -0
  107. package/src/drt-skills/1-analysis/research/drt-technical-research/SKILL.md +96 -0
  108. package/src/drt-skills/1-analysis/research/drt-technical-research/customize.toml +41 -0
  109. package/src/drt-skills/1-analysis/research/drt-technical-research/research.template.md +29 -0
  110. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-01-init.md +137 -0
  111. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-02-technical-overview.md +239 -0
  112. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-03-integration-patterns.md +248 -0
  113. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-04-architectural-patterns.md +202 -0
  114. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-05-implementation-research.md +233 -0
  115. package/src/drt-skills/1-analysis/research/drt-technical-research/technical-steps/step-06-research-synthesis.md +493 -0
  116. package/src/drt-skills/2-plan-workflows/drt-agent-pm/SKILL.md +76 -0
  117. package/src/drt-skills/2-plan-workflows/drt-agent-pm/customize.toml +75 -0
  118. package/src/drt-skills/2-plan-workflows/drt-agent-ux-designer/SKILL.md +76 -0
  119. package/src/drt-skills/2-plan-workflows/drt-agent-ux-designer/customize.toml +60 -0
  120. package/src/drt-skills/2-plan-workflows/drt-create-prd/SKILL.md +30 -0
  121. package/src/drt-skills/2-plan-workflows/drt-create-prd/customize.toml +41 -0
  122. package/src/drt-skills/2-plan-workflows/drt-edit-prd/SKILL.md +30 -0
  123. package/src/drt-skills/2-plan-workflows/drt-edit-prd/customize.toml +42 -0
  124. package/src/drt-skills/2-plan-workflows/drt-prd/SKILL.md +92 -0
  125. package/src/drt-skills/2-plan-workflows/drt-prd/assets/headless-schemas.md +76 -0
  126. package/src/drt-skills/2-plan-workflows/drt-prd/assets/prd-template.md +165 -0
  127. package/src/drt-skills/2-plan-workflows/drt-prd/assets/prd-validation-checklist.md +135 -0
  128. package/src/drt-skills/2-plan-workflows/drt-prd/assets/validation-report-template.html +325 -0
  129. package/src/drt-skills/2-plan-workflows/drt-prd/customize.toml +147 -0
  130. package/src/drt-skills/2-plan-workflows/drt-prd/references/headless.md +39 -0
  131. package/src/drt-skills/2-plan-workflows/drt-prd/references/validate.md +97 -0
  132. package/src/drt-skills/2-plan-workflows/drt-ux/SKILL.md +90 -0
  133. package/src/drt-skills/2-plan-workflows/drt-ux/assets/color-themes.md +9 -0
  134. package/src/drt-skills/2-plan-workflows/drt-ux/assets/design-directions.md +9 -0
  135. package/src/drt-skills/2-plan-workflows/drt-ux/assets/design-example-editorial.md +158 -0
  136. package/src/drt-skills/2-plan-workflows/drt-ux/assets/design-example-mobile.md +93 -0
  137. package/src/drt-skills/2-plan-workflows/drt-ux/assets/design-example-shadcn.md +109 -0
  138. package/src/drt-skills/2-plan-workflows/drt-ux/assets/excalidraw-wireframe.md +19 -0
  139. package/src/drt-skills/2-plan-workflows/drt-ux/assets/experience-example-mobile.md +112 -0
  140. package/src/drt-skills/2-plan-workflows/drt-ux/assets/experience-example-shadcn.md +133 -0
  141. package/src/drt-skills/2-plan-workflows/drt-ux/assets/headless-schemas.md +84 -0
  142. package/src/drt-skills/2-plan-workflows/drt-ux/assets/key-screens.md +29 -0
  143. package/src/drt-skills/2-plan-workflows/drt-ux/assets/validation-report-template.html +319 -0
  144. package/src/drt-skills/2-plan-workflows/drt-ux/customize.toml +100 -0
  145. package/src/drt-skills/2-plan-workflows/drt-ux/references/creative-tools.md +19 -0
  146. package/src/drt-skills/2-plan-workflows/drt-ux/references/design-md-spec.md +50 -0
  147. package/src/drt-skills/2-plan-workflows/drt-ux/references/headless.md +37 -0
  148. package/src/drt-skills/2-plan-workflows/drt-ux/references/validate.md +115 -0
  149. package/src/drt-skills/2-plan-workflows/drt-validate-prd/SKILL.md +30 -0
  150. package/src/drt-skills/2-plan-workflows/drt-validate-prd/customize.toml +42 -0
  151. package/src/drt-skills/3-solutioning/drt-agent-architect/SKILL.md +76 -0
  152. package/src/drt-skills/3-solutioning/drt-agent-architect/customize.toml +65 -0
  153. package/src/drt-skills/3-solutioning/drt-architecture/SKILL.md +85 -0
  154. package/src/drt-skills/3-solutioning/drt-architecture/assets/spine-template.md +79 -0
  155. package/src/drt-skills/3-solutioning/drt-architecture/customize.toml +100 -0
  156. package/src/drt-skills/3-solutioning/drt-architecture/references/headless.md +26 -0
  157. package/src/drt-skills/3-solutioning/drt-architecture/references/reviewer-gate.md +13 -0
  158. package/src/drt-skills/3-solutioning/drt-architecture/scripts/lint_spine.py +257 -0
  159. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/SKILL.md +91 -0
  160. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/customize.toml +41 -0
  161. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-01-document-discovery.md +179 -0
  162. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-02-prd-analysis.md +168 -0
  163. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-03-epic-coverage-validation.md +169 -0
  164. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-04-ux-alignment.md +129 -0
  165. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-05-epic-quality-review.md +241 -0
  166. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/steps/step-06-final-assessment.md +132 -0
  167. package/src/drt-skills/3-solutioning/drt-check-implementation-readiness/templates/readiness-report-template.md +4 -0
  168. package/src/drt-skills/3-solutioning/drt-create-architecture/SKILL.md +30 -0
  169. package/src/drt-skills/3-solutioning/drt-create-architecture/customize.toml +41 -0
  170. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/SKILL.md +93 -0
  171. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/customize.toml +41 -0
  172. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/steps/step-01-validate-prerequisites.md +263 -0
  173. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/steps/step-02-design-epics.md +242 -0
  174. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/steps/step-03-create-stories.md +255 -0
  175. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/steps/step-04-final-validation.md +143 -0
  176. package/src/drt-skills/3-solutioning/drt-create-epics-and-stories/templates/epics-template.md +61 -0
  177. package/src/drt-skills/3-solutioning/drt-generate-project-context/SKILL.md +81 -0
  178. package/src/drt-skills/3-solutioning/drt-generate-project-context/customize.toml +41 -0
  179. package/src/drt-skills/3-solutioning/drt-generate-project-context/project-context-template.md +21 -0
  180. package/src/drt-skills/3-solutioning/drt-generate-project-context/steps/step-01-discover.md +186 -0
  181. package/src/drt-skills/3-solutioning/drt-generate-project-context/steps/step-02-generate.md +321 -0
  182. package/src/drt-skills/3-solutioning/drt-generate-project-context/steps/step-03-complete.md +284 -0
  183. package/src/drt-skills/4-implementation/drt-agent-dev/SKILL.md +76 -0
  184. package/src/drt-skills/4-implementation/drt-agent-dev/customize.toml +95 -0
  185. package/src/drt-skills/4-implementation/drt-checkpoint-preview/SKILL.md +68 -0
  186. package/src/drt-skills/4-implementation/drt-checkpoint-preview/customize.toml +41 -0
  187. package/src/drt-skills/4-implementation/drt-checkpoint-preview/generate-trail.md +38 -0
  188. package/src/drt-skills/4-implementation/drt-checkpoint-preview/step-01-orientation.md +105 -0
  189. package/src/drt-skills/4-implementation/drt-checkpoint-preview/step-02-walkthrough.md +89 -0
  190. package/src/drt-skills/4-implementation/drt-checkpoint-preview/step-03-detail-pass.md +106 -0
  191. package/src/drt-skills/4-implementation/drt-checkpoint-preview/step-04-testing.md +74 -0
  192. package/src/drt-skills/4-implementation/drt-checkpoint-preview/step-05-wrapup.md +30 -0
  193. package/src/drt-skills/4-implementation/drt-code-review/SKILL.md +90 -0
  194. package/src/drt-skills/4-implementation/drt-code-review/customize.toml +93 -0
  195. package/src/drt-skills/4-implementation/drt-code-review/steps/step-01-gather-context.md +84 -0
  196. package/src/drt-skills/4-implementation/drt-code-review/steps/step-02-review.md +32 -0
  197. package/src/drt-skills/4-implementation/drt-code-review/steps/step-03-triage.md +50 -0
  198. package/src/drt-skills/4-implementation/drt-code-review/steps/step-04-present.md +132 -0
  199. package/src/drt-skills/4-implementation/drt-correct-course/SKILL.md +301 -0
  200. package/src/drt-skills/4-implementation/drt-correct-course/checklist.md +288 -0
  201. package/src/drt-skills/4-implementation/drt-correct-course/customize.toml +41 -0
  202. package/src/drt-skills/4-implementation/drt-create-story/SKILL.md +432 -0
  203. package/src/drt-skills/4-implementation/drt-create-story/checklist.md +357 -0
  204. package/src/drt-skills/4-implementation/drt-create-story/customize.toml +41 -0
  205. package/src/drt-skills/4-implementation/drt-create-story/discover-inputs.md +88 -0
  206. package/src/drt-skills/4-implementation/drt-create-story/template.md +49 -0
  207. package/src/drt-skills/4-implementation/drt-dev-auto/SKILL.md +123 -0
  208. package/src/drt-skills/4-implementation/drt-dev-auto/compile-epic-context.md +62 -0
  209. package/src/drt-skills/4-implementation/drt-dev-auto/customize.toml +108 -0
  210. package/src/drt-skills/4-implementation/drt-dev-auto/spec-template.md +98 -0
  211. package/src/drt-skills/4-implementation/drt-dev-auto/step-01-clarify-and-route.md +84 -0
  212. package/src/drt-skills/4-implementation/drt-dev-auto/step-02-plan.md +31 -0
  213. package/src/drt-skills/4-implementation/drt-dev-auto/step-03-implement.md +42 -0
  214. package/src/drt-skills/4-implementation/drt-dev-auto/step-04-review.md +95 -0
  215. package/src/drt-skills/4-implementation/drt-dev-story/SKILL.md +500 -0
  216. package/src/drt-skills/4-implementation/drt-dev-story/checklist.md +80 -0
  217. package/src/drt-skills/4-implementation/drt-dev-story/customize.toml +41 -0
  218. package/src/drt-skills/4-implementation/drt-implement-task/SKILL.md +101 -0
  219. package/src/drt-skills/4-implementation/drt-implement-task/assets/task-spec-template.md +60 -0
  220. package/src/drt-skills/4-implementation/drt-implement-task/customize.toml +17 -0
  221. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-01-gather-intent.md +42 -0
  222. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-02-plan-and-approve.md +43 -0
  223. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-03-confirm-dependencies.md +38 -0
  224. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-04-implement.md +42 -0
  225. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-05-qc-test.md +31 -0
  226. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-06-quality-review.md +30 -0
  227. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-07-fix-findings.md +33 -0
  228. package/src/drt-skills/4-implementation/drt-implement-task/steps/step-08-complete.md +35 -0
  229. package/src/drt-skills/4-implementation/drt-qa-generate-e2e-tests/SKILL.md +176 -0
  230. package/src/drt-skills/4-implementation/drt-qa-generate-e2e-tests/checklist.md +33 -0
  231. package/src/drt-skills/4-implementation/drt-qa-generate-e2e-tests/customize.toml +41 -0
  232. package/src/drt-skills/4-implementation/drt-quick-dev/SKILL.md +13 -0
  233. package/src/drt-skills/4-implementation/drt-quick-dev/compile-epic-context.md +62 -0
  234. package/src/drt-skills/4-implementation/drt-quick-dev/customize.toml +83 -0
  235. package/src/drt-skills/4-implementation/drt-quick-dev/render.js +206 -0
  236. package/src/drt-skills/4-implementation/drt-quick-dev/spec-template.md +89 -0
  237. package/src/drt-skills/4-implementation/drt-quick-dev/step-01-clarify-and-route.md +103 -0
  238. package/src/drt-skills/4-implementation/drt-quick-dev/step-02-plan.md +47 -0
  239. package/src/drt-skills/4-implementation/drt-quick-dev/step-03-implement.md +45 -0
  240. package/src/drt-skills/4-implementation/drt-quick-dev/step-04-review.md +55 -0
  241. package/src/drt-skills/4-implementation/drt-quick-dev/step-05-present.md +78 -0
  242. package/src/drt-skills/4-implementation/drt-quick-dev/step-oneshot.md +78 -0
  243. package/src/drt-skills/4-implementation/drt-quick-dev/sync-sprint-status.md +19 -0
  244. package/src/drt-skills/4-implementation/drt-quick-dev/workflow.md +85 -0
  245. package/src/drt-skills/4-implementation/drt-retrospective/SKILL.md +1527 -0
  246. package/src/drt-skills/4-implementation/drt-retrospective/customize.toml +41 -0
  247. package/src/drt-skills/4-implementation/drt-sprint-planning/SKILL.md +319 -0
  248. package/src/drt-skills/4-implementation/drt-sprint-planning/checklist.md +34 -0
  249. package/src/drt-skills/4-implementation/drt-sprint-planning/customize.toml +41 -0
  250. package/src/drt-skills/4-implementation/drt-sprint-planning/sprint-status-template.yaml +69 -0
  251. package/src/drt-skills/4-implementation/drt-sprint-status/SKILL.md +311 -0
  252. package/src/drt-skills/4-implementation/drt-sprint-status/customize.toml +41 -0
  253. package/src/drt-skills/module-help.csv +32 -0
  254. package/src/drt-skills/module.yaml +95 -0
  255. package/src/scripts/lib/load-toml.js +43 -0
  256. package/src/scripts/lib/merge-utils.js +89 -0
  257. package/src/scripts/memlog.js +184 -0
  258. package/src/scripts/package.json +7 -0
  259. package/src/scripts/resolve-config.js +56 -0
  260. package/src/scripts/resolve-customization.js +77 -0
  261. package/tools/installer/cli-utils.js +53 -0
  262. package/tools/installer/commands/install.js +149 -0
  263. package/tools/installer/commands/status.js +65 -0
  264. package/tools/installer/commands/uninstall.js +167 -0
  265. package/tools/installer/core/config.js +73 -0
  266. package/tools/installer/core/existing-install.js +121 -0
  267. package/tools/installer/core/install-paths.js +132 -0
  268. package/tools/installer/core/installer.js +1762 -0
  269. package/tools/installer/core/legacy-warnings.js +151 -0
  270. package/tools/installer/core/manifest-generator.js +859 -0
  271. package/tools/installer/core/manifest.js +433 -0
  272. package/tools/installer/core/uv-check.js +97 -0
  273. package/tools/installer/core/wsl-node-check.js +109 -0
  274. package/tools/installer/drt-cli.js +104 -0
  275. package/tools/installer/file-ops.js +204 -0
  276. package/tools/installer/fs-native.js +116 -0
  277. package/tools/installer/ide/_config-driven.js +972 -0
  278. package/tools/installer/ide/manager.js +324 -0
  279. package/tools/installer/ide/platform-codes.js +80 -0
  280. package/tools/installer/ide/platform-codes.yaml +343 -0
  281. package/tools/installer/ide/shared/installed-skills.js +50 -0
  282. package/tools/installer/ide/shared/path-utils.js +217 -0
  283. package/tools/installer/ide/shared/skill-manifest.js +57 -0
  284. package/tools/installer/install-messages.yaml +29 -0
  285. package/tools/installer/list-options.js +210 -0
  286. package/tools/installer/message-loader.js +83 -0
  287. package/tools/installer/modules/channel-plan.js +203 -0
  288. package/tools/installer/modules/channel-resolver.js +241 -0
  289. package/tools/installer/modules/custom-module-manager.js +918 -0
  290. package/tools/installer/modules/external-manager.js +667 -0
  291. package/tools/installer/modules/module-help-schema.js +13 -0
  292. package/tools/installer/modules/official-modules.js +2257 -0
  293. package/tools/installer/modules/plugin-resolver.js +398 -0
  294. package/tools/installer/modules/version-resolver.js +336 -0
  295. package/tools/installer/project-root.js +224 -0
  296. package/tools/installer/prompts.js +852 -0
  297. package/tools/installer/set-overrides.js +330 -0
  298. package/tools/installer/ui.js +2090 -0
  299. package/tools/installer/yaml-format.js +245 -0
@@ -0,0 +1,1762 @@
1
+ const path = require('node:path');
2
+ const fs = require('../fs-native');
3
+ const { Manifest } = require('./manifest');
4
+ const { OfficialModules } = require('../modules/official-modules');
5
+ const { IdeManager } = require('../ide/manager');
6
+ const { FileOps } = require('../file-ops');
7
+ const { Config } = require('./config');
8
+ const { getProjectRoot, getSourcePath } = require('../project-root');
9
+ const { ManifestGenerator } = require('./manifest-generator');
10
+ const prompts = require('../prompts');
11
+ const { DRT_FOLDER_NAME } = require('../ide/shared/path-utils');
12
+ const { InstallPaths } = require('./install-paths');
13
+ const { ExternalModuleManager } = require('../modules/external-manager');
14
+ const { resolveModuleVersion } = require('../modules/version-resolver');
15
+ const { MODULE_HELP_CSV_HEADER } = require('../modules/module-help-schema');
16
+
17
+ const { ExistingInstall } = require('./existing-install');
18
+ const { warnPreNativeSkillsLegacy } = require('./legacy-warnings');
19
+
20
+ class Installer {
21
+ constructor() {
22
+ this.externalModuleManager = new ExternalModuleManager();
23
+ this.manifest = new Manifest();
24
+ this.ideManager = new IdeManager();
25
+ this.fileOps = new FileOps();
26
+ this.installedFiles = new Set(); // Track all installed files
27
+ this.drtFolderName = DRT_FOLDER_NAME;
28
+ }
29
+
30
+ /**
31
+ * Main installation method
32
+ * @param {Object} config - Installation configuration
33
+ * @param {string} config.directory - Target directory
34
+ * @param {string[]} config.modules - Modules to install (including 'core')
35
+ * @param {string[]} config.ides - IDEs to configure
36
+ */
37
+ async install(originalConfig) {
38
+ let updateState = null;
39
+
40
+ try {
41
+ const config = Config.build(originalConfig);
42
+ const paths = await InstallPaths.create(config);
43
+ const officialModules = await OfficialModules.build(config, paths);
44
+ const existingInstall = await ExistingInstall.detect(paths.drtDir);
45
+
46
+ try {
47
+ await warnPreNativeSkillsLegacy({
48
+ projectRoot: paths.projectRoot,
49
+ existingVersion: existingInstall.installed ? existingInstall.version : null,
50
+ });
51
+ } catch (error) {
52
+ // Legacy-dir scan is informational; never let it abort install.
53
+ await prompts.log.warn(`Warning: Could not check for legacy DRT entries: ${error.message}`);
54
+ }
55
+
56
+ if (existingInstall.installed) {
57
+ await this._removeDeselectedModules(existingInstall, config, paths, originalConfig._preserveModules || []);
58
+ updateState = await this._prepareUpdateState(paths, config, existingInstall, officialModules);
59
+ await this._removeDeselectedIdes(existingInstall, config, paths);
60
+ }
61
+
62
+ await this._validateIdeSelection(config);
63
+
64
+ // Capture pre-install module versions for from→to display
65
+ const preInstallVersions = new Map();
66
+ if (existingInstall.installed) {
67
+ const existingModules = await this.manifest.getAllModuleVersions(paths.drtDir);
68
+ for (const mod of existingModules) {
69
+ if (mod.name && mod.version) {
70
+ preInstallVersions.set(mod.name, mod.version);
71
+ }
72
+ }
73
+ }
74
+
75
+ // Results collector for consolidated summary
76
+ const results = [];
77
+ const addResult = (step, status, detail = '', meta = {}) => results.push({ step, status, detail, ...meta });
78
+
79
+ // Capture previously installed skill rows before they get overwritten
80
+ const preservedModules = originalConfig._preserveModules || [];
81
+ const previousSkillManifestRows = await this._readSkillManifestRows(paths.drtDir);
82
+ const previousSkillIds = this._getPreviousSkillIdsForCleanup(previousSkillManifestRows, preservedModules);
83
+
84
+ const allModules = config.modules || [];
85
+
86
+ await this._installAndConfigure(
87
+ config,
88
+ originalConfig,
89
+ paths,
90
+ allModules,
91
+ allModules,
92
+ addResult,
93
+ officialModules,
94
+ previousSkillManifestRows,
95
+ );
96
+
97
+ await this._setupIdes(config, allModules, paths, addResult, previousSkillIds);
98
+
99
+ // Skills are now in IDE directories — remove redundant copies from _drt/.
100
+ // Also cleans up skill dirs left by older installer versions.
101
+ await this._cleanupSkillDirs(paths.drtDir);
102
+
103
+ const restoreResult = await this._restoreUserFiles(paths, updateState);
104
+
105
+ // Surface any "action needed" post-install messages for installed modules
106
+ // (e.g. run a setup skill) and let the user acknowledge them before the
107
+ // final summary, so "DRT is ready to use!" stays the last thing shown.
108
+ await this._displayPostInstallMessages(config, officialModules);
109
+
110
+ // Render consolidated summary
111
+ await this.renderInstallSummary(results, {
112
+ drtDir: paths.drtDir,
113
+ modules: config.modules,
114
+ ides: config.ides,
115
+ customFiles: restoreResult.customFiles.length > 0 ? restoreResult.customFiles : undefined,
116
+ modifiedFiles: restoreResult.modifiedFiles.length > 0 ? restoreResult.modifiedFiles : undefined,
117
+ preInstallVersions,
118
+ });
119
+
120
+ return {
121
+ success: true,
122
+ path: paths.drtDir,
123
+ modules: config.modules,
124
+ ides: config.ides,
125
+ projectDir: paths.projectRoot,
126
+ };
127
+ } catch (error) {
128
+ await prompts.log.error('Installation failed');
129
+
130
+ // Clean up any temp backup directories that were created before the failure
131
+ try {
132
+ if (updateState?.tempBackupDir && (await fs.pathExists(updateState.tempBackupDir))) {
133
+ await fs.remove(updateState.tempBackupDir);
134
+ }
135
+ if (updateState?.tempModifiedBackupDir && (await fs.pathExists(updateState.tempModifiedBackupDir))) {
136
+ await fs.remove(updateState.tempModifiedBackupDir);
137
+ }
138
+ } catch {
139
+ // Best-effort cleanup — don't mask the original error
140
+ }
141
+
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Remove modules that were previously installed but are no longer selected.
148
+ * No confirmation — the user's module selection is the decision.
149
+ */
150
+ async _removeDeselectedModules(existingInstall, config, paths, preservedModules = []) {
151
+ const previouslyInstalled = new Set(existingInstall.moduleIds);
152
+ const newlySelected = new Set(config.modules || []);
153
+ const preserved = new Set(preservedModules);
154
+ const toRemove = [...previouslyInstalled].filter((m) => !newlySelected.has(m) && m !== 'core' && !preserved.has(m));
155
+
156
+ for (const moduleId of toRemove) {
157
+ const modulePath = paths.moduleDir(moduleId);
158
+ try {
159
+ if (await fs.pathExists(modulePath)) {
160
+ await fs.remove(modulePath);
161
+ }
162
+ } catch (error) {
163
+ await prompts.log.warn(`Warning: Failed to remove ${moduleId}: ${error.message}`);
164
+ }
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Fail fast if all selected IDEs are suspended.
170
+ */
171
+ async _validateIdeSelection(config) {
172
+ if (!config.ides || config.ides.length === 0) return;
173
+
174
+ await this.ideManager.ensureInitialized();
175
+ const suspendedIdes = config.ides.filter((ide) => {
176
+ const handler = this.ideManager.handlers.get(ide);
177
+ return handler?.platformConfig?.suspended;
178
+ });
179
+
180
+ if (suspendedIdes.length > 0 && suspendedIdes.length === config.ides.length) {
181
+ for (const ide of suspendedIdes) {
182
+ const handler = this.ideManager.handlers.get(ide);
183
+ await prompts.log.error(`${handler.displayName || ide}: ${handler.platformConfig.suspended}`);
184
+ }
185
+ throw new Error(
186
+ `All selected tool(s) are suspended: ${suspendedIdes.join(', ')}. Installation aborted to prevent upgrading _drt/ without a working IDE configuration.`,
187
+ );
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Remove IDEs that were previously installed but are no longer selected.
193
+ * No confirmation — the user's IDE selection is the decision.
194
+ */
195
+ async _removeDeselectedIdes(existingInstall, config, paths) {
196
+ const previouslyInstalled = new Set(existingInstall.ides);
197
+ const newlySelected = new Set(config.ides || []);
198
+ const toRemove = [...previouslyInstalled].filter((ide) => !newlySelected.has(ide));
199
+
200
+ if (toRemove.length === 0) return;
201
+
202
+ // Pass the newly-selected list as remainingIdes so cleanupByList skips
203
+ // target_dir wipes for IDEs whose directory is still owned by a peer
204
+ // (e.g. removing 'cursor' while 'gemini' remains — both share .agents/skills).
205
+ const results = await this.ideManager.cleanupByList(paths.projectRoot, toRemove, {
206
+ remainingIdes: [...newlySelected],
207
+ });
208
+
209
+ for (const result of results || []) {
210
+ if (result && result.success === false) {
211
+ await prompts.log.warn(`Warning: Failed to remove ${result.ide}: ${result.error || 'unknown error'}`);
212
+ }
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Install modules, create directories, generate configs and manifests.
218
+ */
219
+ async _installAndConfigure(
220
+ config,
221
+ originalConfig,
222
+ paths,
223
+ officialModuleIds,
224
+ allModules,
225
+ addResult,
226
+ officialModules,
227
+ previousSkillManifestRows = [],
228
+ ) {
229
+ const isQuickUpdate = config.isQuickUpdate();
230
+ const moduleConfigs = officialModules.moduleConfigs;
231
+
232
+ const dirResults = { createdDirs: [], movedDirs: [], createdWdsFolders: [] };
233
+
234
+ const installTasks = [];
235
+
236
+ installTasks.push({
237
+ title: 'Installing shared scripts',
238
+ task: async () => {
239
+ await this._installSharedScripts(paths);
240
+ addResult('Shared scripts', 'ok');
241
+ return 'Shared scripts installed';
242
+ },
243
+ });
244
+
245
+ if (allModules.length > 0) {
246
+ installTasks.push({
247
+ title: isQuickUpdate ? `Updating ${allModules.length} module(s)` : `Installing ${allModules.length} module(s)`,
248
+ task: async (message) => {
249
+ const installedModuleNames = new Set();
250
+
251
+ await this._installOfficialModules(config, paths, officialModuleIds, addResult, isQuickUpdate, officialModules, {
252
+ message,
253
+ installedModuleNames,
254
+ });
255
+
256
+ return `${allModules.length} module(s) ${isQuickUpdate ? 'updated' : 'installed'}`;
257
+ },
258
+ });
259
+ }
260
+
261
+ installTasks.push({
262
+ title: 'Creating module directories',
263
+ task: async (message) => {
264
+ const verboseMode = process.env.DRT_VERBOSE_INSTALL === 'true' || config.verbose;
265
+ const moduleLogger = {
266
+ log: async (msg) => (verboseMode ? await prompts.log.message(msg) : undefined),
267
+ error: async (msg) => await prompts.log.error(msg),
268
+ warn: async (msg) => await prompts.log.warn(msg),
269
+ };
270
+
271
+ if (config.modules && config.modules.length > 0) {
272
+ for (const moduleName of config.modules) {
273
+ message(`Setting up ${moduleName}...`);
274
+ const result = await officialModules.createModuleDirectories(moduleName, paths.drtDir, {
275
+ installedIDEs: config.ides || [],
276
+ moduleConfig: moduleConfigs[moduleName] || {},
277
+ existingModuleConfig: officialModules.existingConfig?.[moduleName] || {},
278
+ coreConfig: moduleConfigs.core || {},
279
+ logger: moduleLogger,
280
+ silent: true,
281
+ });
282
+ if (result) {
283
+ dirResults.createdDirs.push(...result.createdDirs);
284
+ dirResults.movedDirs.push(...(result.movedDirs || []));
285
+ dirResults.createdWdsFolders.push(...result.createdWdsFolders);
286
+ }
287
+ }
288
+ }
289
+
290
+ addResult('Module directories', 'ok');
291
+ return 'Module directories created';
292
+ },
293
+ });
294
+
295
+ const configTask = {
296
+ title: 'Generating configurations',
297
+ task: async (message) => {
298
+ await this.generateModuleConfigs(paths.drtDir, moduleConfigs);
299
+ addResult('Configurations', 'ok', 'generated');
300
+
301
+ this.installedFiles.add(paths.manifestFile());
302
+ this.installedFiles.add(paths.centralConfig());
303
+ this.installedFiles.add(paths.centralUserConfig());
304
+
305
+ message('Generating manifests...');
306
+ const manifestGen = new ManifestGenerator();
307
+ const preservedModules = originalConfig._preserveModules || [];
308
+
309
+ const allModulesForManifest = config.isQuickUpdate()
310
+ ? originalConfig._existingModules || allModules || []
311
+ : preservedModules.length > 0
312
+ ? [...allModules, ...preservedModules]
313
+ : allModules || [];
314
+
315
+ let modulesForCsvPreserve;
316
+ if (config.isQuickUpdate()) {
317
+ modulesForCsvPreserve = originalConfig._existingModules || allModules || [];
318
+ } else {
319
+ modulesForCsvPreserve = preservedModules.length > 0 ? [...allModules, ...preservedModules] : allModules;
320
+ }
321
+
322
+ await this._trackPreservedModuleFiles(paths.drtDir, preservedModules);
323
+
324
+ await manifestGen.generateManifests(paths.drtDir, allModulesForManifest, [...this.installedFiles], {
325
+ ides: config.ides || [],
326
+ preservedModules: modulesForCsvPreserve,
327
+ moduleConfigs,
328
+ });
329
+ await this._appendPreservedSkillManifestRows(paths.drtDir, previousSkillManifestRows, preservedModules);
330
+
331
+ // Apply post-install --set TOML patches. Runs after writeCentralConfig
332
+ // (inside generateManifests above) so the patch operates on the
333
+ // freshly written `_drt/config.toml` / `_drt/config.user.toml`.
334
+ // See `tools/installer/set-overrides.js` for routing rules.
335
+ if (config.setOverrides && Object.keys(config.setOverrides).length > 0) {
336
+ const { applySetOverrides } = require('../set-overrides');
337
+ const applied = await applySetOverrides(config.setOverrides, paths.drtDir);
338
+ if (applied.length > 0) {
339
+ const summary = applied.map((a) => `${a.module}.${a.key} → ${a.file}`).join(', ');
340
+ await prompts.log.info(`Applied --set overrides: ${summary}`);
341
+ }
342
+ }
343
+
344
+ message('Generating help catalog...');
345
+ await this.mergeModuleHelpCatalogs(paths.drtDir, manifestGen.agents);
346
+ addResult('Help catalog', 'ok');
347
+
348
+ await this._installGettingStarted(paths);
349
+
350
+ return 'Configurations generated';
351
+ },
352
+ };
353
+ installTasks.push(configTask);
354
+
355
+ // Run install + dirs first, then render dir output, then run config generation
356
+ const mainTasks = installTasks.filter((t) => t !== configTask);
357
+ await prompts.tasks(mainTasks);
358
+
359
+ const color = await prompts.getColor();
360
+ if (dirResults.movedDirs.length > 0) {
361
+ const lines = dirResults.movedDirs.map((d) => ` ${d}`).join('\n');
362
+ await prompts.log.message(color.cyan(`Moved directories:\n${lines}`));
363
+ }
364
+ if (dirResults.createdDirs.length > 0) {
365
+ const lines = dirResults.createdDirs.map((d) => ` ${d}`).join('\n');
366
+ await prompts.log.message(color.yellow(`Created directories:\n${lines}`));
367
+ }
368
+ if (dirResults.createdWdsFolders.length > 0) {
369
+ const lines = dirResults.createdWdsFolders.map((f) => color.dim(` \u2713 ${f}/`)).join('\n');
370
+ await prompts.log.message(color.cyan(`Created WDS folder structure:\n${lines}`));
371
+ }
372
+
373
+ await prompts.tasks([configTask]);
374
+ }
375
+
376
+ /**
377
+ * Set up IDE integrations for each selected IDE.
378
+ */
379
+ async _setupIdes(config, allModules, paths, addResult, previousSkillIds = new Set()) {
380
+ if (config.skipIde || !config.ides || config.ides.length === 0) return;
381
+
382
+ await this.ideManager.ensureInitialized();
383
+ const validIdes = config.ides.filter((ide) => ide && typeof ide === 'string');
384
+
385
+ if (validIdes.length === 0) {
386
+ addResult('IDE configuration', 'warn', 'no valid IDEs selected');
387
+ return;
388
+ }
389
+
390
+ const setupResults = await this.ideManager.setupBatch(validIdes, paths.projectRoot, paths.drtDir, {
391
+ selectedModules: allModules || [],
392
+ verbose: config.verbose,
393
+ previousSkillIds,
394
+ });
395
+
396
+ for (const setupResult of setupResults) {
397
+ const ide = setupResult.ide;
398
+ if (setupResult.success) {
399
+ addResult(ide, 'ok', setupResult.detail || '');
400
+ } else {
401
+ addResult(ide, 'error', setupResult.error || 'failed');
402
+ }
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Remove skill directories from _drt/ after IDE installation.
408
+ * Skills are self-contained in IDE directories, so _drt/ only needs
409
+ * module-level files (config.yaml, _config/, etc.).
410
+ * Also cleans up skill dirs left by older installer versions.
411
+ * @param {string} drtDir - DRT installation directory
412
+ */
413
+ async _cleanupSkillDirs(drtDir) {
414
+ const csv = require('csv-parse/sync');
415
+ const csvPath = path.join(drtDir, '_config', 'skill-manifest.csv');
416
+ if (!(await fs.pathExists(csvPath))) return;
417
+
418
+ const csvContent = await fs.readFile(csvPath, 'utf8');
419
+ const records = csv.parse(csvContent, { columns: true, skip_empty_lines: true });
420
+ const drtFolderName = path.basename(drtDir);
421
+ const drtPrefix = drtFolderName + '/';
422
+
423
+ for (const record of records) {
424
+ if (!record.path) continue;
425
+ const relativePath = record.path.startsWith(drtPrefix) ? record.path.slice(drtPrefix.length) : record.path;
426
+ const sourceDir = path.dirname(path.join(drtDir, relativePath));
427
+ if (await fs.pathExists(sourceDir)) {
428
+ await fs.remove(sourceDir);
429
+ await this._removeEmptyParents(path.dirname(sourceDir), drtDir);
430
+ }
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Remove now-empty parent directories left behind after skill dir cleanup.
436
+ * Walks up from dir, stopping at (and never removing) drtDir. Best-effort:
437
+ * a directory that vanishes or fills in mid-walk just ends the walk.
438
+ * @param {string} dir - Directory to start walking up from
439
+ * @param {string} drtDir - DRT installation directory (boundary)
440
+ */
441
+ async _removeEmptyParents(dir, drtDir) {
442
+ let current = dir;
443
+ while (true) {
444
+ // Path-boundary check (not a string prefix, so siblings like _drt2 don't match).
445
+ const rel = path.relative(drtDir, current);
446
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) break;
447
+ try {
448
+ const entries = await fs.readdir(current);
449
+ if (entries.length > 0) break;
450
+ await fs.rmdir(current);
451
+ } catch {
452
+ break;
453
+ }
454
+ current = path.dirname(current);
455
+ }
456
+ }
457
+
458
+ async _readSkillManifestRows(drtDir) {
459
+ const csvPath = path.join(drtDir, '_config', 'skill-manifest.csv');
460
+ if (!(await fs.pathExists(csvPath))) return [];
461
+
462
+ try {
463
+ const csvParse = require('csv-parse/sync');
464
+ const content = await fs.readFile(csvPath, 'utf8');
465
+ return csvParse.parse(content, { columns: true, skip_empty_lines: true });
466
+ } catch (error) {
467
+ await prompts.log.warn(`Failed to parse skill-manifest.csv: ${error.message}`);
468
+ return [];
469
+ }
470
+ }
471
+
472
+ _getPreviousSkillIdsForCleanup(previousRows, preservedModules = []) {
473
+ const preservedModuleSet = new Set(preservedModules || []);
474
+ const ids = new Set();
475
+ for (const row of previousRows || []) {
476
+ if (row.canonicalId && !preservedModuleSet.has(row.module)) {
477
+ ids.add(row.canonicalId);
478
+ }
479
+ }
480
+ return ids;
481
+ }
482
+
483
+ async _appendPreservedSkillManifestRows(drtDir, previousRows, preservedModules = []) {
484
+ if (!previousRows || previousRows.length === 0 || preservedModules.length === 0) return;
485
+
486
+ const preservedModuleSet = new Set(preservedModules);
487
+ const rowsToPreserve = previousRows.filter((row) => row.canonicalId && row.module && preservedModuleSet.has(row.module));
488
+ if (rowsToPreserve.length === 0) return;
489
+
490
+ const csvPath = path.join(drtDir, '_config', 'skill-manifest.csv');
491
+ if (!(await fs.pathExists(csvPath))) return;
492
+
493
+ const currentRows = await this._readSkillManifestRows(drtDir);
494
+ const activeIds = new Set(currentRows.map((row) => row.canonicalId).filter(Boolean));
495
+ const appendedRows = [];
496
+
497
+ for (const row of rowsToPreserve) {
498
+ if (activeIds.has(row.canonicalId)) continue;
499
+ activeIds.add(row.canonicalId);
500
+ appendedRows.push(
501
+ [row.canonicalId, row.name || row.canonicalId, row.description || '', row.module, row.path || '']
502
+ .map((field) => this.escapeCSVField(field))
503
+ .join(','),
504
+ );
505
+ }
506
+
507
+ if (appendedRows.length === 0) return;
508
+
509
+ const currentContent = await fs.readFile(csvPath, 'utf8');
510
+ const prefix = currentContent.endsWith('\n') ? currentContent : `${currentContent}\n`;
511
+ await fs.writeFile(csvPath, prefix + appendedRows.join('\n') + '\n', 'utf8');
512
+ }
513
+
514
+ /**
515
+ * Restore custom and modified files that were backed up before the update.
516
+ * No-op for fresh installs (updateState is null).
517
+ * @param {Object} paths - InstallPaths instance
518
+ * @param {Object|null} updateState - From _prepareUpdateState, or null for fresh installs
519
+ * @returns {Object} { customFiles, modifiedFiles } — lists of restored files
520
+ */
521
+ async _restoreUserFiles(paths, updateState) {
522
+ const noFiles = { customFiles: [], modifiedFiles: [] };
523
+
524
+ if (!updateState || (updateState.customFiles.length === 0 && updateState.modifiedFiles.length === 0)) {
525
+ return noFiles;
526
+ }
527
+
528
+ let restoredCustomFiles = [];
529
+ let restoredModifiedFiles = [];
530
+
531
+ await prompts.tasks([
532
+ {
533
+ title: 'Finalizing installation',
534
+ task: async (message) => {
535
+ if (updateState.customFiles.length > 0) {
536
+ message(`Restoring ${updateState.customFiles.length} custom files...`);
537
+
538
+ for (const originalPath of updateState.customFiles) {
539
+ const relativePath = path.relative(paths.drtDir, originalPath);
540
+ const backupPath = path.join(updateState.tempBackupDir, relativePath);
541
+
542
+ if (await fs.pathExists(backupPath)) {
543
+ await fs.ensureDir(path.dirname(originalPath));
544
+ await fs.copy(backupPath, originalPath, { overwrite: true });
545
+ }
546
+ }
547
+
548
+ if (updateState.tempBackupDir && (await fs.pathExists(updateState.tempBackupDir))) {
549
+ await fs.remove(updateState.tempBackupDir);
550
+ }
551
+
552
+ restoredCustomFiles = updateState.customFiles;
553
+ }
554
+
555
+ if (updateState.modifiedFiles.length > 0) {
556
+ restoredModifiedFiles = updateState.modifiedFiles;
557
+
558
+ if (updateState.tempModifiedBackupDir && (await fs.pathExists(updateState.tempModifiedBackupDir))) {
559
+ message(`Restoring ${restoredModifiedFiles.length} modified files as .bak...`);
560
+
561
+ for (const modifiedFile of restoredModifiedFiles) {
562
+ const relativePath = path.relative(paths.drtDir, modifiedFile.path);
563
+ const tempBackupPath = path.join(updateState.tempModifiedBackupDir, relativePath);
564
+ const bakPath = modifiedFile.path + '.bak';
565
+
566
+ if (await fs.pathExists(tempBackupPath)) {
567
+ await fs.ensureDir(path.dirname(bakPath));
568
+ await fs.copy(tempBackupPath, bakPath, { overwrite: true });
569
+ }
570
+ }
571
+
572
+ await fs.remove(updateState.tempModifiedBackupDir);
573
+ }
574
+ }
575
+
576
+ return 'Installation finalized';
577
+ },
578
+ },
579
+ ]);
580
+
581
+ return { customFiles: restoredCustomFiles, modifiedFiles: restoredModifiedFiles };
582
+ }
583
+
584
+ /**
585
+ * Common update preparation: detect files, preserve core config, back up.
586
+ * @param {Object} paths - InstallPaths instance
587
+ * @param {Object} config - Clean config (may have coreConfig updated)
588
+ * @param {Object} existingInstall - Detection result
589
+ * @param {Object} officialModules - OfficialModules instance
590
+ * @returns {Object} Update state: { customFiles, modifiedFiles, tempBackupDir, tempModifiedBackupDir }
591
+ */
592
+ async _prepareUpdateState(paths, config, existingInstall, officialModules) {
593
+ // Detect custom and modified files BEFORE updating (compare current files vs files-manifest.csv)
594
+ const existingFilesManifest = await this.readFilesManifest(paths.drtDir);
595
+ const { customFiles, modifiedFiles } = await this.detectCustomFiles(paths.drtDir, existingFilesManifest);
596
+
597
+ // Preserve existing core configuration during updates
598
+ // (no-op for quick-update which already has core config from collectModuleConfigQuick)
599
+ const coreConfigPath = paths.moduleConfig('core');
600
+ if ((await fs.pathExists(coreConfigPath)) && (!config.coreConfig || Object.keys(config.coreConfig).length === 0)) {
601
+ try {
602
+ const yaml = require('yaml');
603
+ const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');
604
+ const existingCoreConfig = yaml.parse(coreConfigContent);
605
+
606
+ config.coreConfig = existingCoreConfig;
607
+ officialModules.moduleConfigs.core = existingCoreConfig;
608
+ } catch (error) {
609
+ await prompts.log.warn(`Warning: Could not read existing core config: ${error.message}`);
610
+ }
611
+ }
612
+
613
+ const backupDirs = await this._backupUserFiles(paths, customFiles, modifiedFiles);
614
+
615
+ return {
616
+ customFiles,
617
+ modifiedFiles,
618
+ tempBackupDir: backupDirs.tempBackupDir,
619
+ tempModifiedBackupDir: backupDirs.tempModifiedBackupDir,
620
+ };
621
+ }
622
+
623
+ /**
624
+ * Back up custom and modified files to temp directories before overwriting.
625
+ * Returns the temp directory paths (or undefined if no files to back up).
626
+ * @param {Object} paths - InstallPaths instance
627
+ * @param {string[]} customFiles - Absolute paths of custom (user-added) files
628
+ * @param {Object[]} modifiedFiles - Array of { path, relativePath } for modified files
629
+ * @returns {Object} { tempBackupDir, tempModifiedBackupDir } — undefined if no files
630
+ */
631
+ async _backupUserFiles(paths, customFiles, modifiedFiles) {
632
+ let tempBackupDir;
633
+ let tempModifiedBackupDir;
634
+
635
+ if (customFiles.length > 0) {
636
+ tempBackupDir = path.join(paths.projectRoot, '_drt-custom-backup-temp');
637
+ await fs.ensureDir(tempBackupDir);
638
+
639
+ for (const customFile of customFiles) {
640
+ const relativePath = path.relative(paths.drtDir, customFile);
641
+ const backupPath = path.join(tempBackupDir, relativePath);
642
+ await fs.ensureDir(path.dirname(backupPath));
643
+ await fs.copy(customFile, backupPath);
644
+ }
645
+ }
646
+
647
+ if (modifiedFiles.length > 0) {
648
+ tempModifiedBackupDir = path.join(paths.projectRoot, '_drt-modified-backup-temp');
649
+ await fs.ensureDir(tempModifiedBackupDir);
650
+
651
+ for (const modifiedFile of modifiedFiles) {
652
+ const relativePath = path.relative(paths.drtDir, modifiedFile.path);
653
+ const tempBackupPath = path.join(tempModifiedBackupDir, relativePath);
654
+ await fs.ensureDir(path.dirname(tempBackupPath));
655
+ await fs.copy(modifiedFile.path, tempBackupPath, { overwrite: true });
656
+ }
657
+ }
658
+
659
+ return { tempBackupDir, tempModifiedBackupDir };
660
+ }
661
+
662
+ /**
663
+ * Sync src/scripts/* → _drt/scripts/ so shared Node runtime scripts
664
+ * (resolve-config.js, resolve-customization.js, memlog.js) are available at install time.
665
+ * Excludes dev-only tests and legacy Python sources.
666
+ */
667
+ async _installSharedScripts(paths) {
668
+ const srcScriptsDir = path.join(paths.srcDir, 'src', 'scripts');
669
+ if (!(await fs.pathExists(srcScriptsDir))) {
670
+ throw new Error(`Shared scripts source directory not found: ${srcScriptsDir}`);
671
+ }
672
+
673
+ await fs.remove(paths.scriptsDir);
674
+ await fs.ensureDir(paths.scriptsDir);
675
+ const isInstallable = (srcPath) => {
676
+ const base = path.basename(srcPath);
677
+ if (base === 'tests' || base === '__pycache__' || base === '.pytest_cache' || base === 'node_modules') {
678
+ return false;
679
+ }
680
+ if (base.endsWith('.pyc') || base.endsWith('.py')) {
681
+ return false;
682
+ }
683
+ return true;
684
+ };
685
+ await fs.copy(srcScriptsDir, paths.scriptsDir, { overwrite: true, filter: isInstallable });
686
+ await this._trackFilesRecursive(paths.scriptsDir);
687
+
688
+ const scriptsPkg = path.join(paths.scriptsDir, 'package.json');
689
+ if (await fs.pathExists(scriptsPkg)) {
690
+ const { execSync } = require('node:child_process');
691
+ execSync('npm install --omit=dev --no-audit --no-fund', {
692
+ cwd: paths.scriptsDir,
693
+ stdio: 'pipe',
694
+ });
695
+ }
696
+
697
+ const customGitignore = path.join(paths.customDir, '.gitignore');
698
+ if (!(await fs.pathExists(customGitignore))) {
699
+ await fs.writeFile(customGitignore, '*.user.toml\n', 'utf8');
700
+ this.installedFiles.add(customGitignore);
701
+ }
702
+ }
703
+
704
+ async _installGettingStarted(paths) {
705
+ const source = path.join(paths.srcDir, 'GETTING-STARTED.md');
706
+ if (!(await fs.pathExists(source))) {
707
+ return;
708
+ }
709
+ const dest = path.join(paths.projectRoot, 'GETTING-STARTED.md');
710
+ await fs.copy(source, dest, { overwrite: true });
711
+ this.installedFiles.add(dest);
712
+ }
713
+
714
+ async _trackFilesRecursive(dir) {
715
+ const entries = await fs.readdir(dir, { withFileTypes: true });
716
+ for (const entry of entries) {
717
+ const full = path.join(dir, entry.name);
718
+ if (entry.isDirectory()) {
719
+ await this._trackFilesRecursive(full);
720
+ } else if (entry.isFile()) {
721
+ this.installedFiles.add(full);
722
+ }
723
+ }
724
+ }
725
+
726
+ async _trackPreservedModuleFiles(drtDir, preservedModules = []) {
727
+ for (const moduleName of preservedModules) {
728
+ const modulePath = path.join(drtDir, moduleName);
729
+ if (await fs.pathExists(modulePath)) {
730
+ await this._trackFilesRecursive(modulePath);
731
+ }
732
+ }
733
+ }
734
+
735
+ /**
736
+ * Install official (non-custom) modules.
737
+ * @param {Object} config - Installation configuration
738
+ * @param {Object} paths - InstallPaths instance
739
+ * @param {string[]} officialModuleIds - Official module IDs to install
740
+ * @param {Function} addResult - Callback to record installation results
741
+ * @param {boolean} isQuickUpdate - Whether this is a quick update
742
+ * @param {Object} ctx - Shared context: { message, installedModuleNames }
743
+ */
744
+ async _installOfficialModules(config, paths, officialModuleIds, addResult, isQuickUpdate, officialModules, ctx) {
745
+ const { message, installedModuleNames } = ctx;
746
+ const { CustomModuleManager } = require('../modules/custom-module-manager');
747
+
748
+ for (const moduleName of officialModuleIds) {
749
+ if (installedModuleNames.has(moduleName)) continue;
750
+ installedModuleNames.add(moduleName);
751
+
752
+ message(`${isQuickUpdate ? 'Updating' : 'Installing'} ${moduleName}...`);
753
+
754
+ const moduleConfig = officialModules.moduleConfigs[moduleName] || {};
755
+ const installResult = await officialModules.install(
756
+ moduleName,
757
+ paths.drtDir,
758
+ (filePath) => {
759
+ this.installedFiles.add(filePath);
760
+ },
761
+ {
762
+ skipModuleInstaller: true,
763
+ moduleConfig: moduleConfig,
764
+ installer: this,
765
+ silent: true,
766
+ channelOptions: config.channelOptions,
767
+ },
768
+ );
769
+
770
+ // Get display name from source module.yaml and resolve the freshest version metadata we can find locally.
771
+ const sourcePath = await officialModules.findModuleSource(moduleName, {
772
+ silent: true,
773
+ channelOptions: config.channelOptions,
774
+ });
775
+ const moduleInfo = sourcePath ? await officialModules.getModuleInfo(sourcePath, moduleName, '') : null;
776
+ const displayName = moduleInfo?.name || moduleName;
777
+
778
+ const resolution = officialModules.externalModuleManager.getResolution(moduleName);
779
+ const cachedResolution = CustomModuleManager._resolutionCache.get(moduleName);
780
+ const versionInfo = await resolveModuleVersion(moduleName, {
781
+ moduleSourcePath: sourcePath,
782
+ fallbackVersion: resolution?.version || cachedResolution?.version,
783
+ marketplacePluginNames: cachedResolution?.pluginName ? [cachedResolution.pluginName] : [],
784
+ });
785
+ // Prefer the git tag recorded by the resolution (e.g. "v1.7.0") over
786
+ // the on-disk package.json (which may be ahead of the released tag).
787
+ const version = resolution?.version || versionInfo.version || '';
788
+ addResult(displayName, 'ok', '', {
789
+ moduleCode: moduleName,
790
+ newVersion: version,
791
+ newChannel: resolution?.channel || null,
792
+ newSha: resolution?.sha || null,
793
+ });
794
+ }
795
+ }
796
+
797
+ /**
798
+ * Read files-manifest.csv
799
+ * @param {string} drtDir - DRT installation directory
800
+ * @returns {Array} Array of file entries from files-manifest.csv
801
+ */
802
+ async readFilesManifest(drtDir) {
803
+ const filesManifestPath = path.join(drtDir, '_config', 'files-manifest.csv');
804
+ if (!(await fs.pathExists(filesManifestPath))) {
805
+ return [];
806
+ }
807
+
808
+ try {
809
+ const content = await fs.readFile(filesManifestPath, 'utf8');
810
+ const lines = content.split('\n');
811
+ const files = [];
812
+
813
+ for (let i = 1; i < lines.length; i++) {
814
+ // Skip header
815
+ const line = lines[i].trim();
816
+ if (!line) continue;
817
+
818
+ // Parse CSV line properly handling quoted values
819
+ const parts = [];
820
+ let current = '';
821
+ let inQuotes = false;
822
+
823
+ for (const char of line) {
824
+ if (char === '"') {
825
+ inQuotes = !inQuotes;
826
+ } else if (char === ',' && !inQuotes) {
827
+ parts.push(current);
828
+ current = '';
829
+ } else {
830
+ current += char;
831
+ }
832
+ }
833
+ parts.push(current); // Add last part
834
+
835
+ if (parts.length >= 4) {
836
+ files.push({
837
+ type: parts[0],
838
+ name: parts[1],
839
+ module: parts[2],
840
+ path: parts[3],
841
+ hash: parts[4] || null, // Hash may not exist in old manifests
842
+ });
843
+ }
844
+ }
845
+
846
+ return files;
847
+ } catch (error) {
848
+ await prompts.log.warn('Could not read files-manifest.csv: ' + error.message);
849
+ return [];
850
+ }
851
+ }
852
+
853
+ /**
854
+ * Detect custom and modified files
855
+ * @param {string} drtDir - DRT installation directory
856
+ * @param {Array} existingFilesManifest - Previous files from files-manifest.csv
857
+ * @returns {Object} Object with customFiles and modifiedFiles arrays
858
+ */
859
+ async detectCustomFiles(drtDir, existingFilesManifest) {
860
+ const customFiles = [];
861
+ const modifiedFiles = [];
862
+
863
+ // Memory subtrees (v6.1: _drt/_memory, current: _drt/memory) hold
864
+ // per-user runtime data generated by agents with sidecars. These files
865
+ // aren't installer-managed and must never be reported as "custom" or
866
+ // "modified" — they're user state, not user overrides.
867
+ const drtMemoryPaths = ['_memory', 'memory'];
868
+
869
+ // Check if the manifest has hashes - if not, we can't detect modifications
870
+ let manifestHasHashes = false;
871
+ if (existingFilesManifest && existingFilesManifest.length > 0) {
872
+ manifestHasHashes = existingFilesManifest.some((f) => f.hash);
873
+ }
874
+
875
+ // Build map of previously installed files from files-manifest.csv with their hashes
876
+ const installedFilesMap = new Map();
877
+ for (const fileEntry of existingFilesManifest) {
878
+ if (fileEntry.path) {
879
+ const absolutePath = path.join(drtDir, fileEntry.path);
880
+ installedFilesMap.set(path.normalize(absolutePath), {
881
+ hash: fileEntry.hash,
882
+ relativePath: fileEntry.path,
883
+ });
884
+ }
885
+ }
886
+
887
+ // Recursively scan drtDir for all files
888
+ const scanDirectory = async (dir) => {
889
+ try {
890
+ const entries = await fs.readdir(dir, { withFileTypes: true });
891
+ for (const entry of entries) {
892
+ const fullPath = path.join(dir, entry.name);
893
+
894
+ if (entry.isDirectory()) {
895
+ // Skip certain directories
896
+ if (entry.name === 'node_modules' || entry.name === '.git') {
897
+ continue;
898
+ }
899
+ await scanDirectory(fullPath);
900
+ } else if (entry.isFile()) {
901
+ const normalizedPath = path.normalize(fullPath);
902
+ const fileInfo = installedFilesMap.get(normalizedPath);
903
+
904
+ // Skip certain system files that are auto-generated
905
+ const relativePath = path.relative(drtDir, fullPath);
906
+ const fileName = path.basename(fullPath);
907
+
908
+ // Skip _config directory EXCEPT for modified agent customizations
909
+ if (relativePath.startsWith('_config/') || relativePath.startsWith('_config\\')) {
910
+ // Special handling for .customize.yaml files - only preserve if modified
911
+ if (relativePath.includes('/agents/') && fileName.endsWith('.customize.yaml')) {
912
+ // Check if the customization file has been modified from manifest
913
+ const manifestPath = path.join(drtDir, '_config', 'manifest.yaml');
914
+ if (await fs.pathExists(manifestPath)) {
915
+ const crypto = require('node:crypto');
916
+ const currentContent = await fs.readFile(fullPath, 'utf8');
917
+ const currentHash = crypto.createHash('sha256').update(currentContent).digest('hex');
918
+
919
+ const yaml = require('yaml');
920
+ const manifestContent = await fs.readFile(manifestPath, 'utf8');
921
+ const manifestData = yaml.parse(manifestContent);
922
+ const originalHash = manifestData.agentCustomizations?.[relativePath];
923
+
924
+ // Only add to customFiles if hash differs (user modified)
925
+ if (originalHash && currentHash !== originalHash) {
926
+ customFiles.push(fullPath);
927
+ }
928
+ }
929
+ }
930
+ continue;
931
+ }
932
+
933
+ if (drtMemoryPaths.some((mp) => relativePath === mp || relativePath.startsWith(mp + '/'))) {
934
+ continue;
935
+ }
936
+
937
+ // Skip config.yaml files - these are regenerated on each install/update
938
+ if (fileName === 'config.yaml') {
939
+ continue;
940
+ }
941
+
942
+ if (!fileInfo) {
943
+ // File not in manifest = custom file
944
+ // EXCEPT: Agent .md files in module folders are generated files, not custom
945
+ // Only treat .md files under _config/agents/ as custom
946
+ if (!(fileName.endsWith('.md') && relativePath.includes('/agents/') && !relativePath.startsWith('_config/'))) {
947
+ customFiles.push(fullPath);
948
+ }
949
+ } else if (manifestHasHashes && fileInfo.hash) {
950
+ // File in manifest with hash - check if it was modified
951
+ const currentHash = await this.manifest.calculateFileHash(fullPath);
952
+ if (currentHash && currentHash !== fileInfo.hash) {
953
+ // Hash changed = file was modified
954
+ modifiedFiles.push({
955
+ path: fullPath,
956
+ relativePath: fileInfo.relativePath,
957
+ });
958
+ }
959
+ }
960
+ }
961
+ }
962
+ } catch {
963
+ // Ignore errors scanning directories
964
+ }
965
+ };
966
+
967
+ await scanDirectory(drtDir);
968
+ return { customFiles, modifiedFiles };
969
+ }
970
+
971
+ /**
972
+ * Generate clean config.yaml files for each installed module
973
+ * @param {string} drtDir - DRT installation directory
974
+ * @param {Object} moduleConfigs - Collected configuration values
975
+ */
976
+ async generateModuleConfigs(drtDir, moduleConfigs) {
977
+ const yaml = require('yaml');
978
+
979
+ // Extract core config values to share with other modules
980
+ const coreConfig = moduleConfigs.core || {};
981
+
982
+ // Get all installed module directories
983
+ const entries = await fs.readdir(drtDir, { withFileTypes: true });
984
+ const nonModuleDirs = new Set(['_config', '_memory', 'memory', 'docs', 'scripts', 'custom']);
985
+ const installedModules = entries.filter((entry) => entry.isDirectory() && !nonModuleDirs.has(entry.name)).map((entry) => entry.name);
986
+
987
+ // Generate config.yaml for each installed module
988
+ for (const moduleName of installedModules) {
989
+ const modulePath = path.join(drtDir, moduleName);
990
+
991
+ // Get module-specific config or use empty object if none
992
+ const config = moduleConfigs[moduleName] || {};
993
+
994
+ if (await fs.pathExists(modulePath)) {
995
+ const configPath = path.join(modulePath, 'config.yaml');
996
+
997
+ // Create header
998
+ const packageJson = require(path.join(getProjectRoot(), 'package.json'));
999
+ const header = `# ${moduleName.toUpperCase()} Module Configuration
1000
+ # Generated by DRT installer
1001
+ # Version: ${packageJson.version}
1002
+ # Date: ${new Date().toISOString()}
1003
+
1004
+ `;
1005
+
1006
+ // For non-core modules, add core config values directly
1007
+ let finalConfig = { ...config };
1008
+ let coreSection = '';
1009
+
1010
+ if (moduleName !== 'core' && coreConfig && Object.keys(coreConfig).length > 0) {
1011
+ // Add core values directly to the module config
1012
+ // These will be available for reference in the module
1013
+ finalConfig = {
1014
+ ...config,
1015
+ ...coreConfig, // Spread core config values directly into the module config
1016
+ };
1017
+
1018
+ // Create a comment section to identify core values
1019
+ coreSection = '\n# Core Configuration Values\n';
1020
+ }
1021
+
1022
+ // Clean the config to remove any non-serializable values (like functions)
1023
+ const cleanConfig = structuredClone(finalConfig);
1024
+
1025
+ // Convert config to YAML
1026
+ let yamlContent = yaml.stringify(cleanConfig, {
1027
+ indent: 2,
1028
+ lineWidth: 0,
1029
+ minContentWidth: 0,
1030
+ });
1031
+
1032
+ // If we have core values, reorganize the YAML to group them with their comment
1033
+ if (coreSection && moduleName !== 'core') {
1034
+ // Split the YAML into lines
1035
+ const lines = yamlContent.split('\n');
1036
+ const moduleConfigLines = [];
1037
+ const coreConfigLines = [];
1038
+
1039
+ // Separate module-specific and core config lines
1040
+ for (const line of lines) {
1041
+ const key = line.split(':')[0].trim();
1042
+ if (Object.prototype.hasOwnProperty.call(coreConfig, key)) {
1043
+ coreConfigLines.push(line);
1044
+ } else {
1045
+ moduleConfigLines.push(line);
1046
+ }
1047
+ }
1048
+
1049
+ // Rebuild YAML with module config first, then core config with comment
1050
+ yamlContent = moduleConfigLines.join('\n');
1051
+ if (coreConfigLines.length > 0) {
1052
+ yamlContent += coreSection + coreConfigLines.join('\n');
1053
+ }
1054
+ }
1055
+
1056
+ // Write the clean config file with POSIX-compliant final newline
1057
+ const content = header + yamlContent;
1058
+ await fs.writeFile(configPath, content.endsWith('\n') ? content : content + '\n', 'utf8');
1059
+
1060
+ // Track the config file in installedFiles
1061
+ this.installedFiles.add(configPath);
1062
+ }
1063
+ }
1064
+ }
1065
+
1066
+ /**
1067
+ * Merge all module-help.csv files into a single drt-help.csv.
1068
+ * Scans all installed modules for module-help.csv and merges them.
1069
+ * Output preserves the source schema verbatim — see schema below.
1070
+ * @param {string} drtDir - DRT installation directory
1071
+ * @param {Array<Object>} _agentEntries - Unused; retained for call-site compatibility
1072
+ */
1073
+ async mergeModuleHelpCatalogs(drtDir, _agentEntries = []) {
1074
+ const allRows = [];
1075
+ const headerRow = MODULE_HELP_CSV_HEADER;
1076
+ const COLUMN_COUNT = 13;
1077
+ const PHASE_INDEX = 7;
1078
+
1079
+ // Get all installed module directories
1080
+ const entries = await fs.readdir(drtDir, { withFileTypes: true });
1081
+ const nonModuleDirs = new Set(['_config', '_memory', 'memory', 'docs', 'scripts', 'custom']);
1082
+ const installedModules = entries.filter((entry) => entry.isDirectory() && !nonModuleDirs.has(entry.name)).map((entry) => entry.name);
1083
+
1084
+ // Add core module to scan (it's installed at root level as _config, but we check src/core-skills)
1085
+ const coreModulePath = getSourcePath('core-skills');
1086
+ const modulePaths = new Map();
1087
+
1088
+ // Map all module source paths
1089
+ if (await fs.pathExists(coreModulePath)) {
1090
+ modulePaths.set('core', coreModulePath);
1091
+ }
1092
+
1093
+ // Map installed module paths
1094
+ for (const moduleName of installedModules) {
1095
+ const modulePath = path.join(drtDir, moduleName);
1096
+ modulePaths.set(moduleName, modulePath);
1097
+ }
1098
+
1099
+ // Scan each module for module-help.csv
1100
+ for (const [moduleName, modulePath] of modulePaths) {
1101
+ const helpFilePath = path.join(modulePath, 'module-help.csv');
1102
+
1103
+ if (await fs.pathExists(helpFilePath)) {
1104
+ try {
1105
+ const content = await fs.readFile(helpFilePath, 'utf8');
1106
+ const lines = content.split('\n').filter((line) => line.trim() && !line.startsWith('#'));
1107
+
1108
+ let headerWarned = false;
1109
+ for (const line of lines) {
1110
+ // Header row: warn on drift from canonical schema, then skip.
1111
+ // Data rows are loaded positionally regardless, so the warning
1112
+ // is advisory — the maintainer should rename their columns.
1113
+ if (line.startsWith('module,')) {
1114
+ if (!headerWarned && line.trim() !== headerRow) {
1115
+ await prompts.log.warn(
1116
+ ` ${moduleName}/module-help.csv header does not match canonical schema. ` +
1117
+ `Expected: ${headerRow} | Found: ${line.trim()} | Data loaded positionally.`,
1118
+ );
1119
+ headerWarned = true;
1120
+ }
1121
+ continue;
1122
+ }
1123
+
1124
+ // Parse the line - handle quoted fields with commas
1125
+ const columns = this.parseCSVLine(line);
1126
+ if (columns.length < COLUMN_COUNT - 1) continue;
1127
+
1128
+ // Pad short rows; truncate over-long rows
1129
+ const padded = columns.slice(0, COLUMN_COUNT);
1130
+ while (padded.length < COLUMN_COUNT) padded.push('');
1131
+
1132
+ // If module column is empty, fill with this module's name
1133
+ // (core stays empty so its rows render as universal tools)
1134
+ if ((!padded[0] || padded[0].trim() === '') && moduleName !== 'core') {
1135
+ padded[0] = moduleName;
1136
+ }
1137
+
1138
+ allRows.push(padded.map((c) => this.escapeCSVField(c)).join(','));
1139
+ }
1140
+
1141
+ if (process.env.DRT_VERBOSE_INSTALL === 'true') {
1142
+ await prompts.log.message(` Merged module-help from: ${moduleName}`);
1143
+ }
1144
+ } catch (error) {
1145
+ await prompts.log.warn(` Warning: Failed to read module-help.csv from ${moduleName}: ${error.message}`);
1146
+ }
1147
+ }
1148
+ }
1149
+
1150
+ // Sort by module, then phase. Stable sort preserves authored order within a phase.
1151
+ const decorated = allRows.map((row, index) => ({ row, index, cols: this.parseCSVLine(row) }));
1152
+ decorated.sort((a, b) => {
1153
+ const moduleA = (a.cols[0] || '').toLowerCase();
1154
+ const moduleB = (b.cols[0] || '').toLowerCase();
1155
+ if (moduleA !== moduleB) return moduleA.localeCompare(moduleB);
1156
+
1157
+ const phaseA = a.cols[PHASE_INDEX] || '';
1158
+ const phaseB = b.cols[PHASE_INDEX] || '';
1159
+ if (phaseA !== phaseB) return phaseA.localeCompare(phaseB);
1160
+
1161
+ return a.index - b.index;
1162
+ });
1163
+ const sortedRows = decorated.map((d) => d.row);
1164
+
1165
+ // Write merged catalog
1166
+ const outputDir = path.join(drtDir, '_config');
1167
+ await fs.ensureDir(outputDir);
1168
+ const outputPath = path.join(outputDir, 'drt-help.csv');
1169
+
1170
+ const mergedContent = [headerRow, ...sortedRows].join('\n');
1171
+ await fs.writeFile(outputPath, mergedContent, 'utf8');
1172
+
1173
+ // Track the installed file
1174
+ this.installedFiles.add(outputPath);
1175
+
1176
+ if (process.env.DRT_VERBOSE_INSTALL === 'true') {
1177
+ await prompts.log.message(` Generated drt-help.csv: ${sortedRows.length} workflows`);
1178
+ }
1179
+ }
1180
+
1181
+ /**
1182
+ * Render a consolidated install summary using prompts.note()
1183
+ * @param {Array} results - Array of {step, status: 'ok'|'error'|'warn', detail}
1184
+ * @param {Object} context - {drtDir, modules, ides, customFiles, modifiedFiles}
1185
+ */
1186
+ async renderInstallSummary(results, context = {}) {
1187
+ const color = await prompts.getColor();
1188
+ const selectedIdes = new Set((context.ides || []).map((ide) => String(ide).toLowerCase()));
1189
+
1190
+ // Build step lines with status indicators
1191
+ const preVersions = context.preInstallVersions || new Map();
1192
+ const lines = [];
1193
+ for (const r of results) {
1194
+ const stepLabel = r.step;
1195
+
1196
+ let icon;
1197
+ if (r.status === 'ok') {
1198
+ icon = color.green('\u2713');
1199
+ } else if (r.status === 'warn') {
1200
+ icon = color.yellow('!');
1201
+ } else {
1202
+ icon = color.red('\u2717');
1203
+ }
1204
+
1205
+ // Build version detail for module results
1206
+ let detail = '';
1207
+ if (r.moduleCode && r.newVersion) {
1208
+ const oldVersion = preVersions.get(r.moduleCode);
1209
+ // Format a version label for display:
1210
+ // "main" → "main @ <short-sha>" (next channel shows what SHA landed)
1211
+ // "v1.7.0" or "1.7.0" → "v1.7.0" (prefix 'v' when missing)
1212
+ // anything else (legacy strings) → as-is
1213
+ const fmt = (v, sha) => {
1214
+ if (typeof v !== 'string' || !v) return '';
1215
+ if (v === 'main' || v === 'HEAD') return sha ? `main @ ${sha.slice(0, 7)}` : 'main';
1216
+ if (/^v?\d+\.\d+\.\d+/.test(v)) return v.startsWith('v') ? v : `v${v}`;
1217
+ return v;
1218
+ };
1219
+ const newV = fmt(r.newVersion, r.newSha);
1220
+ // 'main'/'HEAD' strings only identify the channel, not the commit, so
1221
+ // we can't assert "no change" without comparing SHAs — and preVersions
1222
+ // doesn't carry the old SHA. Render these as a refresh instead of a
1223
+ // false-negative "no change".
1224
+ const isMainLike = oldVersion === 'main' || oldVersion === 'HEAD';
1225
+ if (oldVersion && oldVersion === r.newVersion && !isMainLike) {
1226
+ detail = ` (${newV}, no change)`;
1227
+ } else if (oldVersion && isMainLike) {
1228
+ detail = ` (${newV}, refreshed)`;
1229
+ } else if (oldVersion) {
1230
+ detail = ` (${fmt(oldVersion, r.newSha)} → ${newV})`;
1231
+ } else {
1232
+ detail = ` (${newV}, installed)`;
1233
+ }
1234
+ } else if (r.detail) {
1235
+ detail = ` (${r.detail})`;
1236
+ }
1237
+ lines.push(` ${icon} ${stepLabel}${detail}`);
1238
+ }
1239
+
1240
+ if ((context.ides || []).length === 0) {
1241
+ lines.push(` ${color.green('\u2713')} No IDE selected (installed in _drt only)`);
1242
+ }
1243
+
1244
+ // Context and warnings
1245
+ lines.push('');
1246
+ if (context.drtDir) {
1247
+ lines.push(` Installed to: ${context.drtDir}`);
1248
+ }
1249
+ if (context.customFiles && context.customFiles.length > 0) {
1250
+ lines.push(` ${color.cyan(`Custom files preserved: ${context.customFiles.length}`)}`);
1251
+ }
1252
+ if (context.modifiedFiles && context.modifiedFiles.length > 0) {
1253
+ lines.push(` ${color.yellow(`Modified files backed up (.bak): ${context.modifiedFiles.length}`)}`);
1254
+ }
1255
+
1256
+ // Next steps
1257
+ lines.push(
1258
+ '',
1259
+ ' Get started:',
1260
+ ` 1. Launch your AI agent from your project folder`,
1261
+ ` 2. Not sure what to do? Invoke the ${color.cyan('drt-help')} skill and ask it what to do!`,
1262
+ ''
1263
+ );
1264
+
1265
+ await prompts.box(lines.join('\n'), 'DRT is ready to use!', {
1266
+ rounded: true,
1267
+ formatBorder: color.green,
1268
+ });
1269
+ }
1270
+
1271
+ /**
1272
+ * Display registry-defined post-install messages for the modules installed in
1273
+ * this run. These are "action needed" notices (e.g. "run the drt-loop-setup
1274
+ * skill") that the user must see to finish setup. They are defined via the
1275
+ * `post-install-message` property on a module's drt-modules.yaml entry.
1276
+ *
1277
+ * Interactive installs require the user to acknowledge each message (press
1278
+ * Enter); non-interactive (--yes / skipPrompts) installs print the message
1279
+ * and continue without blocking, so CI/scripted installs don't hang.
1280
+ *
1281
+ * @param {Object} config - Install config (config.modules, config.skipPrompts)
1282
+ * @param {Object} officialModules - OfficialModules instance (carries the registry)
1283
+ */
1284
+ async _displayPostInstallMessages(config, officialModules) {
1285
+ const moduleCodes = config.modules || [];
1286
+ if (moduleCodes.length === 0) return;
1287
+
1288
+ const externalManager = officialModules.externalModuleManager;
1289
+ if (!externalManager) return;
1290
+
1291
+ const color = await prompts.getColor();
1292
+
1293
+ for (const code of moduleCodes) {
1294
+ let moduleInfo;
1295
+ try {
1296
+ moduleInfo = await externalManager.getModuleByCode(code);
1297
+ } catch {
1298
+ continue; // Built-in modules (core/bmm) aren't in the registry — skip.
1299
+ }
1300
+
1301
+ const message = moduleInfo && moduleInfo.postInstallMessage;
1302
+ if (!message) continue;
1303
+
1304
+ await prompts.box(String(message).trim(), `⚑ Action needed — ${moduleInfo.name || code}`, {
1305
+ rounded: true,
1306
+ formatBorder: color.yellow,
1307
+ });
1308
+
1309
+ // Interactive: require the user to acknowledge before continuing. Skip the
1310
+ // blocking prompt in non-interactive installs (the message is still shown).
1311
+ if (!config.skipPrompts) {
1312
+ await prompts.text({
1313
+ message: 'Press Enter to acknowledge',
1314
+ placeholder: '',
1315
+ default: '',
1316
+ });
1317
+ }
1318
+ }
1319
+ }
1320
+
1321
+ /**
1322
+ * Quick update method - preserves all settings and only prompts for new config fields
1323
+ * @param {Object} config - Configuration with directory
1324
+ * @returns {Object} Update result
1325
+ */
1326
+ async quickUpdate(config) {
1327
+ const projectDir = path.resolve(config.directory);
1328
+ const { drtDir } = await this.findDrtDir(projectDir);
1329
+
1330
+ // Check if drt directory exists
1331
+ if (!(await fs.pathExists(drtDir))) {
1332
+ throw new Error(`DRT not installed at ${drtDir}. Use regular install for first-time setup.`);
1333
+ }
1334
+
1335
+ // Detect existing installation
1336
+ const existingInstall = await ExistingInstall.detect(drtDir);
1337
+ const configuredIdes = existingInstall.ides;
1338
+ const projectRoot = path.dirname(drtDir);
1339
+
1340
+ // Resolve any legacy/aliased module codes (e.g. an install recorded as
1341
+ // `bauto` before the registry renamed it to `drt-loop`) to their current
1342
+ // canonical code up front. Without this, a renamed module's old installs
1343
+ // would fall out of `availableModuleIds` below and get silently frozen
1344
+ // (see the `baut` → `automator` incident in CHANGELOG v6.7.1) instead of
1345
+ // migrating forward.
1346
+ const aliasMigrations = [];
1347
+ const seenModuleIds = new Set();
1348
+ const installedModules = [];
1349
+ for (const rawId of existingInstall.moduleIds) {
1350
+ const canonicalId = await this.externalModuleManager.resolveCanonicalCode(rawId);
1351
+ if (canonicalId !== rawId) {
1352
+ aliasMigrations.push({ from: rawId, to: canonicalId });
1353
+ }
1354
+ if (!seenModuleIds.has(canonicalId)) {
1355
+ seenModuleIds.add(canonicalId);
1356
+ installedModules.push(canonicalId);
1357
+ }
1358
+ }
1359
+ for (const { from, to } of aliasMigrations) {
1360
+ await prompts.log.info(`Migrating installed module '${from}' to its renamed successor '${to}'.`);
1361
+ }
1362
+
1363
+ // Get available modules (what we have source for)
1364
+ const availableModulesData = await new OfficialModules().listAvailable();
1365
+ const availableModules = [...availableModulesData.modules];
1366
+
1367
+ // Add external official modules to available modules
1368
+ const externalModules = await this.externalModuleManager.listAvailable();
1369
+ for (const externalModule of externalModules) {
1370
+ if (installedModules.includes(externalModule.code) && !availableModules.some((m) => m.id === externalModule.code)) {
1371
+ availableModules.push({
1372
+ id: externalModule.code,
1373
+ name: externalModule.name,
1374
+ isExternal: true,
1375
+ fromExternal: true,
1376
+ });
1377
+ }
1378
+ }
1379
+
1380
+ // Add installed custom modules to available modules
1381
+ const { CustomModuleManager } = require('../modules/custom-module-manager');
1382
+ const customMgr = new CustomModuleManager();
1383
+ for (const moduleId of installedModules) {
1384
+ if (!availableModules.some((m) => m.id === moduleId)) {
1385
+ const customSource = await customMgr.findModuleSourceByCode(moduleId, { drtDir });
1386
+ if (customSource) {
1387
+ availableModules.push({
1388
+ id: moduleId,
1389
+ name: moduleId,
1390
+ isExternal: true,
1391
+ fromCustom: true,
1392
+ });
1393
+ }
1394
+ }
1395
+ }
1396
+
1397
+ const availableModuleIds = new Set(availableModules.map((m) => m.id));
1398
+
1399
+ // Only update modules that are BOTH installed AND available (we have source for)
1400
+ const modulesToUpdate = installedModules.filter((id) => availableModuleIds.has(id));
1401
+ const skippedModules = installedModules.filter((id) => !availableModuleIds.has(id));
1402
+
1403
+ if (skippedModules.length > 0) {
1404
+ await prompts.log.warn(`Skipping ${skippedModules.length} module(s) - no source available: ${skippedModules.join(', ')}`);
1405
+ }
1406
+
1407
+ // Build channel options from the existing manifest FIRST so the config
1408
+ // collector below (which triggers external-module clones via
1409
+ // findModuleSource) knows each module's recorded channel and doesn't
1410
+ // silently redecide it. Without this, modules previously on 'next' or
1411
+ // 'pinned' would trigger a stable-channel tag lookup at config-collection
1412
+ // time, burning GitHub API quota and potentially failing.
1413
+ const manifestData = await this.manifest.read(drtDir);
1414
+ const channelOptions = { global: null, nextSet: new Set(), pins: new Map(), warnings: [] };
1415
+ if (manifestData?.modulesDetailed) {
1416
+ const { fetchStableTags, classifyUpgrade, parseGitHubRepo } = require('../modules/channel-resolver');
1417
+ for (const entry of manifestData.modulesDetailed) {
1418
+ if (!entry?.name || !entry?.channel) continue;
1419
+ if (entry.channel === 'pinned' && entry.version) {
1420
+ channelOptions.pins.set(entry.name, entry.version);
1421
+ continue;
1422
+ }
1423
+ if (entry.channel === 'next') {
1424
+ channelOptions.nextSet.add(entry.name);
1425
+ continue;
1426
+ }
1427
+ // Stable: classify the available upgrade. Patches and minors fall
1428
+ // through (stable default picks up the top tag). A major upgrade
1429
+ // requires opt-in, so under quick-update's non-interactive semantics
1430
+ // we pin to the current version to prevent a silent breaking jump.
1431
+ if (entry.channel === 'stable' && entry.version && entry.repoUrl) {
1432
+ const parsed = parseGitHubRepo(entry.repoUrl);
1433
+ if (!parsed) continue;
1434
+ try {
1435
+ const tags = await fetchStableTags(parsed.owner, parsed.repo);
1436
+ if (tags.length === 0) continue;
1437
+ const topTag = tags[0].tag;
1438
+ const cls = classifyUpgrade(entry.version, topTag);
1439
+ if (cls === 'major') {
1440
+ channelOptions.pins.set(entry.name, entry.version);
1441
+ await prompts.log.warn(
1442
+ `${entry.name} ${entry.version} → ${topTag} is a new major release; staying on ${entry.version}. ` +
1443
+ `Run \`drt install\` (Modify) with \`--pin ${entry.name}=${topTag}\` to accept.`,
1444
+ );
1445
+ }
1446
+ } catch (error) {
1447
+ // Tag lookup failed (offline, rate-limited). Stay on the current
1448
+ // version rather than guessing — the existing cache is already
1449
+ // at that ref, so re-using it keeps the install stable.
1450
+ channelOptions.pins.set(entry.name, entry.version);
1451
+ await prompts.log.warn(`Could not check ${entry.name} for updates (${error.message}); staying on ${entry.version}.`);
1452
+ }
1453
+ }
1454
+ }
1455
+ }
1456
+
1457
+ // Load existing configs and collect new fields (if any)
1458
+ await prompts.log.info('Checking for new configuration options...');
1459
+ const quickModules = new OfficialModules({ channelOptions });
1460
+ await quickModules.loadExistingConfig(projectDir);
1461
+
1462
+ let promptedForNewFields = false;
1463
+
1464
+ const corePrompted = await quickModules.collectModuleConfigQuick('core', projectDir, true);
1465
+ if (corePrompted) {
1466
+ promptedForNewFields = true;
1467
+ }
1468
+
1469
+ for (const moduleName of modulesToUpdate) {
1470
+ if (moduleName === 'core') continue; // Already collected above
1471
+ const modulePrompted = await quickModules.collectModuleConfigQuick(moduleName, projectDir, true);
1472
+ if (modulePrompted) {
1473
+ promptedForNewFields = true;
1474
+ }
1475
+ }
1476
+
1477
+ if (!promptedForNewFields) {
1478
+ await prompts.log.success('All configuration is up to date, no new options to configure');
1479
+ }
1480
+
1481
+ quickModules.collectedConfig._meta = {
1482
+ version: require(path.join(getProjectRoot(), 'package.json')).version,
1483
+ installDate: new Date().toISOString(),
1484
+ lastModified: new Date().toISOString(),
1485
+ };
1486
+
1487
+ // Build config and delegate to install()
1488
+ const installConfig = {
1489
+ directory: projectDir,
1490
+ modules: modulesToUpdate,
1491
+ ides: configuredIdes,
1492
+ coreConfig: quickModules.collectedConfig.core,
1493
+ moduleConfigs: quickModules.collectedConfig,
1494
+ // Forward `--set` overrides so the post-install patch step
1495
+ // (`applySetOverrides`) runs at the end of quick-update too. The
1496
+ // installer.install path applies them after writeCentralConfig.
1497
+ setOverrides: config.setOverrides || {},
1498
+ actionType: 'install',
1499
+ _quickUpdate: true,
1500
+ _preserveModules: skippedModules,
1501
+ _existingModules: installedModules,
1502
+ channelOptions,
1503
+ };
1504
+
1505
+ await this.install(installConfig);
1506
+
1507
+ // Now that the canonical module has been installed successfully, remove
1508
+ // the stale directory left behind under its old code so the two don't
1509
+ // coexist (e.g. `_drt/bauto/` once `_drt/drt-loop/` is in place).
1510
+ for (const { from, to } of aliasMigrations) {
1511
+ if (!modulesToUpdate.includes(to)) continue; // new code wasn't actually installed this run
1512
+ const oldModuleDir = path.join(drtDir, from);
1513
+ if (await fs.pathExists(oldModuleDir)) {
1514
+ await fs.remove(oldModuleDir);
1515
+ await prompts.log.success(`Removed legacy '${from}' directory after migrating to '${to}'.`);
1516
+ }
1517
+ }
1518
+
1519
+ return {
1520
+ success: true,
1521
+ moduleCount: modulesToUpdate.length,
1522
+ hadNewFields: promptedForNewFields,
1523
+ modules: modulesToUpdate,
1524
+ skippedModules: skippedModules,
1525
+ ides: configuredIdes,
1526
+ };
1527
+ }
1528
+
1529
+ /**
1530
+ * Uninstall DRT with selective removal options
1531
+ * @param {string} directory - Project directory
1532
+ * @param {Object} options - Uninstall options
1533
+ * @param {boolean} [options.removeModules=true] - Remove _drt/ directory
1534
+ * @param {boolean} [options.removeIdeConfigs=true] - Remove IDE configurations
1535
+ * @param {boolean} [options.removeOutputFolder=false] - Remove user artifacts output folder
1536
+ * @returns {Object} Result with success status and removed components
1537
+ */
1538
+ async uninstall(directory, options = {}) {
1539
+ const projectDir = path.resolve(directory);
1540
+ const { drtDir } = await this.findDrtDir(projectDir);
1541
+
1542
+ if (!(await fs.pathExists(drtDir))) {
1543
+ return { success: false, reason: 'not-installed' };
1544
+ }
1545
+
1546
+ // 1. DETECT: Read state BEFORE deleting anything
1547
+ const existingInstall = await ExistingInstall.detect(drtDir);
1548
+ const outputFolder = await this._readOutputFolder(drtDir);
1549
+
1550
+ const removed = { modules: false, ideConfigs: false, outputFolder: false };
1551
+
1552
+ // 2. IDE CLEANUP (before _drt/ deletion so configs are accessible)
1553
+ if (options.removeIdeConfigs !== false) {
1554
+ await this.uninstallIdeConfigs(projectDir, existingInstall, { silent: options.silent });
1555
+ removed.ideConfigs = true;
1556
+ }
1557
+
1558
+ // 3. OUTPUT FOLDER (only if explicitly requested)
1559
+ if (options.removeOutputFolder === true && outputFolder) {
1560
+ removed.outputFolder = await this.uninstallOutputFolder(projectDir, outputFolder);
1561
+ }
1562
+
1563
+ // 4. DRT DIRECTORY (last, after everything that needs it)
1564
+ if (options.removeModules !== false) {
1565
+ removed.modules = await this.uninstallModules(projectDir);
1566
+ }
1567
+
1568
+ return { success: true, removed, version: existingInstall.installed ? existingInstall.version : null };
1569
+ }
1570
+
1571
+ /**
1572
+ * Uninstall IDE configurations only
1573
+ * @param {string} projectDir - Project directory
1574
+ * @param {Object} existingInstall - Detection result from detector.detect()
1575
+ * @param {Object} [options] - Options (e.g. { silent: true })
1576
+ * @returns {Promise<Object>} Results from IDE cleanup
1577
+ */
1578
+ async uninstallIdeConfigs(projectDir, existingInstall, options = {}) {
1579
+ await this.ideManager.ensureInitialized();
1580
+ const cleanupOptions = { isUninstall: true, silent: options.silent };
1581
+ const ideList = existingInstall.ides;
1582
+ if (ideList.length > 0) {
1583
+ return this.ideManager.cleanupByList(projectDir, ideList, cleanupOptions);
1584
+ }
1585
+ return this.ideManager.cleanup(projectDir, cleanupOptions);
1586
+ }
1587
+
1588
+ /**
1589
+ * Remove user artifacts output folder
1590
+ * @param {string} projectDir - Project directory
1591
+ * @param {string} outputFolder - Output folder name (relative)
1592
+ * @returns {Promise<boolean>} Whether the folder was removed
1593
+ */
1594
+ async uninstallOutputFolder(projectDir, outputFolder) {
1595
+ if (!outputFolder) return false;
1596
+ const resolvedProject = path.resolve(projectDir);
1597
+ const outputPath = path.resolve(resolvedProject, outputFolder);
1598
+ if (!outputPath.startsWith(resolvedProject + path.sep)) {
1599
+ return false;
1600
+ }
1601
+ if (await fs.pathExists(outputPath)) {
1602
+ await fs.remove(outputPath);
1603
+ return true;
1604
+ }
1605
+ return false;
1606
+ }
1607
+
1608
+ /**
1609
+ * Remove the _drt/ directory
1610
+ * @param {string} projectDir - Project directory
1611
+ * @returns {Promise<boolean>} Whether the directory was removed
1612
+ */
1613
+ async uninstallModules(projectDir) {
1614
+ const { drtDir } = await this.findDrtDir(projectDir);
1615
+ if (await fs.pathExists(drtDir)) {
1616
+ await fs.remove(drtDir);
1617
+ return true;
1618
+ }
1619
+ return false;
1620
+ }
1621
+
1622
+ /**
1623
+ * Get installation status
1624
+ */
1625
+ async getStatus(directory) {
1626
+ const projectDir = path.resolve(directory);
1627
+ const { drtDir } = await this.findDrtDir(projectDir);
1628
+ return await ExistingInstall.detect(drtDir);
1629
+ }
1630
+
1631
+ /**
1632
+ * Get available modules
1633
+ */
1634
+ async getAvailableModules() {
1635
+ return await new OfficialModules().listAvailable();
1636
+ }
1637
+
1638
+ /**
1639
+ * Get the configured output folder name for a project
1640
+ * Resolves drtDir internally from projectDir
1641
+ * @param {string} projectDir - Project directory
1642
+ * @returns {string} Output folder name (relative, default: '_drt-output')
1643
+ */
1644
+ async getOutputFolder(projectDir) {
1645
+ const { drtDir } = await this.findDrtDir(projectDir);
1646
+ return this._readOutputFolder(drtDir);
1647
+ }
1648
+
1649
+ /**
1650
+ * Find the drt installation directory in a project
1651
+ * Always uses the standard _drt folder name
1652
+ * @param {string} projectDir - Project directory
1653
+ * @returns {Promise<Object>} { drtDir: string }
1654
+ */
1655
+ async findDrtDir(projectDir) {
1656
+ const drtDir = path.join(projectDir, DRT_FOLDER_NAME);
1657
+ return { drtDir };
1658
+ }
1659
+
1660
+ /**
1661
+ * Read the output_folder setting from module config files
1662
+ * Checks bmm/config.yaml first, then other module configs
1663
+ * @param {string} drtDir - DRT installation directory
1664
+ * @returns {string} Output folder path or default
1665
+ */
1666
+ async _readOutputFolder(drtDir) {
1667
+ const yaml = require('yaml');
1668
+
1669
+ // Check bmm/config.yaml first (most common)
1670
+ const bmmConfigPath = path.join(drtDir, 'drt', 'config.yaml');
1671
+ if (await fs.pathExists(bmmConfigPath)) {
1672
+ try {
1673
+ const content = await fs.readFile(bmmConfigPath, 'utf8');
1674
+ const config = yaml.parse(content);
1675
+ if (config && config.output_folder) {
1676
+ // Strip {project-root}/ prefix if present
1677
+ return config.output_folder.replace(/^\{project-root\}[/\\]/, '');
1678
+ }
1679
+ } catch {
1680
+ // Fall through to other modules
1681
+ }
1682
+ }
1683
+
1684
+ // Scan other module config.yaml files
1685
+ try {
1686
+ const entries = await fs.readdir(drtDir, { withFileTypes: true });
1687
+ for (const entry of entries) {
1688
+ if (!entry.isDirectory() || entry.name === 'drt' || entry.name.startsWith('_')) continue;
1689
+ const configPath = path.join(drtDir, entry.name, 'config.yaml');
1690
+ if (await fs.pathExists(configPath)) {
1691
+ try {
1692
+ const content = await fs.readFile(configPath, 'utf8');
1693
+ const config = yaml.parse(content);
1694
+ if (config && config.output_folder) {
1695
+ return config.output_folder.replace(/^\{project-root\}[/\\]/, '');
1696
+ }
1697
+ } catch {
1698
+ // Continue scanning
1699
+ }
1700
+ }
1701
+ }
1702
+ } catch {
1703
+ // Directory scan failed
1704
+ }
1705
+
1706
+ // Default fallback
1707
+ return '_drt-output';
1708
+ }
1709
+
1710
+ /**
1711
+ * Parse a CSV line, handling quoted fields
1712
+ * @param {string} line - CSV line to parse
1713
+ * @returns {Array} Array of field values
1714
+ */
1715
+ parseCSVLine(line) {
1716
+ const result = [];
1717
+ let current = '';
1718
+ let inQuotes = false;
1719
+
1720
+ for (let i = 0; i < line.length; i++) {
1721
+ const char = line[i];
1722
+ const nextChar = line[i + 1];
1723
+
1724
+ if (char === '"') {
1725
+ if (inQuotes && nextChar === '"') {
1726
+ // Escaped quote
1727
+ current += '"';
1728
+ i++; // Skip next quote
1729
+ } else {
1730
+ // Toggle quote mode
1731
+ inQuotes = !inQuotes;
1732
+ }
1733
+ } else if (char === ',' && !inQuotes) {
1734
+ result.push(current);
1735
+ current = '';
1736
+ } else {
1737
+ current += char;
1738
+ }
1739
+ }
1740
+ result.push(current);
1741
+ return result;
1742
+ }
1743
+
1744
+ /**
1745
+ * Escape a CSV field if it contains special characters
1746
+ * @param {string} field - Field value to escape
1747
+ * @returns {string} Escaped field
1748
+ */
1749
+ escapeCSVField(field) {
1750
+ if (field === null || field === undefined) {
1751
+ return '';
1752
+ }
1753
+ const str = String(field);
1754
+ // If field contains comma, quote, or newline, wrap in quotes and escape inner quotes
1755
+ if (str.includes(',') || str.includes('"') || str.includes('\n')) {
1756
+ return `"${str.replaceAll('"', '""')}"`;
1757
+ }
1758
+ return str;
1759
+ }
1760
+ }
1761
+
1762
+ module.exports = { Installer };