Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(cli): warn at edit time when a file has a run of recent bug fixes (#947)
Raghav Chamadiyae107bdf7f1b7
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.pyindex e66307bf5..8346c2ca4 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py@@ -10,7 +10,11 @@ from __future__ import annotationsfrom pathlib import Pathfrom ._shared import _find_repo_root-from .decision_inject import _edit_decision_notice, _session_decision_block+from .decision_inject import (+ _edit_decision_notice,+ _edit_fix_history_notice,+ _session_decision_block,+)from .read_state import _load_session_state, _save_session_state_MCP_CONTEXT = (@@ -22,9 +26,7 @@ _MCP_CONTEXT = ()-def _handle_codex_context_event(- event: str, cwd: str, session_id: str = ""-) -> str | None:+def _handle_codex_context_event(event: str, cwd: str, session_id: str = "") -> str | None:"""Return Codex developer context + standing decisions on SessionStart."""if event not in ("SessionStart", "UserPromptSubmit"):return None@@ -67,8 +69,9 @@ def _handle_post_edit_use("risk checks, or dead-code results.")- # Governing-decision notice — same builder Claude Code's edit-time path uses.- notice: str | None = None+ # Governing-decision and bug-history notices, from the same builders Claude+ # Code's edit-time path uses, under the same per-session caps.+ notices: list[str] = []if tool_input is not None and session_id:file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else Noneif isinstance(file_path, str) and file_path.strip():@@ -77,10 +80,16 @@ def _handle_post_edit_use(rel = _relativize(file_path, repo_path)if rel is not None:state = _load_session_state(repo_path, session_id)- try:- notice = _edit_decision_notice(repo_path, rel, session_id, state)- except Exception:- notice = None+ for emit in (+ lambda: _edit_decision_notice(repo_path, rel, session_id, state),+ lambda: _edit_fix_history_notice(repo_path, rel, session_id),+ ):+ try:+ line = emit()+ except Exception:+ line = None+ if line:+ notices.append(line)_save_session_state(repo_path, state)- return "\n".join(filter(None, (staleness, notice))) if notice else staleness+ return "\n".join([staleness, *notices]) if notices else stalenessdiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex 0eacc6995..74e5962ce 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -538,6 +538,137 @@ def _edit_decision_notice(repo_path: Path, rel: str, session_id: str, state: dicreturn line + "."+# ---------------------------------------------------------------------------+# Edit-time bug-history notice+# ---------------------------------------------------------------------------++#: Silence past this age, no matter how large the historical count. A file fixed+#: four times two years ago is history; the notice exists to interrupt an edit,+#: and only a recent run of fixes earns that. Mirrors the ``prior_defect``+#: window the count itself is drawn from.+_FIX_NOTICE_MAX_AGE_DAYS = 180+#: Below this many counted fixes the notice is not worth an agent's attention.+_FIX_NOTICE_MIN_COUNT = 3+++def _humanize_age(days: int) -> str:+ """Render an age as "2 weeks ago" / "3 months ago", never as a bare count."""+ if days <= 1:+ return "today" if days <= 0 else "yesterday"+ if days < 14:+ return f"{days} days ago"+ if days < 60:+ weeks = round(days / 7)+ return f"{weeks} week{'' if weeks == 1 else 's'} ago"+ months = round(days / 30)+ return f"{months} month{'' if months == 1 else 's'} ago"+++def _edit_fix_history_notice(repo_path: Path, rel: str, session_id: str) -> str | None:+ """One-line bug-history heads-up for an edited file, or ``None`` for silence.++ Fires on files with a real recent run of fixes and nothing else. Three gates,+ all of which have to hold: at least :data:`_FIX_NOTICE_MIN_COUNT` counted+ fixes, a last fix inside :data:`_FIX_NOTICE_MAX_AGE_DAYS`, and one claim per+ file per session (the same atomic ``INSERT OR IGNORE`` ledger the decision+ notice uses, so two racing hook processes cannot double-fire).++ The age is mandatory in the copy. A two-week-old fix and a two-year-old fix+ must never read the same, which is also why the age gate exists rather than+ a count gate alone.+ """+ conn = _open_wiki_ro(repo_path)+ if conn is None:+ return None+ try:+ row = conn.execute(+ "SELECT prior_defect_count, bug_magnet, last_fix_at, fix_symbol_counts_json "+ "FROM git_metadata WHERE file_path = ? LIMIT 1",+ (rel,),+ ).fetchone()+ except sqlite3.Error:+ # A pre-fix-events index has no such columns: silence, not an error.+ return None+ finally:+ conn.close()+ if row is None:+ return None++ count = row[0] or 0+ if count < _FIX_NOTICE_MIN_COUNT:+ return None+ days = _days_since(row[2])+ if days is None or days > _FIX_NOTICE_MAX_AGE_DAYS:+ return None++ line = (+ f"[repowise] {rel} has been bug-fixed {count}x in the last 6 months, "+ f"last {_humanize_age(days)}"+ )+ if row[1]:+ line += " (bug magnet)"+ symbol = _top_fix_symbol(row[3])+ if symbol:+ # Hedged on purpose: symbol spans are current-tree and the fix ranges+ # are from each fix's own parent, so this is "mostly", not "exactly".+ line += f"; mostly in {symbol}"+ line += "."++ if session_id:+ claimed, shown = _claim_ledger(+ repo_path,+ session_id,+ f"fix_history:{rel}",+ node_id=rel,+ surface="fix_history",+ category="edit_notice",+ chars=len(line),+ )+ if not claimed or shown > _MAX_EDIT_NOTICES:+ return None+ return line+++def _days_since(raw: object) -> int | None:+ """Whole days between a stored ``last_fix_at`` and now, or ``None``.++ The column round-trips through sqlite as a naive-UTC string (the ORM writes+ naive UTC), so it is read here without a timezone and compared to a naive+ UTC now. Anything unparseable is no signal.+ """+ from datetime import UTC, datetime++ if isinstance(raw, str):+ try:+ moment = datetime.fromisoformat(raw)+ except ValueError:+ return None+ elif isinstance(raw, datetime):+ moment = raw+ else:+ return None+ if moment.tzinfo is not None:+ moment = moment.astimezone(UTC).replace(tzinfo=None)+ return max(0, (datetime.now(UTC).replace(tzinfo=None) - moment).days)+++def _top_fix_symbol(raw: object) -> str | None:+ """The most-fixed symbol's bare name, or ``None``.++ The stored map is already in descending-count order, so the first key wins.+ Keys are ``path/to/file.py::Name`` and the line already names the path.+ """+ if not isinstance(raw, str) or not raw:+ return None+ try:+ counts = json.loads(raw)+ except (TypeError, ValueError):+ return None+ if not isinstance(counts, dict) or not counts:+ return None+ return str(next(iter(counts))).rsplit("::", 1)[-1] or None++# ---------------------------------------------------------------------------# Injection recording (usage feedback v1)# ---------------------------------------------------------------------------diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.pyindex e6d842178..2e2ba4359 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py@@ -89,12 +89,14 @@ def _handle_edit_post(*,with_decisions: bool = True,) -> str | None:- """Record an Edit/Write; surface the file's governing decision, if any.-- The decision notice fires once per session per decision under a strict- per-session cap (see :func:`decision_inject._edit_decision_notice`) so a- governed file gets one heads-up, not a drumbeat. Codex lifecycle hooks- call this with ``with_decisions=False``: they get their own edit banner.+ """Record an Edit/Write; surface the file's governing decision and bug history.++ Both notices fire once per session per file under their own strict+ per-session caps (see :func:`decision_inject._edit_decision_notice` and+ :func:`decision_inject._edit_fix_history_notice`) so a governed or+ much-fixed file gets a heads-up, not a drumbeat. A file that is both emits+ two lines and never more. Codex lifecycle hooks call this with+ ``with_decisions=False``: they get their own edit banner."""file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else Noneif not isinstance(file_path, str) or not file_path.strip():@@ -109,17 +111,23 @@ def _handle_edit_post(state["seq"] += 1state["edits"][rel] = state["seq"]- notice: str | None = None+ notices: list[str] = []if with_decisions:- from .decision_inject import _edit_decision_notice-- try:- notice = _edit_decision_notice(repo_path, rel, session_id, state)- except Exception:- notice = None+ from .decision_inject import _edit_decision_notice, _edit_fix_history_notice++ for emit in (+ lambda: _edit_decision_notice(repo_path, rel, session_id, state),+ lambda: _edit_fix_history_notice(repo_path, rel, session_id),+ ):+ try:+ line = emit()+ except Exception:+ line = None+ if line:+ notices.append(line)_save_session_state(repo_path, state)- return notice+ return "\n".join(notices) or Nonedef _handle_read_post(diff --git a/tests/unit/cli/test_augment_fix_history.py b/tests/unit/cli/test_augment_fix_history.pynew file mode 100644index 000000000..4725ffc0a--- /dev/null+++ b/tests/unit/cli/test_augment_fix_history.py@@ -0,0 +1,153 @@+"""Edit-time bug-history notice: fires on a real recent run of fixes, else silent.++The contract is the same "relevance or silence" one the decision notice follows,+with recency added: the copy always carries the last-fix age, and a file whose+fixes have aged past the window goes quiet no matter how many it accumulated.+The wiki.db is built through the real ORM schema so the hook's raw SQL runs+against the true column names.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta+from pathlib import Path++from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.cli.commands.augment_cmd import decision_inject+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import GitMetadata, Repository++_REPO_ID = "repo1"+_PATH = "src/core/pipeline.py"+++async def _build_wiki_db(repo_root: Path, **columns) -> None:+ """Create .repowise/wiki.db with one git_metadata row for :data:`_PATH`."""+ db_path = repo_root / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(repo_root)))+ session.add(+ GitMetadata(+ id="gm1",+ repository_id=_REPO_ID,+ file_path=_PATH,+ **columns,+ )+ )+ await session.commit()+ await engine.dispose()+++def _days_ago(days: int) -> datetime:+ # Stored naive-UTC, the way the rollup writes it.+ return datetime.now(UTC).replace(tzinfo=None) - timedelta(days=days)+++async def test_recent_run_of_fixes_fires_with_age_and_magnet(tmp_path):+ await _build_wiki_db(+ tmp_path,+ prior_defect_count=5,+ bug_magnet=True,+ last_fix_at=_days_ago(14),+ fix_symbol_counts_json=json.dumps({f"{_PATH}::run_pipeline": 4, f"{_PATH}::load": 1}),+ )++ notice = decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1")++ assert notice is not None+ assert "bug-fixed 5x in the last 6 months" in notice+ # Recency is mandatory in the copy, not an optional flourish.+ assert "2 weeks ago" in notice+ assert "(bug magnet)" in notice+ # The most-fixed symbol, named without repeating the path.+ assert "mostly in run_pipeline" in notice+ assert f"{_PATH}::" not in notice+++async def test_stale_history_is_silent_however_large(tmp_path):+ """A file fixed a lot two years ago is history, not a warning."""+ await _build_wiki_db(+ tmp_path,+ prior_defect_count=12,+ bug_magnet=True,+ last_fix_at=_days_ago(700),+ )+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is None+++async def test_too_few_fixes_is_silent(tmp_path):+ await _build_wiki_db(tmp_path, prior_defect_count=2, last_fix_at=_days_ago(3))+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is None+++async def test_no_fix_data_is_silent(tmp_path):+ """A file with git history but no counted fixes adds nothing."""+ await _build_wiki_db(tmp_path, prior_defect_count=0)+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is None+++async def test_untracked_file_is_silent(tmp_path):+ await _build_wiki_db(tmp_path, prior_defect_count=5, last_fix_at=_days_ago(3))+ assert decision_inject._edit_fix_history_notice(tmp_path, "other/file.py", "s") is None+++async def test_no_index_is_silent(tmp_path):+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is None+++async def test_fires_once_per_session_per_file(tmp_path):+ """The ledger claim is the dedup, so a re-edit in the same session is quiet."""+ await _build_wiki_db(tmp_path, prior_defect_count=4, last_fix_at=_days_ago(5))++ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is not None+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-1") is None+ # A new session starts over.+ assert decision_inject._edit_fix_history_notice(tmp_path, _PATH, "sess-2") is not None+++async def test_session_cap_stops_the_drumbeat(tmp_path):+ """Past the per-session cap the notice goes quiet even on fresh files."""+ db_path = tmp_path / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ paths = [f"src/f{i}.py" for i in range(decision_inject._MAX_EDIT_NOTICES + 2)]+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(tmp_path)))+ for i, path in enumerate(paths):+ session.add(+ GitMetadata(+ id=f"gm{i}",+ repository_id=_REPO_ID,+ file_path=path,+ prior_defect_count=4,+ last_fix_at=_days_ago(5),+ )+ )+ await session.commit()+ await engine.dispose()++ fired = [decision_inject._edit_fix_history_notice(tmp_path, p, "sess-1") for p in paths]+ assert sum(1 for line in fired if line) == decision_inject._MAX_EDIT_NOTICES+++def test_humanize_age_reads_like_a_person_wrote_it():+ assert decision_inject._humanize_age(0) == "today"+ assert decision_inject._humanize_age(1) == "yesterday"+ assert decision_inject._humanize_age(5) == "5 days ago"+ assert decision_inject._humanize_age(14) == "2 weeks ago"+ assert decision_inject._humanize_age(90) == "3 months ago"+++def test_top_fix_symbol_tolerates_junk():+ assert decision_inject._top_fix_symbol(None) is None+ assert decision_inject._top_fix_symbol("not json") is None+ assert decision_inject._top_fix_symbol("{}") is None+ assert decision_inject._top_fix_symbol('{"a.py::save": 3}') == "save"