netherframe.cli 0.2.1__py3-none-any.whl

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 (92) hide show
  1. netherframe/cli/__init__.py +1 -0
  2. netherframe/cli/__main__.py +4 -0
  3. netherframe/cli/commands/__init__.py +93 -0
  4. netherframe/cli/commands/backend.py +305 -0
  5. netherframe/cli/commands/config_command.py +98 -0
  6. netherframe/cli/commands/convert.py +40 -0
  7. netherframe/cli/commands/discover.py +679 -0
  8. netherframe/cli/commands/drift.py +499 -0
  9. netherframe/cli/commands/encode.py +130 -0
  10. netherframe/cli/commands/generation.py +861 -0
  11. netherframe/cli/commands/graph_state.py +439 -0
  12. netherframe/cli/commands/hybrid.py +461 -0
  13. netherframe/cli/commands/idiff.py +493 -0
  14. netherframe/cli/commands/infrastructure.py +1182 -0
  15. netherframe/cli/commands/init_command.py +11 -0
  16. netherframe/cli/commands/lint.py +49 -0
  17. netherframe/cli/commands/providers.py +315 -0
  18. netherframe/cli/commands/shell_command.py +17 -0
  19. netherframe/cli/commands/skill.py +167 -0
  20. netherframe/cli/commands/synthesis.py +732 -0
  21. netherframe/cli/commands/terraform_command.py +17 -0
  22. netherframe/cli/commands/watch_command.py +117 -0
  23. netherframe/cli/entrypoint.py +18 -0
  24. netherframe/cli/logging.py +33 -0
  25. netherframe/cli/main.py +177 -0
  26. netherframe/cli/options.py +32 -0
  27. netherframe/cli/py.typed +0 -0
  28. netherframe/cli/services/__init__.py +1 -0
  29. netherframe/cli/services/app_loader.py +62 -0
  30. netherframe/cli/services/app_resolver.py +205 -0
  31. netherframe/cli/services/graph_onboarding.py +144 -0
  32. netherframe/cli/services/legacy_cli.py +51 -0
  33. netherframe/cli/services/project_config.py +107 -0
  34. netherframe/cli/services/provider_batch.py +620 -0
  35. netherframe/cli/services/stack_inventory.py +342 -0
  36. netherframe/cli/skills/netherframe/SKILL.md +53 -0
  37. netherframe/cli/skills/netherframe/agents/openai.yaml +3 -0
  38. netherframe/cli/skills/netherframe/references/authoring.md +77 -0
  39. netherframe/cli/skills/netherframe/references/execution.md +70 -0
  40. netherframe/cli/skills/netherframe/references/migration.md +69 -0
  41. netherframe/cli/state_migration.py +111 -0
  42. netherframe/cli/tui/__init__.py +1 -0
  43. netherframe/cli/tui/plan_filters.py +200 -0
  44. netherframe/cli/tui/plan_models.py +51 -0
  45. netherframe/cli/tui/plan_viewer.py +745 -0
  46. netherframe/cli/ui.py +25 -0
  47. netherframe_cli-0.2.1.dist-info/METADATA +86 -0
  48. netherframe_cli-0.2.1.dist-info/RECORD +92 -0
  49. netherframe_cli-0.2.1.dist-info/WHEEL +4 -0
  50. netherframe_cli-0.2.1.dist-info/entry_points.txt +3 -0
  51. netherframe_cli-0.2.1.dist-info/licenses/LICENSE +21 -0
  52. nf/cli/__init__.py +4 -0
  53. nf/cli/__main__.py +4 -0
  54. nf/cli/commands/__init__.py +4 -0
  55. nf/cli/commands/backend.py +4 -0
  56. nf/cli/commands/config_command.py +4 -0
  57. nf/cli/commands/convert.py +4 -0
  58. nf/cli/commands/discover.py +4 -0
  59. nf/cli/commands/drift.py +4 -0
  60. nf/cli/commands/encode.py +4 -0
  61. nf/cli/commands/generation.py +4 -0
  62. nf/cli/commands/graph_state.py +4 -0
  63. nf/cli/commands/hybrid.py +4 -0
  64. nf/cli/commands/idiff.py +4 -0
  65. nf/cli/commands/infrastructure.py +4 -0
  66. nf/cli/commands/init_command.py +4 -0
  67. nf/cli/commands/lint.py +4 -0
  68. nf/cli/commands/providers.py +4 -0
  69. nf/cli/commands/shell_command.py +4 -0
  70. nf/cli/commands/skill.py +4 -0
  71. nf/cli/commands/synthesis.py +4 -0
  72. nf/cli/commands/terraform_command.py +4 -0
  73. nf/cli/commands/watch_command.py +4 -0
  74. nf/cli/entrypoint.py +4 -0
  75. nf/cli/logging.py +4 -0
  76. nf/cli/main.py +4 -0
  77. nf/cli/options.py +4 -0
  78. nf/cli/py.typed +0 -0
  79. nf/cli/services/__init__.py +4 -0
  80. nf/cli/services/app_loader.py +4 -0
  81. nf/cli/services/app_resolver.py +4 -0
  82. nf/cli/services/graph_onboarding.py +4 -0
  83. nf/cli/services/legacy_cli.py +4 -0
  84. nf/cli/services/project_config.py +4 -0
  85. nf/cli/services/provider_batch.py +4 -0
  86. nf/cli/services/stack_inventory.py +4 -0
  87. nf/cli/state_migration.py +4 -0
  88. nf/cli/tui/__init__.py +4 -0
  89. nf/cli/tui/plan_filters.py +4 -0
  90. nf/cli/tui/plan_models.py +4 -0
  91. nf/cli/tui/plan_viewer.py +4 -0
  92. nf/cli/ui.py +4 -0
@@ -0,0 +1,732 @@
1
+ """Synthesis and app management commands for the NF CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ import click
13
+ from netherframe.cli.ui import console
14
+
15
+ from .hybrid import deferred_options, print_plan_counts, print_result_errors, set_execution_overrides
16
+ from netherframe.cli.services.project_config import (
17
+ load_app_config,
18
+ load_project_config,
19
+ )
20
+ from netherframe.cli.services.stack_inventory import discover_stacks, has_legacy_phased_artifacts
21
+
22
+
23
+ def run_example_script(
24
+ script_path: str,
25
+ python_cmd: list[str],
26
+ enable_phased: bool = False,
27
+ ) -> None:
28
+ """Run an example script in a subprocess with codec preregistration."""
29
+ script_file = Path(script_path)
30
+ if not script_file.exists():
31
+ raise click.ClickException(f"Example script not found: {script_path}")
32
+
33
+ python_code = f"""
34
+ import os
35
+ import runpy
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ sys.path.insert(0, str(Path.cwd()))
40
+
41
+ try:
42
+ from netherframe.codec.autoid import register_codec
43
+ register_codec()
44
+ except Exception:
45
+ pass
46
+
47
+ runpy.run_path({script_path!r}, run_name="__main__")
48
+ """
49
+
50
+ cmd = python_cmd + ["-c", python_code]
51
+ env = os.environ.copy()
52
+ if enable_phased:
53
+ env["NF_PHASED_EXECUTION"] = "true"
54
+
55
+ result = subprocess.run(
56
+ cmd,
57
+ check=False,
58
+ capture_output=True,
59
+ text=True,
60
+ cwd=Path.cwd(),
61
+ env=env,
62
+ )
63
+ if result.returncode != 0:
64
+ console.print("[bold red]Script failed:[/bold red]")
65
+ if result.stdout:
66
+ console.print("[bold]stdout:[/bold]")
67
+ console.print(result.stdout)
68
+ if result.stderr:
69
+ console.print("[bold]stderr:[/bold]")
70
+ console.print(result.stderr)
71
+ raise click.ClickException(f"Example script failed: {script_path}")
72
+
73
+
74
+ def import_app(
75
+ app_spec: str,
76
+ python_cmd: list[str],
77
+ enable_auto_naming: bool = True,
78
+ enable_phased: bool = False,
79
+ outdir: str | None = None,
80
+ ) -> int:
81
+ """Import and synthesize App object(s) using subprocess with configured Python command."""
82
+ module_path, app_name = app_spec.rsplit(":", 1)
83
+
84
+ # Create Python code to import, validate, and synthesize the app(s)
85
+ auto_naming_code = (
86
+ """
87
+ # Auto-naming functionality has been moved to preprocessor
88
+ # No explicit enabling needed
89
+ """
90
+ if enable_auto_naming
91
+ else ""
92
+ )
93
+
94
+ # Native/hybrid execution is not used in synthesis
95
+ native_code = ""
96
+
97
+ python_code = f"""
98
+ import sys
99
+ import os
100
+ from pathlib import Path
101
+
102
+ # Add current directory to Python path for local imports
103
+ sys.path.insert(0, str(Path.cwd()))
104
+
105
+ # Ensure nf_autoid codec is registered before importing encoded modules
106
+ try:
107
+ from netherframe.codec.autoid import register_codec
108
+ register_codec()
109
+ except Exception:
110
+ pass
111
+
112
+ {auto_naming_code}
113
+ {native_code}
114
+
115
+ try:
116
+ # Import the module
117
+ import {module_path}
118
+ app_or_function = getattr({module_path}, "{app_name}")
119
+
120
+ # Determine what we have
121
+ if callable(app_or_function):
122
+ print("FUNCTION_CALL")
123
+ result = app_or_function()
124
+
125
+ # Check if it's a single App or sequence of Apps
126
+ if hasattr(result, 'synth'):
127
+ # Single App
128
+ print("SINGLE_APP")
129
+ result.synth()
130
+ print("SYNTH_SUCCESS")
131
+ elif hasattr(result, '__iter__') and not isinstance(result, str):
132
+ # Sequence of Apps
133
+ apps = list(result)
134
+ print(f"MULTIPLE_APPS:{{len(apps)}}")
135
+ for i, app in enumerate(apps):
136
+ if not hasattr(app, 'synth'):
137
+ print(f"ERROR:App at index {{i}} missing synth method")
138
+ sys.exit(1)
139
+ app.synth()
140
+ print("SYNTH_SUCCESS")
141
+ else:
142
+ print("ERROR:Function must return App object or sequence of Apps")
143
+ sys.exit(1)
144
+
145
+ elif hasattr(app_or_function, 'synth'):
146
+ # Direct App object
147
+ print("SINGLE_APP")
148
+ app_or_function.synth()
149
+ print("SYNTH_SUCCESS")
150
+ else:
151
+ print("ERROR:Object is not an App or function (missing synth method)")
152
+ sys.exit(1)
153
+
154
+ except Exception as e:
155
+ import traceback
156
+ import sys
157
+ # Capture the traceback to stdout instead of stderr
158
+ print("ERROR_TRACEBACK_START", flush=True)
159
+ traceback.print_exc(file=sys.stdout)
160
+ print("ERROR_TRACEBACK_END", flush=True)
161
+ sys.exit(1)
162
+ except AttributeError as e:
163
+ print(f"ATTRIBUTE_ERROR:{{e}}")
164
+ sys.exit(1)
165
+ except Exception as e:
166
+ print(f"ERROR:{{e}}")
167
+ sys.exit(1)
168
+ """
169
+
170
+ try:
171
+ # Run the Python code with the configured Python command
172
+ cmd = python_cmd + ["-c", python_code]
173
+
174
+ # Set up environment with phased execution if requested
175
+ env = os.environ.copy()
176
+ if enable_phased:
177
+ env["NF_PHASED_EXECUTION"] = "true"
178
+ if outdir:
179
+ env["NF_OUTDIR"] = outdir
180
+
181
+ result = subprocess.run(
182
+ cmd,
183
+ check=False,
184
+ capture_output=True,
185
+ text=True,
186
+ cwd=Path.cwd(),
187
+ env=env,
188
+ )
189
+
190
+ if result.returncode != 0:
191
+ # Check if we have a traceback in the output
192
+ output = result.stdout + result.stderr
193
+
194
+ if "ERROR_TRACEBACK_START" in output and "ERROR_TRACEBACK_END" in output:
195
+ # Extract and display the traceback
196
+ start_idx = output.find("ERROR_TRACEBACK_START") + len(
197
+ "ERROR_TRACEBACK_START",
198
+ )
199
+ end_idx = output.find("ERROR_TRACEBACK_END")
200
+ traceback_text = output[start_idx:end_idx].strip()
201
+
202
+ console.print(f"\n[bold red]Error synthesizing {app_spec}:[/bold red]")
203
+ console.print("[red]" + "-" * 60 + "[/red]")
204
+ console.print(traceback_text)
205
+ console.print("[red]" + "-" * 60 + "[/red]")
206
+ raise click.ClickException("App synthesis failed - see traceback above")
207
+ if output.startswith("ERROR:"):
208
+ # Legacy error format for specific error messages
209
+ error_msg = output.replace("ERROR:", "").strip()
210
+ console.print(f"[bold red]Error: {error_msg}[/bold red]")
211
+ raise click.ClickException(error_msg)
212
+ # Unknown error format - show all output
213
+ console.print("[bold red]Synthesis failed:[/bold red]")
214
+ if result.stdout:
215
+ console.print("[bold]stdout:[/bold]")
216
+ console.print(result.stdout)
217
+ if result.stderr:
218
+ console.print("[bold]stderr:[/bold]")
219
+ console.print(result.stderr)
220
+ raise click.ClickException("App synthesis failed")
221
+
222
+ # Parse successful output
223
+ output_lines = result.stdout.strip().split("\n")
224
+ app_count = 1
225
+
226
+ for line in output_lines:
227
+ if line == "FUNCTION_CALL":
228
+ console.print(
229
+ f"[dim]Calling function {app_name}() to get App object(s)...[/dim]",
230
+ )
231
+ elif line == "SINGLE_APP":
232
+ app_count = 1
233
+ elif line.startswith("MULTIPLE_APPS:"):
234
+ app_count = int(line.split(":")[1])
235
+ console.print(f"[dim]Function returned {app_count} App objects[/dim]")
236
+ elif line == "SYNTH_SUCCESS":
237
+ return app_count # Return the number of apps synthesized
238
+ elif "ERROR_TRACEBACK_START" in line:
239
+ # This shouldn't happen in successful output, but just in case
240
+ break
241
+
242
+ # If we get here without SYNTH_SUCCESS, something went wrong
243
+ console.print("[bold red]Unexpected output from synthesis:[/bold red]")
244
+ console.print(result.stdout)
245
+ raise click.ClickException("Synthesis completed but with unexpected output")
246
+
247
+ except subprocess.TimeoutExpired as e:
248
+ console.print(f"[bold red]Synthesis timed out for {app_spec}[/bold red]")
249
+ raise click.ClickException(f"Synthesis timed out for {app_spec}") from e
250
+ except FileNotFoundError as e:
251
+ console.print(
252
+ f"[bold red]Python command not found: {' '.join(python_cmd)}[/bold red]",
253
+ )
254
+ console.print("Check your [tool.nf] python configuration in pyproject.toml")
255
+ raise click.ClickException(
256
+ f"Python command not found: {' '.join(python_cmd)}",
257
+ ) from e
258
+ except Exception as e:
259
+ console.print(f"[bold red]Unexpected error running synthesis: {e}[/bold red]")
260
+ raise click.ClickException(f"Unexpected error: {e}") from e
261
+
262
+
263
+ def run_synthesis(
264
+ app_names: tuple[str, ...] = (),
265
+ *,
266
+ no_auto_naming: bool = False,
267
+ include_all: bool = False,
268
+ phased: bool = False,
269
+ outdir: str | None = None,
270
+ ) -> bool:
271
+ """Run synthesis workflow.
272
+
273
+ Returns:
274
+ True when all configured app specs/scripts succeeded, False otherwise.
275
+ """
276
+ app_config, python_cmd, example_scripts = load_app_config(
277
+ allow_empty_apps=include_all,
278
+ )
279
+
280
+ # Determine which apps to synthesize
281
+ if app_names and include_all:
282
+ raise click.ClickException("Cannot combine --all with specific app names")
283
+
284
+ if app_names:
285
+ # Synthesize specific apps
286
+ apps_to_synth = []
287
+ for app_name in app_names:
288
+ if app_name not in app_config:
289
+ console.print(f"[bold red]App '{app_name}' not found.[/bold red]")
290
+ console.print("\nAvailable apps:")
291
+
292
+ # Group by function name to show duplicates clearly
293
+ by_function = defaultdict(list)
294
+ for key, spec in app_config.items():
295
+ module_path, func_name = spec.rsplit(":", 1)
296
+ by_function[func_name].append((key, spec))
297
+
298
+ for func_name, entries in sorted(by_function.items()):
299
+ if len(entries) == 1:
300
+ key, spec = entries[0]
301
+ console.print(f" {key:<40} -> {spec}")
302
+ else:
303
+ console.print(f"\n Function '{func_name}' (multiple modules):")
304
+ for key, spec in entries:
305
+ console.print(f" {key:<38} -> {spec}")
306
+
307
+ raise click.ClickException(f"App '{app_name}' not found")
308
+ apps_to_synth.append((app_name, app_config[app_name]))
309
+ elif include_all:
310
+ # Synthesize all configured apps and scripts
311
+ apps_to_synth = list(app_config.items())
312
+ scripts_to_run = example_scripts
313
+ else:
314
+ # Synthesize all configured apps only
315
+ apps_to_synth = list(app_config.items())
316
+ scripts_to_run = []
317
+
318
+ if include_all:
319
+ console.print(
320
+ f"[bold green]Synthesizing {len(apps_to_synth)} app(s) and running {len(scripts_to_run)} script(s)...[/bold green]",
321
+ )
322
+ else:
323
+ console.print(
324
+ f"[bold green]Synthesizing {len(apps_to_synth)} app(s)...[/bold green]",
325
+ )
326
+ if not no_auto_naming:
327
+ console.print(
328
+ "[dim]Auto-naming is enabled (use --no-auto-naming to disable)[/dim]",
329
+ )
330
+ if phased:
331
+ console.print(
332
+ "[dim]Phased execution is enabled for circular dependencies[/dim]",
333
+ )
334
+
335
+ success_count = 0
336
+ total_synthesized = 0
337
+ script_success_count = 0
338
+
339
+ for app_name, app_spec in apps_to_synth:
340
+ console.print(f"\n[bold blue]Processing '{app_spec}'...[/bold blue]")
341
+
342
+ try:
343
+ app_count = import_app(
344
+ app_spec,
345
+ python_cmd,
346
+ enable_auto_naming=not no_auto_naming,
347
+ enable_phased=phased,
348
+ outdir=outdir,
349
+ )
350
+ total_synthesized += app_count
351
+
352
+ console.print(
353
+ f"[bold green]✓[/bold green] Successfully synthesized '{app_name}' ({app_count} App{'s' if app_count != 1 else ''})",
354
+ )
355
+ success_count += 1
356
+
357
+ except Exception as e:
358
+ console.print(
359
+ f"[bold red]✗[/bold red] Failed to synthesize '{app_name}': {e}",
360
+ )
361
+ continue
362
+
363
+ for script_path in scripts_to_run:
364
+ console.print(f"\n[bold blue]Running script '{script_path}'...[/bold blue]")
365
+ try:
366
+ run_example_script(
367
+ script_path,
368
+ python_cmd,
369
+ enable_phased=phased,
370
+ )
371
+ console.print(
372
+ f"[bold green]✓[/bold green] Successfully ran '{script_path}'",
373
+ )
374
+ script_success_count += 1
375
+ except Exception as e:
376
+ console.print(f"[bold red]✗[/bold red] Failed to run '{script_path}': {e}")
377
+ continue
378
+
379
+ console.print(
380
+ f"\n[bold green]Synthesis complete:[/bold green] {success_count}/{len(apps_to_synth)} app specs processed successfully",
381
+ )
382
+ console.print(
383
+ f"[bold green]Total Apps synthesized:[/bold green] {total_synthesized}",
384
+ )
385
+ if include_all:
386
+ console.print(
387
+ f"[bold green]Scripts run:[/bold green] {script_success_count}/{len(scripts_to_run)}",
388
+ )
389
+
390
+ selector_map, _, _ = discover_stacks(outdir)
391
+ phased_stack_count = sum(1 for stack_dir in selector_map.values() if has_legacy_phased_artifacts(stack_dir))
392
+ if phased_stack_count:
393
+ console.print(
394
+ f"[bold yellow]Phased export notice:[/bold yellow] {phased_stack_count} stack(s) were synthesized as phased Terraform/OpenTofu exports.",
395
+ )
396
+ console.print(
397
+ "[yellow]These stack roots are export-only for the local CLI runtime. Use the generated README.md/export-manifest.json for handoff, or prefer direct execution instead of local `nf ... --stack` deployment on those roots.[/yellow]",
398
+ )
399
+
400
+ return success_count == len(apps_to_synth) and (not include_all or script_success_count == len(scripts_to_run))
401
+
402
+
403
+ @click.command()
404
+ @click.argument("app_names", nargs=-1)
405
+ @click.option(
406
+ "--no-auto-naming",
407
+ is_flag=True,
408
+ help="Disable automatic construct ID injection",
409
+ )
410
+ @click.option(
411
+ "--all",
412
+ "include_all",
413
+ is_flag=True,
414
+ help="Synthesize configured apps and run example scripts from [tool.nf]",
415
+ )
416
+ @click.option(
417
+ "--phased/--no-phased",
418
+ default=False,
419
+ help="Enable phased execution for circular dependencies",
420
+ )
421
+ def synth(
422
+ app_names: tuple[str],
423
+ no_auto_naming: bool,
424
+ include_all: bool,
425
+ phased: bool,
426
+ ) -> None:
427
+ """Synthesize Netherframe applications to Terraform configuration."""
428
+ success = run_synthesis(
429
+ app_names,
430
+ no_auto_naming=no_auto_naming,
431
+ include_all=include_all,
432
+ phased=phased,
433
+ )
434
+ if not success:
435
+ sys.exit(1)
436
+
437
+
438
+ @click.command()
439
+ @click.option("--stack", "-s", help="Stack name to deploy")
440
+ @click.option("--app", help="Specific app to synthesize before deploying")
441
+ @click.option(
442
+ "--outdir",
443
+ type=click.Path(),
444
+ help="Synthesis output directory (overrides auto-detection)",
445
+ )
446
+ @click.option("--auto-approve", is_flag=True, help="Skip interactive approval")
447
+ @click.option(
448
+ "--no-auto-naming",
449
+ is_flag=True,
450
+ help="Disable automatic construct ID injection",
451
+ )
452
+ @click.option("--skip-synth", is_flag=True, help="Skip synthesis step")
453
+ @deferred_options
454
+ def deploy(
455
+ stack: str | None,
456
+ app: str | None,
457
+ outdir: str | None,
458
+ auto_approve: bool,
459
+ no_auto_naming: bool,
460
+ skip_synth: bool,
461
+ apply_deferred: bool | None = None,
462
+ concurrent_applies: bool | None = None,
463
+ graph_plan_scope: str | None = None,
464
+ deferred_approval: str | None = None,
465
+ incomplete_exit_code: int | None = None,
466
+ provider_data_sources: str | None = None,
467
+ deleted_objects: str | None = None,
468
+ provenance_report: bool | None = None,
469
+ baseline: str | None = None,
470
+ prefer_mine: tuple[str, ...] = (),
471
+ parallelism: int | None = None,
472
+ read_parallelism: int | None = None,
473
+ quiet: bool | None = None,
474
+ refresh: bool | None = None,
475
+ targets: tuple[str, ...] = (),
476
+ plan_scope: str | None = None,
477
+ ) -> None:
478
+ """Deploy infrastructure (synth + init + apply).
479
+
480
+ This command combines multiple steps into one:
481
+ 1. Synthesize the app (unless --skip-synth)
482
+ 2. Initialize Terraform if needed
483
+ 3. Apply the changes
484
+
485
+ Examples:
486
+ nf deploy # Deploy all stacks
487
+ nf deploy -s my-stack # Deploy specific stack
488
+ nf deploy --app my-app # Synth specific app then deploy
489
+ nf deploy --outdir build/.nf.out
490
+
491
+ """
492
+ from .hybrid import exit_if_incomplete, incomplete_exit_code as exit_code_of
493
+
494
+ set_execution_overrides(
495
+ refresh=refresh,
496
+ targets=targets or None,
497
+ plan_scope=plan_scope,
498
+ quiet=quiet,
499
+ parallelism=parallelism,
500
+ read_parallelism=read_parallelism,
501
+ apply_deferred=apply_deferred,
502
+ concurrent_applies=concurrent_applies,
503
+ graph_plan_scope=graph_plan_scope,
504
+ deferred_approval=deferred_approval,
505
+ incomplete_exit_code=incomplete_exit_code,
506
+ provider_data_sources=provider_data_sources,
507
+ deleted_objects=deleted_objects,
508
+ provenance_report=provenance_report,
509
+ baseline=baseline,
510
+ prefer_mine=prefer_mine or None,
511
+ )
512
+ from .infrastructure import (
513
+ _direct_execution_errors,
514
+ _resolve_direct_stack_target,
515
+ find_stack_directory,
516
+ get_stack_name,
517
+ _reject_phased_stack_dir,
518
+ run_terraform_command,
519
+ )
520
+
521
+ project_config = load_project_config(allow_empty_apps=skip_synth)
522
+ hybrid_apps = project_config.hybrid_apps
523
+ direct_stack_target = _resolve_direct_stack_target(
524
+ stack,
525
+ app=app,
526
+ outdir=outdir,
527
+ )
528
+
529
+ if direct_stack_target is not None:
530
+ if skip_synth:
531
+ console.print(
532
+ "[dim]Direct execution does not use synthesized Terraform output; ignoring --skip-synth.[/dim]",
533
+ )
534
+
535
+ app_name, stack_name, direct_exec = direct_stack_target
536
+ console.print("[bold blue]Direct deploy selected[/bold blue]")
537
+ console.print(
538
+ f"[dim]Deploying stack {app_name}/{stack_name} with direct execution[/dim]",
539
+ )
540
+
541
+ console.print(
542
+ "\n[bold blue]Step 1/2: Planning with direct execution...[/bold blue]",
543
+ )
544
+ direct_exec_any = cast("Any", direct_exec)
545
+ with _direct_execution_errors("planning deployment"):
546
+ stack_plan = direct_exec_any.create_stack_plan(stack_name)
547
+ console.print()
548
+ if not print_plan_counts(stack_plan.summary) and not stack_plan.summary.get("graph_state"):
549
+ return
550
+
551
+ console.print(
552
+ "\n[bold blue]Step 2/2: Applying with direct execution...[/bold blue]",
553
+ )
554
+ result = direct_exec_any.apply_stack(
555
+ stack_name,
556
+ auto_approve=auto_approve,
557
+ plan=stack_plan,
558
+ )
559
+ if not result.success:
560
+ console.print(
561
+ f"\n[bold red]✗ Direct deployment failed or was cancelled for '{app_name}/{stack_name}'[/bold red]",
562
+ )
563
+ print_result_errors(result)
564
+ sys.exit(1)
565
+
566
+ code = exit_code_of(result, direct_exec)
567
+ if not code:
568
+ console.print("\n[bold green]✓ Direct deployment complete![/bold green]")
569
+ exit_if_incomplete(code)
570
+ return
571
+
572
+ direct_deploy_targets: list[str] = []
573
+ if app and app in hybrid_apps:
574
+ direct_deploy_targets = [app]
575
+ elif app and app in project_config.legacy_apps:
576
+ direct_deploy_targets = [app]
577
+ elif app is None and not project_config.legacy_apps and hybrid_apps:
578
+ direct_deploy_targets = list(hybrid_apps)
579
+
580
+ if direct_deploy_targets:
581
+ if stack:
582
+ raise click.ClickException(
583
+ "--stack is not currently supported for app-scoped direct deploys; deploy the app as a whole with --app",
584
+ )
585
+
586
+ if skip_synth:
587
+ console.print(
588
+ "[dim]Direct execution does not use synthesized Terraform output; ignoring --skip-synth.[/dim]",
589
+ )
590
+
591
+ console.print("[bold blue]Direct deploy selected[/bold blue]")
592
+ if len(direct_deploy_targets) > 1:
593
+ console.print(
594
+ f"[dim]Deploying {len(direct_deploy_targets)} apps in configuration order[/dim]",
595
+ )
596
+
597
+ code = 0
598
+ for index, direct_app_name in enumerate(direct_deploy_targets, start=1):
599
+ if len(direct_deploy_targets) > 1:
600
+ console.print(
601
+ f"\n[bold blue]App {index}/{len(direct_deploy_targets)}: {direct_app_name}[/bold blue]",
602
+ )
603
+
604
+ from .hybrid import get_direct_app_and_exec
605
+
606
+ hybrid_exec = get_direct_app_and_exec(direct_app_name, outdir=outdir)
607
+
608
+ console.print(
609
+ "\n[bold blue]Step 1/2: Planning with direct execution...[/bold blue]",
610
+ )
611
+ with _direct_execution_errors("planning deployment"):
612
+ plan_artifact = hybrid_exec.create_plan_artifact()
613
+ console.print()
614
+ summary = plan_artifact.to_summary()
615
+ if not print_plan_counts(summary) and not summary.get("graph_state"):
616
+ continue
617
+
618
+ console.print(
619
+ "\n[bold blue]Step 2/2: Applying with direct execution...[/bold blue]",
620
+ )
621
+ result = hybrid_exec.apply(auto_approve=auto_approve, plan=plan_artifact)
622
+ if not result.success:
623
+ console.print(
624
+ f"\n[bold red]✗ Direct deployment failed or was cancelled for '{direct_app_name}'[/bold red]",
625
+ )
626
+ print_result_errors(result)
627
+ sys.exit(1)
628
+ code = code or exit_code_of(result, hybrid_exec)
629
+
630
+ if not code:
631
+ console.print("\n[bold green]✓ Direct deployment complete![/bold green]")
632
+ exit_if_incomplete(code)
633
+ return
634
+
635
+ if concurrent_applies:
636
+ raise click.ClickException("--concurrent-applies requires a hybrid app with graph state")
637
+ if graph_plan_scope == "affected":
638
+ raise click.ClickException("--graph-plan-scope affected requires a hybrid app with graph state")
639
+ if read_parallelism is not None:
640
+ raise click.ClickException("--read-parallelism requires a direct-execution app")
641
+ if plan_scope is not None and plan_scope != "full":
642
+ raise click.ClickException("--plan-scope changed requires direct execution")
643
+ parallel_args = [f"-parallelism={parallelism}"] if parallelism is not None else []
644
+ parallel_args.extend([f"-refresh={str(refresh).lower()}"] if refresh is not None else [])
645
+ parallel_args.extend(f"-target={key}" for key in targets)
646
+
647
+ # Step 1: Synthesize if needed
648
+ if not skip_synth:
649
+ console.print("[bold blue]Step 1/3: Synthesizing...[/bold blue]")
650
+
651
+ if app:
652
+ # Synthesize specific app
653
+ app_config = project_config.legacy_apps
654
+ python_cmd = project_config.python_cmd
655
+ if app not in app_config:
656
+ console.print(f"[bold red]App '{app}' not found.[/bold red]")
657
+ raise click.ClickException(f"App '{app}' not found")
658
+
659
+ try:
660
+ import_app(
661
+ app_config[app],
662
+ python_cmd,
663
+ enable_auto_naming=not no_auto_naming,
664
+ outdir=outdir,
665
+ )
666
+ console.print("[bold green]✓[/bold green] Synthesis complete")
667
+ except Exception as e:
668
+ console.print(f"[bold red]✗[/bold red] Synthesis failed: {e}")
669
+ raise click.ClickException("Synthesis failed") from e
670
+ else:
671
+ # Synthesize all apps via API (avoid invoking CLI from CLI)
672
+ success = run_synthesis(
673
+ (),
674
+ no_auto_naming=no_auto_naming,
675
+ include_all=False,
676
+ phased=False,
677
+ outdir=outdir,
678
+ )
679
+ if not success:
680
+ console.print("[bold red]✗[/bold red] Synthesis failed")
681
+ raise click.ClickException("Synthesis failed")
682
+ console.print("[bold green]✓[/bold green] Synthesis complete")
683
+
684
+ # Step 2: Get stack to deploy
685
+ stack_name = get_stack_name(stack, outdir)
686
+ stack_dir = find_stack_directory(stack_name, outdir)
687
+ _reject_phased_stack_dir(stack_dir, command_name="deploy")
688
+
689
+ # Step 3: Initialize Terraform if needed
690
+ console.print("\n[bold blue]Step 2/3: Initializing Terraform...[/bold blue]")
691
+
692
+ # Check if already initialized
693
+ if not (stack_dir / ".terraform").exists():
694
+ init_result = run_terraform_command(stack_dir, ["init"])
695
+ if init_result != 0:
696
+ console.print("[bold red]✗[/bold red] Terraform init failed")
697
+ sys.exit(init_result)
698
+ console.print("[bold green]✓[/bold green] Terraform initialized")
699
+ else:
700
+ console.print("[dim]Already initialized[/dim]")
701
+
702
+ # Step 4: Apply changes
703
+ console.print("\n[bold blue]Step 3/3: Applying changes...[/bold blue]")
704
+
705
+ # Show plan first if not auto-approving
706
+ if not auto_approve:
707
+ console.print("\n[dim]Running terraform plan...[/dim]")
708
+ plan_result = run_terraform_command(stack_dir, ["plan", *parallel_args])
709
+ if plan_result != 0:
710
+ console.print("[bold red]✗[/bold red] Terraform plan failed")
711
+ sys.exit(plan_result)
712
+
713
+ if not click.confirm("\nDo you want to apply these changes?"):
714
+ console.print("[yellow]Deployment cancelled[/yellow]")
715
+ return
716
+
717
+ # Apply
718
+ apply_result = run_terraform_command(
719
+ stack_dir,
720
+ ["apply", *parallel_args],
721
+ auto_approve=auto_approve,
722
+ )
723
+
724
+ if apply_result == 0:
725
+ console.print("\n[bold green]✓ Deployment complete![/bold green]")
726
+
727
+ # Show outputs if any
728
+ console.print("\n[bold]Outputs:[/bold]")
729
+ run_terraform_command(stack_dir, ["output"])
730
+ else:
731
+ console.print("\n[bold red]✗ Deployment failed[/bold red]")
732
+ sys.exit(apply_result)