Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix: unwedge get_why, and four defects found smoke-testing the release (#1395)

Raghav Chamadiyae0a7e29a68db
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index dc9e7154a..496220471 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -276,7 +276,15 @@ def dead_code_command(
)
console.print(table)
+ # confidence_summary is a {"high": N, ...} dict; interpolating it printed a
+ # raw Python repr, braces and quotes included, at the end of an otherwise
+ # formatted report.
+ tiers = ", ".join(
+ f"{tier} {count}"
+ for tier in ("high", "medium", "low")
+ if (count := report.confidence_summary.get(tier, 0))
+ )
console.print(
- f"\nCleanup-candidate lines: [bold]{report.deletable_lines:,}[/bold] "
- f"(confidence: {report.confidence_summary})"
+ f"\nCleanup-candidate lines: [bold]{report.deletable_lines:,}[/bold]"
+ + (f" ({tiers} confidence)" if tiers else "")
)
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 066df8e04..6c721bd34 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -40,6 +40,24 @@ async def _decision_vector_ids(session, repository_id: str) -> set[str]:
return {f"{DECISION_VECTOR_PREFIX}{r[0]}" for r in rows}
+def _is_stub_fallback_row(page) -> bool:
+ """True when a ``Page`` row is a stub standing in for a failed model page.
+
+ The generation-side predicate reads ``page.metadata``; the ORM row carries
+ the same dict as the ``metadata_json`` text column, so the marker key is
+ shared but the accessor is not.
+ """
+ import json
+
+ from repowise.core.generation.models import STUB_FALLBACK_ERROR
+
+ try:
+ meta = json.loads(page.metadata_json or "{}")
+ except (TypeError, ValueError):
+ return False
+ return isinstance(meta, dict) and STUB_FALLBACK_ERROR in meta
+
+
def _run_repo_checks(
repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"
) -> tuple[bool, list[DoctorCheck]]:
@@ -277,6 +295,19 @@ def _run_repo_checks(
indexable_ids = {
p.id for p in pages if meets_information_floor(p.content or "")
}
+ # A stub standing in for a failed model page is held out of
+ # the vector store on purpose: ``_seed_resume`` reads the
+ # store back as the ledger of pages already written, so a
+ # vector here is what would tell the next ``init --resume``
+ # there is nothing left to write. Reporting it as drift sent
+ # people to ``--repair``, which embedded the stub and quietly
+ # burned the retry. Same permanent-noise argument as the two
+ # exclusions above, plus a real cost to "fixing" it. FTS
+ # still indexes the stub, so this applies to the vector side
+ # only, and only to MISSING — a leftover vector for a page
+ # that has since become a stub is real drift worth deleting.
+ stub_ids = {p.id for p in pages if _is_stub_fallback_row(p)}
+ vector_indexable_ids = indexable_ids - stub_ids
# Check vector store
vs_ids: set[str] = set()
@@ -290,7 +321,7 @@ def _run_repo_checks(
except Exception:
pass # LanceDB not available
- m_vec = indexable_ids - vs_ids if vs_ids else set()
+ m_vec = vector_indexable_ids - vs_ids if vs_ids else set()
o_vec = vs_ids - vector_sql_ids if vs_ids else set()
# Check FTS
@@ -303,11 +334,15 @@ def _run_repo_checks(
o_fts = fts_ids - sql_ids if fts_ids else set()
await engine.dispose()
- return m_vec, o_vec, m_fts, o_fts
+ return m_vec, o_vec, m_fts, o_fts, len(stub_ids)
- missing_from_vector, orphaned_vector, missing_from_fts, orphaned_fts = run_async(
- _check_stores()
- )
+ (
+ missing_from_vector,
+ orphaned_vector,
+ missing_from_fts,
+ orphaned_fts,
+ stub_count,
+ ) = run_async(_check_stores())
vec_ok = not missing_from_vector and not orphaned_vector
vec_detail = (
@@ -315,6 +350,11 @@ def _run_repo_checks(
if vec_ok
else (f"{len(missing_from_vector)} missing, {len(orphaned_vector)} orphaned")
)
+ # Held-back stubs are not drift, but they are also not nothing: the
+ # wiki has a page there that no model wrote. Say so on the same row
+ # rather than letting "in sync" imply the wiki is complete.
+ if stub_count:
+ vec_detail += f" · {stub_count} stub(s) awaiting --resume"
checks.append(_check("SQL ↔ Vector Store", vec_ok, vec_detail))
fts_ok = not missing_from_fts and not orphaned_fts
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
index 0dbcc6e37..9309d7772 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
@@ -38,7 +38,11 @@ from repowise.cli.providers import (
flush_cost_tracker,
)
from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER, MaybeCountColumn, RichProgressCallback
-from repowise.core.generation.models import count_stub_fallbacks
+from repowise.core.generation.models import (
+ STUB_FALLBACK_ERROR,
+ count_stub_fallbacks,
+ is_stub_fallback,
+)
__all__ = [
"COST_GATE_USD",
@@ -396,9 +400,24 @@ def run_repo_generation(
if stub_count
else ""
)
+ # Not necessarily the provider's fault: the commonest cause is this
+ # run's own artifact check rejecting the text the model returned. The
+ # old wording named the provider unconditionally, which sent people to
+ # check their key and their status page over a quality gate firing.
+ # The per-page reason is on the stub, so quote it instead of guessing.
+ reasons = sorted(
+ {
+ str(p.metadata.get(STUB_FALLBACK_ERROR, "")).strip()
+ for p in generated_pages
+ if is_stub_fallback(p)
+ }
+ - {""}
+ )
+ reason_note = "".join(f" [dim]· {r[:160]}[/dim]\n" for r in reasons[:3])
console.print(
- "\n [yellow]The wiki is incomplete due to provider failures.[/yellow]\n"
+ "\n [yellow]The wiki is incomplete: some pages were not written.[/yellow]\n"
f"{placeholder_note}"
+ f"{reason_note}"
" [dim]Run [bold]repowise init --resume[/bold] to generate the pages that "
"failed, without re-spending on the ones that succeeded.[/dim]\n"
)
diff --git a/packages/cli/src/repowise/cli/commands/reindex_cmd.py b/packages/cli/src/repowise/cli/commands/reindex_cmd.py
index 70848452e..2b6cb23b0 100644
--- a/packages/cli/src/repowise/cli/commands/reindex_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/reindex_cmd.py
@@ -201,7 +201,12 @@ async def _reindex(repo_path, embedder_name: str, batch_size: int) -> None:
# decision: namespace, batched like the pages. Uses embed_batch
# directly (which raises on failure) rather than the ingest-side
# best-effort wrapper, so the indexed/failed counters stay honest.
- progress.update(task, description="Indexing decisions...")
+ # Only when there are any. Set unconditionally, this relabelled a bar
+ # that had just finished the pages, so a repo with no decisions ended
+ # its reindex reading "Indexing decisions... 186/186" — 186 pages
+ # reported as decisions that were never indexed.
+ if decisions:
+ progress.update(task, description="Indexing decisions...")
for i in range(0, len(decisions), batch_size):
batch = decisions[i : i + batch_size]
items = [
diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.py
index 6be70439e..dcf179734 100644
--- a/packages/cli/src/repowise/cli/ui/result_panels.py
+++ b/packages/cli/src/repowise/cli/ui/result_panels.py
@@ -202,7 +202,7 @@ def build_contextual_next_steps(
steps.append((f"repowise risk {top_hotspot}", "assess risk for top hotspot"))
if decision_count > 0:
- steps.append(("repowise decisions", f"browse {decision_count} architectural decisions"))
+ steps.append(("repowise decision list", f"browse {decision_count} architectural decisions"))
return steps
diff --git a/packages/core/src/repowise/core/precedent/currency.py b/packages/core/src/repowise/core/precedent/currency.py
index c66e8208d..0f5463b76 100644
--- a/packages/core/src/repowise/core/precedent/currency.py
+++ b/packages/core/src/repowise/core/precedent/currency.py
@@ -107,6 +107,17 @@ def commits_since(
capture_output=True,
text=True,
timeout=timeout,
+ # stdin=DEVNULL is load-bearing, not tidiness. Under the stdio MCP
+ # transport a child that inherits the JSON-RPC stdin pipe can hold
+ # it open forever, and the timeout above does not save us: on
+ # Windows subprocess.run kills the child on TimeoutExpired and then
+ # re-enters communicate() with no timeout, which blocks on reader
+ # threads the dead-but-unreaped child still holds. The call is
+ # reached from get_why on every request that resolves an episode,
+ # so without this the tool never returns and the agent's session
+ # wedges. Same failure mode already guarded at _meta.py and
+ # _code_rationale.py.
+ stdin=subprocess.DEVNULL,
)
except (subprocess.TimeoutExpired, OSError):
return None
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index 4e5235cb4..76adf400c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -887,6 +887,10 @@ async def _run_git_log(
capture_output=True,
text=True,
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():
@@ -918,6 +922,7 @@ async def _run_git_log(
capture_output=True,
text=True,
timeout=10,
+ stdin=subprocess.DEVNULL, # see above
)
if proc2.returncode == 0:
seen = {r["sha"] for r in results}
diff --git a/tests/unit/cli/test_doctor_resume_stub.py b/tests/unit/cli/test_doctor_resume_stub.py
new file mode 100644
index 000000000..3d8e15934
--- /dev/null
+++ b/tests/unit/cli/test_doctor_resume_stub.py
@@ -0,0 +1,131 @@
+"""``doctor`` does not report a stub awaiting ``--resume`` as vector drift.
+
+A stub standing in for a failed model page is held out of the vector store on
+purpose: the resume seed reads the store back as the ledger of pages already
+written, so a vector here is what would tell the next ``init --resume`` there
+is nothing left to write. Reporting it as missing sent people to ``--repair``,
+which embedded the stub and silently burned the retry.
+
+FTS still indexes the stub, so the exclusion is vector-side only, and MISSING
+only — a leftover vector for a page that has since become a stub is real drift.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+from repowise.cli.commands.doctor_cmd import repo_checks
+from repowise.core.generation.models import STUB_FALLBACK_ERROR
+
+WRITTEN = "module_page:src/written"
+STUB = "module_page:src/stub"
+
+BODY = (
+ "## Overview\n\n"
+ "Resolves each import against the package manifest before descending, so "
+ "a symlinked workspace member is visited once rather than once per alias "
+ "that reaches it. Cycles break on the real path, never the alias, which "
+ "is why two aliases of one directory cannot both claim to own a module. "
+ "The manifest is read once per package and cached for the walk.\n"
+)
+
+
+async def _build_repo(tmp_path: Path, *, embed_stub: bool) -> Path:
+ """Both pages in SQL and FTS; the stub's vector is present only on request."""
+ import git as gitpython
+
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import upsert_page, upsert_repository
+ from repowise.core.persistence.database import init_db
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ repo_path = (tmp_path / "repo").resolve()
+ repo_path.mkdir()
+ gitpython.Repo.init(repo_path)
+ repowise_dir = repo_path / ".repowise"
+ repowise_dir.mkdir()
+
+ engine = create_engine(f"sqlite+aiosqlite:///{repowise_dir / 'wiki.db'}")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name="repo", local_path=str(repo_path), url="https://example.test/repo"
+ )
+ for page_id, path, meta in (
+ (WRITTEN, "src/written", {}),
+ (STUB, "src/stub", {STUB_FALLBACK_ERROR: "artifact check rejected the response"}),
+ ):
+ await upsert_page(
+ session,
+ page_id=page_id,
+ repository_id=repo.id,
+ page_type="module_page",
+ title=f"Module: {path}",
+ content=BODY,
+ summary="",
+ target_path=path,
+ source_hash="",
+ model_name="mock",
+ provider_name="mock",
+ metadata=meta,
+ )
+ await session.commit()
+
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ for page_id, path in ((WRITTEN, "src/written"), (STUB, "src/stub")):
+ await fts.index(page_id, f"Module: {path}", BODY, summary="", target_path=path)
+ await engine.dispose()
+
+ store = LanceDBVectorStore(str(repowise_dir / "lancedb"), embedder=MockEmbedder())
+ await store.embed_and_upsert(WRITTEN, BODY, {"title": "Module: src/written"})
+ if embed_stub:
+ await store.embed_and_upsert(STUB, BODY, {"title": "Module: src/stub"})
+ await store.close()
+
+ return repo_path
+
+
+def _rows(repo_path: Path) -> dict[str, tuple[bool, str]]:
+ _all_ok, checks = repo_checks._run_repo_checks(repo_path, repair=False)
+ return {c.name: (c.ok, c.detail) for c in checks}
+
+
+def test_an_unembedded_stub_is_not_vector_drift(tmp_path: Path) -> None:
+ rows = _rows(asyncio.run(_build_repo(tmp_path, embed_stub=False)))
+
+ ok, detail = rows["SQL ↔ Vector Store"]
+ assert ok, detail
+ assert "missing" not in detail
+ # Not drift, but not nothing either: the wiki has a page there that no
+ # model wrote, and "in sync" alone would imply the wiki is complete.
+ assert "1 stub(s) awaiting --resume" in detail
+
+
+def test_the_stub_is_still_indexed_for_full_text(tmp_path: Path) -> None:
+ """The exclusion is vector-side only — FTS carries the stub like any page."""
+ rows = _rows(asyncio.run(_build_repo(tmp_path, embed_stub=False)))
+
+ assert rows["SQL ↔ FTS Index"] == (True, "in sync")
+
+
+def test_an_embedded_stub_is_not_reported_as_an_orphan(tmp_path: Path) -> None:
+ """A stub that does have a vector is a legitimate SQL row, not an orphan.
+
+ ``--repair`` may already have embedded one before this exclusion existed,
+ and that store should read as consistent rather than flipping to the other
+ kind of drift.
+ """
+ rows = _rows(asyncio.run(_build_repo(tmp_path, embed_stub=True)))
+
+ ok, detail = rows["SQL ↔ Vector Store"]
+ assert ok, detail
+ assert "orphaned" not in detail
diff --git a/tests/unit/cli/test_init_failure_reporting.py b/tests/unit/cli/test_init_failure_reporting.py
index af74e9754..82e2fdf22 100644
--- a/tests/unit/cli/test_init_failure_reporting.py
+++ b/tests/unit/cli/test_init_failure_reporting.py
@@ -111,7 +111,11 @@ def test_run_repo_generation_reports_failures(tmp_path, monkeypatch):
assert "module_page: 1" in output
assert "layer_page: 1" in output
assert "onboarding: 1" in output
- assert "The wiki is incomplete due to provider failures." in output
+ # Deliberately not "due to provider failures": the commonest cause is this
+ # run's own artifact check rejecting the model's text, and naming the
+ # provider sent people to check a key that was working.
+ assert "The wiki is incomplete: some pages were not written." in output
+ assert "provider failures" not in output
assert "repowise init --resume" in output
@@ -231,7 +235,7 @@ def test_run_repo_generation_zero_failures(tmp_path, monkeypatch, verbose_flag):
assert len(pages) == 1
output = "\n".join(printed_lines)
assert "failed" not in output
- assert "The wiki is incomplete due to provider failures." not in output
+ assert "The wiki is incomplete" not in output
if verbose_flag:
assert "Generated [bold]1[/bold] pages" in output
else:
diff --git a/tests/unit/precedent/test_currency.py b/tests/unit/precedent/test_currency.py
index ec625a18e..7fdafad93 100644
--- a/tests/unit/precedent/test_currency.py
+++ b/tests/unit/precedent/test_currency.py
@@ -131,3 +131,31 @@ def test_silence_when_git_cannot_decide(tmp_path: Path) -> None:
)
assert sentence is None
+
+
+def test_git_never_inherits_the_callers_stdin(
+ repo: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The one spawn detail that is load-bearing rather than tidiness.
+
+ ``get_why`` reaches this on every request that resolves an episode, and the
+ MCP server it runs inside speaks JSON-RPC over stdio. A git child that
+ inherits that stdin can hold it open indefinitely, and the ``timeout=``
+ here is not a backstop: on Windows ``subprocess.run`` kills the child on
+ ``TimeoutExpired`` and then re-enters ``communicate()`` with no timeout,
+ blocking on reader threads the child still holds. The observed result was
+ ``get_why`` never returning and the agent's session wedging behind it.
+ """
+ import repowise.core.precedent.currency as currency_mod
+
+ seen: dict[str, object] = {}
+ real_run = subprocess.run
+
+ def _spy(cmd, **kwargs):
+ seen.update(kwargs)
+ return real_run(cmd, **kwargs)
+
+ monkeypatch.setattr(currency_mod.subprocess, "run", _spy)
+ commits_since(repo, since_commit="HEAD", nodes=["a.py"])
+
+ assert seen.get("stdin") is subprocess.DEVNULL