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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): episodic events with absolute time anchoring
Ruben Lütke7b6f4a8be0a0
diff --git a/UltraWiki/01-architecture.md b/UltraWiki/01-architecture.mdindex 571b9d1bbc..581be91b6c 100644--- a/UltraWiki/01-architecture.md+++ b/UltraWiki/01-architecture.md@@ -101,6 +101,25 @@ Column lists are indicative, not final DDL.are always absolute (relative expressions are resolved against the sourceitem's own timestamp at extraction time — "next Friday" is never stored astext).+ **Shipped (2026-07-28, `migrations/0004_events.sql`).** Three properties+ worth stating because they are load-bearing rather than incidental:+ - **Bi-temporal.** `occurred_at`/`occurred_end` are VALID time (when it+ happened); `recorded_at` is TRANSACTION time (when the source recorded the+ statement). A Monday message about a Friday dinner answers both "when was+ it" and "when did I plan it". `occurred_end` is always filled — from+ `occurred_precision` when the source gave no end — so a month-precision+ event still matches a query about one day inside it.+ - **No new model call.** Events ride the per-document distillation that+ already runs: prompt version 2 emits an `events` array in the SAME call.+ The model normalizes LANGUAGE (a relative expression in any language+ becomes one token of a closed English vocabulary); the deterministic+ resolver in `jarvis/ultrawiki/events.py` does the arithmetic. A corpus+ distilled under version 1 still yields events wherever its stored+ distillation states an absolute date, without being re-distilled.+ - **`time_anchor` is the honesty column** (`absolute` / `relative` /+ `recorded`): an event anchored merely on the item's own timestamp is worth+ far less than one whose source spelled the date out, and a surface that+ cannot tell them apart will state a guess as a fact.- **`uw_areas`** — named source bundles (D-12): `id, name, icon, is_default`.A source belongs to one or more areas; items inherit their source's areas atingest time so scoping is a cheap indexed filter, not a join cascade.diff --git a/UltraWiki/03-retrieval-and-voice.md b/UltraWiki/03-retrieval-and-voice.mdindex 64f2857996..c09d5cde5c 100644--- a/UltraWiki/03-retrieval-and-voice.md+++ b/UltraWiki/03-retrieval-and-voice.md@@ -120,6 +120,28 @@ event**, and the synthesis stage merely verbalizes it with its citations.Vector search over documents is the safety net for whatever extraction didnot anticipate, not the primary episodic path.+**Shipped (2026-07-28): the event leg.** Events reach the read path as a+THIRD ranked list beside keyword and vector — its own keyword index over a+stored card that carries the absolute date in several written forms, the+place and the participants (FTS5 on SQLite, a generated `tsvector` on+Postgres). Consequences:++- It is fused, never privileged: `[ultrawiki].rrf_event_weight` (default 1.0,+ `0` silences the leg) enters the same RRF sum as every other list, so a+ precomputed event still has to win on consensus (principle 5). What the leg+ DOES get is the representative slot when an event and its evidence item+ merge — an event card states the date, the place and who was there, which+ is the better citation for an episodic question than a fragment of chat.+- Event hits are ranked and age-decayed by the event's own `occurred_at`, not+ by when the message that mentioned it was written.+- The leg is optional in the strict sense: a store without the episodic+ tables (a third-party backend, a corpus that predates them) returns nothing+ and every other leg answers unchanged.+- `events_between` ships as the design's primitive+ (`GET /api/ultrawiki/events`, `GET /api/ultrawiki/events/{id}`, and+ therefore `jarvis api ultrawiki list-events` / `get-event`) — cheap,+ LLM-free, narrow in and out.+## Voice from day one (D-8): the latency budgetThe realtime voice pipeline queries UltraWiki in v1. Budget to first spokendiff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 7c7174fea8..6c5ba78f5d 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2227,6 +2227,17 @@ class UltraWikiConfig(BaseModel):# the article's default; 0 silences a leg without removing it.rrf_keyword_weight: float = 1.0rrf_vector_weight: float = 1.0+ # The episodic-event leg (jarvis/ultrawiki/events.py). Events are+ # precomputed answers to "when did X happen", so they are weighted like+ # any other list rather than allowed to veto one: consensus still decides+ # (design doc 01, principle 5). 0 silences the leg.+ rrf_event_weight: float = 1.0++ # -- episodic events (design doc 01, uw_events) --------------------------+ # Derive events from the distillation that already ran. Costs no extra+ # model call and nothing on the read path; false stops the derivation and+ # leaves existing rows untouched.+ events_enabled: bool = True# Age decay on the fused score: 0.5 ** (age_days / half_life). Stale# answers lose when relevance is otherwise equal. 0 disables the decay# (the epsilon-sized recency tiebreak still settles exact ties).diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex ff7b10f328..1fbb5b8ee8 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -60,6 +60,7 @@ _RANKING_KEYS = ("rerank_min_score","rrf_keyword_weight","rrf_vector_weight",+ "rrf_event_weight","recency_half_life_days",)@@ -68,6 +69,7 @@ _RANKING_BOUNDS: dict[str, tuple[float, float]] = {"rerank_min_score": (0.0, 10.0), # the shared 0-10 relevance scale"rrf_keyword_weight": (0.0, 10.0),"rrf_vector_weight": (0.0, 10.0),+ "rrf_event_weight": (0.0, 10.0),"recency_half_life_days": (0.0, 36500.0), # a century is "effectively off"}@@ -1119,6 +1121,9 @@ class UpdateSettingsBody(BaseModel):rerank_min_score: float | None = Nonerrf_keyword_weight: float | None = Nonerrf_vector_weight: float | None = None+ #: Weight of the episodic-event leg (design doc 01, uw_events). 0 silences+ #: it without removing the stored events.+ rrf_event_weight: float | None = Nonerecency_half_life_days: float | None = Noneconfirm_reembed: bool = False@@ -2175,6 +2180,83 @@ async def get_platform_export(platform_id: str) -> dict[str, Any]:return platform_guide.as_dict(entry)+# ---------------------------------------------------------------------------+# Episodic events (design doc 01 · uw_events)+# ---------------------------------------------------------------------------+++def _event_kind_or_400(raw: str) -> str | None:+ """Validate an event-kind filter against the canonical enum, or 400."""+ wanted = (raw or "").strip()+ if not wanted:+ return None+ from jarvis.ultrawiki.events import EventKind # noqa: PLC0415 — lazy (AP-26)++ known = {member.value for member in EventKind}+ if wanted not in known:+ raise HTTPException(+ status_code=400,+ detail=(+ f"unknown event kind {wanted!r} (one of: "+ f"{', '.join(sorted(known))})"+ ),+ )+ return wanted++[email protected]("/events", summary="List episodic events with their absolute dates")+async def list_events(+ request: Request,+ since: str = Query(+ default="",+ description="ISO-8601 lower bound on when the event HAPPENED (valid time)",+ ),+ until: str = Query(+ default="", description="ISO-8601 upper bound on when the event happened"+ ),+ kind: str = Query(+ default="",+ description="Only events of this kind (meal, travel, meeting, purchase, milestone, other)",+ ),+ entity_id: int | None = Query(+ default=None, description="Only events this person/place took part in"+ ),+ limit: int = Query(default=50, ge=1, le=200),+ offset: int = Query(default=0, ge=0),+) -> dict[str, Any]:+ """What happened, when, where and with whom — newest first.++ The window bounds VALID time (when it happened), never the recorded time,+ and matches by overlap: an event the source only pinned down to a month is+ returned for a question about a day inside it. Every row carries an+ absolute ``occurred_at`` plus ``time_anchor``, which says whether the+ source stated that date, whether it was resolved from a relative+ expression, or whether it is merely the moment the item was recorded.+ """+ service = _service(request)+ store = await _store_of(service)+ rows = await store.list_events(+ since=since.strip() or None,+ until=until.strip() or None,+ kind=_event_kind_or_400(kind),+ entity_id=entity_id,+ limit=limit,+ offset=offset,+ )+ return {"events": rows, "total": len(rows), "limit": limit, "offset": offset}++[email protected]("/events/{event_id}", summary="Read one episodic event in full")+async def get_event(event_id: int, request: Request) -> dict[str, Any]:+ """One event with its participants, place and evidence permalink."""+ service = _service(request)+ store = await _store_of(service)+ event = await store.get_event(event_id)+ if event is None:+ raise HTTPException(status_code=404, detail=f"unknown event {event_id}")+ return event++# ---------------------------------------------------------------------------# Search# ---------------------------------------------------------------------------diff --git a/jarvis/ultrawiki/distill.py b/jarvis/ultrawiki/distill.pyindex aa0e84022b..031492243f 100644--- a/jarvis/ultrawiki/distill.py+++ b/jarvis/ultrawiki/distill.py@@ -17,6 +17,28 @@ Caching contract (design doc 02, determinism economics): results are cached on``(content_hash, PROMPT_VERSION, model)``. Bump :data:`PROMPT_VERSION` on ANYprompt change so improved prompts re-enrich incrementally instead of servingstale cached distillations.++**Version 2 — episodic events.** The document now also carries an ``events``+array (design doc 01, ``uw_events``). It rides the SAME call: extracting+events costs no extra round trip, no extra model, and nothing on the read+path. Two rules make that array safe to consume:++- ``when`` is either ISO-8601 (whenever the source states a date outright) or+ ONE token from a closed English relative vocabulary+ (:data:`jarvis.ultrawiki.events.RELATIVE_VOCABULARY`). The model therefore+ does the LANGUAGE normalization — a German or Spanish source arrives already+ translated — while ``jarvis/ultrawiki/events.py`` does the arithmetic that+ turns the token into an absolute instant. No per-language phrase table, so+ the feature works for every locale rather than the two somebody tested.+- The model never computes a date. Asking an LLM to add five days to a+ timestamp is asking for a wrong answer that looks right; the resolver+ anchors every relative expression against the item's own timestamp.++The bump invalidates every cached distillation, so a corpus re-distills+incrementally in the background at the cheap router tier. Nothing is lost+meanwhile: items keep their existing summary document until the new one+lands, and events are also derived from PRE-v2 distillations wherever they+state an absolute date (``events.derive_events``'s legacy path)."""from __future__ import annotations@@ -49,7 +71,9 @@ __all__ = []#: Part of the distillation cache key — bump on EVERY prompt change.-PROMPT_VERSION = 1+#: 1 = question/summary/resolution/entities/refs.+#: 2 = + the ``events`` array (episodic facts, same call).+PROMPT_VERSION = 2#: Raw bodies are truncated before prompting; a distillation summarizes, it#: does not need six-figure transcripts, and the marker keeps the cut honest.@@ -84,6 +108,11 @@ class DistillResult:resolution: str = ""entities: list[str] = field(default_factory=list)refs: list[str] = field(default_factory=list)+ #: Episodic facts (prompt version 2). Raw payload dicts, deliberately NOT+ #: parsed here: turning ``when`` into an absolute instant needs the item's+ #: own timestamp, which the distiller does not have and must not guess.+ #: ``jarvis.ultrawiki.events.derive_events`` owns that step.+ events: list[dict[str, Any]] = field(default_factory=list)raw_json: str = "" # the JSON exactly as the provider produced it@@ -93,6 +122,19 @@ def _truncate_body(body: str) -> str:return body[:_BODY_TRUNCATE_CHARS] + _TRUNCATION_MARKER+#: The closed relative vocabulary the prompt is allowed to emit, spelled out+#: for the model. It MUST stay in sync with+#: ``jarvis.ultrawiki.events.RELATIVE_VOCABULARY`` — a token invented here+#: resolves to nothing and the event silently falls back to the item's own+#: timestamp. ``tests/unit/ultrawiki/test_events.py`` pins the pair together.+_RELATIVE_TOKENS = (+ "today|yesterday|tomorrow|this <weekday>|last <weekday>|next <weekday>|"+ "last week|next week|last month|next month|last year|next year|"+ "<n> days ago|<n> weeks ago|<n> months ago|<n> years ago|"+ "in <n> days|in <n> weeks|in <n> months|in <n> years"+)++def build_distill_prompt(*, title: str, body: str, source_kind: str) -> str:"""The normalized user prompt: XML-tagged sections, strict-JSON contract."""return (@@ -110,11 +152,34 @@ def build_distill_prompt(*, title: str, body: str, source_kind: str) -> str:'ask it","summary":"a 2-4 sentence factual summary","resolution":"the ''outcome, decision, or answer; empty string if none","entities":''["mentioned people, places, organizations, projects, systems"],'- '"refs":["explicit references to other documents, URLs, or ids"]}\n'- "Rules: no markdown fences; no additional keys; entities and refs are\n"- "arrays of short strings; use empty values where the item provides\n"- "nothing; never invent facts.\n"- "</output_format>"+ '"refs":["explicit references to other documents, URLs, or ids"],'+ '"events":[{"kind":"meal|travel|meeting|purchase|milestone|other",'+ '"title":"short name of what happened","when":"see the time rules",'+ '"when_end":"same format, empty unless the item states an end",'+ '"where":"place name, empty if none","participants":["people who were '+ 'there"],"confidence":0.0}]}\n'+ "Rules: no markdown fences; no additional keys; entities, refs and\n"+ "participants are arrays of short strings; use empty values where the\n"+ "item provides nothing; never invent facts.\n"+ "</output_format>\n"+ "<event_rules>\n"+ "An event is something that HAPPENED or is scheduled to happen at a\n"+ "point in time: a meal, a trip, a meeting, a purchase, a milestone.\n"+ 'Return "events":[] when the item records none — most items record\n'+ "none, and an invented event poisons the memory permanently.\n"+ "Time format for when / when_end, in this order of preference:\n"+ "1. The item states an absolute date or time: return ISO-8601\n"+ ' ("2026-03-14", "2026-03-14T19:30", "2026-03" for a whole month,\n'+ ' "2026" for a whole year). Never shift or reformat the date.\n'+ "2. The item uses a relative expression, in ANY language: translate it\n"+ " to EXACTLY ONE of these English tokens, optionally followed by\n"+ f' " at HH:MM" or a daypart word:\n {_RELATIVE_TOKENS}\n'+ "3. Neither applies: return an empty string.\n"+ "NEVER compute a date yourself and never guess a year: the system\n"+ "resolves relative tokens against the item's own timestamp.\n"+ "confidence is 0.0-1.0: how sure you are the event really happened as\n"+ "described.\n"+ "</event_rules>")@@ -174,6 +239,19 @@ def _string_list(value: Any) -> list[str]:return []+def _event_list(value: Any) -> list[dict[str, Any]]:+ """Salvage the ``events`` array into ``list[dict]``; junk entries drop.++ Deliberately structure-only: no field is validated or resolved here.+ ``events.derive_events`` is the single place that decides what a payload+ means, so a provider quirk cannot produce two different interpretations+ depending on which layer looked at it first.+ """+ if not isinstance(value, (list, tuple)):+ return []+ return [dict(entry) for entry in value if isinstance(entry, dict)]++def _result_from(raw_json: str, parsed: dict[str, Any]) -> DistillResult:"""Salvage whatever keys arrived; missing keys become empty values."""return DistillResult(@@ -182,6 +260,7 @@ def _result_from(raw_json: str, parsed: dict[str, Any]) -> DistillResult:resolution=str(parsed.get("resolution") or "").strip(),entities=_string_list(parsed.get("entities")),refs=_string_list(parsed.get("refs")),+ events=_event_list(parsed.get("events")),raw_json=raw_json,)@@ -258,7 +337,10 @@ async def distill_text(),system=_SYSTEM_PROMPT,temperature=0.1, # normalization, not creativity- max_tokens=1600,+ # Raised with prompt version 2: the events array shares this budget,+ # and a truncated JSON object is an unparseable one — the whole+ # distillation would be retried for the sake of a few tokens.+ max_tokens=2000,stream=True,)diff --git a/jarvis/ultrawiki/event_store.py b/jarvis/ultrawiki/event_store.pynew file mode 100644index 0000000000..98a7d3659b--- /dev/null+++ b/jarvis/ultrawiki/event_store.py@@ -0,0 +1,546 @@+"""The SQL half of UltraWiki episodic events (design doc 01 · ``uw_events``).++:class:`EventMixin` is inherited by BOTH store backends, so the event rules+exist exactly once. Like :class:`~jarvis.ultrawiki.identity_store.IdentityMixin`+it relies only on the small surface both backends already provide — ``_txn()``,+``_fetchall()``, ``_fetchone()``, ``_ensure_open()``, ``_id_sql()`` and the+``_id_insert()`` dialect hook — plus one further hook of its own,+:attr:`EventMixin._EVENT_DIALECT`, because the keyword index is the one thing+the two engines genuinely cannot express the same way (FTS5 virtual table vs a+generated ``tsvector`` column).++The contract this module keeps:++- **Re-derivation is idempotent.** :meth:`replace_events` replaces an item's+ whole event set inside one transaction, keyed by+ :attr:`~jarvis.ultrawiki.events.DerivedEvent.dedupe_key`, so a second+ pipeline pass over unchanged content changes nothing.+- **Events die with their evidence.** ``item_id`` cascades, and a content+ CHANGE purges them alongside the stale documents and FTS rows — an event+ derived from a sentence that no longer exists must not keep answering.+- **Participants link through the identity layer, never around it.** Names are+ resolved with :meth:`IdentityMixin.resolve_identity`, which merges only on+ deterministic evidence and otherwise proposes; an unresolvable participant+ keeps its spelling and stays searchable rather than being dropped.+- **The keyword card is stored, not recomputed.** ``search_text`` lives on the+ row, so both dialects index the identical text and a search cannot depend+ on which engine answered.++Nothing here calls a model or touches the network; derivation runs on the+write path inside the distillation stage that produced its input (AP-9/AP-26).+"""++from __future__ import annotations++import json+import logging+import re+from collections.abc import Sequence+from datetime import UTC, datetime+from typing import Any++from jarvis.ultrawiki.events import (+ EVENT_VERSION,+ DerivedEvent,+ EventKind,+ TimePrecision,+ format_occurred,+)+from jarvis.ultrawiki.types import SearchResult++log = logging.getLogger(__name__)++__all__ = ["EventMixin"]++#: Pool size of the event keyword leg before fusion; the same order of+#: magnitude as the item legs so no leg can dominate the RRF purely by+#: returning more rows.+EVENT_LEG_POOL = 30++_FTS_QUOTE_STRIP_RE = re.compile(r'["\']')++#: Cap on the stored card, so one pathological event cannot bloat the index.+_MAX_CARD_CHARS = 2000+++def _utc_now_iso() -> str:+ return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")+++def _match_expr(query: str) -> str:+ """OR-combined quoted tokens; quoting neutralizes FTS5 operators.++ Mirrors ``store._fts_match_expr``; duplicated deliberately rather than+ imported, because ``store`` imports this module and the cycle would make+ both unimportable.+ """+ tokens = [_FTS_QUOTE_STRIP_RE.sub("", tok) for tok in str(query or "").split() if tok.strip()]+ return " OR ".join(f'"{tok}"' for tok in tokens if tok)+++def _normalize_bm25(raw: float) -> float:+ """FTS5 bm25 (lower = better, usually negative) -> [0, 1] higher-is-better."""+ return 1.0 / (1.0 + max(0.0, float(raw)))+++def _as_int(value: Any) -> int | None:+ if value is None:+ return None+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++class EventMixin:+ """Episodic events: storage, bi-temporal queries and the keyword leg."""++ # -- dialect hook --------------------------------------------------------++ #: ``"sqlite"`` (FTS5 side table) or ``"postgres"`` (generated tsvector).+ #: The ONLY difference between the two backends in this module.+ _EVENT_DIALECT: str = "sqlite"++ # -- tiny query helpers (shared with the identity layer's translation) ---++ async def _ev_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 _ev_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 _ev_exec(self, conn: Any, sql: str, params: Sequence[Any] = ()) -> None:+ await conn.execute(self._id_sql(sql), params) # type: ignore[attr-defined]++ # -- write path ----------------------------------------------------------++ async def replace_events(+ self,+ item_id: int,+ events: Sequence[DerivedEvent],+ *,+ create_entities: bool = True,+ ) -> list[int]:+ """Replace one item's whole event set; returns the new event ids.++ Identity resolution happens BEFORE the write transaction on purpose:+ :meth:`resolve_identity` opens its own transaction, and nesting two+ ``BEGIN IMMEDIATE`` blocks on one SQLite connection deadlocks the+ store against itself.++ ``create_entities=False`` links participants and places only to+ entities that already exist — the conservative mode for low-confidence+ derivations, where creating a row per mentioned name would flood the+ People view with noise.+ """+ item_id = int(item_id)+ resolved = await self._ev_resolve_names(events, create_entities=create_entities)+ now = _utc_now_iso()+ new_ids: list[int] = []+ async with self._txn() as conn: # type: ignore[attr-defined]+ await self._ev_purge(conn, [item_id])+ for event in events:+ event_id = await self._ev_insert(+ conn, item_id, event, now=now, resolved=resolved+ )+ new_ids.append(event_id)+ for name in event.participants:+ await self._ev_exec(+ conn,+ "INSERT INTO uw_event_participants"+ " (event_id, entity_id, display_name) VALUES (?, ?, ?)",+ (event_id, resolved.get(("person", name.casefold())), name),+ )+ return new_ids++ async def _ev_resolve_names(+ self, events: Sequence[DerivedEvent], *, create_entities: bool+ ) -> dict[tuple[str, str], int | None]:+ """Map every participant/place name onto a live entity id (or ``None``).++ A name the identity layer refuses to decide (several live holders) maps+ to ``None`` and is stored by its spelling — an honest "I know the name,+ not who it is" beats guessing, and guessing is the wrong-merge failure+ the whole identity layer exists to prevent.+ """+ from jarvis.ultrawiki.identity import EntityKind # noqa: PLC0415 — lazy (AP-26)++ wanted: list[tuple[str, str]] = []+ seen: set[tuple[str, str]] = set()+ for event in events:+ for name in event.participants:+ key = ("person", name.casefold())+ if key not in seen:+ seen.add(key)+ wanted.append((name, EntityKind.PERSON))+ if event.place:+ key = ("place", event.place.casefold())+ if key not in seen:+ seen.add(key)+ wanted.append((event.place, EntityKind.PLACE))++ out: dict[tuple[str, str], int | None] = {}+ for name, kind in wanted:+ slot = ("person" if kind is EntityKind.PERSON else "place", name.casefold())+ try:+ resolution = await self.resolve_identity( # type: ignore[attr-defined]+ name=name,+ kind=kind,+ source_ref="uw_events",+ create=create_entities,+ )+ except Exception: # noqa: BLE001 — a refused link never fails an event+ log.debug("event identity resolution failed for %r", name, exc_info=True)+ out[slot] = None+ continue+ out[slot] = _as_int(getattr(resolution, "entity_id", None))+ return out++ async def _ev_insert(+ self,+ conn: Any,+ item_id: int,+ event: DerivedEvent,+ *,+ now: str,+ resolved: dict[tuple[str, str], int | None],+ ) -> int:+ card = event.search_text()[:_MAX_CARD_CHARS]+ place_id = (+ resolved.get(("place", event.place.casefold())) if event.place else None+ )+ event_id = await self._id_insert( # type: ignore[attr-defined]+ conn,+ self._id_sql( # type: ignore[attr-defined]+ "INSERT INTO uw_events"+ " (item_id, kind, title, summary, occurred_at, occurred_end,"+ " occurred_precision, time_anchor, recorded_at, place_entity_id,"+ " place_raw, confidence, extraction_version, dedupe_key,"+ " evidence_json, search_text, created_at)"+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"+ ),+ (+ item_id,+ str(event.kind),+ event.title,+ event.summary,+ event.time.occurred_at,+ event.time.occurred_end,+ str(event.time.precision),+ str(event.time.anchor),+ event.time.recorded_at,+ place_id,+ event.place,+ float(event.confidence),+ int(event.extraction_version or EVENT_VERSION),+ event.dedupe_key,+ json.dumps([item_id]),+ card,+ now,+ ),+ )+ if self._EVENT_DIALECT == "sqlite":+ await conn.execute(+ "DELETE FROM uw_event_fts WHERE event_id = ?", (event_id,)+ )+ await conn.execute(+ "INSERT INTO uw_event_fts (event_id, title, body) VALUES (?, ?, ?)",+ (event_id, event.title, card),+ )+ return event_id++ async def _ev_purge(self, conn: Any, item_ids: Sequence[int]) -> None:+ """Delete every event derived from *item_ids*, index rows included.++ Called by :meth:`replace_events` and by both backends' ``_purge_derived``+ (a content change invalidates events exactly like it invalidates+ documents and vectors).+ """+ ids = [int(value) for value in item_ids]+ if not ids:+ return+ marks = ",".join("?" for _ in ids)+ if self._EVENT_DIALECT == "sqlite":+ # FTS5 has no foreign keys: its rows must go first and explicitly.+ await conn.execute(+ self._id_sql( # type: ignore[attr-defined]+ "DELETE FROM uw_event_fts WHERE event_id IN" # noqa: S608 — placeholder marks only+ f" (SELECT id FROM uw_events WHERE item_id IN ({marks}))"+ ),+ ids,+ )+ await conn.execute(+ self._id_sql(f"DELETE FROM uw_events WHERE item_id IN ({marks})"), # type: ignore[attr-defined] # noqa: S608 — placeholder marks only+ ids,+ )++ # -- read path -----------------------------------------------------------++ @staticmethod+ def _ev_row_to_dict(row: Any) -> dict[str, Any]:+ data = dict(row)+ precision = str(data.get("occurred_precision") or TimePrecision.DAY)+ try:+ evidence = json.loads(data.get("evidence_json") or "[]")+ except (TypeError, ValueError):+ evidence = []+ return {+ "id": _as_int(data.get("id")),+ "item_id": _as_int(data.get("item_id")),+ "kind": str(data.get("kind") or EventKind.OTHER),+ "title": str(data.get("title") or ""),+ "summary": str(data.get("summary") or ""),+ "occurred_at": str(data.get("occurred_at") or ""),+ "occurred_end": str(data.get("occurred_end") or ""),+ "occurred_precision": precision,+ "time_anchor": str(data.get("time_anchor") or ""),+ "recorded_at": str(data.get("recorded_at") or ""),+ "date_label": format_occurred(str(data.get("occurred_at") or ""), precision),+ "place": str(data.get("place_raw") or ""),+ "place_entity_id": _as_int(data.get("place_entity_id")),+ "confidence": float(data.get("confidence") or 0.0),+ "extraction_version": _as_int(data.get("extraction_version")) or 0,+ "evidence_item_ids": [value for value in evidence if isinstance(value, int)],+ "source_id": str(data.get("source_id") or ""),+ "permalink": str(data.get("permalink") or ""),+ "item_title": str(data.get("item_title") or ""),+ "participants": [],+ }++ _EVENT_SELECT = (+ "SELECT e.id, e.item_id, e.kind, e.title, e.summary, e.occurred_at,"+ " e.occurred_end, e.occurred_precision, e.time_anchor, e.recorded_at,"+ " e.place_entity_id, e.place_raw, e.confidence, e.extraction_version,"+ " e.evidence_json, i.source_id AS source_id, i.permalink AS permalink,"+ " i.title AS item_title"+ " FROM uw_events e JOIN uw_items i ON i.id = e.item_id"+ )++ async def get_event(self, event_id: int) -> dict[str, Any] | None:+ """One event with its participants, or ``None``."""+ conn = await self._ensure_open() # type: ignore[attr-defined]+ row = await self._ev_row(+ conn, f"{self._EVENT_SELECT} WHERE e.id = ?", (int(event_id),)+ )+ if row is None:+ return None+ event = self._ev_row_to_dict(row)+ await self._ev_attach_participants(conn, [event])+ return event++ async def list_events(+ self,+ *,+ since: str | None = None,+ until: str | None = None,+ kind: str | None = None,+ entity_id: int | None = None,+ place_entity_id: int | None = None,+ item_id: int | None = None,+ include_deleted: bool = False,+ limit: int = 50,+ offset: int = 0,+ ) -> list[dict[str, Any]]:+ """Events in a bi-temporal window, newest first.++ ``since``/``until`` bound the VALID time and match by OVERLAP, not by+ containment: an event that spans a month is returned for a query about+ one day inside it. Containment would silently hide every coarse event,+ which is the majority of what a personal corpus actually knows.+ """+ conn = await self._ensure_open() # type: ignore[attr-defined]+ sql = self._EVENT_SELECT+ clauses: list[str] = []+ params: list[Any] = []+ if not include_deleted:+ clauses.append("i.deleted_at IS NULL")+ if since:+ clauses.append("e.occurred_end >= ?")+ params.append(str(since))+ if until:+ clauses.append("e.occurred_at <= ?")+ params.append(str(until))+ if kind:+ clauses.append("e.kind = ?")+ params.append(str(kind))+ if place_entity_id is not None:+ clauses.append("e.place_entity_id = ?")+ params.append(int(place_entity_id))+ if item_id is not None:+ clauses.append("e.item_id = ?")+ params.append(int(item_id))+ if entity_id is not None:+ # A merged-away entity id must still find its events: the identity+ # layer forwards it, so an old citation never goes dead.+ live = await self.resolve_entity_id(int(entity_id)) # type: ignore[attr-defined]+ clauses.append(+ "(e.place_entity_id = ? OR EXISTS (SELECT 1 FROM"+ " uw_event_participants p WHERE p.event_id = e.id"+ " AND p.entity_id = ?))"+ )+ target = int(live if live is not None else entity_id)+ params.extend([target, target])+ if clauses:+ sql += " WHERE " + " AND ".join(clauses)+ sql += " ORDER BY e.occurred_at DESC, e.id DESC LIMIT ? OFFSET ?"+ params.extend([max(1, int(limit)), max(0, int(offset))])+ rows = await self._ev_rows(conn, sql, params)+ events = [self._ev_row_to_dict(row) for row in rows]+ await self._ev_attach_participants(conn, events)+ return events++ async def events_between(+ self,+ start: str,+ end: str,+ *,+ kind: str | None = None,+ entity_id: int | None = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """The design's ``events_between`` primitive (doc 03, "primitive tools")."""+ return await self.list_events(+ since=start, until=end, kind=kind, entity_id=entity_id, limit=limit+ )++ async def _ev_attach_participants(+ self, conn: Any, events: list[dict[str, Any]]+ ) -> None:+ """Fill in each event's participant list in one extra query."""+ ids = [event["id"] for event in events if event.get("id") is not None]+ if not ids:+ return+ marks = ",".join("?" for _ in ids)+ rows = await self._ev_rows(+ conn,+ "SELECT p.event_id, p.entity_id, p.display_name" # noqa: S608 — placeholder marks only+ f" FROM uw_event_participants p WHERE p.event_id IN ({marks})"+ " ORDER BY p.id",+ ids,+ )+ by_event: dict[int, list[dict[str, Any]]] = {}+ for row in rows:+ data = dict(row)+ by_event.setdefault(int(data["event_id"]), []).append(+ {+ "entity_id": _as_int(data.get("entity_id")),+ "display_name": str(data.get("display_name") or ""),+ }+ )+ for event in events:+ event["participants"] = by_event.get(int(event["id"]), [])++ async def search_events(+ self,+ query: str,+ k: int = 10,+ *,+ since: str | None = None,+ until: str | None = None,+ kind: str | None = None,+ area_id: str | None = None,+ ) -> list[SearchResult]:+ """The event keyword leg, shaped exactly like the item legs.++ Returns :class:`SearchResult` rows so the fusion stage can treat events+ as one more ranked list (design doc 01, principle 5: no single scorer+ is trusted). ``timestamp_utc`` carries the event's OWN ``occurred_at``+ rather than the evidence item's — the date the user asked about is the+ date the answer should be ordered and decayed by.+ """+ if not query or not query.strip():+ return []+ conn = await self._ensure_open() # type: ignore[attr-defined]+ params: list[Any] = []+ if self._EVENT_DIALECT == "postgres":+ expression = query+ sql = (+ "SELECT e.id AS event_id, e.item_id, e.kind, e.title,"+ " e.summary, e.occurred_at, e.occurred_end, e.occurred_precision,"+ " e.place_raw, e.search_text,"+ " i.source_id, i.permalink, i.areas_json,"+ " ts_rank(e.search_tsv, websearch_to_tsquery('simple', ?)) AS raw_score"+ " FROM uw_events e JOIN uw_items i ON i.id = e.item_id"+ " WHERE e.search_tsv @@ websearch_to_tsquery('simple', ?)"+ " AND i.deleted_at IS NULL"+ )+ params.extend([expression, expression])+ else:+ expression = _match_expr(query)+ if not expression:+ return []+ sql = (+ "SELECT e.id AS event_id, e.item_id, e.kind, e.title,"+ " e.summary, e.occurred_at, e.occurred_end, e.occurred_precision,"+ " e.place_raw, e.search_text,"+ " i.source_id, i.permalink, i.areas_json,"+ " bm25(uw_event_fts, 0.0, 3.0, 1.0) AS raw_score"+ " FROM uw_event_fts JOIN uw_events e ON e.id = uw_event_fts.event_id"+ " JOIN uw_items i ON i.id = e.item_id"+ " WHERE uw_event_fts MATCH ? AND i.deleted_at IS NULL"+ )+ params.append(expression)+ if since:+ sql += " AND e.occurred_end >= ?"+ params.append(str(since))+ if until:+ sql += " AND e.occurred_at <= ?"+ params.append(str(until))+ if kind:+ sql += " AND e.kind = ?"+ params.append(str(kind))+ if area_id is not None:+ if self._EVENT_DIALECT == "postgres":+ sql += " AND i.areas_json::jsonb @> to_jsonb(?::text)"+ else:+ sql += (+ " AND EXISTS (SELECT 1 FROM json_each(i.areas_json)"+ " WHERE json_each.value = ?)"+ )+ params.append(area_id)+ sql += (+ " ORDER BY raw_score DESC LIMIT ?"+ if self._EVENT_DIALECT == "postgres"+ else " ORDER BY raw_score LIMIT ?"+ )+ params.append(max(1, int(k)))+ rows = await self._ev_rows(conn, sql, params)+ return [self._ev_hit(dict(row)) for row in rows]++ def _ev_hit(self, data: dict[str, Any]) -> SearchResult:+ raw = float(data.get("raw_score") or 0.0)+ score = (+ raw / (1.0 + raw) if self._EVENT_DIALECT == "postgres" else _normalize_bm25(raw)+ )+ precision = str(data.get("occurred_precision") or TimePrecision.DAY)+ label = format_occurred(str(data.get("occurred_at") or ""), precision)+ snippet = " ".join(str(data.get("search_text") or "").split())[:400]+ return SearchResult(+ item_id=int(data["item_id"]),+ source_id=str(data.get("source_id") or ""),+ title=str(data.get("title") or ""),+ snippet=f"{label} — {snippet}" if label else snippet,+ permalink=str(data.get("permalink") or ""),+ timestamp_utc=str(data.get("occurred_at") or ""),+ score=round(score, 4),+ matched_by=("event",),+ )++ async def event_counts(self) -> dict[str, int]:+ """``{kind: n}`` over live events, plus ``total`` — the surface's badge."""+ conn = await self._ensure_open() # type: ignore[attr-defined]+ rows = await self._ev_rows(+ conn,+ "SELECT e.kind AS kind, COUNT(*) AS n FROM uw_events e"+ " JOIN uw_items i ON i.id = e.item_id"+ " WHERE i.deleted_at IS NULL GROUP BY e.kind",+ )+ counts = {kind.value: 0 for kind in EventKind}+ total = 0+ for row in rows:+ data = dict(row)+ number = int(data.get("n") or 0)+ counts[str(data.get("kind") or EventKind.OTHER)] = number+ total += number+ counts["total"] = total+ return countsdiff --git a/jarvis/ultrawiki/events.py b/jarvis/ultrawiki/events.pynew file mode 100644index 0000000000..c612838c71--- /dev/null+++ b/jarvis/ultrawiki/events.py@@ -0,0 +1,946 @@+"""UltraWiki episodic events — derivation logic with absolute time anchoring.++Design doc 01 (`uw_events`) and doc 03 ("cross-source reconstruction"). An+episodic question — *when did I have dinner with X in Y* — must hit a+**precomputed** row, because reconstructing it at read time from chat+fragments, a calendar entry and a photo's metadata cannot fit the voice+budget. This module is the deterministic half of that: it turns what the+per-document distillation ALREADY produced into event structures, and it does+the one thing a language model must never be trusted with — the arithmetic+that turns *"next Friday"* into an absolute instant.++Three rules the whole module exists to keep:++1. **No new model call, ever.** Events ride the distillation that already ran+ (``distill.PROMPT_VERSION`` 2 emits an ``events`` array in the SAME call).+ A corpus distilled under the old prompt still yields events through the+ legacy path below, which reads nothing but the stored distillation text.+2. **Time is stored absolute, never as text.** A relative expression is+ resolved against the source item's OWN timestamp at extraction time+ (design doc 01), so an event keeps meaning years later and after the+ sentence that produced it has scrolled away. **No anchor, no event**: an+ item whose timestamp does not parse produces nothing rather than an event+ floating in an unknown year.+3. **The model normalizes language, this module does the maths.** The prompt+ asks for ISO-8601 whenever the source states a date outright and otherwise+ for ONE token from a closed English vocabulary (``yesterday``,+ ``last friday``, ``3 days ago``, ...). A German, Spanish or Japanese source+ therefore arrives here already normalized, and the resolver below never+ needs a per-language phrase table — which is exactly what makes it work for+ every locale instead of the two somebody happened to test.++Everything here is pure, deterministic, stdlib-only and offline: no model, no+network, no clock (the anchor is always passed in), no database. The SQL side+lives in ``jarvis/ultrawiki/event_store.py``.+"""++from __future__ import annotations++import calendar+import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from enum import StrEnum+from typing import Any++from jarvis.ultrawiki.types import content_hash_for++__all__ = [+ "EVENT_KIND_VALUES",+ "EVENT_VERSION",+ "MAX_EVENTS_PER_ITEM",+ "MAX_PARTICIPANTS",+ "RELATIVE_VOCABULARY",+ "TIME_ANCHOR_VALUES",+ "TIME_PRECISION_VALUES",+ "DerivedEvent",+ "EventKind",+ "EventTime",+ "TimeAnchor",+ "TimePrecision",+ "coerce_kind",+ "derive_events",+ "format_occurred",+ "iso_utc",+ "parse_absolute",+ "parse_instant",+ "resolve_time",+ "scan_absolute_dates",+ "window_end",+]+++# ---------------------------------------------------------------------------+# Canonical value sets (five-layer drift rule, AP-4 / BUG-008)+# ---------------------------------------------------------------------------+++class EventKind(StrEnum):+ """What kind of episodic fact this is (design doc 01, ``event_type``).++ A deliberately SHORT closed list: the kinds a person actually asks+ questions about. ``OTHER`` is the honest bucket — an event whose kind is+ unknown is still worth having, because its date, participants and place+ are the answer to "when did that happen".+ """++ MEAL = "meal"+ TRAVEL = "travel"+ MEETING = "meeting"+ PURCHASE = "purchase"+ MILESTONE = "milestone"+ OTHER = "other"+++class TimePrecision(StrEnum):+ """How sharply the source pinned the moment down.++ Precision is not decoration: it decides the END of the interval an event+ occupies, and therefore whether a range query matches it. "In March" is+ one event covering 31 days, not an event at midnight on the 1st.+ """++ MINUTE = "minute"+ HOUR = "hour"+ DAY = "day"+ WEEK = "week"+ MONTH = "month"+ YEAR = "year"+++class TimeAnchor(StrEnum):+ """Where the absolute time came from — the honesty column.++ Distinguishing these is what keeps a confident-looking date from lying: a+ ``RECORDED`` event happened *around* when the message was written and is+ worth far less than an ``ABSOLUTE`` one the source spelled out.+ """++ #: The source stated a date/time outright ("2026-03-14", "14 March 2026").+ ABSOLUTE = "absolute"+ #: A relative expression resolved against the item's own timestamp.+ RELATIVE = "relative"+ #: Nothing was stated; the item's own timestamp IS the anchor.+ RECORDED = "recorded"+++#: Extraction version stamped onto every row — bump when the derivation rules+#: change so a re-extraction pass can be told apart from old rows.+EVENT_VERSION = 1++#: Hard caps. One item never becomes a wall of events, and a hallucinated+#: participant list never becomes an entity flood on the write path.+MAX_EVENTS_PER_ITEM = 5+MAX_PARTICIPANTS = 12+MAX_TITLE_CHARS = 160+MAX_SUMMARY_CHARS = 400+MAX_PLACE_CHARS = 120++#: Legacy path only: at most this many dates are lifted out of a distillation+#: that predates the ``events`` key, so an itinerary full of dates does not+#: become an itinerary full of junk events.+MAX_LEGACY_EVENTS = 2++#: Confidence floor/ceiling and the values the two derivation paths assign+#: when the source offers none. The legacy path scores LOW on purpose: it+#: knows a date and some names, and nothing about what actually happened.+DEFAULT_CONFIDENCE = 0.5+LEGACY_CONFIDENCE = 0.35+++# ---------------------------------------------------------------------------+# Absolute time parsing+# ---------------------------------------------------------------------------+++def iso_utc(moment: datetime) -> str:+ """UTC ISO-8601 with a ``Z`` suffix and second resolution."""+ aware = moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)+ return (+ aware.astimezone(UTC)+ .replace(microsecond=0)+ .isoformat()+ .replace("+00:00", "Z")+ )+++#: Month names the written forms use. English is the artifact language of this+#: repo (§1) AND the language the distillation prompt normalizes into, so this+#: table is a formatter, not a matcher for user text.+_MONTHS = (+ "January",+ "February",+ "March",+ "April",+ "May",+ "June",+ "July",+ "August",+ "September",+ "October",+ "November",+ "December",+)+_MONTH_INDEX = {name.lower(): number for number, name in enumerate(_MONTHS, start=1)}+_MONTH_INDEX.update({name[:3].lower(): number for number, name in enumerate(_MONTHS, start=1)})++_MONTH_ALTERNATION = "|".join(sorted(_MONTH_INDEX, key=len, reverse=True))++#: ISO-ish instants: date, optional time, optional zone. The one format the+#: prompt asks for, and the only one a machine-written source ever emits.+_ISO_RE = re.compile(+ r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"+ r"(?:[T ](?P<hour>\d{2}):(?P<minute>\d{2})(?::(?P<second>\d{2}))?"+ r"(?P<zone>Z|[+-]\d{2}:?\d{2})?)?"+)+_ISO_MONTH_RE = re.compile(r"^(?P<year>\d{4})-(?P<month>\d{2})$")+_ISO_YEAR_RE = re.compile(r"^(?P<year>\d{4})$")++#: Day-first dotted dates ("14.03.2026"). Dots are the one separator with an+#: unambiguous convention worldwide; slash dates are deliberately NOT parsed,+#: because 03/04/2026 is two different days on two continents and a personal+#: memory that guesses is worse than one that stays quiet.+_DOTTED_RE = re.compile(r"\b(?P<day>\d{1,2})\.(?P<month>\d{1,2})\.(?P<year>\d{4})\b")++#: Written English dates in both orders, with or without a year.+_WRITTEN_DMY_RE = re.compile(+ rf"\b(?P<day>\d{{1,2}})(?:st|nd|rd|th)?\s+(?P<month>{_MONTH_ALTERNATION})"+ r"(?:\s+(?P<year>\d{4}))?\b",+ re.IGNORECASE,+)+_WRITTEN_MDY_RE = re.compile(+ rf"\b(?P<month>{_MONTH_ALTERNATION})\s+(?P<day>\d{{1,2}})(?:st|nd|rd|th)?"+ r"(?:,?\s+(?P<year>\d{4}))?\b",+ re.IGNORECASE,+)++#: A clock time appended to any of the above ("at 19:30", "19:30", "7pm").+#: A BARE number never counts as a time — otherwise "3 days ago" would resolve+#: to 03:00 and state a made-up hour as a fact. One of the three explicit+#: markers must be present: an "at" prefix, a ":MM" component, or am/pm.+_CLOCK_RE = re.compile(+ r"\b(?P<prefix>at\s+)?(?P<hour>\d{1,2})(?::(?P<minute>\d{2}))?"+ r"\s*(?P<ampm>am|pm)?\b",+ re.IGNORECASE,+)++#: Coarse dayparts the prompt may append instead of a clock time. Values are+#: the conventional midpoint of each; precision stays HOUR so the stored+#: interval still says "somewhere in that part of the day".+_DAYPARTS = {+ "morning": 9,+ "noon": 12,+ "midday": 12,+ "afternoon": 15,+ "evening": 19,+ "night": 21,+}++#: Written weekday names. Spelled out rather than taken from ``calendar.+#: day_name``, which follows the process LOCALE — a store indexed on a German+#: desktop and queried on an English one would otherwise hold two different+#: spellings of the same day.+_WEEKDAY_NAMES = (+ "Monday",+ "Tuesday",+ "Wednesday",+ "Thursday",+ "Friday",+ "Saturday",+ "Sunday",+)++_WEEKDAYS = {+ "monday": 0,+ "tuesday": 1,+ "wednesday": 2,+ "thursday": 3,+ "friday": 4,+ "saturday": 5,+ "sunday": 6,+}+++def _safe_date(year: int, month: int, day: int) -> datetime | None:+ try:+ return datetime(year, month, day, tzinfo=UTC)+ except ValueError:+ return None+++def _clock_from(text: str) -> tuple[int, int] | None:+ """Extract a wall-clock time from a fragment, if it states one."""+ lowered = text.lower()+ for word, hour in _DAYPARTS.items():+ if word in lowered:+ return hour, 0+ for match in _CLOCK_RE.finditer(text):+ if not (match.group("prefix") or match.group("minute") or match.group("ampm")):+ continue # a bare number is a count, not a time+ hour = int(match.group("hour"))+ minute = int(match.group("minute") or 0)+ ampm = (match.group("ampm") or "").lower()+ if ampm == "pm" and hour < 12:+ hour += 12+ elif ampm == "am" and hour == 12:+ hour = 0+ if 0 <= hour <= 23 and 0 <= minute <= 59:+ return hour, minute+ return None+++def parse_instant(value: str) -> datetime | None:+ """Parse one ISO-8601 timestamp into an aware UTC datetime, or ``None``.++ Deliberately tolerant of the shapes connectors actually produce (``Z``,+ ``+02:00``, a bare date, a space instead of ``T``) and deliberately silent+ on everything else — an unparseable anchor means "no event", never "now".+ """+ text = str(value or "").strip()+ if not text:+ return None+ match = _ISO_RE.match(text)+ if match is None:+ return None+ base = _safe_date(+ int(match.group("year")), int(match.group("month")), int(match.group("day"))+ )+ if base is None:+ return None+ hour = int(match.group("hour") or 0)+ minute = int(match.group("minute") or 0)+ second = int(match.group("second") or 0)+ if hour > 23 or minute > 59 or second > 59:+ return None+ moment = base.replace(hour=hour, minute=minute, second=second)+ zone = match.group("zone")+ if zone and zone != "Z":+ sign = 1 if zone[0] == "+" else -1+ digits = zone[1:].replace(":", "")+ offset = timedelta(hours=int(digits[:2]), minutes=int(digits[2:4]))+ moment = moment - sign * offset+ return moment+++def parse_absolute(value: str) -> tuple[datetime, TimePrecision] | None:+ """Parse an absolute date/time expression into ``(instant, precision)``.++ Accepts ISO instants and dates, ``YYYY-MM``, ``YYYY``, dotted day-first+ dates, and written English dates in either order — each optionally+ followed by a clock time or a daypart word.+ """+ text = str(value or "").strip()+ if not text:+ return None++ iso_month = _ISO_MONTH_RE.match(text)+ if iso_month is not None:+ moment = _safe_date(int(iso_month.group("year")), int(iso_month.group("month")), 1)+ return None if moment is None else (moment, TimePrecision.MONTH)+ iso_year = _ISO_YEAR_RE.match(text)+ if iso_year is not None:+ moment = _safe_date(int(iso_year.group("year")), 1, 1)+ return None if moment is None else (moment, TimePrecision.YEAR)++ iso = _ISO_RE.match(text)+ if iso is not None:+ moment = parse_instant(text)+ if moment is None:+ return None+ if iso.group("hour") is None:+ tail = text[iso.end() :]+ clock = _clock_from(tail) if tail.strip() else None+ if clock is not None:+ return moment.replace(hour=clock[0], minute=clock[1]), TimePrecision.MINUTE+ return moment, TimePrecision.DAY+ return moment, TimePrecision.MINUTE++ found = _scan_one(text)+ if found is None:+ return None+ moment, precision, end = found+ if precision is TimePrecision.DAY:+ clock = _clock_from(text[end:])+ if clock is not None:+ return moment.replace(hour=clock[0], minute=clock[1]), TimePrecision.MINUTE+ return moment, precision+++def _scan_one(text: str) -> tuple[datetime, TimePrecision, int] | None:+ """First dotted/written date in *text* as ``(instant, precision, end)``."""+ best: tuple[int, datetime, TimePrecision, int] | None = None+ for pattern in (_DOTTED_RE, _WRITTEN_DMY_RE, _WRITTEN_MDY_RE):+ match = pattern.search(text)+ if match is None:+ continue+ groups = match.groupdict()+ month_raw = groups.get("month") or ""+ month = (+ int(month_raw)+ if month_raw.isdigit()+ else _MONTH_INDEX.get(month_raw.lower(), 0)+ )+ year_raw = groups.get("year")+ if not year_raw:+ # A written date without a year cannot be anchored on its own; the+ # caller's anchor year would be a guess, and a guessed year is the+ # exact failure this module refuses to ship.+ continue+ moment = _safe_date(int(year_raw), month, int(groups.get("day") or 0))+ if moment is None:+ continue+ if best is None or match.start() < best[0]:+ best = (match.start(), moment, TimePrecision.DAY, match.end())+ if best is None:+ return None+ return best[1], best[2], best[3]+++def scan_absolute_dates(+ text: str, *, limit: int = MAX_LEGACY_EVENTS+) -> list[tuple[datetime, TimePrecision]]:+ """Every distinct absolute date stated in *text*, in order of appearance.++ The legacy derivation path's only time signal: a distillation written+ before the ``events`` key still SAYS when things happened, in prose.+ """+ out: list[tuple[datetime, TimePrecision]] = []+ seen: set[str] = set()+ for pattern in (_ISO_RE, _DOTTED_RE, _WRITTEN_DMY_RE, _WRITTEN_MDY_RE):+ for match in pattern.finditer(text or ""):+ parsed = parse_absolute(match.group(0))+ if parsed is None:+ continue+ moment, precision = parsed+ key = f"{iso_utc(moment)}|{precision}"+ if key in seen:+ continue+ seen.add(key)+ out.append((moment, precision))+ if len(out) >= max(1, int(limit)):+ return out+ return out+++# ---------------------------------------------------------------------------+# Relative time resolution — the closed vocabulary+# ---------------------------------------------------------------------------++#: What the distillation prompt is allowed to emit when the source used a+#: relative expression. Documented here because prompt and resolver must move+#: together: a token the prompt invents and this table does not know resolves+#: to nothing and the event falls back to the item's own timestamp.+RELATIVE_VOCABULARY: tuple[str, ...] = (+ "today",+ "yesterday",+ "tomorrow",+ "this <weekday>",+ "last <weekday>",+ "next <weekday>",+ "last week",+ "next week",+ "last month",+ "next month",+ "last year",+ "next year",+ "<n> days ago",+ "<n> weeks ago",+ "<n> months ago",+ "<n> years ago",+ "in <n> days",+ "in <n> weeks",+ "in <n> months",+ "in <n> years",+)++_REL_WEEKDAY_RE = re.compile(+ r"\b(?P<which>this|last|next|past|coming)\s+(?P<weekday>"+ + "|".join(_WEEKDAYS)+ + r")\b",+ re.IGNORECASE,+)+_REL_AGO_RE = re.compile(+ r"\b(?P<count>\d{1,3})\s+(?P<unit>day|days|week|weeks|month|months|year|years)\s+ago\b",+ re.IGNORECASE,+)+_REL_IN_RE = re.compile(+ r"\bin\s+(?P<count>\d{1,3})\s+(?P<unit>day|days|week|weeks|month|months|year|years)\b",+ re.IGNORECASE,+)+_REL_UNIT_RE = re.compile(+ r"\b(?P<which>last|next|this)\s+(?P<unit>week|month|year)\b", re.IGNORECASE+)+++def _start_of_day(moment: datetime) -> datetime:+ return moment.replace(hour=0, minute=0, second=0, microsecond=0)+++def _shift_months(moment: datetime, months: int) -> datetime:+ total = (moment.year * 12 + moment.month - 1) + months+ year, month = divmod(total, 12)+ month += 1+ last_day = calendar.monthrange(year, month)[1]+ return moment.replace(year=year, month=month, day=min(moment.day, last_day))+++def _resolve_relative(+ text: str, anchor: datetime+) -> tuple[datetime, TimePrecision] | None:+ """Resolve one closed-vocabulary relative expression against *anchor*."""+ lowered = " ".join(str(text or "").lower().split())+ if not lowered:+ return None+ day = _start_of_day(anchor)++ if "today" in lowered or "tonight" in lowered:+ return day, TimePrecision.DAY+ if "yesterday" in lowered:+ return day - timedelta(days=1), TimePrecision.DAY+ if "tomorrow" in lowered:+ return day + timedelta(days=1), TimePrecision.DAY++ weekday = _REL_WEEKDAY_RE.search(lowered)+ if weekday is not None:+ which = weekday.group("which")+ target = _WEEKDAYS[weekday.group("weekday")]+ delta = (target - day.weekday()) % 7+ if which in {"last", "past"}:+ back = (day.weekday() - target) % 7 or 7+ return day - timedelta(days=back), TimePrecision.DAY+ if which in {"next", "coming"}:+ return day + timedelta(days=delta or 7), TimePrecision.DAY+ # "this <weekday>" = the one inside the anchor's own Monday-Sunday week.+ return day - timedelta(days=day.weekday()) + timedelta(days=target), TimePrecision.DAY++ ago = _REL_AGO_RE.search(lowered)+ if ago is not None:+ return _apply_offset(day, int(ago.group("count")), ago.group("unit"), sign=-1)+ ahead = _REL_IN_RE.search(lowered)+ if ahead is not None:+ return _apply_offset(day, int(ahead.group("count")), ahead.group("unit"), sign=1)++ unit = _REL_UNIT_RE.search(lowered)+ if unit is not None:+ which = unit.group("which")+ step = 0 if which == "this" else (-1 if which == "last" else 1)+ kind = unit.group("unit")+ if kind == "week":+ monday = day - timedelta(days=day.weekday())+ return monday + timedelta(weeks=step), TimePrecision.WEEK+ if kind == "month":+ shifted = _shift_months(day, step)+ return shifted.replace(day=1), TimePrecision.MONTH+ return day.replace(month=1, day=1, year=day.year + step), TimePrecision.YEAR+ return None+++def _apply_offset(+ day: datetime, count: int, unit: str, *, sign: int+) -> tuple[datetime, TimePrecision]:+ unit = unit.rstrip("s")+ if unit == "day":+ return day + sign * timedelta(days=count), TimePrecision.DAY+ if unit == "week":+ return day + sign * timedelta(weeks=count), TimePrecision.WEEK+ if unit == "month":+ return _shift_months(day, sign * count), TimePrecision.MONTH+ return day.replace(year=day.year + sign * count), TimePrecision.YEAR+++# ---------------------------------------------------------------------------+# The resolved interval+# ---------------------------------------------------------------------------+++def window_end(moment: datetime, precision: TimePrecision) -> datetime:+ """Last instant still inside the window *precision* describes.++ This is what makes "in March" match a query for the 14th: an event is not+ a point unless the source said so.+ """+ if precision is TimePrecision.MINUTE:+ return moment.replace(second=59)+ if precision is TimePrecision.HOUR:+ return moment.replace(minute=59, second=59)+ if precision is TimePrecision.DAY:+ return moment.replace(hour=23, minute=59, second=59)+ if precision is TimePrecision.WEEK:+ return (moment + timedelta(days=6)).replace(hour=23, minute=59, second=59)+ if precision is TimePrecision.MONTH:+ last_day = calendar.monthrange(moment.year, moment.month)[1]+ return moment.replace(day=last_day, hour=23, minute=59, second=59)+ return moment.replace(month=12, day=31, hour=23, minute=59, second=59)+++@dataclass(frozen=True, slots=True)+class EventTime:+ """One event's absolute, bi-temporal position.++ ``occurred_at``/``occurred_end`` are VALID time (when it happened in the+ world); ``recorded_at`` is TRANSACTION time (when the source recorded the+ statement). Keeping them apart is what lets a Monday message about a+ Friday dinner answer both "when was the dinner" and "when did I plan it".+ """++ occurred_at: str+ occurred_end: str+ precision: TimePrecision+ anchor: TimeAnchor+ recorded_at: str++ @classmethod+ def build(+ cls,+ moment: datetime,+ precision: TimePrecision,+ anchor: TimeAnchor,+ *,+ recorded_at: datetime,+ end: datetime | None = None,+ ) -> EventTime:+ finish = end if end is not None and end >= moment else window_end(moment, precision)+ return cls(+ occurred_at=iso_utc(moment),+ occurred_end=iso_utc(finish),+ precision=precision,+ anchor=anchor,+ recorded_at=iso_utc(recorded_at),+ )+++def resolve_time(+ raw_when: str,+ *,+ recorded_at: datetime,+ raw_end: str = "",+) -> EventTime:+ """Turn one ``when`` expression into an absolute interval.++ Precedence: an absolute expression wins, a closed-vocabulary relative one+ is resolved against *recorded_at*, and anything else falls back to+ *recorded_at* itself with :attr:`TimeAnchor.RECORDED` — honest about the+ fact that the item's own timestamp is all that is known.+ """+ text = str(raw_when or "").strip()+ absolute = parse_absolute(text) if text else None+ if absolute is not None:+ moment, precision = absolute+ anchor = TimeAnchor.ABSOLUTE+ else:+ relative = _resolve_relative(text, recorded_at) if text else None+ if relative is not None:+ moment, precision = relative+ clock = _clock_from(text)+ if clock is not None and precision is TimePrecision.DAY:+ moment = moment.replace(hour=clock[0], minute=clock[1])+ precision = TimePrecision.MINUTE+ anchor = TimeAnchor.RELATIVE+ else:+ moment, precision, anchor = recorded_at, TimePrecision.MINUTE, TimeAnchor.RECORDED++ end: datetime | None = None+ finish_text = str(raw_end or "").strip()+ if finish_text:+ finish = parse_absolute(finish_text)+ if finish is None:+ resolved = _resolve_relative(finish_text, recorded_at)+ finish = resolved if resolved is not None else None+ if finish is not None:+ end = window_end(finish[0], finish[1])+ return EventTime.build(+ moment, precision, anchor, recorded_at=recorded_at, end=end+ )+++def format_occurred(occurred_at: str, precision: TimePrecision | str) -> str:+ """Human-readable date label for one event ("14 March 2026 at 19:30").++ Used in the search card and by every surface that verbalizes an event, so+ a date is written ONE way across UI, CLI, chat and voice.+ """+ moment = parse_instant(occurred_at)+ if moment is None:+ return str(occurred_at or "")+ level = TimePrecision(str(precision)) if precision else TimePrecision.DAY+ if level is TimePrecision.YEAR:+ return f"{moment.year}"+ if level is TimePrecision.MONTH:+ return f"{_MONTHS[moment.month - 1]} {moment.year}"+ day_label = f"{moment.day} {_MONTHS[moment.month - 1]} {moment.year}"+ if level is TimePrecision.WEEK:+ return f"week of {day_label}"+ if level is TimePrecision.DAY:+ return day_label+ if level is TimePrecision.HOUR:+ return f"{day_label} around {moment.hour:02d}:00"+ return f"{day_label} at {moment.hour:02d}:{moment.minute:02d}"+++# ---------------------------------------------------------------------------+# The derived event+# ---------------------------------------------------------------------------+++def coerce_kind(value: Any) -> EventKind:+ """Map whatever the distillation said onto the closed kind list."""+ text = str(value or "").strip().lower()+ for kind in EventKind:+ if text == kind.value:+ return kind+ return EventKind.OTHER+++def _clean(value: Any, limit: int) -> str:+ return " ".join(str(value or "").split())[:limit]+++def _names(value: Any) -> list[str]:+ """Salvage a participant list; scalars wrap, junk and duplicates drop."""+ raw: Sequence[Any]+ if isinstance(value, str):+ raw = [value]+ elif isinstance(value, (list, tuple)):+ raw = value+ else:+ return []+ out: list[str] = []+ seen: set[str] = set()+ for entry in raw:+ name = _clean(entry, MAX_TITLE_CHARS)+ key = name.casefold()+ if not name or key in seen:+ continue+ seen.add(key)+ out.append(name)+ if len(out) >= MAX_PARTICIPANTS:+ break+ return out+++@dataclass(frozen=True, slots=True)+class DerivedEvent:+ """One episodic fact, ready to be stored — absolute in time by construction."""++ kind: EventKind+ title: str+ summary: str+ time: EventTime+ participants: tuple[str, ...] = ()+ place: str = ""+ confidence: float = DEFAULT_CONFIDENCE+ extraction_version: int = EVENT_VERSION++ @property+ def dedupe_key(self) -> str:+ """Stable identity of this event WITHIN its item.++ Re-deriving an unchanged item must land on the same key, which is what+ makes ``replace_events`` idempotent instead of duplicating on every+ pipeline pass.+ """+ return content_hash_for(+ str(self.kind),+ self.time.occurred_at,+ self.title.casefold(),+ self.place.casefold(),+ "|".join(sorted(name.casefold() for name in self.participants)),+ )[:32]++ @property+ def date_label(self) -> str:+ return format_occurred(self.time.occurred_at, self.time.precision)++ def search_text(self) -> str:+ """The keyword-index card: everything a person might ask this event by.++ Deliberately redundant — the label, the ISO date, the weekday, the+ month name and the bare year all appear, so "March", "2026" and+ "14.03" reach the same row. This is the text the FTS leg indexes.+ """+ moment = parse_instant(self.time.occurred_at)+ parts = [self.title, str(self.kind), self.date_label]+ if moment is not None:+ parts.extend(+ [+ f"{moment.year:04d}-{moment.month:02d}-{moment.day:02d}",+ f"{moment.day:02d}.{moment.month:02d}.{moment.year:04d}",+ _WEEKDAY_NAMES[moment.weekday()],+ _MONTHS[moment.month - 1],+ str(moment.year),+ ]+ )+ if self.participants:+ parts.append("with " + ", ".join(self.participants))+ if self.place:+ parts.append("in " + self.place)+ if self.summary:+ parts.append(self.summary)+ return " ".join(part for part in parts if part).strip()++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": str(self.kind),+ "title": self.title,+ "summary": self.summary,+ "occurred_at": self.time.occurred_at,+ "occurred_end": self.time.occurred_end,+ "occurred_precision": str(self.time.precision),+ "time_anchor": str(self.time.anchor),+ "recorded_at": self.time.recorded_at,+ "date_label": self.date_label,+ "participants": list(self.participants),+ "place": self.place,+ "confidence": round(float(self.confidence), 3),+ "extraction_version": int(self.extraction_version),+ }+++# ---------------------------------------------------------------------------+# Derivation+# ---------------------------------------------------------------------------+++def _confidence(value: Any, default: float) -> float:+ try:+ number = float(value)+ except (TypeError, ValueError):+ return default+ if number != number: # NaN+ return default+ return max(0.0, min(1.0, number))+++def _from_payload(+ entry: Mapping[str, Any],+ *,+ recorded: datetime,+ fallback_title: str,+ fallback_summary: str,+) -> DerivedEvent | None:+ """One entry of the distillation's ``events`` array, or ``None`` if junk."""+ title = _clean(entry.get("title"), MAX_TITLE_CHARS) or fallback_title+ place = _clean(entry.get("where") or entry.get("place"), MAX_PLACE_CHARS)+ participants = _names(entry.get("participants") or entry.get("people"))+ when = _clean(entry.get("when"), MAX_TITLE_CHARS)+ kind = coerce_kind(entry.get("kind") or entry.get("event_type"))+ if not title and not place and not participants and not when:+ return None # an entry with nothing in it is not an event+ time = resolve_time(+ when, recorded_at=recorded, raw_end=_clean(entry.get("when_end"), MAX_TITLE_CHARS)+ )+ summary = _clean(entry.get("summary"), MAX_SUMMARY_CHARS) or fallback_summary+ return DerivedEvent(+ kind=kind,+ title=title or str(kind),+ summary=summary,+ time=time,+ participants=tuple(participants),+ place=place,+ confidence=_confidence(entry.get("confidence"), DEFAULT_CONFIDENCE),+ )+++def _legacy_events(+ distill: Mapping[str, Any],+ *,+ recorded: datetime,+ fallback_title: str,+) -> list[DerivedEvent]:+ """Events from a distillation that predates the ``events`` key.++ Reads nothing but text that is ALREADY stored — no model call, no+ re-distillation — and fires only where the distillation states an+ absolute date outright. A date is the one episodic signal that can be+ recognized without understanding the sentence; guessing a KIND from words+ would need a per-language lexicon, and shipping one for two languages is+ how a feature quietly stops existing for everyone else.+ """+ question = _clean(distill.get("question"), MAX_TITLE_CHARS)+ summary = _clean(distill.get("summary"), MAX_SUMMARY_CHARS)+ resolution = _clean(distill.get("resolution"), MAX_SUMMARY_CHARS)+ haystack = " ".join(part for part in (question, summary, resolution) if part)+ dates = scan_absolute_dates(haystack)+ if not dates:+ return []+ participants = tuple(_names(distill.get("entities")))+ title = question or fallback_title or summary[:MAX_TITLE_CHARS]+ return [+ DerivedEvent(+ kind=EventKind.OTHER,+ title=title or "Recorded event",+ summary=summary,+ time=EventTime.build(+ moment, precision, TimeAnchor.ABSOLUTE, recorded_at=recorded+ ),+ participants=participants,+ confidence=LEGACY_CONFIDENCE,+ )+ for moment, precision in dates+ ]+++def derive_events(+ *,+ distill: Mapping[str, Any] | None,+ title: str = "",+ recorded_at: str = "",+ max_events: int = MAX_EVENTS_PER_ITEM,+) -> list[DerivedEvent]:+ """Derive every episodic event one distilled item carries.++ *distill* is the parsed distillation JSON exactly as the pipeline already+ holds it; *recorded_at* is the item's own ``timestamp_utc`` and is the+ ONLY clock involved — without a parseable one this returns nothing, by+ design (rule 2 in the module docstring).++ Never calls a model, never touches the network, and is safe to run on the+ write path inside the distillation stage that produced its input.+ """+ recorded = parse_instant(recorded_at)+ if recorded is None or not distill:+ return []+ fallback_title = _clean(title, MAX_TITLE_CHARS)+ fallback_summary = _clean(distill.get("summary"), MAX_SUMMARY_CHARS)++ raw_events = distill.get("events")+ events: list[DerivedEvent] = []+ if isinstance(raw_events, (list, tuple)):+ for entry in raw_events:+ if not isinstance(entry, Mapping):+ continue+ derived = _from_payload(+ entry,+ recorded=recorded,+ fallback_title=fallback_title,+ fallback_summary=fallback_summary,+ )+ if derived is not None:+ events.append(derived)+ if len(events) >= max(1, int(max_events)):+ break+ if events:+ return _dedupe(events)+ return _dedupe(+ _legacy_events(distill, recorded=recorded, fallback_title=fallback_title)+ )+++def _dedupe(events: Sequence[DerivedEvent]) -> list[DerivedEvent]:+ seen: set[str] = set()+ out: list[DerivedEvent] = []+ for event in events:+ key = event.dedupe_key+ if key in seen:+ continue+ seen.add(key)+ out.append(event)+ return out+++#: Convenience for schema derivation (five-layer rule): the CHECK lists both+#: dialects build their DDL from, never retyped by hand.+EVENT_KIND_VALUES: tuple[str, ...] = tuple(kind.value for kind in EventKind)+TIME_PRECISION_VALUES: tuple[str, ...] = tuple(level.value for level in TimePrecision)+TIME_ANCHOR_VALUES: tuple[str, ...] = tuple(anchor.value for anchor in TimeAnchor)diff --git a/jarvis/ultrawiki/migrations/0004_events.sql b/jarvis/ultrawiki/migrations/0004_events.sqlnew file mode 100644index 0000000000..105a76eabe--- /dev/null+++ b/jarvis/ultrawiki/migrations/0004_events.sql@@ -0,0 +1,116 @@+-- Episodic events with absolute time anchoring (design doc 01 · uw_events,+-- doc 03 · "cross-source reconstruction").+--+-- Why a table and not a document type: an episodic question ("when did I have+-- dinner with X in Y") has a STRUCTURED answer — a date, a place, a set of+-- people — and reconstructing that from prose at read time cannot fit the+-- voice budget. The write path fuses the fragments once; the read path looks+-- one row up.+--+-- BI-TEMPORAL, and the two clocks must never be collapsed:+-- * occurred_at / occurred_end = VALID time. When it happened in the world.+-- Always absolute: a relative expression is resolved against the source+-- item's own timestamp at extraction time, so "next Friday" is never+-- stored as text and still means something two years later.+-- * recorded_at = TRANSACTION time. When the SOURCE recorded the statement+-- (the evidence item's timestamp). A Monday message about a Friday dinner+-- has two different, both correct, answers to "when" — this is what keeps+-- them apart.+-- * created_at = when this row was written. Bookkeeping, not a temporal+-- dimension: a re-derivation moves it and means nothing changed in the+-- world.+--+-- occurred_end is ALWAYS filled, from occurred_precision when the source gave+-- no end: "in March" is one event covering 31 days, not an event at midnight+-- on the 1st, and a range query that treats it as a point silently misses it.+--+-- Dialect note: this is the SQLite source of truth. `PostgresStore.+-- ddl_statements()` mirrors it (BIGSERIAL/BIGINT keys, a generated tsvector+-- instead of the FTS5 table) and DERIVES every CHECK list from the enums in+-- `jarvis/ultrawiki/events.py`; `tests/unit/ultrawiki/test_event_store.py`+-- holds the layers together (AP-4 / BUG-008).++BEGIN;++CREATE TABLE IF NOT EXISTS uw_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ -- The anchor evidence. ON DELETE CASCADE is the whole deletion story:+ -- purging a source removes its items, and every event derived from them+ -- goes with it (design doc 05, "deletion is honored end-to-end").+ item_id INTEGER NOT NULL REFERENCES uw_items(id) ON DELETE CASCADE,+ kind TEXT NOT NULL DEFAULT 'other'+ CHECK (kind IN ('meal', 'travel', 'meeting', 'purchase',+ 'milestone', 'other')),+ title TEXT NOT NULL DEFAULT '',+ summary TEXT NOT NULL DEFAULT '',+ -- Valid time.+ occurred_at TEXT NOT NULL,+ occurred_end TEXT NOT NULL,+ occurred_precision TEXT NOT NULL DEFAULT 'day'+ CHECK (occurred_precision IN ('minute', 'hour', 'day', 'week',+ 'month', 'year')),+ -- Where the absolute time came from. An event anchored merely on the+ -- item's own timestamp is worth far less than one whose source spelled+ -- the date out, and a surface that cannot tell them apart will state a+ -- guessed date as a fact.+ time_anchor TEXT NOT NULL DEFAULT 'recorded'+ CHECK (time_anchor IN ('absolute', 'relative', 'recorded')),+ -- Transaction time (the evidence item's own timestamp).+ recorded_at TEXT NOT NULL,+ place_entity_id INTEGER REFERENCES uw_entities(id) ON DELETE SET NULL,+ place_raw TEXT NOT NULL DEFAULT '',+ confidence REAL NOT NULL DEFAULT 0,+ extraction_version INTEGER NOT NULL DEFAULT 0,+ -- Stable identity of the event WITHIN its item: re-deriving an unchanged+ -- item lands on the same key, which is what makes re-extraction idempotent+ -- instead of duplicating on every pipeline pass.+ dedupe_key TEXT NOT NULL DEFAULT '',+ -- Further items corroborating the same event (cross-source fusion). The+ -- anchor stays in item_id so the citation permalink is never ambiguous.+ evidence_json TEXT NOT NULL DEFAULT '[]',+ -- The denormalized keyword card (title + date in several written forms ++ -- participants + place). Kept on the row so BOTH dialects index the same+ -- text: FTS5 here, a generated tsvector on Postgres.+ search_text TEXT NOT NULL DEFAULT '',+ created_at TEXT NOT NULL+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_events_dedupe+ ON uw_events(item_id, dedupe_key);+-- The range-query shape: "what happened between A and B", newest first.+CREATE INDEX IF NOT EXISTS idx_uw_events_occurred+ ON uw_events(occurred_at, id);+CREATE INDEX IF NOT EXISTS idx_uw_events_kind_time+ ON uw_events(kind, occurred_at);+CREATE INDEX IF NOT EXISTS idx_uw_events_item ON uw_events(item_id);+CREATE INDEX IF NOT EXISTS idx_uw_events_recorded ON uw_events(recorded_at);+CREATE INDEX IF NOT EXISTS idx_uw_events_place ON uw_events(place_entity_id);++-- Who was there. entity_id is NULLABLE on purpose: a participant the identity+-- layer refuses to resolve (ambiguous name, nothing known yet) keeps its+-- spelling here and stays searchable, instead of being dropped because the+-- store could not decide who it was.+CREATE TABLE IF NOT EXISTS uw_event_participants (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ event_id INTEGER NOT NULL REFERENCES uw_events(id) ON DELETE CASCADE,+ entity_id INTEGER REFERENCES uw_entities(id) ON DELETE SET NULL,+ display_name TEXT NOT NULL DEFAULT ''+);++CREATE INDEX IF NOT EXISTS idx_uw_event_participants_event+ ON uw_event_participants(event_id);+CREATE INDEX IF NOT EXISTS idx_uw_event_participants_entity+ ON uw_event_participants(entity_id);++-- The event keyword leg: contentless FTS5 over the card, keyed by event id+-- (delete+insert upsert, the uw_fts pattern). Separate from uw_fts because an+-- event is not an item: it has its own title, its own date and its own+-- lifetime, and mixing them would make one purge impossible to express.+CREATE VIRTUAL TABLE IF NOT EXISTS uw_event_fts USING fts5(+ event_id UNINDEXED,+ title,+ body,+ tokenize = "unicode61 remove_diacritics 2"+);++COMMIT;diff --git a/jarvis/ultrawiki/migrations/README.md b/jarvis/ultrawiki/migrations/README.mdindex e4829b0494..3d028c443f 100644--- a/jarvis/ultrawiki/migrations/README.md+++ b/jarvis/ultrawiki/migrations/README.md@@ -27,13 +27,15 @@ The contract:Shipped so far: `0001` (multi-chunk documents), `0002` (the shadow embeddingspace — widening the `uw_embeddings` key so a model switch can build the newvector 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.+identifiers, the confirmation queue and the reversible merge log), `0004`+(episodic events: the bi-temporal `uw_events` table, its participant links and+its own FTS5 keyword index). The Postgres backend applies its DDL idempotently+from `PostgresStore.ddl_statements()`, including the in-place key widening that+mirrors `0002`, the identity tables that mirror `0003` and the event tables+that mirror `0004`; 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+A migration that only ADDS tables (like `0003` and `0004`) is still the right home forthem: keeping one dialect-complete DDL per feature in one numbered file beatssplitting it between here and `schema.sql`, and the runner applies pendingfiles to fresh databases too (a new store starts at `user_version = 0`).diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.pyindex 69a38dee79..17f2ed3ef9 100644--- a/jarvis/ultrawiki/pipeline.py+++ b/jarvis/ultrawiki/pipeline.py@@ -1088,6 +1088,9 @@ class PipelineWorker:"resolution": getattr(result, "resolution", ""),"entities": list(getattr(result, "entities", []) or []),"refs": list(getattr(result, "refs", []) or []),+ # Prompt version 2. Cached alongside everything else, so a+ # re-run never pays for the events either.+ "events": list(getattr(result, "events", []) or []),}raw_json = str(getattr(result, "raw_json", "") or "")if not raw_json:@@ -1123,12 +1126,62 @@ class PipelineWorker:await self._store.distill_cache_put(content_hash, prompt_version, cache_model, raw_json)+ await self._derive_events(item, fields)return bool(await self._store.mark_stage_done(int(item["id"]), ItemState.DISTILLED, **self._claim_guard(item)))+ async def _derive_events(+ self, item: dict[str, Any], fields: dict[str, Any]+ ) -> None:+ """Turn this item's distillation into episodic events (design doc 01).++ Rides the distillation that just ran: **no model call, no network, no+ extra pass**. Purely deterministic work over data already in hand, so+ it costs a few hundred microseconds on the slowest stage of the write+ path and nothing at all on the read path.++ Never fatal. A store without the event tables (a third-party backend,+ a test fake), a derivation that raises, a database that refuses the+ write — all of them leave the item distilled and searchable. Events+ are an accelerator for episodic questions, not a precondition for+ having a memory at all.+ """+ ultrawiki = getattr(self._cfg, "ultrawiki", None)+ if not bool(getattr(ultrawiki, "events_enabled", True)):+ return+ replace = getattr(self._store, "replace_events", None)+ if not callable(replace):+ return+ try:+ from jarvis.ultrawiki.events import ( # noqa: PLC0415 — lazy (AP-26)+ derive_events,+ )++ events = derive_events(+ distill=fields,+ title=str(item.get("title") or ""),+ recorded_at=str(item.get("timestamp_utc") or ""),+ )+ if not events:+ # Still a replace: an item that USED to yield events and no+ # longer does must lose them, or a corrected source leaves the+ # old answer standing.+ await replace(int(item["id"]), [])+ return+ await replace(int(item["id"]), events)+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — events never block a distillation+ log.warning(+ "event derivation failed for item %s — the item stays "+ "distilled and searchable without episodic rows",+ item.get("id"),+ exc_info=True,+ )+# -- media enrichment ----------------------------------------------------async def _media_pass(self) -> int:diff --git a/jarvis/ultrawiki/schema.sql b/jarvis/ultrawiki/schema.sqlindex 7beaa6df75..69b8f64bb7 100644--- a/jarvis/ultrawiki/schema.sql+++ b/jarvis/ultrawiki/schema.sql@@ -170,3 +170,6 @@ CREATE TABLE IF NOT EXISTS uw_distill_cache (-- 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.+--+-- Episodic events (uw_events / uw_event_participants / uw_event_fts, design+-- doc 01) ship the same way as migrations/0004_events.sql.diff --git a/jarvis/ultrawiki/search.py b/jarvis/ultrawiki/search.pyindex e4560b00e9..4806defeaf 100644--- a/jarvis/ultrawiki/search.py+++ b/jarvis/ultrawiki/search.py@@ -3,7 +3,7 @@The read path, stage by stage (the Cerebras knowledge-base pipeline, adaptedto a single-user store):- keyword leg · vector leg (concurrent, plus the IDF probe)+ keyword leg · vector leg · event leg (concurrent, + the IDF probe)│▼RRF FUSION score(d) = Σ_legs weight / (60 + rank)@@ -30,8 +30,18 @@ lesson the normal wiki already paid for once.**Nothing here may brick a search.** Every stage degrades on its own: no/deadembedding provider => keyword answers alone; no/dead rerank provider => fusionorder stands; a store without the ranking-signal methods => neutral weights; a-failing context expansion => bare snippets. ``matched_by`` and ``rerank_score``-report honestly what actually ran.+store without the episodic tables => no event leg; a failing context expansion+=> bare snippets. ``matched_by`` and ``rerank_score`` report honestly what+actually ran.++**Events are a leg, not an oracle.** The episodic leg (design doc 01,+``uw_events``) contributes precomputed answers to "when did X happen" — each+one already carrying its absolute date, its place and its participants — but+it is fused like every other list rather than allowed to veto them. Its hits+are ranked by the event's OWN ``occurred_at``, which is the date the question+was about; when an event and its evidence item both match, the event's card+becomes the representative, because a bare fragment of chat is the worse+citation for an episodic question.Heavy/optional pieces (httpx-backed embedding + rerank adapters) are importedlazily inside the functions (AP-26); this module itself is stdlib + types only.@@ -164,6 +174,7 @@ def ranking_settings(cfg: Any) -> dict[str, float]:"recency_half_life_days": max(0.0, _float_setting(cfg, "recency_half_life_days", 180.0)),+ "event_weight": max(0.0, _float_setting(cfg, "rrf_event_weight", 1.0)),"rerank_min_score": max(0.0, _float_setting(cfg, "rerank_min_score", 4.0)),# Hard wall-clock bound on the WHOLE rerank stage (all provider# attempts together). Without it, a chain of dead/hung providers can@@ -214,9 +225,9 @@ async def hybrid_search(``timings`` (optional) is filled with the wall-clock cost of every stagethat ran, in milliseconds (``keyword_ms``, ``vector_ms`` with its- ``vector_embed_ms`` / ``vector_ann_ms`` split, ``signals_ms``,- ``rerank_ms``, ``context_ms``, ``total_ms``) — the query text itself is- never logged, only durations and counts.+ ``vector_embed_ms`` / ``vector_ann_ms`` split, ``event_ms``,+ ``signals_ms``, ``rerank_ms``, ``context_ms``, ``total_ms``) — the query+ text itself is never logged, only durations and counts.An empty/blank query returns ``[]`` without touching any leg."""@@ -227,12 +238,15 @@ async def hybrid_search(vector_coro = _vector_leg(store, cfg, query, area_id=area_id, timings=sink)if vector_timeout_s and vector_timeout_s > 0:vector_coro = _bounded_vector_leg(vector_coro, vector_timeout_s)- keyword_hits, vector_hits, signals = await asyncio.gather(+ keyword_hits, vector_hits, event_hits, signals = await asyncio.gather(_timed("keyword_ms", store.keyword_search(query, k=LEG_POOL, area_id=area_id), sink),_timed("vector_ms", vector_coro, sink),+ _timed("event_ms", _event_leg(store, cfg, query, area_id=area_id), sink),_timed("signals_ms", _term_signals(store, query), sink),)- fused = _fuse(keyword_hits, vector_hits, cfg=cfg, signals=signals)+ fused = _fuse(+ keyword_hits, vector_hits, cfg=cfg, signals=signals, event_hits=event_hits+ )if not fused:_finish_timings(sink, started, results=0)return []@@ -488,6 +502,29 @@ async def _vector_leg(# ---------------------------------------------------------------------------+async def _event_leg(+ store: Any, cfg: Any, query: str, *, area_id: str | None = None+) -> list[SearchResult]:+ """The episodic leg: precomputed events matched by their keyword card.++ Silent and empty on every store that does not have one — a third-party+ backend, a test fake, an install whose corpus predates the event tables.+ A leg that raises would take the whole search down with it for a feature+ that is, by design, an accelerator.+ """+ if ranking_settings(cfg)["event_weight"] <= 0:+ return []+ search_events = getattr(store, "search_events", None)+ if not callable(search_events):+ return []+ try:+ hits = await search_events(query, k=LEG_POOL, area_id=area_id)+ except Exception: # noqa: BLE001 — an optional leg never fails a search+ log.debug("event leg unavailable", exc_info=True)+ return []+ return list(hits or [])++def query_terms(query: str) -> list[str]:"""Distinct lowercased query tokens, order preserved."""return list(dict.fromkeys(match.group(0).lower() for match in _TOKEN_RE.finditer(query)))@@ -592,25 +629,40 @@ def _fuse(*,cfg: Any = None,signals: dict[str, float] | None = None,+ event_hits: list[SearchResult] | None = None,) -> list[SearchResult]:- """RRF-fuse the two ranked lists; merge duplicates by ``item_id``.+ """RRF-fuse the ranked lists; merge duplicates by ``item_id``.The fused score is ``sum(weight / (RRF_K + rank))`` over the legs the itemappeared in, scaled by the term-rarity signal and the age decay, plus astrictly-tiebreak-sized recency bonus derived from the candidatesthemselves (newer ``timestamp_utc`` wins ties — no extra DB query).- ``matched_by`` is the union of the contributing legs; snippet and citation- fields come from the keyword occurrence when both legs matched (its- snippet is query-specific).+ ``matched_by`` is the union of the contributing legs.++ The representative (the row whose title, snippet and timestamp survive the+ merge) is taken from the FIRST leg that produced the item, and the legs+ are walked event → keyword → vector on purpose: an event card states the+ date, the place and who was there, a keyword snippet is query-specific+ prose, and a vector hit is neither. For an episodic question that ordering+ is the difference between "on 14 March 2026 in Porto Verde with …" and a+ fragment of the chat that happened to mention it."""knobs = ranking_settings(cfg)- weights = {"keyword": knobs["keyword_weight"], "vector": knobs["vector_weight"]}+ weights = {+ "event": knobs["event_weight"],+ "keyword": knobs["keyword_weight"],+ "vector": knobs["vector_weight"],+ }half_life = knobs["recency_half_life_days"]rrf_score: dict[int, float] = {}matched: dict[int, list[str]] = {}representative: dict[int, SearchResult] = {}- for leg_name, hits in (("keyword", keyword_hits), ("vector", vector_hits)):+ for leg_name, hits in (+ ("event", list(event_hits or [])),+ ("keyword", keyword_hits),+ ("vector", vector_hits),+ ):weight = weights[leg_name]for rank, hit in enumerate(hits, start=1):rrf_score[hit.item_id] = (diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.pyindex 6aa58ea08f..4f0cee20e0 100644--- a/jarvis/ultrawiki/service.py+++ b/jarvis/ultrawiki/service.py@@ -1786,6 +1786,59 @@ class UltraWikiService:entity_id=entity_id, limit=limit)+ # -- episodic events (design doc 01 · uw_events) -------------------------++ async def list_events(+ self,+ *,+ since: str | None = None,+ until: str | None = None,+ kind: str | None = None,+ entity_id: int | None = None,+ limit: int = 50,+ offset: int = 0,+ ) -> list[dict[str, Any]]:+ """Episodic events in a time window, newest first.++ ``since``/``until`` bound the VALID time (when it happened), not the+ recorded time, and match by overlap — an event that spans a month is+ returned for a query about one day inside it.+ """+ await self.ensure_started()+ return await self._require_store().list_events(+ since=since,+ until=until,+ kind=kind,+ entity_id=entity_id,+ limit=limit,+ offset=offset,+ )++ async def events_between(+ self,+ start: str,+ end: str,+ *,+ kind: str | None = None,+ entity_id: int | None = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """The design's ``events_between`` primitive (doc 03) — cheap, LLM-free."""+ await self.ensure_started()+ return await self._require_store().events_between(+ start, end, kind=kind, entity_id=entity_id, limit=limit+ )++ async def event_detail(self, event_id: int) -> dict[str, Any] | None:+ """One event with its participants, place and evidence."""+ await self.ensure_started()+ return await self._require_store().get_event(int(event_id))++ async def event_counts(self) -> dict[str, int]:+ """How many events of each kind the store holds."""+ await self.ensure_started()+ return await self._require_store().event_counts()+# -- search --------------------------------------------------------------async def search(self, query: str, **kwargs: Any) -> Any:diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.pyindex 7fe0e7c8d8..160c0025a5 100644--- a/jarvis/ultrawiki/store.py+++ b/jarvis/ultrawiki/store.py@@ -50,6 +50,12 @@ from urllib.parse import quoteimport aiosqlite+from jarvis.ultrawiki.event_store import EventMixin+from jarvis.ultrawiki.events import (+ EVENT_KIND_VALUES,+ TIME_ANCHOR_VALUES,+ TIME_PRECISION_VALUES,+)from jarvis.ultrawiki.identity import (MERGEABLE_TIERS,EntityKind,@@ -521,7 +527,7 @@ _DISTILLED_FINGERPRINT_SQL = (# ----------------------------------------------------------------------------class UltraStore(IdentityMixin):+class UltraStore(IdentityMixin, EventMixin):"""Async SQLite store for UltraWiki (the universal reference backend).One instance = one ``aiosqlite`` connection, opened lazily on first use@@ -1052,11 +1058,16 @@ class UltraStore(IdentityMixin):async def _purge_derived(self, conn: aiosqlite.Connection, item_ids: Sequence[int]) -> None:- """Remove FTS rows, documents (cascading embeddings) and — when the- vec index is live on this connection — vector rows for *item_ids*.+ """Remove FTS rows, documents (cascading embeddings), derived events+ and — when the vec index is live on this connection — vector rows for+ *item_ids*.Vector rows a session without the extension cannot delete arereconciled on the next :meth:`_ensure_vec` (stale-row sweep).++ Events belong here for the same reason documents do: they were derived+ from text that has just changed or been tombstoned, so leaving them+ would let a sentence that no longer exists keep answering questions."""if not item_ids:return@@ -1066,6 +1077,7 @@ class UltraStore(IdentityMixin):f"DELETE FROM uw_fts WHERE item_id IN ({marks})", # noqa: S608 — placeholders onlychunk,)+ await self._ev_purge(conn, chunk)doc_rows = await self._fetchall(conn,f"SELECT id FROM uw_documents WHERE item_id IN ({marks})", # noqa: S608 — placeholders only@@ -2579,7 +2591,7 @@ class UltraStore(IdentityMixin):# ----------------------------------------------------------------------------class PostgresStore(IdentityMixin):+class PostgresStore(IdentityMixin, EventMixin):"""Postgres backend behind the same public surface as :class:`UltraStore`.- The keyword leg is a generated ``tsvector`` column with a GIN index,@@ -2598,6 +2610,10 @@ class PostgresStore(IdentityMixin):#: :meth:`IdentityMixin._id_sql` rewrites the placeholders for psycopg._IDENTITY_PARAM = "%s"+ #: The event keyword leg is the one thing the engines cannot share: a+ #: generated ``tsvector`` column here, an FTS5 side table on SQLite.+ _EVENT_DIALECT = "postgres"+def __init__(self, conn_str: str) -> None:self._conn_str = conn_strself._conn: Any = None@@ -2629,6 +2645,9 @@ class PostgresStore(IdentityMixin):merge_tiers = ", ".join(f"'{tier.value}'" for tier in sorted(MERGEABLE_TIERS, key=str))+ event_kinds = ", ".join(f"'{value}'" for value in EVENT_KIND_VALUES)+ precisions = ", ".join(f"'{value}'" for value in TIME_PRECISION_VALUES)+ anchors = ", ".join(f"'{value}'" for value in TIME_ANCHOR_VALUES)return ["CREATE TABLE IF NOT EXISTS uw_meta ("" key TEXT PRIMARY KEY, value TEXT NOT NULL)",@@ -2782,6 +2801,57 @@ class PostgresStore(IdentityMixin):" 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)",+ # Episodic events (design doc 01 · uw_events) — the Postgres twin+ # of migrations/0004_events.sql. Same columns, same CHECK lists+ # (derived from jarvis/ultrawiki/events.py), same overlap-friendly+ # occurred_at/occurred_end pair; the FTS5 side table is replaced by+ # a generated tsvector on the stored card, so both engines index+ # the identical text.+ "CREATE TABLE IF NOT EXISTS uw_events ("+ " id BIGSERIAL PRIMARY KEY,"+ " item_id BIGINT NOT NULL REFERENCES uw_items(id) ON DELETE CASCADE,"+ " kind TEXT NOT NULL DEFAULT 'other'"+ f" CHECK (kind IN ({event_kinds})),"+ " title TEXT NOT NULL DEFAULT '', summary TEXT NOT NULL DEFAULT '',"+ " occurred_at TEXT NOT NULL, occurred_end TEXT NOT NULL,"+ " occurred_precision TEXT NOT NULL DEFAULT 'day'"+ f" CHECK (occurred_precision IN ({precisions})),"+ " time_anchor TEXT NOT NULL DEFAULT 'recorded'"+ f" CHECK (time_anchor IN ({anchors})),"+ " recorded_at TEXT NOT NULL,"+ " place_entity_id BIGINT REFERENCES uw_entities(id) ON DELETE SET NULL,"+ " place_raw TEXT NOT NULL DEFAULT '',"+ " confidence DOUBLE PRECISION NOT NULL DEFAULT 0,"+ " extraction_version INTEGER NOT NULL DEFAULT 0,"+ " dedupe_key TEXT NOT NULL DEFAULT '',"+ " evidence_json TEXT NOT NULL DEFAULT '[]',"+ " search_text TEXT NOT NULL DEFAULT '',"+ " created_at TEXT NOT NULL,"+ " search_tsv tsvector GENERATED ALWAYS AS"+ " (to_tsvector('simple',"+ " coalesce(title, '') || ' ' || coalesce(search_text, ''))) STORED)",+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_events_dedupe"+ " ON uw_events(item_id, dedupe_key)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_occurred"+ " ON uw_events(occurred_at, id)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_kind_time"+ " ON uw_events(kind, occurred_at)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_item ON uw_events(item_id)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_recorded"+ " ON uw_events(recorded_at)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_place"+ " ON uw_events(place_entity_id)",+ "CREATE INDEX IF NOT EXISTS idx_uw_events_tsv"+ " ON uw_events USING GIN (search_tsv)",+ "CREATE TABLE IF NOT EXISTS uw_event_participants ("+ " id BIGSERIAL PRIMARY KEY,"+ " event_id BIGINT NOT NULL REFERENCES uw_events(id) ON DELETE CASCADE,"+ " entity_id BIGINT REFERENCES uw_entities(id) ON DELETE SET NULL,"+ " display_name TEXT NOT NULL DEFAULT '')",+ "CREATE INDEX IF NOT EXISTS idx_uw_event_participants_event"+ " ON uw_event_participants(event_id)",+ "CREATE INDEX IF NOT EXISTS idx_uw_event_participants_entity"+ " ON uw_event_participants(entity_id)",# 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@@ -3163,8 +3233,8 @@ class PostgresStore(IdentityMixin):async def _purge_derived(self, conn: Any, item_ids: Sequence[int]) -> None:"""Postgres twin of the SQLite purge: the tsvector column follows the- row automatically, documents/embeddings cascade; only pgvector rows- need an explicit delete when the index is live."""+ row automatically, documents/embeddings/event participants cascade;+ only pgvector rows need an explicit delete when the index is live."""if not item_ids:returnids = list(item_ids)@@ -3177,6 +3247,7 @@ class PostgresStore(IdentityMixin):await conn.execute("DELETE FROM uw_documents WHERE item_id = ANY(%s)", (ids,))+ await conn.execute("DELETE FROM uw_events WHERE item_id = ANY(%s)", (ids,))@staticmethoddef _item_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:diff --git a/tests/unit/ultrawiki/test_distill.py b/tests/unit/ultrawiki/test_distill.pyindex 31f2ebd907..1f572ba574 100644--- a/tests/unit/ultrawiki/test_distill.py+++ b/tests/unit/ultrawiki/test_distill.py@@ -239,7 +239,10 @@ def test_prompt_truncates_long_bodies_with_a_marker():prompt = build_distill_prompt(title="t", body=long_body, source_kind="note")assert "truncated for distillation" in prompt- assert len(prompt) < 10_000+ # The body is capped at _BODY_TRUNCATE_CHARS; the rest is the fixed+ # scaffolding (the JSON contract plus the event/time rules of prompt+ # version 2), which is what this headroom covers.+ assert len(prompt) < 12_000async def test_request_sent_to_chain_carries_the_truncated_prompt(chain_env):diff --git a/tests/unit/ultrawiki/test_event_store.py b/tests/unit/ultrawiki/test_event_store.pynew file mode 100644index 0000000000..f36f12aa82--- /dev/null+++ b/tests/unit/ultrawiki/test_event_store.py@@ -0,0 +1,492 @@+"""The event layer against a real (temporary) store — fully offline.++Everything here runs against a fresh SQLite file: no network, no credentials,+no model. What it proves:++1. the migration applies to fresh AND to pre-existing databases,+2. re-deriving an unchanged item changes nothing (idempotency),+3. events die with the evidence they were derived from — on a content change,+ on a tombstone and on a source purge,+4. participants and places link through the identity layer rather than around+ it, and an unresolvable name keeps its spelling instead of vanishing,+5. the bi-temporal window matches by OVERLAP, so a coarse event is not+ invisible to a question about a day inside it,+6. both dialects declare the same logical schema.+"""++from __future__ import annotations++import sqlite3+from datetime import UTC, datetime+from pathlib import Path++import pytest++from jarvis.ultrawiki.events import (+ DerivedEvent,+ EventKind,+ EventTime,+ TimeAnchor,+ TimePrecision,+ derive_events,+)+from jarvis.ultrawiki.store import PostgresStore, UltraStore+from jarvis.ultrawiki.types import ConsentState, RawItem++RECORDED = datetime(2026, 3, 10, 12, 0, tzinfo=UTC)+RECORDED_ISO = "2026-03-10T12:00:00Z"+++async def store(tmp_path: Path):+ instance = UltraStore(tmp_path / "ultrawiki.db")+ await instance.open()+ await instance.upsert_source("src1", connector="local-folder", label="Test source")+ await instance.set_consent("src1", ConsentState.APPROVED)+ yield instance+ await instance.close()+++async def add_item(+ store: UltraStore,+ external_id: str = "chat-1",+ *,+ body: str = "message body",+ title: str = "Chat thread",+ timestamp_utc: str = RECORDED_ISO,+) -> int:+ await store.upsert_items(+ "src1",+ [+ RawItem(+ external_id=external_id,+ body=body,+ permalink=f"app://{external_id}",+ timestamp_utc=timestamp_utc,+ title=title,+ )+ ],+ )+ row = await store.get_item_by_external_id("src1", external_id)+ assert row is not None+ return int(row["id"])+++def event(+ *,+ kind: EventKind = EventKind.MEAL,+ title: str = "Dinner with Marlow Vance",+ when: datetime = datetime(2026, 3, 13, 19, 30, tzinfo=UTC),+ precision: TimePrecision = TimePrecision.MINUTE,+ participants: tuple[str, ...] = ("Marlow Vance",),+ place: str = "Porto Verde",+) -> DerivedEvent:+ return DerivedEvent(+ kind=kind,+ title=title,+ summary="They ate together.",+ time=EventTime.build(+ when, precision, TimeAnchor.RELATIVE, recorded_at=RECORDED+ ),+ participants=participants,+ place=place,+ confidence=0.9,+ )+++def db_scalar(db_path: Path, sql: str, params: tuple = ()) -> object:+ conn = sqlite3.connect(db_path)+ try:+ return conn.execute(sql, params).fetchone()[0]+ finally:+ conn.close()+++# ---------------------------------------------------------------------------+# Schema+# ---------------------------------------------------------------------------+++async def test_the_event_migration_is_idempotent(tmp_path: Path):+ """Re-opening an existing store must be a no-op, including for a database+ created before the event tables existed."""+ path = tmp_path / "ultrawiki.db"+ first = UltraStore(path)+ await first.open()+ await first.close()++ second = UltraStore(path)+ await second.open()+ assert await second.event_counts() == {+ "meal": 0,+ "travel": 0,+ "meeting": 0,+ "purchase": 0,+ "milestone": 0,+ "other": 0,+ "total": 0,+ }+ await second.close()+++async def test_postgres_mirrors_the_event_ddl():+ """The two backends run the same logical schema (design doc 01)."""+ ddl = "\n".join(PostgresStore.ddl_statements())+ for table in ("uw_events", "uw_event_participants"):+ assert f"CREATE TABLE IF NOT EXISTS {table} (" in ddl+ # The CHECK lists are DERIVED from the enums, never retyped (AP-4).+ for kind in EventKind:+ assert f"'{kind.value}'" in ddl+ for precision in TimePrecision:+ assert f"'{precision.value}'" in ddl+ for anchor in TimeAnchor:+ assert f"'{anchor.value}'" in ddl+ # Postgres indexes the same stored card the SQLite FTS5 table indexes.+ assert "search_tsv tsvector GENERATED ALWAYS AS" in ddl+ assert "idx_uw_events_tsv" in ddl+ assert PostgresStore._EVENT_DIALECT == "postgres"+ assert UltraStore._EVENT_DIALECT == "sqlite"+++async def test_the_sqlite_check_constraints_match_the_enums(store, tmp_path):+ """The SQL file is hand-written; this is the guard that keeps it honest."""+ sql = str(+ db_scalar(+ tmp_path / "ultrawiki.db",+ "SELECT sql FROM sqlite_master WHERE name = 'uw_events'",+ )+ )+ for kind in EventKind:+ assert f"'{kind.value}'" in sql+ for precision in TimePrecision:+ assert f"'{precision.value}'" in sql+ for anchor in TimeAnchor:+ assert f"'{anchor.value}'" in sql+++# ---------------------------------------------------------------------------+# Write path+# ---------------------------------------------------------------------------+++async def test_re_deriving_an_unchanged_item_changes_nothing(store, tmp_path):+ item_id = await add_item(store)+ first = await store.replace_events(item_id, [event()])+ before = await store.list_events()++ second = await store.replace_events(item_id, [event()])+ after = await store.list_events()++ assert len(first) == len(second) == 1+ assert len(after) == 1+ assert db_scalar(tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_events") == 1+ assert (+ db_scalar(tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_event_fts") == 1+ )+ assert before[0]["title"] == after[0]["title"]+ assert before[0]["occurred_at"] == after[0]["occurred_at"]+++async def test_an_empty_replacement_removes_the_previous_events(store, tmp_path):+ """A corrected source must not leave its old answer standing."""+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ await store.replace_events(item_id, [])+ assert await store.list_events() == []+ assert (+ db_scalar(tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_event_fts") == 0+ )+++async def test_changed_content_purges_the_events_it_produced(store, tmp_path):+ """A sentence that no longer exists must not keep answering questions."""+ item_id = await add_item(store, body="dinner on friday")+ await store.replace_events(item_id, [event()])+ assert len(await store.list_events()) == 1++ await add_item(store, body="completely different text now")+ assert await store.list_events() == []+ assert (+ db_scalar(tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_event_fts") == 0+ )+++async def test_a_tombstone_takes_its_events_with_it(store):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ await store.upsert_items(+ "src1",+ [+ RawItem(+ external_id="chat-1",+ body="",+ permalink="app://chat-1",+ timestamp_utc=RECORDED_ISO,+ deleted=True,+ )+ ],+ )+ assert await store.list_events() == []+++async def test_purging_a_source_cascades_to_its_events(store, tmp_path):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ await store.delete_source("src1", purge=True)+ assert db_scalar(tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_events") == 0+ assert (+ db_scalar(+ tmp_path / "ultrawiki.db", "SELECT COUNT(*) FROM uw_event_participants"+ )+ == 0+ )+++# ---------------------------------------------------------------------------+# Identity linking+# ---------------------------------------------------------------------------+++async def test_participants_and_places_link_through_the_identity_layer(store):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])++ stored = (await store.list_events())[0]+ assert stored["participants"][0]["display_name"] == "Marlow Vance"+ person_id = stored["participants"][0]["entity_id"]+ place_id = stored["place_entity_id"]+ assert person_id is not None and place_id is not None++ person = await store.get_entity(person_id)+ place = await store.get_entity(place_id)+ assert person is not None and person["kind"] == "person"+ assert place is not None and place["kind"] == "place"+ assert stored["place"] == "Porto Verde"+++async def test_an_existing_contact_is_reused_rather_than_duplicated(store):+ """Seeded contacts are the point of the identity layer: an event with a+ known person must attach to that person, not create a second one."""+ known = await store.upsert_entity(display_name="Marlow Vance")+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])++ stored = (await store.list_events())[0]+ assert stored["participants"][0]["entity_id"] == known+ people = await store.list_people(query="Marlow")+ assert len(people) == 1+++async def test_conservative_mode_links_without_creating_entities(store):+ """The low-confidence path must not turn every mentioned name into a row+ in the People view."""+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()], create_entities=False)+ stored = (await store.list_events())[0]+ assert stored["participants"][0]["display_name"] == "Marlow Vance"+ assert stored["participants"][0]["entity_id"] is None+ assert await store.list_people() == []+++async def test_an_unresolvable_participant_keeps_its_spelling(store):+ """An ambiguous name links to nobody — but the event must still say who+ was there, or the evidence is silently lost."""+ await store.upsert_entity(display_name="Ines Halloran")+ await store.upsert_entity(display_name="Ines Halloran")+ item_id = await add_item(store)+ await store.replace_events(item_id, [event(participants=("Ines Halloran",))])++ stored = (await store.list_events())[0]+ assert stored["participants"][0]["display_name"] == "Ines Halloran"+ assert stored["participants"][0]["entity_id"] is None+++async def test_events_are_found_through_a_merged_away_entity_id(store):+ """An old citation must never go dead just because two identities fused."""+ winner = await store.upsert_entity(display_name="Marlow Vance")+ loser = await store.upsert_entity(display_name="M. Vance")+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ await store.merge_entities(winner, loser, tier="deterministic", reason="test")++ assert len(await store.list_events(entity_id=loser)) == 1+++# ---------------------------------------------------------------------------+# Read path+# ---------------------------------------------------------------------------+++async def test_the_window_matches_by_overlap_not_by_containment(store):+ """A month-precision event is the majority of what a personal corpus+ knows; containment would hide every one of them."""+ item_id = await add_item(store)+ await store.replace_events(+ item_id,+ [+ event(+ title="Porto Verde trip",+ kind=EventKind.TRAVEL,+ when=datetime(2026, 3, 1, tzinfo=UTC),+ precision=TimePrecision.MONTH,+ participants=(),+ place="",+ )+ ],+ )+ inside = await store.events_between("2026-03-14T00:00:00Z", "2026-03-14T23:59:59Z")+ outside = await store.events_between("2026-05-01T00:00:00Z", "2026-05-31T23:59:59Z")+ assert len(inside) == 1+ assert outside == []+++async def test_filters_narrow_by_kind_and_by_participant(store):+ first = await add_item(store, "chat-1")+ second = await add_item(store, "chat-2")+ await store.replace_events(first, [event()])+ await store.replace_events(+ second,+ [+ event(+ kind=EventKind.MEETING,+ title="Standup",+ participants=("Bo Reyes",),+ place="",+ )+ ],+ )++ assert len(await store.list_events(kind="meal")) == 1+ assert len(await store.list_events(kind="meeting")) == 1+ assert len(await store.list_events()) == 2++ people = {person["display_name"]: person["id"] for person in await store.list_people()}+ by_person = await store.list_events(entity_id=people["Bo Reyes"])+ assert len(by_person) == 1+ assert by_person[0]["title"] == "Standup"+++async def test_list_events_is_newest_first_and_pages(store):+ item_id = await add_item(store)+ await store.replace_events(+ item_id,+ [+ event(title="Older", when=datetime(2026, 1, 5, tzinfo=UTC), place=""),+ event(title="Newer", when=datetime(2026, 4, 5, tzinfo=UTC), place=""),+ ],+ )+ rows = await store.list_events()+ assert [row["title"] for row in rows] == ["Newer", "Older"]+ assert [row["title"] for row in await store.list_events(limit=1)] == ["Newer"]+ assert [row["title"] for row in await store.list_events(limit=1, offset=1)] == [+ "Older"+ ]+++async def test_get_event_returns_participants_and_the_evidence_permalink(store):+ item_id = await add_item(store)+ [event_id] = await store.replace_events(item_id, [event()])+ detail = await store.get_event(event_id)+ assert detail is not None+ assert detail["permalink"] == "app://chat-1"+ assert detail["item_id"] == item_id+ assert detail["evidence_item_ids"] == [item_id]+ assert detail["date_label"] == "13 March 2026 at 19:30"+ assert [p["display_name"] for p in detail["participants"]] == ["Marlow Vance"]+ assert await store.get_event(999_999) is None+++async def test_the_keyword_leg_finds_an_event_by_person_place_and_month(store):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ for query in (+ "dinner Marlow Vance",+ "Porto Verde",+ "March 2026",+ "13.03.2026",+ "Friday dinner",+ ):+ hits = await store.search_events(query)+ assert hits, query+ assert hits[0].title == "Dinner with Marlow Vance"+ assert hits[0].matched_by == ("event",)+ # The event is ranked and decayed by the date it HAPPENED, not by when+ # the message that mentioned it was written.+ assert hits[0].timestamp_utc == "2026-03-13T19:30:00Z"+ assert "13 March 2026" in hits[0].snippet+++async def test_the_keyword_leg_respects_the_time_window_and_the_kind(store):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ assert await store.search_events("dinner", since="2026-04-01T00:00:00Z") == []+ assert await store.search_events("dinner", until="2026-01-01T00:00:00Z") == []+ assert await store.search_events("dinner", kind="meeting") == []+ assert await store.search_events("dinner", kind="meal")+++async def test_the_keyword_leg_ignores_a_tombstoned_items_events(store):+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ await store.upsert_items(+ "src1",+ [+ RawItem(+ external_id="chat-1",+ body="",+ permalink="app://chat-1",+ timestamp_utc=RECORDED_ISO,+ deleted=True,+ )+ ],+ )+ assert await store.search_events("dinner") == []+++async def test_an_empty_query_never_touches_the_index(store):+ assert await store.search_events("") == []+ assert await store.search_events(" ") == []+++async def test_event_counts_are_grouped_by_kind(store):+ first = await add_item(store, "chat-1")+ second = await add_item(store, "chat-2")+ await store.replace_events(first, [event()])+ await store.replace_events(+ second, [event(kind=EventKind.TRAVEL, title="Flight", place="")]+ )+ counts = await store.event_counts()+ assert counts["meal"] == 1+ assert counts["travel"] == 1+ assert counts["total"] == 2+++# ---------------------------------------------------------------------------+# Derivation into the store (the seam the pipeline uses)+# ---------------------------------------------------------------------------+++async def test_a_distillation_payload_lands_as_an_absolute_dated_row(store):+ item_id = await add_item(store)+ events = derive_events(+ distill={+ "summary": "They agreed on dinner.",+ "events": [+ {+ "kind": "meal",+ "title": "Dinner with Marlow Vance",+ "when": "next friday at 19:30",+ "where": "Porto Verde",+ "participants": ["Marlow Vance"],+ "confidence": 0.9,+ }+ ],+ },+ title="Chat thread",+ recorded_at=RECORDED_ISO,+ )+ await store.replace_events(item_id, events)+ stored = (await store.list_events())[0]+ assert stored["occurred_at"] == "2026-03-13T19:30:00Z"+ assert stored["recorded_at"] == RECORDED_ISO+ assert stored["time_anchor"] == "relative"diff --git a/tests/unit/ultrawiki/test_events.py b/tests/unit/ultrawiki/test_events.pynew file mode 100644index 0000000000..70e35a8a30--- /dev/null+++ b/tests/unit/ultrawiki/test_events.py@@ -0,0 +1,454 @@+"""Event derivation logic — pure, offline, no store and no model.++The centrepiece is the time anchoring: design doc 01 forbids storing a+relative expression as text, so every path through this module has to end in+an absolute instant or in nothing at all. The tests below pin the three+outcomes apart (absolute / relative / recorded), pin the refusals (a bare+number is not a clock, a slash date is not parsed, an item without a+timestamp yields no event), and pin the prompt and the resolver to the same+closed vocabulary.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest++from jarvis.ultrawiki.distill import _RELATIVE_TOKENS, PROMPT_VERSION+from jarvis.ultrawiki.events import (+ EVENT_VERSION,+ MAX_EVENTS_PER_ITEM,+ RELATIVE_VOCABULARY,+ DerivedEvent,+ EventKind,+ EventTime,+ TimeAnchor,+ TimePrecision,+ coerce_kind,+ derive_events,+ format_occurred,+ iso_utc,+ parse_absolute,+ parse_instant,+ resolve_time,+ scan_absolute_dates,+ window_end,+)++#: A Tuesday, so "last friday" and "next friday" land on different days and a+#: test cannot pass by accident on a week boundary.+ANCHOR = datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC)+ANCHOR_ISO = "2026-03-10T12:00:00Z"+++def test_the_anchor_fixture_is_a_tuesday():+ """Every weekday expectation below depends on it."""+ assert ANCHOR.weekday() == 1+++# ---------------------------------------------------------------------------+# Instant parsing+# ---------------------------------------------------------------------------+++ ("raw", "expected"),+ [+ ("2026-03-14T19:30:00Z", "2026-03-14T19:30:00Z"),+ ("2026-03-14T19:30:00+02:00", "2026-03-14T17:30:00Z"),+ ("2026-03-14T19:30:00-05:00", "2026-03-15T00:30:00Z"),+ ("2026-03-14 19:30", "2026-03-14T19:30:00Z"),+ ("2026-03-14", "2026-03-14T00:00:00Z"),+ ],+)+def test_parse_instant_accepts_the_shapes_connectors_actually_emit(raw, expected):+ parsed = parse_instant(raw)+ assert parsed is not None+ assert iso_utc(parsed) == expected+++ "raw", ["", " ", "next friday", "14.03.2026", "2026-13-40", "not a date"]+)+def test_parse_instant_refuses_everything_else(raw):+ """An unparseable timestamp must never quietly become "now"."""+ assert parse_instant(raw) is None+++# ---------------------------------------------------------------------------+# Absolute expressions+# ---------------------------------------------------------------------------+++ ("raw", "instant", "precision"),+ [+ ("2026-03-14T19:30", "2026-03-14T19:30:00Z", TimePrecision.MINUTE),+ ("2026-03-14", "2026-03-14T00:00:00Z", TimePrecision.DAY),+ ("2026-03-14 at 19:30", "2026-03-14T19:30:00Z", TimePrecision.MINUTE),+ ("2026-03", "2026-03-01T00:00:00Z", TimePrecision.MONTH),+ ("2026", "2026-01-01T00:00:00Z", TimePrecision.YEAR),+ ("14.03.2026", "2026-03-14T00:00:00Z", TimePrecision.DAY),+ ("14 March 2026", "2026-03-14T00:00:00Z", TimePrecision.DAY),+ ("March 14, 2026", "2026-03-14T00:00:00Z", TimePrecision.DAY),+ ("14 March 2026 at 7pm", "2026-03-14T19:00:00Z", TimePrecision.MINUTE),+ ("14 March 2026 evening", "2026-03-14T19:00:00Z", TimePrecision.MINUTE),+ ],+)+def test_parse_absolute_covers_iso_dotted_and_written_dates(raw, instant, precision):+ parsed = parse_absolute(raw)+ assert parsed is not None+ moment, level = parsed+ assert iso_utc(moment) == instant+ assert level is precision+++def test_slash_dates_are_deliberately_not_parsed():+ """03/04/2026 is two different days on two continents.++ A personal memory that guesses which one is worse than one that stays+ quiet: the expression falls through to the relative resolver, finds+ nothing, and the event is anchored on the item's own timestamp with+ ``TimeAnchor.RECORDED`` instead of on an invented day.+ """+ assert parse_absolute("03/04/2026") is None+ resolved = resolve_time("03/04/2026", recorded_at=ANCHOR)+ assert resolved.anchor is TimeAnchor.RECORDED+++def test_a_written_date_without_a_year_is_refused():+ """Filling the year in from the anchor would be a guess, and a guessed+ year silently files a memory under the wrong twelve months."""+ assert parse_absolute("14 March") is None+++# ---------------------------------------------------------------------------+# Relative expressions+# ---------------------------------------------------------------------------+++ ("raw", "expected", "precision"),+ [+ ("today", "2026-03-10T00:00:00Z", TimePrecision.DAY),+ ("yesterday", "2026-03-09T00:00:00Z", TimePrecision.DAY),+ ("tomorrow", "2026-03-11T00:00:00Z", TimePrecision.DAY),+ ("next friday", "2026-03-13T00:00:00Z", TimePrecision.DAY),+ ("last friday", "2026-03-06T00:00:00Z", TimePrecision.DAY),+ ("this friday", "2026-03-13T00:00:00Z", TimePrecision.DAY),+ ("last monday", "2026-03-09T00:00:00Z", TimePrecision.DAY),+ ("3 days ago", "2026-03-07T00:00:00Z", TimePrecision.DAY),+ ("in 3 days", "2026-03-13T00:00:00Z", TimePrecision.DAY),+ ("2 weeks ago", "2026-02-24T00:00:00Z", TimePrecision.WEEK),+ ("in 2 months", "2026-05-10T00:00:00Z", TimePrecision.MONTH),+ ("last week", "2026-03-02T00:00:00Z", TimePrecision.WEEK),+ ("next week", "2026-03-16T00:00:00Z", TimePrecision.WEEK),+ ("last month", "2026-02-01T00:00:00Z", TimePrecision.MONTH),+ ("next month", "2026-04-01T00:00:00Z", TimePrecision.MONTH),+ ("last year", "2025-01-01T00:00:00Z", TimePrecision.YEAR),+ ("next year", "2027-01-01T00:00:00Z", TimePrecision.YEAR),+ ],+)+def test_relative_expressions_resolve_against_the_items_own_timestamp(+ raw, expected, precision+):+ resolved = resolve_time(raw, recorded_at=ANCHOR)+ assert resolved.occurred_at == expected+ assert resolved.precision is precision+ assert resolved.anchor is TimeAnchor.RELATIVE+ assert resolved.recorded_at == ANCHOR_ISO+++def test_a_relative_day_may_carry_a_clock_time():+ resolved = resolve_time("next friday at 19:30", recorded_at=ANCHOR)+ assert resolved.occurred_at == "2026-03-13T19:30:00Z"+ assert resolved.precision is TimePrecision.MINUTE+++def test_a_bare_count_is_never_read_as_a_clock_time():+ """"3 days ago" must not become 03:00 — stating an invented hour as a fact+ is exactly the failure absolute anchoring exists to prevent."""+ resolved = resolve_time("3 days ago", recorded_at=ANCHOR)+ assert resolved.occurred_at == "2026-03-07T00:00:00Z"+ assert resolved.precision is TimePrecision.DAY+++def test_a_daypart_word_sharpens_a_relative_day():+ resolved = resolve_time("tomorrow morning", recorded_at=ANCHOR)+ assert resolved.occurred_at == "2026-03-11T09:00:00Z"+++def test_an_unknown_expression_falls_back_to_the_recorded_moment():+ resolved = resolve_time("whenever we last got around to it", recorded_at=ANCHOR)+ assert resolved.occurred_at == ANCHOR_ISO+ assert resolved.anchor is TimeAnchor.RECORDED+ assert resolved.precision is TimePrecision.MINUTE+++def test_an_absolute_expression_beats_a_relative_one():+ resolved = resolve_time("2026-03-14", recorded_at=ANCHOR)+ assert resolved.anchor is TimeAnchor.ABSOLUTE+ assert resolved.occurred_at == "2026-03-14T00:00:00Z"+++def test_every_token_of_the_closed_vocabulary_actually_resolves():+ """A token the prompt may emit and the resolver does not know would+ silently degrade every event of that shape to ``RECORDED``."""+ for token in RELATIVE_VOCABULARY:+ phrase = token.replace("<weekday>", "friday").replace("<n>", "3")+ resolved = resolve_time(phrase, recorded_at=ANCHOR)+ assert resolved.anchor is TimeAnchor.RELATIVE, phrase+++def test_the_prompt_and_the_resolver_share_one_vocabulary():+ """Drift here is invisible in production: the model keeps emitting a token+ nothing resolves, and every affected event quietly loses its date."""+ assert set(_RELATIVE_TOKENS.split("|")) == set(RELATIVE_VOCABULARY)+ assert PROMPT_VERSION >= 2 # the version that introduced the events array+++# ---------------------------------------------------------------------------+# Intervals+# ---------------------------------------------------------------------------+++ ("precision", "expected_end"),+ [+ (TimePrecision.MINUTE, "2026-03-10T12:00:59Z"),+ (TimePrecision.HOUR, "2026-03-10T12:59:59Z"),+ (TimePrecision.DAY, "2026-03-10T23:59:59Z"),+ (TimePrecision.WEEK, "2026-03-16T23:59:59Z"),+ (TimePrecision.MONTH, "2026-03-31T23:59:59Z"),+ (TimePrecision.YEAR, "2026-12-31T23:59:59Z"),+ ],+)+def test_precision_defines_the_interval_the_event_occupies(precision, expected_end):+ """"In March" is one event covering 31 days, not one at midnight on the+ 1st — a range query that treats it as a point silently misses it."""+ assert iso_utc(window_end(ANCHOR, precision)) == expected_end+++def test_an_explicit_end_wins_over_the_precision_window():+ resolved = resolve_time("2026-03-14", recorded_at=ANCHOR, raw_end="2026-03-18")+ assert resolved.occurred_at == "2026-03-14T00:00:00Z"+ assert resolved.occurred_end == "2026-03-18T23:59:59Z"+++def test_an_end_before_the_start_is_ignored_rather_than_stored_backwards():+ resolved = resolve_time("2026-03-14", recorded_at=ANCHOR, raw_end="2026-03-01")+ assert resolved.occurred_end == "2026-03-14T23:59:59Z"+++ ("precision", "label"),+ [+ (TimePrecision.MINUTE, "10 March 2026 at 12:00"),+ (TimePrecision.HOUR, "10 March 2026 around 12:00"),+ (TimePrecision.DAY, "10 March 2026"),+ (TimePrecision.WEEK, "week of 10 March 2026"),+ (TimePrecision.MONTH, "March 2026"),+ (TimePrecision.YEAR, "2026"),+ ],+)+def test_one_date_is_written_one_way_everywhere(precision, label):+ assert format_occurred(ANCHOR_ISO, precision) == label+++# ---------------------------------------------------------------------------+# Derivation — the structured path+# ---------------------------------------------------------------------------+++def structured(**overrides):+ entry = {+ "kind": "meal",+ "title": "Dinner with Marlow Vance",+ "when": "next friday at 19:30",+ "where": "Porto Verde",+ "participants": ["Marlow Vance"],+ "confidence": 0.9,+ }+ entry.update(overrides)+ return {"summary": "They agreed on dinner.", "events": [entry]}+++def test_a_structured_event_keeps_its_kind_place_and_participants():+ events = derive_events(+ distill=structured(), title="Chat thread", recorded_at=ANCHOR_ISO+ )+ assert len(events) == 1+ event = events[0]+ assert event.kind is EventKind.MEAL+ assert event.title == "Dinner with Marlow Vance"+ assert event.place == "Porto Verde"+ assert event.participants == ("Marlow Vance",)+ assert event.time.occurred_at == "2026-03-13T19:30:00Z"+ assert event.time.anchor is TimeAnchor.RELATIVE+ assert event.time.recorded_at == ANCHOR_ISO+ assert event.extraction_version == EVENT_VERSION+++def test_an_unknown_kind_degrades_to_other_instead_of_being_dropped():+ events = derive_events(distill=structured(kind="wedding"), recorded_at=ANCHOR_ISO)+ assert events[0].kind is EventKind.OTHER+ assert coerce_kind(None) is EventKind.OTHER+++def test_an_item_without_a_parseable_timestamp_yields_nothing():+ """No anchor, no event: an episodic row floating in an unknown year is+ worse than no row at all."""+ assert derive_events(distill=structured(), recorded_at="") == []+ assert derive_events(distill=structured(), recorded_at="whenever") == []+++def test_an_empty_entry_is_dropped_and_a_missing_array_yields_nothing():+ assert derive_events(distill={"events": [{}]}, recorded_at=ANCHOR_ISO) == []+ assert derive_events(distill={"events": "nonsense"}, recorded_at=ANCHOR_ISO) == []+ assert derive_events(distill=None, recorded_at=ANCHOR_ISO) == []+ assert derive_events(distill={}, recorded_at=ANCHOR_ISO) == []+++def test_the_per_item_event_cap_holds():+ payload = {+ "events": [+ {"title": f"Meeting {index}", "when": f"2026-03-{index + 1:02d}"}+ for index in range(20)+ ]+ }+ events = derive_events(distill=payload, recorded_at=ANCHOR_ISO)+ assert len(events) == MAX_EVENTS_PER_ITEM+++def test_identical_entries_collapse_to_one_event():+ payload = {"events": [structured()["events"][0], structured()["events"][0]]}+ assert len(derive_events(distill=payload, recorded_at=ANCHOR_ISO)) == 1+++def test_the_participant_list_is_capped_and_deduplicated():+ payload = structured(participants=["Ines Halloran", "ines halloran", "Bo Reyes"])+ events = derive_events(distill=payload, recorded_at=ANCHOR_ISO)+ assert events[0].participants == ("Ines Halloran", "Bo Reyes")+++def test_confidence_is_clamped_rather_than_trusted():+ assert derive_events(distill=structured(confidence=7), recorded_at=ANCHOR_ISO)[+ 0+ ].confidence == 1.0+ assert derive_events(distill=structured(confidence="junk"), recorded_at=ANCHOR_ISO)[+ 0+ ].confidence == pytest.approx(0.5)+++# ---------------------------------------------------------------------------+# Derivation — the legacy path (a distillation from before the events array)+# ---------------------------------------------------------------------------+++def test_a_pre_v2_distillation_still_yields_an_event_when_it_states_a_date():+ """The whole point of the legacy path: a corpus distilled under prompt+ version 1 gains episodic rows WITHOUT being re-distilled — it reads only+ text that is already stored."""+ legacy = {+ "question": "When did the Porto Verde trip start?",+ "summary": "The trip began on 2026-02-02 and ran for a week.",+ "resolution": "",+ "entities": ["Marlow Vance", "Porto Verde"],+ }+ events = derive_events(distill=legacy, recorded_at=ANCHOR_ISO)+ assert len(events) == 1+ assert events[0].time.occurred_at == "2026-02-02T00:00:00Z"+ assert events[0].time.anchor is TimeAnchor.ABSOLUTE+ assert events[0].kind is EventKind.OTHER # no kind can be known without a lexicon+ assert events[0].participants == ("Marlow Vance", "Porto Verde")+ assert events[0].confidence < 0.5 # honest: a date and some names, no story+++def test_a_pre_v2_distillation_without_a_date_yields_nothing():+ """Otherwise every one of a quarter-million items would become an event."""+ legacy = {+ "question": "What did they decide about the deployment?",+ "summary": "They agreed to ship on the usual cadence.",+ "entities": ["Bo Reyes"],+ }+ assert derive_events(distill=legacy, recorded_at=ANCHOR_ISO) == []+++def test_the_legacy_path_is_capped_at_two_dates():+ legacy = {+ "summary": "2026-01-01 then 2026-02-02 then 2026-03-03 then 2026-04-04.",+ }+ assert len(derive_events(distill=legacy, recorded_at=ANCHOR_ISO)) == 2+++def test_scan_absolute_dates_keeps_source_order_and_drops_duplicates():+ found = scan_absolute_dates("first 2026-02-02, again 2026-02-02, then 14.03.2026")+ assert [iso_utc(moment) for moment, _ in found] == [+ "2026-02-02T00:00:00Z",+ "2026-03-14T00:00:00Z",+ ]+++# ---------------------------------------------------------------------------+# The stored card + dedupe identity+# ---------------------------------------------------------------------------+++def make_event(**overrides) -> DerivedEvent:+ values = {+ "kind": EventKind.MEAL,+ "title": "Dinner with Marlow Vance",+ "summary": "They ate together.",+ "time": EventTime.build(+ datetime(2026, 3, 13, 19, 30, tzinfo=UTC),+ TimePrecision.MINUTE,+ TimeAnchor.RELATIVE,+ recorded_at=ANCHOR,+ ),+ "participants": ("Marlow Vance",),+ "place": "Porto Verde",+ }+ values.update(overrides)+ return DerivedEvent(**values)+++def test_the_search_card_carries_the_date_in_several_written_forms():+ """A user asks "in March", "on the 13th" and "2026" for the same event."""+ card = make_event().search_text()+ for fragment in (+ "Dinner with Marlow Vance",+ "13 March 2026 at 19:30",+ "2026-03-13",+ "13.03.2026",+ "Friday",+ "March",+ "2026",+ "Porto Verde",+ ):+ assert fragment in card, fragment+++def test_the_dedupe_key_is_stable_across_re_derivations():+ assert make_event().dedupe_key == make_event().dedupe_key+++ "change",+ [+ {"title": "Lunch with Marlow Vance"},+ {"place": "Halloran Bay"},+ {"participants": ("Bo Reyes",)},+ {"kind": EventKind.MEETING},+ ],+)+def test_a_different_event_gets_a_different_dedupe_key(change):+ assert make_event().dedupe_key != make_event(**change).dedupe_key+++def test_to_dict_exposes_both_clocks_and_the_honest_anchor():+ payload = make_event().to_dict()+ assert payload["occurred_at"] == "2026-03-13T19:30:00Z"+ assert payload["recorded_at"] == ANCHOR_ISO+ assert payload["time_anchor"] == "relative"+ assert payload["date_label"] == "13 March 2026 at 19:30"diff --git a/tests/unit/ultrawiki/test_events_e2e.py b/tests/unit/ultrawiki/test_events_e2e.pynew file mode 100644index 0000000000..5d38ed0a83--- /dev/null+++ b/tests/unit/ultrawiki/test_events_e2e.py@@ -0,0 +1,514 @@+"""North star: "when did I have dinner with <person> in <city>" is answerable.++The question the whole episodic layer exists for is one no single row answers+(design doc 03, "cross-source reconstruction"): the chat says *"19:30?"*, the+calendar says *"Dinner w/ Marlow Vance"*, and the photo's caption says Porto+Verde. This test builds exactly that corpus across three sources, runs the+real staged pipeline over it with an offline distiller, and then asks the real+search path the real question.++Fixture names are deliberately invented (Marlow Vance, Bo Reyes, Porto Verde,+Halloran Bay) so nothing here can be mistaken for a real person, place or+product.++Everything is offline: a fake embedding backend, a fake distiller, no network,+no credentials, no model. The search runs with NO embedding provider+configured at all — the honest floor of an install that holds one key or none,+where the keyword and event legs are the whole read path.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.ultrawiki.pipeline import PipelineWorker+from jarvis.ultrawiki.search import hybrid_search+from jarvis.ultrawiki.store import UltraStore+from jarvis.ultrawiki.types import ConsentState, ItemState, RawItem++VECTOR = [0.1, 0.2, 0.3]+QUESTION = "when did I have dinner with Marlow Vance in Porto Verde"++#: The distillation gate, stated explicitly: this worker uses an INJECTED+#: distiller, so the production credential probe must never run — a test whose+#: outcome depends on the host's keys is the AP-23 trap.+DISTILL_READY = lambda: (True, "") # noqa: E731 — a one-line test seam+++# ---------------------------------------------------------------------------+# The corpus+# ---------------------------------------------------------------------------+++class Source:+ """One fixture source: its items and the distillation each item produces."""++ def __init__(self, source_id: str, label: str) -> None:+ self.source_id = source_id+ self.label = label+ self.items: list[RawItem] = []+++CHAT = Source("chat", "Message archive")+CALENDAR = Source("calendar", "Calendar export")+PHOTOS = Source("photos", "Photo library")++CHAT.items = [+ RawItem(+ external_id="thread-2026-03-10",+ title="Thread with Marlow Vance",+ body=(+ "Marlow: are we still on for dinner on friday?\n"+ "Me: yes — 19:30 works. Porto Verde, the place by the water?\n"+ "Marlow: perfect."+ ),+ permalink="app://chat/thread-2026-03-10",+ timestamp_utc="2026-03-10T12:00:00Z",+ ),+ RawItem(+ external_id="thread-2025-11-02",+ title="Thread with Bo Reyes",+ body="Bo: lunch tomorrow in Halloran Bay? Me: works for me.",+ permalink="app://chat/thread-2025-11-02",+ timestamp_utc="2025-11-02T09:00:00Z",+ ),+ RawItem(+ external_id="thread-invoice",+ title="Invoice question",+ body="Could you resend the invoice as a PDF? The last one would not open.",+ permalink="app://chat/thread-invoice",+ timestamp_utc="2026-02-18T08:30:00Z",+ ),+]++CALENDAR.items = [+ RawItem(+ external_id="cal-88",+ title="Dinner w/ Marlow Vance",+ body="Table for two, Porto Verde.",+ permalink="app://calendar/cal-88",+ timestamp_utc="2026-03-13T18:00:00Z",+ )+]++PHOTOS.items = [+ RawItem(+ external_id="img-4711",+ title="IMG_4711.jpg",+ body="Two plates on a terrace at dusk.",+ permalink="app://photos/img-4711",+ timestamp_utc="2026-03-13T20:14:00Z",+ metadata={"place": "Porto Verde"},+ )+]++#: What the distiller returns per item. The ``events`` arrays are the shape+#: prompt version 2 asks for — note that only ONE of them states an absolute+#: date: the chat says "next friday" and the photo says "yesterday", and the+#: resolver has to turn both into the same evening.+DISTILLATIONS: dict[str, dict[str, Any]] = {+ "thread-2026-03-10": {+ "question": "When is dinner with Marlow Vance?",+ "summary": "They agreed on dinner at Porto Verde.",+ "resolution": "Friday at 19:30.",+ "entities": ["Marlow Vance", "Porto Verde"],+ "events": [+ {+ "kind": "meal",+ "title": "Dinner with Marlow Vance",+ "when": "next friday at 19:30",+ "where": "Porto Verde",+ "participants": ["Marlow Vance"],+ "confidence": 0.9,+ }+ ],+ },+ "cal-88": {+ "question": "What was scheduled on that evening?",+ "summary": "A dinner reservation for two.",+ "resolution": "",+ "entities": ["Marlow Vance", "Porto Verde"],+ "events": [+ {+ "kind": "meal",+ "title": "Dinner with Marlow Vance",+ "when": "2026-03-13T19:30",+ "where": "Porto Verde",+ "participants": ["Marlow Vance"],+ "confidence": 0.95,+ }+ ],+ },+ "img-4711": {+ "question": "Where was this photo taken?",+ "summary": "A terrace at dusk with two plates.",+ "resolution": "",+ "entities": ["Porto Verde"],+ "events": [+ # A caption states no time at all, so this one is anchored on the+ # photo's own capture timestamp: the third and weakest anchor kind,+ # and the reason `time_anchor` is a stored column.+ {+ "kind": "meal",+ "title": "Dinner with Marlow Vance",+ "when": "",+ "where": "Porto Verde",+ "participants": ["Marlow Vance"],+ "confidence": 0.6,+ }+ ],+ },+ "thread-2025-11-02": {+ "question": "When is lunch with Bo Reyes?",+ "summary": "They agreed on lunch in Halloran Bay.",+ "resolution": "",+ "entities": ["Bo Reyes", "Halloran Bay"],+ "events": [+ {+ "kind": "meal",+ "title": "Lunch with Bo Reyes",+ "when": "tomorrow",+ "where": "Halloran Bay",+ "participants": ["Bo Reyes"],+ "confidence": 0.8,+ }+ ],+ },+ "thread-invoice": {+ "question": "How should the invoice be resent?",+ "summary": "A request to resend an invoice as a PDF.",+ "resolution": "",+ "entities": [],+ "events": [],+ },+}+++# ---------------------------------------------------------------------------+# Offline doubles+# ---------------------------------------------------------------------------+++class FakeEmbeddingBackend:+ name = "fake"++ def ready(self) -> tuple[bool, str]:+ return True, ""++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ return [list(VECTOR) for _ in texts]+++class ScriptedDistiller:+ """Returns the fixture distillation and counts every call it received."""++ def __init__(self) -> None:+ self.calls: list[str] = []++ async def __call__(+ self, cfg: Any, *, title: str, body: str, source_kind: str+ ) -> Any:+ for external_id, payload in DISTILLATIONS.items():+ source = next(+ (+ item+ for src in (CHAT, CALENDAR, PHOTOS)+ for item in src.items+ if item.external_id == external_id+ ),+ None,+ )+ if source is not None and source.title == title:+ self.calls.append(external_id)+ return SimpleNamespace(raw_json="", **payload)+ raise AssertionError(f"no fixture distillation for {title!r}")+++def pipeline_cfg() -> SimpleNamespace:+ return SimpleNamespace(+ ultrawiki=SimpleNamespace(+ enabled=True,+ db_backend="sqlite",+ embedding_provider="fake",+ embedding_model="fake-model",+ distill_provider="",+ distill_model="",+ rerank_provider="",+ ollama_endpoint="",+ events_enabled=True,+ ),+ memory=SimpleNamespace(data_dir="unused"),+ brain=SimpleNamespace(primary=""),+ )+++def read_cfg() -> SimpleNamespace:+ """A keyless install: no embedding provider, no reranker.++ The event leg has to carry this question on its own here — which is the+ universality claim worth testing, because most downloaders will never+ configure an embedding slot at all.+ """+ return SimpleNamespace(+ ultrawiki=SimpleNamespace(+ enabled=True,+ embedding_provider="",+ embedding_model="",+ rerank_provider="",+ rerank_model="",+ rerank_min_score=4.0,+ rrf_keyword_weight=1.0,+ rrf_vector_weight=1.0,+ rrf_event_weight=1.0,+ recency_half_life_days=180.0,+ ollama_endpoint="",+ )+ )+++async def corpus(tmp_path: Path):+ """The three-source corpus, fully ingested through the real pipeline."""+ store = UltraStore(tmp_path / "ultrawiki.db")+ await store.open()+ for source in (CHAT, CALENDAR, PHOTOS):+ await store.upsert_source(+ source.source_id, connector="local-folder", label=source.label+ )+ await store.set_consent(source.source_id, ConsentState.APPROVED)+ await store.upsert_items(source.source_id, source.items)++ distiller = ScriptedDistiller()+ worker = PipelineWorker(+ store,+ pipeline_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=distiller,+ distill_ready_fn=DISTILL_READY,+ )+ for _ in range(6): # three stages over five items, with room to spare+ if not await worker.run_once():+ break+ counts = await store.counts()+ assert counts.distilled == 5, f"corpus did not fully distil: {counts}"+ yield store, distiller+ await store.close()+++# ---------------------------------------------------------------------------+# The north star+# ---------------------------------------------------------------------------+++async def test_the_episodic_question_is_answered_with_date_place_and_people(corpus):+ """The whole point, end to end: ask the question, get the evening back."""+ store, _ = corpus+ results = await hybrid_search(store, read_cfg(), QUESTION, k=5)+ assert results, "the corpus answered nothing at all"++ top = results[0]+ assert "event" in top.matched_by+ assert top.title == "Dinner with Marlow Vance"+ # The date, the place and the person are IN the returned citation — the+ # surface never has to go back to the database to say them out loud.+ assert "13 March 2026 at 19:30" in top.snippet+ assert "Porto Verde" in top.snippet+ assert "Marlow Vance" in top.snippet+ assert top.permalink.startswith("app://")+ assert top.timestamp_utc == "2026-03-13T19:30:00Z"+++async def test_three_sources_agree_on_one_evening(corpus):+ """Cross-source reconstruction: the chat's "next friday", the calendar's+ ISO timestamp and the photo's silent capture time all had to resolve to+ the same absolute evening for this to hold."""+ store, _ = corpus+ events = await store.events_between(+ "2026-03-13T00:00:00Z", "2026-03-13T23:59:59Z"+ )+ assert len(events) == 3+ assert {event["source_id"] for event in events} == {"chat", "calendar", "photos"}+ for event in events:+ assert event["kind"] == "meal"+ assert event["place"] == "Porto Verde"+ assert [p["display_name"] for p in event["participants"]] == ["Marlow Vance"]+ assert event["occurred_at"].startswith("2026-03-13")++ # And each one is honest about WHERE its date came from — all three+ # anchors are represented, so a surface can weigh them differently instead+ # of reading a guessed timestamp as a stated fact.+ assert {event["time_anchor"] for event in events} == {+ "relative",+ "absolute",+ "recorded",+ }+++async def test_the_three_sources_resolve_to_one_person(corpus):+ """Without identity linking, "who was there" would be three strangers who+ happen to share a name."""+ store, _ = corpus+ events = await store.events_between(+ "2026-03-13T00:00:00Z", "2026-03-13T23:59:59Z"+ )+ entity_ids = {event["participants"][0]["entity_id"] for event in events}+ assert len(entity_ids) == 1+ (person_id,) = entity_ids+ assert person_id is not None+ assert len(await store.list_events(entity_id=person_id)) == 3+++async def test_the_other_meal_ranks_below_the_real_answer(corpus):+ """A near-miss in the same corpus — also a meal, also with a person, also+ in a city — must lose, and lose to all three corroborating rows.++ Deliberately a RANKING assertion, not an exclusion one: the keyword leg+ ORs its tokens, so "with"/"in"/"dinner" match the near-miss too, and+ hard-filtering candidates on content is the AP-27 trap. What has to hold+ is that consensus wins.+ """+ store, _ = corpus+ window = await store.events_between(+ "2026-03-13T00:00:00Z", "2026-03-13T23:59:59Z"+ )+ assert all("Bo Reyes" not in event["title"] for event in window)++ results = await hybrid_search(store, read_cfg(), QUESTION, k=5)+ corroborated = [+ index+ for index, hit in enumerate(results)+ if hit.title == "Dinner with Marlow Vance"+ and {"event", "keyword"} <= set(hit.matched_by)+ ]+ near_miss = [+ index+ for index, hit in enumerate(results)+ if "Halloran Bay" in hit.snippet or "Bo Reyes" in hit.title+ ]+ assert len(corroborated) == 2, "two sources should agree on the answer"+ assert near_miss, "the near-miss should be a candidate, just a losing one"+ # Every row two legs agreed on outranks it. The photo, which only the+ # event leg matched, sits BELOW the near-miss two legs found — that is the+ # RRF contract working as designed (design doc 01, principle 5: consensus+ # beats a single strong vote), not a defect.+ assert min(near_miss) > max(corroborated)++ # It IS in the store, under its own resolved date ("tomorrow" from the+ # 2nd of November) — a wrong split is repairable, a wrong answer is not.+ other = await store.events_between("2025-11-03T00:00:00Z", "2025-11-03T23:59:59Z")+ assert [event["title"] for event in other] == ["Lunch with Bo Reyes"]+++async def test_an_item_that_records_no_event_produces_none(corpus):+ """Most items record no event. One that produced one anyway would make the+ timeline useless within a week."""+ store, _ = corpus+ item = await store.get_item_by_external_id("chat", "thread-invoice")+ assert item is not None+ assert await store.list_events(item_id=int(item["id"])) == []+ assert (await store.event_counts())["total"] == 4+++async def test_the_read_path_calls_no_model_at_all(corpus):+ """Token-efficiency is a design property, not a hope: the event rows were+ paid for once, on the write path, inside the distillation that had to run+ anyway. Searching them must add nothing."""+ store, distiller = corpus+ before = len(distiller.calls)+ assert before == 5 # exactly one distillation per item, no second pass++ await hybrid_search(store, read_cfg(), QUESTION, k=5)+ await store.events_between("2026-03-01T00:00:00Z", "2026-03-31T23:59:59Z")+ await store.search_events(QUESTION)+ assert len(distiller.calls) == before+++async def test_the_unsolicited_surface_gets_the_same_answer(corpus):+ """The ambient path passes ``enforce_floor=True`` (design doc 03). With no+ reranker configured the candidates arrive ungraded and are passed through+ for the caller's own deterministic gate — what must NOT happen is the+ event silently disappearing from that path."""+ store, _ = corpus+ results = await hybrid_search(+ store, read_cfg(), QUESTION, k=5, enforce_floor=True, rerank=False+ )+ assert results+ assert "event" in results[0].matched_by+ assert results[0].rerank_score is None+++async def test_a_re_run_of_the_pipeline_does_not_duplicate_the_timeline(corpus):+ """Idempotency across the whole ladder, not just the store method."""+ store, distiller = corpus+ before = await store.event_counts()++ worker = PipelineWorker(+ store,+ pipeline_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=distiller,+ distill_ready_fn=DISTILL_READY,+ )+ await worker.run_once()+ assert await store.event_counts() == before+++async def test_the_event_leg_degrades_silently_when_it_is_switched_off(corpus):+ """``rrf_event_weight = 0`` silences the leg without touching the rows —+ every other leg keeps answering."""+ store, _ = corpus+ cfg = read_cfg()+ cfg.ultrawiki.rrf_event_weight = 0.0+ results = await hybrid_search(store, cfg, QUESTION, k=5)+ assert results # the keyword leg still answers+ assert all("event" not in hit.matched_by for hit in results)+ assert (await store.event_counts())["total"] == 4+++async def test_events_disappear_with_the_evidence_they_came_from(corpus):+ """Deletion is honored end-to-end (design doc 05)."""+ store, _ = corpus+ await store.delete_source("photos", purge=True)+ events = await store.events_between(+ "2026-03-13T00:00:00Z", "2026-03-13T23:59:59Z"+ )+ assert {event["source_id"] for event in events} == {"chat", "calendar"}++ results = await hybrid_search(store, read_cfg(), QUESTION, k=5)+ assert all(hit.source_id != "photos" for hit in results)+++async def test_an_item_reaches_distilled_even_when_derivation_explodes(+ tmp_path: Path, monkeypatch+):+ """Events are an accelerator, not a precondition for having a memory."""+ store = UltraStore(tmp_path / "ultrawiki.db")+ await store.open()+ await store.upsert_source("chat", connector="local-folder", label="Chat")+ await store.set_consent("chat", ConsentState.APPROVED)+ await store.upsert_items("chat", [CHAT.items[0]])++ async def boom(*args: Any, **kwargs: Any) -> None:+ raise RuntimeError("the event tables are on fire")++ monkeypatch.setattr(store, "replace_events", boom)+ worker = PipelineWorker(+ store,+ pipeline_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=ScriptedDistiller(),+ distill_ready_fn=DISTILL_READY,+ )+ for _ in range(4):+ if not await worker.run_once():+ break++ item = await store.get_item_by_external_id("chat", "thread-2026-03-10")+ assert item is not None+ assert item["state"] == ItemState.DISTILLED.value+ assert await store.keyword_search("Porto Verde")+ await store.close()diff --git a/tests/unit/ultrawiki/test_identity_parity.py b/tests/unit/ultrawiki/test_identity_parity.pyindex bc0054351d..2b32df54ab 100644--- a/tests/unit/ultrawiki/test_identity_parity.py+++ b/tests/unit/ultrawiki/test_identity_parity.py@@ -98,7 +98,12 @@ def test_both_dialects_declare_the_same_identity_tables_and_indexes():def test_migration_is_numbered_after_the_current_head():- """Forward-only: a new file never renumbers or rewrites a shipped one."""+ """Forward-only: a new file never renumbers or rewrites a shipped one.++ The numbers must stay gapless and strictly ascending, and the identity+ layer must keep the slot it shipped in — later features append, they never+ renumber a file thousands of installs have already applied.+ """directory = Path(jarvis.ultrawiki.__file__).parent / "migrations"numbers = sorted(int(path.name[:4])@@ -106,4 +111,6 @@ def test_migration_is_numbered_after_the_current_head():if re.match(r"^\d{4}_", path.name))assert numbers == list(range(1, len(numbers) + 1))- assert numbers[-1] == 3+ assert [path.name for path in directory.glob("0003_*.sql")] == [+ "0003_identity.sql"+ ]diff --git a/tests/unit/ultrawiki/test_search.py b/tests/unit/ultrawiki/test_search.pyindex 9d584dde1b..6457eb6e1b 100644--- a/tests/unit/ultrawiki/test_search.py+++ b/tests/unit/ultrawiki/test_search.py@@ -139,6 +139,7 @@ def make_cfg(**overrides) -> SimpleNamespace:"rerank_min_score": 4.0,"rrf_keyword_weight": 1.0,"rrf_vector_weight": 1.0,+ "rrf_event_weight": 1.0,"recency_half_life_days": 180.0,"ollama_endpoint": "http://localhost:11434",}@@ -543,6 +544,7 @@ def test_search_status_reports_the_live_ranking_knobs():make_cfg(rrf_keyword_weight=2.0,rrf_vector_weight=0.5,+ rrf_event_weight=0.25,recency_half_life_days=30,rerank_min_score=6,rerank_timeout_s=8,@@ -552,6 +554,7 @@ def test_search_status_reports_the_live_ranking_knobs():assert status["ranking"] == {"keyword_weight": 2.0,"vector_weight": 0.5,+ "event_weight": 0.25,"recency_half_life_days": 30.0,"rerank_min_score": 6.0,"rerank_timeout_s": 8.0,