mcp-adr-analysis-server 2.1.9 → 2.1.20

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 (408) hide show
  1. package/README.md +55 -8
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/src/index.d.ts +78 -2
  4. package/dist/src/index.d.ts.map +1 -1
  5. package/dist/src/index.js +1793 -577
  6. package/dist/src/index.js.map +1 -1
  7. package/dist/src/prompts/index.d.ts.map +1 -1
  8. package/dist/src/prompts/index.js +23 -6
  9. package/dist/src/prompts/index.js.map +1 -1
  10. package/dist/src/prompts/validated-pattern-prompts.d.ts +33 -0
  11. package/dist/src/prompts/validated-pattern-prompts.d.ts.map +1 -0
  12. package/dist/src/prompts/validated-pattern-prompts.js +337 -0
  13. package/dist/src/prompts/validated-pattern-prompts.js.map +1 -0
  14. package/dist/src/resources/adr-by-id-resource.d.ts +116 -0
  15. package/dist/src/resources/adr-by-id-resource.d.ts.map +1 -0
  16. package/dist/src/resources/adr-by-id-resource.js +213 -0
  17. package/dist/src/resources/adr-by-id-resource.js.map +1 -0
  18. package/dist/src/resources/code-quality-resource.d.ts +105 -0
  19. package/dist/src/resources/code-quality-resource.d.ts.map +1 -0
  20. package/dist/src/resources/code-quality-resource.js +282 -0
  21. package/dist/src/resources/code-quality-resource.js.map +1 -0
  22. package/dist/src/resources/deployment-history-resource.d.ts +214 -0
  23. package/dist/src/resources/deployment-history-resource.d.ts.map +1 -0
  24. package/dist/src/resources/deployment-history-resource.js +308 -0
  25. package/dist/src/resources/deployment-history-resource.js.map +1 -0
  26. package/dist/src/resources/deployment-status-resource.d.ts +256 -0
  27. package/dist/src/resources/deployment-status-resource.d.ts.map +1 -0
  28. package/dist/src/resources/deployment-status-resource.js +665 -0
  29. package/dist/src/resources/deployment-status-resource.js.map +1 -0
  30. package/dist/src/resources/environment-analysis-resource.d.ts +237 -0
  31. package/dist/src/resources/environment-analysis-resource.d.ts.map +1 -0
  32. package/dist/src/resources/environment-analysis-resource.js +646 -0
  33. package/dist/src/resources/environment-analysis-resource.js.map +1 -0
  34. package/dist/src/resources/index.d.ts +6 -2
  35. package/dist/src/resources/index.d.ts.map +1 -1
  36. package/dist/src/resources/index.js +247 -492
  37. package/dist/src/resources/index.js.map +1 -1
  38. package/dist/src/resources/memory-snapshots-resource.d.ts +180 -0
  39. package/dist/src/resources/memory-snapshots-resource.d.ts.map +1 -0
  40. package/dist/src/resources/memory-snapshots-resource.js +847 -0
  41. package/dist/src/resources/memory-snapshots-resource.js.map +1 -0
  42. package/dist/src/resources/pattern-base-code-by-platform-resource.d.ts +35 -0
  43. package/dist/src/resources/pattern-base-code-by-platform-resource.d.ts.map +1 -0
  44. package/dist/src/resources/pattern-base-code-by-platform-resource.js +72 -0
  45. package/dist/src/resources/pattern-base-code-by-platform-resource.js.map +1 -0
  46. package/dist/src/resources/pattern-by-name-resource.d.ts +53 -0
  47. package/dist/src/resources/pattern-by-name-resource.d.ts.map +1 -0
  48. package/dist/src/resources/pattern-by-name-resource.js +200 -0
  49. package/dist/src/resources/pattern-by-name-resource.js.map +1 -0
  50. package/dist/src/resources/pattern-sources-by-platform-resource.d.ts +26 -0
  51. package/dist/src/resources/pattern-sources-by-platform-resource.d.ts.map +1 -0
  52. package/dist/src/resources/pattern-sources-by-platform-resource.js +59 -0
  53. package/dist/src/resources/pattern-sources-by-platform-resource.js.map +1 -0
  54. package/dist/src/resources/project-metrics-resource.d.ts +180 -0
  55. package/dist/src/resources/project-metrics-resource.d.ts.map +1 -0
  56. package/dist/src/resources/project-metrics-resource.js +487 -0
  57. package/dist/src/resources/project-metrics-resource.js.map +1 -0
  58. package/dist/src/resources/project-status-resource.d.ts +75 -0
  59. package/dist/src/resources/project-status-resource.d.ts.map +1 -0
  60. package/dist/src/resources/project-status-resource.js +189 -0
  61. package/dist/src/resources/project-status-resource.js.map +1 -0
  62. package/dist/src/resources/research-by-topic-resource.d.ts +21 -0
  63. package/dist/src/resources/research-by-topic-resource.d.ts.map +1 -0
  64. package/dist/src/resources/research-by-topic-resource.js +125 -0
  65. package/dist/src/resources/research-by-topic-resource.js.map +1 -0
  66. package/dist/src/resources/research-index-resource.d.ts +100 -0
  67. package/dist/src/resources/research-index-resource.d.ts.map +1 -0
  68. package/dist/src/resources/research-index-resource.js +200 -0
  69. package/dist/src/resources/research-index-resource.js.map +1 -0
  70. package/dist/src/resources/resource-cache.d.ts +144 -0
  71. package/dist/src/resources/resource-cache.d.ts.map +1 -0
  72. package/dist/src/resources/resource-cache.js +316 -0
  73. package/dist/src/resources/resource-cache.js.map +1 -0
  74. package/dist/src/resources/resource-router.d.ts +45 -0
  75. package/dist/src/resources/resource-router.d.ts.map +1 -0
  76. package/dist/src/resources/resource-router.js +96 -0
  77. package/dist/src/resources/resource-router.js.map +1 -0
  78. package/dist/src/resources/rule-by-id-resource.d.ts +38 -0
  79. package/dist/src/resources/rule-by-id-resource.d.ts.map +1 -0
  80. package/dist/src/resources/rule-by-id-resource.js +104 -0
  81. package/dist/src/resources/rule-by-id-resource.js.map +1 -0
  82. package/dist/src/resources/rule-catalog-resource.d.ts +126 -0
  83. package/dist/src/resources/rule-catalog-resource.d.ts.map +1 -0
  84. package/dist/src/resources/rule-catalog-resource.js +224 -0
  85. package/dist/src/resources/rule-catalog-resource.js.map +1 -0
  86. package/dist/src/resources/rule-generation-resource.d.ts +80 -0
  87. package/dist/src/resources/rule-generation-resource.d.ts.map +1 -0
  88. package/dist/src/resources/rule-generation-resource.js +282 -0
  89. package/dist/src/resources/rule-generation-resource.js.map +1 -0
  90. package/dist/src/resources/technology-by-name-resource.d.ts +43 -0
  91. package/dist/src/resources/technology-by-name-resource.d.ts.map +1 -0
  92. package/dist/src/resources/technology-by-name-resource.js +176 -0
  93. package/dist/src/resources/technology-by-name-resource.js.map +1 -0
  94. package/dist/src/resources/todo-by-id-resource.d.ts +46 -0
  95. package/dist/src/resources/todo-by-id-resource.d.ts.map +1 -0
  96. package/dist/src/resources/todo-by-id-resource.js +192 -0
  97. package/dist/src/resources/todo-by-id-resource.js.map +1 -0
  98. package/dist/src/resources/todo-list-resource.d.ts +96 -0
  99. package/dist/src/resources/todo-list-resource.d.ts.map +1 -0
  100. package/dist/src/resources/todo-list-resource.js +209 -0
  101. package/dist/src/resources/todo-list-resource.js.map +1 -0
  102. package/dist/src/resources/validated-pattern-by-platform-resource.d.ts +14 -0
  103. package/dist/src/resources/validated-pattern-by-platform-resource.d.ts.map +1 -0
  104. package/dist/src/resources/validated-pattern-by-platform-resource.js +45 -0
  105. package/dist/src/resources/validated-pattern-by-platform-resource.js.map +1 -0
  106. package/dist/src/resources/validated-patterns-catalog-resource.d.ts +36 -0
  107. package/dist/src/resources/validated-patterns-catalog-resource.d.ts.map +1 -0
  108. package/dist/src/resources/validated-patterns-catalog-resource.js +57 -0
  109. package/dist/src/resources/validated-patterns-catalog-resource.js.map +1 -0
  110. package/dist/src/templates/domain-knowledge-templates.d.ts.map +1 -1
  111. package/dist/src/templates/domain-knowledge-templates.js +49 -49
  112. package/dist/src/templates/domain-knowledge-templates.js.map +1 -1
  113. package/dist/src/tools/adr-bootstrap-validation-tool.d.ts.map +1 -1
  114. package/dist/src/tools/adr-bootstrap-validation-tool.js +214 -4
  115. package/dist/src/tools/adr-bootstrap-validation-tool.js.map +1 -1
  116. package/dist/src/tools/adr-suggestion-tool.d.ts +2 -2
  117. package/dist/src/tools/adr-suggestion-tool.d.ts.map +1 -1
  118. package/dist/src/tools/adr-suggestion-tool.js +129 -12
  119. package/dist/src/tools/adr-suggestion-tool.js.map +1 -1
  120. package/dist/src/tools/adr-validation-tool.d.ts +98 -0
  121. package/dist/src/tools/adr-validation-tool.d.ts.map +1 -0
  122. package/dist/src/tools/adr-validation-tool.js +372 -0
  123. package/dist/src/tools/adr-validation-tool.js.map +1 -0
  124. package/dist/src/tools/bootstrap-validation-loop-tool.d.ts +262 -0
  125. package/dist/src/tools/bootstrap-validation-loop-tool.d.ts.map +1 -0
  126. package/dist/src/tools/bootstrap-validation-loop-tool.js +1934 -0
  127. package/dist/src/tools/bootstrap-validation-loop-tool.js.map +1 -0
  128. package/dist/src/tools/conversation-memory-tool.d.ts +48 -0
  129. package/dist/src/tools/conversation-memory-tool.d.ts.map +1 -0
  130. package/dist/src/tools/conversation-memory-tool.js +254 -0
  131. package/dist/src/tools/conversation-memory-tool.js.map +1 -0
  132. package/dist/src/tools/deployment-analysis-tool.d.ts.map +1 -1
  133. package/dist/src/tools/deployment-analysis-tool.js +82 -6
  134. package/dist/src/tools/deployment-analysis-tool.js.map +1 -1
  135. package/dist/src/tools/deployment-guidance-tool.d.ts.map +1 -1
  136. package/dist/src/tools/deployment-guidance-tool.js +126 -25
  137. package/dist/src/tools/deployment-guidance-tool.js.map +1 -1
  138. package/dist/src/tools/deployment-readiness-tool.d.ts.map +1 -1
  139. package/dist/src/tools/deployment-readiness-tool.js +166 -5
  140. package/dist/src/tools/deployment-readiness-tool.js.map +1 -1
  141. package/dist/src/tools/environment-analysis-tool.d.ts.map +1 -1
  142. package/dist/src/tools/environment-analysis-tool.js +36 -1
  143. package/dist/src/tools/environment-analysis-tool.js.map +1 -1
  144. package/dist/src/tools/expand-analysis-tool.d.ts +23 -0
  145. package/dist/src/tools/expand-analysis-tool.d.ts.map +1 -0
  146. package/dist/src/tools/expand-analysis-tool.js +107 -0
  147. package/dist/src/tools/expand-analysis-tool.js.map +1 -0
  148. package/dist/src/tools/get-server-context-tool.d.ts +67 -0
  149. package/dist/src/tools/get-server-context-tool.d.ts.map +1 -0
  150. package/dist/src/tools/get-server-context-tool.js +75 -0
  151. package/dist/src/tools/get-server-context-tool.js.map +1 -0
  152. package/dist/src/tools/interactive-adr-planning-tool.d.ts.map +1 -1
  153. package/dist/src/tools/interactive-adr-planning-tool.js +82 -9
  154. package/dist/src/tools/interactive-adr-planning-tool.js.map +1 -1
  155. package/dist/src/tools/llm-cloud-management-tool.d.ts +62 -0
  156. package/dist/src/tools/llm-cloud-management-tool.d.ts.map +1 -0
  157. package/dist/src/tools/llm-cloud-management-tool.js +202 -0
  158. package/dist/src/tools/llm-cloud-management-tool.js.map +1 -0
  159. package/dist/src/tools/llm-database-management-tool.d.ts +62 -0
  160. package/dist/src/tools/llm-database-management-tool.d.ts.map +1 -0
  161. package/dist/src/tools/llm-database-management-tool.js +203 -0
  162. package/dist/src/tools/llm-database-management-tool.js.map +1 -0
  163. package/dist/src/tools/llm-web-search-tool.d.ts +59 -0
  164. package/dist/src/tools/llm-web-search-tool.d.ts.map +1 -0
  165. package/dist/src/tools/llm-web-search-tool.js +165 -0
  166. package/dist/src/tools/llm-web-search-tool.js.map +1 -0
  167. package/dist/src/tools/mcp-planning-tool.d.ts.map +1 -1
  168. package/dist/src/tools/mcp-planning-tool.js +10 -3
  169. package/dist/src/tools/mcp-planning-tool.js.map +1 -1
  170. package/dist/src/tools/memory-loading-tool.d.ts.map +1 -1
  171. package/dist/src/tools/memory-loading-tool.js +4 -2
  172. package/dist/src/tools/memory-loading-tool.js.map +1 -1
  173. package/dist/src/tools/perform-research-tool.d.ts +61 -0
  174. package/dist/src/tools/perform-research-tool.d.ts.map +1 -0
  175. package/dist/src/tools/perform-research-tool.js +324 -0
  176. package/dist/src/tools/perform-research-tool.js.map +1 -0
  177. package/dist/src/tools/research-question-tool.d.ts.map +1 -1
  178. package/dist/src/tools/research-question-tool.js +11 -9
  179. package/dist/src/tools/research-question-tool.js.map +1 -1
  180. package/dist/src/tools/review-existing-adrs-tool.d.ts.map +1 -1
  181. package/dist/src/tools/review-existing-adrs-tool.js +42 -3
  182. package/dist/src/tools/review-existing-adrs-tool.js.map +1 -1
  183. package/dist/src/tools/tool-chain-orchestrator.d.ts +15 -94
  184. package/dist/src/tools/tool-chain-orchestrator.d.ts.map +1 -1
  185. package/dist/src/tools/tool-chain-orchestrator.js +2 -2
  186. package/dist/src/tools/tool-chain-orchestrator.js.map +1 -1
  187. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts +25 -120
  188. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts.map +1 -1
  189. package/dist/src/tools/troubleshoot-guided-workflow-tool.js +91 -2
  190. package/dist/src/tools/troubleshoot-guided-workflow-tool.js.map +1 -1
  191. package/dist/src/types/ape-framework.d.ts +50 -283
  192. package/dist/src/types/ape-framework.d.ts.map +1 -1
  193. package/dist/src/types/conversation-context.d.ts.map +1 -1
  194. package/dist/src/types/conversation-context.js +12 -12
  195. package/dist/src/types/conversation-context.js.map +1 -1
  196. package/dist/src/types/conversation-memory.d.ts +184 -0
  197. package/dist/src/types/conversation-memory.d.ts.map +1 -0
  198. package/dist/src/types/conversation-memory.js +8 -0
  199. package/dist/src/types/conversation-memory.js.map +1 -0
  200. package/dist/src/types/index.d.ts +112 -339
  201. package/dist/src/types/index.d.ts.map +1 -1
  202. package/dist/src/types/knowledge-generation.d.ts +96 -401
  203. package/dist/src/types/knowledge-generation.d.ts.map +1 -1
  204. package/dist/src/types/knowledge-graph-schemas.d.ts +77 -715
  205. package/dist/src/types/knowledge-graph-schemas.d.ts.map +1 -1
  206. package/dist/src/types/knowledge-graph-schemas.js +8 -8
  207. package/dist/src/types/knowledge-graph-schemas.js.map +1 -1
  208. package/dist/src/types/memory-entities.d.ts +1230 -6164
  209. package/dist/src/types/memory-entities.d.ts.map +1 -1
  210. package/dist/src/types/memory-entities.js +8 -8
  211. package/dist/src/types/memory-entities.js.map +1 -1
  212. package/dist/src/types/reflexion-framework.d.ts +35 -264
  213. package/dist/src/types/reflexion-framework.d.ts.map +1 -1
  214. package/dist/src/types/reflexion-framework.js +1 -1
  215. package/dist/src/types/reflexion-framework.js.map +1 -1
  216. package/dist/src/types/state-reinforcement.d.ts +87 -0
  217. package/dist/src/types/state-reinforcement.d.ts.map +1 -0
  218. package/dist/src/types/state-reinforcement.js +5 -0
  219. package/dist/src/types/state-reinforcement.js.map +1 -0
  220. package/dist/src/types/tiered-response.d.ts +61 -0
  221. package/dist/src/types/tiered-response.d.ts.map +1 -0
  222. package/dist/src/types/tiered-response.js +8 -0
  223. package/dist/src/types/tiered-response.js.map +1 -0
  224. package/dist/src/types/tool-context.d.ts +50 -0
  225. package/dist/src/types/tool-context.d.ts.map +1 -0
  226. package/dist/src/types/tool-context.js +20 -0
  227. package/dist/src/types/tool-context.js.map +1 -0
  228. package/dist/src/utils/adr-action-analyzer.d.ts +23 -0
  229. package/dist/src/utils/adr-action-analyzer.d.ts.map +1 -0
  230. package/dist/src/utils/adr-action-analyzer.js +323 -0
  231. package/dist/src/utils/adr-action-analyzer.js.map +1 -0
  232. package/dist/src/utils/adr-context-detector.d.ts +33 -0
  233. package/dist/src/utils/adr-context-detector.d.ts.map +1 -0
  234. package/dist/src/utils/adr-context-detector.js +279 -0
  235. package/dist/src/utils/adr-context-detector.js.map +1 -0
  236. package/dist/src/utils/adr-discovery.d.ts +28 -2
  237. package/dist/src/utils/adr-discovery.d.ts.map +1 -1
  238. package/dist/src/utils/adr-discovery.js +91 -7
  239. package/dist/src/utils/adr-discovery.js.map +1 -1
  240. package/dist/src/utils/adr-knowledge-initializer.d.ts +54 -0
  241. package/dist/src/utils/adr-knowledge-initializer.d.ts.map +1 -0
  242. package/dist/src/utils/adr-knowledge-initializer.js +240 -0
  243. package/dist/src/utils/adr-knowledge-initializer.js.map +1 -0
  244. package/dist/src/utils/adr-timeline-extractor.d.ts +21 -0
  245. package/dist/src/utils/adr-timeline-extractor.d.ts.map +1 -0
  246. package/dist/src/utils/adr-timeline-extractor.js +294 -0
  247. package/dist/src/utils/adr-timeline-extractor.js.map +1 -0
  248. package/dist/src/utils/adr-timeline-types.d.ts +234 -0
  249. package/dist/src/utils/adr-timeline-types.d.ts.map +1 -0
  250. package/dist/src/utils/adr-timeline-types.js +7 -0
  251. package/dist/src/utils/adr-timeline-types.js.map +1 -0
  252. package/dist/src/utils/ai-executor.d.ts +36 -0
  253. package/dist/src/utils/ai-executor.d.ts.map +1 -1
  254. package/dist/src/utils/ai-executor.js +39 -3
  255. package/dist/src/utils/ai-executor.js.map +1 -1
  256. package/dist/src/utils/apply-cot-enhancement.d.ts.map +1 -1
  257. package/dist/src/utils/apply-cot-enhancement.js +15 -15
  258. package/dist/src/utils/apply-cot-enhancement.js.map +1 -1
  259. package/dist/src/utils/automatic-prompt-engineering.d.ts.map +1 -1
  260. package/dist/src/utils/automatic-prompt-engineering.js +68 -58
  261. package/dist/src/utils/automatic-prompt-engineering.js.map +1 -1
  262. package/dist/src/utils/conditional-request.d.ts +105 -0
  263. package/dist/src/utils/conditional-request.d.ts.map +1 -0
  264. package/dist/src/utils/conditional-request.js +186 -0
  265. package/dist/src/utils/conditional-request.js.map +1 -0
  266. package/dist/src/utils/config.d.ts +72 -18
  267. package/dist/src/utils/config.d.ts.map +1 -1
  268. package/dist/src/utils/config.js +75 -0
  269. package/dist/src/utils/config.js.map +1 -1
  270. package/dist/src/utils/context-document-manager.d.ts +112 -0
  271. package/dist/src/utils/context-document-manager.d.ts.map +1 -0
  272. package/dist/src/utils/context-document-manager.js +351 -0
  273. package/dist/src/utils/context-document-manager.js.map +1 -0
  274. package/dist/src/utils/conversation-memory-manager.d.ts +86 -0
  275. package/dist/src/utils/conversation-memory-manager.d.ts.map +1 -0
  276. package/dist/src/utils/conversation-memory-manager.js +443 -0
  277. package/dist/src/utils/conversation-memory-manager.js.map +1 -0
  278. package/dist/src/utils/dag-executor.d.ts +106 -0
  279. package/dist/src/utils/dag-executor.d.ts.map +1 -0
  280. package/dist/src/utils/dag-executor.js +453 -0
  281. package/dist/src/utils/dag-executor.js.map +1 -0
  282. package/dist/src/utils/deployment-analysis.d.ts.map +1 -1
  283. package/dist/src/utils/deployment-analysis.js +17 -9
  284. package/dist/src/utils/deployment-analysis.js.map +1 -1
  285. package/dist/src/utils/deployment-type-registry.d.ts +52 -0
  286. package/dist/src/utils/deployment-type-registry.d.ts.map +1 -0
  287. package/dist/src/utils/deployment-type-registry.js +543 -0
  288. package/dist/src/utils/deployment-type-registry.js.map +1 -0
  289. package/dist/src/utils/dynamic-deployment-intelligence.d.ts +117 -0
  290. package/dist/src/utils/dynamic-deployment-intelligence.d.ts.map +1 -0
  291. package/dist/src/utils/dynamic-deployment-intelligence.js +445 -0
  292. package/dist/src/utils/dynamic-deployment-intelligence.js.map +1 -0
  293. package/dist/src/utils/environment-analysis.d.ts.map +1 -1
  294. package/dist/src/utils/environment-analysis.js +63 -44
  295. package/dist/src/utils/environment-analysis.js.map +1 -1
  296. package/dist/src/utils/environment-capability-registry.d.ts +101 -0
  297. package/dist/src/utils/environment-capability-registry.d.ts.map +1 -0
  298. package/dist/src/utils/environment-capability-registry.js +489 -0
  299. package/dist/src/utils/environment-capability-registry.js.map +1 -0
  300. package/dist/src/utils/index.d.ts +3 -3
  301. package/dist/src/utils/index.d.ts.map +1 -1
  302. package/dist/src/utils/index.js +3 -3
  303. package/dist/src/utils/index.js.map +1 -1
  304. package/dist/src/utils/knowledge-generation.d.ts.map +1 -1
  305. package/dist/src/utils/knowledge-generation.js +61 -35
  306. package/dist/src/utils/knowledge-generation.js.map +1 -1
  307. package/dist/src/utils/knowledge-graph-manager.d.ts +19 -0
  308. package/dist/src/utils/knowledge-graph-manager.d.ts.map +1 -1
  309. package/dist/src/utils/knowledge-graph-manager.js +165 -1
  310. package/dist/src/utils/knowledge-graph-manager.js.map +1 -1
  311. package/dist/src/utils/llm-artifact-detector.d.ts.map +1 -1
  312. package/dist/src/utils/llm-artifact-detector.js +28 -24
  313. package/dist/src/utils/llm-artifact-detector.js.map +1 -1
  314. package/dist/src/utils/mermaid-diagrams.d.ts +101 -0
  315. package/dist/src/utils/mermaid-diagrams.d.ts.map +1 -0
  316. package/dist/src/utils/mermaid-diagrams.js +445 -0
  317. package/dist/src/utils/mermaid-diagrams.js.map +1 -0
  318. package/dist/src/utils/monitoring.d.ts +249 -0
  319. package/dist/src/utils/monitoring.d.ts.map +1 -0
  320. package/dist/src/utils/monitoring.js +513 -0
  321. package/dist/src/utils/monitoring.js.map +1 -0
  322. package/dist/src/utils/pattern-contribution-helper.d.ts +60 -0
  323. package/dist/src/utils/pattern-contribution-helper.d.ts.map +1 -0
  324. package/dist/src/utils/pattern-contribution-helper.js +308 -0
  325. package/dist/src/utils/pattern-contribution-helper.js.map +1 -0
  326. package/dist/src/utils/pattern-loader.d.ts +183 -0
  327. package/dist/src/utils/pattern-loader.d.ts.map +1 -0
  328. package/dist/src/utils/pattern-loader.js +200 -0
  329. package/dist/src/utils/pattern-loader.js.map +1 -0
  330. package/dist/src/utils/pattern-research-utility.d.ts +107 -0
  331. package/dist/src/utils/pattern-research-utility.d.ts.map +1 -0
  332. package/dist/src/utils/pattern-research-utility.js +360 -0
  333. package/dist/src/utils/pattern-research-utility.js.map +1 -0
  334. package/dist/src/utils/pattern-to-dag-converter.d.ts +62 -0
  335. package/dist/src/utils/pattern-to-dag-converter.d.ts.map +1 -0
  336. package/dist/src/utils/pattern-to-dag-converter.js +265 -0
  337. package/dist/src/utils/pattern-to-dag-converter.js.map +1 -0
  338. package/dist/src/utils/platform-detector.d.ts +86 -0
  339. package/dist/src/utils/platform-detector.d.ts.map +1 -0
  340. package/dist/src/utils/platform-detector.js +509 -0
  341. package/dist/src/utils/platform-detector.js.map +1 -0
  342. package/dist/src/utils/prompt-composition.d.ts.map +1 -1
  343. package/dist/src/utils/prompt-composition.js +1 -4
  344. package/dist/src/utils/prompt-composition.js.map +1 -1
  345. package/dist/src/utils/reflexion.d.ts.map +1 -1
  346. package/dist/src/utils/reflexion.js +51 -42
  347. package/dist/src/utils/reflexion.js.map +1 -1
  348. package/dist/src/utils/research-integration.d.ts.map +1 -1
  349. package/dist/src/utils/research-integration.js +8 -2
  350. package/dist/src/utils/research-integration.js.map +1 -1
  351. package/dist/src/utils/research-orchestrator.d.ts +209 -0
  352. package/dist/src/utils/research-orchestrator.d.ts.map +1 -0
  353. package/dist/src/utils/research-orchestrator.js +863 -0
  354. package/dist/src/utils/research-orchestrator.js.map +1 -0
  355. package/dist/src/utils/research-questions.d.ts.map +1 -1
  356. package/dist/src/utils/research-questions.js +4 -1
  357. package/dist/src/utils/research-questions.js.map +1 -1
  358. package/dist/src/utils/resource-extractor.d.ts +57 -0
  359. package/dist/src/utils/resource-extractor.d.ts.map +1 -0
  360. package/dist/src/utils/resource-extractor.js +323 -0
  361. package/dist/src/utils/resource-extractor.js.map +1 -0
  362. package/dist/src/utils/resource-versioning.d.ts +124 -0
  363. package/dist/src/utils/resource-versioning.d.ts.map +1 -0
  364. package/dist/src/utils/resource-versioning.js +272 -0
  365. package/dist/src/utils/resource-versioning.js.map +1 -0
  366. package/dist/src/utils/root-manager.d.ts +118 -0
  367. package/dist/src/utils/root-manager.d.ts.map +1 -0
  368. package/dist/src/utils/root-manager.js +154 -0
  369. package/dist/src/utils/root-manager.js.map +1 -0
  370. package/dist/src/utils/rule-generation.d.ts.map +1 -1
  371. package/dist/src/utils/rule-generation.js +4 -1
  372. package/dist/src/utils/rule-generation.js.map +1 -1
  373. package/dist/src/utils/server-context-generator.d.ts +47 -0
  374. package/dist/src/utils/server-context-generator.d.ts.map +1 -0
  375. package/dist/src/utils/server-context-generator.js +666 -0
  376. package/dist/src/utils/server-context-generator.js.map +1 -0
  377. package/dist/src/utils/state-reinforcement-manager.d.ts +60 -0
  378. package/dist/src/utils/state-reinforcement-manager.d.ts.map +1 -0
  379. package/dist/src/utils/state-reinforcement-manager.js +200 -0
  380. package/dist/src/utils/state-reinforcement-manager.js.map +1 -0
  381. package/dist/src/utils/system-card-manager.d.ts +194 -0
  382. package/dist/src/utils/system-card-manager.d.ts.map +1 -0
  383. package/dist/src/utils/system-card-manager.js +336 -0
  384. package/dist/src/utils/system-card-manager.js.map +1 -0
  385. package/dist/src/utils/tiered-response-manager.d.ts +40 -0
  386. package/dist/src/utils/tiered-response-manager.d.ts.map +1 -0
  387. package/dist/src/utils/tiered-response-manager.js +243 -0
  388. package/dist/src/utils/tiered-response-manager.js.map +1 -0
  389. package/dist/src/utils/tree-sitter-analyzer.d.ts.map +1 -1
  390. package/dist/src/utils/tree-sitter-analyzer.js +83 -11
  391. package/dist/src/utils/tree-sitter-analyzer.js.map +1 -1
  392. package/dist/src/utils/validated-pattern-definitions.d.ts +219 -0
  393. package/dist/src/utils/validated-pattern-definitions.d.ts.map +1 -0
  394. package/dist/src/utils/validated-pattern-definitions.js +1511 -0
  395. package/dist/src/utils/validated-pattern-definitions.js.map +1 -0
  396. package/package.json +22 -13
  397. package/dist/src/prompts/todo-prompts.d.ts +0 -49
  398. package/dist/src/prompts/todo-prompts.d.ts.map +0 -1
  399. package/dist/src/prompts/todo-prompts.js +0 -824
  400. package/dist/src/prompts/todo-prompts.js.map +0 -1
  401. package/dist/src/types/todo-json-schemas.d.ts +0 -17
  402. package/dist/src/types/todo-json-schemas.d.ts.map +0 -1
  403. package/dist/src/types/todo-json-schemas.js +0 -9
  404. package/dist/src/types/todo-json-schemas.js.map +0 -1
  405. package/dist/src/utils/todo-file-watcher.d.ts +0 -14
  406. package/dist/src/utils/todo-file-watcher.d.ts.map +0 -1
  407. package/dist/src/utils/todo-file-watcher.js +0 -25
  408. package/dist/src/utils/todo-file-watcher.js.map +0 -1
@@ -0,0 +1,1934 @@
1
+ /**
2
+ * MCP Tool for Bootstrap Validation Loop with ADR Learning
3
+ *
4
+ * Implements a self-learning architecture validation system:
5
+ * 1. Generate bootstrap scripts from ADRs
6
+ * 2. Execute scripts in real environment with monitoring
7
+ * 3. Capture learnings and failures
8
+ * 4. Mask sensitive information
9
+ * 5. Update ADRs with deployment experience
10
+ * 6. Re-generate improved scripts
11
+ * 7. Validate until success
12
+ *
13
+ * This creates a bidirectional feedback loop where ADRs evolve
14
+ * based on real-world deployment experience.
15
+ */
16
+ import { promises as fs } from 'fs';
17
+ import { exec } from 'child_process';
18
+ import { promisify } from 'util';
19
+ import * as path from 'path';
20
+ import { createHash } from 'crypto';
21
+ import { McpAdrError } from '../types/index.js';
22
+ import { EnhancedLogger } from '../utils/enhanced-logging.js';
23
+ import { ResearchOrchestrator } from '../utils/research-orchestrator.js';
24
+ import { MemoryEntityManager } from '../utils/memory-entity-manager.js';
25
+ import { DynamicDeploymentIntelligence, } from '../utils/dynamic-deployment-intelligence.js';
26
+ import generateAdrBootstrapScripts from './adr-bootstrap-validation-tool.js';
27
+ // NEW: Validated Patterns Integration
28
+ import { detectPlatforms } from '../utils/platform-detector.js';
29
+ import { getPattern } from '../utils/validated-pattern-definitions.js';
30
+ import { generatePatternResearchReport } from '../utils/pattern-research-utility.js';
31
+ // NEW: Tool Context Documentation System
32
+ import { ToolContextManager } from '../utils/context-document-manager.js';
33
+ // NEW: Hybrid DAG Architecture
34
+ import { DAGExecutor } from '../utils/dag-executor.js';
35
+ import { PatternToDAGConverter } from '../utils/pattern-to-dag-converter.js';
36
+ import { PatternContributionHelper } from '../utils/pattern-contribution-helper.js';
37
+ import { PatternLoader } from '../utils/pattern-loader.js';
38
+ // NEW: SystemCard for Resource Tracking
39
+ import { SystemCardManager } from '../utils/system-card-manager.js';
40
+ const execAsync = promisify(exec);
41
+ /**
42
+ * Bootstrap Validation Loop orchestrator
43
+ */
44
+ export class BootstrapValidationLoop {
45
+ logger;
46
+ projectPath;
47
+ adrDirectory;
48
+ researchOrchestrator;
49
+ memoryManager;
50
+ deploymentIntelligence;
51
+ executionHistory = [];
52
+ maxIterations;
53
+ currentIteration = 0;
54
+ deploymentPlan = null;
55
+ // NEW: Validated Patterns fields
56
+ platformDetection = null;
57
+ validatedPattern = null;
58
+ patternResearchReport = null;
59
+ // NEW: Tool Context Documentation
60
+ contextManager;
61
+ // NEW: Hybrid DAG Architecture
62
+ dagExecutor;
63
+ patternLoader;
64
+ patternConverter;
65
+ contributionHelper;
66
+ // NEW: SystemCard Resource Tracking
67
+ systemCardManager;
68
+ constructor(projectPath, adrDirectory, maxIterations = 5) {
69
+ this.logger = new EnhancedLogger();
70
+ this.projectPath = projectPath;
71
+ this.adrDirectory = adrDirectory;
72
+ this.maxIterations = maxIterations;
73
+ this.researchOrchestrator = new ResearchOrchestrator(projectPath, adrDirectory);
74
+ this.memoryManager = new MemoryEntityManager();
75
+ this.deploymentIntelligence = new DynamicDeploymentIntelligence(projectPath, adrDirectory);
76
+ this.contextManager = new ToolContextManager(projectPath);
77
+ // Initialize SystemCard for resource tracking (must be before DAGExecutor)
78
+ this.systemCardManager = new SystemCardManager(projectPath);
79
+ // Initialize DAG architecture components
80
+ this.dagExecutor = new DAGExecutor(5, this.systemCardManager); // Max 5 parallel tasks, with resource tracking
81
+ this.patternLoader = new PatternLoader();
82
+ this.patternConverter = new PatternToDAGConverter();
83
+ this.contributionHelper = new PatternContributionHelper();
84
+ }
85
+ /**
86
+ * Initialize the validation loop
87
+ */
88
+ async initialize() {
89
+ await this.memoryManager.initialize();
90
+ await this.contextManager.initialize();
91
+ this.logger.info('Bootstrap Validation Loop initialized', 'BootstrapValidationLoop', {
92
+ projectPath: this.projectPath,
93
+ adrDirectory: this.adrDirectory,
94
+ maxIterations: this.maxIterations,
95
+ });
96
+ }
97
+ /**
98
+ * Execute the complete validation loop
99
+ */
100
+ async executeLoop(args) {
101
+ const { targetEnvironment, autoFix, captureEnvironmentSnapshot, updateAdrsWithLearnings } = args;
102
+ this.logger.info('Starting Bootstrap Validation Loop', 'BootstrapValidationLoop', {
103
+ targetEnvironment,
104
+ autoFix,
105
+ maxIterations: this.maxIterations,
106
+ });
107
+ // STEP 0: Detect platform using Validated Patterns framework
108
+ this.logger.info('🔍 Detecting platform type using Validated Patterns...', 'BootstrapValidationLoop');
109
+ this.platformDetection = await detectPlatforms(this.projectPath);
110
+ this.logger.info(`📋 Platform detection complete (confidence: ${(this.platformDetection.confidence * 100).toFixed(0)}%)`, 'BootstrapValidationLoop', {
111
+ primaryPlatform: this.platformDetection.primaryPlatform,
112
+ detectedPlatforms: this.platformDetection.detectedPlatforms.map(p => p.type),
113
+ evidence: this.platformDetection.evidence.length,
114
+ });
115
+ // STEP 0.1: Get validated pattern for detected platform
116
+ if (this.platformDetection.primaryPlatform) {
117
+ this.validatedPattern = getPattern(this.platformDetection.primaryPlatform);
118
+ if (this.validatedPattern) {
119
+ this.logger.info(`✅ Loaded validated pattern: ${this.validatedPattern.name}`, 'BootstrapValidationLoop', {
120
+ version: this.validatedPattern.version,
121
+ lastUpdated: this.validatedPattern.metadata.lastUpdated,
122
+ authoritativeSources: this.validatedPattern.authoritativeSources.length,
123
+ requiredSources: this.validatedPattern.authoritativeSources.filter(s => s.requiredForDeployment).length,
124
+ });
125
+ // STEP 0.2: Generate research report for authoritative sources
126
+ this.patternResearchReport = generatePatternResearchReport(this.platformDetection.primaryPlatform);
127
+ this.logger.info('📚 Generated research report with authoritative source instructions', 'BootstrapValidationLoop');
128
+ this.logger.info(`⚠️ IMPORTANT: LLM should query ${this.validatedPattern.authoritativeSources.filter(s => s.requiredForDeployment).length} REQUIRED authoritative sources before deployment`, 'BootstrapValidationLoop');
129
+ // Log the research report for LLM to see
130
+ this.logger.info('📖 Research Report:\n' + this.patternResearchReport, 'BootstrapValidationLoop');
131
+ }
132
+ else {
133
+ this.logger.warn(`No validated pattern found for ${this.platformDetection.primaryPlatform}, falling back to dynamic intelligence`, 'BootstrapValidationLoop');
134
+ }
135
+ }
136
+ // STEP 0.3: Generate AI-powered deployment plan (fallback or hybrid approach)
137
+ this.logger.info('🤖 Generating dynamic deployment plan with AI + research...', 'BootstrapValidationLoop');
138
+ this.deploymentPlan = await this.deploymentIntelligence.generateDeploymentPlan();
139
+ this.logger.info(`📊 Deployment plan generated (confidence: ${this.deploymentPlan.confidence})`, 'BootstrapValidationLoop', {
140
+ platforms: this.deploymentPlan.detectedPlatforms,
141
+ recommended: this.deploymentPlan.recommendedPlatform,
142
+ source: this.deploymentPlan.source,
143
+ requiredFiles: this.deploymentPlan.requiredFiles.length,
144
+ });
145
+ // STEP 0.5: Create Bootstrap ADR for human review
146
+ const bootstrapAdrPath = await this.createBootstrapAdr(this.deploymentPlan);
147
+ this.logger.info(`📝 Bootstrap ADR created: ${bootstrapAdrPath}`, 'BootstrapValidationLoop');
148
+ // STEP 0.6: Save context document for future sessions
149
+ const contextDocumentPath = await this.saveBootstrapContext(this.platformDetection, this.validatedPattern, this.deploymentPlan, bootstrapAdrPath);
150
+ this.logger.info(`📄 Context document saved: ${contextDocumentPath}`, 'BootstrapValidationLoop');
151
+ this.logger.info('⏸️ WAITING FOR HUMAN APPROVAL - Review the bootstrap ADR before proceeding', 'BootstrapValidationLoop');
152
+ // ═══════════════════════════════════════════════════════════════════
153
+ // INFRASTRUCTURE LAYER (Hybrid DAG Architecture)
154
+ // ═══════════════════════════════════════════════════════════════════
155
+ // Execute infrastructure DAG before application deployment iterations
156
+ // This runs ONCE and sets up the platform infrastructure
157
+ this.logger.info('🏗️ Starting Infrastructure Layer (DAG-based execution)...', 'BootstrapValidationLoop');
158
+ const infrastructureResult = await this.executeInfrastructureDAG(this.platformDetection);
159
+ if (!infrastructureResult.success) {
160
+ const failedTasksList = infrastructureResult.failedTasks.join(', ');
161
+ this.logger.error(`❌ Infrastructure Layer failed: ${infrastructureResult.failedTasks.length} tasks failed`, 'BootstrapValidationLoop', undefined, {
162
+ failedTasks: infrastructureResult.failedTasks,
163
+ skippedTasks: infrastructureResult.skippedTasks,
164
+ });
165
+ // Infrastructure failure is critical - cannot proceed to application layer
166
+ throw new McpAdrError(`Infrastructure deployment failed. Failed tasks: ${failedTasksList}`, 'INFRASTRUCTURE_DEPLOYMENT_ERROR');
167
+ }
168
+ this.logger.info(`✅ Infrastructure Layer complete (${infrastructureResult.duration}ms)`, 'BootstrapValidationLoop', {
169
+ executedTasks: infrastructureResult.executedTasks.length,
170
+ duration: infrastructureResult.duration,
171
+ });
172
+ // ═══════════════════════════════════════════════════════════════════
173
+ // APPLICATION LAYER (Phase-based iteration with auto-fix)
174
+ // ═══════════════════════════════════════════════════════════════════
175
+ this.logger.info('🚀 Starting Application Layer (iterative deployment with auto-fix)...', 'BootstrapValidationLoop');
176
+ let success = false;
177
+ let finalResult = null;
178
+ const adrUpdates = [];
179
+ for (let i = 0; i < this.maxIterations; i++) {
180
+ this.currentIteration = i + 1;
181
+ this.logger.info(`Iteration ${this.currentIteration}/${this.maxIterations}`, 'BootstrapValidationLoop');
182
+ // Step 1: Generate bootstrap scripts from current ADRs
183
+ const scriptsGenerated = await this.generateBootstrapScripts();
184
+ if (!scriptsGenerated) {
185
+ throw new McpAdrError('Failed to generate bootstrap scripts', 'SCRIPT_GENERATION_ERROR');
186
+ }
187
+ // Step 1.5: Detect and handle missing files
188
+ this.logger.info('Detecting missing files referenced in ADRs...', 'BootstrapValidationLoop');
189
+ const missingFiles = await this.detectMissingFiles();
190
+ if (missingFiles.length > 0) {
191
+ this.logger.warn(`Found ${missingFiles.length} missing files`, 'BootstrapValidationLoop', {
192
+ critical: missingFiles.filter(f => f.severity === 'critical').length,
193
+ errors: missingFiles.filter(f => f.severity === 'error').length,
194
+ });
195
+ // Handle missing files (create templates, add prerequisites)
196
+ const missingFileLearnings = await this.handleMissingFiles(missingFiles);
197
+ // Log missing file handling results
198
+ this.logger.info(`Handled ${missingFileLearnings.length} missing file issues`, 'BootstrapValidationLoop', {
199
+ created: missingFileLearnings.filter(l => l.type === 'success').length,
200
+ prerequisites: missingFileLearnings.filter(l => l.type === 'prerequisite').length,
201
+ });
202
+ }
203
+ // Step 2: Execute bootstrap.sh with monitoring
204
+ const executionResult = await this.executeBootstrapWithMonitoring(targetEnvironment, captureEnvironmentSnapshot);
205
+ this.executionHistory.push(executionResult);
206
+ // Step 3: Run validation script and capture results
207
+ const validationResult = await this.executeValidationScript(executionResult.executionId);
208
+ executionResult.validationResults = validationResult.validationResults;
209
+ // Step 4: Analyze results and extract learnings
210
+ const learnings = await this.extractLearnings(executionResult, validationResult);
211
+ executionResult.learnings = learnings;
212
+ // Step 5: Store execution in memory system
213
+ await this.storeExecutionInMemory(executionResult);
214
+ // Check if validation passed
215
+ if (validationResult.allPassed) {
216
+ this.logger.info('✅ Validation passed!', 'BootstrapValidationLoop');
217
+ success = true;
218
+ finalResult = executionResult;
219
+ // Update ADRs with successful learnings
220
+ if (updateAdrsWithLearnings) {
221
+ const updates = await this.generateAdrUpdates(learnings, 'success');
222
+ adrUpdates.push(...updates);
223
+ }
224
+ break;
225
+ }
226
+ // Step 6: If auto-fix enabled, update scripts based on learnings
227
+ if (autoFix) {
228
+ this.logger.info('Auto-fixing bootstrap scripts based on failures', 'BootstrapValidationLoop');
229
+ const scriptsUpdated = await this.updateBootstrapScriptsFromLearnings(learnings, executionResult);
230
+ if (!scriptsUpdated) {
231
+ this.logger.warn('Failed to auto-fix scripts, stopping loop', 'BootstrapValidationLoop');
232
+ finalResult = executionResult;
233
+ break;
234
+ }
235
+ }
236
+ else {
237
+ // No auto-fix, stop after first iteration
238
+ finalResult = executionResult;
239
+ break;
240
+ }
241
+ finalResult = executionResult;
242
+ }
243
+ // Generate final ADR update proposals
244
+ if (updateAdrsWithLearnings && finalResult) {
245
+ const updates = await this.generateAdrUpdates(finalResult.learnings, success ? 'success' : 'failure');
246
+ adrUpdates.push(...updates);
247
+ }
248
+ // Ensure finalResult exists before proceeding
249
+ if (!finalResult) {
250
+ throw new McpAdrError('No execution result available - bootstrap validation loop failed to execute', 'EXECUTION_ERROR');
251
+ }
252
+ const result = {
253
+ success,
254
+ iterations: this.currentIteration,
255
+ finalResult,
256
+ adrUpdates,
257
+ executionHistory: this.executionHistory,
258
+ requiresHumanApproval: true,
259
+ };
260
+ // Only add optional properties if they have values
261
+ if (this.deploymentPlan) {
262
+ result.deploymentPlan = this.deploymentPlan;
263
+ }
264
+ if (bootstrapAdrPath) {
265
+ result.bootstrapAdrPath = bootstrapAdrPath;
266
+ }
267
+ if (contextDocumentPath) {
268
+ result.contextDocumentPath = contextDocumentPath;
269
+ }
270
+ return result;
271
+ }
272
+ /**
273
+ * Create Bootstrap ADR with deployment plan and architecture diagrams
274
+ */
275
+ async createBootstrapAdr(plan) {
276
+ try {
277
+ const adrContent = `# Bootstrap Deployment Plan
278
+
279
+ ## Status
280
+ PROPOSED - Awaiting human approval
281
+
282
+ ## Context
283
+ This ADR documents the automated deployment plan generated for this project.
284
+
285
+ **Detected Platforms**: ${plan.detectedPlatforms.join(', ')}
286
+ **Recommended Platform**: ${plan.recommendedPlatform}
287
+ **Confidence**: ${(plan.confidence * 100).toFixed(1)}%
288
+ **Source**: ${plan.source}
289
+ **Generated**: ${plan.timestamp}
290
+
291
+ ## Architecture Diagram
292
+
293
+ ${plan.architectureDiagram}
294
+
295
+ ## Required Files
296
+
297
+ ${plan.requiredFiles
298
+ .map(f => `
299
+ ### ${f.path}
300
+ - **Purpose**: ${f.purpose}
301
+ - **Required**: ${f.required ? 'Yes' : 'No'}
302
+ - **Secret**: ${f.isSecret ? 'Yes' : 'No'}
303
+ - **Can Auto-Generate**: ${f.canAutoGenerate ? 'Yes' : 'No'}
304
+ - **Best Practice**: ${f.currentBestPractice}
305
+ ${f.validationCommand ? `- **Validation**: \`${f.validationCommand}\`` : ''}
306
+ `)
307
+ .join('\n')}
308
+
309
+ ## Environment Variables
310
+
311
+ ${plan.environmentVariables
312
+ .map(e => `
313
+ - **${e.name}** (${e.required ? 'Required' : 'Optional'})${e.isSecret ? ' 🔒' : ''}
314
+ - ${e.purpose}
315
+ ${e.defaultValue ? `- Default: \`${e.defaultValue}\`` : ''}
316
+ `)
317
+ .join('\n')}
318
+
319
+ ## Deployment Steps
320
+
321
+ ${plan.deploymentSteps
322
+ .map(s => `
323
+ ### Step ${s.order}: ${s.title}
324
+ **Command**: \`${s.command}\`
325
+ **Description**: ${s.description}
326
+ **Expected Output**: ${s.expectedOutput}
327
+ **Estimated Time**: ${s.estimatedTime}
328
+
329
+ **Troubleshooting**:
330
+ ${s.troubleshooting.map(t => `- ${t}`).join('\n')}
331
+ `)
332
+ .join('\n')}
333
+
334
+ ## Validation Checks
335
+
336
+ ${plan.validationChecks
337
+ .map(c => `
338
+ - **${c.name}** (${c.severity})
339
+ - Command: \`${c.command}\`
340
+ - Expected: ${c.expectedResult}
341
+ `)
342
+ .join('\n')}
343
+
344
+ ## Risks
345
+
346
+ ${plan.risks
347
+ .map(r => `
348
+ ### ${r.risk} (${r.severity})
349
+ - **Likelihood**: ${r.likelihood}
350
+ - **Mitigation**: ${r.mitigation}
351
+ `)
352
+ .join('\n')}
353
+
354
+ ## Prerequisites
355
+
356
+ ${plan.prerequisites.map(p => `- ${p}`).join('\n')}
357
+
358
+ ## Estimated Duration
359
+ ${plan.estimatedDuration}
360
+
361
+ ## Research Sources
362
+
363
+ ${plan.researchSources.map(s => `- ${s}`).join('\n')}
364
+
365
+ ## Decision
366
+
367
+ **Status**: ⏸️ **AWAITING HUMAN APPROVAL**
368
+
369
+ Please review this deployment plan and:
370
+ 1. Verify the recommended platform is appropriate
371
+ 2. Check that all required files are identified
372
+ 3. Review security considerations (environment variables, secrets)
373
+ 4. Validate deployment steps make sense for your environment
374
+ 5. Approve or provide feedback for modifications
375
+
376
+ ## Consequences
377
+
378
+ ### Positive
379
+ - Automated deployment infrastructure
380
+ - Environment-aware configuration
381
+ - Validated deployment process
382
+
383
+ ### Negative
384
+ - Initial setup overhead
385
+ - Platform-specific complexity
386
+ - Maintenance requirements
387
+
388
+ ---
389
+ *This ADR was auto-generated by the Bootstrap Validation Loop system using AI-powered deployment intelligence.*
390
+ `;
391
+ // Ensure ADR directory exists
392
+ const adrDir = path.isAbsolute(this.adrDirectory)
393
+ ? this.adrDirectory
394
+ : path.join(this.projectPath, this.adrDirectory);
395
+ await fs.mkdir(adrDir, { recursive: true });
396
+ // Create absolute path for ADR file
397
+ const adrPath = path.join(adrDir, `bootstrap-deployment-${Date.now()}.md`);
398
+ await fs.writeFile(adrPath, adrContent, 'utf-8');
399
+ return adrPath;
400
+ }
401
+ catch (error) {
402
+ this.logger.error('Failed to create bootstrap ADR', 'BootstrapValidationLoop', error);
403
+ throw error;
404
+ }
405
+ }
406
+ /**
407
+ * Save bootstrap context document for future sessions
408
+ */
409
+ async saveBootstrapContext(platformDetection, validatedPattern, deploymentPlan, bootstrapAdrPath) {
410
+ try {
411
+ const contextDoc = {
412
+ metadata: {
413
+ toolName: 'bootstrap_validation_loop',
414
+ toolVersion: '1.0.0',
415
+ generated: new Date().toISOString(),
416
+ projectPath: this.projectPath,
417
+ projectName: path.basename(this.projectPath),
418
+ status: 'success',
419
+ confidence: platformDetection.confidence * 100,
420
+ },
421
+ quickReference: `
422
+ Detected ${platformDetection.primaryPlatform} (${(platformDetection.confidence * 100).toFixed(0)}% confidence).
423
+ ${validatedPattern ? `Using validated pattern: ${validatedPattern.name} v${validatedPattern.version}.` : 'Using dynamic AI analysis.'}
424
+ Bootstrap ADR: ${bootstrapAdrPath}
425
+ `.trim(),
426
+ executionSummary: {
427
+ status: 'Platform detected and deployment plan generated',
428
+ confidence: platformDetection.confidence * 100,
429
+ keyFindings: [
430
+ `Primary platform: ${platformDetection.primaryPlatform}`,
431
+ validatedPattern
432
+ ? `Validated pattern: ${validatedPattern.name}`
433
+ : 'Dynamic AI deployment plan',
434
+ `Required files: ${deploymentPlan.requiredFiles.length}`,
435
+ `Deployment steps: ${deploymentPlan.deploymentSteps.length}`,
436
+ `Environment variables: ${deploymentPlan.environmentVariables.length}`,
437
+ ],
438
+ },
439
+ detectedContext: {
440
+ platform: {
441
+ primary: platformDetection.primaryPlatform,
442
+ all: platformDetection.detectedPlatforms.map(p => p.type),
443
+ confidence: platformDetection.confidence,
444
+ evidence: platformDetection.evidence.slice(0, 10).map(e => ({
445
+ file: e.file,
446
+ indicator: e.indicator,
447
+ weight: e.weight,
448
+ })),
449
+ },
450
+ validatedPattern: validatedPattern
451
+ ? {
452
+ name: validatedPattern.name,
453
+ version: validatedPattern.version,
454
+ platformType: validatedPattern.platformType,
455
+ source: 'typescript-builtin', // Could be enhanced to detect YAML vs TS
456
+ sourceHash: this.computePatternHash(validatedPattern),
457
+ loadedAt: new Date().toISOString(),
458
+ baseRepository: validatedPattern.baseCodeRepository.url,
459
+ authoritativeSources: validatedPattern.authoritativeSources.map(s => ({
460
+ type: s.type,
461
+ url: s.url,
462
+ required: s.requiredForDeployment,
463
+ purpose: s.purpose,
464
+ })),
465
+ deploymentPhases: validatedPattern.deploymentPhases.length,
466
+ validationChecks: validatedPattern.validationChecks.length,
467
+ }
468
+ : null,
469
+ deploymentPlan: {
470
+ recommendedPlatform: deploymentPlan.recommendedPlatform,
471
+ confidence: deploymentPlan.confidence,
472
+ source: deploymentPlan.source,
473
+ requiredFiles: deploymentPlan.requiredFiles.map(f => ({
474
+ path: f.path,
475
+ purpose: f.purpose,
476
+ required: f.required,
477
+ })),
478
+ environmentVariables: deploymentPlan.environmentVariables.map(e => ({
479
+ name: e.name,
480
+ required: e.required,
481
+ isSecret: e.isSecret,
482
+ })),
483
+ deploymentSteps: deploymentPlan.deploymentSteps.length,
484
+ estimatedDuration: deploymentPlan.estimatedDuration,
485
+ },
486
+ },
487
+ generatedArtifacts: [bootstrapAdrPath, 'bootstrap.sh', 'validate_bootstrap.sh'],
488
+ keyDecisions: [
489
+ {
490
+ decision: `Use ${platformDetection.primaryPlatform} as deployment platform`,
491
+ rationale: `Detected with ${(platformDetection.confidence * 100).toFixed(0)}% confidence based on project structure and configuration files`,
492
+ alternatives: platformDetection.detectedPlatforms
493
+ .filter(p => p.type !== platformDetection.primaryPlatform)
494
+ .map(p => `${p.type} (${(p.confidence * 100).toFixed(0)}% confidence)`)
495
+ .slice(0, 3),
496
+ },
497
+ ],
498
+ learnings: {
499
+ successes: ['Platform detection completed successfully'],
500
+ failures: [],
501
+ recommendations: [
502
+ 'Review bootstrap ADR before proceeding with deployment',
503
+ validatedPattern
504
+ ? `Consult authoritative sources for ${validatedPattern.name}`
505
+ : 'Validate deployment plan with team',
506
+ ],
507
+ environmentSpecific: [],
508
+ },
509
+ relatedDocuments: {
510
+ adrs: [bootstrapAdrPath],
511
+ configs: deploymentPlan.requiredFiles.map(f => f.path),
512
+ otherContexts: [],
513
+ },
514
+ rawData: {
515
+ // Full validated pattern snapshot for reproducibility
516
+ validatedPatternSnapshot: validatedPattern
517
+ ? {
518
+ source: 'typescript-builtin', // Could be enhanced to detect YAML vs TS
519
+ hash: this.computePatternHash(validatedPattern),
520
+ timestamp: new Date().toISOString(),
521
+ definition: validatedPattern, // FULL pattern object with all commands, checks, templates
522
+ }
523
+ : null,
524
+ // Deployment plan details
525
+ deploymentPlan: {
526
+ recommendedPlatform: deploymentPlan.recommendedPlatform,
527
+ confidence: deploymentPlan.confidence,
528
+ source: deploymentPlan.source,
529
+ requiredFiles: deploymentPlan.requiredFiles,
530
+ environmentVariables: deploymentPlan.environmentVariables,
531
+ deploymentSteps: deploymentPlan.deploymentSteps,
532
+ estimatedDuration: deploymentPlan.estimatedDuration,
533
+ },
534
+ },
535
+ };
536
+ // Add validated pattern details if available
537
+ if (validatedPattern) {
538
+ contextDoc.keyDecisions.push({
539
+ decision: `Use ${validatedPattern.name} validated pattern`,
540
+ rationale: `Best practice pattern for ${platformDetection.primaryPlatform} deployments. Provides proven deployment workflow and authoritative sources.`,
541
+ alternatives: ['Custom deployment plan', 'Dynamic AI-generated plan'],
542
+ });
543
+ }
544
+ const contextPath = await this.contextManager.saveContext('bootstrap', contextDoc);
545
+ return contextPath;
546
+ }
547
+ catch (error) {
548
+ this.logger.error('Failed to save bootstrap context', 'BootstrapValidationLoop', error);
549
+ throw error;
550
+ }
551
+ }
552
+ /**
553
+ * Generate bootstrap scripts from validated pattern (NEW)
554
+ */
555
+ async generateBootstrapScriptsFromPattern() {
556
+ if (!this.validatedPattern) {
557
+ return false;
558
+ }
559
+ try {
560
+ this.logger.info(`Generating bootstrap scripts from validated pattern: ${this.validatedPattern.name}`, 'BootstrapValidationLoop');
561
+ // Generate bootstrap.sh from pattern's deployment phases
562
+ let bootstrapScript = `#!/bin/bash
563
+ # Bootstrap script generated from ${this.validatedPattern.name} v${this.validatedPattern.version}
564
+ # Pattern source: ${this.validatedPattern.metadata.source}
565
+ # Last updated: ${this.validatedPattern.metadata.lastUpdated}
566
+ # Generated: ${new Date().toISOString()}
567
+
568
+ set -e # Exit on error
569
+ set -u # Exit on undefined variable
570
+
571
+ echo "========================================"
572
+ echo "Bootstrap Deployment - ${this.validatedPattern.platformType}"
573
+ echo "Pattern: ${this.validatedPattern.name}"
574
+ echo "========================================"
575
+ echo ""
576
+
577
+ `;
578
+ // Add each deployment phase
579
+ for (const phase of this.validatedPattern.deploymentPhases) {
580
+ bootstrapScript += `
581
+ # ============================================================================
582
+ # Phase ${phase.order}: ${phase.name}
583
+ # ${phase.description}
584
+ # Estimated duration: ${phase.estimatedDuration}
585
+ # ============================================================================
586
+
587
+ echo "Starting Phase ${phase.order}: ${phase.name}"
588
+
589
+ `;
590
+ // Add commands for this phase
591
+ for (const command of phase.commands) {
592
+ bootstrapScript += `# ${command.description}\n`;
593
+ bootstrapScript += `echo " → ${command.description}"\n`;
594
+ bootstrapScript += `${command.command}\n\n`;
595
+ }
596
+ bootstrapScript += `echo "✓ Phase ${phase.order} complete"\necho ""\n`;
597
+ }
598
+ bootstrapScript += `
599
+ echo "========================================"
600
+ echo "✅ Bootstrap deployment complete!"
601
+ echo "========================================"
602
+ `;
603
+ // Generate validate_bootstrap.sh from pattern's validation checks
604
+ let validationScript = `#!/bin/bash
605
+ # Validation script generated from ${this.validatedPattern.name}
606
+ # Generated: ${new Date().toISOString()}
607
+
608
+ set -e
609
+
610
+ echo "========================================"
611
+ echo "Bootstrap Validation"
612
+ echo "========================================"
613
+ echo ""
614
+
615
+ FAILED_CHECKS=0
616
+
617
+ `;
618
+ for (const check of this.validatedPattern.validationChecks) {
619
+ validationScript += `
620
+ # ${check.name} (${check.severity})
621
+ echo "Checking: ${check.name}"
622
+ if ${check.command}; then
623
+ echo " ✅ PASSED: ${check.name}"
624
+ else
625
+ echo " ❌ FAILED: ${check.name}"
626
+ echo " ${check.failureMessage}"
627
+ echo " Remediation steps:"
628
+ ${check.remediationSteps.map(step => ` echo " - ${step}"`).join('\n')}
629
+ FAILED_CHECKS=$((FAILED_CHECKS + 1))
630
+ fi
631
+ echo ""
632
+
633
+ `;
634
+ }
635
+ validationScript += `
636
+ if [ $FAILED_CHECKS -eq 0 ]; then
637
+ echo "========================================"
638
+ echo "✅ All validation checks passed!"
639
+ echo "========================================"
640
+ exit 0
641
+ else
642
+ echo "========================================"
643
+ echo "❌ $FAILED_CHECKS validation check(s) failed"
644
+ echo "========================================"
645
+ exit 1
646
+ fi
647
+ `;
648
+ // Write scripts
649
+ const bootstrapPath = path.join(this.projectPath, 'bootstrap.sh');
650
+ await fs.writeFile(bootstrapPath, bootstrapScript, { mode: 0o755 });
651
+ const validationPath = path.join(this.projectPath, 'validate_bootstrap.sh');
652
+ await fs.writeFile(validationPath, validationScript, { mode: 0o755 });
653
+ this.logger.info('Bootstrap scripts generated from validated pattern', 'BootstrapValidationLoop', {
654
+ bootstrapPath,
655
+ validationPath,
656
+ phases: this.validatedPattern.deploymentPhases.length,
657
+ validationChecks: this.validatedPattern.validationChecks.length,
658
+ });
659
+ return true;
660
+ }
661
+ catch (error) {
662
+ this.logger.error('Failed to generate scripts from validated pattern', 'BootstrapValidationLoop', error);
663
+ return false;
664
+ }
665
+ }
666
+ /**
667
+ * Generate bootstrap scripts from current ADRs (FALLBACK)
668
+ */
669
+ async generateBootstrapScripts() {
670
+ // NEW: Try validated pattern first if available
671
+ if (this.validatedPattern) {
672
+ this.logger.info('🎯 Using validated pattern to generate bootstrap scripts', 'BootstrapValidationLoop');
673
+ const patternSuccess = await this.generateBootstrapScriptsFromPattern();
674
+ if (patternSuccess) {
675
+ return true;
676
+ }
677
+ this.logger.warn('Failed to generate from validated pattern, falling back to ADR-based generation', 'BootstrapValidationLoop');
678
+ }
679
+ try {
680
+ this.logger.info('Generating bootstrap scripts from ADRs', 'BootstrapValidationLoop');
681
+ const result = await generateAdrBootstrapScripts({
682
+ projectPath: this.projectPath,
683
+ adrDirectory: this.adrDirectory,
684
+ outputPath: this.projectPath,
685
+ scriptType: 'both',
686
+ includeTests: true,
687
+ includeDeployment: true,
688
+ enableTreeSitterAnalysis: true,
689
+ });
690
+ // Validate result structure
691
+ if (!result?.content?.[0]?.text) {
692
+ throw new McpAdrError('Invalid response from bootstrap script generator - missing content', 'INVALID_RESPONSE');
693
+ }
694
+ // Extract and validate scripts from result
695
+ let response;
696
+ try {
697
+ response = JSON.parse(result.content[0].text);
698
+ }
699
+ catch (parseError) {
700
+ this.logger.error('Failed to parse bootstrap script response as JSON', 'BootstrapValidationLoop', parseError);
701
+ throw new McpAdrError('Malformed JSON response from script generator', 'PARSE_ERROR');
702
+ }
703
+ // Validate response structure and required properties
704
+ if (!response?.scripts) {
705
+ throw new McpAdrError('Invalid response structure - missing scripts property', 'INVALID_RESPONSE');
706
+ }
707
+ if (typeof response.scripts.bootstrap !== 'string' || !response.scripts.bootstrap.trim()) {
708
+ throw new McpAdrError('Invalid or empty bootstrap script in response', 'INVALID_SCRIPT');
709
+ }
710
+ if (typeof response.scripts.validation !== 'string' || !response.scripts.validation.trim()) {
711
+ throw new McpAdrError('Invalid or empty validation script in response', 'INVALID_SCRIPT');
712
+ }
713
+ // Write bootstrap.sh
714
+ const bootstrapPath = path.join(this.projectPath, 'bootstrap.sh');
715
+ await fs.writeFile(bootstrapPath, response.scripts.bootstrap, { mode: 0o755 });
716
+ // Write validate_bootstrap.sh
717
+ const validationPath = path.join(this.projectPath, 'validate_bootstrap.sh');
718
+ await fs.writeFile(validationPath, response.scripts.validation, { mode: 0o755 });
719
+ this.logger.info('Bootstrap scripts generated successfully', 'BootstrapValidationLoop', {
720
+ bootstrapPath,
721
+ validationPath,
722
+ });
723
+ return true;
724
+ }
725
+ catch (error) {
726
+ this.logger.error('Failed to generate bootstrap scripts', 'BootstrapValidationLoop', error);
727
+ return false;
728
+ }
729
+ }
730
+ /**
731
+ * Execute bootstrap.sh with environment monitoring
732
+ */
733
+ async executeBootstrapWithMonitoring(targetEnvironment, captureSnapshot) {
734
+ const executionId = `bootstrap_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
735
+ const timestamp = new Date().toISOString();
736
+ const startTime = Date.now();
737
+ this.logger.info('Executing bootstrap.sh with monitoring', 'BootstrapValidationLoop', {
738
+ executionId,
739
+ targetEnvironment,
740
+ });
741
+ let environmentSnapshot = {};
742
+ // Capture pre-execution environment snapshot
743
+ if (captureSnapshot) {
744
+ environmentSnapshot = await this.captureEnvironmentSnapshot();
745
+ }
746
+ // Execute bootstrap.sh
747
+ const bootstrapPath = path.join(this.projectPath, 'bootstrap.sh');
748
+ let exitCode = 0;
749
+ let stdout = '';
750
+ let stderr = '';
751
+ try {
752
+ const result = await execAsync(`bash "${bootstrapPath}"`, {
753
+ cwd: this.projectPath,
754
+ timeout: 300000, // 5 minute timeout
755
+ maxBuffer: 10 * 1024 * 1024, // 10MB buffer
756
+ });
757
+ stdout = result.stdout;
758
+ stderr = result.stderr;
759
+ }
760
+ catch (error) {
761
+ exitCode = error.code || 1;
762
+ stdout = error.stdout || '';
763
+ stderr = error.stderr || error.message || '';
764
+ this.logger.warn('Bootstrap execution failed', 'BootstrapValidationLoop', {
765
+ exitCode,
766
+ stderr: stderr.substring(0, 500),
767
+ });
768
+ }
769
+ const duration = Date.now() - startTime;
770
+ return {
771
+ executionId,
772
+ timestamp,
773
+ success: exitCode === 0,
774
+ duration,
775
+ exitCode,
776
+ stdout,
777
+ stderr,
778
+ environmentSnapshot,
779
+ learnings: [], // Will be populated later
780
+ };
781
+ }
782
+ /**
783
+ * Execute validate_bootstrap.sh and analyze results
784
+ */
785
+ async executeValidationScript(executionId) {
786
+ this.logger.info('Executing validate_bootstrap.sh', 'BootstrapValidationLoop', { executionId });
787
+ const validationPath = path.join(this.projectPath, 'validate_bootstrap.sh');
788
+ const validationResults = [];
789
+ let allPassed = true;
790
+ try {
791
+ const result = await execAsync(`bash "${validationPath}"`, {
792
+ cwd: this.projectPath,
793
+ timeout: 180000, // 3 minute timeout
794
+ });
795
+ // Parse validation output
796
+ // This is a simplified parser - actual implementation would be more sophisticated
797
+ const lines = result.stdout.split('\n');
798
+ for (const line of lines) {
799
+ if (line.includes('PASSED') || line.includes('FAILED')) {
800
+ const passed = line.includes('PASSED');
801
+ if (!passed)
802
+ allPassed = false;
803
+ validationResults.push({
804
+ checkId: `validation_${validationResults.length}`,
805
+ adrId: 'unknown', // Would be parsed from output
806
+ requirement: line.trim(),
807
+ passed,
808
+ actualState: passed ? 'compliant' : 'non-compliant',
809
+ expectedState: 'compliant',
810
+ confidence: 0.9,
811
+ evidence: [line],
812
+ });
813
+ }
814
+ }
815
+ }
816
+ catch (error) {
817
+ allPassed = false;
818
+ this.logger.error('Validation script failed', 'BootstrapValidationLoop', error);
819
+ // Record the failure
820
+ validationResults.push({
821
+ checkId: 'validation_execution',
822
+ adrId: 'system',
823
+ requirement: 'Execute validation script',
824
+ passed: false,
825
+ actualState: 'failed',
826
+ expectedState: 'success',
827
+ confidence: 1.0,
828
+ evidence: [error.message],
829
+ });
830
+ }
831
+ return { allPassed, validationResults };
832
+ }
833
+ /**
834
+ * Extract learnings from execution results
835
+ */
836
+ async extractLearnings(executionResult, validationResult) {
837
+ const learnings = [];
838
+ // Analyze failures
839
+ for (const validation of validationResult.validationResults) {
840
+ if (!validation.passed) {
841
+ learnings.push({
842
+ type: 'failure',
843
+ category: 'infrastructure',
844
+ description: `Validation failed: ${validation.requirement}`,
845
+ adrReference: validation.adrId,
846
+ severity: 'error',
847
+ recommendation: await this.generateRecommendation(validation, executionResult),
848
+ evidence: validation.evidence,
849
+ environmentSpecific: true,
850
+ timestamp: new Date().toISOString(),
851
+ });
852
+ }
853
+ }
854
+ // Analyze stderr for issues
855
+ if (executionResult.stderr) {
856
+ const errorLines = executionResult.stderr.split('\n').filter(line => line.trim());
857
+ for (const errorLine of errorLines) {
858
+ if (errorLine.toLowerCase().includes('error') ||
859
+ errorLine.toLowerCase().includes('failed')) {
860
+ learnings.push({
861
+ type: 'failure',
862
+ category: 'configuration',
863
+ description: errorLine.substring(0, 200),
864
+ severity: 'error',
865
+ recommendation: 'Review error message and adjust bootstrap script',
866
+ evidence: [errorLine],
867
+ environmentSpecific: true,
868
+ timestamp: new Date().toISOString(),
869
+ });
870
+ }
871
+ }
872
+ }
873
+ // Use ResearchOrchestrator to understand environment state
874
+ try {
875
+ const envCheck = await this.researchOrchestrator.answerResearchQuestion('What is the current state of the deployment environment? List all running services.');
876
+ if (envCheck.confidence > 0.7) {
877
+ learnings.push({
878
+ type: 'success',
879
+ category: 'infrastructure',
880
+ description: `Environment state verified: ${envCheck.answer?.substring(0, 200)}`,
881
+ severity: 'info',
882
+ recommendation: 'Document current environment state in ADRs',
883
+ evidence: [envCheck.answer || 'Environment check completed'],
884
+ environmentSpecific: true,
885
+ timestamp: new Date().toISOString(),
886
+ });
887
+ }
888
+ }
889
+ catch (error) {
890
+ this.logger.warn('Failed to check environment state', 'BootstrapValidationLoop', error);
891
+ }
892
+ return learnings;
893
+ }
894
+ /**
895
+ * Generate recommendation for a failed validation
896
+ */
897
+ async generateRecommendation(validation, _executionResult) {
898
+ // Use ResearchOrchestrator to generate context-aware recommendation
899
+ try {
900
+ const question = `How can we fix this deployment issue: ${validation.requirement}?
901
+ Current state: ${validation.actualState}
902
+ Expected state: ${validation.expectedState}
903
+ Evidence: ${validation.evidence.join(', ')}`;
904
+ const answer = await this.researchOrchestrator.answerResearchQuestion(question);
905
+ if (answer.confidence > 0.6 && answer.answer) {
906
+ return answer.answer.substring(0, 500);
907
+ }
908
+ }
909
+ catch (error) {
910
+ this.logger.warn('Failed to generate AI recommendation', 'BootstrapValidationLoop', error);
911
+ }
912
+ return 'Review validation failure and adjust bootstrap script accordingly';
913
+ }
914
+ /**
915
+ * Update bootstrap scripts based on learnings
916
+ */
917
+ async updateBootstrapScriptsFromLearnings(learnings, _executionResult) {
918
+ try {
919
+ const bootstrapPath = path.join(this.projectPath, 'bootstrap.sh');
920
+ let bootstrapContent = await fs.readFile(bootstrapPath, 'utf-8');
921
+ // Apply fixes based on learnings
922
+ for (const learning of learnings) {
923
+ if (learning.type === 'failure' && learning.category === 'infrastructure') {
924
+ // Add prerequisite checks
925
+ if (learning.description.toLowerCase().includes('postgres')) {
926
+ const postgresCheck = `
927
+ # Auto-fix: Added PostgreSQL startup check
928
+ if ! pgrep -x "postgres" > /dev/null; then
929
+ echo "Starting PostgreSQL..."
930
+ systemctl start postgresql || brew services start postgresql
931
+ sleep 3
932
+ fi
933
+ `;
934
+ bootstrapContent = bootstrapContent.replace('# Phase 2: Build and Prepare', postgresCheck + '\n# Phase 2: Build and Prepare');
935
+ }
936
+ // Add Docker checks
937
+ if (learning.description.toLowerCase().includes('docker')) {
938
+ const dockerCheck = `
939
+ # Auto-fix: Added Docker check
940
+ if ! docker ps > /dev/null 2>&1; then
941
+ echo "Docker is not running. Please start Docker and retry."
942
+ exit 1
943
+ fi
944
+ `;
945
+ bootstrapContent = dockerCheck + '\n' + bootstrapContent;
946
+ }
947
+ }
948
+ }
949
+ // Write updated script
950
+ await fs.writeFile(bootstrapPath, bootstrapContent, { mode: 0o755 });
951
+ this.logger.info('Bootstrap script updated with auto-fixes', 'BootstrapValidationLoop', {
952
+ fixesApplied: learnings.filter(l => l.type === 'failure').length,
953
+ });
954
+ return true;
955
+ }
956
+ catch (error) {
957
+ this.logger.error('Failed to update bootstrap scripts', 'BootstrapValidationLoop', error);
958
+ return false;
959
+ }
960
+ }
961
+ /**
962
+ * Generate ADR update proposals based on learnings
963
+ */
964
+ async generateAdrUpdates(learnings, outcome) {
965
+ const proposals = [];
966
+ const { discoverAdrsInDirectory } = await import('../utils/adr-discovery.js');
967
+ const adrs = await discoverAdrsInDirectory(this.adrDirectory, this.projectPath, {
968
+ includeContent: true,
969
+ includeTimeline: false,
970
+ });
971
+ for (const adr of adrs.adrs) {
972
+ // Find learnings related to this ADR
973
+ const relatedLearnings = learnings.filter(l => l.adrReference === adr.filename || adr.content?.includes(l.description.substring(0, 50)));
974
+ if (relatedLearnings.length === 0)
975
+ continue;
976
+ // Generate update content
977
+ const updateContent = this.generateDeploymentExperienceSection(relatedLearnings, outcome);
978
+ proposals.push({
979
+ adrPath: path.join(this.adrDirectory, adr.filename || 'unknown.md'),
980
+ adrTitle: adr.title || 'Unknown ADR',
981
+ updateType: 'append',
982
+ sectionToUpdate: 'Deployment Experience',
983
+ proposedContent: updateContent,
984
+ learnings: relatedLearnings,
985
+ confidence: 0.85,
986
+ requiresReview: outcome === 'failure' && relatedLearnings.some(l => l.severity === 'critical'),
987
+ });
988
+ }
989
+ return proposals;
990
+ }
991
+ /**
992
+ * Generate deployment experience section content
993
+ */
994
+ generateDeploymentExperienceSection(learnings, outcome) {
995
+ const timestamp = new Date().toISOString().split('T')[0];
996
+ let content = `\n## Deployment Experience\n\n`;
997
+ content += `**Last Updated**: ${timestamp}\n`;
998
+ content += `**Deployment Outcome**: ${outcome === 'success' ? '✅ Successful' : '⚠️ Issues Encountered'}\n\n`;
999
+ // Group learnings by category
1000
+ const byCategory = {};
1001
+ for (const learning of learnings) {
1002
+ if (!byCategory[learning.category]) {
1003
+ byCategory[learning.category] = [];
1004
+ }
1005
+ byCategory[learning.category].push(learning);
1006
+ }
1007
+ for (const [category, categoryLearnings] of Object.entries(byCategory)) {
1008
+ content += `### ${category.charAt(0).toUpperCase() + category.slice(1)}\n\n`;
1009
+ for (const learning of categoryLearnings) {
1010
+ const icon = learning.type === 'success' ? '✅' : learning.type === 'failure' ? '❌' : 'ℹ️';
1011
+ content += `${icon} **${learning.description}**\n`;
1012
+ content += ` - Severity: ${learning.severity}\n`;
1013
+ content += ` - Recommendation: ${learning.recommendation}\n`;
1014
+ if (learning.environmentSpecific) {
1015
+ content += ` - *Environment-specific consideration*\n`;
1016
+ }
1017
+ content += `\n`;
1018
+ }
1019
+ }
1020
+ return content;
1021
+ }
1022
+ /**
1023
+ * Detect missing files that might break bootstrap
1024
+ */
1025
+ async detectMissingFiles() {
1026
+ const missingFiles = [];
1027
+ try {
1028
+ // Parse .gitignore patterns
1029
+ const gitignorePatterns = await this.parseGitignore();
1030
+ // Extract file references from ADRs
1031
+ const { discoverAdrsInDirectory } = await import('../utils/adr-discovery.js');
1032
+ const adrs = await discoverAdrsInDirectory(this.adrDirectory, this.projectPath, {
1033
+ includeContent: true,
1034
+ includeTimeline: false,
1035
+ });
1036
+ const fileReferences = await this.extractFileReferencesFromAdrs(adrs.adrs);
1037
+ // Check each referenced file
1038
+ for (const [filePath, referencedBy] of fileReferences.entries()) {
1039
+ const fullPath = path.join(this.projectPath, filePath);
1040
+ try {
1041
+ await fs.access(fullPath);
1042
+ // File exists, continue
1043
+ }
1044
+ catch (error) {
1045
+ // Only treat as missing if it's a "file not found" error
1046
+ // Other errors (permissions, etc.) should be logged but not treated as missing
1047
+ if (error.code === 'ENOENT') {
1048
+ const isIgnored = this.isFileIgnored(filePath, gitignorePatterns);
1049
+ const fileInfo = this.analyzeMissingFile(filePath, referencedBy, isIgnored);
1050
+ missingFiles.push(fileInfo);
1051
+ }
1052
+ else {
1053
+ this.logger.warn(`Error accessing file ${filePath}: ${error.message}`, 'BootstrapValidationLoop');
1054
+ }
1055
+ }
1056
+ }
1057
+ // Check for common missing files
1058
+ const commonFiles = [
1059
+ { path: '.env', type: 'env', critical: true },
1060
+ { path: '.env.example', type: 'env', critical: false },
1061
+ { path: 'config/database.yml', type: 'config', critical: true },
1062
+ { path: 'config/secrets.yml', type: 'secret', critical: true },
1063
+ { path: '.npmrc', type: 'config', critical: false },
1064
+ { path: 'tsconfig.json', type: 'build', critical: false },
1065
+ ];
1066
+ for (const common of commonFiles) {
1067
+ const fullPath = path.join(this.projectPath, common.path);
1068
+ try {
1069
+ await fs.access(fullPath);
1070
+ }
1071
+ catch (error) {
1072
+ // Only treat as missing if it's a "file not found" error
1073
+ if (error.code === 'ENOENT') {
1074
+ const isIgnored = this.isFileIgnored(common.path, gitignorePatterns);
1075
+ if (isIgnored || common.critical) {
1076
+ missingFiles.push({
1077
+ filePath: common.path,
1078
+ fileType: common.type,
1079
+ isIgnored,
1080
+ requiredBy: ['bootstrap-process'],
1081
+ severity: common.critical ? 'critical' : 'warning',
1082
+ canCreateTemplate: true,
1083
+ templateContent: this.generateTemplateContent(common.path, common.type),
1084
+ recommendation: isIgnored
1085
+ ? `Create ${common.path} from template (file is gitignored)`
1086
+ : `Consider creating ${common.path} for better configuration`,
1087
+ });
1088
+ }
1089
+ }
1090
+ else {
1091
+ this.logger.warn(`Error accessing common file ${common.path}: ${error.message}`, 'BootstrapValidationLoop');
1092
+ }
1093
+ }
1094
+ }
1095
+ }
1096
+ catch (error) {
1097
+ this.logger.warn('Failed to detect missing files', 'BootstrapValidationLoop', error);
1098
+ }
1099
+ return missingFiles;
1100
+ }
1101
+ /**
1102
+ * Parse .gitignore file patterns
1103
+ */
1104
+ async parseGitignore() {
1105
+ const gitignorePath = path.join(this.projectPath, '.gitignore');
1106
+ const patterns = [];
1107
+ try {
1108
+ const content = await fs.readFile(gitignorePath, 'utf-8');
1109
+ const lines = content.split('\n');
1110
+ for (const line of lines) {
1111
+ const trimmed = line.trim();
1112
+ // Skip comments and empty lines
1113
+ if (trimmed && !trimmed.startsWith('#')) {
1114
+ patterns.push(trimmed);
1115
+ }
1116
+ }
1117
+ }
1118
+ catch {
1119
+ // .gitignore doesn't exist or can't be read
1120
+ this.logger.info('No .gitignore file found', 'BootstrapValidationLoop');
1121
+ }
1122
+ return patterns;
1123
+ }
1124
+ /**
1125
+ * Check if a file path matches gitignore patterns
1126
+ */
1127
+ isFileIgnored(filePath, patterns) {
1128
+ for (const pattern of patterns) {
1129
+ // Simple pattern matching (could be enhanced with minimatch)
1130
+ if (pattern.includes('*')) {
1131
+ // Wildcard pattern
1132
+ const regex = new RegExp(pattern.replace(/\*/g, '.*').replace(/\?/g, '.'));
1133
+ if (regex.test(filePath))
1134
+ return true;
1135
+ }
1136
+ else {
1137
+ // Exact match or directory match
1138
+ if (filePath === pattern || filePath.startsWith(pattern + '/')) {
1139
+ return true;
1140
+ }
1141
+ }
1142
+ }
1143
+ return false;
1144
+ }
1145
+ /**
1146
+ * Extract file references from ADR content
1147
+ */
1148
+ async extractFileReferencesFromAdrs(adrs) {
1149
+ const references = new Map();
1150
+ // Common file path patterns
1151
+ const filePatterns = [
1152
+ /(?:config|src|lib|dist)\/[a-zA-Z0-9_\-/.]+\.[a-zA-Z0-9]+/g,
1153
+ /\.[a-zA-Z0-9_-]+(?:\.example)?\.(?:json|yml|yaml|env|conf|config)/g,
1154
+ /`([^`]+\.[a-zA-Z0-9]+)`/g, // Files in backticks
1155
+ ];
1156
+ for (const adr of adrs) {
1157
+ if (!adr.content)
1158
+ continue;
1159
+ for (const pattern of filePatterns) {
1160
+ const matches = adr.content.matchAll(pattern);
1161
+ for (const match of matches) {
1162
+ const filePath = match[1] || match[0];
1163
+ if (!references.has(filePath)) {
1164
+ references.set(filePath, []);
1165
+ }
1166
+ references.get(filePath).push(adr.title || adr.filename || 'Unknown ADR');
1167
+ }
1168
+ }
1169
+ }
1170
+ return references;
1171
+ }
1172
+ /**
1173
+ * Analyze a missing file and provide recommendations
1174
+ */
1175
+ analyzeMissingFile(filePath, referencedBy, isIgnored) {
1176
+ const ext = path.extname(filePath).toLowerCase();
1177
+ let fileType = 'unknown';
1178
+ let severity = 'warning';
1179
+ let canCreateTemplate = false;
1180
+ // Determine file type and severity
1181
+ if (filePath.includes('.env') || ext === '.env') {
1182
+ fileType = 'env';
1183
+ severity = isIgnored ? 'critical' : 'error';
1184
+ canCreateTemplate = true;
1185
+ }
1186
+ else if (['.json', '.yml', '.yaml', '.conf'].includes(ext)) {
1187
+ fileType = 'config';
1188
+ severity = 'error';
1189
+ canCreateTemplate = true;
1190
+ }
1191
+ else if (['tsconfig.json', 'webpack.config.js', 'vite.config.ts'].includes(path.basename(filePath))) {
1192
+ fileType = 'build';
1193
+ severity = 'warning';
1194
+ canCreateTemplate = true;
1195
+ }
1196
+ else if (filePath.includes('secret') || filePath.includes('credential')) {
1197
+ fileType = 'secret';
1198
+ severity = 'critical';
1199
+ canCreateTemplate = false; // Never create secrets automatically
1200
+ }
1201
+ const templateContent = canCreateTemplate
1202
+ ? this.generateTemplateContent(filePath, fileType)
1203
+ : undefined;
1204
+ return {
1205
+ filePath,
1206
+ fileType,
1207
+ isIgnored,
1208
+ requiredBy: referencedBy,
1209
+ severity,
1210
+ canCreateTemplate,
1211
+ templateContent,
1212
+ recommendation: this.generateMissingFileRecommendation(filePath, fileType, isIgnored, referencedBy),
1213
+ };
1214
+ }
1215
+ /**
1216
+ * Generate template content for missing files
1217
+ */
1218
+ generateTemplateContent(filePath, _fileType) {
1219
+ const fileName = path.basename(filePath);
1220
+ if (fileName === '.env' || fileName === '.env.example') {
1221
+ return `# Environment Configuration
1222
+ # Generated by Bootstrap Validation Loop
1223
+ # IMPORTANT: Update these values before deployment
1224
+
1225
+ # Application
1226
+ NODE_ENV=development
1227
+ PORT=3000
1228
+
1229
+ # Database
1230
+ DATABASE_URL=postgresql://localhost:5432/myapp
1231
+ DATABASE_POOL_SIZE=10
1232
+
1233
+ # Security
1234
+ JWT_SECRET=CHANGE_ME_IN_PRODUCTION
1235
+ SESSION_SECRET=CHANGE_ME_IN_PRODUCTION
1236
+
1237
+ # External Services
1238
+ API_KEY=your_api_key_here
1239
+
1240
+ # Logging
1241
+ LOG_LEVEL=info
1242
+ `;
1243
+ }
1244
+ if (fileName.endsWith('.json')) {
1245
+ return `{
1246
+ "// NOTE": "Generated template - customize for your project",
1247
+ "name": "project-config",
1248
+ "version": "1.0.0",
1249
+ "description": "Generated configuration file"
1250
+ }
1251
+ `;
1252
+ }
1253
+ if (fileName.endsWith('.yml') || fileName.endsWith('.yaml')) {
1254
+ return `# Generated template - customize for your project
1255
+ # YAML Configuration
1256
+
1257
+ default:
1258
+ setting: value
1259
+ enabled: false
1260
+
1261
+ development:
1262
+ debug: true
1263
+
1264
+ production:
1265
+ debug: false
1266
+ `;
1267
+ }
1268
+ return `# Generated template for ${fileName}
1269
+ # Please customize this file for your project
1270
+ `;
1271
+ }
1272
+ /**
1273
+ * Generate recommendation for missing file
1274
+ */
1275
+ generateMissingFileRecommendation(filePath, fileType, isIgnored, referencedBy) {
1276
+ let recommendation = `Missing file: ${filePath}\n`;
1277
+ recommendation += `Referenced by: ${referencedBy.join(', ')}\n`;
1278
+ if (isIgnored) {
1279
+ recommendation += `⚠️ File is gitignored - this is intentional for security\n`;
1280
+ }
1281
+ switch (fileType) {
1282
+ case 'env':
1283
+ recommendation += isIgnored
1284
+ ? `ACTION: Create ${filePath} from template or .env.example\n`
1285
+ : `ACTION: Add ${filePath} to .gitignore and create from template\n`;
1286
+ break;
1287
+ case 'secret':
1288
+ recommendation += `⛔ CRITICAL: Never commit secrets to version control\n`;
1289
+ recommendation += `ACTION: Create ${filePath} manually with secure values\n`;
1290
+ break;
1291
+ case 'config':
1292
+ recommendation += `ACTION: Create configuration file from template\n`;
1293
+ break;
1294
+ case 'build':
1295
+ recommendation += `ACTION: Generate build configuration or copy from similar project\n`;
1296
+ break;
1297
+ default:
1298
+ recommendation += `ACTION: Create file or update ADRs to remove reference\n`;
1299
+ }
1300
+ return recommendation;
1301
+ }
1302
+ /**
1303
+ * Handle missing files - create templates or add to bootstrap prerequisites
1304
+ */
1305
+ async handleMissingFiles(missingFiles) {
1306
+ const learnings = [];
1307
+ for (const missing of missingFiles) {
1308
+ // Create template files if safe to do so
1309
+ if (missing.canCreateTemplate && missing.templateContent && missing.fileType !== 'secret') {
1310
+ try {
1311
+ const fullPath = path.join(this.projectPath, missing.filePath);
1312
+ const dir = path.dirname(fullPath);
1313
+ // Ensure directory exists
1314
+ await fs.mkdir(dir, { recursive: true });
1315
+ // Create template file
1316
+ await fs.writeFile(fullPath, missing.templateContent, 'utf-8');
1317
+ learnings.push({
1318
+ type: 'success',
1319
+ category: 'configuration',
1320
+ description: `Created template file: ${missing.filePath}`,
1321
+ severity: 'info',
1322
+ recommendation: `Review and customize ${missing.filePath} before deployment`,
1323
+ evidence: [`File created with template content`],
1324
+ environmentSpecific: false,
1325
+ timestamp: new Date().toISOString(),
1326
+ });
1327
+ this.logger.info(`Created template file: ${missing.filePath}`, 'BootstrapValidationLoop');
1328
+ }
1329
+ catch (error) {
1330
+ learnings.push({
1331
+ type: 'failure',
1332
+ category: 'configuration',
1333
+ description: `Failed to create template: ${missing.filePath}`,
1334
+ severity: missing.severity,
1335
+ recommendation: missing.recommendation,
1336
+ evidence: [error.message],
1337
+ environmentSpecific: true,
1338
+ timestamp: new Date().toISOString(),
1339
+ });
1340
+ }
1341
+ }
1342
+ else {
1343
+ // File cannot be auto-created, add as prerequisite
1344
+ learnings.push({
1345
+ type: 'prerequisite',
1346
+ category: missing.fileType === 'secret' ? 'security' : 'configuration',
1347
+ description: `Missing required file: ${missing.filePath}`,
1348
+ severity: missing.severity,
1349
+ recommendation: missing.recommendation,
1350
+ evidence: missing.requiredBy,
1351
+ environmentSpecific: missing.isIgnored,
1352
+ timestamp: new Date().toISOString(),
1353
+ });
1354
+ }
1355
+ }
1356
+ return learnings;
1357
+ }
1358
+ /**
1359
+ * Capture environment snapshot
1360
+ */
1361
+ async captureEnvironmentSnapshot() {
1362
+ const snapshot = {};
1363
+ try {
1364
+ // Docker check
1365
+ try {
1366
+ const docker = await execAsync('docker ps --format "{{json .}}"', { timeout: 5000 });
1367
+ snapshot.docker = {
1368
+ available: true,
1369
+ containers: docker.stdout.split('\n').filter(Boolean),
1370
+ };
1371
+ }
1372
+ catch {
1373
+ snapshot.docker = { available: false };
1374
+ }
1375
+ // Kubernetes check
1376
+ try {
1377
+ const k8s = await execAsync('kubectl get all --all-namespaces -o json', { timeout: 10000 });
1378
+ snapshot.kubernetes = { available: true, resources: JSON.parse(k8s.stdout) };
1379
+ }
1380
+ catch {
1381
+ snapshot.kubernetes = { available: false };
1382
+ }
1383
+ // OpenShift check
1384
+ try {
1385
+ const oc = await execAsync('oc status', { timeout: 5000 });
1386
+ snapshot.openshift = { available: true, status: oc.stdout };
1387
+ }
1388
+ catch {
1389
+ snapshot.openshift = { available: false };
1390
+ }
1391
+ // System info
1392
+ snapshot.systemInfo = {
1393
+ platform: process.platform,
1394
+ arch: process.arch,
1395
+ nodeVersion: process.version,
1396
+ timestamp: new Date().toISOString(),
1397
+ };
1398
+ }
1399
+ catch (error) {
1400
+ this.logger.warn('Failed to capture complete environment snapshot', 'BootstrapValidationLoop', error);
1401
+ }
1402
+ return snapshot;
1403
+ }
1404
+ /**
1405
+ * Store execution result in memory system
1406
+ */
1407
+ async storeExecutionInMemory(result) {
1408
+ try {
1409
+ await this.memoryManager.upsertEntity({
1410
+ type: 'bootstrap_execution',
1411
+ title: `Bootstrap Execution ${result.executionId} - ${result.success ? 'Success' : 'Failed'}`,
1412
+ description: `Bootstrap execution on ${result.timestamp} with ${result.learnings.length} learnings captured`,
1413
+ tags: [
1414
+ 'bootstrap',
1415
+ 'deployment',
1416
+ result.success ? 'success' : 'failure',
1417
+ `iteration-${this.currentIteration}`,
1418
+ `learnings-${result.learnings.length}`,
1419
+ `execution-${result.executionId}`,
1420
+ ],
1421
+ relationships: [],
1422
+ context: {
1423
+ projectPhase: 'deployment',
1424
+ technicalStack: ['bootstrap', 'validation'],
1425
+ environmentalFactors: [result.success ? 'success' : 'failure'],
1426
+ stakeholders: ['deployment-team', 'infrastructure-team'],
1427
+ },
1428
+ });
1429
+ }
1430
+ catch (error) {
1431
+ this.logger.warn('Failed to store execution in memory', 'BootstrapValidationLoop', error);
1432
+ }
1433
+ }
1434
+ /**
1435
+ * Compute SHA-256 hash of validated pattern for change detection
1436
+ * @param pattern - Validated pattern to hash
1437
+ * @returns Hex-encoded SHA-256 hash
1438
+ */
1439
+ /**
1440
+ * Execute Infrastructure Layer using DAG with validated pattern
1441
+ *
1442
+ * This method:
1443
+ * 1. Attempts to load validated pattern from YAML
1444
+ * 2. If pattern exists: Auto-generates DAG tasks from pattern definition
1445
+ * 3. If pattern doesn't exist: Works with user to create GitHub issue
1446
+ * 4. Executes infrastructure DAG with parallel execution where possible
1447
+ */
1448
+ async executeInfrastructureDAG(platformDetection) {
1449
+ const platform = platformDetection.primaryPlatform || 'unknown';
1450
+ this.logger.info(`🏗️ Starting Infrastructure Layer DAG execution for ${platform}`, 'BootstrapValidationLoop');
1451
+ // Try to load validated pattern from YAML
1452
+ let dynamicPattern = await this.patternLoader.loadPattern(platform);
1453
+ // If no pattern exists, work with user to create GitHub issue
1454
+ if (!dynamicPattern) {
1455
+ this.logger.warn(`⚠️ No validated pattern found for platform: ${platform}`, 'BootstrapValidationLoop');
1456
+ // Prompt user for contribution
1457
+ const prompt = this.contributionHelper.promptUserForContribution(platform, platformDetection);
1458
+ this.logger.info(prompt, 'BootstrapValidationLoop');
1459
+ // Create GitHub issue (in production, this would use GitHub API)
1460
+ const issueResult = await this.contributionHelper.createGitHubIssue(platform, platformDetection);
1461
+ const successMessage = this.contributionHelper.generateSuccessMessage(issueResult, platform);
1462
+ this.logger.info(successMessage, 'BootstrapValidationLoop');
1463
+ // Fall back to AI-generated pattern
1464
+ this.logger.info('🤖 Generating fallback pattern using AI...', 'BootstrapValidationLoop');
1465
+ dynamicPattern = await this.generateFallbackPattern(platformDetection);
1466
+ }
1467
+ // Auto-generate infrastructure DAG tasks from validated pattern
1468
+ const tasks = this.patternConverter.buildInfrastructureTasksFromPattern(dynamicPattern, platform);
1469
+ this.logger.info(`📊 Generated ${tasks.length} infrastructure DAG tasks`, 'BootstrapValidationLoop');
1470
+ // Initialize SystemCard before execution
1471
+ const bootstrapId = `${platform}-bootstrap-${Date.now()}`;
1472
+ const detectedPlatform = platformDetection.detectedPlatforms.find(p => p.type === platform);
1473
+ await this.systemCardManager.initialize({
1474
+ systemId: bootstrapId,
1475
+ created: new Date().toISOString(),
1476
+ platform: {
1477
+ type: platform,
1478
+ ...(detectedPlatform?.version && { version: detectedPlatform.version }),
1479
+ detectionConfidence: platformDetection.confidence,
1480
+ },
1481
+ bootstrapContext: {
1482
+ bootstrapId,
1483
+ validatedPatternId: dynamicPattern.id,
1484
+ // These will be updated after bootstrap completion
1485
+ },
1486
+ metadata: {
1487
+ tags: ['bootstrap', platform, 'infrastructure'],
1488
+ description: `Bootstrap deployment for ${platform}`,
1489
+ },
1490
+ });
1491
+ this.logger.info('📝 SystemCard initialized for resource tracking', 'BootstrapValidationLoop');
1492
+ // Execute infrastructure DAG
1493
+ const result = await this.dagExecutor.execute(tasks);
1494
+ // Log results
1495
+ if (result.success) {
1496
+ this.logger.info(`✅ Infrastructure Layer complete: ${result.executedTasks.length} tasks executed in ${result.duration}ms`, 'BootstrapValidationLoop');
1497
+ // Extract resources from task results and update SystemCard
1498
+ // Note: Resource extraction will be implemented in next phase
1499
+ // For now, we'll generate cleanup phases based on what was executed
1500
+ const cleanupPhases = await this.systemCardManager.generateCleanupPhases();
1501
+ this.logger.info(`🧹 Generated ${cleanupPhases.length} cleanup phases with ${this.systemCardManager.getResourceCount()} tracked resources`, 'BootstrapValidationLoop');
1502
+ }
1503
+ else {
1504
+ this.logger.error(`❌ Infrastructure Layer failed: ${result.failedTasks.length} tasks failed, ${result.skippedTasks.length} skipped`, 'BootstrapValidationLoop');
1505
+ // Log failed tasks
1506
+ for (const taskId of result.failedTasks) {
1507
+ const taskResult = result.taskResults.get(taskId);
1508
+ if (taskResult) {
1509
+ this.logger.error(` ❌ ${taskId}: ${taskResult.stderr || taskResult.error?.message}`, 'BootstrapValidationLoop');
1510
+ }
1511
+ }
1512
+ }
1513
+ return result;
1514
+ }
1515
+ /**
1516
+ * Generate fallback pattern using AI when validated pattern doesn't exist
1517
+ */
1518
+ async generateFallbackPattern(detection) {
1519
+ this.logger.warn('⚠️ Generating fallback pattern using AI - less tested than validated patterns', 'BootstrapValidationLoop');
1520
+ // Use existing dynamic deployment intelligence as fallback
1521
+ const plan = await this.deploymentIntelligence.generateDeploymentPlan();
1522
+ // Convert to DynamicPattern format
1523
+ return {
1524
+ version: '1.0-fallback',
1525
+ id: `${detection.primaryPlatform}-ai-generated`,
1526
+ name: `${detection.primaryPlatform} (AI-Generated)`,
1527
+ description: 'Auto-generated deployment pattern - not validated by community',
1528
+ authoritativeSources: [],
1529
+ deploymentPhases: plan.deploymentSteps.map((step, i) => {
1530
+ const prevStep = i > 0 ? plan.deploymentSteps[i - 1] : undefined;
1531
+ return {
1532
+ order: i + 1,
1533
+ name: step.title,
1534
+ description: step.description,
1535
+ estimatedDuration: step.estimatedTime,
1536
+ canParallelize: false,
1537
+ prerequisites: prevStep ? [prevStep.title] : [],
1538
+ commands: [
1539
+ {
1540
+ description: step.description,
1541
+ command: step.command,
1542
+ expectedExitCode: 0,
1543
+ },
1544
+ ],
1545
+ };
1546
+ }),
1547
+ validationChecks: plan.validationChecks.map((check, i) => ({
1548
+ id: `check-${i}`,
1549
+ name: check.name,
1550
+ description: check.name,
1551
+ command: check.command,
1552
+ expectedExitCode: 0,
1553
+ severity: check.severity,
1554
+ failureMessage: `Validation failed: ${check.name}`,
1555
+ remediationSteps: [],
1556
+ })),
1557
+ metadata: {
1558
+ source: 'AI-Generated (Fallback)',
1559
+ lastUpdated: new Date().toISOString(),
1560
+ tags: [detection.primaryPlatform || 'unknown', 'ai-generated', 'unvalidated'],
1561
+ },
1562
+ };
1563
+ }
1564
+ computePatternHash(pattern) {
1565
+ try {
1566
+ // Create a deterministic string representation of the pattern
1567
+ const patternString = JSON.stringify({
1568
+ id: pattern.id,
1569
+ name: pattern.name,
1570
+ version: pattern.version,
1571
+ platformType: pattern.platformType,
1572
+ deploymentPhases: pattern.deploymentPhases,
1573
+ validationChecks: pattern.validationChecks,
1574
+ authoritativeSources: pattern.authoritativeSources,
1575
+ baseCodeRepository: pattern.baseCodeRepository,
1576
+ }, null, 2);
1577
+ // Compute SHA-256 hash
1578
+ return createHash('sha256').update(patternString).digest('hex');
1579
+ }
1580
+ catch (error) {
1581
+ this.logger.warn('Failed to compute pattern hash', 'BootstrapValidationLoop', error);
1582
+ return 'hash-computation-failed';
1583
+ }
1584
+ }
1585
+ }
1586
+ /**
1587
+ * Generate guided execution instructions for LLM
1588
+ * This function returns step-by-step commands for the LLM to execute
1589
+ */
1590
+ async function generateGuidedExecutionInstructions(params) {
1591
+ const { projectPath, targetEnvironment, maxIterations, currentIteration, previousExecutionOutput, previousExecutionSuccess, } = params;
1592
+ // PHASE 0: Environment Validation (Iteration 0)
1593
+ if (currentIteration === 0) {
1594
+ // Detect platform
1595
+ const platformDetection = await detectPlatforms(projectPath);
1596
+ const validatedPattern = platformDetection.primaryPlatform
1597
+ ? getPattern(platformDetection.primaryPlatform)
1598
+ : null;
1599
+ const connectionCommands = {
1600
+ openshift: 'oc status && oc whoami',
1601
+ kubernetes: 'kubectl cluster-info && kubectl get nodes',
1602
+ docker: 'docker ps && docker info',
1603
+ 'docker-compose': 'docker-compose --version && docker ps',
1604
+ ansible: 'ansible --version && ansible localhost -m ping',
1605
+ nodejs: 'node --version && npm --version',
1606
+ python: 'python --version && pip --version',
1607
+ };
1608
+ const detectedPlatform = platformDetection.primaryPlatform || 'unknown';
1609
+ const connectionCommand = connectionCommands[detectedPlatform] || 'echo "Unknown platform"';
1610
+ return {
1611
+ content: [
1612
+ {
1613
+ type: 'text',
1614
+ text: `# 🔍 Bootstrap Validation Loop - Phase 0: Environment Validation
1615
+
1616
+ ## Detected Platform
1617
+ **Primary Platform**: ${detectedPlatform.toUpperCase()}
1618
+ **Confidence**: ${(platformDetection.confidence * 100).toFixed(0)}%
1619
+ **All Detected**: ${platformDetection.detectedPlatforms?.map(p => p.type).join(', ') || detectedPlatform}
1620
+
1621
+ ${validatedPattern
1622
+ ? `
1623
+ ## 📚 Validated Pattern Available
1624
+ **Pattern**: ${validatedPattern.name} v${validatedPattern.version}
1625
+ **Base Repository**: ${validatedPattern.baseCodeRepository.url}
1626
+ **Documentation**: ${validatedPattern.authoritativeSources.find(s => s.type === 'documentation')?.url || 'N/A'}
1627
+ ${detectedPlatform === 'openshift' ? '**OpenShift Framework Guide**: https://validatedpatterns.io/learn/vp_openshift_framework/' : ''}
1628
+ `
1629
+ : ''}
1630
+
1631
+ ## ⚠️ ACTION REQUIRED: Validate Environment Connection
1632
+
1633
+ Before proceeding with deployment, you MUST:
1634
+
1635
+ ### 1. Verify Target Environment Connection
1636
+
1637
+ Run the following command to validate your connection to **${detectedPlatform.toUpperCase()}**:
1638
+
1639
+ \`\`\`bash
1640
+ ${connectionCommand}
1641
+ \`\`\`
1642
+
1643
+ ### 2. Confirm Target Environment
1644
+
1645
+ **IMPORTANT**: Please confirm with the human user:
1646
+
1647
+ > "I've detected **${detectedPlatform}** as the target deployment platform (${(platformDetection.confidence * 100).toFixed(0)}% confidence).
1648
+ >
1649
+ > Is this correct? Should I proceed with ${detectedPlatform} deployment, or would you like to target a different platform?"
1650
+
1651
+ ### 3. After Confirmation, Report Back
1652
+
1653
+ Once you've:
1654
+ - ✅ Run the connection validation command
1655
+ - ✅ Confirmed the command succeeded (exit code 0)
1656
+ - ✅ Received human approval for the target environment
1657
+
1658
+ Call this tool again with:
1659
+ \`\`\`json
1660
+ {
1661
+ "currentIteration": 1,
1662
+ "previousExecutionOutput": "<paste the output from the connection command>",
1663
+ "previousExecutionSuccess": true,
1664
+ "targetEnvironment": "${targetEnvironment}"
1665
+ }
1666
+ \`\`\`
1667
+
1668
+ ## Evidence Found
1669
+
1670
+ ${platformDetection.evidence
1671
+ .slice(0, 5)
1672
+ .map((e, i) => `${i + 1}. **${e.file}**: ${e.indicator} (weight: ${(e.weight * 100).toFixed(0)}%)`)
1673
+ .join('\n')}
1674
+
1675
+ ---
1676
+
1677
+ **Current Iteration**: 0/${maxIterations}
1678
+ **Phase**: Environment Validation
1679
+ **Next Phase**: Bootstrap Script Generation
1680
+ `,
1681
+ },
1682
+ ],
1683
+ isError: false,
1684
+ };
1685
+ }
1686
+ // Check if deployment cleanup requested (CI/CD workflow)
1687
+ if (params.deploymentCleanupRequested) {
1688
+ const platformDetection = await detectPlatforms(projectPath);
1689
+ const detectedPlatform = platformDetection.primaryPlatform || 'unknown';
1690
+ const cleanupCommands = {
1691
+ openshift: {
1692
+ teardown: 'oc delete all --selector app=myapp && oc delete configmap --selector app=myapp && oc delete secret --selector app=myapp',
1693
+ verify: 'oc get all --selector app=myapp',
1694
+ restart: './bootstrap.sh',
1695
+ },
1696
+ kubernetes: {
1697
+ teardown: 'kubectl delete deployment,service,configmap,secret -l app=myapp',
1698
+ verify: 'kubectl get all -l app=myapp',
1699
+ restart: './bootstrap.sh',
1700
+ },
1701
+ docker: {
1702
+ teardown: 'docker-compose down -v && docker system prune -f',
1703
+ verify: 'docker ps -a',
1704
+ restart: 'docker-compose up -d',
1705
+ },
1706
+ 'docker-compose': {
1707
+ teardown: 'docker-compose down -v && docker system prune -f',
1708
+ verify: 'docker ps -a && docker volume ls',
1709
+ restart: 'docker-compose up -d',
1710
+ },
1711
+ };
1712
+ const cleanup = cleanupCommands[detectedPlatform] || {
1713
+ teardown: 'echo "Manual cleanup required for ' + detectedPlatform + '"',
1714
+ verify: 'echo "Manual verification required"',
1715
+ restart: './bootstrap.sh',
1716
+ };
1717
+ return {
1718
+ content: [
1719
+ {
1720
+ type: 'text',
1721
+ text: `# 🗑️ Deployment Cleanup & Restart (CI/CD Mode)
1722
+
1723
+ ## Detected Platform
1724
+ **Platform**: ${detectedPlatform.toUpperCase()}
1725
+
1726
+ ## ⚠️ CI/CD Workflow: Teardown → Verify → Restart
1727
+
1728
+ This workflow is designed for CI/CD pipelines that need to completely tear down and restart deployments.
1729
+
1730
+ ### Step 1: Teardown Current Deployment
1731
+
1732
+ **IMPORTANT**: This will DELETE all resources. Confirm with human before proceeding.
1733
+
1734
+ Run:
1735
+ \`\`\`bash
1736
+ ${cleanup.teardown}
1737
+ \`\`\`
1738
+
1739
+ **What this does**:
1740
+ - Deletes all deployments, services, and resources
1741
+ - Removes configuration and secrets
1742
+ - Cleans up volumes and persistent data
1743
+
1744
+ ### Step 2: Verify Cleanup
1745
+
1746
+ Confirm resources are deleted:
1747
+ \`\`\`bash
1748
+ ${cleanup.verify}
1749
+ \`\`\`
1750
+
1751
+ **Expected result**: No resources found (or minimal system resources only).
1752
+
1753
+ ### Step 3: Restart Deployment
1754
+
1755
+ After cleanup verification, restart the deployment:
1756
+ \`\`\`bash
1757
+ ${cleanup.restart}
1758
+ \`\`\`
1759
+
1760
+ ### Step 4: Report Back
1761
+
1762
+ After running teardown, verification, and restart, call this tool again with:
1763
+ \`\`\`json
1764
+ {
1765
+ "currentIteration": ${currentIteration + 1},
1766
+ "previousExecutionOutput": "<paste all command outputs>",
1767
+ "previousExecutionSuccess": true,
1768
+ "deploymentCleanupRequested": false
1769
+ }
1770
+ \`\`\`
1771
+
1772
+ ---
1773
+
1774
+ **Current Iteration**: ${currentIteration}/${maxIterations}
1775
+ **Phase**: Deployment Cleanup
1776
+ **Next Phase**: Deployment Validation
1777
+ `,
1778
+ },
1779
+ ],
1780
+ isError: false,
1781
+ };
1782
+ }
1783
+ // PHASE 1+: Bootstrap script generation and execution guidance
1784
+ if (currentIteration >= 1 && currentIteration < maxIterations) {
1785
+ const platformDetection = await detectPlatforms(projectPath);
1786
+ const detectedPlatform = platformDetection.primaryPlatform || 'unknown';
1787
+ // Analyze previous execution output for failures
1788
+ const hadFailures = !previousExecutionSuccess ||
1789
+ previousExecutionOutput.toLowerCase().includes('error') ||
1790
+ previousExecutionOutput.toLowerCase().includes('failed');
1791
+ if (hadFailures && currentIteration === 1) {
1792
+ // First iteration failed - provide troubleshooting guidance
1793
+ return {
1794
+ content: [
1795
+ {
1796
+ type: 'text',
1797
+ text: `# ⚠️ Bootstrap Validation Loop - Connection Failed
1798
+
1799
+ ## Iteration ${currentIteration}/${maxIterations}
1800
+
1801
+ The environment connection validation failed. Let's troubleshoot:
1802
+
1803
+ ## Previous Output Analysis
1804
+ \`\`\`
1805
+ ${previousExecutionOutput.substring(0, 500)}
1806
+ \`\`\`
1807
+
1808
+ ## Troubleshooting Steps
1809
+
1810
+ ### Common Issues for ${detectedPlatform}:
1811
+
1812
+ 1. **Authentication**: Ensure you're logged in
1813
+ 2. **Permissions**: Verify you have sufficient privileges
1814
+ 3. **Network**: Check connectivity to the cluster/service
1815
+ 4. **Configuration**: Validate connection settings
1816
+
1817
+ ### Recommended Actions:
1818
+
1819
+ 1. Review the error message above
1820
+ 2. Fix the identified issue
1821
+ 3. Re-run the connection validation command
1822
+ 4. Call this tool again with updated output
1823
+
1824
+ ---
1825
+
1826
+ **Current Iteration**: ${currentIteration}/${maxIterations}
1827
+ **Phase**: Connection Troubleshooting
1828
+ `,
1829
+ },
1830
+ ],
1831
+ isError: false,
1832
+ };
1833
+ }
1834
+ // Connection successful - proceed with bootstrap
1835
+ return {
1836
+ content: [
1837
+ {
1838
+ type: 'text',
1839
+ text: `# 🔄 Bootstrap Validation Loop - Iteration ${currentIteration}/${maxIterations}
1840
+
1841
+ Previous execution: ${previousExecutionSuccess ? '✅ Success' : '❌ Failed'}
1842
+
1843
+ ${previousExecutionOutput ? `## Previous Output\n\n\`\`\`\n${previousExecutionOutput.substring(0, 1000)}\n\`\`\`` : ''}
1844
+
1845
+ ## Next Steps
1846
+
1847
+ ${previousExecutionSuccess ? '✅ Environment validated successfully!' : '⚠️ Previous step had issues'}
1848
+
1849
+ ### Phase ${currentIteration}: Bootstrap Script Generation
1850
+
1851
+ The tool will now generate bootstrap and validation scripts. In the next iteration:
1852
+
1853
+ 1. Call \`generate_adr_bootstrap\` to create deployment scripts
1854
+ 2. Run the generated \`bootstrap.sh\` script
1855
+ 3. Run \`validate_bootstrap.sh\` to check compliance
1856
+ 4. Report back with results
1857
+
1858
+ **Next Call**:
1859
+ \`\`\`json
1860
+ {
1861
+ "currentIteration": ${currentIteration + 1},
1862
+ "previousExecutionOutput": "<command outputs>",
1863
+ "previousExecutionSuccess": true/false
1864
+ }
1865
+ \`\`\`
1866
+
1867
+ ---
1868
+
1869
+ **Current Iteration**: ${currentIteration}/${maxIterations}
1870
+ **Phase**: Bootstrap Generation
1871
+ **Next Phase**: Bootstrap Execution
1872
+ `,
1873
+ },
1874
+ ],
1875
+ isError: false,
1876
+ };
1877
+ }
1878
+ // Iteration limit reached
1879
+ return {
1880
+ content: [
1881
+ {
1882
+ type: 'text',
1883
+ text: `# 🏁 Bootstrap Validation Loop - Complete
1884
+
1885
+ Maximum iterations (${maxIterations}) reached.
1886
+
1887
+ ## Summary
1888
+
1889
+ - **Total Iterations**: ${currentIteration}
1890
+ - **Final Status**: ${previousExecutionSuccess ? '✅ Success' : '⚠️ Issues Remain'}
1891
+
1892
+ ## Final Output
1893
+ \`\`\`
1894
+ ${previousExecutionOutput.substring(0, 1000)}
1895
+ \`\`\`
1896
+
1897
+ ## Next Steps
1898
+
1899
+ ${previousExecutionSuccess ? '✅ Deployment validation complete!\n\nReview the results and update ADRs with deployment learnings.' : '⚠️ Deployment validation incomplete.\n\nReview errors, make necessary fixes, and restart the validation loop.'}
1900
+
1901
+ ---
1902
+
1903
+ **Note**: To restart the validation loop, call this tool again with \`currentIteration: 0\`.
1904
+ `,
1905
+ },
1906
+ ],
1907
+ isError: false,
1908
+ };
1909
+ }
1910
+ /**
1911
+ * Main tool function for bootstrap validation loop
1912
+ */
1913
+ export async function bootstrapValidationLoop(args) {
1914
+ const { projectPath = process.cwd(), adrDirectory = 'docs/adrs', targetEnvironment = 'development', maxIterations = 5, autoFix = true, updateAdrsWithLearnings = true, currentIteration = 0, previousExecutionOutput = '', previousExecutionSuccess = false, deploymentCleanupRequested = false, } = args;
1915
+ const loop = new BootstrapValidationLoop(projectPath, adrDirectory, maxIterations);
1916
+ await loop.initialize();
1917
+ // GUIDED MODE: Return instructions for LLM to execute commands
1918
+ // This mode tells the LLM what to run and processes the output iteratively
1919
+ return await generateGuidedExecutionInstructions({
1920
+ loop,
1921
+ projectPath,
1922
+ adrDirectory,
1923
+ targetEnvironment,
1924
+ maxIterations,
1925
+ autoFix,
1926
+ updateAdrsWithLearnings,
1927
+ currentIteration,
1928
+ previousExecutionOutput,
1929
+ previousExecutionSuccess,
1930
+ deploymentCleanupRequested,
1931
+ });
1932
+ }
1933
+ export default bootstrapValidationLoop;
1934
+ //# sourceMappingURL=bootstrap-validation-loop-tool.js.map