Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(learn): keep CLAUDE.local.md out of git via .git/info/exclude (#3108)
gglucassc072251c10a1
diff --git a/headroom/learn/writer.py b/headroom/learn/writer.pyindex 06d90fcb5..f031dd158 100644--- a/headroom/learn/writer.py+++ b/headroom/learn/writer.py@@ -7,10 +7,13 @@ injection mechanism for each agent system (CLAUDE.md, .cursorrules, etc.).from __future__ import annotationsimport re+import subprocessfrom abc import ABC, abstractmethodfrom datetime import datetime, timezonefrom pathlib import Path+from headroom._subprocess import run+from ._shared import claude_config_dirfrom .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.diff --git a/tests/test_learn/test_writer.py b/tests/test_learn/test_writer.pyindex a88c4e66a..4af3dd5bc 100644--- a/tests/test_learn/test_writer.py+++ b/tests/test_learn/test_writer.py@@ -1,5 +1,6 @@"""Tests for recommendation writer — marker-based file updates."""+import subprocessfrom pathlib import Pathimport 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_newlineclass TestNewlineContract:"""Regression guard for #3594 / #3698 — every learn-writer write pins LF.