Coverage for src/governed_harness/events/anchor.py: 77%
123 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"""Copies of the head of each run's event chain kept outside ``.harness`` (``governance.chainAnchor``).
3The event chain detects an edited or reordered event, but not a chain whose last events were
4deleted: the shorter chain is still well linked. An anchor records the sequence and digest of the
5head after every command that appended events; ``harness verify`` then checks that the chain still
6contains that event. Two places are supported:
8* ``file``: a JSON file per workspace under the user's data directory
9 (``$HARNESS_ANCHOR_DIR``, else ``$XDG_DATA_HOME/governed-harness/anchors``, else the platform's
10 application-data directory).
11* ``git-note``: a Git note on a blob named after the run, under ``refs/notes/governed-harness`` of
12 the workspace repository.
14Neither is tamper-proof: a process with the user's permissions can rewrite both. The anchor
15raises the cost of a silent truncation from editing one SQLite file to editing two places.
16"""
18from __future__ import annotations
20import json
21import os
22import platform
23import subprocess # nosec B404 - git notes with a fixed argv, no shell
24import tempfile
25from dataclasses import dataclass
26from datetime import UTC, datetime
27from pathlib import Path
28from typing import Literal
30from governed_harness.evidence.hashing import sha256_bytes
32AnchorMode = Literal["file", "git-note", "off"]
34ANCHOR_DIR_ENV = "HARNESS_ANCHOR_DIR"
35NOTES_REF = "refs/notes/governed-harness"
36_NOTE_IDENTITY = {
37 "GIT_AUTHOR_NAME": "governed-harness",
38 "GIT_AUTHOR_EMAIL": "governed-harness@localhost",
39 "GIT_COMMITTER_NAME": "governed-harness",
40 "GIT_COMMITTER_EMAIL": "governed-harness@localhost",
41}
44@dataclass(frozen=True)
45class ChainAnchor:
46 execution_id: str
47 sequence: int
48 event_digest: str
49 recorded_at: str
51 def as_dict(self) -> dict[str, object]:
52 return {
53 "executionId": self.execution_id,
54 "sequence": self.sequence,
55 "eventDigest": self.event_digest,
56 "recordedAt": self.recorded_at,
57 }
60def default_anchor_dir() -> Path:
61 configured = os.environ.get(ANCHOR_DIR_ENV)
62 if configured: 62 ↛ 64line 62 didn't jump to line 64 because the condition on line 62 was always true
63 return Path(configured).expanduser()
64 xdg = os.environ.get("XDG_DATA_HOME")
65 if xdg:
66 return Path(xdg) / "governed-harness" / "anchors"
67 home = Path.home()
68 system = platform.system()
69 if system == "Darwin":
70 return home / "Library" / "Application Support" / "governed-harness" / "anchors"
71 if system == "Windows":
72 base = os.environ.get("LOCALAPPDATA")
73 return (Path(base) if base else home) / "governed-harness" / "anchors"
74 return home / ".local" / "share" / "governed-harness" / "anchors"
77class AnchorStore:
78 """Read and write the chain anchors of one workspace in the configured place."""
80 def __init__(
81 self, mode: AnchorMode, workspace: Path, project_id: str, directory: Path | None = None
82 ) -> None:
83 self.mode = mode
84 self.workspace = workspace
85 self.project_id = project_id
86 self.directory = directory
88 @property
89 def location(self) -> str | None:
90 if self.mode == "file":
91 return str(self._file())
92 if self.mode == "git-note": 92 ↛ 94line 92 didn't jump to line 94 because the condition on line 92 was always true
93 return f"{self.workspace} {NOTES_REF}"
94 return None
96 def record(self, execution_id: str, sequence: int, event_digest: str) -> ChainAnchor:
97 anchor = ChainAnchor(execution_id, sequence, event_digest, datetime.now(UTC).isoformat())
98 if self.mode == "file":
99 self._write_file(anchor)
100 elif self.mode == "git-note": 100 ↛ 102line 100 didn't jump to line 102 because the condition on line 100 was always true
101 self._write_note(anchor)
102 return anchor
104 def read(self, execution_id: str) -> ChainAnchor | None:
105 if self.mode == "file":
106 runs = self._read_file().get("runs", {})
107 value = runs.get(execution_id) if isinstance(runs, dict) else None
108 elif self.mode == "git-note": 108 ↛ 111line 108 didn't jump to line 111 because the condition on line 108 was always true
109 value = self._read_note(execution_id)
110 else:
111 value = None
112 if not isinstance(value, dict):
113 return None
114 try:
115 return ChainAnchor(
116 execution_id=execution_id,
117 sequence=int(value["sequence"]),
118 event_digest=str(value["eventDigest"]),
119 recorded_at=str(value.get("recordedAt", "")),
120 )
121 except (KeyError, TypeError, ValueError):
122 return None
124 # ----- file -------------------------------------------------------------------
125 def _file(self) -> Path:
126 directory = self.directory or default_anchor_dir()
127 key = sha256_bytes(str(self.workspace).encode("utf-8")).split(":", 1)[1][:16]
128 return directory / f"{self.project_id}-{key}.json"
130 def _read_file(self) -> dict[str, object]:
131 try:
132 value = json.loads(self._file().read_text(encoding="utf-8"))
133 except (OSError, ValueError):
134 return {}
135 return value if isinstance(value, dict) else {}
137 def _write_file(self, anchor: ChainAnchor) -> None:
138 path = self._file()
139 path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
140 content = self._read_file()
141 runs = content.get("runs")
142 runs = dict(runs) if isinstance(runs, dict) else {}
143 runs[anchor.execution_id] = anchor.as_dict()
144 data = {"workspace": str(self.workspace), "projectId": self.project_id, "runs": runs}
145 descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
146 try:
147 with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
148 json.dump(data, handle, indent=2, sort_keys=True)
149 handle.flush()
150 os.fsync(handle.fileno())
151 os.replace(temporary, path)
152 finally:
153 Path(temporary).unlink(missing_ok=True)
155 # ----- git note ---------------------------------------------------------------
156 def _git(self, *args: str, stdin: bytes | None = None) -> subprocess.CompletedProcess[bytes]:
157 return subprocess.run( # nosec B603 B607 - git from PATH, fixed argv without hooks, no shell
158 ["git", "-c", f"core.hooksPath={os.devnull}", *args],
159 cwd=self.workspace,
160 input=stdin,
161 capture_output=True,
162 check=False,
163 timeout=30,
164 env={**os.environ, **_NOTE_IDENTITY},
165 )
167 def _subject(self, execution_id: str, write: bool) -> str | None:
168 arguments = ["hash-object", "--stdin"] + (["-w"] if write else [])
169 result = self._git(
170 *arguments, stdin=f"governed-harness chain anchor {execution_id}\n".encode()
171 )
172 text = result.stdout.decode("utf-8", "replace").strip()
173 return text if result.returncode == 0 and text else None
175 def _write_note(self, anchor: ChainAnchor) -> None:
176 subject = self._subject(anchor.execution_id, write=True)
177 if subject is None: 177 ↛ 178line 177 didn't jump to line 178 because the condition on line 177 was never true
178 raise OSError("the workspace is not a Git repository; cannot write a chain anchor note")
179 message = json.dumps(anchor.as_dict(), sort_keys=True)
180 result = self._git("notes", "--ref", NOTES_REF, "add", "-f", "-m", message, subject)
181 if result.returncode != 0: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true
182 raise OSError(result.stderr.decode("utf-8", "replace").strip() or "git notes failed")
184 def _read_note(self, execution_id: str) -> object:
185 subject = self._subject(execution_id, write=False)
186 if subject is None: 186 ↛ 187line 186 didn't jump to line 187 because the condition on line 186 was never true
187 return None
188 result = self._git("notes", "--ref", NOTES_REF, "show", subject)
189 if result.returncode != 0: 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was never true
190 return None
191 try:
192 return json.loads(result.stdout.decode("utf-8", "replace"))
193 except ValueError:
194 return None