Files
ai-agent/backend/meta.py

431 lines
18 KiB
Python

"""
Per-conversation *action* metadata, kept in a single JSON sidecar
(``/data/conversations-meta.json``) keyed by Claude Code session id:
{ "<sessionId>": {
"title": "…"|null, # self-chosen title, overrides the
# parsed one (first user message /
# Claude's ai-title)
"projects": ["foo", "bar"], # projects worked on (manual)
"state": "running"|"finished"|…, # explicit override (optional)
"exitedAt": iso|null, # when the run's process died
# (exit watcher; guards the
# "finished" stamp — the closing
# push's is trusted only once set)
"committed": iso|null, # last time work was committed
"pushed": iso|null,
"merged": iso|null,
"deployed": iso|null,
"notified": iso|null,
"notifications": [ {title, body, type, url, at}, … ],
"worker": "<workerId>"|null, # paired worker the hub launched
# the run on (workers.py)
"workerSource": "<workerId>"|null, # worker the transcript was
# mirrored from (remotefeed.py) —
# a terminal session there
"hooks": { "<hookId>": iso }, # conversation-done hooks that
# already fired on this session
# (the once-per-hook loop guard —
# see hooks.py)
"titleSource": "user"|"agent"|"resources"|null, # who set `title`
"resources": [ {kind, id, url, label, title, state, primary, source,
firstSeen, at}, … ], # what the session is about, as
# recorded by `conv add` / the
# owner (merged by kind:id)
"resourcesHidden": ["kind:id", …], # removed — hides the parser's
# copy too
} }
This file is the source of truth the skill scripts edit (``conv-meta.sh`` /
``select-project.sh``); the backend reloads it on change and merges it into the
conversation list/detail responses. Parsed-from-transcript fields (cost, tokens,
``byTool``, inferred projects, auto state) live in the SQLite summary instead —
the two are merged at request time.
"""
import json
import os
import pathlib
import sqlite3
import threading
import time
from datetime import datetime
_SCHEMA = """
CREATE TABLE IF NOT EXISTS conv_meta (
cid TEXT PRIMARY KEY,
data_json TEXT NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS _meta (
key TEXT PRIMARY KEY,
value TEXT
);
"""
# Action fields a conversation's metadata may carry (besides projects/state).
STAMP_FIELDS = ("committed", "pushed", "merged", "deployed", "notified")
# Two notifications recorded within this many seconds with identical
# title/body/type/url are treated as the same push (a double-send / retry in a
# single turn) and collapsed. Genuine later repeats fall outside the window.
NOTIF_DEDUP_WINDOW_S = 120
def _notif_key(n: dict) -> tuple:
"""Content identity of a notification, ignoring its timestamp."""
return (n.get("title") or "", n.get("body") or "",
n.get("type") or "", n.get("url") or "")
def _is_dupe(note: dict, existing: list[dict]) -> bool:
"""True if ``note`` duplicates a recent entry in ``existing`` — same content
(title/body/type/url) within ``NOTIF_DEDUP_WINDOW_S`` seconds."""
key = _notif_key(note)
at = note.get("at") or ""
for prev in reversed(existing):
if _notif_key(prev) != key:
continue
# Identical content: dupe if timestamps are missing or close together.
pat = prev.get("at") or ""
if not at or not pat:
return True
try:
delta = abs(
(datetime.fromisoformat(at) - datetime.fromisoformat(pat)).total_seconds()
)
if delta <= NOTIF_DEDUP_WINDOW_S:
return True
except ValueError:
return True
return False
def _rkey(r: dict) -> str:
return f"{r.get('kind')}:{r.get('id')}"
def merge_resources(existing: list[dict], incoming: list[dict]) -> list[dict]:
"""Fold recorded resources in by ``kind:id``: a later record's non-empty
fields win, ``firstSeen`` keeps the earliest, and ``primary`` is exclusive
— a new primary demotes the old one."""
out = [dict(r) for r in existing]
for r in incoming:
k = _rkey(r)
if r.get("primary"):
for x in out:
x.pop("primary", None)
cur = next((x for x in out if _rkey(x) == k), None)
if cur is None:
out.append(dict(r))
continue
first = min(x for x in (cur.get("firstSeen"), r.get("firstSeen")) if x) \
if (cur.get("firstSeen") or r.get("firstSeen")) else None
cur.update({f: v for f, v in r.items() if v not in (None, "")})
if first:
cur["firstSeen"] = first
return out
def empty() -> dict:
return {
"title": None,
"projects": [],
"state": None,
"committed": None, "pushed": None, "merged": None,
"deployed": None, "notified": None,
"notifications": [],
"worktrees": [],
"archived": False,
# {"markdown": …, "at": iso} — the conversation's published summary,
# written by the `complete` skill's end-of-task pass (see scaffold.py).
"summary": None,
}
def apply_worktree_event(worktrees: list[dict], ev: dict) -> list[dict]:
"""Fold a single worktree create/remove event into ``worktrees`` in place.
Entries are keyed by directory basename (``dir``); a create fills ``name`` +
``createdAt`` (earliest wins), a remove sets ``removedAt``. Returns the list."""
key = ev.get("dir") or ev.get("name")
if not key:
return worktrees
wt = next((w for w in worktrees
if (w.get("dir") or w.get("name")) == key), None)
if wt is None:
wt = {"name": ev.get("name") or key, "dir": ev.get("dir") or key,
"createdAt": None, "removedAt": None}
worktrees.append(wt)
if ev.get("name"):
wt["name"] = ev["name"]
if ev.get("project"):
wt["project"] = ev["project"]
if ev.get("createdAt") and not wt.get("createdAt"):
wt["createdAt"] = ev["createdAt"]
if ev.get("removedAt"):
wt["removedAt"] = ev["removedAt"]
return worktrees
class MetaStore:
def __init__(self, path: str):
self.path = pathlib.Path(path)
self.db_path = self.path.with_suffix(".db")
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.Lock()
self._legacy_mtime: float | None = None
self._mtime: float | None = None
self._data: dict[str, dict] = {}
# Bumped on every reload/update so request-level caches keyed on the
# sidecar's state (e.g. project cost rollups) know when to recompute.
self.version = 0
self._db = sqlite3.connect(str(self.db_path), check_same_thread=False)
self._db.execute("PRAGMA journal_mode=WAL")
self._db.execute("PRAGMA synchronous=NORMAL")
self._db.execute("PRAGMA busy_timeout=5000")
self._db.execute("PRAGMA journal_size_limit=16777216")
self._db.executescript(_SCHEMA)
self._db.commit()
self._load()
def _get_meta(self, key: str) -> str | None:
row = self._db.execute("SELECT value FROM _meta WHERE key=?", (key,)).fetchone()
return row[0] if row else None
def _set_meta(self, key: str, value: str) -> None:
self._db.execute(
"INSERT INTO _meta (key, value) VALUES (?,?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, value),
)
def _load(self) -> None:
migrated = self._get_meta("migrated_mtime")
count = self._db.execute("SELECT COUNT(*) FROM conv_meta").fetchone()[0]
if migrated is None and count == 0 and self.path.exists():
try:
st_mtime = self.path.stat().st_mtime
data = json.loads(self.path.read_text(encoding="utf-8")) or {}
except (OSError, ValueError):
data = {}
st_mtime = None
if isinstance(data, dict) and data:
now = time.time()
self._db.executemany(
"INSERT OR REPLACE INTO conv_meta (cid, data_json, updated_at) VALUES (?,?,?)",
[(k, json.dumps(v), now) for k, v in data.items() if isinstance(v, dict)],
)
if st_mtime is not None:
self._set_meta("migrated_mtime", str(st_mtime))
self._legacy_mtime = st_mtime
self._mtime = st_mtime
self._db.commit()
elif migrated is not None:
try:
self._legacy_mtime = float(migrated)
self._mtime = self._legacy_mtime
except ValueError:
self._legacy_mtime = None
self._mtime = None
rows = self._db.execute("SELECT cid, data_json FROM conv_meta").fetchall()
old = self._data
loaded: dict[str, dict] = {}
for cid, raw in rows:
try:
v = json.loads(raw)
except (ValueError, TypeError):
continue
if isinstance(v, dict):
loaded[cid] = old[cid] if old.get(cid) == v else v
self._data = loaded
self.version += 1
# If an external script touched the legacy JSON while the backend was
# down after migration, pick up those changes now.
self._merge_legacy_if_newer()
def _merge_legacy_if_newer(self) -> bool:
try:
m = self.path.stat().st_mtime
except OSError:
return False
if self._legacy_mtime is not None and m <= self._legacy_mtime:
return False
try:
data = json.loads(self.path.read_text(encoding="utf-8")) or {}
except (OSError, ValueError):
return False
if not isinstance(data, dict):
return False
now = time.time()
changed_rows: list[tuple[str, str, float]] = []
changed_entries: dict[str, dict] = {}
for cid, v in data.items():
if isinstance(v, dict) and self._data.get(cid) != v:
changed_entries[cid] = v
changed_rows.append((cid, json.dumps(v), now))
if changed_rows:
self._db.executemany(
"INSERT INTO conv_meta (cid, data_json, updated_at) VALUES (?,?,?) "
"ON CONFLICT(cid) DO UPDATE SET data_json=excluded.data_json, "
"updated_at=excluded.updated_at",
changed_rows,
)
for cid, v in changed_entries.items():
self._data[cid] = v
self._set_meta("migrated_mtime", str(m))
self._db.commit()
self._legacy_mtime = m
self._mtime = m
if changed_rows:
self.version += 1
return True
return False
def reload_if_changed(self) -> bool:
"""Pick up edits made to the legacy JSON file out-of-band (by skill scripts)."""
try:
m = self.path.stat().st_mtime
except OSError:
return False
if self._legacy_mtime is None or m > self._legacy_mtime:
with self._lock:
return self._merge_legacy_if_newer()
return False
def all(self) -> dict[str, dict]:
with self._lock:
return json.loads(json.dumps(self._data)) # deep copy
def get(self, cid: str) -> dict:
with self._lock:
return json.loads(json.dumps(self._data.get(cid) or {}))
def peek(self, cid: str) -> dict:
"""Read-only, no-copy lookup for hot per-card paths — the deep copy in
:meth:`get` costs a JSON round-trip per call, which adds up when a list
request merges metadata for hundreds of conversations. Callers must
not mutate the returned dict.
Lock-free on purpose: writers only ever *replace* ``_data`` or one of
its entries (never mutate an entry in place), and a dict lookup is
atomic under the GIL. Taking the lock here made every list build
(thousands of peeks) convoy behind any thread holding it."""
return self._data.get(cid) or {}
def items(self) -> list[tuple[str, dict]]:
"""Shallow ``(cid, entry)`` snapshot — :meth:`all` without the deep
copy, for read-only sweeps. Same contract as :meth:`peek`."""
return list(self._data.items())
def update(self, cid: str, patch: dict) -> dict:
"""Shallow-merge ``patch`` into the conversation's metadata and persist.
``projects`` is unioned (preserving order); ``notifications`` is appended
to (the patch supplies one entry under ``notification``); ``worktree`` is
a single create/remove event folded into the ``worktrees`` list;
``resources`` are merged by ``kind:id`` and ``resourcesRemove`` (keys)
drops — and hides — them. ``title`` follows ``titleSource``: a
``resources`` stamp never replaces a title, an ``agent`` one never
replaces the owner's (``user``) rename. ``look`` (colour / action /
icon) merges key by key."""
with self._lock:
cur = {**empty(), **(self._data.get(cid) or {})}
note = patch.pop("notification", None)
projects = patch.pop("projects", None)
wt_event = patch.pop("worktree", None)
res_in = patch.pop("resources", None)
res_rm = patch.pop("resourcesRemove", None)
look_in = patch.pop("look", None)
title_src = patch.pop("titleSource", None)
if patch.get("title") is not None:
if title_src == "resources" and cur.get("title"):
patch.pop("title")
elif (title_src == "agent" and cur.get("title")
and cur.get("titleSource") == "user"):
patch.pop("title")
else:
cur["titleSource"] = title_src if patch["title"] else None
cur.update({k: v for k, v in patch.items() if v is not None})
if res_in:
cur["resources"] = merge_resources(list(cur.get("resources") or []),
list(res_in))
back = {_rkey(r) for r in res_in}
if cur.get("resourcesHidden"):
cur["resourcesHidden"] = [k for k in cur["resourcesHidden"]
if k not in back]
if res_rm:
gone = set(res_rm)
cur["resources"] = [r for r in cur.get("resources") or []
if _rkey(r) not in gone]
hidden = list(cur.get("resourcesHidden") or [])
cur["resourcesHidden"] = hidden + [k for k in res_rm if k not in hidden]
if look_in:
# Key by key (conversations/look.py): setting the action keeps
# the colour, "" clears one key.
look = {**(cur.get("look") or {}), **look_in}
look = {k: v for k, v in look.items() if v}
if look:
cur["look"] = look
else:
cur.pop("look", None)
if wt_event:
cur["worktrees"] = apply_worktree_event(
list(cur.get("worktrees") or []), wt_event)
if projects:
seen = list(cur.get("projects") or [])
for p in (projects if isinstance(projects, list) else [projects]):
if p and p not in seen:
seen.append(p)
cur["projects"] = seen
if note:
notes = list(cur.get("notifications") or [])
if not _is_dupe(note, notes):
notes.append(note)
cur["notifications"] = notes[-20:] # keep the last 20
# Always advance the "notified" stamp (a duplicate push still
# means the conversation just notified again).
cur["notified"] = note.get("at") or cur.get("notified")
raw = json.dumps(cur)
self._db.execute(
"INSERT INTO conv_meta (cid, data_json, updated_at) VALUES (?,?,?) "
"ON CONFLICT(cid) DO UPDATE SET data_json=excluded.data_json, "
"updated_at=excluded.updated_at",
(cid, raw, time.time()),
)
self._db.commit()
self._data[cid] = cur
self.version += 1
return json.loads(raw)
def stamp_many(self, patches: dict[str, dict]) -> int:
"""Set plain fields on many conversations in **one** transaction. Only
keys whose value differs are written; returns how many conversations
changed."""
rows: list[tuple[str, str, float]] = []
updated: dict[str, dict] = {}
now = time.time()
with self._lock:
for cid, patch in patches.items():
cur = self._data.get(cid) or {}
diff = {k: v for k, v in patch.items()
if v is not None and cur.get(k) != v}
if diff:
new_cur = {**empty(), **cur, **diff}
updated[cid] = new_cur
rows.append((cid, json.dumps(new_cur), now))
if rows:
self._db.executemany(
"INSERT INTO conv_meta (cid, data_json, updated_at) VALUES (?,?,?) "
"ON CONFLICT(cid) DO UPDATE SET data_json=excluded.data_json, "
"updated_at=excluded.updated_at",
rows,
)
self._db.commit()
for cid, new_cur in updated.items():
self._data[cid] = new_cur
self.version += 1
return len(rows)