Coverage for src/governed_harness/runtime/state_location.py: 77%
109 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Where a project's run registry lives (``runtime.stateDir``, since 2.0, #55).
3In 1.0.0 the state database and the artifact store live in the workspace's ``.harness/``: an
4agent with write access to the workspace could reach them (only the sandbox and the excluded
5path guard stood in the way), a workspace cleanup deleted the record, and every repository had
6its own dashboard. With ``runtime.stateDir`` the registry moves out of the workspace:
8* ``auto``: ``$HARNESS_STATE_DIR``, else ``$XDG_DATA_HOME/governed-harness/state``, else the
9 platform's application-data directory (``~/Library/Application Support`` on macOS,
10 ``%LOCALAPPDATA%`` on Windows, ``~/.local/share`` elsewhere);
11* an absolute path, or one that starts with ``~/``, used as given.
13Each project gets one directory there, named after its id and a digest of the repository it
14belongs to (the Git common directory, so every worktree of a repository shares it), holding
15``state.db``, ``artifacts/`` and ``registry.json`` (the project id and the workspace path, read
16by the dashboard to list the runs of several repositories). The workspace keeps ``.harness/``
17for the configuration, the lease, caches and scratch copies.
19A worktree the harness created for an isolated run (``workspace.isolation``) carries
20``.harness/isolation.json``, which names the registry of the workspace it was created from, so
21its runs are recorded where the person looks for them. Without ``stateDir`` and without that
22marker nothing changes: ``.harness/state.db`` and ``.harness/artifacts/``."""
24from __future__ import annotations
26import json
27import os
28import platform
29import re
30import subprocess # nosec B404 - git rev-parse with a fixed argv, no shell
31from dataclasses import dataclass
32from datetime import UTC, datetime
33from pathlib import Path
34from typing import Any
36from governed_harness.domain.errors import ConfigurationError
37from governed_harness.evidence.hashing import sha256_bytes
39STATE_DIR_ENV = "HARNESS_STATE_DIR"
40ISOLATION_MARKER = "isolation.json"
41REGISTRY_FILE = "registry.json"
42_DATABASE = "state.db"
43_SLUG = re.compile(r"[^a-z0-9_.-]+")
46def default_state_root() -> Path:
47 """The directory ``runtime.stateDir: auto`` resolves to."""
48 configured = os.environ.get(STATE_DIR_ENV)
49 if configured: 49 ↛ 51line 49 didn't jump to line 51 because the condition on line 49 was always true
50 return Path(configured).expanduser()
51 xdg = os.environ.get("XDG_DATA_HOME")
52 if xdg:
53 return Path(xdg) / "governed-harness" / "state"
54 home = Path.home()
55 system = platform.system()
56 if system == "Darwin":
57 return home / "Library" / "Application Support" / "governed-harness" / "state"
58 if system == "Windows":
59 base = os.environ.get("LOCALAPPDATA")
60 return (Path(base) if base else home) / "governed-harness" / "state"
61 return home / ".local" / "share" / "governed-harness" / "state"
64def configured_root(state_dir: str) -> Path:
65 """The base directory of a ``runtime.stateDir`` value (``auto`` or a path)."""
66 if state_dir == "auto":
67 return default_state_root()
68 return Path(state_dir).expanduser()
71def repository_identity(workspace: Path) -> Path:
72 """The Git common directory of ``workspace`` (shared by its worktrees), else the workspace
73 itself."""
74 try:
75 result = subprocess.run( # nosec B603 B607 - git from PATH, fixed argv, no shell
76 ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
77 cwd=workspace,
78 capture_output=True,
79 check=False,
80 timeout=30,
81 stdin=subprocess.DEVNULL,
82 env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
83 )
84 except (OSError, subprocess.SubprocessError):
85 return workspace.resolve()
86 value = result.stdout.decode("utf-8", "replace").strip()
87 if result.returncode != 0 or not value:
88 return workspace.resolve()
89 return Path(value).resolve()
92def project_key(project_id: str, identity: Path) -> str:
93 slug = _SLUG.sub("_", project_id.lower()).strip("_")[:60] or "project"
94 digest = sha256_bytes(str(identity).encode("utf-8")).removeprefix("sha256:")[:12]
95 return f"{slug}-{digest}"
98@dataclass(frozen=True)
99class StateLocation:
100 """Where the state database and the artifact store of a workspace are."""
102 root: Path
103 database: Path
104 artifacts: Path
105 external: bool
106 """The registry lives outside the workspace (``runtime.stateDir`` or an isolated run)."""
109def isolation_marker(workspace: Path) -> dict[str, Any] | None:
110 """The marker of a worktree the harness created, or ``None``."""
111 path = workspace / ".harness" / ISOLATION_MARKER
112 try:
113 value = json.loads(path.read_text(encoding="utf-8"))
114 except (OSError, ValueError):
115 return None
116 return value if isinstance(value, dict) and isinstance(value.get("stateRoot"), str) else None
119def resolve_state_location(
120 workspace: Path, project_id: str, state_dir: str | None, *, create: bool = True
121) -> StateLocation:
122 """The state location of ``workspace``: the registry its isolation marker names, else the
123 ``runtime.stateDir`` registry, else ``.harness/`` (1.0.0)."""
124 root_workspace = workspace.resolve()
125 marker = isolation_marker(root_workspace)
126 if marker is not None:
127 root = Path(marker["stateRoot"])
128 return StateLocation(root, root / _DATABASE, root / "artifacts", True)
129 if state_dir is None:
130 harness = root_workspace / ".harness"
131 return StateLocation(harness, harness / _DATABASE, harness / "artifacts", False)
132 identity = repository_identity(root_workspace)
133 root = configured_root(state_dir) / project_key(project_id, identity)
134 if create:
135 try:
136 root.mkdir(parents=True, exist_ok=True, mode=0o700)
137 except OSError as error:
138 raise ConfigurationError(
139 f"cannot create the run registry {root} (runtime.stateDir: {state_dir}): "
140 f"{error.strerror or error}; set {STATE_DIR_ENV} or runtime.stateDir to a "
141 "writable directory"
142 ) from error
143 _register(root, project_id, root_workspace, identity)
144 return StateLocation(root, root / _DATABASE, root / "artifacts", True)
147def _register(root: Path, project_id: str, workspace: Path, identity: Path) -> None:
148 """Write ``registry.json`` (project id, workspace) once per workspace path, so the dashboard
149 can list the runs of several repositories. A failure to write it never stops a command."""
150 path = root / REGISTRY_FILE
151 try:
152 current = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
153 except (OSError, ValueError):
154 current = {}
155 main = identity.parent if identity.name == ".git" else workspace
156 value = {
157 "schemaVersion": "1.0",
158 "projectId": project_id,
159 "workspace": str(main),
160 "stateRoot": str(root),
161 "registeredAt": current.get("registeredAt") or datetime.now(UTC).isoformat(),
162 }
163 if current == value:
164 return
165 try:
166 path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
167 except OSError:
168 return
171def registered_projects(state_root: Path | None = None) -> list[dict[str, Any]]:
172 """Every project registered under a state root (default: ``auto``), sorted by id."""
173 base = state_root or default_state_root()
174 found: list[dict[str, Any]] = []
175 if not base.is_dir(): 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 return found
177 for path in sorted(base.glob(f"*/{REGISTRY_FILE}")):
178 try:
179 value = json.loads(path.read_text(encoding="utf-8"))
180 except (OSError, ValueError):
181 continue
182 if isinstance(value, dict) and isinstance(value.get("projectId"), str): 182 ↛ 177line 182 didn't jump to line 177 because the condition on line 182 was always true
183 found.append({**value, "database": str(path.parent / _DATABASE)})
184 return sorted(found, key=lambda item: (item["projectId"], item.get("workspace", "")))
187__all__ = [
188 "ISOLATION_MARKER",
189 "STATE_DIR_ENV",
190 "StateLocation",
191 "configured_root",
192 "default_state_root",
193 "isolation_marker",
194 "project_key",
195 "registered_projects",
196 "repository_identity",
197 "resolve_state_location",
198]