summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests/test_project_rules_after_cd.py
blob: 58bbe611fd598d8d24aa16a1f096c58eb4f29d78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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