Skip to content

Commit 7fcb1cb

Browse files
committed
fix(doctor): honor host worktree roots and preserve Git paths (#602)
1 parent 6714ed9 commit 7fcb1cb

9 files changed

Lines changed: 152 additions & 88 deletions

‎CHANGELOG.md‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,12 @@ adheres to [Semantic Versioning](https://semver.org/).
5555

5656
### Fixed
5757

58-
- **`.gitignore`'s `.Codex/` rule was unanchored, so it matched at any
59-
depth (#601 follow-up, ADR-1078).** `git status` silently swallowed any
60-
nested `.Codex` directory anywhere in the tree, not just the repo-root
61-
one PR #601 intended. Anchored to `/.Codex/`. The condition that rule
62-
was hiding — a git worktree outside `.claude/worktrees/`, the only
63-
location `docs/agent-guidance.md` names — is now reported, never
64-
silenced: `python -m mcp_server.doctor` (and `check_setup`,
65-
`/preflight`) gained an optional, non-blocking `worktree locations`
66-
check that lists any `git worktree list --porcelain` entry outside
67-
`<main-worktree>/.claude/worktrees/`, sourced from the main worktree's
68-
own listing rather than `git rev-parse --show-toplevel` (which
69-
resolves to a linked worktree's own path and would false-positive on
70-
every sibling). The worktree itself is left exactly where it is.
58+
- **Report worktrees outside the repository host directories (#602, ADR-1079).**
59+
Anchor the `.Codex/` ignore rule to the repository root. The optional
60+
doctor check accepts `.Codex/worktrees/` and `.claude/worktrees/`, using
61+
the main checkout as its root even when called from a linked checkout.
62+
Outside worktrees produce a warning without changing the exit code.
63+
NUL-delimited Git output preserves newlines and spaces in their paths.
7164

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

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

Lines changed: 0 additions & 27 deletions
This file was deleted.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<!-- Generated by Cortex wiki_reindex from wiki/adr/cortex/1079-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md; ADR-1079. Read-only mirror: edit the canonical wiki page. -->
2+
3+
---
4+
created: 2026-09-16T21:21:15Z
5+
kind: adr
6+
number: 1079
7+
status: accepted
8+
tags: [doctor, worktree, diagnostics]
9+
title: Report out-of-convention git worktrees as an optional doctor WARN
10+
---
11+
# ADR-1079: Report out-of-convention git worktrees as an optional doctor WARN
12+
13+
## Status
14+
15+
accepted
16+
17+
## Context
18+
19+
PR #601 left an unanchored `.Codex/` ignore rule. The repository guidance previously allowed only `.claude/worktrees/`, while the current Codex instructions mandate `.Codex/worktrees/`. Each host needs its own repository-local directory.
20+
21+
## Decision
22+
23+
Anchor the ignore rule to `/.Codex/`. Add an optional doctor warning for registered worktrees outside both `<main-worktree>/.claude/worktrees/` and `<main-worktree>/.Codex/worktrees/`. Keep the existing Claude convention and honor the current Codex instructions. Update the repository guidance to name both host locations.
24+
25+
Derive the roots from the first worktree in `git worktree list --porcelain -z`, which git-worktree(1) documents as the main worktree. This also works from a linked checkout. Skip bare repositories and prunable entries. The check never moves a worktree and never changes the doctor exit code.
26+
27+
## Consequences
28+
29+
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.
30+
31+
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.

‎docs/agent-guidance.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,11 @@ separate **cortex-viz** MCP (reads this same store read-only).
158158
absent re-ranker, 6 benchmarks invalidated) came from exactly this.
159159
`HF_HOME`/`cache_dir` must be persistent.
160160
- Do NOT create git worktrees outside this repository — no `/private/tmp/cortex-*`,
161-
no `../Cortex-wt-*` sibling, no `~/.claude/worktrees/`. The only location is
162-
`.claude/worktrees/<name>/` (already gitignored via `.claude/*`): it is where
161+
no `../Cortex-wt-*` sibling, no `~/.claude/worktrees/`. The allowed locations are
162+
`.Codex/worktrees/<name>/` for Codex (current AGENTS.md instructions) and
163+
`.claude/worktrees/<name>/` for Claude Code (gitignored via `.claude/*`). The latter is where
163164
Claude Code's own worktree tooling (`isolation: worktree`, `EnterWorktree`,
164-
`--worktree`) puts them and the only directory its cleanup sweep looks at.
165+
`--worktree`) puts them and the directory its cleanup sweep looks at.
165166
Owner correction 2026-09-08, after 76 outside worktrees (43 detached + 33 on
166167
branches, all under `/private/tmp/cortex-green-*`) had to be removed by hand.
167168
`scripts/spawn-agent.sh` and `benchmarks/lib/bench_regression.sh` follow this.

‎mcp_server/doctor.py‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def _codebase_pipeline() -> Check:
252252

253253

254254
def _worktree_list() -> list[dict[str, object]] | None:
255-
"""Parse ``git worktree list --porcelain``, main worktree first.
255+
"""Parse ``git worktree list --porcelain -z``, main worktree first.
256256
257257
precondition: none — safe to call outside a git checkout.
258258
postcondition: returns one dict per worktree block, in the order git
@@ -263,22 +263,22 @@ def _worktree_list() -> list[dict[str, object]] | None:
263263
of ``run_with_hard_timeout`` collapses to the same "not applicable"
264264
signal, never a raised exception.
265265
266-
source: ADR-1078"""
266+
source: ADR-1079"""
267267
out = run_with_hard_timeout(
268-
["git", "worktree", "list", "--porcelain"],
268+
["git", "worktree", "list", "--porcelain", "-z"],
269269
cwd=Path.cwd(),
270270
timeout=_WORKTREE_LIST_TIMEOUT_S,
271271
)
272272
if out is None:
273273
return None
274274
entries: list[dict[str, object]] = []
275275
current: dict[str, object] | None = None
276-
for line in out.splitlines():
276+
for line in out.split("\0"):
277277
if line.startswith("worktree "):
278278
if current is not None:
279279
entries.append(current)
280280
current = {
281-
"path": line[len("worktree ") :].strip(),
281+
"path": line[len("worktree ") :],
282282
"bare": False,
283283
"prunable": False,
284284
}
@@ -297,44 +297,51 @@ def _worktree_classification(entries: list[dict[str, object]]) -> tuple[bool, st
297297
298298
postcondition: ``ok`` is True for "not a git checkout" (empty
299299
``entries``), a bare main repo, and full compliance; False carries
300-
every offending resolved path in ``detail``. The allowed root is
300+
every offending resolved path in ``detail``. The allowed roots are
301301
derived from ``entries[0]`` (the main worktree — always first, per
302302
git-worktree(1) section list), never from ``git rev-parse
303303
--show-toplevel``, which resolves to a linked worktree's own path
304304
when run from inside one and would false-positive on every sibling.
305305
306-
source: ADR-1078 (rule: docs/agent-guidance.md:160-166)"""
306+
source: ADR-1079 (rule: docs/agent-guidance.md, What NOT to do)"""
307307
if not entries:
308308
return True, "not a git checkout"
309309
main = entries[0]
310310
if main.get("bare"):
311311
return True, "bare repository — rule not applicable"
312-
allowed_root = (Path(str(main["path"])) / ".claude" / "worktrees").resolve()
312+
allowed_roots = [
313+
(Path(str(main["path"])) / host / "worktrees").resolve()
314+
for host in (".claude", ".Codex")
315+
]
313316
outside = [
314317
str(Path(str(e["path"])).resolve())
315318
for e in entries[1:]
316319
if not e.get("prunable")
317-
and not _under(Path(str(e["path"])).resolve(), allowed_root)
320+
and not any(
321+
_under(Path(str(e["path"])).resolve(), root) for root in allowed_roots
322+
)
318323
]
324+
allowed = " or ".join(map(str, allowed_roots))
319325
if not outside:
320-
return True, f"all worktrees under {allowed_root}"
321-
return False, f"outside {allowed_root}: {', '.join(outside)}"
326+
return True, f"all worktrees under {allowed}"
327+
return False, f"outside {allowed}: {', '.join(outside)}"
322328

323329

324330
def _worktree_locations() -> Check:
325331
"""Optional: WARN when a registered worktree lives outside
326-
``<main-worktree>/.claude/worktrees/``. Reports only — never fixes,
332+
the host-specific ``.claude/worktrees`` or ``.Codex/worktrees``.
333+
Reports only — never fixes,
327334
never moves the worktree, never fails doctor's exit code
328335
(``optional=True``).
329336
330-
source: ADR-1078 (rule reported: docs/agent-guidance.md:160-166)"""
337+
source: ADR-1079 (rule reported: docs/agent-guidance.md, What NOT to do)"""
331338
ok, detail = _worktree_classification(_worktree_list() or [])
332339
fix = (
333340
""
334341
if ok
335-
else "Move or remove these worktrees — the only allowed location "
336-
"is <repo>/.claude/worktrees/<name>/ "
337-
"(source: docs/agent-guidance.md:160-166)."
342+
else "Move or remove these worktrees — the allowed locations "
343+
"are <repo>/.claude/worktrees/<name>/ or <repo>/.Codex/worktrees/<name>/ "
344+
"(source: docs/agent-guidance.md, What NOT to do)."
338345
)
339346
return Check("worktree locations (optional)", ok, detail, fix, optional=True)
340347

‎tests_py/test_doctor.py‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from __future__ import annotations
1212

1313
import subprocess
14+
import sys
1415

1516
import pytest
1617

@@ -23,6 +24,7 @@
2324
_python_version,
2425
_sqlite_store,
2526
_worktree_locations,
27+
_worktree_classification,
2628
active_checks,
2729
ensure_reranker_ready,
2830
run,
@@ -120,9 +122,47 @@ def real_git_repo(tmp_path):
120122

121123

122124
class TestWorktreeLocations:
123-
"""source: ADR-1078 — the check reports docs/agent-guidance.md:160-166,
125+
"""source: ADR-1079 — the check reports docs/agent-guidance.md, What NOT to do,
124126
never blocks (optional=True), never rewrites the rule."""
125127

128+
@pytest.mark.parametrize("host", [".claude", ".Codex"])
129+
def test_host_worktree_passes_from_linked_checkout(
130+
self, real_git_repo, monkeypatch, host
131+
):
132+
linked = real_git_repo / host / "worktrees" / "good"
133+
subprocess.run(
134+
["git", "worktree", "add", "-q", "--detach", str(linked)],
135+
cwd=real_git_repo,
136+
check=True,
137+
)
138+
monkeypatch.chdir(linked)
139+
check = _worktree_locations()
140+
assert check.ok is True
141+
assert check.optional is True
142+
143+
def test_both_hosts_and_prunable_entries(self, tmp_path):
144+
entries = [{"path": str(tmp_path)}] + [
145+
{"path": str(tmp_path / host / "worktrees" / "good")}
146+
for host in (".claude", ".Codex")
147+
]
148+
entries.append({"path": str(tmp_path / "removed"), "prunable": True})
149+
assert _worktree_classification(entries)[0] is True
150+
assert _worktree_classification([{"path": str(tmp_path), "bare": True}])[0]
151+
152+
def test_rejects_prefix_sibling_and_symlink_escape(self, tmp_path):
153+
allowed = tmp_path / ".Codex" / "worktrees"
154+
allowed.mkdir(parents=True)
155+
outside = tmp_path / ".Codex" / "worktrees-other"
156+
outside.mkdir()
157+
link = allowed / "escape"
158+
link.symlink_to(outside, target_is_directory=True)
159+
for path in (outside, link):
160+
ok, detail = _worktree_classification(
161+
[{"path": str(tmp_path)}, {"path": str(path)}]
162+
)
163+
assert ok is False
164+
assert str(outside.resolve()) in detail
165+
126166
def test_main_checkout_only_passes(self, real_git_repo, monkeypatch):
127167
monkeypatch.chdir(real_git_repo)
128168
check = _worktree_locations()
@@ -135,6 +175,21 @@ def test_not_a_git_checkout_passes(self, tmp_path, monkeypatch):
135175
assert check.ok is True
136176
assert check.optional is True
137177

178+
@pytest.mark.skipif(
179+
sys.platform == "win32", reason="Windows forbids newlines in paths"
180+
)
181+
def test_reports_exact_path_with_newline(self, real_git_repo, monkeypatch):
182+
outside = real_git_repo.parent / "outside\nworktree "
183+
subprocess.run(
184+
["git", "worktree", "add", "-q", "--detach", str(outside)],
185+
cwd=real_git_repo,
186+
check=True,
187+
)
188+
monkeypatch.chdir(real_git_repo)
189+
check = _worktree_locations()
190+
assert check.ok is False
191+
assert str(outside.resolve()) in check.detail
192+
138193
def test_flags_worktree_outside_claude_worktrees(self, real_git_repo, monkeypatch):
139194
subprocess.run(
140195
["git", "worktree", "add", "-q", ".claude/worktrees/good", "-b", "good"],

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

Lines changed: 0 additions & 25 deletions
This file was deleted.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
created: 2026-09-16T21:21:15Z
3+
kind: adr
4+
number: 1079
5+
status: accepted
6+
tags: [doctor, worktree, diagnostics]
7+
title: Report out-of-convention git worktrees as an optional doctor WARN
8+
---
9+
# ADR-1079: Report out-of-convention git worktrees as an optional doctor WARN
10+
11+
## Status
12+
13+
accepted
14+
15+
## Context
16+
17+
PR #601 left an unanchored `.Codex/` ignore rule. The repository guidance previously allowed only `.claude/worktrees/`, while the current Codex instructions mandate `.Codex/worktrees/`. Each host needs its own repository-local directory.
18+
19+
## Decision
20+
21+
Anchor the ignore rule to `/.Codex/`. Add an optional doctor warning for registered worktrees outside both `<main-worktree>/.claude/worktrees/` and `<main-worktree>/.Codex/worktrees/`. Keep the existing Claude convention and honor the current Codex instructions. Update the repository guidance to name both host locations.
22+
23+
Derive the roots from the first worktree in `git worktree list --porcelain -z`, which git-worktree(1) documents as the main worktree. This also works from a linked checkout. Skip bare repositories and prunable entries. The check never moves a worktree and never changes the doctor exit code.
24+
25+
## Consequences
26+
27+
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.
28+
29+
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.

‎wiki/manifest.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3480,9 +3480,9 @@
34803480
"mirror": "ADR-1077-the-advertised-tool-count-is-read-from-the-registries.md",
34813481
"path": "adr/cortex/1077-the-advertised-tool-count-is-read-from-the-registries.md"
34823482
},
3483-
"ADR-1078": {
3484-
"mirror": "ADR-1078-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md",
3485-
"path": "adr/cortex/1078-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md"
3483+
"ADR-1079": {
3484+
"mirror": "ADR-1079-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md",
3485+
"path": "adr/cortex/1079-report-out-of-convention-git-worktrees-as-an-optional-doctor-warn.md"
34863486
}
34873487
},
34883488
"project": "cortex",

0 commit comments

Comments
 (0)