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.

refactor(server): split get_why into mode and layer modules (#2547)

Raghav Chamadiyaa195ab6ca946
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 819fe0115..a387b4f63 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -1060,7 +1060,7 @@ repowise decision health # health summary
| `core/analysis/decision_extractor.py` | All 4 capture sources + staleness computation |
| `core/persistence/models.py` | `DecisionRecord` ORM model |
| `core/persistence/crud.py` | 8 decision CRUD functions |
-| `server/mcp_server/tool_why.py` | MCP tool `get_why` (3-mode: search, path, health dashboard) |
+| `server/mcp_server/tool_why/` | MCP tool `get_why` (package: one module per mode, plus shared loading, ranking, projection and caps) |
| `server/routers/decisions.py` | REST API endpoints |
| `cli/commands/decision_cmd.py` | CLI command group (7 subcommands) |
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
deleted file mode 100644
index a2ef987be..000000000
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ /dev/null
@@ -1,2397 +0,0 @@
-"""MCP Tool 4: get_why — intent archaeology and decision search."""
-
-from __future__ import annotations
-
-import asyncio
-import contextlib
-import json
-import re
-from pathlib import Path
-from typing import Any
-
-from sqlalchemy import select
-
-from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
-from repowise.core.analysis.decisions.lifecycle import is_governing, status_rank
-from repowise.core.analysis.decisions.scope import binds_to_paths
-from repowise.core.persistence.crud.authority import (
- accepted_decision_ids,
- decision_currencies,
- resolve_decision_id,
-)
-from repowise.core.persistence.database import get_session
-from repowise.core.persistence.models import (
- DecisionEdge,
- DecisionEvidence,
- DecisionRecord,
- GitMetadata,
-)
-from repowise.core.precedent.currency import describe_decision_currency
-from repowise.core.providers.embedding import store_has_semantic_vectors
-from repowise.core.registry import ToolRecipe
-from repowise.core.registry import mcp_tool_registry as mcp
-from repowise.server.mcp_server._budget import (
- OmissionCollector,
- cap_collection,
- fit_to_budget,
- over_budget,
- register_post_shed,
-)
-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,
- _decision_body,
- _get_exclude_spec,
- _get_repo,
- _is_path,
- _is_workspace_mode,
- _resolve_all_contexts,
- _resolve_repo_context,
- _unsupported_repo_all,
- decision_is_excluded,
- filter_path_list,
- is_excluded,
-)
-from repowise.server.mcp_server._meta import build_meta as _build_meta
-from repowise.server.mcp_server._why_evidence import (
- annotate_response_evidence_async,
- decision_collapse_key,
-)
-from repowise.server.mcp_server._why_relevance import (
- clears_floor,
- query_scorer,
- question_terms,
- recovery_note,
- redirect_for,
- redirect_when_served,
- relevance,
- term_idf,
-)
-
-
-def _has_archaeology(archaeology: Any) -> bool:
- """Whether an archaeology block found anything.
-
- ``_git_archaeology_fallback`` always returns a dict, carrying ``triggered``
- and a summary that may say it found nothing, so the block's presence proves
- only that it ran.
- """
- return isinstance(archaeology, dict) and any(
- archaeology.get(lane)
- for lane in ("file_commits", "cross_references", "git_log")
- )
-
-
-def _is_accepted_row(row: Any) -> bool:
- """Whether an emitted decision row rests on an acceptance.
-
- Reads the ``authority`` key this module stamps rather than ``status``, for
- the reason ``decision_currencies`` gives: the column is a projection every
- writer keeps in step, and it agrees right up until something writes it
- without an acceptance. A row with no ``authority`` at all is a semantic hit
- projected from the vector store, which carries no record to join on and so
- cannot be claimed as accepted either.
- """
- return isinstance(row, dict) and row.get("authority") == "accepted"
-
-
-def _stamp_answer_basis(result: dict) -> dict:
- """Name the strongest lane the response actually rests on.
-
- This tool serves commit messages and mined comments beside decision
- records. Only an *accepted* decision is a ruling; the rest are evidence a
- reader has to weigh. Per-row ``provenance`` answers that one row at a time,
- which is no help in deciding how much of the whole response to trust.
-
- ``decision`` requires an acceptance, not a record. A ``DecisionRecord`` is a
- candidate until a ``DecisionAcceptance`` row exists for it, and accepting is
- a deliberate manual step, so a store of nothing but candidates is the state
- every user who has not worked through the acceptance UI is in — the common
- case, not an edge one. Stamping ``decision`` off the mere presence of a
- record therefore claimed a ruling on most calls this tool ever serves, and
- it did so beside titles like "Do not ship UI components yet": session
- artifacts nobody confirmed, presented as governing.
-
- ``candidate`` sits *below* every evidence lane rather than above them for
- the same reason. A mined comment or a commit message is something a reader
- can weigh; an unconfirmed candidate is a guess about what somebody once
- meant, so it must not outrank the lanes that carry real evidence.
-
- Absent when nothing was served, so a refusal cannot read as an answer.
- Re-derived after the budget pass has shed, so the claim cannot outlive the
- lane it names; clears first to stay correct on that second call.
- """
- result.pop("answer_basis", None)
- entries = [
- e for e in (result.get("target_context") or {}).values() if isinstance(e, dict)
- ]
- decision_rows = [
- *(result.get("decisions") or []),
- *(r for e in entries for r in (e.get("governing_decisions") or [])),
- ]
- candidate_rows = [
- *(r for e in entries for r in (e.get("candidate_decisions") or [])),
- *(r for r in decision_rows if not _is_accepted_row(r)),
- ]
- if any(_is_accepted_row(r) for r in decision_rows):
- result["answer_basis"] = "decision"
- elif result.get("episodes"):
- result["answer_basis"] = "episode"
- elif result.get("code_rationale"):
- result["answer_basis"] = "rationale"
- elif _has_archaeology(result.get("git_archaeology")) or any(
- _has_archaeology(e.get("git_archaeology")) for e in entries
- ):
- result["answer_basis"] = "archaeology"
- elif result.get("related_documentation"):
- result["answer_basis"] = "documentation"
- elif candidate_rows:
- result["answer_basis"] = "candidate"
- return result
-
-
-def _restamp_answer_basis(result: dict, _collector: OmissionCollector) -> None:
- """Re-derive the basis after shedding.
-
- The basis names a lane, and a lane the budget pass emptied must not leave
- the claim standing.
- """
- _stamp_answer_basis(result)
-
-
-register_post_shed("get_why", _restamp_answer_basis)
-
-
- surface_order=70,
- artifact_type="decisions",
- presentation="decision_evidence",
- evidence_basis="inferred",
- recipes=(
- ToolRecipe(
- "read_rationale",
- 'get_why(targets=["path"])',
- ("get_why",),
- ),
- ),
-)
-async def get_why(
- query: str | None = None,
- targets: list[str] | None = None,
- repo: str | None = None,
- id: str | None = None,
- reference: dict[str, Any] | None = None,
-) -> dict:
- """Why this code is shaped this way — decision records + evidence commits.
-
- Call before refactors or pattern divergences. Query modes: a question
- ("why is auth using JWT?"), a file path (governing decisions + origin
- story + alignment score), a question anchored to targets, or no query
- (decision health dashboard). Falls back to git archaeology when no
- decisions exist for a path — never empty. Evidence-bearing rows carry an
- explicit ``provenance`` and self-contained ``evidence_refs``; matching ids
- mean shared evidence, not independent corroboration. Every decision row
- carries ``authority``: ``accepted`` means somebody signed it, ``candidate``
- means nobody has yet. ``answer_basis`` names the strongest lane the response
- rests on (decision, episode, rationale, archaeology, documentation,
- candidate); only ``decision`` is a ruling, and ``candidate`` is the weakest
- -- it means nothing cleared that bar.
-
- Args:
- query: question, file/module path, or omit for the dashboard.
- targets: optional file paths to anchor the search, or to ask about on
- their own when there is no query.
- repo: usually omitted.
- id: decision or ``ev_...`` evidence id emitted by this or another tool.
- reference: structured evidence reference. Its id and repository are
- accepted together without caller translation.
- """
- if reference:
- if id is None and isinstance(reference.get("id"), str):
- id = reference["id"]
- if (
- repo is None
- and _is_workspace_mode()
- and isinstance(reference.get("repository"), str)
- ):
- repo = reference["repository"]
- if id:
- if repo == "all":
- return _unsupported_repo_all("get_why (reference lookup)")
- return _stamp_answer_basis(await _why_reference(id, repo, reference=reference))
-
- # --- repo="all": search decisions across ALL repos ---
- if repo == "all":
- if not query:
- return _unsupported_repo_all("get_why (health dashboard)")
- return _stamp_answer_basis(await _why_workspace_search(query))
-
- # --- Mode 1: No query → the targets, or the health dashboard ---
- # Targets first: a caller who named files and asked nothing has asked about
- # those files. Reaching the dashboard from here returned the same bytes for
- # every target and for no arguments at all, so the answer never mentioned
- # what was asked about.
- if not query:
- if targets:
- return _stamp_answer_basis(await _why_targets(list(targets), repo))
- # The dashboard is an orientation call, not an answer, so it carries no
- # basis to name.
- return await _why_health_dashboard(repo)
-
- # --- Mode 2: Path → decisions, origin story, alignment ---
- if _is_path(query):
- return _stamp_answer_basis(await _why_path(query, repo))
-
- # --- Mode 3: Natural language → target-aware search ---
- return _stamp_answer_basis(await _why_search(query, targets, repo))
-
-
-async def _why_reference(
- reference_id: str,
- repo: str | None,
- *,
- reference: dict[str, Any] | None = None,
-) -> dict[str, Any]:
- """Resolve one emitted decision/evidence id without relevance search."""
-
- ctx, repository, records, _target_git, accepted = await _load_corpus(repo, None)
- async with get_session(ctx.session_factory) as session:
- await _attach_decision_evidence(session, records)
- # This tool tells callers to hold onto the ids it emits, so an id quoted
- # from an earlier session may name a decision that has since moved.
- # Follow the alias for one that no longer matches anything live; a live
- # id is left alone, so a merged candidate still answers about itself.
- stale_decision_id = not reference_id.startswith("ev_") and not any(
- record.id == reference_id for record in records
- )
- if stale_decision_id:
- reference_id = await resolve_decision_id(session, reference_id) or reference_id
-
- payload = {
- "decisions": [
- _governing_decision_entry(
- record,
- filter_path_list(
- json.loads(record.affected_files_json or "[]"),
- _get_exclude_spec(ctx.path),
- ),
- [],
- accepted=accepted,
- )
- for record in records
- ]
- }
- await annotate_response_evidence_async(
- payload,
- ctx.alias,
- records,
- repo_root=ctx.path,
- )
- matches = [
- row
- for row in payload["decisions"]
- if row["id"] == reference_id
- or any(ref["id"] == reference_id for ref in row.get("evidence_refs", []))
- ]
- matching_refs = {
- ref["id"]: ref
- for row in matches
- for ref in row.get("evidence_refs", [])
- if ref["id"] == reference_id
- }
- if not matches and reference_id.startswith("ev_"):
- live_ref = _resolve_unattached_evidence_reference(
- reference_id, ctx.alias, ctx.path
- )
- if live_ref is not None:
- matching_refs[live_ref["id"]] = live_ref
- if (
- reference is not None
- and matching_refs
- and _evidence_reference_matches_id(reference)
- ):
- matching_refs[reference_id] = dict(reference)
- meta = _build_meta(repository=repository)
- persistence = (payload.get("_meta") or {}).get("reference_persistence")
- if persistence is not None:
- meta["reference_persistence"] = persistence
- return {
- "mode": "reference",
- "reference_id": reference_id,
- "resolved": bool(matches or matching_refs),
- "decisions": matches,
- "evidence_refs": list(matching_refs.values()),
- "_meta": meta,
- }
-
-
-def _evidence_reference_matches_id(value: dict[str, Any]) -> bool:
- """Validate the identity-bearing coordinates of a structured evidence ref."""
-
- from repowise.server.mcp_server._references import reference as build_reference
-
- identifier = value.get("id")
- repository = value.get("repository")
- kind = value.get("kind")
- if not all(isinstance(item, str) for item in (identifier, repository, kind)):
- return False
- coordinate_keys = {
- "commit": ("commit",),
- "file_range": ("path", "range"),
- "file_content": ("path", "line", "content_id"),
- "legacy": ("path", "content_id", "commit_prefix"),
- }.get(kind)
- if coordinate_keys is None:
- return False
- coordinates = {key: value[key] for key in coordinate_keys if key in value}
- return build_reference(kind, repository, **coordinates)["id"] == identifier
-
-
-def _resolve_unattached_evidence_reference(
- reference_id: str,
- repository: str,
- repo_root: str | Path,
-) -> dict[str, Any] | None:
- """Resolve evidence not attached to a persisted decision without a repo scan."""
-
- from repowise.server.mcp_server._references import repository_identity
- from repowise.server.mcp_server._why_evidence import (
- resolve_cached_evidence_reference,
- resolve_persisted_evidence_reference,
- )
-
- repository = repository_identity(repository)
- return resolve_cached_evidence_reference(
- repository, reference_id
- ) or resolve_persisted_evidence_reference(repository, reference_id, repo_root)
-
-
-async def _why_workspace_search(query: str) -> dict:
- """repo="all": the question single-repo search answers, across the workspace.
-
- This used to be the whole tool as it stood before the relevance work: match
- any query word as a substring, append in whatever order the workspace
- resolved its stores, serve fifteen whole records. That is the shape the
- single-repo mode was rebuilt away from, still reachable one argument away and
- over several stores at once. It now loads its corpus the way ``_load_corpus``
- does, so dismissed tombstones and records anchored entirely in excluded
- paths stop being served here alone, and it ranks with the shared machinery, so
- a question the workspace cannot answer gets the redirect rather than fifteen
- records that happen to contain "the".
-
- **Each store is scored against its own corpus, never a pooled one**, and the
- consequence is asymmetric. The floor keeps the meaning it was swept for:
- ``relevance`` is a normalised share of the question's weight, so it survives
- a uniform rescale of the idf vector untouched. What a pooled corpus moves is
- the *ratio* between term weights, and with it which records clear 0.6.
- Scoring each store on its own statistics keeps that filter the one that was
- calibrated. The merge is where the cost lands, and it is a real one: the cut
- below is decided across stores whose scores come from different
- distributions, since a large store polarises toward 0 and 1 while a small one
- lands mid-range. So which store loses a slot is settled approximately, and
- that is a *selection*, not merely an order. It is the price of not silently
- re-scaling a constant nobody re-swept. The upgrade path, if workspace
- ranking ever needs to be exact, is to sweep a floor against a pooled corpus,
- not to pool the statistics underneath the floor that exists.
- """
- contexts = await _resolve_all_contexts()
- scored: list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]] = []
- for ctx in contexts:
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- records = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
- ranked = _score_keyword_matches(records, query, set())
- # Collapsed per store, not across the merge: ``_evidence_key`` is a
- # (source, commit) pair carrying no repo, so two stores sharing a commit
- # sha would fold into one and a repo would lose its record.
- key_by_id = {d.id: key for key, d in ranked}
- for d, folded in _collapse_restatements([d for _, d in ranked]):
- scored.append((key_by_id[d.id], ctx.alias, ctx, d.id, d, folded))
-
- if not scored:
- return {
- "mode": "search",
- "query": query,
- "workspace": True,
- "decisions": [],
- **redirect_for(query),
- "_meta": _build_meta(),
- }
-
- # The store's own key first, so relevance, occurrence count and status decide
- # as they do within one repo; alias and id only settle what those three leave
- # equal, and are here so the answer is the same on two runs.
- scored.sort(key=lambda t: (t[0], t[1], t[3]))
- selected = scored
- collector = OmissionCollector(
- "get_why", repo_root=selected[0][2].path if selected else None
- )
- for selected_ctx in {entry[2].alias: entry[2] for entry in selected}.values():
- selected_records = [entry[4] for entry in selected if entry[2] is selected_ctx]
- async with get_session(selected_ctx.session_factory) as session:
- await _attach_decision_evidence(session, selected_records)
- decisions: list[dict] = []
- entries_by_alias: dict[str, list[dict[str, Any]]] = {}
- records_by_alias: dict[str, list[Any]] = {}
- contexts_by_alias = {entry[1]: entry[2] for entry in selected}
- for _, alias, _selected_ctx, _id, d, folded in selected:
- entry = {
- "repo": alias,
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "decision": _decision_body(d),
- "rationale": d.rationale,
- "source": d.source,
- "confidence": d.confidence,
- }
- if folded:
- entry["restates"] = folded
- entries_by_alias.setdefault(alias, []).append(entry)
- records_by_alias.setdefault(alias, []).append(d)
- decisions.append(entry)
- for alias, entries in entries_by_alias.items():
- await annotate_response_evidence_async(
- {"decisions": entries},
- alias,
- records_by_alias[alias],
- repo_root=contexts_by_alias[alias].path,
- )
- result = {
- "mode": "search",
- "query": query,
- "workspace": True,
- "decisions": decisions,
- "_meta": _build_meta(),
- }
- cap_collection(
- result,
- "decisions",
- decisions,
- _MAX_WORKSPACE_DECISIONS,
- collector,
- label=f"workspace decisions beyond cap={_MAX_WORKSPACE_DECISIONS}",
- )
- collector.attach(result)
- return result
-
-
-async def _why_health_dashboard(repo: str | None) -> dict:
- """Mode 1: no query — return the decision health dashboard."""
- from repowise.core.persistence.crud import get_decision_health_summary
-
- ctx = await _resolve_repo_context(repo)
- collector = OmissionCollector("get_why", repo_root=ctx.path)
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- health = await get_decision_health_summary(session, repository.id)
-
- stale = health["stale_decisions"]
- proposed = health["proposed_awaiting_review"]
- ungoverned = health["ungoverned_hotspots"]
- retired = health["retired_decisions"]
- unscoped = health["unscoped_decisions"]
-
- result_data = {
- "mode": "health",
- "summary": (
- f"{health['summary'].get('active', 0)} active · "
- f"{health['summary'].get('stale', 0)} stale · "
- f"{len(proposed)} proposed · "
- f"{len(ungoverned)} ungoverned hotspots"
- ),
- "counts": health["summary"],
- "stale_decisions": [
- {
- "id": d.id,
- "title": d.title,
- "staleness_score": d.staleness_score,
- "affected_files": filter_path_list(
- json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)
- ),
- }
- for d in stale
- ],
- "proposed_awaiting_review": [
- {
- "id": d.id,
- "title": d.title,
- "source": d.source,
- "confidence": d.confidence,
- }
- for d in proposed
- ],
- "ungoverned_hotspots": ungoverned,
- "conflicts": list(health.get("conflicts", [])),
- # Lanes ``counts`` reported as a number with no list. Query and
- # path mode do reach these records, but only if you already know
- # the question or the path — no mode enumerates either lane, which
- # is what an orientation call is for. ``active`` stays count-only:
- # it is the lane every other mode exists to serve.
- "retired_decisions": [
- {"id": d.id, "title": d.title, "lane": lane} for lane, d in retired
- ],
- "unscoped_decisions": [
- {"id": d.id, "title": d.title, "confidence": d.confidence} for d in unscoped
- ],
- "_meta": _build_meta(repository=repository),
- }
- for entry in result_data["stale_decisions"]:
- cap_collection(
- entry,
- "affected_files",
- entry["affected_files"],
- 5,
- collector,
- label=f"health stale decision {entry['id']} :: affected_files beyond cap=5",
- )
- await _attach_decision_evidence(session, [*stale, *proposed])
- result_data = await annotate_response_evidence_async(
- result_data,
- ctx.alias,
- [*stale, *proposed],
- repo_root=ctx.path,
- )
- for key, cap in (
- ("stale_decisions", _MAX_HEALTH_STALE),
- ("proposed_awaiting_review", _MAX_HEALTH_PROPOSED),
- ("ungoverned_hotspots", _MAX_HEALTH_UNGOVERNED),
- ("conflicts", 10),
- ("retired_decisions", _MAX_HEALTH_RETIRED),
- ("unscoped_decisions", _MAX_HEALTH_RETIRED),
- ):
- cap_collection(
- result_data,
- key,
- result_data[key],
- cap,
- collector,
- label=f"health {key} beyond cap={cap}",
- )
- collector.attach(result_data)
- return result_data
-
-
-# --- Path-mode cap and projection -------------------------------------------
-#
-# Path mode used to return every governing record whole: on ``persist.py`` that
-# was 15 records inlining 241 file paths between them, plus an origin story
-# carrying full commit bodies — 81 854 chars, which the MCP host rejects
-# outright (see ``_budget.budgeter``: over the cap is an isError, not a
-# truncation). The mode that matters most, "what governs this file right before
-# I edit it", hard-failed on exactly the bug-magnet files it exists for.
-#
-# So: rank, project, then enforce. The caps below are the projection; the
-# budget pass after them is the guarantee, since no fixed cap can bound a
-# response whose fields are free text.
-
-#: Governing records kept, best-first. Past ~8 the tail is review-queue noise.
-_MAX_PATH_DECISIONS = 8
-
-#: Candidates inlined beside a path's decisions. Deliberately far below the
-#: decisions cap: this lane exists so a reader knows a queue is there and can
-#: go and work it, not so they can work it from inside a get_why response. A
-#: live index carries 380 candidates, and a hot path can be named by dozens.
-_MAX_PATH_CANDIDATES = 3
-
-#: Paths kept per record. The array answers "how wide is this decision", which
-#: a head plus a total answers as well as 241 paths do.
-_MAX_AFFECTED_FILES = 10
-
-#: Commit *bodies* are the weight in an origin story: the subject is already
-#: capped at 200 chars at ingest, but ``body`` is kept up to 1 KB per
-#: significant commit (``git_indexer/file_history.py``) and up to 10 of those
-#: ride along in ``key_commits``. An origin story reads the intent, not the
-#: whole message.
-_MAX_COMMIT_TEXT_CHARS = 320
-
-#: Headroom left under the budget for ``OmissionCollector.attach``, which adds
-#: ``omission_marker`` + ``_meta.omitted`` *after* the last size check.
-_COLLECTOR_HEADROOM_CHARS = 600
-
-# Ranking uses ``status_rank`` from lifecycle. The local table this file kept
-# had drifted from it: it ranked ``deprecated`` ahead of ``superseded`` while
-# the list endpoint ranked them the other way, so a record moved position
-# depending on which surface was asked.
-
-
-# --- Search-mode caps -------------------------------------------------------
-#
-# Search mode had no caps at all: it served eight whole records with their file
-# arrays inlined, measuring 27 640 - 34 917 chars over five probe questions
-# against a 32 000 budget, so two of the five went over the ceiling outright.
-# The cost was not only transport. On a question the store does answer ("why
-# ruff check and not ruff format", held by two active records) it returned eight
-# records, none of them those, three restating one unrelated decision. A long
-# low-relevance answer teaches an agent that the tool is not worth calling,
-# which is more expensive than a miss.
-#
-# So this mode gets few records served whole rather than many served thin: a
-# padded answer is the failure mode, and thinning every record to keep eight of
-# them is padding with extra steps.
-
-#: Records kept by search mode. Three whole beats eight thinned: past the third
-#: hit the ranking is not trustworthy enough to spend an agent's context on.
-_MAX_SEARCH_DECISIONS = 3
-
-#: Records kept by workspace search. Above the single-repo three because the
-#: answer can genuinely live in more than one store and the repo is part of it;
-#: nowhere near the fifteen whole records this path served before it was ranked.
-_MAX_WORKSPACE_DECISIONS = 5
-
-#: Nearest pages pulled for the *one* semantic lookup search mode makes. Both
-#: lanes (decisions, documentation) are partitioned out of this single window,
-#: so the depth is the old decision lane's rather than the sum of the two.
-_SEMANTIC_WINDOW = 50
-
-#: Records search mode ranks over. It used to be 200, against a store holding
-#: 614: ``list_decisions`` sorts confirmed-then-confident, so the 414 records
-#: below the cut were unreachable by any question, and the cap was a silent
-#: recall ceiling rather than a cost control. It is not a cost control either —
-#: ranking is a substring scan over short fields, measured at 2 ms for 182
-#: records here, so the whole store costs single-digit milliseconds. Kept
-#: bounded only so an unattended extractor cannot turn one call into an
-#: unbounded scan.
-_DECISION_CORPUS_LIMIT = 2000
-
-#: Keyword candidates scored before restatements are collapsed. Wider than the
-#: serving cap on purpose: the worst cluster here is fourteen phrasings of one
-#: decision, so a pool cut to three first would serve one decision three times.
-#: Bounded because the lineage walk after the collapse costs a query per record.
-_KEYWORD_POOL = 24
-
-#: Items per list in the health dashboard. This mode is an orientation call:
-#: asked once, skimmed, acted on twice. It served 45 items to be read as a
-#: verdict. Halved now that ``get_decision_health_summary`` ranks what it
-#: returns: cutting an unranked list only makes a list nobody reads shorter,
-#: cutting a ranked one keeps the part that is worth reading. The full sizes stay
-#: legible in ``counts`` and in the summary line, and every row cut here is
-#: recoverable through the omission collector, so nothing is silently dropped.
-#:
-#: That clause needs a list to be true of: for a count-only lane there was
-#: nothing to recover, which is why the two below exist.
-_MAX_HEALTH_STALE = 5
-_MAX_HEALTH_PROPOSED = 5
-_MAX_HEALTH_UNGOVERNED = 8
-
-#: Retired records and accepted records naming no file. Same 5 as its peers:
-#: a pointer into history, not a place to read it from.
-_MAX_HEALTH_RETIRED = 5
-
-
-def _authority_of(decision_id: str, accepted: set[str]) -> str:
- """``"accepted"`` when an acceptance binds this record, else ``"candidate"``.
-
- The one test that separates the two entities, per
- :func:`~repowise.core.persistence.crud.authority.decision_currencies`:
- membership of the acceptance set, never ``status``. Stamped on every row
- this tool emits so a reader — and :func:`_stamp_answer_basis` — can tell a
- ruling from a guess without a second call.
- """
- return "accepted" if decision_id in accepted else "candidate"
-
-
-def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:
- return (
- status_rank(d.status),
- -(d.confidence or 0.0),
- d.staleness_score or 0.0,
- )
-
-
-def _governing_decision_entry(
- d: Any,
- affected_files: list,
- lineage: list[dict],
- collector: OmissionCollector | None = None,
- accepted: set[str] | None = None,
-) -> dict:
- """Serialize a decision that governs a path, including its lineage chain."""
- entry = {
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "authority": _authority_of(d.id, accepted or set()),
- "context": d.context,
- "decision": _decision_body(d),
- "rationale": d.rationale,
- "alternatives": json.loads(d.alternatives_json),
- "consequences": json.loads(d.consequences_json),
- "affected_files": affected_files[:_MAX_AFFECTED_FILES],
- "source": d.source,
- "confidence": d.confidence,
- "staleness_score": d.staleness_score,
- "lineage": lineage if len(lineage) > 1 else [],
- }
- if len(affected_files) > _MAX_AFFECTED_FILES:
- cap_collection(
- entry,
- "affected_files",
- affected_files,
- _MAX_AFFECTED_FILES,
- collector,
- label=f"decision {d.id} :: affected_files beyond cap={_MAX_AFFECTED_FILES}",
- )
- return entry
-
-
-def _trim_commit_text(origin_story: dict) -> None:
- """Cap commit prose in place, wherever the origin story inlines it.
-
- ``message`` and ``body`` both, because which one carries the weight depends
- on the repo: a squash-merge repo puts the whole rationale in ``body`` and
- the ingest keeps it up to 1 KB, while ``message`` is already capped at 200.
- Capping both means this does not quietly become a no-op if that changes.
- """
-
- def _trim(commits: Any) -> None:
- if not isinstance(commits, list):
- return
- for c in commits:
- if not isinstance(c, dict):
- continue
- for field in ("message", "body"):
- text = c.get(field)
- if isinstance(text, str) and len(text) > _MAX_COMMIT_TEXT_CHARS:
- c[field] = text[:_MAX_COMMIT_TEXT_CHARS] + "…"
-
- _trim(origin_story.get("key_commits"))
- for linked in origin_story.get("linked_decisions") or []:
- if isinstance(linked, dict):
- _trim(linked.get("evidence_commits"))
-
-
-def _cap_origin_story(
- origin_story: dict[str, Any],
- collector: OmissionCollector,
- *,
- label: str,
-) -> None:
- """Bound each origin lane independently and bank its exact omitted rows."""
- for key, cap in (
- ("contributors", 5),
- ("key_commits", 5),
- ("linked_decisions", _MAX_PATH_DECISIONS),
- ):
- rows = origin_story.get(key)
- if isinstance(rows, list):
- cap_collection(
- origin_story,
- key,
- rows,
- cap,
- collector,
- label=f"{label} :: origin.{key} beyond cap={cap}",
- )
- for linked in origin_story.get("linked_decisions") or []:
- if not isinstance(linked, dict):
- continue
- commits = linked.get("evidence_commits")
- if isinstance(commits, list):
- cap_collection(
- linked,
- "evidence_commits",
- commits,
- 5,
- collector,
- label=f"{label} :: origin.linked_decisions.evidence_commits beyond cap=5",
- )
-
-
-def _cap_archaeology(
- archaeology: dict[str, Any], collector: OmissionCollector, *, label: str
-) -> None:
- """Cap fully annotated archaeology lanes without discarding their tails."""
- for key, cap in (("file_commits", 10), ("cross_references", 10), ("git_log", 20)):
- rows = archaeology.get(key)
- if isinstance(rows, list):
- cap_collection(
- archaeology,
- key,
- rows,
- cap,
- collector,
- label=f"{label} :: archaeology.{key} beyond cap={cap}",
- )
-
-
-def _cap_supporting_lanes(
- result: dict[str, Any], collector: OmissionCollector, *, label: str
-) -> None:
- """Cap supporting Why lanes only after evidence annotation is complete."""
- origin = result.get("origin_story")
- if isinstance(origin, dict):
- _cap_origin_story(origin, collector, label=label)
- archaeology = result.get("git_archaeology")
- if isinstance(archaeology, dict):
- _cap_archaeology(archaeology, collector, label=label)
- rationale = result.get("code_rationale")
- if isinstance(rationale, list):
- cap_collection(
- result,
- "code_rationale",
- rationale,
- 5,
- collector,
- label=f"{label} :: code_rationale beyond cap=5",
- )
- for target, context in (result.get("target_context") or {}).items():
- if not isinstance(context, dict):
- continue
- target_origin = context.get("origin")
- if isinstance(target_origin, dict):
- _cap_origin_story(target_origin, collector, label=target)
- target_archaeology = context.get("git_archaeology")
- if isinstance(target_archaeology, dict):
- _cap_archaeology(target_archaeology, collector, label=target)
-
-
-def _prepare_episode_bodies(
- population: list[dict[str, Any]],
- visible_count: int,
- pending: list[tuple[dict, str, str]],
- collector: OmissionCollector,
- repo_root: Path,
-) -> OmissionCollector:
- """Inline-bank visible long bodies; keep omitted episode rows byte-complete."""
- visible_ids = {id(entry) for entry in population[:visible_count]}
- visible_pending: list[tuple[dict, str, str]] = []
- for entry, label, body in pending:
- if id(entry) in visible_ids:
- visible_pending.append((entry, label, body))
- else:
- entry["recorded"] = body
- return bank_overflow(
- visible_pending,
- tool="get_why",
- repo_root=repo_root,
- collector=collector,
- ) or collector
-
-
-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
- text ones, which no fixed cap can — a single record's ``rationale`` is
- unbounded, and the ungoverned-file branch returns git archaeology instead
- of decisions and so is not capped by any of them.
-
- Stages, cheapest loss first:
-
- 1. Drop ``origin_story.linked_decisions``, which re-inlines each record's
- title, rationale and matched commits — all of it already in
- ``decisions``.
- 2. Drop the candidate lane whole. A candidate is a review request, and a
- response that cannot afford the rules it must not spend on the queue.
- 3. Drop governing records from the tail, all the way to none if it comes
- to that. They are sorted best-first, so the tail is review-queue noise,
- and an empty list plus a marker beats a rejected response.
- 4. Trim the fallback blocks the ungoverned branch adds (``code_rationale``,
- then ``git_archaeology``) to a tail, dropping them whole only if that is
- not enough, then ``origin_story``. What survives — mode, path,
- alignment, ``_meta`` — is bounded.
-
- 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.
- """
-
- def _over() -> bool:
- return over_budget(result_data, headroom=_COLLECTOR_HEADROOM_CHARS)
-
- if not _over():
- if collector is not None:
- collector.attach(result_data)
- return result_data
-
- if collector is None:
- collector = OmissionCollector("get_why", repo_root=repo_root)
-
- def _shed(*order: str) -> None:
- fit_to_budget(
- result_data,
- order,
- collector,
- headroom=_COLLECTOR_HEADROOM_CHARS,
- record_counts=True,
- )
-
- # Episodes go before the governing records, not after: they 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.
- # ``episodes[]`` floors at one row, so the whole-block entry behind it is
- # what still empties the lane before the decisions loop below. Trimming
- # first is why mild pressure costs rows: this served 0 of 20.
- # Candidates first of everything: they are the one lane whose whole
- # purpose is to be reviewed later, so under pressure they are the cheapest
- # thing in the response to lose. Their note goes with them, because a
- # sentence counting candidates that are no longer in the payload is worse
- # than no sentence.
- _shed(
- "origin_story.linked_decisions",
- "history[]",
- "history",
- "candidates[]",
- "candidates",
- )
- for lane_key in ("candidates", "history"):
- if not result_data.get(lane_key):
- result_data.pop(f"{lane_key}_note", None)
-
- _shed("episodes[]", "episodes")
-
- decisions: list = result_data.get("decisions") or []
- while decisions and _over():
- dropped = decisions.pop()
- collector.add(f"dropped governing decision {dropped.get('title', '')}", dropped)
- result_data["truncated"] = True
- result_data.setdefault("dropped_decisions", []).append(dropped.get("id", ""))
- if "decisions_total" in result_data:
- result_data["decisions_emitted"] = len(decisions)
- if len(decisions) < result_data["decisions_total"]:
- prior = result_data.get("decisions_reduced_reason")
- result_data["decisions_reduced_reason"] = (
- "construction_cap_and_response_budget"
- if prior == "construction_cap"
- else "response_budget"
- )
- result_data["decisions_truncated"] = True
- result_data["decisions_omitted"] = result_data["decisions_total"] - len(decisions)
-
- # The ungoverned branch's whole answer, and it served 0 of 58 mined
- # rationale comments on a file with no governing record at all.
- _shed(
- "code_rationale[]",
- "git_archaeology.file_commits[]",
- "git_archaeology.cross_references[]",
- "git_archaeology.git_log[]",
- "code_rationale",
- "git_archaeology.file_commits",
- "git_archaeology.cross_references",
- "git_archaeology.git_log",
- "origin_story",
- )
-
- collector.attach(result_data)
- return result_data
-
-
-async def _why_path(query: str, repo: str | None) -> dict:
- """Mode 2: query is a path — governing decisions, origin story, alignment."""
- ctx = await _resolve_repo_context(repo)
- collector = OmissionCollector("get_why", repo_root=ctx.path)
- if is_excluded(query, _get_exclude_spec(ctx.path)):
- return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- res = await session.execute(
- select(DecisionRecord).where(
- DecisionRecord.repository_id == repository.id,
- )
- )
- all_decisions = res.scalars().all()
-
- # Load git metadata for origin story
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- GitMetadata.file_path == query,
- )
- )
- git_meta = git_res.scalar_one_or_none()
-
- # Pre-load all git metadata for cross-file search (used by fallback)
- all_git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- )
- )
- all_git_meta = all_git_res.scalars().all()
-
- # A record whose file list is the footprint of the commit it was
- # mined from does not answer "what governs this file". It keeps its
- # files and its place in search; it stops claiming to be specific.
- matched = [
- d
- for d in all_decisions
- if binds_to_paths(d.scope_basis)
- and (
- query in json.loads(d.affected_files_json)
- or query in json.loads(d.affected_modules_json)
- )
- ]
- # The authority split, and the only test that makes it: a record with
- # no acceptance row is a candidate whatever its status column says.
- # Computed over every record in the repository, because the sibling
- # coverage inside alignment reads records this path did not match.
- currencies = await decision_currencies(session, repository.id, all_decisions)
-
- # Rank before capping, so the 8 that survive are the 8 that govern —
- # not whichever 8 the table scan happened to yield first.
- matched.sort(key=_path_decision_sort_key)
- lineage_by_id = await _lineage_for_records(session, matched, all_decisions)
- governing: list[dict] = []
- candidates: list[dict] = []
- retired: list[dict] = []
- for d in matched:
- # Walk supersedes/refines back to roots so the answer is a
- # lineage chain (sessions → JWT → OAuth2), not a flat list.
- lineage = lineage_by_id.get(d.id, [])
- entry = _governing_decision_entry(
- d, json.loads(d.affected_files_json), lineage, collector
- )
- currency = currencies.get(d.id)
- if currency is None:
- entry["authority"] = "candidate"
- # Never accepted. It goes in its own lane, labelled, rather
- # than into the list an agent reads as the rules for this file.
- entry["review_state"] = "open"
- candidates.append(entry)
- continue
- entry["currency"] = currency
- if is_governing(currency):
- entry["authority"] = "accepted"
- governing.append(entry)
- else:
- # Accepted once, withdrawn since: not a ruling any more, so it
- # must not read as one to ``_stamp_answer_basis`` either.
- entry["authority"] = "withdrawn"
- # Accepted once and withdrawn since. Not a rule and not a
- # review request, so it gets a third lane rather than being
- # dropped: on a file whose only record was superseded, dropping
- # it left the answer with nothing to say about the one thing
- # anybody had ever decided there.
- retired.append(entry)
-
- # Ask git whether the top governing record still holds — and only the
- # top one. The query is ~60 ms, which is affordable once inside an MCP
- # call and is not affordable eight times; the record ranked first is
- # the one a reader acts on. Everything below it keeps the stored
- # proportion, which needed no subprocess to compute. A candidate never
- # gets the check: it is not something anyone should be acting on.
- if governing:
- top = next(d for d in matched if d.id == governing[0]["id"])
- sentence = await asyncio.to_thread(
- describe_decision_currency,
- ctx.path,
- created_at=top.created_at,
- nodes=json.loads(top.affected_files_json or "[]"),
- )
- if sentence:
- governing[0]["still_true"] = sentence
-
- # Every lane: the origin story is history, and a commit that matches a
- # candidate's or a retired record's title is still the commit that
- # explains the file. It is evidence, not instruction, so nothing here
- # needs the authority test.
- origin_story = _build_origin_story(
- query, git_meta, governing + candidates + retired
- )
-
- result_data: dict[str, Any] = {
- "mode": "path",
- "path": query,
- "decisions": governing,
- "origin_story": origin_story,
- # Alignment is scored over every matching record, not just the
- # ones that survived the cap — it is a coverage number, and
- # capping its input would make a well-governed hotspot look thin.
- # It reads the id, the title and the acceptance map, so the cheap
- # projection is the whole of what it needs.
- "alignment": _compute_alignment(
- query,
- [{"id": d.id, "title": d.title} for d in matched],
- all_decisions,
- currencies,
- ),
- }
- if candidates:
- # Named, counted and separated from the rules. An agent reading
- # this must be able to tell a request to review something from an
- # instruction to follow it, without parsing a status string.
- result_data["candidates"] = candidates
- result_data["candidates_note"] = (
- f"{len(candidates)} candidate(s) mention this path and none of them "
- "govern it. Nobody has accepted them, so they are a review "
- "request, not a rule. A person accepts one with "
- "`repowise decision confirm <id> --scope <path>`. An agent "
- "cannot, unless this repository has allowed it; where it has, "
- "pass `--agent <your slug>` so the acceptance is not recorded "
- "under a person's name."
- )
-
- if retired:
- # Named as history, never as a rule. A reader asking why a file
- # looks the way it does is owed "this was decided and then
- # replaced", which is the sentence a dropped record cannot say.
- result_data["history"] = retired
- result_data["history_note"] = (
- f"{len(retired)} decision(s) governing this path were accepted "
- "and have since been superseded or withdrawn. They are history, "
- "not rules."
- )
-
- # --- Fallback: git archaeology when no accepted decision governs ---
- if not governing:
- result_data["git_archaeology"] = await _git_archaeology_fallback(
- query,
- git_meta,
- all_git_meta,
- repository,
- collector,
- )
- # Decisions and git history both silent → the "why" may live in a
- # code comment. Mine this file's rationale comments directly.
- rationale = _mine_rationale(
- ctx.path, [query], None, max_results=1000, truncate_blocks=False
- )
- 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.
- episode_population: list[dict] = []
- episodes, pending = await asyncio.to_thread(
- episode_evidence,
- ctx.path,
- paths=[query],
- full_population=episode_population,
- )
- if episodes:
- collector = _prepare_episode_bodies(
- episode_population, len(episodes), pending, collector, ctx.path
- )
- result_data["episodes"] = episode_population
-
- result_data["_meta"] = _build_meta(repository=repository)
- await _attach_response_decision_evidence(session, result_data, all_decisions)
- await annotate_response_evidence_async(
- result_data, ctx.alias, all_decisions, repo_root=ctx.path
- )
- _cap_supporting_lanes(result_data, collector, label=query)
- if episodes:
- cap_collection(
- result_data,
- "episodes",
- result_data["episodes"],
- len(episodes),
- collector,
- label="episodes beyond construction cap",
- )
- cap_collection(
- result_data,
- "decisions",
- result_data["decisions"],
- _MAX_PATH_DECISIONS,
- collector,
- label=f"path decisions beyond cap={_MAX_PATH_DECISIONS}",
- )
- for lane_key in ("candidates", "history"):
- if result_data.get(lane_key):
- cap_collection(
- result_data,
- lane_key,
- result_data[lane_key],
- _MAX_PATH_CANDIDATES,
- collector,
- label=f"path {lane_key} beyond cap={_MAX_PATH_CANDIDATES}",
- )
- return _fit_path_response(result_data, ctx.path, collector=collector)
-
-
-async def _load_target_git(
- session: Any, repository_id: Any, targets: list[str] | None
-) -> dict[str, Any]:
- """Load per-target git metadata keyed by file path (only present ones)."""
- target_git: dict[str, Any] = {}
- if not targets:
- return target_git
- for t in targets:
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository_id,
- GitMetadata.file_path == t,
- )
- )
- meta = git_res.scalar_one_or_none()
- if meta:
- target_git[t] = meta
- return target_git
-
-
-def _score_keyword_matches(
- all_decisions: list, query: str, target_set: set[str]
-) -> list[tuple[tuple[float, float, int], Any]]:
- """``_rank_keyword_matches`` with each record's whole sort key kept beside it.
-
- Split out for workspace search, which ranks one store at a time and then has
- to merge the survivors. It is the *whole* key rather than the score because a
- merge that kept only the score would silently drop the other two rules: the
- occurrence-count tie-break and the status tie-break both exist because
- ``relevance`` is a share of one idf vector, so any two records covering the
- same set of question terms score bit-identically and something has to
- separate them. The floor and the ordering rules are documented on
- ``_rank_keyword_matches``; this returns the key that implements them.
- """
- terms = question_terms(query)
- texts = {id(d): _record_text(d) for d in all_decisions}
- idf = term_idf(terms, list(texts.values()))
-
- scored_decisions: list[tuple[float, float, int, Any]] = []
- for d in all_decisions:
- # Naming a file used to be a floor bypass: a record governing a target
- # scored 1.0 outright, on the reasoning that a caller who pointed at a
- # file instead of describing it left the record owing the question no
- # vocabulary. That reasoning holds for a call with *no* query, and this
- # function is never reached without one. With a query it meant the same
- # store, the same question and the same second refused without targets
- # and answered with them — measured on this repo, "why does
- # changed_lines() drop deletion-only files" came back led by "Move risk
- # scale reference metadata behind opt-in inclusion", whose only claim to
- # the question was appearing in the same directory.
- #
- # So every record is scored on what it says about the question. Naming a
- # target stays worth 5.0 in the ``_score_decision`` tie-break below, so a
- # governing record still outranks an equally relevant stranger; it just
- # no longer enters on a file path alone.
- score = relevance(texts[id(d)], idf)
- if not clears_floor(score):
- continue
- scored_decisions.append(
- (
- -score,
- -_score_decision(d, set(terms), target_set),
- status_rank(d.status),
- d,
- )
- )
- scored_decisions.sort(key=lambda t: (t[0], t[1], t[2]))
- return [((t[0], t[1], t[2]), t[3]) for t in scored_decisions]
-
-
-def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:
- """Records relevant enough to serve, best-first. Empty when none are.
-
- Ranks by how much of the question's *vocabulary* a record carries, rarer
- words weighing more, with the older occurrence count breaking ties and
- status breaking the ties after that. Ordering by the occurrence count alone
- scored by length and by how ordinary a word is: measured here, "why do we
- use ruff check instead of ruff format" was won by records matching "use",
- "check", "format" and "instead" while the two ``active`` records that answer
- it — one of them 48 characters long — did not place at all.
-
- Status stays a tie-break and never a gate. Ordering by it *first* was tried
- and measured worse, and the reason generalises: only 69 of this repo's 614
- records are active, so a hard status gate serves three weakly-matching
- confirmed records ahead of the only relevant ones. The four records that
- answer "why is entry-point candidacy decided at ingestion" are all proposed,
- and status-first ordering made them unreachable.
-
- Records below the floor are dropped rather than ranked last, so an empty
- return is the honest answer and the caller turns it into a redirect. The
- surviving pool is wider than the serving cap because restatements are
- collapsed downstream, and a pool cut to the cap first would let three
- phrasings of one decision fill every slot.
- """
- return [d for _, d in _score_keyword_matches(all_decisions, query, target_set)]
-
-
-async def _fts_doc_results(ctx: Any, query: str) -> list:
- """Documentation hits from the lexical index.
-
- The keyless path, and the fallback whenever the vector store is present but
- unusable: a store that cannot rank gives the same answer as no store.
- """
- doc_results: list = []
- with contextlib.suppress(Exception):
- doc_results = await ctx.fts.search(query, limit=_SEMANTIC_WINDOW)
- return doc_results
-
-
-async def _semantic_lanes(ctx: Any, query: str) -> tuple[list, list]:
- """``(decision_hits, doc_hits)`` from **one** embedding of *query*.
-
- These were two awaits embedding the same string back to back, so every
- search-mode call paid two network round trips to ask one question. One
- ``embed_texts`` plus ``search_by_vector`` is the documented way to spend one
- (see ``vector_store._base``), and ``search`` remains the fallback for a
- backend that cannot search by raw vector.
-
- Partitioning one window also fixes a quieter bug: the doc lane took the
- nearest three pages *of any kind*, so decision records were being served
- back as "related documentation" beside the decisions list they came from.
- Splitting by namespace gives each lane only what belongs to it.
-
- The decision lane stays empty on a keyless index, deliberately: there is no
- lexical fallback for it, because a window of arbitrary decisions is worse
- than none for a tool whose whole job is explaining one specific thing.
- """
- if not store_has_semantic_vectors(getattr(ctx, "vector_store", None)):
- return [], await _fts_doc_results(ctx, query)
-
- raw: list | None = None
- with contextlib.suppress(Exception):
- vectors = await ctx.vector_store.embed_texts([query])
- if vectors:
- raw = await ctx.vector_store.search_by_vector(vectors[0], limit=_SEMANTIC_WINDOW)
- if raw is None:
- # Backend holds no embedder, or cannot search by raw vector.
- raw = await ctx.vector_store.search(query, limit=_SEMANTIC_WINDOW)
- if raw is None:
- return [], await _fts_doc_results(ctx, query)
-
- decision_hits, doc_hits = [], []
- for r in raw:
- page_id = getattr(r, "page_id", "")
- if page_id.startswith(DECISION_VECTOR_PREFIX):
- decision_hits.append(r)
- else:
- doc_hits.append(r)
- return decision_hits, doc_hits
-
-
-async def _lineage_for_records(
- session: Any, candidates: list[Any], all_decisions: list[Any]
-) -> dict[str, list[dict]]:
- """Build every candidate lineage from one edge query and in-memory records."""
- if not candidates:
- return {}
- edges = list(
- (
- await session.execute(
- select(DecisionEdge).where(
- DecisionEdge.repository_id == candidates[0].repository_id,
- DecisionEdge.kind.in_(("supersedes", "refines")),
- )
- )
- )
- .scalars()
- .all()
- )
- outgoing: dict[str, list[Any]] = {}
- for edge in edges:
- outgoing.setdefault(edge.src_decision_id, []).append(edge)
- for rows in outgoing.values():
- rows.sort(
- key=lambda edge: (
- edge.kind == "supersedes",
- edge.confidence or 0.0,
- edge.dst_decision_id,
- ),
- reverse=True,
- )
- records = {record.id: record for record in all_decisions}
- edge_record_ids = {
- decision_id
- for edge in edges
- for decision_id in (edge.src_decision_id, edge.dst_decision_id)
- }
- missing_ids = edge_record_ids - records.keys()
- if missing_ids:
- missing_records = list(
- (
- await session.execute(
- select(DecisionRecord).where(DecisionRecord.id.in_(missing_ids))
- )
- )
- .scalars()
- .all()
- )
- records.update({record.id: record for record in missing_records})
- result: dict[str, list[dict]] = {}
- for candidate in candidates:
- order: list[tuple[str, str | None]] = []
- visited: set[str] = set()
- current = candidate.id
- relation: str | None = None
- while current and current not in visited and len(order) < 50:
- visited.add(current)
- order.append((current, relation))
- edge = next(
- (
- row
- for row in outgoing.get(current, [])
- if row.dst_decision_id not in visited
- ),
- None,
- )
- if edge is None:
- break
- current = edge.dst_decision_id
- relation = edge.kind
- if len(order) <= 1:
- continue
- chain = []
- for decision_id, kind in reversed(order):
- record = records.get(decision_id)
- if record is not None:
- chain.append(
- {
- "id": record.id,
- "title": record.title,
- "status": record.status,
- "source": record.source,
- "relation": kind,
- }
- )
- if len(chain) > 1:
- result[candidate.id] = chain
- return result
-
-
-async def _lineage_for_matches(
- ctx: Any, keyword_matches: list, all_decisions: list[Any]
-) -> dict[str, list[dict]]:
- """Build all keyword lineages with one bounded edge query."""
- if not keyword_matches:
- return {}
- async with get_session(ctx.session_factory) as session3:
- return await _lineage_for_records(session3, keyword_matches, all_decisions)
-
-
-def _evidence_key(d: Any) -> tuple[object, ...] | None:
- """The evidence a record cites, as a merge key, or ``None`` when it cites none.
-
- Re-extraction paraphrases a record's prose but not its provenance. The
- fourteen records on this repo that all restate one LIKE-escaping decision
- carry fourteen titles and fourteen ids and the same single
- ``evidence_commits`` entry; comment-sourced restatements repeat an
- ``evidence_file`` instead. Store-wide, 478 of 614 records sit in a cluster
- like that, which is why one query could return five phrasings of one
- decision.
-
- So the key is every cited full commit, or one exact source range, plus the
- extractor that read it, never the text. Normalising titles would need a
- tuned similarity threshold, and a wrong merge there hides a human-confirmed
- record. Incomplete commit hashes and file-only coordinates return ``None``:
- preserving an apparent duplicate is safer than erasing a real decision.
-
- This local decision-restatement key is intentionally narrower than the
- public evidence ids. A commit can support several real decisions, so shared
- public evidence never merges decision rows by itself.
- """
- return decision_collapse_key(d)
-
-
-def _collapse_restatements(records: list) -> list[tuple[Any, list[str]]]:
- """``(kept, folded_ids)`` per distinct decision, input order preserved.
-
- Runs on records rather than on the projected dicts so the collapse happens
- *before* the lineage walk and the projection, neither of which should spend
- work on three phrasings of one decision. Records citing no evidence at all
- cannot be compared this way and are always kept.
- """
- by_evidence: dict[tuple[object, ...], int] = {}
- out: list[tuple[Any, list[str]]] = []
- for d in records:
- key = _evidence_key(d)
- if key is not None and key in by_evidence:
- out[by_evidence[key]][1].append(d.id)
- continue
- if key is not None:
- by_evidence[key] = len(out)
- out.append((d, []))
- return out
-
-
-def _merge_decisions(
- keyword_matches: list[tuple[Any, list[str]]],
- decision_results: list,
- lineage_by_id: dict[str, list[dict]],
- collector: OmissionCollector | None = None,
- accepted: set[str] | None = None,
-) -> list[dict]:
- """Project collapsed keyword hits, then append semantic hits not already in.
-
- *keyword_matches* arrives from :func:`_collapse_restatements`, so the folded
- ids ride along on ``restates``: nothing becomes unaddressable and the store
- is untouched.
- """
- seen_ids: set[str] = set()
- merged_decisions: list[dict] = []
- for d, folded in keyword_matches:
- if d.id in seen_ids:
- continue
- seen_ids.update([d.id, *folded])
- affected_files = json.loads(d.affected_files_json)
- entry = {
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "authority": _authority_of(d.id, accepted or set()),
- "decision": _decision_body(d),
- "rationale": d.rationale,
- "context": d.context,
- "consequences": json.loads(d.consequences_json),
- # Whole arrays reached 83 paths and 4 812 chars, 36% of the payload
- # across the eight records served. A head plus a total answers "how
- # wide is this decision" as well, and path mode already says so.
- "affected_files": affected_files[:_MAX_AFFECTED_FILES],
- "source": d.source,
- "confidence": d.confidence,
- "lineage": lineage_by_id.get(d.id, []),
- }
- if len(affected_files) > _MAX_AFFECTED_FILES:
- cap_collection(
- entry,
- "affected_files",
- affected_files,
- _MAX_AFFECTED_FILES,
- collector,
- label=f"decision {d.id} :: affected_files beyond cap={_MAX_AFFECTED_FILES}",
- )
- if folded:
- entry["restates"] = folded
- merged_decisions.append(entry)
-
- for r in decision_results:
- # Strip the "decision:" prefix so the returned id matches the SQL primary key.
- real_id = r.page_id[len(DECISION_VECTOR_PREFIX) :]
- if real_id in seen_ids:
- continue
- seen_ids.add(real_id)
- merged_decisions.append(
- {
- "id": real_id,
- "title": r.title,
- "snippet": r.snippet,
- "relevance_score": r.score,
- "authority": _authority_of(real_id, accepted or set()),
- }
- )
- return merged_decisions
-
-
-async def _build_target_context(
- ctx: Any,
- repository: Any,
- all_decisions: list,
- target_git: dict[str, Any],
- targets: list[str],
- collector: OmissionCollector | None = None,
- accepted: set[str] | None = None,
-) -> dict[str, Any]:
- """Per-target governing decisions + origin story, with archaeology fallback.
-
- ``governing_decisions`` holds only records an acceptance binds; unaccepted
- ones go to ``candidate_decisions`` under the name they have earned. The two
- lanes were one, and on a store with no acceptances — the state of every
- repository whose maintainer has not worked through the acceptance UI — that
- one lane presented candidates as governing the file.
-
- The archaeology fallback is therefore keyed on the *accepted* lane. A file
- whose only records are candidates is a file no decision governs, which is
- exactly the case the fallback exists for, and its commits are stronger
- evidence than an unconfirmed candidate is.
- """
- async with get_session(ctx.session_factory) as session2:
- # Load all git metadata for cross-file search
- all_git_res = await session2.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- )
- )
- all_git_meta_list = all_git_res.scalars().all()
-
- target_context: dict[str, Any] = {}
- for t in targets:
- governing_records = []
- for d in all_decisions:
- # Same gate as ``_why_path``, which one target routes to.
- if not binds_to_paths(d.scope_basis):
- continue
- affected = json.loads(d.affected_files_json)
- affected_mods = json.loads(d.affected_modules_json)
- if t in affected or any(t.startswith(m + "/") for m in affected_mods):
- governing_records.append(d)
- governing_records.sort(key=_path_decision_sort_key)
- accepted_ids = accepted or set()
- rows = [
- {
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "source": d.source,
- "authority": _authority_of(d.id, accepted_ids),
- }
- for d in governing_records
- ]
- t_governing = [r for r in rows if r["authority"] == "accepted"]
- t_candidates = [r for r in rows if r["authority"] != "accepted"]
- git_m = target_git.get(t)
- origin = (
- _build_origin_story(t, git_m, t_governing)
- if git_m
- else {
- "available": False,
- "summary": f"No git history for {t}.",
- }
- )
- ctx_entry: dict[str, Any] = {
- "governing_decisions": t_governing,
- "origin": origin,
- }
- if t_candidates:
- ctx_entry["candidate_decisions"] = t_candidates
- # Git archaeology fallback when no *accepted* decision governs
- if not t_governing:
- ctx_entry["git_archaeology"] = await _git_archaeology_fallback(
- t,
- git_m,
- all_git_meta_list,
- repository,
- collector,
- )
- target_context[t] = ctx_entry
- return target_context
-
-
-def _focus_target_context(
- target_context: dict[str, Any],
- query: str,
- targets: list[str],
- corpus: list[str],
-) -> None:
- """Drop from each target card whatever does not bear on *query*, in place.
-
- A target card is built from a path, so without this it answers the same
- bytes to every question asked about that file. Measured on this repo, two
- unrelated questions about ``changed_lines.py`` returned byte-identical
- ``candidate_decisions``, ``origin`` and ``git_archaeology``, together 13,397
- of a 20,000-char response, while the mined comment that answered both sat
- below them.
-
- Only when a query is present. A call with targets and no query *is* the
- dashboard for those files, and there is nothing to be relevant to.
-
- Each block reduces to a count and the call that recovers it in full, never
- to silence: "no history mentions what you asked" and "no history" are
- different answers and the reader has to be able to tell them apart.
- """
- recall = f"get_why(targets={json.dumps(targets)})"
- # One scorer for the whole response, built from the decision corpus — the
- # same vocabulary the ranked lane is judged against, so one question gets
- # one set of term weights everywhere in the answer.
- #
- # Deriving rarity from the card's own handful of strings was tried first and
- # is the degeneracy ``term_idf`` warns about: over three short rows, a word
- # none of them happens to contain outweighs the two that identify the
- # answer, and "why is JWT used for authentication" scored the row titled
- # "Use JWT for authentication" at 0.489 — under the floor, on the strength
- # of the word "used".
- score = query_scorer(query, corpus)
- for entry in target_context.values():
- if not isinstance(entry, dict):
- continue
-
- # ``governing_decisions`` is exempt. An accepted decision binds this
- # file whatever the question was, so a reader asking anything about it
- # is owed the rules — suppressing one for sharing no vocabulary with the
- # question would hide a ruling from the person about to edit the file.
- # A candidate binds nothing, so it has to earn its place like any other
- # unranked text.
- rows = entry.get("candidate_decisions")
- if isinstance(rows, list) and rows:
- kept = [r for r in rows if clears_floor(score(json.dumps(r, default=str)))]
- if kept:
- entry["candidate_decisions"] = kept
- else:
- entry.pop("candidate_decisions", None)
- entry["candidate_decisions_omitted"] = recovery_note(
- len(rows), recall
- )
-
- # Only the origin story's decision lane, not the story. Reducing the
- # whole block was tried and was the wrong cut: it saved ~700 of the
- # 13,397 chars at issue while costing ``primary_author`` and the first
- # commit — facts a reader wants whatever they asked, and cheap. The
- # lane inside it is the query-blind part, because it is decisions again.
- origin = entry.get("origin")
- if isinstance(origin, dict):
- linked = origin.get("linked_decisions")
- if isinstance(linked, list) and linked:
- kept = [
- d for d in linked if clears_floor(score(json.dumps(d, default=str)))
- ]
- if kept:
- origin["linked_decisions"] = kept
- else:
- origin.pop("linked_decisions", None)
- origin["linked_decisions_omitted"] = recovery_note(
- len(linked), recall
- )
-
- arch = entry.get("git_archaeology")
- if isinstance(arch, dict):
- _focus_archaeology(arch, score, recall)
-
-
-def _focus_archaeology(
- arch: dict[str, Any], score: Any, recall: str
-) -> None:
- """Keep the commits that carry the question's terms, count the rest.
-
- Filtered rather than dropped, unlike the decision lanes. A commit message is
- prose somebody wrote about this file, so "which of these commits mention
- what I asked about" is a question it can actually answer — and on the branch
- this block is reached from, no decision cleared the floor, which makes these
- commits the best evidence left.
- """
- for lane in ("file_commits", "cross_references", "git_log"):
- rows = arch.get(lane)
- if not isinstance(rows, list) or not rows:
- continue
- kept = [r for r in rows if clears_floor(score(json.dumps(r, default=str)))]
- if kept:
- arch[lane] = kept
- else:
- arch.pop(lane, None)
- arch[f"{lane}_omitted"] = recovery_note(len(rows), recall)
-
-
-def _cap_target_context(
- target_context: dict[str, Any], collector: OmissionCollector
-) -> None:
- """Cap evidence-enriched per-target decision lanes independently."""
- for target, entry in target_context.items():
- for lane in ("governing_decisions", "candidate_decisions"):
- decisions = entry.get(lane)
- if isinstance(decisions, list):
- cap_collection(
- entry,
- lane,
- decisions,
- _MAX_PATH_DECISIONS,
- collector,
- label=f"{target} :: {lane} beyond cap={_MAX_PATH_DECISIONS}",
- )
-
-
-async def _why_no_match(
- query: str,
- targets: list[str] | None,
- ctx: Any,
- repository: Any,
- all_decisions: list,
- target_git: dict[str, Any],
- accepted: set[str] | None = None,
-) -> dict[str, Any]:
- """The whole response when no record clears the relevance floor.
-
- Returns early rather than serving the closest three anyway, and returns
- *before* the semantic lookup: a nearest-neighbour search over a 614-record
- store always returns three records, and on the questions this store cannot
- answer those were "14-language AST support" for "where is the episode store"
- and "Escape LIKE patterns" for "why is entry-point candidacy decided at
- ingestion". Serving them beside a redirect would be the padding the redirect
- exists to stop, and skipping the lookup is also the latency this branch
- saves. Episodes are held back for the same reason — they are what made the
- unanswerable questions the *largest* responses in the measured set.
-
- Named targets are the exception, and both blocks they carry are kept. A
- caller who passes them has handed over a concrete handle, so this file's
- git archaeology and this file's rationale comments are evidence about the
- thing asked rather than the nearest guess at it — the same reason path mode
- serves them. That is also the branch the redirect is *least* useful on,
- since `get_why` on a path is the tool the caller already reached for.
- """
- result: dict[str, Any] = {
- "mode": "search",
- "query": query,
- "decisions": [],
- **redirect_for(query),
- }
- collector: OmissionCollector | None = None
- if targets:
- collector = OmissionCollector("get_why", repo_root=ctx.path)
- result["target_context"] = await _build_target_context(
- ctx, repository, all_decisions, target_git, targets, collector, accepted
- )
- rationale = _mine_rationale(
- ctx.path, targets, query, max_results=1000, truncate_blocks=False
- )
- if rationale:
- result["code_rationale"] = rationale
- await _hydrate_response_decision_evidence(ctx, result, all_decisions)
- await annotate_response_evidence_async(
- result, ctx.alias, all_decisions, repo_root=ctx.path
- )
- if collector is not None:
- _focus_target_context(
- result["target_context"],
- query,
- list(targets or []),
- [_record_text(d) for d in all_decisions],
- )
- _cap_supporting_lanes(result, collector, label=query)
- _cap_target_context(result["target_context"], collector)
- # The redirect is stapled on before the target lanes are built, because
- # without targets there is nothing else this branch can serve. With them
- # there often is, and pointing away from an answer it is holding is the
- # padding-by-another-name the redirect exists to prevent.
- served = [
- label
- for key, label in (
- ("code_rationale", "rationale comments"),
- ("git_archaeology", "commit history"),
- )
- if result.get(key)
- or any(
- isinstance(e, dict) and _has_archaeology(e.get(key))
- for e in (result.get("target_context") or {}).values()
- )
- ]
- if served:
- result.pop("try_instead", None)
- result.update(
- redirect_when_served(served, f"get_why(targets={json.dumps(targets)})")
- )
- result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
- if collector is not None:
- collector.attach(result)
- return result
-
-
-async def _decision_corpus(session: Any, repository_id: str, exclude_spec: Any) -> list:
- """The rankable decision records of one repository.
-
- A record anchored entirely in excluded paths is noise for every mode, and a
- dismissed one is a tombstone, so both filters belong wherever a corpus is
- built. Takes a session rather than a context so the caller that also needs a
- repository row and git metadata still opens one. Shared with workspace search
- precisely because that path used to build its own corpus and got neither
- filter.
- """
- from repowise.core.persistence.crud import list_decisions as _list_decisions
-
- records = await _list_decisions(
- session, repository_id, include_proposed=True, limit=_DECISION_CORPUS_LIMIT
- )
- return [d for d in records if not decision_is_excluded(d, exclude_spec)]
-
-
-async def _attach_decision_evidence(session: Any, records: list) -> None:
- """Attach all persisted provenance rows with one bounded query.
-
- ``DecisionRecord`` is the compatibility headline. The child rows are the
- canonical accreted evidence and must travel with it when trust metadata is
- projected, without introducing an N+1 query in workspace or search modes.
- """
- if not records:
- return
- ids = [record.id for record in records]
- rows = list(
- (
- await session.execute(
- select(DecisionEvidence)
- .where(DecisionEvidence.decision_id.in_(ids))
- .order_by(
- DecisionEvidence.source_rank.desc(),
- DecisionEvidence.created_at.asc(),
- DecisionEvidence.id.asc(),
- )
- )
- )
- .scalars()
- .all()
- )
- by_decision: dict[str, list[DecisionEvidence]] = {}
- for row in rows:
- by_decision.setdefault(row.decision_id, []).append(row)
- for record in records:
- record._why_evidence_rows = by_decision.get(record.id, [])
-
-
-async def _attach_response_decision_evidence(
- session: Any, result: dict[str, Any], records: list
-) -> None:
- """Hydrate the decision rows *result* currently carries.
-
- Shared by all three modes, so what it covers is whatever the caller has
- built by the time it runs. Search mode calls it before its cap, which
- means the whole projected pool rather than the served head. That is
- deliberate: the rows the cap sheds are written to the omission store, and
- they have to carry their evidence by then or recovery returns bodies with
- no provenance.
- """
- ids: set[str] = set()
-
- def visit(value: object) -> None:
- if isinstance(value, dict):
- candidate = value.get("id") or value.get("decision_id")
- if isinstance(candidate, str):
- ids.add(candidate)
- for child in value.values():
- visit(child)
- elif isinstance(value, list):
- for child in value:
- visit(child)
-
- visit(result)
- await _attach_decision_evidence(
- session, [record for record in records if record.id in ids]
- )
-
-
-async def _hydrate_response_decision_evidence(
- ctx: Any, result: dict[str, Any], records: list
-) -> None:
- async with get_session(ctx.session_factory) as session:
- await _attach_response_decision_evidence(session, result, records)
-
-
-async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:
- """Repo context, corpus, git metadata for targets, and the acceptance set.
-
- The prologue both target-aware modes open with. Shared so the corpus is
- filtered once: a record anchored entirely in excluded paths is noise for
- every mode downstream, and a mode that skipped the filter would answer from
- a different store than its neighbour.
- """
- ctx = await _resolve_repo_context(repo)
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- all_decisions = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
- # ``governing_only`` drops the ones whose authority was withdrawn, so
- # what comes back is what still binds rather than what was ever signed.
- accepted = await accepted_decision_ids(
- session, repository.id, governing_only=True
- )
- # Load git metadata for targets (for origin context in results)
- target_git = await _load_target_git(session, repository.id, targets)
- return ctx, repository, all_decisions, target_git, accepted
-
-
-async def _why_targets(targets: list[str], repo: str | None) -> dict:
- """Mode 2b: targets and no query — the paths themselves are the question.
-
- One target is path mode outright: its lineage walk, alignment score and
- origin story are the fullest answer this tool has about a file, and that
- content is why the mode exists. Several get the per-target card instead —
- the same evidence a target already earns in search mode — because running
- path mode once per target would mean a corpus scan and a currency
- subprocess each, for a shape no caller renders.
- """
- if len(targets) == 1:
- return await _why_path(targets[0], repo)
-
- ctx, repository, all_decisions, target_git, accepted = await _load_corpus(
- repo, targets
- )
- collector = OmissionCollector("get_why", repo_root=ctx.path)
- result_data = {
- "mode": "path",
- "paths": targets,
- "target_context": await _build_target_context(
- ctx, repository, all_decisions, target_git, targets, collector, accepted
- ),
- "_meta": _build_meta(repository=repository, targets=targets),
- }
- await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
- result_data = await annotate_response_evidence_async(
- result_data, ctx.alias, all_decisions, repo_root=ctx.path
- )
- _cap_supporting_lanes(result_data, collector, label="targets")
- _cap_target_context(result_data["target_context"], collector)
- collector.attach(result_data)
- return result_data
-
-
-async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:
- """Mode 3: natural-language, target-aware decision + documentation search."""
- ctx, repository, all_decisions, target_git, accepted = await _load_corpus(
- repo, targets
- )
-
- target_set = set(targets) if targets else set()
- # Rank wide, collapse restatements, and project the whole surviving pool.
- # The decisions cap comes last, at the bottom of this function, and what it
- # sheds is banked whole: the omission document is the projected rows, so
- # building only the three that are served would leave recovery with nothing
- # to hand back. Measured on this repo, a
- # realistic question collapses to a median of 7 records and up to 33, and
- # capping first saves 4-21ms of a call whose cost is dominated by a fixed
- # annotation floor. The recovery is worth more than the milliseconds.
- ranked = _rank_keyword_matches(all_decisions, query, target_set)
- if not ranked:
- return await _why_no_match(
- query, targets, ctx, repository, all_decisions, target_git, accepted
- )
- collector = OmissionCollector("get_why", repo_root=ctx.path)
- collapsed = _collapse_restatements(ranked)
- decision_results, doc_results = await _semantic_lanes(ctx, query)
- lineage_by_id = await _lineage_for_matches(
- ctx, [d for d, _ in collapsed], all_decisions
- )
- merged_decisions = _merge_decisions(
- collapsed, decision_results, lineage_by_id, collector, accepted
- )
-
- # Semantic hits append as id-plus-snippet at roughly 200 chars each, so
- # dropping them to fit a record count would cost the lane that carries a
- # calibrated relevance score for the sake of no measurable payload.
- result_data: dict[str, Any] = {
- "mode": "search",
- "query": query,
- "decisions": merged_decisions,
- "related_documentation": [
- {
- "page_id": r.page_id,
- "title": r.title,
- "page_type": r.page_type,
- "snippet": r.snippet,
- "relevance_score": r.score,
- }
- for r in doc_results
- ],
- }
-
- # If targets provided, include target context
- if targets:
- result_data["target_context"] = await _build_target_context(
- ctx, repository, all_decisions, target_git, targets, collector, accepted
- )
- # The comment-mining fallback that used to sit here was gated on
- # ``not merged_decisions``, which nothing ever reached. It now lives in
- # ``_why_no_match``, behind the floor — the condition it always meant.
-
- # Targets resolve through the node index; without them the question itself
- # is the only handle, so it is ranked against the bodies.
- episode_population: list[dict] = []
- episodes, pending = await asyncio.to_thread(
- episode_evidence,
- ctx.path,
- paths=targets or None,
- query=None if targets else query,
- full_population=episode_population,
- )
- if episodes and targets:
- # ``episode_evidence`` takes *either* a scope or a query, and a scope
- # wins, so the targeted lane never saw the question: the same three
- # episodes came back for every question asked about a file. Scoping is
- # still the right retrieval — these are the episodes bound to the file
- # asked about — but what survives has to bear on what was asked.
- score = query_scorer(query, [_record_text(d) for d in all_decisions])
- kept = [
- e
- for e in episode_population
- if clears_floor(score(json.dumps(e, default=str)))
- ]
- if len(kept) != len(episode_population):
- episodes = [e for e in episodes if e in kept]
- episode_population[:] = kept
- pending = [t for t in pending if t[0] in kept]
- if episodes:
- collector = _prepare_episode_bodies(
- episode_population, len(episodes), pending, collector, ctx.path
- )
- result_data["episodes"] = episode_population
-
- await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
- await annotate_response_evidence_async(
- result_data, ctx.alias, all_decisions, repo_root=ctx.path
- )
- if targets:
- _focus_target_context(
- result_data["target_context"],
- query,
- list(targets),
- [_record_text(d) for d in all_decisions],
- )
- _cap_supporting_lanes(result_data, collector, label=query)
- _cap_target_context(result_data["target_context"], collector)
- else:
- _cap_supporting_lanes(result_data, collector, label=query)
- if episodes:
- cap_collection(
- result_data,
- "episodes",
- result_data["episodes"],
- len(episodes),
- collector,
- label="episodes beyond construction cap",
- )
- result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
- # Episode overflow is banked here because it is produced before the shared
- # final budget pass. The middleware owns the complete search-mode shed
- # order after trust metadata is attached; routing this shape through the
- # path-only fitter would discard its primary decision lane prematurely.
- cap_collection(
- result_data,
- "decisions",
- result_data["decisions"],
- _MAX_SEARCH_DECISIONS,
- collector,
- label=f"search decisions beyond cap={_MAX_SEARCH_DECISIONS}",
- )
- cap_collection(
- result_data,
- "related_documentation",
- result_data["related_documentation"],
- 3,
- collector,
- label="related_documentation beyond cap=3",
- )
- collector.attach(result_data)
- return result_data
-
-
-def _weighted_fields(d: Any) -> list[tuple[float, str]]:
- """The searchable text of a record, lowercased, by field weight.
-
- ``affected_files`` is deliberately absent. Joining a record's whole path
- list into one haystack and substring-matching a question against it scores
- by *breadth*: the record here governing 83 files matched almost every
- question asked, because ordinary query words ("index", "page", "format")
- occur somewhere in 83 paths, and it became the top hit for three of five
- probe questions including one about ruff. A scope is not question text.
- The legitimate use of that field — does this record govern the file the
- caller named — is the exact set membership in the target boost inside
- :func:`_score_decision`.
- """
- return [
- (3.0, d.title.lower()),
- (2.0, d.decision.lower()),
- (2.0, d.rationale.lower()),
- (1.5, d.context.lower()),
- (1.0, " ".join(json.loads(d.consequences_json)).lower()),
- (1.0, " ".join(json.loads(d.tags_json)).lower()),
- (1.0, (d.evidence_file or "").lower()),
- ]
-
-
-def _record_text(d: Any) -> str:
- """The same text, unweighted, for term coverage and the relevance floor.
-
- Built from :func:`_weighted_fields` so a record cannot clear the floor on a
- field the tie-break cannot see, or the reverse.
- """
- return " ".join(text for _, text in _weighted_fields(d))
-
-
-def _score_decision(
- d: Any,
- query_words: set[str],
- target_files: set[str],
-) -> float:
- """Score a decision against query words with field weighting and target boosting."""
- if not query_words:
- return 1.0 if target_files else 0.0
-
- score = 0.0
- for weight, text in _weighted_fields(d):
- for word in query_words:
- if word in text:
- score += weight
-
- # Target file boosting: decisions governing target files get a bonus
- if target_files:
- affected = set(json.loads(d.affected_files_json))
- affected_mods = json.loads(d.affected_modules_json)
- for t in target_files:
- if t in affected:
- score += 5.0 # Strong boost for exact file match
- elif any(t.startswith(m + "/") for m in affected_mods):
- score += 3.0 # Module-level match
-
- return score
-
-
-async def _git_archaeology_fallback(
- file_path: str,
- git_meta: Any | None,
- all_git_meta: list,
- repository: Any,
- collector: OmissionCollector | None = None,
-) -> dict:
- """When no decisions govern a file, mine git history for intent signals."""
- result: dict[str, Any] = {"triggered": True}
-
- # --- Layer 1: File's own significant commits ---
- file_commits = []
- if git_meta and git_meta.significant_commits_json:
- commits = json.loads(git_meta.significant_commits_json)
- file_commits = [
- {
- "sha": c.get("sha", ""),
- "message": c.get("message", ""),
- "author": c.get("author", ""),
- "date": c.get("date", ""),
- }
- for c in commits
- ]
- result["file_commits"] = file_commits
-
- # --- Layer 2: Cross-file search — other files' commits mentioning this file ---
- basename = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path
- stem = basename.rsplit(".", 1)[0] if "." in basename else basename
- # Convert snake_case/kebab to searchable terms: auth_cache_service -> {"auth", "cache", "service"}
- search_terms = set(re.split(r"[_\-/.]", stem.lower()))
- search_terms.discard("")
- # Also search for the full basename
- search_terms.add(basename.lower())
-
- cross_references = []
- for gm in all_git_meta:
- if gm.file_path == file_path:
- continue
- commits = json.loads(gm.significant_commits_json) if gm.significant_commits_json else []
- for c in commits:
- msg_lower = c.get("message", "").lower()
- # Match if the commit message mentions the file basename or 2+ stem terms
- matched_terms = sorted(t for t in search_terms if t in msg_lower)
- if basename.lower() in msg_lower or len(matched_terms) >= 2:
- cross_references.append(
- {
- "source_file": gm.file_path,
- "sha": c.get("sha", ""),
- "message": c.get("message", ""),
- "author": c.get("author", ""),
- "date": c.get("date", ""),
- "matched_terms": matched_terms,
- }
- )
- # Deduplicate by SHA and sort by date descending
- seen_shas: set[str] = set()
- unique_refs = []
- for cr in cross_references:
- if cr["sha"] not in seen_shas:
- seen_shas.add(cr["sha"])
- unique_refs.append(cr)
- unique_refs.sort(key=lambda x: x.get("date", ""), reverse=True)
- result["cross_references"] = unique_refs
-
- # --- Layer 3: Live git log (when local repo exists) ---
- git_log_results = []
- local_path = getattr(repository, "local_path", None)
- if local_path and (Path(local_path) / ".git").exists():
- git_log_results = await _run_git_log(local_path, file_path, stem)
- result["git_log"] = git_log_results
-
- # --- Summary ---
- total = len(file_commits) + len(unique_refs) + len(git_log_results)
- if total > 0:
- result["summary"] = (
- f"No architectural decisions found for {file_path}, but git archaeology "
- f"recovered {len(file_commits)} direct commit(s), "
- f"{len(unique_refs)} cross-reference(s), and "
- f"{len(git_log_results)} git log result(s). "
- "Review these to understand the intent behind this code."
- )
- else:
- result["summary"] = (
- f"No architectural decisions or git history found for {file_path}. "
- "This file may be new or not yet indexed."
- )
-
- return result
-
-
-async def _run_git_log(
- repo_path: str,
- file_path: str,
- stem: str,
-) -> list[dict]:
- """Run git log against the local repo for deeper history. Best-effort."""
- import asyncio
- import subprocess
-
- def _sync_git_log() -> list[dict]:
- import re
-
- results: list[dict] = []
- # Sanitize stem to prevent argument injection via --grep
- safe_stem = re.sub(r"[^a-zA-Z0-9_\-.]", "", stem) if stem else ""
- try:
- proc = subprocess.run(
- ["git", "log", "--follow", "--format=%H\t%an\t%ai\t%s", "-20", "--", file_path],
- cwd=repo_path,
- capture_output=True,
- text=True,
- # ``%s`` is the commit subject and ``%an`` the author name, both
- # utf-8 from git. text=True alone decodes with the locale codec,
- # which is cp1252 on a default Windows install.
- encoding="utf-8",
- errors="replace",
- timeout=10,
- # See commits_since() in core/precedent/currency.py: a git child
- # that inherits this server's JSON-RPC stdin can wedge the
- # session, and the timeout above is not a reliable ceiling.
- stdin=subprocess.DEVNULL,
- )
- if proc.returncode == 0:
- for line in proc.stdout.strip().splitlines():
- parts = line.split("\t", 3)
- if len(parts) == 4:
- results.append(
- {
- "sha": parts[0][:12],
- "commit": parts[0],
- "author": parts[1],
- "date": parts[2][:10],
- "message": parts[3],
- "source": "git_log_follow",
- }
- )
-
- if safe_stem and len(safe_stem) >= 3:
- proc2 = subprocess.run(
- [
- "git",
- "log",
- "--all",
- "--grep",
- safe_stem,
- "--format=%H\t%an\t%ai\t%s",
- "-10",
- "--", # end of options — prevent argument injection
- ],
- cwd=repo_path,
- capture_output=True,
- text=True,
- encoding="utf-8", # see above
- errors="replace",
- timeout=10,
- stdin=subprocess.DEVNULL, # see above
- )
- if proc2.returncode == 0:
- seen = {r["sha"] for r in results}
- for line in proc2.stdout.strip().splitlines():
- parts = line.split("\t", 3)
- if len(parts) == 4 and parts[0][:12] not in seen:
- seen.add(parts[0][:12])
- results.append(
- {
- "sha": parts[0][:12],
- "commit": parts[0],
- "author": parts[1],
- "date": parts[2][:10],
- "message": parts[3],
- "source": "git_log_grep",
- }
- )
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
- pass
- return results
-
- try:
- return await asyncio.wait_for(asyncio.to_thread(_sync_git_log), timeout=15)
- except TimeoutError:
- return []
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_why/__init__.py
new file mode 100644
index 000000000..8c37dab40
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/__init__.py
@@ -0,0 +1,32 @@
+"""MCP Tool 4: get_why, intent archaeology and decision search.
+
+One module per mode over shared layers; importing the package registers the
+tool and re-exports the names tests read. Monkeypatch a collaborator on the
+module that looks it up (e.g. ``path_mode.describe_decision_currency``), not here.
+"""
+
+from __future__ import annotations
+
+from repowise.server.mcp_server.tool_why.caps import (
+ _MAX_AFFECTED_FILES,
+ _MAX_HEALTH_PROPOSED,
+ _MAX_HEALTH_STALE,
+ _MAX_HEALTH_UNGOVERNED,
+ _MAX_PATH_DECISIONS,
+ _MAX_SEARCH_DECISIONS,
+ _fit_path_response,
+)
+from repowise.server.mcp_server.tool_why.ranking import _rank_keyword_matches
+from repowise.server.mcp_server.tool_why.tool import get_why
+
+__all__ = [
+ "_MAX_AFFECTED_FILES",
+ "_MAX_HEALTH_PROPOSED",
+ "_MAX_HEALTH_STALE",
+ "_MAX_HEALTH_UNGOVERNED",
+ "_MAX_PATH_DECISIONS",
+ "_MAX_SEARCH_DECISIONS",
+ "_fit_path_response",
+ "_rank_keyword_matches",
+ "get_why",
+]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py b/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py
new file mode 100644
index 000000000..b1cfa9440
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py
@@ -0,0 +1,213 @@
+"""Git archaeology: the fallback evidence when no decision governs a file."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from repowise.server.mcp_server._budget import OmissionCollector
+
+_GIT_LOG_FORMAT = "--format=%H\t%an\t%ai\t%s"
+
+
+async def _git_archaeology_fallback(
+ file_path: str,
+ git_meta: Any | None,
+ all_git_meta: list,
+ repository: Any,
+ collector: OmissionCollector | None = None,
+) -> dict:
+ """When no decisions govern a file, mine git history for intent signals."""
+ result: dict[str, Any] = {"triggered": True}
+
+ # --- Layer 1: File's own significant commits ---
+ file_commits = _file_commits(git_meta)
+ result["file_commits"] = file_commits
+
+ # --- Layer 2: Cross-file search — other files' commits mentioning this file ---
+ basename, stem, search_terms = _search_terms(file_path)
+ unique_refs = _cross_references(file_path, basename, search_terms, all_git_meta)
+ result["cross_references"] = unique_refs
+
+ # --- Layer 3: Live git log (when local repo exists) ---
+ git_log_results = []
+ local_path = getattr(repository, "local_path", None)
+ if local_path and (Path(local_path) / ".git").exists():
+ git_log_results = await _run_git_log(local_path, file_path, stem)
+ result["git_log"] = git_log_results
+
+ # --- Summary ---
+ result["summary"] = _archaeology_summary(
+ file_path, len(file_commits), len(unique_refs), len(git_log_results)
+ )
+ return result
+
+
+def _commit_row(c: dict[str, Any]) -> dict[str, Any]:
+ """A stored significant commit as an archaeology row."""
+ return {
+ "sha": c.get("sha", ""),
+ "message": c.get("message", ""),
+ "author": c.get("author", ""),
+ "date": c.get("date", ""),
+ }
+
+
+def _file_commits(git_meta: Any | None) -> list[dict[str, Any]]:
+ """The file's own significant commits, as indexed."""
+ if not (git_meta and git_meta.significant_commits_json):
+ return []
+ return [_commit_row(c) for c in json.loads(git_meta.significant_commits_json)]
+
+
+def _search_terms(file_path: str) -> tuple[str, str, set[str]]:
+ """``(basename, stem, terms)`` a commit message can name this file by."""
+ basename = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path
+ stem = basename.rsplit(".", 1)[0] if "." in basename else basename
+ # Convert snake_case/kebab to searchable terms: auth_cache_service -> {"auth", "cache", "service"}
+ search_terms = set(re.split(r"[_\-/.]", stem.lower()))
+ search_terms.discard("")
+ # Also search for the full basename
+ search_terms.add(basename.lower())
+ return basename, stem, search_terms
+
+
+def _cross_references(
+ file_path: str, basename: str, search_terms: set[str], all_git_meta: list
+) -> list[dict[str, Any]]:
+ """Other files' commits that mention this one, one per SHA, newest first."""
+ cross_references = []
+ for gm in all_git_meta:
+ if gm.file_path == file_path:
+ continue
+ commits = json.loads(gm.significant_commits_json) if gm.significant_commits_json else []
+ for c in commits:
+ msg_lower = c.get("message", "").lower()
+ # Match if the commit message mentions the file basename or 2+ stem terms
+ matched_terms = sorted(t for t in search_terms if t in msg_lower)
+ if basename.lower() in msg_lower or len(matched_terms) >= 2:
+ cross_references.append(
+ {"source_file": gm.file_path, **_commit_row(c), "matched_terms": matched_terms}
+ )
+ # Deduplicate by SHA and sort by date descending
+ seen_shas: set[str] = set()
+ unique_refs = []
+ for cr in cross_references:
+ if cr["sha"] not in seen_shas:
+ seen_shas.add(cr["sha"])
+ unique_refs.append(cr)
+ unique_refs.sort(key=lambda x: x.get("date", ""), reverse=True)
+ return unique_refs
+
+
+def _archaeology_summary(
+ file_path: str, file_commits: int, cross_references: int, git_log: int
+) -> str:
+ """One sentence counting what each layer recovered, or saying none did."""
+ if file_commits + cross_references + git_log > 0:
+ return (
+ f"No architectural decisions found for {file_path}, but git archaeology "
+ f"recovered {file_commits} direct commit(s), "
+ f"{cross_references} cross-reference(s), and "
+ f"{git_log} git log result(s). "
+ "Review these to understand the intent behind this code."
+ )
+ return (
+ f"No architectural decisions or git history found for {file_path}. "
+ "This file may be new or not yet indexed."
+ )
+
+
+async def _run_git_log(
+ repo_path: str,
+ file_path: str,
+ stem: str,
+) -> list[dict]:
+ """Run git log against the local repo for deeper history. Best-effort."""
+ try:
+ return await asyncio.wait_for(
+ asyncio.to_thread(_sync_git_log, repo_path, file_path, stem), timeout=15
+ )
+ except TimeoutError:
+ return []
+
+
+def _sync_git_log(repo_path: str, file_path: str, stem: str) -> list[dict]:
+ """The file's own log, then commits whose message names its stem."""
+ results: list[dict] = []
+ # Sanitize stem to prevent argument injection via --grep
+ safe_stem = re.sub(r"[^a-zA-Z0-9_\-.]", "", stem) if stem else ""
+ try:
+ stdout = _git_log_stdout(
+ repo_path, ["--follow", _GIT_LOG_FORMAT, "-20", "--", file_path]
+ )
+ if stdout is not None:
+ results.extend(_parse_git_log(stdout, "git_log_follow"))
+
+ if safe_stem and len(safe_stem) >= 3:
+ stdout = _git_log_stdout(
+ repo_path,
+ [
+ "--all",
+ "--grep",
+ safe_stem,
+ _GIT_LOG_FORMAT,
+ "-10",
+ "--", # end of options — prevent argument injection
+ ],
+ )
+ if stdout is not None:
+ seen = {r["sha"] for r in results}
+ results.extend(_parse_git_log(stdout, "git_log_grep", seen))
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ pass
+ return results
+
+
+def _git_log_stdout(repo_path: str, args: list[str]) -> str | None:
+ """``git log <args>`` output, or ``None`` when git exits non-zero."""
+ proc = subprocess.run(
+ ["git", "log", *args],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ # Git emits utf-8; text=True alone uses the locale codec (cp1252 on Windows).
+ encoding="utf-8",
+ errors="replace",
+ timeout=10,
+ # A git child inheriting the JSON-RPC stdin can wedge the session
+ # (see commits_since() in core/precedent/currency.py).
+ stdin=subprocess.DEVNULL,
+ )
+ return proc.stdout if proc.returncode == 0 else None
+
+
+def _parse_git_log(
+ stdout: str, source: str, seen: set[str] | None = None
+) -> list[dict]:
+ """Rows from ``_GIT_LOG_FORMAT`` output; with *seen*, skip SHAs already in it."""
+ rows: list[dict] = []
+ for line in stdout.strip().splitlines():
+ parts = line.split("\t", 3)
+ if len(parts) != 4:
+ continue
+ sha = parts[0][:12]
+ if seen is not None:
+ if sha in seen:
+ continue
+ seen.add(sha)
+ rows.append(
+ {
+ "sha": sha,
+ "commit": parts[0],
+ "author": parts[1],
+ "date": parts[2][:10],
+ "message": parts[3],
+ "source": source,
+ }
+ )
+ return rows
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/basis.py b/packages/server/src/repowise/server/mcp_server/tool_why/basis.py
new file mode 100644
index 000000000..f0f420339
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/basis.py
@@ -0,0 +1,82 @@
+"""``answer_basis``: the strongest evidence lane a get_why response rests on."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.server.mcp_server._budget import (
+ OmissionCollector,
+ register_post_shed,
+)
+
+
+def _has_archaeology(archaeology: Any) -> bool:
+ """Whether an archaeology block found anything.
+
+ ``_git_archaeology_fallback`` always returns a dict, carrying ``triggered``
+ and a summary that may say it found nothing, so the block's presence proves
+ only that it ran.
+ """
+ return isinstance(archaeology, dict) and any(
+ archaeology.get(lane)
+ for lane in ("file_commits", "cross_references", "git_log")
+ )
+
+
+def _is_accepted_row(row: Any) -> bool:
+ """Whether an emitted decision row rests on an acceptance.
+
+ Reads the stamped ``authority``, not ``status`` (see
+ ``decision_currencies``). A row with no ``authority`` is a semantic hit with
+ no record to join on, so it cannot count as accepted.
+ """
+ return isinstance(row, dict) and row.get("authority") == "accepted"
+
+
+def _stamp_answer_basis(result: dict) -> dict:
+ """Name the strongest lane the response actually rests on.
+
+ Only an accepted decision is a ruling; everything else is evidence to weigh.
+
+ ``decision`` requires a ``DecisionAcceptance``, not just a record: most
+ stores hold only unconfirmed candidates. ``candidate`` ranks below every
+ evidence lane, since an unconfirmed guess must not outrank real evidence.
+
+ Absent when nothing was served, so a refusal cannot read as an answer.
+ Re-derived after the budget pass sheds, so it clears first.
+ """
+ result.pop("answer_basis", None)
+ entries = [
+ e for e in (result.get("target_context") or {}).values() if isinstance(e, dict)
+ ]
+ decision_rows = [
+ *(result.get("decisions") or []),
+ *(r for e in entries for r in (e.get("governing_decisions") or [])),
+ ]
+ candidate_rows = [
+ *(r for e in entries for r in (e.get("candidate_decisions") or [])),
+ *(r for r in decision_rows if not _is_accepted_row(r)),
+ ]
+ if any(_is_accepted_row(r) for r in decision_rows):
+ result["answer_basis"] = "decision"
+ elif result.get("episodes"):
+ result["answer_basis"] = "episode"
+ elif result.get("code_rationale"):
+ result["answer_basis"] = "rationale"
+ elif _has_archaeology(result.get("git_archaeology")) or any(
+ _has_archaeology(e.get("git_archaeology")) for e in entries
+ ):
+ result["answer_basis"] = "archaeology"
+ elif result.get("related_documentation"):
+ result["answer_basis"] = "documentation"
+ elif candidate_rows:
+ result["answer_basis"] = "candidate"
+ return result
+
+
+def _restamp_answer_basis(result: dict, _collector: OmissionCollector) -> None:
+ """Re-derive the basis after shedding, so it never names an emptied lane."""
+ _stamp_answer_basis(result)
+
+
+register_post_shed("get_why", _restamp_answer_basis)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/caps.py b/packages/server/src/repowise/server/mcp_server/tool_why/caps.py
new file mode 100644
index 000000000..72b1b6f4b
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/caps.py
@@ -0,0 +1,360 @@
+"""Response caps for every mode, and the budget fitting path mode needs."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from repowise.server.mcp_server._budget import (
+ OmissionCollector,
+ cap_collection,
+ fit_to_budget,
+ over_budget,
+)
+from repowise.server.mcp_server._episodes import bank_overflow
+
+# --- Path-mode cap and projection -------------------------------------------
+#
+# Rank, project, then enforce. Over-budget is a host error, not a truncation,
+# so the caps below project and the budget pass after them is the guarantee:
+# no fixed cap bounds free-text fields.
+
+#: Governing records kept, best-first. Past ~8 the tail is review-queue noise.
+_MAX_PATH_DECISIONS = 8
+
+#: Candidates inlined beside a path's decisions. Far below the decisions cap:
+#: this lane signals that a review queue exists, it is not the queue.
+_MAX_PATH_CANDIDATES = 3
+
+#: Paths kept per record. A head plus a total shows how wide a decision is.
+_MAX_AFFECTED_FILES = 10
+
+#: Headroom left under the budget for ``OmissionCollector.attach``, which adds
+#: ``omission_marker`` + ``_meta.omitted`` *after* the last size check.
+_COLLECTOR_HEADROOM_CHARS = 600
+
+# Status ranking uses lifecycle's ``status_rank``, so every surface orders
+# records the same way.
+
+
+# --- Search-mode caps -------------------------------------------------------
+#
+# Few records served whole rather than many served thin: a long low-relevance
+# answer teaches an agent the tool is not worth calling.
+
+#: Records kept by search mode. Past the third hit the ranking is not
+#: trustworthy enough to spend an agent's context on.
+_MAX_SEARCH_DECISIONS = 3
+
+#: Records kept by workspace search. Above three because the answer can live
+#: in more than one repo's store.
+_MAX_WORKSPACE_DECISIONS = 5
+
+#: Nearest pages pulled for search mode's one semantic lookup. Both lanes
+#: (decisions, documentation) are partitioned out of this single window.
+_SEMANTIC_WINDOW = 50
+
+#: Records search mode ranks over. Not a cost control (ranking is a cheap
+#: substring scan) and a low cut would be a silent recall ceiling; bounded only
+#: so an unattended extractor cannot make one call an unbounded scan.
+_DECISION_CORPUS_LIMIT = 2000
+
+#: Items per list in the health dashboard, an orientation call. The lists are
+#: ranked, so the cut keeps the part worth reading; full sizes stay in
+#: ``counts`` and every cut row is recoverable through the omission collector.
+_MAX_HEALTH_STALE = 5
+_MAX_HEALTH_PROPOSED = 5
+_MAX_HEALTH_UNGOVERNED = 8
+
+#: Retired records and accepted records naming no file: a pointer into history.
+_MAX_HEALTH_RETIRED = 5
+
+
+def _cap_origin_story(
+ origin_story: dict[str, Any],
+ collector: OmissionCollector,
+ *,
+ label: str,
+) -> None:
+ """Bound each origin lane independently and bank its exact omitted rows."""
+ for key, cap in (
+ ("contributors", 5),
+ ("key_commits", 5),
+ ("linked_decisions", _MAX_PATH_DECISIONS),
+ ):
+ rows = origin_story.get(key)
+ if isinstance(rows, list):
+ cap_collection(
+ origin_story,
+ key,
+ rows,
+ cap,
+ collector,
+ label=f"{label} :: origin.{key} beyond cap={cap}",
+ )
+ for linked in origin_story.get("linked_decisions") or []:
+ if not isinstance(linked, dict):
+ continue
+ commits = linked.get("evidence_commits")
+ if isinstance(commits, list):
+ cap_collection(
+ linked,
+ "evidence_commits",
+ commits,
+ 5,
+ collector,
+ label=f"{label} :: origin.linked_decisions.evidence_commits beyond cap=5",
+ )
+
+
+def _cap_archaeology(
+ archaeology: dict[str, Any], collector: OmissionCollector, *, label: str
+) -> None:
+ """Cap fully annotated archaeology lanes without discarding their tails."""
+ for key, cap in (("file_commits", 10), ("cross_references", 10), ("git_log", 20)):
+ rows = archaeology.get(key)
+ if isinstance(rows, list):
+ cap_collection(
+ archaeology,
+ key,
+ rows,
+ cap,
+ collector,
+ label=f"{label} :: archaeology.{key} beyond cap={cap}",
+ )
+
+
+def _cap_supporting_lanes(
+ result: dict[str, Any], collector: OmissionCollector, *, label: str
+) -> None:
+ """Cap supporting Why lanes only after evidence annotation is complete."""
+ origin = result.get("origin_story")
+ if isinstance(origin, dict):
+ _cap_origin_story(origin, collector, label=label)
+ archaeology = result.get("git_archaeology")
+ if isinstance(archaeology, dict):
+ _cap_archaeology(archaeology, collector, label=label)
+ rationale = result.get("code_rationale")
+ if isinstance(rationale, list):
+ cap_collection(
+ result,
+ "code_rationale",
+ rationale,
+ 5,
+ collector,
+ label=f"{label} :: code_rationale beyond cap=5",
+ )
+ for target, context in (result.get("target_context") or {}).items():
+ if not isinstance(context, dict):
+ continue
+ target_origin = context.get("origin")
+ if isinstance(target_origin, dict):
+ _cap_origin_story(target_origin, collector, label=target)
+ target_archaeology = context.get("git_archaeology")
+ if isinstance(target_archaeology, dict):
+ _cap_archaeology(target_archaeology, collector, label=target)
+
+
+def _prepare_episode_bodies(
+ population: list[dict[str, Any]],
+ visible_count: int,
+ pending: list[tuple[dict, str, str]],
+ collector: OmissionCollector,
+ repo_root: Path,
+) -> OmissionCollector:
+ """Inline-bank visible long bodies; keep omitted episode rows byte-complete."""
+ visible_ids = {id(entry) for entry in population[:visible_count]}
+ visible_pending: list[tuple[dict, str, str]] = []
+ for entry, label, body in pending:
+ if id(entry) in visible_ids:
+ visible_pending.append((entry, label, body))
+ else:
+ entry["recorded"] = body
+ return bank_overflow(
+ visible_pending,
+ tool="get_why",
+ repo_root=repo_root,
+ collector=collector,
+ ) or collector
+
+
+def _serve_episodes(
+ result: dict[str, Any],
+ episodes: list[dict[str, Any]],
+ population: list[dict[str, Any]],
+ pending: list[tuple[dict, str, str]],
+ collector: OmissionCollector,
+ repo_root: Path,
+) -> OmissionCollector:
+ """Put the episode population on *result*, long visible bodies banked first.
+
+ Returns the collector to carry on with: banking can start a new one, and
+ the caller must attach that one rather than the one it passed in.
+ """
+ if not episodes:
+ return collector
+ collector = _prepare_episode_bodies(
+ population, len(episodes), pending, collector, repo_root
+ )
+ result["episodes"] = population
+ return collector
+
+
+def _cap_episodes(
+ result: dict[str, Any], episodes: list[dict[str, Any]], collector: OmissionCollector
+) -> None:
+ """Cap the served population back to the rows episode retrieval chose."""
+ if episodes:
+ cap_collection(
+ result,
+ "episodes",
+ result["episodes"],
+ len(episodes),
+ collector,
+ label="episodes beyond construction cap",
+ )
+
+
+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 caps bound the structured fields; this bounds the free-text ones.
+
+ Stages, cheapest loss first:
+
+ 1. ``origin_story.linked_decisions`` (duplicates ``decisions``), then the
+ history and candidate lanes: review requests, not rules.
+ 2. Episodes, which must only ever spend slack.
+ 3. Governing records from the tail, down to none if need be: an empty list
+ plus a marker beats a rejected response.
+ 4. The ungoverned branch's ``code_rationale`` and ``git_archaeology``,
+ trimmed then dropped, then ``origin_story``.
+
+ Every drop goes to the omission store. Call after ``_meta`` is set.
+
+ Reuse the caller's *collector*: a second one's ``attach`` would overwrite
+ ``_meta.omitted``. It is also why the under-budget path still attaches.
+ """
+
+ def _over() -> bool:
+ return over_budget(result_data, headroom=_COLLECTOR_HEADROOM_CHARS)
+
+ if not _over():
+ if collector is not None:
+ collector.attach(result_data)
+ return result_data
+
+ if collector is None:
+ collector = OmissionCollector("get_why", repo_root=repo_root)
+
+ def _shed(*order: str) -> None:
+ fit_to_budget(
+ result_data,
+ order,
+ collector,
+ headroom=_COLLECTOR_HEADROOM_CHARS,
+ record_counts=True,
+ )
+
+ # Review lanes first; each note goes with its lane, since a note counting
+ # rows no longer in the payload is worse than none.
+ _shed(
+ "origin_story.linked_decisions",
+ "history[]",
+ "history",
+ "candidates[]",
+ "candidates",
+ )
+ for lane_key in ("candidates", "history"):
+ if not result_data.get(lane_key):
+ result_data.pop(f"{lane_key}_note", None)
+
+ # Episodes before the governing records, so a record is never evicted to
+ # make room for one. Trimmed first, so mild pressure costs rows, not the lane.
+ _shed("episodes[]", "episodes")
+
+ _shed_tail_decisions(result_data, collector)
+
+ # The ungoverned branch's answer: trim rows before dropping whole lanes.
+ _shed(
+ "code_rationale[]",
+ "git_archaeology.file_commits[]",
+ "git_archaeology.cross_references[]",
+ "git_archaeology.git_log[]",
+ "code_rationale",
+ "git_archaeology.file_commits",
+ "git_archaeology.cross_references",
+ "git_archaeology.git_log",
+ "origin_story",
+ )
+
+ collector.attach(result_data)
+ return result_data
+
+
+def _shed_tail_decisions(result_data: dict, collector: OmissionCollector) -> None:
+ """Drop governing records from the tail until the response fits.
+
+ Stage 3 of :func:`_fit_path_response`. The ``decisions_*`` counts the
+ construction cap wrote are brought up to date, so a reader can tell the
+ budget cut from the cap, or both, apart.
+ """
+ decisions: list = result_data.get("decisions") or []
+ while decisions and over_budget(result_data, headroom=_COLLECTOR_HEADROOM_CHARS):
+ dropped = decisions.pop()
+ collector.add(f"dropped governing decision {dropped.get('title', '')}", dropped)
+ result_data["truncated"] = True
+ result_data.setdefault("dropped_decisions", []).append(dropped.get("id", ""))
+ if "decisions_total" in result_data:
+ result_data["decisions_emitted"] = len(decisions)
+ if len(decisions) < result_data["decisions_total"]:
+ prior = result_data.get("decisions_reduced_reason")
+ result_data["decisions_reduced_reason"] = (
+ "construction_cap_and_response_budget"
+ if prior == "construction_cap"
+ else "response_budget"
+ )
+ result_data["decisions_truncated"] = True
+ result_data["decisions_omitted"] = result_data["decisions_total"] - len(decisions)
+
+
+def _cap_target_context(
+ target_context: dict[str, Any], collector: OmissionCollector
+) -> None:
+ """Cap evidence-enriched per-target decision lanes independently."""
+ for target, entry in target_context.items():
+ for lane in ("governing_decisions", "candidate_decisions"):
+ decisions = entry.get(lane)
+ if isinstance(decisions, list):
+ cap_collection(
+ entry,
+ lane,
+ decisions,
+ _MAX_PATH_DECISIONS,
+ collector,
+ label=f"{target} :: {lane} beyond cap={_MAX_PATH_DECISIONS}",
+ )
+
+
+def _cap_path_decision_lanes(result_data: dict[str, Any], collector: OmissionCollector) -> None:
+ """Cap path mode's rules lane and the two lanes beside it."""
+ cap_collection(
+ result_data,
+ "decisions",
+ result_data["decisions"],
+ _MAX_PATH_DECISIONS,
+ collector,
+ label=f"path decisions beyond cap={_MAX_PATH_DECISIONS}",
+ )
+ for lane_key in ("candidates", "history"):
+ if result_data.get(lane_key):
+ cap_collection(
+ result_data,
+ lane_key,
+ result_data[lane_key],
+ _MAX_PATH_CANDIDATES,
+ collector,
+ label=f"path {lane_key} beyond cap={_MAX_PATH_CANDIDATES}",
+ )
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_why/dashboard.py
new file mode 100644
index 000000000..b8da937b6
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/dashboard.py
@@ -0,0 +1,121 @@
+"""Dashboard mode: no query and no targets, the decision health summary."""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.persistence.database import get_session
+from repowise.server.mcp_server._budget import (
+ OmissionCollector,
+ cap_collection,
+)
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ _get_repo,
+ _resolve_repo_context,
+ filter_path_list,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import (
+ annotate_response_evidence_async,
+)
+from repowise.server.mcp_server.tool_why.caps import (
+ _MAX_HEALTH_PROPOSED,
+ _MAX_HEALTH_RETIRED,
+ _MAX_HEALTH_STALE,
+ _MAX_HEALTH_UNGOVERNED,
+)
+from repowise.server.mcp_server.tool_why.loading import _attach_decision_evidence
+
+
+async def _why_health_dashboard(repo: str | None) -> dict:
+ """Mode 1: no query — return the decision health dashboard."""
+ from repowise.core.persistence.crud import get_decision_health_summary
+
+ ctx = await _resolve_repo_context(repo)
+ collector = OmissionCollector("get_why", repo_root=ctx.path)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ health = await get_decision_health_summary(session, repository.id)
+
+ stale = health["stale_decisions"]
+ proposed = health["proposed_awaiting_review"]
+ ungoverned = health["ungoverned_hotspots"]
+ retired = health["retired_decisions"]
+ unscoped = health["unscoped_decisions"]
+
+ result_data = {
+ "mode": "health",
+ "summary": (
+ f"{health['summary'].get('active', 0)} active · "
+ f"{health['summary'].get('stale', 0)} stale · "
+ f"{len(proposed)} proposed · "
+ f"{len(ungoverned)} ungoverned hotspots"
+ ),
+ "counts": health["summary"],
+ "stale_decisions": [
+ {
+ "id": d.id,
+ "title": d.title,
+ "staleness_score": d.staleness_score,
+ "affected_files": filter_path_list(
+ json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)
+ ),
+ }
+ for d in stale
+ ],
+ "proposed_awaiting_review": [
+ {
+ "id": d.id,
+ "title": d.title,
+ "source": d.source,
+ "confidence": d.confidence,
+ }
+ for d in proposed
+ ],
+ "ungoverned_hotspots": ungoverned,
+ "conflicts": list(health.get("conflicts", [])),
+ # No other mode enumerates these lanes. ``active`` stays count-only:
+ # every other mode exists to serve it.
+ "retired_decisions": [
+ {"id": d.id, "title": d.title, "lane": lane} for lane, d in retired
+ ],
+ "unscoped_decisions": [
+ {"id": d.id, "title": d.title, "confidence": d.confidence} for d in unscoped
+ ],
+ "_meta": _build_meta(repository=repository),
+ }
+ for entry in result_data["stale_decisions"]:
+ cap_collection(
+ entry,
+ "affected_files",
+ entry["affected_files"],
+ 5,
+ collector,
+ label=f"health stale decision {entry['id']} :: affected_files beyond cap=5",
+ )
+ await _attach_decision_evidence(session, [*stale, *proposed])
+ result_data = await annotate_response_evidence_async(
+ result_data,
+ ctx.alias,
+ [*stale, *proposed],
+ repo_root=ctx.path,
+ )
+ for key, cap in (
+ ("stale_decisions", _MAX_HEALTH_STALE),
+ ("proposed_awaiting_review", _MAX_HEALTH_PROPOSED),
+ ("ungoverned_hotspots", _MAX_HEALTH_UNGOVERNED),
+ ("conflicts", 10),
+ ("retired_decisions", _MAX_HEALTH_RETIRED),
+ ("unscoped_decisions", _MAX_HEALTH_RETIRED),
+ ):
+ cap_collection(
+ result_data,
+ key,
+ result_data[key],
+ cap,
+ collector,
+ label=f"health {key} beyond cap={cap}",
+ )
+ collector.attach(result_data)
+ return result_data
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/lineage.py b/packages/server/src/repowise/server/mcp_server/tool_why/lineage.py
new file mode 100644
index 000000000..3f2910e7c
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/lineage.py
@@ -0,0 +1,146 @@
+"""Decision lineage: the supersedes / refines chain a record sits in."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import DecisionEdge, DecisionRecord
+
+#: Records one chain may visit. A guard against a cycle the visited set misses,
+#: not a depth anyone expects a real lineage to reach.
+_MAX_LINEAGE_HOPS = 50
+
+
+async def _outgoing_lineage_edges(
+ session: Any, repository_id: Any
+) -> dict[str, list[Any]]:
+ """Every supersedes / refines edge, grouped by source, strongest first."""
+ edges = list(
+ (
+ await session.execute(
+ select(DecisionEdge).where(
+ DecisionEdge.repository_id == repository_id,
+ DecisionEdge.kind.in_(("supersedes", "refines")),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ outgoing: dict[str, list[Any]] = {}
+ for edge in edges:
+ outgoing.setdefault(edge.src_decision_id, []).append(edge)
+ for rows in outgoing.values():
+ rows.sort(
+ key=lambda edge: (
+ edge.kind == "supersedes",
+ edge.confidence or 0.0,
+ edge.dst_decision_id,
+ ),
+ reverse=True,
+ )
+ return outgoing
+
+
+async def _lineage_records(
+ session: Any, outgoing: dict[str, list[Any]], all_decisions: list[Any]
+) -> dict[str, Any]:
+ """Records by id for every edge endpoint, loading only those not in hand."""
+ records = {record.id: record for record in all_decisions}
+ edge_record_ids = {
+ decision_id
+ for rows in outgoing.values()
+ for edge in rows
+ for decision_id in (edge.src_decision_id, edge.dst_decision_id)
+ }
+ missing_ids = edge_record_ids - records.keys()
+ if missing_ids:
+ missing_records = list(
+ (
+ await session.execute(
+ select(DecisionRecord).where(DecisionRecord.id.in_(missing_ids))
+ )
+ )
+ .scalars()
+ .all()
+ )
+ records.update({record.id: record for record in missing_records})
+ return records
+
+
+def _walk_lineage(
+ start_id: str, outgoing: dict[str, list[Any]]
+) -> list[tuple[str, str | None]]:
+ """``(decision_id, relation)`` from *start_id* along the strongest unvisited edge."""
+ order: list[tuple[str, str | None]] = []
+ visited: set[str] = set()
+ current = start_id
+ relation: str | None = None
+ while current and current not in visited and len(order) < _MAX_LINEAGE_HOPS:
+ visited.add(current)
+ order.append((current, relation))
+ edge = next(
+ (
+ row
+ for row in outgoing.get(current, [])
+ if row.dst_decision_id not in visited
+ ),
+ None,
+ )
+ if edge is None:
+ break
+ current = edge.dst_decision_id
+ relation = edge.kind
+ return order
+
+
+def _lineage_chain(
+ order: list[tuple[str, str | None]], records: dict[str, Any]
+) -> list[dict]:
+ """The walk as rows, root first, skipping ids no record backs."""
+ chain = []
+ for decision_id, kind in reversed(order):
+ record = records.get(decision_id)
+ if record is not None:
+ chain.append(
+ {
+ "id": record.id,
+ "title": record.title,
+ "status": record.status,
+ "source": record.source,
+ "relation": kind,
+ }
+ )
+ return chain
+
+
+async def _lineage_for_records(
+ session: Any, candidates: list[Any], all_decisions: list[Any]
+) -> dict[str, list[dict]]:
+ """Build every candidate lineage from one edge query and in-memory records."""
+ if not candidates:
+ return {}
+ outgoing = await _outgoing_lineage_edges(session, candidates[0].repository_id)
+ records = await _lineage_records(session, outgoing, all_decisions)
+ result: dict[str, list[dict]] = {}
+ for candidate in candidates:
+ order = _walk_lineage(candidate.id, outgoing)
+ if len(order) <= 1:
+ continue
+ chain = _lineage_chain(order, records)
+ if len(chain) > 1:
+ result[candidate.id] = chain
+ return result
+
+
+async def _lineage_for_matches(
+ ctx: Any, keyword_matches: list, all_decisions: list[Any]
+) -> dict[str, list[dict]]:
+ """Build all keyword lineages with one bounded edge query."""
+ if not keyword_matches:
+ return {}
+ async with get_session(ctx.session_factory) as session3:
+ return await _lineage_for_records(session3, keyword_matches, all_decisions)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/loading.py b/packages/server/src/repowise/server/mcp_server/tool_why/loading.py
new file mode 100644
index 000000000..e7c0f5ac0
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/loading.py
@@ -0,0 +1,152 @@
+"""Database reads the modes share: corpus, git metadata, evidence rows."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.persistence.crud.authority import accepted_decision_ids
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import DecisionEvidence, GitMetadata
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ _get_repo,
+ _resolve_repo_context,
+ decision_is_excluded,
+)
+from repowise.server.mcp_server.tool_why.caps import _DECISION_CORPUS_LIMIT
+
+
+async def _git_metadata_for(session: Any, repository_id: Any, file_path: str) -> Any | None:
+ """One file's git metadata row, or ``None`` when git never indexed it."""
+ git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.file_path == file_path,
+ )
+ )
+ return git_res.scalar_one_or_none()
+
+
+async def _all_git_metadata(session: Any, repository_id: Any) -> list:
+ """Every file's git metadata, for the archaeology cross-file search."""
+ all_git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository_id,
+ )
+ )
+ return all_git_res.scalars().all()
+
+
+async def _load_target_git(
+ session: Any, repository_id: Any, targets: list[str] | None
+) -> dict[str, Any]:
+ """Load per-target git metadata keyed by file path (only present ones)."""
+ target_git: dict[str, Any] = {}
+ if not targets:
+ return target_git
+ for t in targets:
+ meta = await _git_metadata_for(session, repository_id, t)
+ if meta:
+ target_git[t] = meta
+ return target_git
+
+
+async def _decision_corpus(session: Any, repository_id: str, exclude_spec: Any) -> list:
+ """The rankable decision records of one repository.
+
+ Records anchored entirely in excluded paths, and dismissed ones, are
+ filtered out. Shared with workspace search so every mode ranks the same
+ corpus. Takes a session so a caller can share one.
+ """
+ from repowise.core.persistence.crud import list_decisions as _list_decisions
+
+ records = await _list_decisions(
+ session, repository_id, include_proposed=True, limit=_DECISION_CORPUS_LIMIT
+ )
+ return [d for d in records if not decision_is_excluded(d, exclude_spec)]
+
+
+async def _attach_decision_evidence(session: Any, records: list) -> None:
+ """Attach all persisted provenance rows with one bounded query.
+
+ The child rows are the canonical evidence behind each ``DecisionRecord``
+ and must travel with it when trust metadata is projected.
+ """
+ if not records:
+ return
+ ids = [record.id for record in records]
+ rows = list(
+ (
+ await session.execute(
+ select(DecisionEvidence)
+ .where(DecisionEvidence.decision_id.in_(ids))
+ .order_by(
+ DecisionEvidence.source_rank.desc(),
+ DecisionEvidence.created_at.asc(),
+ DecisionEvidence.id.asc(),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ by_decision: dict[str, list[DecisionEvidence]] = {}
+ for row in rows:
+ by_decision.setdefault(row.decision_id, []).append(row)
+ for record in records:
+ record._why_evidence_rows = by_decision.get(record.id, [])
+
+
+async def _attach_response_decision_evidence(
+ session: Any, result: dict[str, Any], records: list
+) -> None:
+ """Hydrate the decision rows *result* currently carries.
+
+ Search mode calls it before its cap on purpose: rows the cap sheds go to
+ the omission store and must carry their evidence by then.
+ """
+ ids: set[str] = set()
+
+ def visit(value: object) -> None:
+ if isinstance(value, dict):
+ candidate = value.get("id") or value.get("decision_id")
+ if isinstance(candidate, str):
+ ids.add(candidate)
+ for child in value.values():
+ visit(child)
+ elif isinstance(value, list):
+ for child in value:
+ visit(child)
+
+ visit(result)
+ await _attach_decision_evidence(
+ session, [record for record in records if record.id in ids]
+ )
+
+
+async def _hydrate_response_decision_evidence(
+ ctx: Any, result: dict[str, Any], records: list
+) -> None:
+ async with get_session(ctx.session_factory) as session:
+ await _attach_response_decision_evidence(session, result, records)
+
+
+async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:
+ """Repo context, corpus, git metadata for targets, and the acceptance set.
+
+ The prologue both target-aware modes open with, so both answer from the
+ same filtered corpus.
+ """
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ all_decisions = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
+ # ``governing_only``: what still binds, not what was ever accepted.
+ accepted = await accepted_decision_ids(
+ session, repository.id, governing_only=True
+ )
+ # Load git metadata for targets (for origin context in results)
+ target_git = await _load_target_git(session, repository.id, targets)
+ return ctx, repository, all_decisions, target_git, accepted
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
new file mode 100644
index 000000000..8d00d4f62
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
@@ -0,0 +1,385 @@
+"""Path mode: what governs one file, and the per-target cards several get."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.analysis.decisions.lifecycle import is_governing
+from repowise.core.analysis.decisions.scope import binds_to_paths
+from repowise.core.persistence.crud.authority import decision_currencies
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import DecisionRecord
+from repowise.core.precedent.currency import describe_decision_currency
+from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale
+from repowise.server.mcp_server._episodes import episode_evidence
+from repowise.server.mcp_server._helpers import (
+ _build_origin_story,
+ _compute_alignment,
+ _get_exclude_spec,
+ _get_repo,
+ _resolve_repo_context,
+ is_excluded,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import annotate_response_evidence_async
+from repowise.server.mcp_server.tool_why.archaeology import _git_archaeology_fallback
+from repowise.server.mcp_server.tool_why.caps import (
+ _cap_episodes,
+ _cap_path_decision_lanes,
+ _cap_supporting_lanes,
+ _cap_target_context,
+ _fit_path_response,
+ _serve_episodes,
+)
+from repowise.server.mcp_server.tool_why.lineage import _lineage_for_records
+from repowise.server.mcp_server.tool_why.loading import (
+ _all_git_metadata,
+ _attach_response_decision_evidence,
+ _git_metadata_for,
+ _hydrate_response_decision_evidence,
+ _load_corpus,
+)
+from repowise.server.mcp_server.tool_why.projection import (
+ _authority_of,
+ _governing_decision_entry,
+ _path_decision_sort_key,
+)
+
+
+async def _why_path(query: str, repo: str | None) -> dict:
+ """Mode 2: query is a path — governing decisions, origin story, alignment."""
+ ctx = await _resolve_repo_context(repo)
+ collector = OmissionCollector("get_why", repo_root=ctx.path)
+ if is_excluded(query, _get_exclude_spec(ctx.path)):
+ return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ res = await session.execute(
+ select(DecisionRecord).where(
+ DecisionRecord.repository_id == repository.id,
+ )
+ )
+ all_decisions = res.scalars().all()
+
+ # Load git metadata for origin story
+ git_meta = await _git_metadata_for(session, repository.id, query)
+
+ # Pre-load all git metadata for cross-file search (used by fallback)
+ all_git_meta = await _all_git_metadata(session, repository.id)
+
+ matched = _records_naming_path(all_decisions, query)
+ # A record with no acceptance row is a candidate whatever its status.
+ # Over every record, since alignment reads records this path did not match.
+ currencies = await decision_currencies(session, repository.id, all_decisions)
+
+ # Rank before capping, so the survivors are the ones that govern.
+ matched.sort(key=_path_decision_sort_key)
+ lineage_by_id = await _lineage_for_records(session, matched, all_decisions)
+ governing, candidates, retired = _split_by_authority(
+ matched, lineage_by_id, currencies, collector
+ )
+ await _stamp_still_true(governing, matched, ctx.path)
+
+ # Every lane: the origin story is evidence, not instruction.
+ origin_story = _build_origin_story(
+ query, git_meta, governing + candidates + retired
+ )
+
+ result_data: dict[str, Any] = {
+ "mode": "path",
+ "path": query,
+ "decisions": governing,
+ "origin_story": origin_story,
+ # A coverage number, so scored over every match, not the capped head.
+ "alignment": _compute_alignment(
+ query,
+ [{"id": d.id, "title": d.title} for d in matched],
+ all_decisions,
+ currencies,
+ ),
+ }
+ _add_review_lanes(result_data, candidates, retired)
+
+ # --- Fallback: git archaeology when no accepted decision governs ---
+ if not governing:
+ await _add_ungoverned_evidence(
+ result_data, query, git_meta, all_git_meta, repository, collector, ctx.path
+ )
+
+ # Episodes are additive, not a fallback: a governed file still has history.
+ episode_population: list[dict] = []
+ episodes, pending = await asyncio.to_thread(
+ episode_evidence,
+ ctx.path,
+ paths=[query],
+ full_population=episode_population,
+ )
+ collector = _serve_episodes(
+ result_data, episodes, episode_population, pending, collector, ctx.path
+ )
+
+ result_data["_meta"] = _build_meta(repository=repository)
+ await _attach_response_decision_evidence(session, result_data, all_decisions)
+ await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
+ _cap_supporting_lanes(result_data, collector, label=query)
+ _cap_episodes(result_data, episodes, collector)
+ _cap_path_decision_lanes(result_data, collector)
+ return _fit_path_response(result_data, ctx.path, collector=collector)
+
+
+def _records_naming_path(all_decisions: list, path: str) -> list:
+ """Records whose own scope names *path* as a file or a module."""
+ # A record whose file list is just its source commit's footprint does not
+ # govern those files; it stays in search.
+ return [
+ d
+ for d in all_decisions
+ if binds_to_paths(d.scope_basis)
+ and (
+ path in json.loads(d.affected_files_json)
+ or path in json.loads(d.affected_modules_json)
+ )
+ ]
+
+
+def _split_by_authority(
+ matched: list,
+ lineage_by_id: dict[str, list[dict]],
+ currencies: dict[str, Any],
+ collector: OmissionCollector,
+) -> tuple[list[dict], list[dict], list[dict]]:
+ """Project *matched* into ``(governing, candidates, retired)`` rows, in order."""
+ governing: list[dict] = []
+ candidates: list[dict] = []
+ retired: list[dict] = []
+ for d in matched:
+ # The supersedes/refines chain, so the answer is a lineage, not a list.
+ lineage = lineage_by_id.get(d.id, [])
+ entry = _governing_decision_entry(
+ d, json.loads(d.affected_files_json), lineage, collector
+ )
+ currency = currencies.get(d.id)
+ if currency is None:
+ entry["authority"] = "candidate"
+ # Never accepted: its own lane, not the rules for this file.
+ entry["review_state"] = "open"
+ candidates.append(entry)
+ continue
+ entry["currency"] = currency
+ if is_governing(currency):
+ entry["authority"] = "accepted"
+ governing.append(entry)
+ else:
+ # Accepted once, withdrawn since: neither rule nor review request,
+ # so a third lane rather than dropped.
+ entry["authority"] = "withdrawn"
+ retired.append(entry)
+ return governing, candidates, retired
+
+
+async def _stamp_still_true(
+ governing: list[dict], matched: list, repo_path: str | Path
+) -> None:
+ """Ask git whether the top governing record still holds, and say so on it."""
+ # Only the top record: the git query is affordable once per call, and the
+ # first-ranked record is the one a reader acts on. Candidates never get it.
+ if not governing:
+ return
+ top = next(d for d in matched if d.id == governing[0]["id"])
+ sentence = await asyncio.to_thread(
+ describe_decision_currency,
+ repo_path,
+ created_at=top.created_at,
+ nodes=json.loads(top.affected_files_json or "[]"),
+ )
+ if sentence:
+ governing[0]["still_true"] = sentence
+
+
+def _add_review_lanes(
+ result_data: dict[str, Any], candidates: list[dict], retired: list[dict]
+) -> None:
+ """Serve candidates and retired records beside the rules, each labelled."""
+ if candidates:
+ # Separated from the rules, so a review request never reads as one.
+ result_data["candidates"] = candidates
+ result_data["candidates_note"] = (
+ f"{len(candidates)} candidate(s) mention this path and none of them "
+ "govern it. Nobody has accepted them, so they are a review "
+ "request, not a rule. A person accepts one with "
+ "`repowise decision confirm <id> --scope <path>`. An agent "
+ "cannot, unless this repository has allowed it; where it has, "
+ "pass `--agent <your slug>` so the acceptance is not recorded "
+ "under a person's name."
+ )
+
+ if retired:
+ # History, never a rule.
+ result_data["history"] = retired
+ result_data["history_note"] = (
+ f"{len(retired)} decision(s) governing this path were accepted "
+ "and have since been superseded or withdrawn. They are history, "
+ "not rules."
+ )
+
+
+async def _add_ungoverned_evidence(
+ result_data: dict[str, Any],
+ path: str,
+ git_meta: Any | None,
+ all_git_meta: list,
+ repository: Any,
+ collector: OmissionCollector,
+ repo_path: str | Path,
+) -> None:
+ """Git archaeology and mined rationale for a file no accepted decision governs."""
+ result_data["git_archaeology"] = await _git_archaeology_fallback(
+ path,
+ git_meta,
+ all_git_meta,
+ repository,
+ collector,
+ )
+ # The "why" may live in a code comment.
+ rationale = _mine_rationale(
+ repo_path, [path], None, max_results=1000, truncate_blocks=False
+ )
+ if rationale:
+ result_data["code_rationale"] = rationale
+
+
+async def _build_target_context(
+ ctx: Any,
+ repository: Any,
+ all_decisions: list,
+ target_git: dict[str, Any],
+ targets: list[str],
+ collector: OmissionCollector | None = None,
+ accepted: set[str] | None = None,
+) -> dict[str, Any]:
+ """Per-target governing decisions + origin story, with archaeology fallback.
+
+ ``governing_decisions`` holds only accepted records; the rest go to
+ ``candidate_decisions``. The archaeology fallback keys on the accepted lane:
+ a file with only candidates is ungoverned, and its commits are stronger
+ evidence than an unconfirmed candidate.
+ """
+ async with get_session(ctx.session_factory) as session2:
+ # Load all git metadata for cross-file search
+ all_git_meta_list = await _all_git_metadata(session2, repository.id)
+
+ target_context: dict[str, Any] = {}
+ for t in targets:
+ target_context[t] = await _target_card(
+ t,
+ all_decisions,
+ target_git.get(t),
+ all_git_meta_list,
+ repository,
+ collector,
+ accepted or set(),
+ )
+ return target_context
+
+
+def _records_governing_target(all_decisions: list, target: str) -> list:
+ """Records naming *target*, or a module it sits under, best-first."""
+ governing_records = []
+ for d in all_decisions:
+ # Same gate as ``_why_path``, which one target routes to.
+ if not binds_to_paths(d.scope_basis):
+ continue
+ affected = json.loads(d.affected_files_json)
+ affected_mods = json.loads(d.affected_modules_json)
+ if target in affected or any(target.startswith(m + "/") for m in affected_mods):
+ governing_records.append(d)
+ governing_records.sort(key=_path_decision_sort_key)
+ return governing_records
+
+
+async def _target_card(
+ t: str,
+ all_decisions: list,
+ git_m: Any | None,
+ all_git_meta_list: list,
+ repository: Any,
+ collector: OmissionCollector | None,
+ accepted_ids: set[str],
+) -> dict[str, Any]:
+ """One target's card: its rules, its candidates, its origin, and archaeology."""
+ rows = [
+ {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "source": d.source,
+ "authority": _authority_of(d.id, accepted_ids),
+ }
+ for d in _records_governing_target(all_decisions, t)
+ ]
+ t_governing = [r for r in rows if r["authority"] == "accepted"]
+ t_candidates = [r for r in rows if r["authority"] != "accepted"]
+ origin = (
+ _build_origin_story(t, git_m, t_governing)
+ if git_m
+ else {
+ "available": False,
+ "summary": f"No git history for {t}.",
+ }
+ )
+ ctx_entry: dict[str, Any] = {
+ "governing_decisions": t_governing,
+ "origin": origin,
+ }
+ if t_candidates:
+ ctx_entry["candidate_decisions"] = t_candidates
+ # Git archaeology fallback when no *accepted* decision governs
+ if not t_governing:
+ ctx_entry["git_archaeology"] = await _git_archaeology_fallback(
+ t,
+ git_m,
+ all_git_meta_list,
+ repository,
+ collector,
+ )
+ return ctx_entry
+
+
+async def _why_targets(targets: list[str], repo: str | None) -> dict:
+ """Mode 2b: targets and no query — the paths themselves are the question.
+
+ One target is path mode outright, the fullest answer about a file. Several
+ get the per-target card instead: path mode per target would cost a corpus
+ scan and a git subprocess each.
+ """
+ if len(targets) == 1:
+ return await _why_path(targets[0], repo)
+
+ ctx, repository, all_decisions, target_git, accepted = await _load_corpus(
+ repo, targets
+ )
+ collector = OmissionCollector("get_why", repo_root=ctx.path)
+ result_data = {
+ "mode": "path",
+ "paths": targets,
+ "target_context": await _build_target_context(
+ ctx, repository, all_decisions, target_git, targets, collector, accepted
+ ),
+ "_meta": _build_meta(repository=repository, targets=targets),
+ }
+ await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
+ result_data = await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
+ _cap_supporting_lanes(result_data, collector, label="targets")
+ _cap_target_context(result_data["target_context"], collector)
+ collector.attach(result_data)
+ return result_data
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/projection.py b/packages/server/src/repowise/server/mcp_server/tool_why/projection.py
new file mode 100644
index 000000000..e00d8d129
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/projection.py
@@ -0,0 +1,139 @@
+"""Decision rows as get_why serves them: authority, ordering, projection."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
+from repowise.core.analysis.decisions.lifecycle import status_rank
+from repowise.server.mcp_server._budget import (
+ OmissionCollector,
+ cap_collection,
+)
+from repowise.server.mcp_server._helpers import (
+ _decision_body,
+)
+from repowise.server.mcp_server.tool_why.caps import _MAX_AFFECTED_FILES
+
+
+def _authority_of(decision_id: str, accepted: set[str]) -> str:
+ """``"accepted"`` when an acceptance binds this record, else ``"candidate"``.
+
+ Membership of the acceptance set, never ``status`` (see
+ :func:`~repowise.core.persistence.crud.authority.decision_currencies`).
+ Stamped on every emitted row so a ruling reads apart from a guess.
+ """
+ return "accepted" if decision_id in accepted else "candidate"
+
+
+def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:
+ return (
+ status_rank(d.status),
+ -(d.confidence or 0.0),
+ d.staleness_score or 0.0,
+ )
+
+
+def _governing_decision_entry(
+ d: Any,
+ affected_files: list,
+ lineage: list[dict],
+ collector: OmissionCollector | None = None,
+ accepted: set[str] | None = None,
+) -> dict:
+ """Serialize a decision that governs a path, including its lineage chain."""
+ entry = {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "authority": _authority_of(d.id, accepted or set()),
+ "context": d.context,
+ "decision": _decision_body(d),
+ "rationale": d.rationale,
+ "alternatives": json.loads(d.alternatives_json),
+ "consequences": json.loads(d.consequences_json),
+ "affected_files": affected_files[:_MAX_AFFECTED_FILES],
+ "source": d.source,
+ "confidence": d.confidence,
+ "staleness_score": d.staleness_score,
+ "lineage": lineage if len(lineage) > 1 else [],
+ }
+ _cap_affected_files(entry, d.id, affected_files, collector)
+ return entry
+
+
+def _cap_affected_files(
+ entry: dict,
+ decision_id: str,
+ affected_files: list,
+ collector: OmissionCollector | None,
+) -> None:
+ """Bank the paths past the head *entry* serves, and count them on it."""
+ if len(affected_files) > _MAX_AFFECTED_FILES:
+ cap_collection(
+ entry,
+ "affected_files",
+ affected_files,
+ _MAX_AFFECTED_FILES,
+ collector,
+ label=f"decision {decision_id} :: affected_files beyond cap={_MAX_AFFECTED_FILES}",
+ )
+
+
+def _merge_decisions(
+ keyword_matches: list[tuple[Any, list[str]]],
+ decision_results: list,
+ lineage_by_id: dict[str, list[dict]],
+ collector: OmissionCollector | None = None,
+ accepted: set[str] | None = None,
+) -> list[dict]:
+ """Project collapsed keyword hits, then append semantic hits not already in.
+
+ *keyword_matches* arrives from :func:`_collapse_restatements`, so the folded
+ ids ride along on ``restates``: nothing becomes unaddressable and the store
+ is untouched.
+ """
+ seen_ids: set[str] = set()
+ merged_decisions: list[dict] = []
+ for d, folded in keyword_matches:
+ if d.id in seen_ids:
+ continue
+ seen_ids.update([d.id, *folded])
+ affected_files = json.loads(d.affected_files_json)
+ entry = {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "authority": _authority_of(d.id, accepted or set()),
+ "decision": _decision_body(d),
+ "rationale": d.rationale,
+ "context": d.context,
+ "consequences": json.loads(d.consequences_json),
+ # A head plus a total; see ``_MAX_AFFECTED_FILES``.
+ "affected_files": affected_files[:_MAX_AFFECTED_FILES],
+ "source": d.source,
+ "confidence": d.confidence,
+ "lineage": lineage_by_id.get(d.id, []),
+ }
+ _cap_affected_files(entry, d.id, affected_files, collector)
+ if folded:
+ entry["restates"] = folded
+ merged_decisions.append(entry)
+
+ for r in decision_results:
+ # Strip the "decision:" prefix so the returned id matches the SQL primary key.
+ real_id = r.page_id[len(DECISION_VECTOR_PREFIX) :]
+ if real_id in seen_ids:
+ continue
+ seen_ids.add(real_id)
+ merged_decisions.append(
+ {
+ "id": real_id,
+ "title": r.title,
+ "snippet": r.snippet,
+ "relevance_score": r.score,
+ "authority": _authority_of(real_id, accepted or set()),
+ }
+ )
+ return merged_decisions
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/ranking.py b/packages/server/src/repowise/server/mcp_server/tool_why/ranking.py
new file mode 100644
index 000000000..cf7f9e7cb
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/ranking.py
@@ -0,0 +1,159 @@
+"""Keyword relevance ranking and restatement collapse over decision records."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from repowise.core.analysis.decisions.lifecycle import status_rank
+from repowise.server.mcp_server._why_evidence import (
+ decision_collapse_key,
+)
+from repowise.server.mcp_server._why_relevance import (
+ clears_floor,
+ question_terms,
+ relevance,
+ term_idf,
+)
+
+
+def _score_keyword_matches(
+ all_decisions: list, query: str, target_set: set[str]
+) -> list[tuple[tuple[float, float, int], Any]]:
+ """``_rank_keyword_matches`` with each record's whole sort key kept beside it.
+
+ For workspace search, which merges per-store survivors. The whole key, not
+ the score: records covering the same question terms score identically, so a
+ merge on score alone would drop both tie-breaks. The rules are documented on
+ ``_rank_keyword_matches``.
+ """
+ terms = question_terms(query)
+ texts = {id(d): _record_text(d) for d in all_decisions}
+ idf = term_idf(terms, list(texts.values()))
+
+ scored_decisions: list[tuple[float, float, int, Any]] = []
+ for d in all_decisions:
+ # Every record must clear the floor on what it says about the question;
+ # naming a target only boosts the tie-break, never bypasses the floor.
+ score = relevance(texts[id(d)], idf)
+ if not clears_floor(score):
+ continue
+ scored_decisions.append(
+ (
+ -score,
+ -_score_decision(d, set(terms), target_set),
+ status_rank(d.status),
+ d,
+ )
+ )
+ scored_decisions.sort(key=lambda t: (t[0], t[1], t[2]))
+ return [((t[0], t[1], t[2]), t[3]) for t in scored_decisions]
+
+
+def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:
+ """Records relevant enough to serve, best-first. Empty when none are.
+
+ Ranks by how much of the question's vocabulary a record carries, rarer
+ words weighing more; a raw occurrence count would reward length and common
+ words. The occurrence count breaks ties, then status.
+
+ Status is a tie-break, never a gate: few records are active, so a status
+ gate would serve weak confirmed matches ahead of the relevant proposed ones.
+
+ Records below the floor are dropped, so an empty return is an honest miss.
+ The pool is wider than the serving cap because restatements collapse
+ downstream.
+ """
+ return [d for _, d in _score_keyword_matches(all_decisions, query, target_set)]
+
+
+def _evidence_key(d: Any) -> tuple[object, ...] | None:
+ """The evidence a record cites, as a merge key, or ``None`` when it cites none.
+
+ Re-extraction paraphrases a record's prose but not its provenance, so the
+ key is the cited commits or exact source range plus the extractor, never
+ the text: a wrong title merge could hide a confirmed record. Incomplete
+ coordinates return ``None``, since keeping a duplicate beats erasing a
+ decision. Narrower than public evidence ids, which several decisions share.
+ """
+ return decision_collapse_key(d)
+
+
+def _collapse_restatements(records: list) -> list[tuple[Any, list[str]]]:
+ """``(kept, folded_ids)`` per distinct decision, input order preserved.
+
+ Runs on records, before the lineage walk and projection. Records citing no
+ evidence cannot be compared and are always kept.
+ """
+ by_evidence: dict[tuple[object, ...], int] = {}
+ out: list[tuple[Any, list[str]]] = []
+ for d in records:
+ key = _evidence_key(d)
+ if key is not None and key in by_evidence:
+ out[by_evidence[key]][1].append(d.id)
+ continue
+ if key is not None:
+ by_evidence[key] = len(out)
+ out.append((d, []))
+ return out
+
+
+def _weighted_fields(d: Any) -> list[tuple[float, str]]:
+ """The searchable text of a record, lowercased, by field weight.
+
+ ``affected_files`` is deliberately absent: matching words against paths
+ scores a record by its breadth. A scope is not question text; it feeds the
+ target boost in :func:`_score_decision` instead.
+ """
+ return [
+ (3.0, d.title.lower()),
+ (2.0, d.decision.lower()),
+ (2.0, d.rationale.lower()),
+ (1.5, d.context.lower()),
+ (1.0, " ".join(json.loads(d.consequences_json)).lower()),
+ (1.0, " ".join(json.loads(d.tags_json)).lower()),
+ (1.0, (d.evidence_file or "").lower()),
+ ]
+
+
+def _record_text(d: Any) -> str:
+ """The same text, unweighted, for term coverage and the relevance floor.
+
+ Built from :func:`_weighted_fields` so the floor and tie-break see one text.
+ """
+ return " ".join(text for _, text in _weighted_fields(d))
+
+
+def _score_decision(
+ d: Any,
+ query_words: set[str],
+ target_files: set[str],
+) -> float:
+ """Score a decision against query words with field weighting and target boosting."""
+ if not query_words:
+ return 1.0 if target_files else 0.0
+
+ score = 0.0
+ for weight, text in _weighted_fields(d):
+ for word in query_words:
+ if word in text:
+ score += weight
+
+ # Target file boosting: decisions governing target files get a bonus
+ if target_files:
+ score += _target_boost(d, target_files)
+
+ return score
+
+
+def _target_boost(d: Any, target_files: set[str]) -> float:
+ """Bonus for a record that governs the files the caller named."""
+ boost = 0.0
+ affected = set(json.loads(d.affected_files_json))
+ affected_mods = json.loads(d.affected_modules_json)
+ for t in target_files:
+ if t in affected:
+ boost += 5.0 # Strong boost for exact file match
+ elif any(t.startswith(m + "/") for m in affected_mods):
+ boost += 3.0 # Module-level match
+ return boost
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/reference.py b/packages/server/src/repowise/server/mcp_server/tool_why/reference.py
new file mode 100644
index 000000000..19b0570fa
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/reference.py
@@ -0,0 +1,160 @@
+"""Reference mode: resolve one emitted decision or evidence id."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from repowise.core.persistence.crud.authority import resolve_decision_id
+from repowise.core.persistence.database import get_session
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ filter_path_list,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import annotate_response_evidence_async
+from repowise.server.mcp_server.tool_why.loading import _attach_decision_evidence, _load_corpus
+from repowise.server.mcp_server.tool_why.projection import _governing_decision_entry
+
+
+async def _why_reference(
+ reference_id: str,
+ repo: str | None,
+ *,
+ reference: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Resolve one emitted decision/evidence id without relevance search."""
+
+ ctx, repository, records, _target_git, accepted = await _load_corpus(repo, None)
+ async with get_session(ctx.session_factory) as session:
+ await _attach_decision_evidence(session, records)
+ reference_id = await _follow_moved_decision_id(session, reference_id, records)
+
+ payload = {
+ "decisions": [
+ _governing_decision_entry(
+ record,
+ filter_path_list(
+ json.loads(record.affected_files_json or "[]"),
+ _get_exclude_spec(ctx.path),
+ ),
+ [],
+ accepted=accepted,
+ )
+ for record in records
+ ]
+ }
+ await annotate_response_evidence_async(
+ payload,
+ ctx.alias,
+ records,
+ repo_root=ctx.path,
+ )
+ matches = [
+ row
+ for row in payload["decisions"]
+ if row["id"] == reference_id
+ or any(ref["id"] == reference_id for ref in row.get("evidence_refs", []))
+ ]
+ matching_refs = _matching_evidence_refs(matches, reference_id, reference, ctx)
+ meta = _build_meta(repository=repository)
+ persistence = (payload.get("_meta") or {}).get("reference_persistence")
+ if persistence is not None:
+ meta["reference_persistence"] = persistence
+ return {
+ "mode": "reference",
+ "reference_id": reference_id,
+ "resolved": bool(matches or matching_refs),
+ "decisions": matches,
+ "evidence_refs": list(matching_refs.values()),
+ "_meta": meta,
+ }
+
+
+async def _follow_moved_decision_id(
+ session: Any, reference_id: str, records: list
+) -> str:
+ """The live id for a decision id that no longer names a live record."""
+ # A quoted id may name a decision that has since moved. A live id is left
+ # alone, so a merged candidate still answers about itself.
+ stale_decision_id = not reference_id.startswith("ev_") and not any(
+ record.id == reference_id for record in records
+ )
+ if stale_decision_id:
+ reference_id = await resolve_decision_id(session, reference_id) or reference_id
+ return reference_id
+
+
+def _matching_evidence_refs(
+ matches: list[dict[str, Any]],
+ reference_id: str,
+ reference: dict[str, Any] | None,
+ ctx: Any,
+) -> dict[str, dict[str, Any]]:
+ """Evidence refs answering *reference_id*, keyed by id.
+
+ From the matched rows first; an ``ev_`` id no row carries is looked up in
+ the evidence stores; a caller's structured reference is echoed back only
+ once something matched and its coordinates reproduce its own id.
+ """
+ matching_refs = {
+ ref["id"]: ref
+ for row in matches
+ for ref in row.get("evidence_refs", [])
+ if ref["id"] == reference_id
+ }
+ if not matches and reference_id.startswith("ev_"):
+ live_ref = _resolve_unattached_evidence_reference(
+ reference_id, ctx.alias, ctx.path
+ )
+ if live_ref is not None:
+ matching_refs[live_ref["id"]] = live_ref
+ if (
+ reference is not None
+ and matching_refs
+ and _evidence_reference_matches_id(reference)
+ ):
+ matching_refs[reference_id] = dict(reference)
+ return matching_refs
+
+
+def _evidence_reference_matches_id(value: dict[str, Any]) -> bool:
+ """Validate the identity-bearing coordinates of a structured evidence ref."""
+
+ from repowise.server.mcp_server._references import reference as build_reference
+
+ identifier = value.get("id")
+ repository = value.get("repository")
+ kind = value.get("kind")
+ if not all(isinstance(item, str) for item in (identifier, repository, kind)):
+ return False
+ coordinate_keys = {
+ "commit": ("commit",),
+ "file_range": ("path", "range"),
+ "file_content": ("path", "line", "content_id"),
+ "legacy": ("path", "content_id", "commit_prefix"),
+ }.get(kind)
+ if coordinate_keys is None:
+ return False
+ coordinates = {key: value[key] for key in coordinate_keys if key in value}
+ return build_reference(kind, repository, **coordinates)["id"] == identifier
+
+
+def _resolve_unattached_evidence_reference(
+ reference_id: str,
+ repository: str,
+ repo_root: str | Path,
+) -> dict[str, Any] | None:
+ """Resolve evidence not attached to a persisted decision without a repo scan."""
+
+ from repowise.server.mcp_server._references import repository_identity
+ from repowise.server.mcp_server._why_evidence import (
+ resolve_cached_evidence_reference,
+ resolve_persisted_evidence_reference,
+ )
+
+ repository = repository_identity(repository)
+ return resolve_cached_evidence_reference(
+ repository, reference_id
+ ) or resolve_persisted_evidence_reference(repository, reference_id, repo_root)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/search.py b/packages/server/src/repowise/server/mcp_server/tool_why/search.py
new file mode 100644
index 000000000..5c3ecb90f
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/search.py
@@ -0,0 +1,357 @@
+"""Search mode: a natural-language question, optionally anchored to targets."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+from typing import Any
+
+from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
+from repowise.core.providers.embedding import store_has_semantic_vectors
+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale
+from repowise.server.mcp_server._episodes import episode_evidence
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import annotate_response_evidence_async
+from repowise.server.mcp_server._why_relevance import (
+ clears_floor,
+ query_scorer,
+ recovery_note,
+ redirect_for,
+ redirect_when_served,
+)
+from repowise.server.mcp_server.tool_why.basis import _has_archaeology
+from repowise.server.mcp_server.tool_why.caps import (
+ _MAX_SEARCH_DECISIONS,
+ _SEMANTIC_WINDOW,
+ _cap_episodes,
+ _cap_supporting_lanes,
+ _cap_target_context,
+ _serve_episodes,
+)
+from repowise.server.mcp_server.tool_why.lineage import _lineage_for_matches
+from repowise.server.mcp_server.tool_why.loading import (
+ _hydrate_response_decision_evidence,
+ _load_corpus,
+)
+from repowise.server.mcp_server.tool_why.path_mode import _build_target_context
+from repowise.server.mcp_server.tool_why.projection import _merge_decisions
+from repowise.server.mcp_server.tool_why.ranking import (
+ _collapse_restatements,
+ _rank_keyword_matches,
+ _record_text,
+)
+
+
+async def _fts_doc_results(ctx: Any, query: str) -> list:
+ """Documentation hits from the lexical index.
+
+ The keyless path, and the fallback whenever the vector store is present but
+ unusable: a store that cannot rank gives the same answer as no store.
+ """
+ doc_results: list = []
+ with contextlib.suppress(Exception):
+ doc_results = await ctx.fts.search(query, limit=_SEMANTIC_WINDOW)
+ return doc_results
+
+
+async def _semantic_lanes(ctx: Any, query: str) -> tuple[list, list]:
+ """``(decision_hits, doc_hits)`` from **one** embedding of *query*.
+
+ One ``embed_texts`` plus ``search_by_vector`` (see ``vector_store._base``),
+ with ``search`` as the fallback for a backend without raw-vector search. The
+ window is split by namespace, so decisions never come back as documentation.
+
+ The decision lane stays empty on a keyless index, deliberately: a window of
+ arbitrary decisions is worse than none.
+ """
+ if not store_has_semantic_vectors(getattr(ctx, "vector_store", None)):
+ return [], await _fts_doc_results(ctx, query)
+
+ raw: list | None = None
+ with contextlib.suppress(Exception):
+ vectors = await ctx.vector_store.embed_texts([query])
+ if vectors:
+ raw = await ctx.vector_store.search_by_vector(vectors[0], limit=_SEMANTIC_WINDOW)
+ if raw is None:
+ # Backend holds no embedder, or cannot search by raw vector.
+ raw = await ctx.vector_store.search(query, limit=_SEMANTIC_WINDOW)
+ if raw is None:
+ return [], await _fts_doc_results(ctx, query)
+
+ decision_hits, doc_hits = [], []
+ for r in raw:
+ page_id = getattr(r, "page_id", "")
+ if page_id.startswith(DECISION_VECTOR_PREFIX):
+ decision_hits.append(r)
+ else:
+ doc_hits.append(r)
+ return decision_hits, doc_hits
+
+
+def _focus_target_context(
+ target_context: dict[str, Any],
+ query: str,
+ targets: list[str],
+ corpus: list[str],
+) -> None:
+ """Drop from each target card whatever does not bear on *query*, in place.
+
+ A card is built from a path, so without this it would answer every
+ question about a file with the same bytes. Only when a query is present.
+
+ Each emptied block becomes a count plus the call that recovers it, so "no
+ history mentions what you asked" reads apart from "no history".
+ """
+ recall = f"get_why(targets={json.dumps(targets)})"
+ # Term weights from the whole decision corpus: a card's few rows are too
+ # small a sample for ``term_idf`` (see its warning).
+ score = query_scorer(query, corpus)
+ for entry in target_context.values():
+ if not isinstance(entry, dict):
+ continue
+
+ # ``governing_decisions`` is exempt: an accepted rule binds whatever the
+ # question. A candidate binds nothing, so it must earn its place.
+ _keep_relevant(entry, "candidate_decisions", score, recall)
+
+ # Only the origin's decision lane; the author and first commit are
+ # cheap and wanted whatever the question.
+ origin = entry.get("origin")
+ if isinstance(origin, dict):
+ _keep_relevant(origin, "linked_decisions", score, recall)
+
+ arch = entry.get("git_archaeology")
+ if isinstance(arch, dict):
+ _focus_archaeology(arch, score, recall)
+
+
+def _focus_archaeology(
+ arch: dict[str, Any], score: Any, recall: str
+) -> None:
+ """Keep the commits that carry the question's terms, count the rest.
+
+ Here no decision cleared the floor, so these commits are the best evidence
+ left.
+ """
+ for lane in ("file_commits", "cross_references", "git_log"):
+ _keep_relevant(arch, lane, score, recall)
+
+
+def _keep_relevant(block: dict[str, Any], key: str, score: Any, recall: str) -> None:
+ """Keep the rows of ``block[key]`` that clear the floor for *score*.
+
+ When none do, the lane becomes ``<key>_omitted``: a count and the recall.
+ """
+ rows = block.get(key)
+ if not isinstance(rows, list) or not rows:
+ return
+ kept = [r for r in rows if clears_floor(score(json.dumps(r, default=str)))]
+ if kept:
+ block[key] = kept
+ else:
+ block.pop(key, None)
+ block[f"{key}_omitted"] = recovery_note(len(rows), recall)
+
+
+async def _why_no_match(
+ query: str,
+ targets: list[str] | None,
+ ctx: Any,
+ repository: Any,
+ all_decisions: list,
+ target_git: dict[str, Any],
+ accepted: set[str] | None = None,
+) -> dict[str, Any]:
+ """The whole response when no record clears the relevance floor.
+
+ Returns before the semantic lookup and episodes: nearest neighbours always
+ return something, and serving them beside a redirect is padding.
+
+ Named targets are the exception: their git archaeology and rationale
+ comments are evidence about the thing asked, as in path mode.
+ """
+ result: dict[str, Any] = {
+ "mode": "search",
+ "query": query,
+ "decisions": [],
+ **redirect_for(query),
+ }
+ collector: OmissionCollector | None = None
+ if targets:
+ collector = OmissionCollector("get_why", repo_root=ctx.path)
+ result["target_context"] = await _build_target_context(
+ ctx, repository, all_decisions, target_git, targets, collector, accepted
+ )
+ rationale = _mine_rationale(
+ ctx.path, targets, query, max_results=1000, truncate_blocks=False
+ )
+ if rationale:
+ result["code_rationale"] = rationale
+ await _hydrate_response_decision_evidence(ctx, result, all_decisions)
+ await annotate_response_evidence_async(
+ result, ctx.alias, all_decisions, repo_root=ctx.path
+ )
+ if collector is not None:
+ _focus_target_context(
+ result["target_context"],
+ query,
+ list(targets or []),
+ [_record_text(d) for d in all_decisions],
+ )
+ _cap_supporting_lanes(result, collector, label=query)
+ _cap_target_context(result["target_context"], collector)
+ # Don't redirect away from evidence this response is already serving.
+ served = _served_lanes(result)
+ if served:
+ result.pop("try_instead", None)
+ result.update(
+ redirect_when_served(served, f"get_why(targets={json.dumps(targets)})")
+ )
+ result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
+ if collector is not None:
+ collector.attach(result)
+ return result
+
+
+def _served_lanes(result: dict[str, Any]) -> list[str]:
+ """Labels of the evidence lanes *result* carries, top level or on a target card."""
+ cards = (result.get("target_context") or {}).values()
+ return [
+ label
+ for key, label in (
+ ("code_rationale", "rationale comments"),
+ ("git_archaeology", "commit history"),
+ )
+ if result.get(key)
+ or any(isinstance(e, dict) and _has_archaeology(e.get(key)) for e in cards)
+ ]
+
+
+async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:
+ """Mode 3: natural-language, target-aware decision + documentation search."""
+ ctx, repository, all_decisions, target_git, accepted = await _load_corpus(
+ repo, targets
+ )
+
+ target_set = set(targets) if targets else set()
+ # Rank wide, collapse, and project the whole pool; the cap comes last so
+ # the rows it sheds are banked whole for recovery.
+ ranked = _rank_keyword_matches(all_decisions, query, target_set)
+ if not ranked:
+ return await _why_no_match(
+ query, targets, ctx, repository, all_decisions, target_git, accepted
+ )
+ collector = OmissionCollector("get_why", repo_root=ctx.path)
+ collapsed = _collapse_restatements(ranked)
+ decision_results, doc_results = await _semantic_lanes(ctx, query)
+ lineage_by_id = await _lineage_for_matches(
+ ctx, [d for d, _ in collapsed], all_decisions
+ )
+ merged_decisions = _merge_decisions(
+ collapsed, decision_results, lineage_by_id, collector, accepted
+ )
+
+ # Semantic hits are small id-plus-snippet rows, not worth dropping.
+ result_data: dict[str, Any] = {
+ "mode": "search",
+ "query": query,
+ "decisions": merged_decisions,
+ "related_documentation": _related_documentation(doc_results),
+ }
+
+ if targets:
+ result_data["target_context"] = await _build_target_context(
+ ctx, repository, all_decisions, target_git, targets, collector, accepted
+ )
+
+ # Targets resolve through the node index; without them the question itself
+ # is the only handle, so it is ranked against the bodies.
+ episode_population: list[dict] = []
+ episodes, pending = await asyncio.to_thread(
+ episode_evidence,
+ ctx.path,
+ paths=targets or None,
+ query=None if targets else query,
+ full_population=episode_population,
+ )
+ if episodes and targets:
+ episodes, pending = _focus_target_episodes(
+ query, all_decisions, episodes, episode_population, pending
+ )
+ collector = _serve_episodes(
+ result_data, episodes, episode_population, pending, collector, ctx.path
+ )
+
+ await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
+ await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
+ if targets:
+ _focus_target_context(
+ result_data["target_context"],
+ query,
+ list(targets),
+ [_record_text(d) for d in all_decisions],
+ )
+ _cap_supporting_lanes(result_data, collector, label=query)
+ if targets:
+ _cap_target_context(result_data["target_context"], collector)
+ _cap_episodes(result_data, episodes, collector)
+ result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
+ # The middleware owns the search-mode shed order; the path-only fitter would
+ # drop the primary decision lane too early.
+ cap_collection(
+ result_data,
+ "decisions",
+ result_data["decisions"],
+ _MAX_SEARCH_DECISIONS,
+ collector,
+ label=f"search decisions beyond cap={_MAX_SEARCH_DECISIONS}",
+ )
+ cap_collection(
+ result_data,
+ "related_documentation",
+ result_data["related_documentation"],
+ 3,
+ collector,
+ label="related_documentation beyond cap=3",
+ )
+ collector.attach(result_data)
+ return result_data
+
+
+def _related_documentation(doc_results: list) -> list[dict[str, Any]]:
+ """Documentation hits as served rows."""
+ return [
+ {
+ "page_id": r.page_id,
+ "title": r.title,
+ "page_type": r.page_type,
+ "snippet": r.snippet,
+ "relevance_score": r.score,
+ }
+ for r in doc_results
+ ]
+
+
+def _focus_target_episodes(
+ query: str,
+ all_decisions: list,
+ episodes: list[dict],
+ population: list[dict],
+ pending: list[tuple[dict, str, str]],
+) -> tuple[list[dict], list[tuple[dict, str, str]]]:
+ """Narrow target-scoped episodes to those bearing on *query*.
+
+ Trims *population* in place and returns the matching ``(episodes,
+ pending)``, unchanged when every episode clears the floor.
+ """
+ # ``episode_evidence`` ignores the query when scoped, so filter by it here.
+ score = query_scorer(query, [_record_text(d) for d in all_decisions])
+ kept = [e for e in population if clears_floor(score(json.dumps(e, default=str)))]
+ if len(kept) == len(population):
+ return episodes, pending
+ population[:] = kept
+ return [e for e in episodes if e in kept], [t for t in pending if t[0] in kept]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/tool.py b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
new file mode 100644
index 000000000..b713cafdc
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
@@ -0,0 +1,107 @@
+"""The ``get_why`` MCP tool: argument handling and dispatch to one mode."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.registry import ToolRecipe
+from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.server.mcp_server._helpers import (
+ _is_path,
+ _is_workspace_mode,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server.tool_why.basis import _stamp_answer_basis
+from repowise.server.mcp_server.tool_why.dashboard import _why_health_dashboard
+from repowise.server.mcp_server.tool_why.path_mode import _why_path, _why_targets
+from repowise.server.mcp_server.tool_why.reference import _why_reference
+from repowise.server.mcp_server.tool_why.search import _why_search
+from repowise.server.mcp_server.tool_why.workspace import _why_workspace_search
+
+
+ surface_order=70,
+ artifact_type="decisions",
+ presentation="decision_evidence",
+ evidence_basis="inferred",
+ recipes=(
+ ToolRecipe(
+ "read_rationale",
+ 'get_why(targets=["path"])',
+ ("get_why",),
+ ),
+ ),
+)
+async def get_why(
+ query: str | None = None,
+ targets: list[str] | None = None,
+ repo: str | None = None,
+ id: str | None = None,
+ reference: dict[str, Any] | None = None,
+) -> dict:
+ """Why this code is shaped this way — decision records + evidence commits.
+
+ Call before refactors or pattern divergences. Query modes: a question
+ ("why is auth using JWT?"), a file path (governing decisions + origin
+ story + alignment score), a question anchored to targets, or no query
+ (decision health dashboard). Falls back to git archaeology when no
+ decisions exist for a path — never empty. Evidence-bearing rows carry an
+ explicit ``provenance`` and self-contained ``evidence_refs``; matching ids
+ mean shared evidence, not independent corroboration. Every decision row
+ carries ``authority``: ``accepted`` means somebody signed it, ``candidate``
+ means nobody has yet. ``answer_basis`` names the strongest lane the response
+ rests on (decision, episode, rationale, archaeology, documentation,
+ candidate); only ``decision`` is a ruling, and ``candidate`` is the weakest
+ -- it means nothing cleared that bar.
+
+ Args:
+ query: question, file/module path, or omit for the dashboard.
+ targets: optional file paths to anchor the search, or to ask about on
+ their own when there is no query.
+ repo: usually omitted.
+ id: decision or ``ev_...`` evidence id emitted by this or another tool.
+ reference: structured evidence reference. Its id and repository are
+ accepted together without caller translation.
+ """
+ if reference:
+ id, repo = _reference_coordinates(reference, id, repo)
+ if id:
+ if repo == "all":
+ return _unsupported_repo_all("get_why (reference lookup)")
+ return _stamp_answer_basis(await _why_reference(id, repo, reference=reference))
+
+ # --- repo="all": search decisions across ALL repos ---
+ if repo == "all":
+ if not query:
+ return _unsupported_repo_all("get_why (health dashboard)")
+ return _stamp_answer_basis(await _why_workspace_search(query))
+
+ # --- Mode 1: No query → the targets, or the health dashboard ---
+ # Targets first: naming files and asking nothing asks about those files.
+ if not query:
+ if targets:
+ return _stamp_answer_basis(await _why_targets(list(targets), repo))
+ # An orientation call, not an answer: no basis to name.
+ return await _why_health_dashboard(repo)
+
+ # --- Mode 2: Path → decisions, origin story, alignment ---
+ if _is_path(query):
+ return _stamp_answer_basis(await _why_path(query, repo))
+
+ # --- Mode 3: Natural language → target-aware search ---
+ return _stamp_answer_basis(await _why_search(query, targets, repo))
+
+
+def _reference_coordinates(
+ reference: dict[str, Any], decision_id: str | None, repo: str | None
+) -> tuple[str | None, str | None]:
+ """Fill the id and repo a caller left unset from their structured reference."""
+ if decision_id is None and isinstance(reference.get("id"), str):
+ decision_id = reference["id"]
+ if (
+ repo is None
+ and _is_workspace_mode()
+ and isinstance(reference.get("repository"), str)
+ ):
+ repo = reference["repository"]
+ return decision_id, repo
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py b/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py
new file mode 100644
index 000000000..be4116044
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py
@@ -0,0 +1,134 @@
+"""Workspace mode (``repo="all"``): ranked decision search across every store."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.persistence.database import get_session
+from repowise.server.mcp_server._budget import (
+ OmissionCollector,
+ cap_collection,
+)
+from repowise.server.mcp_server._helpers import (
+ _decision_body,
+ _get_exclude_spec,
+ _get_repo,
+ _resolve_all_contexts,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import (
+ annotate_response_evidence_async,
+)
+from repowise.server.mcp_server._why_relevance import (
+ redirect_for,
+)
+from repowise.server.mcp_server.tool_why.caps import _MAX_WORKSPACE_DECISIONS
+from repowise.server.mcp_server.tool_why.loading import _attach_decision_evidence, _decision_corpus
+from repowise.server.mcp_server.tool_why.ranking import (
+ _collapse_restatements,
+ _score_keyword_matches,
+)
+
+
+async def _why_workspace_search(query: str) -> dict:
+ """repo="all": the question single-repo search answers, across the workspace.
+
+ Same corpus filters and ranking as single-repo search, so an unanswerable
+ question gets the redirect.
+
+ Each store is scored against its own corpus, never a pooled one: pooling
+ would change term-weight ratios and so which records clear the calibrated
+ floor. The cost is at the merge, where scores from different distributions
+ decide which store loses a slot, approximately. If that ever needs to be
+ exact, sweep a floor against a pooled corpus rather than pool under this one.
+ """
+ scored = await _score_workspace(query)
+ if not scored:
+ return {
+ "mode": "search",
+ "query": query,
+ "workspace": True,
+ "decisions": [],
+ **redirect_for(query),
+ "_meta": _build_meta(),
+ }
+
+ # The store's own key first; alias and id settle ties, for a stable order.
+ scored.sort(key=lambda t: (t[0], t[1], t[3]))
+ selected = scored
+ collector = OmissionCollector(
+ "get_why", repo_root=selected[0][2].path if selected else None
+ )
+ for selected_ctx in {entry[2].alias: entry[2] for entry in selected}.values():
+ selected_records = [entry[4] for entry in selected if entry[2] is selected_ctx]
+ async with get_session(selected_ctx.session_factory) as session:
+ await _attach_decision_evidence(session, selected_records)
+ decisions: list[dict] = []
+ entries_by_alias: dict[str, list[dict[str, Any]]] = {}
+ records_by_alias: dict[str, list[Any]] = {}
+ contexts_by_alias = {entry[1]: entry[2] for entry in selected}
+ for _, alias, _selected_ctx, _id, d, folded in selected:
+ entry = _workspace_entry(alias, d, folded)
+ entries_by_alias.setdefault(alias, []).append(entry)
+ records_by_alias.setdefault(alias, []).append(d)
+ decisions.append(entry)
+ for alias, entries in entries_by_alias.items():
+ await annotate_response_evidence_async(
+ {"decisions": entries},
+ alias,
+ records_by_alias[alias],
+ repo_root=contexts_by_alias[alias].path,
+ )
+ result = {
+ "mode": "search",
+ "query": query,
+ "workspace": True,
+ "decisions": decisions,
+ "_meta": _build_meta(),
+ }
+ cap_collection(
+ result,
+ "decisions",
+ decisions,
+ _MAX_WORKSPACE_DECISIONS,
+ collector,
+ label=f"workspace decisions beyond cap={_MAX_WORKSPACE_DECISIONS}",
+ )
+ collector.attach(result)
+ return result
+
+
+async def _score_workspace(
+ query: str,
+) -> list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]]:
+ """Every store's relevant records, collapsed per store, with their sort keys."""
+ contexts = await _resolve_all_contexts()
+ scored: list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]] = []
+ for ctx in contexts:
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ records = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
+ ranked = _score_keyword_matches(records, query, set())
+ # Collapsed per store: ``_evidence_key`` carries no repo, so stores
+ # sharing a commit would fold into one across the merge.
+ key_by_id = {d.id: key for key, d in ranked}
+ for d, folded in _collapse_restatements([d for _, d in ranked]):
+ scored.append((key_by_id[d.id], ctx.alias, ctx, d.id, d, folded))
+ return scored
+
+
+def _workspace_entry(alias: str, d: Any, folded: list[str]) -> dict[str, Any]:
+ """One workspace search row, naming the store it came from."""
+ entry = {
+ "repo": alias,
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "decision": _decision_body(d),
+ "rationale": d.rationale,
+ "source": d.source,
+ "confidence": d.confidence,
+ }
+ if folded:
+ entry["restates"] = folded
+ return entry
diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
index 280da7af8..3100f123a 100644
--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
@@ -611,7 +611,7 @@ async def test_why_real_minimum_and_typical_wire_shapes(
async def test_why_real_adversarial_wire_recovers_decisions_docs_and_episodes(
setup_mcp: str, session: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- import repowise.server.mcp_server.tool_why as why_mod
+ import repowise.server.mcp_server.tool_why.search as why_search
_configure_omissions(tmp_path)
await _seed_why_decisions(session, setup_mcp, 9)
@@ -659,8 +659,8 @@ async def test_why_real_adversarial_wire_recovers_decisions_docs_and_episodes(
full.extend(population)
return population[:3], pending
- monkeypatch.setattr(why_mod, "_semantic_lanes", sealed_semantic)
- monkeypatch.setattr(why_mod, "episode_evidence", sealed_episodes)
+ monkeypatch.setattr(why_search, "_semantic_lanes", sealed_semantic)
+ monkeypatch.setattr(why_search, "episode_evidence", sealed_episodes)
result = await tool_middleware(get_why)(
"why use sealed response contract",
@@ -811,7 +811,8 @@ async def test_why_fallback_archaeology_and_rationale_wire_recover_annotated_tai
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- import repowise.server.mcp_server.tool_why as why_mod
+ import repowise.server.mcp_server.tool_why.archaeology as why_archaeology
+ import repowise.server.mcp_server.tool_why.path_mode as why_path_mode
_configure_omissions(tmp_path)
commits = [
@@ -874,9 +875,9 @@ async def test_why_fallback_archaeology_and_rationale_wire_recover_annotated_tai
for index in range(23)
]
- monkeypatch.setattr(why_mod, "_run_git_log", sealed_git_log)
+ monkeypatch.setattr(why_archaeology, "_run_git_log", sealed_git_log)
monkeypatch.setattr(
- why_mod,
+ why_path_mode,
"_mine_rationale",
lambda *_args, **_kwargs: [
{
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index beeff0979..69bfa2a64 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -539,7 +539,8 @@ async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, mo
a path that also does everything else. The record ranked first is the one
a reader acts on; the rest keep the stored proportion, which cost nothing.
"""
- from repowise.server.mcp_server import get_why, tool_why
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server.tool_why import path_mode
calls: list[tuple] = []
@@ -547,7 +548,7 @@ async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, mo
calls.append((root, tuple(nodes)))
return "nothing in the 1 file it governs has changed since 2026-01-01"
- monkeypatch.setattr(tool_why, "describe_decision_currency", _fake)
+ monkeypatch.setattr(path_mode, "describe_decision_currency", _fake)
await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)
result = await get_why("src/auth/service.py")
@@ -559,10 +560,11 @@ async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, mo
@pytest.mark.asyncio
async def test_get_why_stays_silent_when_git_cannot_decide(session, setup_mcp, monkeypatch):
- from repowise.server.mcp_server import get_why, tool_why
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server.tool_why import path_mode
monkeypatch.setattr(
- tool_why, "describe_decision_currency", lambda root, **kw: None
+ path_mode, "describe_decision_currency", lambda root, **kw: None
)
result = await get_why("src/auth/service.py")