mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(learn): keep CLAUDE.local.md out of git via .git/info/exclude (#3108)
## Description
`headroom learn` writes per-project learnings to `CLAUDE.local.md`
rather than the team-shared `CLAUDE.md` (#1115, for #1072). The premise
is that `CLAUDE.local.md` is personal and gitignored — `writer.py` says
so in its own docstring — but nothing makes that true. Git ships no
default rule for the name, Claude Code does not add one, and no ignore
rule is written at learn time. The file is therefore swept up by the
next `git add -A`, and the machine-specific absolute paths inside it
reach teammates anyway. The pollution #1072 set out to prevent just
moved one filename over.
This is item 3 of #1070 ("Add `*.local.md` to the gitignore template"),
the half that never shipped. The codebase already half-acknowledges the
gap: `writer.py:317` builds a `gitignore_hint` telling users to add the
rule by hand, but it is only attached to the legacy-`CLAUDE.md`
migration warning, so users who never had a legacy block never see it.
Closes #1070
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- Add `_ensure_git_ignored()`, which registers the written filename in
`.git/info/exclude` after a non-dry-run write.
- Use `.git/info/exclude` rather than the repo's `.gitignore`: the
exclude file is per-clone and untracked, so Headroom never leaves an
unexpected diff in a team-shared file. Writing to `.gitignore` would
trade one kind of pollution for another.
- Resolve the exclude path through `git rev-parse --git-common-dir` so
linked worktrees share the entry.
- Gate on `git check-ignore` so a rule the user already has (or one we
wrote on a previous run) is left alone and never duplicated.
- Emit a `WriteResult.warnings` entry instead when the file is **already
tracked**: git honors no ignore rule for tracked paths, so only `git rm
--cached` fixes it, and running that here would silently stage a
deletion in the user's repo.
- Gate the whole thing on `target_path.name.endswith(".local.md")`, so
an explicit `--target CLAUDE.md` (a deliberate opt-in to the shared
file) and the home-directory `~/.claude/CLAUDE.md` case are untouched.
The latter matters because `~/.claude` is often itself a dotfiles repo.
- Best-effort by design: no git on PATH, not a repo, or a read-only
`.git` all no-op rather than failing the write.
The entry is deliberately unanchored (`CLAUDE.local.md`, not
`/CLAUDE.local.md`). A project may be a subdirectory of a larger repo,
so anchoring would require the path relative to the repo root; and a
`CLAUDE.local.md` at any depth is personal by the same argument.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
New tests drive real `git` in a real temp repo rather than mocking it —
the behavior under test *is* git's, and a mocked `check-ignore` would
assert nothing.
### Test Output
```text
$ uv run --frozen --extra dev pytest tests/test_learn/test_writer.py
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_apply_adds_exclude_entry PASSED [ 83%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_second_run_does_not_duplicate_the_entry PASSED [ 86%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_existing_gitignore_rule_is_left_alone PASSED [ 89%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_tracked_file_warns_instead_of_excluding PASSED [ 91%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_dry_run_does_not_touch_exclude PASSED [ 94%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_explicit_shared_target_is_never_excluded PASSED [ 97%]
tests/test_learn/test_writer.py::TestClaudeLocalMdStaysOutOfGit::test_outside_a_git_repo_is_a_no_op PASSED [100%]
============================== 37 passed in 2.53s ==============================
$ uvx ruff check headroom/learn/writer.py tests/test_learn/test_writer.py
All checks passed!
$ uvx ruff format --check headroom/learn/writer.py tests/test_learn/test_writer.py
2 files already formatted
$ uv run --frozen --extra dev mypy headroom/learn/writer.py
Success: no issues found in 1 source file
```
## Real Behavior Proof
- Environment: macOS 15.6 (darwin 24.6.0), Python 3.12, git 2.51.0,
worktree off `upstream/main` @ 7ef736fb
- Exact command / steps: `git init` a scratch repo, then run
`ClaudeCodeWriter().write([rec], proj, dry_run=False)` against it with
`dry_run=False`, once with this patch stashed and once with it applied;
then a third run against a repo where `CLAUDE.local.md` was already `git
add`ed.
- Observed result: before the patch, `git status --short
--untracked-files=all` in the learned-on repo reports `??
CLAUDE.local.md`, i.e. the file is staged by the next `git add -A`.
After the patch, `git status` is empty, `.git/info/exclude` gains a
comment line plus the bare name `CLAUDE.local.md`, and `ls` confirms the
file is still on disk. In the already-tracked repo the write returns
exactly one warning: ``/tmp/hr-proof/tracked/CLAUDE.local.md is tracked
in git, so learned patterns (including absolute paths from this machine)
are committed and shared with your team. Run `git rm --cached
CLAUDE.local.md` to untrack it; the file itself stays on disk.``
- Not tested: Windows. The implementation shells out to `git` with no
path separators of its own and falls back to a no-op on
`OSError`/`FileNotFoundError`, so the failure mode there is "no ignore
rule written", not a crash — but I have not run it on Windows.
## Runtime Rollout Safety
- Rollout-managed feature(s): none — this is a `learn` write-path fix,
not a proxy/runtime feature.
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, but only additively — a line is
appended to `.git/info/exclude` (never a tracked file) when `learn
--apply` writes `CLAUDE.local.md` into a git repo that does not already
ignore it. No change to what is written into the context file itself.
- Kill switch / disable path: `--target <name>` with any name not ending
in `.local.md` skips the logic entirely. A user who wants the file
tracked deletes the one line from `.git/info/exclude`; nothing rewrites
it, because `check-ignore` is not consulted for tracked files and the
entry is only added when absent.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the commit — the only persistent artifact is the
`.git/info/exclude` line, which is inert once the code is gone and
removable by hand.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
### Out of scope
`CodexWriter`, `GeminiWriter`, and `GrokWriter` still write straight to
the shared `AGENTS.md` / `GEMINI.md` / `GROK.md` with no `.local.md`
variant at all — the other half of #1070. That is a behavior change
rather than a leak fix, so it belongs in its own PR. Happy to follow up
if you want it.
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5
JerrettDavis
parent
231a627702
commit
c072251c10
@@ -7,10 +7,13 @@ injection mechanism for each agent system (CLAUDE.md, .cursorrules, etc.).
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from headroom._subprocess import run
|
||||
|
||||
from ._shared import claude_config_dir
|
||||
from .models import (
|
||||
ProjectInfo,
|
||||
@@ -205,6 +208,79 @@ def _strip_marker_block(content: str) -> str:
|
||||
return cleaned + "\n" if cleaned else ""
|
||||
|
||||
|
||||
def _git(repo: Path, *argv: str) -> subprocess.CompletedProcess | None:
|
||||
"""Run a git command in ``repo``; None when git is absent or hangs."""
|
||||
try:
|
||||
return run(
|
||||
["git", *argv],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=repo,
|
||||
timeout=5,
|
||||
)
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def _ensure_git_ignored(target_path: Path, dry_run: bool) -> str | None:
|
||||
"""Keep a personal context file out of git via ``.git/info/exclude``.
|
||||
|
||||
``CLAUDE.local.md`` is only personal if git actually ignores it, and nothing
|
||||
makes that true by default: git ships no rule for the name and neither does
|
||||
Claude Code, so the file lands in the next ``git add -A`` and the machine-
|
||||
specific absolute paths inside it reach teammates anyway -- the exact
|
||||
outcome issue #1072 set out to prevent.
|
||||
|
||||
Writes to the per-clone exclude file rather than the repo's ``.gitignore``
|
||||
because the latter is team-shared and committed: appending to it would leave
|
||||
an unexpected diff in someone else's repo, trading one kind of pollution for
|
||||
another. Returns a warning instead of acting when the file is already
|
||||
tracked -- git honors no ignore rule for tracked files, so only
|
||||
``git rm --cached`` can fix that, and running it here would silently stage a
|
||||
deletion in the user's repo.
|
||||
"""
|
||||
repo = target_path.parent
|
||||
name = target_path.name
|
||||
|
||||
common_dir = _git(repo, "rev-parse", "--git-common-dir")
|
||||
if common_dir is None or common_dir.returncode != 0:
|
||||
return None # not a git repo, or no git on PATH: nothing to ignore
|
||||
|
||||
tracked = _git(repo, "ls-files", "--error-unmatch", "--", name)
|
||||
if tracked is not None and tracked.returncode == 0:
|
||||
return (
|
||||
f"{target_path} is tracked in git, so learned patterns (including "
|
||||
f"absolute paths from this machine) are committed and shared with "
|
||||
f"your team. Run `git rm --cached {name}` to untrack it; the file "
|
||||
f"itself stays on disk."
|
||||
)
|
||||
|
||||
ignored = _git(repo, "check-ignore", "-q", "--", name)
|
||||
if ignored is not None and ignored.returncode == 0:
|
||||
return None # already covered by .gitignore or a previous run
|
||||
|
||||
if dry_run:
|
||||
return None
|
||||
|
||||
# Deliberately unanchored: a CLAUDE.local.md at any depth is personal, and
|
||||
# anchoring would need the path relative to the repo root, which differs
|
||||
# when the project is a subdirectory of a larger repo.
|
||||
# git shares info/exclude across linked worktrees via the common dir.
|
||||
exclude = Path(common_dir.stdout.strip() or ".git")
|
||||
exclude = (repo / exclude / "info" / "exclude").resolve()
|
||||
try:
|
||||
exclude.parent.mkdir(parents=True, exist_ok=True)
|
||||
prior = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
|
||||
prefix = "" if not prior or prior.endswith("\n") else "\n"
|
||||
exclude.write_text(
|
||||
f"{prior}{prefix}\n# Personal `headroom learn` output, not team-shared\n{name}\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
except OSError:
|
||||
return None # read-only .git, exotic setup: the write is best-effort
|
||||
return None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Claude Code Writer
|
||||
# =============================================================================
|
||||
@@ -249,6 +325,13 @@ class ClaudeCodeWriter(ContextWriter):
|
||||
|
||||
if context_recs:
|
||||
target_path = self._resolve_context_path(project)
|
||||
# Only ever auto-ignore a file whose name marks it personal: an
|
||||
# explicit --target CLAUDE.md is a deliberate opt-in to the shared
|
||||
# file, and ~/.claude/CLAUDE.md may sit in a dotfiles repo.
|
||||
if target_path.name.endswith(".local.md"):
|
||||
tracked_warning = _ensure_git_ignored(target_path, dry_run)
|
||||
if tracked_warning:
|
||||
result.warnings.append(tracked_warning)
|
||||
# Migrate any stale block left in the team-shared CLAUDE.md by older
|
||||
# headroom versions into the new target, then strip it from CLAUDE.md
|
||||
# so the shared file is no longer polluted.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for recommendation writer — marker-based file updates."""
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -575,6 +576,128 @@ class TestEncodingResilience:
|
||||
assert raw.count(b"\r") == raw.count(b"\r\n")
|
||||
|
||||
|
||||
def _git(proj: ProjectInfo, *args: str, check: bool = True) -> subprocess.CompletedProcess:
|
||||
"""Run git against the test repo, under the isolated config below."""
|
||||
return subprocess.run(["git", *args], cwd=proj.project_path, check=check, capture_output=True)
|
||||
|
||||
|
||||
def _git_project(tmp_path: Path) -> ProjectInfo:
|
||||
"""A project whose directory is a real git repo."""
|
||||
proj = _project(tmp_path)
|
||||
_git(proj, "init", "-q")
|
||||
return proj
|
||||
|
||||
|
||||
def _exclude(proj: ProjectInfo) -> Path:
|
||||
return proj.project_path / ".git" / "info" / "exclude"
|
||||
|
||||
|
||||
def _exclude_entries(proj: ProjectInfo) -> list[str]:
|
||||
"""The repo-local exclude rules this PR is responsible for, one per line."""
|
||||
path = _exclude(proj)
|
||||
if not path.exists():
|
||||
return []
|
||||
return [line.strip() for line in path.read_text().splitlines() if line.strip()]
|
||||
|
||||
|
||||
def _is_ignored(proj: ProjectInfo, name: str) -> bool:
|
||||
return _git(proj, "check-ignore", "-q", "--", name, check=False).returncode == 0
|
||||
|
||||
|
||||
class TestClaudeLocalMdStaysOutOfGit:
|
||||
"""CLAUDE.local.md is only personal if git actually ignores it (#1070)."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolated_git_config(self, monkeypatch, tmp_path):
|
||||
"""Decide these tests on the repository alone, on every machine.
|
||||
|
||||
``git check-ignore`` consults ``core.excludesFile`` from the developer's
|
||||
global and system config, and the writer shells out to it too (it skips
|
||||
adding a rule when one already covers the file). So a contributor whose
|
||||
global ignore lists CLAUDE.md or CLAUDE.local.md saw this suite fail
|
||||
while the writer was behaving correctly. Patching the environment rather
|
||||
than a helper covers the writer's own subprocess as well as ours.
|
||||
"""
|
||||
absent = tmp_path / "absent-gitconfig"
|
||||
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(absent))
|
||||
monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(absent))
|
||||
monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
|
||||
def test_apply_adds_exclude_entry(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
result = ClaudeCodeWriter().write(recs, proj, dry_run=False)
|
||||
|
||||
assert "CLAUDE.local.md" in _exclude(proj).read_text()
|
||||
# The point is the effect, not the file contents.
|
||||
assert _is_ignored(proj, "CLAUDE.local.md")
|
||||
assert result.warnings == []
|
||||
|
||||
def test_second_run_does_not_duplicate_the_entry(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
writer = ClaudeCodeWriter()
|
||||
|
||||
writer.write(recs, proj, dry_run=False)
|
||||
writer.write(recs, proj, dry_run=False)
|
||||
|
||||
assert _exclude(proj).read_text().count("CLAUDE.local.md") == 1
|
||||
|
||||
def test_existing_gitignore_rule_is_left_alone(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
(proj.project_path / ".gitignore").write_text("CLAUDE.local.md\n")
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
ClaudeCodeWriter().write(recs, proj, dry_run=False)
|
||||
|
||||
assert not _exclude(proj).exists() or "CLAUDE.local.md" not in _exclude(proj).read_text()
|
||||
|
||||
def test_tracked_file_warns_instead_of_excluding(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
local = proj.project_path / "CLAUDE.local.md"
|
||||
local.write_text("# prior\n")
|
||||
_git(proj, "add", "CLAUDE.local.md")
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
result = ClaudeCodeWriter().write(recs, proj, dry_run=False)
|
||||
|
||||
# An ignore rule does nothing for a tracked file, so say so rather than
|
||||
# staging a deletion in the user's repo on their behalf.
|
||||
assert len(result.warnings) == 1
|
||||
assert "git rm --cached CLAUDE.local.md" in result.warnings[0]
|
||||
assert not _exclude(proj).exists() or "CLAUDE.local.md" not in _exclude(proj).read_text()
|
||||
|
||||
def test_dry_run_does_not_touch_exclude(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
ClaudeCodeWriter().write(recs, proj, dry_run=True)
|
||||
|
||||
assert not _exclude(proj).exists() or "CLAUDE.local.md" not in _exclude(proj).read_text()
|
||||
|
||||
def test_explicit_shared_target_is_never_excluded(self, tmp_path):
|
||||
proj = _git_project(tmp_path)
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
ClaudeCodeWriter(context_target="CLAUDE.md").write(recs, proj, dry_run=False)
|
||||
|
||||
# --target CLAUDE.md is a deliberate opt-in to the team-shared file, so
|
||||
# the writer must not add a rule for it. Assert the side effect this PR
|
||||
# actually owns - the repo's own exclude file - as well as the effect.
|
||||
assert "CLAUDE.md" not in _exclude_entries(proj)
|
||||
assert not _is_ignored(proj, "CLAUDE.md")
|
||||
|
||||
def test_outside_a_git_repo_is_a_no_op(self, tmp_path):
|
||||
proj = _project(tmp_path) # no git init
|
||||
recs = [_rec(RecommendationTarget.CONTEXT_FILE, "Environment", "- Use uv")]
|
||||
|
||||
result = ClaudeCodeWriter().write(recs, proj, dry_run=False)
|
||||
|
||||
assert (proj.project_path / "CLAUDE.local.md").exists()
|
||||
assert result.warnings == []
|
||||
|
||||
|
||||
@pytest.mark.windows_newline
|
||||
class TestNewlineContract:
|
||||
"""Regression guard for #3594 / #3698 — every learn-writer write pins LF.
|
||||
|
||||
Reference in New Issue
Block a user