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,144 @@
1
+ """Durable project routing for a resumable document-to-graph handoff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import fcntl
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import secrets
11
+ import subprocess
12
+ import time
13
+
14
+ import click
15
+
16
+ from netherframe.core.backends.graph_migration import storage_identity
17
+ from netherframe.core.backends.graph_state import GraphStateBackend
18
+ from netherframe.core.execution.hybrid import HybridExecutionMode
19
+
20
+
21
+ def route_path() -> Path:
22
+ return Path(".nf.out") / "graph-backends.json"
23
+
24
+
25
+ def read_routes() -> dict:
26
+ path = route_path()
27
+ if not path.exists():
28
+ return {"version": 1, "apps": {}}
29
+ data = json.loads(path.read_text())
30
+ if data.get("version") != 1 or not isinstance(data.get("apps"), dict):
31
+ raise click.ClickException(f"Invalid graph backend routing in {path}")
32
+ return data
33
+
34
+
35
+ def write_route(app_name: str, specification: dict, source, *, pending: bool) -> None:
36
+ path = route_path()
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ with path.with_suffix(".lock").open("a+") as lock:
39
+ fcntl.flock(lock, fcntl.LOCK_EX)
40
+ _write_route_locked(app_name, specification, source, pending=pending)
41
+
42
+
43
+ def _write_route_locked(app_name, specification, source, *, pending):
44
+ data = read_routes()
45
+ data["apps"][app_name] = {"backend": specification, "source": storage_identity(source), "pending": pending}
46
+ path = route_path()
47
+ path.parent.mkdir(parents=True, exist_ok=True)
48
+ temporary = path.with_name(path.name + f".{secrets.token_hex(8)}.tmp")
49
+ try:
50
+ with temporary.open("x") as stream:
51
+ os.chmod(temporary, 0o600)
52
+ json.dump(data, stream, indent=2)
53
+ stream.flush()
54
+ os.fsync(stream.fileno())
55
+ temporary.replace(path)
56
+ descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
57
+ try:
58
+ os.fsync(descriptor)
59
+ finally:
60
+ os.close(descriptor)
61
+ finally:
62
+ temporary.unlink(missing_ok=True)
63
+
64
+
65
+ def graph_backend(specification: dict) -> GraphStateBackend:
66
+ if not isinstance(specification, dict) or specification.get("type") != "postgresql-graph" or not isinstance(specification.get("config"), dict):
67
+ raise click.ClickException('Graph config must contain {"type": "postgresql-graph", "config": {...}}')
68
+ config = specification["config"]
69
+ if "password" in config or "password_source" in config:
70
+ raise click.ClickException("Graph config must use password_env or password_file, never a literal password")
71
+ try:
72
+ from netherframe.backends.postgresql import PostgreSQLGraphBackend
73
+ except ImportError as exc:
74
+ raise click.ClickException("Install netherframe.backends.postgresql to use graph state") from exc
75
+ return PostgreSQLGraphBackend(**config)
76
+
77
+
78
+ def attach_route(execution, app_name: str):
79
+ execution.__dict__["project_app"] = app_name
80
+ record = read_routes()["apps"].get(app_name)
81
+ if record is None:
82
+ return execution
83
+ if isinstance(execution.state_backend, GraphStateBackend):
84
+ if execution.state_backend.state_identity() != graph_backend(record["backend"]).state_identity():
85
+ raise click.ClickException("The app's graph backend disagrees with its project onboarding route")
86
+ return execution
87
+ source = execution.state_backend
88
+ if record["source"] != storage_identity(source):
89
+ raise click.ClickException("The configured document backend changed after graph onboarding; review the graph route before proceeding")
90
+ result = HybridExecutionMode(execution.app, state_backend=graph_backend(record["backend"]), outdir=execution.outdir, migration_source=source)
91
+ result.app._hybrid_execution = result
92
+ result.__dict__["project_app"] = app_name
93
+ return result
94
+
95
+
96
+ def local_graph_specification(app_name: str) -> dict:
97
+ """A durable local PostgreSQL container; credentials stay in a private file."""
98
+ identity = hashlib.sha256(f"{Path.cwd().resolve()}:{app_name}".encode()).hexdigest()[:12]
99
+ name = f"nf-graph-{identity}"
100
+ password = (Path(".nf.out") / "local-graph" / f"{identity}.password").resolve()
101
+ password.parent.mkdir(parents=True, exist_ok=True)
102
+ if not password.exists():
103
+ descriptor = os.open(password, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
104
+ with os.fdopen(descriptor, "w") as stream:
105
+ stream.write(secrets.token_urlsafe(32))
106
+ found = subprocess.run(["docker", "inspect", name], capture_output=True, text=True)
107
+ if found.returncode:
108
+ subprocess.run(
109
+ [
110
+ "docker",
111
+ "run",
112
+ "--detach",
113
+ "--name",
114
+ name,
115
+ "--publish",
116
+ "127.0.0.1::5432",
117
+ "--mount",
118
+ f"type=volume,source={name},target=/var/lib/postgresql/data",
119
+ "--mount",
120
+ f"type=bind,source={password},target=/run/secrets/password,readonly",
121
+ "--env",
122
+ "POSTGRES_USER=nf",
123
+ "--env",
124
+ "POSTGRES_DB=nf",
125
+ "--env",
126
+ "POSTGRES_PASSWORD_FILE=/run/secrets/password",
127
+ "postgres:16-alpine",
128
+ ],
129
+ check=True,
130
+ capture_output=True,
131
+ text=True,
132
+ )
133
+ else:
134
+ state = json.loads(found.stdout)[0]
135
+ if not state["State"]["Running"]:
136
+ subprocess.run(["docker", "start", name], check=True, capture_output=True, text=True)
137
+ end = time.monotonic() + 30
138
+ while subprocess.run(["docker", "exec", name, "pg_isready", "-U", "nf"], capture_output=True).returncode:
139
+ if time.monotonic() >= end:
140
+ raise click.ClickException(f"Local graph database {name} did not become ready")
141
+ time.sleep(0.2)
142
+ details = json.loads(subprocess.run(["docker", "inspect", name], check=True, capture_output=True, text=True).stdout)[0]
143
+ port = int(details["NetworkSettings"]["Ports"]["5432/tcp"][0]["HostPort"])
144
+ return {"type": "postgresql-graph", "config": {"host": "127.0.0.1", "port": port, "database": "nf", "username": "nf", "password_file": str(password), "state_id": app_name}}
@@ -0,0 +1,51 @@
1
+ """Legacy Terraform/OpenTofu subprocess helpers for CLI commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from typing import TYPE_CHECKING
7
+
8
+ from netherframe.cli.ui import console
9
+ from netherframe.core.config import get_legacy_binary
10
+
11
+ if TYPE_CHECKING:
12
+ from pathlib import Path
13
+
14
+
15
+ def run_legacy_cli_command(
16
+ stack_dir: Path,
17
+ legacy_args: list[str],
18
+ *,
19
+ auto_approve: bool = False,
20
+ legacy_bin: str | None = None,
21
+ ) -> int:
22
+ """Run a legacy CLI command in the specified stack directory."""
23
+ resolved_legacy_bin = get_legacy_binary(app_value=legacy_bin)
24
+ try:
25
+ subprocess.run(
26
+ [resolved_legacy_bin, "--version"],
27
+ capture_output=True,
28
+ check=True,
29
+ )
30
+ except subprocess.CalledProcessError, FileNotFoundError:
31
+ console.print(
32
+ "[bold red]Legacy CLI binary is not installed or not available in PATH.[/bold red]",
33
+ )
34
+ console.print(
35
+ "Set NF_LEGACY_BINARY to the correct path or install a compatible binary.",
36
+ )
37
+ return 1
38
+
39
+ if auto_approve and legacy_args and legacy_args[0] in ["apply", "destroy"]:
40
+ legacy_args = legacy_args + ["-auto-approve"]
41
+
42
+ cmd = [resolved_legacy_bin] + legacy_args
43
+ console.print(f"[bold blue]Running:[/bold blue] {' '.join(cmd)}")
44
+ console.print(f"[bold blue]Working directory:[/bold blue] {stack_dir}")
45
+
46
+ try:
47
+ result = subprocess.run(cmd, cwd=stack_dir, check=False)
48
+ return result.returncode
49
+ except KeyboardInterrupt:
50
+ console.print("\n[bold yellow]Command interrupted by user[/bold yellow]")
51
+ return 130
@@ -0,0 +1,107 @@
1
+ """Shared [tool.nf] project configuration helpers for the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import click
8
+
9
+ from netherframe.core.config import find_pyproject_toml, get_cached_tool_nf_config
10
+ from netherframe.cli.ui import console
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class NFProjectConfig:
15
+ """Parsed [tool.nf] configuration."""
16
+
17
+ legacy_apps: dict[str, str]
18
+ hybrid_apps: dict[str, str]
19
+ python_cmd: list[str]
20
+ example_scripts: list[str]
21
+
22
+
23
+ def _build_app_dict(apps_config: list[str]) -> dict[str, str]:
24
+ """Convert app specs into CLI selector keys."""
25
+ app_dict: dict[str, str] = {}
26
+ name_counts: dict[str, int] = {}
27
+
28
+ for app_spec in apps_config:
29
+ if ":" not in app_spec:
30
+ console.print(f"[bold red]Invalid app specification: {app_spec}[/bold red]")
31
+ console.print("App specifications must be in format 'module.path:app_name'")
32
+ raise click.ClickException(f"Invalid app specification: {app_spec}")
33
+
34
+ module_path, app_name = app_spec.rsplit(":", 1)
35
+ name_counts[app_name] = name_counts.get(app_name, 0) + 1
36
+
37
+ for app_spec in apps_config:
38
+ module_path, app_name = app_spec.rsplit(":", 1)
39
+
40
+ if name_counts[app_name] > 1:
41
+ module_parts = module_path.split(".")
42
+ if module_parts[0] == "examples" and len(module_parts) > 1:
43
+ key = f"{module_parts[1]}:{app_name}"
44
+ else:
45
+ key = f"{module_parts[-1]}:{app_name}"
46
+ else:
47
+ key = app_name
48
+
49
+ app_dict[key] = app_spec
50
+
51
+ return app_dict
52
+
53
+
54
+ def load_project_config(*, allow_empty_apps: bool = False) -> NFProjectConfig:
55
+ """Load and parse [tool.nf] configuration from pyproject.toml."""
56
+ pyproject_path = find_pyproject_toml()
57
+ if not pyproject_path:
58
+ console.print("[bold red]pyproject.toml not found.[/bold red]")
59
+ console.print(
60
+ "Make sure you're in a directory containing pyproject.toml with [tool.nf] configuration.",
61
+ )
62
+ raise click.ClickException("pyproject.toml not found")
63
+
64
+ try:
65
+ nf_config = get_cached_tool_nf_config(pyproject_path)
66
+ except Exception as exc:
67
+ console.print(f"[bold red]Error reading pyproject.toml: {exc}[/bold red]")
68
+ raise click.ClickException(f"Error reading pyproject.toml: {exc}") from exc
69
+
70
+ legacy_apps_config = nf_config.get("legacy_apps", [])
71
+ hybrid_apps_config = nf_config.get("hybrid_apps", [])
72
+ example_scripts = nf_config.get("example_scripts", [])
73
+ python_cmd = nf_config.get("python", ["python"])
74
+
75
+ if isinstance(python_cmd, str):
76
+ python_cmd = python_cmd.split()
77
+
78
+ if not legacy_apps_config and not hybrid_apps_config and not allow_empty_apps:
79
+ console.print("[bold red]No apps configured.[/bold red]")
80
+ console.print("Add app configuration to pyproject.toml:")
81
+ console.print("")
82
+ console.print("[tool.nf]")
83
+ console.print('python = ["uv", "run", "python"] # optional')
84
+ console.print('legacy_apps = ["path.to.module:app_name"]')
85
+ console.print('hybrid_apps = ["path.to.module:app_name"] # optional')
86
+ raise click.ClickException("No legacy_apps or hybrid_apps configured in pyproject.toml")
87
+
88
+ if legacy_apps_config and not isinstance(legacy_apps_config, list):
89
+ raise click.ClickException("[tool.nf].legacy_apps must be a list")
90
+ if hybrid_apps_config and not isinstance(hybrid_apps_config, list):
91
+ raise click.ClickException("[tool.nf].hybrid_apps must be a list")
92
+
93
+ return NFProjectConfig(
94
+ legacy_apps=_build_app_dict(legacy_apps_config),
95
+ hybrid_apps=_build_app_dict(hybrid_apps_config),
96
+ python_cmd=list(python_cmd),
97
+ example_scripts=list(example_scripts),
98
+ )
99
+
100
+
101
+ def load_app_config(
102
+ *,
103
+ allow_empty_apps: bool = False,
104
+ ) -> tuple[dict[str, str], list[str], list[str]]:
105
+ """Load legacy app configuration."""
106
+ project_config = load_project_config(allow_empty_apps=allow_empty_apps)
107
+ return project_config.legacy_apps, project_config.python_cmd, project_config.example_scripts