Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

@ feat(ultrawiki): identity layer with deterministic, reversible resolution (P5)

Ruben Lütkeb925b6ab88c7
diff --git a/jarvis/ultrawiki/identity.py b/jarvis/ultrawiki/identity.py
new file mode 100644
index 0000000000..350c96844d
--- /dev/null
+++ b/jarvis/ultrawiki/identity.py
@@ -0,0 +1,505 @@
+"""UltraWiki identity resolution — the decision logic, free of any database.
+
+Design doc 05 (D-10). The single most dangerous failure in a personal memory
+is a **wrong merge**: fuse two people into one entity and every answer about
+either is silently wrong, discovered months later. A wrong *split* is annoying
+and repairable; a wrong merge is poison. The whole module exists to make that
+asymmetry structural rather than a matter of tuning.
+
+Three tiers, and only the first one is ever applied without asking:
+
+1. :attr:`MatchTier.DETERMINISTIC` — the two identities share a **unique**
+ identifier: the same e-mail address, the same phone number, the same
+ address-book record. Merged automatically.
+2. :attr:`MatchTier.PROBABLE` — name similarity, a nickname pattern, an exact
+ *name* collision. Proposed only: the pair lands in the confirmation queue
+ and both identities keep answering separately until a human decides.
+3. :attr:`MatchTier.WEAK` — below the proposal threshold. Nothing happens at
+ all; the queue stays short by design.
+
+**A name never auto-merges, however close it looks.** That is not caution for
+its own sake: speech-to-text produces near-name variants of one topic
+("agentic-i", "gentic-ide"), and normalization aggressive enough to fuse
+those would equally fuse two different people who share a name. So name
+normalization here stays deliberately conservative — Unicode NFC, whitespace
+collapse, edge punctuation, case folding, and nothing else. "Ultra Wiki",
+"ultra-wiki" and "UltraWiki" therefore remain three keys that get *proposed*
+to each other, never silently welded together.
+
+Everything in this module is pure, deterministic, stdlib-only and offline: no
+model, no network, no clock, no database. The SQL side lives in
+``jarvis/ultrawiki/identity_store.py``.
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+from dataclasses import dataclass, field
+from difflib import SequenceMatcher
+from enum import StrEnum
+from typing import Any
+
+__all__ = [
+ "DETERMINISTIC_KINDS",
+ "FUZZY_CANDIDATE_LIMIT",
+ "LEN_WINDOW",
+ "MAX_NAME_CHARS",
+ "MAX_PROPOSALS",
+ "MERGEABLE_TIERS",
+ "MIN_NAME_CHARS",
+ "MIN_NICKNAME_CHARS",
+ "MIN_PHONE_DIGITS",
+ "NICKNAME_MAX_RATIO",
+ "NICKNAME_SCORE",
+ "PREFIX_BLOCK_CHARS",
+ "PROPOSE_THRESHOLD",
+ "EntityKind",
+ "IdentifierKind",
+ "IdentityError",
+ "MatchEvidence",
+ "MatchTier",
+ "QueueStatus",
+ "Resolution",
+ "ResolutionKind",
+ "could_match",
+ "escape_like",
+ "name_similarity",
+ "nickname_score",
+ "normalize_contact_slug",
+ "normalize_email",
+ "normalize_handle",
+ "normalize_identifier",
+ "normalize_name",
+ "normalize_phone",
+ "pair_key",
+ "tier_for_score",
+]
+
+
+class IdentityError(RuntimeError):
+ """Raised when an identity operation is refused (never for a bad match).
+
+ A refusal means the *operation* is impossible — an unknown queue id, a
+ merge that was already undone, an out-of-order unmerge. Uncertainty about
+ a match is never an error; it is a queue row.
+ """
+
+
+# ---------------------------------------------------------------------------
+# Canonical value sets (five-layer drift rule, AP-4/BUG-008)
+# ---------------------------------------------------------------------------
+
+
+class EntityKind(StrEnum):
+ """What an entity *is*. Identity resolution treats every kind the same;
+ the kind only scopes lookups and the People view."""
+
+ PERSON = "person"
+ PLACE = "place"
+ ORG = "org"
+ PROJECT = "project"
+ TOPIC = "topic"
+
+
+class IdentifierKind(StrEnum):
+ """One raw handle mapped onto an entity.
+
+ ``CONTACT`` is the slug of a record in the Jarvis contacts store — the
+ address book the user curates by hand, and therefore an identifier as
+ unique as an e-mail address.
+ """
+
+ EMAIL = "email"
+ PHONE = "phone"
+ CONTACT = "contact"
+ HANDLE = "handle"
+ NAME = "name"
+
+
+#: The kinds unique enough that an exact match may merge two entities without
+#: asking (design doc 05, tier 1). ``HANDLE`` is deliberately NOT here: the
+#: same handle on two platforms is two different people, and the namespace
+#: prefix is only as trustworthy as the connector that supplied it.
+DETERMINISTIC_KINDS: frozenset[IdentifierKind] = frozenset(
+ {IdentifierKind.EMAIL, IdentifierKind.PHONE, IdentifierKind.CONTACT}
+)
+
+
+class MatchTier(StrEnum):
+ """How strong the evidence linking two identities is."""
+
+ DETERMINISTIC = "deterministic"
+ PROBABLE = "probable"
+ WEAK = "weak"
+
+
+#: The tiers a merge row may ever carry. ``WEAK`` is structurally excluded:
+#: below the proposal threshold nothing is written at all, so a weak merge
+#: cannot exist and the SQL CHECK says so.
+MERGEABLE_TIERS: frozenset[MatchTier] = frozenset(
+ {MatchTier.DETERMINISTIC, MatchTier.PROBABLE}
+)
+
+
+class QueueStatus(StrEnum):
+ """State of one confirmation-queue row.
+
+ ``REJECTED`` is permanent by design (anti-confirmation-fatigue): once the
+ user has said "these are two different people", re-observing the same weak
+ evidence must never ask again.
+ """
+
+ PENDING = "pending"
+ CONFIRMED = "confirmed"
+ REJECTED = "rejected"
+
+
+class ResolutionKind(StrEnum):
+ """How one observation was resolved onto an entity.
+
+ Distinct from :class:`MatchTier`, which grades the evidence between a
+ *pair* of entities. ``AMBIGUOUS`` is the honest refusal: the observation
+ pointed at several entities at once, so nothing was linked and the
+ colliding pairs were proposed instead.
+ """
+
+ DETERMINISTIC = "deterministic"
+ NAME_ANCHOR = "name_anchor"
+ CREATED = "created"
+ AMBIGUOUS = "ambiguous"
+ UNRESOLVED = "unresolved"
+
+
+# ---------------------------------------------------------------------------
+# Tuning constants — every one of them is a policy, not a magic number
+# ---------------------------------------------------------------------------
+
+#: Length bounds of a usable name. Below the floor a "name" is an initial or
+#: stray punctuation; above the ceiling an extractor handed back a sentence.
+#: Kept in lockstep with ``projection.MIN_LABEL_CHARS`` / ``MAX_LABEL_CHARS``
+#: by ``tests/unit/ultrawiki/test_identity.py``.
+MIN_NAME_CHARS = 2
+MAX_NAME_CHARS = 80
+
+#: A phone number shorter than this is a short code or a fragment, not a
+#: globally unique identifier — it normalizes to ``None`` and therefore can
+#: never merge anything.
+MIN_PHONE_DIGITS = 6
+
+#: At or above this similarity a pair is PROPOSED; below it nothing happens.
+#: Calibrated against two real families of near-names: speech-to-text variants
+#: of one topic ("agentic-i" ~ "gentic-ide" = 0.84) must be proposed, while
+#: two distinct people sharing a surname ("john smith" ~ "jane smith" = 0.80)
+#: must not even reach the queue.
+PROPOSE_THRESHOLD = 0.82
+
+#: Score assigned to a nickname/abbreviation hit ("viki" inside "viktoria").
+#: Deliberately just above the proposal threshold: it is enough to ask, never
+#: enough to act.
+NICKNAME_SCORE = 0.84
+
+#: A nickname candidate must be at least this long and the token it abbreviates
+#: at most this many times longer — otherwise "ana" would propose itself into
+#: half the address book.
+MIN_NICKNAME_CHARS = 4
+NICKNAME_MAX_RATIO = 3
+
+#: Candidate blocking. A fuzzy partner is only ever looked for among names of
+#: a similar LENGTH or sharing the leading characters; both halves are applied
+#: identically in SQL and in :func:`could_match`, so the two layers cannot
+#: disagree about what a candidate is.
+LEN_WINDOW = 4
+PREFIX_BLOCK_CHARS = 3
+
+#: Hard caps so one observation can never flood the queue or the CPU.
+FUZZY_CANDIDATE_LIMIT = 400
+MAX_PROPOSALS = 5
+
+
+_WS_RE = re.compile(r"\s+")
+_NON_DIGIT_RE = re.compile(r"\D")
+#: Dependency-free e-mail shape check (the base install carries no validator
+#: library) — the same pragmatic rule the contacts store applies.
+_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+#: Trimmed from both ENDS of a name only. Internal punctuation is preserved on
+#: purpose: collapsing "ultra-wiki" onto "ultra wiki" would be an implicit
+#: merge on name similarity, which is exactly what this module refuses to do.
+_EDGE_PUNCTUATION = " \t\r\n.,;:!?-–—_'\"()[]{}<>/\\|*@#"
+
+
+# ---------------------------------------------------------------------------
+# Normalization
+# ---------------------------------------------------------------------------
+
+
+def normalize_name(raw: object) -> str | None:
+ """Canonical lookup key for a name, or ``None`` when it is unusable.
+
+ NFC is load-bearing rather than cosmetic: macOS hands text back
+ decomposed, so without it the same name becomes two entities.
+ """
+ if not isinstance(raw, str):
+ return None
+ collapsed = _WS_RE.sub(" ", raw).strip()
+ text = unicodedata.normalize("NFC", collapsed).strip(_EDGE_PUNCTUATION)
+ text = _WS_RE.sub(" ", text).strip()
+ if not MIN_NAME_CHARS <= len(text) <= MAX_NAME_CHARS:
+ return None
+ return text.casefold()
+
+
+def normalize_email(raw: object) -> str | None:
+ """Lower-cased address without a ``mailto:`` wrapper, or ``None``."""
+ if not isinstance(raw, str):
+ return None
+ text = raw.strip().strip("<>").strip().lower()
+ if text.startswith("mailto:"):
+ text = text[len("mailto:") :].strip()
+ return text if _EMAIL_RE.match(text) else None
+
+
+def normalize_phone(raw: object) -> str | None:
+ """Best-effort E.164 key, mirroring ``jarvis.contacts.store``.
+
+ ``"+49 151 2345-6789"`` and ``"0049 151 23456789"`` collapse onto the same
+ key, which is what makes "same phone number" a deterministic match across
+ two sources that formatted it differently. Numbers with fewer than
+ :data:`MIN_PHONE_DIGITS` digits are refused rather than trusted.
+ """
+ if not isinstance(raw, str):
+ return None
+ text = raw.strip()
+ digits = _NON_DIGIT_RE.sub("", text)
+ if text.startswith("+"):
+ normalized = "+" + digits
+ elif digits.startswith("00"):
+ normalized = "+" + digits[2:]
+ else:
+ normalized = digits
+ if len(_NON_DIGIT_RE.sub("", normalized)) < MIN_PHONE_DIGITS:
+ return None
+ return normalized
+
+
+def normalize_handle(raw: object) -> str | None:
+ """``"Slack:@RL"`` → ``"slack:rl"``; a bare handle keeps its own name."""
+ if not isinstance(raw, str):
+ return None
+ text = _WS_RE.sub("", raw).strip().lower().lstrip("@")
+ if ":" in text:
+ namespace, _, rest = text.partition(":")
+ text = f"{namespace.strip()}:{rest.strip().lstrip('@')}"
+ if not namespace.strip() or not rest.strip().lstrip("@"):
+ return None
+ return text if len(text) >= 2 else None
+
+
+def normalize_contact_slug(raw: object) -> str | None:
+ """The address-book slug, lower-cased and whitespace-free."""
+ if not isinstance(raw, str):
+ return None
+ text = _WS_RE.sub("", raw).strip().lower()
+ return text or None
+
+
+_NORMALIZERS: dict[IdentifierKind, Any] = {
+ IdentifierKind.EMAIL: normalize_email,
+ IdentifierKind.PHONE: normalize_phone,
+ IdentifierKind.CONTACT: normalize_contact_slug,
+ IdentifierKind.HANDLE: normalize_handle,
+ IdentifierKind.NAME: normalize_name,
+}
+
+
+def normalize_identifier(kind: IdentifierKind | str, raw: object) -> str | None:
+ """Canonical stored value for one identifier, or ``None`` to drop it."""
+ try:
+ resolved = IdentifierKind(kind)
+ except ValueError:
+ return None
+ return _NORMALIZERS[resolved](raw)
+
+
+# ---------------------------------------------------------------------------
+# Similarity — deterministic, stdlib only, no model anywhere near it
+# ---------------------------------------------------------------------------
+
+
+def _token_sorted(name: str) -> str:
+ return " ".join(sorted(name.split()))
+
+
+def _is_subsequence(short: str, long: str) -> bool:
+ it = iter(long)
+ return all(char in it for char in short)
+
+
+def nickname_score(a: str, b: str) -> float:
+ """:data:`NICKNAME_SCORE` when one name abbreviates a token of the other.
+
+ "Viki" is not similar to "Viktoria Novak" by any string metric, yet it is
+ the canonical example of a probable match. The rule is deliberately narrow:
+ the short form must be a single word, start on the same character, be a
+ subsequence of one token of the long form, and not be dwarfed by it.
+ """
+ short, long = (a, b) if len(a) <= len(b) else (b, a)
+ if len(short) < MIN_NICKNAME_CHARS or " " in short or short == long:
+ return 0.0
+ for token in long.split():
+ if not len(short) < len(token) <= NICKNAME_MAX_RATIO * len(short):
+ continue
+ if token[0] != short[0]:
+ continue
+ if _is_subsequence(short, token):
+ return NICKNAME_SCORE
+ return 0.0
+
+
+def name_similarity(a: str, b: str) -> float:
+ """0..1 similarity of two ALREADY NORMALIZED names.
+
+ Three deterministic views, best one wins: raw character similarity, the
+ same over token-sorted forms (so "novak viktoria" matches "viktoria
+ novak"), and the nickname rule.
+ """
+ if not a or not b:
+ return 0.0
+ if a == b:
+ return 1.0
+ best = SequenceMatcher(None, a, b).ratio()
+ sorted_a, sorted_b = _token_sorted(a), _token_sorted(b)
+ if (sorted_a, sorted_b) != (a, b):
+ best = max(best, SequenceMatcher(None, sorted_a, sorted_b).ratio())
+ return max(best, nickname_score(a, b))
+
+
+def could_match(a: str, b: str) -> bool:
+ """Cheap O(len) gate applied before the quadratic ratio.
+
+ The exact predicate the candidate SQL uses, so a partner the database
+ returns is never discarded by a rule the database did not know about.
+ """
+ if not a or not b:
+ return False
+ if abs(len(a) - len(b)) <= LEN_WINDOW:
+ return True
+ prefix = a[:PREFIX_BLOCK_CHARS]
+ return len(prefix) == PREFIX_BLOCK_CHARS and b.startswith(prefix)
+
+
+def tier_for_score(score: float) -> MatchTier:
+ """Map a similarity score onto its tier. Never returns DETERMINISTIC —
+ a score can only ever propose, never decide."""
+ return MatchTier.PROBABLE if score >= PROPOSE_THRESHOLD else MatchTier.WEAK
+
+
+def pair_key(left_id: int, right_id: int) -> str:
+ """Order-independent key of an entity pair (one open proposal per pair)."""
+ low, high = sorted((int(left_id), int(right_id)))
+ return f"{low}:{high}"
+
+
+def escape_like(text: str) -> str:
+ """Escape ``\\``, ``%`` and ``_`` for a ``LIKE ... ESCAPE '\\'`` pattern."""
+ return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
+# ---------------------------------------------------------------------------
+# Result shapes
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class MatchEvidence:
+ """One reason two identities were linked — or proposed.
+
+ Persisted verbatim into ``uw_merge_log.evidence_json`` and
+ ``uw_confirm_queue.evidence_json``, because "why did this merge happen"
+ must still be answerable months later, by a human, without the code.
+ """
+
+ tier: MatchTier
+ kind: str
+ value: str
+ score: float = 1.0
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "tier": str(self.tier),
+ "kind": self.kind,
+ "value": self.value,
+ "score": round(float(self.score), 4),
+ }
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> MatchEvidence:
+ return cls(
+ tier=MatchTier(str(payload.get("tier", MatchTier.PROBABLE))),
+ kind=str(payload.get("kind", "")),
+ value=str(payload.get("value", "")),
+ score=float(payload.get("score", 0.0) or 0.0),
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Resolution:
+ """What resolving one observation did.
+
+ ``entity_id`` is ``None`` exactly when nothing was linked: either the
+ evidence was ambiguous (``kind == AMBIGUOUS``, the colliding entities are
+ in ``ambiguous``) or nothing matched and creation was not requested.
+ """
+
+ entity_id: int | None
+ kind: ResolutionKind
+ created: bool = False
+ merged: tuple[int, ...] = () # uw_merge_log ids written by this call
+ queued: tuple[int, ...] = () # uw_confirm_queue ids created/refreshed
+ ambiguous: tuple[int, ...] = ()
+ evidence: tuple[MatchEvidence, ...] = field(default_factory=tuple)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "entity_id": self.entity_id,
+ "kind": str(self.kind),
+ "created": self.created,
+ "merged": list(self.merged),
+ "queued": list(self.queued),
+ "ambiguous": list(self.ambiguous),
+ "evidence": [item.to_dict() for item in self.evidence],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class IdentifierResult:
+ """Outcome of attaching one identifier to an entity."""
+
+ entity_id: int | None
+ identifier_id: int | None = None
+ created: bool = False
+ merged: tuple[int, ...] = ()
+ queued: tuple[int, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class SeedReport:
+ """What one contacts seeding pass did (idempotent, so a second pass is
+ all ``linked`` and zero ``created``)."""
+
+ created: int = 0
+ linked: int = 0
+ identifiers_added: int = 0
+ merged: int = 0
+ queued: int = 0
+ skipped: int = 0
+
+ def to_dict(self) -> dict[str, int]:
+ return {
+ "created": self.created,
+ "linked": self.linked,
+ "identifiers_added": self.identifiers_added,
+ "merged": self.merged,
+ "queued": self.queued,
+ "skipped": self.skipped,
+ }
diff --git a/jarvis/ultrawiki/identity_store.py b/jarvis/ultrawiki/identity_store.py
new file mode 100644
index 0000000000..d9939a0a54
--- /dev/null
+++ b/jarvis/ultrawiki/identity_store.py
@@ -0,0 +1,1557 @@
+"""The SQL half of UltraWiki identity resolution (design doc 05 · D-10).
+
+:class:`IdentityMixin` is inherited by BOTH store backends, so the identity
+rules exist exactly once. It relies on nothing but the small surface both
+already provide — ``_txn()``, ``_fetchall()``, ``_fetchone()``,
+``_ensure_open()`` — plus two dialect hooks the backends implement:
+``_IDENTITY_PARAM`` (the placeholder) and ``_id_insert()`` (how a freshly
+inserted row reports its id).
+
+The contract this module is built to keep:
+
+- **Deterministic evidence merges; everything else asks.** A shared e-mail,
+ phone number or address-book slug fuses two entities on the spot. Name
+ similarity — however striking — only ever writes a row into
+ ``uw_confirm_queue``.
+- **Ambiguity is never resolved by guessing.** An observation whose name
+ points at several live entities links to none of them; it returns
+ ``ResolutionKind.AMBIGUOUS`` and proposes the collisions instead.
+- **Every merge is reversible.** ``uw_merge_log`` stores the identifier rows
+ that moved, the duplicates that were dropped and the loser's own
+ bookkeeping, which is exactly what :meth:`IdentityMixin.unmerge` replays.
+- **A rejected pair stays rejected.** Undoing a merge (or rejecting a
+ proposal) is durable: the same evidence must never re-fuse the pair behind
+ the user's back, and must never ask a second time either.
+
+Nothing here calls a model, touches the network, or runs on the voice hot
+path; resolution happens on the write path (AP-9/AP-26).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from jarvis.ultrawiki.identity import (
+ DETERMINISTIC_KINDS,
+ FUZZY_CANDIDATE_LIMIT,
+ LEN_WINDOW,
+ MAX_PROPOSALS,
+ PREFIX_BLOCK_CHARS,
+ PROPOSE_THRESHOLD,
+ EntityKind,
+ IdentifierKind,
+ IdentifierResult,
+ IdentityError,
+ MatchEvidence,
+ MatchTier,
+ QueueStatus,
+ Resolution,
+ ResolutionKind,
+ SeedReport,
+ could_match,
+ escape_like,
+ name_similarity,
+ normalize_identifier,
+ normalize_name,
+ pair_key,
+)
+
+log = logging.getLogger(__name__)
+
+__all__ = ["IdentityMixin", "seed_from_contacts"]
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
+
+
+def _as_int(value: Any) -> int | None:
+ if value is None:
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+@dataclass(frozen=True, slots=True)
+class _Observed:
+ """One normalized identifier as it arrived."""
+
+ kind: IdentifierKind
+ value: str
+ display: str
+
+
+@dataclass(slots=True)
+class _Attached:
+ """Result of attaching one identifier inside an open transaction."""
+
+ entity_id: int
+ identifier_id: int | None = None
+ created: bool = False
+ merged: list[int] = field(default_factory=list)
+ queued: list[int] = field(default_factory=list)
+
+
+class IdentityMixin:
+ """Entities, identifiers, the confirmation queue and reversible merges."""
+
+ # -- dialect hooks -------------------------------------------------------
+
+ #: Parameter placeholder of the backend ("?" for SQLite, "%s" for
+ #: Postgres). Every statement below is written in the SQLite dialect and
+ #: translated once, so the two backends cannot drift apart on identity SQL.
+ _IDENTITY_PARAM: str = "?"
+
+ def _id_sql(self, sql: str) -> str:
+ if self._IDENTITY_PARAM == "?":
+ return sql
+ return sql.replace("?", self._IDENTITY_PARAM)
+
+ async def _id_insert(self, conn: Any, sql: str, params: Sequence[Any]) -> int:
+ """Run an INSERT and return the new row id (backend-specific)."""
+ raise NotImplementedError # pragma: no cover — backends override
+
+ # -- tiny query helpers --------------------------------------------------
+
+ async def _id_rows(
+ self, conn: Any, sql: str, params: Sequence[Any] = ()
+ ) -> list[Any]:
+ return await self._fetchall(conn, self._id_sql(sql), params) # type: ignore[attr-defined]
+
+ async def _id_row(
+ self, conn: Any, sql: str, params: Sequence[Any] = ()
+ ) -> Any | None:
+ return await self._fetchone(conn, self._id_sql(sql), params) # type: ignore[attr-defined]
+
+ async def _id_exec(self, conn: Any, sql: str, params: Sequence[Any] = ()) -> None:
+ await conn.execute(self._id_sql(sql), params)
+
+ # -- chain resolution ----------------------------------------------------
+
+ async def _chain(self, conn: Any, entity_id: int | None) -> int | None:
+ """Follow ``merged_into`` to the surviving entity (cycle-safe)."""
+ current = _as_int(entity_id)
+ if current is None:
+ return None
+ seen: set[int] = set()
+ while current not in seen:
+ seen.add(current)
+ row = await self._id_row(
+ conn,
+ "SELECT id, merged_into FROM uw_entities WHERE id = ?",
+ (current,),
+ )
+ if row is None:
+ return None
+ nxt = _as_int(row["merged_into"])
+ if nxt is None:
+ return current
+ current = nxt
+ log.warning("UltraWiki identity: merge cycle at entity %s", current)
+ return current
+
+ async def resolve_entity_id(self, entity_id: int) -> int | None:
+ """Public: the live entity a (possibly merged-away) id now points at."""
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ return await self._chain(conn, entity_id)
+
+ # -- entity CRUD ---------------------------------------------------------
+
+ async def upsert_entity(
+ self,
+ *,
+ display_name: str,
+ kind: EntityKind | str = EntityKind.PERSON,
+ source_ref: str = "",
+ profile: dict[str, Any] | None = None,
+ ) -> int:
+ """Create an entity (and its own name identifier); returns its id.
+
+ When ``source_ref`` is already known the existing entity is returned
+ instead — that is what makes seeding re-runnable.
+ """
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ return await self._id_create_entity(
+ conn,
+ display_name=display_name,
+ kind=kind,
+ source_ref=source_ref,
+ profile=profile,
+ now=_utc_now_iso(),
+ )
+
+ async def _id_create_entity(
+ self,
+ conn: Any,
+ *,
+ display_name: str,
+ kind: EntityKind | str,
+ source_ref: str,
+ profile: dict[str, Any] | None,
+ now: str,
+ with_name_identifier: bool = True,
+ ) -> int:
+ resolved_kind = EntityKind(kind) if not isinstance(kind, EntityKind) else kind
+ label = " ".join(str(display_name or "").split())
+ if not label:
+ raise IdentityError("an entity needs a non-empty display name")
+ ref = str(source_ref or "").strip()
+ if ref:
+ existing = await self._id_row(
+ conn, "SELECT id FROM uw_entities WHERE source_ref = ?", (ref,)
+ )
+ if existing is not None:
+ known = await self._chain(conn, _as_int(existing["id"]))
+ if known is not None:
+ return known
+ canonical = normalize_name(label) or ""
+ entity_id = await self._id_insert(
+ conn,
+ self._id_sql(
+ "INSERT INTO uw_entities"
+ " (kind, display_name, canonical_key, merged_into, source_ref,"
+ " profile_json, created_at, updated_at)"
+ " VALUES (?, ?, ?, NULL, ?, ?, ?, ?)"
+ ),
+ (
+ str(resolved_kind),
+ label,
+ canonical,
+ ref,
+ json.dumps(profile or {}, ensure_ascii=False),
+ now,
+ now,
+ ),
+ )
+ # An entity labelled after an e-mail address (an observation that
+ # carried no name at all) must NOT gain that address as a "name" —
+ # every other address at the same domain would then look like a
+ # near-name of it and flood the queue with nonsense proposals.
+ if canonical and with_name_identifier:
+ await self._id_write_identifier(
+ conn,
+ entity_id,
+ IdentifierKind.NAME,
+ canonical,
+ label,
+ ref,
+ now=now,
+ )
+ return entity_id
+
+ async def get_entity(self, entity_id: int) -> dict[str, Any] | None:
+ """The raw entity row (following merges), or ``None``."""
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ live = await self._chain(conn, entity_id)
+ if live is None:
+ return None
+ row = await self._id_row(
+ conn, "SELECT * FROM uw_entities WHERE id = ?", (live,)
+ )
+ return None if row is None else self._id_entity_dict(row)
+
+ @staticmethod
+ def _id_entity_dict(row: Any) -> dict[str, Any]:
+ try:
+ profile = json.loads(str(row["profile_json"] or "{}"))
+ except (TypeError, ValueError):
+ profile = {}
+ return {
+ "id": int(row["id"]),
+ "kind": str(row["kind"]),
+ "display_name": str(row["display_name"]),
+ "canonical_key": str(row["canonical_key"] or ""),
+ "merged_into": _as_int(row["merged_into"]),
+ "source_ref": str(row["source_ref"] or ""),
+ "profile": profile if isinstance(profile, dict) else {},
+ "created_at": str(row["created_at"]),
+ "updated_at": str(row["updated_at"]),
+ }
+
+ async def set_entity_source_ref(self, entity_id: int, source_ref: str) -> bool:
+ """Stamp provenance onto an entity that has none yet.
+
+ Refuses silently when the ref already belongs to another row — the
+ partial unique index would reject it anyway, and a seeding pass must
+ never fail because two contacts resolved onto one person.
+ """
+ ref = str(source_ref or "").strip()
+ if not ref:
+ return False
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ live = await self._chain(conn, entity_id)
+ if live is None:
+ return False
+ row = await self._id_row(
+ conn,
+ "SELECT id, source_ref FROM uw_entities WHERE id = ?",
+ (live,),
+ )
+ if row is None or str(row["source_ref"] or ""):
+ return False
+ holder = await self._id_row(
+ conn, "SELECT id FROM uw_entities WHERE source_ref = ?", (ref,)
+ )
+ if holder is not None:
+ return False
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET source_ref = ?, updated_at = ? WHERE id = ?",
+ (ref, _utc_now_iso(), live),
+ )
+ return True
+
+ # -- identifiers ---------------------------------------------------------
+
+ async def _id_write_identifier(
+ self,
+ conn: Any,
+ entity_id: int,
+ kind: IdentifierKind,
+ value: str,
+ display: str,
+ source_ref: str,
+ *,
+ now: str,
+ ) -> tuple[int, bool]:
+ """Insert one normalized identifier if the entity lacks it."""
+ existing = await self._id_row(
+ conn,
+ "SELECT id FROM uw_identifiers"
+ " WHERE entity_id = ? AND kind = ? AND value = ?",
+ (entity_id, str(kind), value),
+ )
+ if existing is not None:
+ return int(existing["id"]), False
+ identifier_id = await self._id_insert(
+ conn,
+ self._id_sql(
+ "INSERT INTO uw_identifiers"
+ " (entity_id, kind, value, display_value, value_len, source_ref,"
+ " created_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?)"
+ ),
+ (
+ entity_id,
+ str(kind),
+ value,
+ display or value,
+ len(value),
+ str(source_ref or ""),
+ now,
+ ),
+ )
+ return identifier_id, True
+
+ async def _id_holders(
+ self, conn: Any, kind: IdentifierKind, value: str, *, exclude: int | None
+ ) -> list[int]:
+ """Live entities that already hold this exact normalized identifier."""
+ rows = await self._id_rows(
+ conn,
+ "SELECT DISTINCT entity_id FROM uw_identifiers"
+ " WHERE kind = ? AND value = ?",
+ (str(kind), value),
+ )
+ holders: list[int] = []
+ for row in rows:
+ live = await self._chain(conn, _as_int(row["entity_id"]))
+ if live is None or live == exclude or live in holders:
+ continue
+ holders.append(live)
+ return holders
+
+ async def add_identifier(
+ self,
+ entity_id: int,
+ kind: IdentifierKind | str,
+ raw_value: str,
+ *,
+ source_ref: str = "",
+ ) -> IdentifierResult:
+ """Attach one raw handle to an entity, applying the tier rules.
+
+ A deterministic kind already held by another entity MERGES the two; a
+ name or handle collision is proposed instead. An unusable value (an
+ unparsable e-mail, a two-digit phone number) is dropped and reported
+ as ``identifier_id=None``.
+ """
+ try:
+ resolved_kind = IdentifierKind(kind)
+ except ValueError as exc:
+ raise IdentityError(f"unknown identifier kind: {kind!r}") from exc
+ value = normalize_identifier(resolved_kind, raw_value)
+ if not value:
+ return IdentifierResult(entity_id=_as_int(entity_id))
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ live = await self._chain(conn, entity_id)
+ if live is None:
+ raise IdentityError(f"unknown entity id: {entity_id!r}")
+ attached = await self._id_attach(
+ conn,
+ live,
+ _Observed(resolved_kind, value, str(raw_value or "")),
+ source_ref=source_ref,
+ now=_utc_now_iso(),
+ )
+ return IdentifierResult(
+ entity_id=attached.entity_id,
+ identifier_id=attached.identifier_id,
+ created=attached.created,
+ merged=tuple(attached.merged),
+ queued=tuple(attached.queued),
+ )
+
+ async def _id_attach(
+ self,
+ conn: Any,
+ entity_id: int,
+ observed: _Observed,
+ *,
+ source_ref: str,
+ now: str,
+ ) -> _Attached:
+ out = _Attached(entity_id=entity_id)
+ holders = await self._id_holders(
+ conn, observed.kind, observed.value, exclude=entity_id
+ )
+ if holders and observed.kind in DETERMINISTIC_KINDS:
+ evidence = (
+ MatchEvidence(
+ tier=MatchTier.DETERMINISTIC,
+ kind=str(observed.kind),
+ value=observed.value,
+ ),
+ )
+ candidates = [entity_id, *holders]
+ winner = await self._id_pick_winner(conn, candidates)
+ for other in candidates:
+ if other == winner:
+ continue
+ merged_id = await self._id_merge(
+ conn,
+ winner,
+ other,
+ tier=MatchTier.DETERMINISTIC,
+ reason=f"shared {observed.kind}",
+ evidence=evidence,
+ queue_id=None,
+ now=now,
+ )
+ if merged_id:
+ out.merged.append(merged_id)
+ out.entity_id = winner
+ elif holders:
+ evidence = (
+ MatchEvidence(
+ tier=MatchTier.PROBABLE,
+ kind=f"{observed.kind}_exact",
+ value=observed.value,
+ ),
+ )
+ for other in holders:
+ queue_id = await self._id_enqueue(
+ conn, entity_id, other, 1.0, evidence, now=now
+ )
+ if queue_id:
+ out.queued.append(queue_id)
+ identifier_id, created = await self._id_write_identifier(
+ conn,
+ out.entity_id,
+ observed.kind,
+ observed.value,
+ observed.display,
+ source_ref,
+ now=now,
+ )
+ out.identifier_id = identifier_id
+ out.created = created
+ return out
+
+ # -- winner selection ----------------------------------------------------
+
+ async def _id_pick_winner(self, conn: Any, entity_ids: Iterable[int]) -> int:
+ """Deterministic survivor of a merge — never "whichever came first".
+
+ A hand-curated address-book record outranks an inferred one; among
+ equals the older id wins. Deterministic so that re-running an import
+ converges on the same graph instead of oscillating.
+ """
+ rows: list[tuple[int, int]] = []
+ for entity_id in dict.fromkeys(int(x) for x in entity_ids):
+ row = await self._id_row(
+ conn,
+ "SELECT id, source_ref FROM uw_entities WHERE id = ?",
+ (entity_id,),
+ )
+ if row is None:
+ continue
+ seeded = 0 if str(row["source_ref"] or "") else 1
+ rows.append((seeded, int(row["id"])))
+ if not rows:
+ raise IdentityError("cannot pick a merge winner among unknown entities")
+ rows.sort()
+ return rows[0][1]
+
+ # -- confirmation queue --------------------------------------------------
+
+ async def _id_enqueue(
+ self,
+ conn: Any,
+ left_id: int,
+ right_id: int,
+ score: float,
+ evidence: Sequence[MatchEvidence],
+ *,
+ now: str,
+ ) -> int | None:
+ """Propose a pair. Returns the queue id, or ``None`` when the pair is
+ already decided (a rejected pair is never asked about again)."""
+ left = await self._chain(conn, left_id)
+ right = await self._chain(conn, right_id)
+ if left is None or right is None or left == right:
+ return None
+ key = pair_key(left, right)
+ payload = json.dumps([item.to_dict() for item in evidence], ensure_ascii=False)
+ row = await self._id_row(
+ conn,
+ "SELECT id, status, score FROM uw_confirm_queue WHERE pair_key = ?",
+ (key,),
+ )
+ if row is None:
+ low, high = sorted((left, right))
+ return await self._id_insert(
+ conn,
+ self._id_sql(
+ "INSERT INTO uw_confirm_queue"
+ " (pair_key, left_entity_id, right_entity_id, status, score,"
+ " evidence_json, created_at, updated_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
+ ),
+ (
+ key,
+ low,
+ high,
+ str(QueueStatus.PENDING),
+ float(score),
+ payload,
+ now,
+ now,
+ ),
+ )
+ if str(row["status"]) != str(QueueStatus.PENDING):
+ return None
+ best = max(float(row["score"] or 0.0), float(score))
+ await self._id_exec(
+ conn,
+ "UPDATE uw_confirm_queue"
+ " SET score = ?, evidence_json = ?, updated_at = ? WHERE id = ?",
+ (best, payload, now, int(row["id"])),
+ )
+ return int(row["id"])
+
+ async def _id_pair_rejected(self, conn: Any, left: int, right: int) -> bool:
+ row = await self._id_row(
+ conn,
+ "SELECT status FROM uw_confirm_queue WHERE pair_key = ?",
+ (pair_key(left, right),),
+ )
+ return row is not None and str(row["status"]) == str(QueueStatus.REJECTED)
+
+ # -- merge / unmerge -----------------------------------------------------
+
+ async def merge_entities(
+ self,
+ winner_id: int,
+ loser_id: int,
+ *,
+ tier: MatchTier | str = MatchTier.DETERMINISTIC,
+ reason: str = "",
+ evidence: Sequence[MatchEvidence] = (),
+ ) -> int:
+ """Merge two entities; returns the ``uw_merge_log`` id (0 = no-op)."""
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ return await self._id_merge(
+ conn,
+ winner_id,
+ loser_id,
+ tier=MatchTier(tier),
+ reason=reason,
+ evidence=evidence,
+ queue_id=None,
+ now=_utc_now_iso(),
+ )
+
+ async def _id_merge(
+ self,
+ conn: Any,
+ winner_id: int,
+ loser_id: int,
+ *,
+ tier: MatchTier,
+ reason: str,
+ evidence: Sequence[MatchEvidence],
+ queue_id: int | None,
+ now: str,
+ ) -> int:
+ winner = await self._chain(conn, winner_id)
+ loser = await self._chain(conn, loser_id)
+ if winner is None or loser is None:
+ raise IdentityError(
+ f"cannot merge unknown entities ({winner_id!r}, {loser_id!r})"
+ )
+ if winner == loser:
+ return 0
+ if queue_id is None and await self._id_pair_rejected(conn, winner, loser):
+ # The user has already said these two are different. Deterministic
+ # evidence does not overrule that: a shared mailbox or a family
+ # phone is exactly how a rejected pair keeps colliding.
+ log.info(
+ "UltraWiki identity: refusing to re-merge the rejected pair %s/%s",
+ winner,
+ loser,
+ )
+ return 0
+
+ winner_row = await self._id_row(
+ conn, "SELECT id, source_ref FROM uw_entities WHERE id = ?", (winner,)
+ )
+ loser_row = await self._id_row(
+ conn, "SELECT id, source_ref FROM uw_entities WHERE id = ?", (loser,)
+ )
+ if winner_row is None or loser_row is None: # pragma: no cover — chain checked
+ raise IdentityError("merge lost one of its entities mid-transaction")
+
+ held = {
+ (str(row["kind"]), str(row["value"]))
+ for row in await self._id_rows(
+ conn,
+ "SELECT kind, value FROM uw_identifiers WHERE entity_id = ?",
+ (winner,),
+ )
+ }
+ moved: list[int] = []
+ dropped: list[dict[str, Any]] = []
+ for row in await self._id_rows(
+ conn,
+ "SELECT id, kind, value, display_value, source_ref, created_at"
+ " FROM uw_identifiers WHERE entity_id = ? ORDER BY id",
+ (loser,),
+ ):
+ key = (str(row["kind"]), str(row["value"]))
+ if key in held:
+ dropped.append(
+ {
+ "kind": str(row["kind"]),
+ "value": str(row["value"]),
+ "display_value": str(row["display_value"] or ""),
+ "source_ref": str(row["source_ref"] or ""),
+ "created_at": str(row["created_at"]),
+ }
+ )
+ await self._id_exec(
+ conn, "DELETE FROM uw_identifiers WHERE id = ?", (int(row["id"]),)
+ )
+ continue
+ await self._id_exec(
+ conn,
+ "UPDATE uw_identifiers SET entity_id = ? WHERE id = ?",
+ (winner, int(row["id"])),
+ )
+ moved.append(int(row["id"]))
+ held.add(key)
+
+ loser_ref = str(loser_row["source_ref"] or "")
+ winner_took_ref = False
+ if loser_ref:
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET source_ref = '', updated_at = ? WHERE id = ?",
+ (now, loser),
+ )
+ if not str(winner_row["source_ref"] or ""):
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET source_ref = ?, updated_at = ?"
+ " WHERE id = ?",
+ (loser_ref, now, winner),
+ )
+ winner_took_ref = True
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET merged_into = ?, updated_at = ? WHERE id = ?",
+ (winner, now, loser),
+ )
+
+ undo = {
+ "moved": moved,
+ "dropped": dropped,
+ "loser_source_ref": loser_ref,
+ "winner_took_source_ref": winner_took_ref,
+ "loser_prev_merged_into": None,
+ }
+ merge_log_id = await self._id_insert(
+ conn,
+ self._id_sql(
+ "INSERT INTO uw_merge_log"
+ " (winner_id, loser_id, tier, reason, evidence_json, undo_json,"
+ " queue_id, merged_at, undone_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)"
+ ),
+ (
+ winner,
+ loser,
+ str(tier),
+ str(reason or ""),
+ json.dumps(
+ [item.to_dict() for item in evidence], ensure_ascii=False
+ ),
+ json.dumps(undo, ensure_ascii=False),
+ queue_id,
+ now,
+ ),
+ )
+ # Self-heal the queue: an open proposal for this exact pair is decided.
+ await self._id_exec(
+ conn,
+ "UPDATE uw_confirm_queue SET status = ?, decided_at = ?,"
+ " decided_by = ?, updated_at = ?"
+ " WHERE pair_key = ? AND status = ?",
+ (
+ str(QueueStatus.CONFIRMED),
+ now,
+ "merge",
+ now,
+ pair_key(winner, loser),
+ str(QueueStatus.PENDING),
+ ),
+ )
+ log.info(
+ "UltraWiki identity: merged entity %s into %s (%s)", loser, winner, tier
+ )
+ return merge_log_id
+
+ async def unmerge(self, merge_log_id: int) -> bool:
+ """Reverse one merge exactly, restoring the state before it.
+
+ Identifier rows go back, dropped duplicates are re-created, the loser
+ stops being a tombstone, and the pair is recorded as REJECTED so the
+ same evidence cannot silently fuse it again on the next import.
+ """
+ now = _utc_now_iso()
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ row = await self._id_row(
+ conn, "SELECT * FROM uw_merge_log WHERE id = ?", (int(merge_log_id),)
+ )
+ if row is None:
+ raise IdentityError(f"unknown merge id: {merge_log_id!r}")
+ if row["undone_at"]:
+ raise IdentityError(f"merge {merge_log_id} was already undone")
+ winner = int(row["winner_id"])
+ loser = int(row["loser_id"])
+ later = await self._id_row(
+ conn,
+ "SELECT id FROM uw_merge_log"
+ " WHERE loser_id = ? AND undone_at IS NULL AND id > ?"
+ " ORDER BY id LIMIT 1",
+ (loser, int(merge_log_id)),
+ )
+ if later is not None:
+ raise IdentityError(
+ f"merge {merge_log_id} is shadowed by the later merge "
+ f"{int(later['id'])} — undo that one first"
+ )
+ loser_row = await self._id_row(
+ conn, "SELECT id FROM uw_entities WHERE id = ?", (loser,)
+ )
+ if loser_row is None:
+ raise IdentityError(
+ f"entity {loser} no longer exists — merge {merge_log_id} "
+ "cannot be undone"
+ )
+ try:
+ undo = json.loads(str(row["undo_json"] or "{}"))
+ except (TypeError, ValueError):
+ undo = {}
+
+ for identifier_id in undo.get("moved", []) or []:
+ await self._id_exec(
+ conn,
+ "UPDATE uw_identifiers SET entity_id = ? WHERE id = ?",
+ (loser, int(identifier_id)),
+ )
+ for payload in undo.get("dropped", []) or []:
+ await self._id_write_identifier(
+ conn,
+ loser,
+ IdentifierKind(str(payload.get("kind"))),
+ str(payload.get("value", "")),
+ str(payload.get("display_value", "")),
+ str(payload.get("source_ref", "")),
+ now=str(payload.get("created_at") or now),
+ )
+ if undo.get("winner_took_source_ref"):
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET source_ref = '', updated_at = ?"
+ " WHERE id = ?",
+ (now, winner),
+ )
+ loser_ref = str(undo.get("loser_source_ref") or "")
+ if loser_ref:
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET source_ref = ?, updated_at = ?"
+ " WHERE id = ?",
+ (loser_ref, now, loser),
+ )
+ await self._id_exec(
+ conn,
+ "UPDATE uw_entities SET merged_into = ?, updated_at = ? WHERE id = ?",
+ (_as_int(undo.get("loser_prev_merged_into")), now, loser),
+ )
+ await self._id_exec(
+ conn,
+ "UPDATE uw_merge_log SET undone_at = ? WHERE id = ?",
+ (now, int(merge_log_id)),
+ )
+ await self._id_record_rejection(conn, winner, loser, now=now)
+ log.info(
+ "UltraWiki identity: unmerged entity %s from %s (merge %s)",
+ loser,
+ winner,
+ merge_log_id,
+ )
+ return True
+
+ async def _id_record_rejection(
+ self, conn: Any, left: int, right: int, *, now: str, decided_by: str = "unmerge"
+ ) -> None:
+ """Durably mark a pair as "not the same", creating the row if needed."""
+ key = pair_key(left, right)
+ row = await self._id_row(
+ conn, "SELECT id FROM uw_confirm_queue WHERE pair_key = ?", (key,)
+ )
+ if row is None:
+ low, high = sorted((int(left), int(right)))
+ await self._id_insert(
+ conn,
+ self._id_sql(
+ "INSERT INTO uw_confirm_queue"
+ " (pair_key, left_entity_id, right_entity_id, status, score,"
+ " evidence_json, created_at, updated_at, decided_at,"
+ " decided_by)"
+ " VALUES (?, ?, ?, ?, 0, '[]', ?, ?, ?, ?)"
+ ),
+ (key, low, high, str(QueueStatus.REJECTED), now, now, now, decided_by),
+ )
+ return
+ await self._id_exec(
+ conn,
+ "UPDATE uw_confirm_queue SET status = ?, decided_at = ?,"
+ " decided_by = ?, updated_at = ? WHERE id = ?",
+ (str(QueueStatus.REJECTED), now, decided_by, now, int(row["id"])),
+ )
+
+ async def confirm_merge(self, queue_id: int, *, decided_by: str = "user") -> int:
+ """Apply a queued proposal; returns the ``uw_merge_log`` id."""
+ now = _utc_now_iso()
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ row = await self._id_row(
+ conn, "SELECT * FROM uw_confirm_queue WHERE id = ?", (int(queue_id),)
+ )
+ if row is None:
+ raise IdentityError(f"unknown confirmation id: {queue_id!r}")
+ if str(row["status"]) != str(QueueStatus.PENDING):
+ raise IdentityError(
+ f"confirmation {queue_id} was already {row['status']}"
+ )
+ left = await self._chain(conn, _as_int(row["left_entity_id"]))
+ right = await self._chain(conn, _as_int(row["right_entity_id"]))
+ await self._id_exec(
+ conn,
+ "UPDATE uw_confirm_queue SET status = ?, decided_at = ?,"
+ " decided_by = ?, updated_at = ? WHERE id = ?",
+ (str(QueueStatus.CONFIRMED), now, decided_by, now, int(queue_id)),
+ )
+ if left is None or right is None or left == right:
+ return 0
+ try:
+ raw = json.loads(str(row["evidence_json"] or "[]"))
+ except (TypeError, ValueError):
+ raw = []
+ evidence = tuple(
+ MatchEvidence.from_dict(item)
+ for item in raw
+ if isinstance(item, dict)
+ )
+ winner = await self._id_pick_winner(conn, (left, right))
+ loser = right if winner == left else left
+ return await self._id_merge(
+ conn,
+ winner,
+ loser,
+ tier=MatchTier.PROBABLE,
+ reason=f"confirmed by {decided_by}",
+ evidence=evidence,
+ queue_id=int(queue_id),
+ now=now,
+ )
+
+ async def reject_merge(self, queue_id: int, *, decided_by: str = "user") -> bool:
+ """Decline a proposal permanently (it is never proposed again)."""
+ now = _utc_now_iso()
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ row = await self._id_row(
+ conn, "SELECT * FROM uw_confirm_queue WHERE id = ?", (int(queue_id),)
+ )
+ if row is None:
+ raise IdentityError(f"unknown confirmation id: {queue_id!r}")
+ if str(row["status"]) == str(QueueStatus.CONFIRMED):
+ raise IdentityError(
+ f"confirmation {queue_id} was already applied — unmerge instead"
+ )
+ await self._id_exec(
+ conn,
+ "UPDATE uw_confirm_queue SET status = ?, decided_at = ?,"
+ " decided_by = ?, updated_at = ? WHERE id = ?",
+ (str(QueueStatus.REJECTED), now, decided_by, now, int(queue_id)),
+ )
+ return True
+
+ # -- resolution ----------------------------------------------------------
+
+ async def resolve_identity(
+ self,
+ *,
+ name: str = "",
+ emails: Sequence[str] = (),
+ phones: Sequence[str] = (),
+ handles: Sequence[str] = (),
+ contact_slug: str = "",
+ kind: EntityKind | str = EntityKind.PERSON,
+ source_ref: str = "",
+ create: bool = True,
+ ) -> Resolution:
+ """Map one observation onto an entity, applying the three tiers.
+
+ Deterministic identifiers decide; an exact name matching exactly ONE
+ live entity anchors onto it; a name matching several anchors onto none
+ (``AMBIGUOUS``) and proposes the collisions; anything else creates a
+ new entity and proposes its near-names. **No path here ever merges on
+ name evidence.**
+
+ Anchoring on an identical name is a lookup, not a merge: no entity is
+ destroyed and nothing is fused — which is why "Ultra-Wiki" joins
+ "ultra-wiki" silently while "UltraWiki" only ever gets *proposed* to
+ both.
+
+ ``source_ref`` labels the identifier rows this observation writes
+ (provenance); stamping the ENTITY's own provenance is the separate,
+ idempotent :meth:`set_entity_source_ref`.
+ """
+ observed = self._id_observe(
+ name=name,
+ emails=emails,
+ phones=phones,
+ handles=handles,
+ contact_slug=contact_slug,
+ )
+ name_value = normalize_name(name) if name else None
+ now = _utc_now_iso()
+ async with self._txn() as conn: # type: ignore[attr-defined]
+ return await self._id_resolve(
+ conn,
+ observed,
+ name_value=name_value,
+ display_name=str(name or "").strip(),
+ kind=kind,
+ source_ref=source_ref,
+ create=create,
+ now=now,
+ )
+
+ @staticmethod
+ def _id_observe(
+ *,
+ name: str,
+ emails: Sequence[str],
+ phones: Sequence[str],
+ handles: Sequence[str],
+ contact_slug: str,
+ ) -> list[_Observed]:
+ raw: list[tuple[IdentifierKind, str]] = []
+ if contact_slug:
+ raw.append((IdentifierKind.CONTACT, contact_slug))
+ raw.extend((IdentifierKind.EMAIL, value) for value in emails)
+ raw.extend((IdentifierKind.PHONE, value) for value in phones)
+ raw.extend((IdentifierKind.HANDLE, value) for value in handles)
+ if name:
+ raw.append((IdentifierKind.NAME, name))
+ seen: set[tuple[str, str]] = set()
+ observed: list[_Observed] = []
+ for kind, value in raw:
+ normalized = normalize_identifier(kind, value)
+ if not normalized or (str(kind), normalized) in seen:
+ continue
+ seen.add((str(kind), normalized))
+ observed.append(_Observed(kind, normalized, str(value)))
+ return observed
+
+ async def _id_resolve(
+ self,
+ conn: Any,
+ observed: Sequence[_Observed],
+ *,
+ name_value: str | None,
+ display_name: str,
+ kind: EntityKind | str,
+ source_ref: str,
+ create: bool,
+ now: str,
+ ) -> Resolution:
+ merged: list[int] = []
+ queued: list[int] = []
+ evidence: list[MatchEvidence] = []
+
+ # Tier 1 — deterministic anchors.
+ anchors: list[int] = []
+ for item in observed:
+ if item.kind not in DETERMINISTIC_KINDS:
+ continue
+ for holder in await self._id_holders(
+ conn, item.kind, item.value, exclude=None
+ ):
+ if holder not in anchors:
+ anchors.append(holder)
+ evidence.append(
+ MatchEvidence(
+ tier=MatchTier.DETERMINISTIC,
+ kind=str(item.kind),
+ value=item.value,
+ )
+ )
+ entity_id: int | None = None
+ resolution_kind = ResolutionKind.UNRESOLVED
+ created = False
+ if anchors:
+ entity_id = await self._id_pick_winner(conn, anchors)
+ resolution_kind = ResolutionKind.DETERMINISTIC
+ for other in anchors:
+ if other == entity_id:
+ continue
+ merge_id = await self._id_merge(
+ conn,
+ entity_id,
+ other,
+ tier=MatchTier.DETERMINISTIC,
+ reason="shared unique identifier",
+ evidence=tuple(evidence),
+ queue_id=None,
+ now=now,
+ )
+ if merge_id:
+ merged.append(merge_id)
+ else:
+ # A rejected pair refused the merge; the observation still
+ # belongs to the winner, both identities keep answering.
+ entity_id = await self._chain(conn, entity_id) or entity_id
+
+ # Tier 2 — an exact name is an anchor only when it is unambiguous.
+ if entity_id is None and name_value:
+ holders = await self._id_holders(
+ conn, IdentifierKind.NAME, name_value, exclude=None
+ )
+ if len(holders) == 1:
+ entity_id = holders[0]
+ resolution_kind = ResolutionKind.NAME_ANCHOR
+ evidence.append(
+ MatchEvidence(
+ tier=MatchTier.PROBABLE, kind="name_exact", value=name_value
+ )
+ )
+ elif len(holders) > 1:
+ pair_evidence = (
+ MatchEvidence(
+ tier=MatchTier.PROBABLE, kind="name_exact", value=name_value
+ ),
+ )
+ for index, left in enumerate(holders):
+ for right in holders[index + 1 :]:
+ queue_id = await self._id_enqueue(
+ conn, left, right, 1.0, pair_evidence, now=now
+ )
+ if queue_id:
+ queued.append(queue_id)
+ return Resolution(
+ entity_id=None,
+ kind=ResolutionKind.AMBIGUOUS,
+ merged=tuple(merged),
+ queued=tuple(queued),
+ ambiguous=tuple(holders),
+ evidence=tuple(pair_evidence),
+ )
+
+ # Tier 3 — nothing recognized it: a new identity, plus proposals.
+ if entity_id is None:
+ if not create:
+ return Resolution(
+ entity_id=None,
+ kind=ResolutionKind.UNRESOLVED,
+ merged=tuple(merged),
+ queued=tuple(queued),
+ evidence=tuple(evidence),
+ )
+ label = display_name or (observed[0].display if observed else "")
+ if not str(label or "").strip():
+ raise IdentityError(
+ "an observation needs a name or at least one identifier"
+ )
+ entity_id = await self._id_create_entity(
+ conn,
+ display_name=label,
+ kind=kind,
+ source_ref="",
+ profile=None,
+ now=now,
+ with_name_identifier=bool(name_value),
+ )
+ created = True
+ resolution_kind = ResolutionKind.CREATED
+
+ for item in observed:
+ attached = await self._id_attach(
+ conn, entity_id, item, source_ref=source_ref, now=now
+ )
+ entity_id = attached.entity_id
+ merged.extend(attached.merged)
+ queued.extend(attached.queued)
+
+ if created and name_value:
+ for queue_id, score, hit in await self._id_fuzzy_proposals(
+ conn, entity_id, name_value, now=now
+ ):
+ queued.append(queue_id)
+ evidence.append(
+ MatchEvidence(
+ tier=MatchTier.PROBABLE,
+ kind="name_similar",
+ value=hit,
+ score=score,
+ )
+ )
+
+ return Resolution(
+ entity_id=entity_id,
+ kind=resolution_kind,
+ created=created,
+ merged=tuple(dict.fromkeys(merged)),
+ queued=tuple(dict.fromkeys(queued)),
+ evidence=tuple(evidence),
+ )
+
+ async def _id_fuzzy_proposals(
+ self, conn: Any, entity_id: int, name_value: str, *, now: str
+ ) -> list[tuple[int, float, str]]:
+ """Propose the near-names of a freshly created entity.
+
+ Blocking happens in SQL (length window OR shared prefix — the exact
+ predicate :func:`identity.could_match` re-applies in Python), scoring
+ happens in Python, and both are capped so one observation can never
+ flood the queue or the CPU.
+ """
+ prefix = escape_like(name_value[:PREFIX_BLOCK_CHARS])
+ rows = await self._id_rows(
+ conn,
+ "SELECT i.entity_id AS entity_id, i.value AS value"
+ " FROM uw_identifiers i"
+ " JOIN uw_entities e ON e.id = i.entity_id"
+ " WHERE i.kind = ? AND e.merged_into IS NULL AND i.entity_id != ?"
+ " AND (i.value_len BETWEEN ? AND ? OR i.value LIKE ? ESCAPE '\\')"
+ " ORDER BY i.id LIMIT ?",
+ (
+ str(IdentifierKind.NAME),
+ entity_id,
+ max(0, len(name_value) - LEN_WINDOW),
+ len(name_value) + LEN_WINDOW,
+ f"{prefix}%",
+ FUZZY_CANDIDATE_LIMIT,
+ ),
+ )
+ best: dict[int, tuple[float, str]] = {}
+ for row in rows:
+ candidate = str(row["value"])
+ if candidate == name_value or not could_match(name_value, candidate):
+ continue
+ score = name_similarity(name_value, candidate)
+ if score < PROPOSE_THRESHOLD:
+ continue
+ holder = _as_int(row["entity_id"])
+ if holder is None:
+ continue
+ if holder not in best or score > best[holder][0]:
+ best[holder] = (score, candidate)
+ ranked = sorted(best.items(), key=lambda pair: (-pair[1][0], pair[0]))
+ proposals: list[tuple[int, float, str]] = []
+ for holder, (score, candidate) in ranked[:MAX_PROPOSALS]:
+ evidence = (
+ MatchEvidence(
+ tier=MatchTier.PROBABLE,
+ kind="name_similar",
+ value=candidate,
+ score=score,
+ ),
+ )
+ queue_id = await self._id_enqueue(
+ conn, entity_id, holder, score, evidence, now=now
+ )
+ if queue_id:
+ proposals.append((queue_id, score, candidate))
+ return proposals
+
+ # -- read surface (the People view and every later phase) ----------------
+
+ async def list_people(
+ self,
+ *,
+ query: str = "",
+ kind: EntityKind | str | None = EntityKind.PERSON,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[dict[str, Any]]:
+ """Live entities with their identifier counts, name-ordered.
+
+ ``kind=None`` lists every kind. ``query`` matches the display name or
+ any identifier value, case-insensitively.
+ """
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ clauses = ["e.merged_into IS NULL"]
+ params: list[Any] = []
+ if kind is not None:
+ clauses.append("e.kind = ?")
+ params.append(str(EntityKind(kind)))
+ needle = " ".join(str(query or "").split()).lower()
+ if needle:
+ pattern = f"%{escape_like(needle)}%"
+ clauses.append(
+ "(LOWER(e.display_name) LIKE ? ESCAPE '\\'"
+ " OR EXISTS (SELECT 1 FROM uw_identifiers x"
+ " WHERE x.entity_id = e.id"
+ " AND LOWER(x.value) LIKE ? ESCAPE '\\'))"
+ )
+ params.extend([pattern, pattern])
+ params.extend([max(1, int(limit)), max(0, int(offset))])
+ rows = await self._id_rows(
+ conn,
+ "SELECT e.id, e.kind, e.display_name, e.canonical_key," # noqa: S608 — code-owned literals, every value bound
+ " e.source_ref, e.created_at, e.updated_at,"
+ " (SELECT COUNT(*) FROM uw_identifiers x WHERE x.entity_id = e.id)"
+ " AS identifier_count"
+ " FROM uw_entities e"
+ f" WHERE {' AND '.join(clauses)}"
+ " ORDER BY e.canonical_key, e.id LIMIT ? OFFSET ?",
+ params,
+ )
+ return [
+ {
+ "id": int(row["id"]),
+ "kind": str(row["kind"]),
+ "display_name": str(row["display_name"]),
+ "source_ref": str(row["source_ref"] or ""),
+ "identifier_count": int(row["identifier_count"] or 0),
+ "created_at": str(row["created_at"]),
+ "updated_at": str(row["updated_at"]),
+ }
+ for row in rows
+ ]
+
+ async def get_person(self, entity_id: int) -> dict[str, Any] | None:
+ """One profile: identifiers by kind, what was merged in, what is open.
+
+ Accepts a merged-away id and forwards to the survivor (reporting the
+ forward in ``requested_id``), so a stale link never 404s.
+ """
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ live = await self._chain(conn, entity_id)
+ if live is None:
+ return None
+ row = await self._id_row(
+ conn, "SELECT * FROM uw_entities WHERE id = ?", (live,)
+ )
+ if row is None: # pragma: no cover — chain guarantees the row
+ return None
+ profile = self._id_entity_dict(row)
+ identifiers: list[dict[str, Any]] = [
+ {
+ "id": int(item["id"]),
+ "kind": str(item["kind"]),
+ "value": str(item["value"]),
+ "display_value": str(item["display_value"] or ""),
+ "source_ref": str(item["source_ref"] or ""),
+ }
+ for item in await self._id_rows(
+ conn,
+ "SELECT id, kind, value, display_value, source_ref"
+ " FROM uw_identifiers WHERE entity_id = ? ORDER BY kind, id",
+ (live,),
+ )
+ ]
+ by_kind: dict[str, list[str]] = {str(k): [] for k in IdentifierKind}
+ for item in identifiers:
+ by_kind[item["kind"]].append(item["display_value"] or item["value"])
+ profile["identifiers"] = identifiers
+ profile["emails"] = by_kind[str(IdentifierKind.EMAIL)]
+ profile["phones"] = by_kind[str(IdentifierKind.PHONE)]
+ profile["handles"] = by_kind[str(IdentifierKind.HANDLE)]
+ profile["names"] = by_kind[str(IdentifierKind.NAME)]
+ profile["contacts"] = by_kind[str(IdentifierKind.CONTACT)]
+ profile["merged_from"] = [
+ {"id": int(item["id"]), "display_name": str(item["display_name"])}
+ for item in await self._id_rows(
+ conn,
+ "SELECT id, display_name FROM uw_entities"
+ " WHERE merged_into = ? ORDER BY id",
+ (live,),
+ )
+ ]
+ profile["merges"] = await self.list_merge_log(entity_id=live)
+ profile["pending_proposals"] = [
+ entry
+ for entry in await self.list_confirm_queue(status=QueueStatus.PENDING)
+ if entry["left"]["id"] == live or entry["right"]["id"] == live
+ ]
+ profile["requested_id"] = int(entity_id)
+ return profile
+
+ async def list_confirm_queue(
+ self,
+ *,
+ status: QueueStatus | str | None = QueueStatus.PENDING,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[dict[str, Any]]:
+ """Open (or decided) merge proposals, strongest evidence first.
+
+ Rows whose two sides have meanwhile become the same entity are skipped
+ — the queue self-heals instead of asking about a settled question.
+ """
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ clauses: list[str] = []
+ params: list[Any] = []
+ if status is not None:
+ clauses.append("q.status = ?")
+ params.append(str(QueueStatus(status)))
+ where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
+ params.extend([max(1, int(limit)), max(0, int(offset))])
+ rows = await self._id_rows(
+ conn,
+ "SELECT q.* FROM uw_confirm_queue q" # noqa: S608 — code-owned literals, every value bound
+ f"{where}"
+ " ORDER BY q.score DESC, q.id LIMIT ? OFFSET ?",
+ params,
+ )
+ out: list[dict[str, Any]] = []
+ for row in rows:
+ left = await self._chain(conn, _as_int(row["left_entity_id"]))
+ right = await self._chain(conn, _as_int(row["right_entity_id"]))
+ if left is None or right is None or left == right:
+ continue
+ try:
+ evidence = json.loads(str(row["evidence_json"] or "[]"))
+ except (TypeError, ValueError):
+ evidence = []
+ out.append(
+ {
+ "id": int(row["id"]),
+ "status": str(row["status"]),
+ "score": float(row["score"] or 0.0),
+ "evidence": evidence if isinstance(evidence, list) else [],
+ "created_at": str(row["created_at"]),
+ "updated_at": str(row["updated_at"]),
+ "decided_at": row["decided_at"],
+ "decided_by": row["decided_by"],
+ "left": await self._id_stub(conn, left),
+ "right": await self._id_stub(conn, right),
+ }
+ )
+ return out
+
+ async def _id_stub(self, conn: Any, entity_id: int) -> dict[str, Any]:
+ row = await self._id_row(
+ conn,
+ "SELECT id, kind, display_name FROM uw_entities WHERE id = ?",
+ (entity_id,),
+ )
+ if row is None: # pragma: no cover — callers pass live ids
+ return {"id": entity_id, "kind": "", "display_name": ""}
+ return {
+ "id": int(row["id"]),
+ "kind": str(row["kind"]),
+ "display_name": str(row["display_name"]),
+ }
+
+ async def list_merge_log(
+ self,
+ *,
+ entity_id: int | None = None,
+ limit: int = 100,
+ include_undone: bool = True,
+ ) -> list[dict[str, Any]]:
+ """The audit trail — every merge, its evidence, and whether it stands."""
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ clauses: list[str] = []
+ params: list[Any] = []
+ if entity_id is not None:
+ clauses.append("(winner_id = ? OR loser_id = ?)")
+ params.extend([int(entity_id), int(entity_id)])
+ if not include_undone:
+ clauses.append("undone_at IS NULL")
+ where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
+ params.append(max(1, int(limit)))
+ rows = await self._id_rows(
+ conn,
+ f"SELECT * FROM uw_merge_log{where} ORDER BY id DESC LIMIT ?", # noqa: S608 — code-owned literals, every value bound
+ params,
+ )
+ out: list[dict[str, Any]] = []
+ for row in rows:
+ try:
+ evidence = json.loads(str(row["evidence_json"] or "[]"))
+ except (TypeError, ValueError):
+ evidence = []
+ out.append(
+ {
+ "id": int(row["id"]),
+ "winner_id": int(row["winner_id"]),
+ "loser_id": int(row["loser_id"]),
+ "tier": str(row["tier"]),
+ "reason": str(row["reason"] or ""),
+ "evidence": evidence if isinstance(evidence, list) else [],
+ "queue_id": _as_int(row["queue_id"]),
+ "merged_at": str(row["merged_at"]),
+ "undone_at": row["undone_at"],
+ }
+ )
+ return out
+
+ async def identity_counts(self) -> dict[str, int]:
+ """Honest counters for the status surface (cheap, index-only)."""
+ conn = await self._ensure_open() # type: ignore[attr-defined]
+ entities = await self._id_row(
+ conn,
+ "SELECT COUNT(*) AS n FROM uw_entities WHERE merged_into IS NULL",
+ )
+ people = await self._id_row(
+ conn,
+ "SELECT COUNT(*) AS n FROM uw_entities"
+ " WHERE merged_into IS NULL AND kind = ?",
+ (str(EntityKind.PERSON),),
+ )
+ identifiers = await self._id_row(
+ conn, "SELECT COUNT(*) AS n FROM uw_identifiers"
+ )
+ pending = await self._id_row(
+ conn,
+ "SELECT COUNT(*) AS n FROM uw_confirm_queue WHERE status = ?",
+ (str(QueueStatus.PENDING),),
+ )
+ merges = await self._id_row(
+ conn, "SELECT COUNT(*) AS n FROM uw_merge_log WHERE undone_at IS NULL"
+ )
+ return {
+ "entities": int((entities or {"n": 0})["n"] or 0),
+ "people": int((people or {"n": 0})["n"] or 0),
+ "identifiers": int((identifiers or {"n": 0})["n"] or 0),
+ "pending_confirmations": int((pending or {"n": 0})["n"] or 0),
+ "merges": int((merges or {"n": 0})["n"] or 0),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Seeding from the Jarvis contacts store
+# ---------------------------------------------------------------------------
+
+
+async def seed_from_contacts(
+ store: Any,
+ *,
+ contacts: Sequence[Any] | None = None,
+ contact_store: Any = None,
+) -> SeedReport:
+ """Seed entities from the user's address book — lazy, idempotent, re-runnable.
+
+ Day one already knows the user's actual circle (design doc 05). The pass
+ is safe to repeat: a contact resolves through its own ``contact`` slug
+ identifier, so a second run links instead of duplicating, and a contact
+ whose e-mail or phone already appeared in the corpus MERGES with that
+ entity deterministically rather than creating a twin.
+
+ Reading the address book is blocking file I/O and the import is lazy
+ (AP-26), so neither touches the boot path.
+ """
+ if contacts is None:
+ import asyncio # noqa: PLC0415 — lazy, keeps the module import cheap
+
+ if contact_store is None:
+ from jarvis.contacts.store import ContactStore # noqa: PLC0415 — lazy
+
+ contact_store = ContactStore()
+ contacts = await asyncio.to_thread(contact_store.list_all)
+
+ created = linked = identifiers_added = merged = queued = skipped = 0
+ for contact in contacts or []:
+ name = str(getattr(contact, "name", "") or "").strip()
+ slug = str(getattr(contact, "slug", "") or "").strip()
+ if not name and not slug:
+ skipped += 1
+ continue
+ source_ref = f"contacts:{slug}" if slug else ""
+ try:
+ resolution = await store.resolve_identity(
+ name=name,
+ emails=list(getattr(contact, "emails", []) or []),
+ phones=list(getattr(contact, "phones", []) or []),
+ contact_slug=slug,
+ kind=EntityKind.PERSON,
+ source_ref=source_ref,
+ create=True,
+ )
+ except IdentityError as exc:
+ log.info("UltraWiki identity: skipping contact %r (%s)", slug or name, exc)
+ skipped += 1
+ continue
+ if resolution.entity_id is None:
+ skipped += 1
+ queued += len(resolution.queued)
+ continue
+ created += 1 if resolution.created else 0
+ linked += 0 if resolution.created else 1
+ merged += len(resolution.merged)
+ queued += len(resolution.queued)
+ if source_ref:
+ await store.set_entity_source_ref(resolution.entity_id, source_ref)
+ for alias in getattr(contact, "aliases", []) or []:
+ result = await store.add_identifier(
+ resolution.entity_id,
+ IdentifierKind.NAME,
+ alias,
+ source_ref=source_ref,
+ )
+ identifiers_added += 1 if result.created else 0
+ merged += len(result.merged)
+ queued += len(result.queued)
+ return SeedReport(
+ created=created,
+ linked=linked,
+ identifiers_added=identifiers_added,
+ merged=merged,
+ queued=queued,
+ skipped=skipped,
+ )
diff --git a/jarvis/ultrawiki/migrations/0003_identity.sql b/jarvis/ultrawiki/migrations/0003_identity.sql
new file mode 100644
index 0000000000..f249cf2db8
--- /dev/null
+++ b/jarvis/ultrawiki/migrations/0003_identity.sql
@@ -0,0 +1,132 @@
+-- Identity layer (design doc 05 · D-10): entities, identifiers, the
+-- confirmation queue, and a reversible merge audit trail.
+--
+-- Why these four tables and not one: the corpus arrives as raw handles — a
+-- phone number here, a display name there, an address-book slug in a third
+-- place — and the ONLY safe way to fuse them is to keep the mapping itself as
+-- data. `uw_identifiers` is that mapping (many handles -> one entity),
+-- `uw_entities` holds the thing they point at, `uw_confirm_queue` holds every
+-- link the evidence merely SUGGESTS, and `uw_merge_log` records each applied
+-- merge together with the exact state needed to undo it.
+--
+-- Reversibility is the whole point. A wrong merge silently poisons every
+-- future answer about both identities and is discovered months later, so no
+-- merge may ever be a one-way door: the audit row carries which identifier
+-- rows moved, which duplicates were dropped, and what the loser's own
+-- bookkeeping looked like before, which is enough to restore the prior state
+-- exactly.
+--
+-- Dialect note: this is the SQLite source of truth. `PostgresStore.
+-- ddl_statements()` mirrors it (BIGSERIAL/BIGINT for the keys) and DERIVES
+-- every CHECK list from the enums in `jarvis/ultrawiki/identity.py`;
+-- `tests/unit/ultrawiki/test_identity_parity.py` holds the three layers
+-- together (AP-4 / BUG-008).
+
+BEGIN;
+
+-- A person, place, organization, project or topic. A merged-away entity is
+-- NOT deleted: it stays as a tombstone whose `merged_into` forwards every old
+-- reference to the survivor, which is what makes an unmerge possible at all.
+CREATE TABLE IF NOT EXISTS uw_entities (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL DEFAULT 'person'
+ CHECK (kind IN ('person', 'place', 'org', 'project', 'topic')),
+ display_name TEXT NOT NULL,
+ -- Normalized `display_name` (identity.normalize_name): the sort key and
+ -- the cheap lookup key. Empty when the display name normalizes to nothing.
+ canonical_key TEXT NOT NULL DEFAULT '',
+ merged_into INTEGER REFERENCES uw_entities(id) ON DELETE SET NULL,
+ -- Provenance of a seeded row, e.g. 'contacts:<slug>'. Unique among the
+ -- rows that carry one, so re-seeding the address book is idempotent.
+ source_ref TEXT NOT NULL DEFAULT '',
+ profile_json TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_uw_entities_live
+ ON uw_entities(merged_into, kind);
+CREATE INDEX IF NOT EXISTS idx_uw_entities_key
+ ON uw_entities(canonical_key);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_entities_source_ref
+ ON uw_entities(source_ref) WHERE source_ref != '';
+
+-- Raw handles mapped many-to-one onto an entity. `value` is ALWAYS the
+-- normalized form (that is what makes a match a match); `display_value` keeps
+-- the spelling a human would recognize.
+--
+-- The uniqueness is per ENTITY, not global, on purpose: the same name
+-- legitimately sits on two different people, and after an unmerge both sides
+-- must be able to hold their own copy again. A deterministic identifier
+-- appearing on a second entity is not a constraint violation — it is the
+-- merge trigger.
+CREATE TABLE IF NOT EXISTS uw_identifiers (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ entity_id INTEGER NOT NULL REFERENCES uw_entities(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL
+ CHECK (kind IN ('email', 'phone', 'contact', 'handle', 'name')),
+ value TEXT NOT NULL,
+ display_value TEXT NOT NULL DEFAULT '',
+ -- Denormalized length of `value`: the indexed half of the fuzzy-candidate
+ -- block (identity.LEN_WINDOW), so a near-name lookup never scans the table.
+ value_len INTEGER NOT NULL DEFAULT 0,
+ source_ref TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_identifiers_unique
+ ON uw_identifiers(entity_id, kind, value);
+CREATE INDEX IF NOT EXISTS idx_uw_identifiers_value
+ ON uw_identifiers(kind, value);
+CREATE INDEX IF NOT EXISTS idx_uw_identifiers_len
+ ON uw_identifiers(kind, value_len);
+CREATE INDEX IF NOT EXISTS idx_uw_identifiers_entity
+ ON uw_identifiers(entity_id);
+
+-- Proposed merges awaiting one human decision. `pair_key` is UNIQUE and
+-- order-independent, so re-observing the same weak evidence refreshes the one
+-- open proposal instead of stacking duplicates — and a REJECTED pair is never
+-- asked about again (anti-confirmation-fatigue).
+CREATE TABLE IF NOT EXISTS uw_confirm_queue (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ pair_key TEXT NOT NULL UNIQUE,
+ left_entity_id INTEGER NOT NULL REFERENCES uw_entities(id) ON DELETE CASCADE,
+ right_entity_id INTEGER NOT NULL REFERENCES uw_entities(id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'confirmed', 'rejected')),
+ score REAL NOT NULL DEFAULT 0,
+ evidence_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ decided_at TEXT,
+ decided_by TEXT
+);
+
+CREATE INDEX IF NOT EXISTS idx_uw_confirm_queue_status
+ ON uw_confirm_queue(status, score DESC, id);
+
+-- Every applied merge, automatic or confirmed, with the evidence that
+-- justified it and the undo payload that reverses it.
+--
+-- Deliberately NO foreign keys onto uw_entities: the audit trail must survive
+-- a purge that removes the entities themselves. A record of what happened is
+-- worth nothing if it disappears together with the thing it happened to.
+CREATE TABLE IF NOT EXISTS uw_merge_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ winner_id INTEGER NOT NULL,
+ loser_id INTEGER NOT NULL,
+ tier TEXT NOT NULL CHECK (tier IN ('deterministic', 'probable')),
+ reason TEXT NOT NULL DEFAULT '',
+ evidence_json TEXT NOT NULL DEFAULT '[]',
+ undo_json TEXT NOT NULL DEFAULT '{}',
+ queue_id INTEGER,
+ merged_at TEXT NOT NULL,
+ undone_at TEXT
+);
+
+CREATE INDEX IF NOT EXISTS idx_uw_merge_log_winner
+ ON uw_merge_log(winner_id, undone_at);
+CREATE INDEX IF NOT EXISTS idx_uw_merge_log_loser
+ ON uw_merge_log(loser_id, undone_at);
+
+COMMIT;
diff --git a/jarvis/ultrawiki/migrations/README.md b/jarvis/ultrawiki/migrations/README.md
index 4dceb8a4f1..e4829b0494 100644
--- a/jarvis/ultrawiki/migrations/README.md
+++ b/jarvis/ultrawiki/migrations/README.md
@@ -26,7 +26,14 @@ The contract:
Shipped so far: `0001` (multi-chunk documents), `0002` (the shadow embedding
space — widening the `uw_embeddings` key so a model switch can build the new
-vector space alongside the live one). The Postgres backend applies its DDL
-idempotently from `PostgresStore.ddl_statements()`, including the in-place
-key widening that mirrors `0002`; it receives its own version tracking when a
-change ships that idempotent DDL cannot express.
+vector space alongside the live one), `0003` (the identity layer: entities,
+identifiers, the confirmation queue and the reversible merge log). The
+Postgres backend applies its DDL idempotently from
+`PostgresStore.ddl_statements()`, including the in-place key widening that
+mirrors `0002` and the identity tables that mirror `0003`; it receives its own
+version tracking when a change ships that idempotent DDL cannot express.
+
+A migration that only ADDS tables (like `0003`) is still the right home for
+them: keeping one dialect-complete DDL per feature in one numbered file beats
+splitting it between here and `schema.sql`, and the runner applies pending
+files to fresh databases too (a new store starts at `user_version = 0`).
diff --git a/jarvis/ultrawiki/schema.sql b/jarvis/ultrawiki/schema.sql
index 81861b2b1d..7beaa6df75 100644
--- a/jarvis/ultrawiki/schema.sql
+++ b/jarvis/ultrawiki/schema.sql
@@ -165,3 +165,8 @@ CREATE TABLE IF NOT EXISTS uw_distill_cache (
created_at TEXT NOT NULL,
PRIMARY KEY (content_hash, prompt_version, model)
);
+
+-- The identity layer (uw_entities / uw_identifiers / uw_confirm_queue /
+-- uw_merge_log, design doc 05) ships as migrations/0003_identity.sql rather
+-- than as part of this file, so its DDL exists exactly once per dialect. The
+-- runner applies it to fresh and existing databases alike.
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
index cf2ae6be14..6aa58ea08f 100644
--- a/jarvis/ultrawiki/service.py
+++ b/jarvis/ultrawiki/service.py
@@ -1711,6 +1711,81 @@ class UltraWikiService:
raise ValueError(f"unknown source {source_id!r}")
return int(await store.requeue_failed(source_id))
+ # -- identity (design doc 05 · D-10) -------------------------------------
+
+ async def seed_identities(self, *, contact_store: Any = None) -> dict[str, Any]:
+ """Seed entities from the user's address book; idempotent and re-runnable.
+
+ Safe to call on every activation: a second pass links instead of
+ duplicating. Runs off the boot path like every other service action.
+ ``contact_store`` is a test seam; production resolves the real one.
+ """
+ await self.ensure_started()
+ from jarvis.ultrawiki.identity_store import ( # noqa: PLC0415 — lazy (AP-26)
+ seed_from_contacts,
+ )
+
+ report = await seed_from_contacts(
+ self._require_store(), contact_store=contact_store
+ )
+ return report.to_dict()
+
+ async def list_people(
+ self, *, query: str = "", limit: int = 100, offset: int = 0
+ ) -> list[dict[str, Any]]:
+ """The People view's list: live person entities, name-ordered."""
+ await self.ensure_started()
+ return await self._require_store().list_people(
+ query=query, limit=limit, offset=offset
+ )
+
+ async def person_profile(self, entity_id: int) -> dict[str, Any] | None:
+ """One person's identifiers, merge history and open proposals."""
+ await self.ensure_started()
+ return await self._require_store().get_person(int(entity_id))
+
+ async def identity_queue(
+ self, *, status: str | None = "pending", limit: int = 100
+ ) -> list[dict[str, Any]]:
+ """Merge proposals awaiting a decision (``status=None`` for all)."""
+ await self.ensure_started()
+ return await self._require_store().list_confirm_queue(
+ status=status, limit=limit
+ )
+
+ async def confirm_identity_merge(
+ self, queue_id: int, *, decided_by: str = "user"
+ ) -> dict[str, Any]:
+ """Apply one proposal. Returns the audit id that reverses it."""
+ await self.ensure_started()
+ merge_id = await self._require_store().confirm_merge(
+ int(queue_id), decided_by=decided_by
+ )
+ return {"queue_id": int(queue_id), "merge_id": int(merge_id)}
+
+ async def reject_identity_merge(
+ self, queue_id: int, *, decided_by: str = "user"
+ ) -> dict[str, Any]:
+ """Decline one proposal permanently (never asked about again)."""
+ await self.ensure_started()
+ await self._require_store().reject_merge(int(queue_id), decided_by=decided_by)
+ return {"queue_id": int(queue_id), "status": "rejected"}
+
+ async def unmerge_identity(self, merge_id: int) -> dict[str, Any]:
+ """Undo one merge, restoring both identities exactly as they were."""
+ await self.ensure_started()
+ await self._require_store().unmerge(int(merge_id))
+ return {"merge_id": int(merge_id), "status": "undone"}
+
+ async def identity_merge_log(
+ self, *, entity_id: int | None = None, limit: int = 100
+ ) -> list[dict[str, Any]]:
+ """The audit trail: every merge, its evidence, and whether it stands."""
+ await self.ensure_started()
+ return await self._require_store().list_merge_log(
+ entity_id=entity_id, limit=limit
+ )
+
# -- search --------------------------------------------------------------
async def search(self, query: str, **kwargs: Any) -> Any:
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index d47a66e99f..7fe0e7c8d8 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -50,6 +50,13 @@ from urllib.parse import quote
import aiosqlite
+from jarvis.ultrawiki.identity import (
+ MERGEABLE_TIERS,
+ EntityKind,
+ IdentifierKind,
+ QueueStatus,
+)
+from jarvis.ultrawiki.identity_store import IdentityMixin
from jarvis.ultrawiki.types import (
STATE_ORDER,
ConsentState,
@@ -514,7 +521,7 @@ _DISTILLED_FINGERPRINT_SQL = (
# ---------------------------------------------------------------------------
-class UltraStore:
+class UltraStore(IdentityMixin):
"""Async SQLite store for UltraWiki (the universal reference backend).
One instance = one ``aiosqlite`` connection, opened lazily on first use
@@ -750,6 +757,19 @@ class UltraStore:
await cur.close()
return row
+ async def _id_insert(
+ self, conn: aiosqlite.Connection, sql: str, params: Sequence[Any]
+ ) -> int:
+ """Identity-layer INSERT hook: SQLite reports the id via ``lastrowid``.
+
+ Deliberately not ``RETURNING``: that needs SQLite ≥ 3.35, and the
+ headless-Linux floor may run whatever the distro ships.
+ """
+ cur = await conn.execute(sql, params)
+ row_id = int(cur.lastrowid or 0)
+ await cur.close()
+ return row_id
+
# -- sources & consent -------------------------------------------------
async def upsert_source(
@@ -2559,7 +2579,7 @@ class UltraStore:
# ---------------------------------------------------------------------------
-class PostgresStore:
+class PostgresStore(IdentityMixin):
"""Postgres backend behind the same public surface as :class:`UltraStore`.
- The keyword leg is a generated ``tsvector`` column with a GIN index,
@@ -2574,6 +2594,10 @@ class PostgresStore:
SQLite is the reference backend; this class mirrors its semantics.
"""
+ #: The identity layer writes its SQL once, in the SQLite dialect;
+ #: :meth:`IdentityMixin._id_sql` rewrites the placeholders for psycopg.
+ _IDENTITY_PARAM = "%s"
+
def __init__(self, conn_str: str) -> None:
self._conn_str = conn_str
self._conn: Any = None
@@ -2581,6 +2605,12 @@ class PostgresStore:
self._vec_state: tuple[bool, str] | None = None
self._vec_dim: int | None = None
+ async def _id_insert(self, conn: Any, sql: str, params: Sequence[Any]) -> int:
+ """Identity-layer INSERT hook: Postgres reports the id via RETURNING."""
+ cur = await conn.execute(f"{sql} RETURNING id", params)
+ row = await cur.fetchone()
+ return int(row["id"])
+
# -- DDL -----------------------------------------------------------------
@classmethod
@@ -2593,6 +2623,12 @@ class PostgresStore:
states = ", ".join(f"'{state.value}'" for state in ItemState)
consents = ", ".join(f"'{consent.value}'" for consent in ConsentState)
doc_types = ", ".join(f"'{doc.value}'" for doc in DocType)
+ entity_kinds = ", ".join(f"'{kind.value}'" for kind in EntityKind)
+ identifier_kinds = ", ".join(f"'{kind.value}'" for kind in IdentifierKind)
+ queue_states = ", ".join(f"'{status.value}'" for status in QueueStatus)
+ merge_tiers = ", ".join(
+ f"'{tier.value}'" for tier in sorted(MERGEABLE_TIERS, key=str)
+ )
return [
"CREATE TABLE IF NOT EXISTS uw_meta ("
" key TEXT PRIMARY KEY, value TEXT NOT NULL)",
@@ -2684,6 +2720,68 @@ class PostgresStore:
" model TEXT NOT NULL, result_json TEXT NOT NULL,"
" created_at TEXT NOT NULL,"
" PRIMARY KEY (content_hash, prompt_version, model))",
+ # Identity layer (design doc 05 · D-10) — the Postgres twin of
+ # migrations/0003_identity.sql. Same tables, same constraints, same
+ # partial indexes; only the key types differ.
+ "CREATE TABLE IF NOT EXISTS uw_entities ("
+ " id BIGSERIAL PRIMARY KEY,"
+ " kind TEXT NOT NULL DEFAULT 'person'"
+ f" CHECK (kind IN ({entity_kinds})),"
+ " display_name TEXT NOT NULL,"
+ " canonical_key TEXT NOT NULL DEFAULT '',"
+ " merged_into BIGINT REFERENCES uw_entities(id) ON DELETE SET NULL,"
+ " source_ref TEXT NOT NULL DEFAULT '',"
+ " profile_json TEXT NOT NULL DEFAULT '{}',"
+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_entities_live"
+ " ON uw_entities(merged_into, kind)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_entities_key"
+ " ON uw_entities(canonical_key)",
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_entities_source_ref"
+ " ON uw_entities(source_ref) WHERE source_ref != ''",
+ "CREATE TABLE IF NOT EXISTS uw_identifiers ("
+ " id BIGSERIAL PRIMARY KEY,"
+ " entity_id BIGINT NOT NULL"
+ " REFERENCES uw_entities(id) ON DELETE CASCADE,"
+ f" kind TEXT NOT NULL CHECK (kind IN ({identifier_kinds})),"
+ " value TEXT NOT NULL, display_value TEXT NOT NULL DEFAULT '',"
+ " value_len INTEGER NOT NULL DEFAULT 0,"
+ " source_ref TEXT NOT NULL DEFAULT '',"
+ " created_at TEXT NOT NULL)",
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_identifiers_unique"
+ " ON uw_identifiers(entity_id, kind, value)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_identifiers_value"
+ " ON uw_identifiers(kind, value)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_identifiers_len"
+ " ON uw_identifiers(kind, value_len)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_identifiers_entity"
+ " ON uw_identifiers(entity_id)",
+ "CREATE TABLE IF NOT EXISTS uw_confirm_queue ("
+ " id BIGSERIAL PRIMARY KEY, pair_key TEXT NOT NULL UNIQUE,"
+ " left_entity_id BIGINT NOT NULL"
+ " REFERENCES uw_entities(id) ON DELETE CASCADE,"
+ " right_entity_id BIGINT NOT NULL"
+ " REFERENCES uw_entities(id) ON DELETE CASCADE,"
+ " status TEXT NOT NULL DEFAULT 'pending'"
+ f" CHECK (status IN ({queue_states})),"
+ " score DOUBLE PRECISION NOT NULL DEFAULT 0,"
+ " evidence_json TEXT NOT NULL DEFAULT '[]',"
+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL,"
+ " decided_at TEXT, decided_by TEXT)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_confirm_queue_status"
+ " ON uw_confirm_queue(status, score DESC, id)",
+ "CREATE TABLE IF NOT EXISTS uw_merge_log ("
+ " id BIGSERIAL PRIMARY KEY,"
+ " winner_id BIGINT NOT NULL, loser_id BIGINT NOT NULL,"
+ f" tier TEXT NOT NULL CHECK (tier IN ({merge_tiers})),"
+ " reason TEXT NOT NULL DEFAULT '',"
+ " evidence_json TEXT NOT NULL DEFAULT '[]',"
+ " undo_json TEXT NOT NULL DEFAULT '{}',"
+ " queue_id BIGINT, merged_at TEXT NOT NULL, undone_at TEXT)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_merge_log_winner"
+ " ON uw_merge_log(winner_id, undone_at)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_merge_log_loser"
+ " ON uw_merge_log(loser_id, undone_at)",
# The same additive columns for databases created before the
# feature that introduced them. Postgres HAS `ADD COLUMN IF NOT
# EXISTS`, so the SQLite pragma dance is unnecessary here — but the
diff --git a/tests/unit/ultrawiki/test_identity.py b/tests/unit/ultrawiki/test_identity.py
new file mode 100644
index 0000000000..90941d4338
--- /dev/null
+++ b/tests/unit/ultrawiki/test_identity.py
@@ -0,0 +1,306 @@
+"""Identity resolution logic — normalization, similarity, tiers.
+
+Pure functions only: no database, no network, no model, no clock. The
+calibration tests are the interesting ones — they pin the two families of
+near-names the store must treat differently (speech-to-text variants of ONE
+thing versus two genuinely different people) against the actual threshold, so
+a future tuning change cannot quietly turn a proposal into a merge.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.ultrawiki.identity import (
+ DETERMINISTIC_KINDS,
+ LEN_WINDOW,
+ MAX_NAME_CHARS,
+ MERGEABLE_TIERS,
+ MIN_NAME_CHARS,
+ MIN_PHONE_DIGITS,
+ NICKNAME_SCORE,
+ PREFIX_BLOCK_CHARS,
+ PROPOSE_THRESHOLD,
+ EntityKind,
+ IdentifierKind,
+ MatchEvidence,
+ MatchTier,
+ QueueStatus,
+ could_match,
+ escape_like,
+ name_similarity,
+ nickname_score,
+ normalize_contact_slug,
+ normalize_email,
+ normalize_handle,
+ normalize_identifier,
+ normalize_name,
+ normalize_phone,
+ pair_key,
+ tier_for_score,
+)
+from jarvis.ultrawiki.projection import MAX_LABEL_CHARS, MIN_LABEL_CHARS
+
+# ---------------------------------------------------------------------------
+# Value sets
+# ---------------------------------------------------------------------------
+
+
+def test_only_unique_identifier_kinds_are_deterministic():
+ """A name never decides anything on its own — that is the whole design."""
+ assert DETERMINISTIC_KINDS == {
+ IdentifierKind.EMAIL,
+ IdentifierKind.PHONE,
+ IdentifierKind.CONTACT,
+ }
+ assert IdentifierKind.NAME not in DETERMINISTIC_KINDS
+ assert IdentifierKind.HANDLE not in DETERMINISTIC_KINDS
+
+
+def test_weak_evidence_can_never_become_a_merge():
+ assert MatchTier.WEAK not in MERGEABLE_TIERS
+ assert MERGEABLE_TIERS == {MatchTier.DETERMINISTIC, MatchTier.PROBABLE}
+
+
+def test_name_bounds_match_the_projection_layer():
+ """One corpus, one idea of what a usable label is."""
+ assert (MIN_NAME_CHARS, MAX_NAME_CHARS) == (MIN_LABEL_CHARS, MAX_LABEL_CHARS)
+
+
+def test_enum_values_are_stable_wire_strings():
+ assert {kind.value for kind in EntityKind} == {
+ "person",
+ "place",
+ "org",
+ "project",
+ "topic",
+ }
+ assert {status.value for status in QueueStatus} == {
+ "pending",
+ "confirmed",
+ "rejected",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Normalization
+# ---------------------------------------------------------------------------
+
+
+ ("raw", "expected"),
+ [
+ (" Viktoria Novak ", "viktoria novak"),
+ ("VIKTORIA NOVAK", "viktoria novak"),
+ ("Novak, Viktoria.", "novak, viktoria"),
+ ("-ultra-wiki-", "ultra-wiki"),
+ ("a", None), # below the floor
+ ("x" * (MAX_NAME_CHARS + 1), None), # above the ceiling
+ ("...", None),
+ (None, None),
+ (42, None),
+ ],
+)
+def test_normalize_name_cases(raw, expected):
+ assert normalize_name(raw) == expected
+
+
+def test_normalize_name_folds_decomposed_unicode():
+ """macOS hands text back decomposed; without NFC the same name becomes
+ two entities."""
+ composed = "Zoë" # Zoe with diaeresis, single code point
+ decomposed = "Zoë" # e + combining diaeresis
+ assert composed != decomposed
+ assert normalize_name(composed) == normalize_name(decomposed)
+
+
+def test_name_normalization_stays_conservative():
+ """The three spellings a speech-to-text pass produces of one title must
+ remain THREE keys. Collapsing them here would be an implicit merge on name
+ similarity — exactly what the design forbids."""
+ keys = {
+ normalize_name("Ultra Wiki"),
+ normalize_name("ultra-wiki"),
+ normalize_name("UltraWiki"),
+ }
+ assert len(keys) == 3
+ # Case alone is not a difference, though.
+ assert normalize_name("Ultra-Wiki") == normalize_name("ultra-wiki")
+
+
+ ("raw", "expected"),
+ [
+ ("not-an-email", None),
+ ("a@b", None),
+ ("", None),
+ (None, None),
+ ],
+)
+def test_normalize_email_cases(raw, expected):
+ assert normalize_email(raw) == expected
+
+
+ ("raw", "expected"),
+ [
+ ("+49 151 2345-6789", "+4915123456789"),
+ ("0049 151 23456789", "+4915123456789"),
+ ("(030) 12 34 56", "030123456"),
+ ("12345", None), # too short to be a unique identifier
+ ("no digits", None),
+ (None, None),
+ ],
+)
+def test_normalize_phone_cases(raw, expected):
+ assert normalize_phone(raw) == expected
+
+
+def test_phone_formats_of_one_number_collapse_onto_one_key():
+ """Two sources formatting the same number differently is precisely what
+ makes 'same phone number' a deterministic match."""
+ assert normalize_phone("+49 151 2345 6789") == normalize_phone("0049-151-23456789")
+
+
+def test_short_numbers_can_never_merge_anything():
+ assert normalize_phone("1" * (MIN_PHONE_DIGITS - 1)) is None
+ assert normalize_phone("1" * MIN_PHONE_DIGITS) is not None
+
+
+ ("raw", "expected"),
+ [
+ ("@RL", "rl"),
+ ("Slack:@RL", "slack:rl"),
+ ("x", None),
+ (":handle", None),
+ (None, None),
+ ],
+)
+def test_normalize_handle_cases(raw, expected):
+ assert normalize_handle(raw) == expected
+
+
+def test_normalize_contact_slug():
+ assert normalize_contact_slug(" Viktoria-Novak ") == "viktoria-novak"
+ assert normalize_contact_slug("") is None
+
+
+def test_normalize_identifier_dispatches_and_refuses_unknown_kinds():
+ assert normalize_identifier(IdentifierKind.EMAIL, "[email protected]") == "[email protected]"
+ assert normalize_identifier("phone", "+49 151 234567") == "+49151234567"
+ assert normalize_identifier("nonsense", "value") is None
+
+
+# ---------------------------------------------------------------------------
+# Similarity calibration — the load-bearing numbers
+# ---------------------------------------------------------------------------
+
+
+ ("left", "right"),
+ [
+ # Speech-to-text variants of ONE topic (observed in the live vault).
+ ("agentic-i", "gentic-ide"),
+ ("ultra wiki", "ultra-wiki"),
+ ("ultrawiki", "ultra-wiki"),
+ # Token order differences.
+ ("viktoria novak", "novak viktoria"),
+ ],
+)
+def test_near_duplicates_reach_the_proposal_threshold(left, right):
+ assert name_similarity(left, right) >= PROPOSE_THRESHOLD
+ assert tier_for_score(name_similarity(left, right)) is MatchTier.PROBABLE
+
+
+ ("left", "right"),
+ [
+ # Two different people who merely share a surname.
+ ("john smith", "jane smith"),
+ # Nothing in common at all.
+ ("agentic-i", "quarterly budget"),
+ ],
+)
+def test_unrelated_names_stay_below_the_threshold(left, right):
+ assert name_similarity(left, right) < PROPOSE_THRESHOLD
+ assert tier_for_score(name_similarity(left, right)) is MatchTier.WEAK
+
+
+def test_identical_names_score_one_but_are_still_not_deterministic():
+ assert name_similarity("john smith", "john smith") == 1.0
+ # A score can only ever propose. Deterministic is reserved for identifiers.
+ assert tier_for_score(1.0) is MatchTier.PROBABLE
+
+
+def test_nickname_rule_covers_the_canonical_example():
+ """"Viki" is not similar to "Viktoria Novak" by any string metric, yet it
+ is the textbook probable match."""
+ assert nickname_score("viki", "viktoria novak") == NICKNAME_SCORE
+ assert name_similarity("viki", "viktoria novak") >= PROPOSE_THRESHOLD
+
+
+ ("short", "long"),
+ [
+ ("ana", "anastasia"), # below the length floor
+ ("rick", "patrick"), # different first character
+ ("vi ki", "viktoria novak"), # a multi-word "nickname" is not one
+ ("marc", "marcelinodefigueroa"), # dwarfed by the long form
+ ],
+)
+def test_nickname_rule_refuses_loose_abbreviations(short, long):
+ assert nickname_score(short, long) == 0.0
+
+
+def test_similarity_is_symmetric_and_bounded():
+ for left, right in (("viki", "viktoria"), ("john smith", "jane smith")):
+ score = name_similarity(left, right)
+ assert score == name_similarity(right, left)
+ assert 0.0 <= score <= 1.0
+
+
+def test_empty_names_never_match():
+ assert name_similarity("", "anything") == 0.0
+ assert not could_match("", "anything")
+
+
+# ---------------------------------------------------------------------------
+# Blocking, keys, escaping
+# ---------------------------------------------------------------------------
+
+
+def test_could_match_mirrors_the_sql_candidate_block():
+ """The SQL fetches by length window OR shared prefix; the Python gate must
+ accept exactly those, or a candidate the database returned gets silently
+ dropped by a rule the database never knew about."""
+ base = "agentic ide"
+ assert could_match(base, "a" * (len(base) + LEN_WINDOW))
+ assert not could_match(base, "a" * (len(base) + LEN_WINDOW + 1))
+ prefixed = base[:PREFIX_BLOCK_CHARS] + "x" * 40
+ assert could_match(base, prefixed)
+
+
+def test_pair_key_is_order_independent():
+ assert pair_key(7, 3) == pair_key(3, 7) == "3:7"
+
+
+def test_escape_like_neutralizes_wildcards():
+ assert escape_like("100%_a\\b") == "100\\%\\_a\\\\b"
+
+
+def test_match_evidence_round_trips_through_json_shape():
+ evidence = MatchEvidence(
+ tier=MatchTier.PROBABLE, kind="name_similar", value="viki", score=0.8412345
+ )
+ payload = evidence.to_dict()
+ assert payload == {
+ "tier": "probable",
+ "kind": "name_similar",
+ "value": "viki",
+ "score": 0.8412,
+ }
+ assert MatchEvidence.from_dict(payload).kind == "name_similar"
diff --git a/tests/unit/ultrawiki/test_identity_parity.py b/tests/unit/ultrawiki/test_identity_parity.py
new file mode 100644
index 0000000000..bc0054351d
--- /dev/null
+++ b/tests/unit/ultrawiki/test_identity_parity.py
@@ -0,0 +1,109 @@
+"""Five-layer drift guard for the identity layer (AP-4 / BUG-008).
+
+The identity value sets cross Python -> SQLite DDL -> Postgres DDL. Each of
+those is a place where a hand-retyped list can silently diverge, and the
+symptom is the nastiest kind: a value the code produces gets rejected by a
+CHECK constraint on ONE backend, months later, on a user's machine. The
+canonical lists live in ``jarvis/ultrawiki/identity.py``; everything else is
+asserted equal to them here.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import jarvis.ultrawiki
+from jarvis.ultrawiki.identity import (
+ MERGEABLE_TIERS,
+ EntityKind,
+ IdentifierKind,
+ QueueStatus,
+)
+from jarvis.ultrawiki.store import PostgresStore
+
+MIGRATION_SQL = (
+ Path(jarvis.ultrawiki.__file__).parent / "migrations" / "0003_identity.sql"
+).read_text(encoding="utf-8")
+POSTGRES_DDL = "\n".join(PostgresStore.ddl_statements())
+
+
+def check_values(sql: str, table: str, column: str) -> set[str]:
+ """Extract the quoted value list of ``CHECK (<column> IN (...))`` from the
+ statement that creates ``table``."""
+ start = sql.index(f"uw_{table} (")
+ fragment = sql[start:]
+ match = re.search(
+ rf"CHECK\s*\(\s*{column}\s+IN\s*\(([^)]*)\)", fragment, re.IGNORECASE
+ )
+ assert match is not None, f"no CHECK list for uw_{table}.{column}"
+ return set(re.findall(r"'([^']+)'", match.group(1)))
+
+
+def test_sqlite_entity_kind_check_matches_the_enum():
+ assert check_values(MIGRATION_SQL, "entities", "kind") == {
+ kind.value for kind in EntityKind
+ }
+
+
+def test_sqlite_identifier_kind_check_matches_the_enum():
+ assert check_values(MIGRATION_SQL, "identifiers", "kind") == {
+ kind.value for kind in IdentifierKind
+ }
+
+
+def test_sqlite_queue_status_check_matches_the_enum():
+ assert check_values(MIGRATION_SQL, "confirm_queue", "status") == {
+ status.value for status in QueueStatus
+ }
+
+
+def test_sqlite_merge_tier_check_excludes_the_weak_tier():
+ """A weak match writes nothing at all, so a weak merge row must be
+ impossible rather than merely unusual."""
+ assert check_values(MIGRATION_SQL, "merge_log", "tier") == {
+ tier.value for tier in MERGEABLE_TIERS
+ }
+
+
+def test_postgres_identity_check_lists_match_the_enums():
+ assert check_values(POSTGRES_DDL, "entities", "kind") == {
+ kind.value for kind in EntityKind
+ }
+ assert check_values(POSTGRES_DDL, "identifiers", "kind") == {
+ kind.value for kind in IdentifierKind
+ }
+ assert check_values(POSTGRES_DDL, "confirm_queue", "status") == {
+ status.value for status in QueueStatus
+ }
+ assert check_values(POSTGRES_DDL, "merge_log", "tier") == {
+ tier.value for tier in MERGEABLE_TIERS
+ }
+
+
+def test_both_dialects_declare_the_same_identity_tables_and_indexes():
+ for table in ("entities", "identifiers", "confirm_queue", "merge_log"):
+ assert f"uw_{table} (" in MIGRATION_SQL
+ assert f"uw_{table} (" in POSTGRES_DDL
+ for index in (
+ "idx_uw_entities_source_ref",
+ "idx_uw_identifiers_unique",
+ "idx_uw_identifiers_value",
+ "idx_uw_identifiers_len",
+ "idx_uw_confirm_queue_status",
+ "idx_uw_merge_log_winner",
+ ):
+ assert index in MIGRATION_SQL
+ assert index in POSTGRES_DDL
+
+
+def test_migration_is_numbered_after_the_current_head():
+ """Forward-only: a new file never renumbers or rewrites a shipped one."""
+ directory = Path(jarvis.ultrawiki.__file__).parent / "migrations"
+ numbers = sorted(
+ int(path.name[:4])
+ for path in directory.glob("*.sql")
+ if re.match(r"^\d{4}_", path.name)
+ )
+ assert numbers == list(range(1, len(numbers) + 1))
+ assert numbers[-1] == 3
diff --git a/tests/unit/ultrawiki/test_identity_service.py b/tests/unit/ultrawiki/test_identity_service.py
new file mode 100644
index 0000000000..c2c0efdefd
--- /dev/null
+++ b/tests/unit/ultrawiki/test_identity_service.py
@@ -0,0 +1,112 @@
+"""The identity facade on ``UltraWikiService`` — the surface later phases call.
+
+Offline, tmp store, a real (temporary) contacts directory instead of a mock:
+the point is that the People view, the CLI and the brain tools can drive the
+whole confirm/reject/unmerge cycle through the service without reaching into
+the store.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.contacts.store import ContactStore
+from jarvis.ultrawiki.identity import IdentityError
+from jarvis.ultrawiki.service import UltraWikiService
+
+
+def make_cfg(tmp_path) -> SimpleNamespace:
+ """UltraWiki disabled: the store opens, the ingest worker stays asleep."""
+ return SimpleNamespace(
+ ultrawiki=SimpleNamespace(
+ enabled=False,
+ db_backend="sqlite",
+ embedding_provider="",
+ embedding_model="",
+ distill_provider="",
+ distill_model="",
+ rerank_provider="",
+ ollama_endpoint="",
+ ),
+ memory=SimpleNamespace(data_dir=str(tmp_path)),
+ brain=SimpleNamespace(primary=""),
+ )
+
+
+async def service(tmp_path):
+ instance = UltraWikiService(make_cfg(tmp_path))
+ await instance.ensure_started()
+ yield instance
+ await instance.shutdown()
+
+
+def contacts(tmp_path) -> ContactStore:
+ store = ContactStore(base_dir=tmp_path / "contacts")
+ store.put(
+ name="Viktoria Novak",
+ aliases=["Viki"],
+ emails=["[email protected]"],
+ phones=["+49 151 2345 6789"],
+ )
+ store.put(name="Viktor Novak", phones=["+49 151 9999 0000"])
+ return store
+
+
+async def test_seed_then_list_people(service, contacts):
+ report = await service.seed_identities(contact_store=contacts)
+ assert report["created"] == 2
+ assert report["merged"] == 0
+
+ people = await service.list_people()
+ assert {person["display_name"] for person in people} == {
+ "Viktoria Novak",
+ "Viktor Novak",
+ }
+ profile = await service.person_profile(people[0]["id"])
+ assert profile["id"] == people[0]["id"]
+ assert profile["identifiers"]
+
+ # A second pass changes nothing (idempotent by contract).
+ again = await service.seed_identities(contact_store=contacts)
+ assert again["created"] == 0
+ assert again["linked"] == 2
+
+
+async def test_queue_confirm_and_unmerge_through_the_service(service, contacts):
+ await service.seed_identities(contact_store=contacts)
+ queue = await service.identity_queue()
+ assert len(queue) == 1, "the two similar names must be PROPOSED, not merged"
+
+ confirmed = await service.confirm_identity_merge(queue[0]["id"])
+ assert confirmed["merge_id"] > 0
+ assert len(await service.list_people()) == 1
+ assert await service.identity_queue() == []
+
+ undone = await service.unmerge_identity(confirmed["merge_id"])
+ assert undone["status"] == "undone"
+ assert len(await service.list_people()) == 2
+
+ log = await service.identity_merge_log()
+ assert log[0]["id"] == confirmed["merge_id"]
+ assert log[0]["undone_at"] is not None
+
+
+async def test_rejecting_through_the_service_empties_the_queue(service, contacts):
+ await service.seed_identities(contact_store=contacts)
+ queue = await service.identity_queue()
+ result = await service.reject_identity_merge(queue[0]["id"])
+ assert result["status"] == "rejected"
+ assert await service.identity_queue() == []
+ assert len(await service.list_people()) == 2
+
+
+async def test_unknown_ids_fail_honestly(service):
+ assert await service.person_profile(4242) is None
+ with pytest.raises(IdentityError):
+ await service.confirm_identity_merge(4242)
+ with pytest.raises(IdentityError):
+ await service.unmerge_identity(4242)
diff --git a/tests/unit/ultrawiki/test_identity_store.py b/tests/unit/ultrawiki/test_identity_store.py
new file mode 100644
index 0000000000..d1907a5e97
--- /dev/null
+++ b/tests/unit/ultrawiki/test_identity_store.py
@@ -0,0 +1,487 @@
+"""The identity layer against a real (temporary) store — P5's gate.
+
+Everything here runs offline against a fresh SQLite file: no network, no
+credentials, no model. The centrepiece is :func:`test_golden_set_resolves_with_
+zero_wrong_merges`, which drives a deliberately nasty fixture set — the same
+person arriving three times in three formats, two different people who look
+alike, a nickname, and the speech-to-text near-name variants observed in the
+live vault — and then proves the two properties the design stands or falls on:
+
+1. every automatic merge was justified by a UNIQUE identifier, and
+2. every uncertain case is sitting in the confirmation queue instead.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.contacts.store import ContactStore
+from jarvis.ultrawiki.identity import (
+ EntityKind,
+ IdentifierKind,
+ IdentityError,
+ MatchTier,
+ QueueStatus,
+ ResolutionKind,
+)
+from jarvis.ultrawiki.identity_store import seed_from_contacts
+from jarvis.ultrawiki.store import PostgresStore, UltraStore
+
+
+async def store(tmp_path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ await instance.open()
+ yield instance
+ await instance.close()
+
+
+async def identifier_pairs(store: UltraStore, entity_id: int) -> set[tuple[str, str]]:
+ profile = await store.get_person(entity_id)
+ assert profile is not None
+ return {(item["kind"], item["value"]) for item in profile["identifiers"]}
+
+
+async def snapshot(store: UltraStore) -> list[tuple[str, set[tuple[str, str]]]]:
+ """Everything an unmerge has to restore: who exists and what they own."""
+ out = []
+ for person in await store.list_people(kind=None, limit=500):
+ out.append(
+ (person["display_name"], await identifier_pairs(store, person["id"]))
+ )
+ return sorted(out, key=lambda entry: entry[0])
+
+
+async def queue_pairs(store: UltraStore) -> set[frozenset[str]]:
+ return {
+ frozenset({entry["left"]["display_name"], entry["right"]["display_name"]})
+ for entry in await store.list_confirm_queue(limit=200)
+ }
+
+
+# ---------------------------------------------------------------------------
+# Schema
+# ---------------------------------------------------------------------------
+
+
+async def test_identity_migration_is_idempotent(tmp_path):
+ """Re-opening an existing store must be a no-op, including for a database
+ that was created before the identity tables existed."""
+ path = tmp_path / "ultrawiki.db"
+ first = UltraStore(path)
+ await first.open()
+ entity_id = await first.upsert_entity(display_name="Viktoria Novak")
+ await first.close()
+
+ second = UltraStore(path)
+ await second.open()
+ assert await second.get_entity(entity_id) is not None
+ assert (await second.identity_counts())["people"] == 1
+ await second.close()
+
+
+async def test_postgres_mirrors_the_identity_ddl():
+ """The two backends run the same logical schema (design doc 01)."""
+ ddl = "\n".join(PostgresStore.ddl_statements())
+ for table in ("uw_entities", "uw_identifiers", "uw_confirm_queue", "uw_merge_log"):
+ assert f"CREATE TABLE IF NOT EXISTS {table} (" in ddl
+ assert PostgresStore._IDENTITY_PARAM == "%s"
+ assert PostgresStore("postgresql://x")._id_sql("WHERE a = ? AND b = ?") == (
+ "WHERE a = %s AND b = %s"
+ )
+
+
+# ---------------------------------------------------------------------------
+# The golden set — P5's gate
+# ---------------------------------------------------------------------------
+
+
+async def test_golden_set_resolves_with_zero_wrong_merges(store):
+ same_person = [
+ # One person, three sources, three spellings and two phone formats.
+ {
+ "name": "Viktoria Novak",
+ "emails": ["[email protected]"],
+ "phones": ["+49 151 2345 6789"],
+ "contact_slug": "viktoria-novak",
+ },
+ {"name": "V. Novak", "emails": ["[email protected]"]},
+ {"name": "Novak, Viktoria", "phones": ["0049-151-23456789"]},
+ ]
+ distinct_people = [
+ # A brother: same surname, similar given name, own phone number.
+ {"name": "Viktor Novak", "phones": ["+49 151 9999 0000"]},
+ # A nickname with no other evidence at all.
+ {"name": "Viki"},
+ # Two people who merely share a surname.
+ {"name": "John Smith", "emails": ["[email protected]"]},
+ {"name": "Jane Smith", "emails": ["[email protected]"]},
+ ]
+
+ resolved = []
+ for observation in same_person:
+ resolved.append(await store.resolve_identity(**observation))
+ distinct_ids = []
+ for observation in distinct_people:
+ distinct_ids.append((await store.resolve_identity(**observation)).entity_id)
+
+ # 1 — the three views of one person collapsed onto ONE entity, and every
+ # collapse was deterministic.
+ assert {item.entity_id for item in resolved} == {resolved[0].entity_id}
+ assert resolved[0].kind is ResolutionKind.CREATED
+ assert resolved[1].kind is ResolutionKind.DETERMINISTIC
+ assert resolved[2].kind is ResolutionKind.DETERMINISTIC
+
+ # 2 — the four other people are four separate entities, none of them fused
+ # with anybody.
+ assert len(set(distinct_ids)) == 4
+ assert resolved[0].entity_id not in distinct_ids
+ assert len(await store.list_people(limit=100)) == 5
+
+ # 3 — NO merge was ever justified by anything but a unique identifier.
+ for entry in await store.list_merge_log(limit=100):
+ assert entry["tier"] == str(MatchTier.DETERMINISTIC)
+ assert entry["evidence"]
+ assert all(
+ item["kind"] in {"email", "phone", "contact"} for item in entry["evidence"]
+ )
+
+ # 4 — the uncertain cases are queued, and only those.
+ pairs = await queue_pairs(store)
+ assert frozenset({"Viktoria Novak", "Viktor Novak"}) in pairs
+ assert frozenset({"Viktoria Novak", "Viki"}) in pairs
+ assert frozenset({"John Smith", "Jane Smith"}) not in pairs
+
+
+async def test_speech_to_text_variants_queue_and_never_merge(store):
+ """The live vault's actual failure mode: one topic arrives as several
+ near-identical names. They must stay separate until a human says otherwise."""
+ variants = ["agentic-i", "gentic-ide", "Agentic IDE", "Ultra Wiki", "ultra-wiki"]
+ for name in variants:
+ await store.resolve_identity(name=name, kind=EntityKind.TOPIC)
+
+ assert await store.list_merge_log(limit=50) == []
+ assert len(await store.list_people(kind=EntityKind.TOPIC, limit=50)) == len(variants)
+ pairs = await queue_pairs(store)
+ assert frozenset({"agentic-i", "gentic-ide"}) in pairs
+ assert frozenset({"Ultra Wiki", "ultra-wiki"}) in pairs
+
+
+async def test_case_only_variant_anchors_instead_of_creating_a_twin(store):
+ """Identical after case folding is a LOOKUP, not a merge: nothing is
+ destroyed and no audit row is written."""
+ first = await store.resolve_identity(name="ultra-wiki", kind=EntityKind.TOPIC)
+ again = await store.resolve_identity(name="Ultra-Wiki", kind=EntityKind.TOPIC)
+ assert again.entity_id == first.entity_id
+ assert again.kind is ResolutionKind.NAME_ANCHOR
+ assert await store.list_merge_log(limit=10) == []
+
+
+async def test_ambiguous_name_links_to_nobody_and_proposes_instead(store):
+ """A name pointing at several live entities resolves to NONE of them —
+ guessing is how a personal memory quietly poisons itself."""
+ left = await store.resolve_identity(
+ name="Alex Winter", emails=["[email protected]"]
+ )
+ right = await store.resolve_identity(name="A. Winter", phones=["+49 151 7777 000"])
+ # The second identity legitimately acquires the same display name later.
+ await store.add_identifier(right.entity_id, IdentifierKind.NAME, "Alex Winter")
+
+ ambiguous = await store.resolve_identity(name="Alex Winter")
+ assert ambiguous.entity_id is None
+ assert ambiguous.kind is ResolutionKind.AMBIGUOUS
+ assert set(ambiguous.ambiguous) == {left.entity_id, right.entity_id}
+ assert await store.list_merge_log(limit=10) == []
+ assert len(await store.list_confirm_queue()) == 1
+
+
+async def test_create_false_never_writes_anything(store):
+ unresolved = await store.resolve_identity(name="Nobody Known", create=False)
+ assert unresolved.entity_id is None
+ assert unresolved.kind is ResolutionKind.UNRESOLVED
+ assert await store.list_people(limit=10) == []
+
+
+async def test_observation_without_a_name_is_not_given_one(store):
+ """An entity labelled after an e-mail must not carry that address as a
+ 'name' — every other address at the domain would look like a near-name."""
+ resolution = await store.resolve_identity(emails=["[email protected]"])
+ profile = await store.get_person(resolution.entity_id)
+ assert profile["names"] == []
+ assert profile["emails"] == ["[email protected]"]
+
+
+# ---------------------------------------------------------------------------
+# Merge, unmerge, and the durability of a decision
+# ---------------------------------------------------------------------------
+
+
+async def test_confirmed_merge_round_trips_through_unmerge(store):
+ left = await store.resolve_identity(
+ name="Chris Meyer", emails=["[email protected]"]
+ )
+ right = await store.resolve_identity(
+ name="Christoph Meyer", phones=["+49 151 0000 111"]
+ )
+ before = await snapshot(store)
+ proposal = (await store.list_confirm_queue())[0]
+
+ merge_id = await store.confirm_merge(proposal["id"])
+ assert merge_id > 0
+ assert len(await store.list_people(limit=10)) == 1
+ # A stale link to the merged-away id still lands on the survivor.
+ assert await store.resolve_entity_id(right.entity_id) == left.entity_id
+ survivor = await store.get_person(right.entity_id)
+ assert survivor["id"] == left.entity_id
+ assert survivor["requested_id"] == right.entity_id
+ assert ("phone", "+491510000111") in await identifier_pairs(store, left.entity_id)
+
+ assert await store.unmerge(merge_id) is True
+ assert await snapshot(store) == before
+ assert [entry["undone_at"] for entry in await store.list_merge_log(limit=10)] != [
+ None
+ ]
+
+
+async def test_unmerge_makes_the_split_stick_against_deterministic_evidence(store):
+ """Undoing a merge is a decision, not a suggestion. A later observation
+ carrying both identifiers must not silently fuse the pair again — a shared
+ mailbox or a family phone is exactly how that would keep happening."""
+ left = await store.resolve_identity(name="Sam Fox", emails=["[email protected]"])
+ right = await store.resolve_identity(name="Robin Fox", phones=["+49 151 1234 000"])
+ merge_id = await store.merge_entities(
+ left.entity_id, right.entity_id, tier=MatchTier.DETERMINISTIC
+ )
+ await store.unmerge(merge_id)
+
+ again = await store.resolve_identity(
+ name="Sam Fox", emails=["[email protected]"], phones=["+49 151 1234 000"]
+ )
+ assert again.merged == ()
+ assert len(await store.list_people(limit=10)) == 2
+ decided = await store.list_confirm_queue(status=QueueStatus.REJECTED)
+ assert len(decided) == 1
+
+
+async def test_rejecting_a_proposal_is_permanent(store):
+ await store.resolve_identity(name="agentic-i", kind=EntityKind.TOPIC)
+ await store.resolve_identity(name="gentic-ide", kind=EntityKind.TOPIC)
+ proposal = (await store.list_confirm_queue())[0]
+ assert await store.reject_merge(proposal["id"]) is True
+
+ assert await store.list_confirm_queue() == []
+ # Re-observing the same weak evidence must not ask a second time.
+ await store.resolve_identity(name="gentic-ides", kind=EntityKind.TOPIC)
+ reopened = [
+ entry
+ for entry in await store.list_confirm_queue()
+ if {entry["left"]["display_name"], entry["right"]["display_name"]}
+ == {"agentic-i", "gentic-ide"}
+ ]
+ assert reopened == []
+
+
+async def test_double_decisions_are_refused_honestly(store):
+ await store.resolve_identity(name="agentic-i", kind=EntityKind.TOPIC)
+ await store.resolve_identity(name="gentic-ide", kind=EntityKind.TOPIC)
+ proposal = (await store.list_confirm_queue())[0]
+ merge_id = await store.confirm_merge(proposal["id"])
+
+ with pytest.raises(IdentityError):
+ await store.confirm_merge(proposal["id"])
+ with pytest.raises(IdentityError):
+ await store.reject_merge(proposal["id"])
+ await store.unmerge(merge_id)
+ with pytest.raises(IdentityError):
+ await store.unmerge(merge_id)
+ with pytest.raises(IdentityError):
+ await store.unmerge(9999)
+
+
+async def test_merge_winner_is_deterministic_not_arbitrary(store):
+ """Re-running an import must converge on the same graph, so the survivor
+ is chosen by rule: a curated address-book record first, then the older id."""
+ inferred = await store.resolve_identity(name="Dana Reed", phones=["+49 151 5555 0"])
+ seeded = await store.resolve_identity(
+ name="D. Reed", emails=["[email protected]"], contact_slug="dana-reed"
+ )
+ await store.set_entity_source_ref(seeded.entity_id, "contacts:dana-reed")
+ assert seeded.entity_id != inferred.entity_id
+
+ # One later observation carries BOTH unique identifiers, so the two are
+ # provably one person — and the curated record is the survivor even though
+ # it is the younger row.
+ joined = await store.resolve_identity(
+ name="Dana Reed",
+ phones=["+49 151 5555 0"],
+ emails=["[email protected]"],
+ )
+ assert joined.merged
+ assert joined.entity_id == seeded.entity_id
+ assert await store.resolve_entity_id(inferred.entity_id) == seeded.entity_id
+
+
+async def test_merge_moves_identifiers_and_keeps_the_audit_trail(store):
+ left = await store.resolve_identity(name="Lee Park", emails=["[email protected]"])
+ right = await store.resolve_identity(name="Lee Parker", phones=["+49 151 4444 0"])
+ merge_id = await store.merge_entities(
+ left.entity_id,
+ right.entity_id,
+ tier=MatchTier.DETERMINISTIC,
+ reason="test merge",
+ )
+ entry = (await store.list_merge_log(entity_id=left.entity_id))[0]
+ assert entry["id"] == merge_id
+ assert entry["winner_id"] == left.entity_id
+ assert entry["loser_id"] == right.entity_id
+ assert entry["reason"] == "test merge"
+ assert entry["undone_at"] is None
+
+ profile = await store.get_person(left.entity_id)
+ assert {item["id"] for item in profile["merged_from"]} == {right.entity_id}
+ assert ("name", "lee parker") in await identifier_pairs(store, left.entity_id)
+
+
+async def test_merge_is_a_no_op_on_one_entity(store):
+ only = await store.resolve_identity(name="Solo Person")
+ assert await store.merge_entities(only.entity_id, only.entity_id) == 0
+
+
+# ---------------------------------------------------------------------------
+# Identifier attachment
+# ---------------------------------------------------------------------------
+
+
+async def test_shared_email_merges_but_shared_name_only_proposes(store):
+ first = await store.resolve_identity(name="Kim Alvarez")
+ second = await store.resolve_identity(name="Kim Alvarez Jr")
+
+ proposed = await store.add_identifier(
+ second.entity_id, IdentifierKind.NAME, "Kim Alvarez"
+ )
+ assert proposed.merged == ()
+ assert proposed.queued
+ assert len(await store.list_people(limit=10)) == 2
+
+ merged = await store.add_identifier(
+ second.entity_id, IdentifierKind.EMAIL, "[email protected]"
+ )
+ assert merged.merged == ()
+ merged_now = await store.add_identifier(
+ first.entity_id, IdentifierKind.EMAIL, "[email protected]"
+ )
+ assert merged_now.merged
+ assert len(await store.list_people(limit=10)) == 1
+
+
+async def test_unusable_identifiers_are_dropped_not_stored(store):
+ person = await store.resolve_identity(name="Robin Stone")
+ result = await store.add_identifier(person.entity_id, IdentifierKind.EMAIL, "junk")
+ assert result.identifier_id is None
+ assert ("email", "junk") not in await identifier_pairs(store, person.entity_id)
+ with pytest.raises(IdentityError):
+ await store.add_identifier(person.entity_id, "nonsense", "value")
+ with pytest.raises(IdentityError):
+ await store.add_identifier(9999, IdentifierKind.NAME, "Ghost")
+
+
+async def test_repeated_observation_of_one_person_is_idempotent(store):
+ payload = {
+ "name": "Nina Bauer",
+ "emails": ["[email protected]"],
+ "phones": ["+49 151 3333 0"],
+ }
+ first = await store.resolve_identity(**payload)
+ before = await identifier_pairs(store, first.entity_id)
+ for _ in range(3):
+ again = await store.resolve_identity(**payload)
+ assert again.entity_id == first.entity_id
+ assert again.created is False
+ assert await identifier_pairs(store, first.entity_id) == before
+ assert len(await store.list_people(limit=10)) == 1
+
+
+# ---------------------------------------------------------------------------
+# Contacts seeding
+# ---------------------------------------------------------------------------
+
+
+def build_contacts(tmp_path) -> ContactStore:
+ contacts = ContactStore(base_dir=tmp_path / "contacts")
+ contacts.put(
+ name="Viktoria Novak",
+ aliases=["Viki"],
+ emails=["[email protected]"],
+ phones=["+49 151 2345 6789"],
+ )
+ contacts.put(name="John Smith", emails=["[email protected]"])
+ contacts.put(name="No Contact Details")
+ return contacts
+
+
+async def test_seeding_from_contacts_is_idempotent(store, tmp_path):
+ contacts = build_contacts(tmp_path)
+
+ first = await seed_from_contacts(store, contact_store=contacts)
+ assert first.created == 3
+ assert first.linked == 0
+ assert first.merged == 0
+ people = await store.list_people(limit=10)
+ assert {person["display_name"] for person in people} == {
+ "Viktoria Novak",
+ "John Smith",
+ "No Contact Details",
+ }
+ assert all(person["source_ref"].startswith("contacts:") for person in people)
+
+ second = await seed_from_contacts(store, contact_store=contacts)
+ assert second.created == 0
+ assert second.linked == 3
+ assert second.identifiers_added == 0
+ assert len(await store.list_people(limit=10)) == 3
+
+
+async def test_seeding_merges_with_what_the_corpus_already_knew(store, tmp_path):
+ """A contact whose phone number already appeared during ingest joins that
+ entity deterministically instead of becoming a twin."""
+ ingested = await store.resolve_identity(
+ name="V. Novak", phones=["0049-151-23456789"]
+ )
+ contacts = build_contacts(tmp_path)
+
+ report = await seed_from_contacts(store, contact_store=contacts)
+ assert report.created == 2 # the third contact matched the ingested entity
+ assert report.linked == 1
+ profile = await store.get_person(ingested.entity_id)
+ assert "[email protected]" in profile["emails"]
+ assert profile["contacts"] == [contacts.list_all()[2].slug]
+ assert "viki" in [name.lower() for name in profile["names"]]
+
+
+async def test_seeded_alias_becomes_a_searchable_identifier(store, tmp_path):
+ await seed_from_contacts(store, contact_store=build_contacts(tmp_path))
+ found = await store.list_people(query="viki", limit=10)
+ assert [person["display_name"] for person in found] == ["Viktoria Novak"]
+
+
+async def test_people_list_filters_and_pages(store):
+ for name in ("Anna Lang", "Boris Lang", "Cleo Marsh"):
+ await store.resolve_identity(name=name)
+ assert len(await store.list_people(limit=2)) == 2
+ assert len(await store.list_people(limit=2, offset=2)) == 1
+ assert {person["display_name"] for person in await store.list_people(query="lang")} == {
+ "Anna Lang",
+ "Boris Lang",
+ }
+ assert await store.list_people(query="100%") == []
+
+
+async def test_counts_report_the_live_graph(store):
+ await store.resolve_identity(name="agentic-i", kind=EntityKind.TOPIC)
+ await store.resolve_identity(name="gentic-ide", kind=EntityKind.TOPIC)
+ await store.resolve_identity(name="Pat Nolan", emails=["[email protected]"])
+ counts = await store.identity_counts()
+ assert counts["entities"] == 3
+ assert counts["people"] == 1
+ assert counts["pending_confirmations"] == 1
+ assert counts["merges"] == 0