loft-cli-core 0.6.3__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 (41) hide show
  1. loft_cli_core/__init__.py +1 -0
  2. loft_cli_core/agent_models.py +34 -0
  3. loft_cli_core/agent_paths.py +27 -0
  4. loft_cli_core/plan/__init__.py +0 -0
  5. loft_cli_core/plan/models.py +80 -0
  6. loft_cli_core/plan/render_diff.py +112 -0
  7. loft_cli_core/plan/render_markdown.py +189 -0
  8. loft_cli_core/plan/render_text.py +86 -0
  9. loft_cli_core/policy.py +218 -0
  10. loft_cli_core/registry/__init__.py +108 -0
  11. loft_cli_core/registry/executors.py +31 -0
  12. loft_cli_core/registry/hooks.py +46 -0
  13. loft_cli_core/registry/local_paths.py +147 -0
  14. loft_cli_core/registry/normalizers.py +21 -0
  15. loft_cli_core/registry/planners.py +21 -0
  16. loft_cli_core/registry/resolvers.py +65 -0
  17. loft_cli_core/registry/specs.py +20 -0
  18. loft_cli_core/registry/validators.py +21 -0
  19. loft_cli_core/specs/__init__.py +0 -0
  20. loft_cli_core/specs/backup_job_schema.py +95 -0
  21. loft_cli_core/specs/bootstrap_schema.py +124 -0
  22. loft_cli_core/specs/compose_project_schema.py +93 -0
  23. loft_cli_core/specs/file_template_schema.py +64 -0
  24. loft_cli_core/specs/http_check_schema.py +64 -0
  25. loft_cli_core/specs/loader.py +250 -0
  26. loft_cli_core/specs/postgres_ensure_schema.py +104 -0
  27. loft_cli_core/specs/service_schema.py +114 -0
  28. loft_cli_core/specs/stack_schema.py +74 -0
  29. loft_cli_core/specs/systemd_timer_schema.py +76 -0
  30. loft_cli_core/specs/systemd_unit_schema.py +86 -0
  31. loft_cli_core/specs/validators.py +755 -0
  32. loft_cli_core/state.py +31 -0
  33. loft_cli_core/utils/__init__.py +0 -0
  34. loft_cli_core/utils/files.py +41 -0
  35. loft_cli_core/utils/hashing.py +10 -0
  36. loft_cli_core/utils/os_detect.py +36 -0
  37. loft_cli_core/utils/templates.py +87 -0
  38. loft_cli_core-0.6.3.dist-info/METADATA +10 -0
  39. loft_cli_core-0.6.3.dist-info/RECORD +41 -0
  40. loft_cli_core-0.6.3.dist-info/WHEEL +5 -0
  41. loft_cli_core-0.6.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.6.3"
@@ -0,0 +1,34 @@
1
+ """Shared agent result models.
2
+
3
+ These Pydantic models define the agent apply/step result schema shared
4
+ between the agent (which produces them) and the client (which consumes
5
+ them via agent_transport).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Literal
11
+
12
+ from pydantic import BaseModel
13
+
14
+
15
+ class AgentStepResult(BaseModel):
16
+ step_index: int
17
+ step_id: str
18
+ scope: str
19
+ status: Literal["success", "failed", "skipped", "unchanged"]
20
+ output: str = ""
21
+ error: str = ""
22
+ duration_seconds: float = 0.0
23
+
24
+
25
+ class AgentApplyResult(BaseModel):
26
+ plan_hash: str
27
+ spec_hash: str
28
+ step_results: list[AgentStepResult]
29
+ status: Literal["success", "failed"]
30
+ aborted_at: int | None = None
31
+ started_at: str
32
+ finished_at: str = ""
33
+ unchanged_count: int = 0
34
+ applied_count: int = 0
@@ -0,0 +1,27 @@
1
+ """Server-side path constants for the loft-cli agent.
2
+
3
+ These constants are shared between the client (for SSH commands targeting
4
+ the agent) and the agent (for local filesystem operations).
5
+
6
+ All agent state lives under well-known paths on the managed server.
7
+ These paths are deterministic and do not depend on user configuration.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ # Configuration (read-only after bootstrap)
15
+ AGENT_CONFIG_DIR = Path("/etc/loft-cli")
16
+
17
+ # Runtime state (mutable: locks, state tracking, desired state)
18
+ AGENT_STATE_DIR = Path("/var/lib/loft-cli")
19
+ AGENT_LOCK_DIR = AGENT_STATE_DIR / "locks"
20
+ AGENT_DESIRED_DIR = AGENT_STATE_DIR / "desired"
21
+ AGENT_STATE_FILE = AGENT_STATE_DIR / "runtime-state.json"
22
+
23
+ # Logs
24
+ AGENT_LOG_DIR = Path("/var/log/loft-cli")
25
+
26
+ # Agent binary location
27
+ AGENT_BINARY_PATH = Path("/usr/local/bin/loft-cli-agent")
File without changes
@@ -0,0 +1,80 @@
1
+ """Central Plan data structures. All downstream modules consume these."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ class StepScope(StrEnum):
11
+ REMOTE = "remote"
12
+ LOCAL = "local"
13
+ VERIFY = "verify"
14
+
15
+
16
+ class StepKind:
17
+ """Open string constants for step execution kinds.
18
+
19
+ Unlike a closed Enum, new step kinds can be added by addons simply by
20
+ registering a handler in the executor registry -- no core edits required:
21
+
22
+ from loft_cli_core.registry import register_step_handler
23
+ register_step_handler("compose_up", _handle_compose_up)
24
+
25
+ All built-in kind strings are preserved as class attributes so existing
26
+ code using StepKind.SSH_COMMAND continues to work unchanged.
27
+ """
28
+
29
+ SSH_COMMAND = "ssh_command"
30
+ SSH_UPLOAD = "ssh_upload"
31
+ LOCAL_COMMAND = "local_command"
32
+ LOCAL_FILE_WRITE = "local_file_write"
33
+ LOCAL_DB_WRITE = "local_db_write"
34
+ VERIFY = "verify"
35
+ GATE = "gate" # must pass before subsequent steps that depend on it execute
36
+ COMPOSE_HEALTH_CHECK = "compose_health_check" # poll docker compose ps for container health
37
+
38
+ # Agent-side step kinds (v0.4) — execute locally on the managed server
39
+ AGENT_COMMAND = "agent_command"
40
+ AGENT_FILE_WRITE = "agent_file_write"
41
+ AGENT_GATE = "agent_gate"
42
+ AGENT_VERIFY = "agent_verify"
43
+ AGENT_COMPOSE_HEALTH = "agent_compose_health"
44
+
45
+
46
+ class Step(BaseModel):
47
+ id: str # e.g. "create_admin_user", "verify_admin_login"
48
+ index: int
49
+ description: str
50
+ scope: StepScope
51
+ kind: str # StepKind constant or addon-defined string
52
+ command: str | None = None # shell command for SSH/local
53
+ file_content: str | None = None # for file writes/uploads
54
+ target_path: str | None = None # for file operations
55
+ sudo: bool = False
56
+ check_command: str | None = None
57
+ rollback_hint: str | None = None
58
+ depends_on: list[int] = Field(default_factory=list)
59
+ gate: bool = False
60
+ tags: list[str] = Field(default_factory=list)
61
+
62
+
63
+ class Plan(BaseModel):
64
+ spec_name: str
65
+ spec_kind: str
66
+ target_host: str
67
+ spec_hash: str
68
+ plan_hash: str
69
+ steps: list[Step]
70
+ created_at: str
71
+ execution_mode: str = "client" # "client" (Fabric) or "agent" (server-local)
72
+
73
+ def remote_steps(self) -> list[Step]:
74
+ return [s for s in self.steps if s.scope == StepScope.REMOTE]
75
+
76
+ def local_steps(self) -> list[Step]:
77
+ return [s for s in self.steps if s.scope == StepScope.LOCAL]
78
+
79
+ def gates(self) -> list[Step]:
80
+ return [s for s in self.steps if s.gate]
@@ -0,0 +1,112 @@
1
+ """Diff renderer for dry-run comparison.
2
+
3
+ Shows what would change on the server if the plan were applied,
4
+ comparing the new plan against the agent's current runtime state.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+ from rich.table import Table
14
+ from rich.text import Text
15
+
16
+ from loft_cli_core.plan.models import Plan, StepScope
17
+ from loft_cli_core.utils.hashing import sha256_string
18
+
19
+ if TYPE_CHECKING:
20
+ from loft_cli_core.state import RuntimeState
21
+
22
+
23
+ def _step_content_hash(step) -> str:
24
+ """Compute the same content hash as the agent executor."""
25
+ parts = [step.id, step.command or "", step.file_content or "", step.target_path or ""]
26
+ return sha256_string("".join(parts))
27
+
28
+
29
+ def render_diff(
30
+ plan: Plan,
31
+ current_state: RuntimeState | None,
32
+ console: Console | None = None,
33
+ ) -> None:
34
+ """Render a diff showing what would change if the plan were applied.
35
+
36
+ Compares each step's content hash against the runtime state to
37
+ classify steps as: added (new), changed, unchanged, or always-run.
38
+ """
39
+ c = console or Console()
40
+
41
+ c.print(
42
+ Panel(
43
+ f"[bold]Spec:[/bold] {plan.spec_name} ({plan.spec_kind})\n"
44
+ f"[bold]Target:[/bold] {plan.target_host}\n"
45
+ f"[bold]Steps:[/bold] {len(plan.steps)}",
46
+ title="loft-cli diff",
47
+ border_style="bright_blue",
48
+ )
49
+ )
50
+
51
+ if current_state is None:
52
+ c.print("[yellow]No runtime state found — all steps would be applied (first run)[/yellow]")
53
+ current_resources = {}
54
+ else:
55
+ current_resources = current_state.resources
56
+
57
+ # Classify steps
58
+ table = Table(show_header=True, header_style="bold", box=None, padding=(0, 1))
59
+ table.add_column("#", style="dim", width=4)
60
+ table.add_column("ID", min_width=30)
61
+ table.add_column("Status", width=12)
62
+ table.add_column("Description", min_width=40)
63
+
64
+ added = 0
65
+ changed = 0
66
+ unchanged = 0
67
+ always_run = 0
68
+
69
+ remote_steps = [s for s in plan.steps if s.scope in (StepScope.REMOTE, StepScope.VERIFY)]
70
+
71
+ for step in remote_steps:
72
+ content_hash = _step_content_hash(step)
73
+ is_always = "always" in step.tags or step.gate or step.scope == StepScope.VERIFY
74
+
75
+ if is_always:
76
+ status = "always"
77
+ color = "cyan"
78
+ always_run += 1
79
+ elif step.id not in current_resources:
80
+ status = "+ added"
81
+ color = "green"
82
+ added += 1
83
+ elif current_resources[step.id].content_hash != content_hash:
84
+ status = "~ changed"
85
+ color = "yellow"
86
+ changed += 1
87
+ else:
88
+ status = "= unchanged"
89
+ color = "dim"
90
+ unchanged += 1
91
+
92
+ table.add_row(
93
+ str(step.index),
94
+ step.id,
95
+ Text(status, style=color),
96
+ step.description[:60],
97
+ )
98
+
99
+ c.print(table)
100
+
101
+ # Summary
102
+ c.print(
103
+ f"\n[green]+{added} added[/green] "
104
+ f"[yellow]~{changed} changed[/yellow] "
105
+ f"[dim]={unchanged} unchanged[/dim] "
106
+ f"[cyan]{always_run} always-run[/cyan]"
107
+ )
108
+
109
+ if changed == 0 and added == 0:
110
+ c.print("\n[bold green]No changes — server is up to date.[/bold green]")
111
+ else:
112
+ c.print(f"\n[bold]{added + changed} step(s) would be applied.[/bold]")
@@ -0,0 +1,189 @@
1
+ """Jinja2-based Markdown rendering for the 'loft-cli docs' command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from jinja2 import Environment
6
+
7
+ from loft_cli_core.plan.models import Plan, StepScope
8
+
9
+ # ---------------------------------------------------------------------------
10
+ # Templates stored as inline string constants — no external .j2 files needed.
11
+ # ---------------------------------------------------------------------------
12
+
13
+ _GUIDE_TEMPLATE = """\
14
+ # {{ plan.spec_name }}
15
+
16
+ > Generated by loft-cli on {{ plan.created_at[:19] }} UTC
17
+ > Spec kind: `{{ plan.spec_kind }}` | Target: `{{ plan.target_host }}`
18
+ > Plan hash: `{{ plan.plan_hash[:16] }}…`
19
+
20
+ ## Summary
21
+
22
+ This guide was generated from the execution plan and describes exactly what
23
+ `loft-cli apply` will perform. Every command shown here is the same command
24
+ that will be executed remotely or locally.
25
+
26
+ {% if local_prep_steps %}
27
+ ---
28
+
29
+ ## Local Preparation
30
+
31
+ {% for step in local_prep_steps %}
32
+ ### Step {{ step.index }}: {{ step.description }}
33
+
34
+ {% if step.command and not step.command.startswith(('ssh_check:', 'check:', 'http_check:')) %}
35
+ ```bash
36
+ {{ step.command }}
37
+ ```
38
+ {% endif %}
39
+ {% if step.rollback_hint %}
40
+ > **Recovery:** {{ step.rollback_hint }}
41
+ {% endif %}
42
+
43
+ {% endfor %}
44
+ {% endif %}
45
+
46
+ ---
47
+
48
+ ## Remote {{ 'Bootstrap' if plan.spec_kind == 'bootstrap' else 'Operations' }}
49
+
50
+ {% for step in remote_steps %}
51
+ ### Step {{ step.index }}: {{ step.description }}
52
+ {% if step.gate %}
53
+ > ⚠️ **GATE** — Failure here will abort the plan to prevent SSH lockout.
54
+ {% endif %}
55
+ {% if step.depends_on %}
56
+ > Depends on steps: {{ step.depends_on | join(', ') }}
57
+ {% endif %}
58
+
59
+ {% if step.kind == 'ssh_upload' %}
60
+ **File:** `{{ step.target_path }}`
61
+
62
+ ```
63
+ {{ step.file_content or '(file content from spec)' }}
64
+ ```
65
+ {% elif step.command and not step.command.startswith(('ssh_check:', 'check:', 'http_check:', 'echo ')) %}
66
+ ```bash
67
+ {{ step.command }}
68
+ ```
69
+ {% elif step.command and step.command.startswith('ssh_check:') %}
70
+ ```bash
71
+ # Verify new SSH login
72
+ ssh -p {{ step.command.split(':')[2] }} {{ step.command.split(':')[3] }}@{{ step.command.split(':')[1] }}
73
+ ```
74
+ {% endif %}
75
+ {% if step.rollback_hint %}
76
+ > **Recovery:** {{ step.rollback_hint }}
77
+ {% endif %}
78
+
79
+ {% endfor %}
80
+
81
+ ---
82
+
83
+ ## Local Finalization
84
+
85
+ {% for step in local_final_steps %}
86
+ ### Step {{ step.index }}: {{ step.description }}
87
+
88
+ {% if step.command and not step.command.startswith(('backup_ssh_config', 'ensure_include', 'init_inventory', 'upsert_', 'record_run')) %}
89
+ ```bash
90
+ {{ step.command }}
91
+ ```
92
+ {% endif %}
93
+
94
+ {% endfor %}
95
+
96
+ ---
97
+
98
+ ## Verification
99
+
100
+ ```bash
101
+ # Verify SSH access via new alias
102
+ ssh {{ plan.spec_name | lower | replace(' ', '-') }}
103
+
104
+ # Check services
105
+ {% for step in verify_steps %}
106
+ # {{ step.description }}
107
+ {% if step.command and not step.command.startswith(('check:', 'http_check:', 'ssh_check:')) %}
108
+ {{ step.command }}
109
+ {% endif %}
110
+ {% endfor %}
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Recovery Notes
116
+
117
+ If the SSH gate check (step {{ gate_index }}) fails:
118
+
119
+ - **Do not** disable root login
120
+ - **Do not** disable password authentication
121
+ - Restore sshd_config from backup:
122
+
123
+ ```bash
124
+ cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
125
+ systemctl reload ssh
126
+ ```
127
+
128
+ If local SSH config update fails:
129
+ - Remote bootstrap may still be successful
130
+ - Manually add the SSH conf.d entry
131
+
132
+ If SQLCipher inventory update fails:
133
+ - Remote bootstrap is still considered successful
134
+ - A warning will be shown in the output
135
+ """
136
+
137
+ _COMMANDS_TEMPLATE = """\
138
+ # {{ plan.spec_name }} — Commands
139
+
140
+ > loft-cli docs --commands | Target: `{{ plan.target_host }}`
141
+
142
+ ## Remote Steps
143
+
144
+ {% for step in remote_steps %}
145
+ {% if step.command and not step.command.startswith(('ssh_check:', 'check:', 'http_check:', 'echo ')) %}
146
+ # [{{ step.index }}] {{ step.description }}
147
+ {{ step.command }}
148
+
149
+ {% endif %}
150
+ {% endfor %}
151
+
152
+ ## Local Steps
153
+
154
+ {% for step in local_final_steps %}
155
+ {% if step.command and not step.command.startswith(('backup_ssh_config', 'ensure_include', 'init_inventory', 'upsert_', 'record_run')) %}
156
+ # [{{ step.index }}] {{ step.description }}
157
+ {{ step.command }}
158
+
159
+ {% endif %}
160
+ {% endfor %}
161
+ """
162
+
163
+
164
+ def render_markdown(plan: Plan, mode: str = "guide") -> str:
165
+ """Render plan as Markdown. mode='guide' (verbose) or 'commands' (compact)."""
166
+ env = Environment(autoescape=False, keep_trailing_newline=True)
167
+
168
+ remote_steps = [s for s in plan.steps if s.scope == StepScope.REMOTE]
169
+ local_steps = [s for s in plan.steps if s.scope == StepScope.LOCAL]
170
+ verify_steps = [s for s in plan.steps if s.scope == StepScope.VERIFY and not s.gate]
171
+
172
+ # Separate local steps into prep (before bootstrap) and finalization (after)
173
+ local_prep_steps: list = []
174
+ local_final_steps = local_steps
175
+
176
+ # Find gate index for recovery notes
177
+ gate_index = next((s.index for s in plan.steps if s.gate), "N/A")
178
+
179
+ template_str = _GUIDE_TEMPLATE if mode == "guide" else _COMMANDS_TEMPLATE
180
+ template = env.from_string(template_str)
181
+
182
+ return template.render(
183
+ plan=plan,
184
+ remote_steps=remote_steps,
185
+ local_prep_steps=local_prep_steps,
186
+ local_final_steps=local_final_steps,
187
+ verify_steps=verify_steps,
188
+ gate_index=gate_index,
189
+ )
@@ -0,0 +1,86 @@
1
+ """Rich console output for the 'loft-cli plan' command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from rich.console import Console
6
+ from rich.panel import Panel
7
+ from rich.table import Table
8
+ from rich.text import Text
9
+
10
+ from loft_cli_core.plan.models import Plan, StepKind, StepScope
11
+
12
+ _SCOPE_COLORS = {
13
+ StepScope.REMOTE: "cyan",
14
+ StepScope.LOCAL: "green",
15
+ StepScope.VERIFY: "blue",
16
+ }
17
+
18
+ _KIND_LABELS: dict[str, str] = {
19
+ StepKind.SSH_COMMAND: "ssh cmd",
20
+ StepKind.SSH_UPLOAD: "ssh upload",
21
+ StepKind.LOCAL_COMMAND: "local cmd",
22
+ StepKind.LOCAL_FILE_WRITE: "file write",
23
+ StepKind.LOCAL_DB_WRITE: "db write",
24
+ StepKind.VERIFY: "verify",
25
+ StepKind.GATE: "GATE",
26
+ StepKind.AGENT_COMMAND: "agent cmd",
27
+ StepKind.AGENT_FILE_WRITE: "agent write",
28
+ StepKind.AGENT_GATE: "GATE",
29
+ StepKind.AGENT_VERIFY: "verify",
30
+ StepKind.AGENT_COMPOSE_HEALTH: "health",
31
+ }
32
+
33
+
34
+ def render_plan(plan: Plan, console: Console | None = None) -> None:
35
+ """Print the plan to the console as a Rich table."""
36
+ if console is None:
37
+ console = Console()
38
+
39
+ # Summary panel
40
+ summary_lines = [
41
+ f"[bold]Spec:[/bold] {plan.spec_name} ({plan.spec_kind})",
42
+ f"[bold]Target:[/bold] {plan.target_host}",
43
+ f"[bold]Steps:[/bold] {len(plan.steps)} "
44
+ f"([cyan]{len(plan.remote_steps())} remote[/cyan], "
45
+ f"[green]{len(plan.local_steps())} local[/green])",
46
+ f"[bold]Hash:[/bold] {plan.plan_hash[:16]}…",
47
+ ]
48
+ console.print(
49
+ Panel("\n".join(summary_lines), title="loft-cli plan", border_style="bright_blue")
50
+ )
51
+
52
+ # Steps table
53
+ table = Table(show_header=True, header_style="bold", box=None, padding=(0, 1))
54
+ table.add_column("#", style="dim", width=4)
55
+ table.add_column("ID", style="italic", min_width=30)
56
+ table.add_column("Description", min_width=40)
57
+ table.add_column("Scope", width=8)
58
+ table.add_column("Kind", width=12)
59
+ table.add_column("Gate", width=6)
60
+ table.add_column("Depends", width=12)
61
+
62
+ for step in plan.steps:
63
+ color = _SCOPE_COLORS.get(step.scope, "white")
64
+ scope_text = Text(step.scope.value, style=color)
65
+ kind_label = _KIND_LABELS.get(step.kind, step.kind)
66
+
67
+ gate_text = Text("YES", style="bold yellow") if step.gate else Text("")
68
+ depends_text = (
69
+ Text(", ".join(str(d) for d in step.depends_on)) if step.depends_on else Text("")
70
+ )
71
+
72
+ desc = step.description
73
+ if step.gate:
74
+ desc = f"[bold yellow]{desc}[/bold yellow]"
75
+
76
+ table.add_row(
77
+ str(step.index),
78
+ step.id,
79
+ desc,
80
+ scope_text,
81
+ kind_label,
82
+ gate_text,
83
+ depends_text,
84
+ )
85
+
86
+ console.print(table)