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,745 @@
1
+ """Interactive TUI for viewing infrastructure plans."""
2
+
3
+ from netherframe.core.serialization import orjson_compat as json
4
+ import pathlib
5
+ from collections.abc import Callable
6
+ from typing import Any, ClassVar
7
+
8
+ from netherframe.core.orchestration.event_loop import run_in_thread
9
+ from netherframe.core.serialization.unknown_values import KNOWN_AFTER_APPLY, displayed
10
+ from rich.console import RenderableType
11
+ from rich.markup import escape
12
+ from rich.syntax import Syntax
13
+ from rich.text import Text
14
+ from textual.app import App, ComposeResult
15
+ from textual.binding import Binding, BindingType
16
+ from textual.containers import Container, Horizontal, Vertical, VerticalScroll
17
+ from textual.reactive import reactive
18
+ from textual.screen import Screen
19
+ from textual.widget import Widget
20
+ from textual.widgets import (
21
+ Footer,
22
+ Header,
23
+ Input,
24
+ ListItem,
25
+ ListView,
26
+ Static,
27
+ TabbedContent,
28
+ TabPane,
29
+ )
30
+ from .plan_filters import build_query_matcher, next_action_filter
31
+ from .plan_models import ResourceChange
32
+
33
+
34
+ class ResourceListItem(ListItem):
35
+ """A list item for displaying a resource change."""
36
+
37
+ def __init__(self, change: ResourceChange) -> None:
38
+ super().__init__()
39
+ self.change = change
40
+
41
+ def compose(self) -> ComposeResult:
42
+ """Compose the resource list item."""
43
+ icon_color = self.change.color
44
+ yield Static(
45
+ f"[{icon_color}]{self.change.icon}[/{icon_color}] {self.change.resource_id}",
46
+ classes="resource-item",
47
+ )
48
+
49
+
50
+ class ResourceList(ListView):
51
+ """List view for resource changes."""
52
+
53
+ def __init__(self, changes: list[ResourceChange], **kwargs: Any) -> None:
54
+ super().__init__(**kwargs)
55
+ self.changes = changes
56
+ self._pending_changes = changes
57
+
58
+ def on_mount(self) -> None:
59
+ """Populate list when mounted."""
60
+ self._populate_list()
61
+
62
+ def _populate_list(self) -> None:
63
+ """Populate the list with resource changes."""
64
+ for change in self._pending_changes:
65
+ self.append(ResourceListItem(change))
66
+ self._pending_changes = []
67
+
68
+ def filter_changes(self, query: str) -> None:
69
+ """Filter changes based on search query."""
70
+ self.clear()
71
+ for change in self.changes:
72
+ if query.lower() in change.resource_id.lower():
73
+ self.append(ResourceListItem(change))
74
+
75
+ def set_changes(self, changes: list[ResourceChange]) -> None:
76
+ """Replace list contents with a new set of changes."""
77
+ self.clear()
78
+ self.changes = changes
79
+ for change in changes:
80
+ self.append(ResourceListItem(change))
81
+
82
+
83
+ class PlanSummary(Widget):
84
+ """Widget to display plan summary statistics."""
85
+
86
+ def __init__(self, summary: dict[str, int]) -> None:
87
+ super().__init__()
88
+ self.summary = summary
89
+ self.filtered_total = summary.get("total_changes", 0)
90
+ self.filters = {"create", "update", "delete"}
91
+ self.action_scope = "all"
92
+ self.filter_query = ""
93
+ self.query_mode = "text"
94
+ self.query_pending = False
95
+ self.query_error = ""
96
+
97
+ def render(self) -> RenderableType:
98
+ """Render the plan summary."""
99
+ total = self.summary.get("total_changes", 0)
100
+ creates = self.summary.get("creates", 0)
101
+ updates = self.summary.get("updates", 0)
102
+ deletes = self.summary.get("deletes", 0)
103
+ filter_badges = [
104
+ f"[green]{'C' if 'create' in self.filters else '·'}[/green]",
105
+ f"[yellow]{'U' if 'update' in self.filters else '·'}[/yellow]",
106
+ f"[red]{'D' if 'delete' in self.filters else '·'}[/red]",
107
+ ]
108
+ visible = self.filtered_total
109
+ query_text = self.filter_query.strip()
110
+ if len(query_text) > 60:
111
+ query_text = f"{query_text[:57]}..."
112
+
113
+ if query_text:
114
+ if self.query_pending:
115
+ query_state = "[yellow]pending[/yellow]"
116
+ elif self.query_error:
117
+ query_state = "[red]invalid[/red]"
118
+ else:
119
+ query_state = "[green]applied[/green]"
120
+ query_label = "Expr" if self.query_mode == "expr" else "Text"
121
+ filter_line = f"Filter: {query_label} ({query_state}) [cyan]{query_text}[/cyan]"
122
+ else:
123
+ filter_line = "Filter: [dim]none[/dim]"
124
+
125
+ if self.action_scope == "all":
126
+ action_line = "Action Filter: [dim]ALL[/dim]"
127
+ else:
128
+ action_line = f"Action Filter: [bold]{self.action_scope.upper()} ONLY[/bold]"
129
+
130
+ has_action_filter = self.action_scope != "all"
131
+ has_query_filter = bool(query_text)
132
+ if has_action_filter or has_query_filter:
133
+ reasons: list[str] = []
134
+ if has_action_filter:
135
+ reasons.append("action")
136
+ if has_query_filter:
137
+ reasons.append("query")
138
+ active_filter_line = f"Active Filters: [green]YES[/green] [dim]({', '.join(reasons)})[/dim]"
139
+ else:
140
+ active_filter_line = "Active Filters: [dim]no[/dim]"
141
+
142
+ return Text.from_markup(
143
+ f"[bold]Plan Summary[/bold]\nVisible: [cyan]{visible}[/cyan] / Total: [cyan]{total}[/cyan]\n{active_filter_line}\n[green]+[/green] Create: [green]{creates}[/green]\n[yellow]~[/yellow] Update: [yellow]{updates}[/yellow]\n[red]-[/red] Delete: [red]{deletes}[/red]\nFilters: {' '.join(filter_badges)}\n{action_line}\n{filter_line}",
144
+ )
145
+
146
+ def set_filters(
147
+ self,
148
+ *,
149
+ filtered_total: int,
150
+ actions: set[str],
151
+ query: str,
152
+ query_mode: str,
153
+ query_pending: bool,
154
+ query_error: str,
155
+ ) -> None:
156
+ """Update active action filters and visible count."""
157
+ self.filtered_total = filtered_total
158
+ self.filters = set(actions)
159
+ self.filter_query = query
160
+ self.query_mode = query_mode
161
+ self.query_pending = query_pending
162
+ self.query_error = query_error
163
+ if actions == {"create"}:
164
+ self.action_scope = "create"
165
+ elif actions == {"update"}:
166
+ self.action_scope = "update"
167
+ elif actions == {"delete"}:
168
+ self.action_scope = "delete"
169
+ else:
170
+ self.action_scope = "all"
171
+ self.refresh()
172
+
173
+
174
+ class ResourceDetail(Widget):
175
+ """Widget to display detailed information about a selected resource."""
176
+
177
+ current_resource: reactive[ResourceChange | None] = reactive(None)
178
+
179
+ def compose(self) -> ComposeResult:
180
+ """Compose the detail view with tabs."""
181
+ with TabbedContent(id="detail-tabs"):
182
+ with TabPane("Overview", id="overview-tab"):
183
+ yield Static(id="overview-content")
184
+ with TabPane("Changes", id="changes-tab"):
185
+ yield Static(id="changes-content")
186
+ with TabPane("Before", id="before-tab"):
187
+ yield Static(id="before-content")
188
+ with TabPane("After", id="after-tab"):
189
+ yield Static(id="after-content")
190
+ with TabPane("Raw", id="raw-tab"):
191
+ yield Static(id="raw-content")
192
+
193
+ def on_mount(self) -> None:
194
+ """Initialize detail tabs with placeholder content."""
195
+ self._render_placeholder()
196
+
197
+ def _render_placeholder(self) -> None:
198
+ """Render placeholder text when no resource is selected."""
199
+ placeholder = Text("Select a resource to view details", style="dim")
200
+ self.query_one("#overview-content", Static).update(placeholder)
201
+ self.query_one("#changes-content", Static).update(placeholder)
202
+ self.query_one("#before-content", Static).update(placeholder)
203
+ self.query_one("#after-content", Static).update(placeholder)
204
+ self.query_one("#raw-content", Static).update(placeholder)
205
+
206
+ def watch_current_resource(self, resource: ResourceChange | None) -> None:
207
+ """Update content when resource changes."""
208
+ if not resource:
209
+ self._render_placeholder()
210
+ return
211
+
212
+ # Update overview
213
+ overview = self.query_one("#overview-content", Static)
214
+ overview_text = [
215
+ f"[bold]{resource.resource_id}[/bold]",
216
+ f"Type: {resource.resource_type}",
217
+ f"Name: {resource.resource_name}",
218
+ f"Action: [{resource.color}]{resource.action.upper()}[/{resource.color}]",
219
+ "",
220
+ f"[dim]{resource.description}[/dim]",
221
+ ]
222
+ overview.update(Text.from_markup("\n".join(overview_text)))
223
+
224
+ # Update changes tab: attribute changes of updates, and what is known only after apply
225
+ changes = self.query_one("#changes-content", Static)
226
+ changes_text = changes_markup(resource)
227
+ if changes_text:
228
+ changes.update(Text.from_markup("\n".join(changes_text)))
229
+ else:
230
+ changes.update(Text("No attribute changes", style="dim"))
231
+
232
+ # Update before state
233
+ before = self.query_one("#before-content", Static)
234
+ if resource.before_state:
235
+ before_json = json.dumps(
236
+ displayed(resource.before_state.get("attributes", {})),
237
+ indent=2,
238
+ )
239
+ before.update(Syntax(before_json, "json", theme="monokai"))
240
+ else:
241
+ before.update(Text("No previous state", style="dim"))
242
+
243
+ # Update after state; a value known only after apply shows as "(known after apply)"
244
+ after = self.query_one("#after-content", Static)
245
+ if resource.after_state:
246
+ after_json = json.dumps(
247
+ displayed(resource.after_state.get("attributes", {})),
248
+ indent=2,
249
+ )
250
+ after.update(Syntax(after_json, "json", theme="monokai"))
251
+ else:
252
+ after.update(Text("No future state", style="dim"))
253
+
254
+ raw_content = self.query_one("#raw-content", Static)
255
+ raw_json = json.dumps(displayed(resource.details), indent=2)
256
+ raw_content.update(Syntax(raw_json, "json", theme="monokai"))
257
+
258
+
259
+ def changes_markup(resource: ResourceChange) -> list[str]:
260
+ """The Changes tab's lines (Rich markup): an update's attribute changes, then the attributes known only after apply."""
261
+ lines: list[str] = []
262
+ if resource.action == "update" and resource.attribute_changes:
263
+ lines += ["[bold]Attribute Changes:[/bold]", ""]
264
+ for change in resource.attribute_changes:
265
+ lines.append(f"[yellow]{escape(str(change['key']))}:[/yellow]")
266
+ before_value = escape(str(displayed(change.get("before"))))
267
+ after_value = escape(str(displayed(change.get("after"))))
268
+ if change["type"] == "add":
269
+ lines.append(f" [green]+ {after_value}[/green]")
270
+ elif change["type"] == "remove":
271
+ lines.append(f" [red]- {before_value}[/red]")
272
+ else:
273
+ lines.append(f" [red]- {before_value}[/red]")
274
+ lines.append(f" [green]+ {after_value}[/green]")
275
+ lines.append("")
276
+ if resource.known_after_apply:
277
+ lines += ["[bold]Known after apply:[/bold]", ""]
278
+ lines += [f"[yellow]{escape(str(path))}[/yellow] = [dim]{KNOWN_AFTER_APPLY}[/dim]" for path in resource.known_after_apply]
279
+ return lines
280
+
281
+
282
+ class StackView(Widget):
283
+ """Widget to display changes grouped by stack."""
284
+
285
+ def __init__(self, stacks: dict[str, list[dict[str, str]]]) -> None:
286
+ super().__init__()
287
+ self.stacks = stacks
288
+
289
+ def compose(self) -> ComposeResult:
290
+ """Compose the stack view."""
291
+ with TabbedContent():
292
+ for stack_name, changes in self.stacks.items():
293
+ with TabPane(stack_name, id=f"stack-{stack_name}"):
294
+ # Convert raw changes to ResourceChange objects
295
+ resource_changes = []
296
+ for change in changes:
297
+ resource_changes.append(
298
+ ResourceChange(
299
+ resource_id=change.get(
300
+ "resource",
301
+ change.get("resource_id", ""),
302
+ ),
303
+ action=change.get("action", ""),
304
+ description=change.get("description", ""),
305
+ details=change,
306
+ ),
307
+ )
308
+ yield ResourceList(resource_changes, id=f"list-{stack_name}")
309
+
310
+
311
+ class PlanViewerScreen(Screen):
312
+ """Main screen for the plan viewer."""
313
+
314
+ BINDINGS: ClassVar[list[BindingType]] = [
315
+ Binding("q", "quit", "Quit"),
316
+ Binding("f", "toggle_filter", "Filter"),
317
+ Binding("r", "refresh", "Refresh"),
318
+ Binding("F", "activate_expression_filter", "Expr"),
319
+ Binding("/", "search", "Search"),
320
+ Binding("c", "filter_create", "Create"),
321
+ Binding("u", "filter_update", "Update"),
322
+ Binding("d", "filter_delete", "Delete"),
323
+ Binding("?", "help", "Help"),
324
+ ]
325
+
326
+ show_filter = reactive(False)
327
+
328
+ def __init__(self, plan_data: dict[str, Any]) -> None:
329
+ super().__init__()
330
+ self.plan_data = plan_data
331
+ self.all_changes = self._extract_all_changes()
332
+ self.search_query = ""
333
+ self.search_error = ""
334
+ self.last_matcher: Callable[[ResourceChange], bool] = lambda _change: True
335
+ self.enabled_actions = {"create", "update", "delete"}
336
+
337
+ def _extract_all_changes(self) -> list[ResourceChange]:
338
+ """Extract all changes from plan data."""
339
+ changes = []
340
+
341
+ # Check if we have the new detailed format
342
+ if "changes" in self.plan_data:
343
+ # New detailed format
344
+ for change in self.plan_data["changes"]:
345
+ changes.append(
346
+ ResourceChange(
347
+ resource_id=change.get("resource_id", ""),
348
+ action=change.get("action", ""),
349
+ description=change.get("description", ""),
350
+ details=change,
351
+ ),
352
+ )
353
+ else:
354
+ # Legacy format
355
+ for stack_name, stack_changes in self.plan_data.get("stacks", {}).items():
356
+ for change in stack_changes:
357
+ changes.append(
358
+ ResourceChange(
359
+ resource_id=change.get(
360
+ "resource",
361
+ change.get("resource_id", ""),
362
+ ),
363
+ action=change.get("action", ""),
364
+ description=change.get("description", ""),
365
+ details={"stack": stack_name},
366
+ ),
367
+ )
368
+ return changes
369
+
370
+ def compose(self) -> ComposeResult:
371
+ """Compose the screen layout."""
372
+ yield Header(show_clock=True)
373
+
374
+ with Container(id="main-container"), Horizontal(id="main-layout"):
375
+ # Left panel - Summary and resource list
376
+ with Vertical(id="left-panel", classes="panel"):
377
+ yield PlanSummary(self.plan_data.get("summary", {}))
378
+ yield Input(
379
+ placeholder="Filter resources...",
380
+ id="filter-input",
381
+ classes="hidden" if not self.show_filter else "",
382
+ )
383
+ yield ResourceList(self.all_changes, id="resource-list")
384
+
385
+ # Right panel - Details or stack view
386
+ with Vertical(id="right-panel", classes="panel"):
387
+ yield ResourceDetail(id="resource-detail")
388
+
389
+ yield Footer()
390
+
391
+ def on_mount(self) -> None:
392
+ """Set initial keyboard focus to the resource list."""
393
+ resource_list = self.query_one("#resource-list", ResourceList)
394
+ resource_list.focus()
395
+ self._apply_filters(ensure_selection=True)
396
+ self._sync_detail_from_list(resource_list, ensure_selection=True)
397
+
398
+ def _sync_detail_from_list(
399
+ self,
400
+ resource_list: ResourceList,
401
+ *,
402
+ ensure_selection: bool = False,
403
+ ) -> None:
404
+ """Sync right-side detail panel from the active/first list item."""
405
+ detail_widget = self.query_one("#resource-detail", ResourceDetail)
406
+
407
+ items = [child for child in list(resource_list.children) if isinstance(child, ResourceListItem)]
408
+ if not items:
409
+ detail_widget.current_resource = None
410
+ return
411
+
412
+ index = resource_list.index
413
+ if index is None or index < 0 or index >= len(items):
414
+ if not ensure_selection:
415
+ detail_widget.current_resource = None
416
+ return
417
+ index = 0
418
+ resource_list.index = index
419
+
420
+ detail_widget.current_resource = items[index].change
421
+
422
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
423
+ """Handle resource selection."""
424
+ if isinstance(event.item, ResourceListItem):
425
+ detail_widget = self.query_one("#resource-detail", ResourceDetail)
426
+ detail_widget.current_resource = event.item.change
427
+
428
+ def on_list_view_highlighted(self, event: ListView.Highlighted) -> None:
429
+ """Handle list highlight changes for live detail updates."""
430
+ if isinstance(event.item, ResourceListItem):
431
+ detail_widget = self.query_one("#resource-detail", ResourceDetail)
432
+ detail_widget.current_resource = event.item.change
433
+ return
434
+
435
+ resource_list = self.query_one("#resource-list", ResourceList)
436
+ self._sync_detail_from_list(resource_list, ensure_selection=True)
437
+
438
+ def action_toggle_filter(self) -> None:
439
+ """Toggle the filter input visibility."""
440
+ self.show_filter = not self.show_filter
441
+ filter_input = self.query_one("#filter-input", Input)
442
+ filter_input.toggle_class("hidden")
443
+ if self.show_filter:
444
+ filter_input.focus()
445
+ else:
446
+ resource_list = self.query_one("#resource-list", ResourceList)
447
+ resource_list.focus()
448
+
449
+ def action_activate_expression_filter(self) -> None:
450
+ """Open filter input and switch it to Python expression mode."""
451
+ if not self.show_filter:
452
+ self.show_filter = True
453
+ filter_input = self.query_one("#filter-input", Input)
454
+ filter_input.remove_class("hidden")
455
+ else:
456
+ filter_input = self.query_one("#filter-input", Input)
457
+
458
+ existing = filter_input.value.strip()
459
+ if not existing:
460
+ filter_input.value = "py: "
461
+ elif not existing.lower().startswith("py:"):
462
+ filter_input.value = f"py: {filter_input.value}"
463
+
464
+ try:
465
+ filter_input.cursor_position = len(filter_input.value)
466
+ except Exception:
467
+ pass
468
+
469
+ filter_input.focus()
470
+
471
+ def on_input_changed(self, event: Input.Changed) -> None:
472
+ """Handle filter input changes."""
473
+ if event.input.id == "filter-input":
474
+ self.search_query = event.value
475
+ self._apply_filters(ensure_selection=True)
476
+
477
+ def action_search(self) -> None:
478
+ """Activate search/filter mode."""
479
+ self.action_toggle_filter()
480
+
481
+ def _focus_action(self, action: str) -> None:
482
+ """Focus one action, toggling back to all when pressed again."""
483
+ self.enabled_actions = next_action_filter(self.enabled_actions, action)
484
+ self._apply_filters(ensure_selection=True)
485
+ if self.enabled_actions == {"create"}:
486
+ self.app.notify("Action filter: create only", timeout=1.5)
487
+ elif self.enabled_actions == {"update"}:
488
+ self.app.notify("Action filter: update only", timeout=1.5)
489
+ elif self.enabled_actions == {"delete"}:
490
+ self.app.notify("Action filter: delete only", timeout=1.5)
491
+ else:
492
+ self.app.notify("Action filter: all actions", timeout=1.5)
493
+
494
+ def action_filter_create(self) -> None:
495
+ """Show only create actions (press again to reset all)."""
496
+ self._focus_action("create")
497
+
498
+ def action_filter_update(self) -> None:
499
+ """Show only update actions (press again to reset all)."""
500
+ self._focus_action("update")
501
+
502
+ def action_filter_delete(self) -> None:
503
+ """Show only delete actions (press again to reset all)."""
504
+ self._focus_action("delete")
505
+
506
+ def _apply_filters(self, *, ensure_selection: bool) -> None:
507
+ """Apply current query/action filters to the resource list."""
508
+ stripped_query = self.search_query.strip()
509
+ query_mode = "expr" if stripped_query.lower().startswith("py:") else "text"
510
+ matcher, error, pending = build_query_matcher(self.search_query)
511
+ if pending:
512
+ matcher = self.last_matcher
513
+ error = None
514
+ else:
515
+ self.last_matcher = matcher
516
+
517
+ if error and error != self.search_error:
518
+ self.app.notify(error, severity="warning", timeout=2.5)
519
+ self.search_error = error or ""
520
+
521
+ filtered_changes = [change for change in self.all_changes if change.action in self.enabled_actions and matcher(change)]
522
+
523
+ resource_list = self.query_one("#resource-list", ResourceList)
524
+ resource_list.set_changes(filtered_changes)
525
+ if ensure_selection:
526
+ resource_list.index = 0 if filtered_changes else None
527
+
528
+ summary_widget = self.query_one(PlanSummary)
529
+ summary_widget.set_filters(
530
+ filtered_total=len(filtered_changes),
531
+ actions=self.enabled_actions,
532
+ query=stripped_query,
533
+ query_mode=query_mode,
534
+ query_pending=pending,
535
+ query_error=error or "",
536
+ )
537
+ self._sync_detail_from_list(resource_list, ensure_selection=ensure_selection)
538
+
539
+ async def action_refresh(self) -> None:
540
+ """Refresh plan data from source and rebuild visible list."""
541
+ app = self.app
542
+ if not isinstance(app, PlanViewerApp):
543
+ return
544
+ if app.reload_plan is None:
545
+ return
546
+
547
+ try:
548
+ refreshed_plan = await run_in_thread(app.reload_plan)
549
+ except Exception as exc:
550
+ app.notify(f"Refresh failed: {exc}", severity="error")
551
+ return
552
+
553
+ self.plan_data = refreshed_plan
554
+ self.all_changes = self._extract_all_changes()
555
+ summary_widget = self.query_one(PlanSummary)
556
+ summary_widget.summary = self.plan_data.get("summary", {})
557
+ self.search_query = self.query_one("#filter-input", Input).value or ""
558
+ self._apply_filters(ensure_selection=True)
559
+ app.plan_data = refreshed_plan
560
+ app.sub_title = f"Total changes: {refreshed_plan.get('summary', {}).get('total_changes', 0)}"
561
+ app.notify("Plan refreshed", timeout=1.5)
562
+
563
+ def action_help(self) -> None:
564
+ """Show help screen."""
565
+ self.app.push_screen(HelpScreen())
566
+
567
+
568
+ class HelpScreen(Screen):
569
+ """Help screen with keyboard shortcuts."""
570
+
571
+ BINDINGS: ClassVar[list[BindingType]] = [
572
+ Binding("escape", "pop_screen", "Back"),
573
+ Binding("q", "pop_screen", "Back"),
574
+ ]
575
+
576
+ def compose(self) -> ComposeResult:
577
+ """Compose the help screen."""
578
+ yield Header(show_clock=False)
579
+ with VerticalScroll():
580
+ yield Static(
581
+ """[bold]Plan Viewer Help[/bold]
582
+
583
+ [bold]Navigation:[/bold]
584
+ ↑/↓ Navigate resources
585
+ Enter Select resource
586
+ Tab Switch panels
587
+
588
+ [bold]Commands:[/bold]
589
+ q Quit
590
+ f or / Filter resources
591
+ r Refresh
592
+ F Expression filter mode (py:)
593
+ c/u/d Show create/update/delete only (press same key again to reset)
594
+ ? Show this help
595
+
596
+ [bold]Resource Symbols:[/bold]
597
+ [green]+[/green] Resource will be created
598
+ [yellow]~[/yellow] Resource will be updated
599
+ [red]-[/red] Resource will be deleted
600
+
601
+ [bold]Tips:[/bold]
602
+ • Use filter to quickly find specific resources
603
+ • Expression mode: py: stack == "main" and action == "update"
604
+ • Available fields: resource_id, action, resource_type, resource_name, description, stack
605
+ • Selected resources show details in the right panel
606
+ • Stack view shows changes grouped by stack
607
+ """,
608
+ id="help-text",
609
+ )
610
+ yield Footer()
611
+
612
+ def action_pop_screen(self) -> None:
613
+ """Return to the previous screen."""
614
+ self.app.pop_screen()
615
+
616
+
617
+ class PlanViewerApp(App):
618
+ """Main application for viewing infrastructure plans."""
619
+
620
+ BINDINGS: ClassVar[list[BindingType]] = [
621
+ Binding("ctrl+c", "quit", "Quit", priority=True),
622
+ ]
623
+
624
+ CSS = """
625
+ #main-container {
626
+ layout: horizontal;
627
+ height: 100%;
628
+ }
629
+
630
+ #main-layout {
631
+ width: 100%;
632
+ }
633
+
634
+ .panel {
635
+ border: solid $primary;
636
+ padding: 1;
637
+ margin: 0 1;
638
+ }
639
+
640
+ #left-panel {
641
+ width: 40%;
642
+ }
643
+
644
+ #right-panel {
645
+ width: 60%;
646
+ }
647
+
648
+ PlanSummary {
649
+ height: auto;
650
+ min-height: 12;
651
+ margin-bottom: 1;
652
+ border: solid $secondary;
653
+ padding: 1;
654
+ }
655
+
656
+ ResourceList {
657
+ height: 100%;
658
+ border: solid $secondary;
659
+ }
660
+
661
+ .resource-item {
662
+ padding: 0 1;
663
+ }
664
+
665
+ #filter-input {
666
+ margin-bottom: 1;
667
+ display: block;
668
+ }
669
+
670
+ #filter-input.hidden {
671
+ display: none;
672
+ }
673
+
674
+ ResourceDetail {
675
+ height: 100%;
676
+ }
677
+
678
+ #detail-tabs {
679
+ height: 100%;
680
+ }
681
+
682
+ #overview-content, #changes-content, #before-content, #after-content {
683
+ padding: 1;
684
+ overflow: auto;
685
+ }
686
+
687
+ #help-text {
688
+ padding: 2;
689
+ }
690
+ """
691
+
692
+ def __init__(
693
+ self,
694
+ plan_data: dict[str, Any],
695
+ *,
696
+ reload_plan: Callable[[], dict[str, Any]] | None = None,
697
+ ) -> None:
698
+ super().__init__()
699
+ self.plan_data = plan_data
700
+ self.reload_plan = reload_plan
701
+ self.title = "NF Plan Viewer"
702
+ self.sub_title = f"Total changes: {plan_data.get('summary', {}).get('total_changes', 0)}"
703
+
704
+ def on_mount(self) -> None:
705
+ """Set up the app when mounted."""
706
+ self.push_screen(PlanViewerScreen(self.plan_data))
707
+
708
+
709
+ if __name__ == "__main__":
710
+ # Test mode - load plan from command line argument
711
+ import sys
712
+
713
+ if len(sys.argv) > 1:
714
+ with pathlib.Path(sys.argv[1]).open() as f:
715
+ plan_data = json.load(f)
716
+ else:
717
+ # Use minimal test data
718
+ plan_data = {
719
+ "summary": {
720
+ "total_changes": 1,
721
+ "creates": 1,
722
+ "updates": 0,
723
+ "deletes": 0,
724
+ },
725
+ "changes": [
726
+ {
727
+ "resource_id": "test.example_resource.demo",
728
+ "resource_type": "example_resource",
729
+ "resource_name": "demo",
730
+ "action": "create",
731
+ "description": "+ example_resource.demo",
732
+ "attribute_changes": [],
733
+ "before_state": None,
734
+ "after_state": {
735
+ "type": "example_resource",
736
+ "id": "demo",
737
+ "provider": "example",
738
+ "attributes": {"name": "demo", "value": 42},
739
+ },
740
+ },
741
+ ],
742
+ }
743
+
744
+ app = PlanViewerApp(plan_data)
745
+ app.run()