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
fix(cli): print each why history commit once (#3608)
Emre K.ae55586413c3
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.pyindex 10482b013..2ffdf6fc5 100644--- a/packages/cli/src/repowise/cli/commands/why_cmd.py+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py@@ -286,7 +286,7 @@ def why_command(QUERY is a question ("why is auth using JWT?"), a file path (its governingdecisions, origin story and alignment score), or omitted for the decision- health dashboard — or for the --targets, when any are named. Falls back to+ health dashboard — or for repeatable --target paths, when named. Falls back togit archaeology when a path has no decisions, so it is never empty."""fmt = _ta.resolve_format_for(fmt, full)@@ -356,6 +356,7 @@ def _render(projected: dict) -> None:f"pass --full for the rest.[/dim]")+ seen_commits: set[tuple[str, str]] = set()origin = projected.get("origin_story") or {}if origin.get("available"):console.print(@@ -365,6 +366,9 @@ def _render(projected: dict) -> None:f"({_owner_share(origin.get('author_commit_pct'))})")for c in origin.get("key_commits") or []:+ sha = str(c.get("sha", "")).lower()+ if sha:+ seen_commits.add((sha, str(c.get("message", ""))))console.print(f" [dim]{c.get('sha', '')} {str(c.get('date', ''))[:10]}[/dim] "f"{c.get('message', '')}"@@ -372,7 +376,7 @@ def _render(projected: dict) -> None:if projected.get("git_archaeology"):console.print("")- _render_archaeology(console, projected["git_archaeology"], indent="")+ _render_archaeology(console, projected["git_archaeology"], indent="", seen=seen_commits)rationale = projected.get("code_rationale") or []if rationale:@@ -487,8 +491,24 @@ _RENDERABLE_BLOCKS = (_owner_share = _ta.owner_share-def _render_archaeology(console, arch: dict, *, indent: str) -> None:+def _already_rendered(seen: set[tuple[str, str]], sha: str, message: str) -> bool:+ """Match full IDs where available; short indexed IDs need the subject too."""+ return any(+ old == sha+ or (+ old_message == message+ and old != sha+ and (old.startswith(sha) or sha.startswith(old))+ )+ for old, old_message in seen+ )+++def _render_archaeology(+ console, arch: dict, *, indent: str, seen: set[tuple[str, str]] | None = None+) -> None:"""The archaeology block, at the top level or nested under one ``--target``."""+ seen = seen if seen is not None else set()console.print(f"{indent}[bold]Git archaeology[/bold] {arch.get('summary', '')}")for label, key in (("this file", "file_commits"),@@ -497,6 +517,12 @@ def _render_archaeology(console, arch: dict, *, indent: str) -> None:):rows = arch.get(key) or []for c in rows:+ sha = str(c.get("sha", "")).lower()+ message = str(c.get("message", ""))+ if key != "cross_references" and sha and _already_rendered(seen, sha, message):+ continue+ if key != "cross_references" and sha:+ seen.add((sha, message))where = f" [dim]({c['source_file']})[/dim]" if c.get("source_file") else ""console.print(f"{indent} [dim]{label}: {str(c.get('sha', ''))[:8]} "@@ -505,7 +531,7 @@ def _render_archaeology(console, arch: dict, *, indent: str) -> None:total = arch.get(f"{key}_total")if total:console.print(- f"{indent} [dim]{len(rows)} of {total} {label} shown; "+ f"{indent} [dim]{len(rows)} of {total} {label} inspected; "f"pass --full for the rest.[/dim]")diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.pyindex b3297581c..1e49347a7 100644--- a/tests/unit/cli/test_tool_adapter_commands.py+++ b/tests/unit/cli/test_tool_adapter_commands.py@@ -881,6 +881,88 @@ def test_why_renders_the_archaeology_it_falls_back_to(monkeypatch, repo):assert "5 of 7" in result.stdout, "the cap was applied but never disclosed"+def test_why_table_prints_each_commit_once_before_showing_new_git_log_rows(monkeypatch, repo):+ shared = "a123456789abcdef"+ second = "b123456789abcdef"+ new = "c123456789abcdef"+ payload = {+ "mode": "path", "path": "a.py",+ "origin_story": {"available": True, "key_commits": [+ {"sha": shared, "date": "2026-01-01", "message": "origin"},+ ]},+ "git_archaeology": {+ "file_commits": [+ {"sha": shared[:8], "date": "2026-01-02", "message": "origin"},+ {"sha": second, "date": "2026-01-03", "message": "indexed"},+ ],+ "git_log": [+ {"sha": shared[:12], "date": "2026-01-04", "message": "origin"},+ {"sha": second, "date": "2026-01-04", "message": "indexed"},+ {"sha": new, "date": "2026-01-05", "message": "new live"},+ *[+ {"sha": f"{letter}123456789abcdef", "message": "another live"}+ for letter in "defgh"+ ],+ ],+ "cross_references": [{"sha": second, "source_file": "b.py", "message": "other file"}],+ }, "_meta": {},+ }+ result = _invoke(monkeypatch, why_command, ["a.py"], repo, payload)+ assert result.stdout.count(shared[:8]) == 1+ assert result.stdout.count(second[:8]) == 2 # cross-references stay independent+ assert result.stdout.count(new[:8]) == 1+ assert "git log: c1234567" in result.stdout+ assert "5 of 8 git log inspected" in result.stdout # duplicate slots still consume the cap+ assert "2026-01-02" not in result.stdout+ json_result = _invoke(monkeypatch, why_command, ["a.py", "--format", "json"], repo, payload)+ assert json.loads(json_result.stdout)["git_archaeology"]["git_log"][0]["sha"] == shared[:12]+++def test_why_nested_target_deduplicates_its_own_history(monkeypatch, repo):+ payload = {+ "mode": "search", "target_context": {+ "b.py": {"git_archaeology": {+ "file_commits": [{"sha": "a123456789", "message": "first"}],+ "git_log": [{"sha": "a123456789", "message": "repeat"},+ {"sha": "b123456789", "message": "fresh"}],+ }},+ "c.py": {"git_archaeology": {+ "git_log": [{"sha": "a123456789", "message": "other target"}],+ }},+ }, "_meta": {},+ }+ result = _invoke(+ monkeypatch, why_command, ["q", "--target", "b.py", "--target", "c.py"], repo, payload+ )+ assert result.stdout.count("a1234567") == 2+ assert result.stdout.count("b1234567") == 1+ assert "git log: a1234567" in result.stdout # independent target+++def test_why_help_names_the_actual_repeatable_target_option():+ result = CliRunner().invoke(why_command, ["--help"])+ assert result.exit_code == 0+ assert "--target TEXT" in result.stdout+ assert "--targets" not in result.stdout+++def test_why_table_keeps_distinct_commits_with_the_same_display_prefix(monkeypatch, repo):+ payload = {+ "mode": "path", "path": "a.py",+ "origin_story": {"available": True, "key_commits": [+ {"sha": "abcdef0011111111", "message": "first commit"},+ ]},+ "git_archaeology": {"git_log": [+ {"sha": "abcdef0022222222", "message": "distinct commit"},+ ]},+ "_meta": {},+ }+ result = _invoke(monkeypatch, why_command, ["a.py"], repo, payload)+ assert "first commit" in result.stdout+ assert "git log: abcdef00" in result.stdout+ assert "distinct commit" in result.stdout++def test_why_renders_a_targets_own_history(monkeypatch, repo):"""``origin.summary`` exists only when there is *no* history.