Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(episodes): serve recorded episodes over HTTP (#1346)
Raghav Chamadiya8acedf780406
diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex 69767b7fd..0ce09b97e 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -20,6 +20,7 @@"./coupling": "./src/coupling.ts","./dead-code": "./src/dead-code.ts","./decisions": "./src/decisions.ts",+ "./episodes": "./src/episodes.ts","./external-systems": "./src/external-systems.ts","./feedback": "./src/feedback.ts","./files": "./src/files.ts",diff --git a/packages/api-client/src/episodes.ts b/packages/api-client/src/episodes.tsnew file mode 100644index 000000000..45d813450--- /dev/null+++ b/packages/api-client/src/episodes.ts@@ -0,0 +1,89 @@+/**+ * Episode endpoints — the dated things that happened to a repository.+ *+ * Types come from `@repowise-dev/types/episodes` rather than this package's+ * local `./types`, following the direction `coupling`, `files` and+ * `blast-radius` already took; this module re-exports them so a consumer+ * needs one import.+ */+import { apiGet } from "./client";+import type {+ EpisodeCountsResponse,+ EpisodeDetail,+ EpisodeListResponse,+ EpisodeSummary,+ EpisodeTier,+} from "@repowise-dev/types/episodes";++export type {+ EpisodeCountsResponse,+ EpisodeDetail,+ EpisodeListResponse,+ EpisodeSummary,+ EpisodeTier,+};++/**+ * A page of episodes, newest first and without their bodies.+ *+ * Costs no git call, so it is safe to render a long list from. Open one+ * through `getEpisode` for the body and the checked currency verdict.+ *+ * A repository that has never derived episodes answers 200 with+ * `available: false` — check that before treating an empty `episodes` as+ * "everything was pruned".+ */+export async function listEpisodes(+ repoId: string,+ opts?: {+ /** Narrows to one tier. An unknown tier selects nothing, never all. */+ tier?: EpisodeTier;+ /** e.g. `code_fix`, `nested_repos`. */+ kind?: string;+ limit?: number;+ offset?: number;+ },+): Promise<EpisodeListResponse> {+ return apiGet<EpisodeListResponse>(`/api/repos/${repoId}/episodes`, opts);+}++/** Totals by tier and by kind, grouped server-side so the number is measured. */+export async function getEpisodeCounts(+ repoId: string,+): Promise<EpisodeCountsResponse> {+ return apiGet<EpisodeCountsResponse>(`/api/repos/${repoId}/episodes/counts`);+}++/**+ * Episodes bound at, above or below `path` — what happened to this file.+ *+ * `total` is the count for that path, so a file page can state a measured+ * number rather than the size of the window it fetched.+ */+export async function listEpisodesByFile(+ repoId: string,+ path: string,+ opts?: { limit?: number },+): Promise<EpisodeListResponse> {+ // `path` last: excess-property checking only fires on object literals, so a+ // caller passing a wider state object that happens to carry its own `path`+ // would otherwise clobber the argument and this page would confidently show+ // another file's history under a measured-looking total.+ return apiGet<EpisodeListResponse>(`/api/repos/${repoId}/episodes/by-file`, {+ ...opts,+ path,+ });+}++/**+ * One episode, whole, with `still_true` answered against the live checkout.+ *+ * The only episode call that shells out to git (~60 ms). Never call it per+ * row to decorate a list — `listEpisodes` already carries the free signal.+ */+export async function getEpisode(+ repoId: string,+ episodeId: string,+): Promise<EpisodeDetail> {+ return apiGet<EpisodeDetail>(`/api/repos/${repoId}/episodes/${episodeId}`);+}diff --git a/packages/core/src/repowise/core/precedent/currency.py b/packages/core/src/repowise/core/precedent/currency.pyindex 14906a756..c66e8208d 100644--- a/packages/core/src/repowise/core/precedent/currency.py+++ b/packages/core/src/repowise/core/precedent/currency.py@@ -10,6 +10,14 @@ Two shapes of claim ask it. An **episode** is born at a commit, so it askshandling, one implementation; the alternative was a second copy that woulddrift from this one the first time either grew a flag.+The episode half lived in ``server.mcp_server._episodes`` while MCP was its+only reader. It moved here when the HTTP layer became a third caller, because+the alternative was two implementations of one verdict and this layer has+already paid for that lesson once. The reason it was over there still holds+for what stayed: ``quote_body`` and ``episode_evidence`` reach into the MCP+budget helpers, and this module must not — it imports the store and nothing+heavier, so the import-budget probe stays clean.+Cost, measured on this checkout (1,011 commits): 55-66 ms cold and warm. Thatis 0.5% of a ``get_answer`` synthesis and fine there. It is **not** fine on ahook path (155 ms total budget) or on ``update`` (a 200 ms ceiling), and no@@ -22,16 +30,44 @@ count is worse than no answer, so the caller decides what silence means.from __future__ import annotationsimport subprocess+import timefrom collections.abc import Sequence+from dataclasses import dataclassfrom datetime import datetimefrom pathlib import Path-__all__ = ["commits_since", "describe_decision_currency"]+from repowise.core.precedent.store import TIER_STRUCTURAL++__all__ = [+ "EPISODE_GIT_TIMEOUT_S",+ "GIT_TIMEOUT_S",+ "RE_DERIVED_TIERS",+ "Currency",+ "commits_since",+ "describe_decision_currency",+ "episode_currency",+ "episode_still_true",+ "free_currency",+ "recorded_on",+ "short",+]#: Hard ceiling on the one subprocess. Generous against the 55-66 ms measured#: here, because a large repository is slower and a timeout costs the answer.GIT_TIMEOUT_S = 5.0+#: The episode readers' tighter ceiling, and deliberately not the one above.+#: They ask inside a response a user is waiting on, where saying nothing beats+#: waiting five seconds; the decision path answers one record on demand.+EPISODE_GIT_TIMEOUT_S = 2.0++#: 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})+def commits_since(root: Path | str,@@ -116,3 +152,153 @@ def describe_decision_currency(return f"nothing in the {files} it governs has changed since {on}"commits = "1 commit" if count == 1 else f"{count} commits"return f"the {files} it governs changed in {commits} since {on}"+++def recorded_on(birth_at: float) -> str:+ """The birth stamp as a date, or a phrase when there is no usable one.++ ``birth_at`` is a bare ``REAL`` in an untyped SQLite column, so no writer+ can be assumed to have put a sane value there. ``time.gmtime`` raises+ ``OSError`` outside ``time_t``, ``OverflowError`` on an infinity and+ ``ValueError`` on NaN, and this runs inside a sentence a reader is being+ shown — a bad row must cost its own date, never the whole response.+ """+ if not birth_at:+ return "at an unknown date"+ try:+ return time.strftime("%Y-%m-%d", time.gmtime(birth_at))+ except (OSError, OverflowError, ValueError):+ return "at an unknown date"+++def short(sha: str) -> str:+ return sha[:12]+++@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 three 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 episode_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.++ **Costs one subprocess in the node-scoped and repo-wide branches**, ~60 ms+ on this checkout. No caller may run it per row of a list; see+ :func:`free_currency` for the form that is free.+ """+ 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=EPISODE_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=EPISODE_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 episode_still_true(row: dict, *, root: Path) -> str | None:+ """The gate form of :func:`episode_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 = episode_currency(row, root=root)+ return verdict.sentence if verdict.current else None+++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.++ This is the only form a list may use. :func:`episode_currency` shells out+ to git per row, so a page of fifty would be three seconds of subprocess.+ """+ 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 Nonediff --git a/packages/core/src/repowise/core/precedent/store.py b/packages/core/src/repowise/core/precedent/store.pyindex 538cd7ae1..a9daa4e7e 100644--- a/packages/core/src/repowise/core/precedent/store.py+++ b/packages/core/src/repowise/core/precedent/store.py@@ -47,6 +47,13 @@ TIER_TRANSCRIPT = "transcript"#: exists only on the laptop that recorded it.SHAREABLE_TIERS = (TIER_STRUCTURAL, TIER_GIT)+# Pinned, because a hand-written TypeScript union mirrors this set+# (``packages/types/src/episodes.ts``) and the HTTP layer narrows a response+# field to it. Adding a tier here without widening that union ships a type+# that lies to every consumer, and nothing on either side would fail. Change+# both, or neither.+assert SHAREABLE_TIERS == (TIER_STRUCTURAL, TIER_GIT)+#: Rows not re-observed for this long are dropped. Every index refreshes#: ``last_seen_at`` for a fact that still holds, so this evicts only episodes#: whose repository has stopped being indexed — never a live one. (Contrast@@ -644,28 +651,21 @@ class EpisodeStore:# -- reads -------------------------------------------------------------- def list_episodes(+ def _filter(self,*,- tier: str | None = None,- tiers: Sequence[str] | None = None,- kind: str | None = None,- subjects: Sequence[str] | None = None,- ) -> list[dict]:- """Episodes, newest birth first. Every filter is optional and ANDed.-- *tiers* is the allowlist form, for a reader that must name the tiers it- is willing to serve rather than take whatever the store happens to- hold — a new tier is then invisible to it until somebody decides- otherwise, which is the opposite of the default it replaced.-- An empty *tiers* or *subjects* selects nothing, which is the honest- reading of an empty allowlist and not the same as ``None``.+ tier: str | None,+ tiers: Sequence[str] | None,+ kind: str | None,+ subjects: Sequence[str] | None,+ ) -> tuple[str, list[object]] | None:+ """The shared ``WHERE`` for the filtered reads, or None to select nothing.++ ``None`` rather than an empty clause, because an empty *tiers* or+ *subjects* allowlist selects nothing and a caller that turned that into+ ``WHERE 1=1`` would serve the whole store on an empty allowlist — the+ exact inversion the allowlist exists to prevent."""- sql = (- "SELECT id, tier, kind, subject, body, evidence, nodes, "- "birth_commit, birth_at, last_seen_at FROM episodes"- )clauses: list[str] = []params: list[object] = []if tier is not None:@@ -673,7 +673,7 @@ class EpisodeStore:params.append(tier)if tiers is not None:if not tiers:- return []+ return Noneclauses.append(f"tier IN ({','.join('?' * len(tiers))})")params.extend(tiers)if kind is not None:@@ -681,7 +681,7 @@ class EpisodeStore:params.append(kind)if subjects is not None:if not subjects:- return []+ return Noneif len(subjects) > _IN_CHUNK:# Chunking a SELECT would mean stitching pages back into one# ordering; the callers that filter by subject ask about the@@ -691,10 +691,149 @@ class EpisodeStore:)clauses.append(f"subject IN ({','.join('?' * len(subjects))})")params.extend(subjects)- if clauses:- sql += " WHERE " + " AND ".join(clauses)- sql += " ORDER BY birth_at DESC, id ASC"- return [_row_to_dict(row) for row in self._conn.execute(sql, params)]+ where = (" WHERE " + " AND ".join(clauses)) if clauses else ""+ return where, params++ def list_episodes(+ self,+ *,+ tier: str | None = None,+ tiers: Sequence[str] | None = None,+ kind: str | None = None,+ subjects: Sequence[str] | None = None,+ limit: int | None = None,+ offset: int = 0,+ with_body: bool = True,+ ) -> list[dict]:+ """Episodes, newest birth first. Every filter is optional and ANDed.++ *tiers* is the allowlist form, for a reader that must name the tiers it+ is willing to serve rather than take whatever the store happens to+ hold — a new tier is then invisible to it until somebody decides+ otherwise, which is the opposite of the default it replaced.++ An empty *tiers* or *subjects* selects nothing, which is the honest+ reading of an empty allowlist and not the same as ``None``.++ *limit* / *offset* page it, and either works alone — an *offset* with+ no *limit* means "the rest", not "everything", which is the trap the+ obvious implementation sets. Unpaged is still the default because the+ three in-process callers want the whole selection, but a caller+ serving a page must bound it: the per-tier cap is+ :data:`DEFAULT_MAX_ROWS` and git bodies run to hundreds of characters+ each, so the unbounded read is multi-megabyte at the ceiling.++ Ordering is ``(birth_at DESC, id ASC)`` and ``id`` is the primary key,+ so it is a total order and paging cannot duplicate or skip a row when+ births tie. There is no index on ``birth_at``, so each page sorts the+ filtered set in a temp b-tree — affordable only because of that cap,+ and cheaper with *with_body* off.++ *with_body* set false drops the ``body`` key entirely rather than+ blanking it, so a reader cannot mistake "not fetched" for "empty". The+ column is never read — the projection substitutes a constant — which+ is the point: a timeline row needs the date, the subject and the+ scope, and the body belongs to whatever opens one.+ """+ built = self._filter(tier=tier, tiers=tiers, kind=kind, subjects=subjects)+ if built is None:+ return []+ where, params = built+ body_col = "body" if with_body else "''"+ sql = (+ f"SELECT id, tier, kind, subject, {body_col}, evidence, nodes, "+ f"birth_commit, birth_at, last_seen_at FROM episodes{where}"+ " ORDER BY birth_at DESC, id ASC"+ )+ if limit is not None or offset:+ # SQLite has no bare OFFSET, so an offset without a limit needs a+ # sentinel. -1 is its own "unbounded" and is the honest one here;+ # a caller paging from an offset with no limit means "the rest",+ # not "nothing". Clamped limits stay >= 0 so a negative limit+ # returns no rows rather than inheriting that unbounded meaning.+ bound = -1 if limit is None else max(0, limit)+ sql += " LIMIT ? OFFSET ?"+ params = [*params, bound, max(0, offset)]+ rows = [_row_to_dict(row) for row in self._conn.execute(sql, params)]+ if not with_body:+ for row in rows:+ del row["body"]+ return rows++ def group_counts(+ self, column: str, *, tiers: Sequence[str] | None = None+ ) -> dict[str, int]:+ """``COUNT(*) GROUP BY column``, for a caller that needs a breakdown.++ *column* is checked against a literal allowlist rather than escaped: it+ is interpolated into the statement because a column name cannot be+ bound as a parameter, and an allowlist is the only form of that which+ is safe by construction rather than by review.++ Grouped in SQL rather than counted in Python, because the caller that+ wants this is rendering a summary and the alternative is materialising+ every row in the store to add up two integers.+ """+ if column not in {"tier", "kind"}:+ raise ValueError(f"group_counts takes 'tier' or 'kind', got {column!r}")+ built = self._filter(tier=None, tiers=tiers, kind=None, subjects=None)+ if built is None:+ return {}+ where, params = built+ sql = f"SELECT {column}, COUNT(*) FROM episodes{where} GROUP BY {column}"+ return {str(name): int(n) for name, n in self._conn.execute(sql, params)}++ def get_episode(+ self, episode_id: str, *, tiers: Sequence[str] | None = None+ ) -> dict | None:+ """One episode by id, or None — including when its tier is not allowed.++ The tier allowlist is applied here rather than by the caller because+ forgetting it on a by-id read is the same disclosure as forgetting it+ on a list, with none of the visibility: one row, addressable by a+ stable hash, is exactly the shape somebody guesses at.++ Built through :meth:`_filter` rather than with its own tier clause, so+ there is exactly one implementation of "which tiers may be read". A+ second copy here is how a later change to the allowlist reaches the+ list and misses the by-id read.+ """+ built = self._filter(tier=None, tiers=tiers, kind=None, subjects=None)+ if built is None:+ return None+ where, params = built+ clause = f"{where} AND id = ?" if where else " WHERE id = ?"+ sql = (+ "SELECT id, tier, kind, subject, body, evidence, nodes, "+ f"birth_commit, birth_at, last_seen_at FROM episodes{clause}"+ )+ row = self._conn.execute(sql, [*params, episode_id]).fetchone()+ return _row_to_dict(row) if row else None++ def count_episodes(+ self,+ *,+ tier: str | None = None,+ tiers: Sequence[str] | None = None,+ kind: str | None = None,+ subjects: Sequence[str] | None = None,+ ) -> int:+ """How many episodes the same filters select.++ Separate from :meth:`count` because a paged reader has to state a total+ it measured rather than the length of the page it happened to fetch,+ and separate from counting the page for the reason the decisions+ endpoint already learned: a capped list reported "97 of 100" on a+ repository holding several hundred records.+ """+ built = self._filter(tier=tier, tiers=tiers, kind=kind, subjects=subjects)+ if built is None:+ return 0+ where, params = built+ (rows,) = self._conn.execute(+ f"SELECT COUNT(*) FROM episodes{where}", params+ ).fetchone()+ return int(rows)def search(self,@@ -810,7 +949,8 @@ class EpisodeStore: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()}+ scanned = self._scan_by_node(paths, tiers, with_body=False)+ return {p: len(rows) for p, rows in scanned.items()}counts: dict[str, int] = {}for path in paths:sub, params = self._node_subquery(path)@@ -884,7 +1024,11 @@ class EpisodeStore:return [_row_to_dict(row) for row in rows]def _scan_by_node(- self, paths: Sequence[str], tiers: Sequence[str] | None+ self,+ paths: Sequence[str],+ tiers: Sequence[str] | None,+ *,+ with_body: bool = True,) -> dict[str, list[dict]]:"""The pre-index implementation, kept as the fallback. Never raises.@@ -894,9 +1038,13 @@ class EpisodeStore:5,000-row cap, versus 1.6 ms indexed), which is the right trade againstthe alternative: answering "nothing is bound here" in the same shape asthe truth, on a surface whose whole job is to say what happened.++ *with_body* exists for :meth:`count_by_node`, whose fallback otherwise+ materialises every body in the store to return integers and throw the+ text away — megabytes allocated per call at the cap, for nothing."""try:- rows = self.list_episodes(tiers=tiers)+ rows = self.list_episodes(tiers=tiers, with_body=with_body)except sqlite3.Error:_log.debug("episode node scan failed", exc_info=True)return {}diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 8ace2eb7b..891d2c316 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -39,6 +39,7 @@ from repowise.server.routers import (coupling,dead_code,decisions,+ episodes,external_systems,feedback,files,@@ -483,6 +484,7 @@ def create_app() -> FastAPI:app.include_router(coupling.router)app.include_router(claude_md.router)app.include_router(decisions.router)+ app.include_router(episodes.router)app.include_router(chat.router)app.include_router(providers.router)app.include_router(mcp.router)diff --git a/packages/server/src/repowise/server/mcp_server/_episodes.py b/packages/server/src/repowise/server/mcp_server/_episodes.pyindex 982b3f989..08a36bf86 100644--- a/packages/server/src/repowise/server/mcp_server/_episodes.py+++ b/packages/server/src/repowise/server/mcp_server/_episodes.py@@ -14,20 +14,39 @@ MCP budget helpers.from __future__ import annotationsimport logging-import timefrom collections.abc import Sequence-from dataclasses import dataclassfrom pathlib import Path-from repowise.core.precedent.currency import commits_since+from repowise.core.precedent.currency import (+ episode_currency as currency,+)+from repowise.core.precedent.currency import (+ episode_still_true as still_true,+)+from repowise.core.precedent.currency import (+ free_currency as _free_currency,+)from repowise.core.precedent.store import (SHAREABLE_TIERS,- TIER_STRUCTURAL,EpisodeStore,default_store_path,)from repowise.server.mcp_server._budget import OmissionCollector+#: Declared because three of these are re-exports. ``currency`` /+#: ``still_true`` / ``_free_currency`` moved to ``core.precedent.currency``+#: when the HTTP layer became a third caller, and the names are kept here so+#: this module's own callers did not have to move with them.+__all__ = [+ "SERVED_TIERS",+ "bank_overflow",+ "currency",+ "enrich_episode_counts",+ "episode_evidence",+ "quote_body",+ "still_true",+]+_log = logging.getLogger(__name__)#: How many episodes an evidence block carries. Small on purpose: this is the@@ -58,122 +77,12 @@ _MAX_SCOPE_NODES = 12#: 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+#: ``currency`` / ``still_true`` / ``_free_currency`` are imported above rather+#: than defined here. They moved to ``core.precedent.currency`` when the HTTP+#: layer became a third caller; the names are kept so this module's callers did+#: not have to move with them.-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 Nonedef quote_body(@@ -415,28 +324,3 @@ def enrich_episode_counts(results: Sequence[dict], root: Path) -> None: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/routers/episodes.py b/packages/server/src/repowise/server/routers/episodes.pynew file mode 100644index 000000000..1122ff6de--- /dev/null+++ b/packages/server/src/repowise/server/routers/episodes.py@@ -0,0 +1,305 @@+"""/api/repos/{repo_id}/episodes — the dated things that happened to the code.++Reads the sidecar episode store (``.repowise/episodes/episodes.db``), not the+SQLAlchemy wiki database, so every handler here resolves the repository's+checkout first and degrades to ``available: false`` when there is nothing on+disk. That is the convention the distill-savings endpoint set for a sidecar+store, and it is what lets a dashboard render a real cold-start state instead+of an error boundary.++Three constraints are inherited rather than re-decided, and each one has cost+somebody a defect already:++**Shareable tiers only.** ``SERVED_TIERS`` excludes the transcript tier, which+is per-machine — two people opening the same repository's dashboard would+otherwise see different pages, and one of them would see sessions the other+never ran.++**The store is never opened to answer a question.** ``EpisodeStore.__init__``+creates the database and runs the schema, so constructing it on a repository+that has never derived episodes would grow a database as a side effect of a+page load. Every handler checks ``is_file()`` first.++**Currency is asked once, on the detail route only.** ``episode_currency``+shells out to ``git rev-list`` at roughly 60 ms; a fifty-row page asking per+row would be three seconds of subprocess. The list routes carry+``free_currency`` instead, which answers from stamps already in the row.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence import crud+from repowise.core.precedent.currency import episode_currency, free_currency+from repowise.core.precedent.store import EpisodeStore, default_store_path+from repowise.server.deps import get_db_session, verify_api_key+from repowise.server.mcp_server._episodes import SERVED_TIERS+from repowise.server.schemas import (+ EpisodeCountsResponse,+ EpisodeDetail,+ EpisodeListResponse,+ EpisodeSummary,+)++_log = logging.getLogger(__name__)++router = APIRouter(+ prefix="/api/repos",+ tags=["episodes"],+ dependencies=[Depends(verify_api_key)],+)++#: Rows one page may hold. The store's own per-tier ceiling is 5,000 and git+#: bodies run to hundreds of characters, so an unbounded page is a multi-+#: megabyte response; summaries carry no body, which is what makes even the+#: maximum affordable.+_MAX_PAGE = 200++#: Episodes returned for one file. Small because this answers "what happened+#: here" beside a file, where a reader takes the recent ones — not an archive.+_MAX_BY_FILE = 20+++async def _repo_root(session: AsyncSession, repo_id: str) -> Path | None:+ """The repository's checkout, or None when there is nothing to read.++ 404s only for a repository that does not exist. A repository that exists+ but has no usable local path is not an error — it is a repository this+ server cannot read a sidecar store for, which the caller renders as an+ unavailable feature rather than a failure.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ if not repo.local_path:+ return None+ return Path(repo.local_path)+++@contextmanager+def _open_store(root: Path | None) -> Iterator[EpisodeStore | None]:+ """The store, or None when there is none to open.++ **This does not open read-only, and the distinction matters.** The+ existence check keeps a read from *creating* a store, which is the+ invariant worth having: a repository that never derived episodes must not+ grow a database because somebody loaded a page. But once the file exists,+ ``EpisodeStore.__init__`` runs the schema script and will rebuild a+ missing FTS or node index, so a GET here can perform DDL and a backfill.+ That is bounded (it happens once, then the objects exist) and it is the+ same constructor every other reader uses, but it is not "read-only" and+ calling it that would be the kind of comment this layer has been burned+ by. A genuinely read-only open belongs with the store, not here.+ """+ if root is None:+ yield None+ return+ store_path = default_store_path(root)+ if not store_path.is_file():+ yield None+ return+ try:+ store = EpisodeStore(store_path)+ except Exception:+ _log.warning("episode store open failed for %s", store_path, exc_info=True)+ yield None+ return+ try:+ yield store+ finally:+ store.close()+++def _read(root: Path | None, fn, default):+ """Run one store read, degrading to *default* on any failure.++ The open guard above catches a store that cannot be opened; this catches+ one that opens and then fails on a query. The realistic case is not+ corruption but ``SQLITE_BUSY`` past the 5 s timeout — a dashboard polling+ while an index writes episodes — and a 500 on the page for that would be+ a worse outcome than the feature saying it has nothing.+ """+ with _open_store(root) as store:+ if store is None:+ return default+ try:+ return fn(store)+ except Exception:+ _log.warning("episode store read failed", exc_info=True)+ return default++[email protected]("/{repo_id}/episodes", response_model=EpisodeListResponse)+async def list_episodes(+ repo_id: str,+ tier: str | None = Query(None, description="Filter to one tier: structural | git"),+ kind: str | None = Query(None, description="Filter to one kind, e.g. code_fix"),+ limit: int = Query(50, ge=1, le=_MAX_PAGE),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> EpisodeListResponse:+ """A page of episodes, newest first, without their bodies.++ Zero git calls by construction: the only currency shown is the one derived+ from stamps already in the row. Runs inline rather than on a worker thread+ because the work is two bounded SQLite reads, matching the other sidecar+ readers in this package; the detail route below is the one that threads,+ because it shells out. Bounded rather than indexed — there is no index on+ ``birth_at``, so each page sorts the filtered set in a temp b-tree, which+ the store's own row cap is what makes affordable.+ """+ root = await _repo_root(session, repo_id)+ tiers = _tier_allowlist(tier)++ def read(store: EpisodeStore) -> tuple[int, list[dict]]:+ return (+ store.count_episodes(tiers=tiers, kind=kind),+ store.list_episodes(+ tiers=tiers, kind=kind, limit=limit, offset=offset, with_body=False+ ),+ )++ got = _read(root, read, None)+ if got is None:+ return EpisodeListResponse(available=False)+ total, rows = got+ return EpisodeListResponse(+ total=total,+ episodes=[EpisodeSummary.from_row(r, still_true=free_currency(r)) for r in rows],+ )++[email protected]("/{repo_id}/episodes/counts", response_model=EpisodeCountsResponse)+async def episode_counts(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> EpisodeCountsResponse:+ """Totals by tier and by kind.++ Declared above ``/{episode_id}`` deliberately: FastAPI matches in+ declaration order, so below it "counts" would be looked up as an episode+ id — the same trap the decisions router documents.+ """+ root = await _repo_root(session, repo_id)++ def read(store: EpisodeStore) -> tuple[dict[str, int], dict[str, int]]:+ return (+ store.group_counts("tier", tiers=SERVED_TIERS),+ store.group_counts("kind", tiers=SERVED_TIERS),+ )++ got = _read(root, read, None)+ if got is None:+ return EpisodeCountsResponse(available=False)+ by_tier, by_kind = got+ return EpisodeCountsResponse(+ total=sum(by_tier.values()), by_tier=by_tier, by_kind=by_kind+ )++[email protected]("/{repo_id}/episodes/by-file", response_model=EpisodeListResponse)+async def episodes_by_file(+ repo_id: str,+ path: str = Query(..., description="Repo-relative file or directory path"),+ limit: int = Query(_MAX_BY_FILE, ge=1, le=_MAX_PAGE),+ session: AsyncSession = Depends(get_db_session),+) -> EpisodeListResponse:+ """Episodes bound at, above or below *path*, newest first.++ Normally served through the store's node index — 0.22 ms against 22 ms for+ a scan over the JSON scope column at the store's row cap. ``total`` is the+ count for this path, which is what makes the number on a file page a+ measured one rather than the size of the window.++ **Threaded, unlike the other list routes, and the index is why.** When+ :meth:`~EpisodeStore._ensure_node_index` cannot build the index — a+ read-only database, a disk error — both reads silently fall back to a full+ scan. That path is the one thing here that can take tens of milliseconds,+ so it does not get to sit on the event loop; the store, not this route,+ decides which one runs.+ """+ root = await _repo_root(session, repo_id)++ def read(store: EpisodeStore) -> tuple[int, list[dict]]:+ return (+ store.count_by_node([path], tiers=SERVED_TIERS).get(path, 0),+ store.list_by_node([path], tiers=SERVED_TIERS, limit=limit),+ )++ got = await asyncio.to_thread(_read, root, read, None)+ if got is None:+ return EpisodeListResponse(available=False)+ total, rows = got+ return EpisodeListResponse(+ total=total,+ episodes=[EpisodeSummary.from_row(r, still_true=free_currency(r)) for r in rows],+ )++[email protected]("/{repo_id}/episodes/{episode_id}", response_model=EpisodeDetail)+async def get_episode(+ repo_id: str,+ episode_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> EpisodeDetail:+ """One episode, whole, with the currency question actually asked of git.++ The only route here that spends a subprocess, and it spends exactly one.+ It runs on a worker thread for that reason — the convention this package+ already applies to every episode read that shells out.++ Two 404s with different wording, because this is the one route where the+ difference decides what a client does next: a repository with no episode+ store at all is a feature that has nothing here, while an unknown id on a+ populated store is a bad request worth not retrying. The list routes make+ the same distinction with ``available``, which a single-object response+ has no room for.+ """+ root = await _repo_root(session, repo_id)+ if not _has_store(root):+ raise HTTPException(status_code=404, detail="No episodes recorded for this repository")+ row = await asyncio.to_thread(_load_episode, root, episode_id)+ if row is None:+ raise HTTPException(status_code=404, detail="Episode not found")+ verdict, current = row.pop("_verdict")+ return EpisodeDetail.from_row(row, sentence=verdict, current=current)+++def _has_store(root: Path | None) -> bool:+ """Whether this repository has an episode store at all. Never creates one."""+ return root is not None and default_store_path(root).is_file()+++def _load_episode(root: Path | None, episode_id: str) -> dict | None:+ """The row plus its git verdict, or None. Blocking; call on a thread."""+ if root is None:+ return None+ row = _read(root, lambda s: s.get_episode(episode_id, tiers=SERVED_TIERS), None)+ if row is None:+ return None+ # Asked outside the store context: the git query needs the checkout, not+ # the database, and holding a SQLite handle open across a subprocess buys+ # nothing.+ verdict = episode_currency(row, root=root)+ row["_verdict"] = (verdict.sentence, verdict.current)+ return row+++def _tier_allowlist(tier: str | None) -> tuple[str, ...]:+ """The tiers to serve, narrowed by *tier* but never widened past the set.++ An unknown or non-shareable tier selects nothing rather than everything,+ which is the difference between a filter that returns an empty page and+ one that quietly serves the transcript tier to a stranger.+ """+ if tier is None:+ return tuple(SERVED_TIERS)+ return (tier,) if tier in SERVED_TIERS else ()diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex b063760a3..e0eb31776 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -58,6 +58,12 @@ from .decisions import (DecisionRecordResponse,DecisionStatusUpdate,)+from .episodes import (+ EpisodeCountsResponse,+ EpisodeDetail,+ EpisodeListResponse,+ EpisodeSummary,+)from .external_systems import (ExternalSystemEntry,ExternalSystemsResponse,@@ -278,6 +284,10 @@ __all__ = ["DistillSavingsGroup","DistillSavingsResponse","EgoGraphResponse",+ "EpisodeCountsResponse",+ "EpisodeDetail",+ "EpisodeListResponse",+ "EpisodeSummary","ExecutionFlowEntry","ExecutionFlowsResponse","ExternalSystemEntry",diff --git a/packages/server/src/repowise/server/schemas/episodes.py b/packages/server/src/repowise/server/schemas/episodes.pynew file mode 100644index 000000000..3f60e8bbd--- /dev/null+++ b/packages/server/src/repowise/server/schemas/episodes.py@@ -0,0 +1,154 @@+"""Episode response models — the dated things that happened to a repository.++Three shapes, and the split between them is a cost decision rather than a+presentational one. A **summary** carries no body and asks git nothing, so a+page of them is one indexed SQLite read. A **detail** carries the body and+spends the one ``git rev-list`` the currency answer needs. **Counts** are a+grouped aggregate, so a caller can state a total it measured instead of the+length of whatever page it happened to fetch.++Every response carries ``available``. A repository that has never derived+episodes is a normal 200 with ``available: false`` — not a 404, which would be+untrue (the repository exists), and not an empty list, which would be+indistinguishable from a repository whose episodes were all pruned. This+follows the sidecar-store convention the distill-savings endpoint already set.+"""++from __future__ import annotations++from datetime import UTC, datetime++from pydantic import BaseModel++#: Ceiling on the scope listed in a summary row. The measured worst case on+#: this repository's shareable tiers is 23 paths, and a sweep commit is allowed+#: to name a hundred, so the list is trimmed and ``node_count`` carries the+#: real total beside it. A cap without the count beside it is a silent lie+#: about coverage.+MAX_SUMMARY_NODES = 12+++def _iso(ts: float | None) -> str | None:+ """An epoch stamp as ISO-8601 UTC, or None when there is no usable date.++ Every failure returns None rather than raising, and that is the whole+ point of the guard. ``birth_at`` is a bare ``REAL`` in an untyped SQLite+ column, so the response layer cannot assume any writer put a sane value+ there — an older repowise, an imported history with a year-10000 author+ date, or a hand-edited store are all enough. ``datetime.fromtimestamp``+ raises ``OSError`` outside ``time_t`` on Windows, ``OverflowError`` on+ infinities and ``ValueError`` on NaN, and an unguarded call takes down the+ whole page rather than the one row: a single bad stamp anywhere in the+ page would 500 the list.+ """+ if not ts:+ return None+ try:+ return datetime.fromtimestamp(ts, tz=UTC).isoformat()+ except (OSError, OverflowError, ValueError):+ return None+++class EpisodeSummary(BaseModel):+ """One timeline row. No body, and no git call was made to build it."""++ id: str+ tier: str+ kind: str+ subject: str+ evidence: str+ # The scope, trimmed to MAX_SUMMARY_NODES. `node_count` is the untrimmed+ # total, so a reader can tell "bound to 3 files" from "bound to 3 of 85".+ nodes: list[str]+ node_count: int+ birth_commit: str | None+ birth_at: str | None+ last_seen_at: str | None+ # The currency signal that costs nothing: a structural fact re-observed by+ # a later index vouches for itself. Absent on every tier that accumulates+ # members, where the same stamp proves nothing — see `free_currency`. A+ # row without it is not stale, it is unchecked, and the detail endpoint is+ # where checking happens.+ still_true: str | None = None++ @classmethod+ def from_row(cls, row: dict, *, still_true: str | None = None) -> EpisodeSummary:+ nodes = [n for n in (row.get("nodes") or []) if isinstance(n, str) and n]+ return cls(+ id=row["id"],+ tier=row["tier"],+ kind=row["kind"],+ subject=row["subject"],+ evidence=row.get("evidence") or "",+ nodes=nodes[:MAX_SUMMARY_NODES],+ node_count=len(nodes),+ birth_commit=row.get("birth_commit"),+ birth_at=_iso(row.get("birth_at")),+ last_seen_at=_iso(row.get("last_seen_at")),+ still_true=still_true,+ )+++class EpisodeDetail(BaseModel):+ """One episode, whole, with the currency question actually asked.++ ``current`` is the gate half of the verdict and ``still_true`` the sentence+ half. Both are served because they answer different questions: a reader+ asking *what happened here* wants the sentence even when the scope has+ moved, while anything putting a claim beside a statement about the present+ must respect the boolean.+ """++ id: str+ tier: str+ kind: str+ subject: str+ body: str+ evidence: str+ nodes: list[str]+ node_count: int+ birth_commit: str | None+ birth_at: str | None+ last_seen_at: str | None+ still_true: str+ current: bool++ @classmethod+ def from_row(cls, row: dict, *, sentence: str, current: bool) -> EpisodeDetail:+ nodes = [n for n in (row.get("nodes") or []) if isinstance(n, str) and n]+ return cls(+ id=row["id"],+ tier=row["tier"],+ kind=row["kind"],+ subject=row["subject"],+ body=row.get("body") or "",+ evidence=row.get("evidence") or "",+ nodes=nodes,+ node_count=len(nodes),+ birth_commit=row.get("birth_commit"),+ birth_at=_iso(row.get("birth_at")),+ last_seen_at=_iso(row.get("last_seen_at")),+ still_true=sentence,+ current=current,+ )+++class EpisodeListResponse(BaseModel):+ """A page of summaries, with the measured total behind it."""++ available: bool = True+ total: int = 0+ episodes: list[EpisodeSummary] = []+++class EpisodeCountsResponse(BaseModel):+ """Counts by tier and by kind, from a grouped read of the same filters.++ Exists for the same reason the decision counts endpoint does: a page that+ counts its own rows reports the size of a window, not the size of a store.+ """++ available: bool = True+ total: int = 0+ by_tier: dict[str, int] = {}+ by_kind: dict[str, int] = {}diff --git a/packages/types/__tests__/contracts.test.ts b/packages/types/__tests__/contracts.test.tsindex 508beca3b..8a4d50027 100644--- a/packages/types/__tests__/contracts.test.ts+++ b/packages/types/__tests__/contracts.test.ts@@ -11,6 +11,8 @@* - DeadCodeFinding: optional enrichment fields stay optional so canonical* artifacts still satisfy the contract without them.* - DecisionRecord: status + source are union literals, not bare strings.+ * - Episode: tier excludes the per-machine transcript tier, and a summary+ * never grows a body.* - Hotspot key shape: canonical Hotspot uses `file_path`, not `path`, so* raw entries with a `path` key must adapt before assignment.*/@@ -27,6 +29,11 @@ import type {import type { GraphLink } from "../src/graph.js";import type { DeadCodeFinding } from "../src/dead-code.js";import type { DecisionRecord, DecisionStatus } from "../src/decisions.js";+import type {+ EpisodeDetail,+ EpisodeSummary,+ EpisodeTier,+} from "../src/episodes.js";import type { Hotspot } from "../src/git.js";import type {HeritageKind,@@ -218,3 +225,30 @@ describe("C4 io_kind parity", () => {expect(untyped.io_kind).toBeNull();});});++describe("Episode tier is an allowlist, not a bare string", () => {+ it("excludes the per-machine transcript tier", () => {+ // The engine has a third tier. It never crosses HTTP, and the type is+ // where that stays true for a consumer: widening this to `string` would+ // let a component render a session somebody else's laptop recorded.+ expectTypeOf<EpisodeTier>().toEqualTypeOf<"structural" | "git">();+ expectTypeOf<EpisodeSummary["tier"]>().toEqualTypeOf<EpisodeTier>();+ expectTypeOf<EpisodeDetail["tier"]>().toEqualTypeOf<EpisodeTier>();+ });++ it("keeps a summary bodyless and a detail's verdict non-null", () => {+ // A summary that grew a `body` would mean a list route started paying+ // for one; `still_true` non-optional on a detail is what makes the+ // checked verdict impossible to forget to render.+ expectTypeOf<Extract<keyof EpisodeSummary, "body">>().toEqualTypeOf<never>();+ // Indexed rather than `keyof`, which survives both optionality and a+ // widening to `unknown` and so only ever catches outright deletion.+ expectTypeOf<EpisodeDetail["body"]>().toEqualTypeOf<string>();+ expectTypeOf<EpisodeDetail["still_true"]>().toEqualTypeOf<string>();+ expectTypeOf<EpisodeDetail["current"]>().toEqualTypeOf<boolean>();+ // Required-but-nullable, not optional: the engine field has a default and+ // pydantic serializes defaults, so the key is always on the wire. A+ // consumer discriminating "unchecked" by key presence would never see it.+ expectTypeOf<EpisodeSummary["still_true"]>().toEqualTypeOf<string | null>();+ });+});diff --git a/packages/types/package.json b/packages/types/package.jsonindex fb67a3277..03d28a26a 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -13,6 +13,7 @@"./git": "./src/git.ts","./docs": "./src/docs.ts","./decisions": "./src/decisions.ts",+ "./episodes": "./src/episodes.ts","./dead-code": "./src/dead-code.ts","./symbols": "./src/symbols.ts","./chat": "./src/chat.ts",diff --git a/packages/types/src/episodes.ts b/packages/types/src/episodes.tsnew file mode 100644index 000000000..535746d05--- /dev/null+++ b/packages/types/src/episodes.ts@@ -0,0 +1,89 @@+/**+ * Canonical episode types — the dated things that happened to a repository.+ *+ * Canonical source: engine `EpisodeSummary` / `EpisodeDetail` /+ * `EpisodeListResponse` / `EpisodeCountsResponse` in+ * `packages/server/src/repowise/server/schemas/episodes.py`. Hand-written and+ * hand-kept in sync; nothing generates these.+ *+ * Two shapes because they cost different amounts. A summary is one indexed+ * SQLite read and carries no body; a detail spends one `git rev-list` to+ * answer whether the claim still holds. A list of summaries must never be+ * assembled by fetching details.+ */++/**+ * Only the tiers that describe the repository itself. The engine has a third,+ * `transcript`, which is per-machine and never crosses HTTP — two people+ * opening one dashboard would otherwise see different pages.+ */+export type EpisodeTier = "structural" | "git";++export interface EpisodeSummary {+ id: string;+ tier: EpisodeTier;+ /** Discriminates episodes within a tier, e.g. `code_fix`, `nested_repos`. */+ kind: string;+ subject: string;+ evidence: string;+ /** The bound scope, trimmed. `node_count` is the untrimmed total. */+ nodes: string[];+ /** Files the episode is bound to, before `nodes` was trimmed for display. */+ node_count: number;+ birth_commit: string | null;+ /** ISO-8601 UTC, or null when the store holds no date. */+ birth_at: string | null;+ last_seen_at: string | null;+ /**+ * The currency signal that costs no git call, or `null` on tiers that+ * accumulate members, where the same stamp proves nothing.+ *+ * `null` means *unchecked*, never *stale* — checking happens on the detail+ * route. Required-but-nullable rather than optional, because the engine+ * field carries a default and pydantic serializes defaults: the key is+ * always on the wire. Discriminate on the value, never on key presence.+ */+ still_true: string | null;+}++export interface EpisodeDetail {+ id: string;+ tier: EpisodeTier;+ kind: string;+ subject: string;+ body: string;+ evidence: string;+ nodes: string[];+ node_count: number;+ birth_commit: string | null;+ birth_at: string | null;+ last_seen_at: string | null;+ /** The sentence half of the verdict. Always present on a detail. */+ still_true: string;+ /**+ * The gate half. A reader asking *what happened here* shows the sentence+ * either way; anything putting a claim beside a statement about the present+ * must respect this.+ */+ current: boolean;+}++/**+ * `available: false` means this repository has never derived episodes — a+ * real cold start, not an error and not an empty store. Render it as+ * "nothing here yet", distinct from a store whose rows were all pruned.+ */+export interface EpisodeListResponse {+ available: boolean;+ /** Measured total behind the page, not the length of `episodes`. */+ total: number;+ episodes: EpisodeSummary[];+}++export interface EpisodeCountsResponse {+ available: boolean;+ total: number;+ /** Keys are a subset of the served tiers, so a consumer can switch on them. */+ by_tier: Partial<Record<EpisodeTier, number>>;+ by_kind: Record<string, number>;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 8d67d2384..13cb871df 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -13,6 +13,7 @@ export * from "./graph.js";export * from "./git.js";export * from "./docs.js";export * from "./decisions.js";+export * from "./episodes.js";export * from "./dead-code.js";export * from "./symbols.js";export * from "./chat.js";diff --git a/packages/web/src/lib/api/episodes.ts b/packages/web/src/lib/api/episodes.tsnew file mode 100644index 000000000..172bde356--- /dev/null+++ b/packages/web/src/lib/api/episodes.ts@@ -0,0 +1,3 @@+import "./client";++export * from "@repowise-dev/api-client/episodes";diff --git a/tests/unit/precedent/test_episode_store.py b/tests/unit/precedent/test_episode_store.pyindex 6b9bdc4a7..f963b5203 100644--- a/tests/unit/precedent/test_episode_store.py+++ b/tests/unit/precedent/test_episode_store.py@@ -1191,3 +1191,151 @@ class TestNodeIndexRecovery:"SELECT COUNT(*) FROM episode_nodes WHERE path = '123'").fetchone()assert rows == 0+++def _tiered(tier: str, kind: str, subject: str, birth_at: float) -> Episode:+ """An episode with an explicit birth, so ordering is deterministic."""+ return Episode(+ tier=tier,+ kind=kind,+ subject=subject,+ body=f"body of {subject}",+ evidence="e",+ nodes=("pkg/a.py",),+ birth_commit="a" * 40,+ birth_at=birth_at,+ )+++def _seeded(tmp_path: Path) -> EpisodeStore:+ """Five episodes across two tiers and three kinds, newest last."""+ store = _store(tmp_path)+ store.append_tier(+ tier=TIER_GIT,+ episodes=[_tiered(TIER_GIT, "code_fix", f"sha{i}", 1000.0 + i) for i in range(3)],+ oldest_birth_at=1000.0,+ )+ store.replace_kinds(+ tier=TIER_STRUCTURAL,+ kinds=["nested_repos", "formatter_drift"],+ episodes=[+ _tiered(TIER_STRUCTURAL, "nested_repos", ".", 900.0),+ _tiered(TIER_STRUCTURAL, "formatter_drift", "ruff", 901.0),+ ],+ )+ return store+++class TestPaging:+ def test_limit_and_offset_walk_the_ordering(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ everything = store.list_episodes(tiers=SHAREABLE_TIERS)+ first = store.list_episodes(tiers=SHAREABLE_TIERS, limit=2, offset=0)+ second = store.list_episodes(tiers=SHAREABLE_TIERS, limit=2, offset=2)+ assert [r["id"] for r in first + second] == [r["id"] for r in everything[:4]]++ def test_unpaged_is_still_the_default(self, tmp_path: Path) -> None:+ """The three in-process callers pass no limit and must keep everything."""+ with _seeded(tmp_path) as store:+ assert len(store.list_episodes(tiers=SHAREABLE_TIERS)) == 5++ def test_offset_past_the_end_is_empty_not_an_error(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ assert store.list_episodes(tiers=SHAREABLE_TIERS, limit=10, offset=99) == []+++class TestBodyProjection:+ def test_without_body_the_key_is_absent_not_blank(self, tmp_path: Path) -> None:+ """Absent, so a reader cannot mistake "not fetched" for "empty"."""+ with _seeded(tmp_path) as store:+ (row,) = store.list_episodes(tiers=SHAREABLE_TIERS, limit=1, with_body=False)+ (full,) = store.list_episodes(tiers=SHAREABLE_TIERS, limit=1)+ assert "body" not in row+ assert full["body"]+ assert {*row} | {"body"} == {*full}++ def test_every_other_field_survives(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ (row,) = store.list_episodes(tiers=SHAREABLE_TIERS, limit=1, with_body=False)+ assert row["nodes"] == ["pkg/a.py"]+ assert row["birth_commit"] and row["birth_at"]+++class TestCountEpisodes:+ def test_counts_what_the_same_filters_select(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ for kwargs in ({}, {"tier": TIER_GIT}, {"kind": "code_fix"}):+ assert store.count_episodes(**kwargs) == len(store.list_episodes(**kwargs))++ def test_an_empty_allowlist_counts_nothing(self, tmp_path: Path) -> None:+ """Not everything — the inversion the allowlist exists to prevent."""+ with _seeded(tmp_path) as store:+ assert store.count_episodes(tiers=[]) == 0+ assert store.list_episodes(tiers=[]) == []++ def test_total_is_independent_of_the_page(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ page = store.list_episodes(tiers=SHAREABLE_TIERS, limit=2)+ assert len(page) == 2+ assert store.count_episodes(tiers=SHAREABLE_TIERS) == 5+++class TestGroupCounts:+ def test_groups_by_tier_and_kind(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ assert store.group_counts("tier", tiers=SHAREABLE_TIERS) == {+ TIER_GIT: 3,+ TIER_STRUCTURAL: 2,+ }+ assert store.group_counts("kind", tiers=SHAREABLE_TIERS) == {+ "code_fix": 3,+ "formatter_drift": 1,+ "nested_repos": 1,+ }++ def test_an_unlisted_column_raises_rather_than_interpolating(+ self, tmp_path: Path+ ) -> None:+ with _seeded(tmp_path) as store:+ with pytest.raises(ValueError):+ store.group_counts("body")+ with pytest.raises(ValueError):+ store.group_counts("id) --")++ def test_the_allowlist_is_honoured(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ store.accumulate_tier(+ tier=TIER_TRANSCRIPT,+ kind="session",+ episodes=[_tiered(TIER_TRANSCRIPT, "session", "s1", 1200.0)],+ present_subjects=["s1"],+ )+ assert TIER_TRANSCRIPT not in store.group_counts("tier", tiers=SHAREABLE_TIERS)+ assert TIER_TRANSCRIPT in store.group_counts("tier")+++class TestGetEpisode:+ def test_returns_the_row_by_id(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ (want,) = store.list_episodes(tier=TIER_STRUCTURAL, kind="nested_repos")+ got = store.get_episode(want["id"], tiers=SHAREABLE_TIERS)+ assert got == want++ def test_a_tier_outside_the_allowlist_is_not_reachable_by_id(+ self, tmp_path: Path+ ) -> None:+ """A stable hash is exactly the shape somebody guesses at."""+ with _seeded(tmp_path) as store:+ store.accumulate_tier(+ tier=TIER_TRANSCRIPT,+ kind="session",+ episodes=[_tiered(TIER_TRANSCRIPT, "session", "s1", 1200.0)],+ present_subjects=["s1"],+ )+ (secret,) = store.list_episodes(tier=TIER_TRANSCRIPT)+ assert store.get_episode(secret["id"], tiers=SHAREABLE_TIERS) is None+ assert store.get_episode(secret["id"]) is not None++ def test_unknown_id_is_none(self, tmp_path: Path) -> None:+ with _seeded(tmp_path) as store:+ assert store.get_episode("nope", tiers=SHAREABLE_TIERS) is Nonediff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex 2e40b023f..6dd4f8fc0 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -32,6 +32,7 @@ def _create_test_app():costs,dead_code,decisions,+ episodes,external_systems,files,git,@@ -88,6 +89,7 @@ def _create_test_app():app.include_router(owners.router)app.include_router(modules.router)app.include_router(decisions.router)+ app.include_router(episodes.router)app.include_router(external_systems.router)app.include_router(overview.router)app.include_router(refactoring.router)diff --git a/tests/unit/server/mcp/test_answer_episodes.py b/tests/unit/server/mcp/test_answer_episodes.pyindex 4cfd0d653..e4ec6fe4e 100644--- a/tests/unit/server/mcp/test_answer_episodes.py+++ b/tests/unit/server/mcp/test_answer_episodes.py@@ -414,7 +414,7 @@ def git_calls(monkeypatch):currency verdict is one implementation serving every reader, so this iswhere the query is made from."""- from repowise.server.mcp_server import _episodes as mod+ from repowise.core.precedent import currency as modcalls: list[tuple] = []real = mod.commits_sincediff --git a/tests/unit/server/mcp/test_why_episodes.py b/tests/unit/server/mcp/test_why_episodes.pyindex 268c7bdde..77dd8bf48 100644--- a/tests/unit/server/mcp/test_why_episodes.py+++ b/tests/unit/server/mcp/test_why_episodes.py@@ -233,7 +233,7 @@ class TestCurrency:The same bound, for the same reason, that this mode already applies tothe decision it ranks first."""- from repowise.server.mcp_server import _episodes as mod+ from repowise.core.precedent import currency as modcalls: list = []real = mod.commits_since@@ -252,7 +252,7 @@ class TestCurrency:assert len(calls) == 1def test_a_re_observed_structural_fact_needs_no_git_query(self, repo, monkeypatch):- from repowise.server.mcp_server import _episodes as mod+ from repowise.core.precedent import currency as modcalls: list = []monkeypatch.setattr(mod, "commits_since", lambda *a, **k: calls.append(a))diff --git a/tests/unit/server/test_episodes_api.py b/tests/unit/server/test_episodes_api.pynew file mode 100644index 000000000..87d38480e--- /dev/null+++ b/tests/unit/server/test_episodes_api.py@@ -0,0 +1,433 @@+"""/api/repos/{repo_id}/episodes — the HTTP surface over the sidecar store.++Three things these tests exist to hold, each of which is a defect the code+would otherwise be free to acquire quietly: the transcript tier never leaves+the machine, a repository with no store is a 200 rather than a 404 or a+crash, and a list route never shells out to git.+"""++from __future__ import annotations++import sqlite3+import subprocess+from pathlib import Path++import pytest+from httpx import AsyncClient++from repowise.core.precedent.store import (+ TIER_GIT,+ TIER_STRUCTURAL,+ TIER_TRANSCRIPT,+ Episode,+ EpisodeStore,+)++from .conftest import create_test_repo+++def _episode(tier: str, kind: str, subject: str, birth_at: float, **kw) -> Episode:+ return Episode(+ tier=tier,+ kind=kind,+ subject=subject,+ body=f"the whole body of {subject}",+ evidence="evidence line",+ nodes=kw.get("nodes", ("pkg/a.py",)),+ birth_commit=kw.get("birth_commit", "b" * 40),+ birth_at=birth_at,+ )+++def _seed(repo_dir: Path) -> None:+ """Two git episodes, one structural, one transcript that must stay local."""+ store = EpisodeStore.open_for_repo(repo_dir)+ store.append_tier(+ tier=TIER_GIT,+ episodes=[+ _episode(TIER_GIT, "code_fix", "sha1", 1000.0),+ _episode(TIER_GIT, "code_fix", "sha2", 1001.0, nodes=("pkg/b.py",)),+ ],+ oldest_birth_at=1000.0,+ )+ store.replace_kinds(+ tier=TIER_STRUCTURAL,+ kinds=["nested_repos"],+ episodes=[_episode(TIER_STRUCTURAL, "nested_repos", ".", 900.0)],+ )+ store.accumulate_tier(+ tier=TIER_TRANSCRIPT,+ kind="session",+ episodes=[_episode(TIER_TRANSCRIPT, "session", "secret-session", 1200.0)],+ present_subjects=["secret-session"],+ )+ store.close()+++class TestColdStart:+ async def test_no_store_is_a_200_saying_so(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Not a 404: the repository exists, the feature has no data yet."""+ repo = await create_test_repo(client, tmp_path)+ resp = await client.get(f"/api/repos/{repo['id']}/episodes")+ assert resp.status_code == 200+ body = resp.json()+ assert body["available"] is False+ assert body["episodes"] == []+ assert body["total"] == 0++ async def test_reading_does_not_create_the_store(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Constructing EpisodeStore runs mkdir + the schema script."""+ repo = await create_test_repo(client, tmp_path)+ db = Path(repo["local_path"]) / ".repowise" / "episodes" / "episodes.db"+ for route in ("episodes", "episodes/counts", "episodes/by-file?path=pkg/a.py"):+ assert (await client.get(f"/api/repos/{repo['id']}/{route}")).status_code == 200+ assert not db.exists()+ assert not db.parent.exists()++ async def test_counts_degrade_the_same_way(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ body = (await client.get(f"/api/repos/{repo['id']}/episodes/counts")).json()+ assert body["available"] is False+ assert body["by_tier"] == {} and body["by_kind"] == {}++ async def test_unknown_repository_is_still_a_404(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Paired with a real repo, or a deleted router would pass this too."""+ assert (await client.get("/api/repos/nope/episodes")).status_code == 404+ repo = await create_test_repo(client, tmp_path)+ assert (await client.get(f"/api/repos/{repo['id']}/episodes")).status_code == 200+++class TestTierSafety:+ async def test_the_transcript_tier_never_reaches_http(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Per-machine, so two people would otherwise see different pages."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()+ assert body["total"] == 3+ assert {e["tier"] for e in body["episodes"]} == {TIER_GIT, TIER_STRUCTURAL}+ assert not any("secret-session" in e["subject"] for e in body["episodes"])++ async def test_a_transcript_episode_is_not_reachable_by_id(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ repo_dir = Path(repo["local_path"])+ _seed(repo_dir)+ store = EpisodeStore.open_for_repo(repo_dir)+ (secret,) = store.list_episodes(tier=TIER_TRANSCRIPT)+ store.close()+ resp = await client.get(f"/api/repos/{repo['id']}/episodes/{secret['id']}")+ assert resp.status_code == 404++ async def test_filtering_to_a_non_shareable_tier_returns_nothing(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """An unknown tier must select nothing, never fall through to all."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ for bad in (TIER_TRANSCRIPT, "made-up"):+ body = (+ await client.get(f"/api/repos/{repo['id']}/episodes?tier={bad}")+ ).json()+ assert body["episodes"] == [] and body["total"] == 0+++class TestListing:+ async def test_rows_carry_no_body(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()+ assert body["episodes"]+ assert all("body" not in e for e in body["episodes"])++ async def test_newest_first_and_pageable(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ base = f"/api/repos/{repo['id']}/episodes"+ every = (await client.get(f"{base}?limit=50")).json()["episodes"]+ assert [e["subject"] for e in every] == ["sha2", "sha1", "."]+ page = (await client.get(f"{base}?limit=1&offset=1")).json()+ assert [e["subject"] for e in page["episodes"]] == ["sha1"]+ # The total is measured, not the length of the window.+ assert page["total"] == 3++ async def test_scope_is_capped_with_the_real_count_beside_it(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """A cap without the count beside it is a silent lie about coverage."""+ from repowise.server.schemas.episodes import MAX_SUMMARY_NODES++ repo = await create_test_repo(client, tmp_path)+ repo_dir = Path(repo["local_path"])+ wide = tuple(f"pkg/f{i}.py" for i in range(MAX_SUMMARY_NODES + 8))+ store = EpisodeStore.open_for_repo(repo_dir)+ store.append_tier(+ tier=TIER_GIT,+ episodes=[_episode(TIER_GIT, "code_fix", "wide", 1000.0, nodes=wide)],+ oldest_birth_at=1000.0,+ )+ store.close()+ (row,) = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()["episodes"]+ assert len(row["nodes"]) == MAX_SUMMARY_NODES+ assert row["node_count"] == len(wide)++ async def test_a_list_never_shells_out_to_git(+ self, client: AsyncClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """~60 ms per row; a page of fifty would be three seconds of subprocess.++ Every route is asserted to have served *real rows*, not just a 200. A+ regression that quietly degraded all three to ``available: false``+ would satisfy "git was never called" while measuring nothing.+ """+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: pytest.fail("a list route asked git"),+ )+ for route in ("episodes", "episodes/by-file?path=pkg/a.py"):+ body = (await client.get(f"/api/repos/{repo['id']}/{route}")).json()+ assert body["available"] is True+ assert body["episodes"], f"{route} served nothing, so it proved nothing"+ counts = (await client.get(f"/api/repos/{repo['id']}/episodes/counts")).json()+ assert counts["available"] is True and counts["total"] == 3+++class TestCounts:+ async def test_grouped_by_tier_and_kind(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (await client.get(f"/api/repos/{repo['id']}/episodes/counts")).json()+ assert body["total"] == 3+ assert body["by_tier"] == {TIER_GIT: 2, TIER_STRUCTURAL: 1}+ assert body["by_kind"] == {"code_fix": 2, "nested_repos": 1}++ async def test_counts_is_not_read_as_an_episode_id(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """FastAPI matches in declaration order; below /{id} this would 404."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ resp = await client.get(f"/api/repos/{repo['id']}/episodes/counts")+ assert resp.status_code == 200+ assert "by_tier" in resp.json()+++class TestByFile:+ async def test_returns_only_what_is_bound_there(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (+ await client.get(+ f"/api/repos/{repo['id']}/episodes/by-file", params={"path": "pkg/b.py"}+ )+ ).json()+ assert [e["subject"] for e in body["episodes"]] == ["sha2"]+ assert body["total"] == 1++ async def test_a_path_with_nothing_bound_is_empty_but_available(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (+ await client.get(+ f"/api/repos/{repo['id']}/episodes/by-file", params={"path": "pkg/zzz.py"}+ )+ ).json()+ assert body["available"] is True+ assert body["episodes"] == [] and body["total"] == 0++ async def test_path_is_required(self, client: AsyncClient, tmp_path: Path) -> None:+ repo = await create_test_repo(client, tmp_path)+ resp = await client.get(f"/api/repos/{repo['id']}/episodes/by-file")+ assert resp.status_code == 422+++class TestDetail:+ async def test_serves_the_body_and_a_verdict(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ repo_dir = Path(repo["local_path"])+ _seed(repo_dir)+ listing = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()+ one = listing["episodes"][0]+ body = (+ await client.get(f"/api/repos/{repo['id']}/episodes/{one['id']}")+ ).json()+ assert body["body"].startswith("the whole body of")+ assert body["subject"] == one["subject"]+ # git cannot answer in a bare tmp dir, so the verdict says so rather+ # than claiming currency. Both halves are always present.+ assert isinstance(body["current"], bool)+ assert body["still_true"]++ async def test_full_scope_is_not_capped_on_detail(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ from repowise.server.schemas.episodes import MAX_SUMMARY_NODES++ repo = await create_test_repo(client, tmp_path)+ repo_dir = Path(repo["local_path"])+ wide = tuple(f"pkg/f{i}.py" for i in range(MAX_SUMMARY_NODES + 8))+ store = EpisodeStore.open_for_repo(repo_dir)+ store.append_tier(+ tier=TIER_GIT,+ episodes=[_episode(TIER_GIT, "code_fix", "wide", 1000.0, nodes=wide)],+ oldest_birth_at=1000.0,+ )+ (row,) = store.list_episodes(tier=TIER_GIT)+ store.close()+ body = (+ await client.get(f"/api/repos/{repo['id']}/episodes/{row['id']}")+ ).json()+ assert len(body["nodes"]) == len(wide)++ async def test_unknown_episode_is_a_404(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Paired with a real id, or a deleted router would pass this too."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ real = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()+ good = await client.get(+ f"/api/repos/{repo['id']}/episodes/{real['episodes'][0]['id']}"+ )+ assert good.status_code == 200+ bad = await client.get(f"/api/repos/{repo['id']}/episodes/deadbeef")+ assert bad.status_code == 404+ assert bad.json()["detail"] == "Episode not found"++ async def test_no_store_and_bad_id_are_told_apart(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """Same status, different reason: one is worth a retry, one is not.++ The list routes draw this line with `available`; a single-object+ response has no room for it, so the wording carries it.+ """+ other = tmp_path / "other"+ other.mkdir()+ empty = await create_test_repo(client, tmp_path)+ seeded = await create_test_repo(client, other)+ _seed(Path(seeded["local_path"]))++ no_store = await client.get(f"/api/repos/{empty['id']}/episodes/deadbeef")+ bad_id = await client.get(f"/api/repos/{seeded['id']}/episodes/deadbeef")+ assert no_store.status_code == bad_id.status_code == 404+ assert no_store.json()["detail"] != bad_id.json()["detail"]+ assert "No episodes recorded" in no_store.json()["detail"]+++class TestCoverageGaps:+ """Cases the first cut of this file asserted around rather than through."""++ async def test_a_valid_tier_filter_actually_filters(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ base = f"/api/repos/{repo['id']}/episodes"+ git_only = (await client.get(f"{base}?tier={TIER_GIT}")).json()+ structural = (await client.get(f"{base}?tier={TIER_STRUCTURAL}")).json()+ assert {e["tier"] for e in git_only["episodes"]} == {TIER_GIT}+ assert git_only["total"] == 2+ assert {e["tier"] for e in structural["episodes"]} == {TIER_STRUCTURAL}+ assert structural["total"] == 1++ async def test_a_kind_filter_actually_filters(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ base = f"/api/repos/{repo['id']}/episodes"+ body = (await client.get(f"{base}?kind=nested_repos")).json()+ assert [e["subject"] for e in body["episodes"]] == ["."]+ assert body["total"] == 1+ assert (await client.get(f"{base}?kind=no_such_kind")).json()["total"] == 0++ async def test_an_empty_tier_param_selects_nothing_not_everything(+ self, client: AsyncClient, tmp_path: Path+ ) -> None:+ """`?tier=` arrives as "", which must not read as "no filter"."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ body = (await client.get(f"/api/repos/{repo['id']}/episodes?tier=")).json()+ assert body["episodes"] == [] and body["total"] == 0++ async def test_a_repo_with_no_local_path_is_unavailable_not_a_crash(+ self, client: AsyncClient, tmp_path: Path, app+ ) -> None:+ """`local_path` is non-null in the model but empty rows predate that."""+ repo = await create_test_repo(client, tmp_path)+ async with app.state.session_factory() as session:+ from repowise.core.persistence import crud++ row = await crud.get_repository(session, repo["id"])+ row.local_path = ""+ await session.commit()+ for route in ("episodes", "episodes/counts", "episodes/by-file?path=a.py"):+ resp = await client.get(f"/api/repos/{repo['id']}/{route}")+ assert resp.status_code == 200+ assert resp.json()["available"] is False+ detail = await client.get(f"/api/repos/{repo['id']}/episodes/deadbeef")+ assert detail.status_code == 404++ async def test_detail_asks_git_exactly_once(+ self, client: AsyncClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Bounded at one, not merely "few" — the budget the docstring claims."""+ from repowise.core.precedent import currency as currency_mod++ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))+ calls: list[tuple] = []+ monkeypatch.setattr(+ currency_mod,+ "commits_since",+ lambda *a, **k: calls.append((a, k)) or 0,+ )+ listing = (await client.get(f"/api/repos/{repo['id']}/episodes")).json()+ git_row = next(e for e in listing["episodes"] if e["tier"] == TIER_GIT)+ resp = await client.get(f"/api/repos/{repo['id']}/episodes/{git_row['id']}")+ assert resp.status_code == 200+ assert len(calls) == 1++ async def test_a_failing_query_degrades_rather_than_500ing(+ self, client: AsyncClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """SQLITE_BUSY past the timeout — a dashboard read during an index write."""+ repo = await create_test_repo(client, tmp_path)+ _seed(Path(repo["local_path"]))++ def boom(self, *a, **k):+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(EpisodeStore, "count_episodes", boom)+ monkeypatch.setattr(EpisodeStore, "group_counts", boom)+ monkeypatch.setattr(EpisodeStore, "count_by_node", boom)+ for route in ("episodes", "episodes/counts", "episodes/by-file?path=pkg/a.py"):+ resp = await client.get(f"/api/repos/{repo['id']}/{route}")+ assert resp.status_code == 200, route+ assert resp.json()["available"] is False