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,439 @@
1
+ """Graph-backed ``nf state`` recovery, history, checkpoints, baselines, query and migration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ import json
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ import click
11
+ from netherframe.cli.ui import console
12
+
13
+ if TYPE_CHECKING:
14
+ from netherframe.core.execution.hybrid import HybridExecutionMode
15
+
16
+ #: The ``nf state`` subcommands this module handles
17
+ GRAPH_STATE_COMMANDS = ("recover", "operations", "history", "retention", "query", "migrate", "onboard", "baseline", "checkpoint", "import")
18
+
19
+
20
+ @click.group()
21
+ def graph_state_commands() -> None:
22
+ """Graph state backend commands (run through ``nf state``)."""
23
+
24
+
25
+ def _hybrid() -> HybridExecutionMode:
26
+ return click.get_current_context().obj["hybrid"]
27
+
28
+
29
+ @graph_state_commands.command("import")
30
+ @click.argument("address")
31
+ @click.argument("import_id", required=False)
32
+ @click.option("--identity", "identity_json", help="The provider's resource identity as a JSON object, instead of an import ID")
33
+ @click.option("--auto-approve", is_flag=True, help="Approve the import without an interactive prompt")
34
+ def import_entry(address: str, import_id: str | None, identity_json: str | None, auto_approve: bool) -> None:
35
+ """Track an existing object at its declared ADDRESS; infrastructure is unchanged."""
36
+ if (import_id is None) == (identity_json is None):
37
+ raise click.UsageError("Give an import ID or --identity JSON")
38
+ if identity_json is not None:
39
+ try:
40
+ identity = json.loads(identity_json)
41
+ except ValueError as exc:
42
+ raise click.BadParameter("Expected a JSON identity object", param_hint="--identity") from exc
43
+ if not isinstance(identity, dict) or not identity:
44
+ raise click.BadParameter("Expected a non-empty JSON identity object", param_hint="--identity")
45
+ selector = {"identity": identity}
46
+ else:
47
+ selector = {"import_id": import_id}
48
+ hybrid = _hybrid()
49
+ hybrid.graph_state_engine() # Refuse document backends before invoking the import API.
50
+ result = hybrid.import_resources([{"address": address, **selector}], auto_approve=auto_approve)
51
+ for key in result["imported"]:
52
+ console.print(f"Imported {key}. A reviewed apply is needed to reconcile its configuration.", markup=False)
53
+ for key, error in result["failed"].items():
54
+ console.print(f"{key}: {error}", markup=False)
55
+ if not result["success"]:
56
+ raise click.exceptions.Exit(1)
57
+
58
+
59
+ @graph_state_commands.command("rm")
60
+ @click.argument("addresses", nargs=-1, required=True)
61
+ def forget_entries(addresses: tuple[str, ...]) -> None:
62
+ """Forget resources/outputs without deleting infrastructure; include their consumers."""
63
+ removed = _hybrid().graph_state_engine().edit_resources("forget", addresses)
64
+ for key in removed:
65
+ console.print(f"Removed {key} from state.", markup=False)
66
+ console.print("Infrastructure was unchanged.")
67
+
68
+
69
+ @graph_state_commands.command("mv")
70
+ @click.argument("source")
71
+ @click.argument("target")
72
+ @click.option("--auto-approve", is_flag=True, help="Approve the state move without an interactive prompt")
73
+ def move_entry(source: str, target: str, auto_approve: bool) -> None:
74
+ """Move SOURCE to TARGET and rewrite consumers atomically; infrastructure is unchanged."""
75
+ hybrid = _hybrid()
76
+ hybrid.graph_state_engine()
77
+ result = hybrid.move_resources([{"from": source, "to": target}], auto_approve=auto_approve)
78
+ for before, after in result["moved"].items():
79
+ console.print(f"Moved {before} to {after}. A reviewed apply is needed to reconcile its configuration.", markup=False)
80
+ for key, error in result["failed"].items():
81
+ console.print(f"{key}: {error}", markup=False)
82
+ if not result["success"]:
83
+ raise click.exceptions.Exit(1)
84
+
85
+
86
+ @graph_state_commands.group("checkpoint")
87
+ def checkpoint_commands() -> None:
88
+ """Inspect and restore retained pre-apply history checkpoints."""
89
+
90
+
91
+ @checkpoint_commands.command("list")
92
+ def list_checkpoints() -> None:
93
+ """List references, origins and target counts without exposing state values."""
94
+ records = _hybrid().graph_state_engine().backend_graph.history_checkpoints()
95
+ if not records:
96
+ console.print("No retained checkpoints.")
97
+ for record in records:
98
+ console.print(f"{record.location} {record.name} sequence {record.sequence}, run {record.run_id}, {len(record.targets)} targets", markup=False)
99
+
100
+
101
+ @checkpoint_commands.command("show")
102
+ @click.argument("reference")
103
+ def show_checkpoint(reference: str) -> None:
104
+ """Show a checkpoint's targets and current restore conflicts; values stay private."""
105
+ preview = _hybrid().graph_state_engine().backend_graph.prepare_history_restore(reference)
106
+ record = preview.checkpoint
107
+ console.print(f"{record.location} {record.name}\nOrigin: sequence {record.sequence}, run {record.run_id}", markup=False)
108
+ for target in record.targets:
109
+ console.print(f" {target.kind} {target.key}: revision {target.revision}", markup=False)
110
+ if preview.blockers:
111
+ console.print("Restore conflicts:")
112
+ for blocker in preview.blockers:
113
+ console.print(f" {blocker}", markup=False)
114
+ else:
115
+ console.print("No later writers or consumers found. Restore rechecks conflicts under its grant.")
116
+
117
+
118
+ @checkpoint_commands.command("restore")
119
+ @click.argument("reference")
120
+ @click.option("--force", is_flag=True, help="Permit overwriting later writers or consumed values; ownership, history and lease checks still apply")
121
+ def restore_checkpoint(reference: str, force: bool) -> None:
122
+ """Restore only the checkpoint's targets as fresh revisions. Infrastructure is unchanged."""
123
+ sequence = _hybrid().graph_state_engine().restore_history_checkpoint(reference, force=force)
124
+ console.print(f"Restored checkpoint targets at sequence {sequence}. Infrastructure was unchanged.")
125
+
126
+
127
+ @graph_state_commands.group("baseline")
128
+ def baseline_commands() -> None:
129
+ """Pin the deployed state a branch is based on and manage its nf.baseline reference."""
130
+
131
+
132
+ @baseline_commands.command("pin")
133
+ @click.option("--at", help="Commit sequence or run ID (default: the current committed frontier)")
134
+ @click.option("--file", "path", type=click.Path(dir_okay=False, path_type=Path), default=Path("nf.baseline"), show_default=True)
135
+ def pin_baseline(at: str | None, path: Path) -> None:
136
+ """Pin a frontier against retention and save it with the branch. Earlier pins stay valid for other branches."""
137
+ from netherframe.core.backends.graph_baseline import GraphBaseline
138
+
139
+ backend = _hybrid().graph_state_engine().backend_graph
140
+ if path.exists():
141
+ previous = GraphBaseline.read(path)
142
+ previous.check_scope(backend.get_backend_type(), str(backend.get_config().get("state_id", "")), backend.snapshot().lineage)
143
+ selector: dict[str, Any] = {}
144
+ if at is not None:
145
+ selector = {"sequence": int(at)} if at.isdigit() else {"run_id": at}
146
+ baseline = backend.pin_baseline(**selector)
147
+ try:
148
+ baseline.write(path)
149
+ except OSError:
150
+ backend.unpin_baseline(baseline.pin_id)
151
+ raise
152
+ console.print(f"Pinned sequence {baseline.sequence} of {baseline.state_id} in {path} (pin {baseline.pin_id}).")
153
+
154
+
155
+ @baseline_commands.command("show")
156
+ @click.option("--file", "path", type=click.Path(exists=True, dir_okay=False, path_type=Path), default=Path("nf.baseline"), show_default=True)
157
+ def show_baseline(path: Path) -> None:
158
+ """Validate and show the branch's pinned origin."""
159
+ from netherframe.core.backends.graph_baseline import GraphBaseline
160
+
161
+ baseline = GraphBaseline.read(path)
162
+ records = _hybrid().graph_state_engine().backend_graph.baseline_intents(baseline)
163
+ console.print(f"{baseline.backend_type} {baseline.state_id}: sequence {baseline.sequence}, lineage {baseline.lineage}, pin {baseline.pin_id} ({len(records)} entries).")
164
+
165
+
166
+ @baseline_commands.command("unpin")
167
+ @click.argument("pin_id")
168
+ def unpin_baseline(pin_id: str) -> None:
169
+ """Release a pin when no branch or saved plan needs it; later history cleanup may prune its origin."""
170
+ if not _hybrid().graph_state_engine().backend_graph.unpin_baseline(pin_id):
171
+ raise click.ClickException(f"Baseline pin {pin_id} does not exist in this state")
172
+ console.print(f"Released baseline pin {pin_id}.")
173
+
174
+
175
+ @graph_state_commands.command("recover")
176
+ @click.argument("op_id", required=False)
177
+ @click.option("--confirm-terminated", is_flag=True, help="Confirm a dispatched operation's call ended (its process and provider are gone and it can no longer take effect)")
178
+ @click.option("--import-id", help="Recover a create whose object cannot be found by its configuration by importing this ID")
179
+ def recover(op_id: str | None, confirm_terminated: bool, import_id: str | None) -> None:
180
+ """Resolve unresolved operations (all, or OP_ID) after a run crashed or lost its lease."""
181
+ outcomes = _hybrid().recover_operations(op_id, confirm_terminated=confirm_terminated, import_id=import_id)
182
+ if not outcomes:
183
+ console.print("No unresolved operations.")
184
+ return
185
+ for outcome in outcomes:
186
+ colour = {"committed": "green", "aborted": "green", "skipped": "yellow"}.get(outcome.resolution, "red")
187
+ console.print(f"[{colour}]{outcome.resolution}[/{colour}] {outcome.op_id} {outcome.action} {outcome.address} ({outcome.stage}): {outcome.detail}")
188
+ if any(outcome.resolution == "quarantined" for outcome in outcomes):
189
+ raise click.exceptions.Exit(1)
190
+
191
+
192
+ @graph_state_commands.command("operations")
193
+ @click.option("--all", "show_all", is_flag=True, help="Include committed and aborted operations")
194
+ def operations(show_all: bool) -> None:
195
+ """List operations (by default the unresolved ones, which hold their addresses)."""
196
+ records = _hybrid().graph_state_engine().backend_graph.operations(unresolved=not show_all)
197
+ if not records:
198
+ console.print("No unresolved operations." if not show_all else "No operations.")
199
+ return
200
+ for record in records:
201
+ live = "live" if record.owner_live else (record.owner_status or "unknown")
202
+ console.print(f"{record.op_id} {record.action:<8} {record.stage:<18} {record.address} run {record.run_id} ({live}, attempt {record.attempt})" + (f" {record.outcome}" if record.outcome else ""))
203
+
204
+
205
+ @graph_state_commands.command("history")
206
+ @click.argument("address", required=False)
207
+ @click.option("--limit", type=click.IntRange(1, 1000), default=50, show_default=True, help="Most recent versions to show per page")
208
+ @click.option("--run", "run_id", help="Only versions committed by this run")
209
+ @click.option("--since", type=click.IntRange(min=0), default=0, help="Only versions at or after this commit sequence")
210
+ @click.option("--cursor", help="Continue the same query at its original frontier")
211
+ @click.option("--values", is_flag=True, help="Include attributes and output values with sensitive fields masked")
212
+ @click.option("--json", "json_output", is_flag=True, help="Print a machine-readable page, including its next cursor")
213
+ def history(address: str | None, limit: int, run_id: str | None, since: int, cursor: str | None, values: bool, json_output: bool) -> None:
214
+ """Show committed versions, newest first, with actor, run, baseline, intent and operation."""
215
+ from netherframe.core.backends.graph_history import public_record
216
+
217
+ page = _hybrid().graph_state_engine().backend_graph.history_page(address, run_id=run_id, since=since, limit=limit, cursor=cursor)
218
+ if json_output:
219
+ click.echo(json.dumps(page.to_dict(values=values)))
220
+ return
221
+ records = page.records
222
+ if not records:
223
+ console.print("No history.")
224
+ return
225
+ for record in records:
226
+ when = datetime.fromtimestamp(record.committed_at, tz=UTC).isoformat(timespec="seconds")
227
+ change = "deleted" if record.tombstone else f"revision {record.revision}"
228
+ by = f"{record.operation or 'run'} {record.run_id}" + (f" by {record.actor}" if record.actor else "")
229
+ console.print(f"#{record.sequence} {when} {record.kind} {record.key} {change}, {record.status} ({by}" + (f", operation {record.op_id}" if record.op_id else "") + ")", markup=False)
230
+ origin = f"#{record.baseline.sequence} (pin {record.baseline.pin_id})" if record.baseline else "unrecorded"
231
+ console.print(f" baseline {origin}; intent {record.intent_fp or 'unrecorded'}", markup=False)
232
+ if values:
233
+ console.print(" value: " + json.dumps(public_record(record, values=True)["value"]), markup=False)
234
+ if page.next_cursor:
235
+ click.echo(f"Next cursor: {page.next_cursor}")
236
+
237
+
238
+ @graph_state_commands.group("retention")
239
+ def retention_commands() -> None:
240
+ """Inspect and prune retained evidence, preserving current state, pins and recovery."""
241
+
242
+
243
+ def _retention_summary(report: Any) -> None:
244
+ cutoff = datetime.fromtimestamp(report.cutoff, tz=UTC).isoformat(timespec="seconds")
245
+ console.print(f"Keep at least {report.days} days; eligible evidence is older than {cutoff}.", markup=False)
246
+ for label, count in (("Versions", report.versions), ("Operations", report.operations), ("Checkpoints", report.checkpoints)):
247
+ console.print(f"{label}: {count.total} retained, {count.eligible} eligible for pruning.", markup=False)
248
+ console.print(f"Baseline pins: {report.baseline_pins}. History generation: {report.history_epoch}.", markup=False)
249
+ if report.pruned_before:
250
+ console.print(f"Unpinned snapshots through sequence {report.pruned_before} may be incomplete; retained pins remain available.", markup=False)
251
+
252
+
253
+ @retention_commands.command("show")
254
+ @click.option("--keep-days", type=click.IntRange(min=1), help="Preview a one-time policy instead of the configured retention")
255
+ @click.option("--json", "json_output", is_flag=True)
256
+ def show_retention(keep_days: int | None, json_output: bool) -> None:
257
+ """Preview eligible counts without deleting evidence or holding an apply grant."""
258
+ report = _hybrid().graph_state_engine().backend_graph.preview_history_retention(days=keep_days)
259
+ if json_output:
260
+ click.echo(json.dumps(report.to_dict()))
261
+ else:
262
+ _retention_summary(report)
263
+
264
+
265
+ @retention_commands.command("prune")
266
+ @click.option("--keep-days", type=click.IntRange(min=1), help="Use a one-time retention policy; configuration stays unchanged")
267
+ @click.option("--auto-approve", is_flag=True, help="Approve pruning without an interactive prompt")
268
+ @click.option("--json", "json_output", is_flag=True)
269
+ def prune_retention(keep_days: int | None, auto_approve: bool, json_output: bool) -> None:
270
+ """Prune old evidence after rechecking current pins. Current state is retained."""
271
+ from netherframe.core.execution.approval import ApprovalRequest
272
+
273
+ if json_output and not auto_approve:
274
+ raise click.UsageError("JSON pruning requires --auto-approve")
275
+ hybrid = _hybrid()
276
+ backend = hybrid.graph_state_engine().backend_graph
277
+ preview = backend.preview_history_retention(days=keep_days)
278
+ eligible = sum(count.eligible for count in (preview.versions, preview.operations, preview.checkpoints))
279
+ if not json_output:
280
+ _retention_summary(preview)
281
+ if (
282
+ eligible
283
+ and not auto_approve
284
+ and not hybrid._request_approval(
285
+ ApprovalRequest(
286
+ operation="prune-history",
287
+ title="History Retention",
288
+ details=[f"Prune eligible evidence older than the displayed cutoff, keeping at least {preview.days} days.", "Pins and recovery protections are rechecked; eligible counts may change."],
289
+ question="Prune this history?",
290
+ )
291
+ )
292
+ ):
293
+ raise click.exceptions.Exit(1)
294
+ report = backend.prune_history(preview)
295
+ if json_output:
296
+ click.echo(json.dumps(report.to_dict()))
297
+ else:
298
+ console.print(f"Pruned {report.versions.eligible} versions, {report.operations.eligible} operations and {report.checkpoints.eligible} checkpoints. Current state is retained.", markup=False)
299
+
300
+
301
+ def parse_at(value: str) -> dict[str, Any]:
302
+ """``--at``: a commit sequence (an integer), a time (ISO 8601), else a run id."""
303
+ if value.isdigit():
304
+ return {"sequence": int(value)}
305
+ try:
306
+ return {"time": datetime.fromisoformat(value).timestamp()}
307
+ except ValueError:
308
+ return {"run_id": value}
309
+
310
+
311
+ def show_at(hybrid: HybridExecutionMode, at: str) -> None:
312
+ """Print the app's state as it was at a sequence, the end of a run, or a time (sensitive values masked)."""
313
+ state = hybrid.graph_state_engine().backend_graph.state_at(**parse_at(at))
314
+ console.print(f"State at sequence {state.serial}: {len(state.resources)} resources, {len(state.outputs)} outputs")
315
+ for key in sorted(state.resources):
316
+ console.print(f" {key}", markup=False)
317
+ for key in sorted(state.outputs):
318
+ output = state.outputs[key]
319
+ value = "(sensitive)" if isinstance(output, dict) and output.get("sensitive") else (output.get("value") if isinstance(output, dict) else output)
320
+ console.print(f" {key} = {value}")
321
+
322
+
323
+ @graph_state_commands.command("query")
324
+ @click.argument("sql")
325
+ @click.option("--timeout", default=30.0, show_default=True, help="Statement timeout in seconds")
326
+ def query(sql: str, timeout: float) -> None:
327
+ """Run read-only SQL over state, history, operations and state_transfers views; sensitive values are masked."""
328
+ from rich.table import Table
329
+
330
+ columns, rows = _hybrid().graph_state_engine().backend_graph.query(sql, timeout=timeout)
331
+ table = Table(*columns)
332
+ for row in rows:
333
+ table.add_row(*(str(value) for value in row))
334
+ console.print(table)
335
+
336
+
337
+ @graph_state_commands.command("migrate")
338
+ @click.option("--to", "target", type=click.Choice(["graph", "document"]), required=True, help="Where state goes: the app's graph backend, or a document state file")
339
+ @click.option("--source", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="--to graph: the document state file to migrate from")
340
+ @click.option("--path", "target_path", type=click.Path(dir_okay=False, path_type=Path), help="--to document: the state file to write")
341
+ def migrate(target: str, source: Path | None, target_path: Path | None) -> None:
342
+ """Move state between a document state file and the app's graph backend, as a migrate run; the old state is marked migrated."""
343
+ from netherframe.core.backends.local_backend import LocalStateBackend
344
+ from netherframe.core.execution.hybrid_graph_state import migrate_document_to_graph, migrate_graph_to_document
345
+
346
+ hybrid = _hybrid()
347
+ engine = hybrid.graph_state_engine()
348
+ if target == "graph":
349
+ from netherframe.core.backends.state_backend import StateBackend
350
+
351
+ configured = getattr(hybrid, "migration_source", None)
352
+ if source is None and isinstance(configured, StateBackend):
353
+ moved = migrate_document_to_graph(configured, engine.backend_graph)
354
+ console.print(f"Migrated {moved} entries from the configured document backend.")
355
+ return
356
+ if source is None:
357
+ candidate = Path(hybrid.outdir or ".nf.out") / "nf.tfstate"
358
+ if candidate.exists():
359
+ source = candidate
360
+ else:
361
+ raise click.UsageError("--to graph needs --source or a retained configured document backend; nf state onboard uses the app's current backend")
362
+ moved = migrate_document_to_graph(LocalStateBackend(source), engine.backend_graph)
363
+ console.print(f"[green]Migrated {moved} entries from {source} to the graph state backend; {source} is marked migrated.[/green]")
364
+ return
365
+ if target_path is None:
366
+ raise click.UsageError("--to document needs --path, the state file to write")
367
+ moved = migrate_graph_to_document(engine.backend_graph, LocalStateBackend(target_path))
368
+ console.print(f"[green]Migrated {moved} entries to {target_path}; the graph state is marked migrated.[/green]")
369
+
370
+
371
+ @graph_state_commands.command("onboard")
372
+ @click.option("--graph", "configuration", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Graph backend JSON, with type and config fields")
373
+ @click.option("--local", is_flag=True, help="Create or reuse a durable local PostgreSQL Docker container")
374
+ @click.option("--auto-approve", is_flag=True, help="Approve the reconciliation plan without a prompt")
375
+ @click.option("--baseline-file", type=click.Path(dir_okay=False, path_type=Path), default=Path("nf.baseline"), show_default=True)
376
+ def onboard(configuration: Path | None, local: bool, auto_approve: bool, baseline_file: Path) -> None:
377
+ """Migrate the configured backend, reconcile identity/intent, and pin a baseline.
378
+
379
+ The routing receipt is written before the handoff; rerunning resumes it.
380
+ Reconciliation shows a normal plan and never silently approves provider changes.
381
+ """
382
+ from netherframe.cli.services.graph_onboarding import graph_backend, local_graph_specification, read_routes, write_route
383
+ from netherframe.core.backends.graph_state import GraphStateBackend
384
+ from netherframe.core.execution.hybrid import HybridExecutionMode
385
+ from netherframe.core.execution.graph_state_migration import migrate_document_to_graph
386
+ from .hybrid import cli_approval, cli_progress, print_result_errors
387
+
388
+ original = _hybrid()
389
+ app_name = getattr(original, "project_app", None) or str(original.app.nf_id)
390
+ existing = read_routes()["apps"].get(app_name)
391
+ if configuration is not None and local:
392
+ raise click.UsageError("Choose --graph FILE or --local")
393
+ if configuration is not None:
394
+ specification = json.loads(configuration.read_text())
395
+ elif local:
396
+ specification = local_graph_specification(app_name)
397
+ elif existing is not None:
398
+ specification = existing["backend"]
399
+ else:
400
+ raise click.UsageError("Give --graph FILE or --local for the first onboarding run")
401
+ source = original.migration_source if isinstance(original.state_backend, GraphStateBackend) else original.state_backend
402
+ if source is None or isinstance(source, GraphStateBackend):
403
+ raise click.ClickException("Onboarding needs the app's configured document backend; keep it configured until the handoff completes")
404
+ target = graph_backend(specification)
405
+ try:
406
+ if existing is not None and existing["backend"] != specification:
407
+ raise click.ClickException("A graph handoff already exists for this app; resume its original destination")
408
+ write_route(app_name, specification, source, pending=True)
409
+ moved = migrate_document_to_graph(source, target)
410
+ write_route(app_name, specification, source, pending=False)
411
+ console.print(f"Migrated {moved} entries. Reviewing configuration and canonical ownership before pinning.")
412
+ mode = HybridExecutionMode(original.app, state_backend=target, outdir=original.outdir, migration_source=source)
413
+ mode.approval = cli_approval
414
+ mode._progress_callback = cli_progress
415
+ result = mode.apply(auto_approve=auto_approve)
416
+ if not result.success or not result.complete:
417
+ print_result_errors(result)
418
+ raise click.ClickException("Onboarding reconciliation is incomplete; state is retained in graph storage. Rerun nf state onboard to resume.")
419
+ baseline = target.pin_baseline()
420
+ try:
421
+ if baseline_file.exists():
422
+ from netherframe.core.backends.graph_baseline import GraphBaseline
423
+
424
+ GraphBaseline.read(baseline_file).check_scope(baseline.backend_type, baseline.state_id, baseline.lineage)
425
+ baseline.write(baseline_file)
426
+ except BaseException:
427
+ target.unpin_baseline(baseline.pin_id)
428
+ raise
429
+ console.print(f"Graph onboarding complete: {moved} migrated entries; baseline sequence {baseline.sequence} in {baseline_file}.")
430
+ finally:
431
+ if callable(close := getattr(target, "close", None)):
432
+ close()
433
+
434
+
435
+ def run_graph_state_command(hybrid: HybridExecutionMode, args: tuple[str, ...]) -> None:
436
+ """Run one of ``GRAPH_STATE_COMMANDS`` with its arguments against ``hybrid``'s graph state."""
437
+ code = graph_state_commands.main(list(args), prog_name="nf state", standalone_mode=False, obj={"hybrid": hybrid})
438
+ if isinstance(code, int) and code:
439
+ raise click.exceptions.Exit(code)