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(risk): keep repowise's own output out of working-tree change risk, and count untracked files the same everywhere (#3712)

Swati Ahujaf1967d2778ae
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index f9f37f5d5..d8ea23fc6 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -169,16 +169,17 @@ def hooks_config() -> dict[str, object]:
startup and edits alone.
"""
from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER
+ from repowise.core.owned_paths import CODEX_HOOK_COMMAND
context_hook = {
"type": "command",
- "command": "repowise-augment --client codex",
+ "command": CODEX_HOOK_COMMAND,
"timeout": _HOOK_TIMEOUT,
"statusMessage": "Loading repowise context...",
}
freshness_hook = {
"type": "command",
- "command": "repowise-augment --client codex",
+ "command": CODEX_HOOK_COMMAND,
"timeout": _HOOK_TIMEOUT,
"statusMessage": "Checking repowise freshness...",
}
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
index 74925b67e..01fae5664 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -47,6 +47,7 @@ import json
from pathlib import Path
from repowise.core.agents import identity
+from repowise.core.owned_paths import CURSOR_RULES_PREFIX
from ..types import (
Capability,
@@ -85,15 +86,8 @@ METHODS = (
#: Paired with ``marker_block.remove(delete_if_only=...)`` so install then
#: uninstall round-trips back to "no file" rather than leaving a stub carrying
#: nothing but our own frontmatter — which would still read as repowise-managed
-#: to anyone who opened it.
-RULES_PREFIX = (
- "---\n"
- "alwaysApply: true\n"
- "---\n"
- "\n"
- "<!-- Add your own Cursor rules above or below the Repowise section. "
- "Repowise only updates the managed section between markers. -->\n"
-)
+#: to anyone who opened it. Defined in core, which strips it from a working-tree score.
+RULES_PREFIX = CURSOR_RULES_PREFIX
class RemoteServerEntryError(ValueError):
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
index d623f2bda..a03257e6a 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -31,6 +31,9 @@ from pathlib import Path
from repowise.core.agents import identity
+# Defined in core: change risk tells this recommendation from a user's edit.
+from repowise.core.owned_paths import EXTENSION_ID
+
from ..formats.server_entry import RemoteServerEntryError
from ..types import (
Capability,
@@ -49,7 +52,6 @@ ID = IDENTITY.cli_target_id
DISPLAY_NAME = IDENTITY.display_name
DOCS_URL = "https://code.visualstudio.com/docs/copilot/chat/mcp-servers"
-EXTENSION_ID = "repowise-dev.repowise"
#: Config key gating this agent's managed project files.
PROJECT_FILE_ID = "vscode_mcp"
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index f7fc53dc3..c9cd6d2c5 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -404,11 +404,8 @@ def _failure_entry() -> dict:
#: The repo-local coverage re-ingest entry (shell tools). ``--coverage-only``
#: runs that one surface, so it never revives the shell notices the narrowed
-#: :data:`_AUGMENT_MATCHER` dropped.
-_COVERAGE_HOOK_COMMAND = (
- "if command -v repowise-augment >/dev/null 2>&1; "
- "then exec repowise-augment --coverage-only; fi"
-)
+#: :data:`_AUGMENT_MATCHER` dropped. Its command is defined in core, which
+#: tells it from a user's hook in a working-tree score.
_COVERAGE_HOOK_EVENTS = ("PostToolUse", "PostToolUseFailure")
@@ -418,12 +415,15 @@ def claude_code_local_settings_path(repo_path: Path) -> Path:
def _coverage_entry() -> dict:
+ # Imported here: the hook's self-heal loads this module and must stay light.
+ from repowise.core.owned_paths import COVERAGE_HOOK_COMMAND
+
return {
"matcher": SHELL_TOOL_MATCHER,
"hooks": [
{
"type": "command",
- "command": _COVERAGE_HOOK_COMMAND,
+ "command": COVERAGE_HOOK_COMMAND,
"timeout": 10,
}
],
diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.py
index a1af78ff8..114ef58fb 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -147,7 +147,8 @@ class ChangeHealthDeltaService:
"""Identity of a comparison: the two sides plus how they were analysed."""
if pair.working_tree:
# Content identity: HEAD alone does not describe an edited tree.
- paths = sorted(p for p in pair.head_paths)
+ # Only the compared files: an excluded untracked blob is not read.
+ paths = sorted(c.head_path for c in _filter(pair.changes, request) if c.head_path)
blobs = self.source.read_working_tree(paths)
digest = hashlib.sha256()
for path in paths:
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index eea9ebe32..1ee5aada7 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -14,8 +14,8 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol
-from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff
-from ..git_cli import split_revspec
+from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff, untracked_diffs
+from ..git_cli import split_revspec, untracked_paths
GIT_TIMEOUT_SECONDS = 120
@@ -176,13 +176,23 @@ class GitRevisionSource:
def _resolve_working_tree(self) -> RevisionPair:
head = self._sha("HEAD")
+ # Untracked files are part of the uncommitted change, as change risk
+ # and the changed lines count them.
+ if self.hunks:
+ untracked = untracked_diffs(self.repo_path)
+ else:
+ untracked = dict.fromkeys(untracked_paths(self.repo_path))
return RevisionPair(
"HEAD",
"WORKTREE",
head,
"",
True,
- self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", "HEAD"]),
+ self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", "HEAD"])
+ + [
+ FileChange(head_path=path, base_path=None, status="added", diff=diff)
+ for path, diff in untracked.items()
+ ],
)
def _resolve_commit(self, ref: str) -> RevisionPair:
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 a33b7469d..9a8774703 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -19,11 +19,11 @@ from __future__ import annotations
import math
from collections.abc import Iterable
from dataclasses import dataclass
-from pathlib import Path
import pathspec
from ...ingestion.git_indexer._constants import is_fix_commit
+from ..changed_lines import untracked_diffs
# Re-exported: callers across the package import these from here.
from ..git_cli import GIT_TIMEOUT_SECONDS, _git, split_revspec # noqa: F401
@@ -227,29 +227,6 @@ def working_tree_is_dirty(repo_path: str) -> bool:
return bool(_git(["status", "--porcelain"], repo_path, check=False).strip())
-#: Untracked files above this are counted as a touched file with zero added
-#: lines rather than read into memory to be counted. A multi-megabyte untracked
-#: blob is a build artifact, not authored code, and its exact line count would
-#: not change the risk band.
-_UNTRACKED_READ_LIMIT = 2_000_000
-
-
-def _untracked_additions(repo_path: str, path: str) -> int:
- """Line count of an untracked file, matching what git would call additions."""
- target = Path(repo_path) / path
- try:
- if target.stat().st_size > _UNTRACKED_READ_LIMIT:
- return 0
- data = target.read_bytes()
- except OSError:
- return 0
- if b"\x00" in data:
- return 0 # binary: git reports "-" in numstat, which we count as 0
- if not data:
- return 0
- return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)
-
-
def extract_worktree_features(
repo_path: str,
*,
@@ -261,21 +238,17 @@ def extract_worktree_features(
Covers staged and unstaged edits to tracked files plus untracked files,
which is what a caller who just wrote code and asked "how risky is this?"
means by "this". Untracked files are invisible to ``git diff HEAD``, so they
- are folded in as pure additions.
+ are folded in as pure additions, from the same listing the changed lines
+ and the health delta read.
Experience is the configured author's prior commit count at ``HEAD``, and
``is_fix`` is always false — an uncommitted change has no subject to read.
"""
- # Both walks run from the repo root: ``git diff`` reports root-relative
- # paths whatever the cwd, but ``ls-files --others`` is scoped to the cwd and
- # reports relative to it, so from a subdirectory the two halves would use
- # different path roots and only half would match a root-anchored exclude.
+ # Both walks run from the repo root, where untracked paths are read from.
root = _git(["rev-parse", "--show-toplevel"], repo_path, check=False).strip() or repo_path
numstat = _git(["diff", "--numstat", "HEAD"], root, check=False)
- untracked = _git(["ls-files", "--others", "--exclude-standard"], root, check=False)
- rows = [
- f"{_untracked_additions(root, path)}\t0\t{path}" for path in untracked.splitlines() if path
- ]
+ untracked = untracked_diffs(root, exclude_patterns)
+ rows = [f"{len(diff.new_lines)}\t0\t{path}" for path, diff in untracked.items()]
if rows:
numstat = numstat.rstrip("\n") + "\n" + "\n".join(rows)
la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index 828458b16..febc5a67f 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -7,6 +7,8 @@ from collections.abc import Mapping, Sequence
from dataclasses import dataclass, replace
from pathlib import Path
+from ...owned_paths import OWNED_PATTERNS
+from ..git_cli import generated_worktree_paths
from ..risk_semantics import change_risk_authority, change_risk_scales
from .baseline import BaselineSample, baseline_samples_cached, densities_excluding, scores_excluding
from .features import (
@@ -63,7 +65,15 @@ class ChangeRiskResult:
def riskignore_patterns(repo_path: str) -> tuple[str, ...]:
- """Load non-comment patterns from the repository-root ``.riskignore``."""
+ """Non-comment patterns of the repository-root ``.riskignore``, then repowise's own paths.
+
+ Repowise's output is not the user's change, so the paths it writes whole
+ (:data:`~repowise.core.owned_paths.OWNED_PATTERNS`) are left out of every
+ score, commits and ranges included, so a tracked, hand-edited Kiro steering
+ file or workspace config is not scored either. Only those present are
+ listed, so a repo that never ran repowise reports no exclusions it did not
+ ask for.
+ """
proc = subprocess.run(
["git", "-C", repo_path, "rev-parse", "--show-toplevel"],
capture_output=True,
@@ -74,13 +84,18 @@ def riskignore_patterns(repo_path: str) -> tuple[str, ...]:
)
if proc.returncode != 0:
return ()
- ignore_file = Path(proc.stdout.strip()) / ".riskignore"
+ root = Path(proc.stdout.strip())
+ owned = tuple(p for p in OWNED_PATTERNS if (root / p).exists())
+ ignore_file = root / ".riskignore"
if not ignore_file.is_file():
- return ()
- return tuple(
- line
- for line in ignore_file.read_text(encoding="utf-8").splitlines()
- if line and not line.startswith("#")
+ return owned
+ return (
+ tuple(
+ line
+ for line in ignore_file.read_text(encoding="utf-8").splitlines()
+ if line and not line.startswith("#")
+ )
+ + owned
)
@@ -168,18 +183,24 @@ def score_live_change(
extensions = normalize_extensions(extensions)
from_riskignore = riskignore_patterns(repo_path)
- effective_excludes = from_riskignore + exclude_patterns
+ # The baseline walks committed history, which the working-tree-only
+ # exclusions below say nothing about; keeping them out keeps its cache key.
+ baseline_excludes = from_riskignore + exclude_patterns
target = revspec or "HEAD"
- uncommitted = (
- extract_worktree_features(
- repo_path, extensions=extensions, exclude_patterns=effective_excludes
+ uncommitted = None
+ if revspec is None and working_tree_is_dirty(repo_path):
+ # A managed file (CLAUDE.md, .mcp.json) whose edit is only repowise's
+ # block or entry is repowise's output too, while the user's edits count.
+ worktree_ignores = from_riskignore + generated_worktree_paths(repo_path)
+ uncommitted = extract_worktree_features(
+ repo_path, extensions=extensions, exclude_patterns=worktree_ignores + exclude_patterns
)
- if revspec is None and working_tree_is_dirty(repo_path)
- else None
- )
# A tree dirty only in paths the filters drop is not a change this command
# can score, so fall through to HEAD rather than answer "empty change".
working_tree = uncommitted is not None and uncommitted.nf > 0
+ if working_tree:
+ from_riskignore = worktree_ignores
+ effective_excludes = from_riskignore + exclude_patterns
# Ref whose history the fix record is read from (see ``history_ref``).
history = history_ref(repo_path, target, working_tree=working_tree)
if working_tree:
@@ -216,7 +237,7 @@ def score_live_change(
anchor,
baseline,
extensions,
- exclude_patterns=effective_excludes,
+ exclude_patterns=baseline_excludes,
)
result = assess_change(
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index f6185a85f..41145b261 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -26,7 +26,7 @@ from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
-from .git_cli import _git, split_revspec
+from .git_cli import _git, split_revspec, untracked_paths
# ``@@ -a,b +c,d @@`` - both sides. ``b``/``d`` default to 1 when omitted; a
# count of 0 means "nothing on that side" (pure insertion / pure deletion).
@@ -227,6 +227,7 @@ def changed_lines(
staged: bool = False,
working_tree: bool = False,
base: str | None = None,
+ skip_untracked: tuple[str, ...] = (),
) -> tuple[dict[str, set[int]], str]:
"""Return ``({file: changed_lines}, label)`` for a change.
@@ -234,17 +235,18 @@ def changed_lines(
``base...head`` the change since the two forked, a bare ref a single commit. With no *revspec* (or *staged*), the staged diff
(``git diff --cached``) is used - the "what will I commit" case.
*working_tree* widens that to everything ``HEAD`` does not have, staged or
- not, matching what change risk counts for an uncommitted change. With
- *base* as well, it diffs the working tree from the merge-base of *base*
- and ``HEAD``, untracked files included (every line changed): everything a
- push of this branch would bring. A *base* that does not resolve, or shares
+ not, untracked files included (every line changed), matching what change
+ risk counts for an uncommitted change. With *base* as well, it diffs the
+ working tree from the merge-base of *base* and ``HEAD``: everything a push
+ of this branch would bring. A *base* that does not resolve, or shares
no merge-base, falls back to the plain working-tree diff and its label.
- *label* is a human string naming what was diffed. Raises ``ValueError`` on
- an unknown revision so the caller can fail loudly rather than silently
- reporting "no changes".
+ *skip_untracked* (gitignore-style) names untracked files not to read; the
+ caller still filters tracked paths. *label* is a human string naming what
+ was diffed. Raises ``ValueError`` on an unknown revision so the caller can
+ fail loudly rather than silently reporting "no changes".
"""
if working_tree:
- return _working_tree_lines(repo_path, base)
+ return _working_tree_lines(repo_path, base, skip_untracked)
command, revisions, label = _change_command(repo_path, revspec, staged=staged)
diff = _diff(repo_path, [*command, "--unified=0", *DIFF_ARGS, *revisions])
@@ -306,9 +308,9 @@ def change_set(
) -> ChangeSet:
"""The change :func:`changed_lines` reads, with every touched path and its ends.
- *working_tree* reads what ``HEAD`` does not have, staged or not (untracked
- files stay out, as in :func:`changed_lines`); its base is ``HEAD``. Raises
- ``ValueError`` on an unknown revision, as :func:`changed_lines` does.
+ *working_tree* reads what ``HEAD`` does not have, staged or not, untracked
+ files included; its base is ``HEAD``. Raises ``ValueError`` on an unknown
+ revision, as :func:`changed_lines` does.
"""
if working_tree:
command, revisions, label = ["diff"], ["HEAD"], working_tree_label()
@@ -327,6 +329,8 @@ def change_set(
deleted.add(path)
else:
files[path] = diffs.get(path) or FileDiff(path=path)
+ if working_tree:
+ files.update(untracked_diffs(repo_path))
base, head = _change_ends(repo_path, revspec, staged=staged or working_tree)
return ChangeSet(files, deleted, label, base, head)
@@ -351,22 +355,17 @@ def _change_ends(
return sha(f"{revspec}^"), sha(revspec)
-def _working_tree_lines(repo_path: str, base: str | None) -> tuple[dict[str, set[int]], str]:
+def _working_tree_lines(
+ repo_path: str, base: str | None, skip_untracked: tuple[str, ...]
+) -> tuple[dict[str, set[int]], str]:
"""The working-tree half of :func:`changed_lines`: from *base*'s merge-base, else ``HEAD``."""
start = _merge_base_or_empty(repo_path, base) if base and base != "HEAD" else ""
- if start:
- diff = _git(["diff", "--unified=0", *DIFF_ARGS, start], repo_path)
- changed = _parse_unified_diff(diff)
- changed.update(_untracked_lines(repo_path))
- return changed, working_tree_label(base)
- diff = _git(["diff", "--unified=0", *DIFF_ARGS, "HEAD"], repo_path)
+ diff = _git(["diff", "--unified=0", *DIFF_ARGS, start or "HEAD"], repo_path)
changed = _parse_unified_diff(diff)
- if base:
- # Asked for what a push brings, with no merge-base to diff from: new
- # files are still part of it. Without a base this is what the commit
- # would change, and untracked files stay out by design.
- changed.update(_untracked_lines(repo_path))
- return changed, working_tree_label()
+ # New files are part of the work whether or not they are staged yet.
+ untracked = untracked_diffs(repo_path, skip_untracked)
+ changed.update({p: d.new_lines for p, d in untracked.items() if d.new_lines})
+ return changed, working_tree_label(base if start else None)
def _merge_base_or_empty(repo_path: str, base: str) -> str:
@@ -378,21 +377,49 @@ def _merge_base_or_empty(repo_path: str, base: str) -> str:
return ""
-def _untracked_lines(repo_path: str) -> dict[str, set[int]]:
- """Every line of each untracked, not-ignored file: new code a push would add."""
- out: dict[str, set[int]] = {}
- listing = _git(["ls-files", "--others", "--exclude-standard", "-z"], repo_path)
- for path in filter(None, listing.split("\0")):
+#: Untracked files above this count as touched with no lines rather than being
+#: read into memory. A multi-megabyte untracked blob is a build artifact, not
+#: authored code, and its exact line count would not change the risk band.
+_UNTRACKED_READ_LIMIT = 2_000_000
+
+
+def untracked_diffs(repo_path: str, exclude_patterns: tuple[str, ...] = ()) -> dict[str, FileDiff]:
+ """Each untracked, not-ignored file as the diff ``git add`` would make of it.
+
+ Every line is new, as git counts additions; a binary or oversized file has
+ none, as a tracked one would in ``--numstat``. One reader for every
+ working-tree surface, so they count the same files. A path matching
+ *exclude_patterns* is never read.
+ """
+ out: dict[str, FileDiff] = {}
+ for path in untracked_paths(repo_path, exclude_patterns):
+ target = Path(repo_path) / path
try:
- data = (Path(repo_path) / path).read_bytes()
+ data = b"" if target.stat().st_size > _UNTRACKED_READ_LIMIT else target.read_bytes()
except OSError:
continue
- count = data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)
- if count:
- out[path] = set(range(1, count + 1))
+ out[path] = _new_file_diff(path, data)
return out
+def _new_file_diff(path: str, data: bytes) -> FileDiff:
+ """*data* as an added file's diff; a binary file adds no lines."""
+ # Split on "\n" alone, as git counts lines; a final newline ends a line.
+ added = [] if b"\x00" in data else data.decode("utf-8", errors="replace").split("\n")
+ if added and added[-1] == "":
+ added.pop()
+ if not added:
+ return FileDiff(path=path)
+ count = len(added)
+ return FileDiff(
+ path=path,
+ new_lines=set(range(1, count + 1)),
+ insert_anchors=[0],
+ added=added,
+ hunks=[(0, 0, 1, count)],
+ )
+
+
def diff_since(
repo_path: str, since: str, until: str | None, paths: Iterable[str]
) -> dict[str, FileDiff]:
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/scope.py b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
index 0be931b92..6a014ae27 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/scope.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
@@ -28,7 +28,7 @@ from dataclasses import dataclass
from typing import Any
from ..change_health.sources import FileChange, GitRevisionSource
-from ..git_cli import _git, split_revspec
+from ..git_cli import split_revspec
from .constants import MANIFEST_NAMES
from .extractor import is_checkable_document
from .resolver import join_relative
@@ -158,11 +158,6 @@ def scope_since(root: str, revspec: str) -> ChangeScope:
source = GitRevisionSource(root, hunks=False)
changes = list(source.resolve(revspec).changes)
if parts is not None and parts[2] == "HEAD":
+ # Untracked files included: the working tree resolves them as added.
changes += source.resolve(None).changes
- changes += [
- FileChange(head_path=path, base_path=None, status="added")
- for path in _git(["ls-files", "-z", "--others", "--exclude-standard"], root)
- .split("\0")
- if path
- ]
return ChangeScope.from_changes(changes, label=revspec)
diff --git a/packages/core/src/repowise/core/analysis/git_cli.py b/packages/core/src/repowise/core/analysis/git_cli.py
index 59a08e04f..1f3eabc85 100644
--- a/packages/core/src/repowise/core/analysis/git_cli.py
+++ b/packages/core/src/repowise/core/analysis/git_cli.py
@@ -1,13 +1,19 @@
-"""The two git helpers every change reader shares: split a revspec, run git.
+"""The git helpers every change reader shares: split a revspec, run git, list
+the untracked files and the managed files only repowise edited.
-A leaf with no package imports, so a caller that only needs the diff shape
-(changed lines, the drift gate's scope) does not load change risk's baseline
-and, through it, GitPython.
+A leaf (only the owned-path list beside it), so a caller that only needs the
+diff shape (changed lines, the drift gate's scope) does not load change risk's
+baseline and, through it, GitPython.
"""
from __future__ import annotations
import subprocess
+from pathlib import Path
+
+import pathspec
+
+from ..owned_paths import MANAGED_FILES, OWNED_PATTERNS, only_repowise_differs
# Generous ceiling: even a 200-commit numstat walk finishes in seconds. The
# point is that a stuck git (lock contention, network filesystem) must fail
@@ -49,3 +55,50 @@ def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
)
return proc.stdout
+
+
+def untracked_paths(repo_path: str, exclude_patterns: tuple[str, ...] = ()) -> list[str]:
+ """Untracked, not-ignored files, root-relative like ``git diff``'s paths.
+
+ The one source of untracked files for every working-tree reader (the score,
+ the changed lines, the health delta), so they agree on the file set. Paths
+ repowise writes whole are left out here, before anything reads them: an
+ unignored index directory holds thousands of files. *exclude_patterns*
+ (gitignore-style) drops a caller's excluded paths at the same point.
+ """
+ listing = _git(
+ ["ls-files", "--others", "--exclude-standard", "-z", "--full-name", "--", ":/"],
+ repo_path,
+ check=False,
+ )
+ skip = pathspec.PathSpec.from_lines("gitwildmatch", OWNED_PATTERNS + exclude_patterns)
+ return [path for path in listing.split("\0") if path and not skip.match_file(path)]
+
+
+def generated_worktree_paths(repo_path: str) -> tuple[str, ...]:
+ """Root-anchored patterns for managed files whose uncommitted change is repowise's alone.
+
+ A file is compared at ``HEAD`` and on disk with repowise's block or entry
+ removed, so a refreshed CLAUDE.md block or a newly written ``.mcp.json``
+ drops out while any edit of the user's own text keeps the file in.
+ """
+ root = _git(["rev-parse", "--show-toplevel"], repo_path, check=False).strip()
+ if not root:
+ return ()
+ # --no-renames: a rename entry carries a second path, which would misparse.
+ status = ["status", "--porcelain", "-z", "--no-renames", "--untracked-files=all"]
+ listing = _git(
+ [*status, "--", *MANAGED_FILES],
+ root,
+ check=False,
+ )
+ out: list[str] = []
+ for path in sorted({entry[3:] for entry in listing.split("\0") if len(entry) > 3}):
+ try:
+ new = (Path(root) / path).read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ new = ""
+ old = _git(["show", f"HEAD:{path}"], root, check=False)
+ if only_repowise_differs(path, old, new):
+ out.append(f"/{path}")
+ return tuple(out)
diff --git a/packages/core/src/repowise/core/owned_paths.py b/packages/core/src/repowise/core/owned_paths.py
new file mode 100644
index 000000000..cef96c698
--- /dev/null
+++ b/packages/core/src/repowise/core/owned_paths.py
@@ -0,0 +1,170 @@
+"""The paths repowise writes into a repository, and how to tell its edits from a user's.
+
+One list for every reader that must not take repowise's own output for the
+user's change; change risk reads it through ``riskignore_patterns``. Two kinds:
+
+* :data:`OWNED_PATTERNS` are written whole by repowise, so any change there is
+ repowise's.
+* :data:`MANAGED_FILES` are files users write in too, where repowise owns a
+ fenced block and the placeholder written with a new file (markdown), or a
+ ``repowise`` server entry, its hooks and its extension recommendation (JSON,
+ TOML). A change to one is repowise's only when removing exactly what the
+ writers emit leaves both sides equal (:func:`only_repowise_differs`), so a
+ user's own edit still counts.
+
+The writers live in the CLI, which imports core and not the other way round, so
+the values they emit into a project's shared files are defined here and the
+writers import them. A test over every agent target's ``describe_paths`` and
+the generators keeps the path list in step with them.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import tomllib
+
+from .workspace.config import WORKSPACE_CONFIG_FILENAME, WORKSPACE_DATA_DIR
+
+#: Gitignore-style. Writers: ``init`` / ``update`` (the index, config and
+#: decisions), ``workspace init`` (the two workspace paths), the Kiro target
+#: (its steering file, written whole).
+OWNED_PATTERNS: tuple[str, ...] = (
+ ".repowise/",
+ f"{WORKSPACE_DATA_DIR}/",
+ WORKSPACE_CONFIG_FILENAME,
+ ".kiro/steering/repowise.md",
+)
+
+#: Root-relative. Markdown holds the writers' exactly marked blocks: the
+#: CLAUDE.md and AGENTS.md generators, and the instruction blocks of the codex,
+#: opencode, hermes, copilot, vscode and cursor targets. The JSON and TOML
+#: files hold a ``repowise`` server entry, hook or extension recommendation
+#: from the agent targets (claude code, vscode, cursor, kiro, codex, opencode).
+MANAGED_FILES: tuple[str, ...] = (
+ ".claude/CLAUDE.md",
+ "AGENTS.md",
+ ".github/copilot-instructions.md",
+ ".cursor/rules/repowise.mdc",
+ ".mcp.json",
+ ".claude/settings.local.json",
+ ".vscode/mcp.json",
+ ".vscode/extensions.json",
+ ".cursor/mcp.json",
+ ".kiro/settings/mcp.json",
+ ".codex/config.toml",
+ ".codex/hooks.json",
+ "opencode.json",
+ "opencode.jsonc",
+)
+
+#: The VS Code extension the vscode target recommends in ``extensions.json``.
+EXTENSION_ID = "repowise-dev.repowise"
+#: The Claude Code coverage re-ingest hook, in ``.claude/settings.local.json``.
+COVERAGE_HOOK_COMMAND = (
+ "if command -v repowise-augment >/dev/null 2>&1; "
+ "then exec repowise-augment --coverage-only; fi"
+)
+#: The Codex context and freshness hooks, in ``.codex/hooks.json``.
+CODEX_HOOK_COMMAND = "repowise-augment --client codex"
+#: What the cursor target writes above its block in a new rules file.
+CURSOR_RULES_PREFIX = (
+ "---\n"
+ "alwaysApply: true\n"
+ "---\n"
+ "\n"
+ "<!-- Add your own Cursor rules above or below the Repowise section. "
+ "Repowise only updates the managed section between markers. -->\n"
+)
+
+#: The CLI targets' marker pairs: the instruction block the codex, opencode,
+#: hermes, vscode and cursor targets write in the generators' format, and the
+#: bare pair the copilot target writes beside it as its claim. A test checks
+#: them against the targets' own constants.
+_DISTILL_TAG = "REPOWISE_DISTILL"
+_COPILOT_OWNER_PAIR = ("<!-- REPOWISE_COPILOT_CLI:START -->", "<!-- REPOWISE_COPILOT_CLI:END -->")
+
+_HOOK_COMMANDS = (COVERAGE_HOOK_COMMAND, CODEX_HOOK_COMMAND)
+#: The server entry's key in every target's config (each target's ``SERVER_NAME``).
+_SERVER_NAME = "repowise"
+
+
+def only_repowise_differs(path: str, old: str, new: str) -> bool:
+ """Whether *old* and *new* (``""`` for absent) differ only in repowise's part of *path*."""
+ before = _without_repowise(path, old)
+ return before is not None and before == _without_repowise(path, new)
+
+
+def _without_repowise(path: str, text: str) -> object:
+ """*text* minus repowise's part, in a form two versions compare by; ``None`` if unreadable."""
+ if not path.endswith((".json", ".jsonc", ".toml")):
+ placeholder = next((p for p in _placeholders() if text.startswith(p)), "")
+ text = text[len(placeholder) :]
+ for start, end in _marker_pairs():
+ text = re.sub(re.escape(start) + ".*?" + re.escape(end), "", text, flags=re.DOTALL)
+ # Only the ends: a block is appended after a blank line and ends the file.
+ return text.strip()
+ if not text.strip():
+ return {}
+ try:
+ data = tomllib.loads(text) if path.endswith(".toml") else json.loads(text)
+ except ValueError:
+ # JSONC with comments, or a broken file: never repowise's alone, so it counts.
+ return None
+ return _prune(data)
+
+
+def _prune(value: object) -> object:
+ """Drop the server entry, repowise's hooks and recommendation, and what that alone empties."""
+ if isinstance(value, dict):
+ items = [(k, v) for k, v in value.items() if k != _SERVER_NAME]
+ elif isinstance(value, list):
+ items = [(None, v) for v in value if not _is_ours(v)]
+ else:
+ return value
+ kept = []
+ for key, v in items:
+ pruned = _prune(v)
+ # A container emptied by the removal goes; one the user left empty
+ # stays. Falsy scalars (0, false, "") are never emptied: ``not v``.
+ if not (pruned or not v) or _lost_its_hooks(v, pruned):
+ continue
+ kept.append((key, pruned))
+ return dict(kept) if isinstance(value, dict) else [p for _, p in kept]
+
+
+def _is_ours(item: object) -> bool:
+ """A list item the writers emit: the recommendation, or a hook running our command."""
+ if isinstance(item, dict):
+ return item.get("type") == "command" and item.get("command") in _HOOK_COMMANDS
+ return item == EXTENSION_ID
+
+
+def _lost_its_hooks(group: object, pruned: object) -> bool:
+ """A hook group whose every hook was ours: the writers add the group with them."""
+ return isinstance(group, dict) and bool(group.get("hooks")) and "hooks" not in pruned
+
+
+def _marker_pairs() -> list[tuple[str, str]]:
+ """The exact ``(start, end)`` markers every writer fences its block with."""
+ from .generation.editor_files.agents_md import AgentsMdGenerator
+ from .generation.editor_files.base import BaseEditorFileGenerator as Gen
+ from .generation.editor_files.claude_md import ClaudeMdGenerator, WorkspaceClaudeMdGenerator
+
+ generators = (ClaudeMdGenerator, WorkspaceClaudeMdGenerator, AgentsMdGenerator)
+ tags = {*(g.marker_tag for g in generators), _DISTILL_TAG}
+ pairs = [(Gen.MARKER_START_FMT.format(tag=t), Gen.MARKER_END_FMT.format(tag=t)) for t in tags]
+ return [*pairs, _COPILOT_OWNER_PAIR]
+
+
+def _placeholders() -> tuple[str, ...]:
+ """The text each writer puts above its block when it creates the file."""
+ from .generation.editor_files.agents_md import AgentsMdGenerator
+ from .generation.editor_files.claude_md import ClaudeMdGenerator, WorkspaceClaudeMdGenerator
+
+ return (
+ ClaudeMdGenerator.user_placeholder,
+ WorkspaceClaudeMdGenerator.user_placeholder,
+ AgentsMdGenerator.user_placeholder,
+ CURSOR_RULES_PREFIX,
+ )
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 0aeb1f84e..33787b50c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -941,6 +941,7 @@ async def _changed_with_label(
revspec or "HEAD",
working_tree=working_tree,
base=base,
+ skip_untracked=exclude_patterns,
)
)
except ValueError as exc:
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
index 8c39ad382..fb2ed19cb 100644
--- a/tests/unit/analysis/test_change_risk.py
+++ b/tests/unit/analysis/test_change_risk.py
@@ -503,6 +503,95 @@ def test_dirt_the_filters_drop_falls_back_to_head(git_repo: Path) -> None:
assert result.features.nf == 1 # the committed src/a.py, not an empty change
+def _block_format() -> str:
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator as Gen
+
+ start = Gen.MARKER_START_FMT.format(tag="REPOWISE")
+ return start + "\n{body}\n" + Gen.MARKER_END_FMT.format(tag="REPOWISE") + "\n"
+
+
+_BLOCK = _block_format()
+
+
+def test_repowise_output_alone_falls_back_to_head(git_repo: Path) -> None:
+ """The index, a written .mcp.json and a refreshed managed block are not the user's change."""
+ _commit(
+ git_repo, {".claude/CLAUDE.md": "# Mine\n\n" + _BLOCK.format(body="v1")}, "docs", "Dev"
+ )
+ (git_repo / ".claude" / "CLAUDE.md").write_text(
+ "# Mine\n\n" + _BLOCK.format(body="v2\nmore"), encoding="utf-8"
+ )
+ (git_repo / ".repowise").mkdir()
+ (git_repo / ".repowise" / "config.yaml").write_text("provider: x\n", encoding="utf-8")
+ (git_repo / ".mcp.json").write_text(
+ '{"mcpServers": {"repowise": {"command": "repowise"}}}', encoding="utf-8"
+ )
+ (git_repo / "AGENTS.md").write_text(_BLOCK.format(body="hi"), encoding="utf-8")
+
+ result = score_live_change(str(git_repo), baseline=0)
+
+ assert result.working_tree is False
+ assert result.features.ref == "HEAD"
+ assert ".repowise/" in change_risk_payload(result)["exclude_patterns"]
+
+
+def test_a_users_edit_to_a_managed_file_still_counts(git_repo: Path) -> None:
+ block = _BLOCK.format(body="v1")
+ _commit(git_repo, {".claude/CLAUDE.md": "# Mine\n\n" + block}, "docs", "Dev")
+ (git_repo / ".claude" / "CLAUDE.md").write_text("# Mine, edited\n\n" + block, encoding="utf-8")
+ (git_repo / ".mcp.json").write_text(
+ '{"mcpServers": {"repowise": {}, "mine": {"command": "x"}}}', encoding="utf-8"
+ )
+
+ result = score_live_change(str(git_repo), baseline=0)
+
+ assert result.working_tree is True
+ assert {path for path, _ in result.features.file_churn} == {".claude/CLAUDE.md", ".mcp.json"}
+
+
+def _working_tree_file_sets(repo: Path, result) -> tuple[set[str], set[str]]:
+ """The files the score and the changed lines read; the health delta must count as many."""
+ from repowise.core.analysis.change_health.service import (
+ ChangeHealthDeltaService,
+ DeltaRequest,
+ )
+ from repowise.core.analysis.changed_lines import changed_lines
+
+ scored = {path for path, _ in result.features.file_churn}
+ changed, _ = changed_lines(str(repo), working_tree=True)
+ delta = ChangeHealthDeltaService(repo_path=str(repo)).compare(
+ DeltaRequest(str(repo), None, (), result.riskignore_excludes)
+ )
+ assert delta.scope.changed == result.features.nf
+ return scored, set(changed)
+
+
+def test_untracked_files_are_one_file_set_for_score_lines_and_delta(git_repo: Path) -> None:
+ """An untracked-only tree is a real change everywhere, never "high" beside "no files"."""
+ (git_repo / "src").mkdir()
+ (git_repo / "src" / "new.py").write_text("def f():\n return 1\n", encoding="utf-8")
+ (git_repo / "notes.md").write_text("n\n", encoding="utf-8")
+
+ result = score_live_change(str(git_repo), baseline=0)
+
+ assert result.working_tree is True
+ assert _working_tree_file_sets(git_repo, result) == ({"src/new.py", "notes.md"},) * 2
+ assert result.features.la == 3
+
+
+def test_a_tracked_edit_and_an_untracked_file_both_count(git_repo: Path) -> None:
+ _commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")
+ (git_repo / "src" / "a.py").write_text("x = 1\ny = 2\n", encoding="utf-8")
+ (git_repo / "src" / "new.py").write_text("n = 1\n", encoding="utf-8")
+ (git_repo / ".repowise").mkdir()
+ (git_repo / ".repowise" / "wiki.db").write_bytes(b"\x00" * 64)
+
+ result = score_live_change(str(git_repo), baseline=0)
+
+ assert result.features.nf == 2
+ assert _working_tree_file_sets(git_repo, result) == ({"src/a.py", "src/new.py"},) * 2
+
+
def test_explicit_head_scores_the_commit_even_when_dirty(git_repo: Path) -> None:
"""An explicit revspec always means committed refs."""
_commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")
diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.py
index bceff208d..c9087ce1a 100644
--- a/tests/unit/analysis/test_changed_lines.py
+++ b/tests/unit/analysis/test_changed_lines.py
@@ -179,14 +179,11 @@ def test_working_tree_from_a_base_is_everything_a_push_brings(git_repo) -> None:
assert label == "main...working tree"
# An untracked file is new code the push brings: every line changed.
assert changed == {"mod.py": {2, 4}, "new.py": {1, 2}}
- # Without a base it stays the uncommitted edit alone.
- assert changed_lines(str(git_repo), working_tree=True) == ({"mod.py": {4}}, "working tree")
- # A base that does not resolve falls back to the uncommitted edit, still
- # with the new files a push would bring.
- assert changed_lines(str(git_repo), working_tree=True, base="nope") == (
- {"mod.py": {4}, "new.py": {1, 2}},
- "working tree",
- )
+ # Without a base, or with one that does not resolve, it is the uncommitted
+ # edit, new files included, as change risk counts it.
+ uncommitted = ({"mod.py": {4}, "new.py": {1, 2}}, "working tree")
+ assert changed_lines(str(git_repo), working_tree=True) == uncommitted
+ assert changed_lines(str(git_repo), working_tree=True, base="nope") == uncommitted
def test_map_old_line_follows_insertions_deletions_and_rewrites() -> None:
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index 5f06084eb..3f546f49b 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -569,6 +569,35 @@ async def test_get_change_risk_keeps_working_tree_without_a_revspec(tmp_path, mo
assert result["working_tree"] is True
+async def test_get_change_risk_untracked_only_tree_is_one_change(tmp_path, monkeypatch) -> None:
+ """Score, manifest and delta read one file set; repowise's own output drops out."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")
+ (repo / "app.py").write_text("def f():\n return 1\n", encoding="utf-8")
+ (repo / ".github").mkdir()
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ (repo / ".github" / "copilot-instructions.md").write_text(
+ f"{DISTILL_MARKER_START}\nx\n{DISTILL_MARKER_END}\n", encoding="utf-8"
+ )
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0, include=["diagnostics"])
+
+ assert result["working_tree"] is True
+ assert result["features"]["nf"] == 1
+ assert result["health_delta"]["scope"]["changed"] == 1
+ assert result["exclude_patterns"] == ["/.github/copilot-instructions.md"]
+
+
@pytest.mark.asyncio
async def test_get_change_risk_keeps_is_fix_when_true(tmp_path, monkeypatch) -> None:
repo = tmp_path / "repo"
diff --git a/tests/unit/test_owned_paths.py b/tests/unit/test_owned_paths.py
new file mode 100644
index 000000000..7f0a93572
--- /dev/null
+++ b/tests/unit/test_owned_paths.py
@@ -0,0 +1,164 @@
+"""The repowise-owned path list, kept in step with the writers it describes."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pathspec
+import pytest
+
+from repowise.core.owned_paths import MANAGED_FILES, OWNED_PATTERNS, only_repowise_differs
+
+
+def _covered(relative: str) -> bool:
+ owned = pathspec.PathSpec.from_lines("gitwildmatch", OWNED_PATTERNS)
+ return relative in MANAGED_FILES or owned.match_file(relative)
+
+
+def test_every_project_file_a_writer_names_is_listed(tmp_path: Path) -> None:
+ from repowise.cli.agent_targets.registry import all_targets
+ from repowise.cli.agent_targets.types import Scope
+ from repowise.cli.uninstall.generated_files import generated_blocks
+
+ named = [block.relative_path for block in generated_blocks()]
+ for target in all_targets():
+ if target.supports_scope(Scope.PROJECT):
+ for raw in target.describe_paths(Scope.PROJECT, repo_path=tmp_path):
+ named.append(Path(raw).relative_to(tmp_path).as_posix())
+ assert named
+ assert [path for path in named if not _covered(path)] == []
+
+
+_TAGS = ("REPOWISE", "REPOWISE_AGENTS")
+
+
+def test_every_writers_marker_is_stripped() -> None:
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets.copilot import OWNER_END, OWNER_START
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator as Gen
+
+ pairs = [
+ (DISTILL_MARKER_START, DISTILL_MARKER_END),
+ (OWNER_START, OWNER_END),
+ *((Gen.MARKER_START_FMT.format(tag=t), Gen.MARKER_END_FMT.format(tag=t)) for t in _TAGS),
+ ]
+ for start, end in pairs:
+ assert only_repowise_differs("AGENTS.md", "# Mine\n", f"# Mine\n\n{start}\nbody\n{end}\n")
+
+
+def test_a_file_a_writer_creates_is_repowise_s_alone() -> None:
+ """New file: the writer's placeholder sits above its block, and both are ours."""
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets.cursor import RULES_PREFIX
+ from repowise.cli.editor_integrations.codex_config import _NEW_FILE_PLACEHOLDER
+ from repowise.core.generation.editor_files.agents_md import AgentsMdGenerator
+ from repowise.core.generation.editor_files.claude_md import (
+ ClaudeMdGenerator,
+ WorkspaceClaudeMdGenerator,
+ )
+
+ block = f"{DISTILL_MARKER_START}\nbody\n{DISTILL_MARKER_END}"
+ for prefix, path in (
+ (ClaudeMdGenerator.user_placeholder, ".claude/CLAUDE.md"),
+ (WorkspaceClaudeMdGenerator.user_placeholder, ".claude/CLAUDE.md"),
+ (AgentsMdGenerator.user_placeholder, "AGENTS.md"),
+ (_NEW_FILE_PLACEHOLDER, "AGENTS.md"),
+ (RULES_PREFIX, ".cursor/rules/repowise.mdc"),
+ ):
+ created = f"{prefix}\n{block}\n"
+ assert only_repowise_differs(path, "", created)
+ assert not only_repowise_differs(path, "", created + "\nMy rule.\n")
+
+
+def _settings(allow: list[str], groups: list[dict]) -> str:
+ hooks = {"hooks": {"PostToolUse": groups}} if groups else {}
+ return json.dumps({"permissions": {"allow": allow}, **hooks})
+
+
+def test_hook_and_permission_edits_are_matched_exactly() -> None:
+ """Only what the writers emit is repowise's; text that merely names repowise is not."""
+ from repowise.cli.editor_integrations.claude_config import _coverage_entry
+
+ ours = _coverage_entry()
+ mine = {"type": "command", "command": "make lint"}
+ path = ".claude/settings.local.json"
+ allow = ["Bash(cd /x/repowise && ls)"]
+ # The coverage entry, added whole: repowise's.
+ assert only_repowise_differs(path, _settings(allow, []), _settings(allow, [ours]))
+ # A user removing a permission that names repowise: theirs.
+ assert not only_repowise_differs(path, _settings(allow, [ours]), _settings([], [ours]))
+ # A user's hook in a group repowise's hook also sits in: pruned per hook.
+ mixed = {**ours, "hooks": [*ours["hooks"], mine]}
+ edited = {**ours, "hooks": [*ours["hooks"], {**mine, "command": "make test"}]}
+ assert not only_repowise_differs(path, _settings([], [mixed]), _settings([], [edited]))
+ assert only_repowise_differs(
+ path, _settings([], [{**ours, "hooks": [mine]}]), _settings([], [mixed])
+ )
+ # The Codex hooks file as its writer creates it.
+ from repowise.cli.agent_targets.targets.codex import hooks_config
+
+ assert only_repowise_differs(".codex/hooks.json", "", json.dumps(hooks_config()))
+ # A hook that only resembles ours is the user's.
+ lookalike = {**ours, "hooks": [{"type": "command", "command": "repowise hook x"}]}
+ assert not only_repowise_differs(path, _settings([], []), _settings([], [lookalike]))
+
+
+def _generator_pair(tag: str) -> tuple[str, str]:
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator as Gen
+
+ return Gen.MARKER_START_FMT.format(tag=tag), Gen.MARKER_END_FMT.format(tag=tag)
+
+
+_START, _END = _generator_pair("REPOWISE")
+_USER_START, _USER_END = "<!-- REPOWISE_USER:START -->", "<!-- REPOWISE_USER:END -->"
+
+
+ ("path", "old", "new", "ours"),
+ [
+ # A block refreshed in place, a block appended, and a user's edit beside it.
+ ("AGENTS.md", f"x\n{_START}\nv1\n{_END}\n", f"x\n{_START}\nv2\n{_END}\n", True),
+ ("AGENTS.md", "x\n", f"x\n\n{_START}\nv\n{_END}\n", True),
+ ("AGENTS.md", "x\n", f"y\n{_START}\nv\n{_END}\n", False),
+ # A block fenced by markers no writer emits is the user's, whatever its name.
+ (
+ "AGENTS.md",
+ f"x\n{_USER_START}\nv1\n{_USER_END}\n",
+ f"x\n{_USER_START}\nv2\n{_USER_END}\n",
+ False,
+ ),
+ ("AGENTS.md", "", "<!-- REPOWISE:START -->\nv\n<!-- REPOWISE:END -->\n", False),
+ # A user's own comment or a bare title is content, not a placeholder.
+ ("AGENTS.md", "x\n", "x\n<!-- my note -->\n", False),
+ (".claude/CLAUDE.md", "", "# CLAUDE.md\n", False),
+ (".mcp.json", "", '{"mcpServers": {"repowise": {"command": "repowise"}}}', True),
+ # A server the user added, even an empty one, counts.
+ (".mcp.json", "", '{"mcpServers": {"repowise": {}, "other": {}}}', False),
+ (".mcp.json", "", '{"mcpServers": {"repowise": {}, "other": {"command": "x"}}}', False),
+ (".vscode/extensions.json", "", '{"recommendations": ["repowise-dev.repowise"]}', True),
+ (".vscode/extensions.json", "", '{"recommendations": ["repowise-dev.other"]}', False),
+ (".codex/config.toml", "", '[mcp_servers.repowise]\ncommand = "repowise"\n', True),
+ (".codex/config.toml", "", 'model = "o3"\n', False),
+ # A config with comments cannot be compared, so it is never repowise's alone.
+ (".vscode/mcp.json", "", '// mine\n{"servers": {"repowise": {}}}', False),
+ ],
+)
+def test_only_repowise_differs(path: str, old: str, new: str, ours: bool) -> None:
+ assert only_repowise_differs(path, old, new) is ours
+
+
+def test_a_renamed_managed_file_is_read_as_its_two_paths(tmp_path: Path) -> None:
+ from repowise.core.analysis.git_cli import generated_worktree_paths
+
+ def git(*args: str) -> None:
+ subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True)
+
+ git("init", "-q")
+ (tmp_path / "opencode.json").write_text('{"mcp": {"repowise": {}}}', encoding="utf-8")
+ git("add", "opencode.json")
+ git("-c", "user.name=T", "-c", "[email protected]", "commit", "-qm", "seed")
+ git("mv", "opencode.json", "opencode.jsonc")
+
+ assert generated_worktree_paths(str(tmp_path)) == ("/opencode.json", "/opencode.jsonc")