@build-astron-co/nimbus 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (441) hide show
  1. package/bin/nimbus.cmd +41 -0
  2. package/bin/nimbus.mjs +70 -0
  3. package/completions/nimbus.bash +38 -0
  4. package/completions/nimbus.fish +48 -0
  5. package/completions/nimbus.zsh +81 -0
  6. package/dist/src/agent/compaction-agent.js +215 -0
  7. package/dist/src/agent/context-manager.js +385 -0
  8. package/dist/src/agent/context.js +322 -0
  9. package/dist/src/agent/deploy-preview.js +395 -0
  10. package/dist/src/agent/expand-files.js +95 -0
  11. package/dist/src/agent/index.js +18 -0
  12. package/dist/src/agent/loop.js +1535 -0
  13. package/dist/src/agent/modes.js +347 -0
  14. package/dist/src/agent/permissions.js +396 -0
  15. package/dist/src/agent/subagents/base.js +67 -0
  16. package/dist/src/agent/subagents/cost.js +45 -0
  17. package/dist/src/agent/subagents/explore.js +36 -0
  18. package/dist/src/agent/subagents/general.js +41 -0
  19. package/dist/src/agent/subagents/index.js +88 -0
  20. package/dist/src/agent/subagents/infra.js +52 -0
  21. package/dist/src/agent/subagents/security.js +60 -0
  22. package/dist/src/agent/system-prompt.js +860 -0
  23. package/dist/src/app.js +152 -0
  24. package/dist/src/audit/activity-log.js +209 -0
  25. package/dist/src/audit/compliance-checker.js +419 -0
  26. package/dist/src/audit/cost-tracker.js +231 -0
  27. package/dist/src/audit/index.js +10 -0
  28. package/dist/src/audit/security-scanner.js +490 -0
  29. package/dist/src/auth/guard.js +64 -0
  30. package/dist/src/auth/index.js +19 -0
  31. package/dist/src/auth/keychain.js +79 -0
  32. package/dist/src/auth/oauth.js +389 -0
  33. package/dist/src/auth/providers.js +415 -0
  34. package/dist/src/auth/sso.js +87 -0
  35. package/dist/src/auth/store.js +424 -0
  36. package/dist/src/auth/types.js +5 -0
  37. package/dist/src/cli/index.js +8 -0
  38. package/dist/src/cli/init.js +1048 -0
  39. package/dist/src/cli/openapi-spec.js +346 -0
  40. package/dist/src/cli/run.js +505 -0
  41. package/dist/src/cli/serve-auth.js +56 -0
  42. package/dist/src/cli/serve.js +432 -0
  43. package/dist/src/cli/web.js +50 -0
  44. package/dist/src/cli.js +1574 -0
  45. package/dist/src/clients/core-engine-client.js +156 -0
  46. package/dist/src/clients/enterprise-client.js +246 -0
  47. package/dist/src/clients/generator-client.js +219 -0
  48. package/dist/src/clients/git-client.js +367 -0
  49. package/dist/src/clients/github-client.js +229 -0
  50. package/dist/src/clients/helm-client.js +299 -0
  51. package/dist/src/clients/index.js +18 -0
  52. package/dist/src/clients/k8s-client.js +270 -0
  53. package/dist/src/clients/llm-client.js +119 -0
  54. package/dist/src/clients/rest-client.js +104 -0
  55. package/dist/src/clients/service-discovery.js +35 -0
  56. package/dist/src/clients/terraform-client.js +302 -0
  57. package/dist/src/clients/tools-client.js +1227 -0
  58. package/dist/src/clients/ws-client.js +93 -0
  59. package/dist/src/commands/alias.js +91 -0
  60. package/dist/src/commands/analyze/index.js +313 -0
  61. package/dist/src/commands/apply/helm.js +375 -0
  62. package/dist/src/commands/apply/index.js +176 -0
  63. package/dist/src/commands/apply/k8s.js +350 -0
  64. package/dist/src/commands/apply/terraform.js +465 -0
  65. package/dist/src/commands/ask.js +137 -0
  66. package/dist/src/commands/audit/index.js +322 -0
  67. package/dist/src/commands/auth-cloud.js +345 -0
  68. package/dist/src/commands/auth-list.js +112 -0
  69. package/dist/src/commands/auth-profile.js +104 -0
  70. package/dist/src/commands/auth-refresh.js +161 -0
  71. package/dist/src/commands/auth-status.js +122 -0
  72. package/dist/src/commands/aws/ec2.js +402 -0
  73. package/dist/src/commands/aws/iam.js +304 -0
  74. package/dist/src/commands/aws/index.js +108 -0
  75. package/dist/src/commands/aws/lambda.js +317 -0
  76. package/dist/src/commands/aws/rds.js +345 -0
  77. package/dist/src/commands/aws/s3.js +346 -0
  78. package/dist/src/commands/aws/vpc.js +302 -0
  79. package/dist/src/commands/aws-discover.js +413 -0
  80. package/dist/src/commands/aws-terraform.js +618 -0
  81. package/dist/src/commands/azure/aks.js +305 -0
  82. package/dist/src/commands/azure/functions.js +200 -0
  83. package/dist/src/commands/azure/index.js +93 -0
  84. package/dist/src/commands/azure/storage.js +378 -0
  85. package/dist/src/commands/azure/vm.js +291 -0
  86. package/dist/src/commands/billing/index.js +224 -0
  87. package/dist/src/commands/chat.js +259 -0
  88. package/dist/src/commands/completions.js +255 -0
  89. package/dist/src/commands/config.js +291 -0
  90. package/dist/src/commands/cost/cloud-cost-estimator.js +211 -0
  91. package/dist/src/commands/cost/estimator.js +73 -0
  92. package/dist/src/commands/cost/index.js +625 -0
  93. package/dist/src/commands/cost/parsers/terraform.js +234 -0
  94. package/dist/src/commands/cost/parsers/types.js +4 -0
  95. package/dist/src/commands/cost/pricing/aws.js +501 -0
  96. package/dist/src/commands/cost/pricing/azure.js +462 -0
  97. package/dist/src/commands/cost/pricing/gcp.js +359 -0
  98. package/dist/src/commands/cost/pricing/index.js +24 -0
  99. package/dist/src/commands/demo.js +196 -0
  100. package/dist/src/commands/deploy.js +215 -0
  101. package/dist/src/commands/doctor.js +1291 -0
  102. package/dist/src/commands/drift/index.js +674 -0
  103. package/dist/src/commands/explain.js +235 -0
  104. package/dist/src/commands/export.js +120 -0
  105. package/dist/src/commands/feedback.js +319 -0
  106. package/dist/src/commands/fix.js +263 -0
  107. package/dist/src/commands/fs/index.js +338 -0
  108. package/dist/src/commands/gcp/compute.js +266 -0
  109. package/dist/src/commands/gcp/functions.js +221 -0
  110. package/dist/src/commands/gcp/gke.js +357 -0
  111. package/dist/src/commands/gcp/iam.js +295 -0
  112. package/dist/src/commands/gcp/index.js +105 -0
  113. package/dist/src/commands/gcp/storage.js +232 -0
  114. package/dist/src/commands/generate-helm.js +1026 -0
  115. package/dist/src/commands/generate-k8s.js +1263 -0
  116. package/dist/src/commands/generate-terraform.js +1058 -0
  117. package/dist/src/commands/gh/index.js +663 -0
  118. package/dist/src/commands/git/index.js +1208 -0
  119. package/dist/src/commands/helm/index.js +985 -0
  120. package/dist/src/commands/help.js +639 -0
  121. package/dist/src/commands/history.js +120 -0
  122. package/dist/src/commands/import.js +782 -0
  123. package/dist/src/commands/incident.js +144 -0
  124. package/dist/src/commands/index.js +109 -0
  125. package/dist/src/commands/init.js +955 -0
  126. package/dist/src/commands/k8s/index.js +979 -0
  127. package/dist/src/commands/login.js +588 -0
  128. package/dist/src/commands/logout.js +61 -0
  129. package/dist/src/commands/logs.js +160 -0
  130. package/dist/src/commands/onboarding.js +382 -0
  131. package/dist/src/commands/pipeline.js +153 -0
  132. package/dist/src/commands/plan/display.js +216 -0
  133. package/dist/src/commands/plan/index.js +525 -0
  134. package/dist/src/commands/plugin.js +325 -0
  135. package/dist/src/commands/preview.js +356 -0
  136. package/dist/src/commands/profile.js +297 -0
  137. package/dist/src/commands/questionnaire.js +1021 -0
  138. package/dist/src/commands/resume.js +35 -0
  139. package/dist/src/commands/rollback.js +259 -0
  140. package/dist/src/commands/rollout.js +74 -0
  141. package/dist/src/commands/runbook.js +307 -0
  142. package/dist/src/commands/schedule.js +202 -0
  143. package/dist/src/commands/status.js +213 -0
  144. package/dist/src/commands/team/index.js +309 -0
  145. package/dist/src/commands/team-context.js +200 -0
  146. package/dist/src/commands/template.js +204 -0
  147. package/dist/src/commands/tf/index.js +989 -0
  148. package/dist/src/commands/upgrade.js +515 -0
  149. package/dist/src/commands/usage/index.js +118 -0
  150. package/dist/src/commands/version.js +145 -0
  151. package/dist/src/commands/watch.js +127 -0
  152. package/dist/src/compat/index.js +2 -0
  153. package/dist/src/compat/runtime.js +10 -0
  154. package/dist/src/compat/sqlite.js +144 -0
  155. package/dist/src/config/index.js +6 -0
  156. package/dist/src/config/manager.js +469 -0
  157. package/dist/src/config/mode-store.js +57 -0
  158. package/dist/src/config/profiles.js +66 -0
  159. package/dist/src/config/safety-policy.js +251 -0
  160. package/dist/src/config/schema.js +107 -0
  161. package/dist/src/config/types.js +311 -0
  162. package/dist/src/config/workspace-state.js +38 -0
  163. package/dist/src/context/context-db.js +138 -0
  164. package/dist/src/demo/index.js +295 -0
  165. package/dist/src/demo/scenarios/full-journey.js +226 -0
  166. package/dist/src/demo/scenarios/getting-started.js +124 -0
  167. package/dist/src/demo/scenarios/helm-release.js +334 -0
  168. package/dist/src/demo/scenarios/k8s-deployment.js +190 -0
  169. package/dist/src/demo/scenarios/terraform-vpc.js +167 -0
  170. package/dist/src/demo/types.js +6 -0
  171. package/dist/src/engine/cost-estimator.js +334 -0
  172. package/dist/src/engine/diagram-generator.js +192 -0
  173. package/dist/src/engine/drift-detector.js +688 -0
  174. package/dist/src/engine/executor.js +832 -0
  175. package/dist/src/engine/index.js +39 -0
  176. package/dist/src/engine/orchestrator.js +436 -0
  177. package/dist/src/engine/planner.js +616 -0
  178. package/dist/src/engine/safety.js +609 -0
  179. package/dist/src/engine/verifier.js +664 -0
  180. package/dist/src/enterprise/audit.js +241 -0
  181. package/dist/src/enterprise/auth.js +189 -0
  182. package/dist/src/enterprise/billing.js +512 -0
  183. package/dist/src/enterprise/index.js +16 -0
  184. package/dist/src/enterprise/teams.js +315 -0
  185. package/dist/src/generator/best-practices.js +1375 -0
  186. package/dist/src/generator/helm.js +495 -0
  187. package/dist/src/generator/index.js +11 -0
  188. package/dist/src/generator/intent-parser.js +420 -0
  189. package/dist/src/generator/kubernetes.js +773 -0
  190. package/dist/src/generator/terraform.js +1472 -0
  191. package/dist/src/history/index.js +6 -0
  192. package/dist/src/history/manager.js +199 -0
  193. package/dist/src/history/types.js +6 -0
  194. package/dist/src/hooks/config.js +318 -0
  195. package/dist/src/hooks/engine.js +317 -0
  196. package/dist/src/hooks/index.js +2 -0
  197. package/dist/src/llm/auth-bridge.js +157 -0
  198. package/dist/src/llm/circuit-breaker.js +116 -0
  199. package/dist/src/llm/config-loader.js +172 -0
  200. package/dist/src/llm/cost-calculator.js +137 -0
  201. package/dist/src/llm/index.js +7 -0
  202. package/dist/src/llm/model-aliases.js +99 -0
  203. package/dist/src/llm/provider-registry.js +57 -0
  204. package/dist/src/llm/providers/anthropic.js +430 -0
  205. package/dist/src/llm/providers/bedrock.js +409 -0
  206. package/dist/src/llm/providers/google.js +344 -0
  207. package/dist/src/llm/providers/ollama.js +661 -0
  208. package/dist/src/llm/providers/openai-compatible.js +289 -0
  209. package/dist/src/llm/providers/openai.js +284 -0
  210. package/dist/src/llm/providers/openrouter.js +293 -0
  211. package/dist/src/llm/router.js +844 -0
  212. package/dist/src/llm/types.js +69 -0
  213. package/dist/src/lsp/client.js +239 -0
  214. package/dist/src/lsp/languages.js +95 -0
  215. package/dist/src/lsp/manager.js +243 -0
  216. package/dist/src/mcp/client.js +289 -0
  217. package/dist/src/mcp/index.js +5 -0
  218. package/dist/src/mcp/manager.js +113 -0
  219. package/dist/src/nimbus.js +212 -0
  220. package/dist/src/plugins/index.js +13 -0
  221. package/dist/src/plugins/loader.js +280 -0
  222. package/dist/src/plugins/manager.js +282 -0
  223. package/dist/src/plugins/types.js +23 -0
  224. package/dist/src/scanners/cicd-scanner.js +230 -0
  225. package/dist/src/scanners/cloud-scanner.js +415 -0
  226. package/dist/src/scanners/framework-scanner.js +430 -0
  227. package/dist/src/scanners/iac-scanner.js +350 -0
  228. package/dist/src/scanners/index.js +454 -0
  229. package/dist/src/scanners/language-scanner.js +258 -0
  230. package/dist/src/scanners/package-manager-scanner.js +252 -0
  231. package/dist/src/scanners/types.js +6 -0
  232. package/dist/src/sessions/manager.js +395 -0
  233. package/dist/src/sessions/types.js +4 -0
  234. package/dist/src/sharing/sync.js +238 -0
  235. package/dist/src/sharing/viewer.js +131 -0
  236. package/dist/src/snapshots/index.js +1 -0
  237. package/dist/src/snapshots/manager.js +432 -0
  238. package/dist/src/state/artifacts.js +94 -0
  239. package/dist/src/state/audit.js +73 -0
  240. package/dist/src/state/billing.js +126 -0
  241. package/dist/src/state/checkpoints.js +81 -0
  242. package/dist/src/state/config.js +58 -0
  243. package/dist/src/state/conversations.js +7 -0
  244. package/dist/src/state/credentials.js +96 -0
  245. package/dist/src/state/db.js +53 -0
  246. package/dist/src/state/index.js +23 -0
  247. package/dist/src/state/messages.js +76 -0
  248. package/dist/src/state/projects.js +92 -0
  249. package/dist/src/state/schema.js +233 -0
  250. package/dist/src/state/sessions.js +79 -0
  251. package/dist/src/state/teams.js +131 -0
  252. package/dist/src/telemetry.js +91 -0
  253. package/dist/src/tools/aws-ops.js +747 -0
  254. package/dist/src/tools/azure-ops.js +491 -0
  255. package/dist/src/tools/file-ops.js +451 -0
  256. package/dist/src/tools/gcp-ops.js +559 -0
  257. package/dist/src/tools/git-ops.js +557 -0
  258. package/dist/src/tools/github-ops.js +460 -0
  259. package/dist/src/tools/helm-ops.js +634 -0
  260. package/dist/src/tools/index.js +16 -0
  261. package/dist/src/tools/k8s-ops.js +579 -0
  262. package/dist/src/tools/schemas/converter.js +129 -0
  263. package/dist/src/tools/schemas/devops.js +3319 -0
  264. package/dist/src/tools/schemas/index.js +19 -0
  265. package/dist/src/tools/schemas/standard.js +966 -0
  266. package/dist/src/tools/schemas/types.js +409 -0
  267. package/dist/src/tools/spawn-exec.js +109 -0
  268. package/dist/src/tools/terraform-ops.js +627 -0
  269. package/dist/src/types/config.js +1 -0
  270. package/dist/src/types/drift.js +4 -0
  271. package/dist/src/types/enterprise.js +5 -0
  272. package/dist/src/types/index.js +14 -0
  273. package/dist/src/types/plan.js +1 -0
  274. package/dist/src/types/request.js +1 -0
  275. package/dist/src/types/response.js +1 -0
  276. package/dist/src/types/service.js +1 -0
  277. package/dist/src/ui/App.js +1672 -0
  278. package/dist/src/ui/DeployPreview.js +60 -0
  279. package/dist/src/ui/FileDiffModal.js +108 -0
  280. package/dist/src/ui/Header.js +46 -0
  281. package/dist/src/ui/HelpModal.js +9 -0
  282. package/dist/src/ui/InputBox.js +408 -0
  283. package/dist/src/ui/MessageList.js +795 -0
  284. package/dist/src/ui/PermissionPrompt.js +72 -0
  285. package/dist/src/ui/StatusBar.js +109 -0
  286. package/dist/src/ui/TerminalPane.js +31 -0
  287. package/dist/src/ui/ToolCallDisplay.js +303 -0
  288. package/dist/src/ui/TreePane.js +83 -0
  289. package/dist/src/ui/chat-ui.js +721 -0
  290. package/dist/src/ui/index.js +11 -0
  291. package/dist/src/ui/ink/index.js +1325 -0
  292. package/dist/src/ui/streaming.js +137 -0
  293. package/dist/src/ui/theme.js +78 -0
  294. package/dist/src/ui/types.js +7 -0
  295. package/dist/src/utils/analytics.js +61 -0
  296. package/dist/src/utils/cost-warning.js +25 -0
  297. package/dist/src/utils/env.js +42 -0
  298. package/dist/src/utils/errors.js +54 -0
  299. package/dist/src/utils/event-bus.js +22 -0
  300. package/dist/src/utils/index.js +16 -0
  301. package/dist/src/utils/logger.js +150 -0
  302. package/dist/src/utils/rate-limiter.js +90 -0
  303. package/dist/src/utils/service-auth.js +36 -0
  304. package/dist/src/utils/validation.js +39 -0
  305. package/dist/src/version.js +3 -0
  306. package/dist/src/watcher/index.js +192 -0
  307. package/dist/src/wizard/approval.js +275 -0
  308. package/dist/src/wizard/index.js +13 -0
  309. package/dist/src/wizard/prompts.js +273 -0
  310. package/dist/src/wizard/types.js +4 -0
  311. package/dist/src/wizard/ui.js +453 -0
  312. package/dist/src/wizard/wizard.js +227 -0
  313. package/package.json +22 -15
  314. package/src/__tests__/alias.test.ts +133 -0
  315. package/src/__tests__/cli-run.test.ts +237 -1
  316. package/src/__tests__/compat-sqlite.test.ts +68 -0
  317. package/src/__tests__/context-manager.test.ts +130 -0
  318. package/src/__tests__/devops-terminal-gaps.test.ts +718 -0
  319. package/src/__tests__/doctor.test.ts +48 -0
  320. package/src/__tests__/export.test.ts +236 -0
  321. package/src/__tests__/gap-11-18-20.test.ts +958 -0
  322. package/src/__tests__/helm-streaming.test.ts +127 -0
  323. package/src/__tests__/incident.test.ts +179 -0
  324. package/src/__tests__/init.test.ts +54 -3
  325. package/src/__tests__/logs.test.ts +107 -0
  326. package/src/__tests__/loop-errors.test.ts +244 -0
  327. package/src/__tests__/perf-optimizations.test.ts +847 -0
  328. package/src/__tests__/pipeline.test.ts +50 -0
  329. package/src/__tests__/polish-phase3.test.ts +340 -0
  330. package/src/__tests__/profile.test.ts +237 -0
  331. package/src/__tests__/rollback.test.ts +83 -0
  332. package/src/__tests__/runbook.test.ts +219 -0
  333. package/src/__tests__/schedule.test.ts +206 -0
  334. package/src/__tests__/sessions.test.ts +95 -0
  335. package/src/__tests__/standalone-migration.test.ts +199 -0
  336. package/src/__tests__/status.test.ts +158 -0
  337. package/src/__tests__/stream-with-tools.test.ts +49 -1
  338. package/src/__tests__/system-prompt.test.ts +81 -2
  339. package/src/__tests__/terminal-gap-v2.test.ts +395 -0
  340. package/src/__tests__/terminal-parity.test.ts +393 -0
  341. package/src/__tests__/tf-apply.test.ts +187 -0
  342. package/src/__tests__/tool-schemas.test.ts +209 -4
  343. package/src/__tests__/version-json.test.ts +184 -0
  344. package/src/__tests__/watch.test.ts +129 -0
  345. package/src/agent/compaction-agent.ts +40 -1
  346. package/src/agent/context-manager.ts +67 -3
  347. package/src/agent/deploy-preview.ts +62 -1
  348. package/src/agent/expand-files.ts +108 -0
  349. package/src/agent/loop.ts +1312 -31
  350. package/src/agent/permissions.ts +51 -4
  351. package/src/agent/system-prompt.ts +573 -19
  352. package/src/app.ts +58 -0
  353. package/src/audit/security-scanner.ts +45 -0
  354. package/src/auth/keychain.ts +82 -0
  355. package/src/cli/init.ts +378 -5
  356. package/src/cli/run.ts +407 -16
  357. package/src/cli/serve.ts +78 -1
  358. package/src/cli/web.ts +10 -6
  359. package/src/cli.ts +312 -1
  360. package/src/clients/service-discovery.ts +30 -25
  361. package/src/commands/alias.ts +100 -0
  362. package/src/commands/audit/index.ts +121 -2
  363. package/src/commands/auth-cloud.ts +113 -0
  364. package/src/commands/auth-refresh.ts +187 -0
  365. package/src/commands/aws-discover.ts +144 -251
  366. package/src/commands/aws-terraform.ts +68 -118
  367. package/src/commands/chat.ts +9 -3
  368. package/src/commands/completions.ts +268 -0
  369. package/src/commands/config.ts +26 -0
  370. package/src/commands/cost/index.ts +218 -2
  371. package/src/commands/deploy.ts +260 -0
  372. package/src/commands/doctor.ts +744 -152
  373. package/src/commands/drift/index.ts +371 -23
  374. package/src/commands/export.ts +146 -0
  375. package/src/commands/generate-k8s.ts +9 -61
  376. package/src/commands/generate-terraform.ts +191 -449
  377. package/src/commands/help.ts +212 -36
  378. package/src/commands/history.ts +8 -1
  379. package/src/commands/incident.ts +166 -0
  380. package/src/commands/init.ts +5 -0
  381. package/src/commands/login.ts +86 -1
  382. package/src/commands/logs.ts +167 -0
  383. package/src/commands/onboarding.ts +211 -34
  384. package/src/commands/pipeline.ts +186 -0
  385. package/src/commands/plugin.ts +398 -0
  386. package/src/commands/profile.ts +342 -0
  387. package/src/commands/questionnaire.ts +0 -98
  388. package/src/commands/resume.ts +26 -34
  389. package/src/commands/rollback.ts +315 -0
  390. package/src/commands/rollout.ts +88 -0
  391. package/src/commands/runbook.ts +346 -0
  392. package/src/commands/schedule.ts +236 -0
  393. package/src/commands/status.ts +252 -0
  394. package/src/commands/team-context.ts +220 -0
  395. package/src/commands/template.ts +58 -57
  396. package/src/commands/tf/index.ts +70 -11
  397. package/src/commands/upgrade.ts +57 -0
  398. package/src/commands/version.ts +54 -50
  399. package/src/commands/watch.ts +153 -0
  400. package/src/compat/sqlite.ts +75 -5
  401. package/src/config/mode-store.ts +62 -0
  402. package/src/config/profiles.ts +84 -0
  403. package/src/config/types.ts +83 -1
  404. package/src/config/workspace-state.ts +53 -0
  405. package/src/engine/cost-estimator.ts +52 -10
  406. package/src/engine/executor.ts +33 -2
  407. package/src/engine/planner.ts +68 -1
  408. package/src/generator/terraform.ts +8 -0
  409. package/src/history/manager.ts +2 -74
  410. package/src/llm/cost-calculator.ts +2 -2
  411. package/src/llm/providers/anthropic.ts +50 -21
  412. package/src/llm/router.ts +76 -7
  413. package/src/lsp/languages.ts +3 -0
  414. package/src/lsp/manager.ts +20 -4
  415. package/src/nimbus.ts +34 -1
  416. package/src/sessions/manager.ts +108 -1
  417. package/src/sharing/viewer.ts +66 -0
  418. package/src/tools/file-ops.ts +22 -0
  419. package/src/tools/schemas/devops.ts +3007 -117
  420. package/src/tools/schemas/standard.ts +5 -1
  421. package/src/tools/schemas/types.ts +31 -1
  422. package/src/tools/spawn-exec.ts +148 -0
  423. package/src/ui/App.tsx +1183 -66
  424. package/src/ui/DeployPreview.tsx +62 -57
  425. package/src/ui/FileDiffModal.tsx +162 -0
  426. package/src/ui/Header.tsx +87 -24
  427. package/src/ui/HelpModal.tsx +57 -0
  428. package/src/ui/InputBox.tsx +163 -10
  429. package/src/ui/MessageList.tsx +487 -40
  430. package/src/ui/PermissionPrompt.tsx +17 -5
  431. package/src/ui/StatusBar.tsx +122 -3
  432. package/src/ui/TerminalPane.tsx +84 -0
  433. package/src/ui/ToolCallDisplay.tsx +252 -18
  434. package/src/ui/TreePane.tsx +132 -0
  435. package/src/ui/chat-ui.ts +41 -44
  436. package/src/ui/ink/index.ts +771 -38
  437. package/src/ui/theme.ts +104 -0
  438. package/src/ui/types.ts +18 -0
  439. package/src/version.ts +1 -1
  440. package/src/watcher/index.ts +66 -15
  441. package/src/wizard/types.ts +1 -0
@@ -0,0 +1,674 @@
1
+ /**
2
+ * Drift Commands
3
+ *
4
+ * Commands for detecting and fixing infrastructure drift
5
+ */
6
+ import { ui } from '../../wizard/ui';
7
+ import { select, confirm } from '../../wizard/prompts';
8
+ // ==========================================
9
+ // Parsers
10
+ // ==========================================
11
+ /**
12
+ * Parse drift detect options
13
+ */
14
+ export function parseDriftDetectOptions(args) {
15
+ const options = {};
16
+ for (let i = 0; i < args.length; i++) {
17
+ const arg = args[i];
18
+ if (arg === '--provider' && args[i + 1]) {
19
+ options.provider = args[++i];
20
+ }
21
+ else if (arg === '--directory' && args[i + 1]) {
22
+ options.directory = args[++i];
23
+ }
24
+ else if (arg === '-d' && args[i + 1]) {
25
+ options.directory = args[++i];
26
+ }
27
+ else if (arg === '--json') {
28
+ options.json = true;
29
+ }
30
+ else if (arg === '--verbose' || arg === '-v') {
31
+ options.verbose = true;
32
+ }
33
+ else if (!arg.startsWith('-') && !options.provider) {
34
+ options.provider = arg;
35
+ }
36
+ }
37
+ return options;
38
+ }
39
+ /**
40
+ * Parse drift fix options
41
+ */
42
+ export function parseDriftFixOptions(args) {
43
+ const options = {};
44
+ for (let i = 0; i < args.length; i++) {
45
+ const arg = args[i];
46
+ if (arg === '--provider' && args[i + 1]) {
47
+ options.provider = args[++i];
48
+ }
49
+ else if (arg === '--directory' && args[i + 1]) {
50
+ options.directory = args[++i];
51
+ }
52
+ else if (arg === '-d' && args[i + 1]) {
53
+ options.directory = args[++i];
54
+ }
55
+ else if (arg === '--auto-approve' || arg === '-y') {
56
+ options.autoApprove = true;
57
+ }
58
+ else if (arg === '--dry-run') {
59
+ options.dryRun = true;
60
+ }
61
+ else if (arg === '--json') {
62
+ options.json = true;
63
+ }
64
+ else if (!arg.startsWith('-') && !options.provider) {
65
+ options.provider = arg;
66
+ }
67
+ }
68
+ return options;
69
+ }
70
+ // ==========================================
71
+ // Display Functions
72
+ // ==========================================
73
+ /**
74
+ * Format drift severity with color
75
+ */
76
+ function _formatSeverity(severity) {
77
+ switch (severity) {
78
+ case 'critical':
79
+ return ui.color('CRITICAL', 'red');
80
+ case 'high':
81
+ return ui.color('HIGH', 'red');
82
+ case 'medium':
83
+ return ui.color('MEDIUM', 'yellow');
84
+ case 'low':
85
+ default:
86
+ return ui.color('LOW', 'blue');
87
+ }
88
+ }
89
+ /**
90
+ * Format drift type with color
91
+ */
92
+ function formatDriftType(type) {
93
+ switch (type) {
94
+ case 'added':
95
+ return ui.color('+', 'green');
96
+ case 'removed':
97
+ return ui.color('-', 'red');
98
+ case 'modified':
99
+ return ui.color('~', 'yellow');
100
+ default:
101
+ return '?';
102
+ }
103
+ }
104
+ /**
105
+ * Display drift report
106
+ */
107
+ function displayDriftReport(report) {
108
+ ui.newLine();
109
+ ui.section(`Drift Report - ${report.provider.toUpperCase()}`);
110
+ ui.print(` ${ui.dim('Detected at:')} ${new Date(report.detectedAt).toLocaleString()}`);
111
+ ui.print(` ${ui.dim('Total items:')} ${report.summary.total}`);
112
+ ui.print(` ${ui.dim('Has drift:')} ${report.hasDrift ? ui.color('Yes', 'yellow') : ui.color('No', 'green')}`);
113
+ ui.newLine();
114
+ if (!report.hasDrift) {
115
+ ui.success('No drift detected. Infrastructure is in sync.');
116
+ return;
117
+ }
118
+ // Summary
119
+ ui.print(' Changes:');
120
+ if (report.summary.added > 0) {
121
+ ui.print(` ${ui.color('+', 'green')} Added: ${report.summary.added}`);
122
+ }
123
+ if (report.summary.removed > 0) {
124
+ ui.print(` ${ui.color('-', 'red')} Removed: ${report.summary.removed}`);
125
+ }
126
+ if (report.summary.modified > 0) {
127
+ ui.print(` ${ui.color('~', 'yellow')} Modified: ${report.summary.modified}`);
128
+ }
129
+ ui.newLine();
130
+ // Resource Details
131
+ ui.section('Resources with Drift');
132
+ for (const resource of report.resources) {
133
+ ui.newLine();
134
+ ui.print(` ${formatDriftType(resource.driftType)} ${ui.bold(resource.resourceId)}`);
135
+ ui.print(` ${ui.dim('Type:')} ${resource.resourceType}`);
136
+ if (resource.name) {
137
+ ui.print(` ${ui.dim('Name:')} ${resource.name}`);
138
+ }
139
+ if (resource.changes.length > 0) {
140
+ ui.print(` ${ui.dim('Changes:')}`);
141
+ for (const change of resource.changes.slice(0, 5)) {
142
+ const expected = change.expected !== undefined ? JSON.stringify(change.expected) : 'null';
143
+ const actual = change.actual !== undefined ? JSON.stringify(change.actual) : 'null';
144
+ ui.print(` ${ui.dim(change.attribute)}: ${ui.color(expected, 'red')} -> ${ui.color(actual, 'green')}`);
145
+ }
146
+ if (resource.changes.length > 5) {
147
+ ui.print(ui.dim(` ... and ${resource.changes.length - 5} more changes`));
148
+ }
149
+ }
150
+ }
151
+ }
152
+ /**
153
+ * Display remediation result
154
+ */
155
+ function displayRemediationResult(result) {
156
+ ui.newLine();
157
+ ui.section('Remediation Result');
158
+ const statusColor = result.success ? 'green' : 'red';
159
+ ui.print(` ${ui.dim('Status:')} ${ui.color(result.success ? 'Success' : 'Failed', statusColor)}`);
160
+ ui.print(` ${ui.dim('Applied:')} ${result.appliedCount}`);
161
+ ui.print(` ${ui.dim('Failed:')} ${result.failedCount}`);
162
+ ui.print(` ${ui.dim('Skipped:')} ${result.skippedCount}`);
163
+ ui.newLine();
164
+ if (result.actions.length > 0) {
165
+ ui.section('Actions Taken');
166
+ for (const action of result.actions) {
167
+ const icon = action.status === 'applied'
168
+ ? ui.color('✓', 'green')
169
+ : action.status === 'failed'
170
+ ? ui.color('✗', 'red')
171
+ : ui.color('○', 'dim');
172
+ ui.print(` ${icon} ${action.description}`);
173
+ if (action.error) {
174
+ ui.print(` ${ui.color('Error:', 'red')} ${action.error}`);
175
+ }
176
+ }
177
+ }
178
+ if (result.report) {
179
+ ui.newLine();
180
+ ui.print(ui.dim('Full report:'));
181
+ ui.print(result.report);
182
+ }
183
+ }
184
+ // ==========================================
185
+ // Commands
186
+ // ==========================================
187
+ /**
188
+ * Detect drift directly using CLI tools (no CoreEngineClient).
189
+ * For terraform: uses terraform plan -detailed-exitcode.
190
+ * For kubernetes/helm: returns a minimal "no API" report.
191
+ */
192
+ async function detectDriftDirect(provider, directory) {
193
+ const { execFileSync } = await import('child_process');
194
+ if (provider === 'terraform') {
195
+ try {
196
+ execFileSync('terraform', ['plan', '-no-color', '-detailed-exitcode'], {
197
+ cwd: directory,
198
+ encoding: 'utf-8',
199
+ timeout: 120_000,
200
+ stdio: ['pipe', 'pipe', 'pipe'],
201
+ });
202
+ // exit 0 = no drift
203
+ return { hasDrift: false, provider, directory, detectedAt: new Date().toISOString(), resources: [], summary: { total: 0, added: 0, removed: 0, modified: 0, bySeverity: {} } };
204
+ }
205
+ catch (e) {
206
+ if (e.status === 2) {
207
+ // exit 2 = changes present
208
+ const planOutput = e.stdout ?? '';
209
+ const planLine = planOutput.split('\n').find((l) => l.startsWith('Plan:')) ?? 'Changes detected';
210
+ return {
211
+ hasDrift: true,
212
+ provider,
213
+ directory,
214
+ detectedAt: new Date().toISOString(),
215
+ resources: [{ resourceId: planLine.trim(), resourceType: 'terraform', driftType: 'modified', severity: 'medium', changes: [] }],
216
+ summary: { total: 1, added: 0, removed: 0, modified: 1, bySeverity: { medium: 1 } },
217
+ };
218
+ }
219
+ throw new Error(`terraform plan failed: ${String(e.message ?? e).slice(0, 200)}`);
220
+ }
221
+ }
222
+ if (provider === 'kubernetes') {
223
+ try {
224
+ const out = execFileSync('kubectl', ['diff', '-R', '-f', directory], {
225
+ encoding: 'utf-8', timeout: 30_000, stdio: ['pipe', 'pipe', 'pipe'],
226
+ });
227
+ const hasDiff = out.trim().length > 0;
228
+ return { hasDrift: hasDiff, provider, directory, detectedAt: new Date().toISOString(), resources: [], summary: { total: hasDiff ? 1 : 0, added: 0, removed: 0, modified: hasDiff ? 1 : 0, bySeverity: {} } };
229
+ }
230
+ catch (e) {
231
+ // kubectl diff exits 1 when there are differences
232
+ if (e.status === 1) {
233
+ return { hasDrift: true, provider, directory, detectedAt: new Date().toISOString(), resources: [], summary: { total: 1, added: 0, removed: 0, modified: 1, bySeverity: { medium: 1 } } };
234
+ }
235
+ throw new Error(`kubectl diff failed: ${String(e.message ?? e).slice(0, 200)}`);
236
+ }
237
+ }
238
+ if (provider === 'helm') {
239
+ try {
240
+ const out = execFileSync('helm', ['list', '--all-namespaces', '--output', 'json'], {
241
+ encoding: 'utf-8', timeout: 15_000, stdio: ['pipe', 'pipe', 'pipe'],
242
+ });
243
+ const releases = JSON.parse(out || '[]');
244
+ const drifted = releases.filter(r => r.status !== 'deployed');
245
+ return {
246
+ hasDrift: drifted.length > 0,
247
+ provider,
248
+ directory,
249
+ detectedAt: new Date().toISOString(),
250
+ resources: drifted.map(r => ({ resourceId: r.name, resourceType: 'helm', driftType: 'modified', severity: 'medium', changes: [{ attribute: 'status', expected: 'deployed', actual: r.status }] })),
251
+ summary: { total: drifted.length, added: 0, removed: 0, modified: drifted.length, bySeverity: { medium: drifted.length } },
252
+ };
253
+ }
254
+ catch (e) {
255
+ throw new Error(`helm list failed: ${String(e.message ?? e).slice(0, 200)}`);
256
+ }
257
+ }
258
+ throw new Error(`Unknown provider: ${provider}`);
259
+ }
260
+ /**
261
+ * Fix drift directly using CLI tools (no CoreEngineClient).
262
+ * For terraform: runs terraform apply -auto-approve.
263
+ * For kubernetes: runs kubectl apply -f <dir>.
264
+ * For helm: no automated fix; returns guidance.
265
+ */
266
+ async function fixDriftDirect(provider, directory) {
267
+ const { execFileSync } = await import('child_process');
268
+ if (provider === 'terraform') {
269
+ try {
270
+ const output = execFileSync('terraform', ['apply', '-auto-approve', '-no-color'], {
271
+ cwd: directory,
272
+ encoding: 'utf-8',
273
+ timeout: 300_000,
274
+ stdio: ['pipe', 'pipe', 'pipe'],
275
+ });
276
+ return { success: true, appliedCount: 1, failedCount: 0, skippedCount: 0, actions: [{ id: '1', type: 'apply', resourceId: directory, description: 'terraform apply', status: 'applied' }], report: output.slice(0, 500) };
277
+ }
278
+ catch (e) {
279
+ return { success: false, appliedCount: 0, failedCount: 1, skippedCount: 0, actions: [{ id: '1', type: 'apply', resourceId: directory, description: 'terraform apply', status: 'failed', error: String(e.message ?? e).slice(0, 200) }] };
280
+ }
281
+ }
282
+ if (provider === 'kubernetes') {
283
+ try {
284
+ const output = execFileSync('kubectl', ['apply', '-R', '-f', directory], {
285
+ encoding: 'utf-8', timeout: 60_000, stdio: ['pipe', 'pipe', 'pipe'],
286
+ });
287
+ return { success: true, appliedCount: 1, failedCount: 0, skippedCount: 0, actions: [{ id: '1', type: 'apply', resourceId: directory, description: 'kubectl apply', status: 'applied' }], report: output.slice(0, 500) };
288
+ }
289
+ catch (e) {
290
+ return { success: false, appliedCount: 0, failedCount: 1, skippedCount: 0, actions: [{ id: '1', type: 'apply', resourceId: directory, description: 'kubectl apply', status: 'failed', error: String(e.message ?? e).slice(0, 200) }] };
291
+ }
292
+ }
293
+ // Helm: no automated fix
294
+ return { success: false, appliedCount: 0, failedCount: 0, skippedCount: 1, actions: [{ id: '1', type: 'manual', resourceId: directory, description: 'helm fix', status: 'skipped', error: 'Helm drift fix requires manual intervention. Run "helm upgrade <release> <chart>" to remediate.' }] };
295
+ }
296
+ /**
297
+ * H3: Direct drift scan — runs terraform plan -detailed-exitcode in all
298
+ * subdirectories that contain Terraform configs, without needing CoreEngineClient.
299
+ */
300
+ export async function driftScanCommand(opts = {}) {
301
+ const { execFileSync } = await import('child_process');
302
+ const fsSync = await import('fs');
303
+ const pathMod = await import('path');
304
+ const rootDir = pathMod.resolve(opts.workdir ?? process.cwd());
305
+ // Find terraform directories up to depth 3
306
+ const tfDirs = [];
307
+ function walk(dir, depth) {
308
+ if (depth > 3)
309
+ return;
310
+ try {
311
+ if (fsSync.existsSync(pathMod.join(dir, '.terraform')) || fsSync.readdirSync(dir).some(f => f.endsWith('.tf'))) {
312
+ tfDirs.push(dir);
313
+ }
314
+ for (const entry of fsSync.readdirSync(dir, { withFileTypes: true })) {
315
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
316
+ walk(pathMod.join(dir, entry.name), depth + 1);
317
+ }
318
+ }
319
+ }
320
+ catch { /* skip unreadable dirs */ }
321
+ }
322
+ walk(rootDir, 0);
323
+ if (tfDirs.length === 0) {
324
+ ui.info('No Terraform directories found.');
325
+ return;
326
+ }
327
+ ui.header('Terraform Drift Scan');
328
+ const results = [];
329
+ for (const dir of tfDirs) {
330
+ const relDir = pathMod.relative(rootDir, dir) || '.';
331
+ try {
332
+ execFileSync('terraform', ['plan', '-no-color', '-detailed-exitcode'], {
333
+ cwd: dir,
334
+ encoding: 'utf-8',
335
+ timeout: 120_000,
336
+ stdio: ['pipe', 'pipe', 'pipe'],
337
+ });
338
+ // exit 0 = no changes
339
+ results.push({ directory: relDir, status: 'clean', summary: 'No changes' });
340
+ }
341
+ catch (e) {
342
+ if (e.status === 2) {
343
+ // exit 2 = changes present
344
+ const planOutput = e.stdout ?? '';
345
+ const planLine = planOutput.split('\n').find((l) => l.startsWith('Plan:')) ?? 'Changes detected';
346
+ results.push({ directory: relDir, status: 'drift', summary: planLine.trim() });
347
+ }
348
+ else {
349
+ results.push({ directory: relDir, status: 'error', summary: String(e.message ?? 'error').slice(0, 80) });
350
+ }
351
+ }
352
+ }
353
+ if (opts.format === 'json') {
354
+ console.log(JSON.stringify(results, null, 2));
355
+ return;
356
+ }
357
+ // Print table
358
+ const COL = { dir: 40, status: 8, summary: 60 };
359
+ const pad = (s, n) => s.slice(0, n).padEnd(n);
360
+ const divider = `${'-'.repeat(COL.dir + 2)}+${'-'.repeat(COL.status + 2)}+${'-'.repeat(COL.summary + 2)}`;
361
+ console.log(divider);
362
+ console.log(`| ${pad('Directory', COL.dir)} | ${pad('Status', COL.status)} | ${pad('Summary', COL.summary)} |`);
363
+ console.log(divider);
364
+ for (const r of results) {
365
+ console.log(`| ${pad(r.directory, COL.dir)} | ${pad(r.status, COL.status)} | ${pad(r.summary, COL.summary)} |`);
366
+ }
367
+ console.log(divider);
368
+ }
369
+ /**
370
+ * H3: Check ConfigMap/Secret drift versus a stored baseline.
371
+ * Runs `kubectl get configmap,secret -A` to get current counts per namespace,
372
+ * compares against ~/.nimbus/drift-baseline.json, and reports new/missing resources.
373
+ */
374
+ export async function checkK8sDrift(opts = {}) {
375
+ const { execFile } = await import('child_process');
376
+ const { promisify } = await import('util');
377
+ const { existsSync, readFileSync, writeFileSync, mkdirSync } = await import('fs');
378
+ const { join } = await import('path');
379
+ const { homedir } = await import('os');
380
+ const execFileAsync = promisify(execFile);
381
+ const baselinePath = join(homedir(), '.nimbus', 'drift-baseline.json');
382
+ // Get current resource counts per namespace
383
+ let rawOutput = '';
384
+ try {
385
+ const { stdout } = await execFileAsync('kubectl', [
386
+ 'get', 'configmap,secret', '-A', '--no-headers', '-o',
387
+ 'custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name',
388
+ ], { timeout: 15000 });
389
+ rawOutput = stdout;
390
+ }
391
+ catch {
392
+ ui.error('kubectl not available or cluster unreachable.');
393
+ return;
394
+ }
395
+ const lines = rawOutput.trim().split('\n').filter(Boolean);
396
+ const namespaceCounts = {};
397
+ for (const line of lines) {
398
+ const parts = line.trim().split(/\s+/);
399
+ const ns = parts[0] ?? 'default';
400
+ namespaceCounts[ns] = (namespaceCounts[ns] ?? 0) + 1;
401
+ }
402
+ if (opts.updateBaseline) {
403
+ const baseline = { capturedAt: new Date().toISOString(), namespaceCounts };
404
+ mkdirSync(join(homedir(), '.nimbus'), { recursive: true });
405
+ writeFileSync(baselinePath, JSON.stringify(baseline, null, 2), 'utf-8');
406
+ ui.success(`Baseline saved: ${Object.keys(namespaceCounts).length} namespaces, ${lines.length} resources total.`);
407
+ return;
408
+ }
409
+ // Load baseline
410
+ if (!existsSync(baselinePath)) {
411
+ ui.warning('No K8s drift baseline found. Run with --update-baseline to capture current state.');
412
+ ui.newLine();
413
+ ui.print(`Current state: ${lines.length} ConfigMaps/Secrets across ${Object.keys(namespaceCounts).length} namespaces.`);
414
+ return;
415
+ }
416
+ let baseline;
417
+ try {
418
+ baseline = JSON.parse(readFileSync(baselinePath, 'utf-8'));
419
+ }
420
+ catch {
421
+ ui.error('Failed to parse drift baseline file. Re-capture with --update-baseline.');
422
+ return;
423
+ }
424
+ // Compare counts
425
+ const driftEntries = [];
426
+ const allNamespaces = new Set([...Object.keys(baseline.namespaceCounts), ...Object.keys(namespaceCounts)]);
427
+ for (const ns of allNamespaces) {
428
+ const baseCount = baseline.namespaceCounts[ns] ?? 0;
429
+ const currCount = namespaceCounts[ns] ?? 0;
430
+ if (baseCount !== currCount) {
431
+ driftEntries.push({ namespace: ns, baseline: baseCount, current: currCount, delta: currCount - baseCount });
432
+ }
433
+ }
434
+ if (opts.format === 'json') {
435
+ console.log(JSON.stringify({ capturedAt: baseline.capturedAt, drift: driftEntries }, null, 2));
436
+ return;
437
+ }
438
+ ui.header('K8s ConfigMap/Secret Drift');
439
+ ui.print(` Baseline captured: ${new Date(baseline.capturedAt).toLocaleString()}`);
440
+ ui.newLine();
441
+ if (driftEntries.length === 0) {
442
+ ui.success('No drift detected — ConfigMap/Secret counts match baseline.');
443
+ return;
444
+ }
445
+ ui.warning(`${driftEntries.length} namespace(s) have drifted from baseline:`);
446
+ ui.newLine();
447
+ for (const entry of driftEntries) {
448
+ const sign = entry.delta > 0 ? '+' : '';
449
+ const color = entry.delta > 0 ? 'yellow' : 'red';
450
+ ui.print(` ${ui.bold(entry.namespace.padEnd(30))} baseline: ${String(entry.baseline).padStart(4)} current: ${String(entry.current).padStart(4)} delta: ${ui.color(sign + entry.delta, color)}`);
451
+ }
452
+ ui.newLine();
453
+ ui.print(ui.dim('Run "nimbus drift k8s --update-baseline" to update the baseline.'));
454
+ }
455
+ /**
456
+ * Drift parent command
457
+ */
458
+ export async function driftCommand(args) {
459
+ if (args.length === 0) {
460
+ ui.header('Nimbus Drift', 'Infrastructure drift detection and remediation');
461
+ ui.newLine();
462
+ ui.print('Usage: nimbus drift <command> [options]');
463
+ ui.newLine();
464
+ ui.print('Commands:');
465
+ ui.print(` ${ui.bold('scan')} Direct terraform drift scan (no service dependency)`);
466
+ ui.print(` ${ui.bold('k8s')} K8s ConfigMap/Secret drift vs baseline`);
467
+ ui.print(` ${ui.bold('detect')} Detect infrastructure drift`);
468
+ ui.print(` ${ui.bold('fix')} Fix detected drift`);
469
+ ui.newLine();
470
+ ui.print('Examples:');
471
+ ui.print(' nimbus drift scan');
472
+ ui.print(' nimbus drift scan --format json');
473
+ ui.print(' nimbus drift k8s');
474
+ ui.print(' nimbus drift k8s --update-baseline');
475
+ ui.print(' nimbus drift detect --provider terraform');
476
+ ui.print(' nimbus drift detect kubernetes -d ./manifests');
477
+ ui.print(' nimbus drift fix terraform --auto-approve');
478
+ ui.print(' nimbus drift fix --dry-run');
479
+ return;
480
+ }
481
+ const subcommand = args[0];
482
+ const subArgs = args.slice(1);
483
+ switch (subcommand) {
484
+ case 'scan': {
485
+ const format = subArgs.includes('--json') ? 'json' : 'table';
486
+ const workdirIdx = subArgs.indexOf('--workdir');
487
+ const workdir = workdirIdx !== -1 ? subArgs[workdirIdx + 1] : undefined;
488
+ await driftScanCommand({ workdir, format });
489
+ break;
490
+ }
491
+ case 'k8s': {
492
+ const updateBaseline = subArgs.includes('--update-baseline');
493
+ const format = subArgs.includes('--json') ? 'json' : 'table';
494
+ await checkK8sDrift({ updateBaseline, format });
495
+ break;
496
+ }
497
+ case 'detect':
498
+ await driftDetectCommand(parseDriftDetectOptions(subArgs));
499
+ break;
500
+ case 'fix':
501
+ await driftFixCommand(parseDriftFixOptions(subArgs), subArgs);
502
+ break;
503
+ default:
504
+ ui.error(`Unknown drift command: ${subcommand}`);
505
+ ui.info('Run "nimbus drift" for usage');
506
+ }
507
+ }
508
+ /**
509
+ * Detect drift command
510
+ */
511
+ export async function driftDetectCommand(options) {
512
+ const directory = options.directory || process.cwd();
513
+ let provider = options.provider;
514
+ ui.header('Nimbus Drift Detect', directory);
515
+ // If no provider specified, try to detect or ask
516
+ if (!provider) {
517
+ const providerChoice = await select({
518
+ message: 'Select infrastructure provider to check:',
519
+ options: [
520
+ { label: 'Terraform', value: 'terraform', description: 'Check Terraform state drift' },
521
+ {
522
+ label: 'Kubernetes',
523
+ value: 'kubernetes',
524
+ description: 'Check Kubernetes manifest drift',
525
+ },
526
+ { label: 'Helm', value: 'helm', description: 'Check Helm release drift' },
527
+ ],
528
+ });
529
+ provider = providerChoice;
530
+ }
531
+ ui.startSpinner({ message: `Detecting ${provider} drift...` });
532
+ try {
533
+ const report = await detectDriftDirect(provider, directory);
534
+ ui.stopSpinnerSuccess('Drift detection complete');
535
+ if (options.json) {
536
+ console.log(JSON.stringify(report, null, 2));
537
+ return;
538
+ }
539
+ displayDriftReport(report);
540
+ if (report.hasDrift) {
541
+ ui.newLine();
542
+ ui.info('Run "nimbus drift fix" to remediate detected drift');
543
+ }
544
+ }
545
+ catch (error) {
546
+ ui.stopSpinnerFail('Drift detection failed');
547
+ ui.error(error.message);
548
+ }
549
+ }
550
+ /**
551
+ * Fix drift command
552
+ */
553
+ export async function driftFixCommand(options, args = []) {
554
+ const directory = options.directory || process.cwd();
555
+ let provider = options.provider;
556
+ ui.header('Nimbus Drift Fix', directory);
557
+ // If no provider specified, ask
558
+ if (!provider) {
559
+ const providerChoice = await select({
560
+ message: 'Select infrastructure provider to fix:',
561
+ options: [
562
+ { label: 'Terraform', value: 'terraform', description: 'Fix Terraform state drift' },
563
+ { label: 'Kubernetes', value: 'kubernetes', description: 'Fix Kubernetes manifest drift' },
564
+ { label: 'Helm', value: 'helm', description: 'Fix Helm release drift' },
565
+ ],
566
+ });
567
+ provider = providerChoice;
568
+ }
569
+ // First detect drift
570
+ ui.startSpinner({ message: `Detecting ${provider} drift...` });
571
+ let report;
572
+ try {
573
+ report = await detectDriftDirect(provider, directory);
574
+ ui.stopSpinnerSuccess('Drift detection complete');
575
+ }
576
+ catch (error) {
577
+ ui.stopSpinnerFail('Drift detection failed');
578
+ ui.error(error.message);
579
+ return;
580
+ }
581
+ if (!report.hasDrift) {
582
+ ui.newLine();
583
+ ui.success('No drift detected. Nothing to fix.');
584
+ return;
585
+ }
586
+ // Show what will be fixed
587
+ displayDriftReport(report);
588
+ // Confirm before fixing (unless auto-approve or dry-run)
589
+ if (!options.autoApprove && !options.dryRun) {
590
+ ui.newLine();
591
+ const proceed = await confirm({
592
+ message: `Apply ${report.summary.total} remediation actions?`,
593
+ defaultValue: false,
594
+ });
595
+ if (!proceed) {
596
+ ui.info('Fix cancelled.');
597
+ return;
598
+ }
599
+ }
600
+ if (options.dryRun) {
601
+ ui.newLine();
602
+ ui.info('Dry run mode - no changes will be applied');
603
+ ui.newLine();
604
+ // Show what would be done
605
+ ui.section('Actions that would be taken:');
606
+ for (const resource of report.resources) {
607
+ ui.print(` ${formatDriftType(resource.driftType)} ${resource.resourceId}`);
608
+ if (resource.driftType === 'added') {
609
+ ui.print(` ${ui.dim('Would be removed from actual state')}`);
610
+ }
611
+ else if (resource.driftType === 'removed') {
612
+ ui.print(` ${ui.dim('Would be recreated')}`);
613
+ }
614
+ else {
615
+ ui.print(` ${ui.dim('Would be updated to match desired state')}`);
616
+ }
617
+ }
618
+ return;
619
+ }
620
+ // Apply fixes
621
+ ui.startSpinner({ message: 'Applying remediation...' });
622
+ let driftReport;
623
+ try {
624
+ const result = await fixDriftDirect(provider, directory);
625
+ driftReport = report;
626
+ if (result.success) {
627
+ ui.stopSpinnerSuccess('Remediation complete');
628
+ }
629
+ else {
630
+ ui.stopSpinnerFail('Remediation partially failed');
631
+ }
632
+ if (options.json) {
633
+ console.log(JSON.stringify(result, null, 2));
634
+ }
635
+ else {
636
+ displayRemediationResult(result);
637
+ }
638
+ }
639
+ catch (error) {
640
+ ui.stopSpinnerFail('Remediation failed');
641
+ ui.error(error.message);
642
+ }
643
+ // GAP-23: --notify support for Slack/email
644
+ const notifyFlag = args.find((a) => a.startsWith('--notify='))?.split('=')[1]
645
+ ?? (args.includes('--notify') ? args[args.indexOf('--notify') + 1] : undefined);
646
+ if (notifyFlag === 'slack') {
647
+ const webhookUrl = process.env.NIMBUS_SLACK_WEBHOOK;
648
+ if (!webhookUrl) {
649
+ ui.warning('Set NIMBUS_SLACK_WEBHOOK env var to enable Slack notifications');
650
+ }
651
+ else {
652
+ try {
653
+ const summary = driftReport ? JSON.stringify(driftReport).slice(0, 2000) : 'Drift check completed';
654
+ await fetch(webhookUrl, {
655
+ method: 'POST',
656
+ headers: { 'Content-Type': 'application/json' },
657
+ body: JSON.stringify({ text: `*Nimbus Drift Report*\n${summary}` }),
658
+ });
659
+ ui.success('Slack notification sent');
660
+ }
661
+ catch (e) {
662
+ ui.warning(`Slack notification failed: ${e instanceof Error ? e.message : String(e)}`);
663
+ }
664
+ }
665
+ }
666
+ else if (notifyFlag === 'email') {
667
+ // Generate curl command for email via SMTP relay / webhook
668
+ ui.print('To send drift report via email, run:');
669
+ ui.print(` curl -X POST https://api.mailersend.com/v1/email \\
670
+ -H "Authorization: Bearer $MAILERSEND_API_KEY" \\
671
+ -H "Content-Type: application/json" \\
672
+ -d '{"from":{"email":"nimbus@yourdomain.com"},"to":[{"email":"team@yourdomain.com"}],"subject":"Nimbus Drift Report","text":"${JSON.stringify(driftReport ?? 'completed').slice(0, 500)}"}'`);
673
+ }
674
+ }