The best way to control Claude Code, Codex and more from any computer or phone

main
ts 304 lines 8.2 KB
Raw
1 import * as Command from "effect/cli/Command";
2 import * as Flag from "effect/cli/Flag";
3 import * as Effect from "effect/Effect";
4 import * as Option from "effect/Option";
5 import * as Alchemist from "../../Alchemist/index.ts";
6 import * as Interaction from "../../Interaction.ts";
7 import { Cli } from "../../Report.ts";
8 import { renderApply } from "../../Report.ts";
9 import { planDecisionScreen } from "../components/view/PlanDecision.tsx";
10 import { stackOutputsView } from "../components/view/StackOutputs.tsx";
11 import { exitDeclined } from "./errors.ts";
12 import {
13 configPath,
14 dryRun as dryRunFlag,
15 envFile,
16 force,
17 include,
18 exclude,
19 validateSelectionOptions,
20 optionalConfig,
21 profile,
22 resolveStackArgs,
23 stage,
24 yes,
25 } from "./flags.ts";
26 import { instrumentCommand } from "./instrument.ts";
27 import { renderPlanning } from "./render.ts";
28
29 interface StackCommandOptions {
30 readonly main: string;
31 readonly stage: string;
32 readonly envFile: Option.Option<string>;
33 readonly profile?: string;
34 readonly dryRun?: boolean;
35 readonly force?: boolean;
36 readonly include?: ReadonlyArray<string>;
37 readonly exclude?: ReadonlyArray<string>;
38 readonly yes?: boolean;
39 readonly destroy?: boolean;
40 readonly adopt?: boolean;
41 readonly detailed?: boolean;
42 readonly detectDrift?: boolean;
43 }
44
45 const stackSpanAttrs = (args: StackCommandOptions) => ({
46 "alchemy.stage": args.stage,
47 "alchemy.profile": args.profile,
48 "alchemy.main": args.main,
49 "alchemy.dry_run": !!args.dryRun,
50 "alchemy.force": !!args.force,
51 "alchemy.destroy": !!args.destroy,
52 "alchemy.adopt": !!args.adopt,
53 "alchemy.detailed": !!args.detailed,
54 "alchemy.detect_drift": !!args.detectDrift,
55 });
56
57 const adopt = Flag.Boolean("adopt").pipe(
58 Flag.withDescription(
59 "Adopt pre-existing cloud resources that conflict with this stack instead of failing. " +
60 "Useful for re-importing infrastructure into a fresh state store.",
61 ),
62 Flag.withDefault(false),
63 );
64
65 const detailed = Flag.Boolean("detailed").pipe(
66 Flag.withDescription("Show declared resource properties as YAML"),
67 Flag.withDefault(false),
68 );
69
70 const detectDrift = Flag.Boolean("detect-drift").pipe(
71 Flag.withDescription("Detect infrastructure drift and offer to repair it before deploying"),
72 Flag.withDefault(false),
73 );
74
75 const detectAndMaybeRepairDrift = Effect.fn(function* <E, R>(
76 scanDrift: Effect.Effect<Alchemist.Drift.DriftScan, E, R>,
77 options: {
78 readonly stage: string;
79 readonly yes?: boolean;
80 readonly detailed?: boolean;
81 readonly dryRun?: boolean;
82 },
83 ) {
84 const cli = yield* Cli;
85 const snapshot = yield* scanDrift.pipe(
86 renderPlanning({
87 operation: "Drift",
88 stage: options.stage,
89 computingLabel: "Checking drift",
90 readyLabel: "Drift check complete",
91 }),
92 );
93 if (!Alchemist.Drift.hasDrift(snapshot)) return true;
94
95 if (options.dryRun) {
96 yield* cli.displayPlan(snapshot.native, {
97 detailed: options.detailed,
98 stage: options.stage,
99 });
100 return true;
101 }
102
103 let decision: "repair" | "deploy" | "cancel" = options.yes ? "repair" : "cancel";
104 if (!options.yes) {
105 const terminal = yield* Interaction.Interaction;
106 if (terminal.terminal.input) {
107 decision = yield* terminal.prompt
108 .screen(
109 planDecisionScreen({
110 plan: snapshot.native,
111 message: "Drift detected",
112 choices: [
113 {
114 value: "repair" as const,
115 label: "Repair and Deploy",
116 },
117 {
118 value: "deploy" as const,
119 label: "Deploy without Repair",
120 },
121 {
122 value: "cancel" as const,
123 label: "Cancel",
124 },
125 ],
126 initialValue: "repair" as const,
127 }),
128 )
129 .pipe(Effect.catchTag("TerminalCancelled", () => Effect.succeed("cancel" as const)));
130 } else {
131 yield* cli.displayPlan(snapshot.native, {
132 detailed: options.detailed,
133 stage: options.stage,
134 });
135 yield* Interaction.warning(
136 "Drift detected in a non-interactive terminal. Re-run with --yes to repair and deploy.",
137 );
138 }
139 }
140
141 if (decision === "repair") {
142 yield* Alchemist.Drift.execute(snapshot).pipe(
143 renderApply(snapshot.native, {
144 detailed: options.detailed,
145 stage: options.stage,
146 }),
147 );
148 }
149 return decision !== "cancel";
150 });
151
152 const runStack = Effect.fn(function* (options: StackCommandOptions) {
153 yield* validateSelectionOptions(options);
154 const cli = yield* Cli;
155 const display = { detailed: options.detailed, stage: options.stage };
156 const buildOptions = {
157 stage: options.stage,
158 profile: options.profile,
159 envFile: Option.getOrUndefined(options.envFile),
160 adopt: options.adopt,
161 updateStateStore: options.yes,
162 };
163 const stack = Alchemist.importStack(options.main);
164
165 const operation = options.destroy ? "Destroy" : options.dryRun ? "Plan" : "Deploy";
166 const withPlanningProgress = renderPlanning({
167 operation,
168 stage: options.stage,
169 });
170
171 if (options.detectDrift && !options.destroy) {
172 // The drift check closes its build before the deploy builds again: a
173 // remote state store holds one lease per stage per build.
174 const proceed = yield* detectAndMaybeRepairDrift(
175 Effect.flatMap(stack, (stack) => Alchemist.Drift.scan({ ...buildOptions, stack })),
176 options,
177 ).pipe(Effect.scoped);
178 if (!proceed) {
179 yield* Interaction.info("Deploy aborted: drift was detected and not approved.");
180 return yield* exitDeclined;
181 }
182 }
183
184 const snapshot = yield* Effect.flatMap(stack, (stack) =>
185 Alchemist.plan(
186 options.destroy
187 ? { ...buildOptions, stack, operation: "destroy" }
188 : {
189 ...buildOptions,
190 stack,
191 operation: "deploy",
192 force: options.force,
193 include: options.include,
194 exclude: options.exclude,
195 },
196 ),
197 ).pipe(withPlanningProgress);
198
199 if (options.dryRun) {
200 return yield* cli.displayPlan(snapshot.native, display);
201 }
202
203 if (!options.yes && Alchemist.hasChanges(snapshot)) {
204 const approved = yield* cli.approvePlan(snapshot.native, display).pipe(
205 Effect.tap((approved) =>
206 approved ? Effect.void : Interaction.info(`${operation} aborted: plan declined.`),
207 ),
208 Effect.catchTag("NonInteractiveTerminal", () =>
209 Interaction.warning(
210 `Cannot prompt for approval in a non-interactive terminal. Nothing was changed — re-run with --yes to ${operation.toLowerCase()}.`,
211 ).pipe(Effect.as(false)),
212 ),
213 );
214 if (!approved) return yield* exitDeclined;
215 }
216
217 const result = yield* Alchemist.apply(snapshot).pipe(renderApply(snapshot.native, display));
218 if (result !== undefined) {
219 const kit = yield* Interaction.Interaction;
220 yield* kit.output.print(stackOutputsView(result));
221 }
222 });
223
224 export const deployCommand = Command.make(
225 "deploy",
226 {
227 dryRun: dryRunFlag,
228 force,
229 include,
230 exclude,
231 config: optionalConfig,
232 configPath,
233 envFile,
234 stage,
235 yes,
236 profile,
237 adopt,
238 detailed,
239 detectDrift,
240 },
241 (args) =>
242 resolveStackArgs("live")(args).pipe(
243 Effect.flatMap(instrumentCommand("deploy", stackSpanAttrs)(runStack)),
244 ),
245 );
246
247 export const destroyCommand = Command.make(
248 "destroy",
249 {
250 include,
251 exclude,
252 dryRun: dryRunFlag,
253 config: optionalConfig,
254 configPath,
255 envFile,
256 stage,
257 yes,
258 profile,
259 },
260 (args) =>
261 resolveStackArgs("live")(args).pipe(
262 Effect.flatMap(
263 instrumentCommand(
264 "destroy",
265 stackSpanAttrs,
266 )((options) =>
267 runStack({
268 ...options,
269 destroy: true,
270 }),
271 ),
272 ),
273 ),
274 );
275
276 export const planCommand = Command.make(
277 "plan",
278 {
279 include,
280 exclude,
281 config: optionalConfig,
282 configPath,
283 envFile,
284 stage,
285 profile,
286 adopt,
287 detailed,
288 },
289 (args) =>
290 resolveStackArgs("live")(args).pipe(
291 Effect.flatMap(
292 instrumentCommand(
293 "plan",
294 stackSpanAttrs,
295 )((options) =>
296 runStack({
297 ...options,
298 // plan is the same as deploy with dryRun always set to true
299 dryRun: true,
300 }),
301 ),
302 ),
303 ),
304 );