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): expose the identity layer as REST, CLI and voice commands

Ruben Lütke9ad9b126488e
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index d97bb0410a..19971fe591 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -161,6 +161,36 @@ Store one self-contained fact or summary through the guarded Wiki curator. The c
- **Desktop UI section:** `memory`
- **Voice example (EN):** "store that in my wiki"
+## `people-list` — List the people I know
+
+List the people the knowledge base has identified, newest evidence merged, optionally filtered by a name or an identifier (an e-mail address, a phone number). Use this to answer 'who do you know about' and to look up which stored person a spoken name refers to.
+
+- **Endpoint:** `GET /api/ultrawiki/identity/people`
+- **Arguments:** `q` (string; optional); `limit` (integer; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `memory`
+- **Voice example (EN):** "which people do you know about"
+
+## `person-profile` — Show what I know about one person
+
+Read one identified person in full: every known name, e-mail, phone and handle, which identities were merged into them, and which merge proposals are still open. Take the id from people-list; a merged-away id forwards to the surviving person.
+
+- **Endpoint:** `GET /api/ultrawiki/identity/people/{entity_id}`
+- **Arguments:** `entity_id` (integer; required)
+- **Requires confirmation:** no
+- **Desktop UI section:** `memory`
+- **Voice example (EN):** "what do you know about this person"
+
+## `identity-queue-list` — List possible duplicate people
+
+List the pairs the knowledge base suspects are the same person but refused to merge on its own, strongest evidence first. Nothing here has been merged — each pair waits for a human decision.
+
+- **Endpoint:** `GET /api/ultrawiki/identity/queue`
+- **Arguments:** `status` (one of: pending, confirmed, rejected, all; optional); `limit` (integer; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `memory`
+- **Voice example (EN):** "which people might be the same person"
+
## `session-latest-turn` — Show latest voice turn
Return the latest persisted user transcript and its complete voice turn, optionally restricted to one session.
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 149a57b1cc..0bfe41061d 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -459,6 +459,103 @@ def _build_registry() -> tuple[AppCommand, ...]:
"es": ("guarda eso en mi wiki",), # i18n-allow: input vocab
},
),
+ AppCommand(
+ id="people-list",
+ title="List the people I know",
+ description=(
+ "List the people the knowledge base has identified, newest "
+ "evidence merged, optionally filtered by a name or an "
+ "identifier (an e-mail address, a phone number). Use this to "
+ "answer 'who do you know about' and to look up which stored "
+ "person a spoken name refers to."
+ ),
+ method="GET",
+ path="/api/ultrawiki/identity/people",
+ params={
+ "type": "object",
+ "properties": {
+ "q": _str_param(
+ "Optional filter over display names and identifiers.",
+ max_length=200,
+ ),
+ "limit": {
+ "type": "integer",
+ "description": "Maximum people to return (1-1000).",
+ "minimum": 1,
+ "maximum": 1000,
+ },
+ },
+ },
+ ui_section="memory",
+ voice_aliases={
+ "de": ("welche personen kennst du",), # i18n-allow: input vocab
+ "en": ("which people do you know about",),
+ "es": ("qué personas conoces",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="person-profile",
+ title="Show what I know about one person",
+ description=(
+ "Read one identified person in full: every known name, e-mail, "
+ "phone and handle, which identities were merged into them, and "
+ "which merge proposals are still open. Take the id from "
+ "people-list; a merged-away id forwards to the surviving person."
+ ),
+ method="GET",
+ path="/api/ultrawiki/identity/people/{entity_id}",
+ params={
+ "type": "object",
+ "properties": {
+ "entity_id": {
+ "type": "integer",
+ "description": "Person id as returned by people-list.",
+ "minimum": 1,
+ },
+ },
+ "required": ["entity_id"],
+ },
+ path_params=("entity_id",),
+ ui_section="memory",
+ voice_aliases={
+ "de": ("was weißt du über diese person",), # i18n-allow: input vocab
+ "en": ("what do you know about this person",),
+ "es": ("qué sabes de esta persona",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="identity-queue-list",
+ title="List possible duplicate people",
+ description=(
+ "List the pairs the knowledge base suspects are the same "
+ "person but refused to merge on its own, strongest evidence "
+ "first. Nothing here has been merged — each pair waits for a "
+ "human decision."
+ ),
+ method="GET",
+ path="/api/ultrawiki/identity/queue",
+ params={
+ "type": "object",
+ "properties": {
+ "status": _str_param(
+ "Which proposals to list.",
+ enum=["pending", "confirmed", "rejected", "all"],
+ ),
+ "limit": {
+ "type": "integer",
+ "description": "Maximum proposals to return (1-1000).",
+ "minimum": 1,
+ "maximum": 1000,
+ },
+ },
+ },
+ ui_section="memory",
+ voice_aliases={
+ "de": ("welche personen könnten dieselbe sein",), # i18n-allow: input vocab
+ "en": ("which people might be the same person",),
+ "es": ("qué personas podrían ser la misma",), # i18n-allow: input vocab
+ },
+ ),
AppCommand(
id="session-latest-turn",
title="Show latest voice turn",
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index d694e5ee25..3a2acc365a 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -356,6 +356,7 @@ class WebServer:
from .tool_model_routes import router as tool_model_router
from .tools_routes import router as tools_router
from .ultrawiki_explore_routes import router as ultrawiki_explore_router
+ from .ultrawiki_identity_routes import router as ultrawiki_identity_router
from .ultrawiki_routes import router as ultrawiki_router
from .update_routes import router as update_router
from .wiki_routes import router as wiki_router
@@ -499,6 +500,9 @@ class WebServer:
# The readable Explore surface over the same store — separate module,
# same prefix and tag (see ultrawiki_explore_routes for why).
app.include_router(ultrawiki_explore_router)
+ # The identity surface over the same store — People, the merge
+ # confirmation queue, and the reversible merge audit trail.
+ app.include_router(ultrawiki_identity_router)
# ConnectionManager singleton for the global event stream. Attached
# to MissionBus.subscribe_all() in start().
app.state.missions_ws_manager = _MissionsConnMgr()
diff --git a/jarvis/ui/web/ultrawiki_identity_routes.py b/jarvis/ui/web/ultrawiki_identity_routes.py
new file mode 100644
index 0000000000..509275b90f
--- /dev/null
+++ b/jarvis/ui/web/ultrawiki_identity_routes.py
@@ -0,0 +1,309 @@
+"""UltraWiki identity REST surface — people, merge proposals, merge audit.
+
+The identity layer (``jarvis.ultrawiki.identity`` + ``identity_store``) decides
+which mentions across a corpus are the SAME person, place or project. It only
+ever merges on deterministic evidence (a shared e-mail, phone or contact slug);
+everything weaker becomes a proposal a human decides, and every merge stays
+reversible. These routes are what makes that decidable from outside the
+database: the People list, one person's profile, the confirmation queue, the
+two decisions, the undo, and the audit trail behind all of it.
+
+Own module rather than more lines in ``ultrawiki_routes.py`` (already past
+2200 lines and edited concurrently in this shared tree) — same prefix and same
+``ultrawiki`` tag, so the CLI-first contract still resolves every handler to
+``jarvis api ultrawiki <op>``. The mode gate and the store accessor are reused
+from the main module: one definition of "is UltraWiki answering right now".
+
+Everything is a thin shell over :class:`jarvis.ultrawiki.service.UltraWikiService`
+— no matching, ranking or merge logic lives here. Heavy imports stay inside the
+handlers (AP-26); nothing on this surface is on the voice hot path (AP-9) and
+no handler calls a model.
+
+Refusals: the store raises ``IdentityError`` when an OPERATION is impossible
+(unknown queue id, a merge already undone, an out-of-order unmerge). Those
+become 409 with the store's own sentence rather than a route-side 404/409
+split — re-deriving that classification here would be a second opinion on a
+question the store already answers, which is exactly the drift class CLAUDE.md
+§5 forbids.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request
+
+from jarvis.ui.web.ultrawiki_routes import _require_active, _store_of
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/ultrawiki", tags=["ultrawiki"])
+
+#: ``status=all`` on the queue means "every decision, not just the open ones".
+_QUEUE_ANY = "all"
+
+__all__ = ["router"]
+
+
+def _queue_status(raw: str) -> str | None:
+ """Validate a queue status filter; ``None`` means "every status".
+
+ Rejects an unknown value instead of silently listing everything: a typo in
+ a CLI filter that returns MORE rows than asked for is worse than an error.
+ """
+ from jarvis.ultrawiki.identity import QueueStatus # noqa: PLC0415 — lazy (AP-26)
+
+ wanted = str(raw or "").strip().lower()
+ if wanted in ("", _QUEUE_ANY):
+ return None
+ allowed = {str(member) for member in QueueStatus}
+ if wanted not in allowed:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown status {wanted!r} (one of: "
+ f"{', '.join(sorted(allowed))}, {_QUEUE_ANY})"
+ ),
+ )
+ return wanted
+
+
+def _refused(exc: Exception) -> HTTPException:
+ """Turn an identity refusal into a 409 that repeats the honest reason."""
+ return HTTPException(status_code=409, detail=str(exc))
+
+
+async def _identity_counts(service: Any) -> dict[str, int]:
+ """Honest counters for every list answer (index-only, no scan).
+
+ They travel with EVERY list, not just the empty ones: an empty People list
+ with ``entities: 0`` is "nothing was ever seeded", the same list with
+ ``entities: 40`` is "your filter matched nobody" — two different problems
+ that look identical without the counters.
+ """
+ try:
+ store = await _store_of(service)
+ return await store.identity_counts()
+ except Exception: # noqa: BLE001 — counters must never break a list answer
+ log.debug("identity counts unavailable", exc_info=True)
+ return {}
+
+
+# ---------------------------------------------------------------------------
+# People
+# ---------------------------------------------------------------------------
+
+
+ "/identity/people",
+ summary="List the people the knowledge base has identified",
+)
+async def list_people(
+ request: Request,
+ q: str = Query(
+ default="", description="Filter by display name or any identifier value"
+ ),
+ limit: int = Query(default=100, ge=1, le=1000),
+ offset: int = Query(default=0, ge=0),
+) -> dict[str, Any]:
+ """Live people, name-ordered, with how many identifiers each one carries.
+
+ "Live" excludes entities that were merged away: after a merge the loser is
+ a tombstone pointing at the survivor, and listing both would report two
+ people where the user decided there is one. Non-person entities (places,
+ orgs, projects, topics) are the Explore surface's job, not this one's.
+ """
+ service = _require_active(request)
+ people = await service.list_people(query=q.strip(), limit=limit, offset=offset)
+ return {
+ "ok": True,
+ "people": people,
+ "query": q.strip(),
+ "limit": limit,
+ "offset": offset,
+ "counts": await _identity_counts(service),
+ }
+
+
+ "/identity/people/{entity_id}",
+ summary="One person's identifiers, merge history and open proposals",
+)
+async def get_person(entity_id: int, request: Request) -> dict[str, Any]:
+ """Everything the identity layer holds about one entity.
+
+ A merged-away id is FORWARDED to the survivor rather than 404'd (the
+ answer reports the id that was asked for in ``requested_id``), so a link
+ saved before a merge keeps working instead of dead-ending.
+ """
+ service = _require_active(request)
+ profile = await service.person_profile(entity_id)
+ if profile is None:
+ raise HTTPException(status_code=404, detail=f"unknown entity {entity_id}")
+ return {
+ "ok": True,
+ "person": profile,
+ # True when the requested id was a tombstone and this is the survivor.
+ "forwarded": int(profile.get("id", entity_id)) != int(entity_id),
+ }
+
+
+ "/identity/seed",
+ summary="Seed people from the address book (idempotent, re-runnable)",
+ openapi_extra={
+ # Writes entities and can fuse existing ones on deterministic evidence.
+ # Idempotent and every merge is reversible, but it is a bulk write over
+ # the user's own address book, so it asks first.
+ "x-jarvis-dangerous": True
+ },
+)
+async def seed_identities(request: Request) -> dict[str, Any]:
+ """Import the user's contacts as identity entities; report what changed.
+
+ Safe to run again at any time: a contact resolves through its own contact
+ slug, so a second pass links instead of duplicating (``created: 0``). A
+ contact whose e-mail or phone already appeared in the corpus merges with
+ that entity deterministically instead of creating a twin.
+ """
+ service = _require_active(request)
+ report = await service.seed_identities()
+ return {"ok": True, "report": report, "counts": await _identity_counts(service)}
+
+
+# ---------------------------------------------------------------------------
+# The confirmation queue — everything the layer refused to decide alone
+# ---------------------------------------------------------------------------
+
+
+ "/identity/queue",
+ summary="Merge proposals waiting for a human decision",
+)
+async def list_identity_queue(
+ request: Request,
+ status: str = Query(
+ default="pending",
+ description="pending | confirmed | rejected | all",
+ ),
+ limit: int = Query(default=100, ge=1, le=1000),
+) -> dict[str, Any]:
+ """Pairs the layer thinks MIGHT be the same, strongest evidence first.
+
+ Nothing here was merged: a proposal is what the layer produces when the
+ evidence is a name similarity rather than a shared e-mail, phone or
+ contact. Rows whose two sides have meanwhile become one entity are skipped
+ — the queue self-heals instead of asking about a settled question.
+ """
+ service = _require_active(request)
+ wanted = _queue_status(status)
+ proposals = await service.identity_queue(status=wanted, limit=limit)
+ return {
+ "ok": True,
+ "proposals": proposals,
+ "status": wanted or _QUEUE_ANY,
+ "limit": limit,
+ "counts": await _identity_counts(service),
+ }
+
+
+ "/identity/queue/{queue_id}/confirm",
+ summary="Confirm one merge proposal — the two become one person",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def confirm_identity_merge(queue_id: int, request: Request) -> dict[str, Any]:
+ """Apply a proposal; returns the audit id that reverses it.
+
+ The answer's ``merge_id`` is the exact argument for the unmerge route, so
+ "confirmed the wrong pair" is one call away from undone. ``merge_id: 0``
+ means the pair had already become one entity by other evidence — the
+ proposal is closed, and there is nothing to reverse.
+ """
+ service = _require_active(request)
+ from jarvis.ultrawiki.identity import IdentityError # noqa: PLC0415 — lazy (AP-26)
+
+ try:
+ result = await service.confirm_identity_merge(queue_id)
+ except IdentityError as exc:
+ raise _refused(exc) from exc
+ return {"ok": True, **result}
+
+
+ "/identity/queue/{queue_id}/reject",
+ summary="Reject one merge proposal — they stay two different people",
+ openapi_extra={
+ # Permanent by design: a rejected pair is never proposed again, and the
+ # rejection outranks even later deterministic evidence. There is no
+ # un-reject, which makes this the least reversible identity action.
+ "x-jarvis-dangerous": True
+ },
+)
+async def reject_identity_merge(queue_id: int, request: Request) -> dict[str, Any]:
+ """Decline a proposal permanently — the pair is never proposed again."""
+ service = _require_active(request)
+ from jarvis.ultrawiki.identity import IdentityError # noqa: PLC0415 — lazy (AP-26)
+
+ try:
+ result = await service.reject_identity_merge(queue_id)
+ except IdentityError as exc:
+ raise _refused(exc) from exc
+ return {"ok": True, **result}
+
+
+# ---------------------------------------------------------------------------
+# The merge audit trail + the undo it exists for
+# ---------------------------------------------------------------------------
+
+
+ "/identity/merges",
+ summary="The merge audit trail — what was fused, on what evidence",
+)
+async def list_identity_merges(
+ request: Request,
+ entity_id: int | None = Query(
+ default=None, description="Only merges involving this entity"
+ ),
+ limit: int = Query(default=100, ge=1, le=1000),
+) -> dict[str, Any]:
+ """Every merge, newest first, with its tier, evidence and undo state.
+
+ The log outlives the entities it names (no foreign key by design), so a
+ purge cannot quietly erase the record of what was once fused.
+ """
+ service = _require_active(request)
+ merges = await service.identity_merge_log(entity_id=entity_id, limit=limit)
+ return {
+ "ok": True,
+ "merges": merges,
+ "entity_id": entity_id,
+ "limit": limit,
+ "counts": await _identity_counts(service),
+ }
+
+
+ "/identity/merges/{merge_id}/unmerge",
+ summary="Undo one merge — both identities come back exactly as they were",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def unmerge_identity(merge_id: int, request: Request) -> dict[str, Any]:
+ """Reverse one merge and make the split stick.
+
+ Identifiers go back where they came from, dropped duplicates are
+ re-created, and the pair is recorded as rejected — so the same evidence
+ cannot silently fuse them again on the next import. Merges undo in reverse
+ order: a merge shadowed by a later one is refused (409) naming the merge to
+ undo first, rather than half-restoring a chain.
+ """
+ service = _require_active(request)
+ from jarvis.ultrawiki.identity import IdentityError # noqa: PLC0415 — lazy (AP-26)
+
+ try:
+ result = await service.unmerge_identity(merge_id)
+ except IdentityError as exc:
+ raise _refused(exc) from exc
+ return {"ok": True, **result}
diff --git a/tests/unit/web/test_ultrawiki_identity_routes.py b/tests/unit/web/test_ultrawiki_identity_routes.py
new file mode 100644
index 0000000000..c04c8903ec
--- /dev/null
+++ b/tests/unit/web/test_ultrawiki_identity_routes.py
@@ -0,0 +1,389 @@
+"""Full-app tests for the /api/ultrawiki/identity REST surface.
+
+Pattern follows the Explore route tests: a real ``WebServer`` (so the mount,
+the OpenAPI metadata and the danger flags are the production ones) with a
+hand-wired ``UltraWikiService`` on ``app.state.ultrawiki``.
+
+Offline discipline: no embedding factory, no pipeline, no network. The address
+book is the REAL ``ContactStore`` pointed at a tmp directory through
+``LOCALAPPDATA`` — so the seed route exercises its production path (which
+constructs its own ``ContactStore``) instead of a stand-in that could drift
+from it.
+
+The interesting property under test is not the happy path but the CONTRACT the
+identity layer promises: similar names are PROPOSED and never merged, a
+confirmed merge is exactly reversible, and a decision that was already made
+fails loudly instead of silently succeeding twice.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+from jarvis.ultrawiki import service as uw_service_mod
+from jarvis.ultrawiki.service import UltraWikiService
+
+#: Identity routes that MUST carry the x-jarvis-dangerous OpenAPI extra.
+DANGEROUS_ROUTES = (
+ ("/api/ultrawiki/identity/seed", "post"),
+ ("/api/ultrawiki/identity/queue/{queue_id}/confirm", "post"),
+ ("/api/ultrawiki/identity/queue/{queue_id}/reject", "post"),
+ ("/api/ultrawiki/identity/merges/{merge_id}/unmerge", "post"),
+)
+
+
+def env(tmp_path: Path, monkeypatch):
+ toml_path = tmp_path / "jarvis.toml"
+ toml_path.write_text("", encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CONFIG", str(toml_path))
+ # user_data_dir() reads LOCALAPPDATA on every platform once it is set, so
+ # the real ContactStore the seed route builds lands under tmp — the test
+ # can never read (or write) the machine's actual address book.
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "appdata"))
+
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.memory.data_dir = str(tmp_path / "data")
+ cfg.ultrawiki.enabled = True
+
+ server = WebServer(cfg, bus=EventBus())
+ service = UltraWikiService(cfg, embedding_backend_factory=lambda: None)
+ server.app.state.ultrawiki = service
+ uw_service_mod.clear_jobs()
+ with TestClient(server.app) as client:
+ yield SimpleNamespace(
+ client=client, service=service, server=server, cfg=cfg, tmp=tmp_path
+ )
+ client.portal.call(service.shutdown)
+ uw_service_mod.clear_jobs()
+
+
+def address_book(env):
+ """Two contacts whose names are similar enough to be PROPOSED, not merged.
+
+ "Viktoria Novak" and "Viktor Novak" share no e-mail, phone or contact slug,
+ so the layer has nothing deterministic to merge on — exactly the case the
+ confirmation queue exists for.
+ """
+ from jarvis.contacts.store import ContactStore
+
+ store = ContactStore()
+ 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
+
+
+def seed(env) -> dict:
+ response = env.client.post("/api/ultrawiki/identity/seed")
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def people(env, **params) -> list[dict]:
+ response = env.client.get("/api/ultrawiki/identity/people", params=params)
+ assert response.status_code == 200, response.text
+ return response.json()["people"]
+
+
+def queue(env, **params) -> list[dict]:
+ response = env.client.get("/api/ultrawiki/identity/queue", params=params)
+ assert response.status_code == 200, response.text
+ return response.json()["proposals"]
+
+
+# ---------------------------------------------------------------------------
+# Seeding + the People list
+# ---------------------------------------------------------------------------
+
+
+def test_seeding_fills_the_people_list_and_repeats_harmlessly(env, address_book):
+ body = seed(env)
+
+ assert body["report"]["created"] == 2
+ assert body["report"]["merged"] == 0
+ assert {person["display_name"] for person in people(env)} == {
+ "Viktoria Novak",
+ "Viktor Novak",
+ }
+
+ again = seed(env)
+
+ # Idempotent by contract: a second pass links what exists, creates nothing.
+ assert again["report"]["created"] == 0
+ assert again["report"]["linked"] == 2
+ assert len(people(env)) == 2
+
+
+def test_people_can_be_filtered_by_name_or_by_identifier(env, address_book):
+ seed(env)
+
+ by_name = people(env, q="viktoria")
+ by_email = people(env, q="[email protected]")
+ by_phone = people(env, q="9999")
+
+ assert [p["display_name"] for p in by_name] == ["Viktoria Novak"]
+ assert [p["display_name"] for p in by_email] == ["Viktoria Novak"]
+ assert [p["display_name"] for p in by_phone] == ["Viktor Novak"]
+
+
+def test_every_list_carries_the_counters_that_explain_an_empty_one(env, address_book):
+ empty = env.client.get("/api/ultrawiki/identity/people").json()
+
+ # Nothing seeded yet: the counters say so instead of leaving an empty list
+ # indistinguishable from "your filter matched nobody".
+ assert empty["people"] == []
+ assert empty["counts"]["people"] == 0
+
+ seed(env)
+ filtered = env.client.get(
+ "/api/ultrawiki/identity/people", params={"q": "nobody-by-this-name"}
+ ).json()
+
+ assert filtered["people"] == []
+ assert filtered["counts"]["people"] == 2
+ assert filtered["counts"]["pending_confirmations"] == 1
+
+
+def test_person_profile_carries_every_identifier_and_the_open_proposal(
+ env, address_book
+):
+ seed(env)
+ viktoria = next(p for p in people(env) if p["display_name"] == "Viktoria Novak")
+
+ response = env.client.get(f"/api/ultrawiki/identity/people/{viktoria['id']}")
+
+ assert response.status_code == 200, response.text
+ profile = response.json()["person"]
+ assert response.json()["forwarded"] is False
+ assert profile["emails"] == ["[email protected]"]
+ assert profile["phones"] == ["+4915123456789"]
+ assert "Viki" in profile["names"]
+ assert len(profile["pending_proposals"]) == 1
+
+
+def test_unknown_person_is_a_404_not_an_empty_profile(env, address_book):
+ seed(env)
+
+ assert env.client.get("/api/ultrawiki/identity/people/424242").status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# The confirmation queue
+# ---------------------------------------------------------------------------
+
+
+def test_similar_names_are_proposed_and_never_merged_on_their_own(env, address_book):
+ seed(env)
+
+ proposals = queue(env)
+
+ assert len(proposals) == 1
+ assert {proposals[0]["left"]["display_name"], proposals[0]["right"]["display_name"]} == {
+ "Viktoria Novak",
+ "Viktor Novak",
+ }
+ assert proposals[0]["status"] == "pending"
+ # Proposed is not merged: both people are still their own entity, and the
+ # audit trail is empty because nothing was fused.
+ assert len(people(env)) == 2
+ assert env.client.get("/api/ultrawiki/identity/merges").json()["merges"] == []
+
+
+def test_an_unknown_queue_status_is_refused_rather_than_widened(env, address_book):
+ seed(env)
+
+ response = env.client.get(
+ "/api/ultrawiki/identity/queue", params={"status": "maybe"}
+ )
+
+ assert response.status_code == 400
+ assert "maybe" in response.json()["detail"]
+
+
+def test_status_all_lists_decided_proposals_too(env, address_book):
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+
+ rejected = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/reject"
+ )
+
+ assert rejected.status_code == 200, rejected.text
+ assert rejected.json()["status"] == "rejected"
+ assert queue(env) == []
+ assert [p["status"] for p in queue(env, status="all")] == ["rejected"]
+ # Rejecting keeps them apart — it never merges anything.
+ assert len(people(env)) == 2
+
+
+# ---------------------------------------------------------------------------
+# Confirm → merge → unmerge, the reversibility contract
+# ---------------------------------------------------------------------------
+
+
+def test_confirmed_merge_round_trips_through_unmerge(env, address_book):
+ seed(env)
+ before = {p["id"]: p["display_name"] for p in people(env)}
+ proposal_id = queue(env)[0]["id"]
+
+ confirmed = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/confirm"
+ )
+
+ assert confirmed.status_code == 200, confirmed.text
+ merge_id = confirmed.json()["merge_id"]
+ assert merge_id > 0
+ assert len(people(env)) == 1
+ assert queue(env) == []
+
+ merges = env.client.get("/api/ultrawiki/identity/merges").json()["merges"]
+ assert [m["id"] for m in merges] == [merge_id]
+ assert merges[0]["undone_at"] is None
+
+ undone = env.client.post(f"/api/ultrawiki/identity/merges/{merge_id}/unmerge")
+
+ assert undone.status_code == 200, undone.text
+ assert undone.json()["status"] == "undone"
+ assert {p["id"]: p["display_name"] for p in people(env)} == before
+ assert env.client.get("/api/ultrawiki/identity/merges").json()["merges"][0][
+ "undone_at"
+ ]
+
+
+def test_a_merged_away_id_forwards_instead_of_dead_ending(env, address_book):
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+ confirmed = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/confirm"
+ ).json()
+ survivor = people(env)[0]["id"]
+ merges = env.client.get("/api/ultrawiki/identity/merges").json()["merges"]
+ loser = next(m["loser_id"] for m in merges if m["id"] == confirmed["merge_id"])
+
+ response = env.client.get(f"/api/ultrawiki/identity/people/{loser}")
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["forwarded"] is True
+ assert body["person"]["id"] == survivor
+ assert body["person"]["requested_id"] == loser
+
+
+def test_merges_can_be_scoped_to_one_person(env, address_book):
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+ merge_id = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/confirm"
+ ).json()["merge_id"]
+ survivor = people(env)[0]["id"]
+
+ scoped = env.client.get(
+ "/api/ultrawiki/identity/merges", params={"entity_id": survivor}
+ ).json()
+ unrelated = env.client.get(
+ "/api/ultrawiki/identity/merges", params={"entity_id": 999_999}
+ ).json()
+
+ assert [m["id"] for m in scoped["merges"]] == [merge_id]
+ assert unrelated["merges"] == []
+
+
+# ---------------------------------------------------------------------------
+# Refusals — a decision already made must fail loudly, not silently repeat
+# ---------------------------------------------------------------------------
+
+
+def test_deciding_twice_is_a_409_with_the_honest_reason(env, address_book):
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+ env.client.post(f"/api/ultrawiki/identity/queue/{proposal_id}/confirm")
+
+ again = env.client.post(f"/api/ultrawiki/identity/queue/{proposal_id}/confirm")
+ rejecting_an_applied_one = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/reject"
+ )
+
+ assert again.status_code == 409
+ assert "already" in again.json()["detail"]
+ assert rejecting_an_applied_one.status_code == 409
+
+
+def test_undoing_an_unknown_or_already_undone_merge_is_a_409(env, address_book):
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+ merge_id = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/confirm"
+ ).json()["merge_id"]
+ env.client.post(f"/api/ultrawiki/identity/merges/{merge_id}/unmerge")
+
+ again = env.client.post(f"/api/ultrawiki/identity/merges/{merge_id}/unmerge")
+ unknown = env.client.post("/api/ultrawiki/identity/merges/424242/unmerge")
+
+ assert again.status_code == 409
+ assert unknown.status_code == 409
+ assert "424242" in unknown.json()["detail"]
+
+
+def test_unmerging_makes_the_split_stick(env, address_book):
+ """The pair must not be re-proposed by the same evidence after an undo."""
+ seed(env)
+ proposal_id = queue(env)[0]["id"]
+ merge_id = env.client.post(
+ f"/api/ultrawiki/identity/queue/{proposal_id}/confirm"
+ ).json()["merge_id"]
+ env.client.post(f"/api/ultrawiki/identity/merges/{merge_id}/unmerge")
+
+ seed(env) # re-running the import must not fuse them again
+
+ assert len(people(env)) == 2
+ assert queue(env) == []
+
+
+# ---------------------------------------------------------------------------
+# Contract metadata + mode discipline
+# ---------------------------------------------------------------------------
+
+
+def test_destructive_identity_routes_declare_the_danger_flag(env):
+ schema = env.server.app.openapi()
+
+ for path, method in DANGEROUS_ROUTES:
+ operation = schema["paths"][path][method]
+ assert operation.get("x-jarvis-dangerous") is True, f"{method} {path}"
+
+
+def test_identity_routes_are_tagged_for_the_cli(env):
+ schema = env.server.app.openapi()
+
+ for path in (
+ "/api/ultrawiki/identity/people",
+ "/api/ultrawiki/identity/queue",
+ "/api/ultrawiki/identity/merges",
+ ):
+ assert schema["paths"][path]["get"]["tags"] == ["ultrawiki"]
+
+
+def test_identity_answers_409_while_ultra_mode_is_off(env):
+ env.cfg.ultrawiki.enabled = False
+
+ for path in (
+ "/api/ultrawiki/identity/people",
+ "/api/ultrawiki/identity/queue",
+ "/api/ultrawiki/identity/merges",
+ ):
+ assert env.client.get(path).status_code == 409, path
+ assert env.client.post("/api/ultrawiki/identity/seed").status_code == 409