gabriel / muse public
test_code_stage.py python
999 lines 38.3 KB
Raw
sha256:51ce277f663e01a43eaffbe77509b1de7ac2d4251b55d23306304bcdeb92c90d feat(pack): delta-encode snapshots in MPackBundle wire format Sonnet 4.6 minor ⚠ breaking 121 days ago
1 """Tests for ``muse code add`` / ``muse code reset`` and stage-aware commit/status.
2
3 Coverage matrix:
4
5 Unit tests (pure functions):
6 - _split_into_hunks: empty diff, single hunk, multi-hunk, trailing newlines
7 - _apply_hunks_to_bytes: accept all, accept none, accept partial, new-file
8 - _infer_mode: all three modes (A / M / D)
9 - _colorize_hunk: color escape codes present for +/- lines
10
11 Integration tests (CLI round-trips):
12 - muse code add <file> — stages modified file as mode M
13 - muse code add <new-file> — stages new file as mode A
14 - muse code add . — stages everything
15 - muse code add -A — stages all including new files
16 - muse code add -u — stages tracked files only (excludes untracked)
17 - muse code add -u — stages deleted files as mode D
18 - muse code add <dir> — expands directory recursively
19 - muse code add --dry-run — shows intent without writing
20 - muse code add -v — verbose per-file output
21 - muse code add (re-stage) — updates object_id when file changes again
22 - nonexistent path — exits non-zero
23 - wrong domain — exits non-zero
24
25 Stage-aware commit:
26 - Only staged files appear in the committed snapshot
27 - Unstaged changes do NOT appear in the committed snapshot
28 - Stage is cleared after a successful commit
29 - Staged deletion removes file from next commit
30
31 muse status — three-bucket view:
32 - "Changes staged for commit" section present
33 - "Changes not staged" section present
34 - Untracked files listed
35 - --format json includes staged/unstaged/untracked keys
36 - --json format
37
38 muse code reset:
39 - reset <file> — unstages that file only
40 - reset HEAD <file> — Git-syntax alias works
41 - reset (no args) — clears everything
42 - reset when nothing staged — exits cleanly
43
44 Resilience:
45 - Corrupt stage.json degrades gracefully (read_stage returns {})
46 - Staging a file outside the repo root is rejected
47
48 Stress:
49 - Staging 100 files in one shot
50 """
51
52 from __future__ import annotations
53
54 import json
55 import os
56 import pathlib
57
58 import msgpack
59 import pytest
60
61 from muse.core.types import fake_id
62 from muse.plugins.code.stage import read_stage, stage_path, StagedEntry, StagedFileMap
63 from muse.core.paths import code_dir, muse_dir
64 from tests.cli_test_helper import CliRunner
65
66 cli = None # argparse migration — CliRunner ignores this arg
67 runner = CliRunner()
68
69
70 def _read_stage_raw(root: pathlib.Path) -> StagedFileMap:
71 """Read the current stage index using the production API."""
72 return read_stage(root)
73
74
75 # ---------------------------------------------------------------------------
76 # Unit tests — pure functions
77 # ---------------------------------------------------------------------------
78
79
80 class TestSplitIntoHunks:
81 """Unit tests for _split_into_hunks (no I/O)."""
82
83 def _run(self, diff_text: str) -> list[list[str]]:
84 from muse.cli.commands.code_stage import _split_into_hunks
85 lines = [f"{l}\n" for l in diff_text.splitlines()]
86 return _split_into_hunks(lines)
87
88 def test_empty_diff_returns_no_hunks(self) -> None:
89 assert self._run("") == []
90
91 def test_single_hunk(self) -> None:
92 diff = (
93 "--- a/foo.py\n"
94 "+++ b/foo.py\n"
95 "@@ -1,2 +1,3 @@\n"
96 " def f():\n"
97 "- pass\n"
98 "+ return 1\n"
99 )
100 hunks = self._run(diff)
101 assert len(hunks) == 1
102 assert any("@@" in l for l in hunks[0])
103
104 def test_multi_hunk_has_header_on_each(self) -> None:
105 diff = (
106 "--- a/foo.py\n"
107 "+++ b/foo.py\n"
108 "@@ -1,2 +1,3 @@\n"
109 " line1\n"
110 "-old\n"
111 "+new\n"
112 "@@ -10,2 +11,3 @@\n"
113 " line10\n"
114 "-old10\n"
115 "+new10\n"
116 )
117 hunks = self._run(diff)
118 assert len(hunks) == 2
119 # Each hunk starts with the file header (--- / +++), then @@
120 for h in hunks:
121 assert any(l.startswith("---") for l in h)
122 assert any(l.startswith("+++") for l in h)
123 assert any(l.startswith("@@") for l in h)
124
125 def test_no_header_lines_before_first_hunk_is_still_valid(self) -> None:
126 diff = (
127 "@@ -1,1 +1,1 @@\n"
128 "-old\n"
129 "+new\n"
130 )
131 hunks = self._run(diff)
132 assert len(hunks) == 1
133
134
135 class TestApplyHunksToBytes:
136 """Unit tests for _apply_hunks_to_bytes."""
137
138 def _run(self, before: str, diff_text: str, accept_all: bool = True) -> str:
139 from muse.cli.commands.code_stage import _split_into_hunks, _apply_hunks_to_bytes
140
141 before_lines = before.splitlines(keepends=True)
142 after_lines = diff_text.splitlines(keepends=True)
143
144 import difflib
145 diff = list(difflib.unified_diff(
146 before_lines, after_lines, fromfile="a/f", tofile="b/f", lineterm=""
147 ))
148 diff_nl = [f"{l}\n" for l in diff]
149 hunks = _split_into_hunks(diff_nl)
150
151 accepted = hunks if accept_all else []
152 result = _apply_hunks_to_bytes(before.encode(), accepted)
153 return result.decode()
154
155 def test_accept_all_hunks_produces_after_content(self) -> None:
156 before = "def f():\n pass\n"
157 after = "def f():\n return 1\n"
158 result = self._run(before, after, accept_all=True)
159 assert "return 1" in result
160
161 def test_accept_no_hunks_preserves_original(self) -> None:
162 before = "def f():\n pass\n"
163 after = "def f():\n return 1\n"
164 result = self._run(before, after, accept_all=False)
165 assert result == before
166
167 def test_new_file_from_empty(self) -> None:
168 """Staging a new file from empty before-bytes produces after-content."""
169 before = ""
170 after = "x = 1\ny = 2\n"
171 result = self._run(before, after, accept_all=True)
172 assert "x = 1" in result
173
174 def test_binary_safe_with_replacement(self) -> None:
175 from muse.cli.commands.code_stage import _apply_hunks_to_bytes
176 result = _apply_hunks_to_bytes(b"\xff\xfe", [])
177 assert isinstance(result, bytes)
178
179
180 class TestInferMode:
181 """Unit tests for _infer_mode."""
182
183 def _run(self, rel: str, head: Manifest, exists: bool) -> str:
184 from muse.cli.commands.code_stage import _infer_mode
185 return _infer_mode(rel, head, exists)
186
187 def test_existing_tracked_is_M(self) -> None:
188 assert self._run("src/a.py", {"src/a.py": "abc"}, True) == "M"
189
190 def test_new_untracked_is_A(self) -> None:
191 assert self._run("src/new.py", {}, True) == "A"
192
193 def test_missing_from_disk_is_D(self) -> None:
194 assert self._run("src/gone.py", {"src/gone.py": "abc"}, False) == "D"
195
196 def test_missing_and_not_tracked_is_D(self) -> None:
197 # Shouldn't normally occur, but must not crash.
198 assert self._run("ghost.py", {}, False) == "D"
199
200
201 class TestColorizeHunk:
202 """Unit tests for _colorize_hunk."""
203
204 def test_added_lines_get_green(self) -> None:
205 from muse.cli.commands.code_stage import _colorize_hunk
206 result = _colorize_hunk(["+new line\n"])
207 assert "\x1b[32m" in result # green
208
209 def test_removed_lines_get_red(self) -> None:
210 from muse.cli.commands.code_stage import _colorize_hunk
211 result = _colorize_hunk(["-old line\n"])
212 assert "\x1b[31m" in result # red
213
214 def test_file_header_not_colored(self) -> None:
215 from muse.cli.commands.code_stage import _colorize_hunk
216 result = _colorize_hunk(["--- a/foo.py\n", "+++ b/foo.py\n"])
217 # file header lines should not get red/green
218 assert "\x1b[31m" not in result
219 assert "\x1b[32m" not in result
220
221 def test_at_at_header_gets_cyan(self) -> None:
222 from muse.cli.commands.code_stage import _colorize_hunk
223 result = _colorize_hunk(["@@ -1,2 +1,3 @@\n"])
224 assert "\x1b[36m" in result # cyan
225
226
227 # ---------------------------------------------------------------------------
228 # Fixtures
229 # ---------------------------------------------------------------------------
230
231
232 def _env(root: pathlib.Path) -> Manifest:
233 return {"MUSE_REPO_ROOT": str(root)}
234
235
236 @pytest.fixture()
237 def code_repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path:
238 """Initialise a fresh code-domain Muse repo with one initial commit."""
239 monkeypatch.chdir(tmp_path)
240
241 result = runner.invoke(cli, ["init", "--domain", "code"], env=_env(tmp_path))
242 assert result.exit_code == 0, result.output
243
244 (tmp_path / "auth.py").write_text("def authenticate():\n pass\n")
245 (tmp_path / "models.py").write_text("class User:\n pass\n")
246
247 r = runner.invoke(cli, ["commit", "-m", "initial"], env=_env(tmp_path))
248 assert r.exit_code == 0, r.output
249
250 return tmp_path
251
252
253 # ---------------------------------------------------------------------------
254 # muse code add — integration tests
255 # ---------------------------------------------------------------------------
256
257
258 class TestCodeAdd:
259 def test_stage_modified_file_is_mode_M(self, code_repo: pathlib.Path) -> None:
260 (code_repo / "auth.py").write_text("def authenticate():\n return True\n")
261 result = runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
262 assert result.exit_code == 0, result.output
263 assert "Staged 1 file" in result.output
264
265 stage = _read_stage_raw(code_repo)
266 assert stage["auth.py"]["mode"] == "M"
267
268 def test_stage_new_file_is_mode_A(self, code_repo: pathlib.Path) -> None:
269 (code_repo / "new_module.py").write_text("x = 1\n")
270 runner.invoke(cli, ["code", "add", "new_module.py"], env=_env(code_repo))
271 stage = _read_stage_raw(code_repo)
272 assert stage["new_module.py"]["mode"] == "A"
273
274 def test_stage_dot_stages_everything(self, code_repo: pathlib.Path) -> None:
275 (code_repo / "auth.py").write_text("# changed\n")
276 runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
277 stage = _read_stage_raw(code_repo)
278 assert "auth.py" in stage
279
280 def test_stage_A_includes_new_files(self, code_repo: pathlib.Path) -> None:
281 (code_repo / "auth.py").write_text("# changed\n")
282 (code_repo / "new.py").write_text("x = 1\n")
283 runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
284 stage = _read_stage_raw(code_repo)
285 assert "auth.py" in stage
286 assert "new.py" in stage
287
288 def test_stage_u_excludes_new_untracked_files(
289 self, code_repo: pathlib.Path
290 ) -> None:
291 """-u stages only tracked files; new/untracked files are NOT staged."""
292 (code_repo / "auth.py").write_text("# tracked change\n")
293 (code_repo / "brand_new.py").write_text("x = 1\n")
294
295 runner.invoke(cli, ["code", "add", "-u"], env=_env(code_repo))
296
297 assert stage_path(code_repo).exists()
298 stage = _read_stage_raw(code_repo)
299 assert "auth.py" in stage
300 assert "brand_new.py" not in stage
301
302 def test_stage_u_includes_deleted_files(self, code_repo: pathlib.Path) -> None:
303 (code_repo / "models.py").unlink()
304 runner.invoke(cli, ["code", "add", "-u"], env=_env(code_repo))
305 stage = _read_stage_raw(code_repo)
306 assert "models.py" in stage
307 assert stage["models.py"]["mode"] == "D"
308
309 def test_stage_directory_expands_recursively(
310 self, code_repo: pathlib.Path
311 ) -> None:
312 src = code_repo / "src"
313 src.mkdir()
314 (src / "a.py").write_text("x = 1\n")
315 (src / "b.py").write_text("y = 2\n")
316
317 runner.invoke(cli, ["code", "add", "src"], env=_env(code_repo))
318 stage = _read_stage_raw(code_repo)
319 assert "src/a.py" in stage
320 assert "src/b.py" in stage
321
322 def test_dry_run_does_not_write_stage(self, code_repo: pathlib.Path) -> None:
323 (code_repo / "auth.py").write_text("# dry\n")
324 runner.invoke(
325 cli, ["code", "add", "--dry-run", "auth.py"], env=_env(code_repo)
326 )
327 assert not stage_path(code_repo).exists()
328
329 def test_dry_run_output_shows_files(self, code_repo: pathlib.Path) -> None:
330 (code_repo / "auth.py").write_text("# dry\n")
331 result = runner.invoke(
332 cli, ["code", "add", "--dry-run", "auth.py"], env=_env(code_repo)
333 )
334 assert "auth.py" in result.output
335
336 def test_verbose_shows_per_file_output(self, code_repo: pathlib.Path) -> None:
337 (code_repo / "auth.py").write_text("# verbose\n")
338 result = runner.invoke(
339 cli, ["code", "add", "-v", "auth.py"], env=_env(code_repo)
340 )
341 assert result.exit_code == 0
342 assert "auth.py" in result.output
343
344 def test_restage_updates_object_id(self, code_repo: pathlib.Path) -> None:
345 """Staging a file twice with different content updates the object_id."""
346 (code_repo / "auth.py").write_text("# version 1\n")
347 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
348 oid_v1 = _read_stage_raw(code_repo)["auth.py"]["object_id"]
349
350 (code_repo / "auth.py").write_text("# version 2\n")
351 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
352 oid_v2 = _read_stage_raw(code_repo)["auth.py"]["object_id"]
353
354 assert oid_v1 != oid_v2
355
356 def test_staging_unchanged_file_is_idempotent(
357 self, code_repo: pathlib.Path
358 ) -> None:
359 """Staging a file that has not changed since last staging is a no-op."""
360 (code_repo / "auth.py").write_text("# same\n")
361 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
362 result = runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
363 assert result.exit_code == 0
364 assert "already up to date" in result.output
365
366 def test_nonexistent_path_exits_error(self, code_repo: pathlib.Path) -> None:
367 result = runner.invoke(
368 cli, ["code", "add", "does_not_exist.py"], env=_env(code_repo)
369 )
370 assert result.exit_code != 0
371
372 def test_wrong_domain_exits_error(
373 self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
374 ) -> None:
375 monkeypatch.chdir(tmp_path)
376 runner.invoke(cli, ["init", "--domain", "midi"], env=_env(tmp_path))
377 result = runner.invoke(cli, ["code", "add", "file.py"], env=_env(tmp_path))
378 assert result.exit_code != 0
379
380
381 # ---------------------------------------------------------------------------
382 # Stage-aware commit
383 # ---------------------------------------------------------------------------
384
385
386 class TestStageAwareCommit:
387 def test_only_staged_file_is_committed(self, code_repo: pathlib.Path) -> None:
388 (code_repo / "auth.py").write_text("def authenticate():\n return True\n")
389 (code_repo / "models.py").write_text("class User:\n name = 'anon'\n")
390
391 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
392
393 r = runner.invoke(
394 cli, ["commit", "-m", "auth only", "--json"],
395 env=_env(code_repo),
396 )
397 assert r.exit_code == 0, r.output
398 data = json.loads(r.output.strip())
399
400 from muse.core.store import read_commit, read_snapshot
401 from muse.core.object_store import read_object
402
403 commit = read_commit(code_repo, data["commit_id"])
404 assert commit is not None
405 snap = read_snapshot(code_repo, commit.snapshot_id)
406 assert snap is not None
407
408 auth_bytes = read_object(code_repo, snap.manifest["auth.py"])
409 assert auth_bytes is not None
410 assert b"return True" in auth_bytes
411
412 models_bytes = read_object(code_repo, snap.manifest["models.py"])
413 assert models_bytes is not None
414 # models.py was NOT staged — should have old content (pass, not name='anon')
415 assert b"name = 'anon'" not in models_bytes
416 assert b"pass" in models_bytes
417
418 def test_stage_cleared_after_commit(self, code_repo: pathlib.Path) -> None:
419 (code_repo / "auth.py").write_text("# cleared after commit\n")
420 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
421
422 assert stage_path(code_repo).exists()
423
424 runner.invoke(cli, ["commit", "-m", "clear stage test"], env=_env(code_repo))
425 assert not stage_path(code_repo).exists()
426
427 def test_staged_deletion_removes_file_from_commit(
428 self, code_repo: pathlib.Path
429 ) -> None:
430 (code_repo / "models.py").unlink()
431 runner.invoke(cli, ["code", "add", "-u"], env=_env(code_repo))
432
433 r = runner.invoke(
434 cli, ["commit", "-m", "delete models", "--json"],
435 env=_env(code_repo),
436 )
437 assert r.exit_code == 0, r.output
438 data = json.loads(r.output.strip())
439
440 from muse.core.store import read_commit, read_snapshot
441 commit = read_commit(code_repo, data["commit_id"])
442 assert commit is not None
443 snap = read_snapshot(code_repo, commit.snapshot_id)
444 assert snap is not None
445 assert "models.py" not in snap.manifest
446
447 def test_full_snapshot_when_no_stage(self, code_repo: pathlib.Path) -> None:
448 """Without a stage, commit captures the full working tree."""
449 (code_repo / "extra.py").write_text("z = 99\n")
450
451 r = runner.invoke(
452 cli, ["commit", "-m", "full snapshot", "--json"],
453 env=_env(code_repo),
454 )
455 assert r.exit_code == 0, r.output
456 data = json.loads(r.output.strip())
457
458 from muse.core.store import read_commit, read_snapshot
459 commit = read_commit(code_repo, data["commit_id"])
460 assert commit is not None
461 snap = read_snapshot(code_repo, commit.snapshot_id)
462 assert snap is not None
463 assert "extra.py" in snap.manifest
464
465
466 # ---------------------------------------------------------------------------
467 # muse status — staged view
468 # ---------------------------------------------------------------------------
469
470
471 class TestStageStatus:
472 def test_shows_staged_section_when_stage_active(
473 self, code_repo: pathlib.Path
474 ) -> None:
475 (code_repo / "auth.py").write_text("# staged change\n")
476 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
477
478 result = runner.invoke(cli, ["status"], env=_env(code_repo))
479 assert result.exit_code == 0, result.output
480 assert "staged for commit" in result.output
481 assert "auth.py" in result.output
482
483 def test_shows_unstaged_section_for_unmodified_tracked_with_changes(
484 self, code_repo: pathlib.Path
485 ) -> None:
486 (code_repo / "auth.py").write_text("# staged\n")
487 (code_repo / "models.py").write_text("# NOT staged\n")
488 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
489
490 result = runner.invoke(cli, ["status"], env=_env(code_repo))
491 assert "not staged" in result.output
492 assert "models.py" in result.output
493
494 def test_shows_untracked_section(self, code_repo: pathlib.Path) -> None:
495 (code_repo / "auth.py").write_text("# staged\n")
496 (code_repo / "brand_new.py").write_text("x = 1\n")
497 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
498
499 result = runner.invoke(cli, ["status"], env=_env(code_repo))
500 assert "Untracked" in result.output
501 assert "brand_new.py" in result.output
502
503 def test_json_format_has_all_buckets(self, code_repo: pathlib.Path) -> None:
504 (code_repo / "auth.py").write_text("# json stage\n")
505 (code_repo / "new_file.py").write_text("x = 1\n")
506 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
507
508 result = runner.invoke(
509 cli, ["status", "--json"], env=_env(code_repo)
510 )
511 assert result.exit_code == 0, result.output
512 data = json.loads(result.output.strip())
513 assert "staged" in data
514 assert "unstaged" in data
515 assert "untracked" in data
516 assert "auth.py" in data["staged"]["modified"]
517 assert "new_file.py" in data["untracked"]
518
519 def test_json_format_with_stage(self, code_repo: pathlib.Path) -> None:
520 (code_repo / "auth.py").write_text("# staged\n")
521 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
522
523 result = runner.invoke(cli, ["status", "--json"], env=_env(code_repo))
524 assert result.exit_code == 0
525 assert "auth.py" in result.output
526
527 def test_short_format_with_stage(self, code_repo: pathlib.Path) -> None:
528 (code_repo / "auth.py").write_text("# short\n")
529 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
530
531 result = runner.invoke(cli, ["status", "--short"], env=_env(code_repo))
532 assert result.exit_code == 0
533 assert "auth.py" in result.output
534
535 def test_clean_tree_after_commit_clears_stage(
536 self, code_repo: pathlib.Path
537 ) -> None:
538 """After staging and committing, status should show clean tree."""
539 (code_repo / "auth.py").write_text("# committed\n")
540 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
541 runner.invoke(cli, ["commit", "-m", "staged commit"], env=_env(code_repo))
542
543 result = runner.invoke(cli, ["status"], env=_env(code_repo))
544 assert result.exit_code == 0
545 # No stage file → falls back to normal drift-based status.
546 assert "staged for commit" not in result.output
547
548
549 # ---------------------------------------------------------------------------
550 # muse code reset
551 # ---------------------------------------------------------------------------
552
553
554 class TestCodeReset:
555 def test_reset_specific_file(self, code_repo: pathlib.Path) -> None:
556 (code_repo / "auth.py").write_text("# staged\n")
557 (code_repo / "models.py").write_text("# also staged\n")
558 runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
559
560 result = runner.invoke(
561 cli, ["code", "reset", "auth.py"], env=_env(code_repo)
562 )
563 assert result.exit_code == 0
564 stage = _read_stage_raw(code_repo)
565 assert "auth.py" not in stage
566 assert "models.py" in stage
567
568 def test_reset_HEAD_syntax(self, code_repo: pathlib.Path) -> None:
569 (code_repo / "auth.py").write_text("# head\n")
570 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
571 result = runner.invoke(
572 cli, ["code", "reset", "HEAD", "auth.py"], env=_env(code_repo)
573 )
574 assert result.exit_code == 0
575 assert not stage_path(code_repo).exists()
576
577 def test_reset_no_args_clears_all(self, code_repo: pathlib.Path) -> None:
578 (code_repo / "auth.py").write_text("# a\n")
579 (code_repo / "models.py").write_text("# b\n")
580 runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
581 result = runner.invoke(cli, ["code", "reset"], env=_env(code_repo))
582 assert result.exit_code == 0
583 assert not stage_path(code_repo).exists()
584
585 def test_reset_when_nothing_staged(self, code_repo: pathlib.Path) -> None:
586 result = runner.invoke(cli, ["code", "reset"], env=_env(code_repo))
587 assert result.exit_code == 0
588 assert "Nothing staged" in result.output
589
590 def test_reset_nonexistent_file_does_not_crash(
591 self, code_repo: pathlib.Path
592 ) -> None:
593 (code_repo / "auth.py").write_text("# staged\n")
594 runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
595 result = runner.invoke(
596 cli, ["code", "reset", "not_in_stage.py"], env=_env(code_repo)
597 )
598 assert result.exit_code == 0
599 assert "not staged" in result.output
600
601
602 # ---------------------------------------------------------------------------
603 # Resilience
604 # ---------------------------------------------------------------------------
605
606
607 class TestResilience:
608 def test_corrupt_stage_msgpack_returns_empty(
609 self, code_repo: pathlib.Path
610 ) -> None:
611 """Corrupt stage.msgpack must degrade gracefully — returns {} on read."""
612 stage_dir = code_dir(code_repo)
613 stage_dir.mkdir(parents=True, exist_ok=True)
614 (stage_dir / "stage.msgpack").write_bytes(b"\xde\xad\xbe\xef garbage")
615
616 entries = read_stage(code_repo)
617 assert entries == {}
618
619 def test_truncated_stage_msgpack_returns_empty(
620 self, code_repo: pathlib.Path
621 ) -> None:
622 stage_dir = code_dir(code_repo)
623 stage_dir.mkdir(parents=True, exist_ok=True)
624 (stage_dir / "stage.msgpack").write_bytes(b"\x00\x01\x02")
625
626 entries = read_stage(code_repo)
627 assert entries == {}
628
629 def test_legacy_json_is_migrated_transparently(
630 self, code_repo: pathlib.Path
631 ) -> None:
632 """Legacy stage.json is read and transparently migrated to msgpack."""
633 import json as _json
634 stage_dir = code_dir(code_repo)
635 stage_dir.mkdir(parents=True, exist_ok=True)
636 legacy = stage_dir / "stage.json"
637 legacy.write_text(_json.dumps({
638 "version": 1,
639 "entries": {
640 "auth.py": {"object_id": f"{'abc123' * 10}ab12", "mode": "M", "staged_at": "2026-01-01T00:00:00+00:00"},
641 },
642 }))
643
644 entries = read_stage(code_repo)
645 assert "auth.py" in entries
646 assert entries["auth.py"]["mode"] == "M"
647 # Legacy JSON must be removed after migration.
648 assert not legacy.exists()
649 # Msgpack file must now exist.
650 assert stage_path(code_repo).exists()
651
652 def test_missing_stage_returns_empty(self, code_repo: pathlib.Path) -> None:
653 entries = read_stage(code_repo)
654 assert entries == {}
655
656 def test_write_empty_entries_removes_file(
657 self, code_repo: pathlib.Path
658 ) -> None:
659 from muse.plugins.code.stage import write_stage, StagedFileMap
660
661 path = stage_path(code_repo)
662 path.parent.mkdir(parents=True, exist_ok=True)
663 # Create a non-empty msgpack file first.
664 import msgpack as _mp
665 path.write_bytes(_mp.packb({"version": 2, "entries": {"f.py": {"object_id": "a" * 64, "mode": "M", "staged_at": "x"}}}, use_bin_type=True))
666
667 write_stage(code_repo, {})
668 assert not path.exists()
669
670 def test_clear_stage_idempotent(self, code_repo: pathlib.Path) -> None:
671 from muse.plugins.code.stage import clear_stage, StagedFileMap
672
673 clear_stage(code_repo) # no stage to clear — must not raise
674 clear_stage(code_repo) # idempotent
675
676
677 # ---------------------------------------------------------------------------
678 # Stress test
679 # ---------------------------------------------------------------------------
680
681
682 class TestStageStress:
683 def test_stage_100_files(
684 self, code_repo: pathlib.Path
685 ) -> None:
686 """Staging 100 files must complete without error and write all entries."""
687 for i in range(100):
688 (code_repo / f"module_{i:03d}.py").write_text(f"X_{i} = {i}\n")
689
690 result = runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
691 assert result.exit_code == 0, result.output
692
693 stage = _read_stage_raw(code_repo)
694 # 100 new files + 2 original tracked files (auth.py, models.py)
695 assert len(stage) >= 100
696
697 def test_commit_100_staged_files(
698 self, code_repo: pathlib.Path
699 ) -> None:
700 """Committing 100 staged files produces a correct manifest."""
701 for i in range(100):
702 (code_repo / f"mod_{i:03d}.py").write_text(f"V = {i}\n")
703
704 runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
705 r = runner.invoke(
706 cli, ["commit", "-m", "100 files", "--json"],
707 env=_env(code_repo),
708 )
709 assert r.exit_code == 0, r.output
710 data = json.loads(r.output.strip())
711
712 from muse.core.store import read_commit, read_snapshot
713 commit = read_commit(code_repo, data["commit_id"])
714 assert commit is not None
715 snap = read_snapshot(code_repo, commit.snapshot_id)
716 assert snap is not None
717 assert len(snap.manifest) >= 100
718
719
720 def test_add_all_stages_deletions(
721 code_repo: pathlib.Path,
722 ) -> None:
723 """``muse code add -A`` must stage tracked files that have been deleted.
724
725 Regression test: before the fix, ``-A`` used ``_walk_tree`` which only
726 returns files present on disk. Deleted tracked files were therefore
727 silently omitted and the deletion was never recorded in the stage.
728 """
729 # code_repo already has auth.py and models.py committed.
730 os.remove(code_repo / "auth.py")
731
732 r = runner.invoke(cli, ["code", "add", "-A"], env=_env(code_repo))
733 assert r.exit_code == 0, r.output
734
735 from muse.plugins.code.stage import read_stage, StagedFileMap
736 stage = read_stage(code_repo)
737 assert "auth.py" in stage, "deleted tracked file must appear in stage"
738 assert stage["auth.py"]["mode"] == "D", "deleted file must have mode D"
739
740
741 def test_add_dot_stages_museattributes(
742 code_repo: pathlib.Path,
743 ) -> None:
744 """`muse code add .` must stage `.museattributes` when it exists.
745
746 Regression test: before the fix, ``_walk_tree`` skipped all files whose
747 name started with ``.``, so ``.museattributes`` and ``.museignore`` could
748 never be staged with ``muse code add .`` — they required an explicit path.
749 """
750 (code_repo / ".museattributes").write_text("[*.py]\nmerge = python\n")
751
752 r = runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
753 assert r.exit_code == 0, r.output
754
755 from muse.plugins.code.stage import read_stage
756 stage = read_stage(code_repo)
757 assert ".museattributes" in stage, ".museattributes must be staged by `muse code add .`"
758
759
760 def test_add_dot_stages_museignore(
761 code_repo: pathlib.Path,
762 ) -> None:
763 """`muse code add .` must stage `.museignore` itself when it exists.
764
765 The file that controls ignore patterns should be version-controlled just
766 like ``.gitignore`` is — ``muse code add .`` must include it.
767 Note: the test uses empty patterns so the file doesn't suppress itself.
768 """
769 (code_repo / ".museignore").write_text('[global]\npatterns = []\n')
770
771 r = runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
772 assert r.exit_code == 0, r.output
773
774 from muse.plugins.code.stage import read_stage
775 stage = read_stage(code_repo)
776 assert ".museignore" in stage, ".museignore itself must be staged by `muse code add .`"
777
778
779 def test_add_dot_does_not_stage_museignore_files(
780 code_repo: pathlib.Path,
781 ) -> None:
782 """``muse code add .`` must not stage files matched by ``.museignore``.
783
784 Regression test: before the fix, ``_walk_tree`` never consulted
785 ``.museignore``, so any file on disk — including ones the user explicitly
786 excluded — could be silently staged and committed.
787 """
788 (code_repo / ".museignore").write_text('[global]\npatterns = ["*.log"]\n')
789 (code_repo / "debug.log").write_text("ignored content\n")
790 (code_repo / "app.py").write_text("# new code\n")
791
792 r = runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
793 assert r.exit_code == 0, r.output
794
795 from muse.plugins.code.stage import read_stage, StagedFileMap
796 stage = read_stage(code_repo)
797 assert "debug.log" not in stage, ".museignore'd file must NOT be staged"
798 assert "app.py" in stage, "non-ignored new file must be staged"
799
800
801 def test_add_dot_does_not_stage_unchanged_files(
802 code_repo: pathlib.Path,
803 ) -> None:
804 """``muse code add .`` must only stage files whose content differs from HEAD.
805
806 Regression test for the bug where ``muse code add .`` staged every file in
807 the working tree regardless of whether it had changed, because the
808 "skip-if-already-staged" guard was only consulted (and only correct) after a
809 second ``add`` run. On a fresh stage the check was vacuously false for all
810 files, so even unchanged files were staged.
811 """
812 # Make an initial commit so HEAD has a manifest.
813 (code_repo / "alpha.py").write_text("x = 1\n")
814 (code_repo / "beta.py").write_text("y = 2\n")
815 runner.invoke(cli, ["commit", "-m", "initial"], env=_env(code_repo))
816
817 # Modify only one file; leave the other untouched.
818 (code_repo / "alpha.py").write_text("x = 99\n")
819
820 # Stage everything.
821 r = runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
822 assert r.exit_code == 0, r.output
823
824 # Only the changed file must be staged — NOT the unchanged beta.py.
825 from muse.plugins.code.stage import read_stage, StagedFileMap
826 stage = read_stage(code_repo)
827 assert "alpha.py" in stage, "modified file must be staged"
828 assert "beta.py" not in stage, "unchanged file must NOT appear in stage"
829
830
831 def test_add_dot_stages_deletions(
832 code_repo: pathlib.Path,
833 ) -> None:
834 """``muse code add .`` must stage tracked files that have been deleted from disk.
835
836 Regression test: before the fix, ``muse code add .`` (no flags) only walked
837 the working tree, so deleted files were silently omitted. Users had to know
838 to pass ``-A`` or explicitly name each deleted file — a significant ergonomic
839 gap vs ``git add .`` which has staged deletions since Git 2.0.
840 """
841 # code_repo already has auth.py and models.py committed.
842 os.remove(code_repo / "auth.py")
843
844 r = runner.invoke(cli, ["code", "add", "."], env=_env(code_repo))
845 assert r.exit_code == 0, r.output
846
847 from muse.plugins.code.stage import read_stage, StagedFileMap
848 stage = read_stage(code_repo)
849 assert "auth.py" in stage, "deleted tracked file must appear in stage with `muse code add .`"
850 assert stage["auth.py"]["mode"] == "D", "deleted file must have mode D"
851
852
853 def test_add_explicit_path_stages_deletion(
854 code_repo: pathlib.Path,
855 ) -> None:
856 """``muse code add <path>`` must stage a deletion when the file is gone from disk.
857
858 Mirrors ``git add <path>`` which stages the deletion regardless of whether
859 the file still exists on disk. Before the fix, naming a non-existent path
860 emitted ``❌ Path not found`` and silently skipped the deletion.
861 """
862 # code_repo already has auth.py committed — delete it from disk.
863 os.remove(code_repo / "auth.py")
864
865 r = runner.invoke(cli, ["code", "add", "auth.py"], env=_env(code_repo))
866 assert r.exit_code == 0, r.output
867
868 from muse.plugins.code.stage import read_stage
869 stage = read_stage(code_repo)
870 assert "auth.py" in stage, "deleted tracked file must appear in stage when named explicitly"
871 assert stage["auth.py"]["mode"] == "D", "deleted file must have mode D"
872
873
874 # ---------------------------------------------------------------------------
875 # Regression tests — _head_manifest branch resolution (Bug A)
876 #
877 # Written BEFORE the fix to document expected behaviour. Both tests verify
878 # that _head_manifest resolves the branch through the store abstraction
879 # (get_head_commit_id), not by reading the ref file directly.
880 # ---------------------------------------------------------------------------
881
882
883 class TestHeadManifestResolution:
884 """_head_manifest must use the store abstraction, not the raw ref file."""
885
886 def test_empty_branch_returns_empty_dict(
887 self, tmp_path: pathlib.Path
888 ) -> None:
889 """With no commits on the branch, _head_manifest returns {}."""
890 from muse.cli.commands.code_stage import _head_manifest
891
892 dot_muse = muse_dir(tmp_path)
893 dot_muse.mkdir()
894 (dot_muse / "repo.json").write_text('{"repo_id":"test"}')
895 (dot_muse / "HEAD").write_text("ref: refs/heads/main")
896 (dot_muse / "refs" / "heads").mkdir(parents=True)
897 (dot_muse / "commits").mkdir()
898 (dot_muse / "snapshots").mkdir()
899 # No ref file written — branch has no commits.
900
901 result = _head_manifest(tmp_path)
902 assert result == {}
903
904 def test_branch_with_commit_returns_manifest(
905 self, tmp_path: pathlib.Path
906 ) -> None:
907 """With a real commit on the branch, _head_manifest returns its manifest."""
908 import datetime
909 from muse.cli.commands.code_stage import _head_manifest
910 from muse.core.store import write_commit, CommitRecord, SnapshotRecord
911 from muse.core.store import write_snapshot
912 from muse.core.snapshot import compute_commit_id, compute_snapshot_id
913
914 dot_muse = muse_dir(tmp_path)
915 dot_muse.mkdir()
916 (dot_muse / "repo.json").write_text('{"repo_id":"test"}')
917 (dot_muse / "HEAD").write_text("ref: refs/heads/main")
918 (dot_muse / "refs" / "heads").mkdir(parents=True)
919 (dot_muse / "commits").mkdir()
920 (dot_muse / "snapshots").mkdir()
921
922 _hello_id = fake_id("hello.py-content")
923 manifest = {"hello.py": _hello_id}
924 snap_id = compute_snapshot_id(manifest)
925 snap = SnapshotRecord(snapshot_id=snap_id, manifest=manifest)
926 write_snapshot(tmp_path, snap)
927
928 committed_at = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
929 commit_id = compute_commit_id(
930 parent_ids=[],
931 snapshot_id=snap_id,
932 message="init",
933 committed_at_iso=committed_at.isoformat(),
934 author="tester",
935 )
936 commit = CommitRecord(
937 repo_id="test",
938 commit_id=commit_id,
939 branch="main",
940 snapshot_id=snap_id,
941 message="init",
942 committed_at=committed_at,
943 author="tester",
944 )
945 write_commit(tmp_path, commit)
946 (dot_muse / "refs" / "heads" / "main").write_text(commit_id)
947
948 result = _head_manifest(tmp_path)
949 assert result == {"hello.py": _hello_id}
950
951
952 # ---------------------------------------------------------------------------
953 # TestRegisterFlags
954 # ---------------------------------------------------------------------------
955
956
957 import argparse as _argparse
958
959
960 class TestRegisterFlags:
961 """register_add() and register_reset() wire --json / -j correctly."""
962
963 def _parse_add(self, *args: str) -> _argparse.Namespace:
964 from muse.cli.commands.code_stage import register_add
965 p = _argparse.ArgumentParser()
966 sub = p.add_subparsers()
967 register_add(sub)
968 return p.parse_args(["add", *args])
969
970 def _parse_reset(self, *args: str) -> _argparse.Namespace:
971 from muse.cli.commands.code_stage import register_reset
972 p = _argparse.ArgumentParser()
973 sub = p.add_subparsers()
974 register_reset(sub)
975 return p.parse_args(["reset", *args])
976
977 def test_add_default_json_out_is_false(self) -> None:
978 ns = self._parse_add("foo.py")
979 assert ns.json_out is False
980
981 def test_add_json_flag_sets_json_out(self) -> None:
982 ns = self._parse_add("--json", "foo.py")
983 assert ns.json_out is True
984
985 def test_add_j_shorthand_sets_json_out(self) -> None:
986 ns = self._parse_add("-j", "foo.py")
987 assert ns.json_out is True
988
989 def test_reset_default_json_out_is_false(self) -> None:
990 ns = self._parse_reset()
991 assert ns.json_out is False
992
993 def test_reset_json_flag_sets_json_out(self) -> None:
994 ns = self._parse_reset("--json")
995 assert ns.json_out is True
996
997 def test_reset_j_shorthand_sets_json_out(self) -> None:
998 ns = self._parse_reset("-j")
999 assert ns.json_out is True
File History 1 commit
sha256:51ce277f663e01a43eaffbe77509b1de7ac2d4251b55d23306304bcdeb92c90d feat(pack): delta-encode snapshots in MPackBundle wire format Sonnet 4.6 minor 121 days ago