gabriel / muse public
test_plumbing_read_commit.py python
375 lines 15.0 KB
Raw
sha256:660fcac1df3ab28f61862e961890bd2ca8b754fa0242079d93ca1e25037ec8a6 chore(tests): add docstring to tests/__init__.py so rc14 tr… Human 26 days ago
1 """Comprehensive tests for ``muse plumbing read-commit``.
2
3 Coverage tiers
4 --------------
5 - Unit: _ALL_FIELDS completeness
6 - Integration: JSON/text format, prefix resolution, --fields filter, parent chain
7 - Security: ANSI in branch/author/message stripped in text mode
8 - Stress: 200 sequential reads, --fields on large schema
9 """
10 from __future__ import annotations
11
12 import datetime
13 import json
14 import pathlib
15
16 from muse.core.errors import ExitCode
17 from muse.core.snapshot import compute_commit_id, compute_snapshot_id
18 from muse.core.store import CommitRecord, SnapshotRecord, write_commit, write_snapshot
19 from tests.cli_test_helper import CliRunner, InvokeResult
20
21 runner = CliRunner()
22
23 # Module-level constants so every test uses the same deterministic inputs.
24 _SNAP_ID: str = compute_snapshot_id({})
25 _COMMITTED_AT: datetime.datetime = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
26
27
28 # ---------------------------------------------------------------------------
29 # Helpers
30 # ---------------------------------------------------------------------------
31
32 def _make_repo(tmp_path: pathlib.Path) -> pathlib.Path:
33 repo = tmp_path / "repo"
34 muse = repo / ".muse"
35 for sub in ("objects", "commits", "snapshots", "refs/heads"):
36 (muse / sub).mkdir(parents=True)
37 (muse / "HEAD").write_text("ref: refs/heads/main")
38 (muse / "repo.json").write_text(json.dumps({"repo_id": "test-repo", "domain": "code"}))
39 return repo
40
41
42 def _commit(
43 repo: pathlib.Path,
44 *,
45 branch: str = "main",
46 message: str = "test commit",
47 author: str = "tester",
48 parent: str | None = None,
49 agent_id: str = "",
50 model_id: str = "",
51 ) -> str:
52 """Write a commit with a real content-addressed ID; return the commit_id."""
53 parent_ids: list[str] = [parent] if parent else []
54 commit_id = compute_commit_id(parent_ids, _SNAP_ID, message, _COMMITTED_AT.isoformat())
55 write_snapshot(repo, SnapshotRecord(
56 snapshot_id=_SNAP_ID,
57 manifest={},
58 created_at=_COMMITTED_AT,
59 ))
60 rec = CommitRecord(
61 commit_id=commit_id,
62 repo_id="test-repo",
63 branch=branch,
64 snapshot_id=_SNAP_ID,
65 message=message,
66 committed_at=_COMMITTED_AT,
67 author=author,
68 parent_commit_id=parent,
69 agent_id=agent_id,
70 model_id=model_id,
71 )
72 write_commit(repo, rec)
73 return commit_id
74
75
76 def _rc(repo: pathlib.Path, *args: str) -> InvokeResult:
77 from muse.cli.app import main as cli
78 return runner.invoke(
79 cli,
80 ["read-commit", *args],
81 env={"MUSE_REPO_ROOT": str(repo)},
82 )
83
84
85 # ---------------------------------------------------------------------------
86 # Unit — _ALL_FIELDS
87 # ---------------------------------------------------------------------------
88
89
90 class TestAllFields:
91 def test_all_fields_matches_commitdict_annotations(self) -> None:
92 """_ALL_FIELDS must be exactly the keys in CommitDict.__annotations__."""
93 from muse.cli.commands.plumbing.read_commit import _ALL_FIELDS
94 from muse.core.store import CommitDict
95 assert _ALL_FIELDS == frozenset(CommitDict.__annotations__.keys())
96
97 def test_required_fields_present(self) -> None:
98 from muse.cli.commands.plumbing.read_commit import _ALL_FIELDS
99 for field in ("commit_id", "branch", "message", "committed_at",
100 "agent_id", "model_id", "format_version", "reviewed_by"):
101 assert field in _ALL_FIELDS
102
103
104 # ---------------------------------------------------------------------------
105 # Integration — JSON format
106 # ---------------------------------------------------------------------------
107
108
109 class TestJsonFormat:
110 def test_full_schema_returned(self, tmp_path: pathlib.Path) -> None:
111 repo = _make_repo(tmp_path)
112 cid = _commit(repo, message="hello world")
113 result = _rc(repo, cid)
114 assert result.exit_code == 0
115 data = json.loads(result.output)
116 assert data["commit_id"] == cid
117 assert data["message"] == "hello world"
118 assert data["branch"] == "main"
119 assert "format_version" in data
120
121 def test_json_flag_shorthand(self, tmp_path: pathlib.Path) -> None:
122 repo = _make_repo(tmp_path)
123 cid = _commit(repo, message="shorthand test")
124 result = _rc(repo, "--json", cid)
125 assert result.exit_code == 0
126 assert "commit_id" in json.loads(result.output)
127
128 def test_agent_provenance_fields_present(self, tmp_path: pathlib.Path) -> None:
129 repo = _make_repo(tmp_path)
130 cid = _commit(repo, agent_id="my-agent", model_id="claude-4")
131 data = json.loads(_rc(repo, cid).output)
132 assert data["agent_id"] == "my-agent"
133 assert data["model_id"] == "claude-4"
134
135 def test_parent_commit_id_null_for_root(self, tmp_path: pathlib.Path) -> None:
136 repo = _make_repo(tmp_path)
137 cid = _commit(repo, message="root commit")
138 data = json.loads(_rc(repo, cid).output)
139 assert data["parent_commit_id"] is None
140
141 def test_parent_commit_id_set_for_child(self, tmp_path: pathlib.Path) -> None:
142 repo = _make_repo(tmp_path)
143 parent = _commit(repo, message="parent commit")
144 child = _commit(repo, message="child commit", parent=parent)
145 data = json.loads(_rc(repo, child).output)
146 assert data["parent_commit_id"] == parent
147
148 def test_committed_at_is_iso8601(self, tmp_path: pathlib.Path) -> None:
149 repo = _make_repo(tmp_path)
150 cid = _commit(repo, message="iso date test")
151 data = json.loads(_rc(repo, cid).output)
152 # Should parse without error
153 datetime.datetime.fromisoformat(data["committed_at"])
154
155 def test_snapshot_id_in_output(self, tmp_path: pathlib.Path) -> None:
156 repo = _make_repo(tmp_path)
157 cid = _commit(repo, message="snapshot test")
158 data = json.loads(_rc(repo, cid).output)
159 assert len(data["snapshot_id"]) == 64
160
161
162 # ---------------------------------------------------------------------------
163 # Integration — text format
164 # ---------------------------------------------------------------------------
165
166
167 class TestTextFormat:
168 def test_text_format_contains_commit_prefix(self, tmp_path: pathlib.Path) -> None:
169 repo = _make_repo(tmp_path)
170 cid = _commit(repo, message="text test")
171 result = _rc(repo, "--format", "text", cid)
172 assert result.exit_code == 0
173 line = result.output.strip()
174 assert cid[:12] in line
175
176 def test_text_format_contains_branch(self, tmp_path: pathlib.Path) -> None:
177 repo = _make_repo(tmp_path)
178 cid = _commit(repo, branch="main", message="branch test")
179 result = _rc(repo, "--format", "text", cid)
180 assert "main" in result.output
181
182 def test_text_format_contains_message(self, tmp_path: pathlib.Path) -> None:
183 repo = _make_repo(tmp_path)
184 cid = _commit(repo, message="my commit message")
185 result = _rc(repo, "--format", "text", cid)
186 assert "my commit message" in result.output
187
188 def test_text_multiline_message_flattened(self, tmp_path: pathlib.Path) -> None:
189 repo = _make_repo(tmp_path)
190 cid = _commit(repo, message="line one\nline two")
191 result = _rc(repo, "--format", "text", cid)
192 # Newline replaced with space — output stays on one line
193 assert "\n" not in result.output.strip()
194 assert "line one" in result.output
195
196
197 # ---------------------------------------------------------------------------
198 # Integration — prefix resolution
199 # ---------------------------------------------------------------------------
200
201
202 class TestPrefixResolution:
203 def test_8char_prefix_resolves(self, tmp_path: pathlib.Path) -> None:
204 repo = _make_repo(tmp_path)
205 cid = _commit(repo, message="prefix resolve test")
206 result = _rc(repo, cid[:8])
207 assert result.exit_code == 0
208 assert json.loads(result.output)["commit_id"] == cid
209
210 def test_ambiguous_prefix_errors(self, tmp_path: pathlib.Path) -> None:
211 repo = _make_repo(tmp_path)
212 # "msg 121" and "msg 127" produce commit IDs sharing the "3f47" 4-char
213 # prefix when hashed with an empty manifest and 2026-01-01T00:00:00+00:00.
214 # Verified by precomputation; changing _SNAP_ID or _COMMITTED_AT requires
215 # updating these message strings.
216 cid1 = _commit(repo, message="msg 121")
217 cid2 = _commit(repo, message="msg 127")
218 result = _rc(repo, "3f47")
219 assert result.exit_code == ExitCode.USER_ERROR
220 data = json.loads(result.output)
221 assert "ambiguous" in data["error"]
222 assert set(data["candidates"]) == {cid1, cid2}
223
224 def test_missing_commit_errors(self, tmp_path: pathlib.Path) -> None:
225 repo = _make_repo(tmp_path)
226 # Valid hex ID that doesn't exist in the store
227 result = _rc(repo, "dead" + "beef" * 15)
228 assert result.exit_code == ExitCode.USER_ERROR
229 data = json.loads(result.output)
230 assert "not found" in data["error"]
231
232 def test_invalid_commit_id_errors(self, tmp_path: pathlib.Path) -> None:
233 repo = _make_repo(tmp_path)
234 result = _rc(repo, "ZZZZ" + "a" * 60)
235 assert result.exit_code == ExitCode.USER_ERROR
236
237
238 # ---------------------------------------------------------------------------
239 # Integration — --fields filter
240 # ---------------------------------------------------------------------------
241
242
243 class TestFieldsFilter:
244 def test_single_field(self, tmp_path: pathlib.Path) -> None:
245 repo = _make_repo(tmp_path)
246 cid = _commit(repo, message="filtered")
247 result = _rc(repo, "--fields", "message", cid)
248 assert result.exit_code == 0
249 data = json.loads(result.output)
250 assert list(data.keys()) == ["message"]
251 assert data["message"] == "filtered"
252
253 def test_multiple_fields(self, tmp_path: pathlib.Path) -> None:
254 repo = _make_repo(tmp_path)
255 cid = _commit(repo, branch="dev", message="multi field test")
256 result = _rc(repo, "--fields", "commit_id,branch,message", cid)
257 data = json.loads(result.output)
258 assert set(data.keys()) == {"commit_id", "branch", "message"}
259 assert data["commit_id"] == cid
260 assert data["branch"] == "dev"
261
262 def test_agent_fields_filter(self, tmp_path: pathlib.Path) -> None:
263 """Agents extracting provenance fields should get exactly what they asked for."""
264 repo = _make_repo(tmp_path)
265 cid = _commit(repo, agent_id="audit-bot", model_id="claude-4")
266 result = _rc(repo, "--fields", "agent_id,model_id,format_version", cid)
267 data = json.loads(result.output)
268 assert set(data.keys()) == {"agent_id", "model_id", "format_version"}
269 assert data["agent_id"] == "audit-bot"
270 assert data["model_id"] == "claude-4"
271
272 def test_unknown_field_errors(self, tmp_path: pathlib.Path) -> None:
273 repo = _make_repo(tmp_path)
274 cid = _commit(repo, message="unknown field test")
275 result = _rc(repo, "--fields", "nonexistent_field", cid)
276 assert result.exit_code == ExitCode.USER_ERROR
277
278 def test_fields_with_text_format_errors(self, tmp_path: pathlib.Path) -> None:
279 repo = _make_repo(tmp_path)
280 cid = _commit(repo, message="fields text error test")
281 result = _rc(repo, "--fields", "commit_id", "--format", "text", cid)
282 assert result.exit_code == ExitCode.USER_ERROR
283
284 def test_fields_whitespace_trimmed(self, tmp_path: pathlib.Path) -> None:
285 repo = _make_repo(tmp_path)
286 cid = _commit(repo, message="whitespace trim test")
287 result = _rc(repo, "--fields", " commit_id , message ", cid)
288 assert result.exit_code == 0
289 data = json.loads(result.output)
290 assert "commit_id" in data
291 assert "message" in data
292
293
294 # ---------------------------------------------------------------------------
295 # Security
296 # ---------------------------------------------------------------------------
297
298
299 class TestSecurity:
300 def test_ansi_in_branch_stripped_in_text(self, tmp_path: pathlib.Path) -> None:
301 repo = _make_repo(tmp_path)
302 _commit(repo, branch="main")
303 # Write an evil commit directly, bypassing the normal helper.
304 # The commit_id must be a real hash of the stored fields for read_commit
305 # to pass content-hash verification.
306 from muse.core.store import write_commit as _wc
307 evil_message = "test"
308 evil_cid = compute_commit_id([], _SNAP_ID, evil_message, _COMMITTED_AT.isoformat())
309 evil_rec = CommitRecord(
310 commit_id=evil_cid,
311 repo_id="test-repo",
312 branch="\x1b[31mevil\x1b[0m",
313 snapshot_id=_SNAP_ID,
314 message=evil_message,
315 committed_at=_COMMITTED_AT,
316 )
317 _wc(repo, evil_rec)
318 result = _rc(repo, "--format", "text", evil_cid)
319 assert result.exit_code == 0
320 assert "\x1b" not in result.output
321
322 def test_ansi_in_message_stripped_in_text(self, tmp_path: pathlib.Path) -> None:
323 repo = _make_repo(tmp_path)
324 # snapshot_id does not need to be a valid hex string for read_commit to
325 # succeed — _verify_commit_id uses it as an opaque string in the hash.
326 evil_snap_id = "s" * 64
327 evil_message = "\x1b[31mmalicious\x1b[0m"
328 evil_committed_at = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
329 evil_cid = compute_commit_id([], evil_snap_id, evil_message, evil_committed_at.isoformat())
330 evil_rec = CommitRecord(
331 commit_id=evil_cid,
332 repo_id="test-repo",
333 branch="main",
334 snapshot_id=evil_snap_id,
335 message=evil_message,
336 committed_at=evil_committed_at,
337 )
338 write_commit(repo, evil_rec)
339 result = _rc(repo, "--format", "text", evil_cid)
340 assert result.exit_code == 0
341 assert "\x1b" not in result.output
342
343 def test_ansi_in_commit_id_rejected(self, tmp_path: pathlib.Path) -> None:
344 repo = _make_repo(tmp_path)
345 result = _rc(repo, "\x1b[31m" + "a" * 64)
346 assert result.exit_code == ExitCode.USER_ERROR
347
348 def test_no_traceback_on_bad_input(self, tmp_path: pathlib.Path) -> None:
349 repo = _make_repo(tmp_path)
350 result = _rc(repo, "not-valid")
351 assert "Traceback" not in result.output
352
353
354 # ---------------------------------------------------------------------------
355 # Stress
356 # ---------------------------------------------------------------------------
357
358
359 class TestStress:
360 def test_200_sequential_reads(self, tmp_path: pathlib.Path) -> None:
361 repo = _make_repo(tmp_path)
362 cid = _commit(repo, message="stable")
363 for i in range(200):
364 result = _rc(repo, cid)
365 assert result.exit_code == 0, f"failed at iteration {i}"
366 assert json.loads(result.output)["message"] == "stable"
367
368 def test_fields_filter_200_iterations(self, tmp_path: pathlib.Path) -> None:
369 repo = _make_repo(tmp_path)
370 cid = _commit(repo, agent_id="bot")
371 for i in range(200):
372 result = _rc(repo, "--fields", "commit_id,agent_id", cid)
373 assert result.exit_code == 0, f"failed at iteration {i}"
374 data = json.loads(result.output)
375 assert data["agent_id"] == "bot"
File History 3 commits
sha256:660fcac1df3ab28f61862e961890bd2ca8b754fa0242079d93ca1e25037ec8a6 chore(tests): add docstring to tests/__init__.py so rc14 tr… Human 26 days ago
sha256:d8316ffae901be06347e16ab55be11868eb519dd16ade3e8aa16a99e662f7e62 baseline: rc14 re-baseline after rc3 store corruption recovery Human patch 26 days ago
sha256:1c4b3e3a9a1f300774c3ee662b572a698d5fd405bf765a71e6011a2e9c3eaaaa feat: Muse — version control for the agent era Human 100 days ago