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): make `decision add` usable without a terminal, and answer `get_why` --target (#1566)
Raghav Chamadiya20b6befce828
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex f169ebbfa..1c7530ca7 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -8,6 +8,7 @@ import clickfrom rich.panel import Panelfrom rich.table import Table+from repowise.cli.commands import _tool_adapters as _tafrom repowise.cli.helpers import (console,ensure_repowise_dir,@@ -81,34 +82,99 @@ async def _resolve_decision_id(session, decision_id: str) -> str | None:@decision_group.command("add")@click.argument("path", required=False, default=None)-def decision_add(path: str | None) -> None:- """Interactively add a new architectural decision."""- repo_path = _resolve_decision_repo(path)[email protected]("--title", default=None, help="Decision title (short).")[email protected]("--context", default=None, help="What forced this decision?")[email protected]("--decision", "decision_text", default=None, help="What was chosen?")[email protected]("--rationale", default=None, help="Why it was chosen.")+ "--alternative", "alternatives", multiple=True, help="A rejected alternative. Repeatable."+)+ "--consequence", "consequences", multiple=True, help="A tradeoff accepted. Repeatable."+)+ "--affects", "affected", multiple=True, help="A file or module this governs. Repeatable."+)[email protected]("--tag", "tags", multiple=True, help="A tag. Repeatable.")+@format_option()+def decision_add(+ path: str | None,+ title: str | None,+ context: str | None,+ decision_text: str | None,+ rationale: str | None,+ alternatives: tuple[str, ...],+ consequences: tuple[str, ...],+ affected: tuple[str, ...],+ tags: tuple[str, ...],+ fmt: str,+) -> None:+ """Add an architectural decision, interactively or from flags.++ With both --title and --decision, records without prompting and prints the+ new id, so a script or an agent can call it. Everything else is optional.++ A flag-driven record lands as `proposed`, where the prompts record `active`.+ A person answering eight questions has reviewed the decision; a caller+ inferring one from a diff has not, and the store should be able to tell+ them apart. Promote with `repowise decision confirm <id>`.+ """+ # Flags and prompts are the two paths, and a half-filled command line is+ # neither: falling through to the prompts would hang a caller that has no+ # stdin, which is the failure this command exists to stop having.+ non_interactive = bool(title and decision_text)+ if not non_interactive:+ flagged = any((title, context, decision_text, rationale)) or any(+ (alternatives, consequences, affected, tags)+ )+ if flagged or fmt == "json":+ _ta.emit_error(+ {+ "error": "--title and --decision are both required to add a "+ "decision without prompting.",+ "guidance": "Run `repowise decision add` with no flags to be "+ "prompted for each field instead.",+ },+ fmt,+ )++ repo_path = _resolve_decision_repo(path, fmt)ensure_repowise_dir(repo_path)- console.print("[bold]Add Architectural Decision[/bold]\n")+ status = "proposed" if non_interactive else "active"+ alternatives_list = list(alternatives)+ consequences_list = list(consequences)+ affected_files = list(affected)+ tags_list = list(tags)- title = click.prompt("Decision title (short)")- context = click.prompt("Context (what forced this decision?)", default="")- decision_text = click.prompt("Decision (what was chosen?)")- rationale = click.prompt("Rationale (why?)", default="")+ if not non_interactive:+ console.print("[bold]Add Architectural Decision[/bold]\n")- alternatives_raw = click.prompt("Rejected alternatives (comma-separated, optional)", default="")- alternatives = [a.strip() for a in alternatives_raw.split(",") if a.strip()]+ title = click.prompt("Decision title (short)")+ context = click.prompt("Context (what forced this decision?)", default="")+ decision_text = click.prompt("Decision (what was chosen?)")+ rationale = click.prompt("Rationale (why?)", default="")- consequences_raw = click.prompt(- "Tradeoffs/consequences (comma-separated, optional)", default=""- )- consequences = [c.strip() for c in consequences_raw.split(",") if c.strip()]+ alternatives_raw = click.prompt(+ "Rejected alternatives (comma-separated, optional)", default=""+ )+ alternatives_list = [a.strip() for a in alternatives_raw.split(",") if a.strip()]- affected_raw = click.prompt("Affected files/modules (comma-separated, optional)", default="")- affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]+ consequences_raw = click.prompt(+ "Tradeoffs/consequences (comma-separated, optional)", default=""+ )+ consequences_list = [c.strip() for c in consequences_raw.split(",") if c.strip()]- tags_raw = click.prompt(- "Tags (comma-separated: auth, database, api, performance, security, infra, testing)",- default="",- )- tags = [t.strip() for t in tags_raw.split(",") if t.strip()]+ affected_raw = click.prompt(+ "Affected files/modules (comma-separated, optional)", default=""+ )+ affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]++ tags_raw = click.prompt(+ "Tags (comma-separated: auth, database, api, performance, security, infra, testing)",+ default="",+ )+ tags_list = [t.strip() for t in tags_raw.split(",") if t.strip()]async def _persist() -> str:from repowise.core.persistence import (@@ -131,15 +197,15 @@ def decision_add(path: str | None) -> None:session,repository_id=repo.id,title=title,- status="active",- context=context,+ status=status,+ context=context or "",decision=decision_text,- rationale=rationale,- alternatives=alternatives,- consequences=consequences,+ rationale=rationale or "",+ alternatives=alternatives_list,+ consequences=consequences_list,affected_files=affected_files,affected_modules=[],- tags=tags,+ tags=tags_list,source="cli",confidence=1.0,)@@ -149,7 +215,21 @@ def decision_add(path: str | None) -> None:return decision_iddecision_id = run_async(_persist())- console.print(f"\n[green]Decision recorded[/green] — ID: [bold]{decision_id[:8]}[/bold]")++ if fmt == "json":+ # The full id, not the table's 8-char prefix — a caller that parses+ # this is about to pass it back to `confirm` or `show`.+ emit_json(+ {+ "repo": str(repo_path),+ "decision": {"id": decision_id, "title": title, "status": status},+ }+ )+ return+ console.print(+ f"\n[green]Decision recorded[/green] [dim]({status})[/dim] — "+ f"ID: [bold]{decision_id[:8]}[/bold]"+ )# ---------------------------------------------------------------------------diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.pyindex 900eff8a9..e0f32a312 100644--- a/packages/cli/src/repowise/cli/commands/why_cmd.py+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py@@ -137,6 +137,10 @@ def project(payload: dict) -> dict:out["query"] = payload["query"]if payload.get("path"):out["path"] = payload["path"]+ # Several --targets and no query: the paths asked about, since there is no+ # single ``path`` naming them and ``target_context`` is keyed by them.+ if payload.get("paths"):+ out["paths"] = payload["paths"]if payload.get("summary"):out["summary"] = payload["summary"]if payload.get("counts"):@@ -235,7 +239,7 @@ def project(payload: dict) -> dict:"--target","targets",multiple=True,- help="File path to anchor the search to. Repeatable.",+ help="File path to anchor the search to, or to ask about when QUERY is omitted. Repeatable.",)@_ta.target_optionsdef why_command(@@ -251,8 +255,8 @@ 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. Falls back to git archaeology when a path has no- decisions, so it is never empty.+ health dashboard — or for the --targets, when any are named. Falls back to+ git archaeology when a path has no decisions, so it is never empty."""fmt = _ta.resolve_format_for(fmt, full)repo_path = _ta.resolve_indexed_repo(diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2index 21895c013..5329755d1 100644--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -7,6 +7,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Reading a file before you edit it is correct and expected.- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>`, the same command with its exit code preserved and errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.+- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.### Toolsdiff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index 8bf5ba450..cdd1a07e3 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -7,6 +7,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected.- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.+- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.### Toolsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 4bb4cd4e4..afecb1da8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -63,7 +63,8 @@ async def get_why(Args:query: question, file/module path, or omit for the dashboard.- targets: optional file paths to anchor the search.+ targets: optional file paths to anchor the search, or to ask about on+ their own when there is no query.repo: usually omitted."""# --- repo="all": search decisions across ALL repos ---@@ -72,8 +73,14 @@ async def get_why(return _unsupported_repo_all("get_why (health dashboard)")return await _why_workspace_search(query)- # --- Mode 1: No query → health dashboard ---+ # --- 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 await _why_targets(list(targets), repo)return await _why_health_dashboard(repo)# --- Mode 2: Path → decisions, origin story, alignment ---@@ -844,8 +851,14 @@ async def _why_no_match(return result-async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:- """Mode 3: natural-language, target-aware decision + documentation search."""+async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:+ """Repo context, the rankable decision corpus, and git metadata for targets.++ 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.+ """from repowise.core.persistence.crud import list_decisions as _list_decisionsctx = await _resolve_repo_context(repo)@@ -854,12 +867,40 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -all_decisions = await _list_decisions(session, repository.id, include_proposed=True, limit=_DECISION_CORPUS_LIMIT)- # Records anchored entirely in excluded paths (vendored venvs mined- # before exclude rules changed) are noise for every mode downstream._spec = _get_exclude_spec(ctx.path)all_decisions = [d for d in all_decisions if not decision_is_excluded(d, _spec)]# 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+++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 = await _load_corpus(repo, targets)+ return {+ "mode": "path",+ "paths": targets,+ "target_context": await _build_target_context(+ ctx, repository, all_decisions, target_git, targets+ ),+ "_meta": _build_meta(repository=repository, targets=targets),+ }+++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 = await _load_corpus(repo, targets)target_set = set(targets) if targets else set()# Rank wide, collapse restatements, then cap — so the cap spends its slots ondiff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.pyindex 880490ee6..57d0558fe 100644--- a/tests/unit/cli/test_decision_cmd.py+++ b/tests/unit/cli/test_decision_cmd.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import jsonfrom pathlib import Pathimport pytest@@ -65,6 +66,119 @@ def test_decision_help_lists_subcommands() -> None:assert name in result.output+def test_decision_add_records_without_prompting(indexed_repo: Path) -> None:+ """With --title and --decision, nothing is asked and the id comes back.++ ``add`` was eight blocking prompts and no flags, so with no stdin it died+ on the first one — the whole command was unreachable to anything scripted.+ """+ result = CliRunner().invoke(+ cli,+ [+ "decision", "add",+ "--title", "Escape LIKE patterns",+ "--decision", "Escape % and _ before interpolating",+ "--rationale", "an unescaped pattern scans the table",+ "--alternative", "match in Python",+ "--consequence", "one more helper on the query path",+ "--affects", "src/db/models.py",+ "--tag", "database",+ "--format", "json",+ str(indexed_repo),+ ],+ input="",+ )++ assert result.exit_code == 0, result.output+ payload = json.loads(result.output)+ assert payload["decision"]["title"] == "Escape LIKE patterns"+ assert len(payload["decision"]["id"]) > 8, "the full id, not the table's prefix"++ shown = CliRunner().invoke(+ cli, ["decision", "show", payload["decision"]["id"], str(indexed_repo), "--format", "json"]+ )+ assert shown.exit_code == 0, shown.output+ record = json.loads(shown.output)["decision"]+ assert record["rationale"] == "an unescaped pattern scans the table"+ assert record["alternatives"] == ["match in Python"]+ assert record["consequences"] == ["one more helper on the query path"]+ assert record["affected_files"] == ["src/db/models.py"]+ assert record["tags"] == ["database"]+++def test_a_flag_driven_decision_lands_proposed(indexed_repo: Path) -> None:+ """A caller that inferred a decision has not reviewed it, and the store says so.++ The prompts still record ``active``: a person answering eight questions is+ the reviewed case. Both paths writing one status is what makes the+ difference invisible.+ """+ result = CliRunner().invoke(+ cli,+ [+ "decision", "add",+ "--title", "Prefer ruff check",+ "--decision", "Run ruff check, never ruff format",+ "--format", "json",+ str(indexed_repo),+ ],+ input="",+ )++ assert result.exit_code == 0, result.output+ assert json.loads(result.output)["decision"]["status"] == "proposed"+++def test_decision_add_prompts_record_active(indexed_repo: Path) -> None:+ """The interactive path is unchanged, including the status it writes."""+ answers = "Interactive title\ncontext\nthe decision\nwhy\n\n\n\n\n"+ result = CliRunner().invoke(+ cli, ["decision", "add", str(indexed_repo)], input=answers+ )++ assert result.exit_code == 0, result.output+ listed = CliRunner().invoke(+ cli, ["decision", "list", str(indexed_repo), "--format", "json"]+ )+ records = json.loads(listed.output)["decisions"]+ assert [d["status"] for d in records if d["title"] == "Interactive title"] == ["active"]+++def test_half_a_command_line_is_an_error_not_a_prompt(indexed_repo: Path) -> None:+ """--title alone must not fall through to the prompts.++ A caller with no stdin would hang there, or abort on a message naming+ neither flag. The exit code carries it too: printing the reason and+ returning 0 is what a script reads as success.+ """+ result = CliRunner().invoke(+ cli,+ ["decision", "add", "--title", "Half a decision", str(indexed_repo), "--format", "json"],+ input="",+ )++ assert result.exit_code == 1, result.output+ assert json.loads(result.output)["error"].startswith("--title and --decision")+++def test_decision_add_help_lists_a_flag_per_field() -> None:+ result = CliRunner().invoke(cli, ["decision", "add", "--help"])++ assert result.exit_code == 0, result.output+ for flag in (+ "--title",+ "--context",+ "--decision",+ "--rationale",+ "--alternative",+ "--consequence",+ "--affects",+ "--tag",+ "--format",+ ):+ assert flag in result.output++def test_decision_list_help_lists_filters() -> None:result = CliRunner().invoke(cli, ["decision", "list", "--help"])diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex 526cfba2d..96e35cdb7 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -182,6 +182,51 @@ async def test_get_why_no_args(setup_mcp):assert "ungoverned_hotspots" in result+async def test_one_target_and_no_query_answers_about_that_target(setup_mcp):+ """A named file with nothing asked about it is a question about that file.++ The no-query branch reached the health dashboard before it looked at+ targets, so this returned the same repo-wide summary for every file — an+ answer that never mentioned what was asked about.+ """+ from repowise.server.mcp_server import get_why++ result = await get_why(targets=["src/auth/service.py"])++ assert result["mode"] == "path"+ assert result["path"] == "src/auth/service.py"+ assert result["decisions"]+++async def test_targets_and_no_query_differ_by_target(setup_mcp):+ """Two different files must not produce one answer.++ The dashboard is byte-identical whatever it is asked about, so equality+ here is the whole symptom rather than a proxy for it.+ """+ from repowise.server.mcp_server import get_why++ first = await get_why(targets=["src/auth/service.py"])+ second = await get_why(targets=["src/db/models.py"])++ assert first != second+++async def test_every_target_is_answered_when_several_are_named(setup_mcp):+ """Answering only the first target would be the same silent drop, halved."""+ from repowise.server.mcp_server import get_why++ targets = ["src/auth/service.py", "src/db/models.py"]+ result = await get_why(targets=targets)++ assert result["mode"] == "path"+ assert result["paths"] == targets+ assert sorted(result["target_context"]) == sorted(targets)++@pytest.mark.asyncioasync def test_get_why_module_path(setup_mcp):from repowise.server.mcp_server import get_why