Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(init): keep secret ignore rules inside .repowise/ and stop counting it as a dirty tree (#4496)

Raghav Chamadiya203f48a5d8da
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index e7e8a3748..47c0869a6 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -22,9 +22,11 @@ Everything Repowise knows about your repository, created at the repo root by
└── .env # API keys (gitignored automatically)
```
-Repowise adds `.repowise/` to `.gitignore`: it is a local cache, not a source
-of truth. Only [`decisions.yaml`](#repowisedecisionsyaml) is meant to be
-committed.
+`.repowise/` is a local cache, not a source of truth: add it to your
+`.gitignore` if you like, as Repowise does not edit that file during `init`. Only
+[`decisions.yaml`](#repowisedecisionsyaml) is meant to be committed. The secrets
+`.env` and `events.key` are ignored by `.repowise/.gitignore`, so they stay out
+of git even where `.repowise/` is committed.
## `config.yaml`
diff --git a/packages/cli/src/repowise/cli/_helpers/config.py b/packages/cli/src/repowise/cli/_helpers/config.py
index f151795ed..18d2794ef 100644
--- a/packages/cli/src/repowise/cli/_helpers/config.py
+++ b/packages/cli/src/repowise/cli/_helpers/config.py
@@ -111,9 +111,8 @@ def _persist_provider_key(repo_path: Path, provider: str) -> None:
hand-rolled write would leave a committable secret.
Best-effort by design. It runs at the tail of a completed init, after the
- index has been paid for, and it is the first thing on that path to write
- outside ``.repowise/``, so a read-only checkout or an unwritable
- ``.gitignore`` must cost the user a warning, not the run.
+ index has been paid for, so a read-only checkout or an unwritable
+ ``.repowise/.gitignore`` must cost the user a warning, not the run.
"""
from repowise.cli import helpers as _facade # patch point for tests
from repowise.core.providers.llm.registry import PROVIDER_API_KEY_ENVS
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index 9e5d7aa71..f9114c183 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -215,11 +215,18 @@ def change_features_from_stored(
def working_tree_is_dirty(repo_path: str) -> bool:
- """Whether the checkout holds staged, unstaged or untracked changes."""
+ """Whether the checkout holds staged, unstaged or untracked changes.
+
+ The repo's own ``.repowise/`` does not count: it is repowise's state, never
+ a change to the code, and a fresh ``init`` leaves it untracked.
+ """
# check=False so a non-repo path answers "not dirty" rather than raising:
# the caller falls back to scoring a committed ref, which then reports the
# real git error with its own revspec in the message.
- return bool(_git(["status", "--porcelain"], repo_path, check=False).strip())
+ # The exclude pathspec is relative to repo_path, so a package's .repowise/
+ # inside a larger git repo is the one left out.
+ status = _git(["status", "--porcelain", "--", ":(exclude).repowise"], repo_path, check=False)
+ return bool(status.strip())
def extract_worktree_features(
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index 7c01e7363..ca866d68b 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -377,13 +377,15 @@ def write_private_file(
"""Write a secret ``.repowise/<name>``: git-ignored first, owner-only after.
Some repositories commit ``.repowise/`` for its shared config, so a secret
- there needs its own ignore rule. Ignore rule first, secret second: if the
- .gitignore write fails (a read-only checkout, a root-owned file) this
- raises before the secret is on disk rather than after, which costs the
- caller a saved secret instead of leaving a committable one behind.
+ there needs its own ignore rule. It goes in ``.repowise/.gitignore``, not
+ the repo root's: nothing outside ``.repowise/`` is touched, and the rule
+ travels with the directory when it is committed. Ignore rule first, secret
+ second: if that write fails this raises before the secret is on disk
+ rather than after, which costs the caller a saved secret instead of
+ leaving a committable one behind.
"""
if ignore:
- _ensure_gitignored(repo_path, f".repowise/{name}", comment)
+ _ensure_gitignored(repo_path, name, comment)
path = get_repowise_dir(repo_path) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
@@ -439,24 +441,23 @@ def ensure_manifest_tracked(repo_path: Path | str) -> bool:
return True
-def _ensure_gitignored(repo_path: Path | str, pattern: str, comment: str) -> None:
- """Add *pattern* to the repo's ``.gitignore`` unless git already ignores it."""
- gitignore = Path(repo_path) / ".gitignore"
- if _git_ignores(repo_path, pattern):
- return # e.g. a ``.repowise/`` rule: a second line would only dirty the file
-
- if gitignore.exists():
- content = gitignore.read_text(encoding="utf-8")
- # Line membership, not substring, so the pattern buried in an unrelated
- # comment doesn't suppress the real ignore rule.
- if pattern in {line.strip() for line in content.splitlines()}:
- return
- if not content.endswith("\n"):
- content += "\n"
- content += f"\n# {comment}\n{pattern}\n"
- gitignore.write_text(content, encoding="utf-8")
- else:
- gitignore.write_text(f"# {comment}\n{pattern}\n", encoding="utf-8")
+def _ensure_gitignored(repo_path: Path | str, name: str, comment: str) -> None:
+ """Ignore ``.repowise/<name>`` from ``.repowise/.gitignore`` unless git already does."""
+ if _git_ignores(repo_path, f".repowise/{name}"):
+ return # e.g. a root ``.repowise/`` rule: a second line would only add noise
+
+ gitignore = get_repowise_dir(repo_path) / ".gitignore"
+ rule = f"/{name}"
+ content = gitignore.read_text(encoding="utf-8") if gitignore.exists() else ""
+ # Line membership, not substring, so the name buried in an unrelated
+ # comment doesn't suppress the real ignore rule.
+ if rule in {line.strip() for line in content.splitlines()}:
+ return
+ if content:
+ content = content.rstrip("\n") + "\n\n"
+ content += f"# {comment}\n{rule}\n"
+ gitignore.parent.mkdir(parents=True, exist_ok=True)
+ gitignore.write_text(content, encoding="utf-8")
def _git_ignores(repo_path: Path | str, pattern: str) -> bool:
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
index 2bfd05510..b35e5caf8 100644
--- a/tests/unit/analysis/test_change_risk.py
+++ b/tests/unit/analysis/test_change_risk.py
@@ -17,6 +17,7 @@ from repowise.core.analysis.change_risk import (
features_from_file_changes,
score_change,
score_live_change,
+ working_tree_is_dirty,
)
from repowise.core.analysis.change_risk.model import _CONSTANTS, _sigmoid
@@ -206,6 +207,15 @@ def git_repo(tmp_path: Path) -> Path:
return repo
+def test_repowise_state_alone_does_not_make_the_tree_dirty(git_repo: Path) -> None:
+ """A fresh init leaves .repowise/ untracked; that is not a code change."""
+ (git_repo / ".repowise").mkdir()
+ (git_repo / ".repowise" / "wiki.db").write_text("x", encoding="utf-8")
+ assert not working_tree_is_dirty(str(git_repo))
+ (git_repo / "new.py").write_text("x = 1\n", encoding="utf-8")
+ assert working_tree_is_dirty(str(git_repo))
+
+
def test_extract_commit_features_counts_diffusion(git_repo: Path) -> None:
_commit(
git_repo,
diff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.py
index c81f2a0c0..68f26273a 100644
--- a/tests/unit/cli/test_init_noninteractive.py
+++ b/tests/unit/cli/test_init_noninteractive.py
@@ -299,8 +299,9 @@ class TestNonInteractiveKeyPersistence:
monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-environment")
save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
- ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8")
- assert ".repowise/.env" in {line.strip() for line in ignored.splitlines()}
+ ignored = (tmp_path / ".repowise" / ".gitignore").read_text(encoding="utf-8")
+ assert "/.env" in {line.strip() for line in ignored.splitlines()}
+ assert not (tmp_path / ".gitignore").exists()
def test_no_save_key_leaves_nothing_behind(self, tmp_path, monkeypatch):
"""The opt-out is for keys injected per-process that must not hit disk."""
@@ -350,13 +351,10 @@ class TestNonInteractiveKeyPersistence:
def test_unwritable_gitignore_warns_but_does_not_lose_the_index(
self, tmp_path, monkeypatch, capsys
):
- """This runs after the index is paid for, so it must never abort the run.
-
- It is also the first thing on the scripted path to write outside
- `.repowise/`, so it is the first that can fail on a read-only checkout.
- """
+ """This runs after the index is paid for, so it must never abort the run."""
monkeypatch.setenv("OPENAI_API_KEY", "sk-key")
- (tmp_path / ".gitignore").mkdir() # a directory where a file must go
+ # A directory where the ignore file must go.
+ (tmp_path / ".repowise" / ".gitignore").mkdir(parents=True)
save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
diff --git a/tests/unit/core/test_events.py b/tests/unit/core/test_events.py
index 3d37226bc..980ab8ee5 100644
--- a/tests/unit/core/test_events.py
+++ b/tests/unit/core/test_events.py
@@ -343,9 +343,11 @@ def test_owner_key_is_kept_and_digests_are_not_plain_hashes(tmp_path):
key = snapshot_mod.owner_key(tmp_path)
assert key is not None and snapshot_mod.owner_key(tmp_path) == key
- # Some repos commit .repowise/: the key gets its own ignore rule.
- ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8").splitlines()
- assert ".repowise/events.key" in ignored
+ # Some repos commit .repowise/: the key gets its own ignore rule, kept
+ # inside .repowise/ so nothing outside it changes.
+ ignored = (tmp_path / ".repowise" / ".gitignore").read_text(encoding="utf-8").splitlines()
+ assert "/events.key" in ignored
+ assert not (tmp_path / ".gitignore").exists()
digest = snapshot_mod._keyed(key, "[email protected]")
assert digest != hashlib.sha256(b"[email protected]").hexdigest()[: len(digest)]
@@ -357,6 +359,7 @@ def test_owner_key_leaves_a_gitignore_that_already_covers_it(tmp_path):
(tmp_path / ".gitignore").write_text(".repowise/\n", encoding="utf-8")
assert snapshot_mod.owner_key(tmp_path) is not None
assert (tmp_path / ".gitignore").read_text(encoding="utf-8") == ".repowise/\n"
+ assert not (tmp_path / ".repowise" / ".gitignore").exists()
def test_owner_key_is_still_gitignored_when_only_info_exclude_covers_it(tmp_path):
@@ -366,8 +369,32 @@ def test_owner_key_is_still_gitignored_when_only_info_exclude_covers_it(tmp_path
(tmp_path / ".git" / "info").mkdir(parents=True, exist_ok=True)
(tmp_path / ".git" / "info" / "exclude").write_text(".repowise/\n", encoding="utf-8")
assert snapshot_mod.owner_key(tmp_path) is not None
- ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8").splitlines()
- assert ".repowise/events.key" in ignored
+ ignored = (tmp_path / ".repowise" / ".gitignore").read_text(encoding="utf-8").splitlines()
+ assert "/events.key" in ignored
+
+
+def test_owner_key_leaves_the_working_tree_clean_outside_repowise(tmp_path):
+ """A committed .repowise/ still keeps the key out, and the root is untouched."""
+ import subprocess
+
+ def git(*args):
+ return subprocess.run(
+ ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args],
+ cwd=tmp_path,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout
+
+ git("init", "-q")
+ (tmp_path / ".gitignore").write_text("build/\n", encoding="utf-8")
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text("x: 1\n", encoding="utf-8")
+ git("add", ".")
+ git("commit", "-qm", "init")
+
+ assert snapshot_mod.owner_key(tmp_path) is not None
+ assert git("status", "--porcelain", "--untracked-files=all") == "?? .repowise/.gitignore\n"
def test_main_owners_are_digested_under_the_repo_key(tmp_path):