Files
gabrielvidalandClaude Opus 5.5 baebe6b9e2 feat(parse): an old-format transcript may switch to v1 mid-file; rewrite_v1 for the past ones
A converter that resumes a conversation from before v1 writes a v1 header
line ahead of its first event: LegacyReader hands every line after it to a
V1Reader. conversations/parse/rewrite_v1.py turns a legacy pi / opencode /
agy transcript into the v1 events a converter would have written — the
legacy reader's own events, steps written whole, the mirrors' dedup keys
kept — with each fix switchable: whole_steps (quirk a: opencode's late
usage joins its step), source_times (quirk c: agy's turn closes take the
source's last time, not the mirror's clock), harness (pi named in the
header), no_pi_fallback (an opencode step that failed empty no longer reads
as pi's pre-2026-11-06 error turn: one made-up error card less). With no
fix the v1 file parses exactly like the old one (summary, thread, chunked).

ids.head_timestamp_ms and toolimage.read_path read v1 lines too; parse
output for files that are not rewritten is unchanged (no PARSER_VERSION
bump).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:13:08 +01:00

298 lines
11 KiB
Python

"""Public conversation ids: a UUIDv7 per transcript — the path stays inside.
A conversation used to be addressed by its transcript's path under the archive
(``-home-gabrielvidal-projects-x/<sid>.jsonl``), which put the owner's home dir,
project names and branch names in every URL — a guest's included. Now every
archived transcript (each subagent's too) has a UUIDv7:
- its **timestamp** is the transcript's first timestamped record, so ids sort by
start date, the past conversations' included (a transcript with none in its
head takes the moment it was first seen);
- its **other 74 bits** come from a sha256 of the relative path rather than
``os.urandom``, so a lost registry re-derives the very same ids. Nothing can
be read back from them: the session id inside the path is 122 random bits.
The registry — the ``conv_uids`` table in ai-agent.db — is the source of truth
once an id is handed out; :func:`bind` loads it at startup. A legacy path id
still resolves (old pushes, links in docs and PR bodies): :func:`rel_for`
accepts both spellings, and the thread view swaps the old one for the uid in
the address bar. Everything a response carries goes through
``tree._conv_id`` → :func:`uid_for_path`, so an API never emits a path.
"""
from __future__ import annotations
import datetime
import hashlib
import itertools
import json
import os
import pathlib
import re
import threading
import time
import uuid
# Any UUID (v7 is what we mint; the check stays loose so a future version or a
# hand-made id still routes here rather than to the path validator).
UID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
_HEAD_LINES = 200
def derive(rel: str, ts_ms: int) -> str:
"""The UUIDv7 for a transcript: ``ts_ms`` in the 48-bit timestamp, the
version/variant bits, and 74 bits of sha256(rel) in the "random" fields."""
h = hashlib.sha256(rel.encode("utf-8")).digest()
rand_a = int.from_bytes(h[0:2], "big") & 0x0FFF
rand_b = int.from_bytes(h[2:10], "big") & ((1 << 62) - 1)
value = ((max(ts_ms, 0) & ((1 << 48) - 1)) << 80) | (0x7 << 76) \
| (rand_a << 64) | (0b10 << 62) | rand_b
return str(uuid.UUID(int=value))
def uid_time(uid: str) -> float | None:
"""Epoch seconds a UUIDv7 encodes (None for anything else)."""
if not is_uid(uid):
return None
return (uuid.UUID(uid).int >> 80) / 1000.0
def is_uid(s: str | None) -> bool:
return bool(s) and UID_RE.match(s) is not None # type: ignore[arg-type]
def is_legacy(s: str | None) -> bool:
"""A path-style id (``<project dir>/<sid>.jsonl``, a subagent's deeper)."""
if not s or not s.endswith(".jsonl") or "/" not in s:
return False
p = pathlib.PurePosixPath(s)
return not p.is_absolute() and ".." not in p.parts
def head_timestamp_ms(path: str | os.PathLike) -> int | None:
"""The first record timestamp in a transcript's head, in epoch ms (a
record's ``timestamp``, a v1 event's ``at``)."""
try:
with open(path, "rb") as fh:
for line in itertools.islice(fh, _HEAD_LINES):
if b'"timestamp"' not in line and b'"at"' not in line:
continue
try:
rec = json.loads(line)
except ValueError:
continue
ts = (rec.get("timestamp") if "t" not in rec else rec.get("at")) \
if isinstance(rec, dict) else None
ms = _iso_ms(ts)
if ms is not None:
return ms
except OSError:
return None
return None
def _iso_ms(ts) -> int | None:
if isinstance(ts, (int, float)) and ts > 0:
return int(ts if ts > 1e11 else ts * 1000)
if not isinstance(ts, str) or not ts:
return None
try:
d = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00"))
except ValueError:
return None
if d.tzinfo is None:
d = d.replace(tzinfo=datetime.timezone.utc)
return int(d.timestamp() * 1000)
class Registry:
"""rel path ↔ uid, in memory, persisted through the bound Store."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._by_rel: dict[str, str] = {}
self._by_uid: dict[str, str] = {}
self._store = None
self._root: pathlib.Path | None = None
def bind(self, store, root: pathlib.Path | None) -> None:
"""Load every assigned id from ``store`` and persist new ones there."""
pairs = store.all_conv_uids()
with self._lock:
self._store = store
self._root = root
self._remember(dict(pairs))
def _mint(self, rel: str, abs_path: str | os.PathLike | None) -> str:
if abs_path is None and self._root is not None:
abs_path = self._root / rel
ms = head_timestamp_ms(abs_path) if abs_path is not None else None
ts = ms if ms is not None else int(time.time() * 1000)
uid = derive(rel, ts)
# A 74-bit clash between two transcripts started the same millisecond
# is not going to happen — but never hand one uid to two paths.
salt = 0
while uid in self._by_uid and self._by_uid[uid] != rel:
salt += 1
uid = derive(f"{rel}#{salt}", ts)
return uid
def _remember(self, pairs: dict[str, str]) -> None:
for rel, uid in pairs.items():
self._by_rel[rel] = uid
self._by_uid[uid] = rel
def uid(self, rel: str, abs_path: str | os.PathLike | None = None) -> str:
"""The uid for a transcript, minted (and persisted) on first sight.
Another process on the same DB (the standby container of a
blue-green deploy) may have minted it already: the table's value
wins, so both hand out the same id."""
got = self._by_rel.get(rel)
if got is not None:
return got
store = self._store
if store is not None:
row = store.conv_uid_row(rel=rel)
if row:
with self._lock:
self._remember({row[0]: row[1]})
return row[1]
with self._lock:
got = self._by_rel.get(rel)
if got is not None:
return got
uid = self._mint(rel, abs_path)
self._remember({rel: uid})
if store is not None:
held = store.add_conv_uids([(rel, uid)]).get(rel, uid)
if held != uid:
with self._lock:
self._by_uid.pop(uid, None)
self._remember({rel: held})
uid = held
return uid
def rel(self, uid: str) -> str | None:
got = self._by_uid.get(uid)
# Only a v7 can be ours: a bare session id (v4 — `access.session_of`
# asks with those all the time) never costs a query.
if got is not None or self._store is None or uid[14:15] != "7":
return got
row = self._store.conv_uid_row(uid=uid) # minted by another process
if not row:
return None
with self._lock:
self._remember({row[0]: row[1]})
return row[0]
def known(self, rel: str) -> str | None:
return self._by_rel.get(rel)
def register_tree(self, root: pathlib.Path) -> int:
"""Mint an id for every transcript under ``root`` that has none yet
(one transaction) — the backfill, re-run at every start (a walk when
nothing is new). Returns how many were new."""
new: list[tuple[str, str]] = []
for dirpath, _dirs, files in os.walk(root):
for name in files:
if not name.endswith(".jsonl"):
continue
ap = pathlib.Path(dirpath) / name
rel = ap.relative_to(root).as_posix()
if rel in self._by_rel:
continue
with self._lock:
if rel in self._by_rel:
continue
uid = self._mint(rel, ap)
self._remember({rel: uid})
new.append((rel, uid))
if new and self._store is not None:
held = self._store.add_conv_uids(new)
with self._lock:
for rel, uid in new:
if held.get(rel, uid) != uid:
self._by_uid.pop(uid, None)
self._remember({rel: held[rel]})
return len(new)
def snapshot(self) -> dict[str, str]:
"""rel → uid for every assigned id."""
with self._lock:
return dict(self._by_rel)
REGISTRY = Registry()
def bind(store, root: pathlib.Path | None) -> None:
REGISTRY.bind(store, root)
def _root() -> pathlib.Path | None:
from core.config import TRANSCRIPTS_DIR
return TRANSCRIPTS_DIR
def rel_of_path(abs_path: str | os.PathLike) -> str:
"""An archived transcript's path relative to the archive."""
root = _root()
p = pathlib.Path(abs_path)
if root:
try:
return p.relative_to(root).as_posix()
except ValueError:
pass
return p.name
def uid_for_path(abs_path: str | os.PathLike) -> str:
"""The public id of an archived transcript (by absolute path)."""
return REGISTRY.uid(rel_of_path(abs_path), abs_path)
def uid_for_rel(rel: str) -> str:
return REGISTRY.uid(rel)
def rel_for(id: str | None) -> str | None:
"""A conversation id in either spelling → the transcript's rel path.
A uid resolves through the registry; a legacy path id is returned as is
(the caller still checks it stays inside the archive and exists)."""
if not id:
return None
if is_uid(id):
return REGISTRY.rel(id)
if is_legacy(id):
return id
return None
def canonical(id: str | None) -> str | None:
"""Whatever spelling came in → the uid (a legacy id of a transcript that
exists gets one minted); an unknown id is returned unchanged."""
if not id or is_uid(id):
return id
if is_legacy(id):
got = REGISTRY.known(id)
if got:
return got
root = _root()
if root is not None and (root / id).is_file():
return REGISTRY.uid(id, root / id)
return id
def path_of(id: str | None) -> str | None:
"""A conversation id (either spelling) → its archived transcript's
absolute path, as the store keys summaries — None when unknown. No
existence or containment check: for lookups, not for opening files from
a request (``catalog._resolve_transcript`` does that)."""
rel = rel_for(id)
root = _root()
if rel is None or root is None:
return None
return str(root / rel)