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(decisions): store staged decision paths the index can resolve (#2421)

Raghav Chamadiyadb0eb63a5a62
diff --git a/packages/core/src/repowise/core/sessions/events.py b/packages/core/src/repowise/core/sessions/events.py
index f3c9548c4..635672775 100644
--- a/packages/core/src/repowise/core/sessions/events.py
+++ b/packages/core/src/repowise/core/sessions/events.py
@@ -156,17 +156,39 @@ def is_prose_user_text(event: Event) -> bool:
def relative_files(files: Iterable[str], repo_root: Any) -> list[str]:
- """Repo-relative POSIX paths, in first-seen order; outsiders dropped."""
- import os.path
+ """Repo-relative POSIX paths, in first-seen order; outsiders dropped.
+
+ Idempotent, and that is the point: a path already relative is returned as
+ it stands rather than resolved again. Resolving it would make the answer
+ depend on the process working directory, which is right only while that
+ happens to be the repository root and silently drops every file
+ otherwise, so a caller that stores relative paths and one reading rows
+ stored absolute before it get the same answer from the same call.
+
+ Compares as text rather than through :mod:`os.path`, because the store it
+ serves is written by whichever machine ran the agent: a Windows path has
+ to read as a path on any interpreter, not as a relative name that happens
+ to begin with a drive letter. The root match is case-insensitive for the
+ same reason, and to agree with the ``cwd`` scoping the miners already do;
+ the cost is two directories under a case-sensitive filesystem that differ
+ only in case, which the miner could not have told apart either.
+ """
+ import posixpath
+ root = str(repo_root).replace("\\", "/").rstrip("/")
+ prefix = root.lower() + "/"
out: list[str] = []
for f in files:
- try:
- rel = os.path.relpath(f, str(repo_root))
- except (ValueError, OSError):
+ if not f:
+ continue
+ path = posixpath.normpath(f.replace("\\", "/"))
+ if path.startswith("/") or (len(path) > 1 and path[1] == ":"):
+ if not path.lower().startswith(prefix):
+ continue
+ path = path[len(prefix) :]
+ if path == ".." or path.startswith("../"):
continue
- if not rel.startswith(".."):
- out.append(rel.replace("\\", "/"))
+ out.append(path)
return list(dict.fromkeys(out))
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 9aab3a011..4143d40ff 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -327,23 +327,49 @@ def _result_anchor(name: str, use_input: dict[str, Any]) -> str:
return name.lower()
+def _repo_relative_touches(
+ touches: list[tuple[str, str]], repo_root: Any
+) -> list[tuple[str, str]]:
+ """``(path, intent)`` with each path repo-relative POSIX, outsiders dropped.
+
+ A transcript records the path the tool call was given, which for every
+ agent this reads is an absolute one. Staging that verbatim writes a
+ machine's directory layout into a row the index later has to match
+ against repo-relative paths, so it is normalized here, at the single
+ point a touch enters the miner, rather than by each reader guessing.
+ """
+ out: list[tuple[str, str]] = []
+ for path, intent in touches:
+ relative = relative_files([path], repo_root)
+ if relative:
+ out.append((relative[0], intent))
+ return out
+
+
def mine_events(
events: Iterable[Event],
- repo_prefix: str,
+ repo_root: Any,
*,
edit_tools: Container[str] = frozenset(),
) -> list[SessionCandidate]:
"""Run the deterministic candidate gates over one session's events.
- *repo_prefix* is the lowercased resolved repo root; only events whose
- ``cwd`` sits inside it count (same scoping as the distill miners). Pure
- and streaming: state is bounded regardless of transcript size.
+ *repo_root* is the resolved repository root; only events whose ``cwd``
+ sits inside it count (same scoping as the distill miners), and every file
+ a candidate carries is stated relative to it. Pure and streaming: state
+ is bounded regardless of transcript size.
+
+ A file the session touched outside the root is dropped rather than kept
+ absolute. It names another checkout, a scratch directory, or the agent's
+ own state, none of which this index can resolve, and a scope built from
+ paths that resolve to nothing is worse than an empty one.
*edit_tools* is the producing adapter's edit vocabulary. It orders each
candidate's files, putting the ones the session changed ahead of the ones
it only opened, because a decision is about the code that moved and the
surrounding reads are how it got there.
"""
+ repo_prefix = str(repo_root).lower().rstrip("\\/")
candidates: list[SessionCandidate] = []
#: (path, intent) for the recent file-touching calls, so a candidate opened
#: here knows which of the files in play were being changed at the time.
@@ -367,7 +393,9 @@ def mine_events(
continue
if event.kind == "assistant" and event.tool_uses:
- touches = event_file_touches(event, edit_tools=edit_tools)
+ touches = _repo_relative_touches(
+ event_file_touches(event, edit_tools=edit_tools), repo_root
+ )
files = [path for path, _ in touches]
trailing_files.extend(touches)
changed = {path for path, intent in touches if intent == "edit"}
@@ -569,7 +597,6 @@ def _sweep_harness(
harness: str,
*,
repo_root: Path,
- repo_prefix: str,
projects_root: Path | None,
store: SessionStagingStore,
recorder: TranscriptEpisodeRecorder,
@@ -610,7 +637,7 @@ def _sweep_harness(
if collector is not None:
stream = collector.observe(stream)
for candidate in mine_events(
- stream, repo_prefix, edit_tools=adapter.edit_tool_names
+ stream, repo_root, edit_tools=adapter.edit_tool_names
):
counts["found"] += 1
if store.add_raw(
@@ -1008,7 +1035,6 @@ async def mine_session_decisions(
has no set does not start binding scope it cannot check.
"""
repo_root = Path(repo_path).resolve()
- repo_prefix = str(repo_root).lower().rstrip("\\/")
# The caller's resolved policy wins; reading config again here would be a
# second answer to a question it has already asked.
names = registered_harnesses(harnesses) if harnesses is not None else harnesses_for(repo_path)
@@ -1035,7 +1061,6 @@ async def mine_session_decisions(
yields[name] = _sweep_harness(
name,
repo_root=repo_root,
- repo_prefix=repo_prefix,
projects_root=projects_root,
store=store,
recorder=recorder,
diff --git a/tests/unit/sessions/test_decision_miner.py b/tests/unit/sessions/test_decision_miner.py
index 7aa94da3a..1f244a2eb 100644
--- a/tests/unit/sessions/test_decision_miner.py
+++ b/tests/unit/sessions/test_decision_miner.py
@@ -164,7 +164,7 @@ def test_forward_files_attach_to_correction():
_tool_call("Edit", {"file_path": "C:\\Users\\x\\repo\\adapter.py"}),
]
(candidate,) = mine_events(events, REPO_PREFIX)
- assert candidate.files == ["C:\\Users\\x\\repo\\adapter.py"]
+ assert candidate.files == ["adapter.py"]
# ---------------------------------------------------------------------------
@@ -183,7 +183,27 @@ def test_choice_near_file_activity_is_candidate():
(candidate,) = mine_events(events, REPO_PREFIX)
assert candidate.kind == "explicit_choice"
assert candidate.quotes == [CHOICE_TEXT]
- assert candidate.files == ["C:\\Users\\x\\repo\\staging.py"]
+ assert candidate.files == ["staging.py"]
+
+
+def test_a_choice_touching_only_another_checkout_is_dropped():
+ """An out-of-repo path is not a scope, so it cannot carry the gate."""
+ events = [
+ _tool_call("Write", {"file_path": "C:\\Users\\x\\other\\staging.py"}),
+ _tool_result("t1", {"ok": True}),
+ Event(kind="assistant", cwd=CWD, session_id="sess-1", text=CHOICE_TEXT),
+ ]
+ assert mine_events(events, REPO_PREFIX) == []
+
+
+def test_a_correction_keeps_only_the_files_inside_the_repository():
+ events = [
+ _user("No, keep the parser in the adapter module, don't inline it"),
+ _tool_call("Edit", {"file_path": "C:\\Users\\x\\repo\\a.py"}, "t1"),
+ _tool_call("Edit", {"file_path": "C:\\Users\\x\\elsewhere\\b.py"}, "t2"),
+ ]
+ (candidate,) = mine_events(events, REPO_PREFIX)
+ assert candidate.files == ["a.py"]
def test_choice_with_no_files_anywhere_is_dropped():
diff --git a/tests/unit/sessions/test_relative_files.py b/tests/unit/sessions/test_relative_files.py
new file mode 100644
index 000000000..3e5ff6a86
--- /dev/null
+++ b/tests/unit/sessions/test_relative_files.py
@@ -0,0 +1,60 @@
+"""Path normalization for the paths a transcript records.
+
+The staged decision rows and the index disagreed about what a path is: the
+miner wrote whatever the tool call was given, which is absolute, while the
+index holds repo-relative POSIX. These pin the seam from both sides, because
+a store written before the miner was fixed still has to read correctly.
+"""
+
+from __future__ import annotations
+
+import os
+
+from repowise.core.sessions.events import relative_files
+
+ROOT = r"C:\Users\x\repo"
+POSIX_ROOT = "/home/x/repo"
+
+
+def test_an_absolute_path_under_the_root_becomes_relative_posix():
+ assert relative_files([ROOT + r"\packages\core\a.py"], ROOT) == ["packages/core/a.py"]
+ assert relative_files([POSIX_ROOT + "/packages/core/a.py"], POSIX_ROOT) == [
+ "packages/core/a.py"
+ ]
+
+
+def test_an_absolute_path_outside_the_root_is_dropped():
+ assert relative_files([r"C:\Users\x\other\a.py"], ROOT) == []
+ assert relative_files(["/home/x/other/a.py"], POSIX_ROOT) == []
+
+
+def test_a_windows_path_reads_as_a_path_on_any_interpreter():
+ """Not as a relative name that happens to start with a drive letter."""
+ assert relative_files([r"D:\elsewhere\a.py"], POSIX_ROOT) == []
+
+
+def test_relativizing_twice_is_the_same_as_relativizing_once():
+ once = relative_files([ROOT + r"\a.py", r"C:\Users\x\other\b.py"], ROOT)
+ assert relative_files(once, ROOT) == once == ["a.py"]
+
+
+def test_an_already_relative_path_does_not_depend_on_the_working_directory(tmp_path, monkeypatch):
+ """The defect this guards: resolving against the process cwd.
+
+ ``os.path.relpath`` on a relative input resolves it against wherever the
+ process happens to be, which is the repository root only by luck. From
+ anywhere else every file escaped the root and was dropped, so a promoted
+ decision silently lost its whole scope.
+ """
+ monkeypatch.chdir(tmp_path)
+ assert relative_files(["packages/core/a.py"], ROOT) == ["packages/core/a.py"]
+ assert relative_files(["packages/core/a.py"], os.getcwd()) == ["packages/core/a.py"]
+
+
+def test_a_relative_path_that_escapes_the_root_is_still_dropped():
+ assert relative_files(["../sibling/a.py", "..", "a/../../b.py"], ROOT) == []
+
+
+def test_order_is_first_seen_and_duplicates_collapse():
+ files = [ROOT + r"\b.py", "a.py", ROOT + "/b.py", "a.py"]
+ assert relative_files(files, ROOT) == ["b.py", "a.py"]