Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(decisions): derive a decision's id from the identity it dedupes on (#2071)
Raghav Chamadiya8d0b405ddee4
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 4d6437929..781731ec4 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -811,8 +811,19 @@ async def _persist_full_update_async(await purge_proposed_decisions_by_source(session, repo_id, _retired)await reconcile_source_ranks(session)- # Same repair on the path a ``repowise update`` user takes: the- # entity split is only coherent once legacy rows are classified.+ # Same repairs on the path a ``repowise update`` user takes.+ # Derived ids come first, so everything after this reads a+ # record by the id it will still have after a rebuild.+ from repowise.core.persistence.decision_id_migration import (+ apply_id_migration,+ )++ await apply_id_migration(+ session, repo_id, vector_store=decision_vector_store+ )++ # The entity split is only coherent once legacy rows are+ # classified.from repowise.core.persistence.decision_migration import apply_migrationawait apply_migration(session, repo_id)diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex 9df673568..bc071eb81 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -6,6 +6,7 @@ every public name, so existing imports are unaffected.from __future__ import annotations+import hashlibimport jsonfrom datetime import datetimefrom typing import Any@@ -28,7 +29,6 @@ from ..models import (DecisionNodeLink,DecisionRecord,GitMetadata,- _new_uuid,_now_utc,)@@ -36,6 +36,19 @@ from ..models import (# DecisionRecord CRUD# ---------------------------------------------------------------------------+# Namespaced so a decision id can never collide with another kind of derived+# id, and versioned so a future change of the recipe is a visible new value+# rather than a silent reshuffle of every id in every store.+_ID_NAMESPACE = "repowise.decision.id.v1"++# The four identity fields are joined with a separator none of them can+# contain, so no pair of distinct records can flatten to the same string.+_FIELD_SEP = "\x00"++# ``evidence_file`` is nullable and NULL is not the empty string here: the+# dedupe query treats them as different records, so the derivation must too.+_NULL_EVIDENCE_FILE = "\x01"+_VALID_DECISION_STATUSES = frozenset({"proposed", "active", "deprecated", "superseded", "dismissed"})@@ -97,6 +110,51 @@ def _dedup_query(return q.where(DecisionRecord.evidence_file.is_(None))+def derive_decision_id(+ repository_id: str,+ title: str,+ *,+ source: str,+ evidence_file: str | None,+) -> str:+ """The id a decision with this identity has, in every store, on every run.++ Deliberately the same four columns :func:`_dedup_query` matches on, and+ kept beside it so the id and the dedupe key cannot drift apart. Those+ columns are what ``uq_decision_record`` names, so this makes the primary+ key agree with the identity the schema already declares rather than+ inventing one. A random id, by contrast, is re-minted whenever a store is+ rebuilt instead of updated, which strands every reference held outside the+ row: an acceptance, an alias, a vector key, a link somebody wrote down.++ That constraint is weaker than it looks, and this is stricter than it:+ ``evidence_file`` is nullable and SQL calls two NULLs distinct, so the+ constraint does not fire for the majority of records, while two rows that+ agree on all four do collapse to one id here. Every write path reaches an+ insert only after a dedupe that would have found such a row, so the+ stricter reading is not reachable from them; the migration classifies the+ pairs a store already holds and leaves them alone.++ Note the id follows the identity, so editing one of the four moves it. The+ migration at the head of each run is what settles that.++ 32 lowercase hex, because ``DecisionRecord.id`` is ``String(32)`` and so is+ every foreign key to it, so a truncated digest fits without a column+ change. ``evidence_file`` is NULL far more often than not, and NULL is a+ distinct case in the dedupe query, so it gets a sentinel no path can+ contain rather than collapsing into the empty string.+ """+ parts = (+ _ID_NAMESPACE,+ repository_id,+ title,+ source,+ _NULL_EVIDENCE_FILE if evidence_file is None else evidence_file,+ )+ digest = hashlib.sha256(_FIELD_SEP.join(parts).encode("utf-8")).hexdigest()+ return digest[:32]++async def find_decision_by_title(session: AsyncSession,repository_id: str,@@ -186,7 +244,12 @@ async def upsert_decision(return existingrec = DecisionRecord(- id=decision_id or _new_uuid(),+ # An explicit id still wins: the manifest importer carries ids in from+ # a tracked file and those are the record's identity, not ours.+ id=decision_id+ or derive_decision_id(+ repository_id, title, source=source, evidence_file=evidence_file+ ),repository_id=repository_id,title=title,status=status,@@ -1013,10 +1076,18 @@ async def bulk_upsert_decisions(continueif rec is None:+ headline_title = headline.get("title", "")+ headline_source = headline.get("source", "cli")+ headline_evidence_file = headline.get("evidence_file")rec = DecisionRecord(- id=_new_uuid(),+ id=derive_decision_id(+ repository_id,+ headline_title,+ source=headline_source,+ evidence_file=headline_evidence_file,+ ),repository_id=repository_id,- title=headline.get("title", ""),+ title=headline_title,status=_extraction_status(headline.get("status", "proposed")),context=headline.get("context") or "",decision=headline.get("decision") or "",@@ -1027,8 +1098,8 @@ async def bulk_upsert_decisions(affected_modules_json=json.dumps(headline.get("affected_modules") or []),tags_json=json.dumps(headline.get("tags") or []),evidence_commits_json=json.dumps(headline.get("evidence_commits") or []),- source=headline.get("source", "cli"),- evidence_file=headline.get("evidence_file"),+ source=headline_source,+ evidence_file=headline_evidence_file,evidence_line=headline.get("evidence_line"),confidence=headline.get("confidence", 0.5),)diff --git a/packages/core/src/repowise/core/persistence/decision_id_migration.py b/packages/core/src/repowise/core/persistence/decision_id_migration.pynew file mode 100644index 000000000..4e31ffbdc--- /dev/null+++ b/packages/core/src/repowise/core/persistence/decision_id_migration.py@@ -0,0 +1,369 @@+"""Move existing decisions onto ids derived from their own identity.++A record minted before :func:`derive_decision_id` carries a random id, so a+store that is rebuilt rather than updated gives the same decision a different+id, and every reference held outside the row stops resolving. This walks a+repository's records, computes the id each one would have today, and moves it+there.++A runtime repair rather than an Alembic step, for the reason+:mod:`decision_migration` gives: a data fix that lives in a migration and one+that lives in the code eventually disagree, and only one of them runs on an+existing store. This one has a second reason. The decision vector keys are part+of the rewrite, and Alembic has no handle on the vector store.++Nothing is deleted. A record moves by being copied to its derived id, having+every dependent row repointed at the copy, and only then releasing the id it+came from; an alias records where it went, so an id already written down+somewhere keeps resolving. Idempotent: a second run finds every id already+derived and does nothing.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++import structlog+from sqlalchemy import inspect as sa_inspect+from sqlalchemy import select+from sqlalchemy import text as _sql_text+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.decisions.semantic_match import (+ DECISION_VECTOR_PREFIX,+ decision_vector_item,+ upsert_decision_vectors,+)++from .crud.decisions import derive_decision_id+from .models import (+ DecisionAcceptance,+ DecisionAlias,+ DecisionCandidateMeta,+ DecisionEdge,+ DecisionEvidence,+ DecisionNodeLink,+ DecisionRecord,+ _now_utc,+)++logger = structlog.get_logger(__name__)++#: Written on the alias left behind by a rewrite. Deliberately not "merged":+#: ``resolve_decision_id`` follows a merge even when the aliased record still+#: exists, which is right for a fold and wrong here, where the old id names the+#: same decision rather than a different one that was folded into it.+ALIAS_REASON = "rekeyed"++#: Every column that carries a decision id, including the two that hold one+#: without a foreign key and so are swept along by nothing the database does on+#: its own.+_DEPENDENT_COLUMNS: tuple[tuple[str, str], ...] = (+ ("decision_evidence", "decision_id"),+ ("decision_edges", "src_decision_id"),+ ("decision_edges", "dst_decision_id"),+ ("decision_node_links", "decision_id"),+ ("decision_acceptances", "decision_id"),+ ("decision_candidate_meta", "decision_id"),+ ("decision_candidate_meta", "merged_into"),+ ("decision_aliases", "decision_id"),+ ("decision_records", "superseded_by"),+)+++@dataclass(frozen=True)+class IdRowPlan:+ """What this migration would do to one record."""++ old_id: str+ new_id: str+ title: str+ outcome: str+ reason: str = ""+++@dataclass+class IdMigrationPlan:+ """The per-record outcomes for one repository."""++ rows: list[IdRowPlan] = field(default_factory=list)++ def rewrites(self) -> list[IdRowPlan]:+ return [row for row in self.rows if row.outcome == "rewrite"]++ def counts(self) -> dict[str, int]:+ counts: dict[str, int] = {}+ for row in self.rows:+ counts[row.outcome] = counts.get(row.outcome, 0) + 1+ return counts+++async def plan_id_migration(session: AsyncSession, repository_id: str) -> IdMigrationPlan:+ """Classify every record in *repository_id*. Writes nothing.++ Three outcomes. ``stable`` is a record whose id already derives from its+ own identity, which is what a second run sees for everything. ``rewrite``+ is a move. ``collision`` is a record whose derived id is already spoken+ for, and it is left exactly as it is: two records cannot share a primary+ key, and picking a winner would be resolving a duplicate on the user's+ behalf.+ """+ result = await session.execute(+ select(DecisionRecord)+ .where(DecisionRecord.repository_id == repository_id)+ .order_by(DecisionRecord.created_at, DecisionRecord.id)+ )+ records = list(result.scalars().all())+ existing_ids = {rec.id for rec in records}+ claimed: dict[str, str] = {}+ rows: list[IdRowPlan] = []++ for rec in records:+ new_id = derive_decision_id(+ rec.repository_id,+ rec.title,+ source=rec.source,+ evidence_file=rec.evidence_file,+ )+ if new_id == rec.id:+ rows.append(IdRowPlan(rec.id, new_id, rec.title, "stable"))+ continue+ if new_id in existing_ids:+ rows.append(+ IdRowPlan(+ rec.id,+ new_id,+ rec.title,+ "collision",+ "derived id already belongs to another record",+ )+ )+ continue+ if new_id in claimed:+ rows.append(+ IdRowPlan(+ rec.id,+ new_id,+ rec.title,+ "collision",+ f"another record derives the same id ({claimed[new_id]})",+ )+ )+ continue+ claimed[new_id] = rec.id+ rows.append(IdRowPlan(rec.id, new_id, rec.title, "rewrite"))++ return IdMigrationPlan(rows=rows)+++def _table_names(sync_connection: Any) -> set[str]:+ return set(sa_inspect(sync_connection).get_table_names())+++async def _existing_tables(session: AsyncSession) -> set[str]:+ """Which decision tables this store actually has.++ Introspected on the session's own connection. Reaching for the engine+ instead takes a second connection, and closing it rolls back the+ transaction this migration is running in.+ """+ connection = await session.connection()+ return await connection.run_sync(_table_names)+++async def _rewrite_one(+ session: AsyncSession,+ repository_id: str,+ row: IdRowPlan,+ tables: set[str],+) -> None:+ """Move one record to its derived id without ever orphaning a dependent.++ The order is forced by the foreign keys, which cascade on delete and do+ nothing on update: a dependent cannot point at an id that does not exist+ yet, and a record cannot change a primary key that dependents still point+ at. So the copy comes first and the old row is released last, and between+ those two the decision exists under both ids.++ The copy lands under a placeholder title because the real title is part of+ ``uq_decision_record``, and for the moment both rows exist the real one+ would make them the same decision twice.+ """+ columns = [column.name for column in DecisionRecord.__table__.columns]+ placeholder = f"repowise:id-migration:{row.old_id}"+ projected = ", ".join(+ ":new_id" if name == "id" else (":placeholder" if name == "title" else name)+ for name in columns+ )+ column_list = ", ".join(columns)+ await session.execute(+ _sql_text(+ f"INSERT INTO decision_records ({column_list}) "+ f"SELECT {projected} FROM decision_records WHERE id = :old_id"+ ),+ {"new_id": row.new_id, "placeholder": placeholder, "old_id": row.old_id},+ )++ for table, column in _DEPENDENT_COLUMNS:+ if table not in tables:+ continue+ await session.execute(+ _sql_text(f"UPDATE {table} SET {column} = :new_id WHERE {column} = :old_id"),+ {"new_id": row.new_id, "old_id": row.old_id},+ )++ await session.execute(+ _sql_text("DELETE FROM decision_records WHERE id = :old_id"),+ {"old_id": row.old_id},+ )+ await session.execute(+ _sql_text("UPDATE decision_records SET title = :title WHERE id = :new_id"),+ {"title": row.title, "new_id": row.new_id},+ )++ if "decision_aliases" not in tables:+ return+ if await session.get(DecisionAlias, row.old_id) is not None:+ # This id was already retired once, and the row saying where it went is+ # not ours to rewrite. A merged candidate keeps its record, so it is+ # reachable here: repointing its alias at the moved candidate would+ # undo the merge and leave nothing recording that it happened.+ return+ session.add(+ DecisionAlias(+ alias_id=row.old_id,+ repository_id=repository_id,+ decision_id=row.new_id,+ reason=ALIAS_REASON,+ created_at=_now_utc(),+ )+ )+++def _detach_moved(session: AsyncSession) -> None:+ """Drop every loaded decision row from the session's identity map.++ The rewrites are raw SQL, so anything already loaded still holds the id it+ was loaded under and a later flush would write that departed id back. The+ dependents matter as much as the records: ``DecisionCandidateMeta`` is+ keyed *by* ``decision_id``, so a stale instance flushes an UPDATE matching+ no rows. Detaching rather than expiring, because expiring makes every one+ of them reload on next access, including for a caller that only wanted a+ field it already had.+ """+ detachable = (+ DecisionRecord,+ DecisionAlias,+ DecisionAcceptance,+ DecisionCandidateMeta,+ DecisionEdge,+ DecisionEvidence,+ DecisionNodeLink,+ )+ for obj in list(session.sync_session.identity_map.values()):+ if isinstance(obj, detachable):+ session.expunge(obj)+++async def _rekey_vectors(+ vector_store: Any,+ session: AsyncSession,+ rewrites: list[IdRowPlan],+) -> int:+ """Write each moved decision's embedding under its new key, then drop the old.++ The store cannot hand back a stored vector, so the new key is embedded+ rather than moved. An old key is deleted only once its new key is+ demonstrably in the store: a re-key that half-succeeded should leave a+ stale vector for ``doctor`` to report, not a decision with no vector at+ all.+ """+ if not rewrites:+ return 0+ new_ids = [row.new_id for row in rewrites]+ result = await session.execute(+ select(+ DecisionRecord.id,+ DecisionRecord.title,+ DecisionRecord.decision,+ DecisionRecord.evidence_file,+ ).where(DecisionRecord.id.in_(new_ids))+ )+ items = []+ for new_id, title, decision, evidence_file in result.all():+ item = decision_vector_item(+ new_id, title=title, decision=decision, evidence_file=evidence_file+ )+ if item is not None:+ items.append(item)+ if not items:+ return 0++ await upsert_decision_vectors(vector_store, items)++ try:+ present = await vector_store.list_page_ids()+ except Exception:+ return 0+ landed = {+ row.old_id+ for row in rewrites+ if f"{DECISION_VECTOR_PREFIX}{row.new_id}" in present+ and f"{DECISION_VECTOR_PREFIX}{row.old_id}" in present+ }+ if not landed:+ return 0+ await vector_store.delete_many([f"{DECISION_VECTOR_PREFIX}{old}" for old in sorted(landed)])+ return len(landed)+++async def apply_id_migration(+ session: AsyncSession,+ repository_id: str,+ *,+ plan: IdMigrationPlan | None = None,+ vector_store: Any = None,+) -> IdMigrationPlan:+ """Move every rewritable record onto its derived id, and re-key its vector.++ Idempotent, because the plan classifies an already-derived id as ``stable``+ and this touches nothing else.+ """+ plan = plan or await plan_id_migration(session, repository_id)+ rewrites = plan.rewrites()+ if not rewrites:+ return plan++ # The rewrites are raw SQL, so a record already loaded keeps the id it was+ # loaded under and could write it back. Flush what is pending first, and+ # detach the moved records afterwards.+ await session.flush()++ tables = await _existing_tables(session)+ for row in rewrites:+ # A savepoint per record, because a rewrite that fails halfway has+ # already inserted the copy under a placeholder title. Both callers+ # swallow the exception and commit later, so without this the store+ # keeps a phantom decision that every count and search would pick up,+ # and that the next run would faithfully rekey rather than clean.+ async with session.begin_nested():+ await _rewrite_one(session, repository_id, row, tables)+ await session.flush()+ _detach_moved(session)++ rekeyed = 0+ if vector_store is not None:+ rekeyed = await _rekey_vectors(vector_store, session, rewrites)++ # Collisions are left where they are, so name them rather than letting a+ # count imply everything moved.+ collisions = [row for row in plan.rows if row.outcome == "collision"]+ logger.info(+ "decision_ids_derived",+ repository_id=repository_id,+ rewritten=len(rewrites),+ vectors_rekeyed=rekeyed,+ unchanged_collisions=[row.old_id for row in collisions],+ )+ return plandiff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.pyindex 89e578c47..b6932054d 100644--- a/packages/core/src/repowise/core/persistence/decision_manifest.py+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py@@ -161,13 +161,21 @@ def _differs()-def _apply_entry(entry: ManifestDecision, record: DecisionRecord) -> None:+async def _apply_entry(+ session: AsyncSession, entry: ManifestDecision, record: DecisionRecord+) -> None:"""Copy the file's version of a decision onto the stored record."""record.title = entry.titlerecord.decision = entry.decisionrecord.rationale = entry.reasonrecord.affected_files_json = json.dumps(sorted(entry.scope))- record.superseded_by = entry.superseded_by or None+ # 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+ # retired id back into the column.+ successor = entry.superseded_by or None+ if successor is not None:+ successor = await resolve_decision_id(session, successor) or successor+ record.superseded_by = successorasync def import_manifest(@@ -225,7 +233,7 @@ async def import_manifest(outcome.reaffirmed.append(entry.id)if dry_run:continue- _apply_entry(entry, record)+ await _apply_entry(session, entry, record)if record is None:outcome.created.append(entry.id)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 47dde91e4..b2f5ad217 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -12,6 +12,7 @@ repowise.core.ingestion.models.Symbol in files that import from both modules.from __future__ import annotationsfrom datetime import UTC, datetime+from typing import Anyfrom uuid import uuid4from sqlalchemy import (@@ -33,10 +34,41 @@ def _new_uuid() -> str:return uuid4().hex+#: The source a decision carries when nothing names one. Shared by the column+#: default and by the id derivation, which has to agree with it.+DEFAULT_DECISION_SOURCE = "cli"++def _now_utc() -> datetime:return datetime.now(UTC)+def _derive_decision_id_default(context: Any) -> str:+ """Derive a ``DecisionRecord`` id from the row being inserted.++ The two callers that build a record explicitly derive the id already. This+ catches every other construction path, so a record cannot reach the store+ with a random id merely because it was created somewhere neither covers.++ Imported inside the function because the derivation lives beside the dedupe+ query it has to agree with, in a module that imports this one. It runs at+ flush time, by which point both modules are loaded.+ """+ from .crud.decisions import derive_decision_id++ params = context.get_current_parameters()+ # Column defaults are applied in column order and ``id`` comes first, so a+ # record that left ``source`` to its default has not been given one yet.+ # This and the column read the same constant, so neither the column order+ # nor the default's spelling can make them disagree.+ return derive_decision_id(+ params["repository_id"],+ params.get("title") or "",+ source=params.get("source") or DEFAULT_DECISION_SOURCE,+ evidence_file=params.get("evidence_file"),+ )++class Base(DeclarativeBase):pass@@ -843,7 +875,9 @@ class DecisionRecord(Base):),)- id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ id: Mapped[str] = mapped_column(+ String(32), primary_key=True, default=_derive_decision_id_default+ )repository_id: Mapped[str] = mapped_column(String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False)@@ -870,7 +904,7 @@ class DecisionRecord(Base):# Provenancesource: Mapped[str] = mapped_column(- String(32), nullable=False, default="cli"+ String(32), nullable=False, default=DEFAULT_DECISION_SOURCE) # git_archaeology | inline_marker | adr | pr | comment | session | clievidence_file: Mapped[str | None] = mapped_column(Text, nullable=True)evidence_line: Mapped[int | None] = mapped_column(Integer, nullable=True)diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex ef2534224..8037cab24 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1739,6 +1739,19 @@ 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))+ # 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+ # outside the row. Idempotent, and it never deletes a record.+ try:+ from repowise.core.persistence.decision_id_migration import apply_id_migration++ await apply_id_migration(+ session, repo_id, vector_store=getattr(result, "vector_store", None)+ )+ except Exception as _id_err:+ logger.debug("decision_id_migration_skipped", error=str(_id_err))+# Classify legacy rows against the entity split. A record promoted by# recurrence rather than by a person becomes a candidate, which visibly# shrinks what governs; leaving it to an explicit command would insteaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 9ce58c5e1..ed925a102 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -13,7 +13,10 @@ from sqlalchemy import selectfrom repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIXfrom repowise.core.analysis.decisions.lifecycle import is_governing, status_rank-from repowise.core.persistence.crud.authority import decision_currencies+from repowise.core.persistence.crud.authority import (+ decision_currencies,+ resolve_decision_id,+)from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (DecisionEdge,@@ -212,6 +215,15 @@ async def _why_reference(ctx, repository, records, _target_git = await _load_corpus(repo, None)async with get_session(ctx.session_factory) as session:await _attach_decision_evidence(session, records)+ # This tool tells callers to hold onto the ids it emits, so an id quoted+ # from an earlier session may name a decision that has since moved.+ # Follow the alias for one that no longer matches anything live; a live+ # id is left alone, so a merged candidate still answers about itself.+ stale_decision_id = not reference_id.startswith("ev_") and not any(+ record.id == reference_id for record in records+ )+ if stale_decision_id:+ reference_id = await resolve_decision_id(session, reference_id) or reference_idpayload = {"decisions": [diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 6b1672ad6..737213c88 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -434,6 +434,26 @@ async def update_decision_settings(return _settings_payload(repo_path, resolution)+async def _live_decision_id(session: AsyncSession, decision_id: str) -> str:+ """The id a caller-supplied decision id names today.++ Only for an id that no longer names a record. Ids get retired underneath+ the places they were written down when a decision moves onto a derived id,+ and following the alias is what keeps those working instead of reading as+ deleted.++ A live record always wins, so this cannot redirect one request to a+ different decision. ``resolve_decision_id`` alone would: it follows a merge+ even when the merged record still exists, which is right where the caller+ is asking about the constraint, and wrong here, where the caller named a+ row it is looking at in the candidates lane. An id with neither record nor+ alias resolves to itself, so the handler still raises its own 404.+ """+ if await crud.get_decision(session, decision_id) is not None:+ return decision_id+ return await crud.resolve_decision_id(session, decision_id) or decision_id++@router.get("/api/repos/{repo_id}/decisions/{decision_id}",response_model=DecisionRecordResponse,@@ -444,6 +464,7 @@ async def get_decision(session: AsyncSession = Depends(get_db_session),) -> DecisionRecordResponse:"""Get a single decision record by ID."""+ decision_id = await _live_decision_id(session, decision_id)rec = await crud.get_decision(session, decision_id)if rec is None or rec.repository_id != repo_id:raise HTTPException(status_code=404, detail="Decision not found")@@ -466,6 +487,7 @@ async def list_decision_evidence(badge (``exact`` | ``fuzzy`` | ``unverified``). 404 if the decision does notexist or belongs to a different repository."""+ decision_id = await _live_decision_id(session, decision_id)rec = await crud.get_decision(session, decision_id)if rec is None or rec.repository_id != repo_id:raise HTTPException(status_code=404, detail="Decision not found")@@ -488,6 +510,7 @@ async def get_decision_lineage(UI can render a timeline. An isolated decision returns a single-entry chain.404 if the decision does not exist or belongs to a different repository."""+ decision_id = await _live_decision_id(session, decision_id)rec = await crud.get_decision(session, decision_id)if rec is None or rec.repository_id != repo_id:raise HTTPException(status_code=404, detail="Decision not found")@@ -581,17 +604,23 @@ async def patch_decision(governance edits (``affected_modules``, ``affected_files``). Any fieldleft as ``None`` in the body is preserved."""+ decision_id = await _live_decision_id(session, decision_id)rec = await crud.get_decision(session, decision_id)if rec is None or rec.repository_id != repo_id:raise HTTPException(status_code=404, detail="Decision not found")if body.status is not None:+ # The successor is a caller-supplied id too, and storing a retired one+ # would record a pointer that no longer resolves.+ superseded_by = body.superseded_by+ if superseded_by is not None:+ superseded_by = await _live_decision_id(session, superseded_by)try:rec = await crud.update_decision_status(session,decision_id,body.status,- superseded_by=body.superseded_by,+ superseded_by=superseded_by,accepter="web",)except ValueError as exc:diff --git a/tests/unit/persistence/test_decision_stable_ids.py b/tests/unit/persistence/test_decision_stable_ids.pynew file mode 100644index 000000000..5e27cadd7--- /dev/null+++ b/tests/unit/persistence/test_decision_stable_ids.py@@ -0,0 +1,449 @@+"""A decision's id derives from its identity, so a rebuild does not move it.++Two contracts. The id of a record is a function of the four columns+``uq_decision_record`` already declares unique, at every site that mints one;+and a store whose records predate that keeps working, because the migration+moves them rather than re-minting them, and leaves an alias behind.+"""++from __future__ import annotations++import pytest+from sqlalchemy import func, select+from sqlalchemy import text as sql_text++from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX+from repowise.core.persistence.crud import bulk_upsert_decisions, upsert_decision+from repowise.core.persistence.crud.authority import resolve_decision_id+from repowise.core.persistence.crud.decisions import derive_decision_id+from repowise.core.persistence.decision_graph import sync_decision_node_links+from repowise.core.persistence.decision_id_migration import (+ ALIAS_REASON,+ apply_id_migration,+ plan_id_migration,+)+from repowise.core.persistence.models import (+ DecisionAlias,+ DecisionEvidence,+ DecisionNodeLink,+ DecisionRecord,+)+from tests.unit.persistence.helpers import insert_repo++# Applied per test: two of these are plain functions.+pytestmark: list = []+++def _dict(title: str, **overrides) -> dict:+ base = {+ "title": title,+ "decision": f"{title}: do the thing",+ "rationale": "because the alternative was measured slower",+ "source": "session",+ "status": "proposed",+ "affected_files": ["src/app.py"],+ "evidence_file": "src/app.py",+ "confidence": 0.7,+ "verification": "exact",+ "source_quote": f"{title}: do the thing",+ }+ base.update(overrides)+ return base+++# ---------------------------------------------------------------------------+# The derivation itself+# ---------------------------------------------------------------------------+++def test_the_id_is_a_function_of_the_four_columns_the_schema_calls_unique():+ args = ("repo1", "Prefer the boring option")+ kwargs = {"source": "session", "evidence_file": "src/app.py"}+ first = derive_decision_id(*args, **kwargs)++ assert first == derive_decision_id(*args, **kwargs)+ assert len(first) == 32+ assert all(char in "0123456789abcdef" for char in first)++ # Each of the four is load-bearing.+ assert first != derive_decision_id("repo2", args[1], **kwargs)+ assert first != derive_decision_id(args[0], "Another title", **kwargs)+ assert first != derive_decision_id(*args, source="pr", evidence_file="src/app.py")+ assert first != derive_decision_id(*args, source="session", evidence_file="src/b.py")+++def test_a_null_evidence_file_is_not_an_empty_one():+ """The dedupe query treats those as different records, so this must too."""+ absent = derive_decision_id("repo1", "T", source="cli", evidence_file=None)+ empty = derive_decision_id("repo1", "T", source="cli", evidence_file="")+ assert absent != empty+++async def test_upsert_derives_the_id_it_stores(async_session):+ repo = await insert_repo(async_session)+ rec = await upsert_decision(+ async_session,+ repository_id=repo.id,+ title="Prefer the boring option",+ source="cli",+ evidence_file="src/app.py",+ )+ assert rec.id == derive_decision_id(+ repo.id, "Prefer the boring option", source="cli", evidence_file="src/app.py"+ )+++async def test_bulk_upsert_derives_the_id_it_stores(async_session):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(async_session, repo.id, [_dict("Cache the parse tree")])+ rec = (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ ).scalar_one()+ assert rec.id == derive_decision_id(+ repo.id, rec.title, source=rec.source, evidence_file=rec.evidence_file+ )+++async def test_a_record_built_anywhere_else_still_derives_its_id(async_session):+ """The column default catches construction paths the two callers do not."""+ repo = await insert_repo(async_session)+ rec = DecisionRecord(+ repository_id=repo.id,+ title="Built without an explicit id",+ source="git_archaeology",+ evidence_file=None,+ )+ async_session.add(rec)+ await async_session.flush()++ assert rec.id == derive_decision_id(+ repo.id, "Built without an explicit id", source="git_archaeology", evidence_file=None+ )+++async def test_an_explicit_id_still_wins(async_session):+ """The manifest importer carries ids in from a tracked file."""+ repo = await insert_repo(async_session)+ rec = await upsert_decision(+ async_session,+ repository_id=repo.id,+ title="Imported from the manifest",+ source="cli",+ decision_id="0" * 32,+ )+ assert rec.id == "0" * 32+++# ---------------------------------------------------------------------------+# The property the whole change exists for+# ---------------------------------------------------------------------------+++async def test_a_store_rebuilt_from_scratch_gives_every_decision_the_same_id(+ session_factory, async_engine+):+ """Index, rebuild from nothing, and the ids have to match.++ The two repositories are seeded identically and independently. Before the+ id derived from the record, this failed on the first row.+ """+ titles = ["Cache the parse tree", "Ship the CLI first", "Keep the schema flat"]++ async def build() -> dict[str, str]:+ async with session_factory() as session:+ repo = await insert_repo(session, name="rebuilt", local_path="/tmp/rebuilt")+ await bulk_upsert_decisions(+ session, repo.id, [_dict(t) for t in titles]+ )+ await session.commit()+ rows = (+ await session.execute(+ select(DecisionRecord.title, DecisionRecord.id).where(+ DecisionRecord.repository_id == repo.id+ )+ )+ ).all()+ # Drop the records, keep nothing, and build the same repo again.+ await session.execute(sql_text("DELETE FROM decision_node_links"))+ await session.execute(sql_text("DELETE FROM decision_evidence"))+ await session.execute(sql_text("DELETE FROM decision_records"))+ await session.commit()+ return {title: rec_id for title, rec_id in rows}++ first = await build()+ second = await build()++ assert first == second+ assert len(first) == len(titles)+++# ---------------------------------------------------------------------------+# Migrating a store whose records predate the derivation+# ---------------------------------------------------------------------------+++async def _legacy_record(session, repo_id: str, title: str, **overrides) -> DecisionRecord:+ """A record carrying a random id, the way every store already holds them."""+ rec = DecisionRecord(+ id=overrides.pop("id", None) or f"legacy{title.replace(' ', '')[:10]:0<26}"[:32],+ repository_id=repo_id,+ title=title,+ source="session",+ evidence_file=overrides.pop("evidence_file", "src/app.py"),+ decision=f"{title}: do the thing",+ **overrides,+ )+ session.add(rec)+ await session.flush()+ return rec+++async def test_the_plan_reports_what_it_would_move_and_writes_nothing(async_session):+ repo = await insert_repo(async_session)+ legacy = await _legacy_record(async_session, repo.id, "Legacy one")++ plan = await plan_id_migration(async_session, repo.id)++ assert plan.counts() == {"rewrite": 1}+ assert plan.rewrites()[0].old_id == legacy.id+ assert plan.rewrites()[0].title == "Legacy one"+ # Nothing moved.+ assert (await async_session.get(DecisionRecord, legacy.id)) is not None+++async def test_the_migration_moves_the_record_and_takes_its_dependents_with_it(async_session):+ repo = await insert_repo(async_session)+ legacy = await _legacy_record(async_session, repo.id, "Legacy one")+ async_session.add(+ DecisionEvidence(+ decision_id=legacy.id, source="session", evidence_file="src/app.py", source_quote="q"+ )+ )+ await sync_decision_node_links(+ async_session, repo.id, legacy.id, files=["src/app.py"], modules=[]+ )+ await async_session.flush()+ old_id = legacy.id+ new_id = derive_decision_id(+ repo.id, "Legacy one", source="session", evidence_file="src/app.py"+ )++ await apply_id_migration(async_session, repo.id)++ assert (await async_session.get(DecisionRecord, new_id)) is not None+ assert (await async_session.get(DecisionRecord, old_id)) is None++ evidence_ids = (+ await async_session.execute(select(DecisionEvidence.decision_id))+ ).scalars().all()+ link_ids = (+ await async_session.execute(select(DecisionNodeLink.decision_id))+ ).scalars().all()+ assert set(evidence_ids) == {new_id}+ assert set(link_ids) == {new_id}+ # The title survived the placeholder it was parked under.+ moved = await async_session.get(DecisionRecord, new_id)+ assert moved.title == "Legacy one"+++async def test_the_old_id_still_resolves_afterwards(async_session):+ repo = await insert_repo(async_session)+ legacy = await _legacy_record(async_session, repo.id, "Legacy one")+ old_id = legacy.id++ await apply_id_migration(async_session, repo.id)++ alias = await async_session.get(DecisionAlias, old_id)+ assert alias is not None+ assert alias.reason == ALIAS_REASON+ # The point of the alias: an id written down elsewhere keeps working.+ assert await resolve_decision_id(async_session, old_id) == alias.decision_id+++async def test_the_migration_never_deletes_a_decision(async_session):+ repo = await insert_repo(async_session)+ for title in ("One", "Two", "Three"):+ await _legacy_record(async_session, repo.id, title)+ before = (await async_session.execute(select(func.count(DecisionRecord.id)))).scalar_one()++ await apply_id_migration(async_session, repo.id)++ after = (await async_session.execute(select(func.count(DecisionRecord.id)))).scalar_one()+ assert after == before == 3+++async def test_a_second_run_finds_every_id_already_derived(async_session):+ repo = await insert_repo(async_session)+ await _legacy_record(async_session, repo.id, "Legacy one")++ await apply_id_migration(async_session, repo.id)+ ids_after_first = set(+ (await async_session.execute(select(DecisionRecord.id))).scalars().all()+ )+ aliases_after_first = (+ await async_session.execute(select(func.count(DecisionAlias.alias_id)))+ ).scalar_one()++ second = await apply_id_migration(async_session, repo.id)++ assert second.counts() == {"stable": 1}+ assert (+ set((await async_session.execute(select(DecisionRecord.id))).scalars().all())+ == ids_after_first+ )+ assert (+ await async_session.execute(select(func.count(DecisionAlias.alias_id)))+ ).scalar_one() == aliases_after_first+++async def test_two_records_that_derive_the_same_id_keep_the_second_one(async_session):+ """A real collision, and neither record is ours to discard.++ ``uq_decision_record`` does not fire when ``evidence_file`` is NULL,+ because SQL calls two NULLs distinct, so a store can already hold two rows+ that derive one id. The first moves; the second stays exactly where it is+ rather than being folded into it.+ """+ repo = await insert_repo(async_session)+ first = await _legacy_record(+ async_session, repo.id, "Same identity", id="a" * 32, evidence_file=None+ )+ second = await _legacy_record(+ async_session, repo.id, "Same identity", id="b" * 32, evidence_file=None+ )+ derived = derive_decision_id(+ repo.id, "Same identity", source="session", evidence_file=None+ )++ plan = await apply_id_migration(async_session, repo.id)++ assert plan.counts() == {"rewrite": 1, "collision": 1}+ assert (await async_session.get(DecisionRecord, derived)) is not None+ # The loser kept its row and its id; nothing was merged away.+ survivor = second.id if first.id == "a" * 32 else first.id+ assert (await async_session.get(DecisionRecord, survivor)) is not None+ assert (+ await async_session.execute(select(func.count(DecisionRecord.id)))+ ).scalar_one() == 2+++async def test_the_rewrite_holds_the_foreign_keys_at_every_step(async_session):+ """The ordering is the whole risk: a wrong one cascades rows away.++ The unit-test engine leaves ``foreign_keys`` off, so this turns it on to+ exercise the constraint the real store enforces on every connection.+ """+ await async_session.execute(sql_text("PRAGMA foreign_keys=ON"))+ repo = await insert_repo(async_session)+ legacy = await _legacy_record(async_session, repo.id, "Legacy one")+ async_session.add(+ DecisionEvidence(+ decision_id=legacy.id, source="session", evidence_file="src/app.py", source_quote="q"+ )+ )+ await async_session.flush()++ await apply_id_migration(async_session, repo.id)++ # A cascade would have taken the evidence row with it.+ assert (+ await async_session.execute(select(func.count(DecisionEvidence.id)))+ ).scalar_one() == 1+++async def test_the_decision_vectors_move_to_the_new_key(async_session, in_memory_vector_store):+ repo = await insert_repo(async_session)+ legacy = await _legacy_record(async_session, repo.id, "Legacy one")+ old_id = legacy.id+ await in_memory_vector_store.embed_and_upsert(+ f"{DECISION_VECTOR_PREFIX}{old_id}",+ "Legacy one: do the thing",+ {"title": "Legacy one", "page_type": "decision_record"},+ )+ new_id = derive_decision_id(+ repo.id, "Legacy one", source="session", evidence_file="src/app.py"+ )++ await apply_id_migration(async_session, repo.id, vector_store=in_memory_vector_store)++ keys = await in_memory_vector_store.list_page_ids()+ assert f"{DECISION_VECTOR_PREFIX}{new_id}" in keys+ assert f"{DECISION_VECTOR_PREFIX}{old_id}" not in keys+++async def test_a_merge_alias_survives_the_move(async_session):+ """A merged candidate keeps its record, so the migration reaches it.++ Repointing its alias at the moved candidate would undo the merge and leave+ nothing recording that it happened.+ """+ repo = await insert_repo(async_session)+ folded = await _legacy_record(async_session, repo.id, "Folded away")+ target = await _legacy_record(async_session, repo.id, "The survivor")+ async_session.add(+ DecisionAlias(+ alias_id=folded.id,+ repository_id=repo.id,+ decision_id=target.id,+ reason="merged",+ )+ )+ await async_session.flush()+ folded_id, target_id = folded.id, target.id++ await apply_id_migration(async_session, repo.id)++ alias = await async_session.get(DecisionAlias, folded_id)+ assert alias.reason == "merged"+ # Still points at the survivor, which itself moved, rather than at the+ # candidate that was folded away.+ assert alias.decision_id != folded_id+ assert alias.decision_id == derive_decision_id(+ repo.id, "The survivor", source="session", evidence_file="src/app.py"+ )+ assert target_id != alias.decision_id+++async def test_a_failed_rewrite_leaves_no_half_moved_record(async_session, monkeypatch):+ """Both callers swallow the exception and commit later.++ Without a savepoint the store would keep the copy, under its placeholder+ title, as a phantom decision that every count and search picks up.+ """+ repo = await insert_repo(async_session)+ await _legacy_record(async_session, repo.id, "Legacy one")++ import repowise.core.persistence.decision_id_migration as mod++ real = mod._rewrite_one++ async def _explode(session, repository_id, row, tables):+ await real(session, repository_id, row, tables)+ raise RuntimeError("boom")++ monkeypatch.setattr(mod, "_rewrite_one", _explode)++ with pytest.raises(RuntimeError):+ await apply_id_migration(async_session, repo.id)++ titles = (+ (await async_session.execute(select(DecisionRecord.title))).scalars().all()+ )+ assert titles == ["Legacy one"]diff --git a/tests/unit/server/test_decisions_alias_resolution.py b/tests/unit/server/test_decisions_alias_resolution.pynew file mode 100644index 000000000..bc87f7a41--- /dev/null+++ b/tests/unit/server/test_decisions_alias_resolution.py@@ -0,0 +1,123 @@+"""An id that outlived the row it named still reaches the right decision.++Decisions move onto derived ids, which retires the id anything outside the+store wrote down, so the id-taking routes resolve through the alias table. The+resolution has to be narrow: a live record always answers about itself, or a+merged candidate sitting in the review lane would answer as the decision it was+folded into, and a PATCH aimed at the candidate would land on that decision.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import DecisionAlias+from tests.unit.server.conftest import create_test_repo+++async def _record(session_factory, repo_id: str, title: str) -> str:+ async with get_session(session_factory) as session:+ rec = await crud.upsert_decision(+ session,+ repository_id=repo_id,+ title=title,+ status="proposed",+ context="ctx",+ decision="dec",+ rationale="why",+ source="inline_marker",+ affected_files=["src/app.py"],+ )+ await session.commit()+ return rec.id+++async def test_a_retired_id_still_reaches_its_decision(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ live = await _record(sf, repo["id"], "Prefer the boring option")+ retired = "f" * 32+ async with get_session(sf) as session:+ session.add(+ DecisionAlias(+ alias_id=retired,+ repository_id=repo["id"],+ decision_id=live,+ reason="rekeyed",+ )+ )+ await session.commit()++ resp = await client.get(f"/api/repos/{repo['id']}/decisions/{retired}")++ assert resp.status_code == 200+ assert resp.json()["id"] == live+ assert resp.json()["title"] == "Prefer the boring option"+++async def test_a_merged_candidate_still_answers_about_itself(+ client: AsyncClient, app+) -> None:+ """A merge keeps the candidate's row, and the review lane still lists it.++ Following the merge here would answer a click on the candidate with a+ different decision's title and evidence.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ folded = await _record(sf, repo["id"], "Folded away")+ target = await _record(sf, repo["id"], "The survivor")+ async with get_session(sf) as session:+ session.add(+ DecisionAlias(+ alias_id=folded,+ repository_id=repo["id"],+ decision_id=target,+ reason="merged",+ )+ )+ await session.commit()++ resp = await client.get(f"/api/repos/{repo['id']}/decisions/{folded}")++ assert resp.status_code == 200+ assert resp.json()["id"] == folded+ assert resp.json()["title"] == "Folded away"+++async def test_a_patch_lands_on_the_record_it_named(client: AsyncClient, app) -> None:+ """The dangerous case: dismissing a leftover candidate from the lane.++ If the merge were followed, this would withdraw the decision it was folded+ into instead.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ folded = await _record(sf, repo["id"], "Folded away")+ target = await _record(sf, repo["id"], "The survivor")+ async with get_session(sf) as session:+ session.add(+ DecisionAlias(+ alias_id=folded,+ repository_id=repo["id"],+ decision_id=target,+ reason="merged",+ )+ )+ await session.commit()++ resp = await client.patch(+ f"/api/repos/{repo['id']}/decisions/{folded}",+ json={"status": "dismissed"},+ )++ assert resp.status_code == 200+ assert resp.json()["id"] == folded+ survivor = await client.get(f"/api/repos/{repo['id']}/decisions/{target}")+ assert survivor.json()["status"] != "dismissed"