Skip to content

Commit 5447cbb

Browse files
committed
test(doctor): verify worktree signals and report unavailable inspection (#602)
1 parent 7fcb1cb commit 5447cbb

6 files changed

Lines changed: 159 additions & 8 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ adheres to [Semantic Versioning](https://semver.org/).
6161
the main checkout as its root even when called from a linked checkout.
6262
Outside worktrees produce a warning without changing the exit code.
6363
NUL-delimited Git output preserves newlines and spaces in their paths.
64+
Failed Git invocations produce an optional warning with a retry command.
6465

6566
- **Procedural skills are stored on the default backend too (#596).** The
6667
`procedural_skills` table existed only on PostgreSQL, so on SQLite the

‎docs/adr/ADR-1079-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,5 @@ Derive the roots from the first worktree in `git worktree list --porcelain -z`,
2929
Positive: the owner sees worktrees outside both host directories via 'python -m mcp_server.doctor', check_setup, and the preflight command without git status noise. Negative: a marketplace user running doctor inside an unrelated repo that happens to keep worktrees elsewhere will see an advisory WARN naming a Cortex-authored convention; the fix text makes that source explicit so it reads as advisory, not a bug report.
3030

3131
Git porcelain uses NUL record delimiters with `-z`; parsing those delimiters preserves literal newlines and trailing spaces in paths (git-worktree(1), Porcelain Format). A real-Git regression verifies that an outside worktree with both characters is reported by its exact path.
32+
33+
A failed Git invocation produces an optional WARN that lists the possible causes and provides the Git command to retry. The existing subprocess helper returns no failure category, so the diagnostic does not claim a specific cause. Successful empty output is reported as no registered worktrees.

‎mcp_server/doctor.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,8 @@ def _worktree_list() -> list[dict[str, object]] | None:
260260
section list). Each dict carries ``path`` (str), ``bare`` (bool),
261261
``prunable`` (bool). Returns ``None`` when ``git`` is missing, the cwd
262262
isn't a git checkout, or the command times out — every failure mode
263-
of ``run_with_hard_timeout`` collapses to the same "not applicable"
264-
signal, never a raised exception.
263+
of ``run_with_hard_timeout`` collapses to the same "inspection unavailable"
264+
signal, never a raised exception. Empty successful output returns [].
265265
266266
source: ADR-1079"""
267267
out = run_with_hard_timeout(
@@ -288,14 +288,14 @@ def _worktree_list() -> list[dict[str, object]] | None:
288288
current["prunable"] = True
289289
if current is not None:
290290
entries.append(current)
291-
return entries or None
291+
return entries
292292

293293

294294
def _worktree_classification(entries: list[dict[str, object]]) -> tuple[bool, str]:
295295
"""Classify worktree ``entries`` (``_worktree_list()`` output, main
296296
first) against the allowed-location rule.
297297
298-
postcondition: ``ok`` is True for "not a git checkout" (empty
298+
postcondition: ``ok`` is True for "no registered worktrees" (empty
299299
``entries``), a bare main repo, and full compliance; False carries
300300
every offending resolved path in ``detail``. The allowed roots are
301301
derived from ``entries[0]`` (the main worktree — always first, per
@@ -305,7 +305,7 @@ def _worktree_classification(entries: list[dict[str, object]]) -> tuple[bool, st
305305
306306
source: ADR-1079 (rule: docs/agent-guidance.md, What NOT to do)"""
307307
if not entries:
308-
return True, "not a git checkout"
308+
return True, "no registered worktrees"
309309
main = entries[0]
310310
if main.get("bare"):
311311
return True, "bare repository — rule not applicable"
@@ -335,7 +335,18 @@ def _worktree_locations() -> Check:
335335
(``optional=True``).
336336
337337
source: ADR-1079 (rule reported: docs/agent-guidance.md, What NOT to do)"""
338-
ok, detail = _worktree_classification(_worktree_list() or [])
338+
entries = _worktree_list()
339+
if entries is None:
340+
return Check(
341+
"worktree locations (optional)",
342+
False,
343+
"Unable to inspect worktree locations: not a Git checkout, "
344+
"Git unavailable, or command failed.",
345+
"Run from a Git checkout with Git available; retry "
346+
"git worktree list --porcelain -z.",
347+
optional=True,
348+
)
349+
ok, detail = _worktree_classification(entries)
339350
fix = (
340351
""
341352
if ok

‎tests_py/test_doctor.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,11 @@ def test_main_checkout_only_passes(self, real_git_repo, monkeypatch):
169169
assert check.ok is True
170170
assert check.optional is True
171171

172-
def test_not_a_git_checkout_passes(self, tmp_path, monkeypatch):
172+
def test_not_a_git_checkout_warns(self, tmp_path, monkeypatch):
173173
monkeypatch.chdir(tmp_path) # plain dir, no .git
174174
check = _worktree_locations()
175-
assert check.ok is True
175+
assert check.ok is False
176+
assert "Unable to inspect" in check.detail
176177
assert check.optional is True
177178

178179
@pytest.mark.skipif(

‎tests_py/test_doctor_worktrees.py‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
"""Worktree parser and consumer contracts. Source: ADR-1079."""
2+
3+
import asyncio
4+
5+
import pytest
6+
7+
from mcp_server import doctor
8+
from mcp_server.handlers import check_setup
9+
10+
11+
@pytest.mark.parametrize("output", [None, "", "HEAD abc\0\0"])
12+
def test_unavailable_or_empty_listing_contract(monkeypatch, output):
13+
monkeypatch.setattr(doctor, "run_with_hard_timeout", lambda *a, **k: output)
14+
check = doctor._worktree_locations()
15+
assert check.optional
16+
if output is None:
17+
assert doctor._worktree_list() is None
18+
assert check.ok is False
19+
assert "Unable to inspect worktree locations" in check.detail
20+
assert "not a Git checkout, Git unavailable, or command failed" in check.detail
21+
assert "git worktree list --porcelain -z" in check.fix
22+
else:
23+
assert doctor._worktree_list() == []
24+
assert check.ok
25+
assert check.detail == "no registered worktrees"
26+
assert check.fix == ""
27+
28+
29+
def test_nul_parser_preserves_records_markers_and_unicode(monkeypatch, tmp_path):
30+
main = str(tmp_path / "répo")
31+
linked = str(tmp_path / "deleted")
32+
output = f"worktree {main}\0bare\0\0worktree {linked}\0prunable gone\0\0"
33+
calls = []
34+
35+
def execute(argv, **kwargs):
36+
calls.append(argv)
37+
return output
38+
39+
monkeypatch.setattr(doctor, "run_with_hard_timeout", execute)
40+
assert doctor._worktree_list() == [
41+
{"path": main, "bare": True, "prunable": False},
42+
{"path": linked, "bare": False, "prunable": True},
43+
]
44+
assert calls == [["git", "worktree", "list", "--porcelain", "-z"]]
45+
46+
47+
def test_orphan_markers_are_ignored(monkeypatch, tmp_path):
48+
output = f"bare\0prunable gone\0worktree {tmp_path}\0HEAD abc\0\0"
49+
monkeypatch.setattr(doctor, "run_with_hard_timeout", lambda *a, **k: output)
50+
assert doctor._worktree_list() == [
51+
{"path": str(tmp_path), "bare": False, "prunable": False}
52+
]
53+
54+
55+
@pytest.mark.parametrize("outside", [False, True])
56+
def test_real_worktree_check_cli_and_mcp_contract(
57+
monkeypatch, tmp_path, capsys, outside
58+
):
59+
location = tmp_path / ("outside" if outside else ".Codex/worktrees/good")
60+
entries = [{"path": str(tmp_path)}, {"path": str(location)}]
61+
monkeypatch.setattr(doctor, "_worktree_list", lambda: entries)
62+
monkeypatch.setattr(doctor, "active_checks", lambda: [doctor._worktree_locations])
63+
monkeypatch.setattr(
64+
check_setup, "active_checks", lambda: [doctor._worktree_locations]
65+
)
66+
monkeypatch.setattr(doctor.sys, "argv", ["doctor"])
67+
assert doctor.run() == 0
68+
output = capsys.readouterr().out
69+
check = doctor._worktree_locations()
70+
assert check.ok is not outside
71+
assert ("[WARN]" in output) is outside
72+
assert "[FAIL]" not in output
73+
if outside:
74+
assert str(location.resolve()) in output
75+
assert check.fix in output
76+
assert ".Codex/worktrees/<name>/" in check.fix
77+
assert ".claude/worktrees/<name>/" in check.fix
78+
else:
79+
assert check.fix == ""
80+
assert "All checks passed" in output
81+
result = asyncio.run(check_setup.handler())
82+
assert result["ready"] is True and result["fixes_needed"] == 0
83+
assert result["checks"] == [
84+
{
85+
"name": check.name,
86+
"ok": check.ok,
87+
"optional": True,
88+
"detail": check.detail,
89+
"fix_command": check.fix,
90+
}
91+
]
92+
93+
94+
def test_registries_include_optional_worktree_check():
95+
assert doctor._worktree_locations in doctor.CHECKS
96+
assert doctor._worktree_locations in doctor.SQLITE_CHECKS
97+
98+
99+
def test_bare_and_exact_root_details(tmp_path):
100+
ok, detail = doctor._worktree_classification(
101+
[{"path": str(tmp_path), "bare": True}]
102+
)
103+
assert ok and detail == "bare repository — rule not applicable"
104+
root = (tmp_path / ".Codex/worktrees").resolve()
105+
assert doctor._under(root, root)
106+
ok, detail = doctor._worktree_classification(
107+
[
108+
{"path": str(tmp_path)},
109+
{"path": str(root)},
110+
{"path": str(root)},
111+
]
112+
)
113+
assert ok and str(root) in detail
114+
assert str((tmp_path / ".claude/worktrees").resolve()) in detail
115+
116+
117+
def test_unavailable_listing_warns_without_blocking_consumers(monkeypatch, capsys):
118+
monkeypatch.setattr(doctor, "run_with_hard_timeout", lambda *a, **k: None)
119+
monkeypatch.setattr(doctor, "active_checks", lambda: [doctor._worktree_locations])
120+
monkeypatch.setattr(
121+
check_setup, "active_checks", lambda: [doctor._worktree_locations]
122+
)
123+
monkeypatch.setattr(doctor.sys, "argv", ["doctor"])
124+
assert doctor.run() == 0
125+
output = capsys.readouterr().out
126+
assert "[WARN]" in output and "[FAIL]" not in output
127+
assert "Unable to inspect worktree locations" in output
128+
assert "git worktree list --porcelain -z" in output
129+
result = asyncio.run(check_setup.handler())
130+
assert result["ready"] and result["fixes_needed"] == 0
131+
check = result["checks"][0]
132+
assert check["optional"] and not check["ok"]
133+
assert "Unable to inspect worktree locations" in check["detail"]
134+
assert "git worktree list --porcelain -z" in check["fix_command"]

‎wiki/adr/cortex/1079-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,5 @@ Derive the roots from the first worktree in `git worktree list --porcelain -z`,
2727
Positive: the owner sees worktrees outside both host directories via 'python -m mcp_server.doctor', check_setup, and the preflight command without git status noise. Negative: a marketplace user running doctor inside an unrelated repo that happens to keep worktrees elsewhere will see an advisory WARN naming a Cortex-authored convention; the fix text makes that source explicit so it reads as advisory, not a bug report.
2828

2929
Git porcelain uses NUL record delimiters with `-z`; parsing those delimiters preserves literal newlines and trailing spaces in paths (git-worktree(1), Porcelain Format). A real-Git regression verifies that an outside worktree with both characters is reported by its exact path.
30+
31+
A failed Git invocation produces an optional WARN that lists the possible causes and provides the Git command to retry. The existing subprocess helper returns no failure category, so the diagnostic does not claim a specific cause. Successful empty output is reported as no registered worktrees.

0 commit comments

Comments
 (0)