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): bind a session-mined decision to code the repo actually has (#2395)

Raghav Chamadiyad4d3311886d6
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 4dd0c97b7..8ce5d23f5 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1851,6 +1851,10 @@ def run_update(
# collect the observation-qualified promotions. They ride the same
# decision upsert as the marker re-scan below. Everything stays local, and
# the lane ships off: `decision source set session --on` enables it.
+ # The indexed file set bounds what a session-mined record may claim to
+ # govern: a transcript names scratch files, plan docs and sibling
+ # checkouts, and only this set knows which paths are this codebase.
+ indexed_files = frozenset(source_map) if source_map else None
session_decisions: list = []
try:
from repowise.core.sessions.miners.decisions import mine_session_decisions
@@ -1863,6 +1867,7 @@ def run_update(
provider=session_provider,
harnesses=decision_policy.harnesses,
collect_discovery_spans=decision_policy.llm_allowed("session_discovery"),
+ indexed=indexed_files,
)
)
if session_decisions and verbose:
@@ -1884,6 +1889,7 @@ def run_update(
repo_path,
provider=provider,
policy=decision_policy,
+ indexed=indexed_files,
)
)
session_decisions = [*session_decisions, *outcome.decisions]
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py b/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py
index 66532ee8a..9e1100f20 100644
--- a/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import hashlib
import time
+from collections.abc import Container
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -128,6 +129,7 @@ async def run_update_discovery(
*,
provider: Any | None,
policy: DecisionPolicy,
+ indexed: Container[str] | None = None,
now: float | None = None,
) -> DiscoveryOutcome:
"""Make zero or one broad discovery call over this update's new prose.
@@ -153,7 +155,7 @@ async def run_update_discovery(
repo_root = Path(repo_path).resolve()
store = SessionStagingStore.open_default(repo_root)
try:
- return await _discover(store, repo_root, provider, policy, report, now)
+ return await _discover(store, repo_root, provider, policy, report, indexed, now)
finally:
store.close()
@@ -164,6 +166,7 @@ async def _discover(
provider: Any,
policy: DecisionPolicy,
report: DiscoveryReport,
+ indexed: Container[str] | None,
now: float | None,
) -> DiscoveryOutcome:
queued = store.pending_discovery_spans(_QUEUE_READ_LIMIT)
@@ -239,7 +242,7 @@ async def _discover(
_persist(store, grounding.grounded, report, now)
store.commit()
- decisions = _promote(store, repo_root, now)
+ decisions = _promote(store, repo_root, indexed, now)
store.commit()
logger.info("decision_discovery.done", **report.to_dict())
@@ -282,7 +285,12 @@ def _persist(
)
-def _promote(store: SessionStagingStore, repo_root: Path, now: float | None) -> list[Any]:
+def _promote(
+ store: SessionStagingStore,
+ repo_root: Path,
+ indexed: Container[str] | None,
+ now: float | None,
+) -> list[Any]:
"""Emit newly qualified discovery rows through the shared promotion path.
Restricted to this lane's own rows: the deterministic miner runs its own
@@ -298,6 +306,6 @@ def _promote(store: SessionStagingStore, repo_root: Path, now: float | None) ->
for row in store.promotable():
if row["kind"] != DISCOVERY_KIND:
continue
- decisions.extend(promotion_decisions(row, repo_root))
+ decisions.extend(promotion_decisions(row, repo_root, indexed=indexed))
store.mark_emitted(row["key"], observations=row["observations"], now=now)
return decisions
diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.py
index 14a6164ca..89b6deb83 100644
--- a/packages/core/src/repowise/core/analysis/decisions/scope.py
+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py
@@ -9,9 +9,17 @@ records to the widest level.
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import Container, Sequence
-__all__ = ["commit_scope_files", "derive_decision_scope", "resolve_module_nodes"]
+from repowise.core.support_paths import file_population
+from repowise.core.test_paths import is_test_related_path
+
+__all__ = [
+ "bind_scope_files",
+ "commit_scope_files",
+ "derive_decision_scope",
+ "resolve_module_nodes",
+]
#: Upper bound on the directories one record may claim. A record naming files
#: across more directories than this is not scoped by its module list anyway —
@@ -27,18 +35,72 @@ _MAX_MODULES = 12
#: files (17 ``git_archaeology``, 86 ``pr``) carry 1,468 scope entries beyond
#: it. 20 keeps the p75 record whole and matches the number ``inline_marker``
#: already caps its graph neighbours at — a different quantity, but reusing the
-#: value avoids a third cap to reason about.
+#: value avoids a third cap to reason about. Also the ceiling on a
+#: session-mined record, through :func:`bind_scope_files`: a decision made in
+#: one conversation is not about every file that conversation happened to open.
_MAX_FILES = 20
+#: Which population a scope entry is ranked under, narrowest claim first. A
+#: decision is about the system, so production code outranks the test that
+#: exercises it, which outranks an example, which outranks the docs and
+#: config files that describe it.
+_POPULATION_RANK = {"production": 0, "test": 1, "example": 2, "doc": 3}
+
+
+def _normalized(files: Sequence[str] | None) -> list[str]:
+ """POSIX-separated, stripped, deduped, in first-seen order."""
+ seen: dict[str, None] = {}
+ for f in files or []:
+ if f and f.strip():
+ seen.setdefault(f.replace("\\", "/").strip(), None)
+ return list(seen)
+
+
def commit_scope_files(files: Sequence[str] | None) -> list[str]:
"""The files a decision mined from one commit may claim to govern.
Sorted before truncating so which files survive the cap is reproducible,
rather than depending on the order git happened to list them in.
"""
- seen = {f.replace("\\", "/").strip() for f in files or [] if f and f.strip()}
- return sorted(seen)[:_MAX_FILES]
+ return sorted(_normalized(files))[:_MAX_FILES]
+
+
+def bind_scope_files(
+ files: Sequence[str] | None,
+ indexed: Container[str] | None,
+) -> list[str]:
+ """The entries of *files* the index holds, best claim first.
+
+ *indexed* is the indexed file set — ingestion's ``source_map`` keys, the
+ only thing that has applied gitignore, size, binary and generated-file
+ rules. Validating against it rather than against the tree is what keeps a
+ plan doc, a scratchpad script, or a file belonging to a sibling checkout
+ out of a scope: those resolve on disk and are still not this codebase.
+ ``None`` means no set was supplied and nothing is filtered, so a caller
+ that cannot reach one keeps its previous behaviour. An empty set is the
+ same case and callers pass ``None`` for it, because filtering everything
+ away is never the right reading of a missing set.
+
+ Ceiling: ``source_map`` is keyed on the files that parsed, so a file that
+ was traversed and then failed to read or parse is dropped from a scope
+ naming it. That is the whole of the gap — a file with no parser never
+ reaches the traverser's own ``FileInfo`` either — and it is worth the
+ narrowing, because ``source_map`` is the one set both the full and the
+ incremental pipeline already carry to this point.
+
+ Order is the claim quality: population first, then the order the caller
+ supplied, which is where a producer that knows which paths were edited
+ puts them first. Stable, so both rankings survive together.
+ """
+ kept = _normalized(files)
+ if indexed is not None:
+ kept = [f for f in kept if f in indexed]
+ ranked = sorted(
+ kept,
+ key=lambda f: _POPULATION_RANK[file_population(f, is_test=is_test_related_path(f))],
+ )
+ return ranked[:_MAX_FILES]
def resolve_module_nodes(files: Sequence[str] | None) -> list[str]:
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index f8d7b59c0..43ab34848 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -7,6 +7,7 @@ orchestrator.py) imports these phase functions. No CLI/click/rich imports.
from __future__ import annotations
import asyncio
+from collections.abc import Container
from dataclasses import replace
from pathlib import Path
from typing import Any
@@ -363,6 +364,7 @@ async def _run_session_discovery(
llm_client: Any | None,
policy: Any,
report: Any,
+ indexed: Container[str] | None = None,
) -> DiscoveryOutcome:
"""The one broad session-discovery call, folded into the decision report.
@@ -375,6 +377,7 @@ async def _run_session_discovery(
repo_path,
provider=llm_client,
policy=policy,
+ indexed=indexed,
),
timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
)
@@ -412,6 +415,11 @@ async def _run_decision_extraction(
if progress:
progress.on_phase_start("decisions", len(enabled))
+ # The indexed file set bounds what a session-mined record may claim
+ # to govern: a transcript names scratch files, plan docs and sibling
+ # checkouts, and only this set knows which paths are this codebase.
+ indexed = frozenset(source_map) if source_map else None
+
extractor = DecisionExtractor(
repo_path=repo_path,
provider=llm_client,
@@ -453,6 +461,7 @@ async def _run_decision_extraction(
provider=session_provider,
harnesses=policy.harnesses,
collect_discovery_spans=policy.llm_allowed("session_discovery"),
+ indexed=indexed,
),
timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
)
@@ -468,7 +477,7 @@ async def _run_decision_extraction(
# what filled its span queue. At most one call, and it reports its own
# zero so a switched-off source never reads as an empty repository.
discovery = await _run_session_discovery(
- repo_path, llm_client=llm_client, policy=policy, report=report
+ repo_path, llm_client=llm_client, policy=policy, report=report, indexed=indexed
)
if progress:
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
index 41a8aa172..bbb4a9f21 100644
--- a/packages/core/src/repowise/core/sessions/adapters/base.py
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -48,6 +48,20 @@ class HarnessAdapter(ABC):
#: Stable identifier, e.g. ``"claude_code"``.
name: ClassVar[str]
+ #: Tool names, in this harness's own vocabulary, whose calls change a file
+ #: rather than only look at one. A consumer ranking what a session did to a
+ #: path reads it from the adapter, never from a shared list: one harness
+ #: normalizes every edit to a single token and has no read tool at all, so
+ #: a flat set would be wrong rather than merely duplicated. Empty means the
+ #: adapter has not declared one, and nothing is treated as an edit.
+ #:
+ #: Namesake, not sibling: ``cli.agent_adapters.AgentAdapter`` declares the
+ #: same attribute for the editor hooks, and answers it for the live tool
+ #: call rather than for a recorded transcript. The two deliberately hold
+ #: different names for the same harness, and core cannot import cli, so
+ #: neither is the other's source of truth.
+ edit_tool_names: ClassVar[frozenset[str]] = frozenset()
+
@abstractmethod
def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
"""Transcript files for sessions rooted at *repo_root*, sorted.
diff --git a/packages/core/src/repowise/core/sessions/adapters/claude_code.py b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
index ad28451c6..83d41a604 100644
--- a/packages/core/src/repowise/core/sessions/adapters/claude_code.py
+++ b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
@@ -58,6 +58,9 @@ class ClaudeCodeAdapter(HarnessAdapter):
"""Normalizes Claude Code session JSONL into the shared Event stream."""
name: ClassVar[str] = "claude_code"
+ edit_tool_names: ClassVar[frozenset[str]] = frozenset(
+ {"Edit", "Write", "MultiEdit", "NotebookEdit"}
+ )
def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
directory = transcript_dir_for(repo_root, projects_root)
diff --git a/packages/core/src/repowise/core/sessions/adapters/codex.py b/packages/core/src/repowise/core/sessions/adapters/codex.py
index c8b1dbeab..2ff7910a3 100644
--- a/packages/core/src/repowise/core/sessions/adapters/codex.py
+++ b/packages/core/src/repowise/core/sessions/adapters/codex.py
@@ -66,6 +66,13 @@ class CodexAdapter(HarnessAdapter):
"""Normalizes Codex session JSONL into the shared Event stream."""
name: ClassVar[str] = "codex"
+ #: Codex reaches a file through apply_patch or a shell command, and
+ #: _normalize_tool_name folds every one of those onto this single token,
+ #: so the set is one name rather than a family. Inert until Codex edits
+ #: carry a path: their input is the patch text under ``command``, and
+ #: nothing scrapes the ``*** Update File:`` markers out of it yet, so no
+ #: Codex edit currently reaches a consumer of this set.
+ edit_tool_names: ClassVar[frozenset[str]] = frozenset({"edit_file"})
def __init__(self):
self._tool_calls: dict[str, ToolUse] = {}
diff --git a/packages/core/src/repowise/core/sessions/events.py b/packages/core/src/repowise/core/sessions/events.py
index bc60521b8..f3c9548c4 100644
--- a/packages/core/src/repowise/core/sessions/events.py
+++ b/packages/core/src/repowise/core/sessions/events.py
@@ -9,7 +9,7 @@ Events never needs to know which agent produced the transcript.
from __future__ import annotations
-from collections.abc import Iterable, Iterator
+from collections.abc import Container, Iterable, Iterator
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@@ -105,8 +105,16 @@ class Event:
FILE_INPUT_KEYS = ("file_path", "path", "notebook_path")
-def event_files(event: Event) -> list[str]:
- """File paths named by this event's tool inputs.
+def event_file_touches(
+ event: Event, *, edit_tools: Container[str] = frozenset()
+) -> list[tuple[str, str]]:
+ """``(path, intent)`` for every file this event's tool inputs name.
+
+ *intent* is ``"edit"`` when the call changed the file and ``"read"`` when
+ it only named one: the difference between the code a session decided about
+ and the code it looked at on the way. *edit_tools* comes from the adapter
+ that produced the event, because the harnesses do not share a tool
+ vocabulary; supplying none reports every touch as a read.
Deliberately blind to prose and to shell commands: a path argued about in
a paragraph, or passed to ``git`` inside a command string, is a mention
@@ -114,14 +122,19 @@ def event_files(event: Event) -> list[str]:
meaning anything. Lives here rather than in a miner because more than one
consumer folds the same stream and they must agree on what "touched" is.
"""
- files: list[str] = []
+ touches: list[tuple[str, str]] = []
for use in event.tool_uses:
for key in FILE_INPUT_KEYS:
value = use.input.get(key)
if isinstance(value, str) and value.strip():
- files.append(value)
+ touches.append((value, "edit" if use.name in edit_tools else "read"))
break
- return files
+ return touches
+
+
+def event_files(event: Event) -> list[str]:
+ """File paths named by this event's tool inputs, intent discarded."""
+ return [path for path, _ in event_file_touches(event)]
def is_prose_user_text(event: Event) -> bool:
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 5b8081fb1..d15ec7704 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -49,7 +49,7 @@ import json
import re
import time
from collections import deque
-from collections.abc import Iterable, Sequence
+from collections.abc import Container, Iterable, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -66,7 +66,7 @@ from repowise.core.analysis.decisions.provenance import (
verify_quote,
)
from repowise.core.analysis.decisions.rationale_comments import CAUSAL_MARKERS
-from repowise.core.analysis.decisions.scope import resolve_module_nodes
+from repowise.core.analysis.decisions.scope import bind_scope_files, resolve_module_nodes
from repowise.core.distill.corrections import command_anchor
from repowise.core.precedent.transcript_episodes import (
TranscriptEpisodeRecorder,
@@ -77,7 +77,7 @@ from repowise.core.sessions.adapters.registry import DEFAULT_ADAPTER, registered
from repowise.core.sessions.cursor import iter_new_events
from repowise.core.sessions.events import (
FILE_INPUT_KEYS,
- event_files,
+ event_file_touches,
is_prose_user_text,
relative_files,
)
@@ -190,6 +190,11 @@ class SessionCandidate:
kind: str # user_correction | explicit_choice | dead_end
quotes: list[str]
files: list[str] = field(default_factory=list)
+ #: Which of ``files`` this candidate saw changed rather than only read.
+ #: Ordering input only, never staged: staging keeps ``files`` and an
+ #: already-staged row is never rewritten, so the order must be right the
+ #: first time.
+ edited: set[str] = field(default_factory=set)
session_id: str | None = None
ts: float | None = None
@@ -321,15 +326,27 @@ def _result_anchor(name: str, use_input: dict[str, Any]) -> str:
return name.lower()
-def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandidate]:
+def mine_events(
+ events: Iterable[Event],
+ repo_prefix: str,
+ *,
+ 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.
+
+ *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.
"""
candidates: list[SessionCandidate] = []
- trailing_files: deque[str] = deque(maxlen=_TRAILING_FILES)
+ #: (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.
+ trailing_files: deque[tuple[str, str]] = deque(maxlen=_TRAILING_FILES)
#: Candidates still collecting forward files, with their remaining budget.
open_candidates: list[list[Any]] = [] # [candidate, remaining_tool_events]
#: tool_use id -> (tool name, input) awaiting its result.
@@ -349,11 +366,13 @@ def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandid
continue
if event.kind == "assistant" and event.tool_uses:
- files = event_files(event)
- for f in files:
- trailing_files.append(f)
+ touches = event_file_touches(event, edit_tools=edit_tools)
+ files = [path for path, _ in touches]
+ trailing_files.extend(touches)
+ changed = {path for path, intent in touches if intent == "edit"}
for entry in open_candidates:
entry[0].files.extend(f for f in files if f not in entry[0].files)
+ entry[0].edited |= changed
entry[1] -= 1
open_candidates = [e for e in open_candidates if e[1] > 0]
for use in event.tool_uses:
@@ -402,7 +421,8 @@ def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandid
SessionCandidate(
kind="dead_end",
quotes=[q for q in (attempt, error, pivot) if q],
- files=list(dict.fromkeys(trailing_files)),
+ files=list(dict.fromkeys(p for p, _ in trailing_files)),
+ edited={p for p, i in trailing_files if i == "edit"},
session_id=event.session_id,
ts=event.ts,
)
@@ -427,7 +447,8 @@ def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandid
SessionCandidate(
kind="user_correction",
quotes=quotes,
- files=list(dict.fromkeys(trailing_files)),
+ files=list(dict.fromkeys(p for p, _ in trailing_files)),
+ edited={p for p, i in trailing_files if i == "edit"},
session_id=event.session_id,
ts=event.ts,
)
@@ -453,12 +474,16 @@ def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandid
SessionCandidate(
kind="explicit_choice",
quotes=[_clip(s) for s in sentences],
- files=list(dict.fromkeys(trailing_files)),
+ files=list(dict.fromkeys(p for p, _ in trailing_files)),
+ edited={p for p, i in trailing_files if i == "edit"},
session_id=event.session_id,
ts=event.ts,
)
)
+ for candidate in candidates:
+ candidate.files.sort(key=lambda f: f not in candidate.edited)
+
# A choice with no code in play is a conversation, not a decision record.
return [c for c in candidates if c.kind != "explicit_choice" or c.files]
@@ -583,7 +608,9 @@ def _sweep_harness(
stream = recorder.observe(path, events)
if collector is not None:
stream = collector.observe(stream)
- for candidate in mine_events(stream, repo_prefix):
+ for candidate in mine_events(
+ stream, repo_prefix, edit_tools=adapter.edit_tool_names
+ ):
counts["found"] += 1
if store.add_raw(
hash_=candidate.hash,
@@ -684,7 +711,9 @@ def _gate_structured(item: dict[str, Any], raw: dict[str, Any]) -> dict[str, Any
if verify_quote(plain_rationale, plain_source, fuzzy_threshold=0.5) == "unverified":
rationale = ""
claimed = item.get("affected_files")
- files = [f for f in claimed if f in raw["files"]] if isinstance(claimed, list) else []
+ # Iterate the mined list rather than the model's: same set either way,
+ # and the mined order is the one carrying what the session edited.
+ files = [f for f in raw["files"] if f in claimed] if isinstance(claimed, list) else []
if not files and raw["kind"] != "user_correction":
# A choice/dead end is about the code in play; a correction with no
# named files is a repo-wide rule, and linking it to whatever files
@@ -708,7 +737,25 @@ def _gate_structured(item: dict[str, Any], raw: dict[str, Any]) -> dict[str, Any
_MAX_EVIDENCE_SESSIONS = 5
-def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedDecision]:
+def _staged_files(structured: dict[str, Any], row: dict[str, Any]) -> list[str]:
+ """The files a staged row claims, distinguishing empty from absent.
+
+ ``_gate_structured`` leaves the list empty on purpose for a correction the
+ model named no files for, because a repo-wide rule linked to whatever was
+ open governs the wrong code. Only a row with no structured claim at all
+ falls back to the gate hits, which staging accretes across observations:
+ the latest structuring pass wins over what earlier ones had in play.
+ """
+ claimed = structured.get("affected_files")
+ return list(claimed) if claimed is not None else list(row["files"])
+
+
+def promotion_decisions(
+ row: dict[str, Any],
+ repo_root: Path,
+ *,
+ indexed: Container[str] | None = None,
+) -> list[ExtractedDecision]:
"""decision_records-ready members for one promotable staging row.
One member per observing session (capped) so each session becomes its own
@@ -719,12 +766,19 @@ def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedD
acceptance event: authority comes from a person confirming the record.
``first_promotion`` still gates re-emission in the staging store, so a
recurring candidate accretes evidence without re-proposing itself.
+
+ *indexed* is the indexed file set, and binding happens here rather than at
+ staging so a candidate staged before the set was threaded is repaired on
+ its way out rather than staying wrong.
"""
structured = row["structured"]
# Both session lanes store source="session"; the staging kind is what tells
# a reviewer which one raised the candidate.
lane = DISCOVERY_KIND if row.get("kind") == DISCOVERY_KIND else "session"
- files = relative_files(structured.get("affected_files") or row["files"], repo_root)
+ files = bind_scope_files(
+ relative_files(_staged_files(structured, row), repo_root),
+ indexed,
+ )
modules = resolve_module_nodes(files)
# Staging carries a decision and a rationale and no more, so a promoted
# record is thin by construction and is scored as such.
@@ -911,6 +965,7 @@ async def mine_session_decisions(
harnesses: Sequence[str] | None = None,
max_structured: int = MAX_STRUCTURED_PER_UPDATE,
collect_discovery_spans: bool = False,
+ indexed: Container[str] | None = None,
now: float | None = None,
) -> list[ExtractedDecision]:
"""Read this repo's new transcript lines once, and serve both consumers.
@@ -936,6 +991,10 @@ async def mine_session_decisions(
assistant prose that the broad discovery lane consumes. It rides this pass
for the same reason the episode recorder does: the cursor advances as the
bytes are read, so a second reader would find an empty file.
+
+ *indexed* is the indexed file set, which bounds what a promoted record may
+ claim to govern. Omitting it keeps the previous behaviour, so a caller that
+ has no set does not start binding scope it cannot check.
"""
repo_root = Path(repo_path).resolve()
repo_prefix = str(repo_root).lower().rstrip("\\/")
@@ -1038,7 +1097,7 @@ async def mine_session_decisions(
for row in store.promotable():
if row["kind"] == DISCOVERY_KIND:
continue # the broad lane runs its own promotion, under its own rules
- decisions.extend(promotion_decisions(row, repo_root))
+ decisions.extend(promotion_decisions(row, repo_root, indexed=indexed))
store.mark_emitted(row["key"], observations=row["observations"], now=now)
store.commit()
diff --git a/tests/unit/analysis/test_decision_authority_containment.py b/tests/unit/analysis/test_decision_authority_containment.py
index 166a755b5..65cea468f 100644
--- a/tests/unit/analysis/test_decision_authority_containment.py
+++ b/tests/unit/analysis/test_decision_authority_containment.py
@@ -258,3 +258,50 @@ class TestPromotionCarriesTheReviewLane:
row["structured"]["needs_split"] = True
assert all(d.needs_split for d in promotion_decisions(row, Path(".")))
+
+
+class TestScopeNamesOnlyIndexedCode:
+ """A record is delivered as a rule about the files it names."""
+
+ INDEXED = frozenset({"pkg/engine.py", "docs/DESIGN.md"})
+
+ def test_a_path_outside_the_index_never_reaches_a_record(self):
+ out = promotion_decisions(
+ _row(structured={**_row()["structured"], "affected_files": ["local-stash/PLAN.md"]}),
+ Path("."),
+ indexed=self.INDEXED,
+ )
+ assert all(d.affected_files == [] for d in out)
+
+ def test_an_indexed_path_survives(self):
+ out = promotion_decisions(
+ _row(structured={**_row()["structured"], "affected_files": ["pkg/engine.py"]}),
+ Path("."),
+ indexed=self.INDEXED,
+ )
+ assert all(d.affected_files == ["pkg/engine.py"] for d in out)
+
+ def test_without_an_index_set_nothing_is_filtered(self):
+ out = promotion_decisions(
+ _row(structured={**_row()["structured"], "affected_files": ["local-stash/PLAN.md"]}),
+ Path("."),
+ )
+ assert all(d.affected_files == ["local-stash/PLAN.md"] for d in out)
+
+ def test_a_structured_claim_of_no_files_is_a_refusal_not_a_missing_key(self):
+ """The correction gate empties the list on purpose; staging must not refill it."""
+ out = promotion_decisions(
+ _row(files=["pkg/engine.py"]), # structured affected_files is []
+ Path("."),
+ indexed=self.INDEXED,
+ )
+ assert all(d.affected_files == [] for d in out)
+
+ def test_a_row_with_no_structured_claim_still_falls_back_to_the_gate_hits(self):
+ structured = {k: v for k, v in _row()["structured"].items() if k != "affected_files"}
+ out = promotion_decisions(
+ _row(structured=structured, files=["pkg/engine.py"]),
+ Path("."),
+ indexed=self.INDEXED,
+ )
+ assert all(d.affected_files == ["pkg/engine.py"] for d in out)
diff --git a/tests/unit/analysis/test_decision_scope.py b/tests/unit/analysis/test_decision_scope.py
index 6a74d434b..191eb7a7d 100644
--- a/tests/unit/analysis/test_decision_scope.py
+++ b/tests/unit/analysis/test_decision_scope.py
@@ -2,7 +2,11 @@
from __future__ import annotations
-from repowise.core.analysis.decisions.scope import commit_scope_files, derive_decision_scope
+from repowise.core.analysis.decisions.scope import (
+ bind_scope_files,
+ commit_scope_files,
+ derive_decision_scope,
+)
def test_single_file_is_file() -> None:
@@ -81,3 +85,75 @@ def test_blank_and_duplicate_entries_do_not_consume_the_cap() -> None:
def test_windows_separators_normalise_before_the_cap() -> None:
assert commit_scope_files([r"pkg\m.py", "pkg/m.py"]) == ["pkg/m.py"]
+
+
+# ---------------------------------------------------------------------------
+# bind_scope_files: a scope may only name files the index holds
+# ---------------------------------------------------------------------------
+
+INDEXED = frozenset(
+ {
+ "packages/core/engine.py",
+ "packages/core/loader.py",
+ "tests/unit/test_engine.py",
+ "docs/DESIGN.md",
+ "examples/demo/main.py",
+ }
+)
+
+
+def test_a_path_the_index_does_not_hold_is_not_a_scope() -> None:
+ """The failure this exists for: a plan doc and a sibling checkout."""
+ assert bind_scope_files(
+ ["local-stash/PLAN.md", "backend/app/main.py", "packages/core/engine.py"], INDEXED
+ ) == ["packages/core/engine.py"]
+
+
+def test_a_candidate_that_names_nothing_real_binds_nothing() -> None:
+ assert bind_scope_files(["local-stash/PLAN.md", "C:/tmp/scratch.py"], INDEXED) == []
+
+
+def test_no_index_set_filters_nothing() -> None:
+ """A caller that cannot reach the set keeps the previous behaviour."""
+ assert bind_scope_files(["local-stash/PLAN.md"], None) == ["local-stash/PLAN.md"]
+
+
+def test_production_code_outranks_test_example_and_prose() -> None:
+ assert bind_scope_files(
+ [
+ "docs/DESIGN.md",
+ "examples/demo/main.py",
+ "tests/unit/test_engine.py",
+ "packages/core/engine.py",
+ ],
+ INDEXED,
+ ) == [
+ "packages/core/engine.py",
+ "tests/unit/test_engine.py",
+ "examples/demo/main.py",
+ "docs/DESIGN.md",
+ ]
+
+
+def test_the_callers_order_survives_inside_one_population() -> None:
+ """Which is how the edited-first order the miner applied reaches the record."""
+ assert bind_scope_files(["packages/core/loader.py", "packages/core/engine.py"], INDEXED) == [
+ "packages/core/loader.py",
+ "packages/core/engine.py",
+ ]
+
+
+def test_windows_separators_normalise_before_the_lookup() -> None:
+ assert bind_scope_files([r"packages\core\engine.py"], INDEXED) == ["packages/core/engine.py"]
+
+
+def test_blanks_and_duplicates_collapse() -> None:
+ assert bind_scope_files(
+ ["packages/core/engine.py", "packages/core/engine.py", " ", ""], INDEXED
+ ) == ["packages/core/engine.py"]
+ assert bind_scope_files(None, INDEXED) == []
+
+
+def test_the_file_cap_still_applies() -> None:
+ wide = frozenset(f"pkg/m{i:03d}.py" for i in range(40))
+ assert len(bind_scope_files(sorted(wide), wide)) == 20
diff --git a/tests/unit/sessions/test_decision_miner.py b/tests/unit/sessions/test_decision_miner.py
index 49aa44456..7aa94da3a 100644
--- a/tests/unit/sessions/test_decision_miner.py
+++ b/tests/unit/sessions/test_decision_miner.py
@@ -353,3 +353,55 @@ def test_session_mining_enabled_parsing():
assert session_mining_enabled({"decisions": {"sources": {"session": True}}}) is True
assert session_mining_enabled({"decisions": {"session_mining": True}}) is True
assert session_mining_enabled({"decisions": {"session_mining": False}}) is False
+
+
+# ---------------------------------------------------------------------------
+# edited-above-read ordering
+# ---------------------------------------------------------------------------
+
+EDIT_TOOLS = frozenset({"Edit", "Write"})
+
+
+def test_edited_files_lead_the_files_the_session_only_read():
+ events = [
+ _tool_call("Read", {"file_path": "a/read.py"}, "t1"),
+ _tool_call("Edit", {"file_path": "a/edit.py"}, "t2"),
+ _user("no, always keep the loader separate because the parser reuses it"),
+ ]
+ # The lead sentence trips the correction gate and falls through to the
+ # choice gate, so both candidates carry the same window.
+ candidates = mine_events(events, REPO_PREFIX, edit_tools=EDIT_TOOLS)
+ assert candidates
+ for candidate in candidates:
+ assert candidate.files == ["a/edit.py", "a/read.py"]
+
+
+def test_without_an_edit_vocabulary_the_order_is_left_alone():
+ """An adapter that declares none must not have its files reordered."""
+ events = [
+ _tool_call("Read", {"file_path": "a/read.py"}, "t1"),
+ _tool_call("Edit", {"file_path": "a/edit.py"}, "t2"),
+ _user("no, always keep the loader separate because the parser reuses it"),
+ ]
+ candidates = mine_events(events, REPO_PREFIX)
+ assert candidates
+ for candidate in candidates:
+ assert candidate.files == ["a/read.py", "a/edit.py"]
+
+
+def test_a_candidates_own_edit_leads_however_long_the_session_runs_on():
+ """The rank is what this candidate saw, not the session's last few touches."""
+ events = [
+ _tool_call("Read", {"file_path": "a/looked.py"}, "t1"),
+ _tool_call("Edit", {"file_path": "a/decided.py"}, "t2"),
+ _user("no, always keep the loader separate because the parser reuses it"),
+ ]
+ events += [_tool_call("Edit", {"file_path": f"z/later{i}.py"}, f"t{i + 10}") for i in range(12)]
+ candidates = mine_events(events, REPO_PREFIX, edit_tools=EDIT_TOOLS)
+ assert candidates
+ for candidate in candidates:
+ # Files edited after the candidate attach to it on purpose, so the
+ # read is last rather than second; what matters is that the file being
+ # changed when the decision landed still leads.
+ assert candidate.files[0] == "a/decided.py"
+ assert candidate.files[-1] == "a/looked.py"