A PARSER_VERSION change used to wipe every summary and re-parse all ~6,600 conversations (lists partial for 11-18 min), and during deploy.sh's blue-green overlap the old and new containers each saw a mismatch and wiped each other, leaving the rows the old one wrote last stale until their file changed. - `transcripts.parser_version` (INTEGER), written with every parse. The first start adds it with the global `meta` version (46 on the lab) as its DEFAULT: O(1), no row rewritten, nothing re-parsed. The meta row stays (a pre-per-row image beside this one wipes on a mismatch). - A covering index `transcripts_book (path, mtime, size, parser_version)`: the sweep's change index and the upgrade queue never read the blobs. - A bump wipes nothing: every row keeps serving its summary while `Indexer.upgrade_rows`, between two sweeps, re-parses older rows most recently active first at REPARSE_DUTY (env, 0.5) of a core, written compare-and-set on (mtime, size, version < own). A container never re-parses a row a newer version wrote, so no ping-pong. - MIN_SERVABLE_VERSION (0): rows below it are hidden and re-parsed by the sweep first, for a change that can't be served stale. - aiagent_index_rows_stale / aiagent_index_rows_upgraded_total metrics. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
636 lines
32 KiB
Python
636 lines
32 KiB
Python
"""
|
||
Background indexing for the ai-agent backend.
|
||
|
||
Two jobs, both run on a single daemon thread so they never block requests:
|
||
|
||
1. **Token + cost accounting** — scan the exposed context files, store their
|
||
metadata in SQLite, and compute the *real* Claude token count (via the
|
||
count_tokens endpoint) + dollar cost. To use the API sparingly we only count
|
||
a file when its content hash changed AND it has been stable for at least
|
||
``DEBOUNCE_SECS`` (so we don't burn a call on every keystroke of an edit).
|
||
|
||
2. **Skill-usage analytics** — mine the Claude Code transcripts (``*.jsonl``)
|
||
for ``Skill`` tool calls, counting invocations and last-used time per skill.
|
||
Parsing is incremental: a transcript is only re-read when its mtime/size
|
||
changed, and per-file contributions are summed into the ``skills`` table.
|
||
"""
|
||
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import os
|
||
import pathlib
|
||
import threading
|
||
import time
|
||
|
||
import conversations
|
||
from conversations import rewrite
|
||
|
||
import fsscan
|
||
import tailcopy
|
||
from db import Store
|
||
from telemetry import metrics as tm
|
||
|
||
# Bump when parse_conversation's stored summary shape changes (forces re-parse).
|
||
# v2: archive-backed indexing + byTool / projectsAuto fields in the summary.
|
||
# v3: lifecycleAuto (CI/CD stamps derived from transcript script/command usage).
|
||
# v4: doneMarker (last message ends with DONE → conversation finished).
|
||
# v5: memoriesRead (slugs of memories recalled into the transcript).
|
||
# v6: searchMsgs (ordered user/assistant text blocks for full-text search).
|
||
# v7: interruptedByUser (trailing "[Request interrupted by user]" → interrupted).
|
||
# v8: isSidechain/agentId (subagent transcripts flagged, hidden from lists,
|
||
# linked from the parent's Task/Agent card + usage rolled into the parent).
|
||
# v9: worktreeAuto (name of the git worktree mined from a new-worktree.sh call).
|
||
# v10: worktreesAuto (list of created/removed worktrees w/ create+remove dates).
|
||
# v11: worktree parse anchored to command position + name validation (drop noise).
|
||
# v12: projectsAuto/servicesAuto tag only projects a conversation *edited* (target
|
||
# path of Write/Edit/MultiEdit/NotebookEdit), not every cwd/read/bash mention.
|
||
# v13: byToolSub (second-level per-bucket usage breakdown).
|
||
# v14: pausedByUser (trailing "No response requested." → paused); interrupt +
|
||
# no-response markers hidden from the thread (rendered as compact tags).
|
||
# v15: models (every model that produced a turn, busiest first) → model tags on
|
||
# past conversations, not just the first model seen.
|
||
# v16: `<synthetic>` (Claude Code's placeholder model on messages it fabricates)
|
||
# never counts as a model the conversation ran on.
|
||
# v20: cost accumulates per assistant record — a pi record's runner-mirrored
|
||
# `costUSD` (real provider cost) beats the price-table estimate, and bare
|
||
# (local EVOX2) qwen ids price at 0.
|
||
# v21: first-turn context split — the first API call's input side divided into
|
||
# injected context (system prompt, CLAUDE.md, memories) vs the user's
|
||
# actual message: new top-level "context" activity bucket +
|
||
# firstContextTokens/firstMessageTokens + per-item turnContext/MessageTokens.
|
||
# v25: completedMarker (last message ends with COMPLETED → the `complete`
|
||
# skill's own reply, distinct from the task's own DONE marker).
|
||
# v26: activeBins — per model, the 5-minute wall-clock bins the run worked in
|
||
# (the activity dashboard's histogram source).
|
||
# v27: a deploy is recognised by the program a Bash call *runs*
|
||
# (conversations/deploycmd.py), not by `deploy*.sh` appearing anywhere in
|
||
# it — `cat`/`grep`/`bash -n` of a deploy script no longer stamps
|
||
# "deployed", marks the card "deploying…" or hangs a deployedUrl.
|
||
# v28: one priced usage per API call (dedup on message id + request id — the
|
||
# per-content-block records each repeat the call's usage), per-version
|
||
# price book, planUnits / byModel (per effort) / meterBins / priceBook.
|
||
# v29: a follow-up a busy run absorbed mid-turn (recorded only as a
|
||
# `queued_command` attachment, no `user` record) is the user's turn —
|
||
# bubble, user-turn count, search, fork point.
|
||
# v30: conversation resources (conversations/resources.py) — resourcesAuto,
|
||
# resourceInfo, resourceTeams, slackChannels; the re-parse is the
|
||
# backfill of every past conversation's pills and resource titles.
|
||
# v31: a skill's injected prompt is found by its record's `sourceToolUseID`
|
||
# (built-in/plugin skills carry no "Base directory" line) or by following a
|
||
# typed `/name` — never a user turn; a typed skill counts as a call; each
|
||
# skill's latest prompt fills `skill_prompts` (the catalog's built-ins).
|
||
# v32: Claude Code's "[Image: original WxH, displayed at WxH…]" resize note is
|
||
# dropped — no "You" bubble, no user turn, not searchable.
|
||
# v33: `firstPrompt` (the opening ask, for the Haiku action label) and a Linear
|
||
# issue's labels / project / team in `resourceInfo` (the card's work icon).
|
||
# v34: project/service auto-tags only from `~/projects/<slug>/` and a homelab
|
||
# checkout's `projects|services/<slug>/` — another repo's folder of that
|
||
# name (Orus's `docs/projects/nl-aovql/`, `…/services/<file>.ts`) and a
|
||
# file (not a directory) no longer tag.
|
||
# v35: commitsAuto — the commits a session made (conversations/commits.py):
|
||
# the Bash hook's exact `gitCommits` record, else git's own
|
||
# `[branch sha] subject` line; pushes mark them pushed.
|
||
# v36: a hook commit dated before its Bash call is dropped (a hook updated
|
||
# mid-call recorded all history); pushes match abbreviated shas.
|
||
# v38: a local (EVOX2) call is priced from its duration — electricity +
|
||
# hardware amortisation (pricing.local_call) — and `local` carries the
|
||
# Wh / seconds behind it.
|
||
# v39: turnEnded — the transcript ends on the CLI's `stop_hook_summary` (or a
|
||
# harness mirror's `turn_end`) with nothing after it: the turn is over,
|
||
# DONE or not.
|
||
# v40: a turn that ends with a background agent still running isn't
|
||
# turnEnded; a blocking agent's report (its trailing "agentId:" line) no
|
||
# longer reads as a launch left open forever; a SendMessage that resumes
|
||
# a stopped agent reopens its call.
|
||
# v41: …and its notification (naming the SendMessage) closes it again.
|
||
# v42: writtenDirsAuto / gitRootsAuto / worktreeAddsAuto — where a worker
|
||
# conversation wrote, for projects/workers.py's project deduction.
|
||
# v43: price book 2026-11-09 — Sonnet 5.5 cache reads are $0.10/M (0.05× its
|
||
# input, like Opus 5.5), not Sonnet 5's $0.20: every Sonnet 5.5 run is
|
||
# re-priced.
|
||
# v44: codeMode — the session runs in Claude Code's Code Mode (its
|
||
# `repl-mode` record): the reply box's badge, and its turns resume on
|
||
# the sidecar's pty wrapper (launch.py "Code Mode").
|
||
# v45: neutral tool names (parse/readers/toolnames.py): a tool card's `name`
|
||
# is `shell` / `read` / `edit` / `agent` / `todo` … or `claude:CronCreate`
|
||
# (`native` keeps the harness's own), the cost buckets `bash` → `shell`
|
||
# and `task` → `todo` (TaskOutput / TaskStop now count as shell, TaskGet /
|
||
# TaskList as todo), byToolSub's tool sub-keys neutral.
|
||
# v46: a background task ends when the CLI *queues* its notice, not when the
|
||
# model reads it (`taskUnreadAt` until then, `taskReadAt` after); the
|
||
# restart's "didn't finish" `stopped` no longer overrides a real end; the
|
||
# sidecar's restart note (`<ai-agent-tasks-done>`) leaves the bubble.
|
||
#
|
||
# Each row keeps the version that wrote it (`transcripts.parser_version`). A
|
||
# bump no longer wipes the store: every row keeps serving its summary until
|
||
# the upgrade pass (`upgrade_rows`, throttled to REPARSE_DUTY of a core, most
|
||
# recently active first) re-parses it, and a file that changes is re-parsed
|
||
# at once as always. A container only upgrades rows *older* than its own
|
||
# version, so the two containers of a blue-green deploy never undo each other.
|
||
PARSER_VERSION = 46
|
||
# Rows older than this are not served: the sweep re-parses them first, as the
|
||
# old global wipe did, but for those rows only. Leave it alone on a normal
|
||
# bump — an old summary lacks the new fields and the UI copes (every field a
|
||
# version adds is optional) — and raise it to PARSER_VERSION only for a change
|
||
# whose old summaries would render *wrong*.
|
||
MIN_SERVABLE_VERSION = 0
|
||
# Share of one core the upgrade pass may use: after each file it rests
|
||
# (1/REPARSE_DUTY - 1) × the time that file took.
|
||
REPARSE_DUTY = min(1.0, max(0.05, float(os.environ.get("REPARSE_DUTY", "0.5"))))
|
||
|
||
MODEL = os.environ.get("TOKEN_MODEL", "claude-opus-4-8")
|
||
# Input-token price in USD per million tokens (Opus 4.8 = $5.00 / 1M).
|
||
INPUT_PRICE_PER_MTOK = float(os.environ.get("INPUT_PRICE_PER_MTOK", "5.0"))
|
||
DEBOUNCE_SECS = float(os.environ.get("TOKEN_DEBOUNCE_SECS", "30"))
|
||
SCAN_INTERVAL = float(os.environ.get("INDEX_INTERVAL_SECS", "60"))
|
||
# How often the workspace is re-walked to *discover* exposed files. The walk
|
||
# visits every project dir to find ~280 files, so it is far too expensive to
|
||
# redo each SCAN_INTERVAL; between walks the cached list is just re-stat'd
|
||
# (which is what catches edits). A save forces a walk, so the UI never waits.
|
||
WALK_INTERVAL_SECS = float(os.environ.get("WALK_INTERVAL_SECS", "120"))
|
||
# With the workspace under inotify (files.discovery.WorkspaceWatch) a walk only
|
||
# follows a change it reported; this is the safety net behind it.
|
||
WALK_SAFETY_SECS = float(os.environ.get("WALK_SAFETY_SECS", "1800"))
|
||
RETRY_ESTIMATE_SECS = 300.0 # retry API-failed (estimated) files at most this often
|
||
|
||
MD_EXTS = {".md", ".markdown"}
|
||
|
||
|
||
def _price(tokens: int) -> float:
|
||
return tokens / 1_000_000 * INPUT_PRICE_PER_MTOK
|
||
|
||
|
||
def _estimate_tokens(text: str) -> int:
|
||
"""Cheap fallback used before/instead of an API count (~chars/4)."""
|
||
return math.ceil(len(text) / 4) if text else 0
|
||
|
||
|
||
class Indexer:
|
||
def __init__(self, store: Store, workspace: pathlib.Path,
|
||
source_dir,
|
||
archive_dir: pathlib.Path | None, iter_files, read_text,
|
||
source_accounts: dict | None = None, on_account=None,
|
||
files_watch=None, on_closing_notify=None):
|
||
self.store = store
|
||
# Called with (summary, block) for a transcript whose latest
|
||
# main-thread message ended on a ```notify block
|
||
# (conversations/closing_notify.py) — the hub pushes it once
|
||
# (notifications/closing.py). Every re-parse calls it again.
|
||
self._on_closing_notify = on_closing_notify
|
||
# Says when the cached workspace walk may be stale (WorkspaceWatch);
|
||
# None = re-walk every WALK_INTERVAL_SECS.
|
||
self._files_watch = files_watch
|
||
# Which Claude account a live source dir belongs to (non-default ones
|
||
# only — accounts.py), and the callback that records it per imported
|
||
# transcript: the archive merges every source into one tree, so the
|
||
# import is the last moment the origin is known.
|
||
self.source_accounts = dict(source_accounts or {})
|
||
self._on_account = on_account
|
||
self.workspace = workspace
|
||
# Live transcript sources (read-only mounts): the Claude Code projects
|
||
# dir, plus the pi runner's mirror dir. A single path or a list — both
|
||
# are imported into the same archive (session UUIDs keep them distinct).
|
||
if source_dir is None:
|
||
self.source_dirs = []
|
||
elif isinstance(source_dir, (list, tuple)):
|
||
self.source_dirs = [d for d in source_dir if d]
|
||
else:
|
||
self.source_dirs = [source_dir]
|
||
# Our persistent copy: transcripts are imported here so deleted ones
|
||
# survive. Indexing + the detail view read from the archive.
|
||
self.archive_dir = archive_dir
|
||
# Back-compat alias used by the conversation detail endpoint.
|
||
self.transcripts_dir = archive_dir or (
|
||
self.source_dirs[0] if self.source_dirs else None)
|
||
self._iter_files = iter_files # () -> yields (abs_path, rel_posix)
|
||
self._read_text = read_text # (abs_path) -> str
|
||
self._client = None
|
||
self._client_tried = False
|
||
self._stop = threading.Event()
|
||
# Resumable parser states for *growing* transcripts: abs path →
|
||
# (byte offset of the next unread line, its rewrite.Mark, ParserState).
|
||
# A live session's transcript changes every couple of seconds; feeding
|
||
# only the appended lines keeps the per-tick parse cost flat instead of
|
||
# O(file size). The mark says when the file was rewritten instead of
|
||
# appended to (conversations/rewrite.py): that one starts over.
|
||
# In-memory only — a restart simply re-parses once. LRU-capped: only a
|
||
# handful of transcripts grow concurrently.
|
||
self._live: dict[str, tuple[int, "rewrite.Mark", "conversations.ParserState"]] = {}
|
||
self._live_cap = 8
|
||
# Cached result of the workspace walk (see _exposed_files).
|
||
self._files_cache: list | None = None
|
||
self._walked_at = 0.0
|
||
# Throttle skill-table rollups on targeted 2 s watcher ticks and run
|
||
# periodic WAL checkpoints in `_loop()`.
|
||
self._skills_dirty = False
|
||
self._skills_agg_at = 0.0
|
||
self._checkpoint_at = time.monotonic()
|
||
store.hide_below(MIN_SERVABLE_VERSION)
|
||
# (path, mtime, size) the upgrade pass failed to parse: not retried
|
||
# every minute, only once the file changes (or on a restart).
|
||
self._upgrade_failed: set[tuple[str, float, int]] = set()
|
||
|
||
# ── Anthropic client (lazy) ──────────────────────────────────────────
|
||
def _anthropic(self):
|
||
if self._client_tried:
|
||
return self._client
|
||
self._client_tried = True
|
||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||
return None
|
||
try:
|
||
import anthropic
|
||
self._client = anthropic.Anthropic()
|
||
except Exception:
|
||
self._client = None
|
||
return self._client
|
||
|
||
def _count_tokens_api(self, text: str) -> int | None:
|
||
if not text.strip():
|
||
return 0
|
||
client = self._anthropic()
|
||
if client is None:
|
||
return None
|
||
try:
|
||
r = client.messages.count_tokens(
|
||
model=MODEL,
|
||
messages=[{"role": "user", "content": text}],
|
||
)
|
||
return int(r.input_tokens)
|
||
except Exception:
|
||
return None
|
||
|
||
# ── file scan + token accounting ─────────────────────────────────────
|
||
def _exposed_files(self, force_walk: bool) -> list:
|
||
"""The exposed context files, from a cached directory walk.
|
||
|
||
Discovering them means walking the whole workspace (every project dir),
|
||
which is far more expensive than the ~280 files it finds — and it was
|
||
being redone on every scan interval. The file *list* changes only when
|
||
a file is added or removed, so the walk is cached and refreshed when
|
||
the workspace watch reports such a change (every ``WALK_SAFETY_SECS``
|
||
regardless), every ``WALK_INTERVAL_SECS`` without a watch, or on
|
||
demand (e.g. right after a save)."""
|
||
now = time.time()
|
||
watch = self._files_watch
|
||
watching = watch is not None and watch.active
|
||
dirty = watching and watch.take()
|
||
interval = WALK_SAFETY_SECS if watching else WALK_INTERVAL_SECS
|
||
if (self._files_cache is None or force_walk or dirty
|
||
or (now - self._walked_at) >= interval):
|
||
self._files_cache = list(self._iter_files())
|
||
self._walked_at = now
|
||
if watch is not None:
|
||
watch.known(self._files_cache)
|
||
return self._files_cache
|
||
|
||
def scan_files(self, force_walk: bool = False) -> None:
|
||
"""Record on-disk metadata for every exposed file.
|
||
|
||
Stat-gated: a file whose (mtime, size) matches its stored row is
|
||
skipped without being read, so a scan costs one stat per exposed file
|
||
— not a read+sha256 of the whole context tree. Word and char counts are
|
||
stored alongside (recomputed only on change) so ``/api/bundle`` can be
|
||
served from the DB without touching disk."""
|
||
seen: set[str] = set()
|
||
rows = self.store.all_files()
|
||
for ap, rel in self._exposed_files(force_walk):
|
||
relstr = str(rel)
|
||
try:
|
||
st = ap.stat()
|
||
except OSError:
|
||
continue # vanished since the walk — let the next walk prune it
|
||
seen.add(relstr)
|
||
row = rows.get(relstr)
|
||
if (row is not None and row["mtime"] == st.st_mtime
|
||
and row["size"] == st.st_size
|
||
and row["words"] is not None):
|
||
continue # unchanged on disk — nothing to record
|
||
try:
|
||
data = ap.read_bytes()
|
||
except OSError:
|
||
continue
|
||
digest = hashlib.sha256(data).hexdigest()
|
||
text = data.decode("utf-8", "ignore")
|
||
self.store.upsert_file_meta(
|
||
relstr, digest, st.st_size, st.st_mtime,
|
||
rel.suffix.lower() in MD_EXTS,
|
||
words=len(text.split()), chars=len(text),
|
||
)
|
||
self.store.prune_files(seen)
|
||
|
||
def count_pending(self) -> int:
|
||
"""Compute real token counts for changed/stale files past the debounce
|
||
window. Returns how many files were (re)counted."""
|
||
now = time.time()
|
||
done = 0
|
||
for path, row in self.store.all_files().items():
|
||
stale = bool(row["estimated"]) or row["tokens"] is None
|
||
if not stale:
|
||
continue
|
||
# debounce: only spend a call once the file has settled
|
||
if row["mtime"] and (now - row["mtime"]) < DEBOUNCE_SECS:
|
||
continue
|
||
# don't hammer the API on files that keep failing
|
||
if (row["tokens"] is not None and row["counted_at"]
|
||
and (now - row["counted_at"]) < RETRY_ESTIMATE_SECS):
|
||
continue
|
||
ap = self.workspace / path
|
||
text = self._read_text(ap)
|
||
tokens = self._count_tokens_api(text)
|
||
if tokens is None:
|
||
tokens = _estimate_tokens(text)
|
||
self.store.set_tokens(path, tokens, _price(tokens), estimated=True)
|
||
else:
|
||
self.store.set_tokens(path, tokens, _price(tokens), estimated=False)
|
||
done += 1
|
||
return done
|
||
|
||
# ── transcript import (persist live transcripts before Claude prunes) ──
|
||
def _copy_in(self, src: pathlib.Path, rel: pathlib.PurePath,
|
||
mtime: float, size: int, changed: list[str]) -> None:
|
||
"""Copy one source transcript into the archive if it's new or grew —
|
||
only the new bytes when it grew (tailcopy)."""
|
||
dst = self.archive_dir / rel
|
||
try:
|
||
d = dst.stat()
|
||
if d.st_size >= size and d.st_mtime >= mtime:
|
||
return
|
||
except OSError:
|
||
pass # not in the archive yet
|
||
try:
|
||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||
tailcopy.sync(src, dst)
|
||
changed.append(rel.as_posix())
|
||
except OSError:
|
||
pass
|
||
|
||
def import_transcripts(self, only: list[str] | None = None) -> list[str]:
|
||
"""Copy new/grown source transcripts into the archive. Append-only, so
|
||
we copy when the source is larger or newer; we never delete archived
|
||
copies whose source has vanished. Returns the rel paths that changed.
|
||
|
||
Also copies each subagent's tiny `agent-<id>.meta.json` sidecar (it
|
||
carries the `toolUseId` that links a subagent back to the parent's
|
||
Task/Agent card, so the detail endpoint can cross-link them).
|
||
|
||
``only`` restricts the import to the given source-relative paths — the
|
||
watcher already knows exactly which transcripts changed, so the live
|
||
path doesn't re-walk thousands of files every couple of seconds. A
|
||
sibling `.meta.json` is pulled in alongside each named `.jsonl`; the
|
||
periodic full pass (``only=None``) catches anything else."""
|
||
if not (self.source_dirs and self.archive_dir):
|
||
return []
|
||
changed: list[str] = []
|
||
for source_dir in self.source_dirs:
|
||
if not source_dir.is_dir():
|
||
continue
|
||
if only is None:
|
||
acct = self.source_accounts.get(source_dir)
|
||
for suffix in (".jsonl", ".meta.json"):
|
||
for path, mtime, size in fsscan.walk_files(source_dir, suffix):
|
||
src = pathlib.Path(path)
|
||
rel = src.relative_to(source_dir)
|
||
self._copy_in(src, rel, mtime, size, changed)
|
||
if acct and suffix == ".jsonl":
|
||
self._note_account(rel, acct)
|
||
continue
|
||
for rel in only:
|
||
relp = pathlib.PurePosixPath(rel)
|
||
cands = [relp]
|
||
if relp.suffix == ".jsonl": # its subagent metadata sidecar
|
||
cands.append(relp.with_suffix(".meta.json"))
|
||
for cand in cands:
|
||
src = source_dir / cand
|
||
try:
|
||
st = src.stat()
|
||
except OSError:
|
||
continue
|
||
self._copy_in(src, cand, st.st_mtime, st.st_size, changed)
|
||
acct = self.source_accounts.get(source_dir)
|
||
if acct and cand.suffix == ".jsonl":
|
||
self._note_account(cand, acct)
|
||
return changed
|
||
|
||
def _note_account(self, rel: pathlib.PurePath, account: str) -> None:
|
||
"""Tell the app a transcript came out of ``account``'s source dir. The
|
||
callback is idempotent and cheap (a no-op once the session is stamped),
|
||
so the full sweep calling it for every file is fine."""
|
||
if self._on_account is None:
|
||
return
|
||
try:
|
||
self._on_account(pathlib.PurePosixPath(rel).as_posix(), account)
|
||
except Exception:
|
||
pass
|
||
|
||
# ── transcript analytics (skills + per-conversation summaries) ────────
|
||
def _parse_summary(self, ap, mtime: float, size: int) -> dict:
|
||
"""Summary of a transcript — incremental when we saw it grow before,
|
||
from the top when it was rewritten since (``rewrite.advance``)."""
|
||
relstr = str(ap)
|
||
live = self._live.pop(relstr, None) # pop = LRU re-insert on success
|
||
offset, mark, state = live if live is not None else (0, None, None)
|
||
fresh = lambda: conversations.ParserState(ap, full=False) # noqa: E731
|
||
res = rewrite.advance(ap, state if state is not None else fresh(), offset,
|
||
mark, mtime, size, fresh)
|
||
if res is None:
|
||
return conversations.parse_conversation(ap, full=False)
|
||
state, offset, mark, _ = res
|
||
if mark is not None: # None: rewritten while read — don't resume it
|
||
self._live[relstr] = (offset, mark, state)
|
||
while len(self._live) > self._live_cap: # evict least-recently-grown
|
||
self._live.pop(next(iter(self._live)))
|
||
return state.summary()
|
||
|
||
def _store_parse(self, relstr: str, mtime: float, size: int, summary: dict,
|
||
upgrade: bool = False) -> bool:
|
||
"""Write a parse into the store: skills, skill prompts, the summary at
|
||
this ``PARSER_VERSION`` (``upgrade``: as the upgrade pass's
|
||
compare-and-set), then the closing push. True when it wrote."""
|
||
skills = summary.pop("skills", {})
|
||
pushed = summary.pop("closingNotify", None)
|
||
# Before the upsert, so the refetch its change event triggers sees it.
|
||
self.store.keep_skill_prompts(relstr, summary.pop("skillPrompts", None) or {})
|
||
if upgrade:
|
||
if not self.store.upgrade_transcript(relstr, mtime, size, PARSER_VERSION,
|
||
skills, summary):
|
||
return False
|
||
else:
|
||
self.store.upsert_transcript(relstr, mtime, size, skills, summary,
|
||
version=PARSER_VERSION)
|
||
if pushed and self._on_closing_notify is not None:
|
||
try:
|
||
self._on_closing_notify(summary, pushed)
|
||
except Exception:
|
||
pass
|
||
return True
|
||
|
||
def scan_transcripts(self, only: list[str] | None = None) -> None:
|
||
"""Import + (re)parse transcripts into the store.
|
||
|
||
``only`` is the source-relative paths the watcher saw change: the live
|
||
path then imports and re-parses just those, instead of re-walking every
|
||
source dir and the whole archive on each 2-second tick. The indexer's
|
||
own periodic pass (``only=None``) still does the full sweep, which is
|
||
what discovers files the watcher missed and prunes deleted ones."""
|
||
self.import_transcripts(only)
|
||
if not self.transcripts_dir or not self.transcripts_dir.is_dir():
|
||
return
|
||
# A parser bump re-parses nothing here: an unchanged file keeps its row
|
||
# (whichever version wrote it) until upgrade_rows reaches it — unless
|
||
# that version is below MIN_SERVABLE_VERSION, which isn't served.
|
||
rows: dict | None = None
|
||
if only is not None:
|
||
targets = []
|
||
for rel in only:
|
||
ap = self.transcripts_dir / rel
|
||
try:
|
||
st = ap.stat()
|
||
except OSError:
|
||
continue
|
||
targets.append((str(ap), st.st_mtime, st.st_size))
|
||
else:
|
||
rows = self.store.all_transcripts()
|
||
targets = list(fsscan.walk_files(self.transcripts_dir, ".jsonl"))
|
||
targets.sort(key=lambda t: t[1], reverse=True) # most recent first
|
||
|
||
seen: set[str] = set()
|
||
changed = False
|
||
for relstr, mtime, size in targets:
|
||
seen.add(relstr)
|
||
row = (rows.get(relstr) if rows is not None
|
||
else self.store.transcript_book(relstr))
|
||
if (row and row["mtime"] == mtime and row["size"] == size
|
||
and row["parser_version"] >= MIN_SERVABLE_VERSION):
|
||
continue
|
||
summary = self._parse_summary(pathlib.Path(relstr), mtime, size)
|
||
self._store_parse(relstr, mtime, size, summary)
|
||
changed = True
|
||
# Only a full sweep knows what's gone; a targeted pass must not prune.
|
||
if only is None and rows is not None and rows.keys() - seen:
|
||
self.store.prune_transcripts(seen)
|
||
changed = True
|
||
if changed:
|
||
self._skills_dirty = True
|
||
now = time.monotonic()
|
||
if self._skills_dirty and (only is None or now - self._skills_agg_at >= 30.0):
|
||
self._aggregate_skills()
|
||
self._skills_dirty = False
|
||
self._skills_agg_at = now
|
||
|
||
# ── the upgrade pass (rows an older PARSER_VERSION wrote) ─────────────
|
||
def _upgrade_one(self, row) -> bool:
|
||
"""Re-parse one row an older parser wrote. Only a file that still is
|
||
what the row describes: one that moved since is the sweep's and the
|
||
watcher's (they re-parse it at this version anyway), and the write is
|
||
a compare-and-set, so a live write meanwhile wins."""
|
||
relstr, mtime, size = row["path"], row["mtime"], row["size"]
|
||
ap = pathlib.Path(relstr)
|
||
try:
|
||
st = ap.stat()
|
||
except OSError:
|
||
return False # gone: the next sweep prunes it
|
||
if (st.st_mtime, st.st_size) != (mtime, size):
|
||
return False
|
||
# One-shot: an idle file has no business in the live-state LRU.
|
||
summary = conversations.parse_conversation(ap, full=False)
|
||
try:
|
||
st = ap.stat()
|
||
except OSError:
|
||
return False
|
||
if (st.st_mtime, st.st_size) != (mtime, size):
|
||
return False # written while parsed: the watcher has it
|
||
return self._store_parse(relstr, mtime, size, summary, upgrade=True)
|
||
|
||
def upgrade_rows(self, deadline: float | None = None) -> int:
|
||
"""Re-parse the rows an older ``PARSER_VERSION`` wrote, most recently
|
||
active first, until none is left or ``deadline`` (monotonic) passes.
|
||
After each file it rests long enough to stay within ``REPARSE_DUTY``
|
||
of a core. Never a row a *newer* version wrote (``<``, numerically):
|
||
during a blue-green deploy the old container leaves the new one's
|
||
rows alone. Returns how many rows it re-parsed."""
|
||
rows = self.store.stale_transcripts(PARSER_VERSION)
|
||
tm.INDEX_ROWS_STALE.set(len(rows))
|
||
done = 0
|
||
for row in rows:
|
||
if self._stop.is_set() or (deadline is not None
|
||
and time.monotonic() >= deadline):
|
||
break
|
||
# Still stale? The live path may have re-parsed it meanwhile.
|
||
cur = self.store.transcript_book(row["path"])
|
||
if cur is None or cur["parser_version"] >= PARSER_VERSION:
|
||
continue
|
||
key = (cur["path"], cur["mtime"], cur["size"])
|
||
if key in self._upgrade_failed:
|
||
continue
|
||
t0 = time.monotonic()
|
||
try:
|
||
ok = self._upgrade_one(cur)
|
||
except Exception:
|
||
ok = False
|
||
self._upgrade_failed.add(key)
|
||
if ok:
|
||
done += 1
|
||
tm.INDEX_ROWS_UPGRADED.inc()
|
||
tm.INDEX_ROWS_STALE.dec()
|
||
self._skills_dirty = True
|
||
if REPARSE_DUTY < 1.0:
|
||
self._stop.wait((time.monotonic() - t0) * (1.0 / REPARSE_DUTY - 1.0))
|
||
return done
|
||
|
||
def _aggregate_skills(self) -> None:
|
||
agg: dict[str, dict] = {}
|
||
for skills_json in self.store.all_transcript_skills():
|
||
try:
|
||
contrib = json.loads(skills_json or "{}")
|
||
except ValueError:
|
||
continue
|
||
for name, d in contrib.items():
|
||
e = agg.setdefault(name, {"count": 0, "last_used": None})
|
||
e["count"] += d.get("count", 0)
|
||
last = d.get("last")
|
||
if last and (e["last_used"] is None or last > e["last_used"]):
|
||
e["last_used"] = last
|
||
self.store.replace_skills(agg)
|
||
|
||
# ── lifecycle ────────────────────────────────────────────────────────
|
||
def run_once(self) -> None:
|
||
"""One full sweep: re-stat the context files, count what's pending, and
|
||
do the complete transcript discovery + prune pass."""
|
||
self.scan_files()
|
||
self.count_pending()
|
||
self.scan_transcripts()
|
||
|
||
def _loop(self) -> None:
|
||
# The watcher already handles live transcript changes (targeted, every
|
||
# couple of seconds). This loop is the slower full sweep: it re-stats
|
||
# the context files for token counting and re-walks the transcript dirs
|
||
# to discover/prune — work that is wasted at a 10-second cadence.
|
||
# Between two sweeps it upgrades the rows an older parser wrote.
|
||
while not self._stop.is_set():
|
||
try:
|
||
self.run_once()
|
||
except Exception:
|
||
pass
|
||
now = time.monotonic()
|
||
if now - self._checkpoint_at >= 3600.0:
|
||
self._checkpoint_at = now
|
||
try:
|
||
getattr(self.store, "wal_checkpoint", lambda: None)()
|
||
except Exception:
|
||
pass
|
||
deadline = time.monotonic() + SCAN_INTERVAL
|
||
try:
|
||
self.upgrade_rows(deadline)
|
||
except Exception:
|
||
pass
|
||
self._stop.wait(max(0.0, deadline - time.monotonic()))
|
||
|
||
def start(self) -> None:
|
||
if self._files_watch is not None:
|
||
self._files_watch.start()
|
||
threading.Thread(target=self._loop, daemon=True).start()
|
||
|
||
def stop(self) -> None:
|
||
self._stop.set()
|