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,493 @@
1
+ """Interactive diff command for viewing infrastructure plans."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import click
9
+ import questionary
10
+
11
+ from netherframe.cli.services.app_loader import load_app_from_spec
12
+ from netherframe.cli.ui import console
13
+ from netherframe.core.serialization import orjson_compat as json
14
+
15
+ from netherframe.cli.services.project_config import load_app_config
16
+
17
+ _VALID_ACTIONS = {"create", "update", "delete"}
18
+ _PRIORITY_PLAN_NAMES = (
19
+ "idiff_plan.json",
20
+ "plan.json",
21
+ )
22
+ _SUMMARY_FORMATS = ("text", "json", "md")
23
+
24
+
25
+ def _select_choice(
26
+ message: str,
27
+ choices: list[str],
28
+ *,
29
+ cancel_message: str,
30
+ ) -> str:
31
+ if not choices:
32
+ raise click.ClickException("No selectable options available.")
33
+ if len(choices) == 1:
34
+ return choices[0]
35
+
36
+ selected = questionary.select(message, choices=choices).ask()
37
+ if selected is None:
38
+ raise click.ClickException(cancel_message)
39
+ return str(selected)
40
+
41
+
42
+ def _build_summary(changes: list[dict[str, Any]]) -> dict[str, int]:
43
+ creates = sum(1 for change in changes if change.get("action") == "create")
44
+ updates = sum(1 for change in changes if change.get("action") == "update")
45
+ deletes = sum(1 for change in changes if change.get("action") == "delete")
46
+ return {
47
+ "total_changes": len(changes),
48
+ "creates": creates,
49
+ "updates": updates,
50
+ "deletes": deletes,
51
+ }
52
+
53
+
54
+ def _normalize_change(
55
+ raw_change: dict[str, Any],
56
+ index: int,
57
+ *,
58
+ fallback_resource_id: str | None = None,
59
+ ) -> dict[str, Any]:
60
+ action = str(raw_change.get("action", "update")).lower()
61
+ if action not in _VALID_ACTIONS:
62
+ action = "update"
63
+
64
+ resource_id = str(
65
+ raw_change.get("resource_id") or raw_change.get("resource") or fallback_resource_id or f"resource-{index}",
66
+ )
67
+ description = str(
68
+ raw_change.get("description") or f"{action.capitalize()} {resource_id}",
69
+ )
70
+
71
+ normalized = dict(raw_change)
72
+ normalized["resource_id"] = resource_id
73
+ normalized["action"] = action
74
+ normalized["description"] = description
75
+ normalized["resource_type"] = str(raw_change.get("resource_type", ""))
76
+ normalized["resource_name"] = str(raw_change.get("resource_name", ""))
77
+ normalized["attribute_changes"] = raw_change.get("attribute_changes") or []
78
+ normalized["before_state"] = raw_change.get("before_state") or {}
79
+ normalized["after_state"] = raw_change.get("after_state") or {}
80
+ return normalized
81
+
82
+
83
+ def _normalize_plan_dict(plan_data: dict[str, Any]) -> dict[str, Any]:
84
+ if isinstance(plan_data.get("changes"), list):
85
+ changes = [_normalize_change(change, index) for index, change in enumerate(plan_data["changes"], start=1) if isinstance(change, dict)]
86
+ computed_summary = _build_summary(changes)
87
+ raw_summary = plan_data.get("summary")
88
+ if isinstance(raw_summary, dict):
89
+ summary = {
90
+ "total_changes": int(
91
+ raw_summary.get("total_changes", computed_summary["total_changes"]),
92
+ ),
93
+ "creates": int(raw_summary.get("creates", computed_summary["creates"])),
94
+ "updates": int(raw_summary.get("updates", computed_summary["updates"])),
95
+ "deletes": int(raw_summary.get("deletes", computed_summary["deletes"])),
96
+ }
97
+ else:
98
+ summary = computed_summary
99
+ return {"summary": summary, "changes": changes}
100
+
101
+ stacks = plan_data.get("stacks")
102
+ if isinstance(stacks, dict):
103
+ changes: list[dict[str, Any]] = []
104
+ change_index = 1
105
+ for stack_name, stack_changes in stacks.items():
106
+ if not isinstance(stack_changes, list):
107
+ continue
108
+ for stack_change in stack_changes:
109
+ if not isinstance(stack_change, dict):
110
+ continue
111
+ normalized = _normalize_change(
112
+ stack_change,
113
+ change_index,
114
+ fallback_resource_id=f"{stack_name}:change-{change_index}",
115
+ )
116
+ normalized["stack"] = stack_name
117
+ changes.append(normalized)
118
+ change_index += 1
119
+
120
+ computed_summary = _build_summary(changes)
121
+ summary = {
122
+ "total_changes": int(plan_data.get("total_changes", computed_summary["total_changes"])),
123
+ "creates": int(plan_data.get("creates", computed_summary["creates"])),
124
+ "updates": int(plan_data.get("updates", computed_summary["updates"])),
125
+ "deletes": int(plan_data.get("deletes", computed_summary["deletes"])),
126
+ }
127
+ return {"summary": summary, "changes": changes}
128
+
129
+ msg = "Unsupported plan format. Expected one of: detailed plan JSON or hybrid summary JSON."
130
+ raise click.ClickException(msg)
131
+
132
+
133
+ def _normalize_plan_data(plan_data: Any) -> dict[str, Any]:
134
+ if isinstance(plan_data, dict):
135
+ return _normalize_plan_dict(plan_data)
136
+ msg = "Unsupported plan format. Expected JSON object. Use --plan-file with a valid plan JSON."
137
+ raise click.ClickException(msg)
138
+
139
+
140
+ def _read_plan_file(plan_path: Path) -> dict[str, Any]:
141
+ try:
142
+ with plan_path.open() as f:
143
+ raw_data = json.load(f)
144
+ except Exception as e:
145
+ raise click.ClickException(f"Failed to read plan file '{plan_path}': {e}") from e
146
+ return _normalize_plan_data(raw_data)
147
+
148
+
149
+ def _discover_plan_candidates(outdir: Path) -> list[Path]:
150
+ if outdir.is_file():
151
+ if outdir.suffix.lower() != ".json":
152
+ raise click.ClickException(f"Plan file must be JSON: {outdir}")
153
+ return [outdir]
154
+
155
+ if not outdir.exists():
156
+ raise click.ClickException(
157
+ f"Outdir does not exist: {outdir}. Pass --plan-file or run synthesis first.",
158
+ )
159
+
160
+ candidates: list[Path] = []
161
+ for plan_name in _PRIORITY_PLAN_NAMES:
162
+ candidates.extend(sorted(outdir.rglob(plan_name)))
163
+
164
+ unique_candidates: list[Path] = []
165
+ seen: set[str] = set()
166
+ for path in candidates:
167
+ path_key = str(path.resolve())
168
+ if path_key in seen:
169
+ continue
170
+ seen.add(path_key)
171
+ unique_candidates.append(path)
172
+
173
+ if not unique_candidates:
174
+ raise click.ClickException(
175
+ f"No plan files found under {outdir}. Pass --plan-file or use --native.",
176
+ )
177
+ return unique_candidates
178
+
179
+
180
+ def _discover_or_select_plan_file(outdir: Path) -> Path:
181
+ candidates = _discover_plan_candidates(outdir)
182
+ if len(candidates) == 1:
183
+ return candidates[0]
184
+
185
+ selected = _select_choice(
186
+ "Select plan file:",
187
+ [str(path) for path in candidates],
188
+ cancel_message="Plan selection cancelled.",
189
+ )
190
+ return Path(selected)
191
+
192
+
193
+ def _resolve_app_spec(app_name: str | None) -> str:
194
+ app_config, _, _ = load_app_config()
195
+
196
+ if app_name:
197
+ if app_name in app_config:
198
+ return app_config[app_name]
199
+ if app_name in app_config.values():
200
+ return app_name
201
+ available = ", ".join(sorted(app_config.keys()))
202
+ raise click.ClickException(
203
+ f"Unknown app '{app_name}'. Available configured apps: {available}",
204
+ )
205
+
206
+ if len(app_config) == 1:
207
+ return next(iter(app_config.values()))
208
+
209
+ selected_name = _select_choice(
210
+ "Select app for native plan generation:",
211
+ sorted(app_config.keys()),
212
+ cancel_message="App selection cancelled.",
213
+ )
214
+ return app_config[selected_name]
215
+
216
+
217
+ def _load_configured_app(app_name: str | None) -> Any:
218
+ app_spec = _resolve_app_spec(app_name)
219
+ return load_app_from_spec(app_spec)
220
+
221
+
222
+ def _generate_native_plan(app_name: str | None, outdir: Path) -> dict[str, Any]:
223
+ from netherframe.core.execution.hybrid import enable_hybrid_execution
224
+
225
+ console.print("[yellow]Loading app and generating hybrid execution plan...[/yellow]")
226
+ app = _load_configured_app(app_name)
227
+ hybrid_exec = enable_hybrid_execution(app, outdir=outdir)
228
+ return _normalize_plan_data(hybrid_exec.plan())
229
+
230
+
231
+ def _build_compare_plan(
232
+ *,
233
+ base_plan: dict[str, Any],
234
+ target_plan: dict[str, Any],
235
+ base_label: str,
236
+ target_label: str,
237
+ ) -> dict[str, Any]:
238
+ base_changes = {change["resource_id"]: change for change in base_plan.get("changes", []) if isinstance(change, dict) and change.get("resource_id")}
239
+ target_changes = {change["resource_id"]: change for change in target_plan.get("changes", []) if isinstance(change, dict) and change.get("resource_id")}
240
+
241
+ compared_changes: list[dict[str, Any]] = []
242
+ for resource_id in sorted(set(base_changes) | set(target_changes)):
243
+ before = base_changes.get(resource_id)
244
+ after = target_changes.get(resource_id)
245
+
246
+ if before is not None and after is not None and before == after:
247
+ continue
248
+
249
+ if before is None:
250
+ action = "create"
251
+ description = f"Added in target plan: {resource_id}"
252
+ elif after is None:
253
+ action = "delete"
254
+ description = f"Removed from target plan: {resource_id}"
255
+ else:
256
+ action = "update"
257
+ description = f"Changed in target plan: {resource_id} ({before.get('action', 'unknown')} -> {after.get('action', 'unknown')})"
258
+
259
+ selected_change = after if after is not None else before
260
+ if selected_change is None:
261
+ continue
262
+
263
+ compared_changes.append(
264
+ {
265
+ "resource_id": resource_id,
266
+ "resource_type": str(selected_change.get("resource_type", "")),
267
+ "resource_name": str(selected_change.get("resource_name", "")),
268
+ "action": action,
269
+ "description": description,
270
+ "attribute_changes": [],
271
+ "before_state": {"attributes": before} if before else {},
272
+ "after_state": {"attributes": after} if after else {},
273
+ "compare": {
274
+ "base_action": before and before.get("action"),
275
+ "target_action": after and after.get("action"),
276
+ },
277
+ },
278
+ )
279
+
280
+ return {
281
+ "summary": _build_summary(compared_changes),
282
+ "changes": compared_changes,
283
+ "compare": {
284
+ "base": base_label,
285
+ "target": target_label,
286
+ },
287
+ }
288
+
289
+
290
+ def _summary_payload(plan_data: dict[str, Any]) -> dict[str, Any]:
291
+ changes = []
292
+ for change in plan_data.get("changes", []):
293
+ if not isinstance(change, dict):
294
+ continue
295
+ changes.append(
296
+ {
297
+ "resource_id": change.get("resource_id", ""),
298
+ "action": change.get("action", ""),
299
+ "description": change.get("description", ""),
300
+ },
301
+ )
302
+
303
+ payload: dict[str, Any] = {
304
+ "summary": plan_data.get("summary", {}),
305
+ "changes": changes,
306
+ }
307
+ if "compare" in plan_data:
308
+ payload["compare"] = plan_data["compare"]
309
+ return payload
310
+
311
+
312
+ def _render_summary_text(plan_data: dict[str, Any], output_format: str) -> str:
313
+ payload = _summary_payload(plan_data)
314
+ summary = payload["summary"]
315
+ if output_format == "json":
316
+ return json.dumps(payload, indent=2)
317
+
318
+ if output_format == "md":
319
+ lines = [
320
+ "# Plan Summary",
321
+ "",
322
+ f"- Total: **{summary.get('total_changes', 0)}**",
323
+ f"- Create: **{summary.get('creates', 0)}**",
324
+ f"- Update: **{summary.get('updates', 0)}**",
325
+ f"- Delete: **{summary.get('deletes', 0)}**",
326
+ ]
327
+ if "compare" in payload:
328
+ compare = payload["compare"]
329
+ lines.extend(
330
+ [
331
+ "",
332
+ f"- Base: `{compare.get('base', '')}`",
333
+ f"- Target: `{compare.get('target', '')}`",
334
+ ],
335
+ )
336
+ lines.extend(
337
+ [
338
+ "",
339
+ "| Action | Resource | Description |",
340
+ "|---|---|---|",
341
+ ],
342
+ )
343
+ for change in payload["changes"]:
344
+ lines.append(
345
+ f"| {change['action']} | `{change['resource_id']}` | {change['description']} |",
346
+ )
347
+ return "\n".join(lines)
348
+
349
+ lines = [
350
+ "Plan Summary",
351
+ f" Total: {summary.get('total_changes', 0)}",
352
+ f" Create: {summary.get('creates', 0)}",
353
+ f" Update: {summary.get('updates', 0)}",
354
+ f" Delete: {summary.get('deletes', 0)}",
355
+ ]
356
+ if "compare" in payload:
357
+ compare = payload["compare"]
358
+ lines.append(f" Base: {compare.get('base', '')}")
359
+ lines.append(f" Target: {compare.get('target', '')}")
360
+ lines.append("")
361
+ for change in payload["changes"]:
362
+ lines.append(f"[{change['action']}] {change['resource_id']} - {change['description']}")
363
+ return "\n".join(lines)
364
+
365
+
366
+ @click.command(name="idiff", help="View infrastructure plans in an interactive TUI")
367
+ @click.option(
368
+ "--plan-file",
369
+ "-p",
370
+ type=click.Path(exists=True, path_type=Path),
371
+ help="Path to a plan file (JSON format)",
372
+ )
373
+ @click.option(
374
+ "--native",
375
+ is_flag=True,
376
+ default=False,
377
+ help="Generate a plan from configured app(s) using hybrid execution mode",
378
+ )
379
+ @click.option(
380
+ "--app",
381
+ help="Configured app name/spec to use with --native",
382
+ )
383
+ @click.option(
384
+ "--outdir",
385
+ "-o",
386
+ type=click.Path(path_type=Path),
387
+ default=Path(".nf.out"),
388
+ show_default=True,
389
+ help="Directory to search for plan files and hybrid state output",
390
+ )
391
+ @click.option(
392
+ "--save-plan",
393
+ "-s",
394
+ type=click.Path(path_type=Path),
395
+ help="Save normalized plan JSON to a file",
396
+ )
397
+ @click.option(
398
+ "--compare",
399
+ type=click.Path(exists=True, path_type=Path),
400
+ help="Compare the selected/base plan against another plan file",
401
+ )
402
+ @click.option(
403
+ "--summary",
404
+ "summary_only",
405
+ is_flag=True,
406
+ help="Print plan summary and exit without launching the TUI",
407
+ )
408
+ @click.option(
409
+ "--format",
410
+ "output_format",
411
+ type=click.Choice(_SUMMARY_FORMATS),
412
+ default="text",
413
+ show_default=True,
414
+ help="Output format for --summary",
415
+ )
416
+ def idiff(
417
+ plan_file: Path | None,
418
+ native: bool,
419
+ app: str | None,
420
+ outdir: Path,
421
+ save_plan: Path | None,
422
+ compare: Path | None,
423
+ summary_only: bool,
424
+ output_format: str,
425
+ ) -> None:
426
+ """Launch interactive TUI for viewing infrastructure plans."""
427
+ from netherframe.cli.tui.plan_viewer import PlanViewerApp
428
+
429
+ if plan_file and native:
430
+ raise click.ClickException("Cannot combine --plan-file and --native.")
431
+ if app and not native:
432
+ raise click.ClickException("--app can only be used with --native.")
433
+ if compare and native:
434
+ raise click.ClickException("Cannot combine --compare and --native.")
435
+
436
+ if native:
437
+ selected_app = app
438
+ if selected_app is None:
439
+ # Resolve interactive/native app selection once and reuse it for refresh.
440
+ selected_app = _resolve_app_spec(None)
441
+
442
+ def _load_native_plan() -> dict[str, Any]:
443
+ return _generate_native_plan(selected_app, outdir)
444
+
445
+ plan_loader = _load_native_plan
446
+ plan_data = _load_native_plan()
447
+ else:
448
+ selected_plan_file = plan_file or _discover_or_select_plan_file(outdir)
449
+ selected_plan_file = selected_plan_file.resolve()
450
+ if not summary_only:
451
+ console.print(f"[dim]Loading plan from {selected_plan_file}[/dim]")
452
+
453
+ if compare:
454
+ compare_file = compare.resolve()
455
+
456
+ def _load_compared_plan() -> dict[str, Any]:
457
+ base_plan = _read_plan_file(selected_plan_file)
458
+ target_plan = _read_plan_file(compare_file)
459
+ return _build_compare_plan(
460
+ base_plan=base_plan,
461
+ target_plan=target_plan,
462
+ base_label=str(selected_plan_file),
463
+ target_label=str(compare_file),
464
+ )
465
+
466
+ plan_loader = _load_compared_plan
467
+ else:
468
+
469
+ def _load_selected_plan() -> dict[str, Any]:
470
+ return _read_plan_file(selected_plan_file)
471
+
472
+ plan_loader = _load_selected_plan
473
+
474
+ plan_data = plan_loader()
475
+
476
+ if summary_only:
477
+ click.echo(_render_summary_text(plan_data, output_format))
478
+ return
479
+
480
+ if save_plan:
481
+ try:
482
+ save_plan.parent.mkdir(parents=True, exist_ok=True)
483
+ with save_plan.open("w") as f:
484
+ json.dump(plan_data, f, indent=2)
485
+ console.print(f"[green]Plan saved to: {save_plan}[/green]")
486
+ except Exception as e:
487
+ raise click.ClickException(f"Failed to save plan to '{save_plan}': {e}") from e
488
+
489
+ viewer = PlanViewerApp(
490
+ plan_data,
491
+ reload_plan=plan_loader,
492
+ )
493
+ viewer.run()