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.

feat(decisions): one capture policy, and acceptance as the only authority (#2067)

Raghav Chamadiya17e8be3b8a6b
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 3cfd29119..7dc9e3cd8 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -664,6 +664,10 @@ Architectural decision intelligence. Falls back to git archaeology when no decis
`answer_basis` names the strongest lane the response rests on: `decision`, `episode`, `rationale`, `archaeology`, or `documentation`. Only `decision` is a ruling; the rest are evidence to weigh. Absent when no lane was served, and on the health dashboard.
+**A record's `status` decides whether it binds you.** `active` means a person accepted it: treat it as a constraint. `proposed` means something was inferred and nobody has confirmed it: read it as a hint and never as a rule. Nothing promotes a record to `active` except an explicit `repowise decision confirm`, so a proposal that has recurred across fifty sessions is still a proposal.
+
+Path mode's `alignment` counts the two separately: `active_count` is what governs the file, `candidate_count` is what is merely awaiting review, and `score` is derived from the accepted records alone. A file with `active_count: 0` is ungoverned however many candidates name it.
+
**When to use:** Before architectural changes, understand existing intent and constraints. After changes, record new decisions.
**Example calls:**
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 34e81e19a..e0f660361 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -61,22 +61,55 @@ Two more sources sit outside the index-time set: `session` (mined from your
coding-agent transcripts, below) and `cli` (a decision you typed yourself, the
most authoritative source there is).
-Turn any source off per repo in `.repowise/config.yaml`:
-
-```yaml
-decisions:
- session_mining: true
- sources:
- comment: false # skip comment archaeology
- # inline_marker: false
- # git_archaeology: false
- # adr: false
- # pr: false
+### Controlling capture
+
+Every source is switchable, and so is the model. One resolved policy backs the
+CLI, the API, and the index pipeline, so what `config show` prints is what the
+next `init` or `update` will actually run.
+
+```bash
+repowise decision config show # resolved policy, per source, with reasons
+repowise decision config preset local_only
+repowise decision source list
+repowise decision source set comment --off
+repowise decision source set adr --no-llm # keep the parse, skip the model
+repowise decision llm --off # no decision extraction reaches a model
+```
+
+```
+repowise decision config show
+
+ Decision capture on · LLM extraction off · preset local_only
+ No LLM provider configured; model stages are skipped.
+
+Source Status LLM Why
+inline_marker deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
+git_archaeology disabled no This source is switched off.
+adr deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
+pr disabled no This source is switched off.
+comment disabled no This source is switched off.
+session deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
+cli always_on - Manual entry is always available.
```
-Sources you do not mention stay on, and unknown keys are ignored, so an old
-config never breaks extraction. Full block reference:
-[CONFIG.md](../reference/CONFIG.md).
+The four presets are `off`, `local_only`, `balanced`, and `full`; editing any
+individual switch afterwards reads as `custom`. Mutations take `--dry-run` and
+`--format json`, write atomically, and preserve every unrelated key in
+`config.yaml`.
+
+Three things the switches deliberately do **not** do. Turning a source off stops
+new capture from it; it deletes nothing already stored. A decision you have
+already accepted keeps governing after the source that found it is switched off,
+because authority comes from your acceptance and not from the source staying on.
+And `llm: false` is a complete mode rather than a broken one: transcripts are
+still read, markers and ADRs still parsed, episodes still recorded, manual
+entry unaffected. Status says *skipped*, never *failed*.
+
+`skipped_no_provider` is the same idea for a missing API key: an LLM-only source
+reports that it had nothing to run with, and a hybrid source falls back to its
+deterministic stage.
+
+Full block reference: [CONFIG.md](../reference/CONFIG.md).
## Evidence: verified, fuzzy, unverified
@@ -193,6 +226,20 @@ further and ask git directly, printing what it says: *"nothing in the 3 files it
governs has changed since 2026-05-02"*. That costs a subprocess, so it is served
only where one is affordable — never from an editor hook or during an update.
+## Driving decisions from an agent
+
+Every subcommand takes `--format json`. The lifecycle commands (`confirm`,
+`dismiss`, `deprecate`, `show`) exit non-zero on an unknown id and emit
+`{"error": "decision_not_found", "decision_id": "..."}`, so a scripted confirm
+cannot be mistaken for a successful one; `dismiss` skips its prompt under
+`--format json` or with `--yes`. `decision config show --format json` returns
+the whole source registry with a `status` and a `reason` per source, which is
+the machine-readable answer to "will this source run, and if not why not".
+
+Reading decisions back, the `status` field is what decides whether a record
+binds: `active` was accepted by a person, `proposed` was inferred and is a hint.
+See [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_why).
+
## Session-mined decisions
`repowise update` (docs mode) reads your local coding-agent transcripts and mines
@@ -211,13 +258,18 @@ Three stages, in order:
2. **One batched LLM structuring call per update**, capped at 60 candidates.
Every produced field must quote the transcript verbatim or it is dropped;
an ungrounded `source_quote` rejects the candidate.
-3. **Observation-counted promotion.** A decision seen in two or more distinct
- sessions is promoted to `active` with `source: session`. A direct user
- correction promotes after one.
+3. **Promotion to a proposal.** A decision seen in two or more distinct
+ sessions, or one direct user correction, is written with `source: session`
+ and status `proposed`. Recurrence is evidence that a candidate is worth
+ reading, not an acceptance event: `repowise decision confirm` is what makes
+ it govern. Repeated observations accrete evidence rows and raise confidence
+ without ever changing status.
Everything stays on your machine. Transcripts are read locally, staging lives in
`.repowise/sessions/sessions.db`, and only the distilled decision text about the
-codebase is stored. Turn the pipeline off with `decisions.session_mining: false`.
+codebase is stored. Turn the pipeline off with
+`repowise decision source set session --off`, or keep the transcript reading and
+drop only the structuring call with `--no-llm`.
## Getting decisions back to your agent
@@ -264,6 +316,11 @@ the primary repo. Decision ids accept an 8-character prefix.
| `repowise decision dismiss ID` | Tombstone it. Never re-proposed on reindex. |
| `repowise decision deprecate ID` | Mark deprecated, optionally `--superseded-by <ID>`. |
| `repowise decision health` | Counts, stale decisions, ungoverned hotspots, proposals awaiting review. |
+| `repowise decision config show` | The resolved capture policy: every source, its status, and why. |
+| `repowise decision config preset NAME` | Apply `off`, `local_only`, `balanced`, or `full`. |
+| `repowise decision source list` | The source registry with capabilities and current state. |
+| `repowise decision source set SRC --on/--off` | Switch one source. `--llm/--no-llm` switches only its model stage. |
+| `repowise decision llm --on/--off` | Master switch for decision-extraction model calls. |
`list` filters:
@@ -283,7 +340,7 @@ Full flag reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-d
| Call shape | Mode | Returns |
|------------|------|---------|
| No `query` | health | `counts`, `stale_decisions`, `proposed_awaiting_review`, `ungoverned_hotspots`, `conflicts` |
-| `query` is a path | path | The decisions governing that file (with `lineage` when the chain is longer than one), an `origin_story` from git, and an `alignment` read |
+| `query` is a path | path | The decisions governing that file (with `lineage` when the chain is longer than one), an `origin_story` from git, and an `alignment` read scored on accepted decisions only |
| `query` is a question | search | Ranked decision records plus `related_documentation`, optionally anchored with `targets` |
| `repo="all"` | workspace search | The same records across every workspace repo, each tagged with its alias |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 4989f4a40..e3cb8caee 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -918,8 +918,31 @@ repowise decision confirm ID [PATH] # confirm a proposal
repowise decision dismiss ID [PATH] # dismiss a proposal (sticky; never re-proposed)
repowise decision deprecate ID [PATH] # mark deprecated
repowise decision health [PATH] # health dashboard
+
+repowise decision config show [PATH] # the resolved capture policy
+repowise decision config preset NAME [PATH] # off | local_only | balanced | full
+repowise decision source list [PATH] # the source registry and its state
+repowise decision source set SRC --on|--off # switch one source
+repowise decision source set SRC --llm|--no-llm # switch only its model stage
+repowise decision llm --on|--off [PATH] # all decision-extraction model calls
```
+**Capture-control options:**
+
+| Flag | Description |
+|------|-------------|
+| `--dry-run` | Print the change and write nothing. On `config preset`, `source set`, `llm`. |
+| `--format` | `table` (default) or `json`. `json` returns the full source registry. |
+
+`confirm` is the acceptance event. Nothing else promotes a record to `active`:
+extraction, recurrence across sessions, and confidence all stop at `proposed`.
+
+**Scripting these:** every subcommand takes `--format json`, and `confirm`,
+`dismiss`, `deprecate`, and `show` exit non-zero on an unknown id with
+`{"error": "decision_not_found", "decision_id": "..."}` so a caller can tell a
+typo from a successful transition. `dismiss` skips its confirmation prompt under
+`--format json`, or with `--yes`.
+
**List options:**
| Flag | Description |
@@ -930,7 +953,7 @@ repowise decision health [PATH] # health dashboard
| `--stale-only` | Only stale decisions |
| `--format` | `table` (default) or `json` |
-`--format json` is also available on `decision show` and `decision health`. In JSON, `decision list` emits full ids rather than the table's 8-character prefixes, and `show` / `health` skip the caps the human output applies to keep a panel readable.
+`--format json` is available on every `decision` subcommand. In JSON, `decision list` emits full ids rather than the table's 8-character prefixes, and `show` / `health` skip the caps the human output applies to keep a panel readable.
---
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index dd426e794..3e5f39d14 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -382,35 +382,86 @@ mcp:
### The `decisions:` block
-Controls decision extraction. Each key under `sources:` names an index-time
-capture source; set it to `false` to skip that source on the next
-`init` / `update`. Unknown keys are ignored, and sources you don't mention
-stay enabled.
+Controls decision capture: whether it runs at all, which sources it uses, and
+whether any of them may call a model. One resolved policy backs the CLI, the
+API, and the index pipeline, so all three agree about what will run.
```yaml
decisions:
- session_mining: true # mine agent-session transcripts (see below)
+ enabled: true # master switch for automatic capture
+ llm: true # master switch for decision-extraction model calls
+ preset: balanced # off | local_only | balanced | full
sources:
- comment: false # LLM comment archaeology (top central files)
- # inline_marker: false # WHY:/DECISION: markers
- # git_archaeology: false
- # adr: false
- # changelog: false
- # pr: false
-```
-
-`session_mining` (default on) lets `repowise update` mine coding-agent
-session transcripts (Claude Code's `~/.claude/projects/`) for durable
-decisions: user corrections, explicit choices with a stated reason, and
-failed approaches replaced by working ones. Candidates pass deterministic
-gates first, then one batched LLM structuring call per update, and every
-produced field must quote the transcript verbatim or it is dropped. A
-decision observed in two or more sessions is promoted as `active` with
-`source: session`; a direct user correction promotes after one. Everything
-stays local: transcripts are read from your machine, staging lives in
-`.repowise/sessions/sessions.db`, and only the distilled decision text about
-the codebase is stored. Set `session_mining: false` to turn the whole
-pipeline off.
+ inline_marker: true # WHY:/DECISION: markers
+ git_archaeology: true # commit messages
+ adr: true # ADR files
+ pr: true # PR / squash-merge bodies
+ comment: false # comment archaeology on top central files
+ session: # long form: run the source, skip its model stage
+ enabled: true
+ llm: false
+```
+
+Every key is optional. **A config with no `decisions:` block behaves exactly as
+it did before these switches existed**: every source on, model stages on.
+
+A source is a bare boolean or a `{enabled, llm}` mapping. The long form only
+matters for a source with both a deterministic and a model stage
+(`inline_marker`, `adr`, `session`): it keeps the deterministic parse and skips
+the model call. A source that is model-only (`git_archaeology`, `pr`,
+`comment`) is skipped entirely when its model stage is off, because running it
+would produce a zero indistinguishable from an empty repository.
+
+Unknown keys are reported as warnings rather than discarded, so a typo'd source
+name shows up instead of silently reading as a working switch. Retired names
+(`code_comment`, `changelog`, `readme_mining`) are among them: an old config
+still loads, it just says which key it ignored.
+
+**Presets** are conveniences that write the same keys:
+
+| Preset | Effect |
+|--------|--------|
+| `off` | No automatic capture. Stored decisions and manual entry keep working. |
+| `local_only` | Deterministic capture only. Zero decision-extraction model calls. |
+| `balanced` | The high-signal sources plus session mining; comment archaeology off. |
+| `full` | Every source, every model stage. |
+
+Editing any individual key after applying a preset drops the `preset` line and
+the resolved policy reads as `custom`.
+
+`llm: false` is a complete mode, not a degraded one: transcripts are still
+read, markers and ADRs are still parsed, episodes are still recorded, manual
+decisions still work, and already-accepted decisions keep governing. It is the
+one switch that proves no decision extraction reaches a model.
+
+Set these from the CLI rather than by hand if you prefer:
+
+```bash
+repowise decision config show # the resolved policy, per source
+repowise decision config preset local_only
+repowise decision source set comment --off
+repowise decision source set adr --no-llm # keep the parse, skip the model
+repowise decision llm --off
+```
+
+Every mutating command takes `--dry-run` to print the change without writing,
+and `--format json` for scripts. Writes are atomic and preserve every unrelated
+key in `config.yaml`.
+
+The legacy `decisions.session_mining: true|false` key is still honoured and
+resolves to the `session` source. The first write through the CLI or the API
+replaces it with `sources.session`.
+
+`session` mining lets `repowise update` read coding-agent session transcripts
+(Claude Code's `~/.claude/projects/`) for durable decisions: user corrections,
+explicit choices with a stated reason, and failed approaches replaced by working
+ones. Candidates pass deterministic gates first, then one batched LLM
+structuring call per update, and every produced field must quote the transcript
+verbatim or it is dropped. **Mined decisions are stored as `proposed`**, however
+many sessions they recur across; confirming one with `repowise decision confirm`
+is what makes it govern. Everything stays local: transcripts are read from your
+machine, staging lives in `.repowise/sessions/sessions.db`, and only the
+distilled decision text about the codebase is stored.
Dismissals are sticky: `repowise decision dismiss` keeps the record as a
`dismissed` tombstone, so reindexing never re-proposes the same decision, and
diff --git a/packages/api-client/src/decisions.ts b/packages/api-client/src/decisions.ts
index a3a49c381..3679ccb56 100644
--- a/packages/api-client/src/decisions.ts
+++ b/packages/api-client/src/decisions.ts
@@ -1,4 +1,4 @@
-import { apiGet, apiPost, apiPatch } from "./client";
+import { apiGet, apiPost, apiPatch, apiPut } from "./client";
import type {
DecisionCreate,
DecisionEvidence,
@@ -8,6 +8,8 @@ import type {
DecisionLineageEntry,
DecisionLineageResponse,
DecisionRecordResponse,
+ DecisionSettings,
+ DecisionSettingsUpdate,
DecisionStatusUpdate,
} from "./types";
@@ -97,3 +99,14 @@ export async function getDecisionLineage(
export async function getDecisionGraph(repoId: string): Promise<DecisionGraph> {
return apiGet<DecisionGraph>(`/api/repos/${repoId}/decisions/graph`);
}
+
+export async function getDecisionSettings(repoId: string): Promise<DecisionSettings> {
+ return apiGet<DecisionSettings>(`/api/repos/${repoId}/decisions/settings`);
+}
+
+export async function updateDecisionSettings(
+ repoId: string,
+ update: DecisionSettingsUpdate,
+): Promise<DecisionSettings> {
+ return apiPut<DecisionSettings>(`/api/repos/${repoId}/decisions/settings`, update);
+}
diff --git a/packages/api-client/src/types/decisions.ts b/packages/api-client/src/types/decisions.ts
index 81343d1ed..b38b70f60 100644
--- a/packages/api-client/src/types/decisions.ts
+++ b/packages/api-client/src/types/decisions.ts
@@ -7,6 +7,16 @@
// accepted — so the UI had no way to say it and sent `deprecated` instead.
import type { DecisionStatus } from "@repowise-dev/types/decisions";
+// Re-exported rather than re-declared: the capture policy has one shape and
+// the server generates it from the same registry.
+export type {
+ DecisionPreset,
+ DecisionSettings,
+ DecisionSettingsUpdate,
+ DecisionSourcePatch,
+ DecisionSourceState,
+} from "@repowise-dev/types/decisions";
+
export interface DecisionRecordResponse {
id: string;
repository_id: string;
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 1c7530ca7..63eba9f4f 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -50,6 +50,26 @@ def decision_group() -> None:
"""Manage architectural decision records."""
+def _register_config_commands() -> None:
+ """Attach the capture-control commands.
+
+ They live in their own module (policy resolution, presets, per-source
+ switches) and are attached here so ``decision`` stays one group.
+ """
+ from repowise.cli.commands.decision_config_cmd import (
+ config_group,
+ llm_command,
+ source_group,
+ )
+
+ decision_group.add_command(config_group)
+ decision_group.add_command(source_group)
+ decision_group.add_command(llm_command)
+
+
+_register_config_commands()
+
+
async def _resolve_decision_id(session, decision_id: str) -> str | None:
"""Expand a (possibly truncated) decision id to the full stored id.
@@ -399,7 +419,9 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:
notice_console(fmt).print(f"[red]Decision not found: {decision_id}[/red]")
if fmt == "json":
emit_json({"query": decision_id, "decision": None})
- return
+ # Non-zero for the same reason the lifecycle commands are: a caller
+ # scripting `show` cannot tell a missing id from an empty record.
+ raise click.exceptions.Exit(1)
if fmt == "json":
emit_json(
@@ -488,6 +510,25 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:
console.print(Panel("\n".join(lines), title=f"Decision {rec.id[:8]}"))
+
+def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = "") -> None:
+ """Report one status transition to a person or to a machine.
+
+ Not found exits non-zero: an agent driving the lifecycle could not tell a
+ typo'd id from a successful confirm when both returned 0.
+ """
+ if rec is None:
+ if fmt == "json":
+ emit_json({"error": "decision_not_found", "decision_id": decision_id})
+ else:
+ console.print(f"[red]Decision not found: {decision_id}[/red]")
+ raise click.exceptions.Exit(1)
+ if fmt == "json":
+ emit_json({"id": rec.id, "status": rec.status, "action": action})
+ return
+ console.print(f"[green]Decision {rec.id[:8]} {action}[/green]" + (f" {note}" if note else ""))
+
+
# ---------------------------------------------------------------------------
# decision confirm
# ---------------------------------------------------------------------------
@@ -496,9 +537,14 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:
@decision_group.command("confirm")
@click.argument("decision_id")
@click.argument("path", required=False, default=None)
-def decision_confirm(decision_id: str, path: str | None) -> None:
- """Confirm a proposed decision (set status to active)."""
- repo_path = _resolve_decision_repo(path)
+@format_option()
+def decision_confirm(decision_id: str, path: str | None, fmt: str) -> None:
+ """Confirm a proposed decision (set status to active).
+
+ This is the acceptance event. Nothing else promotes a record to ``active``:
+ extraction, recurrence and confidence all stop at ``proposed``.
+ """
+ repo_path = _resolve_decision_repo(path, fmt)
async def _update():
from repowise.core.persistence import (
@@ -521,11 +567,7 @@ def decision_confirm(decision_id: str, path: str | None) -> None:
await engine.dispose()
return rec
- rec = run_async(_update())
- if rec is None:
- console.print(f"[red]Decision not found: {decision_id}[/red]")
- else:
- console.print(f"[green]Decision {rec.id[:8]} confirmed (active)[/green]")
+ _emit_lifecycle(run_async(_update()), decision_id, "confirmed", fmt, "(active)")
# ---------------------------------------------------------------------------
@@ -536,11 +578,15 @@ def decision_confirm(decision_id: str, path: str | None) -> None:
@decision_group.command("dismiss")
@click.argument("decision_id")
@click.argument("path", required=False, default=None)
-def decision_dismiss(decision_id: str, path: str | None) -> None:
[email protected]("--yes", "-y", is_flag=True, default=False, help="Skip the confirmation prompt.")
+@format_option()
+def decision_dismiss(decision_id: str, path: str | None, yes: bool, fmt: str) -> None:
"""Dismiss a proposed decision (kept as a tombstone; never re-proposed)."""
- repo_path = _resolve_decision_repo(path)
+ repo_path = _resolve_decision_repo(path, fmt)
- if not click.confirm(f"Dismiss decision {decision_id[:8]}?"):
+ # A machine-readable invocation is non-interactive by construction: the
+ # prompt read EOF and aborted every scripted dismissal.
+ if not yes and fmt != "json" and not click.confirm(f"Dismiss decision {decision_id[:8]}?"):
console.print("[yellow]Cancelled.[/yellow]")
return
@@ -565,14 +611,13 @@ def decision_dismiss(decision_id: str, path: str | None) -> None:
await engine.dispose()
return rec
- rec = run_async(_dismiss())
- if rec is not None:
- console.print(
- f"[green]Decision {rec.id[:8]} dismissed[/green] "
- "[dim](kept as a tombstone; reindexing will not re-propose it)[/dim]"
- )
- else:
- console.print(f"[red]Decision not found: {decision_id}[/red]")
+ _emit_lifecycle(
+ run_async(_dismiss()),
+ decision_id,
+ "dismissed",
+ fmt,
+ "[dim](kept as a tombstone; reindexing will not re-propose it)[/dim]",
+ )
# ---------------------------------------------------------------------------
@@ -584,9 +629,12 @@ def decision_dismiss(decision_id: str, path: str | None) -> None:
@click.argument("decision_id")
@click.argument("path", required=False, default=None)
@click.option("--superseded-by", default=None, help="ID of the decision that replaces this one.")
-def decision_deprecate(decision_id: str, path: str | None, superseded_by: str | None) -> None:
+@format_option()
+def decision_deprecate(
+ decision_id: str, path: str | None, superseded_by: str | None, fmt: str
+) -> None:
"""Deprecate an active decision."""
- repo_path = _resolve_decision_repo(path)
+ repo_path = _resolve_decision_repo(path, fmt)
async def _update():
from repowise.core.persistence import (
@@ -615,11 +663,7 @@ def decision_deprecate(decision_id: str, path: str | None, superseded_by: str |
await engine.dispose()
return rec
- rec = run_async(_update())
- if rec is None:
- console.print(f"[red]Decision not found: {decision_id}[/red]")
- else:
- console.print(f"[yellow]Decision {rec.id[:8]} deprecated.[/yellow]")
+ _emit_lifecycle(run_async(_update()), decision_id, "deprecated", fmt)
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
new file mode 100644
index 000000000..bf168cfab
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
@@ -0,0 +1,276 @@
+"""``repowise decision config`` / ``source`` / ``llm`` — capture controls.
+
+Every command here reads and writes the one resolved policy in
+``repowise.core.analysis.decisions.policy``, so the CLI cannot disagree with
+what the index pipeline and the server report.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+from rich.table import Table
+
+from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option, notice_console
+from repowise.core.analysis.decisions.policy import (
+ PRESET_NAMES,
+ SOURCE_SPECS,
+ DecisionPolicy,
+)
+from repowise.core.analysis.decisions.policy_store import load_policy, write_policy
+
+
+def _load(repo_path: Path):
+ """Resolve the policy, turning an unparseable config into a clean error.
+
+ A malformed ``decisions:`` block is only a warning, but a malformed *file*
+ never reaches the resolver and would surface as a traceback.
+ """
+ from repowise.core.repo_config import RepoConfigError
+
+ try:
+ return load_policy(repo_path)
+ except RepoConfigError as exc:
+ raise click.ClickException(str(exc)) from exc
+
+#: Sources a user can switch. ``cli`` is manual entry, an authority route with
+#: nothing to capture, so offering it here would imply it could be turned off.
+_TOGGLABLE: tuple[str, ...] = tuple(s.key for s in SOURCE_SPECS if s.togglable)
+
+_STATUS_STYLE = {
+ "enabled": "green",
+ "always_on": "green",
+ "deterministic_only": "yellow",
+ "skipped_no_provider": "yellow",
+ "disabled": "dim",
+}
+
+
+def _provider_available(repo_path: Path) -> bool:
+ """Whether an LLM provider resolves for this repo.
+
+ Reported, not enforced: the model on with no key configured is a healthy
+ ``skipped_no_provider``, not a failure.
+ """
+ from repowise.core.providers.llm.registry import provider_available_for_repo
+
+ return provider_available_for_repo(repo_path)
+
+
+def _emit(repo_path: Path, resolution, fmt: str) -> None:
+ """Render a resolved policy, plus any warnings, in the requested format."""
+ policy = resolution.policy
+ provider_available = _provider_available(repo_path)
+ notices = notice_console(fmt)
+
+ if fmt == "json":
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "policy": policy.to_dict(provider_available=provider_available),
+ "provider_available": provider_available,
+ "warnings": list(resolution.warnings),
+ "legacy_keys": list(resolution.legacy_keys),
+ }
+ )
+ return
+
+ header = "on" if policy.enabled else "off"
+ llm = "on" if policy.llm else "off"
+ console.print(
+ f"\n Decision capture [bold]{header}[/bold] · "
+ f"LLM extraction [bold]{llm}[/bold] · preset [bold]{policy.preset_name()}[/bold]"
+ )
+ if not provider_available:
+ console.print(" [dim]No LLM provider configured; model stages are skipped.[/dim]")
+
+ table = Table(box=None, pad_edge=False, show_edge=False)
+ table.add_column("Source", style="bold")
+ table.add_column("Status")
+ table.add_column("LLM")
+ table.add_column("Why")
+ for rt in policy.runtime(provider_available=provider_available):
+ style = _STATUS_STYLE.get(rt.status, "")
+ llm_cell = "-" if not rt.supports_llm else ("yes" if rt.llm_enabled else "no")
+ table.add_row(
+ rt.key,
+ f"[{style}]{rt.status}[/{style}]" if style else rt.status,
+ llm_cell,
+ f"[dim]{rt.reason}[/dim]",
+ )
+ console.print(table)
+ console.print("")
+
+ for warning in resolution.warnings:
+ notices.print(f"[yellow]{warning}[/yellow]")
+ if resolution.legacy_keys:
+ notices.print(
+ "[dim]Legacy keys still honoured: "
+ f"{', '.join(resolution.legacy_keys)}. Any write here replaces them.[/dim]"
+ )
+
+
+def _apply(repo_path: Path, policy: DecisionPolicy, fmt: str, dry_run: bool) -> None:
+ """Persist *policy*, or show the diff it would make under ``--dry-run``."""
+ from repowise.core.analysis.decisions.policy_store import PolicyConflictError
+
+ before = _load(repo_path).policy
+ if dry_run:
+ changes = _diff(before, policy)
+ if fmt == "json":
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "dry_run": True,
+ "changes": changes,
+ "policy": policy.to_dict(provider_available=_provider_available(repo_path)),
+ }
+ )
+ return
+ if not changes:
+ console.print("[dim]No change.[/dim]")
+ return
+ console.print("\n Would change:")
+ for change in changes:
+ console.print(f" {change['key']}: {change['from']} -> {change['to']}")
+ console.print("")
+ return
+
+ try:
+ resolution = write_policy(repo_path, policy)
+ except PolicyConflictError as exc:
+ raise click.ClickException(str(exc)) from exc
+ _emit(repo_path, resolution, fmt)
+
+
+def _diff(before: DecisionPolicy, after: DecisionPolicy) -> list[dict[str, str]]:
+ changes: list[dict[str, str]] = []
+ if before.enabled != after.enabled:
+ changes.append({"key": "enabled", "from": str(before.enabled), "to": str(after.enabled)})
+ if before.llm != after.llm:
+ changes.append({"key": "llm", "from": str(before.llm), "to": str(after.llm)})
+ for key in _TOGGLABLE:
+ old, new = before.sources.get(key), after.sources.get(key)
+ if old == new:
+ continue
+ changes.append(
+ {
+ "key": f"sources.{key}",
+ "from": f"enabled={old.enabled if old else '?'} llm={old.llm if old else '?'}",
+ "to": f"enabled={new.enabled if new else '?'} llm={new.llm if new else '?'}",
+ }
+ )
+ return changes
+
+
+# ---------------------------------------------------------------------------
+# decision config
+# ---------------------------------------------------------------------------
+
+
+def config_group() -> None:
+ """Inspect and set decision capture policy."""
+
+
+@config_group.command("show")
[email protected]("path", required=False, default=None)
+@format_option()
+def config_show(path: str | None, fmt: str) -> None:
+ """Show the resolved capture policy for this repository."""
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ _emit(repo_path, _load(repo_path), fmt)
+
+
+@config_group.command("preset")
[email protected]("name", type=click.Choice(list(PRESET_NAMES)))
[email protected]("path", required=False, default=None)
[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
+@format_option()
+def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
+ """Apply a named preset: off, local_only, balanced, full."""
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+ from repowise.core.analysis.decisions.policy import preset_policy
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ _apply(repo_path, preset_policy(name), fmt, dry_run)
+
+
+# ---------------------------------------------------------------------------
+# decision source
+# ---------------------------------------------------------------------------
+
+
+def source_group() -> None:
+ """List and switch individual capture sources."""
+
+
+@source_group.command("list")
[email protected]("path", required=False, default=None)
+@format_option()
+def source_list(path: str | None, fmt: str) -> None:
+ """List every capture source with its capabilities and current state."""
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ _emit(repo_path, _load(repo_path), fmt)
+
+
+@source_group.command("set")
[email protected]("source", type=click.Choice(list(_TOGGLABLE)))
[email protected]("path", required=False, default=None)
[email protected]("--on/--off", "enabled", default=None, help="Enable or disable this source.")
+ "--llm/--no-llm",
+ "llm",
+ default=None,
+ help="Allow or forbid this source's model stage.",
+)
[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
+@format_option()
+def source_set(
+ source: str,
+ path: str | None,
+ enabled: bool | None,
+ llm: bool | None,
+ dry_run: bool,
+ fmt: str,
+) -> None:
+ """Switch one capture source, or its model stage, on or off."""
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ if enabled is None and llm is None:
+ raise click.ClickException("Pass --on/--off or --llm/--no-llm.")
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ current = _load(repo_path).policy
+ _apply(repo_path, current.with_source(source, enabled=enabled, llm=llm), fmt, dry_run)
+
+
+# ---------------------------------------------------------------------------
+# decision llm
+# ---------------------------------------------------------------------------
+
+
[email protected]("path", required=False, default=None)
[email protected]("--on/--off", "enabled", default=None, required=True, help="Master LLM switch.")
[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
+@format_option()
+def llm_command(path: str | None, enabled: bool | None, dry_run: bool, fmt: str) -> None:
+ """Turn all decision-extraction model calls on or off.
+
+ Off is a complete mode, not a degraded one: deterministic capture,
+ transcript ingestion and manual decisions all keep working, and already
+ accepted decisions keep governing.
+ """
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ current = _load(repo_path).policy
+ _apply(repo_path, current.with_llm(bool(enabled)), fmt, dry_run)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 8be4a354e..9bb4e2c5b 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1468,17 +1468,23 @@ def run_update(
# (dead_code_report computed above, before the index-only branch)
# Re-scan changed files for inline decision markers
+ from repowise.core.analysis.decisions.policy import resolve_policy
+
+ decision_policy = resolve_policy(cfg).policy
new_decision_markers: list = []
try:
from repowise.core.analysis.decision_extractor import DecisionExtractor
changed_paths = [fd.path for fd in file_diffs if fd.status in ("added", "modified")]
- if changed_paths:
+ # The rescan is the inline_marker source; it was running regardless of
+ # whether that source was switched off.
+ if changed_paths and decision_policy.source_enabled("inline_marker"):
extractor = DecisionExtractor(
repo_path=repo_path,
provider=provider,
graph=graph_builder.graph(),
git_meta_map=git_meta_map,
+ policy=decision_policy,
)
# Label these calls as decision extraction so the Costs page can
# tell them apart from page regeneration (both ride this provider).
@@ -1502,13 +1508,13 @@ def run_update(
# `decisions.session_mining: false` in .repowise/config.yaml disables it.
session_decisions: list = []
try:
- from repowise.core.sessions.miners.decisions import (
- mine_session_decisions,
- session_mining_enabled,
- )
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
- if session_mining_enabled(cfg):
- session_decisions = run_async(mine_session_decisions(repo_path, provider=provider))
+ if decision_policy.source_enabled("session"):
+ session_provider = provider if decision_policy.llm_allowed("session") else None
+ session_decisions = run_async(
+ mine_session_decisions(repo_path, provider=session_provider)
+ )
if session_decisions and verbose:
promoted_titles = {d.title for d in session_decisions}
console.print(f"Session decisions promoted: [green]{len(promoted_titles)}[/green]")
@@ -1524,7 +1530,7 @@ def run_update(
try:
from repowise.core.sessions.miners.decisions import apply_injection_feedback
- if session_mining_enabled(cfg):
+ if decision_policy.source_enabled("session"):
async def _run_injection_feedback() -> dict:
from repowise.cli.helpers import get_db_url_for_repo
@@ -1568,7 +1574,7 @@ def run_update(
try:
from repowise.core.sessions.efficacy import ingest_transcript_efficacy
- if session_mining_enabled(cfg):
+ if decision_policy.source_enabled("session"):
classified = ingest_transcript_efficacy(
repo_path, since=time.time() - _EFFICACY_LOOKBACK_SECONDS
)
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 4c30d374f..be08df2fa 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -47,6 +47,11 @@ from typing import Any
import structlog
from repowise.core.analysis.decisions.gate import apply_substring_gate
+from repowise.core.analysis.decisions.policy import (
+ INDEX_SOURCE_KEYS,
+ DecisionPolicy,
+ resolve_policy,
+)
from repowise.core.analysis.decisions.scope import resolve_module_nodes
from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
from repowise.core.ingestion.traverser import load_gitignore_spec
@@ -204,30 +209,18 @@ class DecisionExtractionReport:
# Every index-time capture source, in progress order. The CLI derives its
-# progress-bar step count from this; the config gate validates against it.
-SOURCE_NAMES: tuple[str, ...] = (
- "inline_marker",
- "git_archaeology",
- "adr",
- "pr",
- "comment",
-)
+# progress-bar step count from this. Re-exported from the source registry so
+# capabilities and run order cannot drift apart.
+SOURCE_NAMES: tuple[str, ...] = INDEX_SOURCE_KEYS
def enabled_source_names(repo_config: dict[str, Any] | None) -> tuple[str, ...]:
- """Resolve which capture sources are enabled for a repo.
+ """Resolve which index-time capture sources are enabled for a repo.
- Reads the ``decisions.sources`` mapping from a loaded
- ``.repowise/config.yaml`` dict (``{source_name: bool}``). Sources absent
- from the mapping default to enabled; unknown keys are ignored so a stale
- config (e.g. the removed ``code_comment``) never breaks extraction.
+ Thin wrapper over :func:`resolve_policy`; kept because callers pass a
+ loaded config dict and want only the names.
"""
- cfg = repo_config or {}
- decisions_cfg = cfg.get("decisions") or {}
- sources_cfg = decisions_cfg.get("sources") if isinstance(decisions_cfg, dict) else {}
- if not isinstance(sources_cfg, dict):
- sources_cfg = {}
- return tuple(name for name in SOURCE_NAMES if sources_cfg.get(name, True) is not False)
+ return resolve_policy(repo_config).policy.enabled_index_sources()
# ---------------------------------------------------------------------------
@@ -418,9 +411,13 @@ class DecisionExtractor:
git_meta_map: dict[str, dict] | None = None,
parsed_files: list[Any] | None = None,
source_map: dict[str, bytes] | None = None,
+ policy: DecisionPolicy | None = None,
) -> None:
self._repo_path = Path(repo_path)
self._provider = provider
+ # Per-source model gate. ``None`` means "no policy supplied", which
+ # keeps the provider available to every source, as before this existed.
+ self._policy = policy
self._graph = graph
self._git_meta_map = git_meta_map or {}
self._parsed_files = parsed_files or []
@@ -431,6 +428,17 @@ class DecisionExtractor:
# keeps the legacy self-walk fallback for callers that don't thread it.
self._source_map = source_map
+ def _llm(self, source: str) -> Any | None:
+ """The provider *source* may use, or None when its model stage is off.
+
+ One gate for all five sources: a hybrid source (inline_marker, adr)
+ falls back to its deterministic parse, and an LLM-only source returns
+ nothing, which is the same shape as having no provider at all.
+ """
+ if self._policy is not None and not self._policy.llm_allowed(source):
+ return None
+ return self._provider
+
# ------------------------------------------------------------------
# Source 1: Inline markers
# ------------------------------------------------------------------
@@ -498,6 +506,7 @@ class DecisionExtractor:
if not markers_by_file:
return []
+ marker_llm = self._llm("inline_marker")
decisions: list[ExtractedDecision] = []
for file_path, markers in markers_by_file.items():
@@ -506,7 +515,7 @@ class DecisionExtractor:
markers_by_line = {m["line"]: m for m in markers}
- if self._provider:
+ if marker_llm:
# Use LLM to structure markers
try:
llm_decisions = await self._structure_markers_via_llm(file_path, markers)
@@ -586,6 +595,7 @@ class DecisionExtractor:
exception, so those markers were never structured and never fell
back — they left no record and no log line.
"""
+ provider = self._llm("inline_marker")
decisions: list[ExtractedDecision] = []
for start in range(0, len(markers), _MARKERS_PER_CALL):
batch = markers[start : start + _MARKERS_PER_CALL]
@@ -602,7 +612,7 @@ class DecisionExtractor:
markers_block=markers_block,
)
- response = await self._provider.generate(
+ response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
)
decisions.extend(self._parse_decisions_json(response.content))
@@ -614,7 +624,8 @@ class DecisionExtractor:
async def mine_git_archaeology(self) -> list[ExtractedDecision]:
"""Extract decisions from significant git commits."""
- if not self._provider or not self._git_meta_map:
+ provider = self._llm("git_archaeology")
+ if not provider or not self._git_meta_map:
return []
# Collect unique significant commits with decision signals
@@ -685,7 +696,7 @@ class DecisionExtractor:
source_by_sha[c["sha"]] = f"{c['message']}\n{body}".strip()
prompt = GIT_ARCHAEOLOGY_PROMPT.format(commits_block=commits_block)
- response = await self._provider.generate(
+ response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
)
extracted = self._parse_decisions_json(response.content)
@@ -738,6 +749,7 @@ class DecisionExtractor:
adr_paths = self._find_adr_files()
if not adr_paths:
return []
+ provider = self._llm("adr")
decisions: list[ExtractedDecision] = []
for path in adr_paths:
@@ -755,11 +767,11 @@ class DecisionExtractor:
parsed = self._parse_adr(content, rel)
if parsed is not None:
decisions.append(parsed)
- elif self._provider:
+ elif provider:
try:
stripped = self._strip_code_blocks(content)
prompt = README_MINING_PROMPT.format(file_path=rel, content=stripped[:15_000])
- response = await self._provider.generate(
+ response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
)
for d in self._parse_decisions_json(response.content):
@@ -896,7 +908,8 @@ class DecisionExtractor:
async def mine_pr_bodies(self) -> list[ExtractedDecision]:
"""Extract decisions from PR / squash-merge commit bodies."""
- if not self._provider or not self._git_meta_map:
+ provider = self._llm("pr")
+ if not provider or not self._git_meta_map:
return []
candidates: dict[str, dict] = {}
@@ -944,7 +957,7 @@ class DecisionExtractor:
# saw no errors and the run reported "Nothing found in: pull
# requests" — the exact zero-that-means-failure this change exists
# to remove.
- response = await self._provider.generate(
+ response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
)
extracted = self._parse_decisions_json(response.content)
@@ -982,7 +995,8 @@ class DecisionExtractor:
``instead of`` …) rather than the explicit markers already covered by
``scan_inline_markers``.
"""
- if not self._provider or self._graph is None:
+ provider = self._llm("comment")
+ if not provider or self._graph is None:
return []
top_files = self._top_central_files(_MAX_COMMENT_NODES)
@@ -1009,7 +1023,7 @@ class DecisionExtractor:
# all — the quietest of the three swallows, and the one that made
# "comment: 0" unfalsifiable. Let it propagate to the gather
# below, which counts it.
- response = await self._provider.generate(
+ response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
)
extracted = self._parse_decisions_json(response.content)
@@ -1257,9 +1271,9 @@ class DecisionExtractor:
sub-extractor finishes (the names in :data:`SOURCE_NAMES`). Used by the
CLI to surface per-source progress.
- *enabled_sources* restricts the run to the named sources (``None`` runs
- everything). Callers derive it from ``decisions.sources`` in
- ``.repowise/config.yaml`` via :func:`enabled_source_names`.
+ *enabled_sources* restricts the run to the named sources. It defaults
+ to the policy passed at construction, and to everything when there is
+ none.
Every extracted decision is then put through the anti-hallucination
substring gate (:meth:`_apply_substring_gate`) before being returned —
@@ -1293,6 +1307,8 @@ class DecisionExtractor:
("pr", self.mine_pr_bodies),
("comment", self.mine_comment_archaeology),
]
+ if enabled_sources is None and self._policy is not None:
+ enabled_sources = self._policy.enabled_index_sources()
if enabled_sources is None:
sources = all_sources
else:
diff --git a/packages/core/src/repowise/core/analysis/decisions/policy.py b/packages/core/src/repowise/core/analysis/decisions/policy.py
new file mode 100644
index 000000000..cf94a7753
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/policy.py
@@ -0,0 +1,549 @@
+"""One resolved capture policy for the decisions layer.
+
+Everything that decides whether a capture source runs, or whether it may call a
+model, reads a :class:`DecisionPolicy` built here. CLI, server, the index
+pipeline and the session miner share this module so a source cannot be enabled
+in one surface and invisible in another, which is how the three hand-copied
+source lists in ``provenance`` already drifted.
+
+Resolution is pure: dict in, frozen dataclass out, no I/O and no provider
+knowledge. Provider availability enters only at :meth:`DecisionPolicy.runtime`,
+because the same policy resolves identically on a machine with no API key.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from typing import Any, Literal
+
+from repowise.core.analysis.decisions.provenance import RETIRED_SOURCES
+
+__all__ = [
+ "CAPTURE_SOURCE_KEYS",
+ "INDEX_SOURCE_KEYS",
+ "PRESETS",
+ "PRESET_NAMES",
+ "SOURCE_SPECS",
+ "DecisionPolicy",
+ "PolicyResolution",
+ "SourceRuntime",
+ "SourceSetting",
+ "SourceSpec",
+ "preset_policy",
+ "resolve_policy",
+]
+
+Authority = Literal["machine", "human"]
+SourceStatus = Literal[
+ "enabled",
+ "disabled",
+ "deterministic_only",
+ "skipped_no_provider",
+ "always_on",
+]
+
+
+@dataclass(frozen=True, slots=True)
+class SourceSpec:
+ """Static capability metadata for one capture source.
+
+ ``key`` is the wire name, and it is the name already stored on every
+ ``decision_records`` row and already accepted by ``decisions.sources`` in
+ ``.repowise/config.yaml``. Renaming it would orphan stored rows, most
+ sharply for ``comment``: ``code_comment`` is a *retired* source at rank 2
+ with legacy rows still carrying it.
+ """
+
+ key: str
+ label: str
+ description: str
+ #: Produces something with no provider configured.
+ deterministic: bool
+ #: Has a stage that calls a model.
+ llm: bool
+ authority: Authority
+ default_enabled: bool
+ #: False for authority-bearing entry routes, which are not machine capture
+ #: and so have nothing to switch off.
+ togglable: bool = True
+
+
+SOURCE_SPECS: tuple[SourceSpec, ...] = (
+ SourceSpec(
+ key="inline_marker",
+ label="Inline markers",
+ description="WHY:/DECISION:/TRADEOFF: comment markers in source files.",
+ deterministic=True,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="git_archaeology",
+ label="Git archaeology",
+ description="Commit messages carrying one of the decision verbs.",
+ deterministic=False,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="adr",
+ label="ADR files",
+ description="Nygard and MADR architecture decision records.",
+ deterministic=True,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="pr",
+ label="Pull request bodies",
+ description="Squash-merge and PR bodies that read as a description.",
+ deterministic=False,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="comment",
+ label="Comment archaeology",
+ description="Rationale prose in comments on high-centrality files.",
+ deterministic=False,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="session",
+ label="Agent sessions",
+ description="Durable choices mined from local coding-agent transcripts.",
+ deterministic=True,
+ llm=True,
+ authority="machine",
+ default_enabled=True,
+ ),
+ SourceSpec(
+ key="cli",
+ label="Manual entry",
+ description="Decisions you recorded yourself. Always available.",
+ deterministic=True,
+ llm=False,
+ authority="human",
+ default_enabled=True,
+ togglable=False,
+ ),
+)
+
+_SPECS_BY_KEY: dict[str, SourceSpec] = {spec.key: spec for spec in SOURCE_SPECS}
+
+#: Machine capture sources, in extraction order. ``cli`` is excluded: manual
+#: entry is an authority route, not something a capture run performs.
+CAPTURE_SOURCE_KEYS: tuple[str, ...] = tuple(
+ spec.key for spec in SOURCE_SPECS if spec.authority == "machine"
+)
+
+#: Index-time sources, in the order ``DecisionExtractor.extract_all`` runs them.
+#: ``session`` is mined separately by the transcript miner.
+INDEX_SOURCE_KEYS: tuple[str, ...] = (
+ "inline_marker",
+ "git_archaeology",
+ "adr",
+ "pr",
+ "comment",
+)
+
+
+@dataclass(frozen=True, slots=True)
+class SourceSetting:
+ """Per-source configuration, already merged with defaults."""
+
+ enabled: bool
+ llm: bool
+
+
+def _preset(**overrides: SourceSetting) -> dict[str, SourceSetting]:
+ base = {
+ spec.key: SourceSetting(enabled=spec.default_enabled, llm=spec.llm)
+ for spec in SOURCE_SPECS
+ }
+ base.update(overrides)
+ return base
+
+
+_ON = SourceSetting(enabled=True, llm=True)
+_LOCAL = SourceSetting(enabled=True, llm=False)
+_OFF = SourceSetting(enabled=False, llm=False)
+
+#: Named conveniences over the same policy. A preset is only a way to write
+#: several settings at once; nothing downstream branches on the preset name.
+PRESETS: dict[str, dict[str, Any]] = {
+ "off": {
+ "enabled": False,
+ "llm": True,
+ "sources": _preset(**dict.fromkeys(CAPTURE_SOURCE_KEYS, _OFF)),
+ },
+ "local_only": {
+ "enabled": True,
+ "llm": False,
+ "sources": _preset(
+ inline_marker=_LOCAL,
+ adr=_LOCAL,
+ session=_LOCAL,
+ git_archaeology=_OFF,
+ pr=_OFF,
+ comment=_OFF,
+ ),
+ },
+ "balanced": {
+ "enabled": True,
+ "llm": True,
+ "sources": _preset(comment=_OFF),
+ },
+ "full": {
+ "enabled": True,
+ "llm": True,
+ "sources": _preset(**dict.fromkeys(CAPTURE_SOURCE_KEYS, _ON)),
+ },
+}
+
+PRESET_NAMES: tuple[str, ...] = tuple(PRESETS)
+
+#: What an absent ``decisions:`` block resolves to. Deliberately every source
+#: on with the model enabled, because that is what a repo indexed before this
+#: module existed already did, and a config-less repo must not change behavior
+#: on upgrade. New repos pick a preset explicitly instead of inheriting a
+#: different hidden default.
+_LEGACY_DEFAULT = PRESETS["full"]
+
+
+@dataclass(frozen=True, slots=True)
+class SourceRuntime:
+ """A source's resolved state, with provider availability folded in."""
+
+ key: str
+ label: str
+ description: str
+ authority: Authority
+ deterministic: bool
+ supports_llm: bool
+ togglable: bool
+ enabled: bool
+ llm_enabled: bool
+ status: SourceStatus
+ reason: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "key": self.key,
+ "label": self.label,
+ "description": self.description,
+ "authority": self.authority,
+ "deterministic": self.deterministic,
+ "supports_llm": self.supports_llm,
+ "togglable": self.togglable,
+ "enabled": self.enabled,
+ "llm_enabled": self.llm_enabled,
+ "status": self.status,
+ "reason": self.reason,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class DecisionPolicy:
+ """The resolved capture policy for one repository."""
+
+ enabled: bool
+ llm: bool
+ sources: dict[str, SourceSetting]
+
+ # -- queries ---------------------------------------------------------
+
+ def source_enabled(self, key: str) -> bool:
+ """Whether *key* may capture at all."""
+ spec = _SPECS_BY_KEY.get(key)
+ if spec is None:
+ return False
+ if not spec.togglable:
+ return True
+ if not self.enabled:
+ return False
+ setting = self.sources.get(key)
+ return bool(setting and setting.enabled)
+
+ def llm_allowed(self, key: str) -> bool:
+ """Whether *key* may make a decision-extraction model call.
+
+ The global switch wins over the per-source one, so ``llm: false`` is a
+ single provable statement about the whole layer rather than a default
+ several sources can each opt back out of.
+ """
+ if not self.llm or not self.source_enabled(key):
+ return False
+ spec = _SPECS_BY_KEY.get(key)
+ if spec is None or not spec.llm:
+ return False
+ setting = self.sources.get(key)
+ return bool(setting and setting.llm)
+
+ def enabled_index_sources(self) -> tuple[str, ...]:
+ """Enabled sources for ``DecisionExtractor.extract_all``, in run order.
+
+ A source with no deterministic stage is dropped when the model is off:
+ it would run, call nothing and return zero, which reads on screen as a
+ repo with no PRs rather than a switch the user set.
+ """
+ return tuple(
+ key
+ for key in INDEX_SOURCE_KEYS
+ if self.source_enabled(key)
+ and (self.llm_allowed(key) or _SPECS_BY_KEY[key].deterministic)
+ )
+
+ def any_llm_allowed(self) -> bool:
+ return any(self.llm_allowed(key) for key in CAPTURE_SOURCE_KEYS)
+
+ # -- projections -----------------------------------------------------
+
+ def preset_name(self) -> str:
+ """The preset this policy equals, or ``custom``."""
+ for name, spec in PRESETS.items():
+ if (
+ self.enabled == spec["enabled"]
+ and self.llm == spec["llm"]
+ and self.sources == spec["sources"]
+ ):
+ return name
+ return "custom"
+
+ def runtime(self, *, provider_available: bool) -> tuple[SourceRuntime, ...]:
+ """Per-source state for reporting, with a reason for every non-run."""
+ out: list[SourceRuntime] = []
+ for spec in SOURCE_SPECS:
+ enabled = self.source_enabled(spec.key)
+ llm_enabled = self.llm_allowed(spec.key)
+ status, reason = self._status_for(spec, enabled, llm_enabled, provider_available)
+ out.append(
+ SourceRuntime(
+ key=spec.key,
+ label=spec.label,
+ description=spec.description,
+ authority=spec.authority,
+ deterministic=spec.deterministic,
+ supports_llm=spec.llm,
+ togglable=spec.togglable,
+ enabled=enabled,
+ llm_enabled=llm_enabled and provider_available,
+ status=status,
+ reason=reason,
+ )
+ )
+ return tuple(out)
+
+ def _status_for(
+ self,
+ spec: SourceSpec,
+ enabled: bool,
+ llm_enabled: bool,
+ provider_available: bool,
+ ) -> tuple[SourceStatus, str]:
+ if not spec.togglable:
+ return "always_on", "Manual entry is always available."
+ if not self.enabled:
+ return "disabled", "Decision capture is off for this repository."
+ if not enabled:
+ return "disabled", "This source is switched off."
+ if not spec.llm:
+ return "enabled", "Runs without a model."
+ if not llm_enabled:
+ if not self.llm:
+ reason = "Decision LLM extraction is off."
+ else:
+ reason = "Model structuring is off for this source."
+ if spec.deterministic:
+ return "deterministic_only", f"{reason} The deterministic stage still runs."
+ return "disabled", f"{reason} This source has no deterministic stage."
+ if not provider_available:
+ if spec.deterministic:
+ return "deterministic_only", (
+ "No LLM provider is configured. The deterministic stage still runs."
+ )
+ return "skipped_no_provider", "No LLM provider is configured."
+ return "enabled", "Runs with model structuring."
+
+ def to_config_block(self) -> dict[str, Any]:
+ """The ``decisions:`` mapping to write back to ``config.yaml``.
+
+ A source whose setting equals its capability default is written as a
+ bare bool, so an untouched config stays as short as the user left it.
+ """
+ sources: dict[str, Any] = {}
+ for spec in SOURCE_SPECS:
+ if not spec.togglable:
+ continue
+ setting = self.sources.get(spec.key, SourceSetting(spec.default_enabled, spec.llm))
+ if setting.llm == spec.llm:
+ sources[spec.key] = setting.enabled
+ else:
+ sources[spec.key] = {"enabled": setting.enabled, "llm": setting.llm}
+ return {"enabled": self.enabled, "llm": self.llm, "sources": sources}
+
+ def to_dict(self, *, provider_available: bool = True) -> dict[str, Any]:
+ """The JSON payload shared by ``decision config show`` and the API."""
+ return {
+ "enabled": self.enabled,
+ "llm": self.llm,
+ "preset": self.preset_name(),
+ "sources": [rt.to_dict() for rt in self.runtime(provider_available=provider_available)],
+ }
+
+ # -- mutations (all return a new policy) -----------------------------
+
+ def with_source(self, key: str, *, enabled: bool | None = None, llm: bool | None = None):
+ spec = _SPECS_BY_KEY.get(key)
+ if spec is None:
+ raise ValueError(f"Unknown decision source: {key}")
+ if not spec.togglable:
+ raise ValueError(f"{key} is an authority route and cannot be switched off")
+ current = self.sources.get(key, SourceSetting(spec.default_enabled, spec.llm))
+ merged = SourceSetting(
+ enabled=current.enabled if enabled is None else enabled,
+ llm=current.llm if llm is None else llm,
+ )
+ sources = dict(self.sources)
+ sources[key] = merged
+ return replace(self, sources=sources)
+
+ def with_llm(self, value: bool) -> DecisionPolicy:
+ return replace(self, llm=value)
+
+ def with_enabled(self, value: bool) -> DecisionPolicy:
+ return replace(self, enabled=value)
+
+
+@dataclass(frozen=True, slots=True)
+class PolicyResolution:
+ """A resolved policy plus everything the user should be told about it."""
+
+ policy: DecisionPolicy
+ #: Recoverable problems: unknown keys, wrong types. Never discarded
+ #: silently, because a typo'd source name reads as a working switch.
+ warnings: tuple[str, ...] = ()
+ #: Keys carried through from the legacy shape, for the migration notice.
+ legacy_keys: tuple[str, ...] = ()
+
+
+def preset_policy(name: str) -> DecisionPolicy:
+ """The policy a named preset resolves to."""
+ spec = PRESETS.get(name)
+ if spec is None:
+ raise ValueError(f"Unknown preset: {name}. Choose one of {', '.join(PRESET_NAMES)}.")
+ return DecisionPolicy(
+ enabled=bool(spec["enabled"]),
+ llm=bool(spec["llm"]),
+ sources=dict(spec["sources"]),
+ )
+
+
+def _as_bool(value: Any) -> bool | None:
+ return value if isinstance(value, bool) else None
+
+
+def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
+ """Resolve a loaded ``.repowise/config.yaml`` dict into one policy.
+
+ Accepts both the legacy shape (``session_mining: bool`` and
+ ``sources.<name>: bool``) and the current one, and resolves the legacy
+ shape to exactly the behavior it had before this module existed.
+ """
+ warnings: list[str] = []
+ legacy: list[str] = []
+
+ raw = (repo_config or {}).get("decisions")
+ if raw is None:
+ raw = {}
+ elif not isinstance(raw, dict):
+ warnings.append("`decisions:` is not a mapping; ignoring it and using defaults.")
+ raw = {}
+
+ preset_name = raw.get("preset")
+ if preset_name is not None and preset_name not in PRESETS:
+ warnings.append(f"Unknown preset {preset_name!r}; ignoring it.")
+ preset_name = None
+ base = PRESETS[preset_name] if preset_name else _LEGACY_DEFAULT
+
+ enabled = _as_bool(raw.get("enabled"))
+ if enabled is None:
+ if "enabled" in raw:
+ warnings.append("`decisions.enabled` is not a boolean; ignoring it.")
+ enabled = bool(base["enabled"])
+
+ llm = _as_bool(raw.get("llm"))
+ if llm is None:
+ if "llm" in raw:
+ warnings.append("`decisions.llm` is not a boolean; ignoring it.")
+ llm = bool(base["llm"])
+
+ sources: dict[str, SourceSetting] = dict(base["sources"])
+
+ raw_sources = raw.get("sources")
+ if raw_sources is None:
+ raw_sources = {}
+ elif not isinstance(raw_sources, dict):
+ warnings.append("`decisions.sources:` is not a mapping; ignoring it.")
+ raw_sources = {}
+
+ for key, value in raw_sources.items():
+ spec = _SPECS_BY_KEY.get(str(key))
+ if spec is None or not spec.togglable:
+ if str(key) in RETIRED_SOURCES:
+ # These were documented switches. Say they are gone rather than
+ # implying the user typed something wrong.
+ warnings.append(
+ f"`decisions.sources.{key}` names a retired source that no "
+ "longer extracts; it has no effect."
+ )
+ else:
+ warnings.append(f"Unknown decision source {key!r} in config; ignoring it.")
+ continue
+ current = sources.get(spec.key, SourceSetting(spec.default_enabled, spec.llm))
+ if isinstance(value, bool):
+ sources[spec.key] = SourceSetting(enabled=value, llm=current.llm)
+ elif isinstance(value, dict):
+ src_enabled = _as_bool(value.get("enabled"))
+ src_llm = _as_bool(value.get("llm"))
+ for field in set(value) - {"enabled", "llm"}:
+ warnings.append(f"Unknown key `decisions.sources.{spec.key}.{field}`; ignoring it.")
+ sources[spec.key] = SourceSetting(
+ enabled=current.enabled if src_enabled is None else src_enabled,
+ llm=current.llm if src_llm is None else src_llm,
+ )
+ else:
+ warnings.append(
+ f"`decisions.sources.{spec.key}` must be a boolean or a mapping; ignoring it."
+ )
+
+ # Legacy: session_mining gated the whole transcript miner. It only narrows,
+ # so it is ANDed with sources.session rather than shadowed by it. Letting an
+ # explicit `sources.session: true` win would start reading transcripts on a
+ # config that had switched them off, which is the one thing this resolver
+ # must never do.
+ session_mining = raw.get("session_mining")
+ if session_mining is not None:
+ legacy.append("session_mining")
+ if isinstance(session_mining, bool):
+ current = sources["session"]
+ sources["session"] = SourceSetting(
+ enabled=current.enabled and session_mining, llm=current.llm
+ )
+ else:
+ warnings.append("`decisions.session_mining` is not a boolean; ignoring it.")
+
+ for field in set(raw) - {"preset", "enabled", "llm", "sources", "session_mining"}:
+ warnings.append(f"Unknown key `decisions.{field}`; ignoring it.")
+
+ return PolicyResolution(
+ policy=DecisionPolicy(enabled=enabled, llm=llm, sources=sources),
+ warnings=tuple(warnings),
+ legacy_keys=tuple(legacy),
+ )
diff --git a/packages/core/src/repowise/core/analysis/decisions/policy_store.py b/packages/core/src/repowise/core/analysis/decisions/policy_store.py
new file mode 100644
index 000000000..b166e149e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/policy_store.py
@@ -0,0 +1,83 @@
+"""Reading and writing the decision policy in ``.repowise/config.yaml``.
+
+Kept apart from :mod:`policy` so resolution stays a pure function: this is the
+only module in the layer that touches the filesystem.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+from typing import Any
+
+from repowise.core.repo_config import load_repo_config, save_repo_config
+
+from .policy import PRESETS, DecisionPolicy, PolicyResolution, resolve_policy
+
+__all__ = ["PolicyConflictError", "load_policy", "policy_etag", "write_policy"]
+
+
+class PolicyConflictError(RuntimeError):
+ """A policy write lost a race with another writer."""
+
+
+def load_policy(repo_path: Path | str) -> PolicyResolution:
+ """Resolve the policy for a repo, warnings included."""
+ return resolve_policy(load_repo_config(repo_path))
+
+
+def policy_etag(policy: DecisionPolicy) -> str:
+ """A short hash of the resolved policy, for optimistic concurrency.
+
+ Derived from the resolved block rather than the config file so unrelated
+ edits (a provider change, a coverage path) do not invalidate a settings
+ form the user has open.
+ """
+ payload = json.dumps(policy.to_config_block(), sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def write_policy(
+ repo_path: Path | str,
+ policy: DecisionPolicy,
+ *,
+ expected_etag: str | None = None,
+) -> PolicyResolution:
+ """Persist *policy*, preserving every unrelated key, and re-resolve it.
+
+ Validates by round-tripping: the block is resolved back before the write,
+ and a mismatch raises rather than persisting something that would read as a
+ different policy than the caller set. With *expected_etag*, a concurrent
+ change to the same block raises :class:`PolicyConflictError` and writes nothing.
+ """
+ config = load_repo_config(repo_path)
+
+ if expected_etag is not None:
+ current = resolve_policy(config).policy
+ if policy_etag(current) != expected_etag:
+ raise PolicyConflictError(
+ "The decision settings changed since they were read. Reload and retry."
+ )
+
+ block = policy.to_config_block()
+ round_tripped = resolve_policy({"decisions": block}).policy
+ if round_tripped != policy:
+ raise ValueError("Resolved policy does not round-trip through the config block.")
+
+ merged: dict[str, Any] = dict(config)
+ existing = merged.get("decisions")
+ decisions = dict(existing) if isinstance(existing, dict) else {}
+ # `session_mining` is now expressed as `sources.session`; leaving it behind
+ # would let a stale legacy key contradict the block written above.
+ decisions.pop("session_mining", None)
+ decisions.update(block)
+ preset = policy.preset_name()
+ if preset in PRESETS:
+ decisions["preset"] = preset
+ else:
+ decisions.pop("preset", None)
+ merged["decisions"] = decisions
+
+ save_repo_config(repo_path, merged)
+ return resolve_policy(merged)
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index ab16ebba8..6d44288e6 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -305,17 +305,16 @@ async def _run_decision_extraction(
) -> Any | None:
"""Extract architectural decisions from source and git history."""
try:
- from repowise.core.analysis.decision_extractor import (
- DecisionExtractor,
- enabled_source_names,
- )
+ from repowise.core.analysis.decision_extractor import DecisionExtractor
+ from repowise.core.analysis.decisions.policy import resolve_policy
from repowise.core.repo_config import load_repo_config
# Sources run concurrently inside extract_all(); drive a determinate
- # bar so users see live progress. ``decisions.sources`` in the repo
- # config can disable individual sources (#751).
+ # bar so users see live progress. The resolved policy decides which
+ # sources run and which of them may call a model.
repo_cfg = load_repo_config(repo_path)
- enabled = enabled_source_names(repo_cfg)
+ policy = resolve_policy(repo_cfg).policy
+ enabled = policy.enabled_index_sources()
if progress:
progress.on_phase_start("decisions", len(enabled))
@@ -326,6 +325,7 @@ async def _run_decision_extraction(
git_meta_map=git_meta_map,
parsed_files=parsed_files,
source_map=source_map,
+ policy=policy,
)
def _decision_step(_source: str) -> None:
@@ -344,18 +344,17 @@ async def _run_decision_extraction(
# re-gating without a source_text would wipe its verification. A
# server-side index has no transcript directory and no-ops here.
try:
- from repowise.core.sessions.miners.decisions import (
- mine_session_decisions,
- session_mining_enabled,
- )
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
# Not gated on a provider: the same pass records transcript
# episodes, which need no model, and gating the read on a key
# would leave a keyless index with no transcript supply at all.
- # The miner skips its own structuring pass when provider is None.
- if session_mining_enabled(repo_cfg):
+ # The miner skips its own structuring pass when provider is None,
+ # which is also how the policy's LLM switch is enforced here.
+ if policy.source_enabled("session"):
+ session_provider = llm_client if policy.llm_allowed("session") else None
session_decisions = await asyncio.wait_for(
- mine_session_decisions(repo_path, provider=llm_client),
+ mine_session_decisions(repo_path, provider=session_provider),
timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
)
if session_decisions:
@@ -405,10 +404,27 @@ async def _run_decision_extraction(
# its ``degraded`` list, so both runs report an outage the same
# way instead of one of them printing a reassuring zero.
failures = getattr(report, "failures", {}) or {}
+ # Sources that never ran, and why. Built first because a source
+ # listed here must not also appear as an honest zero below: with no
+ # API key the three model-only sources return [] immediately, and
+ # reporting that as "nothing found" is the confusion this split
+ # exists to remove.
+ runtime = {
+ rt.key: rt
+ for rt in policy.runtime(provider_available=llm_client is not None)
+ }
+ not_run = {
+ key
+ for key, rt in runtime.items()
+ if rt.togglable and rt.status in ("disabled", "skipped_no_provider")
+ }
empty = [
label.removeprefix("from ")
for source, label in _DECISION_SOURCE_LABELS
- if source in enabled and not bs.get(source) and source not in failures
+ if source in enabled
+ and source not in not_run
+ and not bs.get(source)
+ and source not in failures
]
if empty:
progress.on_message("info", f"→ Nothing found in: {', '.join(empty)}")
@@ -419,6 +435,13 @@ async def _run_decision_extraction(
f"Decision source {label.removeprefix('from ')} failed, "
f"so this run found none there: {failures[source]}",
)
+ skipped = [
+ f"{label.removeprefix('from ')} ({runtime[source].reason.rstrip('.')})"
+ for source, label in _DECISION_SOURCE_LABELS
+ if source in not_run
+ ]
+ if skipped:
+ progress.on_message("info", f"→ Not run: {', '.join(skipped)}")
_phase_done(progress, "decisions")
return report
diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.py
index c2ca5dc7d..0d807070e 100644
--- a/packages/core/src/repowise/core/providers/llm/registry.py
+++ b/packages/core/src/repowise/core/providers/llm/registry.py
@@ -33,6 +33,7 @@ from __future__ import annotations
import importlib
import os
from collections.abc import Callable
+from pathlib import Path
from typing import Any
from repowise.core.providers.llm.base import BaseProvider
@@ -326,3 +327,23 @@ def list_providers() -> list[str]:
Includes both built-in and runtime-registered custom providers.
"""
return sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))
+
+
+def provider_available_for_repo(repo_path: Path | str) -> bool:
+ """Whether a provider would resolve for *repo_path*, constructing nothing.
+
+ Mirrors the CLI's resolution order: an explicit choice is checked for
+ usability, auto-detection asks only whether credentials name a provider.
+ Reporting-only, so it answers False rather than raising on a broken config.
+ """
+ try:
+ from repowise.core.repo_config import load_repo_config
+
+ configured = (os.environ.get("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)
+ except Exception:
+ return False
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index a77286752..c700ae91b 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextlib
from pathlib import Path
from typing import Any
@@ -68,15 +69,36 @@ def save_repo_config(repo_path: Path | str, config: dict[str, Any]) -> None:
unrelated keys are preserved; this writer just serializes the final dict.
Key order is preserved and flow style is block style, to match the files the
CLI writes.
+
+ The write is atomic: serialize to a sibling temp file, fsync, then
+ ``os.replace``. A crash or a serializer failure part-way leaves the previous
+ bytes intact rather than a truncated config, which every reader would take
+ for "no provider, no coverage settings, defaults everywhere".
"""
+ import os
+ import tempfile
+
import yaml # type: ignore[import-untyped]
cfg_dir = get_repowise_dir(repo_path)
cfg_dir.mkdir(parents=True, exist_ok=True)
- (cfg_dir / CONFIG_FILENAME).write_text(
- yaml.dump(config, default_flow_style=False, sort_keys=False),
- encoding="utf-8",
- )
+ target = cfg_dir / CONFIG_FILENAME
+ payload = yaml.dump(config, default_flow_style=False, sort_keys=False)
+
+ fd, tmp_name = tempfile.mkstemp(dir=str(cfg_dir), prefix=".config.", suffix=".tmp")
+ try:
+ # No explicit newline: the previous writer used the platform default,
+ # and config_fingerprint hashes raw bytes, so pinning LF here would
+ # move the fingerprint of every existing Windows config on first save.
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_name, target)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
def config_fingerprint(repo_path: Path | str) -> str:
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 1e7c959b4..eefbaf863 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -56,6 +56,7 @@ from typing import Any
import structlog
from repowise.core.analysis.decisions.extractor import ExtractedDecision
+from repowise.core.analysis.decisions.policy import resolve_policy
from repowise.core.analysis.decisions.provenance import (
compute_confidence,
rank_for_source,
@@ -497,12 +498,13 @@ _LLM_CHUNK = 12
def session_mining_enabled(repo_config: dict[str, Any] | None) -> bool:
- """Resolve the ``decisions.session_mining`` config gate (default on)."""
- cfg = repo_config or {}
- decisions_cfg = cfg.get("decisions") or {}
- if not isinstance(decisions_cfg, dict):
- return True
- return decisions_cfg.get("session_mining", True) is not False
+ """Whether the transcript miner may run at all.
+
+ Resolved from the shared policy, which still honours the legacy
+ ``decisions.session_mining`` boolean.
+ """
+ return resolve_policy(repo_config).policy.source_enabled("session")
+
def _candidates_block(raws: list[dict[str, Any]]) -> str:
@@ -601,13 +603,15 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted
"""decision_records-ready members for one promotable staging row.
One member per observing session (capped) so each session becomes its own
- evidence row via the ``bulk_upsert_decisions`` accretion path. The first
- promotion lands ``active``; later observation-driven re-emissions land
- ``proposed``, which adds evidence but can never overwrite a status a
- human (or the evolution judge) set deliberately.
+ evidence row via the ``bulk_upsert_decisions`` accretion path.
+
+ Every member lands ``proposed``, first promotion included. Recurrence
+ across sessions is evidence that a candidate is worth reviewing, not an
+ acceptance event: authority comes from a person confirming the record.
+ ``first_promotion`` still gates re-emission in the staging store, so a
+ recurring candidate accretes evidence without re-proposing itself.
"""
structured = row["structured"]
- status = "active" if row["first_promotion"] else "proposed"
files = relative_files(structured.get("affected_files") or row["files"], repo_root)
modules = resolve_module_nodes(files)
confidence = compute_confidence(
@@ -626,7 +630,7 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted
source="session",
evidence_commits=[sid] if sid else [],
confidence=confidence,
- status=status,
+ status="proposed",
source_quote=structured.get("source_quote", ""),
verification=structured.get("verification", "unverified"),
)
@@ -643,7 +647,6 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted
INJECTION_EVAL_MIN_AGE_SECONDS = 3600.0
-
async def apply_injection_feedback(
db_session: Any,
repository_id: str,
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 0d8bea5d6..909966747 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -463,12 +463,19 @@ def _build_origin_story(
def _sibling_coverage(file_path: str, governing: list[dict], all_decisions: list) -> float | None:
- """Fraction of sibling-file decisions that also cover *file_path* (None if no siblings)."""
+ """Fraction of sibling-file decisions that also cover *file_path* (None if no siblings).
+
+ Both sides count accepted records only. Filtering the numerator alone read
+ a directory whose siblings are covered by proposals as one this file
+ diverges from, when nothing there has been agreed to either.
+ """
dir_path = "/".join(file_path.split("/")[:-1])
sibling_decision_ids = set()
file_decision_titles = {d["title"] for d in governing}
for d in all_decisions:
+ if getattr(d, "status", None) != "active":
+ continue
affected = json.loads(d.affected_files_json)
for af in affected:
af_dir = "/".join(af.split("/")[:-1])
@@ -497,33 +504,42 @@ def _active_alignment(active: list, dir_path: str, sibling_coverage: float | Non
def _alignment_score(
- governing: list[dict],
- active: list,
+ accepted: list,
deprecated: list,
stale: list,
- proposed: list,
+ candidates: list,
dir_path: str,
sibling_coverage: float | None,
) -> tuple:
- """Derive the (score, explanation) tuple from decision status counts."""
- if deprecated and not active and not proposed:
+ """Derive the (score, explanation) tuple from accepted decisions.
+
+ Only accepted (``active``) records score. A proposed record is a candidate
+ awaiting review: counting one as governance let a machine-inferred record
+ report a file as aligned with a decision nobody had agreed to.
+ """
+ if stale and len(stale) >= len(accepted) / 2:
return "low", (
- "All governing decisions are deprecated/superseded. "
- "This file likely contains technical debt that should be migrated."
+ f"{len(stale)} of {len(accepted)} accepted decision(s) are stale. "
+ f"The architectural rationale may no longer apply."
+ )
+ if accepted:
+ return _active_alignment(accepted, dir_path, sibling_coverage)
+ if deprecated:
+ trailer = (
+ f" {len(candidates)} proposed candidate(s) await review."
+ if candidates
+ else ""
)
- if stale and len(stale) >= len(governing) / 2:
return "low", (
- f"{len(stale)} of {len(governing)} governing decision(s) are stale. "
- f"The architectural rationale may no longer apply."
+ "Every accepted decision here is deprecated/superseded. "
+ "This file likely contains technical debt that should be migrated." + trailer
)
- if active:
- return _active_alignment(active, dir_path, sibling_coverage)
- if proposed:
- return "medium", (
- f"Governed by {len(proposed)} proposed (unreviewed) decision(s). "
- f"Patterns are established but not yet formally approved."
+ if candidates:
+ return "none", (
+ f"No accepted decision governs this file. {len(candidates)} proposed "
+ f"candidate(s) mention it, awaiting review."
)
- return "medium", f"Governed by {len(governing)} decision(s) with mixed status."
+ return "none", "No accepted decision governs this file."
def _compute_alignment(
@@ -541,29 +557,35 @@ def _compute_alignment(
),
"governing_count": 0,
"active_count": 0,
+ "candidate_count": 0,
"deprecated_count": 0,
"stale_count": 0,
"sibling_coverage": None,
}
- # Count decision statuses
- active = [d for d in governing if d["status"] == "active"]
+ accepted = [d for d in governing if d["status"] == "active"]
deprecated = [d for d in governing if d["status"] in ("deprecated", "superseded")]
- stale = [d for d in governing if d.get("staleness_score", 0) > 0.5]
- proposed = [d for d in governing if d["status"] == "proposed"]
+ stale = [d for d in accepted if d.get("staleness_score", 0) > 0.5]
+ candidates = [d for d in governing if d["status"] == "proposed"]
dir_path = "/".join(file_path.split("/")[:-1])
- sibling_coverage = _sibling_coverage(file_path, governing, all_decisions)
+ # Scoped to accepted records for the same reason the score is: a sibling
+ # pattern established only by proposals is not an established pattern.
+ sibling_coverage = _sibling_coverage(file_path, accepted, all_decisions)
score, explanation = _alignment_score(
- governing, active, deprecated, stale, proposed, dir_path, sibling_coverage
+ accepted, deprecated, stale, candidates, dir_path, sibling_coverage
)
return {
"score": score,
"explanation": explanation,
+ # Unchanged meaning: how many records name this file at all. The
+ # authority split is carried by active_count / candidate_count, which
+ # is what the score reads.
"governing_count": len(governing),
- "active_count": len(active),
+ "active_count": len(accepted),
+ "candidate_count": len(candidates),
"deprecated_count": len(deprecated),
"stale_count": len(stale),
"sibling_coverage": round(sibling_coverage, 2) if sibling_coverage is not None else None,
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 8d4336431..a5bebdab4 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from pathlib import Path
+
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -22,6 +24,9 @@ from repowise.server.schemas import (
DecisionLineageEntry,
DecisionLineageResponse,
DecisionRecordResponse,
+ DecisionSettings,
+ DecisionSettingsUpdate,
+ DecisionSourceState,
DecisionStatusUpdate,
)
from repowise.server.schemas.decisions import EvidencePreview
@@ -216,6 +221,124 @@ async def get_decision_graph(
return DecisionGraphResponse(nodes=nodes, decision_edges=decision_edges, code_edges=code_edges)
+# ---------------------------------------------------------------------------
+# Capture policy
+#
+# Declared before the dynamic ``/{decision_id}`` GET so the static ``settings``
+# path wins. Backed by ``.repowise/config.yaml``, so it needs a local checkout.
+# ---------------------------------------------------------------------------
+
+
+async def _local_repo_path(session: AsyncSession, repo_id: str) -> Path:
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None or not repo.local_path:
+ raise HTTPException(status_code=404, detail=f"repository not found: {repo_id}")
+ repo_path = Path(repo.local_path)
+ if not repo_path.exists():
+ raise HTTPException(
+ status_code=404, detail="repository checkout not accessible on this server"
+ )
+ return repo_path
+
+
+def _settings_payload(repo_path: Path, resolution) -> DecisionSettings:
+ from repowise.core.analysis.decisions.policy_store import policy_etag
+
+ policy = resolution.policy
+ available = _provider_available(repo_path)
+ return DecisionSettings(
+ enabled=policy.enabled,
+ llm=policy.llm,
+ preset=policy.preset_name(),
+ sources=[
+ DecisionSourceState(**rt.to_dict())
+ for rt in policy.runtime(provider_available=available)
+ ],
+ provider_available=available,
+ warnings=list(resolution.warnings),
+ legacy_keys=list(resolution.legacy_keys),
+ etag=policy_etag(policy),
+ )
+
+
+def _load_policy_or_400(repo_path: Path):
+ """Resolve the policy, turning an unparseable config into a 400.
+
+ A malformed ``decisions:`` block is a warning, but a malformed *file* never
+ reaches the resolver, so it would otherwise surface as a 500 with nothing
+ the user could act on.
+ """
+ from repowise.core.analysis.decisions.policy_store import load_policy
+ from repowise.core.repo_config import RepoConfigError
+
+ try:
+ return load_policy(repo_path)
+ except RepoConfigError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+def _provider_available(repo_path: Path) -> bool:
+ """Whether a provider resolves, without constructing one."""
+ from repowise.core.providers.llm.registry import provider_available_for_repo
+
+ return provider_available_for_repo(repo_path)
+
+
+ "/api/repos/{repo_id}/decisions/settings",
+ response_model=DecisionSettings,
+)
+async def get_decision_settings(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> DecisionSettings:
+ """The resolved decision capture policy and source registry."""
+ repo_path = await _local_repo_path(session, repo_id)
+ return _settings_payload(repo_path, _load_policy_or_400(repo_path))
+
+
+ "/api/repos/{repo_id}/decisions/settings",
+ response_model=DecisionSettings,
+)
+async def update_decision_settings(
+ repo_id: str,
+ body: DecisionSettingsUpdate,
+ session: AsyncSession = Depends(get_db_session),
+) -> DecisionSettings:
+ """Apply a partial policy change to ``.repowise/config.yaml``.
+
+ Omitted fields keep their current value, so a UI can send one switch.
+ ``preset`` is applied before the per-source overrides.
+ """
+ from repowise.core.analysis.decisions.policy import preset_policy
+ from repowise.core.analysis.decisions.policy_store import PolicyConflictError, write_policy
+
+ repo_path = await _local_repo_path(session, repo_id)
+ policy = _load_policy_or_400(repo_path).policy
+
+ if body.preset is not None:
+ try:
+ policy = preset_policy(body.preset)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if body.enabled is not None:
+ policy = policy.with_enabled(body.enabled)
+ if body.llm is not None:
+ policy = policy.with_llm(body.llm)
+ for key, patch in (body.sources or {}).items():
+ try:
+ policy = policy.with_source(key, enabled=patch.enabled, llm=patch.llm)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ try:
+ resolution = write_policy(repo_path, policy, expected_etag=body.etag)
+ except PolicyConflictError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return _settings_payload(repo_path, resolution)
+
+
@router.get(
"/api/repos/{repo_id}/decisions/{decision_id}",
response_model=DecisionRecordResponse,
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index a628c7e20..ca39c71c4 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -87,6 +87,10 @@ from .decisions import (
DecisionLineageEntry,
DecisionLineageResponse,
DecisionRecordResponse,
+ DecisionSettings,
+ DecisionSettingsUpdate,
+ DecisionSourcePatch,
+ DecisionSourceState,
DecisionStatusUpdate,
)
from .episodes import (
@@ -348,6 +352,10 @@ __all__ = [
"DecisionLineageEntry",
"DecisionLineageResponse",
"DecisionRecordResponse",
+ "DecisionSettings",
+ "DecisionSettingsUpdate",
+ "DecisionSourcePatch",
+ "DecisionSourceState",
"DecisionStatusUpdate",
"DependencyPathResponse",
"DirectRiskEntry",
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index 30316d8e1..343abfcfd 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
from datetime import datetime
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict
from repowise.core.analysis.decisions.scope import derive_decision_scope
@@ -247,3 +247,73 @@ class DecisionLineageResponse(BaseModel):
"""The supersedes/refines chain, root first."""
lineage: list[DecisionLineageEntry] = []
+
+
+# ---------------------------------------------------------------------------
+# Capture policy
+# ---------------------------------------------------------------------------
+
+
+class DecisionSourceState(BaseModel):
+ """One capture source's capabilities and resolved state."""
+
+ key: str
+ label: str
+ description: str
+ #: ``machine`` for inferred capture, ``human`` for authority routes.
+ authority: str
+ deterministic: bool
+ supports_llm: bool
+ #: False for authority routes, which have no capture to switch off.
+ togglable: bool
+ enabled: bool
+ llm_enabled: bool
+ #: enabled | disabled | deterministic_only | skipped_no_provider | always_on
+ status: str
+ reason: str
+
+
+class DecisionSettings(BaseModel):
+ """The resolved decision capture policy for one repository."""
+
+ enabled: bool = True
+ llm: bool = True
+ #: off | local_only | balanced | full | custom
+ preset: str = "full"
+ sources: list[DecisionSourceState] = []
+ provider_available: bool = True
+ #: Recoverable config problems, e.g. an unknown source key.
+ warnings: list[str] = []
+ #: Legacy keys still being honoured. A write through this endpoint
+ #: replaces them, so a settings form can say so before saving.
+ legacy_keys: list[str] = []
+ #: Changes ``etag`` whenever the resolved policy changes. Pass it back on
+ #: write to detect a concurrent edit.
+ etag: str = ""
+
+
+class DecisionSourcePatch(BaseModel):
+ """A change to one source. Omitted fields keep their current value.
+
+ ``extra="forbid"`` on purpose: an untyped mapping accepted a misspelt
+ ``{"enable": true}`` and returned 200 having changed nothing, so a UI
+ toggle read as saved when it was not.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ enabled: bool | None = None
+ llm: bool | None = None
+
+
+class DecisionSettingsUpdate(BaseModel):
+ """A partial policy write. Omitted fields keep their current value."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ enabled: bool | None = None
+ llm: bool | None = None
+ #: Applied first, so a preset plus per-source overrides works in one call.
+ preset: str | None = None
+ sources: dict[str, DecisionSourcePatch] | None = None
+ etag: str | None = None
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index b7df68c8e..ed3bf1a4e 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -193,3 +193,56 @@ export interface DecisionCounts {
superseded: number;
deprecated: number;
}
+
+/** One capture source's capabilities and resolved state. */
+export interface DecisionSourceState {
+ key: string;
+ label: string;
+ description: string;
+ /** `machine` for inferred capture, `human` for authority routes. */
+ authority: "machine" | "human";
+ deterministic: boolean;
+ supports_llm: boolean;
+ /** False for authority routes, which have no capture to switch off. */
+ togglable: boolean;
+ enabled: boolean;
+ llm_enabled: boolean;
+ status:
+ | "enabled"
+ | "disabled"
+ | "deterministic_only"
+ | "skipped_no_provider"
+ | "always_on";
+ reason: string;
+}
+
+export type DecisionPreset = "off" | "local_only" | "balanced" | "full" | "custom";
+
+/** The resolved decision capture policy for one repository. */
+export interface DecisionSettings {
+ enabled: boolean;
+ llm: boolean;
+ preset: DecisionPreset;
+ sources: DecisionSourceState[];
+ provider_available: boolean;
+ warnings: string[];
+ /** Legacy config keys still honoured. A save replaces them. */
+ legacy_keys: string[];
+ /** Pass back on write to detect a concurrent edit. */
+ etag: string;
+}
+
+/** A change to one source. Omitted fields keep their current value. */
+export interface DecisionSourcePatch {
+ enabled?: boolean;
+ llm?: boolean;
+}
+
+/** A partial policy write. Omitted fields keep their current value. */
+export interface DecisionSettingsUpdate {
+ enabled?: boolean;
+ llm?: boolean;
+ preset?: Exclude<DecisionPreset, "custom">;
+ sources?: Record<string, DecisionSourcePatch>;
+ etag?: string;
+}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 210639a21..a7865d28b 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -826,6 +826,54 @@ export interface DecisionRecordResponse {
evidence_preview?: EvidencePreview | null;
}
+/** The resolved decision capture policy for one repository. */
+export interface DecisionSettings {
+ enabled?: boolean;
+ llm?: boolean;
+ preset?: string;
+ sources?: DecisionSourceState[];
+ provider_available?: boolean;
+ warnings?: string[];
+ legacy_keys?: string[];
+ etag?: string;
+}
+
+/** A partial policy write. Omitted fields keep their current value. */
+export interface DecisionSettingsUpdate {
+ enabled?: boolean | null;
+ llm?: boolean | null;
+ preset?: string | null;
+ sources?: Record<string, DecisionSourcePatch> | null;
+ etag?: string | null;
+}
+
+/**
+ * A change to one source. Omitted fields keep their current value.
+ *
+ * ``extra="forbid"`` on purpose: an untyped mapping accepted a misspelt
+ * ``{"enable": true}`` and returned 200 having changed nothing, so a UI
+ * toggle read as saved when it was not.
+ */
+export interface DecisionSourcePatch {
+ enabled?: boolean | null;
+ llm?: boolean | null;
+}
+
+/** One capture source's capabilities and resolved state. */
+export interface DecisionSourceState {
+ key: string;
+ label: string;
+ description: string;
+ authority: string;
+ deterministic: boolean;
+ supports_llm: boolean;
+ togglable: boolean;
+ enabled: boolean;
+ llm_enabled: boolean;
+ status: string;
+ reason: string;
+}
+
/**
* PATCH body for /decisions/{id}.
*
diff --git a/tests/unit/analysis/test_decision_authority_containment.py b/tests/unit/analysis/test_decision_authority_containment.py
new file mode 100644
index 000000000..1bcc4fa5d
--- /dev/null
+++ b/tests/unit/analysis/test_decision_authority_containment.py
@@ -0,0 +1,129 @@
+"""Machine inference may propose. Only a person accepts.
+
+The two paths that let an inferred record reach governance without anyone
+agreeing to it: the session miner's first-promotion write, and the alignment
+read that counted proposals as things governing a file.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.sessions.miners.decisions import _promotion_decisions
+from repowise.server.mcp_server._helpers import _compute_alignment
+
+
+def _row(**overrides):
+ row = {
+ "structured": {
+ "decision": "Use one transaction for the full-text write",
+ "rationale": "because per-row commits dominated the tail",
+ "source_quote": "one transaction",
+ "verification": "exact",
+ "affected_files": [],
+ },
+ "title": "One transaction for the FTS write",
+ "files": [],
+ "observations": 4,
+ "sessions": ["s1", "s2"],
+ "first_promotion": True,
+ }
+ row.update(overrides)
+ return row
+
+
+class TestRecurrenceIsNotAcceptance:
+ def test_first_promotion_lands_proposed(self):
+ """Recurrence across sessions is evidence, not an acceptance event."""
+ out = _promotion_decisions(_row(first_promotion=True), Path("."))
+
+ assert out
+ assert {d.status for d in out} == {"proposed"}
+
+ def test_re_emission_also_lands_proposed(self):
+ out = _promotion_decisions(_row(first_promotion=False), Path("."))
+
+ assert {d.status for d in out} == {"proposed"}
+
+ def test_no_observation_count_produces_an_active_record(self):
+ for observations in (1, 2, 5, 50):
+ out = _promotion_decisions(_row(observations=observations), Path("."))
+ assert all(d.status != "active" for d in out)
+
+
+class TestOnlyAcceptedDecisionsGovern:
+ def _decision(self, status: str, title: str = "d", staleness: float = 0.0) -> dict:
+ return {"status": status, "title": title, "staleness_score": staleness}
+
+ def test_proposals_alone_govern_nothing(self):
+ result = _compute_alignment(
+ "src/a.py", [self._decision("proposed"), self._decision("proposed", "d2")], []
+ )
+
+ assert result["score"] == "none"
+ assert result["active_count"] == 0
+ assert result["candidate_count"] == 2
+ # governing_count keeps its old meaning: records naming this file.
+ assert result["governing_count"] == 2
+
+ def test_proposals_are_named_as_awaiting_review(self):
+ result = _compute_alignment("src/a.py", [self._decision("proposed")], [])
+
+ assert "awaiting review" in result["explanation"]
+ assert "No accepted decision" in result["explanation"]
+
+ def test_accepted_decisions_still_govern(self):
+ result = _compute_alignment("src/a.py", [self._decision("active")], [])
+
+ assert result["score"] == "high"
+ assert result["active_count"] == 1
+ assert result["candidate_count"] == 0
+
+ def test_proposals_do_not_inflate_the_accepted_count(self):
+ governing = [
+ self._decision("active"),
+ self._decision("proposed", "d2"),
+ self._decision("proposed", "d3"),
+ ]
+
+ result = _compute_alignment("src/a.py", governing, [])
+
+ assert result["active_count"] == 1
+ assert result["candidate_count"] == 2
+ assert result["governing_count"] == 3
+
+ def test_proposals_cannot_rescue_an_all_deprecated_file(self):
+ governing = [self._decision("deprecated"), self._decision("proposed", "d2")]
+
+ result = _compute_alignment("src/a.py", governing, [])
+
+ assert result["score"] == "low"
+ assert "deprecated" in result["explanation"]
+
+ def test_staleness_is_measured_over_accepted_records_only(self):
+ governing = [
+ self._decision("active", "d1", staleness=0.0),
+ self._decision("proposed", "d2", staleness=1.0),
+ ]
+
+ result = _compute_alignment("src/a.py", governing, [])
+
+ assert result["stale_count"] == 0
+ assert result["score"] == "high"
+
+ def test_a_majority_stale_accepted_set_still_scores_low(self):
+ governing = [
+ self._decision("active", "d1", staleness=0.9),
+ self._decision("active", "d2", staleness=0.0),
+ ]
+
+ result = _compute_alignment("src/a.py", governing, [])
+
+ assert result["score"] == "low"
+
+ def test_ungoverned_shape_carries_the_candidate_count(self):
+ result = _compute_alignment("src/a.py", [], [])
+
+ assert result["candidate_count"] == 0
+ assert result["active_count"] == 0
+ assert result["governing_count"] == 0
diff --git a/tests/unit/analysis/test_decision_policy.py b/tests/unit/analysis/test_decision_policy.py
new file mode 100644
index 000000000..f3d9edd7e
--- /dev/null
+++ b/tests/unit/analysis/test_decision_policy.py
@@ -0,0 +1,345 @@
+"""Resolution, presets, and persistence of the decision capture policy."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+from repowise.core.analysis.decisions.policy import (
+ CAPTURE_SOURCE_KEYS,
+ PRESET_NAMES,
+ SOURCE_SPECS,
+ preset_policy,
+ resolve_policy,
+)
+from repowise.core.analysis.decisions.policy_store import (
+ PolicyConflictError,
+ load_policy,
+ policy_etag,
+ write_policy,
+)
+from repowise.core.analysis.decisions.provenance import RETIRED_SOURCES
+from repowise.core.repo_config import load_repo_config
+
+
+def _write_config(repo: Path, text: str) -> None:
+ cfg_dir = repo / ".repowise"
+ cfg_dir.mkdir(parents=True, exist_ok=True)
+ (cfg_dir / "config.yaml").write_text(text, encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Resolution
+# ---------------------------------------------------------------------------
+
+
[email protected]("config", [None, {}, {"decisions": {}}, {"decisions": None}])
+def test_absent_config_resolves_to_prior_behaviour(config):
+ """A repo indexed before the policy existed must not change on upgrade."""
+ policy = resolve_policy(config).policy
+
+ assert policy.enabled is True
+ assert policy.llm is True
+ assert all(policy.source_enabled(key) for key in CAPTURE_SOURCE_KEYS)
+ assert all(policy.llm_allowed(key) for key in CAPTURE_SOURCE_KEYS)
+ assert policy.preset_name() == "full"
+
+
+def test_legacy_session_mining_false_disables_the_session_source():
+ policy = resolve_policy({"decisions": {"session_mining": False}}).policy
+
+ assert policy.source_enabled("session") is False
+ assert policy.source_enabled("adr") is True
+
+
+def test_legacy_session_mining_is_reported_not_swallowed():
+ resolution = resolve_policy({"decisions": {"session_mining": True}})
+
+ assert resolution.legacy_keys == ("session_mining",)
+
+
+def test_legacy_session_mining_off_cannot_be_widened_by_a_source_key():
+ """The kill switch wins. Widening past it would start reading transcripts
+ on a config that had switched them off."""
+ policy = resolve_policy(
+ {"decisions": {"session_mining": False, "sources": {"session": True}}}
+ ).policy
+
+ assert policy.source_enabled("session") is False
+
+
+def test_a_source_key_can_still_narrow_past_legacy_session_mining():
+ policy = resolve_policy(
+ {"decisions": {"session_mining": True, "sources": {"session": False}}}
+ ).policy
+
+ assert policy.source_enabled("session") is False
+
+
+def test_legacy_bool_sources_resolve_unchanged():
+ policy = resolve_policy({"decisions": {"sources": {"comment": False, "pr": False}}}).policy
+
+ assert policy.source_enabled("comment") is False
+ assert policy.source_enabled("pr") is False
+ assert policy.source_enabled("adr") is True
+
+
[email protected]("retired", RETIRED_SOURCES)
+def test_retired_source_keys_say_retired_not_unknown(retired):
+ """These were documented switches. "Unknown" reads as the user's typo."""
+ resolution = resolve_policy({"decisions": {"sources": {retired: False}}})
+
+ assert any(retired in w and "retired" in w for w in resolution.warnings)
+ assert not any("Unknown decision source" in w for w in resolution.warnings)
+ assert all(resolution.policy.source_enabled(key) for key in CAPTURE_SOURCE_KEYS)
+
+
+ "config",
+ [
+ {"decisions": "nope"},
+ {"decisions": {"sources": "nope"}},
+ {"decisions": {"enabled": "yes"}},
+ {"decisions": {"llm": 1}},
+ {"decisions": {"sources": {"adr": "yes"}}},
+ {"decisions": {"preset": "aggressive"}},
+ {"decisions": {"nonsense": True}},
+ ],
+)
+def test_malformed_config_warns_and_falls_back(config):
+ """Never silently discarded: a typo that reads as a working switch is worse
+ than a loud one."""
+ resolution = resolve_policy(config)
+
+ assert resolution.warnings
+ assert resolution.policy.source_enabled("adr") is True
+
+
+def test_unknown_per_source_key_warns():
+ resolution = resolve_policy({"decisions": {"sources": {"adr": {"enabled": True, "wat": 1}}}})
+
+ assert any("wat" in w for w in resolution.warnings)
+
+
+def test_global_llm_off_stops_every_model_stage():
+ policy = resolve_policy({"decisions": {"llm": False}}).policy
+
+ assert policy.any_llm_allowed() is False
+ assert all(not policy.llm_allowed(key) for key in CAPTURE_SOURCE_KEYS)
+ # Deterministic capture survives.
+ assert policy.source_enabled("adr") is True
+ assert policy.enabled_index_sources() == ("inline_marker", "adr")
+
+
+def test_per_source_llm_off_leaves_other_sources_alone():
+ policy = resolve_policy({"decisions": {"sources": {"adr": {"enabled": True, "llm": False}}}}).policy
+
+ assert policy.llm_allowed("adr") is False
+ assert policy.llm_allowed("pr") is True
+ assert policy.source_enabled("adr") is True
+
+
+def test_global_off_disables_capture_but_not_manual_entry():
+ policy = resolve_policy({"decisions": {"enabled": False}}).policy
+
+ assert all(not policy.source_enabled(key) for key in CAPTURE_SOURCE_KEYS)
+ assert policy.source_enabled("cli") is True
+ assert policy.enabled_index_sources() == ()
+
+
+def test_llm_only_source_is_dropped_from_the_index_run_when_the_model_is_off():
+ """It would run, call nothing and return zero, which reads as an empty repo."""
+ policy = resolve_policy({"decisions": {"llm": False}}).policy
+
+ assert "pr" not in policy.enabled_index_sources()
+ assert "git_archaeology" not in policy.enabled_index_sources()
+
+
+def test_unknown_source_is_never_enabled():
+ policy = resolve_policy(None).policy
+
+ assert policy.source_enabled("code_comment") is False
+ assert policy.llm_allowed("code_comment") is False
+
+
+# ---------------------------------------------------------------------------
+# Presets and runtime status
+# ---------------------------------------------------------------------------
+
+
[email protected]("name", PRESET_NAMES)
+def test_every_preset_round_trips_to_its_own_name(name):
+ assert preset_policy(name).preset_name() == name
+
+
+def test_unknown_preset_raises():
+ with pytest.raises(ValueError, match="Unknown preset"):
+ preset_policy("aggressive")
+
+
+def test_off_preset_keeps_manual_entry_and_stops_everything_else():
+ policy = preset_policy("off")
+
+ assert policy.source_enabled("cli") is True
+ assert policy.any_llm_allowed() is False
+ assert policy.enabled_index_sources() == ()
+
+
+def test_local_only_preset_makes_no_model_calls():
+ policy = preset_policy("local_only")
+
+ assert policy.any_llm_allowed() is False
+ assert policy.source_enabled("session") is True
+ assert policy.source_enabled("inline_marker") is True
+
+
+def test_custom_policy_reports_custom():
+ policy = preset_policy("full").with_source("adr", enabled=False)
+
+ assert policy.preset_name() == "custom"
+
+
+def test_runtime_names_a_reason_for_every_source():
+ runtime = preset_policy("full").runtime(provider_available=False)
+
+ assert {rt.key for rt in runtime} == {spec.key for spec in SOURCE_SPECS}
+ assert all(rt.reason for rt in runtime)
+
+
+def test_missing_provider_degrades_rather_than_fails():
+ by_key = {
+ rt.key: rt for rt in preset_policy("full").runtime(provider_available=False)
+ }
+
+ # An LLM-only source is skipped, not failed.
+ assert by_key["pr"].status == "skipped_no_provider"
+ # A hybrid source keeps its deterministic stage.
+ assert by_key["adr"].status == "deterministic_only"
+ assert by_key["cli"].status == "always_on"
+
+
+def test_llm_off_status_says_skipped_not_failed():
+ by_key = {
+ rt.key: rt
+ for rt in preset_policy("full").with_llm(False).runtime(provider_available=True)
+ }
+
+ assert "off" in by_key["pr"].reason.lower()
+ assert by_key["adr"].status == "deterministic_only"
+
+
+def test_authority_routes_cannot_be_switched_off():
+ with pytest.raises(ValueError, match="authority route"):
+ preset_policy("full").with_source("cli", enabled=False)
+
+
+def test_with_source_rejects_unknown_keys():
+ with pytest.raises(ValueError, match="Unknown decision source"):
+ preset_policy("full").with_source("code_comment", enabled=False)
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def test_write_preserves_unrelated_config_keys(tmp_path):
+ _write_config(tmp_path, "provider: anthropic\nmodel: claude-x\ncoverage:\n path: cov.xml\n")
+
+ write_policy(tmp_path, preset_policy("local_only"))
+
+ cfg = load_repo_config(tmp_path)
+ assert cfg["provider"] == "anthropic"
+ assert cfg["coverage"] == {"path": "cov.xml"}
+ assert cfg["decisions"]["llm"] is False
+
+
+def test_write_round_trips_through_resolution(tmp_path):
+ policy = preset_policy("full").with_source("comment", enabled=False, llm=False)
+
+ write_policy(tmp_path, policy)
+
+ assert load_policy(tmp_path).policy == policy
+
+
+def test_write_replaces_the_legacy_session_mining_key(tmp_path):
+ _write_config(tmp_path, "decisions:\n session_mining: false\n")
+
+ write_policy(tmp_path, load_policy(tmp_path).policy)
+
+ raw = yaml.safe_load((tmp_path / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+ assert "session_mining" not in raw["decisions"]
+ assert raw["decisions"]["sources"]["session"] is False
+
+
+def test_stale_etag_conflicts_and_writes_nothing(tmp_path):
+ write_policy(tmp_path, preset_policy("full"))
+ stale = policy_etag(preset_policy("local_only"))
+ before = (tmp_path / ".repowise" / "config.yaml").read_bytes()
+
+ with pytest.raises(PolicyConflictError):
+ write_policy(tmp_path, preset_policy("off"), expected_etag=stale)
+
+ assert (tmp_path / ".repowise" / "config.yaml").read_bytes() == before
+
+
+def test_matching_etag_writes(tmp_path):
+ resolution = write_policy(tmp_path, preset_policy("full"))
+
+ write_policy(tmp_path, preset_policy("off"), expected_etag=policy_etag(resolution.policy))
+
+ assert load_policy(tmp_path).policy.enabled is False
+
+
+def test_etag_changes_with_the_policy():
+ assert policy_etag(preset_policy("full")) != policy_etag(preset_policy("off"))
+ assert policy_etag(preset_policy("full")) == policy_etag(preset_policy("full"))
+
+
+def test_a_write_that_dies_before_serializing_leaves_the_config_untouched(tmp_path, monkeypatch):
+ _write_config(tmp_path, "provider: anthropic\n")
+ original = (tmp_path / ".repowise" / "config.yaml").read_bytes()
+
+ def _boom(*_args, **_kwargs):
+ raise RuntimeError("serializer died")
+
+ monkeypatch.setattr("yaml.dump", _boom)
+ with pytest.raises(RuntimeError):
+ write_policy(tmp_path, preset_policy("off"))
+
+ assert (tmp_path / ".repowise" / "config.yaml").read_bytes() == original
+ assert not list((tmp_path / ".repowise").glob(".config.*.tmp"))
+
+
+def test_a_write_that_dies_mid_flight_leaves_the_config_untouched(tmp_path, monkeypatch):
+ """The case the temp file exists for: the failure lands after mkstemp.
+
+ Patching yaml.dump alone never reaches that code, because serialization
+ happens before the temp file is opened.
+ """
+ import os
+
+ _write_config(tmp_path, "provider: anthropic\n")
+ original = (tmp_path / ".repowise" / "config.yaml").read_bytes()
+
+ def _boom(*_args, **_kwargs):
+ raise OSError("disk went away")
+
+ monkeypatch.setattr(os, "replace", _boom)
+ with pytest.raises(OSError):
+ write_policy(tmp_path, preset_policy("off"))
+
+ assert (tmp_path / ".repowise" / "config.yaml").read_bytes() == original
+ assert not list((tmp_path / ".repowise").glob(".config.*.tmp"))
+
+
+def test_a_broken_config_file_raises_rather_than_resolving_to_defaults(tmp_path):
+ """A malformed decisions block is a warning; a malformed file is an error."""
+ from repowise.core.repo_config import RepoConfigError
+
+ _write_config(tmp_path, "decisions:\n\tsources: {}\n")
+
+ with pytest.raises(RepoConfigError):
+ load_policy(tmp_path)
diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.py
index 57d0558fe..3c9ded505 100644
--- a/tests/unit/cli/test_decision_cmd.py
+++ b/tests/unit/cli/test_decision_cmd.py
@@ -329,3 +329,87 @@ def test_decision_health_prints_summary(indexed_repo: Path) -> None:
assert "Decision Health" in result.output
assert "Active decisions" in result.output
assert "Proposed (needs review)" in result.output
+
+
+class TestTheLifecycleIsDrivableByAnAgent:
+ """Confirm/dismiss/deprecate are how a decision gains and loses authority.
+
+ They were human-only: no machine-readable output, exit 0 on a bad id, and a
+ dismissal that blocked on a prompt no non-interactive caller can answer.
+ """
+
+ def test_confirm_emits_json_and_the_new_status(self, indexed_repo: Path):
+ _seed_wiki_db(indexed_repo, [{"id": "c0ffee01", "title": "T", "status": "proposed"}])
+
+ result = CliRunner().invoke(
+ cli, ["decision", "confirm", "c0ffee01", str(indexed_repo), "--format", "json"]
+ )
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ assert payload == {"id": "c0ffee01", "status": "active", "action": "confirmed"}
+
+ def test_dismiss_does_not_prompt_under_json(self, indexed_repo: Path):
+ _seed_wiki_db(indexed_repo, [{"id": "c0ffee02", "title": "T", "status": "proposed"}])
+
+ result = CliRunner().invoke(
+ cli, ["decision", "dismiss", "c0ffee02", str(indexed_repo), "--format", "json"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.output)["status"] == "dismissed"
+
+ def test_dismiss_yes_skips_the_prompt_for_a_person_too(self, indexed_repo: Path):
+ _seed_wiki_db(indexed_repo, [{"id": "c0ffee03", "title": "T", "status": "proposed"}])
+
+ result = CliRunner().invoke(
+ cli, ["decision", "dismiss", "c0ffee03", str(indexed_repo), "--yes"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "dismissed" in result.output
+
+ @pytest.mark.parametrize("action", ["confirm", "dismiss", "deprecate", "show"])
+ def test_an_unknown_id_exits_non_zero(self, indexed_repo: Path, action: str):
+ """Exit 0 on a typo'd id made a failed confirm indistinguishable from a
+ successful one."""
+ _seed_wiki_db(indexed_repo, [])
+
+ result = CliRunner().invoke(
+ cli, ["decision", action, "deadbeef", str(indexed_repo), "--format", "json"]
+ )
+
+ assert result.exit_code != 0, result.output
+
+ @pytest.mark.parametrize("action", ["confirm", "dismiss", "deprecate"])
+ def test_an_unknown_id_reports_a_parseable_reason(self, indexed_repo: Path, action: str):
+ _seed_wiki_db(indexed_repo, [])
+
+ result = CliRunner().invoke(
+ cli, ["decision", action, "deadbeef", str(indexed_repo), "--format", "json"]
+ )
+
+ assert json.loads(result.output) == {
+ "error": "decision_not_found",
+ "decision_id": "deadbeef",
+ }
+
+ def test_deprecate_records_the_successor(self, indexed_repo: Path):
+ _seed_wiki_db(
+ indexed_repo,
+ [
+ {"id": "c0ffee04", "title": "old"},
+ {"id": "c0ffee05", "title": "new"},
+ ],
+ )
+
+ result = CliRunner().invoke(
+ cli,
+ [
+ "decision", "deprecate", "c0ffee04", str(indexed_repo),
+ "--superseded-by", "c0ffee05", "--format", "json",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.output)["status"] == "deprecated"
diff --git a/tests/unit/cli/test_decision_config_cmd.py b/tests/unit/cli/test_decision_config_cmd.py
new file mode 100644
index 000000000..86f508c88
--- /dev/null
+++ b/tests/unit/cli/test_decision_config_cmd.py
@@ -0,0 +1,243 @@
+"""``repowise decision config`` / ``source`` / ``llm`` contracts."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+import yaml
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+
+
+def repo(tmp_path: Path, monkeypatch) -> Path:
+ (tmp_path / ".repowise").mkdir()
+ # Keep provider availability deterministic: the rendered status must not
+ # depend on which keys happen to be in the developer's environment.
+ monkeypatch.setattr(
+ "repowise.cli.commands.decision_config_cmd._provider_available", lambda _p: True
+ )
+ return tmp_path
+
+
+def _run(*args) -> object:
+ return CliRunner().invoke(cli, list(args))
+
+
+def _config(repo: Path) -> dict:
+ return yaml.safe_load((repo / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+
+
+def _write(repo: Path, text: str) -> None:
+ (repo / ".repowise" / "config.yaml").write_text(text, encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# show / list
+# ---------------------------------------------------------------------------
+
+
+def test_show_json_lists_every_source(repo: Path):
+ result = _run("decision", "config", "show", str(repo), "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ keys = [s["key"] for s in payload["policy"]["sources"]]
+ assert keys == [
+ "inline_marker",
+ "git_archaeology",
+ "adr",
+ "pr",
+ "comment",
+ "session",
+ "cli",
+ ]
+ assert payload["policy"]["preset"] == "full"
+
+
+def test_show_table_renders_without_a_config(repo: Path):
+ result = _run("decision", "config", "show", str(repo))
+
+ assert result.exit_code == 0, result.output
+ assert "Decision capture" in result.output
+ assert "inline_marker" in result.output
+
+
+def test_source_list_and_config_show_agree(repo: Path):
+ a = _run("decision", "source", "list", str(repo), "--format", "json")
+ b = _run("decision", "config", "show", str(repo), "--format", "json")
+
+ assert json.loads(a.output) == json.loads(b.output)
+
+
+def test_show_surfaces_a_legacy_key_and_an_unknown_source(repo: Path):
+ _write(repo, "decisions:\n session_mining: false\n sources:\n code_comment: false\n")
+
+ result = _run("decision", "config", "show", str(repo), "--format", "json")
+
+ payload = json.loads(result.output)
+ assert payload["legacy_keys"] == ["session_mining"]
+ assert any("code_comment" in w for w in payload["warnings"])
+ session = next(s for s in payload["policy"]["sources"] if s["key"] == "session")
+ assert session["enabled"] is False
+
+
+def test_no_provider_reports_skipped_not_failed(repo: Path, monkeypatch):
+ monkeypatch.setattr(
+ "repowise.cli.commands.decision_config_cmd._provider_available", lambda _p: False
+ )
+
+ result = _run("decision", "config", "show", str(repo), "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ by_key = {s["key"]: s for s in payload["policy"]["sources"]}
+ assert payload["provider_available"] is False
+ assert by_key["pr"]["status"] == "skipped_no_provider"
+ assert by_key["adr"]["status"] == "deterministic_only"
+
+
+# ---------------------------------------------------------------------------
+# mutations
+# ---------------------------------------------------------------------------
+
+
+def test_llm_off_writes_the_master_switch(repo: Path):
+ result = _run("decision", "llm", "--off", str(repo))
+
+ assert result.exit_code == 0, result.output
+ assert _config(repo)["decisions"]["llm"] is False
+
+
+def test_llm_off_leaves_deterministic_sources_enabled(repo: Path):
+ _run("decision", "llm", "--off", str(repo))
+
+ payload = json.loads(
+ _run("decision", "config", "show", str(repo), "--format", "json").output
+ )
+ by_key = {s["key"]: s for s in payload["policy"]["sources"]}
+ assert by_key["adr"]["enabled"] is True
+ assert by_key["adr"]["llm_enabled"] is False
+ assert by_key["cli"]["status"] == "always_on"
+
+
+def test_preset_writes_its_name(repo: Path):
+ result = _run("decision", "config", "preset", "local_only", str(repo))
+
+ assert result.exit_code == 0, result.output
+ assert _config(repo)["decisions"]["preset"] == "local_only"
+
+
+def test_an_edit_after_a_preset_drops_the_preset_name(repo: Path):
+ _run("decision", "config", "preset", "balanced", str(repo))
+ _run("decision", "source", "set", "comment", "--on", str(repo))
+
+ assert "preset" not in _config(repo)["decisions"]
+ payload = json.loads(
+ _run("decision", "config", "show", str(repo), "--format", "json").output
+ )
+ assert payload["policy"]["preset"] == "custom"
+
+
+def test_source_set_toggles_one_source(repo: Path):
+ result = _run("decision", "source", "set", "pr", "--off", str(repo))
+
+ assert result.exit_code == 0, result.output
+ assert _config(repo)["decisions"]["sources"]["pr"] is False
+ assert _config(repo)["decisions"]["sources"]["adr"] is True
+
+
+def test_source_set_can_disable_only_the_model_stage(repo: Path):
+ _run("decision", "source", "set", "adr", "--no-llm", str(repo))
+
+ payload = json.loads(
+ _run("decision", "config", "show", str(repo), "--format", "json").output
+ )
+ adr = next(s for s in payload["policy"]["sources"] if s["key"] == "adr")
+ assert adr["enabled"] is True
+ assert adr["llm_enabled"] is False
+ assert adr["status"] == "deterministic_only"
+
+
+def test_mutations_preserve_unrelated_config_keys(repo: Path):
+ _write(repo, "provider: anthropic\nmodel: claude-x\n")
+
+ _run("decision", "llm", "--off", str(repo))
+
+ cfg = _config(repo)
+ assert cfg["provider"] == "anthropic"
+ assert cfg["model"] == "claude-x"
+
+
+# ---------------------------------------------------------------------------
+# dry run and errors
+# ---------------------------------------------------------------------------
+
+
+def test_dry_run_writes_nothing(repo: Path):
+ result = _run("decision", "config", "preset", "off", str(repo), "--dry-run")
+
+ assert result.exit_code == 0, result.output
+ assert not (repo / ".repowise" / "config.yaml").exists()
+
+
+def test_dry_run_json_reports_the_changes(repo: Path):
+ result = _run(
+ "decision", "llm", "--off", str(repo), "--dry-run", "--format", "json"
+ )
+
+ payload = json.loads(result.output)
+ assert payload["dry_run"] is True
+ assert {c["key"] for c in payload["changes"]} == {"llm"}
+
+
+def test_dry_run_on_a_no_op_says_so(repo: Path):
+ result = _run("decision", "llm", "--on", str(repo), "--dry-run")
+
+ assert result.exit_code == 0, result.output
+ assert "No change" in result.output
+
+
+def test_source_set_without_a_switch_errors(repo: Path):
+ result = _run("decision", "source", "set", "adr", str(repo))
+
+ assert result.exit_code != 0
+ assert "--on/--off" in result.output
+
+
+def test_manual_entry_is_not_offered_as_a_switch(repo: Path):
+ result = _run("decision", "source", "set", "cli", "--off", str(repo))
+
+ assert result.exit_code != 0
+
+
+def test_unknown_source_is_rejected(repo: Path):
+ result = _run("decision", "source", "set", "code_comment", "--off", str(repo))
+
+ assert result.exit_code != 0
+
+
+def test_unknown_preset_is_rejected(repo: Path):
+ result = _run("decision", "config", "preset", "aggressive", str(repo))
+
+ assert result.exit_code != 0
+
+
+def test_llm_with_neither_switch_errors(repo: Path):
+ result = _run("decision", "llm", str(repo))
+
+ assert result.exit_code != 0
+ assert "--on" in result.output
+
+
+def test_a_broken_config_is_a_clean_error_not_a_traceback(repo: Path):
+ _write(repo, "decisions:\n\tsources: {}\n")
+
+ result = _run("decision", "config", "show", str(repo))
+
+ assert result.exit_code != 0
+ assert "Could not parse" in result.output
+ assert "Traceback" not in result.output
diff --git a/tests/unit/pipeline/test_decision_source_reporting.py b/tests/unit/pipeline/test_decision_source_reporting.py
index cc2a115d5..044f0bf49 100644
--- a/tests/unit/pipeline/test_decision_source_reporting.py
+++ b/tests/unit/pipeline/test_decision_source_reporting.py
@@ -8,6 +8,7 @@ the reassuring sentence a failed source used to produce.
from __future__ import annotations
+from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -50,27 +51,34 @@ class _StubExtractor:
)
+def _write_policy(repo: Path, **sources: bool) -> None:
+ """Switch capture sources through the config the pipeline actually reads."""
+ lines = ["decisions:", " sources:"]
+ lines += [f" {key}: {str(value).lower()}" for key, value in sources.items()]
+ cfg = repo / ".repowise"
+ cfg.mkdir(parents=True, exist_ok=True)
+ (cfg / "config.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
@pytest.fixture
def _patched(monkeypatch, tmp_path):
+ """A repo whose whole capture policy is on, with a stubbed extractor.
+
+ The session source is switched off through the policy rather than by
+ patching a gate function: the pipeline reads one resolved policy, so a
+ patch on anything else silently stops isolating the session miner and the
+ test starts reading the developer's real transcripts.
+ """
import repowise.core.analysis.decision_extractor as de
monkeypatch.setattr(de, "DecisionExtractor", _StubExtractor)
- monkeypatch.setattr(
- de,
- "enabled_source_names",
- lambda _cfg: ("inline_marker", "git_archaeology", "adr", "pr", "comment"),
- )
+ _write_policy(tmp_path, session=False)
return tmp_path
-async def test_failed_source_warns_and_is_kept_out_of_the_empty_list(_patched, monkeypatch):
+async def test_failed_source_warns_and_is_kept_out_of_the_empty_list(_patched):
progress = _RecordingProgress()
- # The session miner is a separate pass; keep it out of this assertion.
- import repowise.core.sessions.miners.decisions as miners
-
- monkeypatch.setattr(miners, "session_mining_enabled", lambda _cfg: False)
-
await _run_decision_extraction(
_patched,
llm_client=SimpleNamespace(),
@@ -95,3 +103,55 @@ async def test_failed_source_warns_and_is_kept_out_of_the_empty_list(_patched, m
# Sources that genuinely found nothing still appear there.
assert "git history" in nothing_line
assert "ADR files" in nothing_line
+
+
+async def test_a_source_that_never_ran_is_not_an_honest_zero(_patched):
+ """The keyless default path: three model-only sources return [] at once.
+
+ Reporting those as "nothing found" is the same confusion the failed/empty
+ split exists to remove, so they belong on the "not run" line instead.
+ """
+ progress = _RecordingProgress()
+
+ await _run_decision_extraction(
+ _patched,
+ llm_client=None,
+ graph_builder=SimpleNamespace(graph=lambda: None),
+ git_meta_map={},
+ parsed_files=[],
+ progress=progress,
+ )
+
+ info = progress.text_at("info")
+ assert "Not run" in info
+ not_run = next(t for lvl, t in progress.messages if lvl == "info" and "Not run" in t)
+ assert "pull requests" in not_run
+ assert "git history" in not_run
+ assert "No LLM provider" in not_run
+
+ nothing = [t for lvl, t in progress.messages if lvl == "info" and "Nothing found" in t]
+ for line in nothing:
+ assert "pull requests" not in line
+ assert "git history" not in line
+
+
+async def test_a_disabled_source_is_reported_as_switched_off(tmp_path, monkeypatch):
+ import repowise.core.analysis.decision_extractor as de
+
+ monkeypatch.setattr(de, "DecisionExtractor", _StubExtractor)
+ _write_policy(tmp_path, session=False, comment=False)
+ progress = _RecordingProgress()
+
+ await _run_decision_extraction(
+ tmp_path,
+ llm_client=SimpleNamespace(),
+ graph_builder=SimpleNamespace(graph=lambda: None),
+ git_meta_map={},
+ parsed_files=[],
+ progress=progress,
+ )
+
+ not_run = next(t for lvl, t in progress.messages if lvl == "info" and "Not run" in t)
+ assert "comments" in not_run
+ assert "agent sessions" in not_run
+ assert "switched off" in not_run
diff --git a/tests/unit/server/test_decision_settings_api.py b/tests/unit/server/test_decision_settings_api.py
new file mode 100644
index 000000000..718425a2e
--- /dev/null
+++ b/tests/unit/server/test_decision_settings_api.py
@@ -0,0 +1,236 @@
+"""GET/PUT ``/decisions/settings``: the same policy the CLI resolves."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+from httpx import AsyncClient
+
+from tests.unit.server.conftest import create_test_repo
+
+
[email protected](autouse=True)
+def _stable_provider(monkeypatch):
+ """Status must not depend on which API keys the test machine carries."""
+ monkeypatch.setattr(
+ "repowise.server.routers.decisions._provider_available", lambda _p: True
+ )
+
+
+def _config(repo: dict) -> dict:
+ path = Path(repo["local_path"]) / ".repowise" / "config.yaml"
+ return yaml.safe_load(path.read_text(encoding="utf-8"))
+
+
+def _write_config(repo: dict, text: str) -> None:
+ cfg_dir = Path(repo["local_path"]) / ".repowise"
+ cfg_dir.mkdir(parents=True, exist_ok=True)
+ (cfg_dir / "config.yaml").write_text(text, encoding="utf-8")
+
+
+async def test_get_returns_the_full_source_registry(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/settings")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert [s["key"] for s in body["sources"]] == [
+ "inline_marker",
+ "git_archaeology",
+ "adr",
+ "pr",
+ "comment",
+ "session",
+ "cli",
+ ]
+ assert body["preset"] == "full"
+ assert body["enabled"] is True
+ assert body["etag"]
+
+
+async def test_settings_path_is_not_shadowed_by_the_decision_id_route(client: AsyncClient):
+ """``settings`` must not resolve as a decision id."""
+ repo = await create_test_repo(client)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/settings")
+
+ assert resp.status_code == 200
+ assert "sources" in resp.json()
+
+
+async def test_get_reports_a_legacy_config_without_changing_it(client: AsyncClient):
+ repo = await create_test_repo(client)
+ _write_config(repo, "decisions:\n session_mining: false\n")
+
+ body = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()
+
+ session = next(s for s in body["sources"] if s["key"] == "session")
+ assert session["enabled"] is False
+ assert _config(repo)["decisions"] == {"session_mining": False}
+
+
+async def test_put_applies_a_partial_change(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings", json={"llm": False}
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["llm"] is False
+ assert _config(repo)["decisions"]["llm"] is False
+
+
+async def test_put_preset_then_source_override_in_one_call(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ body = (
+ await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"preset": "balanced", "sources": {"comment": {"enabled": True}}},
+ )
+ ).json()
+
+ by_key = {s["key"]: s for s in body["sources"]}
+ assert by_key["comment"]["enabled"] is True
+ assert by_key["session"]["enabled"] is True
+ assert body["preset"] == "custom"
+
+
+async def test_put_preserves_unrelated_config_keys(client: AsyncClient):
+ repo = await create_test_repo(client)
+ _write_config(repo, "provider: anthropic\ncoverage:\n path: cov.xml\n")
+
+ await client.put(f"/api/repos/{repo['id']}/decisions/settings", json={"enabled": False})
+
+ cfg = _config(repo)
+ assert cfg["provider"] == "anthropic"
+ assert cfg["coverage"] == {"path": "cov.xml"}
+
+
+async def test_a_stale_etag_conflicts(client: AsyncClient):
+ repo = await create_test_repo(client)
+ stale = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()["etag"]
+ await client.put(f"/api/repos/{repo['id']}/decisions/settings", json={"llm": False})
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"enabled": False, "etag": stale},
+ )
+
+ assert resp.status_code == 409
+ assert _config(repo)["decisions"]["enabled"] is True
+
+
+async def test_a_current_etag_writes(client: AsyncClient):
+ repo = await create_test_repo(client)
+ etag = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()["etag"]
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings", json={"llm": False, "etag": etag}
+ )
+
+ assert resp.status_code == 200
+
+
+async def test_an_unknown_preset_is_a_400(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings", json={"preset": "aggressive"}
+ )
+
+ assert resp.status_code == 400
+
+
+async def test_an_unknown_source_is_a_400(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"sources": {"code_comment": {"enabled": False}}},
+ )
+
+ assert resp.status_code == 400
+
+
+async def test_manual_entry_cannot_be_switched_off(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"sources": {"cli": {"enabled": False}}},
+ )
+
+ assert resp.status_code == 400
+
+
+async def test_an_unknown_repo_is_a_404(client: AsyncClient):
+ resp = await client.get("/api/repos/does-not-exist/decisions/settings")
+
+ assert resp.status_code == 404
+
+
+async def test_the_api_and_the_cli_resolve_the_same_policy(client: AsyncClient):
+ """The registry drift guard: one resolver, two surfaces."""
+ from repowise.core.analysis.decisions.policy_store import load_policy
+
+ repo = await create_test_repo(client)
+ await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings", json={"preset": "local_only"}
+ )
+
+ body = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()
+ policy = load_policy(Path(repo["local_path"])).policy
+
+ assert body["preset"] == policy.preset_name()
+ assert body["llm"] == policy.llm
+ assert {s["key"]: s["enabled"] for s in body["sources"]} == {
+ s["key"]: policy.source_enabled(s["key"]) for s in body["sources"]
+ }
+
+
+async def test_a_misspelt_source_key_is_rejected_not_silently_ignored(client: AsyncClient):
+ """A UI toggle that returns 200 having changed nothing reads as saved."""
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"sources": {"comment": {"enable": False}}},
+ )
+
+ assert resp.status_code == 422
+
+
+async def test_an_unparseable_config_is_a_400(client: AsyncClient):
+ repo = await create_test_repo(client)
+ _write_config(repo, "decisions:\n\tsources: {}\n")
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/settings")
+
+ assert resp.status_code == 400
+ assert "Could not parse" in resp.json()["detail"]
+
+
+async def test_legacy_keys_reach_a_settings_client(client: AsyncClient):
+ repo = await create_test_repo(client)
+ _write_config(repo, "decisions:\n session_mining: false\n")
+
+ body = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()
+
+ assert body["legacy_keys"] == ["session_mining"]
+
+
+async def test_a_repo_with_no_checkout_on_this_server_is_a_404(client: AsyncClient, tmp_path):
+ import shutil
+
+ repo = await create_test_repo(client)
+ shutil.rmtree(repo["local_path"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/settings")
+
+ assert resp.status_code == 404
+ assert "not accessible" in resp.json()["detail"]
diff --git a/tests/unit/sessions/test_session_decisions_e2e.py b/tests/unit/sessions/test_session_decisions_e2e.py
index eb5db1582..dc1164fd9 100644
--- a/tests/unit/sessions/test_session_decisions_e2e.py
+++ b/tests/unit/sessions/test_session_decisions_e2e.py
@@ -63,7 +63,9 @@ async def test_correction_mines_structures_and_promotes(tmp_path):
(decision,) = decisions
assert decision.source == "session"
- assert decision.status == "active" # correction fast path, first promotion
+ # A user correction promotes on one observation, but promotion means
+ # "worth reviewing", not "accepted": only `decision confirm` sets active.
+ assert decision.status == "proposed"
assert decision.verification == "exact"
assert decision.evidence_commits == ["sess-1"]
assert decision.source_quote == CORRECTION
@@ -149,7 +151,7 @@ async def test_llm_failure_leaves_candidates_staged(tmp_path):
repo_root, provider=provider, projects_root=projects_root, now=200.0
)
(decision,) = decisions
- assert decision.status == "active"
+ assert decision.status == "proposed"
async def test_init_pipeline_appends_session_decisions(tmp_path, monkeypatch):