13cb82d1 moved searchMsgs out of summary_json into search_json, and three
readers kept looking for them on all_summaries() / get_summary(), which have
none (0 of the live store's 6612 summaries carry them):
- short_title.for_subagents: a subagent was named from its 90-char title
instead of its first prompt;
- refs.py _texts: the conv-ref cards had no opening prompt from the corpus
and no last answer;
- past.py _excerpt: ai-agent past gave no excerpt.
Store.search_msgs(paths) reads just those rows (hidden ones left out, like
all_search_msgs, which now shares its decoding); the three take the message
list, not a summary. test_conv_refs and test_past now build a real db.Store
(their fake handed searchMsgs back inside the summary, so they passed);
test_parser_version pins that summaries carry none and that the servable
floor hides search_msgs too. test_short_title passes again: off the
known-failures list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
771 lines
35 KiB
Python
771 lines
35 KiB
Python
"""
|
|
SQLite store for the ai-agent backend.
|
|
|
|
Holds two kinds of state so we don't recompute them on every request:
|
|
|
|
* ``files`` — one row per exposed context file: content hash, size, mtime, the
|
|
*real* Claude token count and its dollar cost. Token counts are expensive
|
|
(a network round-trip to the count_tokens endpoint), so they are computed
|
|
lazily and only when a file's content hash actually changes.
|
|
* ``skills`` — aggregated skill-usage analytics mined from the Claude Code
|
|
transcripts (how many times each skill ran, and when it was last used).
|
|
* ``transcripts`` — per-transcript-file bookkeeping so skill stats can be
|
|
recomputed incrementally (only re-parse the .jsonl files that changed), and
|
|
the ``PARSER_VERSION`` that wrote each row's summary (``parser_version``):
|
|
a version bump re-parses rows in the background instead of wiping them.
|
|
* ``skill_prompts`` — the newest injected prompt per skill, kept up as the
|
|
indexer parses transcripts (the catalog's view of a built-in skill).
|
|
|
|
A single connection (``check_same_thread=False``) guarded by a lock is plenty
|
|
for this low-traffic, single-process service.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
|
|
_SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS files (
|
|
path TEXT PRIMARY KEY,
|
|
content_hash TEXT,
|
|
size INTEGER,
|
|
mtime REAL,
|
|
is_markdown INTEGER NOT NULL DEFAULT 0,
|
|
tokens INTEGER, -- real (or estimated) token count
|
|
cost REAL, -- tokens priced at the input rate
|
|
estimated INTEGER NOT NULL DEFAULT 1, -- 1 = heuristic, 0 = real API count
|
|
counted_at REAL, -- epoch secs the token count was last set
|
|
seen_at REAL, -- epoch secs the file was last seen on disk
|
|
words INTEGER, -- text stats, stored on content change so
|
|
chars INTEGER -- /api/bundle never re-reads files per request
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS skills (
|
|
name TEXT PRIMARY KEY,
|
|
count INTEGER NOT NULL DEFAULT 0,
|
|
last_used TEXT
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS transcripts (
|
|
path TEXT PRIMARY KEY,
|
|
mtime REAL,
|
|
size INTEGER,
|
|
skills_json TEXT, -- {skill: {"count": n, "last": iso}}
|
|
summary_json TEXT, -- per-conversation rollup for the list view
|
|
search_json TEXT, -- searchMsgs split out so summaries stay light in RAM
|
|
parser_version INTEGER NOT NULL DEFAULT 0 -- indexer.PARSER_VERSION that wrote it
|
|
);
|
|
|
|
-- The newest prompt each skill injected into any transcript: a built-in or
|
|
-- plugin skill has no SKILL.md here, so this is the only place to read it.
|
|
CREATE TABLE IF NOT EXISTS skill_prompts (
|
|
name TEXT PRIMARY KEY,
|
|
prompt TEXT NOT NULL,
|
|
seen_at TEXT, -- the injection's timestamp
|
|
path TEXT, -- the transcript it came from
|
|
base_dir TEXT -- its "Base directory", when it had one
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS meta (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS conversation_diffs (
|
|
session_id TEXT PRIMARY KEY,
|
|
fingerprint TEXT, -- endedAt + repo HEADs; recompute when it moves
|
|
data_json TEXT, -- computed conversation-commits payload
|
|
computed_at REAL
|
|
);
|
|
|
|
-- A conversation's public id (conversations/ids.py): one UUIDv7 per archived
|
|
-- transcript, a subagent's included. The path never leaves the backend.
|
|
CREATE TABLE IF NOT EXISTS conv_uids (
|
|
rel TEXT PRIMARY KEY, -- the transcript, relative to the archive
|
|
uid TEXT NOT NULL UNIQUE,
|
|
created REAL NOT NULL
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS short_titles (
|
|
conv_id TEXT PRIMARY KEY, -- a conversation's id (a subagent's included)
|
|
title TEXT, -- NULL = the ask failed (retried after a while)
|
|
asked_at REAL NOT NULL,
|
|
source TEXT -- the long title it stands for
|
|
);
|
|
"""
|
|
|
|
|
|
def _extract_skill_counts(contrib) -> dict[str, int]:
|
|
if not isinstance(contrib, dict):
|
|
return {}
|
|
out: dict[str, int] = {}
|
|
for name, d in contrib.items():
|
|
if isinstance(d, dict):
|
|
out[name] = d.get("count") or 0
|
|
elif isinstance(d, int):
|
|
out[name] = d
|
|
return out
|
|
|
|
|
|
class Store:
|
|
def __init__(self, path: str):
|
|
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
self._lock = threading.Lock()
|
|
self._db = sqlite3.connect(path, check_same_thread=False)
|
|
self._db.row_factory = sqlite3.Row
|
|
# WAL keeps readers unblocked during the indexer's writes and cuts the
|
|
# fsync-per-commit cost of its frequent small updates.
|
|
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._migrate()
|
|
self._db.commit()
|
|
# Decoded-summary cache: json.loads over every transcript's summary is
|
|
# what every list/analytics request used to pay (~900 blobs, several MB).
|
|
# `summaries_version` bumps on any change so request-level memoizers
|
|
# (e.g. project cost rollups) can key off it.
|
|
self._summaries: dict[str, dict] | None = None
|
|
self.summaries_version = 0
|
|
# Rows an older parser than this wrote are not served (hide_below).
|
|
self._min_servable = 0
|
|
self._skills: dict[str, dict[str, int]] | None = None
|
|
self.files_version = 0
|
|
|
|
def wal_checkpoint(self, mode: str = "TRUNCATE") -> None:
|
|
"""Run a WAL checkpoint under the store lock."""
|
|
if mode not in ("PASSIVE", "FULL", "RESTART", "TRUNCATE"):
|
|
mode = "TRUNCATE"
|
|
with self._lock:
|
|
self._db.execute(f"PRAGMA wal_checkpoint({mode})").fetchall()
|
|
|
|
def _migrate(self) -> None:
|
|
"""Add columns introduced after a DB was first created."""
|
|
cols = {r["name"] for r in self._db.execute("PRAGMA table_info(transcripts)").fetchall()}
|
|
if "summary_json" not in cols:
|
|
self._db.execute("ALTER TABLE transcripts ADD COLUMN summary_json TEXT")
|
|
if "search_json" not in cols:
|
|
self._db.execute("ALTER TABLE transcripts ADD COLUMN search_json TEXT")
|
|
if "parser_version" not in cols:
|
|
# Every row a pre-per-row indexer wrote was parsed at the one
|
|
# global version it kept in `meta` (a bump wiped them all), so that
|
|
# is their version — given as the column's DEFAULT, which SQLite
|
|
# reads for the old records without rewriting them: O(1), where an
|
|
# UPDATE would rewrite all ~90 MB. An older image still running
|
|
# beside this one (blue-green) inserts without the column and gets
|
|
# that same version, which is its own. The `meta` row stays: such
|
|
# an image wipes everything when it no longer reads its version.
|
|
self._db.execute(
|
|
"ALTER TABLE transcripts ADD COLUMN parser_version INTEGER "
|
|
f"NOT NULL DEFAULT {self._legacy_parser_version()}")
|
|
# The bookkeeping columns on their own: the sweep's change index and
|
|
# the upgrade pass's queue read only this, never the rows' blobs
|
|
# (parser_version sits after them, so a table scan would read every
|
|
# summary's overflow pages to reach it).
|
|
self._db.execute("CREATE INDEX IF NOT EXISTS transcripts_book "
|
|
"ON transcripts (path, mtime, size, parser_version)")
|
|
fcols = {r["name"] for r in self._db.execute("PRAGMA table_info(files)").fetchall()}
|
|
for col in ("words", "chars"):
|
|
if col not in fcols:
|
|
self._db.execute(f"ALTER TABLE files ADD COLUMN {col} INTEGER")
|
|
scols = {r["name"] for r in self._db.execute("PRAGMA table_info(short_titles)").fetchall()}
|
|
if "source" not in scols:
|
|
self._db.execute("ALTER TABLE short_titles ADD COLUMN source TEXT")
|
|
self._migrate_search_msgs()
|
|
|
|
def _legacy_parser_version(self) -> int:
|
|
row = self._db.execute(
|
|
"SELECT value FROM meta WHERE key='parser_version'").fetchone()
|
|
try:
|
|
return max(0, int(row["value"])) if row else 0
|
|
except (TypeError, ValueError):
|
|
return 0
|
|
|
|
def _migrate_search_msgs(self) -> None:
|
|
"""One-time batched extraction of searchMsgs out of summary_json into search_json."""
|
|
has_any = self._db.execute(
|
|
"SELECT 1 FROM transcripts "
|
|
"WHERE search_json IS NULL AND summary_json LIKE '%\"searchMsgs\"%' LIMIT 1"
|
|
).fetchone()
|
|
if not has_any:
|
|
return
|
|
rows = self._db.execute(
|
|
"SELECT path, summary_json FROM transcripts "
|
|
"WHERE search_json IS NULL AND summary_json LIKE '%\"searchMsgs\"%'"
|
|
).fetchall()
|
|
batch: list[tuple[str, str, str]] = []
|
|
migrated = 0
|
|
for r in rows:
|
|
raw = r["summary_json"]
|
|
if not raw:
|
|
continue
|
|
try:
|
|
d = json.loads(raw)
|
|
except (ValueError, TypeError):
|
|
continue
|
|
if not isinstance(d, dict) or "searchMsgs" not in d:
|
|
continue
|
|
msgs = d.pop("searchMsgs")
|
|
search_str = json.dumps(msgs if msgs is not None else [])
|
|
summary_str = json.dumps(d)
|
|
batch.append((summary_str, search_str, r["path"]))
|
|
if len(batch) >= 250:
|
|
self._db.executemany(
|
|
"UPDATE transcripts SET summary_json=?, search_json=? WHERE path=?",
|
|
batch,
|
|
)
|
|
self._db.commit()
|
|
migrated += len(batch)
|
|
batch.clear()
|
|
if batch:
|
|
self._db.executemany(
|
|
"UPDATE transcripts SET summary_json=?, search_json=? WHERE path=?",
|
|
batch,
|
|
)
|
|
self._db.commit()
|
|
migrated += len(batch)
|
|
if migrated:
|
|
self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchall()
|
|
|
|
# ── files ────────────────────────────────────────────────────────────
|
|
def get_file(self, path: str) -> sqlite3.Row | None:
|
|
with self._lock:
|
|
cur = self._db.execute("SELECT * FROM files WHERE path = ?", (path,))
|
|
return cur.fetchone()
|
|
|
|
def all_files(self) -> dict[str, sqlite3.Row]:
|
|
with self._lock:
|
|
cur = self._db.execute("SELECT * FROM files")
|
|
return {r["path"]: r for r in cur.fetchall()}
|
|
|
|
def upsert_file_meta(self, path: str, content_hash: str, size: int,
|
|
mtime: float, is_markdown: bool,
|
|
words: int | None = None,
|
|
chars: int | None = None) -> None:
|
|
"""Record a file's on-disk metadata. If the hash changed, the token
|
|
count is invalidated (estimated flag flipped on) so the worker recounts."""
|
|
now = time.time()
|
|
changed = False
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
"SELECT content_hash, size, mtime, is_markdown, words, chars "
|
|
"FROM files WHERE path = ?", (path,)
|
|
).fetchone()
|
|
if row is None:
|
|
self._db.execute(
|
|
"INSERT INTO files (path, content_hash, size, mtime, "
|
|
"is_markdown, estimated, seen_at, words, chars) "
|
|
"VALUES (?,?,?,?,?,1,?,?,?)",
|
|
(path, content_hash, size, mtime, int(is_markdown), now,
|
|
words, chars),
|
|
)
|
|
changed = True
|
|
elif row["content_hash"] != content_hash:
|
|
# content changed → mark token count stale (estimated) to recount
|
|
self._db.execute(
|
|
"UPDATE files SET content_hash=?, size=?, mtime=?, "
|
|
"is_markdown=?, estimated=1, seen_at=?, words=?, chars=? "
|
|
"WHERE path=?",
|
|
(content_hash, size, mtime, int(is_markdown), now,
|
|
words, chars, path),
|
|
)
|
|
changed = True
|
|
else:
|
|
new_words = words if words is not None else row["words"]
|
|
new_chars = chars if chars is not None else row["chars"]
|
|
if (row["size"], row["mtime"], row["is_markdown"],
|
|
row["words"], row["chars"]) != (
|
|
size, mtime, int(is_markdown), new_words, new_chars):
|
|
changed = True
|
|
self._db.execute(
|
|
"UPDATE files SET size=?, mtime=?, is_markdown=?, seen_at=?, "
|
|
"words=COALESCE(?, words), chars=COALESCE(?, chars) "
|
|
"WHERE path=?",
|
|
(size, mtime, int(is_markdown), now, words, chars, path),
|
|
)
|
|
self._db.commit()
|
|
if changed:
|
|
self.files_version += 1
|
|
|
|
def set_tokens(self, path: str, tokens: int, cost: float, estimated: bool) -> None:
|
|
with self._lock:
|
|
cur = self._db.execute(
|
|
"UPDATE files SET tokens=?, cost=?, estimated=?, counted_at=? "
|
|
"WHERE path=?",
|
|
(tokens, cost, int(estimated), time.time(), path),
|
|
)
|
|
self._db.commit()
|
|
if cur.rowcount:
|
|
self.files_version += 1
|
|
|
|
def prune_files(self, keep_paths: set[str]) -> None:
|
|
with self._lock:
|
|
existing = {r["path"] for r in self._db.execute("SELECT path FROM files").fetchall()}
|
|
gone = existing - keep_paths
|
|
if not gone:
|
|
return
|
|
for p in gone:
|
|
self._db.execute("DELETE FROM files WHERE path=?", (p,))
|
|
self._db.commit()
|
|
self.files_version += 1
|
|
|
|
# ── transcripts / skills ─────────────────────────────────────────────
|
|
def get_transcript(self, path: str) -> sqlite3.Row | None:
|
|
with self._lock:
|
|
return self._db.execute(
|
|
"SELECT * FROM transcripts WHERE path=?", (path,)
|
|
).fetchone()
|
|
|
|
def all_transcripts(self) -> dict[str, sqlite3.Row]:
|
|
"""Bookkeeping rows only (path, mtime, size, parser_version — read off
|
|
the ``transcripts_book`` index, no JSON blobs) — this is the
|
|
change-detection index, and pulling every summary_json with it would
|
|
read the whole DB."""
|
|
with self._lock:
|
|
return {r["path"]: r for r in self._db.execute(
|
|
"SELECT path, mtime, size, parser_version FROM transcripts").fetchall()}
|
|
|
|
def transcript_book(self, path: str) -> sqlite3.Row | None:
|
|
"""One row's bookkeeping (as :meth:`all_transcripts`). Pinned to the
|
|
index: the planner takes the primary key's, then reads the row."""
|
|
with self._lock:
|
|
return self._db.execute(
|
|
"SELECT path, mtime, size, parser_version FROM transcripts "
|
|
"INDEXED BY transcripts_book WHERE path=?", (path,)).fetchone()
|
|
|
|
def stale_transcripts(self, version: int) -> list[sqlite3.Row]:
|
|
"""The rows an older parser than ``version`` wrote, most recently
|
|
changed first — the upgrade pass's queue. A row a *newer* parser
|
|
wrote (the other container of a blue-green deploy) is not in it."""
|
|
with self._lock:
|
|
return self._db.execute(
|
|
"SELECT path, mtime, size, parser_version FROM transcripts "
|
|
"WHERE parser_version < ? ORDER BY mtime DESC", (version,)).fetchall()
|
|
|
|
def hide_below(self, version: int) -> None:
|
|
"""Serve no summary a parser older than ``version`` wrote (the
|
|
indexer's ``MIN_SERVABLE_VERSION``): those rows are left out of
|
|
:meth:`all_summaries` / :meth:`get_summary` / :meth:`all_search_msgs`
|
|
until a re-parse replaces them."""
|
|
with self._lock:
|
|
if version != self._min_servable:
|
|
self._min_servable = version
|
|
self._summaries = None
|
|
self.summaries_version += 1
|
|
|
|
def _hidden(self) -> set[str]:
|
|
"""Paths below the servable floor (call with the lock held)."""
|
|
if self._min_servable <= 0:
|
|
return set()
|
|
return {r["path"] for r in self._db.execute(
|
|
"SELECT path FROM transcripts WHERE parser_version < ?",
|
|
(self._min_servable,)).fetchall()}
|
|
|
|
def all_transcript_skills(self) -> list[str]:
|
|
"""Every transcript's raw ``skills_json`` (for the skills rollup)."""
|
|
with self._lock:
|
|
return [r["skills_json"] for r in self._db.execute(
|
|
"SELECT skills_json FROM transcripts").fetchall()]
|
|
|
|
def transcript_skill_rows(self, paths: list[str]) -> list[tuple[str, str]]:
|
|
"""``(path, raw skills_json)`` for just ``paths`` — one conversation
|
|
and its subagents, for a card or thread, without decoding every row
|
|
in the store (`all_transcript_skill_rows`) on each version bump."""
|
|
if not paths:
|
|
return []
|
|
marks = ",".join("?" * len(paths))
|
|
with self._lock:
|
|
return [(r["path"], r["skills_json"]) for r in self._db.execute(
|
|
f"SELECT path, skills_json FROM transcripts WHERE path IN ({marks})",
|
|
paths).fetchall()]
|
|
|
|
def all_transcript_skill_rows(self) -> list[tuple[str, str]]:
|
|
"""``(path, raw skills_json)`` per transcript — the same path key
|
|
:meth:`all_summaries` uses, so the skills catalog can join a skill's
|
|
calls to the spend of the conversations it ran in."""
|
|
with self._lock:
|
|
return [(r["path"], r["skills_json"]) for r in self._db.execute(
|
|
"SELECT path, skills_json FROM transcripts").fetchall()]
|
|
|
|
def _load_skills(self) -> dict[str, dict[str, int]]:
|
|
"""Decode-and-cache every transcript's skill counts (call with lock held)."""
|
|
if self._skills is None:
|
|
out: dict[str, dict[str, int]] = {}
|
|
rows = self._db.execute(
|
|
"SELECT path, skills_json FROM transcripts "
|
|
"WHERE skills_json IS NOT NULL"
|
|
).fetchall()
|
|
for r in rows:
|
|
raw = r["skills_json"]
|
|
if not raw or raw == "{}":
|
|
continue
|
|
try:
|
|
contrib = json.loads(raw)
|
|
except (ValueError, TypeError):
|
|
continue
|
|
counts = _extract_skill_counts(contrib)
|
|
if counts:
|
|
out[r["path"]] = counts
|
|
self._skills = out
|
|
return self._skills
|
|
|
|
def skills_by_path(self) -> dict[str, dict[str, int]]:
|
|
"""Cached ``{path: {skill: count}}`` across transcripts, updated
|
|
incrementally on upsert/prune. Callers must treat inner dicts as read-only."""
|
|
with self._lock:
|
|
return dict(self._load_skills())
|
|
|
|
def all_search_msgs(self) -> dict[str, list]:
|
|
"""Read ``{path: searchMsgs}`` on demand from SQLite (never cached in RAM)."""
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
"SELECT path, search_json FROM transcripts WHERE search_json IS NOT NULL"
|
|
).fetchall()
|
|
hidden = self._hidden()
|
|
return self._decode_search(rows, hidden)
|
|
|
|
def search_msgs(self, paths) -> dict[str, list]:
|
|
"""``{path: searchMsgs}`` for just ``paths`` (an iterable), read from
|
|
SQLite on demand. The summaries of :meth:`all_summaries` /
|
|
:meth:`get_summary` don't carry ``searchMsgs`` — they live apart in
|
|
``search_json`` — so whatever wants a conversation's text blocks (its
|
|
first prompt, its last answer) reads them here. A path with none, or
|
|
hidden (:meth:`hide_below`), is absent."""
|
|
paths = list(dict.fromkeys(p for p in paths if p))
|
|
if not paths:
|
|
return {}
|
|
marks = ",".join("?" * len(paths))
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
f"SELECT path, search_json FROM transcripts WHERE path IN ({marks}) "
|
|
"AND search_json IS NOT NULL", paths).fetchall()
|
|
hidden = self._hidden()
|
|
return self._decode_search(rows, hidden)
|
|
|
|
@staticmethod
|
|
def _decode_search(rows, hidden: set[str]) -> dict[str, list]:
|
|
out: dict[str, list] = {}
|
|
for r in rows:
|
|
if r["path"] in hidden:
|
|
continue
|
|
try:
|
|
val = json.loads(r["search_json"])
|
|
if isinstance(val, list):
|
|
out[r["path"]] = val
|
|
except (ValueError, TypeError):
|
|
continue
|
|
return out
|
|
|
|
@staticmethod
|
|
def _encode(summary: dict | None) -> tuple[str | None, str | None]:
|
|
"""``(summary_json, search_json)`` — searchMsgs stored apart."""
|
|
if summary is None:
|
|
return None, None
|
|
if "searchMsgs" in summary:
|
|
search_msgs = summary["searchMsgs"]
|
|
trimmed = {k: v for k, v in summary.items() if k != "searchMsgs"}
|
|
else:
|
|
search_msgs = None
|
|
trimmed = summary
|
|
return (json.dumps(trimmed),
|
|
json.dumps(search_msgs) if search_msgs is not None else None)
|
|
|
|
def _cached(self, path: str, s_str: str | None, skills: dict) -> None:
|
|
"""Mirror a written row into the decoded caches (lock held)."""
|
|
if self._summaries is not None:
|
|
if s_str is not None:
|
|
# round-trip through JSON so the cache holds exactly what a
|
|
# cold load would (tuples→lists etc.), decoupled from the
|
|
# parser state's live dicts
|
|
self._summaries[path] = json.loads(s_str)
|
|
else:
|
|
self._summaries.pop(path, None)
|
|
if self._skills is not None:
|
|
counts = _extract_skill_counts(skills)
|
|
if counts:
|
|
self._skills[path] = counts
|
|
else:
|
|
self._skills.pop(path, None)
|
|
self.summaries_version += 1
|
|
|
|
def upsert_transcript(self, path: str, mtime: float, size: int,
|
|
skills: dict, summary: dict | None = None,
|
|
version: int = 0) -> None:
|
|
"""Store a transcript's parse. ``version`` = the ``PARSER_VERSION``
|
|
that made ``summary`` (0, unknown: the upgrade pass re-parses it)."""
|
|
s_str, search_str = self._encode(summary)
|
|
skills_str = json.dumps(skills)
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT INTO transcripts (path, mtime, size, skills_json, summary_json, "
|
|
"search_json, parser_version) "
|
|
"VALUES (?,?,?,?,?,?,?) ON CONFLICT(path) DO UPDATE SET "
|
|
"mtime=excluded.mtime, size=excluded.size, "
|
|
"skills_json=excluded.skills_json, summary_json=excluded.summary_json, "
|
|
"search_json=excluded.search_json, parser_version=excluded.parser_version",
|
|
(path, mtime, size, skills_str, s_str, search_str, int(version)),
|
|
)
|
|
self._db.commit()
|
|
self._cached(path, s_str, skills)
|
|
|
|
def upgrade_transcript(self, path: str, mtime: float, size: int, version: int,
|
|
skills: dict, summary: dict) -> bool:
|
|
"""The upgrade pass's write: replace a row an older parser wrote with
|
|
``version``'s parse of the same file — only while the row is still
|
|
that file at (``mtime``, ``size``) and still older than ``version``.
|
|
A live write since (the watcher, the other container of a blue-green
|
|
deploy) wins. True when it wrote."""
|
|
s_str, search_str = self._encode(summary)
|
|
with self._lock:
|
|
cur = self._db.execute(
|
|
"UPDATE transcripts SET skills_json=?, summary_json=?, search_json=?, "
|
|
"parser_version=? WHERE path=? AND mtime=? AND size=? "
|
|
"AND parser_version < ?",
|
|
(json.dumps(skills), s_str, search_str, int(version),
|
|
path, mtime, size, int(version)))
|
|
self._db.commit()
|
|
if cur.rowcount != 1:
|
|
return False
|
|
self._cached(path, s_str, skills)
|
|
return True
|
|
|
|
def _load_summaries(self) -> dict[str, dict]:
|
|
"""Decode-and-cache every stored summary (call with the lock held)."""
|
|
if self._summaries is None:
|
|
out: dict[str, dict] = {}
|
|
rows = self._db.execute(
|
|
"SELECT path, summary_json FROM transcripts "
|
|
"WHERE summary_json IS NOT NULL").fetchall()
|
|
hidden = self._hidden()
|
|
for r in rows:
|
|
if r["path"] in hidden:
|
|
continue
|
|
try:
|
|
out[r["path"]] = json.loads(r["summary_json"])
|
|
except (ValueError, TypeError):
|
|
continue
|
|
self._summaries = out
|
|
return self._summaries
|
|
|
|
def all_summaries(self) -> list[tuple[str, dict]]:
|
|
"""(abs_path, summary dict) for every transcript that has one.
|
|
|
|
Served from the decoded cache — callers must treat the dicts as
|
|
**read-only** (copy before mutating)."""
|
|
with self._lock:
|
|
return list(self._load_summaries().items())
|
|
|
|
def get_summary(self, path: str) -> dict | None:
|
|
"""The parsed summary dict for one transcript (by abs path), or None.
|
|
|
|
Read-only — same shared cache as :meth:`all_summaries`."""
|
|
with self._lock:
|
|
return self._load_summaries().get(path)
|
|
|
|
def prune_transcripts(self, keep_paths: set[str]) -> None:
|
|
with self._lock:
|
|
existing = {r["path"] for r in
|
|
self._db.execute("SELECT path FROM transcripts").fetchall()}
|
|
gone = existing - keep_paths
|
|
if not gone:
|
|
return
|
|
for p in gone:
|
|
self._db.execute("DELETE FROM transcripts WHERE path=?", (p,))
|
|
if self._summaries is not None:
|
|
self._summaries.pop(p, None)
|
|
if self._skills is not None:
|
|
self._skills.pop(p, None)
|
|
self._db.commit()
|
|
self.summaries_version += 1
|
|
|
|
def replace_skills(self, skills: dict[str, dict]) -> None:
|
|
"""skills: {name: {"count": int, "last_used": iso|None}}"""
|
|
with self._lock:
|
|
self._db.execute("DELETE FROM skills")
|
|
self._db.executemany(
|
|
"INSERT INTO skills (name, count, last_used) VALUES (?,?,?)",
|
|
[(n, d["count"], d.get("last_used")) for n, d in skills.items()],
|
|
)
|
|
self._db.commit()
|
|
|
|
def all_skills(self) -> list[sqlite3.Row]:
|
|
with self._lock:
|
|
return self._db.execute(
|
|
"SELECT * FROM skills ORDER BY count DESC, name ASC").fetchall()
|
|
|
|
def keep_skill_prompts(self, path: str, prompts: dict[str, dict]) -> None:
|
|
"""Record a transcript's skill prompts (``{name: {text, at, baseDir}}``)
|
|
where they are at least as new as the stored one. A live transcript
|
|
re-sends the same rows every tick; the WHERE makes those no-ops."""
|
|
if not prompts:
|
|
return
|
|
with self._lock:
|
|
self._db.executemany(
|
|
"INSERT INTO skill_prompts (name, prompt, seen_at, path, base_dir) "
|
|
"VALUES (?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET "
|
|
"prompt=excluded.prompt, seen_at=excluded.seen_at, "
|
|
"path=excluded.path, base_dir=excluded.base_dir "
|
|
"WHERE ifnull(excluded.seen_at, '') > ifnull(skill_prompts.seen_at, '') "
|
|
"OR (ifnull(excluded.seen_at, '') = ifnull(skill_prompts.seen_at, '') "
|
|
"AND excluded.prompt IS NOT skill_prompts.prompt)",
|
|
[(n, p["text"], p.get("at"), path, p.get("baseDir"))
|
|
for n, p in prompts.items() if p.get("text")],
|
|
)
|
|
self._db.commit()
|
|
|
|
def skill_prompt_index(self) -> dict[str, dict]:
|
|
"""``{name: {seenAt, path}}`` — what the catalog list needs, no text."""
|
|
with self._lock:
|
|
return {r["name"]: {"seenAt": r["seen_at"], "path": r["path"]}
|
|
for r in self._db.execute(
|
|
"SELECT name, seen_at, path FROM skill_prompts").fetchall()}
|
|
|
|
def get_skill_prompt(self, name: str) -> dict | None:
|
|
with self._lock:
|
|
r = self._db.execute(
|
|
"SELECT * FROM skill_prompts WHERE name=?", (name,)).fetchone()
|
|
if r is None:
|
|
return None
|
|
return {"prompt": r["prompt"], "seenAt": r["seen_at"], "path": r["path"],
|
|
"baseDir": r["base_dir"]}
|
|
|
|
# ── conversation diff cache ──────────────────────────────────────────
|
|
def get_conversation_diff(self, session_id: str) -> dict | None:
|
|
"""Cached {fingerprint, data} for a conversation, or None."""
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
"SELECT fingerprint, data_json FROM conversation_diffs "
|
|
"WHERE session_id=?", (session_id,)).fetchone()
|
|
if not row or not row["data_json"]:
|
|
return None
|
|
try:
|
|
return {"fingerprint": row["fingerprint"],
|
|
"data": json.loads(row["data_json"])}
|
|
except (ValueError, TypeError):
|
|
return None
|
|
|
|
def set_conversation_diff(self, session_id: str, fingerprint: str,
|
|
data: dict) -> None:
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT INTO conversation_diffs "
|
|
"(session_id, fingerprint, data_json, computed_at) VALUES (?,?,?,?) "
|
|
"ON CONFLICT(session_id) DO UPDATE SET "
|
|
"fingerprint=excluded.fingerprint, data_json=excluded.data_json, "
|
|
"computed_at=excluded.computed_at",
|
|
(session_id, fingerprint, json.dumps(data), time.time()),
|
|
)
|
|
self._db.commit()
|
|
|
|
# ── short titles (conversations/short_title.py) ──────────────────────
|
|
def get_short_title(self, conv_id: str) -> tuple[str | None, float, str | None] | None:
|
|
"""``(title, asked_at, source)`` for a conversation already asked about."""
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
"SELECT title, asked_at, source FROM short_titles WHERE conv_id=?",
|
|
(conv_id,)).fetchone()
|
|
return (row["title"], row["asked_at"], row["source"]) if row else None
|
|
|
|
def get_short_titles(self, conv_ids: list[str]) -> dict[str, tuple[str | None, str | None]]:
|
|
"""``{conv_id: (title, source)}`` for the ones already asked about."""
|
|
if not conv_ids:
|
|
return {}
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
"SELECT conv_id, title, source FROM short_titles WHERE conv_id IN "
|
|
f"({','.join('?' * len(conv_ids))})", conv_ids).fetchall()
|
|
return {r["conv_id"]: (r["title"], r["source"]) for r in rows}
|
|
|
|
def set_short_title(self, conv_id: str, title: str | None, source: str) -> None:
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT INTO short_titles (conv_id, title, asked_at, source) "
|
|
"VALUES (?,?,?,?) ON CONFLICT(conv_id) DO UPDATE SET "
|
|
"title=excluded.title, asked_at=excluded.asked_at, source=excluded.source",
|
|
(conv_id, title, time.time(), source))
|
|
self._db.commit()
|
|
|
|
# ── public conversation ids (conversations/ids.py) ───────────────────
|
|
def all_conv_uids(self) -> list[tuple[str, str]]:
|
|
"""Every ``(rel, uid)`` pair ever assigned."""
|
|
with self._lock:
|
|
return [(r["rel"], r["uid"]) for r in
|
|
self._db.execute("SELECT rel, uid FROM conv_uids").fetchall()]
|
|
|
|
def add_conv_uids(self, pairs: list[tuple[str, str]]) -> dict[str, str]:
|
|
"""Record new ``(rel, uid)`` pairs and return what the table holds for
|
|
those rels — an already-assigned rel (another process got there
|
|
first) keeps its uid, and the caller adopts it."""
|
|
if not pairs:
|
|
return {}
|
|
now = time.time()
|
|
rels = [rel for rel, _ in pairs]
|
|
out: dict[str, str] = {}
|
|
with self._lock:
|
|
self._db.executemany(
|
|
"INSERT OR IGNORE INTO conv_uids (rel, uid, created) VALUES (?,?,?)",
|
|
[(rel, uid, now) for rel, uid in pairs])
|
|
self._db.commit()
|
|
for i in range(0, len(rels), 500):
|
|
chunk = rels[i:i + 500]
|
|
for r in self._db.execute(
|
|
"SELECT rel, uid FROM conv_uids WHERE rel IN "
|
|
f"({','.join('?' * len(chunk))})", chunk).fetchall():
|
|
out[r["rel"]] = r["uid"]
|
|
return out
|
|
|
|
def conv_uid_row(self, *, rel: str | None = None,
|
|
uid: str | None = None) -> tuple[str, str] | None:
|
|
"""One ``(rel, uid)`` pair by either side (another process minted it)."""
|
|
col, val = ("rel", rel) if rel is not None else ("uid", uid)
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
f"SELECT rel, uid FROM conv_uids WHERE {col}=?", (val,)).fetchone()
|
|
return (row["rel"], row["uid"]) if row else None
|
|
|
|
def rekey_short_titles(self, mapping: dict[str, str]) -> int:
|
|
"""Move the short-title rows (and their side-call ledger refs) still
|
|
keyed by an old path id to its uid; drop the ones with no uid."""
|
|
n = 0
|
|
with self._lock:
|
|
olds = [r["conv_id"] for r in self._db.execute(
|
|
"SELECT conv_id FROM short_titles WHERE conv_id LIKE '%.jsonl'").fetchall()]
|
|
for old in olds:
|
|
new = mapping.get(old)
|
|
if new:
|
|
n += self._db.execute(
|
|
"UPDATE OR IGNORE short_titles SET conv_id=? WHERE conv_id=?",
|
|
(new, old)).rowcount
|
|
self._db.execute("DELETE FROM short_titles WHERE conv_id LIKE '%.jsonl'")
|
|
if self._db.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
"AND name='side_calls'").fetchone():
|
|
refs = [r["ref"] for r in self._db.execute(
|
|
"SELECT DISTINCT ref FROM side_calls "
|
|
"WHERE kind='short-title' AND ref LIKE '%.jsonl'").fetchall()]
|
|
for old in refs:
|
|
if mapping.get(old):
|
|
self._db.execute(
|
|
"UPDATE side_calls SET ref=? WHERE ref=? AND kind='short-title'",
|
|
(mapping[old], old))
|
|
self._db.commit()
|
|
return n
|
|
|
|
# ── meta ─────────────────────────────────────────────────────────────
|
|
def get_meta(self, key: str) -> str | None:
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
"SELECT value FROM meta WHERE key=?", (key,)).fetchone()
|
|
return row["value"] if row else None
|
|
|
|
def set_meta(self, key: str, value: str) -> None:
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT INTO meta (key, value) VALUES (?,?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
(key, value),
|
|
)
|
|
self._db.commit()
|