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): answer "what happened here" from get_why, and count it on the risk and context cards (#1333)

Raghav Chamadiya8b407c178d82
diff --git a/packages/core/src/repowise/core/precedent/store.py b/packages/core/src/repowise/core/precedent/store.py
index 6328a5c7a..538cd7ae1 100644
--- a/packages/core/src/repowise/core/precedent/store.py
+++ b/packages/core/src/repowise/core/precedent/store.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import hashlib
import json
import logging
+import posixpath
import sqlite3
import time
from collections.abc import Iterable, Sequence
@@ -86,6 +87,53 @@ CREATE INDEX IF NOT EXISTS idx_episodes_tier_kind ON episodes(tier, kind);
CREATE INDEX IF NOT EXISTS idx_episodes_last_seen ON episodes(last_seen_at);
"""
+#: ``nodes`` normalised one row per path, so "which episodes are bound here"
+#: is an index seek instead of a scan that JSON-decodes every row in the store.
+#:
+#: Measured on this repository before it existed: scanning ``nodes`` for one
+#: path costs 1.3 ms across the 284 shareable rows here, but 22.6 ms at the
+#: store's own 5,000-row cap, against 0.2 ms through this index. Three readers
+#: made that worth normalising rather than two — ``get_why``, the counts on
+#: ``get_risk``/``get_context``, and a hook, where the plan's constraint is not
+#: a preference: hook delivery is one indexed lookup, because the budget is
+#: 155 ms and was fought down from 965 ms.
+#:
+#: Deletes are a trigger and writes are not, which is the split the data
+#: forces rather than a style choice: the store has five delete paths (a kind
+#: sweep, a window drop, the TTL, the cap trim, and a re-derivation replacing a
+#: row) and a trigger catches all of them without needing to parse JSON, while
+#: an insert has the node list already in hand in Python and would otherwise
+#: need ``json_each`` — a build-dependent extension this store's stdlib-only
+#: rule cannot assume.
+_NODES_SCHEMA = """
+CREATE TABLE IF NOT EXISTS episode_nodes (
+ episode_id TEXT NOT NULL,
+ path TEXT NOT NULL,
+ PRIMARY KEY (episode_id, path)
+) WITHOUT ROWID;
+CREATE INDEX IF NOT EXISTS idx_episode_nodes_path ON episode_nodes(path);
+"""
+
+#: Created **last**, after the backfill has succeeded, which is what makes its
+#: presence mean "this index is complete" rather than "somebody started
+#: building one". DDL runs in autocommit, so the table is durable the moment it
+#: is created and a backfill that then fails — a disk error, or ``SQLITE_BUSY``
+#: from another process past the 5 s timeout — would otherwise leave a table
+#: that is present, empty, and never rebuilt, because presence was the only
+#: signal. That is a store answering "no episodes are bound here" in exactly
+#: the shape of the truth. The search index gets away with a presence check
+#: because its triggers cover insert, update *and* delete, so its objects
+#: cannot exist while its contents are wrong; this one can, so it needs a
+#: signal that means the contents are right.
+_NODES_TRIGGER = """
+CREATE TRIGGER IF NOT EXISTS episodes_nodes_ad AFTER DELETE ON episodes BEGIN
+ DELETE FROM episode_nodes WHERE episode_id = old.id;
+END;
+"""
+
+#: The one object whose presence vouches for the whole index. See above.
+_NODES_COMPLETE_MARKER = "episodes_nodes_ad"
+
#: The searchable projection of an episode. External-content rather than a
#: table of its own: ``body`` is already a column and this corpus is 11 MB on
#: a real machine, so a standalone index would keep a second copy of all of it
@@ -179,6 +227,7 @@ class EpisodeStore:
self._conn.executescript(_SCHEMA)
self._conn.commit()
self.fts_enabled = self._ensure_fts()
+ self.node_index_enabled = self._ensure_node_index()
def _ensure_fts(self) -> bool:
"""Create the search index and refill it if it is behind. Never raises.
@@ -220,6 +269,53 @@ class EpisodeStore:
_log.debug("episode search index unavailable", exc_info=True)
return False
+ def _ensure_node_index(self) -> bool:
+ """Create the node index and refill it if it is behind. Never raises.
+
+ Same contract as :meth:`_ensure_fts` and for the same reason: every
+ caller opens the store through here, so an exception over an index
+ would take down a feature that reads perfectly well without one. A
+ store where this returns ``False`` still answers every node query —
+ :meth:`_scan_by_node` is the fallback, and it is the implementation
+ this index replaced.
+
+ Completion, not presence, is the signal — see :data:`_NODES_TRIGGER`.
+ The refill reads ``episodes.nodes``, which stays the system of record,
+ so this table is derived data that can be dropped at any time and
+ rebuilt on next open. That is what makes the migration for existing
+ stores "none needed": a user who never re-indexes gets the index built
+ the first time anything opens their store.
+ """
+ try:
+ complete = self._conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE name = ?", (_NODES_COMPLETE_MARKER,)
+ ).fetchone()
+ self._conn.executescript(_NODES_SCHEMA)
+ if not complete:
+ self._backfill_node_index()
+ self._conn.commit()
+ # Only now, with the contents known good, is the index vouched
+ # for. A failure above leaves no marker and the next open
+ # rebuilds from scratch.
+ self._conn.executescript(_NODES_TRIGGER)
+ self._conn.commit()
+ return True
+ except sqlite3.Error:
+ self._conn.rollback()
+ _log.debug("episode node index unavailable", exc_info=True)
+ return False
+
+ def _backfill_node_index(self) -> None:
+ """Rebuild every node row from ``episodes.nodes``. Caller owns the commit."""
+ self._conn.execute("DELETE FROM episode_nodes")
+ pairs: list[tuple[str, str]] = []
+ for episode_id_, raw in self._conn.execute("SELECT id, nodes FROM episodes"):
+ pairs.extend((episode_id_, path) for path in _decode_nodes(raw))
+ if pairs:
+ self._conn.executemany(
+ "INSERT OR IGNORE INTO episode_nodes (episode_id, path) VALUES (?, ?)", pairs
+ )
+
@classmethod
def open_for_repo(cls, repo_path: Path | str) -> EpisodeStore:
"""Open the store for *repo_path*.
@@ -420,7 +516,13 @@ class EpisodeStore:
``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.
+
+ *episodes* is materialised before use because it is typed as an
+ iterable and two passes are made over it — the rows and then the node
+ index. Every caller today passes a list, so this is cheap insurance
+ against a generator silently writing episodes with no scope.
"""
+ episodes = list(episodes)
rows = [
(
ep.id,
@@ -453,6 +555,36 @@ class EpisodeStore:
""",
rows,
)
+ self._sync_nodes(episodes)
+
+ def _sync_nodes(self, episodes: Iterable[Episode], /) -> None:
+ """Make the node index agree with what :meth:`_upsert` just wrote.
+
+ Delete-then-insert per episode rather than an upsert, because a
+ re-derived claim may name **fewer** nodes than it did last time and an
+ insert-only sync would leave the dropped ones bound forever — a scope
+ that can only grow is how a record ends up matching a file it stopped
+ being about. Scoped to the ids in hand, so this costs the run's own
+ episodes and not the store.
+
+ The insert side lives here and the delete side is a trigger; see
+ :data:`_NODES_SCHEMA` for why they are split.
+
+ Node filtering goes through the same decoder a rebuild uses, so the
+ index is a pure function of ``episodes.nodes``. Filtering on truthiness
+ here while :func:`_decode_nodes` also requires ``str`` let a
+ non-string node into the index on the live path and out of it on a
+ rebuild — the two answers differing is worse than either.
+ """
+ ids = [(ep.id,) for ep in episodes]
+ if not ids:
+ return
+ self._conn.executemany("DELETE FROM episode_nodes WHERE episode_id = ?", ids)
+ pairs = [(ep.id, path) for ep in episodes for path in _valid_nodes(ep.nodes)]
+ if pairs:
+ self._conn.executemany(
+ "INSERT OR IGNORE INTO episode_nodes (episode_id, path) VALUES (?, ?)", pairs
+ )
def prune(self, *, now: float | None = None) -> None:
"""Drop rows past TTL, then trim each tier to the row cap.
@@ -654,6 +786,174 @@ class EpisodeStore:
)
return hits[: max(1, limit)]
+ def count_by_node(
+ self,
+ paths: Sequence[str],
+ *,
+ tiers: Sequence[str] | None = None,
+ ) -> dict[str, int]:
+ """How many episodes each of *paths* is bound to. Never raises.
+
+ A count and nothing else, which is the whole point of the surfaces that
+ call it: an integer invites a follow-up call, while a paragraph spends
+ every caller's budget whether they wanted it or not.
+
+ One indexed query per path rather than one for all of them: the callers
+ ask about a handful of targets and want the answer *per* target, so a
+ single grouped query would have to be un-grouped again on the way out.
+
+ Returns only the paths with at least one episode, so a caller can omit
+ the field rather than serve a zero.
+ """
+ if not paths:
+ return {}
+ if tiers is not None and not tiers:
+ return {}
+ if not self.node_index_enabled:
+ return {p: len(rows) for p, rows in self._scan_by_node(paths, tiers).items()}
+ counts: dict[str, int] = {}
+ for path in paths:
+ sub, params = self._node_subquery(path)
+ if sub is None:
+ continue
+ sql = f"SELECT COUNT(*) FROM episodes e WHERE e.id IN ({sub})"
+ if tiers is not None:
+ sql += f" AND e.tier IN ({','.join('?' * len(tiers))})"
+ params = [*params, *tiers]
+ try:
+ (n,) = self._conn.execute(sql, params).fetchone()
+ except sqlite3.Error:
+ _log.debug("episode node count failed for %r", path, exc_info=True)
+ continue
+ if n:
+ counts[path] = int(n)
+ return counts
+
+ def list_by_node(
+ self,
+ paths: Sequence[str],
+ *,
+ tiers: Sequence[str] | None = None,
+ limit: int = 10,
+ ) -> list[dict]:
+ """Episodes bound to any of *paths*, newest birth first. Never raises.
+
+ The bodied form of :meth:`count_by_node`, for a reader that asked a
+ question rather than one that is annotating a card. Ordered by birth so
+ a caller taking the first *limit* takes the most recent claims, which is
+ the ordering a reader of "what happened here" expects.
+ """
+ if not paths:
+ return []
+ if tiers is not None and not tiers:
+ return []
+ if not self.node_index_enabled:
+ seen: dict[str, dict] = {}
+ for rows in self._scan_by_node(paths, tiers).values():
+ for row in rows:
+ seen[row["id"]] = row
+ ordered = sorted(
+ seen.values(), key=lambda r: (-(r.get("birth_at") or 0.0), r["id"])
+ )
+ return ordered[: max(1, limit)]
+ subs: list[str] = []
+ params: list[object] = []
+ for path in paths:
+ sub, sub_params = self._node_subquery(path)
+ if sub is None:
+ continue
+ subs.append(f"e.id IN ({sub})")
+ params.extend(sub_params)
+ if not subs:
+ return []
+ sql = (
+ "SELECT e.id, e.tier, e.kind, e.subject, e.body, e.evidence, "
+ "e.nodes, e.birth_commit, e.birth_at, e.last_seen_at FROM episodes e "
+ f"WHERE ({' OR '.join(subs)})"
+ )
+ if tiers is not None:
+ sql += f" AND e.tier IN ({','.join('?' * len(tiers))})"
+ params.extend(tiers)
+ sql += " ORDER BY e.birth_at DESC, e.id ASC LIMIT ?"
+ params.append(max(1, limit))
+ try:
+ rows = self._conn.execute(sql, params).fetchall()
+ except sqlite3.Error:
+ _log.debug("episode node lookup failed", exc_info=True)
+ return []
+ return [_row_to_dict(row) for row in rows]
+
+ def _scan_by_node(
+ self, paths: Sequence[str], tiers: Sequence[str] | None
+ ) -> dict[str, list[dict]]:
+ """The pre-index implementation, kept as the fallback. Never raises.
+
+ Only reached when :meth:`_ensure_node_index` could not build the index
+ — a read-only database, a disk error, a build without the objects. It
+ costs a JSON decode per row (measured at 22.6 ms against this store's
+ 5,000-row cap, versus 1.6 ms indexed), which is the right trade against
+ the alternative: answering "nothing is bound here" in the same shape as
+ the truth, on a surface whose whole job is to say what happened.
+ """
+ try:
+ rows = self.list_episodes(tiers=tiers)
+ except sqlite3.Error:
+ _log.debug("episode node scan failed", exc_info=True)
+ return {}
+ out: dict[str, list[dict]] = {}
+ for path in paths:
+ norm = _normalise_node_path(path)
+ if not norm:
+ continue
+ hits = [row for row in rows if _covers_path(row.get("nodes") or [], norm)]
+ if hits:
+ out[path] = hits
+ return out
+
+ def _node_subquery(self, path: str) -> tuple[str | None, list[object]]:
+ """A subquery selecting the ids bound at, above or below *path*.
+
+ Both directions are the question being asked, because a target is a
+ file *or* a directory. An episode naming ``pkg/mod/file.py`` is about
+ the module ``pkg/mod``; an episode naming the directory ``pkg`` is
+ about every file in it. Matching one direction only would answer
+ confidently and wrongly for whichever shape it left out.
+
+ Written as ``id IN (SELECT ...)`` rather than a join, and that is a
+ correctness-of-plan decision rather than a style one. The join form was
+ measured first and SQLite drove it from ``episodes`` — filtering by
+ tier and probing the node table per row — which scans the whole tier
+ and never touches the path index, giving back exactly the cost this
+ table exists to remove. The subquery makes the indexed lookup the
+ driver. A query-plan test holds it there, because the join form was not
+ *wrong*, only slow, and nothing else would have caught it.
+
+ Ancestors are enumerated here and compared with equality, since a path
+ has a handful of them. Descendants are a **half-open range** rather
+ than a pattern, and that is a correctness fix rather than a
+ micro-optimisation: ``GLOB`` reads ``[`` as a character class and
+ SQLite's ``GLOB`` has no ``ESCAPE`` clause, so a framework's dynamic
+ route — ``app/repos/[id]`` — silently matched ``app/repos/i`` and
+ ``app/repos/d`` while missing every real child. 170 rows in this
+ repository's own store carry bracketed paths. ``*`` and ``?`` in a
+ path fail the same way. A range compares bytes and has no
+ metacharacters at all, so there is nothing to escape and nothing to
+ get wrong; ``/`` is ``0x2F`` and ``0`` is its successor, which is what
+ makes the upper bound exact rather than approximate.
+ """
+ norm = _normalise_node_path(path)
+ if not norm:
+ return None, []
+ # ``a/b/c.py`` is covered by an episode bound to it, to ``a/b`` or to
+ # ``a`` — self and every ancestor.
+ parts = norm.split("/")
+ selves = ["/".join(parts[: i + 1]) for i in range(len(parts))]
+ sub = (
+ "SELECT episode_id FROM episode_nodes WHERE "
+ f"path IN ({','.join('?' * len(selves))}) OR (path >= ? AND path < ?)"
+ )
+ return sub, [*selves, f"{norm}/", f"{norm}0"]
+
def count(self) -> int:
(rows,) = self._conn.execute("SELECT COUNT(*) FROM episodes").fetchone()
return int(rows)
@@ -670,11 +970,67 @@ class EpisodeStore:
self.close()
-def _row_to_dict(row: tuple) -> dict:
+def _normalise_node_path(path: str) -> str:
+ """A repo-relative path in the one form the node index stores.
+
+ Separators, redundant segments and stray slashes are all things a caller
+ hands over without meaning anything by them: ``pkg\\mod``, ``pkg/mod/``,
+ ``pkg//mod`` and ``pkg/x/../mod`` are one location, and matching them by
+ bytes would answer three of the four with silence. ``..`` is resolved
+ rather than rejected because an agent composing a path from a symbol's
+ module does produce them.
+
+ A path that climbs out of the repository has no node to match and returns
+ empty, which callers read as "ask nothing".
+ """
+ norm = posixpath.normpath(str(path).replace("\\", "/")).strip("/")
+ if not norm or norm == "." or norm.startswith("../"):
+ return ""
+ return norm
+
+
+def _covers_path(nodes: Sequence[object], norm: str) -> bool:
+ """True when *norm* is at, above or below one of *nodes*.
+
+ The scan-side twin of :meth:`EpisodeStore._node_subquery`, and the two are
+ tested against each other so the fallback cannot drift into answering a
+ different question from the index.
+ """
+ for node in nodes:
+ if not isinstance(node, str):
+ continue
+ n = _normalise_node_path(node)
+ if not n:
+ continue
+ if norm == n or norm.startswith(f"{n}/") or n.startswith(f"{norm}/"):
+ return True
+ return False
+
+
+def _valid_nodes(nodes: Iterable[object]) -> list[str]:
+ """The usable paths in a node list. One predicate, both writers.
+
+ Shared by the live write path and by a rebuild from the stored column, so
+ the index cannot answer differently depending on which one last touched it.
+ """
+ return [n for n in nodes if isinstance(n, str) and n]
+
+
+def _decode_nodes(raw: object) -> list[str]:
+ """The node list a stored ``nodes`` column holds, or empty if unreadable.
+
+ Tolerant on purpose: a row whose scope will not decode is still a claim
+ worth serving repo-wide, and this runs on the read path.
+ """
try:
- nodes = json.loads(row[6])
+ nodes = json.loads(raw) # type: ignore[arg-type]
except (TypeError, ValueError):
- nodes = []
+ return []
+ return _valid_nodes(nodes) if isinstance(nodes, list) else []
+
+
+def _row_to_dict(row: tuple) -> dict:
+ nodes = _decode_nodes(row[6])
return {
"id": row[0],
"tier": row[1],
diff --git a/packages/server/src/repowise/server/mcp_server/_episodes.py b/packages/server/src/repowise/server/mcp_server/_episodes.py
new file mode 100644
index 000000000..982b3f989
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_episodes.py
@@ -0,0 +1,442 @@
+"""Reading episodes on an MCP path: currency, quoting, and the served tiers.
+
+Two tools serve episodes and a third counts them, and the parts they share are
+exactly the parts that are easy to get subtly wrong: which tiers may be shown
+to somebody who did not derive them, whether a dated claim is still true, and
+how a free-text body is quoted without spending the response's whole budget.
+
+They are here rather than in :mod:`repowise.core.precedent.store` because they
+are about *serving* an episode, not storing one — the store stays stdlib-only
+so a hook can import it under a 155 ms budget, and this module reaches into the
+MCP budget helpers.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+from repowise.core.precedent.currency import commits_since
+from repowise.core.precedent.store import (
+ SHAREABLE_TIERS,
+ TIER_STRUCTURAL,
+ EpisodeStore,
+ default_store_path,
+)
+from repowise.server.mcp_server._budget import OmissionCollector
+
+_log = logging.getLogger(__name__)
+
+#: How many episodes an evidence block carries. Small on purpose: this is the
+#: showing stage, where noise is discardable but costs budget and trust, and a
+#: reader who wants more has a whole tool for asking.
+_MAX_EVIDENCE_EPISODES = 3
+
+#: Ceiling on one quoted body. Git episode bodies measure ~818 chars on this
+#: repository and structural ones ~300, so this cuts the tail rather than the
+#: common case, and what it cuts stays recoverable through the omission store.
+_MAX_EVIDENCE_BODY_CHARS = 400
+
+#: Ceiling on the listed scope. Measured worst case on this repository's
+#: shareable tiers is 23 paths / 1,522 chars, so this trims nothing in practice
+#: — it is here because ``nodes`` is free text in a budgeted response and a
+#: sweep commit is allowed to name a hundred files.
+_MAX_SCOPE_NODES = 12
+
+#: The tiers a reader may put in front of a user, named rather than inherited
+#: from whatever the store happens to hold.
+#:
+#: An unnamed default is how the store's second tier reached the ``get_answer``
+#: guard uninvited, and the third would have been worse: a session touches far
+#: more files than a fix commit and has no birth commit, so it outranks the
+#: others and can never be suppressed by the currency query. Beyond ranking,
+#: a transcript episode is per-machine — two people asking one question of one
+#: repository would get different answers — which is the property that decides
+#: it. Structural and git episodes describe the repository and travel with it.
+SERVED_TIERS = SHAREABLE_TIERS
+
+#: Tiers whose episodes are re-derived whole on every index, and for which a
+#: refreshed ``last_seen_at`` is therefore proof of currency at no cost. 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,
+#: so the shortcut would fire always and hide the one question worth asking.
+RE_DERIVED_TIERS = frozenset({TIER_STRUCTURAL})
+
+#: Seconds allowed for one read-time git query. Measured at 55-66 ms on a
+#: 1,000-commit repository; the timeout is for the pathological case (a cold,
+#: very large repo), where saying nothing is the right answer.
+GIT_TIMEOUT_S = 2.0
+
+
+@dataclass(frozen=True)
+class Currency:
+ """What git says about an episode's claim, and whether it vouches for it.
+
+ Two fields rather than one, because two readers need different halves of
+ the same answer and collapsing them is how one of them ends up wrong. A
+ guard appending a claim beside an answer *about the present* must stay
+ silent unless ``current``; a reader asking *what happened here* wants the
+ ``sentence`` either way, since a superseded episode is still a true
+ statement about the past.
+ """
+
+ sentence: str
+ current: bool
+
+
+def currency(row: dict, *, root: Path) -> Currency:
+ """What is known about whether this episode still holds.
+
+ Measured against the checkout's live ``HEAD``, not the indexed commit: an
+ episode is a claim about the tree on disk, and that is the tree the reader
+ is about to act on.
+
+ Three cases, and the third is the one worth reading.
+
+ *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. See :data:`RE_DERIVED_TIERS` for why it is not general.
+
+ *Node-scoped.* ``git rev-list --count <birth>..HEAD -- <nodes>`` is the
+ real question, and zero is a real answer. Anything else — including a git
+ failure — means we cannot vouch for it.
+
+ *Repo-wide, derived once.* Git cannot decide this one. Its scope is the
+ whole tree, so any commit at all makes the count non-zero, and the fact it
+ asserts ("the tree is not formatter-clean") is not what a commit falsifies
+ — running the formatter is. Calling it not-current would retire the record
+ on the very next commit and leave a guard that only passes its own tests,
+ so the age is reported and the claim stands.
+ """
+ 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 and row.get("tier") in RE_DERIVED_TIERS:
+ return Currency(f"re-observed by a later index (recorded {recorded})", True)
+
+ birth_commit = row.get("birth_commit")
+ nodes = [n for n in (row.get("nodes") or []) if isinstance(n, str) and n]
+
+ if nodes:
+ if not birth_commit:
+ # No birth commit means there is nothing to ask git *from*, which
+ # is not the same as git answering badly: the claim is undated
+ # rather than contradicted, and the guard has always served it.
+ return Currency(f"recorded {recorded}; not re-checked since", True)
+ changed = commits_since(
+ root, since_commit=birth_commit, nodes=nodes, timeout=GIT_TIMEOUT_S
+ )
+ if changed is None:
+ return Currency(
+ f"recorded {recorded} at {short(birth_commit)}; git could not be asked", False
+ )
+ if changed > 0:
+ plural = "commit has" if changed == 1 else "commits have"
+ return Currency(
+ f"recorded {recorded} at {short(birth_commit)}; {changed} {plural} "
+ "touched its scope since",
+ False,
+ )
+ return Currency(
+ f"nothing in its scope has changed since {short(birth_commit)} "
+ f"(recorded {recorded})",
+ True,
+ )
+
+ if not birth_commit:
+ return Currency(f"recorded {recorded}; a standing claim about this checkout", True)
+ moved = commits_since(root, since_commit=birth_commit, nodes=[], timeout=GIT_TIMEOUT_S)
+ if moved is None:
+ return Currency(
+ f"recorded {recorded} at {short(birth_commit)}; not re-checked since", True
+ )
+ if moved == 0:
+ return Currency(
+ f"recorded {recorded} at {short(birth_commit)}, the current commit", True
+ )
+ plural = "commit" if moved == 1 else "commits"
+ return Currency(
+ f"recorded {recorded} at {short(birth_commit)}; the tree has moved "
+ f"{moved} {plural} since and this was not re-checked",
+ True,
+ )
+
+
+def still_true(row: dict, *, root: Path) -> str | None:
+ """The gate form of :func:`currency`: a sentence, or None to stay silent.
+
+ For a surface that puts an episode beside an answer about the present,
+ where precision is close to absolute and anything git cannot vouch for is
+ not worth the risk of contradicting a correct synthesis.
+ """
+ verdict = currency(row, root=root)
+ return verdict.sentence if verdict.current else None
+
+
+def quote_body(
+ row: dict,
+ *,
+ tool: str,
+ repo_root: Path,
+ max_chars: int,
+ collector: OmissionCollector | None = None,
+) -> tuple[str, OmissionCollector | None]:
+ """The episode's body, capped, with whatever was cut left recoverable.
+
+ A cap on a *count* is not a bound on a response whose fields are free text
+ — the lesson ``get_why`` path mode paid 81,854 characters for — so every
+ caller that quotes a body goes through here. Overflow is handed to the
+ omission store so it stays reachable via ``repowise expand`` rather than
+ vanishing; the returned collector is the caller's to ``attach``, because
+ only the caller knows which payload the marker belongs on.
+
+ *collector* is reused when given, and that is a correctness requirement
+ rather than an optimisation: ``attach`` **overwrites** ``_meta.omitted``
+ with its own refs, so two collectors finalising onto one response leave
+ the first one's markers pointing at content the response no longer
+ advertises. One response, one collector.
+ """
+ body = row.get("body") or ""
+ if len(body) <= max_chars:
+ return body, collector
+ if collector is None:
+ collector = OmissionCollector(tool, repo_root)
+ marker = collector.add_inline(f"episode:{row.get('kind')}", body)
+ return body[:max_chars].rstrip() + (f" {marker}" if marker else " …"), collector
+
+
+def episode_evidence(
+ root: Path,
+ *,
+ paths: Sequence[str] | None = None,
+ query: str | None = None,
+ limit: int = _MAX_EVIDENCE_EPISODES,
+ max_body_chars: int = _MAX_EVIDENCE_BODY_CHARS,
+) -> tuple[list[dict], list[tuple[dict, str, str]]]:
+ """Episodes as an evidence block, bounded. Never raises.
+
+ Two ways in, matching the two shapes of question a reader asks. *paths*
+ resolves the scope through the store's node index — the reader named a
+ file, and the episodes bound at, above or below it are the answer. *query*
+ ranks bodies by full-text search, for a reader who asked in prose.
+
+ **Currency is a label here, not a gate**, which is a deliberate divergence
+ from the ``get_answer`` guard and worth stating because the two look alike.
+ That guard appends a claim beside an answer *about the present*, so an
+ episode whose scope has moved is suppressed outright. This is answering
+ "what happened here", where a superseded episode is still a true statement
+ about the past — a fix that landed and was later changed is exactly the
+ history the question asked for. Suppressing it would answer a different
+ question than the one asked.
+
+ Only the top-ranked episode is asked about, because the git query is ~60 ms
+ and the reader acts on the first one: the same bound, for the same reason,
+ that this mode already applies to the record it ranks first. The rest carry
+ the free re-observation signal where their tier supports it, and no
+ ``still_true`` key at all where it would be a guess.
+
+ **Returns the overflow rather than banking it**, as ``(entries, pending)``
+ where each pending item is ``(entry, label, full_body)``. Callers run this
+ in a worker thread — it does SQLite and a git subprocess — and the omission
+ store is a ``sqlite3`` connection with ``check_same_thread`` left on, so a
+ collector opened here and finalised on the event loop raises
+ ``ProgrammingError`` inside ``_put``, which swallows it and silently drops
+ *every* banked block. Banking belongs to whichever thread will attach.
+ """
+ if not paths and not query:
+ return [], []
+ store_path = default_store_path(root)
+ # Opening the store would CREATE it. A repo that never derived episodes
+ # must not grow a database because somebody asked a question.
+ if not store_path.is_file():
+ return [], []
+
+ try:
+ with EpisodeStore(store_path) as store:
+ rows = (
+ store.list_by_node(list(paths), tiers=SERVED_TIERS, limit=limit)
+ if paths
+ else store.search(query or "", tiers=SERVED_TIERS, limit=limit)
+ )
+ except Exception:
+ _log.warning("episode store read failed", exc_info=True)
+ return [], []
+ if not rows:
+ return [], []
+
+ entries: list[dict] = []
+ pending: list[tuple[dict, str, str]] = []
+ for rank, row in enumerate(rows[:limit]):
+ body = row.get("body") or ""
+ entry: dict = {
+ "tier": row.get("tier"),
+ "kind": row.get("kind"),
+ "subject": row.get("subject"),
+ "recorded": body,
+ "evidence": row.get("evidence"),
+ "scope": _scope_field(row),
+ }
+ if len(body) > max_body_chars:
+ entry["recorded"] = body[:max_body_chars].rstrip()
+ pending.append((entry, f"episode:{row.get('kind')}", body))
+ verdict = currency(row, root=root).sentence if rank == 0 else _free_currency(row)
+ if verdict:
+ entry["still_true"] = verdict
+ entries.append(entry)
+ return entries, pending
+
+
+def bank_overflow(
+ pending: Sequence[tuple[dict, str, str]], *, tool: str, repo_root: Path
+) -> OmissionCollector | None:
+ """Persist capped bodies and stamp each entry with its recovery marker.
+
+ Call on the thread that will ``attach`` the returned collector — see
+ :func:`episode_evidence` for why that is not the thread that read them.
+
+ Identical bodies are banked once. The omission store keys on a content
+ hash, so a repeated body already resolved to one row, but the collector
+ appends a ref per call and would have advertised the same ref three times
+ and counted its tokens three times over.
+ """
+ if not pending:
+ return None
+ collector = OmissionCollector(tool, repo_root)
+ markers: dict[str, str | None] = {}
+ for entry, label, body in pending:
+ if body not in markers:
+ markers[body] = collector.add_inline(label, body)
+ marker = markers[body]
+ entry["recorded"] = f"{entry['recorded']} {marker}" if marker else f"{entry['recorded']} …"
+ return collector
+
+
+def _scope_field(row: dict) -> list[str] | str:
+ """The episode's scope, bounded.
+
+ An empty node set is a claim about the checkout as a whole rather than an
+ unknown one. A long one is truthful but is free text in a response that has
+ a budget, so it is capped and says how many it stood for.
+ """
+ nodes = [n for n in (row.get("nodes") or []) if isinstance(n, str)]
+ if not nodes:
+ return "the checkout as a whole"
+ if len(nodes) <= _MAX_SCOPE_NODES:
+ return nodes
+ return [*nodes[:_MAX_SCOPE_NODES], f"… and {len(nodes) - _MAX_SCOPE_NODES} more"]
+
+
+def episode_counts(root: Path, paths: Sequence[str]) -> dict[str, int]:
+ """How many episodes each of *paths* carries. Never raises.
+
+ A count and nothing else. A number invites a follow-up call to the tool
+ that serves the bodies; a paragraph spends every caller's budget whether
+ they wanted it or not, and these two tools are called on every target an
+ agent triages.
+
+ Opened once for the whole call rather than once per target, because the
+ open is the expensive part: 3.0 ms against 0.2 ms for the lookup itself on
+ this repository's store. Paths with no episodes are absent from the result
+ so a caller can omit the field instead of serving a zero.
+ """
+ if not paths:
+ return {}
+ store_path = default_store_path(root)
+ # Opening the store would CREATE it. A repo that never derived episodes
+ # must not grow a database because somebody triaged a file.
+ if not store_path.is_file():
+ return {}
+ try:
+ with EpisodeStore(store_path) as store:
+ return store.count_by_node(list(paths), tiers=SERVED_TIERS)
+ except Exception:
+ _log.warning("episode count failed", exc_info=True)
+ return {}
+
+
+def enrich_episode_counts(results: Sequence[dict], root: Path) -> None:
+ """Stamp ``episodes: N`` onto each target card that has any. Never raises.
+
+ Shared by ``get_risk`` and ``get_context``, which build their per-target
+ dicts independently and have no common assembly point — the same shape of
+ post-hoc enrichment both already use for cross-repo and health data.
+
+ Three things decide which paths are asked about, and each was a wrong
+ answer first:
+
+ *A card carrying an ``error`` is skipped.* An unresolved target still has
+ its requested string, and a directory-bound episode matches any path
+ beneath it, so a typo under a governed directory came back with an
+ authoritative-looking count attached to "target not found".
+
+ *A symbol target is asked about as its file.* ``mod.py::Name`` splits on
+ ``/`` to a leaf that matches no node, leaving only the ancestor
+ directories to match — so a symbol card showed the count of its parent
+ directory while the sibling file card showed the file's own, and the
+ symbol read as the quieter of the two. Episodes bind to files; the honest
+ answer for a symbol is its file's.
+
+ *A renamed file is asked about under both names.* ``get_risk`` already
+ resolves ``original_path``, and episodes are filed under the path the
+ commit touched, so without it a file loses its entire history the moment
+ it moves — precisely when an agent most wants it.
+
+ Synchronous, and both callers hand it to a thread: the work is SQLite and
+ belongs off the event loop.
+ """
+ wanted: dict[int, tuple[str, str | None]] = {}
+ for i, card in enumerate(results):
+ target = card.get("target")
+ if not isinstance(target, str) or card.get("error"):
+ continue
+ current = _file_of(target)
+ if not current:
+ continue
+ original = card.get("original_path")
+ former = _file_of(original) if isinstance(original, str) and original else None
+ wanted[i] = (current, former if former and former != current else None)
+
+ asked = {name for pair in wanted.values() for name in pair if name}
+ counts = episode_counts(root, sorted(asked))
+ if not counts:
+ return
+ for i, (current, former) in wanted.items():
+ # Whichever name the history is filed under, not the sum of both: one
+ # commit can touch both sides of a rename, so adding them would count
+ # it twice, and after a rename the episodes are under the old name.
+ total = counts.get(current) or (counts.get(former, 0) if former else 0)
+ if total:
+ results[i]["episodes"] = total
+
+
+def _file_of(target: str) -> str:
+ """The file a target names, dropping any ``::symbol`` suffix."""
+ return target.split("::", 1)[0].strip()
+
+
+def _free_currency(row: dict) -> str | None:
+ """The currency signal available without a git call, or None to say nothing.
+
+ Every index re-derives a structural fact that still holds, so a stamp later
+ than the birth is proof of currency that costs nothing. It proves nothing
+ for a tier that accumulates members, and a guess dressed as a verdict is
+ worse than an absent field.
+ """
+ birth_at = row.get("birth_at") or 0.0
+ last_seen = row.get("last_seen_at") or 0.0
+ if last_seen > birth_at and row.get("tier") in RE_DERIVED_TIERS:
+ return f"re-observed by a later index (recorded {recorded_on(birth_at)})"
+ return None
+
+
+def recorded_on(birth_at: float) -> str:
+ if not birth_at:
+ return "at an unknown date"
+ return time.strftime("%Y-%m-%d", time.gmtime(birth_at))
+
+
+def short(sha: str) -> str:
+ return sha[:12]
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 e2fcbf137..d94489555 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
@@ -32,17 +32,15 @@ import asyncio
import json
import logging
import re
-import time
from pathlib import Path
-from repowise.core.precedent.currency import commits_since
-from repowise.core.precedent.store import (
- SHAREABLE_TIERS,
- TIER_STRUCTURAL,
- EpisodeStore,
- default_store_path,
+from repowise.core.precedent.store import EpisodeStore, default_store_path
+from repowise.server.mcp_server._budget import effective_char_budget
+from repowise.server.mcp_server._episodes import (
+ SERVED_TIERS,
+ quote_body,
+ still_true,
)
-from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget
_log = logging.getLogger(__name__)
@@ -61,38 +59,18 @@ _MAX_BODY_CHARS = 600
#: 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})
-
-#: The tiers this guard is willing to put in front of a reader, named rather
-#: than inherited from whatever the store happens to hold.
-#:
-#: An unnamed default is how the store's second tier reached this surface last
-#: time, and reproducing it with the third showed why that is not survivable
-#: here: with 56 of this repository's 426 sessions recorded, the guard went
-#: **silent on its own reproduction** and served a session instead. Two things
-#: compound. A session touches far more files than a fix commit, so it outranks
-#: one on the window's specificity sort; and it has no birth commit, so
-#: :func:`_still_true` never reaches the git query and can never suppress it.
-#: It wins the window and holds it.
-#:
-#: The harmlessness bar for a surfaced episode is absolute and is unmeasured
-#: for the transcript tier, which is also per-machine — two people asking one
-#: question of one repository would get different answers. Until that has been
-#: measured, this stays a shareable-tiers allowlist.
-_SERVED_TIERS = SHAREABLE_TIERS
+#: The tiers this guard is willing to put in front of a reader. Shared with
+#: every other episode reader (:mod:`repowise.server.mcp_server._episodes`),
+#: because "which tiers are shareable" is a property of the store rather than
+#: of one tool, and the first version of this constant reached the wrong answer
+#: by being local: an unnamed default let the store's second tier arrive
+#: uninvited, and with 56 of this repository's 426 sessions recorded the guard
+#: went **silent on its own reproduction** and served a session instead.
+_SERVED_TIERS = SERVED_TIERS
#: Room the block needs before it is worth attaching at all.
_BLOCK_OVERHEAD_CHARS = 400
-#: Seconds allowed for the one sanctioned read-time git query. Measured at
-#: 55-66 ms on a 1,000-commit repository; the timeout is for the pathological
-#: case (a cold, very large repo), where saying nothing is the right answer.
-_GIT_TIMEOUT_S = 2.0
-
_LEAD_IN = (
"A dated record from this checkout is attached in `episodes` — evidence "
"recorded at a point in time, not a correction of the answer above."
@@ -307,90 +285,10 @@ def _answer_paths(payload: dict) -> set[str]:
# -- precondition 2: still true ----------------------------------------------
-
-def _still_true(row: dict, *, root: Path) -> str | None:
- """How this episode's truth was established, or None to stay silent.
-
- Measured against the checkout's live ``HEAD``, not the indexed commit: an
- episode is a claim about the tree on disk, and that is the tree the reader
- is about to act on.
-
- Three cases, and the third is the one worth reading.
-
- *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
- failure — means we cannot vouch for it, so it is suppressed. Precision at
- the acting stage is close to absolute.
-
- *Repo-wide, derived once.* Git cannot decide this one. Its scope is the
- whole tree, so any commit at all makes the count non-zero, and the fact it
- asserts ("the tree is not formatter-clean") is not what a commit falsifies
- — running the formatter is. Suppressing here would retire the record on the
- very next commit and leave a guard that only passes its own tests. So the
- age **labels** rather than suppresses: it is served with its birth commit
- and how far the tree has moved since, and the reader discounts it. Under
- add-never-replace a stale episode overrides nothing, and the asymmetry runs
- the right way — believing it costs one skipped formatter run, disbelieving
- it costs a reformatted tree in a pull request.
- """
- 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 and row.get("tier") in _RE_DERIVED_TIERS:
- return f"re-observed by a later index (recorded {recorded})"
-
- birth_commit = row.get("birth_commit")
- nodes = [n for n in (row.get("nodes") or []) if isinstance(n, str) and n]
-
- if nodes:
- if not birth_commit:
- return f"recorded {recorded}; not re-checked since"
- changed = _commits_since(root, birth_commit, nodes)
- if changed is None or changed > 0:
- return None
- return f"nothing in its scope has changed since {_short(birth_commit)} (recorded {recorded})"
-
- if not birth_commit:
- return f"recorded {recorded}; a standing claim about this checkout"
- moved = _commits_since(root, birth_commit, [])
- if moved is None:
- return f"recorded {recorded} at {_short(birth_commit)}; not re-checked since"
- if moved == 0:
- return f"recorded {recorded} at {_short(birth_commit)}, the current commit"
- plural = "commit" if moved == 1 else "commits"
- return (
- f"recorded {recorded} at {_short(birth_commit)}; the tree has moved "
- f"{moved} {plural} since and this was not re-checked"
- )
-
-
-def _commits_since(root: Path, birth_commit: str, nodes: list[str]) -> int | None:
- """``git rev-list --count <birth>..HEAD [-- nodes]``. None on any failure.
-
- The one sanctioned read-time computation in this path, and it is bounded:
- a single plumbing call with a hard timeout, measured at 55-66 ms against
- get_answer's multi-second synthesis. The call itself lives in
- :mod:`repowise.core.precedent.currency`, shared with the decision layer,
- which asks the same question from a date instead of a birth commit.
- """
- return commits_since(root, since_commit=birth_commit, nodes=nodes, timeout=_GIT_TIMEOUT_S)
-
-
-def _recorded_on(birth_at: float) -> str:
- if not birth_at:
- return "at an unknown date"
- return time.strftime("%Y-%m-%d", time.gmtime(birth_at))
-
-
-def _short(sha: str) -> str:
- return sha[:12]
+#: The currency verdict, shared with every other episode reader. The one
+#: sanctioned read-time git query lives behind it, bounded by a timeout and by
+#: this module's candidate window.
+_still_true = still_true
# -- emission ----------------------------------------------------------------
@@ -412,12 +310,9 @@ def _emit(
if len(json.dumps(payload, default=str)) + _BLOCK_OVERHEAD_CHARS > effective_char_budget():
return False
- body = row.get("body") or ""
- collector: OmissionCollector | None = None
- if len(body) > _MAX_BODY_CHARS:
- collector = OmissionCollector("get_answer", repo_root)
- marker = collector.add_inline(f"episode:{row.get('kind')}", body)
- body = body[:_MAX_BODY_CHARS].rstrip() + (f" {marker}" if marker else " …")
+ body, collector = quote_body(
+ row, tool="get_answer", repo_root=repo_root, max_chars=_MAX_BODY_CHARS
+ )
entry = {
"tier": row.get("tier"),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index 53bd901c1..b8bed5d39 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -32,6 +32,7 @@ from repowise.core.persistence.database import get_session
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._budget import OmissionCollector, truncate_to_budget
+from repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodes
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
_get_repo,
@@ -58,6 +59,10 @@ async def get_context(
and symbol_ids to pipe into get_symbol (cheaper than Read for bodies).
fix_history appears only on files with counted bug fixes (count, age,
bug_magnet); hotspot is churn. Either one is a cue to call get_risk.
+ episodes counts the dated records bound to a target — what happened here
+ and why — and appears only when there is at least one; get_why serves the
+ bodies. A symbol target is counted as its file, and a module aggregates
+ everything beneath it.
Batch targets in one call. File targets above ~80 lines default to a
skeleton (every signature + top-PageRank bodies, with a verified flag —
a fraction of Read cost); ``mostly_full`` marks files where a direct
@@ -131,6 +136,11 @@ async def get_context(
else:
results.append(r)
+ # One integer per target: how many dated episodes are bound here. A number
+ # invites a follow-up get_why; a paragraph would spend the budget of every
+ # caller that only wanted the triage card. Absent rather than zero.
+ await asyncio.to_thread(_enrich_episodes, results, ctx.path)
+
response: dict[str, Any] = {
"targets": {r["target"]: r for r in results},
"_meta": _build_meta(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
index f45de2c04..f88fb5d40 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
@@ -14,6 +14,7 @@ from repowise.core.persistence.models import (
)
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodes
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
_get_repo,
@@ -55,6 +56,12 @@ async def get_risk(
rather than exact. Nothing here names the commit that introduced a bug.
global_hotspots ranks the same way: fix history first, churn as fallback.
+ episodes counts the dated records bound to a target — what happened here
+ and why, with a commit or a filesystem fact as evidence. It appears only
+ when there is at least one, and get_why serves the bodies. A directory
+ target aggregates everything beneath it, so the numbers compare within a
+ kind of target and not across kinds.
+
Args:
targets: file paths to assess.
repo: usually omitted.
@@ -179,6 +186,12 @@ async def get_risk(
# health tables. Conservative: missing data → no field, never invented.
await _enrich_health(results, ctx, repo_id)
+ # ---- Precedent enrichment ----------------------------------------------
+ # One integer per target: how many dated episodes are bound here. A number
+ # invites a follow-up get_why; a paragraph would spend the budget of every
+ # caller that only wanted the risk card. Absent rather than zero.
+ await asyncio.to_thread(_enrich_episodes, results, ctx.path)
+
response: dict = {
"targets": {r["target"]: r for r in results},
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index f81a5eeee..a52372317 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -21,6 +21,7 @@ from repowise.core.precedent.currency import describe_decision_currency
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget
from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale
+from repowise.server.mcp_server._episodes import bank_overflow, episode_evidence
from repowise.server.mcp_server._helpers import (
_build_origin_story,
_compute_alignment,
@@ -252,7 +253,9 @@ def _trim_commit_text(origin_story: dict) -> None:
_trim(linked.get("evidence_commits"))
-def _fit_path_response(result_data: dict, repo_root: Any) -> dict:
+def _fit_path_response(
+ result_data: dict, repo_root: Any, collector: OmissionCollector | None = None
+) -> dict:
"""Shrink a path response until it fits the transport budget.
The projection above bounds the structured fields; this bounds the free
@@ -275,6 +278,14 @@ def _fit_path_response(result_data: dict, repo_root: Any) -> dict:
Every drop goes to the omission store, so the agent gets a
``[repowise#<ref>]`` marker it can expand rather than a silently shortened
response. Call after ``_meta`` is set: the collector writes into it.
+
+ *collector* is the one a caller already started — the episode block caps
+ long bodies and banks the overflow before this runs. It must be reused
+ rather than joined by a second, because ``attach`` overwrites
+ ``_meta.omitted`` with its own refs and the loser's markers would then
+ point at content the response no longer advertises. It is also why the
+ under-budget path still attaches: a response that fits can still carry a
+ capped body whose remainder needs advertising.
"""
# Reserved so the marker the collector appends after the last check cannot
# itself push the response back over the host cap.
@@ -284,9 +295,12 @@ def _fit_path_response(result_data: dict, repo_root: Any) -> dict:
return len(json.dumps(result_data, separators=(",", ":"), default=str)) > budget
if not _over():
+ if collector is not None:
+ collector.attach(result_data)
return result_data
- collector = OmissionCollector("get_why", repo_root=repo_root)
+ if collector is None:
+ collector = OmissionCollector("get_why", repo_root=repo_root)
def _drop_block(key: str, container: dict) -> None:
if _over() and container.get(key):
@@ -297,6 +311,13 @@ def _fit_path_response(result_data: dict, repo_root: Any) -> dict:
if isinstance(origin_story, dict):
_drop_block("linked_decisions", origin_story)
+ # Before the governing records, not after them: episodes are the newest
+ # evidence kind here and must only ever spend slack. Dropping them later in
+ # the sequence meant the decisions loop ran with the episode block still
+ # inflating the response, and a governing record was evicted to make room
+ # for an episode that then survived — measured, not theorised.
+ _drop_block("episodes", result_data)
+
decisions: list = result_data.get("decisions") or []
while decisions and _over():
dropped = decisions.pop()
@@ -418,8 +439,20 @@ async def _why_path(query: str, repo: str | None) -> dict:
if rationale:
result_data["code_rationale"] = rationale
+ # Episodes are additive rather than a fallback, unlike the two blocks
+ # above. A well-governed file still has a history, and "what happened
+ # here, dated" is the question this mode is asked; gating it on the
+ # absence of decisions would hide it exactly where there is most to say.
+ episodes, pending = await asyncio.to_thread(episode_evidence, ctx.path, paths=[query])
+ if episodes:
+ result_data["episodes"] = episodes
+ # Banked here, not in the thread above: the omission store is a
+ # sqlite3 connection bound to its creating thread, and this collector
+ # is finalised below on this one.
+ collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)
+
result_data["_meta"] = _build_meta(repository=repository)
- return _fit_path_response(result_data, ctx.path)
+ return _fit_path_response(result_data, ctx.path, collector=collector)
# Stop words removed before keyword matching for better signal.
@@ -658,7 +691,32 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -
if rationale:
result_data["code_rationale"] = rationale
+ # Targets resolve through the node index; without them the question itself
+ # is the only handle, so it is ranked against the bodies.
+ episodes, pending = await asyncio.to_thread(
+ episode_evidence,
+ ctx.path,
+ paths=targets or None,
+ query=None if targets else query,
+ )
+ if episodes:
+ result_data["episodes"] = episodes
+
result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
+ # Deliberately *not* routed through `_fit_path_response`. This mode has no
+ # budget pass and predates this block, but that function is written for the
+ # path response's shape: search mode keeps `origin_story` and
+ # `git_archaeology` inside `target_context`, so the two blocks it would
+ # drop whole are no-ops here and the only thing it can actually shed is
+ # this mode's primary payload. Measured on a realistic six-target
+ # response, it emptied `decisions` entirely and was still over budget —
+ # strictly worse than leaving it alone. What this block adds is bounded by
+ # construction (three episodes, each body capped), which is the obligation
+ # it owes; giving the whole mode a budget pass is a separate change with
+ # its own drop order to design.
+ collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)
+ if collector is not None:
+ collector.attach(result_data)
return result_data
diff --git a/tests/unit/precedent/test_episode_store.py b/tests/unit/precedent/test_episode_store.py
index 210c9ee7a..6b9bdc4a7 100644
--- a/tests/unit/precedent/test_episode_store.py
+++ b/tests/unit/precedent/test_episode_store.py
@@ -782,3 +782,412 @@ class TestSearch:
rows = {r["subject"]: r for r in store.list_episodes(tier=TIER_TRANSCRIPT)}
assert SOURCE_GONE_NOTE not in rows["two"]["evidence"]
assert rows["two"]["evidence"] == "e"
+
+
+def _bound(
+ subject: str,
+ nodes: tuple[str, ...],
+ *,
+ tier: str = TIER_GIT,
+ birth_at: float = 1000.0,
+) -> Episode:
+ return Episode(
+ tier=tier,
+ kind="code_fix",
+ subject=subject,
+ body="b",
+ evidence="e",
+ nodes=nodes,
+ birth_commit="a" * 40,
+ birth_at=birth_at,
+ )
+
+
+class TestNodeLookup:
+ """``count_by_node`` / ``list_by_node`` — the scope question, indexed."""
+
+ def test_an_episode_is_found_by_the_file_it_names(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/file.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg/mod/file.py"]) == {"pkg/mod/file.py": 1}
+
+ def test_a_directory_target_finds_the_episodes_beneath_it(self, tmp_path: Path) -> None:
+ """A module target is a real target, and the files under it are its episodes."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/mod/a.py",)), _bound("s2", ("pkg/mod/b.py",))],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["pkg/mod"]) == {"pkg/mod": 2}
+
+ def test_a_file_target_finds_the_episode_bound_to_its_directory(self, tmp_path: Path) -> None:
+ """The other direction: a claim about a directory is a claim about its files."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg/mod/file.py"]) == {"pkg/mod/file.py": 1}
+
+ def test_a_sibling_prefix_is_not_a_match(self, tmp_path: Path) -> None:
+ """``pkg/mod2`` starts with ``pkg/mod`` as a string and is a different directory."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod2/file.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg/mod"]) == {}
+
+ def test_an_episode_naming_a_path_twice_counts_once(self, tmp_path: Path) -> None:
+ """Self and ancestor both match; the caller asked how many episodes, not nodes."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/mod", "pkg/mod/file.py"))],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["pkg/mod/file.py"]) == {"pkg/mod/file.py": 1}
+
+ def test_a_path_with_no_episodes_is_absent_rather_than_zero(self, tmp_path: Path) -> None:
+ """So a caller can omit the field instead of serving a zero."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/a.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["other/file.py"]) == {}
+
+ def test_windows_separators_are_normalised(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/file.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg\\mod\\file.py"]) == {"pkg\\mod\\file.py": 1}
+
+ def test_the_tier_allowlist_is_honoured(self, tmp_path: Path) -> None:
+ """A transcript episode is per-machine and must not reach a shareable reader."""
+ with _store(tmp_path) as store:
+ store.accumulate_tier(
+ tier=TIER_TRANSCRIPT,
+ kind="session",
+ episodes=[
+ Episode(
+ tier=TIER_TRANSCRIPT,
+ kind="session",
+ subject="s",
+ body="b",
+ evidence="e",
+ nodes=("pkg/mod/file.py",),
+ )
+ ],
+ present_subjects=["s"],
+ )
+ assert store.count_by_node(["pkg/mod/file.py"]) == {"pkg/mod/file.py": 1}
+ assert store.count_by_node(["pkg/mod/file.py"], tiers=SHAREABLE_TIERS) == {}
+
+ def test_an_empty_allowlist_selects_nothing(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/a.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg/mod/a.py"], tiers=[]) == {}
+ assert store.list_by_node(["pkg/mod/a.py"], tiers=[]) == []
+
+ def test_no_paths_asks_nothing(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ assert store.count_by_node([]) == {}
+ assert store.list_by_node([]) == []
+
+ def test_list_by_node_returns_newest_births_first(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _bound("old", ("pkg/a.py",), birth_at=1000.0),
+ _bound("new", ("pkg/a.py",), birth_at=2000.0),
+ ],
+ oldest_birth_at=None,
+ )
+ rows = store.list_by_node(["pkg/a.py"])
+ assert [r["subject"] for r in rows] == ["new", "old"]
+
+ def test_list_by_node_honours_its_limit(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound(f"s{i}", ("pkg/a.py",), birth_at=1000.0 + i) for i in range(5)],
+ oldest_birth_at=None,
+ )
+ assert len(store.list_by_node(["pkg/a.py"], limit=2)) == 2
+
+ def test_an_episode_matching_two_targets_is_listed_once(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/a.py", "pkg/b.py"))],
+ oldest_birth_at=None,
+ )
+ assert len(store.list_by_node(["pkg/a.py", "pkg/b.py"])) == 1
+
+
+class TestNodeIndexMaintenance:
+ """The index is derived data and must never disagree with ``episodes.nodes``."""
+
+ def test_a_re_derived_episode_loses_the_nodes_it_stopped_naming(self, tmp_path: Path) -> None:
+ """A scope that can only grow is how a claim ends up matching a file it left."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/a.py", "pkg/b.py"))],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["pkg/b.py"]) == {"pkg/b.py": 1}
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/a.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["pkg/a.py"]) == {"pkg/a.py": 1}
+ assert store.count_by_node(["pkg/b.py"]) == {}
+
+ def test_a_deleted_episode_takes_its_nodes_with_it(self, tmp_path: Path) -> None:
+ """Every delete path goes through the trigger, including the kind sweep."""
+ with _store(tmp_path) as store:
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL,
+ kinds=["nested_repos"],
+ episodes=[_episode()],
+ now=1000.0,
+ )
+ assert store.count_by_node(["backend"]) == {"backend": 1}
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL, kinds=["nested_repos"], episodes=[], now=2000.0
+ )
+ assert store.count_by_node(["backend"]) == {}
+ (orphans,) = store._conn.execute("SELECT COUNT(*) FROM episode_nodes").fetchone()
+ assert orphans == 0
+
+ def test_the_ttl_sweep_leaves_no_orphan_nodes(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/a.py",))],
+ oldest_birth_at=None,
+ now=1000.0,
+ )
+ store.prune(now=1000.0 + store.ttl_days * 86400 * 2)
+ (orphans,) = store._conn.execute("SELECT COUNT(*) FROM episode_nodes").fetchone()
+ assert orphans == 0
+
+ def test_a_store_written_before_the_index_backfills_on_open(self, tmp_path: Path) -> None:
+ """Existing stores need no migration: the rows are the system of record."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/a.py",))], oldest_birth_at=None
+ )
+ db_path = store.db_path
+ # Drop the index the way a store written before it would not have had it.
+ store._conn.executescript("DROP TRIGGER episodes_nodes_ad; DROP TABLE episode_nodes;")
+ store._conn.commit()
+
+ with EpisodeStore(db_path) as reopened:
+ assert reopened.node_index_enabled
+ assert reopened.count_by_node(["pkg/a.py"]) == {"pkg/a.py": 1}
+
+ def test_a_generator_of_episodes_still_gets_its_nodes_indexed(self, tmp_path: Path) -> None:
+ """``_upsert`` makes two passes; a lazy caller must not silently lose scope."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=(e for e in [_bound("s1", ("pkg/a.py",))]),
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["pkg/a.py"]) == {"pkg/a.py": 1}
+
+
+class TestNodeLookupStaysIndexed:
+ """The plan, not the clock: a busy machine cannot make this pass or fail."""
+
+ def test_the_lookup_uses_the_path_index_in_both_directions(self, tmp_path: Path) -> None:
+ """The join form measured 14x slower because SQLite drove it from ``episodes``.
+
+ It was not wrong, only slow, so nothing but the plan would have caught
+ it. Both the self/ancestor equality and the descendant ``GLOB`` must
+ resolve through ``idx_episode_nodes_path``.
+ """
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/a.py",))], oldest_birth_at=None
+ )
+ sub, params = store._node_subquery("pkg/mod/a.py")
+ plan = "\n".join(
+ str(row[-1])
+ for row in store._conn.execute(
+ f"EXPLAIN QUERY PLAN SELECT COUNT(*) FROM episodes e WHERE e.id IN ({sub})",
+ params,
+ )
+ )
+ assert "idx_episode_nodes_path" in plan
+ assert "SCAN episode_nodes" not in plan
+ # The GLOB half is rewritten into a range scan over the same index.
+ assert "path>? AND path<?" in plan
+
+
+class TestPatternCharactersInPaths:
+ """Paths are data, not patterns, and a framework's routes prove it."""
+
+ def test_a_bracketed_directory_matches_its_own_children(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _bound("s1", ("src/app/[repo]/page.tsx",)),
+ _bound("s2", ("src/app/[repo]/layout.tsx",)),
+ ],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["src/app/[repo]"]) == {"src/app/[repo]": 2}
+ assert len(store.list_by_node(["src/app/[repo]"])) == 2
+
+ def test_a_bracket_is_not_a_character_class(self, tmp_path: Path) -> None:
+ """``[repo]`` read as a pattern matches ``r``, ``e``, ``p`` and ``o``."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _bound("s1", ("src/app/r/unrelated.tsx",)),
+ _bound("s2", ("src/app/e/other.tsx",)),
+ ],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["src/app/[repo]"]) == {}
+
+ def test_star_and_question_marks_are_literal(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("docs/aXb/deep.md",))],
+ oldest_birth_at=None,
+ )
+ assert store.count_by_node(["docs/a?b"]) == {}
+ assert store.count_by_node(["docs/a*b"]) == {}
+
+
+class TestPathNormalisation:
+ """One location written four ways is one location."""
+
+ @pytest.mark.parametrize(
+ "target",
+ ["pkg/mod/a.py", "pkg\\mod\\a.py", "pkg//mod/a.py", "pkg/mod/../mod/a.py",
+ "./pkg/mod/a.py", "/pkg/mod/a.py"],
+ )
+ def test_equivalent_spellings_all_match(self, tmp_path: Path, target: str) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/mod/a.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node([target]) == {target: 1}
+
+ def test_a_path_climbing_out_of_the_repo_asks_nothing(self, tmp_path: Path) -> None:
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/a.py",))], oldest_birth_at=None
+ )
+ assert store.count_by_node(["../escape"]) == {}
+ assert store.count_by_node([""]) == {}
+
+
+class TestNodeIndexRecovery:
+ """The index is derived data; a failed build must not become permanent."""
+
+ def test_an_interrupted_build_is_rebuilt_on_the_next_open(self, tmp_path: Path) -> None:
+ """DDL is autocommit, so the table outlives a backfill that fails.
+
+ Presence alone would then read as "complete" forever, and the store
+ would answer "nothing is bound here" in the shape of the truth. The
+ trigger is created last, so its presence is what vouches for the rest.
+ """
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT, episodes=[_bound("s1", ("pkg/a.py",))], oldest_birth_at=None
+ )
+ db_path = store.db_path
+ # Exactly the state an interrupted build leaves behind.
+ store._conn.executescript(
+ "DROP TRIGGER episodes_nodes_ad; DELETE FROM episode_nodes;"
+ )
+ store._conn.commit()
+
+ with EpisodeStore(db_path) as reopened:
+ assert reopened.count_by_node(["pkg/a.py"]) == {"pkg/a.py": 1}
+
+ def test_a_store_that_cannot_build_the_index_still_answers(self, tmp_path: Path) -> None:
+ """A wrong "no history" is worse than a slow right one."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[_bound("s1", ("pkg/a.py",)), _bound("s2", ("pkg/sub/b.py",))],
+ oldest_birth_at=None,
+ )
+ store._conn.executescript(
+ "DROP TRIGGER episodes_nodes_ad; DROP TABLE episode_nodes;"
+ )
+ store._conn.commit()
+ store.node_index_enabled = False
+
+ assert store.count_by_node(["pkg/a.py"]) == {"pkg/a.py": 1}
+ assert store.count_by_node(["pkg"]) == {"pkg": 2}
+ assert store.count_by_node(["nope"]) == {}
+ assert store.count_by_node(["pkg"], tiers=SHAREABLE_TIERS) == {"pkg": 2}
+ assert len(store.list_by_node(["pkg"])) == 2
+
+ @pytest.mark.parametrize(
+ "target",
+ ["pkg/a.py", "pkg", "pkg/sub", "pkg/sub/b.py", "other", "src/app/[repo]",
+ "pkg\\a.py", "pkg/x/../a.py"],
+ )
+ def test_the_fallback_answers_what_the_index_answers(
+ self, tmp_path: Path, target: str
+ ) -> None:
+ """Two implementations of one question is one too many unless they agree."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ _bound("s1", ("pkg/a.py",)),
+ _bound("s2", ("pkg/sub/b.py",)),
+ _bound("s3", ("src/app/[repo]/page.tsx",)),
+ _bound("s4", ("pkg",)),
+ ],
+ oldest_birth_at=None,
+ )
+ indexed = store.count_by_node([target]).get(target, 0)
+ scanned = len(store._scan_by_node([target], None).get(target, []))
+ assert indexed == scanned
+
+ def test_a_non_string_node_is_filtered_the_same_way_by_both_writers(
+ self, tmp_path: Path
+ ) -> None:
+ """Or a rebuild silently answers differently from the live path."""
+ with _store(tmp_path) as store:
+ store.append_tier(
+ tier=TIER_GIT,
+ episodes=[
+ Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject="s1",
+ body="b",
+ evidence="e",
+ nodes=(123, "pkg/a.py"), # type: ignore[arg-type]
+ birth_commit="a" * 40,
+ birth_at=1000.0,
+ )
+ ],
+ oldest_birth_at=None,
+ )
+ live = store.count_by_node(["pkg/a.py"])
+ store._backfill_node_index()
+ store._conn.commit()
+ assert store.count_by_node(["pkg/a.py"]) == live
+ (rows,) = store._conn.execute(
+ "SELECT COUNT(*) FROM episode_nodes WHERE path = '123'"
+ ).fetchone()
+ assert rows == 0
diff --git a/tests/unit/server/mcp/test_answer_episodes.py b/tests/unit/server/mcp/test_answer_episodes.py
index f3ba2a0aa..4cfd0d653 100644
--- a/tests/unit/server/mcp/test_answer_episodes.py
+++ b/tests/unit/server/mcp/test_answer_episodes.py
@@ -408,8 +408,13 @@ def test_a_git_episode_whose_scope_has_not_moved_is_served(repo):
@pytest.fixture
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
+ """Count the sanctioned read-time git queries one attach makes.
+
+ Patched on the shared episode-reading module rather than on this tool: the
+ currency verdict is one implementation serving every reader, so this is
+ where the query is made from.
+ """
+ from repowise.server.mcp_server import _episodes as mod
calls: list[tuple] = []
real = mod.commits_since
diff --git a/tests/unit/server/mcp/test_why_episodes.py b/tests/unit/server/mcp/test_why_episodes.py
new file mode 100644
index 000000000..268c7bdde
--- /dev/null
+++ b/tests/unit/server/mcp/test_why_episodes.py
@@ -0,0 +1,589 @@
+"""Episodes as an evidence kind, and as a count.
+
+Two surfaces over one store. ``get_why`` serves the bodies because the reader
+asked a question; ``get_risk`` and ``get_context`` serve a single integer
+because the reader asked for a card and a paragraph would spend their budget
+whether they wanted it or not.
+
+The divergence worth holding onto is currency. The ``get_answer`` guard
+suppresses an episode whose scope has moved, because it is appending a claim
+beside an answer about the present. These tests assert the opposite for
+``get_why``: the episode is served with the movement **labelled**, because
+"what happened here" is a question about the past and a superseded episode is
+still a true answer to it.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from repowise.core.precedent.store import (
+ TIER_GIT,
+ TIER_STRUCTURAL,
+ TIER_TRANSCRIPT,
+ Episode,
+ EpisodeStore,
+ default_store_path,
+)
+from repowise.server.mcp_server._episodes import (
+ _MAX_EVIDENCE_BODY_CHARS,
+ _MAX_SCOPE_NODES,
+ bank_overflow,
+ currency,
+ enrich_episode_counts,
+ episode_counts,
+ episode_evidence,
+)
+
+
+def repo(tmp_path):
+ """A git checkout with a .repowise directory, one commit deep."""
+ root = tmp_path / "checkout"
+ (root / ".repowise").mkdir(parents=True)
+ (root / "app.py").write_text("x = 1\n", encoding="utf-8")
+ _git(root, "init", "-q")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "T")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-qm", "first")
+ return root
+
+
+def _git(root, *args):
+ subprocess.run(["git", *args], cwd=str(root), check=True, capture_output=True)
+
+
+def _head(root) -> str:
+ out = subprocess.run(
+ ["git", "rev-parse", "HEAD"], cwd=str(root), capture_output=True, text=True, check=True
+ )
+ return out.stdout.strip()
+
+
+def _fix(subject: str, nodes: tuple[str, ...], *, birth_commit: str, body: str = "a fix") -> Episode:
+ return Episode(
+ tier=TIER_GIT,
+ kind="code_fix",
+ subject=subject,
+ body=body,
+ evidence=f"commit {subject}",
+ nodes=nodes,
+ birth_commit=birth_commit,
+ birth_at=1000.0,
+ )
+
+
+def _write(root, *episodes: Episode, tier: str = TIER_GIT) -> None:
+ with EpisodeStore(default_store_path(root)) as store:
+ store.append_tier(tier=tier, episodes=list(episodes), oldest_birth_at=None)
+
+
+# -- the evidence block ------------------------------------------------------
+
+
+class TestEpisodeEvidence:
+ def test_an_episode_bound_to_the_path_is_served(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert len(entries) == 1
+ assert entries[0]["kind"] == "code_fix"
+ assert entries[0]["recorded"] == "a fix"
+ assert entries[0]["scope"] == ["app.py"]
+
+ def test_a_path_with_no_episodes_says_nothing(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ entries, pending = episode_evidence(repo, paths=["other.py"])
+ assert entries == []
+ assert pending == []
+
+ def test_a_repo_that_never_derived_episodes_is_silent(self, tmp_path):
+ """And must not grow a store because somebody asked a question."""
+ root = tmp_path / "bare"
+ (root / ".repowise").mkdir(parents=True)
+ entries, _ = episode_evidence(root, paths=["app.py"])
+ assert entries == []
+ assert not default_store_path(root).exists()
+
+ def test_asking_nothing_reads_nothing(self, repo):
+ assert episode_evidence(repo) == ([], [])
+
+ def test_a_transcript_episode_is_never_served(self, repo):
+ """Per-machine: two people asking one question would get two answers."""
+ _write(
+ repo,
+ Episode(
+ tier=TIER_TRANSCRIPT,
+ kind="session",
+ subject="s",
+ body="a session",
+ evidence="transcript",
+ nodes=("app.py",),
+ birth_at=1000.0,
+ ),
+ tier=TIER_TRANSCRIPT,
+ )
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert entries == []
+
+ def test_the_block_is_bounded(self, repo):
+ _write(
+ repo,
+ *[_fix(f"sha{i}", ("app.py",), birth_commit=_head(repo)) for i in range(10)],
+ )
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert len(entries) == 3
+
+ def test_a_long_body_is_capped_and_stays_recoverable(self, repo):
+ """A cap on a count is not a bound on a response whose fields are free text."""
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo), body="x" * 5000))
+ entries, pending = episode_evidence(repo, paths=["app.py"])
+ collector = bank_overflow(pending, tool="get_why", repo_root=repo)
+ recorded = entries[0]["recorded"]
+ # The cap plus the recovery marker, which is ~95 chars and is the
+ # point: what was cut is advertised rather than silently dropped.
+ assert recorded.startswith("x" * _MAX_EVIDENCE_BODY_CHARS)
+ assert len(recorded) < _MAX_EVIDENCE_BODY_CHARS + 150
+ assert "repowise expand" in recorded
+ assert collector is not None
+ payload: dict = {}
+ collector.attach(payload)
+ assert payload["_meta"]["omitted"]["refs"]
+
+ def test_one_collector_serves_every_capped_body(self, repo):
+ """Two collectors on one response and the second clobbers the first's refs."""
+ _write(
+ repo,
+ *[
+ _fix(f"sha{i}", ("app.py",), birth_commit=_head(repo), body="x" * 5000)
+ for i in range(3)
+ ],
+ )
+ entries, pending = episode_evidence(repo, paths=["app.py"])
+ collector = bank_overflow(pending, tool="get_why", repo_root=repo)
+ assert len(entries) == 3
+ payload: dict = {}
+ collector.attach(payload)
+ # Three identical bodies are one stored row, so one ref, counted once.
+ assert len(payload["_meta"]["omitted"]["refs"]) == 1
+
+ def test_a_query_ranks_bodies_when_there_is_no_path(self, repo):
+ _write(
+ repo,
+ _fix("sha1", ("app.py",), birth_commit=_head(repo), body="fixed the parser crash"),
+ _fix("sha2", ("other.py",), birth_commit=_head(repo), body="bumped a dependency"),
+ )
+ entries, _ = episode_evidence(repo, query="parser crash")
+ assert entries
+ assert "parser" in entries[0]["recorded"]
+
+
+# -- currency ----------------------------------------------------------------
+
+
+class TestCurrency:
+ def test_an_untouched_scope_is_current(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert "nothing in its scope has changed" in entries[0]["still_true"]
+
+ def test_a_moved_scope_is_labelled_rather_than_suppressed(self, repo):
+ """The divergence from the get_answer guard, and the reason for it.
+
+ A fix that landed and was later changed is exactly the history the
+ question asked for. Suppressing it would answer a different question.
+ """
+ born = _head(repo)
+ (repo / "app.py").write_text("x = 2\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "second")
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=born))
+
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert len(entries) == 1
+ assert "1 commit has touched its scope since" in entries[0]["still_true"]
+
+ def test_the_gate_form_still_suppresses_a_moved_scope(self, repo):
+ """get_answer's contract is unchanged by get_why's.
+
+ The two share one implementation, so this is the test that keeps the
+ shared half from being tuned for whichever caller was edited last.
+ """
+ from repowise.server.mcp_server._episodes import still_true
+
+ born = _head(repo)
+ (repo / "app.py").write_text("x = 2\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "second")
+ row = {
+ "tier": TIER_GIT,
+ "nodes": ["app.py"],
+ "birth_commit": born,
+ "birth_at": 1000.0,
+ "last_seen_at": 1000.0,
+ }
+ assert currency(row, root=repo).current is False
+ assert still_true(row, root=repo) is None
+
+ def test_only_the_top_ranked_episode_costs_a_git_query(self, repo, monkeypatch):
+ """~60 ms each, and the reader acts on the first one.
+
+ The same bound, for the same reason, that this mode already applies to
+ the decision it ranks first.
+ """
+ from repowise.server.mcp_server import _episodes as mod
+
+ calls: list = []
+ real = mod.commits_since
+
+ def counted(*args, **kwargs):
+ calls.append(args)
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(mod, "commits_since", counted)
+ _write(
+ repo,
+ *[_fix(f"sha{i}", ("app.py",), birth_commit=_head(repo)) for i in range(5)],
+ )
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert len(entries) == 3
+ assert len(calls) == 1
+
+ def test_a_re_observed_structural_fact_needs_no_git_query(self, repo, monkeypatch):
+ from repowise.server.mcp_server import _episodes as mod
+
+ calls: list = []
+ monkeypatch.setattr(mod, "commits_since", lambda *a, **k: calls.append(a))
+ with EpisodeStore(default_store_path(repo)) as store:
+ ep = Episode(
+ tier=TIER_STRUCTURAL,
+ kind="nested_repos",
+ subject=".",
+ body="8 directories are separate repos",
+ evidence="traverser",
+ nodes=("app.py",),
+ )
+ store.replace_kinds(tier=TIER_STRUCTURAL, kinds=["nested_repos"], episodes=[ep],
+ now=1000.0)
+ store._conn.execute("UPDATE episodes SET last_seen_at = ? WHERE id = ?",
+ (2000.0, ep.id))
+ store._conn.commit()
+
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert "re-observed by a later index" in entries[0]["still_true"]
+ assert calls == []
+
+ def test_a_lower_ranked_episode_makes_no_currency_claim(self, repo):
+ """An absent field beats a guess dressed as a verdict."""
+ _write(
+ repo,
+ *[_fix(f"sha{i}", ("app.py",), birth_commit=_head(repo)) for i in range(3)],
+ )
+ entries, _ = episode_evidence(repo, paths=["app.py"])
+ assert "still_true" in entries[0]
+ assert "still_true" not in entries[1]
+ assert "still_true" not in entries[2]
+
+
+# -- the count ---------------------------------------------------------------
+
+
+class TestEpisodeCounts:
+ def test_a_target_with_episodes_gets_an_integer(self, repo):
+ _write(
+ repo,
+ _fix("sha1", ("app.py",), birth_commit=_head(repo)),
+ _fix("sha2", ("app.py",), birth_commit=_head(repo)),
+ )
+ assert episode_counts(repo, ["app.py"]) == {"app.py": 2}
+
+ def test_a_target_with_none_is_absent_rather_than_zero(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ assert episode_counts(repo, ["other.py"]) == {}
+
+ def test_a_repo_without_a_store_counts_nothing_and_creates_nothing(self, tmp_path):
+ root = tmp_path / "bare"
+ (root / ".repowise").mkdir(parents=True)
+ assert episode_counts(root, ["app.py"]) == {}
+ assert not default_store_path(root).exists()
+
+ def test_transcript_episodes_are_not_counted(self, repo):
+ """The count is a shareable claim and must not depend on whose laptop it is."""
+ _write(
+ repo,
+ Episode(
+ tier=TIER_TRANSCRIPT,
+ kind="session",
+ subject="s",
+ body="a session",
+ evidence="transcript",
+ nodes=("app.py",),
+ birth_at=1000.0,
+ ),
+ tier=TIER_TRANSCRIPT,
+ )
+ assert episode_counts(repo, ["app.py"]) == {}
+
+ def test_enrichment_stamps_only_the_cards_that_have_any(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ cards = [{"target": "app.py"}, {"target": "other.py"}]
+ enrich_episode_counts(cards, repo)
+ assert cards[0]["episodes"] == 1
+ assert "episodes" not in cards[1]
+
+ def test_enrichment_survives_a_card_with_no_target(self, repo):
+ _write(repo, _fix("sha1", ("app.py",), birth_commit=_head(repo)))
+ cards = [{"error": "could not resolve"}, {"target": "app.py"}]
+ enrich_episode_counts(cards, repo)
+ assert cards[1]["episodes"] == 1
+
+
+# -- what the reviews found --------------------------------------------------
+
+
+class TestPathsWithPatternCharacters:
+ """A framework's dynamic routes are ordinary paths and must behave like it.
+
+ ``GLOB`` reads ``[id]`` as a character class and has no ``ESCAPE`` clause,
+ so the first cut matched ``repos/i`` and ``repos/d`` and missed every real
+ child. 170 rows in this repository's own store carry bracketed paths.
+ """
+
+ def test_a_bracketed_directory_finds_its_own_children(self, repo):
+ _write(
+ repo,
+ _fix("s1", ("src/app/[repo]/page.tsx",), birth_commit=_head(repo)),
+ _fix("s2", ("src/app/[repo]/layout.tsx",), birth_commit=_head(repo)),
+ )
+ assert episode_counts(repo, ["src/app/[repo]"]) == {"src/app/[repo]": 2}
+
+ def test_a_bracketed_directory_does_not_match_single_characters(self, repo):
+ """``[repo]`` as a character class matches ``r``, ``e``, ``p``, ``o``."""
+ _write(
+ repo,
+ _fix("s3", ("src/app/r/unrelated.tsx",), birth_commit=_head(repo)),
+ _fix("s4", ("src/app/e/other.tsx",), birth_commit=_head(repo)),
+ )
+ assert episode_counts(repo, ["src/app/[repo]"]) == {}
+
+ def test_star_and_question_are_literal(self, repo):
+ _write(repo, _fix("s1", ("docs/aXb/deep.md",), birth_commit=_head(repo)))
+ assert episode_counts(repo, ["docs/a?b"]) == {}
+ assert episode_counts(repo, ["docs/a*b"]) == {}
+
+
+class TestTargetShapes:
+ """What a card asks about is not always a plain repo-relative file."""
+
+ def test_a_symbol_target_is_counted_as_its_file(self, repo):
+ """Splitting on ``/`` leaves ``service.py::Name``, which matches nothing.
+
+ The count then fell through to the ancestor directory, so a symbol card
+ read as quieter than its own file — the opposite of the truth.
+ """
+ _write(
+ repo,
+ _fix("s1", ("src/auth/service.py",), birth_commit=_head(repo)),
+ _fix("s2", ("src/auth/service.py",), birth_commit=_head(repo)),
+ _fix("s3", ("src/auth",), birth_commit=_head(repo)),
+ )
+ cards = [
+ {"target": "src/auth/service.py"},
+ {"target": "src/auth/service.py::AuthService"},
+ ]
+ enrich_episode_counts(cards, repo)
+ assert cards[0]["episodes"] == cards[1]["episodes"] == 3
+
+ def test_an_unresolved_target_is_not_stamped(self, repo):
+ """A directory-bound episode matches any path beneath it, including a typo."""
+ _write(repo, _fix("s1", ("src/auth",), birth_commit=_head(repo)))
+ cards = [{"target": "src/auth/nope.py::Missing", "error": "Target not found"}]
+ enrich_episode_counts(cards, repo)
+ assert "episodes" not in cards[0]
+
+ def test_a_renamed_file_keeps_its_history(self, repo):
+ """Episodes are filed under the path the commit touched.
+
+ Without the former name a file loses its whole history the moment it
+ moves, which is exactly when an agent most wants it.
+ """
+ _write(repo, _fix("s1", ("old/name.py",), birth_commit=_head(repo)))
+ cards = [{"target": "new/name.py", "original_path": "old/name.py"}]
+ enrich_episode_counts(cards, repo)
+ assert cards[0]["episodes"] == 1
+
+ def test_a_rename_does_not_double_count_a_commit_touching_both_sides(self, repo):
+ _write(repo, _fix("s1", ("new/name.py", "old/name.py"), birth_commit=_head(repo)))
+ cards = [{"target": "new/name.py", "original_path": "old/name.py"}]
+ enrich_episode_counts(cards, repo)
+ assert cards[0]["episodes"] == 1
+
+
+class TestScopeIsBounded:
+ def test_a_sweep_commits_scope_is_capped_and_says_so(self, repo):
+ _write(
+ repo,
+ _fix("s1", tuple(f"pkg/f{i}.py" for i in range(40)), birth_commit=_head(repo)),
+ )
+ entries, _ = episode_evidence(repo, paths=["pkg/f0.py"])
+ scope = entries[0]["scope"]
+ assert len(scope) == _MAX_SCOPE_NODES + 1
+ assert scope[-1] == "… and 28 more"
+
+ def test_an_empty_scope_reads_as_the_whole_checkout(self, repo):
+ with EpisodeStore(default_store_path(repo)) as store:
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL,
+ kinds=["formatter_drift"],
+ episodes=[
+ Episode(
+ tier=TIER_STRUCTURAL,
+ kind="formatter_drift",
+ subject="ruff format",
+ body="not formatter-clean",
+ evidence="ruff",
+ nodes=(),
+ )
+ ],
+ )
+ entries, _ = episode_evidence(repo, query="formatter clean")
+ assert entries[0]["scope"] == "the checkout as a whole"
+
+
+class TestOverflowBanking:
+ """The omission store is a sqlite3 connection bound to its creating thread."""
+
+ def test_reading_banks_nothing_so_the_caller_owns_the_thread(self, repo):
+ """``episode_evidence`` runs in a worker thread; ``attach`` does not.
+
+ A collector opened there and finalised on the event loop raises inside
+ ``_put``, which swallows it — losing every banked block silently,
+ including the governing decisions the budget pass drops later.
+ """
+ _write(repo, _fix("s1", ("app.py",), birth_commit=_head(repo), body="x" * 5000))
+ entries, pending = episode_evidence(repo, paths=["app.py"])
+ assert len(pending) == 1
+ entry, label, body = pending[0]
+ assert entry is entries[0]
+ assert label == "episode:code_fix"
+ assert body == "x" * 5000
+ # Nothing was written, so nothing is advertised yet.
+ assert "repowise#" not in entries[0]["recorded"]
+
+ def test_banking_nothing_makes_no_collector(self, repo):
+ assert bank_overflow([], tool="get_why", repo_root=repo) is None
+
+
+# -- end to end --------------------------------------------------------------
+
+
+def mcp_repo(setup_mcp, repo, monkeypatch):
+ """Point the MCP server's globals at a checkout that has a real store.
+
+ The shared fixture uses a path with no store at all, so every existing
+ test short-circuits at the file-existence guard and the field could not
+ reach a response no matter what it did.
+ """
+ from repowise.server.mcp_server import _state
+
+ monkeypatch.setattr(_state, "_repo_path", str(repo))
+ return repo
+
+
+async def test_get_context_serves_the_count_on_the_target_card(mcp_repo):
+ from repowise.server.mcp_server import get_context
+
+ _write(
+ mcp_repo,
+ _fix("s1", ("src/auth/service.py",), birth_commit=_head(mcp_repo)),
+ _fix("s2", ("src/auth/service.py",), birth_commit=_head(mcp_repo)),
+ )
+ result = await get_context(["src/auth/service.py"])
+ assert result["targets"]["src/auth/service.py"]["episodes"] == 2
+
+
+async def test_get_context_omits_the_count_where_there_is_none(mcp_repo):
+ from repowise.server.mcp_server import get_context
+
+ _write(mcp_repo, _fix("s1", ("src/auth/service.py",), birth_commit=_head(mcp_repo)))
+ result = await get_context(["src/utils/helpers.py"])
+ assert "episodes" not in result["targets"]["src/utils/helpers.py"]
+
+
+async def test_get_risk_serves_the_count_on_the_target_card(mcp_repo):
+ from repowise.server.mcp_server import get_risk
+
+ _write(mcp_repo, _fix("s1", ("src/auth/service.py",), birth_commit=_head(mcp_repo)))
+ result = await get_risk(["src/auth/service.py"])
+ assert result["targets"]["src/auth/service.py"]["episodes"] == 1
+
+
+async def test_get_why_path_mode_serves_the_evidence_block(mcp_repo):
+ from repowise.server.mcp_server import get_why
+
+ _write(mcp_repo, _fix("s1", ("src/auth/service.py",), birth_commit=_head(mcp_repo)))
+ result = await get_why("src/auth/service.py")
+ assert result["mode"] == "path"
+ assert [e["kind"] for e in result["episodes"]] == ["code_fix"]
+ assert result["episodes"][0]["still_true"]
+
+
+async def test_a_transcript_episode_reaches_no_surface(mcp_repo):
+ """The tier allowlist, asserted on the payload rather than left as a comment."""
+ from repowise.server.mcp_server import get_context, get_why
+
+ _write(
+ mcp_repo,
+ Episode(
+ tier=TIER_TRANSCRIPT,
+ kind="session",
+ subject="s",
+ body="a session that touched it",
+ evidence="transcript",
+ nodes=("src/auth/service.py",),
+ birth_at=1000.0,
+ ),
+ tier=TIER_TRANSCRIPT,
+ )
+ ctx = await get_context(["src/auth/service.py"])
+ assert "episodes" not in ctx["targets"]["src/auth/service.py"]
+ why = await get_why("src/auth/service.py")
+ assert "episodes" not in why
+
+
+async def test_a_repo_without_a_store_is_unchanged(setup_mcp):
+ """The default fixture path has no store; every response must be as before."""
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["src/auth/service.py"])
+ assert "episodes" not in result["targets"]["src/auth/service.py"]
+
+
+async def test_a_capped_body_is_banked_from_the_thread_that_attaches(mcp_repo):
+ """The read runs in a worker thread; the omission store must not.
+
+ A collector opened on the worker and finalised on the event loop raises
+ inside ``_put``, which swallows the error and silently drops every banked
+ block. The marker arriving is the proof it did not.
+ """
+ from repowise.server.mcp_server import get_why
+
+ _write(
+ mcp_repo,
+ _fix("s1", ("src/auth/service.py",), birth_commit=_head(mcp_repo), body="y" * 5000),
+ )
+ result = await get_why("src/auth/service.py")
+ recorded = result["episodes"][0]["recorded"]
+ assert recorded.startswith("y" * _MAX_EVIDENCE_BODY_CHARS)
+ assert "repowise#" in recorded
+ assert result["_meta"]["omitted"]["refs"]