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(decisions): require a stated reason before a record can be accepted (#2279)
Raghav Chamadiya05db5128e273
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.pyindex 5c80a0562..873c7f7ec 100644--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py@@ -52,7 +52,7 @@ from repowise.core.analysis.decisions.policy import (DecisionPolicy,resolve_policy,)-from repowise.core.analysis.decisions.scope import resolve_module_nodes+from repowise.core.analysis.decisions.scope import commit_scope_files, resolve_module_nodesfrom repowise.core.fs_walk import PRUNED_DIRS, walk_repofrom repowise.core.ingestion.traverser import load_gitignore_spec@@ -577,7 +577,10 @@ class DecisionExtractor:return ExtractedDecision(title=_truncate_title(marker["text"], 100),decision=marker["text"],- context=f"Found in {file_path}:{marker['line']}",+ # No context. This lane has only the marker's own text, and+ # `evidence_file`/`evidence_line` below already say where it was+ # found, so the location string it used to carry was a restatement+ # that made a record with no stated reason read as having one.source="inline_marker",status="active",confidence=0.7,@@ -719,7 +722,7 @@ class DecisionExtractor:breakif sha:d.evidence_commits = [sha]- d.affected_files = commit_files.get(sha, [])+ d.affected_files = commit_scope_files(commit_files.get(sha))d.source_text = source_by_sha.get(sha, "")d.source = "git_archaeology"d.status = "proposed"@@ -981,7 +984,7 @@ class DecisionExtractor:breakif sha:d.evidence_commits = [sha]- d.affected_files = files_by_sha.get(sha, [])+ d.affected_files = commit_scope_files(files_by_sha.get(sha))d.source_text = source_by_sha.get(sha, "")d.source = "pr"d.status = "proposed"diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.pyindex f0560a967..14a6164ca 100644--- a/packages/core/src/repowise/core/analysis/decisions/scope.py+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom collections.abc import Sequence-__all__ = ["derive_decision_scope", "resolve_module_nodes"]+__all__ = ["commit_scope_files", "derive_decision_scope", "resolve_module_nodes"]#: Upper bound on the directories one record may claim. A record naming files#: across more directories than this is not scoped by its module list anyway —@@ -19,6 +19,27 @@ __all__ = ["derive_decision_scope", "resolve_module_nodes"]#: column into a second copy of the tree._MAX_MODULES = 12+#: Upper bound on the files a commit-derived record may claim. ``git_archaeology``+#: and ``pr`` read one decision out of one commit and then took that commit's+#: whole file list, so a decision mined from a large refactor claimed every file+#: the refactor touched. Measured over the 625-record dev store: scope runs+#: median 5, p75 16, p90 30, max 59, and the 103 records claiming more than 20+#: files (17 ``git_archaeology``, 86 ``pr``) carry 1,468 scope entries beyond+#: it. 20 keeps the p75 record whole and matches the number ``inline_marker``+#: already caps its graph neighbours at — a different quantity, but reusing the+#: value avoids a third cap to reason about.+_MAX_FILES = 20+++def commit_scope_files(files: Sequence[str] | None) -> list[str]:+ """The files a decision mined from one commit may claim to govern.++ Sorted before truncating so which files survive the cap is reproducible,+ rather than depending on the order git happened to list them in.+ """+ seen = {f.replace("\\", "/").strip() for f in files or [] if f and f.strip()}+ return sorted(seen)[:_MAX_FILES]+def resolve_module_nodes(files: Sequence[str] | None) -> list[str]:"""Return the directories that *files* live in, deduped and sorted.diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex a35f702ed..68c99af1d 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -401,8 +401,14 @@ def _requirement(resolved_evidence = evidence if evidence is not None else _record_evidence(record)if not resolved_evidence and self_authored:resolved_evidence = [f"accepted by {accepter}"]+ # The why may come from `rationale` or from `context` ("what forced this+ # decision?"), never from `decision`, which is the what. Measured over the+ # dev store's 513 acceptable records: 199 have a blank rationale, but 145+ # of those give their reason in `context`, so stopping at `rationale` would+ # block 145 records a hand-read sample of 20 judged worth keeping. Stopping+ # at `context` blocks the other 54, each blank in both fields.return AcceptanceRequirement(- reason=_first_non_blank(reason, record.rationale, record.decision),+ reason=_first_non_blank(reason, record.rationale, record.context),scope=scope if scope is not None else _record_scope(record),evidence=resolved_evidence,accepter=accepter,diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.pyindex 0d807070e..c943fc346 100644--- a/packages/core/src/repowise/core/providers/llm/registry.py+++ b/packages/core/src/repowise/core/providers/llm/registry.py@@ -31,6 +31,7 @@ Custom provider registration:from __future__ import annotationsimport importlib+import loggingimport osfrom collections.abc import Callablefrom pathlib import Path@@ -39,6 +40,8 @@ from typing import Anyfrom repowise.core.providers.llm.base import BaseProviderfrom repowise.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter+logger = logging.getLogger(__name__)+# Map of provider name → (module_path, class_name)# Providers are imported lazily to avoid requiring all dependencies at import time.# This means `pip install repowise-core` without anthropic installed still works —@@ -131,6 +134,35 @@ PROVIDER_AUTODETECT_ORDER: tuple[str, ...] = (EnvLookup = Callable[[str], "str | None"]+def repo_env_lookup(repo_path: Any = None) -> EnvLookup:+ """An :data:`EnvLookup` that also sees *repo_path*'s ``.repowise/.env``.++ The process environment still wins. Reading the file instead of merging it+ into ``os.environ`` is what keeps one repo's keys out of another's+ resolution in a workspace server, which is why ``load_repo_env`` exists.++ Without this, a reporting caller sees only ``os.environ`` and answers+ "no provider" for a repo whose key ``repowise init`` wrote to+ ``.repowise/.env`` — the file it writes to by default.+ """+ if repo_path is None:+ return os.environ.get+ try:+ from repowise.core.repo_config import RepoConfigError, load_repo_env++ overlay = load_repo_env(repo_path)+ except RepoConfigError:+ # A broken .env must surface rather than read as "no key" (#852), the+ # same way the CLI and server readers report it.+ logger.warning("Repo .env unreadable for %s; using the environment only", repo_path)+ return os.environ.get+ except Exception:+ return os.environ.get+ if not overlay:+ return os.environ.get+ return lambda key: os.environ.get(key) or overlay.get(key) or None++def _clean(value: str | None) -> str | None:return value.strip() if value and value.strip() else None@@ -335,15 +367,24 @@ def provider_available_for_repo(repo_path: Path | str) -> bool:Mirrors the CLI's resolution order: an explicit choice is checked forusability, auto-detection asks only whether credentials name a provider.Reporting-only, so it answers False rather than raising on a broken config.++ Resolution reads the repo's own ``.repowise/.env`` as well as the process+ environment. Asking ``os.environ`` alone made this disagree with the+ pipeline, which gates the capture lanes on a real client: a repo with its+ key in ``.repowise/.env`` was told its ``pr``, ``comment`` and+ ``git_archaeology`` lanes had no provider while those lanes were running."""try:from repowise.core.repo_config import load_repo_config- configured = (os.environ.get("REPOWISE_PROVIDER") or "").strip()+ getenv = repo_env_lookup(repo_path)+ configured = (getenv("REPOWISE_PROVIDER") or "").strip()if not configured:configured = str(load_repo_config(repo_path).get("provider") or "").strip()if configured:- return provider_is_usable(configured)- return any(provider_credentials_present(name) for name in PROVIDER_AUTODETECT_ORDER)+ return provider_is_usable(configured, getenv)+ return any(+ provider_credentials_present(name, getenv) for name in PROVIDER_AUTODETECT_ORDER+ )except Exception:return Falsediff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 737213c88..0584d070a 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -2,6 +2,7 @@from __future__ import annotations+import contextlibfrom dataclasses import replacefrom pathlib import Path@@ -534,12 +535,14 @@ async def create_decision(rather than written straight into the status column, so this surface andthe CLI agree about what made the record govern.- A record naming no file or module is stored as a candidate instead of- being refused, which is what ``repowise decision add`` does with the same- input. It cannot be checked against the code and cannot reach an agent- editing a governed file, so it cannot govern; discarding the fields the- author did fill in would be worse. The response's ``status`` says which of- the two happened, and a form can predict it from the same one field.+ A record the acceptance contract will not take is stored as a candidate+ instead of being refused, which is what ``repowise decision add`` does with+ the same input. That covers a record naming no file or module, which cannot+ be checked against the code or reach an agent editing a governed file, and+ a record stating no reason, which has not said why it binds. Discarding the+ fields the author did fill in would be worse than keeping the entry+ unaccepted. The response's ``status`` says which of the two happened, and a+ form can predict it from the same one field."""# ``upsert_decision`` dedups on the title and overwrites the scope with# whatever the body carries, so a second post of an accepted decision's@@ -581,10 +584,13 @@ async def create_decision(confidence=1.0,)if scoped:- try:+ # Same rule as the scope-less case above: what the contract will not+ # accept is kept as a candidate, not refused. An entry stating no+ # reason reaches here, and discarding everything the author typed over+ # a missing rationale would be the worse answer. The response's+ # ``status`` reports which of the two happened.+ with contextlib.suppress(crud.AcceptanceRefusedError):await crud.accept_decision(session, rec, accepter="web")- except crud.AcceptanceRefusedError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from excreturn DecisionRecordResponse.from_orm(rec)diff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.tsindex 478658b4d..14c9af9ed 100644--- a/packages/types/__tests__/decisions-vocabulary.test.ts+++ b/packages/types/__tests__/decisions-vocabulary.test.ts@@ -134,16 +134,24 @@ describe("the acceptance contract, mirrored", () => {).toContain("no scope: name the files or modules it governs");});- it("falls back to the decision body when there is no rationale", () => {+ it("falls back to the context when there is no rationale", () => {expect(decisionAcceptanceBlockers({...accepted,rationale: "",- decision: "Issue signed JWTs",+ context: "sessions were lost on every deploy",}),).toEqual([]);});+ it("does not let the decision body stand in for the reason", () => {+ // The what is not the why. Reading `decision` here is what marked records+ // acceptable that say only what was chosen.+ expect(+ decisionAcceptanceBlockers({ ...accepted, rationale: "", context: "" }),+ ).toEqual(["no rationale or explicit constraint reason"]);+ });+it("requires evidence from a mined record and not from a typed one", () => {const bare = { ...accepted, evidence_commits: [], evidence_file: null };expect(decisionAcceptanceBlockers(bare)).toEqual(["no evidence reference"]);diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 0afb6924c..8ff84d5f9 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -443,10 +443,14 @@ export const DECISION_PRESETS = [* `selfAuthored` is the exemption for a record somebody typed: they wrote the* claim rather than reviewing an inference, so the entry is its own provenance.* The engine grants it to `source === "cli"` when an accepter is known.+ *+ * The reason reads `rationale` then `context`, never `decision`: `context` is+ * what forced the choice, `decision` is the choice itself, and letting the what+ * stand in for the why is what marked empty records acceptable.*/export function decisionAcceptanceBlockers(record: {rationale?: string;- decision?: string;+ context?: string;affected_files?: string[];affected_modules?: string[];evidence_commits?: string[];@@ -457,7 +461,7 @@ export function decisionAcceptanceBlockers(record: {const nonBlank = (values: (string | null | undefined)[]) =>values.some((v) => (v ?? "").trim().length > 0);- if (!nonBlank([record.rationale, record.decision])) {+ if (!nonBlank([record.rationale, record.context])) {blockers.push("no rationale or explicit constraint reason");}if (diff --git a/tests/unit/analysis/test_decision_scope.py b/tests/unit/analysis/test_decision_scope.pyindex 4b9e90b8b..6a74d434b 100644--- a/tests/unit/analysis/test_decision_scope.py+++ b/tests/unit/analysis/test_decision_scope.py@@ -2,7 +2,7 @@from __future__ import annotations-from repowise.core.analysis.decisions.scope import derive_decision_scope+from repowise.core.analysis.decisions.scope import commit_scope_files, derive_decision_scopedef test_single_file_is_file() -> None:@@ -53,3 +53,31 @@ def test_nothing_linked_is_none() -> None:def test_duplicate_file_entries_collapse_to_one_file() -> None:assert derive_decision_scope(["a/b.py", "a/b.py"], []) == "file"+++# --- the cap on commit-inherited scope --------------------------------------+++def test_a_small_commit_keeps_every_file() -> None:+ files = [f"pkg/m{i}.py" for i in range(5)]+ assert commit_scope_files(files) == sorted(files)+++def test_a_large_commit_is_capped() -> None:+ """A decision read out of one commit does not govern a 59-file refactor."""+ assert len(commit_scope_files([f"pkg/m{i:03d}.py" for i in range(59)])) == 20+++def test_the_cap_keeps_the_same_files_whatever_order_git_lists_them() -> None:+ """Truncation has to be reproducible, or re-extraction churns the scope."""+ files = [f"pkg/m{i:03d}.py" for i in range(40)]+ assert commit_scope_files(files) == commit_scope_files(list(reversed(files)))+++def test_blank_and_duplicate_entries_do_not_consume_the_cap() -> None:+ assert commit_scope_files(["a.py", "a.py", " ", ""]) == ["a.py"]+ assert commit_scope_files(None) == []+++def test_windows_separators_normalise_before_the_cap() -> None:+ assert commit_scope_files([r"pkg\m.py", "pkg/m.py"]) == ["pkg/m.py"]diff --git a/tests/unit/cli/test_decision_batch_review.py b/tests/unit/cli/test_decision_batch_review.pyindex 7c1d2db15..20903868f 100644--- a/tests/unit/cli/test_decision_batch_review.py+++ b/tests/unit/cli/test_decision_batch_review.py@@ -19,7 +19,8 @@ from .test_decision_cmd import _seed_wiki_db_GOOD = "a" * 32_ALSO_GOOD = "b" * 32-#: No rationale and no scope, so the acceptance contract refuses it.+#: No reason and no scope, so the acceptance contract refuses it. context+#: is blanked too: the seeder defaults it, and the reason reads it._BARE = "c" * 32@@ -39,6 +40,7 @@ def review_repo(tmp_path: Path) -> Path:"status": "proposed","source": "pr","rationale": "",+ "context": "","decision": "","affected_files": [],},diff --git a/tests/unit/persistence/test_decision_candidate_meta_capture.py b/tests/unit/persistence/test_decision_candidate_meta_capture.pyindex de1ff83af..d48d3a23c 100644--- a/tests/unit/persistence/test_decision_candidate_meta_capture.py+++ b/tests/unit/persistence/test_decision_candidate_meta_capture.py@@ -115,6 +115,37 @@ async def test_an_unscoped_candidate_is_flagged_and_sorts_last(async_session):assert [rec.title for rec in page] == ["Ready to accept", "No scope"]+async def test_the_decision_body_is_not_a_reason(async_session):+ """A record that says only what was chosen has not said why.++ ``context`` answers "what forced this decision?" and stands in for a blank+ rationale; ``decision`` is the choice itself and must not. Reading it as a+ reason is what kept 54 records of the dev store acceptable whose rationale+ and context are both blank.+ """+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session,+ repo.id,+ [+ _decision("Only the what", rationale="", context=""),+ _decision("Context carries it", rationale="", context="restarts dropped sessions"),+ ],+ )++ bare = await _record(async_session, "Only the what")+ assert bare.decision+ assert record_blockers(bare) == ["no rationale or explicit constraint reason"]+ meta = await async_session.get(DecisionCandidateMeta, bare.id)+ assert meta is not None and meta.review_priority == 0.0++ carried = await _record(async_session, "Context carries it")+ assert record_blockers(carried) == []++ rows = await list_candidates(async_session, repo.id)+ assert [rec.title for rec, _ in rows] == ["Context carries it", "Only the what"]++async def test_re_extraction_refreshes_priority_without_reopening_review(async_session):repo = await insert_repo(async_session)await bulk_upsert_decisions(diff --git a/tests/unit/persistence/test_decision_evolution_update.py b/tests/unit/persistence/test_decision_evolution_update.pyindex 8230d523c..459c6f1b4 100644--- a/tests/unit/persistence/test_decision_evolution_update.py+++ b/tests/unit/persistence/test_decision_evolution_update.py@@ -100,7 +100,7 @@ async def _seed_decision(session, repo_id: str) -> str:{"title": "Use MySQL for storage","decision": "use MySQL as the primary datastore",- "rationale": "",+ "rationale": "the team already ran MySQL in production","source": "inline_marker","status": "proposed","affected_files": ["src/db.py"],diff --git a/tests/unit/persistence/test_decision_health_ranking.py b/tests/unit/persistence/test_decision_health_ranking.pyindex 76cce4ec9..5eecd9674 100644--- a/tests/unit/persistence/test_decision_health_ranking.py+++ b/tests/unit/persistence/test_decision_health_ranking.py@@ -50,6 +50,7 @@ async def _add_decision(repository_id=repo_id,title=title,decision=f"{title} because reasons",+ rationale=f"the alternative to {title} was measured worse",status=status,staleness_score=staleness,confidence=confidence,diff --git a/tests/unit/persistence/test_decision_source_rank_backfill.py b/tests/unit/persistence/test_decision_source_rank_backfill.pyindex 5e99b7c0a..188780ea1 100644--- a/tests/unit/persistence/test_decision_source_rank_backfill.py+++ b/tests/unit/persistence/test_decision_source_rank_backfill.py@@ -214,6 +214,7 @@ async def test_purge_keeps_what_a_human_confirmed(async_session):{"title": "Kept because someone confirmed it","decision": "mined from a changelog, then confirmed by a human",+ "rationale": "the changelog entry gave the reason","source": "changelog","status": "proposed","affected_files": ["src/changelog.py"],diff --git a/tests/unit/persistence/test_decision_sticky_status.py b/tests/unit/persistence/test_decision_sticky_status.pyindex 8e4133ebc..959c51b24 100644--- a/tests/unit/persistence/test_decision_sticky_status.py+++ b/tests/unit/persistence/test_decision_sticky_status.py@@ -31,7 +31,8 @@ def _decision(title: str, *, source: str = "changelog", status: str = "proposed"return {"title": title,"decision": f"{title} because reasons",- "rationale": "",+ # A reason, so these records can be accepted: the decision body is not one.+ "rationale": f"{title} was the cheaper of the two options","source": source,"status": status,# A scope, so these records can be accepted: acceptance is what thediff --git a/tests/unit/persistence/test_decision_supersession.py b/tests/unit/persistence/test_decision_supersession.pyindex 8bb2f3944..813b85968 100644--- a/tests/unit/persistence/test_decision_supersession.py+++ b/tests/unit/persistence/test_decision_supersession.py@@ -83,7 +83,7 @@ def _dec(title: str, decision: str, *, files: list[str]) -> dict:return {"title": title,"decision": decision,- "rationale": "",+ "rationale": f"{title} was measured the better of the two","source": "inline_marker","status": "proposed","affected_files": files,diff --git a/tests/unit/server/test_decisions_lanes.py b/tests/unit/server/test_decisions_lanes.pyindex cb1d20f38..372fe6fae 100644--- a/tests/unit/server/test_decisions_lanes.py+++ b/tests/unit/server/test_decisions_lanes.py@@ -391,6 +391,7 @@ async def test_creating_with_a_scope_records_an_acceptance(json={"title": "Use JWT","decision": "Issue signed JWTs",+ "rationale": "sessions did not survive a restart","affected_files": ["src/auth/service.py"],},)@@ -429,6 +430,52 @@ async def test_creating_without_a_scope_lands_a_candidate_rather_than_failing(assert await _lane(client, repo["id"], "governing") == []+async def test_a_scoped_entry_with_no_reason_also_lands_a_candidate(+ client: AsyncClient, app+) -> None:+ """A scope is not enough on its own: the entry has to say why it binds.++ Same rule as the scope-less case above, and the same reason for it. The+ author's fields are kept rather than refused, and the record waits in+ review until somebody states the reason.+ """+ repo = await create_test_repo(client)++ res = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Use JWT",+ "decision": "Issue signed JWTs",+ "affected_files": ["src/auth/service.py"],+ },+ )++ assert res.status_code == 201, res.text+ assert res.json()["status"] == "proposed"+ assert res.json()["affected_files"] == ["src/auth/service.py"]+ assert await _lane(client, repo["id"], "governing") == []+++async def test_a_context_is_reason_enough_to_accept(client: AsyncClient, app) -> None:+ """``context`` is what forced the decision, so it is a why and it counts."""+ repo = await create_test_repo(client)++ res = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Use JWT",+ "decision": "Issue signed JWTs",+ "context": "sessions were lost on every deploy",+ "affected_files": ["src/auth/service.py"],+ },+ )++ assert res.status_code == 201, res.text+ assert res.json()["status"] == "active"++@pytest.mark.asyncioasync def test_a_module_only_scope_is_enough_to_accept(client: AsyncClient, app@@ -441,6 +488,7 @@ async def test_a_module_only_scope_is_enough_to_accept(json={"title": "Keep the resolver pure","decision": "No I/O in resolvers",+ "rationale": "a resolver that reads the disk cannot be memoised","affected_modules": ["src/resolvers"],},)@@ -464,6 +512,7 @@ async def test_recording_a_title_again_cannot_withdraw_its_scope(body = {"title": "Use JWT","decision": "Issue signed JWTs",+ "rationale": "sessions did not survive a restart","affected_files": ["src/auth/service.py"],}first = await client.post(f"/api/repos/{repo['id']}/decisions", json=body)@@ -490,6 +539,7 @@ async def test_recording_a_title_again_with_a_scope_still_works(body = {"title": "Use JWT","decision": "Issue signed JWTs",+ "rationale": "sessions did not survive a restart","affected_files": ["src/auth/service.py"],}await client.post(f"/api/repos/{repo['id']}/decisions", json=body)diff --git a/tests/unit/test_providers/test_provider_env_registry.py b/tests/unit/test_providers/test_provider_env_registry.pyindex d77a68ccb..e326186ae 100644--- a/tests/unit/test_providers/test_provider_env_registry.py+++ b/tests/unit/test_providers/test_provider_env_registry.py@@ -18,10 +18,12 @@ from repowise.core.providers.llm.registry import (PROVIDER_AUTODETECT_ORDER,PROVIDER_BASE_URL_ENVS,REPO_PATH_PROVIDERS,+ provider_available_for_repo,provider_credentials_present,provider_is_usable,provider_kwargs,provider_required_envs,+ repo_env_lookup,)# --- drift guards ----------------------------------------------------------@@ -232,3 +234,56 @@ def test_repo_path_is_not_forwarded_to_providers_that_reject_it():"""An HTTP provider's constructor has no repo_path parameter."""kwargs = provider_kwargs("anthropic", repo_path="/repo", getenv={"ANTHROPIC_API_KEY": "k"}.get)assert "repo_path" not in kwargs+++# --- reporting agrees with the pipeline ------------------------------------+++def _repo_with_env(tmp_path, body: str | None):+ (tmp_path / ".repowise").mkdir()+ if body is not None:+ (tmp_path / ".repowise" / ".env").write_text(body, encoding="utf-8")+ return tmp_path+++def _clear_keys(monkeypatch):+ for names in PROVIDER_API_KEY_ENVS.values():+ for name in names:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.delenv("REPOWISE_PROVIDER", raising=False)+++def test_a_repo_key_counts_as_an_available_provider(tmp_path, monkeypatch):+ """``repowise init`` writes the key here, so reporting has to read here.++ Asking ``os.environ`` alone told a repo its ``pr``, ``comment`` and+ ``git_archaeology`` lanes had no provider while the pipeline was running+ them off this very file.+ """+ _clear_keys(monkeypatch)+ repo = _repo_with_env(tmp_path, "OPENAI_API_KEY=sk-from-the-repo-env\n")+ assert provider_available_for_repo(repo) is True+++def test_a_process_key_still_counts(tmp_path, monkeypatch):+ _clear_keys(monkeypatch)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-process")+ assert provider_available_for_repo(_repo_with_env(tmp_path, None)) is True+++def test_no_key_in_either_place_is_still_unavailable(tmp_path, monkeypatch):+ _clear_keys(monkeypatch)+ assert provider_available_for_repo(_repo_with_env(tmp_path, None)) is False+++def test_the_process_environment_wins_over_the_repo_env(tmp_path, monkeypatch):+ """One repo's ``.env`` must never answer for a sibling in a workspace."""+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-process")+ repo = _repo_with_env(tmp_path, "OPENAI_API_KEY=sk-from-the-repo-env\n")+ assert repo_env_lookup(repo)("OPENAI_API_KEY") == "sk-from-the-process"+++def test_the_repo_env_fills_a_gap_the_process_leaves(tmp_path, monkeypatch):+ _clear_keys(monkeypatch)+ repo = _repo_with_env(tmp_path, "OPENAI_API_KEY=sk-from-the-repo-env\n")+ assert repo_env_lookup(repo)("OPENAI_API_KEY") == "sk-from-the-repo-env"