|
| 1 | +"""``kb.timeline`` — chronological trajectory of an entity (vouchdev/vouch#313). |
| 2 | +
|
| 3 | +``kb.read_entity`` returns an entity and its claims as a flat set; ``kb.neighbors`` |
| 4 | +expands graph adjacency at a point in time. Neither answers "what did the KB |
| 5 | +learn about this entity, *in what order*?" — a trajectory. The raw material is |
| 6 | +already on disk: ``Claim`` and ``Relation`` carry ``created_at``, and decision |
| 7 | +time is recoverable from the append-only ``audit.log.jsonl``. This orders an |
| 8 | +entity's approved claims and relations along that time axis. |
| 9 | +
|
| 10 | +Pure read. It never proposes, approves, or writes — a viewport over |
| 11 | +already-reviewed artifacts, exactly like ``read_entity`` / ``neighbors``. Only |
| 12 | +*approved* durable artifacts are read (``list_claims`` / ``list_relations``); |
| 13 | +pending proposals never appear. All ordering logic lives here, not in |
| 14 | +``storage.py``, which stays pure I/O. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from datetime import UTC, datetime |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from .audit import read_events |
| 23 | +from .metrics import _APPROVE_RE |
| 24 | +from .models import Claim, Relation |
| 25 | +from .storage import KBStore |
| 26 | + |
| 27 | +# Ordering axes. ``effective`` orders by the artifact's own ``created_at`` (when |
| 28 | +# the fact entered the KB); ``decided`` orders by the moment the proposal that |
| 29 | +# produced it was approved, recovered from the audit log. |
| 30 | +ORDER_EFFECTIVE = "effective" |
| 31 | +ORDER_DECIDED = "decided" |
| 32 | +ORDERS = (ORDER_EFFECTIVE, ORDER_DECIDED) |
| 33 | + |
| 34 | + |
| 35 | +class TimelineError(ValueError): |
| 36 | + """User-visible bad input (e.g. an unknown ``order``).""" |
| 37 | + |
| 38 | + |
| 39 | +def _as_utc(dt: datetime | None) -> datetime | None: |
| 40 | + if dt is None: |
| 41 | + return None |
| 42 | + return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC) |
| 43 | + |
| 44 | + |
| 45 | +def _iso(dt: datetime | None) -> str | None: |
| 46 | + return dt.isoformat() if dt is not None else None |
| 47 | + |
| 48 | + |
| 49 | +def _decided_map(store: KBStore) -> dict[str, datetime]: |
| 50 | + """artifact id -> approval time, from the authoritative audit stream. |
| 51 | +
|
| 52 | + ``proposals.approve`` logs an approve event with ``object_ids = [proposal_id, |
| 53 | + result_id]``; the event's ``created_at`` is the decision time. Artifacts |
| 54 | + written outside the proposal path (rare, e.g. a seeded starter KB) simply |
| 55 | + have no entry and fall back to their ``created_at``. |
| 56 | + """ |
| 57 | + out: dict[str, datetime] = {} |
| 58 | + for ev in read_events(store.kb_dir): |
| 59 | + if _APPROVE_RE.match(ev.event) and len(ev.object_ids) >= 2: |
| 60 | + ts = _as_utc(ev.created_at) |
| 61 | + if ts is not None: |
| 62 | + out[ev.object_ids[1]] = ts |
| 63 | + return out |
| 64 | + |
| 65 | + |
| 66 | +def _claim_summary(c: Claim) -> str: |
| 67 | + return str(c.text).strip()[:120] or "—" |
| 68 | + |
| 69 | + |
| 70 | +def _relation_summary(r: Relation) -> str: |
| 71 | + return f"{r.source} {r.relation.value} {r.target}" |
| 72 | + |
| 73 | + |
| 74 | +def build_timeline( |
| 75 | + store: KBStore, |
| 76 | + entity_id: str, |
| 77 | + *, |
| 78 | + since: datetime | None = None, |
| 79 | + until: datetime | None = None, |
| 80 | + order: str = ORDER_EFFECTIVE, |
| 81 | + types: list[str] | None = None, |
| 82 | + limit: int | None = None, |
| 83 | +) -> dict[str, Any]: |
| 84 | + """Order an entity's approved claims + relations along a time axis. |
| 85 | +
|
| 86 | + Entries are ``{when, kind, id, summary, status}``, oldest first |
| 87 | + (most-recent-last). ``status`` is the claim's current :class:`ClaimStatus` |
| 88 | + (a superseded/archived claim still appears, flagged); relations have no |
| 89 | + status, so it is ``None``. When ``limit`` is set, the most recent ``limit`` |
| 90 | + entries are kept, still in chronological order. Raises |
| 91 | + :class:`~vouch.storage.ArtifactNotFoundError` if the entity does not exist. |
| 92 | + """ |
| 93 | + if order not in ORDERS: |
| 94 | + raise TimelineError(f"order must be one of {ORDERS}, got {order!r}") |
| 95 | + if limit is not None and limit < 0: |
| 96 | + raise TimelineError("limit must be >= 0") |
| 97 | + since = _as_utc(since) |
| 98 | + until = _as_utc(until) |
| 99 | + |
| 100 | + entity = store.get_entity(entity_id) # raises ArtifactNotFoundError |
| 101 | + |
| 102 | + want = {t.strip() for t in types if t.strip()} if types else None |
| 103 | + decided = _decided_map(store) if order == ORDER_DECIDED else {} |
| 104 | + |
| 105 | + def when_for(artifact_id: str, created: datetime | None) -> datetime | None: |
| 106 | + eff = _as_utc(created) |
| 107 | + if order == ORDER_DECIDED: |
| 108 | + return decided.get(artifact_id) or eff |
| 109 | + return eff |
| 110 | + |
| 111 | + rows: list[dict[str, Any]] = [] |
| 112 | + |
| 113 | + for c in store.list_claims(): |
| 114 | + if entity_id not in c.entities: |
| 115 | + continue |
| 116 | + # type filter: a claim matches on its ClaimType, or the generic "claim". |
| 117 | + if want is not None and c.type.value not in want and "claim" not in want: |
| 118 | + continue |
| 119 | + rows.append( |
| 120 | + { |
| 121 | + "_when": when_for(c.id, c.created_at), |
| 122 | + "kind": "claim", |
| 123 | + "id": c.id, |
| 124 | + "summary": _claim_summary(c), |
| 125 | + "status": c.status.value, |
| 126 | + } |
| 127 | + ) |
| 128 | + |
| 129 | + for r in store.list_relations(): |
| 130 | + if entity_id not in (r.source, r.target): |
| 131 | + continue |
| 132 | + # type filter: a relation matches on its RelationType, or "relation". |
| 133 | + if want is not None and r.relation.value not in want and "relation" not in want: |
| 134 | + continue |
| 135 | + rows.append( |
| 136 | + { |
| 137 | + "_when": when_for(r.id, r.created_at), |
| 138 | + "kind": "relation", |
| 139 | + "id": r.id, |
| 140 | + "summary": _relation_summary(r), |
| 141 | + "status": None, |
| 142 | + } |
| 143 | + ) |
| 144 | + |
| 145 | + # window filter on the chosen timestamp |
| 146 | + if since is not None: |
| 147 | + rows = [e for e in rows if e["_when"] is not None and e["_when"] >= since] |
| 148 | + if until is not None: |
| 149 | + rows = [e for e in rows if e["_when"] is not None and e["_when"] <= until] |
| 150 | + |
| 151 | + # oldest first; id tie-break for deterministic output on identical stamps. |
| 152 | + # entries with no recoverable timestamp sort to the front (epoch). |
| 153 | + _epoch = datetime(1970, 1, 1, tzinfo=UTC) |
| 154 | + rows.sort(key=lambda e: (e["_when"] or _epoch, e["id"])) |
| 155 | + |
| 156 | + total = len(rows) |
| 157 | + if limit is not None and limit < total: |
| 158 | + rows = rows[total - limit :] # keep the most recent `limit`, still chronological |
| 159 | + |
| 160 | + entries = [ |
| 161 | + {"when": _iso(e["_when"]), "kind": e["kind"], "id": e["id"], |
| 162 | + "summary": e["summary"], "status": e["status"]} |
| 163 | + for e in rows |
| 164 | + ] |
| 165 | + |
| 166 | + return { |
| 167 | + "entity": {"id": entity.id, "name": entity.name, "type": entity.type.value}, |
| 168 | + "order": order, |
| 169 | + "count": len(entries), |
| 170 | + "total": total, |
| 171 | + "entries": entries, |
| 172 | + } |
0 commit comments