refactor: Align vocabulary — component → program / deployment

Canonical terms (see docs/registry.md glossary):
- program: any catalog entry (tool/daemon/frontend) — the software
- service / job: how a program is deployed (systemd .service / .timer)
- deployment: umbrella for the unified service+job+program view

Changes:
- core: ServiceSpec/JobSpec component: → program: (component accepted as
  back-compat validation_alias); DeployedComponent → Deployment.
- api: ComponentSummary/Detail → DeploymentSummary/Detail; GET /components
  → /deployments; GatewayRoute.component → program; GatewayInfo
  .component_count → deployment_count; ServiceActionResponse/action keys
  component → program.
- app: matching type renames, /components → /deployments hook, route
  /component/:name → /deployment/:name, GatewayRoute.program.
- docs: component-registry.md → registry.md (+ canonical glossary);
  CLAUDE.md endpoint list refreshed (drop removed /tools, add typed
  program/service/job + config routes).

Tests: core 92, cli 24, api 52 green; app build clean; ruff clean.
This commit is contained in:
2026-06-14 11:05:22 -07:00
parent 482524bfe5
commit 3f3b88f17b
44 changed files with 279 additions and 237 deletions

View File

@@ -252,7 +252,7 @@ def _expand_units(
services[name] = ServiceSpec(
id=name,
component=name,
program=name,
run=run_spec,
expose=ExposeSpec(
http=HttpExposeSpec(
@@ -272,7 +272,7 @@ def _expand_units(
assert unit.argv is not None # guaranteed by validator
jobs[name] = JobSpec(
id=name,
component=name,
program=name,
description=unit.description,
run=RunCommand(runner="command", argv=list(unit.argv)),
schedule=unit.schedule,

View File

@@ -1,7 +1,7 @@
"""Deploy logic — bridge castle.yaml spec to runtime (~/.castle/).
This module contains the core deploy logic shared by the CLI and API.
It reads castle.yaml, resolves services/jobs into DeployedComponents,
It reads castle.yaml, resolves services/jobs into Deployments,
writes the registry, generates systemd units and the Caddyfile, and
copies frontend build outputs.
"""
@@ -31,7 +31,7 @@ from castle_core.generators.systemd import (
from castle_core.manifest import JobSpec, ServiceSpec
from castle_core.registry import (
REGISTRY_PATH,
DeployedComponent,
Deployment,
NodeConfig,
NodeRegistry,
load_registry,
@@ -139,21 +139,21 @@ def _resolve_description(config: CastleConfig, spec: ServiceSpec | JobSpec) -> s
"""Get description, falling through to program if referenced."""
if spec.description:
return spec.description
if spec.component and spec.component in config.programs:
return config.programs[spec.component].description
if spec.program and spec.program in config.programs:
return config.programs[spec.program].description
return None
def _build_deployed_service(
config: CastleConfig, name: str, svc: ServiceSpec, messages: list[str]
) -> DeployedComponent:
"""Build a DeployedComponent from a ServiceSpec."""
) -> Deployment:
"""Build a Deployment from a ServiceSpec."""
run = svc.run
# Env prefix and data dir are keyed by the program (component) the service
# runs, not the service name — that's the prefix the program's settings read
# (e.g. job `protonmail-sync` runs program `protonmail` → PROTONMAIL_DATA_DIR).
# Falls back to the service name when no component is referenced.
config_key = svc.component or name
config_key = svc.program or name
prefix = _env_prefix(config_key)
env: dict[str, str] = {}
@@ -182,7 +182,7 @@ def _build_deployed_service(
env = resolve_env_vars(env)
# Ensure python tool is installed before resolving binary
_ensure_python_tool(config, svc.component, messages)
_ensure_python_tool(config, svc.program, messages)
# Build run_cmd
run_cmd = _build_run_cmd(name, run, env, messages)
@@ -194,13 +194,13 @@ def _build_deployed_service(
# Resolve stack from referenced program
stack = None
if svc.component and svc.component in config.programs:
stack = config.programs[svc.component].stack
if svc.program and svc.program in config.programs:
stack = config.programs[svc.program].stack
# Remote services proxy to an external base_url
base_url = getattr(run, "base_url", None)
return DeployedComponent(
return Deployment(
runner=run.runner,
run_cmd=run_cmd,
env=env,
@@ -217,12 +217,12 @@ def _build_deployed_service(
def _build_deployed_job(
config: CastleConfig, name: str, job: JobSpec, messages: list[str]
) -> DeployedComponent:
"""Build a DeployedComponent from a JobSpec."""
) -> Deployment:
"""Build a Deployment from a JobSpec."""
run = job.run
# Keyed by the program (component) the job runs, not the job name — see
# _build_deployed_service for rationale. Falls back to the job name.
config_key = job.component or name
config_key = job.program or name
prefix = _env_prefix(config_key)
env: dict[str, str] = {}
@@ -232,14 +232,14 @@ def _build_deployed_job(
env.update(job.defaults.env)
env = resolve_env_vars(env)
_ensure_python_tool(config, job.component, messages)
_ensure_python_tool(config, job.program, messages)
run_cmd = _build_run_cmd(name, run, env, messages)
stack = None
if job.component and job.component in config.programs:
stack = config.programs[job.component].stack
if job.program and job.program in config.programs:
stack = config.programs[job.program].stack
return DeployedComponent(
return Deployment(
runner=run.runner,
run_cmd=run_cmd,
env=env,
@@ -273,33 +273,33 @@ def _python_tool_needs_install(program: str) -> bool:
def _ensure_python_tool(
config: CastleConfig, component: str | None, messages: list[str]
config: CastleConfig, program: str | None, messages: list[str]
) -> None:
"""Ensure a Python program's editable install is current."""
if not component or component not in config.programs:
if not program or program not in config.programs:
return
comp = config.programs[component]
comp = config.programs[program]
if not comp.source or not comp.stack or not comp.stack.startswith("python"):
return
source_dir = Path(comp.source)
if not source_dir.is_dir():
messages.append(f"Warning: source not found: {source_dir}")
return
if not _python_tool_needs_install(component):
if not _python_tool_needs_install(program):
return
pkg_spec = str(source_dir)
if comp.install_extras:
pkg_spec += "[" + ",".join(comp.install_extras) + "]"
messages.append(f"Installing {component} from {source_dir}...")
messages.append(f"Installing {program} from {source_dir}...")
result = subprocess.run(
["uv", "tool", "install", "--editable", pkg_spec, "--force"],
capture_output=True,
text=True,
)
if result.returncode != 0:
messages.append(f"Error: {component} install failed:\n{result.stdout}{result.stderr}")
messages.append(f"Error: {program} install failed:\n{result.stdout}{result.stderr}")
else:
messages.append(f"Installed {component}")
messages.append(f"Installed {program}")
def _build_run_cmd(name: str, run: object, env: dict[str, str], messages: list[str]) -> list[str]:
@@ -354,7 +354,7 @@ def _build_run_cmd(name: str, run: object, env: dict[str, str], messages: list[s
raise ValueError(f"Unsupported runner: {run.runner}") # type: ignore[union-attr]
def _format_deployed(name: str, deployed: DeployedComponent) -> str:
def _format_deployed(name: str, deployed: Deployment) -> str:
"""Format deployment summary for a component."""
parts = [name]
if deployed.port:

View File

@@ -6,7 +6,7 @@ import shutil
from pathlib import Path
from castle_core.manifest import RestartPolicy, SystemdSpec
from castle_core.registry import DeployedComponent
from castle_core.registry import Deployment
SYSTEMD_USER_DIR = Path.home() / ".config" / "systemd" / "user"
UNIT_PREFIX = "castle-"
@@ -74,7 +74,7 @@ def cron_to_interval_sec(cron: str) -> int | None:
def generate_unit_from_deployed(
name: str,
deployed: DeployedComponent,
deployed: Deployment,
systemd_spec: SystemdSpec | None = None,
) -> str:
"""Generate a systemd unit from a deployed component (registry-based).

View File

@@ -5,7 +5,7 @@ from __future__ import annotations
from enum import Enum
from typing import Annotated, Literal, Union
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
EnvMap = dict[str, str]
@@ -247,8 +247,13 @@ class ProgramSpec(BaseModel):
class ServiceSpec(BaseModel):
"""Long-running daemon deployment config."""
model_config = ConfigDict(populate_by_name=True)
id: str = ""
component: str | None = None
# The program this service deploys. (`component` accepted as a legacy alias.)
program: str | None = Field(
default=None, validation_alias=AliasChoices("program", "component")
)
description: str | None = None
run: RunSpec
@@ -274,8 +279,13 @@ class ServiceSpec(BaseModel):
class JobSpec(BaseModel):
"""Scheduled task that runs periodically and exits."""
model_config = ConfigDict(populate_by_name=True)
id: str = ""
component: str | None = None
# The program this job runs. (`component` accepted as a legacy alias.)
program: str | None = Field(
default=None, validation_alias=AliasChoices("program", "component")
)
description: str | None = None
run: RunSpec

View File

@@ -28,7 +28,7 @@ class NodeConfig:
@dataclass
class DeployedComponent:
class Deployment:
"""A component deployed on this node with resolved runtime config."""
runner: str
@@ -50,7 +50,7 @@ class NodeRegistry:
"""What's deployed on this node."""
node: NodeConfig
deployed: dict[str, DeployedComponent] = field(default_factory=dict)
deployed: dict[str, Deployment] = field(default_factory=dict)
def load_registry(path: Path | None = None) -> NodeRegistry:
@@ -77,7 +77,7 @@ def load_registry(path: Path | None = None) -> NodeRegistry:
gateway_port=node_data.get("gateway_port", 9000),
)
deployed: dict[str, DeployedComponent] = {}
deployed: dict[str, Deployment] = {}
for name, comp_data in data.get("deployed", {}).items():
# Support both old "category" and new "behavior" keys for migration
behavior = comp_data.get("behavior")
@@ -92,7 +92,7 @@ def load_registry(path: Path | None = None) -> NodeRegistry:
if category == "frontend"
else category
)
deployed[name] = DeployedComponent(
deployed[name] = Deployment(
runner=comp_data.get("runner", "command"),
run_cmd=comp_data.get("run_cmd", []),
env=comp_data.get("env", {}),

View File

@@ -28,9 +28,9 @@ _EXTRA_PATH_DIRS = [
@dataclass
class ActionResult:
"""Result of a stack lifecycle action."""
"""Result of a program lifecycle action."""
component: str
program: str
action: str
status: str # "ok" | "error"
output: str = ""
@@ -90,12 +90,12 @@ class StackHandler:
result = await action_fn(name, comp, root)
if result.status != "ok":
return ActionResult(
component=name,
program=name,
action="check",
status="error",
output=f"{action_name} failed:\n{result.output}",
)
return ActionResult(component=name, action="check", status="ok")
return ActionResult(program=name, action="check", status="ok")
async def install(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
raise NotImplementedError
@@ -111,33 +111,33 @@ class PythonHandler(StackHandler):
src = _source_dir(comp, root)
rc, output = await _run(["uv", "sync"], src)
return ActionResult(
component=name, action="build", status="ok" if rc == 0 else "error", output=output
program=name, action="build", status="ok" if rc == 0 else "error", output=output
)
async def test(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
if not (src / "tests").exists():
return ActionResult(
component=name, action="test", status="ok",
program=name, action="test", status="ok",
output="No tests directory found, skipping.",
)
rc, output = await _run(["uv", "run", "pytest", "tests/", "-v"], src)
return ActionResult(
component=name, action="test", status="ok" if rc == 0 else "error", output=output
program=name, action="test", status="ok" if rc == 0 else "error", output=output
)
async def lint(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
rc, output = await _run(["uv", "run", "ruff", "check", "."], src)
return ActionResult(
component=name, action="lint", status="ok" if rc == 0 else "error", output=output
program=name, action="lint", status="ok" if rc == 0 else "error", output=output
)
async def type_check(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
rc, output = await _run(["uv", "run", "pyright"], src)
return ActionResult(
component=name, action="type-check", status="ok" if rc == 0 else "error", output=output
program=name, action="type-check", status="ok" if rc == 0 else "error", output=output
)
async def install(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
@@ -149,7 +149,7 @@ class PythonHandler(StackHandler):
["uv", "tool", "install", "--editable", pkg_spec, "--force"], src
)
return ActionResult(
component=name, action="install", status="ok" if rc == 0 else "error", output=output
program=name, action="install", status="ok" if rc == 0 else "error", output=output
)
async def uninstall(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
@@ -162,7 +162,7 @@ class PythonHandler(StackHandler):
pkg_name = data.get("project", {}).get("name", pkg_name)
rc, output = await _run(["uv", "tool", "uninstall", pkg_name], src)
return ActionResult(
component=name, action="uninstall", status="ok" if rc == 0 else "error", output=output
program=name, action="uninstall", status="ok" if rc == 0 else "error", output=output
)
@@ -173,28 +173,28 @@ class ReactViteHandler(StackHandler):
src = _source_dir(comp, root)
rc, output = await _run(["pnpm", "build"], src)
return ActionResult(
component=name, action="build", status="ok" if rc == 0 else "error", output=output
program=name, action="build", status="ok" if rc == 0 else "error", output=output
)
async def test(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
rc, output = await _run(["pnpm", "test"], src)
return ActionResult(
component=name, action="test", status="ok" if rc == 0 else "error", output=output
program=name, action="test", status="ok" if rc == 0 else "error", output=output
)
async def lint(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
rc, output = await _run(["pnpm", "lint"], src)
return ActionResult(
component=name, action="lint", status="ok" if rc == 0 else "error", output=output
program=name, action="lint", status="ok" if rc == 0 else "error", output=output
)
async def type_check(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
src = _source_dir(comp, root)
rc, output = await _run(["pnpm", "type-check"], src)
return ActionResult(
component=name, action="type-check", status="ok" if rc == 0 else "error", output=output
program=name, action="type-check", status="ok" if rc == 0 else "error", output=output
)
async def install(self, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
@@ -203,18 +203,18 @@ class ReactViteHandler(StackHandler):
result = await self.build(name, comp, root)
if result.status != "ok":
return ActionResult(
component=name, action="install", status="error",
program=name, action="install", status="error",
output=f"Build failed:\n{result.output}",
)
outputs = comp.build.outputs if comp.build else []
if not outputs:
return ActionResult(
component=name, action="install", status="error",
program=name, action="install", status="error",
output="No build outputs configured.",
)
dist = _source_dir(comp, root) / outputs[0]
return ActionResult(
component=name, action="install", status="ok",
program=name, action="install", status="ok",
output=f"Built; served in place from {dist}",
)
@@ -224,7 +224,7 @@ class ReactViteHandler(StackHandler):
Deactivating one means dropping its gateway route — handled by removing the
program from the registry, not by deleting build output."""
return ActionResult(
component=name, action="uninstall", status="ok",
program=name, action="uninstall", status="ok",
output=f"{name}: served in place; nothing to uninstall.",
)
@@ -287,8 +287,8 @@ async def _run_declared(
rc, output = await _run(argv, src)
outputs.append(output)
if rc != 0:
return ActionResult(component=name, action=verb, status="error", output="".join(outputs))
return ActionResult(component=name, action=verb, status="ok", output="".join(outputs))
return ActionResult(program=name, action=verb, status="error", output="".join(outputs))
return ActionResult(program=name, action=verb, status="ok", output="".join(outputs))
async def run_action(verb: str, name: str, comp: ProgramSpec, root: Path) -> ActionResult:
@@ -303,17 +303,17 @@ async def run_action(verb: str, name: str, comp: ProgramSpec, root: Path) -> Act
subs = [s for s in ("lint", "type-check", "test") if is_available(comp, s)]
if not subs:
return ActionResult(
component=name, action="check", status="error",
program=name, action="check", status="error",
output="No checkable verbs available.",
)
for sub in subs:
result = await run_action(sub, name, comp, root)
if result.status != "ok":
return ActionResult(
component=name, action="check", status="error",
program=name, action="check", status="error",
output=f"{sub} failed:\n{result.output}",
)
return ActionResult(component=name, action="check", status="ok")
return ActionResult(program=name, action="check", status="ok")
# 1. Declared command overrides the stack default.
declared = _declared_commands(comp, verb)
@@ -321,7 +321,7 @@ async def run_action(verb: str, name: str, comp: ProgramSpec, root: Path) -> Act
try:
src = _source_dir(comp, root)
except ValueError:
return ActionResult(component=name, action=verb, status="error", output="No source directory")
return ActionResult(program=name, action=verb, status="error", output="No source directory")
return await _run_declared(name, verb, declared, src)
# 2. Stack default.
@@ -333,7 +333,7 @@ async def run_action(verb: str, name: str, comp: ProgramSpec, root: Path) -> Act
# 3. Unavailable.
return ActionResult(
component=name, action=verb, status="error",
program=name, action=verb, status="error",
output=f"Verb '{verb}' is not available for '{name}' "
f"(no declared command and no stack handler provides it).",
)