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.

feat(episodes): record each code fix as a dated change bound to the files it touched (#1324)

Raghav Chamadiyac6acf039843a
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
index b5a52f6d3..4bcdc776f 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
@@ -96,6 +96,23 @@ _MAX_SIGNIFICANT_COMMITS: int = 50
# Truncation is byte-accurate (UTF-8) so the cap is a real storage ceiling.
_MAX_COMMIT_BODY_BYTES: int = 1024
+
+def _truncate_body(body: str) -> str:
+ """Trim *body* to the byte ceiling, never splitting a UTF-8 sequence.
+
+ Lives beside its ceiling rather than in one of the two modules that need it
+ (``file_history`` retains bodies on significant-commit entries, the
+ prior-defect walk carries them on fix commits) so the cap has exactly one
+ implementation.
+ """
+ if not body:
+ return ""
+ encoded = body.encode("utf-8")
+ if len(encoded) <= _MAX_COMMIT_BODY_BYTES:
+ return body
+ return encoded[:_MAX_COMMIT_BODY_BYTES].decode("utf-8", errors="ignore")
+
+
# PR/squash-description markers — a body containing one of these reads like a
# real PR write-up worth retaining for decision mining (mirrors the extractor's
# ``_PR_BODY_MARKERS``; kept here to avoid a cross-package import at index time).
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
index c544e07c4..ac9b72a5d 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
@@ -23,12 +23,12 @@ from ._constants import (
_COMMIT_CATEGORIES,
_DECISION_SIGNAL_WORDS,
_MAX_BLAME_SIZE_BYTES,
- _MAX_COMMIT_BODY_BYTES,
_MAX_SIGNIFICANT_COMMITS,
_MAX_TOP_AUTHORS,
_PR_BODY_MARKERS,
_PR_NUMBER_RE,
HOTSPOT_HALFLIFE_DAYS,
+ _truncate_body,
)
from .enrich import detect_original_path, is_significant_commit
from .function_blame import (
@@ -62,16 +62,6 @@ def _body_carries_decision(subject: str, body: str) -> bool:
return any(word in blob for word in _DECISION_SIGNAL_WORDS)
-def _truncate_body(body: str) -> str:
- """Trim *body* to the byte ceiling, never splitting a UTF-8 sequence."""
- if not body:
- return ""
- encoded = body.encode("utf-8")
- if len(encoded) <= _MAX_COMMIT_BODY_BYTES:
- return body
- return encoded[:_MAX_COMMIT_BODY_BYTES].decode("utf-8", errors="ignore")
-
-
logger = structlog.get_logger(__name__)
__all__ = ["DECAY_REFRESH_KEYS", "index_file", "new_meta"]
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 79e1119e3..ca4298876 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -73,11 +73,18 @@ class GitIndexer:
follow_renames: bool = False,
tier: GitIndexTier = GitIndexTier.FULL,
exclude_patterns: list[str] | None = None,
+ record_episodes: bool = False,
) -> None:
self.repo_path = Path(repo_path)
self.commit_limit = commit_limit or _DEFAULT_COMMIT_LIMIT
self.follow_renames = follow_renames
self.tier = tier
+ # Off by default, and a constructor parameter rather than a call site.
+ # `health` and `dead-code` build an indexer of their own to read
+ # metadata, without the repo's exclude patterns; letting them write
+ # episodes would make two nominally read-only commands persist rows
+ # naming files the repo excludes, and those rows outlive every prune.
+ self.record_episodes = record_episodes
import pathspec
@@ -287,6 +294,10 @@ class GitIndexer:
# above stand on their own if tracing breaks.
fix_event_rows, built_ok = await asyncio.to_thread(self._build_fix_events, fix_walk)
+ # Git-tier episodes ride the same walk for the same reason. Off the
+ # event loop because it writes SQLite.
+ await asyncio.to_thread(self._record_git_episodes, fix_walk)
+
# Per-file AI line share from the agent-trace records. Keyed by path
# like the aggregates below, so it merges in the same pass and
# works regardless of which commit-index walk (if any) ran.
@@ -738,6 +749,7 @@ class GitIndexer:
skip_shas=known_shas,
)
rows, ok = self._build_fix_events(walk)
+ self._record_git_episodes(walk)
return rows, (walk.oldest_fix_ts if ok else 0), tracked
except Exception as exc:
logger.debug("incremental_fix_events_failed", error=str(exc))
@@ -764,6 +776,20 @@ class GitIndexer:
logger.debug("fix_event_build_failed", error=str(exc))
return [], False
+ def _record_git_episodes(self, walk: FixWalk) -> None:
+ """Persist *walk*'s code fixes as git-tier episodes. Never raises.
+
+ Imported lazily, like the other precedent call sites: the episode store
+ is stdlib-only so hook-time readers can open it cheaply, and keeping it
+ off this module's import graph is what preserves that.
+ """
+ if not self.record_episodes:
+ return
+ with contextlib.suppress(Exception):
+ from ...precedent.git_episodes import record_git_episodes
+
+ record_git_episodes(self.repo_path, walk)
+
def capture_repo_totals(self) -> Any:
"""Whole-history :class:`RepoTotals` for this repo (opens its own repo).
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py
index 05c2cbff9..5fa634ac4 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py
@@ -37,7 +37,7 @@ from typing import TYPE_CHECKING, Any
import structlog
-from ._constants import PRIOR_DEFECT_WINDOW_DAYS, is_fix_commit
+from ._constants import PRIOR_DEFECT_WINDOW_DAYS, _truncate_body, is_fix_commit
from .fix_shape import classify_fix_shape
from .records import _RECORD_SEP, _extract_rename_paths
@@ -50,10 +50,15 @@ logger = structlog.get_logger(__name__)
__all__ = ["FixCommit", "FixWalk", "PriorDefects", "collect_fix_commits", "compute_prior_defects"]
-# sha <US> committer-time <US> subject, one record per commit (NUL-separated);
-# --name-only then emits the touched paths on the lines that follow.
-_PRIOR_LOG_FORMAT = "%x00%H%x1f%ct%x1f%s"
+# sha <US> committer-time <US> subject <US> body <STX>, one record per commit
+# (NUL-separated); --name-only then emits the touched paths on the lines that
+# follow. The body (``%b``) is the only multi-line field, so it is captured last
+# and terminated explicitly: unlike the numstat block ``records.py`` disentangles
+# by shape, a ``--name-only`` path line is indistinguishable from a line of prose,
+# so the boundary has to be a byte git will never emit inside a message.
+_PRIOR_LOG_FORMAT = "%x00%H%x1f%ct%x1f%s%x1f%b%x02"
_FIELD_SEP = "\x1f"
+_BODY_END = "\x02"
# Fix commits per ``git log --no-walk`` batch in the diff pass. One subprocess
# per batch, so bigger is cheaper — but each sha costs 41 characters of command
@@ -84,6 +89,11 @@ class FixCommit:
the shape classifier reads and SZZ blames. *shape_kind* falls back to
``code_fix`` when the diff pass failed for this commit, which keeps the count
on the pre-filter (safe) side of the change.
+
+ *subject* and *body* are the commit's own prose, byte-capped. The counting
+ consumers read neither: they exist for consumers that quote a change rather
+ than count it, and they cost no extra git work because the walk already
+ parses the subject to classify the commit.
"""
sha: str
@@ -91,6 +101,8 @@ class FixCommit:
paths: list[str]
shape_kind: str = "code_fix"
files: dict[str, FileDiff] = field(default_factory=dict)
+ subject: str = ""
+ body: str = ""
@dataclass(frozen=True)
@@ -137,7 +149,8 @@ def collect_fix_commits(
is missing from the walk entirely, not merely un-diffed.
Ceiling: the returned walk holds every fix commit's parsed patch, changed
- line text included, for as long as the caller keeps it. Bounded in practice
+ line text included, plus a byte-capped copy of its message, for as long as
+ the caller keeps it. Bounded in practice
by the window (a few hundred commits), but a repo whose fixes routinely touch
multi-megabyte generated files will hold all of that at once. If that ever
bites, drop ``removed``/``added`` after classification and carry the LOC
@@ -165,6 +178,8 @@ def collect_fix_commits(
paths=fix.paths,
shape_kind=classify_fix_shape(diffs[fix.sha]) if fix.sha in diffs else "code_fix",
files=diffs.get(fix.sha, {}),
+ subject=fix.subject,
+ body=fix.body,
)
for fix in fixes
]
@@ -267,17 +282,50 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> l
record = record.strip("\n")
if not record:
continue
- header, _, body = record.partition("\n")
- sha, _, rest = header.partition(_FIELD_SEP)
- committed, _, subject = rest.partition(_FIELD_SEP)
+ fields, path_block = _split_record(record)
+ sha, committed, subject, body = fields
if not is_fix_commit(subject):
continue
- paths = [p for p in _record_paths(body) if p in indexable_files]
+ paths = [p for p in _record_paths(path_block) if p in indexable_files]
if paths:
- fixes.append(FixCommit(sha=sha, ts=_as_ts(committed), paths=paths))
+ fixes.append(
+ FixCommit(
+ sha=sha,
+ ts=_as_ts(committed),
+ paths=paths,
+ subject=_truncate_body(subject.strip()),
+ body=_truncate_body(body.strip()),
+ )
+ )
return fixes
+def _split_record(record: str) -> tuple[tuple[str, str, str, str], str]:
+ """One log record split into its four header fields and its path block.
+
+ Both boundaries are taken from the right, and for the same reason. Git
+ C-quotes any control byte in a path, so neither the terminator nor a field
+ separator can appear in the path block: the *last* occurrence of each is
+ therefore the real one, and a commit message that somehow carried one keeps
+ its paths and its subject intact. Taking the subject boundary from the left
+ instead would truncate a subject at an embedded separator and change which
+ commits ``is_fix_commit`` matches, which is a defect count rather than a
+ cosmetic loss.
+
+ The terminator is not optional and there is no fallback for its absence:
+ a legacy re-parse would read body prose as paths and *inflate* counts,
+ which is worse than the format change it would be papering over.
+ ``tests/unit/ingestion/test_prior_defect_walk.py`` is the guard.
+ """
+ head, _, path_block = record.rpartition(_BODY_END)
+ sha, _, rest = head.partition(_FIELD_SEP)
+ committed, _, rest = rest.partition(_FIELD_SEP)
+ subject, sep, body = rest.rpartition(_FIELD_SEP)
+ if not sep: # a commit with no body field at all
+ subject, body = rest, ""
+ return (sha, committed, subject, body), path_block
+
+
def _as_ts(raw: str) -> int:
try:
return int(raw.strip())
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 0f7c5fd17..a9e6158dd 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -586,6 +586,8 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
# the repo's excludes an update would store events for files a full
# index never sees, and they would never age out.
exclude_patterns=cfg.get("exclude_patterns"),
+ # Git episodes ride the same capture and inherit those excludes.
+ record_episodes=True,
)
newest = await get_latest_commit_committed_at(session, repo_id)
since_ts: int | None = None
diff --git a/packages/core/src/repowise/core/pipeline/phases/git.py b/packages/core/src/repowise/core/pipeline/phases/git.py
index 1dc60adaa..1307ee8ab 100644
--- a/packages/core/src/repowise/core/pipeline/phases/git.py
+++ b/packages/core/src/repowise/core/pipeline/phases/git.py
@@ -58,6 +58,9 @@ async def _run_git_indexing(
follow_renames=follow_renames,
tier=tier,
exclude_patterns=exclude_patterns,
+ # The indexing pass proper, and the one that knows the repo's
+ # excludes, so this is where a git episode may be recorded.
+ record_episodes=True,
)
def _on_start(total: int) -> None:
diff --git a/packages/core/src/repowise/core/precedent/git_episodes.py b/packages/core/src/repowise/core/precedent/git_episodes.py
new file mode 100644
index 000000000..9144b4359
--- /dev/null
+++ b/packages/core/src/repowise/core/precedent/git_episodes.py
@@ -0,0 +1,149 @@
+"""Git episodes: one dated change, kept whole, bound to the files it touched.
+
+The second tier of the store, and the one that needs a real repository rather
+than a bare checkout. A consumer of the prior-defect walk, never a second pass
+over history: the walk already resolves which commits are fixes, which files
+they touched, what shape their diff has and what their author wrote, so this
+module builds episodes out of what is in hand and spawns nothing.
+
+**What an episode says that ``get_risk`` does not.** The metric is a file with
+a count, recomputed every index. An episode is one dated change: the files that
+moved *together* in it, the author's own account of why, and a birth commit that
+makes "does this still hold" a question git can answer. On this repository
+``get_risk`` reports zero co-change partners for the file whose full-text index
+was repaired in 5e7bcf98, while the episode for that commit names the doctor
+check that was repaired alongside it, because they were one change. A statistic
+over every change and the partner set of one change are different objects.
+
+**Only code fixes become episodes.** ``is_fix_commit`` reads the commit subject,
+and a subject rule over-fires: on flask, 53.5% of the commits it counts as fixes
+change no production code at all (:mod:`..ingestion.git_indexer.fix_shape`).
+Filtering to the ``code_fix`` diff shape is what that measurement says to do,
+and it costs nothing because the walk has already classified every commit.
+
+Two limits worth stating rather than discovering. Selection still rests on the
+subject rule, which is an English-prose dependency: a repository whose authors
+never write "fix", "bug", "patch" or "resolves" in a subject gets few episodes
+here, and degrades to its structural ones. Replacing that with a diff-shape
+proxy needs a wider walk than the defect pass can afford, so it belongs with the
+recurrence detector that needs the same widening; this tier inherits it for free
+when it lands, as another kind beside ``code_fix``.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from .store import TIER_GIT, Episode, EpisodeStore
+
+__all__ = ["KIND_CODE_FIX", "derive_git_episodes", "record_git_episodes"]
+
+# Stdlib logging, like the sibling tier: this package is deliberately free of
+# the core import graph so a hook can open the store inside its budget.
+_log = logging.getLogger(__name__)
+
+#: The one kind this module writes. A commit whose diff changes production code.
+KIND_CODE_FIX = "code_fix"
+
+#: Node-set ceiling. A change touching more files than this is a sweep rather
+#: than a located one, and the scope it would carry is the read-time argument
+#: list of a ``git rev-list``. Commits above it are skipped rather than
+#: truncated: an episode whose node set is a subset of what its body describes
+#: answers a narrower staleness question than it appears to.
+MAX_EPISODE_NODES = 25
+
+
+def derive_git_episodes(walk: Any) -> list[Episode]:
+ """Episodes for the code fixes in *walk*. Pure; opens nothing.
+
+ *walk* is a :class:`~..ingestion.git_indexer.prior_defects.FixWalk`, typed
+ loosely so this package keeps its stdlib-only import graph — the store it
+ writes to is read on a hook path with a 155 ms budget.
+
+ Each commit is isolated, as the sibling tier isolates each check: one
+ malformed entry costs its own episode and not the window's.
+ """
+ episodes: list[Episode] = []
+ for fix in walk.fixes:
+ try:
+ episode = _episode_for(fix)
+ except Exception:
+ _log.debug("git episode skipped", exc_info=True)
+ continue
+ if episode is not None:
+ episodes.append(episode)
+ return episodes
+
+
+def record_git_episodes(repo_path: Path | str, walk: Any) -> int:
+ """Derive and persist *walk*'s episodes. Returns how many were written.
+
+ Best-effort in full: a repository that cannot record an episode is a
+ repository that indexes exactly as it did before. Never raises, and never
+ creates a ``.repowise`` directory where the user has not run ``init``.
+
+ The swallow logs, because the failure it hides — a locked or unwritable
+ sidecar — looks exactly like a repository whose window held no fixes.
+ """
+ root = Path(repo_path)
+ if not (root / ".repowise").is_dir():
+ return 0
+ try:
+ episodes = derive_git_episodes(walk)
+ # Taken before any ``skip_shas`` narrowing, so an incremental run and a
+ # full index agree on where the window ends. Zero means the walk found
+ # nothing and cannot vouch for a trailing edge.
+ oldest = walk.oldest_fix_ts
+ with EpisodeStore.open_for_repo(root) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=episodes,
+ oldest_birth_at=float(oldest) if oldest > 0 else None,
+ )
+ return len(episodes)
+ except Exception:
+ _log.debug("git episodes not recorded", exc_info=True)
+ return 0
+
+
+def _episode_for(fix: Any) -> Episode | None:
+ """One episode, or ``None`` when this commit is not one.
+
+ Four reasons a fix commit produces nothing, each of them a claim the
+ episode could not stand behind: its diff changes no production code, it is
+ a sweep rather than a located change, it has no committer time to be born
+ at, or it says nothing a reader could quote.
+ """
+ if fix.shape_kind != KIND_CODE_FIX:
+ return None
+ paths = sorted(set(fix.paths or ()))
+ if not paths or len(paths) > MAX_EPISODE_NODES:
+ return None
+ if fix.ts <= 0 or not fix.subject.strip():
+ return None
+
+ on = datetime.fromtimestamp(fix.ts, tz=UTC).strftime("%Y-%m-%d")
+ files = "1 file" if len(paths) == 1 else f"{len(paths)} files"
+ return Episode(
+ tier=TIER_GIT,
+ kind=KIND_CODE_FIX,
+ # The sha, not the subject line: two commits may share a subject, and
+ # identity here has to be the commit itself. The prose is the body.
+ subject=fix.sha,
+ body=_message(fix),
+ evidence=f"commit {fix.sha[:12]}, {on}, changed {files} together",
+ nodes=tuple(paths),
+ birth_commit=fix.sha,
+ # A commit's birth is a matter of record, not of when we first saw it.
+ birth_at=float(fix.ts),
+ )
+
+
+def _message(fix: Any) -> str:
+ """The commit's own words, subject first, kept whole under the walk's cap."""
+ subject = fix.subject.strip()
+ body = (fix.body or "").strip()
+ return f"{subject}\n\n{body}" if body else subject
diff --git a/packages/core/src/repowise/core/precedent/store.py b/packages/core/src/repowise/core/precedent/store.py
index 00382d6bf..daa48d8b7 100644
--- a/packages/core/src/repowise/core/precedent/store.py
+++ b/packages/core/src/repowise/core/precedent/store.py
@@ -80,6 +80,12 @@ class Episode:
identity, so re-deriving the same fact updates a row instead of adding
one. ``nodes`` is the repo-relative file set the claim is bound to — the
scope a later staleness query asks git about.
+
+ ``birth_at`` is normally left unset and stamped by the store at first
+ write, which is right for a fact derived from the checkout: it was first
+ observed when it was first derived. An episode whose birth is a matter of
+ record rather than of observation — a commit, which happened at a time the
+ walk can read — passes its own.
"""
tier: str
@@ -89,6 +95,7 @@ class Episode:
evidence: str
nodes: tuple[str, ...] = field(default_factory=tuple)
birth_commit: str | None = None
+ birth_at: float | None = None
@property
def id(self) -> str:
@@ -154,6 +161,76 @@ class EpisodeStore:
if not kinds:
return 0
stamp = time.time() if now is None else now
+ with self._conn: # one transaction: never half-replaced
+ self._upsert(episodes, stamp)
+ placeholders = ",".join("?" * len(kinds))
+ cur = self._conn.execute(
+ f"DELETE FROM episodes WHERE tier = ? AND kind IN ({placeholders}) "
+ "AND last_seen_at < ?",
+ (tier, *kinds, stamp),
+ )
+ retired = cur.rowcount or 0
+ self.prune(now=stamp)
+ return retired
+
+ def append_tier(
+ self,
+ *,
+ tier: str,
+ episodes: Iterable[Episode],
+ oldest_birth_at: float | None = None,
+ now: float | None = None,
+ ) -> int:
+ """Add to *tier* without replacing what is already in it.
+
+ The writer for a tier whose members accumulate. :meth:`replace_kinds`
+ makes a kind say exactly what a run derived, which is right for facts
+ re-derived whole every index; it is wrong here, because an incremental
+ run sees only the commits it has never seen before and its sweep would
+ delete every episode written by the runs before it.
+
+ Three things, one transaction:
+
+ * *episodes* are upserted, so a re-derived member keeps its birth;
+ * rows born before *oldest_birth_at* are dropped, which is how the
+ tier stays bounded by the window it is derived from rather than by
+ the TTL;
+ * and then, **only then**, every row in *tier* is marked re-observed,
+ because the pass that found these members looked at the whole window
+ and the TTL is over ``last_seen_at``. Without it a tier whose window
+ is wider than the TTL loses live episodes between full indexes.
+
+ *oldest_birth_at* being ``None`` says the caller cannot vouch for a
+ trailing edge, and it suppresses the touch as well as the drop. The two
+ belong together: a run that observed nothing must not claim to have
+ re-observed the tier, or the TTL is answered by a pass that looked at
+ no history and rows outlive every bound the store has.
+
+ Returns rows dropped for falling out of the window.
+ """
+ stamp = time.time() if now is None else now
+ with self._conn:
+ self._upsert(episodes, stamp)
+ dropped = 0
+ if oldest_birth_at is not None:
+ cur = self._conn.execute(
+ "DELETE FROM episodes WHERE tier = ? AND birth_at < ?",
+ (tier, oldest_birth_at),
+ )
+ dropped = cur.rowcount or 0
+ self._conn.execute(
+ "UPDATE episodes SET last_seen_at = ? WHERE tier = ?", (stamp, tier)
+ )
+ self.prune(now=stamp)
+ return dropped
+
+ def _upsert(self, episodes: Iterable[Episode], stamp: float) -> None:
+ """Insert or refresh *episodes*. Caller owns the transaction.
+
+ ``birth_at`` is deliberately absent from the conflict clause: a claim
+ that still holds keeps the birth it was first written with, which is
+ what separates an episode from a value recomputed every index.
+ """
rows = [
(
ep.id,
@@ -164,61 +241,84 @@ class EpisodeStore:
ep.evidence,
json.dumps(list(ep.nodes)),
ep.birth_commit,
- stamp,
+ stamp if ep.birth_at is None else ep.birth_at,
stamp,
)
for ep in episodes
]
- with self._conn: # one transaction: never half-replaced
- if rows:
- self._conn.executemany(
- """
- INSERT INTO episodes
- (id, tier, kind, subject, body, evidence, nodes,
- birth_commit, birth_at, last_seen_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(id) DO UPDATE SET
- body = excluded.body,
- evidence = excluded.evidence,
- nodes = excluded.nodes,
- birth_commit = excluded.birth_commit,
- last_seen_at = excluded.last_seen_at
- """,
- rows,
- )
- placeholders = ",".join("?" * len(kinds))
- cur = self._conn.execute(
- f"DELETE FROM episodes WHERE tier = ? AND kind IN ({placeholders}) "
- "AND last_seen_at < ?",
- (tier, *kinds, stamp),
- )
- retired = cur.rowcount or 0
- self.prune(now=stamp)
- return retired
+ if not rows:
+ return
+ self._conn.executemany(
+ """
+ INSERT INTO episodes
+ (id, tier, kind, subject, body, evidence, nodes,
+ birth_commit, birth_at, last_seen_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ body = excluded.body,
+ evidence = excluded.evidence,
+ nodes = excluded.nodes,
+ birth_commit = excluded.birth_commit,
+ last_seen_at = excluded.last_seen_at
+ """,
+ rows,
+ )
def prune(self, *, now: float | None = None) -> None:
- """Drop rows past TTL, then oldest-seen until under the row cap.
+ """Drop rows past TTL, then trim each tier to the row cap.
*now* is the write's own stamp when pruning follows a write: reading
the wall clock instead would make a row written microseconds earlier
older than the cutoff it is measured against.
+
+ **The cap is per tier, not per store.** One tier accumulates members
+ (a repository's history) while another holds a handful of facts
+ re-derived every index — and the structural handful is the only supply
+ a first-ever index of a history-less repository has. Under a shared cap
+ the accumulating tier evicts the cold-start one, and does so first:
+ structural facts are derived in the traverse phase, so a later
+ tier-wide write leaves them with the oldest ``last_seen_at`` in the
+ store and puts them at the front of the deletion queue.
"""
cutoff = (time.time() if now is None else now) - self.ttl_days * 86400
with self._conn:
self._conn.execute("DELETE FROM episodes WHERE last_seen_at < ?", (cutoff,))
- while True:
- (rows,) = self._conn.execute("SELECT COUNT(*) FROM episodes").fetchone()
- # Never evict the last row: it may be the one just written.
- if rows <= max(self.max_rows, 1) or rows <= 1:
- break
- self._conn.execute(
- """
- DELETE FROM episodes WHERE id IN (
- SELECT id FROM episodes ORDER BY last_seen_at ASC
- LIMIT MIN(64, (SELECT COUNT(*) - 1 FROM episodes))
- )
- """
+ tiers = [row[0] for row in self._conn.execute("SELECT DISTINCT tier FROM episodes")]
+ for tier in tiers:
+ self._trim_tier(tier)
+
+ def _trim_tier(self, tier: str) -> None:
+ """Evict *tier*'s least current rows until it is under the cap.
+
+ The ordering carries a tie-break for a reason: :meth:`append_tier`
+ stamps a whole tier with one ``last_seen_at``, so within it the primary
+ key is a total tie and SQLite would fall back to insertion order — the
+ walk's order, newest commit first. That evicts the most recent history
+ from a layer whose whole subject is recent history. ``birth_at``
+ settles it the right way round.
+ """
+ cap = max(self.max_rows, 1)
+ while True:
+ (rows,) = self._conn.execute(
+ "SELECT COUNT(*) FROM episodes WHERE tier = ?", (tier,)
+ ).fetchone()
+ # Never evict the last row: it may be the one just written.
+ if rows <= cap or rows <= 1:
+ return
+ # The excess, not the whole tier minus one: batching by the latter
+ # overshoots the cap by up to a batch on the way down, and empties
+ # the tier outright when the cap is small.
+ batch = min(64, rows - cap, rows - 1)
+ self._conn.execute(
+ """
+ DELETE FROM episodes WHERE id IN (
+ SELECT id FROM episodes WHERE tier = ?
+ ORDER BY last_seen_at ASC, birth_at ASC
+ LIMIT ?
)
+ """,
+ (tier, batch),
+ )
# -- reads -------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py b/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
index e2441dd2b..37f900f86 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
@@ -36,7 +36,7 @@ import time
from pathlib import Path
from repowise.core.precedent.currency import commits_since
-from repowise.core.precedent.store import EpisodeStore, default_store_path
+from repowise.core.precedent.store import TIER_STRUCTURAL, EpisodeStore, default_store_path
from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget
_log = logging.getLogger(__name__)
@@ -49,11 +49,19 @@ _MAX_EPISODES = 1
#: stays recoverable via ``repowise expand`` rather than vanishing.
_MAX_BODY_CHARS = 600
-#: How many scoped candidates are tested for staleness before giving up. Each
-#: test may cost one git query, so this is what keeps the sanctioned read-time
-#: exception bounded no matter how large the store grows.
+#: How many node-scoped candidates are tested for staleness before giving up.
+#: Each test may cost one git query, so this is what keeps the sanctioned
+#: read-time exception bounded no matter how large the store grows. One
+#: repo-wide candidate may follow them (see :func:`_candidate_window`), so the
+#: ceiling on git queries per call is this plus one.
_MAX_SCOPED_CANDIDATES = 4
+#: Tiers whose episodes are re-derived whole on every index, and for which a
+#: refreshed ``last_seen_at`` is therefore proof of currency. A tier that
+#: *accumulates* members has no such proof: re-observing that a commit happened
+#: says nothing about whether the files it changed have moved since.
+_RE_DERIVED_TIERS = frozenset({TIER_STRUCTURAL})
+
#: Room the block needs before it is worth attaching at all.
_BLOCK_OVERHEAD_CHARS = 400
@@ -165,7 +173,7 @@ def _attach(
# falls through to the next rather than silencing a still-true one below
# it, but only _MAX_EPISODES are ever emitted.
emitted = 0
- for row, matched in scoped[:_MAX_SCOPED_CANDIDATES]:
+ for row, matched in _candidate_window(scoped):
if emitted >= _MAX_EPISODES:
break
verdict = _still_true(row, root=root)
@@ -175,6 +183,38 @@ def _attach(
emitted += 1
+def _candidate_window(scoped: list[tuple[dict, list[str]]]) -> list[tuple[dict, list[str]]]:
+ """The candidates staleness is tested on: bounded, and never one-sided.
+
+ Ranking puts path matches above subject matches, which is right. But a
+ node-scoped episode is *suppressed outright* when anything has touched its
+ files since, while a repo-wide one is served with its age labelled. A store
+ holding hundreds of the former and a handful of the latter would therefore
+ fill the whole window with candidates that can only fall through, and the
+ surface would go silent on a repository that had more history rather than
+ less.
+
+ So the best repo-wide candidate is **appended** when the window would
+ otherwise hold none. Appended rather than substituted, and the difference
+ is the whole point: a repo-wide verdict never suppresses, so putting one
+ in the last slot would not fall back to it, it would pre-empt the
+ node-scoped candidate standing there — trading a git-verified "nothing in
+ its scope has changed" for an unchecked claim about the whole tree, which
+ is backwards on a surface whose bar is precision at the acting stage.
+
+ It costs one more possible git query in the worst case, and that is the
+ honest price of a fifth candidate rather than something to hide by
+ dropping the fourth.
+ """
+ window = scoped[:_MAX_SCOPED_CANDIDATES]
+ if any(not matched for _row, matched in window):
+ return window
+ repo_wide = next(((row, matched) for row, matched in scoped if not matched), None)
+ if repo_wide is None:
+ return window
+ return [*window, repo_wide]
+
+
# -- precondition 1: scope ---------------------------------------------------
@@ -254,9 +294,12 @@ def _still_true(row: dict, *, root: Path) -> str | None:
Three cases, and the third is the one worth reading.
- *Re-observed.* Every index refreshes ``last_seen_at`` for a fact that still
- holds, so a stamp later than ``birth_at`` is proof of currency that costs
- no git call at all.
+ *Re-observed.* Every index re-derives a structural fact that still holds,
+ so a stamp later than ``birth_at`` is proof of currency that costs no git
+ call at all. It proves nothing for a tier whose members accumulate: a git
+ episode is born at its commit and re-observed by every later index, so the
+ shortcut would fire always and the real question below would never be
+ asked. Hence :data:`_RE_DERIVED_TIERS`.
*Node-scoped.* ``git rev-list --count <birth>..HEAD -- <nodes>`` is the
real question, and zero is a real answer. Anything else — including a git
@@ -277,7 +320,7 @@ def _still_true(row: dict, *, root: Path) -> str | None:
birth_at = row.get("birth_at") or 0.0
last_seen = row.get("last_seen_at") or 0.0
recorded = _recorded_on(birth_at)
- if last_seen > birth_at:
+ if last_seen > birth_at and row.get("tier") in _RE_DERIVED_TIERS:
return f"re-observed by a later index (recorded {recorded})"
birth_commit = row.get("birth_commit")
diff --git a/tests/unit/ingestion/test_prior_defect_walk.py b/tests/unit/ingestion/test_prior_defect_walk.py
new file mode 100644
index 000000000..b4c9762c3
--- /dev/null
+++ b/tests/unit/ingestion/test_prior_defect_walk.py
@@ -0,0 +1,183 @@
+"""What the prior-defect walk carries, on real temporary repositories.
+
+The walk parses a ``git log --name-only`` whose format now ends with a
+multi-line commit body. A path line and a line of prose are indistinguishable
+by shape, so the boundary between them is a byte git will not emit inside a
+message — and getting that wrong would not raise, it would silently stop
+yielding paths and zero a shipped biomarker. That is what most of this file is
+about.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+
+from repowise.core.ingestion.git_indexer._constants import _MAX_COMMIT_BODY_BYTES
+from repowise.core.ingestion.git_indexer.fix_events import build_fix_events
+from repowise.core.ingestion.git_indexer.prior_defects import (
+ FixWalk,
+ collect_fix_commits,
+ compute_prior_defects,
+)
+
+
+def _repo(tmp_path):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ repo.config_writer().set_value("user", "email", "[email protected]").release()
+ repo.config_writer().set_value("user", "name", "T").release()
+ return repo
+
+
+def _write(repo, tmp_path, name, content, message):
+ (tmp_path / name).write_text(content, encoding="utf-8")
+ repo.index.add([name])
+ return repo.index.commit(message).hexsha
+
+
+def _walk(tmp_path, paths) -> FixWalk:
+ import git as gitpython
+
+ return collect_fix_commits(gitpython.Repo(tmp_path), set(paths), as_of_ts=None)
+
+
+_PROSE_BODY = """The rebuild refused whenever the index held more rows than
+wiki_pages could account for.
+
+- ensure_index prunes orphans on every open
+- doctor --repair steps over a failed schema upgrade
+
+Closes #1309
+"""
+
+
+class TestCommitProse:
+ def test_subject_and_body_ride_the_walk(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", f"fix: repair the index\n\n{_PROSE_BODY}")
+
+ (fix,) = _walk(tmp_path, ["a.py"]).fixes
+
+ assert fix.subject == "fix: repair the index"
+ assert "ensure_index prunes orphans" in fix.body
+ assert "Closes #1309" in fix.body
+
+ def test_a_body_that_looks_like_a_path_does_not_eat_the_path_block(self, tmp_path) -> None:
+ """The regression the terminator exists for.
+
+ A body line spelled like a repo-relative path is exactly what a squash
+ description contains, and the ``--name-only`` block that follows has no
+ shape of its own to be recognised by.
+ """
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(
+ repo,
+ tmp_path,
+ "a.py",
+ "x = 2\n",
+ "fix: repair the index\n\nTouched a.py and also b.py\n\nnot/a/real/path.py\n",
+ )
+
+ (fix,) = _walk(tmp_path, ["a.py"]).fixes
+
+ assert fix.paths == ["a.py"]
+ assert "not/a/real/path.py" in fix.body
+
+ def test_a_subject_only_commit_has_an_empty_body(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: terse")
+
+ (fix,) = _walk(tmp_path, ["a.py"]).fixes
+
+ assert fix.subject == "fix: terse"
+ assert fix.body == ""
+
+ def test_the_body_is_byte_capped(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ long_body = "why " * _MAX_COMMIT_BODY_BYTES
+ _write(repo, tmp_path, "a.py", "x = 2\n", f"fix: verbose\n\n{long_body}")
+
+ (fix,) = _walk(tmp_path, ["a.py"]).fixes
+
+ assert len(fix.body.encode("utf-8")) <= _MAX_COMMIT_BODY_BYTES
+
+ def test_the_subject_is_byte_capped_too(self, tmp_path) -> None:
+ """Git bounds a body by convention and a subject by nothing at all.
+
+ Both are persisted, so an unbounded one is the one that matters.
+ """
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: " + "S" * (_MAX_COMMIT_BODY_BYTES * 4))
+
+ (fix,) = _walk(tmp_path, ["a.py"]).fixes
+
+ assert len(fix.subject.encode("utf-8")) <= _MAX_COMMIT_BODY_BYTES
+
+ def test_a_separator_inside_a_subject_does_not_change_what_counts_as_a_fix(
+ self, tmp_path
+ ) -> None:
+ """The field separator is a byte, and a commit message may contain it.
+
+ Cutting the subject at the first one would drop the keyword that
+ classifies the commit, so the file would silently lose a defect count.
+ Both boundaries are therefore taken from the right.
+ """
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "cleanup\x1f resolve the crash\n\nbody")
+
+ walk = _walk(tmp_path, ["a.py"])
+
+ assert [f.paths for f in walk.fixes] == [["a.py"]]
+ assert walk.fixes[0].subject == "cleanup\x1f resolve the crash"
+ assert walk.fixes[0].body == "body"
+
+
+class TestExistingConsumersAreUnchanged:
+ """Both shipped consumers must produce the same output as before.
+
+ Asserted by construction rather than by eye: run each consumer over the
+ walk and over a copy with the new fields blanked, and require the results
+ to be equal. If either ever starts reading commit prose, this fails.
+ """
+
+ def _both(self, tmp_path, files):
+ import git as gitpython
+
+ walk = _walk(tmp_path, files)
+ blanked = FixWalk(
+ fixes=[replace(f, subject="", body="") for f in walk.fixes],
+ oldest_fix_ts=walk.oldest_fix_ts,
+ )
+ repo = gitpython.Repo(tmp_path)
+ return (
+ (build_fix_events(walk), build_fix_events(blanked)),
+ (
+ compute_prior_defects(repo, set(files), as_of_ts=None, walk=walk),
+ compute_prior_defects(repo, set(files), as_of_ts=None, walk=blanked),
+ ),
+ )
+
+ def test_fix_events_and_prior_defects_ignore_the_prose(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ (tmp_path / "b.py").write_text("y = 1\n", encoding="utf-8")
+ (tmp_path / "a.py").write_text("x = 2\n", encoding="utf-8")
+ repo.index.add(["a.py", "b.py"])
+ repo.index.commit(f"fix: correct both\n\n{_PROSE_BODY}")
+
+ (events, blanked_events), (counts, blanked_counts) = self._both(
+ tmp_path, ["a.py", "b.py"]
+ )
+
+ assert events == blanked_events
+ assert counts == blanked_counts
+ # And the pass still counts what it counted before the prose arrived.
+ assert counts.counts == {"a.py": 1, "b.py": 1}
+ assert [r["file_path"] for r in events] == ["a.py", "b.py"]
diff --git a/tests/unit/precedent/test_episode_store.py b/tests/unit/precedent/test_episode_store.py
index 695779d20..6f41f4c72 100644
--- a/tests/unit/precedent/test_episode_store.py
+++ b/tests/unit/precedent/test_episode_store.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import Path
from repowise.core.precedent.store import (
+ TIER_GIT,
TIER_STRUCTURAL,
Episode,
EpisodeStore,
@@ -114,6 +115,98 @@ class TestPrune:
)
assert store.count() == 1
+ def test_an_accumulating_tier_cannot_evict_the_cold_start_one(self, tmp_path: Path) -> None:
+ """The cap is per tier.
+
+ Structural facts are derived in the traverse phase, so a later
+ tier-wide write leaves them holding the oldest ``last_seen_at`` in the
+ store. Under a shared cap they would be first out of the door, and they
+ are the only supply a first-ever index of a history-less repository
+ has.
+ """
+ (tmp_path / ".repowise").mkdir()
+ with EpisodeStore(default_store_path(tmp_path), max_rows=3) as store:
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL, kinds=["nested_repos"], episodes=[_episode()], now=1000.0
+ )
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject=f"{i}",
+ body="b",
+ evidence="e",
+ nodes=("a.py",),
+ birth_at=float(i),
+ )
+ for i in range(10)
+ ],
+ oldest_birth_at=0.0,
+ now=2000.0,
+ )
+
+ assert len(store.list_episodes(tier=TIER_STRUCTURAL)) == 1
+ assert len(store.list_episodes(tier=TIER_GIT)) == 3
+
+ def test_the_cap_evicts_the_oldest_claims_not_the_newest(self, tmp_path: Path) -> None:
+ """One ``last_seen_at`` across a tier is a total tie.
+
+ SQLite would fall back to insertion order, which is the walk's order,
+ newest commit first. That would evict the most recent history from a
+ layer whose subject is recent history.
+ """
+ (tmp_path / ".repowise").mkdir()
+ with EpisodeStore(default_store_path(tmp_path), max_rows=2) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject=f"{i}",
+ body="b",
+ evidence="e",
+ nodes=("a.py",),
+ birth_at=float(i),
+ )
+ # Newest first, as the walk yields them.
+ for i in (5, 4, 3, 2, 1)
+ ],
+ oldest_birth_at=0.0,
+ )
+
+ kept = {row["birth_at"] for row in store.list_episodes(tier=TIER_GIT)}
+ assert kept == {5.0, 4.0}
+
+ def test_a_run_that_observed_nothing_does_not_refresh_the_tier(self, tmp_path: Path) -> None:
+ """Without a trailing edge to vouch for, the touch is a false claim.
+
+ A repository whose authors stop writing fix-shaped subjects yields no
+ fixes on every later run. If those runs still marked the tier
+ re-observed, the TTL would be answered by a pass that looked at no
+ history and the rows would outlive every bound the store has.
+ """
+ (tmp_path / ".repowise").mkdir()
+ episode = Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject="sha",
+ body="b",
+ evidence="e",
+ nodes=("a.py",),
+ birth_at=10.0,
+ )
+ with EpisodeStore(default_store_path(tmp_path), ttl_days=1.0) as store:
+ store.append_tier(tier=TIER_GIT, episodes=[episode], oldest_birth_at=0.0, now=1000.0)
+
+ store.append_tier(tier=TIER_GIT, episodes=[], oldest_birth_at=None, now=1060.0)
+ assert [row["last_seen_at"] for row in store.list_episodes()] == [1000.0]
+
+ store.prune(now=1000.0 + 2 * 86400)
+ assert store.count() == 0
+
class TestPaths:
def test_store_path_is_a_sidecar(self, tmp_path: Path) -> None:
diff --git a/tests/unit/precedent/test_git_episodes.py b/tests/unit/precedent/test_git_episodes.py
new file mode 100644
index 000000000..09727a10e
--- /dev/null
+++ b/tests/unit/precedent/test_git_episodes.py
@@ -0,0 +1,347 @@
+"""Git-tier episodes: one dated change, bound to the files it touched.
+
+Built on real temporary repositories, like the walk they consume: the things
+worth asserting here (which commits qualify, what a node set answers when git
+is asked about it, what an incremental run must not delete) are git behaviours
+with no useful mock.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+from repowise.core.ingestion.git_indexer.prior_defects import FixWalk, collect_fix_commits
+from repowise.core.precedent.currency import commits_since
+from repowise.core.precedent.git_episodes import (
+ KIND_CODE_FIX,
+ MAX_EPISODE_NODES,
+ derive_git_episodes,
+ record_git_episodes,
+)
+from repowise.core.precedent.store import (
+ TIER_GIT,
+ TIER_STRUCTURAL,
+ Episode,
+ EpisodeStore,
+ default_store_path,
+)
+
+
+def _repo(tmp_path, *, opted_in: bool = True):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ repo.config_writer().set_value("user", "email", "[email protected]").release()
+ repo.config_writer().set_value("user", "name", "T").release()
+ if opted_in:
+ (tmp_path / ".repowise").mkdir()
+ return repo
+
+
+def _write(repo, tmp_path, name, content, message):
+ (tmp_path / name).write_text(content, encoding="utf-8")
+ repo.index.add([name])
+ return repo.index.commit(message).hexsha
+
+
+def _walk(tmp_path, paths, *, skip_shas=None) -> FixWalk:
+ import git as gitpython
+
+ return collect_fix_commits(
+ gitpython.Repo(tmp_path), set(paths), as_of_ts=None, skip_shas=skip_shas
+ )
+
+
+def _rows(tmp_path, **kw) -> list[dict]:
+ with EpisodeStore(default_store_path(tmp_path)) as store:
+ return store.list_episodes(**kw)
+
+
+# ---------------------------------------------------------------------------
+# Derivation
+# ---------------------------------------------------------------------------
+
+
+class TestSelection:
+ def test_a_code_fix_becomes_an_episode(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "def f():\n return None\n", "feat: add f")
+ sha = _write(
+ repo,
+ tmp_path,
+ "a.py",
+ "def f():\n return 0\n",
+ "fix: f returned None\n\nCallers were unwrapping it.",
+ )
+
+ (episode,) = derive_git_episodes(_walk(tmp_path, ["a.py"]))
+
+ assert episode.tier == TIER_GIT
+ assert episode.kind == KIND_CODE_FIX
+ assert episode.subject == sha
+ assert episode.birth_commit == sha
+ assert episode.body.startswith("fix: f returned None")
+ assert "Callers were unwrapping it." in episode.body
+ assert "changed 1 file together" in episode.evidence
+
+ def test_a_doc_only_fix_produces_nothing(self, tmp_path) -> None:
+ """The 53.5% finding, asserted rather than commented.
+
+ The subject rule counts this as a fix. Its diff changes no production
+ code, so it is not an episode.
+ """
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "README.md", "hello\n", "docs: add readme")
+ _write(repo, tmp_path, "README.md", "hello there\n", "fix: wrong wording")
+
+ assert derive_git_episodes(_walk(tmp_path, ["README.md"])) == []
+
+ def test_a_non_fix_commit_is_never_reached(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "feat: change a")
+
+ assert derive_git_episodes(_walk(tmp_path, ["a.py"])) == []
+
+ def test_a_sweep_is_skipped_rather_than_truncated(self, tmp_path) -> None:
+ """Above the node ceiling nothing is emitted.
+
+ Truncating instead would leave an episode whose staleness question is
+ narrower than the change its body describes.
+ """
+ repo = _repo(tmp_path)
+ names = [f"m{i}.py" for i in range(MAX_EPISODE_NODES + 1)]
+ for name in names:
+ (tmp_path / name).write_text("x = 1\n", encoding="utf-8")
+ repo.index.add(names)
+ repo.index.commit("feat: add them")
+ for name in names:
+ (tmp_path / name).write_text("x = 2\n", encoding="utf-8")
+ repo.index.add(names)
+ repo.index.commit("fix: bump them all")
+
+ assert derive_git_episodes(_walk(tmp_path, names)) == []
+
+
+class TestBinding:
+ def test_nodes_are_the_commit_s_own_paths_and_nothing_else(self, tmp_path) -> None:
+ """No directory expansion, unlike a decision record's module scope.
+
+ The reader's scope test is a path prefix match, so adding the parent
+ directory would make one fix match every file beneath it.
+ """
+ repo = _repo(tmp_path)
+ (tmp_path / "pkg").mkdir()
+ _write(repo, tmp_path, "pkg/a.py", "x = 1\n", "feat: add a")
+ (tmp_path / "pkg/b.py").write_text("y = 1\n", encoding="utf-8")
+ (tmp_path / "pkg/a.py").write_text("x = 2\n", encoding="utf-8")
+ repo.index.add(["pkg/a.py", "pkg/b.py"])
+ repo.index.commit("fix: correct both")
+
+ (episode,) = derive_git_episodes(_walk(tmp_path, ["pkg/a.py", "pkg/b.py"]))
+
+ assert episode.nodes == ("pkg/a.py", "pkg/b.py")
+ assert "pkg" not in episode.nodes
+
+ def test_the_episode_is_born_at_the_commit_not_at_index_time(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+ walk = _walk(tmp_path, ["a.py"])
+
+ (episode,) = derive_git_episodes(walk)
+
+ assert episode.birth_at == float(walk.fixes[0].ts)
+
+ def test_its_staleness_question_is_answerable_against_its_birth_sha(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "b.py", "y = 1\n", "feat: add b")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+
+ (episode,) = derive_git_episodes(_walk(tmp_path, ["a.py", "b.py"]))
+ scope = list(episode.nodes)
+
+ assert commits_since(tmp_path, since_commit=episode.birth_commit, nodes=scope) == 0
+ # A commit elsewhere leaves it standing; one in its scope does not.
+ _write(repo, tmp_path, "b.py", "y = 2\n", "feat: change b")
+ assert commits_since(tmp_path, since_commit=episode.birth_commit, nodes=scope) == 0
+ _write(repo, tmp_path, "a.py", "x = 3\n", "feat: change a")
+ assert commits_since(tmp_path, since_commit=episode.birth_commit, nodes=scope) == 1
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+class TestPersistence:
+ def test_a_repo_that_never_opted_in_grows_no_store(self, tmp_path) -> None:
+ repo = _repo(tmp_path, opted_in=False)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+
+ assert record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"])) == 0
+ assert not default_store_path(tmp_path).exists()
+
+ def test_an_incremental_run_appends_without_deleting_what_came_before(self, tmp_path) -> None:
+ """The hazard a kind-scoped sweep would walk straight into.
+
+ An update sees only the commits it has never seen, so a writer that
+ made the kind say exactly what this run derived would delete every
+ episode the runs before it wrote.
+ """
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ first = _write(repo, tmp_path, "a.py", "x = 2\n", "fix: first")
+ record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"]))
+
+ second = _write(repo, tmp_path, "a.py", "x = 3\n", "fix: second")
+ written = record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"], skip_shas={first}))
+
+ assert written == 1
+ assert {row["subject"] for row in _rows(tmp_path, tier=TIER_GIT)} == {first, second}
+
+ def test_an_update_with_no_new_fixes_derives_none_and_deletes_none(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ sha = _write(repo, tmp_path, "a.py", "x = 2\n", "fix: only one")
+ record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"]))
+ before = _rows(tmp_path, tier=TIER_GIT)
+
+ assert record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"], skip_shas={sha})) == 0
+ after = _rows(tmp_path, tier=TIER_GIT)
+
+ assert [row["id"] for row in after] == [row["id"] for row in before]
+ assert [row["birth_at"] for row in after] == [row["birth_at"] for row in before]
+
+ def test_episodes_that_fall_out_of_the_window_are_dropped(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: aged out")
+ walk = _walk(tmp_path, ["a.py"])
+ record_git_episodes(tmp_path, walk)
+ assert len(_rows(tmp_path, tier=TIER_GIT)) == 1
+
+ # A later walk whose trailing edge has moved past that commit.
+ moved = FixWalk(fixes=[], oldest_fix_ts=walk.fixes[0].ts + 1)
+ record_git_episodes(tmp_path, moved)
+
+ assert _rows(tmp_path, tier=TIER_GIT) == []
+
+ def test_appending_to_the_git_tier_leaves_the_structural_one_alone(self, tmp_path) -> None:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+ with EpisodeStore(default_store_path(tmp_path)) as store:
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL,
+ kinds=["formatter_drift"],
+ episodes=[
+ Episode(
+ tier=TIER_STRUCTURAL,
+ kind="formatter_drift",
+ subject="ruff format",
+ body="This tree is not formatter-clean.",
+ evidence="ruff format --check .",
+ )
+ ],
+ )
+
+ record_git_episodes(tmp_path, _walk(tmp_path, ["a.py"]))
+
+ assert len(_rows(tmp_path, tier=TIER_STRUCTURAL)) == 1
+ assert len(_rows(tmp_path, tier=TIER_GIT)) == 1
+
+
+# ---------------------------------------------------------------------------
+# The indexer wiring
+# ---------------------------------------------------------------------------
+
+
+async def test_a_full_index_records_the_window(tmp_path) -> None:
+ from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "def f():\n return None\n", "feat: add f")
+ _write(repo, tmp_path, "a.py", "def f():\n return 0\n", "fix: bad return")
+
+ await GitIndexer(tmp_path, tier=GitIndexTier.FULL, record_episodes=True).index_repo("repo1")
+
+ rows = _rows(tmp_path, tier=TIER_GIT)
+ assert len(rows) == 1
+ assert rows[0]["kind"] == KIND_CODE_FIX
+ assert rows[0]["nodes"] == ["a.py"]
+
+
+def test_the_update_path_records_only_what_it_has_not_seen(tmp_path) -> None:
+ from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ first = _write(repo, tmp_path, "a.py", "x = 2\n", "fix: first")
+ second = _write(repo, tmp_path, "a.py", "x = 3\n", "fix: second")
+
+ indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL, record_episodes=True)
+ indexer.capture_new_fix_events(known_shas={first})
+
+ assert {row["subject"] for row in _rows(tmp_path, tier=TIER_GIT)} == {second}
+
+
+def test_a_read_only_command_s_indexer_writes_nothing(tmp_path) -> None:
+ """`health` and `dead-code` build their own indexer to read metadata.
+
+ They do not pass the repo's exclude patterns, so episodes written there
+ would name files the repo excludes and would outlive every prune.
+ """
+ from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+
+ GitIndexer(tmp_path, tier=GitIndexTier.FULL).capture_new_fix_events()
+
+ assert not default_store_path(tmp_path).exists()
+
+
+def test_only_the_indexing_paths_opt_in() -> None:
+ """The gate is a parameter, not a call site, and the opt-in set is pinned.
+
+ Same shape as the environment-fact gate, and for the same reason: a third
+ caller flipping this on is a decision to take deliberately.
+ """
+ import inspect
+ from pathlib import Path as _Path
+
+ from repowise.core.ingestion.git_indexer import GitIndexer
+
+ assert inspect.signature(GitIndexer.__init__).parameters["record_episodes"].default is False
+
+ roots = [_Path(__file__).resolve().parents[3] / "packages" / p for p in ("cli", "core", "server")]
+ found = {
+ path.as_posix().split("/src/")[-1]
+ for root in roots
+ for path in root.rglob("*.py")
+ if "record_episodes=True" in path.read_text(encoding="utf-8", errors="ignore")
+ }
+ assert found == {
+ "repowise/core/pipeline/phases/git.py",
+ "repowise/core/pipeline/incremental.py",
+ }
+
+
+def test_git_is_never_asked_a_second_time(tmp_path, monkeypatch) -> None:
+ """Derivation is a consumer of the walk, so it spawns nothing of its own."""
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: correct a")
+ walk = _walk(tmp_path, ["a.py"])
+
+ def _explode(*args, **kwargs):
+ raise AssertionError("git episodes must not spawn a subprocess")
+
+ monkeypatch.setattr(subprocess, "run", _explode)
+ monkeypatch.setattr(subprocess, "Popen", _explode)
+
+ assert record_git_episodes(tmp_path, walk) == 1
diff --git a/tests/unit/server/mcp/test_answer_episodes.py b/tests/unit/server/mcp/test_answer_episodes.py
index 43010bc1c..452be96a2 100644
--- a/tests/unit/server/mcp/test_answer_episodes.py
+++ b/tests/unit/server/mcp/test_answer_episodes.py
@@ -20,12 +20,16 @@ import time
import pytest
from repowise.core.precedent.store import (
+ TIER_GIT,
TIER_STRUCTURAL,
Episode,
EpisodeStore,
default_store_path,
)
-from repowise.server.mcp_server.tool_answer.episodes import attach_episode_sync
+from repowise.server.mcp_server.tool_answer.episodes import (
+ _MAX_SCOPED_CANDIDATES,
+ attach_episode_sync,
+)
FORMATTER_ANSWER = (
"**Yes — run `ruff format` before committing.** This repo defines a "
@@ -232,8 +236,12 @@ def test_a_node_scoped_episode_is_suppressed_once_its_scope_changes(repo):
assert run(copy.deepcopy(asked), repo, question="where are routers registered") == asked
-def test_a_re_observed_episode_needs_no_git_query(repo):
- """``last_seen_at > birth_at`` is proof of currency that costs nothing."""
+def test_a_re_observed_episode_needs_no_git_query(repo, git_calls):
+ """``last_seen_at > birth_at`` is proof of currency that costs nothing.
+
+ Only for a tier re-derived whole on every index, which is what makes the
+ stamp mean anything; the git tier has its own case below.
+ """
now = time.time()
_write(repo, formatter_episode(_head(repo)), born=now, seen=now + 60)
@@ -242,6 +250,7 @@ def test_a_re_observed_episode_needs_no_git_query(repo):
assert got["episodes"][0]["still_true"] == (
f"re-observed by a later index (recorded {time.strftime('%Y-%m-%d', time.gmtime(now))})"
)
+ assert git_calls == []
def test_without_git_a_repo_wide_fact_is_served_and_a_scoped_one_is_not(tmp_path):
@@ -343,6 +352,168 @@ def test_a_subject_matches_as_a_phrase_not_a_substring(repo):
assert got == before
+# -- more than one tier ------------------------------------------------------
+
+
+def _git_episode(subject: str, *, birth_commit: str, nodes: tuple[str, ...]) -> Episode:
+ return Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject=subject,
+ body=f"fix: something in {nodes[0]}",
+ evidence=f"commit {subject[:12]}, changed 1 file together",
+ nodes=nodes,
+ birth_commit=birth_commit,
+ )
+
+
+def test_a_git_episode_does_not_take_the_re_observed_shortcut(repo):
+ """Re-observing that a commit happened proves nothing about the code since.
+
+ A structural fact is re-derived whole on every index, so a refreshed stamp
+ means it still holds. A git episode is born at its commit and re-observed
+ by every later index, so the same stamp is guaranteed and would silently
+ replace the only question worth asking.
+ """
+ born_at = _head(repo)
+ now = time.time()
+ _write(repo, _git_episode(born_at, birth_commit=born_at, nodes=("app.py",)), born=now, seen=now + 60)
+ (repo / "app.py").write_text("x = 1\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "touch app")
+
+ before = payload(answer="It is handled in app.py.", citations=["app.py"])
+
+ assert run(copy.deepcopy(before), repo, question="where is it handled") == before
+
+
+def test_a_git_episode_whose_scope_has_not_moved_is_served(repo):
+ (repo / "app.py").write_text("x = 1\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "add app")
+ born_at = _head(repo)
+ _write(repo, _git_episode(born_at, birth_commit=born_at, nodes=("app.py",)), born=time.time())
+
+ got = run(
+ payload(answer="It is handled in app.py.", citations=["app.py"]),
+ repo,
+ question="where is it handled",
+ )
+
+ assert got["episodes"][0]["tier"] == TIER_GIT
+ assert got["episodes"][0]["scope"] == ["app.py"]
+ assert "nothing in its scope has changed" in got["episodes"][0]["still_true"]
+
+
+def git_calls(monkeypatch):
+ """Count the sanctioned read-time git queries one attach makes."""
+ from repowise.server.mcp_server.tool_answer import episodes as mod
+
+ calls: list[tuple] = []
+ real = mod.commits_since
+
+ def counted(*args, **kwargs):
+ calls.append((args, kwargs))
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(mod, "commits_since", counted)
+ return calls
+
+
+def test_a_still_true_scoped_episode_outranks_the_repo_wide_fallback(repo, git_calls):
+ """The reserved slot follows the scoped candidates; it does not replace one.
+
+ A repo-wide verdict never suppresses, so putting one *in* the last slot
+ would pre-empt whatever stood there rather than fall back to it — trading
+ a git-verified "nothing in its scope has changed" for an unchecked claim
+ about the whole tree.
+ """
+ (repo / "stable.py").write_text("x = 1\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "add stable")
+ born_at = _head(repo)
+
+ _write(repo, formatter_episode(born_at), born=time.time())
+ with EpisodeStore(default_store_path(repo)) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ # Longer subjects rank above the short one, so the still-true
+ # episode sits in the last scoped slot.
+ *(
+ _git_episode(f"{i}" * 40, birth_commit=born_at, nodes=("Makefile",))
+ for i in range(3)
+ ),
+ _git_episode("aa", birth_commit=born_at, nodes=("stable.py",)),
+ ],
+ )
+ (repo / "Makefile").write_text("format:\n\truff format .\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "add makefile")
+
+ got = run(
+ payload(citations=["Makefile", "stable.py"], fallback_targets=[]),
+ repo,
+ question="should I run ruff format before committing",
+ )
+
+ assert got["episodes"][0]["kind"] == "code_fix"
+ assert got["episodes"][0]["scope"] == ["stable.py"]
+ assert "nothing in its scope has changed" in got["episodes"][0]["still_true"]
+
+
+def test_the_git_query_stays_bounded_however_large_the_store_gets(repo, git_calls):
+ """The ceiling is the scoped window plus the one repo-wide fallback."""
+ born_at = _head(repo)
+ _write(repo, formatter_episode(born_at), born=time.time())
+ with EpisodeStore(default_store_path(repo)) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _git_episode(f"{i}" * 40, birth_commit=born_at, nodes=("Makefile",))
+ for i in range(20)
+ ],
+ )
+ (repo / "Makefile").write_text("format:\n\truff format .\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "add makefile")
+
+ run(payload(), repo)
+
+ assert len(git_calls) == _MAX_SCOPED_CANDIDATES + 1
+
+
+def test_a_crowd_of_stale_git_episodes_does_not_starve_the_repo_wide_one(repo):
+ """Ranking must not become one-sided as a store accumulates history.
+
+ Path matches outrank subject matches, which is right, but a node-scoped
+ episode is suppressed outright once its files move while a repo-wide one is
+ served with its age labelled. Without a reserved slot, a repository with
+ more history would go silent where one with less does not.
+ """
+ born_at = _head(repo)
+ _write(repo, formatter_episode(born_at), born=time.time())
+ # Through the real writer: they share one kind, so a kind-scoped replace
+ # would leave only the last of them and the crowd would never form.
+ with EpisodeStore(default_store_path(repo)) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _git_episode(f"{i}" * 40, birth_commit=born_at, nodes=("Makefile",))
+ for i in range(6)
+ ],
+ )
+ # Every git episode's scope has moved, so none of them can be vouched for.
+ (repo / "Makefile").write_text("format:\n\truff format .\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "add makefile")
+
+ got = run(payload(), repo)
+
+ assert got["episodes"][0]["kind"] == "formatter_drift"
+
+
# -- budget ------------------------------------------------------------------
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index 8a7c92ccd..3a16a816c 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -536,6 +536,12 @@ class TestPriorDefectCount:
batched ``--no-walk --patch`` shape pass. *diffs* overrides the patch for
a record by index; the default is a plain code change, so a commit that
the subject rule matches also classifies as ``code_fix``.
+
+ The record shape mirrors the real format exactly, terminator included:
+ this fixture stands in for git, so a format it does not emit is a test
+ that passes on output git would never produce. Each record carries a
+ one-line commit body, because a body is the field the terminator exists
+ to separate from the path block.
"""
mock_repo = MagicMock()
mock_repo.head.commit.hexsha = "HEADSHA"
@@ -543,8 +549,11 @@ class TestPriorDefectCount:
patches = {}
for i, (subject, paths) in enumerate(records):
sha = f"{i:040d}"
- body = "\n".join(paths)
- chunks.append(f"\x00{sha}\x1f{1_700_000_000 - i}\x1f{subject}\n{body}")
+ path_block = "\n".join(paths)
+ chunks.append(
+ f"\x00{sha}\x1f{1_700_000_000 - i}\x1f{subject}"
+ f"\x1fwhy commit {i} happened\x02\n{path_block}"
+ )
patches[sha] = (diffs or {}).get(i, self._code_diff(paths))
log_out = "\n".join(chunks)
@@ -650,7 +659,7 @@ class TestPriorDefectCount:
return "PRIORSHA"
if "--no-walk" in args:
raise RuntimeError("git exploded")
- return "\x00" + "0" * 40 + "\x1f1700000000\x1ffix: crash\nsrc/app.py"
+ return "\x00" + "0" * 40 + "\x1f1700000000\x1ffix: crash\x1fwhy\x02\nsrc/app.py"
repo.git.log.side_effect = _log
result = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)