Less stack-centric and location-centric model.

This commit is contained in:
2026-06-13 17:26:49 -07:00
parent 7bf98c17b7
commit 400e0b253b
33 changed files with 1112 additions and 408 deletions

View File

@@ -27,6 +27,9 @@ class ComponentSummary(BaseModel):
systemd: SystemdInfo | None = None
version: str | None = None
source: str | None = None
repo: str | None = None
ref: str | None = None
commands: dict[str, list[list[str]]] | None = None
system_dependencies: list[str] = []
schedule: str | None = None
installed: bool | None = None
@@ -91,6 +94,9 @@ class ProgramSummary(BaseModel):
runner: str | None = None
version: str | None = None
source: str | None = None
repo: str | None = None
ref: str | None = None
commands: dict[str, list[list[str]]] | None = None
system_dependencies: list[str] = []
installed: bool | None = None
actions: list[str] = []

View File

@@ -66,7 +66,6 @@ def _deployed_to_summaries(registry: object, hostname: str) -> list[ComponentSum
def get_mesh_status(request: Request) -> MeshStatus:
"""Get the current state of the mesh coordination layer."""
mqtt_client = getattr(request.app.state, "mqtt_client", None)
mdns = getattr(request.app.state, "mdns", None)
peers = list(mesh_state.all_nodes(include_stale=True).keys())

View File

@@ -4,7 +4,7 @@ from __future__ import annotations
from fastapi import APIRouter, HTTPException, status
from castle_core.stacks import available_actions, get_handler
from castle_core.stacks import available_actions, run_action
from castle_api.config import get_config
@@ -27,7 +27,11 @@ _VALID_ACTIONS = {
@programs_router.post("/programs/{name}/{action}")
async def program_action(name: str, action: str) -> dict:
"""Run a lifecycle action on a program via its stack handler."""
"""Run a lifecycle action on a program.
Resolution-aware: a declared `commands:` entry overrides the stack default,
so a program with no stack can still be linted/tested/built/installed.
"""
if action not in _VALID_ACTIONS:
raise HTTPException(status_code=400, detail=f"Unknown action: {action}")
@@ -41,24 +45,14 @@ async def program_action(name: str, action: str) -> dict:
if not comp.source:
raise HTTPException(status_code=400, detail=f"'{name}' has no source directory")
actions = available_actions(comp)
if action not in actions:
if action not in available_actions(comp):
raise HTTPException(
status_code=400,
detail=f"Action '{action}' not available for '{name}' (stack: {comp.stack})",
detail=f"Action '{action}' not available for '{name}' "
f"(no declared command and no stack handler provides it)",
)
handler = get_handler(comp.stack)
if handler is None:
raise HTTPException(
status_code=400, detail=f"No handler for stack '{comp.stack}'"
)
# Map hyphenated action names to method names (type-check → type_check)
method_name = action.replace("-", "_")
method = getattr(handler, method_name)
result = await method(name, comp, config.root)
result = await run_action(action, name, comp, config.root)
if result.status != "ok":
raise HTTPException(status_code=500, detail=result.output or f"{action} failed")

View File

@@ -34,6 +34,19 @@ from castle_api.models import (
router = APIRouter(tags=["dashboard"])
def _declared_commands_dict(comp: ProgramSpec) -> dict[str, list[list[str]]] | None:
"""Serialize a program's declared verbs for the API (build + CommandsSpec)."""
out: dict[str, list[list[str]]] = {}
if comp.build and comp.build.commands:
out["build"] = comp.build.commands
if comp.commands is not None:
for verb in ("lint", "test", "type-check", "check", "run", "install", "uninstall"):
cmds = comp.commands.for_verb(verb)
if cmds:
out[verb] = cmds
return out or None
def _summary_from_deployed(name: str, deployed: object) -> ComponentSummary:
"""Build a ComponentSummary from a DeployedComponent."""
managed = deployed.managed
@@ -172,7 +185,7 @@ def _summary_from_program(name: str, comp: ProgramSpec, root: Path) -> Component
runner = "command"
installed: bool | None = None
if comp.source and comp.stack:
if comp.source and (comp.stack or comp.commands):
installed = shutil.which(name) is not None
return ComponentSummary(
@@ -184,6 +197,9 @@ def _summary_from_program(name: str, comp: ProgramSpec, root: Path) -> Component
runner=runner,
version=comp.version,
source=source,
repo=comp.repo,
ref=comp.ref,
commands=_declared_commands_dict(comp),
system_dependencies=comp.system_dependencies,
installed=installed,
)
@@ -323,7 +339,7 @@ def _program_from_spec(
runner = "command"
installed: bool | None = None
if comp.source and comp.stack:
if comp.source and (comp.stack or comp.commands):
installed = shutil.which(name) is not None
return ProgramSummary(
@@ -334,6 +350,9 @@ def _program_from_spec(
runner=runner,
version=comp.version,
source=source,
repo=comp.repo,
ref=comp.ref,
commands=_declared_commands_dict(comp),
system_dependencies=comp.system_dependencies,
installed=installed,
actions=available_actions(comp),

View File

@@ -36,6 +36,17 @@ def castle_root(tmp_path: Path) -> Generator[Path, None, None]:
"behavior": "tool",
"version": "2.0.0",
},
"wired-in": {
"description": "Adopted repo, no stack",
"source": "wired-in",
"behavior": "tool",
"repo": "https://github.com/someone/wired-in.git",
"commands": {
"lint": [["make", "lint"]],
"test": [["make", "test"]],
"run": [["./bin/wired-in"]],
},
},
},
"services": {
"test-svc": {

View File

@@ -0,0 +1,32 @@
"""Tests for the new per-program commands/repo fields on the programs API."""
from fastapi.testclient import TestClient
class TestProgramCommands:
def test_wired_in_program_surfaces_commands_and_repo(self, client: TestClient) -> None:
"""A stack-less adopted program exposes its declared commands + repo."""
resp = client.get("/programs")
assert resp.status_code == 200
progs = {p["id"]: p for p in resp.json()}
assert "wired-in" in progs
w = progs["wired-in"]
assert w["stack"] is None
assert w["repo"] == "https://github.com/someone/wired-in.git"
assert w["commands"]["lint"] == [["make", "lint"]]
assert w["commands"]["run"] == [["./bin/wired-in"]]
def test_wired_in_actions_resolved_from_commands(self, client: TestClient) -> None:
"""available actions come from declared commands when there's no stack."""
resp = client.get("/programs")
w = next(p for p in resp.json() if p["id"] == "wired-in")
# declared lint/test/run + the composite check (lint/test available)
assert set(w["actions"]) >= {"lint", "test", "run"}
assert "build" not in w["actions"] # not declared, no stack
def test_tools_via_behavior_filter(self, client: TestClient) -> None:
"""Tools are reached via /programs?behavior=tool (no dedicated /tools)."""
resp = client.get("/programs", params={"behavior": "tool"})
assert resp.status_code == 200
ids = [p["id"] for p in resp.json()]
assert "wired-in" in ids and "test-tool" in ids

View File

@@ -1,78 +0,0 @@
"""Tests for tools endpoints."""
from fastapi.testclient import TestClient
class TestToolsList:
"""GET /tools endpoint tests."""
def test_returns_flat_list(self, client: TestClient) -> None:
"""Returns tools as a flat sorted list."""
response = client.get("/tools")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
ids = [t["id"] for t in data]
assert "test-tool" in ids
assert "test-tool-2" in ids
def test_sorted_alphabetically(self, client: TestClient) -> None:
"""Tools are sorted alphabetically by id."""
response = client.get("/tools")
data = response.json()
ids = [t["id"] for t in data]
assert ids == sorted(ids)
def test_tool_fields(self, client: TestClient) -> None:
"""Tool summary has expected fields."""
response = client.get("/tools")
data = response.json()
tool = next(t for t in data if t["id"] == "test-tool")
assert tool["description"] == "Test tool"
assert tool["source"].endswith("/test-tool")
assert tool["system_dependencies"] == ["pandoc"]
def test_installed_flag(self, client: TestClient) -> None:
"""Tool installed field reflects whether binary is on PATH."""
response = client.get("/tools")
data = response.json()
tool = next(t for t in data if t["id"] == "test-tool")
# test-tool binary won't be on PATH in test env
assert isinstance(tool["installed"], bool)
def test_service_excluded(self, client: TestClient) -> None:
"""Services without tool spec are not listed."""
response = client.get("/tools")
data = response.json()
all_ids = [t["id"] for t in data]
assert "test-svc" not in all_ids
class TestToolDetail:
"""GET /tools/{name} endpoint tests."""
def test_get_tool(self, client: TestClient) -> None:
"""Returns detail for a known tool."""
response = client.get("/tools/test-tool")
assert response.status_code == 200
data = response.json()
assert data["id"] == "test-tool"
assert data["source"].endswith("/test-tool")
assert data["system_dependencies"] == ["pandoc"]
def test_no_docs(self, client: TestClient) -> None:
"""Tool detail returns null docs (no .md files anymore)."""
response = client.get("/tools/test-tool")
assert response.status_code == 200
data = response.json()
assert data["docs"] is None
def test_not_found(self, client: TestClient) -> None:
"""Returns 404 for unknown component."""
response = client.get("/tools/nonexistent")
assert response.status_code == 404
def test_not_a_tool(self, client: TestClient) -> None:
"""Returns 404 for component that is not a tool."""
response = client.get("/tools/test-svc")
assert response.status_code == 404