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): fold record completeness into decision confidence (#2328)

Raghav Chamadiya6d0caf1b49b2
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
index c6ee28d27..068ea4bf7 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
@@ -38,8 +38,10 @@ from repowise.core.co_change import parse_partners
#: Hard budget for the whole injected block, in estimated tokens (chars/4).
_TOKEN_CAP = 400
-#: Minimum final score a decision needs to be injected at all.
-_RELEVANCE_FLOOR = 0.25
+#: Minimum final score a decision needs to be injected at all. Rescaled when
+#: confidence stopped being near-constant per source: keeping 0.25 would have
+#: turned this into a gate on how much a record states.
+_RELEVANCE_FLOOR = 0.20
#: Never inject more than this many decisions regardless of the token cap.
_MAX_ITEMS = 6
#: Working-set caps keep the SQL IN-lists and the hop expansion bounded.
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index df75232ef..150d338ff 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -7,6 +7,7 @@ import re
from pathlib import Path
import click
+import structlog
from rich.panel import Panel
from rich.table import Table
@@ -271,7 +272,7 @@ def decision_add(
affected_modules=[],
tags=tags_list,
source="cli",
- confidence=1.0,
+ # No confidence: upsert_decision scores a manual entry.
)
decision_id = rec.id
# A decision that names nothing cannot be checked against the code
@@ -297,8 +298,17 @@ def decision_add(
f"Cannot accept this decision: {exc}."
) from exc
+ embed = (rec.id, rec.title, rec.decision or "", rec.evidence_file)
+ stored_status = rec.status
+
+ # After the session closes, so a network embed does not hold the write
+ # transaction open and cannot leave a vector for an uncommitted record.
+ # ``cli`` is the rank a duplicate should fold into, so a manual entry
+ # with no vector is the worst one to leave unmatched.
+ await _embed_decision(repo_path, *embed)
+
await engine.dispose()
- return decision_id, rec.status
+ return decision_id, stored_status
decision_id, stored_status = run_async(_persist())
if stored_status != "active" and not non_interactive:
@@ -324,6 +334,50 @@ def decision_add(
)
+async def _embed_decision(
+ repo_path: Path,
+ decision_id: str,
+ title: str,
+ decision: str,
+ evidence_file: str | None,
+) -> None:
+ """Write a record's ``decision:`` vector, or leave the store untouched.
+
+ Without it a manual entry is invisible to semantic dedup in both
+ directions until the next reindex: it can neither find a duplicate nor be
+ found as one. Best-effort, like the mined write path, and a no-op when the
+ repo has no real embedder, because a keyless user must still be able to
+ record a decision.
+ """
+ from repowise.cli.providers.embedders import build_embedder, resolve_embedder_for_repo
+ from repowise.cli.providers.vector_store import build_vector_store
+ from repowise.core.analysis.decisions.semantic_match import upsert_decision_vector
+ from repowise.core.providers.embedding import is_semantic_embedder
+
+ try:
+ # Before building the store, which would create its directory for a
+ # repo whose embedder cannot fill it.
+ embedder = build_embedder(resolve_embedder_for_repo(repo_path), repo_path)
+ if not is_semantic_embedder(embedder):
+ return
+ store = build_vector_store(repo_path, embedder)
+ if store is None:
+ return
+ await upsert_decision_vector(
+ store,
+ decision_id,
+ title=title,
+ decision=decision,
+ evidence_file=evidence_file,
+ )
+ except Exception as err:
+ # Covers resolving and building the store. The embed call itself
+ # swallows its own failures, so this does not see those.
+ structlog.get_logger(__name__).debug(
+ "decision.embed_skipped", decision_id=decision_id, error=str(err)
+ )
+
+
# ---------------------------------------------------------------------------
# decision list
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 3d8e2c429..14bb13a61 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -978,16 +978,19 @@ async def _persist_full_update_async(
if timings is not None:
timings.start("persist.decisions")
try:
- # The same three store repairs the full-index path runs, in the
- # same order (see ``pipeline/persist.py``). They live here too
- # because a user whose workflow is ``repowise update`` never
- # takes that path, and every one of them is a repair the store
- # cannot make for itself: ``superseded`` and the retired-source
- # backlog both survive re-extraction, and ``source_rank`` is a
- # value copied into rows rather than derived on read.
+ # The same four store repairs the full-index path runs, in
+ # the same order (see ``pipeline/persist.py``). They live here
+ # too because a user whose workflow is ``repowise update``
+ # never takes that path, and every one of them is a repair the
+ # store cannot make for itself: ``superseded`` and the
+ # retired-source backlog both survive re-extraction,
+ # ``source_rank`` is a value copied into rows rather than
+ # derived on read, and a stored confidence carries no mark of
+ # which formula produced it.
from repowise.core.analysis.decision_provenance import RETIRED_SOURCES
from repowise.core.persistence.crud import (
purge_proposed_decisions_by_source,
+ reconcile_decision_confidence,
reconcile_source_ranks,
unretire_auto_superseded,
)
@@ -998,6 +1001,7 @@ async def _persist_full_update_async(
for _retired in RETIRED_SOURCES:
await purge_proposed_decisions_by_source(session, repo_id, _retired)
await reconcile_source_ranks(session)
+ await reconcile_decision_confidence(session)
# Same repairs on the path a ``repowise update`` user takes.
# Derived ids come first, so everything after this reads a
diff --git a/packages/core/src/repowise/core/analysis/decisions/conventions.py b/packages/core/src/repowise/core/analysis/decisions/conventions.py
index f2712c780..739468bc6 100644
--- a/packages/core/src/repowise/core/analysis/decisions/conventions.py
+++ b/packages/core/src/repowise/core/analysis/decisions/conventions.py
@@ -29,7 +29,11 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from repowise.core.analysis.decisions.provenance import compute_confidence, rank_for_source
+from repowise.core.analysis.decisions.provenance import (
+ completeness,
+ compute_confidence,
+ rank_for_source,
+)
from repowise.core.analysis.decisions.scope import resolve_module_nodes
from repowise.core.analysis.external_systems.links import declaration_name_candidates
from repowise.core.ingestion.cohesion import UNIT_FANOUT_LANGUAGES
@@ -484,7 +488,17 @@ def _record(candidate: _Candidate) -> ExtractedDecision:
source=SOURCE_KEY,
evidence_file=candidate.wrapper,
evidence_line=candidate.symbol.start_line,
- confidence=compute_confidence(rank_for_source(SOURCE_KEY), 1, "exact"),
+ confidence=compute_confidence(
+ rank_for_source(SOURCE_KEY),
+ 1,
+ "exact",
+ filled_fields=completeness(
+ decision=decision,
+ rationale=rationale,
+ context=context,
+ consequences=consequences,
+ ),
+ ),
status="proposed",
source_quote=quote,
# The counts are the ground truth, so the gate reads them as exact.
diff --git a/packages/core/src/repowise/core/analysis/decisions/provenance.py b/packages/core/src/repowise/core/analysis/decisions/provenance.py
index e1a56e77c..64b2c4ffd 100644
--- a/packages/core/src/repowise/core/analysis/decisions/provenance.py
+++ b/packages/core/src/repowise/core/analysis/decisions/provenance.py
@@ -15,13 +15,16 @@ which records a page's source files / KG layer. They share a word, not a concern
from __future__ import annotations
import re
+from collections.abc import Sequence
__all__ = [
+ "BODY_FIELDS",
"LISTABLE_SOURCES",
"MAX_SOURCE_RANK",
"PLACEHOLDER_SOURCES",
"RETIRED_SOURCES",
"SOURCE_RANK",
+ "completeness",
"compute_confidence",
"normalize_text",
"rank_for_source",
@@ -117,10 +120,36 @@ def rank_for_source(source: str | None) -> int:
# ---------------------------------------------------------------------------
+#: The body fields a decision record can fill: ``decision``, ``rationale``,
+#: ``context``, ``consequences`` and ``alternatives``. The denominator of
+#: :func:`completeness`, and the reason that function has no tuned constant.
+BODY_FIELDS: int = 5
+
+
+def completeness(
+ *,
+ decision: str | None = None,
+ rationale: str | None = None,
+ context: str | None = None,
+ consequences: Sequence[object] | None = None,
+ alternatives: Sequence[object] | None = None,
+) -> int:
+ """How many of a record's five body fields say anything (0-5).
+
+ One definition, because the fold sweep ranks cluster members on it and
+ :func:`compute_confidence` scores records on it, and two copies would be
+ free to disagree about what "says anything" means.
+ """
+ filled = sum(1 for text in (decision, rationale, context) if (text or "").strip())
+ return filled + sum(1 for seq in (consequences, alternatives) if seq)
+
+
def compute_confidence(
top_rank: int,
corroboration_count: int = 1,
verification: str = "exact",
+ *,
+ filled_fields: int | None = None,
) -> float:
"""Confidence for a decision backed by ``corroboration_count`` evidence rows.
@@ -129,8 +158,22 @@ def compute_confidence(
surviving evidence is only fuzzy- or un-verified. Bounded to ``[0, 0.99]``
(we never claim certainty). Recency decay is deferred — staleness scoring
already models age separately.
+
+ An extracted record earns its source's authority in proportion to how much
+ it states: the rank-derived credit is scaled by ``filled_fields`` over
+ :data:`BODY_FIELDS`. Without it the score only restates the source, and a
+ thin record outranks a full one wherever the two run opposite.
+
+ ``filled_fields=None`` leaves the score unadjusted, and is right wherever
+ completeness is not evidence about the record: how many fields a *person*
+ filled in says nothing about whether their decision holds. The ``0.4``
+ floor and the corroboration bonus are never scaled, because both are about
+ the evidence rather than the prose.
"""
- base = 0.4 + 0.5 * (top_rank / MAX_SOURCE_RANK)
+ earned = 0.5 * (top_rank / MAX_SOURCE_RANK)
+ if filled_fields is not None:
+ earned *= min(max(filled_fields, 0), BODY_FIELDS) / BODY_FIELDS
+ base = 0.4 + earned
corroboration_bonus = min(0.12, 0.04 * max(0, corroboration_count - 1))
conf = base + corroboration_bonus
if verification == "fuzzy":
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index b649879ed..5b8a5f85f 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -19,6 +19,7 @@ from repowise.core import __version__
from repowise.core.analysis.decisions.lifecycle import DECISION_STATUS_ORDER, status_rank
from repowise.core.analysis.decisions.provenance import (
SOURCE_RANK,
+ completeness,
compute_confidence,
rank_for_source,
)
@@ -202,7 +203,7 @@ async def upsert_decision(
evidence_commits: list[str] | None = None,
evidence_file: str | None = None,
evidence_line: int | None = None,
- confidence: float = 1.0,
+ confidence: float | None = None,
verification: str = "unverified",
last_code_change: datetime | None = None,
staleness_score: float = 0.0,
@@ -212,12 +213,27 @@ async def upsert_decision(
"""Create or update a decision record.
Dedup key: ``(repository_id, title, source, evidence_file)``.
+
+ This is the manual-entry path, the CLI's ``decision add`` and the HTTP
+ create route. It writes no evidence rows, so nothing re-derives the score
+ later unless a mined decision with the same normalised title lands on the
+ record and brings evidence with it. ``confidence=None`` therefore scores
+ it here. Both call sites used to pass a literal ``1.0``, which is above
+ the formula's own ``0.99`` ceiling and so was never a score at all.
"""
# Normalise text fields — LLM extractors may return explicit None
rationale = rationale or ""
context = context or ""
decision = decision or ""
+ if confidence is None:
+ # Full rank credit, and no completeness term: a person wrote this, and
+ # how many prompts they answered is not evidence about whether the
+ # decision holds. Scored as verified for the same reason, since the
+ # decay it skips discounts a quote that may be hallucinated and this
+ # path takes no quote. ``verification`` still stores what it was given.
+ confidence = compute_confidence(rank_for_source(source), 1, "exact")
+
q = _dedup_query(
repository_id, title, source=source, evidence_file=evidence_file
)
@@ -654,6 +670,15 @@ async def _upsert_decision_evidence(
)
+def _json_list(raw: str | None) -> list[str]:
+ """A JSON array column as a list; anything unparsable reads as empty."""
+ try:
+ value = json.loads(raw or "[]")
+ except (TypeError, ValueError):
+ return []
+ return [str(v) for v in value] if isinstance(value, list) else []
+
+
def _best_verification(values: list[str]) -> str:
"""Reduce per-evidence verdicts to the strongest: exact > fuzzy > unverified."""
if "exact" in values:
@@ -663,17 +688,30 @@ def _best_verification(values: list[str]) -> str:
return "unverified"
+def record_completeness(rec: DecisionRecord) -> int:
+ """:func:`completeness` for a stored row, parsing its two JSON columns."""
+ return completeness(
+ decision=rec.decision,
+ rationale=rec.rationale,
+ context=rec.context,
+ consequences=_json_list(rec.consequences_json),
+ alternatives=_json_list(rec.alternatives_json),
+ )
+
+
def _rederive_headline(rec: DecisionRecord, evidence: list[DecisionEvidence]) -> None:
"""Set a record's confidence + verification from its full evidence set.
- The single definition of how a headline is scored. Both writers use it: the
- upsert path after accreting a run's evidence, and ``reconcile_source_ranks``
- after a ladder edit. Kept as one function because the two were briefly
- copy-pasted and nothing would have forced the copies to stay equal.
+ The single definition of how a headline is scored. Every writer uses it:
+ the upsert path after accreting a run's evidence, ``reconcile_source_ranks``
+ after a ladder edit, and ``reconcile_decision_confidence`` after a formula
+ edit. Kept as one function because two of them were briefly copy-pasted and
+ nothing would have forced the copies to stay equal.
Confidence rises with the best source rank and with the number of
- *independent* corroborating sources, so it is derived from the whole set
- rather than from whichever row happened to arrive last. No-op on empty
+ *independent* corroborating sources, and with how much of its body the
+ record fills, so it is derived from the whole set plus the row rather than
+ from whichever evidence row happened to arrive last. No-op on empty
evidence: a record with nothing behind it keeps whatever it had.
"""
if not evidence:
@@ -683,6 +721,7 @@ def _rederive_headline(rec: DecisionRecord, evidence: list[DecisionEvidence]) ->
max(e.source_rank for e in evidence),
len({e.source for e in evidence}),
best_ver,
+ filled_fields=record_completeness(rec),
)
rec.verification = best_ver
@@ -760,6 +799,55 @@ async def reconcile_source_ranks(session: AsyncSession) -> int:
return len(moved)
+async def reconcile_decision_confidence(session: AsyncSession) -> int:
+ """Re-score headlines whose stored confidence predates a formula edit.
+
+ The sibling of :func:`reconcile_source_ranks`, for the other half of the
+ same problem. That one repairs a stale *input*, a rank copied into a row
+ before the ladder moved, so it can find its work with an indexed
+ filter. A change to the formula itself leaves every input valid and every
+ stored score wrong, and nothing in a row marks which formula produced it,
+ so the only way to find the work is to recompute and compare.
+
+ Ceiling: two selects that hydrate the whole decision table, which is
+ small; a store large enough for that to hurt would want the comparison
+ pushed into SQL.
+
+ Not repo-scoped, for the reason the ladder is not: the formula is global.
+ Idempotent: 0 once reconciled, which is the steady state. Returns the
+ number of records re-scored, and re-derives verification alongside it.
+
+ A record with no evidence rows is left alone, deliberately: this pass
+ re-derives, it does not invent. The rows in that state are the ones no
+ extractor wrote, manual entries and manifest imports, and both score
+ themselves where they are created.
+ """
+ evidence_by_id: dict[str, list[DecisionEvidence]] = {}
+ for row in (await session.execute(select(DecisionEvidence))).scalars().all():
+ evidence_by_id.setdefault(row.decision_id, []).append(row)
+ if not evidence_by_id:
+ return 0
+
+ now = _now_utc()
+ rescored = 0
+ for rec in (await session.execute(select(DecisionRecord))).scalars().all():
+ evidence = evidence_by_id.get(rec.id)
+ if not evidence:
+ continue # see the docstring: re-derive, never invent
+ before = (rec.confidence, rec.verification)
+ _rederive_headline(rec, evidence)
+ if (rec.confidence, rec.verification) != before:
+ rec.updated_at = now
+ rescored += 1
+
+ if rescored:
+ await session.flush()
+ structlog.get_logger(__name__).info(
+ "decisions.confidence_reconciled", records=rescored
+ )
+ return rescored
+
+
#: Prefix ``detect_supersessions_and_conflicts`` stamps on every edge it writes
#: (``auto-detected: <signal> (sim=0.81)``). It is the only marker that
#: separates a machine retirement from a human one, so the repair below keys on
diff --git a/packages/core/src/repowise/core/persistence/decision_dedupe.py b/packages/core/src/repowise/core/persistence/decision_dedupe.py
index 36e37db20..8e8397039 100644
--- a/packages/core/src/repowise/core/persistence/decision_dedupe.py
+++ b/packages/core/src/repowise/core/persistence/decision_dedupe.py
@@ -71,7 +71,12 @@ from repowise.core.providers.embedding import store_has_semantic_vectors
# ``_add_alias`` is private but its chain repointing is the load-bearing part:
# without it a prior alias of a folded record points at an id this sweep deletes.
from .crud.authority import _add_alias, accepted_decision_ids
-from .crud.decisions import _rederive_headline, list_decision_evidence
+from .crud.decisions import (
+ _json_list,
+ _rederive_headline,
+ list_decision_evidence,
+ record_completeness,
+)
from .decision_graph import sync_decision_node_links
from .models import (
DecisionCandidateMeta,
@@ -160,34 +165,18 @@ class DedupePlan:
}
-def _json_list(raw: str | None) -> list[str]:
- try:
- value = json.loads(raw or "[]")
- except (TypeError, ValueError):
- return []
- return [str(v) for v in value] if isinstance(value, list) else []
-
-
-def _completeness(rec: DecisionRecord) -> int:
- """How many of a record's five body fields say anything."""
- filled = sum(
- 1 for text in (rec.decision, rec.rationale, rec.context) if (text or "").strip()
- )
- filled += sum(1 for raw in (rec.consequences_json, rec.alternatives_json) if _json_list(raw))
- return filled
-
-
def _canonical_key(rec: DecisionRecord) -> tuple:
"""Rank the members of a cluster; the maximum survives.
Source rank first, because that is what the write path promotes a headline
on. Completeness breaks the rank ties, so a blank record cannot outrank one
- that says what was decided; confidence does not read completeness, so it
- cannot stand in for it. The last two only make the pick deterministic.
+ that says what was decided. Confidence reads completeness too, but it
+ blends it with rank and verification, so it cannot stand in for the term
+ above it. The last two only make the pick deterministic.
"""
return (
rank_for_source(rec.source),
- _completeness(rec),
+ record_completeness(rec),
rec.confidence or 0.0,
rec.created_at.isoformat() if rec.created_at else "",
rec.id,
diff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.py
index b6932054d..7d763f874 100644
--- a/packages/core/src/repowise/core/persistence/decision_manifest.py
+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py
@@ -22,6 +22,7 @@ from repowise.core.analysis.decisions.manifest import (
load_manifest,
write_manifest,
)
+from repowise.core.analysis.decisions.provenance import compute_confidence, rank_for_source
from .crud.authority import (
accepted_decision_ids,
@@ -29,6 +30,7 @@ from .crud.authority import (
record_acceptance,
resolve_decision_id,
)
+from .crud.decisions import _rederive_headline, list_decision_evidence
from .models import DecisionAlias, DecisionRecord
__all__ = ["ImportOutcome", "export_manifest", "import_manifest"]
@@ -161,6 +163,16 @@ def _differs(
)
+def _entry_confidence(entry: ManifestDecision) -> float:
+ """Score a decision the file is the only record of.
+
+ Same shape as the CLI's manual entry: full rank credit, no completeness
+ term, and scored as verified, because a person wrote it and the file holds
+ no quote to check.
+ """
+ return compute_confidence(rank_for_source(entry.source or "cli"), 1, "exact")
+
+
async def _apply_entry(
session: AsyncSession, entry: ManifestDecision, record: DecisionRecord
) -> None:
@@ -168,6 +180,15 @@ async def _apply_entry(
record.title = entry.title
record.decision = entry.decision
record.rationale = entry.reason
+ # The file exports every accepted decision, most of which were mined and
+ # carry evidence, so re-derive from that where it exists and only score
+ # the entry itself where the file is the whole record. Writing the entry's
+ # score unconditionally would fight the reconcile pass every index.
+ evidence = await list_decision_evidence(session, record.id)
+ if evidence:
+ _rederive_headline(record, evidence)
+ else:
+ record.confidence = _entry_confidence(entry)
record.affected_files_json = json.dumps(sorted(entry.scope))
# The successor is an id the file wrote down, and the file can be older
# than the store it is being read into. Storing it unresolved would put a
@@ -249,7 +270,7 @@ async def import_manifest(
affected_files_json=json.dumps(sorted(entry.scope)),
evidence_commits_json=json.dumps(sorted(entry.evidence)),
superseded_by=entry.superseded_by or None,
- confidence=1.0,
+ confidence=_entry_confidence(entry),
verification="unverified",
)
session.add(record)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index a4cba9c5d..d6f545f04 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -2018,6 +2018,16 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
except Exception as _rank_err:
logger.debug("decision_rank_reconcile_skipped", error=str(_rank_err))
+ # The same repair for the scoring formula, which leaves every input valid
+ # and every stored score stale, so no filter can find it. Its own try, so
+ # a failure here is not logged as the rank repair's.
+ try:
+ from repowise.core.persistence.crud import reconcile_decision_confidence
+
+ await reconcile_decision_confidence(session)
+ except Exception as _conf_err:
+ logger.debug("decision_confidence_reconcile_skipped", error=str(_conf_err))
+
# Move legacy records onto ids derived from their own identity, before
# anything else reads or writes one. A random id is re-minted whenever a
# store is rebuilt rather than updated, which strands every reference held
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 7fee41962..ba60c5d5d 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -60,6 +60,7 @@ from repowise.core.analysis.decisions.discovery.spans import SpanCollector
from repowise.core.analysis.decisions.extractor import ExtractedDecision
from repowise.core.analysis.decisions.policy import resolve_policy
from repowise.core.analysis.decisions.provenance import (
+ completeness,
compute_confidence,
rank_for_source,
verify_quote,
@@ -620,10 +621,16 @@ def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedD
lane = DISCOVERY_KIND if row.get("kind") == DISCOVERY_KIND else "session"
files = relative_files(structured.get("affected_files") or row["files"], repo_root)
modules = resolve_module_nodes(files)
+ # Staging carries a decision and a rationale and no more, so a promoted
+ # record is thin by construction and is scored as such.
confidence = compute_confidence(
rank_for_source("session"),
row["observations"],
structured.get("verification", "unverified"),
+ filled_fields=completeness(
+ decision=structured.get("decision"),
+ rationale=structured.get("rationale"),
+ ),
)
sessions = row["sessions"][-_MAX_EVIDENCE_SESSIONS:] or [None]
return [
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 0584d070a..4022dcdc1 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -581,7 +581,7 @@ async def create_decision(
affected_modules=body.affected_modules,
tags=body.tags,
source="cli",
- confidence=1.0,
+ # No confidence: upsert_decision scores a manual entry.
)
if scoped:
# Same rule as the scope-less case above: what the contract will not
diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsx
index 55696dc21..b60d758e1 100644
--- a/packages/ui/src/decisions/decisions-table.tsx
+++ b/packages/ui/src/decisions/decisions-table.tsx
@@ -162,10 +162,12 @@ export function DecisionsTable({
render: (d) => decisionSourceLabel(d.source),
},
// Scope, Confidence and Trust all left this row. Scope is `cross-module`
- // on three quarters of a live index and confidence is source rank times
- // verification, so every record from one source carries one number: all
+ // on three quarters of a live index, and confidence was source rank times
+ // verification, so every record from one source carried one number: all
// twelve session records read 84%. A column whose value you can predict
- // from the column beside it spends width repeating itself.
+ // from the column beside it spends width repeating itself. Confidence now
+ // also reads how much of its body an extracted record fills, so it varies
+ // within a source.
//
// Trust went for a different reason. 91% of a live index verifies
// `exact`, so the mark belongs on the exception rather than on every row
diff --git a/tests/unit/analysis/test_decision_provenance.py b/tests/unit/analysis/test_decision_provenance.py
index 964fbedcf..dc3332731 100644
--- a/tests/unit/analysis/test_decision_provenance.py
+++ b/tests/unit/analysis/test_decision_provenance.py
@@ -7,7 +7,9 @@ from pathlib import Path
from repowise.core.analysis.decision_extractor import DecisionExtractor, ExtractedDecision
from repowise.core.analysis.decision_provenance import (
+ BODY_FIELDS,
MAX_SOURCE_RANK,
+ completeness,
compute_confidence,
rank_for_source,
verify_quote,
@@ -212,3 +214,53 @@ def test_gate_keeps_unverifiable_when_no_source_text(tmp_path):
assert rejected == 0
assert len(kept) == 1
assert kept[0].verification == "unverified"
+
+
+# --- completeness into confidence ------------------------------------------
+
+
+def test_completeness_counts_only_fields_that_say_something():
+ assert completeness() == 0
+ assert completeness(decision="x", rationale=" ", context=None) == 1
+ assert (
+ completeness(
+ decision="d",
+ rationale="r",
+ context="c",
+ consequences=["one"],
+ alternatives=["two"],
+ )
+ == BODY_FIELDS
+ )
+
+
+def test_a_record_that_says_more_scores_higher_at_the_same_rank():
+ thin = compute_confidence(8, 1, "exact", filled_fields=1)
+ full = compute_confidence(8, 1, "exact", filled_fields=5)
+ assert thin < full
+
+
+def test_completeness_outranks_a_rung_of_source_rank():
+ """The inversion this term exists to fix: a thin high-rank record used to
+ outscore a complete lower-rank one."""
+ thin_session = compute_confidence(8, 1, "exact", filled_fields=1)
+ full_pr = compute_confidence(7, 1, "exact", filled_fields=5)
+ assert full_pr > thin_session
+
+
+def test_an_unknown_body_leaves_the_score_unadjusted():
+ assert compute_confidence(8, 1, "exact") == compute_confidence(
+ 8, 1, "exact", filled_fields=BODY_FIELDS
+ )
+
+
+def test_a_record_that_says_nothing_keeps_the_evidence_floor():
+ """The 0.4 floor means "there is evidence at all", which a blank record
+ still has. The term withholds the rank credit above it, not the floor."""
+ assert compute_confidence(9, 1, "exact", filled_fields=0) == 0.4
+
+
+def test_completeness_never_breaks_the_bounds_or_the_comment_subtier():
+ for filled in range(-1, BODY_FIELDS + 2):
+ assert 0.0 <= compute_confidence(9, 99, "exact", filled_fields=filled) <= 0.99
+ assert compute_confidence(2, 1, "exact", filled_fields=filled) < 0.5
diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.py
index 89778b111..bf38202a9 100644
--- a/tests/unit/cli/test_decision_cmd.py
+++ b/tests/unit/cli/test_decision_cmd.py
@@ -481,3 +481,67 @@ def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path)
)
assert fixed.exit_code == 0, fixed.output
assert json.loads(fixed.output)["status"] == "active"
+
+
+# --- a manual entry is embedded like a mined one ---------------------------
+
+
+def test_embed_decision_writes_the_records_vector(tmp_path, monkeypatch):
+ """Without this, a manual entry is invisible to semantic dedup until a
+ reindex, in both directions, at the top of the source ladder."""
+ import repowise.cli.providers.embedders as embedders
+ import repowise.cli.providers.vector_store as vector_store
+ from repowise.cli.commands import decision_cmd
+
+ written: list[tuple[str, str]] = []
+
+ class _Store:
+ _embedder = object()
+
+ async def embed_and_upsert(self, page_id, text, metadata):
+ written.append((page_id, text))
+ return True
+
+ monkeypatch.setattr(embedders, "resolve_embedder_for_repo", lambda p: "openai")
+ monkeypatch.setattr(embedders, "build_embedder", lambda name, p: object())
+ monkeypatch.setattr(vector_store, "build_vector_store", lambda p, e: _Store())
+
+ asyncio.run(
+ decision_cmd._embed_decision(
+ tmp_path,
+ "abc123",
+ "Use one cache reader",
+ "Do not write a second cache reader",
+ None,
+ )
+ )
+
+ assert written == [
+ ("decision:abc123", "Use one cache reader\nDo not write a second cache reader")
+ ]
+
+
+def test_decision_add_stays_silent_when_the_repo_has_no_real_embedder(tmp_path, monkeypatch):
+ """A keyless user must still be able to record a decision.
+
+ The sentinel is asserted outside the helper, because the helper catches
+ every exception: an ``AssertionError`` raised inside it would be swallowed
+ and the test would pass against an implementation with no guard at all.
+ """
+ import repowise.cli.providers.embedders as embedders
+ import repowise.cli.providers.vector_store as vector_store
+ from repowise.cli.commands import decision_cmd
+ from repowise.core.providers.embedding.base import KeylessEmbedder
+
+ built: list[object] = []
+
+ monkeypatch.setattr(embedders, "resolve_embedder_for_repo", lambda p: "keyless")
+ monkeypatch.setattr(embedders, "build_embedder", lambda name, p: KeylessEmbedder())
+ monkeypatch.setattr(
+ vector_store, "build_vector_store", lambda p, e: built.append(e) or None
+ )
+
+ asyncio.run(decision_cmd._embed_decision(tmp_path, "abc123", "t", "d", None))
+
+ assert built == [], "no store should be built without a real embedder"
+ assert not (tmp_path / ".repowise" / "lancedb").exists()
diff --git a/tests/unit/persistence/test_decision_evidence.py b/tests/unit/persistence/test_decision_evidence.py
index 4a7dad7d5..39997b49e 100644
--- a/tests/unit/persistence/test_decision_evidence.py
+++ b/tests/unit/persistence/test_decision_evidence.py
@@ -5,7 +5,11 @@ from __future__ import annotations
from sqlalchemy import select
from repowise.core.analysis.decision_provenance import compute_confidence, rank_for_source
-from repowise.core.persistence.crud import bulk_upsert_decisions, list_decision_evidence
+from repowise.core.persistence.crud import (
+ bulk_upsert_decisions,
+ list_decision_evidence,
+ record_completeness,
+)
from repowise.core.persistence.crud.authority import latest_acceptance
from repowise.core.persistence.models import DecisionRecord
from tests.unit.persistence.helpers import insert_repo
@@ -80,8 +84,13 @@ async def test_two_sources_merge_into_one_record_with_two_evidence_rows(async_se
# Strongest evidence verification wins; confidence reflects corroboration.
assert rec.verification == "exact"
# Two corroborating sources score strictly above the same decision backed
- # by a single source at the same top rank.
- solo = compute_confidence(rank_for_source("adr"), corroboration_count=1, verification="exact")
+ # by a single source at the same top rank and saying the same amount.
+ solo = compute_confidence(
+ rank_for_source("adr"),
+ corroboration_count=1,
+ verification="exact",
+ filled_fields=record_completeness(rec),
+ )
assert rec.confidence > solo
diff --git a/tests/unit/persistence/test_decision_manifest.py b/tests/unit/persistence/test_decision_manifest.py
index 2ff62dced..bbea2d407 100644
--- a/tests/unit/persistence/test_decision_manifest.py
+++ b/tests/unit/persistence/test_decision_manifest.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.decisions.manifest import (
render_manifest,
write_manifest,
)
+from repowise.core.analysis.decisions.provenance import compute_confidence, rank_for_source
from repowise.core.persistence.crud import bulk_upsert_decisions
from repowise.core.persistence.crud.authority import (
accept_decision,
@@ -256,6 +257,87 @@ async def test_an_edited_entry_is_reconciled_rather_than_reported_unchanged(
assert acceptance.scope_json == '["src/corrected.py"]'
+async def test_an_edited_entry_is_rescored_from_its_evidence_not_from_the_file(
+ async_session, tmp_path
+):
+ """The file exports accepted decisions, and most of those were mined.
+
+ Scoring such a record from the file's two fields would fight
+ ``reconcile_decision_confidence``, which re-derives it from the evidence
+ on the next index: the value would oscillate and ``updated_at`` would
+ churn forever. The file only supplies the score when it is the whole
+ record.
+ """
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [_dict("Mined then edited", context="the situation", consequences=["a cost"])],
+ )
+ rec = (
+ (
+ await async_session.execute(
+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)
+ )
+ )
+ .scalars()
+ .one()
+ )
+ await accept_decision(async_session, rec, accepter="tester")
+ scored_from_evidence = rec.confidence
+ await export_manifest(async_session, repo.id, tmp_path)
+
+ entries, _ = load_manifest(tmp_path)
+ write_manifest(tmp_path, [replace(entries[0], reason="a colleague corrected this")])
+ await import_manifest(async_session, repo.id, tmp_path)
+ await async_session.refresh(rec)
+
+ # The file sees 2 of 5 body fields; the record still has 4 and its
+ # evidence rows. Scoring from the file would land somewhere else.
+ assert rec.confidence == scored_from_evidence
+ assert rec.confidence != compute_confidence(
+ rank_for_source("session"), 1, "exact", filled_fields=2
+ )
+
+
+async def test_a_file_only_decision_is_scored_on_the_ladder_not_at_one(
+ async_session, tmp_path
+):
+ """A decision the file is the only record of has no evidence to derive
+ from, so the import scores it: full rank credit, never the old 1.0."""
+ repo = await insert_repo(async_session)
+ write_manifest(
+ tmp_path,
+ [
+ ManifestDecision(
+ id="f" * 32,
+ title="Only in the file",
+ decision="Route through the client",
+ reason="one place to change the retry policy",
+ scope=["src/app.py"],
+ accepted_at="2026-01-01T00:00:00+00:00",
+ accepted_by="tester",
+ evidence=[],
+ source="cli",
+ )
+ ],
+ )
+
+ await import_manifest(async_session, repo.id, tmp_path)
+
+ rec = (
+ (
+ await async_session.execute(
+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)
+ )
+ )
+ .scalars()
+ .one()
+ )
+ assert rec.confidence == compute_confidence(rank_for_source("cli"), 1, "exact")
+ assert rec.confidence < 1.0
+
+
async def test_an_entry_missing_a_reason_is_skipped_not_guessed_at(
async_session, tmp_path
):
diff --git a/tests/unit/persistence/test_decision_source_rank_backfill.py b/tests/unit/persistence/test_decision_source_rank_backfill.py
index 188780ea1..4ea23f7ad 100644
--- a/tests/unit/persistence/test_decision_source_rank_backfill.py
+++ b/tests/unit/persistence/test_decision_source_rank_backfill.py
@@ -18,7 +18,10 @@ from repowise.core.persistence.crud import (
bulk_upsert_decisions,
list_decision_evidence,
purge_proposed_decisions_by_source,
+ reconcile_decision_confidence,
reconcile_source_ranks,
+ record_completeness,
+ upsert_decision,
)
from repowise.core.persistence.models import DecisionEvidence, DecisionRecord
from tests.unit.persistence.helpers import accept, insert_repo
@@ -100,7 +103,9 @@ async def test_reconcile_restamps_rows_left_on_the_old_ladder(async_session):
)
).scalars().one()
row.source_rank = 7
- rec.confidence = compute_confidence(7, 1, "exact")
+ rec.confidence = compute_confidence(
+ 7, 1, "exact", filled_fields=record_completeness(rec)
+ )
await async_session.flush()
stale_confidence = rec.confidence
@@ -110,7 +115,9 @@ async def test_reconcile_restamps_rows_left_on_the_old_ladder(async_session):
await async_session.refresh(row)
await async_session.refresh(rec)
assert row.source_rank == rank_for_source("session") == 8
- assert rec.confidence == compute_confidence(8, 1, "exact")
+ assert rec.confidence == compute_confidence(
+ 8, 1, "exact", filled_fields=record_completeness(rec)
+ )
assert rec.confidence > stale_confidence
@@ -232,3 +239,107 @@ async def test_purge_keeps_what_a_human_confirmed(async_session):
assert await purge_proposed_decisions_by_source(async_session, repo.id, "changelog") == 0
rec = await _record(async_session, repo.id)
assert rec.status == "active"
+
+
+# --- the formula's own repair path -----------------------------------------
+
+
+async def test_confidence_reconcile_rescores_a_store_left_on_an_old_formula(
+ async_session,
+):
+ """The rank repair cannot find this: every input is still valid.
+
+ A store scored before completeness entered the formula holds records whose
+ ranks all agree with the ladder, so ``reconcile_source_ranks`` scans and
+ returns 0 while every headline is on the previous scale.
+ """
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(async_session, repo.id, [_session_dict()])
+ rec = await _record(async_session, repo.id)
+ scored = rec.confidence
+
+ rec.confidence = compute_confidence(8, 1, "exact") # the pre-completeness value
+ await async_session.flush()
+
+ assert await reconcile_source_ranks(async_session) == 0
+ assert await reconcile_decision_confidence(async_session) == 1
+ await async_session.refresh(rec)
+ assert rec.confidence == scored
+
+
+async def test_confidence_reconcile_is_idempotent(async_session):
+ """It converges: a second pass over its own output writes nothing.
+
+ Otherwise it churns ``updated_at`` on every persist and every update.
+ """
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(async_session, repo.id, [_session_dict(), _adr_dict()])
+ rec = await _record(async_session, repo.id)
+
+ assert await reconcile_decision_confidence(async_session) == 0
+
+ rec.confidence = 0.123
+ await async_session.flush()
+ assert await reconcile_decision_confidence(async_session) == 1
+ assert await reconcile_decision_confidence(async_session) == 0
+
+
+async def test_confidence_reconcile_leaves_an_evidence_less_record_alone(
+ async_session,
+):
+ """A manual entry has no evidence to re-derive from, so it is not touched."""
+ repo = await insert_repo(async_session)
+ rec = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Hand-written",
+ decision="Do the thing",
+ source="cli",
+ verification="exact",
+ )
+ scored_at_creation = rec.confidence
+
+ assert await reconcile_decision_confidence(async_session) == 0
+ await async_session.refresh(rec)
+ assert rec.confidence == scored_at_creation
+
+
+async def test_a_manual_entry_is_scored_on_the_ladder_not_asserted(async_session):
+ """``decision add`` used to write 1.0, above the formula's own ceiling.
+
+ It takes full rank credit and no completeness term: a person wrote it, and
+ how many prompts they answered says nothing about whether it holds.
+ """
+ repo = await insert_repo(async_session)
+ thin = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="One line",
+ decision="Do the thing",
+ source="cli",
+ )
+ full = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Fully stated",
+ context="Here is the situation",
+ decision="Do the thing",
+ rationale="Because of the reason",
+ consequences=["a cost"],
+ alternatives=["the other thing"],
+ source="cli",
+ )
+
+ on_the_ladder = compute_confidence(rank_for_source("cli"), 1, "exact")
+ assert thin.confidence == full.confidence == on_the_ladder
+ assert on_the_ladder < 1.0, "1.0 is above the formula's own ceiling"
+ # An explicit value still wins: the derivation only fills a gap.
+ pinned = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Pinned",
+ decision="Do the thing",
+ source="cli",
+ confidence=0.42,
+ )
+ assert pinned.confidence == 0.42