diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-11-09 17:01:41 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-09 17:01:41 -0800 |
| commit | c1316084b7ab32219aa01cc49cb62f3560175d77 (patch) | |
| tree | a4ffd379fd615bcb3ad8e702751b529f2a00ad89 /plugins | |
| parent | 350fd1722b85ff26fdcc59d8949a68399f13181d (diff) | |
| parent | d7c86c4baf977bb155870a5deadd8bf6164dd253 (diff) | |
Merge pull request #7029 from anthropics/mhegazy/sg-project-rules-after-cd
security-guidance: keep project rules after the session changes folder
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 4 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 109 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_project_rules_after_cd.py | 223 |
3 files changed, 317 insertions, 19 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index cf9fb290..d84dd126 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -96,9 +96,11 @@ Drop a `claude-security-guidance.md` in any of: - `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed - `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d +The project files keep loading after the session moves to another folder of the project (`cd src`). A `.claude` in the folder it moved to is read too, after the project's. In a linked worktree, that worktree's own files are the project files. + Project files must be regular files: a link there, or a `.claude` folder that is a link, is skipped. -All three are loaded and concatenated into the LLM diff review's prompt in the order user → project → project-local. If the combined size exceeds the 8 KB prompt budget, the tail is truncated, so user-wide rules are kept and project-local rules are dropped first. The agentic commit reviewer (layer 3) does not currently read this file. Example: +These are loaded and concatenated into the LLM diff review's prompt in the order user → project → project-local. If the combined size exceeds the 8 KB prompt budget, the tail is truncated, so user-wide rules are kept and project-local rules are dropped first. The agentic commit reviewer (layer 3) does not currently read this file. Example: ```markdown # Acme security rules diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index 1f42945d..10df6b79 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -15,6 +15,8 @@ Discovery, in precedence order (matching CLAUDE.md / settings.json): - ``$CLAUDE_CONFIG_DIR/<name>`` (user, when set to another directory) - ``<cwd>/.claude/<name>`` (project, committed) - ``<cwd>/.claude/<name>.local.<ext>`` (project local, gitignored) + - the last two again in the project's own folder (``CLAUDE_PROJECT_DIR``) + once the session has moved away from it, see ``_project_dirs`` Managed delivery via ``managed-settings.json`` is not yet supported. Org admins can still push files to ``~/.claude/`` (or the directory @@ -121,26 +123,97 @@ def _same_dir(a: str, b: str) -> bool: return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) -def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: - """Existing config file paths, lowest precedence first (so concat reads in - precedence order user → project → project-local). Truncation is done on - the concatenated string, so lowest-precedence content is dropped last.""" - paths = [("User", os.path.join(d, basename)) for d in _user_config_dirs()] - if cwd: - paths.append(("Project", os.path.join(cwd, ".claude", basename))) - # claude-security-guidance.local.md / security-patterns.local.yaml - stem, ext = os.path.splitext(basename) - paths.append(("Project (local)", os.path.join(cwd, ".claude", f"{stem}.local{ext}"))) +def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str, Optional[str]]]: + """(label, path, project folder or None for a user file) of every config + file to look for, lowest precedence first (so concat reads in precedence + order user → project → project-local). Truncation is done on the + concatenated string, so lowest-precedence content is dropped last, and a + subfolder's files never push out the project's.""" + paths: List[Tuple[str, str, Optional[str]]] = [ + ("User", os.path.join(d, basename), None) for d in _user_config_dirs()] + # claude-security-guidance.local.md / security-patterns.local.yaml + stem, ext = os.path.splitext(basename) + for folder in _project_dirs(cwd): + paths.append(("Project", os.path.join(folder, ".claude", basename), folder)) + paths.append(("Project (local)", + os.path.join(folder, ".claude", f"{stem}.local{ext}"), folder)) return paths -def _readable_config(path: str, cwd: Optional[str]) -> bool: - """Whether a config file may be read. A project file (`cwd` given) must be +def _checkout_of(path: str) -> Tuple[Optional[str], Optional[str]]: + """(top folder, shared git directory) of the checkout `path` is in, both + real paths, or (None, None). Read from disk, so no git process starts. + Linked worktrees of one repository share the second.""" + top = os.path.realpath(path) + while not os.path.lexists(os.path.join(top, ".git")): + parent = os.path.dirname(top) + if parent == top: + return None, None + top = parent + git_dir = os.path.join(top, ".git") + if os.path.isfile(git_dir): + try: + with open(git_dir, encoding="utf-8", errors="replace") as f: + text = f.read(4096) + except OSError: + return top, None + if not text.startswith("gitdir:"): + return top, None + git_dir = os.path.join(top, text[len("gitdir:"):].strip()) + try: + # A linked worktree's own git directory names the shared one here. + with open(os.path.join(git_dir, "commondir"), encoding="utf-8", errors="replace") as f: + git_dir = os.path.join(git_dir, f.read(4096).strip()) + except OSError: + pass + return top, os.path.realpath(git_dir) + + +def _is_inside(path: str, folder: str) -> bool: + """Compared on disk, so another spelling of a folder's name (case, an + 8.3 name, a link) does not matter.""" + path = os.path.realpath(path) + while not _same_dir(path, folder): + parent = os.path.dirname(path) + if parent == path: + return False + path = parent + return True + + +def _project_dirs(cwd: Optional[str]) -> List[str]: + """Folders whose ``.claude`` holds this session's project files: the + project's own when the session has moved to another folder of it + (``cd src``), then the session's current folder. In a linked worktree the + first is the same folder of the worktree, which has that branch's files. + A folder of another repository outside the project gets its own only.""" + if not cwd: + return [] + project = (os.environ.get("CLAUDE_PROJECT_DIR") or "").strip() + if not project or not os.path.isabs(project) or _same_dir(cwd, project): + return [cwd] + top, shared = _checkout_of(cwd) + project_top, project_shared = _checkout_of(project) + same_top = bool(top and project_top and _same_dir(top, project_top)) + if not same_top and shared and project_shared and _same_dir(shared, project_shared): + rel = os.path.relpath(os.path.realpath(project), project_top) + project = os.path.normpath(os.path.join(top, rel)) + elif not (same_top or _is_inside(cwd, project)): + return [cwd] + # A session started in the home folder: those are the user files. + config = os.path.join(project, ".claude") + if _same_dir(cwd, project) or any(_same_dir(config, d) for d in _user_config_dirs()): + return [cwd] + return [project, cwd] + + +def _readable_config(path: str, folder: Optional[str]) -> bool: + """Whether a config file may be read. A project file (`folder` given) must be a regular file at that very place: a link, or a `.claude` that is one, would bring in text from wherever it points.""" - if cwd is None or not os.path.lexists(path): + if folder is None or not os.path.lexists(path): return True - expected = os.path.join(os.path.realpath(cwd), os.path.relpath(path, cwd)) + expected = os.path.join(os.path.realpath(folder), os.path.relpath(path, folder)) real = os.path.realpath(path) if os.path.normcase(real) == os.path.normcase(expected) and os.path.isfile(real): return True @@ -150,8 +223,8 @@ def _readable_config(path: str, cwd: Optional[str]) -> bool: def _load_guidance(cwd: Optional[str]) -> str: parts = [] - for label, path in _config_paths(cwd, GUIDANCE_BASENAME): - if not _readable_config(path, cwd if label.startswith("Project") else None): + for label, path, folder in _config_paths(cwd, GUIDANCE_BASENAME): + if not _readable_config(path, folder): continue try: with open(path, encoding="utf-8") as f: @@ -200,7 +273,7 @@ def _wrap_guidance(guidance: str) -> str: def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: rules: List[Dict[str, Any]] = [] - for label, path in _config_paths(cwd, "security-patterns"): + for label, path, folder in _config_paths(cwd, "security-patterns"): # _config_paths returns an extensionless stem (e.g. # ".claude/security-patterns" or ".claude/security-patterns.local"); # try each supported extension. @@ -209,7 +282,7 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: # One unusable file is skipped on its own, so the rules from the # other locations still load. try: - if not _readable_config(candidate, cwd if label.startswith("Project") else None): + if not _readable_config(candidate, folder): continue found = _rules_from_file(candidate, label) except Exception as e: diff --git a/plugins/security-guidance/tests/test_project_rules_after_cd.py b/plugins/security-guidance/tests/test_project_rules_after_cd.py new file mode 100644 index 00000000..58bbe611 --- /dev/null +++ b/plugins/security-guidance/tests/test_project_rules_after_cd.py @@ -0,0 +1,223 @@ +"""Project rules and guidance keep loading after the session moves to another +folder of the project, and only then.""" +import json +import os + +import pytest + +import extensibility +from conftest import edit_payload, git, make_repo, run_hook + +GUIDANCE = extensibility.GUIDANCE_BASENAME + + +@pytest.fixture +def home(tmp_path, monkeypatch): + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + monkeypatch.setattr(extensibility, "_guidance_block", "") + monkeypatch.setattr(extensibility, "_user_patterns", []) + return home + + +@pytest.fixture +def load(home, monkeypatch): + def run(cwd, project=None): + if project is None: + monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) + else: + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) + extensibility.load_for_session(str(cwd) if cwd else cwd) + return ([r["ruleName"][5:] for r in extensibility.user_patterns()], + extensibility.guidance_block()) + return run + + +def _config(folder, name, local=False): + config = folder / ".claude" + config.mkdir(parents=True, exist_ok=True) + suffix = ".local" if local else "" + (config / f"security-patterns{suffix}.json").write_text(json.dumps({"patterns": [ + {"rule_name": name, "reminder": "x", "substrings": ["NEEDLE("]}]})) + (config / f"claude-security-guidance{suffix}.md").write_text(f"text of {name}\n") + + +@pytest.fixture +def repo(tmp_path): + r = make_repo(tmp_path / "repo", {"src/lib/a.py": "1\n"}) + _config(r, "project") + return r + + +@pytest.mark.parametrize("sub", ["src", "src/lib"]) +def test_after_cd(repo, load, sub): + rules, guidance = load(repo / sub, repo) + assert rules == ["project"] and "text of project" in guidance + + +def test_local_files_too(repo, load): + _config(repo, "local", local=True) + assert load(repo / "src", repo)[0] == ["project", "local"] + + +def test_in_the_project_folder_they_load_once(repo, load): + rules, guidance = load(repo, repo) + assert rules == ["project"] and guidance.count("text of project") == 1 + + +def test_project_folder_spelled_another_way_loads_once(repo, load): + assert load(repo, repo / "src" / "..")[0] == ["project"] + + +def test_folder_moved_to_still_counts_and_comes_after(repo, load): + _config(repo / "src", "sub") + rules, guidance = load(repo / "src", repo) + assert rules == ["project", "sub"] + assert guidance.index("text of project") < guidance.index("text of sub") + + +def test_a_subfolder_never_pushes_out_the_projects_own(repo, load, monkeypatch): + _config(repo / "src", "sub") + (repo / "src" / ".claude" / GUIDANCE).write_text("x" * 9000) + monkeypatch.setattr(extensibility, "PATTERN_MAX_RULES", 1) + rules, guidance = load(repo / "src", repo) + assert rules == ["project"] and "text of project" in guidance + + +@pytest.mark.parametrize("project", [None, "", "relative/path"]) +def test_without_a_usable_project_folder_as_before(repo, load, project): + assert load(repo / "src", project) == ([], "") + assert load(repo, project)[0] == ["project"] + + +def test_no_cwd_loads_no_project_file(repo, load): + assert load(None, repo) == ([], "") + + +def test_another_repository_outside_the_project(repo, load, tmp_path): + other = make_repo(tmp_path / "other") + _config(other, "other") + assert load(other, repo)[0] == ["other"] + + +def test_folder_outside_the_project_and_any_repository(repo, load, tmp_path): + (tmp_path / "scratch").mkdir() + assert load(tmp_path / "scratch", repo) == ([], "") + + +def test_project_spelled_in_another_case(repo, load, tmp_path): + """macOS and Windows: the same folder, whatever case it is typed in.""" + other = tmp_path / "REPO" + if not (other.exists() and os.path.samefile(other, repo)): + pytest.skip("this file system tells case apart") + assert load(other / "src", repo)[0] == ["project"] + assert load(repo / "src", other)[0] == ["project"] + + +def test_name_that_only_starts_like_the_project(repo, load, tmp_path): + (tmp_path / "repo-two").mkdir() + assert load(tmp_path / "repo-two", repo) == ([], "") + + +def test_sibling_package_of_a_monorepo(tmp_path, load): + r = make_repo(tmp_path / "mono", {"a/x.py": "1\n", "b/x.py": "1\n"}) + _config(r, "root") + _config(r / "a", "a") + # The project is `a`; the root's own files were never this session's. + assert load(r / "b", r / "a")[0] == ["a"] + + +def test_project_that_is_no_repository(tmp_path, load): + ws = tmp_path / "ws" + _config(ws, "ws") + repo = make_repo(ws / "app", {"src/x.py": "1\n"}) + assert load(repo / "src", ws)[0] == ["ws"] + + +def test_nested_repository_inside_the_project(repo, load): + nested = make_repo(repo / "vendor" / "dep") + assert load(nested, repo)[0] == ["project"] + + +class TestWorktree: + @pytest.fixture + def tree(self, repo): + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "rules") + tree = repo / ".claude" / "worktrees" / "t" + git(repo, "worktree", "add", "-q", "-b", "side", str(tree)) + _config(tree, "branch") + return tree + + def test_at_its_top_its_own_files_once(self, repo, tree, load): + assert load(tree, repo)[0] == ["branch"] + + def test_after_cd_its_own_files_not_the_main_checkouts(self, repo, tree, load): + assert load(tree / "src", repo)[0] == ["branch"] + + def test_outside_the_project_folder(self, repo, load, tmp_path): + tree = tmp_path / "elsewhere" + git(repo, "worktree", "add", "-q", "-b", "side", str(tree)) + _config(tree, "branch") + assert load(tree / "src", repo)[0] == ["branch"] + + def test_project_below_the_top(self, tmp_path, load): + r = make_repo(tmp_path / "mono", {"pkg/src/x.py": "1\n"}) + tree = tmp_path / "tree" + git(r, "worktree", "add", "-q", "-b", "side", str(tree)) + _config(tree / "pkg", "branch") + assert load(tree / "pkg" / "src", r / "pkg")[0] == ["branch"] + + def test_repositories_with_a_git_folder_elsewhere_are_not_worktrees(self, tmp_path, load): + (tmp_path / "worktrees").mkdir() + for name in ("a", "b"): + (tmp_path / name / "src").mkdir(parents=True) + git(tmp_path, "init", "-q", "--separate-git-dir", + str(tmp_path / "worktrees" / f"{name}.git"), str(tmp_path / name)) + _config(tmp_path / name, name) + assert load(tmp_path / "b" / "src", tmp_path / "a") == ([], "") + + def test_session_started_in_the_worktree(self, repo, tree, load): + assert load(tree / "src", tree)[0] == ["branch"] + + +@pytest.mark.parametrize("content", [b"", b"gitdir:", b"nonsense\n", b"gitdir: /no/such\n", b"\xff\xfe"]) +def test_odd_git_file_does_not_stop_loading(tmp_path, load, content): + ws = tmp_path / "ws" + _config(ws, "ws") + (ws / "x").mkdir() + (ws / "x" / ".git").write_bytes(content) + assert load(ws / "x", ws)[0] == ["ws"] + + +def test_home_as_the_project_does_not_load_the_user_files_twice(home, load): + _config(home, "user") + (home / "work").mkdir() + rules, guidance = load(home / "work", home) + assert rules == ["user"] and guidance.count("text of user") == 1 + + +def test_link_in_the_project_folder_is_still_skipped(tmp_path, load): + r = make_repo(tmp_path / "repo", {"src/x.py": "1\n", "secret": "outside\n"}) + (r / ".claude").mkdir() + try: + os.symlink(r / "secret", r / ".claude" / GUIDANCE) + except (OSError, NotImplementedError) as e: + pytest.skip(f"cannot make a link here: {e}") + assert load(r / "src", r)[1] == "" + + +def test_the_hook_gives_the_reminder_after_cd(workspace, hook_env, tmp_path): + _, repo = workspace + _config(repo, "project") + (repo / "src").mkdir() + home = tmp_path / "home" + home.mkdir() + env = {**hook_env, "CLAUDE_PROJECT_DIR": str(repo), "HOME": str(home), "USERPROFILE": str(home)} + env.pop("CLAUDE_CONFIG_DIR", None) + _, out, _ = run_hook( + edit_payload(repo / "src", repo / "src" / "a.py", "NEEDLE(1)\n"), env) + assert "additionalContext" in out |
