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,218 @@
1
+ """Policy engine for loft-cli.
2
+
3
+ Enforces ``policy.yaml`` rules against plan steps before execution.
4
+ Policy is **inert by default**: if no policy.yaml is present, no checks
5
+ run and the agent executes whatever it receives.
6
+
7
+ Policy actions
8
+ --------------
9
+ - ``auto_apply`` — step executes without any human intervention (default).
10
+ - ``require_approval`` — step requires a valid approval token before execution.
11
+ - ``deny`` — step is refused unconditionally.
12
+
13
+ Approval tokens
14
+ ---------------
15
+ Temporary, one-off approvals for ``require_approval`` steps. Tokens are
16
+ opaque HMAC-SHA256 strings with an expiry timestamp. The agent validates
17
+ them locally — no network round-trip required.
18
+
19
+ Design principles
20
+ -----------------
21
+ - Policy is OSS core — auditable by anyone, activated by configuration.
22
+ - No policy.yaml → no policy checks → agent executes what it's told.
23
+ - Policy is evaluated per-step, not per-plan.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import fnmatch
29
+ import hashlib
30
+ import hmac
31
+ import time
32
+ from enum import StrEnum
33
+ from typing import Any
34
+
35
+ import yaml
36
+ from pydantic import BaseModel, Field
37
+
38
+ # ── Policy actions ────────────────────────────────────────────────────────────
39
+
40
+
41
+ class PolicyAction(StrEnum):
42
+ AUTO_APPLY = "auto_apply"
43
+ REQUIRE_APPROVAL = "require_approval"
44
+ DENY = "deny"
45
+
46
+
47
+ # ── Policy rule model ────────────────────────────────────────────────────────
48
+
49
+
50
+ class PolicyRule(BaseModel):
51
+ """A single policy rule matching steps by kind, id pattern, or tags."""
52
+
53
+ name: str = ""
54
+ match_kind: str | None = None # step kind (e.g. "agent_command")
55
+ match_id: str | None = None # step id glob (e.g. "install_*")
56
+ match_tags: list[str] = Field(default_factory=list) # any of these tags
57
+ action: PolicyAction = PolicyAction.AUTO_APPLY
58
+
59
+
60
+ class PolicyConfig(BaseModel):
61
+ """Top-level policy configuration loaded from ``policy.yaml``."""
62
+
63
+ version: str = "1"
64
+ default_action: PolicyAction = PolicyAction.AUTO_APPLY
65
+ rules: list[PolicyRule] = Field(default_factory=list)
66
+
67
+
68
+ # ── Approval tokens ──────────────────────────────────────────────────────────
69
+
70
+ # Token format: "{step_id}:{expires_unix}:{hmac_hex}"
71
+ # The HMAC key is derived from the agent's state file hash — so tokens
72
+ # are scoped to a specific server.
73
+
74
+ _TOKEN_SEP = ":"
75
+
76
+
77
+ class ApprovalToken(BaseModel):
78
+ """A temporary approval token for a specific step."""
79
+
80
+ step_id: str
81
+ expires_at: float # Unix timestamp
82
+ signature: str
83
+
84
+
85
+ def generate_approval_token(
86
+ step_id: str,
87
+ secret_key: str,
88
+ ttl_seconds: int = 3600,
89
+ ) -> str:
90
+ """Generate a time-limited HMAC approval token.
91
+
92
+ Parameters
93
+ ----------
94
+ step_id:
95
+ The step this token authorises.
96
+ secret_key:
97
+ HMAC key (typically derived from server identity).
98
+ ttl_seconds:
99
+ How long the token is valid (default: 1 hour).
100
+
101
+ Returns
102
+ -------
103
+ Opaque token string suitable for passing via ``--approval-token``.
104
+ """
105
+ expires = time.time() + ttl_seconds
106
+ payload = f"{step_id}{_TOKEN_SEP}{expires}"
107
+ sig = hmac.new(secret_key.encode(), payload.encode(), hashlib.sha256).hexdigest()
108
+ return f"{step_id}{_TOKEN_SEP}{expires}{_TOKEN_SEP}{sig}"
109
+
110
+
111
+ def validate_approval_token(token: str, secret_key: str) -> ApprovalToken | None:
112
+ """Validate an approval token.
113
+
114
+ Returns the parsed token if valid and not expired, or ``None``.
115
+ """
116
+ parts = token.split(_TOKEN_SEP, 2)
117
+ if len(parts) != 3:
118
+ return None
119
+
120
+ step_id, expires_str, signature = parts
121
+ try:
122
+ expires = float(expires_str)
123
+ except ValueError:
124
+ return None
125
+
126
+ # Check expiry
127
+ if time.time() > expires:
128
+ return None
129
+
130
+ # Verify HMAC
131
+ payload = f"{step_id}{_TOKEN_SEP}{expires_str}"
132
+ expected = hmac.new(secret_key.encode(), payload.encode(), hashlib.sha256).hexdigest()
133
+ if not hmac.compare_digest(signature, expected):
134
+ return None
135
+
136
+ return ApprovalToken(step_id=step_id, expires_at=expires, signature=signature)
137
+
138
+
139
+ # ── Policy loading ───────────────────────────────────────────────────────────
140
+
141
+
142
+ def load_policy(path: Any | None = None) -> PolicyConfig | None:
143
+ """Load policy from a YAML file path.
144
+
145
+ Returns ``None`` if the path is ``None`` or the file does not exist
146
+ (policy is inert by default).
147
+ """
148
+ if path is None:
149
+ return None
150
+
151
+ from pathlib import Path
152
+
153
+ p = Path(path) if not isinstance(path, Path) else path
154
+ if not p.exists():
155
+ return None
156
+
157
+ text = p.read_text(encoding="utf-8")
158
+ raw = yaml.safe_load(text)
159
+ if raw is None:
160
+ return None
161
+
162
+ return PolicyConfig.model_validate(raw)
163
+
164
+
165
+ # ── Policy evaluation ────────────────────────────────────────────────────────
166
+
167
+
168
+ class PolicyDecision(BaseModel):
169
+ """Result of evaluating policy for a single step."""
170
+
171
+ action: PolicyAction
172
+ rule_name: str = "" # which rule matched (empty = default)
173
+ reason: str = ""
174
+
175
+
176
+ def evaluate_step(
177
+ policy: PolicyConfig | None,
178
+ step_id: str,
179
+ step_kind: str,
180
+ step_tags: list[str],
181
+ ) -> PolicyDecision:
182
+ """Evaluate policy for a single step.
183
+
184
+ If policy is ``None`` (no policy.yaml), returns ``auto_apply``.
185
+ """
186
+ if policy is None:
187
+ return PolicyDecision(action=PolicyAction.AUTO_APPLY, reason="No policy configured")
188
+
189
+ for rule in policy.rules:
190
+ if _rule_matches(rule, step_id, step_kind, step_tags):
191
+ return PolicyDecision(
192
+ action=rule.action,
193
+ rule_name=rule.name,
194
+ reason=f"Matched rule '{rule.name}'",
195
+ )
196
+
197
+ return PolicyDecision(
198
+ action=policy.default_action,
199
+ reason="Default policy action",
200
+ )
201
+
202
+
203
+ def _rule_matches(
204
+ rule: PolicyRule,
205
+ step_id: str,
206
+ step_kind: str,
207
+ step_tags: list[str],
208
+ ) -> bool:
209
+ """Check if a policy rule matches a step."""
210
+ # All specified conditions must match (AND logic).
211
+ if rule.match_kind is not None and rule.match_kind != step_kind:
212
+ return False
213
+ if rule.match_id is not None and not fnmatch.fnmatch(step_id, rule.match_id):
214
+ return False
215
+ if rule.match_tags and not any(t in step_tags for t in rule.match_tags):
216
+ return False
217
+ # At least one condition must be specified for the rule to match.
218
+ return not (rule.match_kind is None and rule.match_id is None and not rule.match_tags)
@@ -0,0 +1,108 @@
1
+ """loft-cli addon/plugin registry.
2
+
3
+ Public API for registering and discovering spec kinds, planners, normalizers,
4
+ validators, step handlers, and lifecycle hooks. Addons call these functions
5
+ during registration to extend loft-cli without modifying any core source files.
6
+
7
+ Built-in kinds (bootstrap, service) are registered by the ``loft-cli`` client
8
+ package via the ``loft_cli.addons`` entry_points group.
9
+
10
+ External addons also register via Python entry_points:
11
+
12
+ # In the addon's pyproject.toml:
13
+ [project.entry-points."loft_cli.addons"]
14
+ my_addon = "my_addon:register"
15
+
16
+ # In my_addon/__init__.py:
17
+ def register():
18
+ from loft_cli_core.registry import register_spec_kind, register_planner, ...
19
+ register_spec_kind("my_kind", MySpec)
20
+ register_planner("my_kind", _plan_my_kind)
21
+ ...
22
+
23
+ load_addons() is idempotent — subsequent calls are no-ops.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from loft_cli_core.registry.executors import get_step_handler, register_step_handler
29
+ from loft_cli_core.registry.hooks import KindHooks, get_kind_hooks, register_kind_hooks
30
+ from loft_cli_core.registry.local_paths import (
31
+ LocalPathsConfig,
32
+ get_local_paths,
33
+ register_local_paths,
34
+ )
35
+ from loft_cli_core.registry.normalizers import get_normalizer, register_normalizer
36
+ from loft_cli_core.registry.planners import get_planner, register_planner
37
+ from loft_cli_core.registry.resolvers import get_resolver, list_resolvers, register_resolver
38
+ from loft_cli_core.registry.specs import get_spec_model, list_spec_kinds, register_spec_kind
39
+ from loft_cli_core.registry.validators import get_validator, register_validator
40
+
41
+ __all__ = [
42
+ # Spec kinds
43
+ "register_spec_kind",
44
+ "get_spec_model",
45
+ "list_spec_kinds",
46
+ # Planners
47
+ "register_planner",
48
+ "get_planner",
49
+ # Normalizers
50
+ "register_normalizer",
51
+ "get_normalizer",
52
+ # Validators
53
+ "register_validator",
54
+ "get_validator",
55
+ # Step handlers
56
+ "register_step_handler",
57
+ "get_step_handler",
58
+ # Lifecycle hooks
59
+ "register_kind_hooks",
60
+ "get_kind_hooks",
61
+ "KindHooks",
62
+ # Value resolvers (7th registry)
63
+ "register_resolver",
64
+ "get_resolver",
65
+ "list_resolvers",
66
+ # Local filesystem paths (addon-overridable)
67
+ "register_local_paths",
68
+ "get_local_paths",
69
+ "LocalPathsConfig",
70
+ # Addon loader
71
+ "load_addons",
72
+ ]
73
+
74
+ _addons_loaded = False
75
+
76
+
77
+ def load_addons() -> None:
78
+ """Load built-in kinds and discover external addons via entry_points.
79
+
80
+ Safe to call multiple times — subsequent calls are no-ops.
81
+ Called automatically by the CLI before any command runs, and also
82
+ lazily by load_spec() and validate_spec() for non-CLI usage (tests, etc.).
83
+ """
84
+ global _addons_loaded
85
+ if _addons_loaded:
86
+ return
87
+ _addons_loaded = True
88
+
89
+ # Discover and load all addons (including built-in kinds) via entry_points.
90
+ # The loft-cli client package registers built-in kinds (bootstrap, service,
91
+ # file_template, compose_project) via its own entry_point.
92
+ try:
93
+ import importlib.metadata
94
+
95
+ entry_points = importlib.metadata.entry_points(group="loft_cli.addons")
96
+ for ep in entry_points:
97
+ try:
98
+ addon_register = ep.load()
99
+ addon_register()
100
+ except Exception as exc:
101
+ import warnings
102
+
103
+ warnings.warn(
104
+ f"Failed to load loft-cli addon '{ep.name}': {exc}",
105
+ stacklevel=2,
106
+ )
107
+ except Exception:
108
+ pass
@@ -0,0 +1,31 @@
1
+ """Step handler registry: maps step kind strings to executor callables.
2
+
3
+ A step handler callable has the signature:
4
+ (executor: Executor, step: Step) -> StepResult
5
+
6
+ The executor instance is passed as the first argument so handlers can
7
+ access session, inventory_db, ctx, spec, and console as needed.
8
+
9
+ Built-in step kinds (ssh_command, ssh_upload, etc.) are registered by
10
+ _builtins._register_builtins() at addon load time. External addons
11
+ register new step kinds the same way:
12
+
13
+ from loft_cli_core.registry import register_step_handler
14
+ register_step_handler("compose_up", _handle_compose_up)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable
20
+
21
+ _STEP_HANDLER_REGISTRY: dict[str, Callable] = {}
22
+
23
+
24
+ def register_step_handler(kind: str, fn: Callable) -> None:
25
+ """Register an executor handler for a step kind string."""
26
+ _STEP_HANDLER_REGISTRY[kind] = fn
27
+
28
+
29
+ def get_step_handler(kind: str) -> Callable | None:
30
+ """Return the handler for a step kind, or None if not registered."""
31
+ return _STEP_HANDLER_REGISTRY.get(kind)
@@ -0,0 +1,46 @@
1
+ """Kind lifecycle hooks: per-spec-kind callbacks used by the CLI.
2
+
3
+ Hooks allow spec kinds to declare special CLI behaviours without
4
+ requiring the CLI to contain isinstance() checks for each concrete type.
5
+
6
+ Built-in hooks are registered by _builtins._register_builtins().
7
+ External addons register hooks for their own spec kinds:
8
+
9
+ from loft_cli_core.registry import register_kind_hooks, KindHooks
10
+ register_kind_hooks("compose_project", KindHooks(
11
+ on_inventory_record=_record_compose_project,
12
+ ))
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+
20
+ _HOOKS_REGISTRY: dict[str, KindHooks] = {}
21
+
22
+
23
+ @dataclass
24
+ class KindHooks:
25
+ """Lifecycle hooks for a spec kind, invoked by the CLI at key moments."""
26
+
27
+ # Bootstrap-style specs: ensure SSH key pairs exist before normalization.
28
+ needs_key_generation: bool = False
29
+
30
+ # Bootstrap-style specs: attempt SSH port fallback on re-runs when
31
+ # login.port is unreachable but ssh.port is reachable.
32
+ ssh_port_fallback: bool = False
33
+
34
+ # Called post-apply to record spec results in the local inventory.
35
+ # Signature: (db: InventoryDB, spec: AnySpec, result: ApplyResult) -> None
36
+ on_inventory_record: Callable | None = None
37
+
38
+
39
+ def register_kind_hooks(kind: str, hooks: KindHooks) -> None:
40
+ """Register lifecycle hooks for a spec kind."""
41
+ _HOOKS_REGISTRY[kind] = hooks
42
+
43
+
44
+ def get_kind_hooks(kind: str) -> KindHooks:
45
+ """Return hooks for a kind, or a default no-op KindHooks if not registered."""
46
+ return _HOOKS_REGISTRY.get(kind, KindHooks())
@@ -0,0 +1,147 @@
1
+ """Addon-overridable local filesystem path configuration.
2
+
3
+ Core code always calls ``get_local_paths()`` to discover where loft-cli
4
+ stores its local state (SSH conf.d entries, WireGuard key material, inventory
5
+ database, run logs, etc.).
6
+
7
+ The defaults place everything under standard XDG-adjacent directories:
8
+
9
+ ~/.ssh/conf.d/loft-cli/ -- per-host SSH config fragments
10
+ ~/.wg/loft-cli/ -- per-host WireGuard key material and metadata
11
+ ~/.loft-cli/inventory.db -- local server inventory
12
+ ~/.loft-cli/runs/ -- apply execution logs
13
+
14
+ When ``LOFT_CLI_STATE_DIR`` is set (or ``state_dir`` is passed explicitly),
15
+ all paths are derived from that base directory instead:
16
+
17
+ {state_dir}/ssh/conf.d/ -- SSH config fragments
18
+ {state_dir}/wg/ -- WireGuard state
19
+ {state_dir}/inventory.db -- inventory database
20
+ {state_dir}/runs/ -- execution logs
21
+
22
+ This allows full isolation between production and test/CI contexts with a
23
+ single environment variable.
24
+
25
+ Priority order (highest to lowest):
26
+
27
+ 1. Explicit field values (``ssh_conf_d_base=...``, ``wg_state_base=...``)
28
+ 2. ``state_dir`` (either from ``LOFT_CLI_STATE_DIR`` env var or explicit)
29
+ 3. Built-in defaults (``~/.ssh/conf.d/loft-cli/``, etc.)
30
+
31
+ Commercial clones or multi-environment addons can override these paths
32
+ **without modifying any core source file** by registering a
33
+ ``LocalPathsConfig`` in their ``register()`` function:
34
+
35
+ from loft_cli_core.registry.local_paths import register_local_paths, LocalPathsConfig
36
+ from pathlib import Path
37
+
38
+ def register():
39
+ register_local_paths(LocalPathsConfig(
40
+ ssh_conf_d_base=Path("~/.ssh/conf.d/mycompany/prod/").expanduser(),
41
+ wg_state_base=Path("~/.wg/mycompany/prod/").expanduser(),
42
+ ))
43
+
44
+ Semantics: last registration wins. Core calls ``register_local_paths``
45
+ once (via ``_builtins._register_builtins``) to set the defaults; addons
46
+ loaded afterward simply replace the config object.
47
+
48
+ Planned: ``loft-cli doctor`` will display the active paths so operators
49
+ always know exactly where their local state lives.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import os
55
+ from dataclasses import dataclass, field
56
+ from pathlib import Path
57
+
58
+ # Sentinel object to distinguish "not provided" from None/explicit values.
59
+ _UNSET: Path = Path("__UNSET__")
60
+
61
+
62
+ def _default_state_dir() -> Path | None:
63
+ """Read LOFT_CLI_STATE_DIR from environment, or return None."""
64
+ val = os.environ.get("LOFT_CLI_STATE_DIR")
65
+ if val:
66
+ return Path(val)
67
+ return None
68
+
69
+
70
+ @dataclass
71
+ class LocalPathsConfig:
72
+ """Filesystem base directories for loft-cli local state.
73
+
74
+ Attributes
75
+ ----------
76
+ state_dir:
77
+ When set, all other paths are derived from this base directory
78
+ unless explicitly overridden. Read from ``LOFT_CLI_STATE_DIR``
79
+ environment variable by default, or passed explicitly.
80
+
81
+ ssh_conf_d_base:
82
+ Directory that contains per-host SSH config fragments.
83
+ Core appends ``{host_name}.conf`` to form the final path.
84
+ The ``Include`` directive written to ``~/.ssh/config`` will be
85
+ ``Include {ssh_conf_d_base}/*``, so all fragments in the directory
86
+ are covered by a single glob -- no per-file Include management needed.
87
+
88
+ wg_state_base:
89
+ Directory under which per-host WireGuard state is stored.
90
+ Core appends ``{host_name}/`` to form the per-host directory, then
91
+ writes ``private.key``, ``public.key``, ``wg0.conf``,
92
+ ``client.key``, ``client.conf``, and ``metadata.json`` inside it.
93
+
94
+ inventory_db_path:
95
+ Path to the SQLite inventory database file.
96
+
97
+ log_dir:
98
+ Directory for JSON apply execution logs.
99
+ """
100
+
101
+ state_dir: Path | None = field(default_factory=_default_state_dir)
102
+ # Use _UNSET sentinel so __post_init__ can distinguish "not provided"
103
+ # from an explicit value.
104
+ ssh_conf_d_base: Path = field(default_factory=lambda: _UNSET)
105
+ wg_state_base: Path = field(default_factory=lambda: _UNSET)
106
+ inventory_db_path: Path = field(default_factory=lambda: _UNSET)
107
+ log_dir: Path = field(default_factory=lambda: _UNSET)
108
+
109
+ def __post_init__(self) -> None:
110
+ """Fill unset paths from state_dir or built-in defaults."""
111
+ if self.ssh_conf_d_base is _UNSET:
112
+ self.ssh_conf_d_base = (
113
+ (self.state_dir / "ssh" / "conf.d")
114
+ if self.state_dir
115
+ else Path("~/.ssh/conf.d/loft-cli").expanduser()
116
+ )
117
+ if self.wg_state_base is _UNSET:
118
+ self.wg_state_base = (
119
+ (self.state_dir / "wg") if self.state_dir else Path("~/.wg/loft-cli").expanduser()
120
+ )
121
+ if self.inventory_db_path is _UNSET:
122
+ self.inventory_db_path = (
123
+ (self.state_dir / "inventory.db")
124
+ if self.state_dir
125
+ else Path("~/.loft-cli/inventory.db").expanduser()
126
+ )
127
+ if self.log_dir is _UNSET:
128
+ self.log_dir = (
129
+ (self.state_dir / "runs")
130
+ if self.state_dir
131
+ else Path("~/.loft-cli/runs").expanduser()
132
+ )
133
+
134
+
135
+ # Module-level singleton -- replaced wholesale on each call to register_local_paths().
136
+ _config: LocalPathsConfig = LocalPathsConfig()
137
+
138
+
139
+ def register_local_paths(config: LocalPathsConfig) -> None:
140
+ """Replace the active local paths config (last registration wins)."""
141
+ global _config
142
+ _config = config
143
+
144
+
145
+ def get_local_paths() -> LocalPathsConfig:
146
+ """Return the currently active local paths config."""
147
+ return _config
@@ -0,0 +1,21 @@
1
+ """Normalizer registry: maps kind strings to normalizer callables.
2
+
3
+ A normalizer callable has the signature:
4
+ (spec: AnySpec, ctx: NormalizedContext) -> None
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+
11
+ _NORMALIZER_REGISTRY: dict[str, Callable] = {}
12
+
13
+
14
+ def register_normalizer(kind: str, fn: Callable) -> None:
15
+ """Register a normalizer function for a spec kind."""
16
+ _NORMALIZER_REGISTRY[kind] = fn
17
+
18
+
19
+ def get_normalizer(kind: str) -> Callable | None:
20
+ """Return the normalizer for a kind, or None if not registered."""
21
+ return _NORMALIZER_REGISTRY.get(kind)
@@ -0,0 +1,21 @@
1
+ """Planner registry: maps kind strings to plan-builder callables.
2
+
3
+ A planner callable has the signature:
4
+ (spec: AnySpec, ctx: NormalizedContext) -> list[Step]
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+
11
+ _PLANNER_REGISTRY: dict[str, Callable] = {}
12
+
13
+
14
+ def register_planner(kind: str, fn: Callable) -> None:
15
+ """Register a plan-builder function for a spec kind."""
16
+ _PLANNER_REGISTRY[kind] = fn
17
+
18
+
19
+ def get_planner(kind: str) -> Callable | None:
20
+ """Return the plan-builder for a kind, or None if not registered."""
21
+ return _PLANNER_REGISTRY.get(kind)
@@ -0,0 +1,65 @@
1
+ """Value resolver registry: maps prefix strings to resolution backends.
2
+
3
+ A resolver callable has the signature:
4
+
5
+ (key: str) -> str | None
6
+
7
+ Returns the resolved string value, or ``None`` if the key was not found /
8
+ is unset. The caller (``_resolve_values`` in ``specs/loader.py``) is
9
+ responsible for handling the ``None`` case — applying the default value
10
+ if provided, raising a ``SpecLoadError`` in strict mode, or leaving the
11
+ ``${...}`` token unchanged in passthrough mode.
12
+
13
+ Built-in resolvers registered at startup by ``_builtins._register_resolvers()``:
14
+
15
+ * ``env`` — looks up ``os.environ`` (identical behaviour to the original
16
+ ``${VAR}`` syntax; bare ``${VAR}`` without a prefix is permanent shorthand
17
+ for ``${env:VAR}``)
18
+ * ``file`` — reads the file at the given path and returns its contents with
19
+ a single trailing newline stripped. Paths are resolved relative to the
20
+ current working directory; ``~`` is expanded.
21
+
22
+ External addons register additional resolvers (e.g. ``sops``, ``vault``) the
23
+ same way they register all other extensions — via a ``register()`` function
24
+ declared as a ``loft_cli.addons`` entry point:
25
+
26
+ from loft_cli_core.registry import register_resolver
27
+
28
+ def register():
29
+ register_resolver("sops", _resolve_sops)
30
+
31
+ def _resolve_sops(key: str) -> str | None:
32
+ # key format: "path/to/secrets.yaml#json.dot.path"
33
+ ...
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from collections.abc import Callable
39
+
40
+ _RESOLVER_REGISTRY: dict[str, Callable[[str], str | None]] = {}
41
+
42
+
43
+ def register_resolver(prefix: str, fn: Callable[[str], str | None]) -> None:
44
+ """Register a value resolver for the given prefix string.
45
+
46
+ Parameters
47
+ ----------
48
+ prefix:
49
+ The prefix used inside ``${prefix:key}`` tokens in spec files.
50
+ Registering an existing prefix replaces the previous resolver.
51
+ fn:
52
+ Callable with signature ``(key: str) -> str | None``.
53
+ Return the resolved string value, or ``None`` if not found.
54
+ """
55
+ _RESOLVER_REGISTRY[prefix] = fn
56
+
57
+
58
+ def get_resolver(prefix: str) -> Callable[[str], str | None] | None:
59
+ """Return the resolver for the given prefix, or ``None`` if not registered."""
60
+ return _RESOLVER_REGISTRY.get(prefix)
61
+
62
+
63
+ def list_resolvers() -> list[str]:
64
+ """Return a sorted list of all registered resolver prefixes."""
65
+ return sorted(_RESOLVER_REGISTRY.keys())
@@ -0,0 +1,20 @@
1
+ """Spec kind registry: maps kind strings to Pydantic model classes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ _SPEC_REGISTRY: dict[str, type] = {}
6
+
7
+
8
+ def register_spec_kind(kind: str, model_class: type) -> None:
9
+ """Register a spec kind and its Pydantic model class."""
10
+ _SPEC_REGISTRY[kind] = model_class
11
+
12
+
13
+ def get_spec_model(kind: str) -> type | None:
14
+ """Return the model class for a given kind, or None if not registered."""
15
+ return _SPEC_REGISTRY.get(kind)
16
+
17
+
18
+ def list_spec_kinds() -> list[str]:
19
+ """Return all registered spec kind names."""
20
+ return list(_SPEC_REGISTRY.keys())