The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_state_search): shared cjk/token helpers, reuse _row_to_message_dict, compact docstrings
Teknium58accf5782a8
diff --git a/hermes_state_search.py b/hermes_state_search.pyindex 25f8ebfb926..b1cc26b2ec7 100644--- a/hermes_state_search.py+++ b/hermes_state_search.py@@ -1,13 +1,10 @@"""Full-text / trigram / CJK message search and FTS maintenance for SessionDB.-Plain mixin consumed by ``hermes_state.SessionDB``: no ``__init__``, no state-of its own; methods use host attributes established by ``SessionDB.__init__``.-Must never import hermes_state (cycle) — shared constants live in-hermes_state_common.+Plain mixin for ``hermes_state.SessionDB`` (no ``__init__``/state of its own).+Must never import hermes_state (cycle); shared constants live in hermes_state_common."""import logging-import jsonimport osimport reimport sqlite3@@ -21,12 +18,11 @@ from hermes_state_common import (escape_like as _escape_like, fts_rebuild_admission,)-# Keep the pre-split logger identity so log filtering/capture is unchanged.+# Pre-split logger identity so log filtering/capture is unchanged.logger = logging.getLogger("hermes_state")-# Characters FTS5's query grammar rejects outside a quoted phrase; anything-# missing here reaches MATCH raw and raises (swallowed into zero results).-# re.escape so the backslash is not eaten. ``%`` is deliberately excluded: the+# Characters FTS5's query grammar rejects outside a quoted phrase (anything missing+# reaches MATCH raw and raises -> zero results). ``%`` is deliberately excluded: the# CJK LIKE fallback needs it literal (that path escapes wildcards itself)._FTS5_SPECIAL_CHARS = '+{}():"^@/#&|~[]<>,;!?$=\\\''_FTS5_SPECIAL_RE = re.compile(f"[{re.escape(_FTS5_SPECIAL_CHARS)}]")@@ -47,8 +43,7 @@ _LIKE_COALESCED_COLUMN_SQL = ("COALESCE(m.tool_name, '') LIKE ? ESCAPE '\\' OR ""COALESCE(m.tool_calls, '') LIKE ? ESCAPE '\\')")-# ``sort`` -> ORDER BY for the FTS routes; anything unknown is rank-only so-# callers can pass user input through.+# ``sort`` -> ORDER BY for the FTS routes; unknown values are rank-only (user input passes through)._FTS_ORDER_BY = {"newest": "ORDER BY m.timestamp DESC, rank", "oldest": "ORDER BY m.timestamp ASC, rank"}# One row before + the hit + one row after, in (timestamp, id) order._CONTEXT_WINDOW_SQL = """WITH target AS (@@ -81,6 +76,15 @@ _CONTEXT_WINDOW_SQL = """WITH target AS (ORDER BY m.timestamp ASC, m.id ASCLIMIT 1)"""+# Unified Ideographs, Extension A, Extension B, CJK Symbols, Hiragana, Katakana, Hangul Syllables.+_CJK_RANGES = (+ (0x4E00, 0x9FFF), (0x3400, 0x4DBF), (0x20000, 0x2A6DF), (0x3000, 0x303F), (0x3040, 0x309F),+ (0x30A0, 0x30FF), (0xAC00, 0xD7AF),+)+_RESULT_FIELDS = (+ "id", "session_id", "role", "snippet", "timestamp", "tool_name", "source", "model",+ "session_started", "context",+)def _meta_row(conn, key: str) -> Optional[sqlite3.Row]:@@ -92,9 +96,16 @@ def _delete_meta(conn, *keys: str) -> None:conn.execute(f"DELETE FROM state_meta WHERE key IN ({','.join('?' for _ in keys)})", keys)+def _is_cjk(cp: int) -> bool:+ return any(lo <= cp <= hi for lo, hi in _CJK_RANGES)+++def _non_operator_tokens(raw_query: str) -> List[str]:+ return [t for t in raw_query.split() if t.upper() not in _FTS_OPERATORS]++def _quote_fts_tokens(raw_query: str) -> str:- """Quote each non-operator token (neutralising FTS5 special characters)- while preserving AND/OR/NOT."""+ """Quote each non-operator token (neutralising FTS5 special characters), keeping AND/OR/NOT."""return " ".join(tok if tok.upper() in _FTS_OPERATORS else '"' + tok.replace('"', '""') + '"'for tok in raw_query.split()@@ -107,21 +118,27 @@ def _like_params(term: str) -> List[str]:def _flatten_text(decoded: Any) -> str:- """Multimodal part list -> joined text (or the placeholder); str passes- through; anything else is ''."""+ """Multimodal part list -> joined text (or the placeholder); str passes through; else ''."""if isinstance(decoded, list):parts = [p.get("text", "") for p in decoded if isinstance(p, dict) and p.get("type") == "text"]return " ".join(t for t in parts if t).strip() or "[multimodal content]"return decoded if isinstance(decoded, str) else ""+def _positive_int(name: str, value: Any) -> None:+ if isinstance(value, bool) or not isinstance(value, int):+ raise TypeError(f"{name} must be an integer")+ if value <= 0:+ raise ValueError(f"{name} must be greater than zero")++def _search_filter_clauses(where: List[str], params: list, *, include_inactive: bool, source_filter: Optional[List[str]],exclude_sources: Optional[List[str]], role_filter: Optional[List[str]],) -> None:- """Append the visibility/source/role predicates every search route shares.- Live rows (active=1) AND compaction-archived rows (compacted=1) are- discoverable; only rewind/undo rows (active=0, compacted=0) are hidden."""+ """Append the visibility/source/role predicates every search route shares. Live rows+ (active=1) AND compaction-archived rows (compacted=1) are discoverable; only+ rewind/undo rows (active=0, compacted=0) are hidden."""if not include_inactive:where.append("(m.active = 1 OR m.compacted = 1)")if source_filter is not None:@@ -138,10 +155,7 @@ def _search_filter_clauses(class SessionSearchMixin:"""See module docstring — mixin for SessionDB (Search cluster)."""- _SEARCH_MESSAGE_RESULT_FIELDS = (- "id", "session_id", "role", "snippet", "timestamp", "tool_name", "source", "model",- "session_started", "context",- )+ _SEARCH_MESSAGE_RESULT_FIELDS = _RESULT_FIELDS@classmethoddef _search_message_fields(cls, fields: Optional[Collection[str]]) -> Optional[Tuple[str, ...]]:@@ -157,11 +171,9 @@ class SessionSearchMixin:return tuple(field for field in cls._SEARCH_MESSAGE_RESULT_FIELDS if field in requested)def _try_incremental_merge_fts(self) -> None:- """Run one bounded FTS5 merge pass without failing the completed write.- The canonical write is already committed: no maintenance failure (even- the bare SystemError CPython's sqlite3 layer can raise under- cross-thread errmsg scrambling) may make the caller replay an- ambiguous, possibly-durable write."""+ """One bounded FTS5 merge pass that never fails the already-committed write (even+ the bare SystemError CPython's sqlite3 layer can raise under cross-thread errmsg+ scrambling must not make the caller replay an ambiguous, possibly-durable write)."""if not self._fts_enabled:returntry:@@ -172,10 +184,9 @@ class SessionSearchMixin:# ── Deferred rebuild engine (base + CJK backfills) ─────────────────────def fts_rebuild_status(self) -> Optional[Dict[str, Any]]:- """Deferred-rebuild progress ``{"pending", "total", "indexed",- "percent"}``, or None when no rebuild is pending. Reads via the pooled- reader (not get_meta, which takes self._lock) so search_messages never- blocks on the writer lock."""+ """Deferred-rebuild progress ``{"pending", "total", "indexed", "percent"}`` or None.+ Reads via the pooled reader (not get_meta, which takes self._lock) so+ search_messages never blocks on the writer lock."""return self._rebuild_status("fts_rebuild")def fts_cjk_rebuild_status(self) -> Optional[Dict[str, Any]]:@@ -214,12 +225,11 @@ class SessionSearchMixin:)def _fts_rebuild_finish(self) -> None:- """Finalize the deferred rebuild: boundary sweep + clear markers.- The sweep is cheap insurance against a write that slipped through the- migration-boundary instant (between high_water capture and trigger- activation). The trigram half is gated on ``_trigram_available``:- without the tokenizer/table an unconditional INSERT raises ``no such- table`` and aborts the whole rebuild (and optimize_fts_storage())."""+ """Finalize the deferred rebuild: boundary sweep + clear markers. The sweep is+ cheap insurance against a write that slipped through the migration-boundary+ instant (between high_water capture and trigger activation). The trigram half+ is gated on ``_trigram_available``: without the tokenizer/table an unconditional+ INSERT raises ``no such table`` and aborts the whole rebuild."""sweeps = [self._BOUNDARY_SWEEP_SQL.format(table="messages_fts", extra="")]if self._trigram_available:sweeps.append(self._BOUNDARY_SWEEP_SQL.format(table="messages_fts_trigram", extra="AND m.role <> 'tool' "))@@ -235,8 +245,7 @@ class SessionSearchMixin:logger.info("CJK FTS index backfill complete — serving CJK search.")def _rebuild_finish(self, prefix: str, sweep_sqls: List[str]) -> None:- """Sweep a generous window around the high-water boundary, then clear- the ``{prefix}_high_water`` / ``{prefix}_progress`` markers."""+ """Sweep a generous window around the high-water boundary, then clear the markers."""def _do(conn):hw_row = _meta_row(conn, f"{prefix}_high_water")if hw_row is not None:@@ -247,10 +256,9 @@ class SessionSearchMixin:self._execute_write(_do)def fts_rebuild_step(self) -> bool:- """Backfill one chunk of the deferred FTS rebuild; True while work- remains. Safe from any process: chunks are claimed atomically inside- the write transaction, so concurrent callers interleave instead of- duplicating rows."""+ """Backfill one chunk of the deferred FTS rebuild; True while work remains. Safe+ from any process: chunks are claimed atomically inside the write transaction, so+ concurrent callers interleave instead of duplicating rows."""if not self._fts_enabled:return Falseinserts = [self._CHUNK_INSERT_SQL.format(table="messages_fts", extra="")]@@ -280,16 +288,15 @@ class SessionSearchMixin:chunk = self._FTS_REBUILD_CHUNK_ROWSdef _do(conn):- # Re-reading progress inside the BEGIN IMMEDIATE held by- # _execute_write IS the claim: two workers cannot read the same value.+ # Re-reading progress inside the BEGIN IMMEDIATE held by _execute_write IS+ # the claim: two workers cannot read the same value.row = _meta_row(conn, f"{prefix}_progress")if row is None:return False # finished (or cleared) by another processprogress = int(row[0])if progress >= high_water:return False- # Upper bound is an id, not a row count, so deleted-row gaps don't- # shrink chunks below the claimed range.+ # Upper bound is an id, not a row count, so deleted-row gaps don't shrink chunks.upper = min(progress + chunk, high_water)for sql in insert_sqls:conn.execute(sql, (progress, upper))@@ -310,14 +317,11 @@ class SessionSearchMixin:return bool(more)def _fts_teardown_trash_step(self) -> bool:- """Tear down one chunk of a demoted v22 FTS shadow table; True while- work remains.-- Trash tables are PLAIN tables (their vtable parent was demoted), so no- FTS5 machinery is involved. Integer single-column-key tables drain with- a high-water marker so each chunk's scan is bounded (restarting the- scan was O(n²)); compound-key tables cannot use a scalar high-water and- keep the chunked ``LIMIT`` delete — they are small by construction."""+ """Tear down one chunk of a demoted v22 FTS shadow table; True while work remains.+ Trash tables are PLAIN tables (their vtable parent was demoted). Integer+ single-column-key tables drain with a high-water marker so each chunk's scan is+ bounded (restarting the scan was O(n²)); compound-key tables keep the chunked+ ``LIMIT`` delete — they are small by construction."""with self._lock:trash = [r[0] for r in self._conn.execute(@@ -335,10 +339,9 @@ class SessionSearchMixin:pk_cols = [name for name, _typ in pk_info]key = ", ".join(pk_cols) if pk_cols else "rowid"if len(pk_cols) == 1 and (not pk_info or pk_info[0][1] == "INTEGER"):- # High-water drain; the marker is read/written in the same- # BEGIN IMMEDIATE as the DELETE so concurrent callers claim- # disjoint ranges. Only INTEGER pks anchor the comparison (the- # TEXT-pk config shadow table falls through below).+ # High-water drain; marker read/written in the same BEGIN IMMEDIATE as the+ # DELETE so concurrent callers claim disjoint ranges. Only INTEGER pks+ # anchor the comparison (the TEXT-pk config shadow table falls through).marker_key = f"fts_teardown_{tbl}_progress"row = _meta_row(conn, marker_key)high_water = int(row[0]) if row is not None else 0@@ -378,10 +381,9 @@ class SessionSearchMixin:return Truedef _fts_cjk_reset_if_stale(self) -> None:- """From-scratch rebuild of a stale cjk index (triggers were dropped,- gap extent unknown): drop table + triggers, clear the breadcrumb,- recreate via ``_ensure_fts_cjk_schema`` (fresh backfill markers on a- populated DB). No-op when not stale."""+ """From-scratch rebuild of a stale cjk index (triggers were dropped, gap extent+ unknown): drop table + triggers, clear the breadcrumb, recreate via+ ``_ensure_fts_cjk_schema`` (fresh backfill markers on a populated DB)."""if not self._fts_cjk_loaded:return@@ -395,18 +397,19 @@ class SessionSearchMixin:_delete_meta(conn, FTS_CJK_STALE_KEY, "fts_cjk_rebuild_high_water", "fts_cjk_rebuild_progress")return Trueif self._execute_write(_do):- # Recreate OUTSIDE the write transaction: _ensure_fts_cjk_schema uses- # executescript(), which implicitly commits.- with self._lock:- self._ensure_fts_cjk_schema(self._conn)- self._conn.commit()+ # Recreate OUTSIDE the write transaction: executescript() implicitly commits.+ self._ensure_cjk_schema_committed()++ def _ensure_cjk_schema_committed(self) -> None:+ with self._lock:+ self._ensure_fts_cjk_schema(self._conn)+ self._conn.commit()def _fts_external_index_empty_with_messages(self, conn) -> bool:- """True when the base FTS table indexes nothing while ``messages`` has- rows (the post-demote empty-index shape). Caller holds ``self._lock``.- Healthy and mid-backfill installs never match. docsize is the- authoritative "is this rowid indexed" surface for external-content- FTS5; EXISTS not COUNT(*) because this runs on every writable open."""+ """True when the base FTS table indexes nothing while ``messages`` has rows (the+ post-demote empty-index shape). Caller holds ``self._lock``. docsize is the+ authoritative "is this rowid indexed" surface for external-content FTS5; EXISTS+ not COUNT(*) because this runs on every writable open."""try:if not conn.execute("SELECT EXISTS(SELECT 1 FROM messages)").fetchone()[0]:return False@@ -415,20 +418,17 @@ class SessionSearchMixin:return False # table absent / FTS disabled mid-init — not this failure classdef _fts_index_known_empty(self, conn) -> bool:- """True when the base external-content index holds no rows; a missing- table counts as empty (the schema ensure that follows creates it)."""+ """True when the base external-content index holds no rows; a missing table counts."""try:return int(conn.execute("SELECT COUNT(*) FROM messages_fts_docsize").fetchone()[0]) == 0except sqlite3.OperationalError:return Truedef _reset_fts_index_to_empty(self, conn) -> None:- """Truncate the v23 external-content tables via FTS5 ``'delete-all'``.- A plain DELETE is O(rows) on external-content FTS5 and corrupts the- index when indexed rows diverged from ``messages`` — exactly the shape- this repair handles. The backfill worker replays its id range with no- anti-join, so a replay from zero is only safe once the index is known- empty; this is how a partially indexed DB gets there."""+ """Truncate the v23 external-content tables via FTS5 ``'delete-all'``. A plain+ DELETE is O(rows) and corrupts the index when indexed rows diverged from+ ``messages``. The backfill worker replays its id range with no anti-join, so a+ replay from zero is only safe once the index is known empty."""for tbl in ("messages_fts", "messages_fts_trigram"):try:conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('delete-all')")@@ -436,21 +436,18 @@ class SessionSearchMixin:pass # table absent — already an empty surfacedef _reseed_missing_progress(self, conn) -> None:- """high_water without progress: fts_rebuild_step reads missing progress- as "done by another process" and optimize would no-op then stamp.- Reset a partially indexed DB to a known-empty surface (the chunk- worker replays without an anti-join) and re-seed progress."""+ """high_water without progress: fts_rebuild_step reads missing progress as "done+ by another process" and optimize would no-op then stamp. Reset a partially+ indexed DB to a known-empty surface and re-seed progress."""if _meta_row(conn, "fts_rebuild_progress") is None:if not self._fts_index_known_empty(conn):self._reset_fts_index_to_empty(conn)self.set_meta("fts_rebuild_progress", "0", cursor=conn)def _seed_fts_rebuild_markers(self, conn, *, force: bool = False) -> int:- """Write ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` for a- full backfill; returns the high-water id. Without ``force`` and with- high_water already set, only repairs a missing progress key (see- ``_reseed_missing_progress`` for why a missing key must not read as- "done"). Caller holds the write transaction."""+ """Write ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` for a full backfill;+ returns the high-water id. Without ``force`` and with high_water already set,+ only repairs a missing progress key. Caller holds the write transaction."""existing_hw = _meta_row(conn, "fts_rebuild_high_water")if existing_hw is not None and not force:self._reseed_missing_progress(conn)@@ -461,12 +458,11 @@ class SessionSearchMixin:return int(hw)def _repair_optimize_bookkeeping(self) -> None:- """Heal interrupted demote/backfill bookkeeping before optimize runs:- orphan high_water-without-progress gets progress re-seeded; an empty- external index with messages and no markers (demote crash window /- premature stamp) gets a full backfill claim. Never invents markers on a- still-legacy inline DB — optimize would then skip demote and INSERT- against the inline table forever."""+ """Heal interrupted demote/backfill bookkeeping before optimize runs: orphan+ high_water-without-progress gets progress re-seeded; an empty external index+ with messages and no markers gets a full backfill claim. Never invents markers+ on a still-legacy inline DB — optimize would then skip demote and INSERT against+ the inline table forever."""def _do(conn):if _meta_row(conn, "fts_rebuild_high_water") is not None:self._reseed_missing_progress(conn)@@ -479,11 +475,9 @@ class SessionSearchMixin:self._execute_write(_do)def fts_optimize_available(self) -> bool:- """True when `optimize_fts_storage()` has work: legacy inline FTS to- migrate, an interrupted optimize to resume (markers/trash remain), a- CJK-bigram backfill/rebuild on this tokenizer-capable host, or an- empty external index left without markers. False for fresh and- fully-optimized installs and when FTS5 is unavailable."""+ """True when `optimize_fts_storage()` has work: legacy inline FTS, an interrupted+ optimize (markers/trash remain), a CJK backfill/rebuild on this tokenizer-capable+ host, or an empty external index without markers. False when FTS5 is unavailable."""if not self._fts_enabled or self.read_only:return Falsewith self._lock:@@ -503,14 +497,12 @@ class SessionSearchMixin:return self._fts_external_index_empty_with_messages(conn)def _demote_legacy_fts_to_trash(self) -> int:- """Demote the legacy inline FTS vtables and stage their shadow tables- for chunked teardown; returns MAX(messages.id) as the rebuild high- water. O(1) schema surgery — the heavy delete is deferred.-- Markers are written in the same BEGIN IMMEDIATE as the demote, BEFORE- the empty v23 schema is created (``executescript`` implicitly COMMITs- and cannot run inside that transaction), closing the crash window- where trash + empty v23 tables exist with no backfill claim."""+ """Demote the legacy inline FTS vtables and stage their shadow tables for chunked+ teardown; returns MAX(messages.id) as the rebuild high water. O(1) schema+ surgery — the heavy delete is deferred. Markers are written in the same BEGIN+ IMMEDIATE as the demote, BEFORE the empty v23 schema is created (``executescript``+ implicitly COMMITs), closing the crash window where trash + empty v23 tables+ exist with no backfill claim."""def _stage(conn):self._drop_fts_triggers(conn)conn.execute("DROP VIEW IF EXISTS messages_fts_trigram_src")@@ -548,9 +540,9 @@ class SessionSearchMixin:return hwdef _ensure_v23_fts_tables(self, failure_message: str) -> None:- """Ensure the v23 base + trigram tables under the lock (IF NOT EXISTS,- cheap); raise *failure_message* without the base table, since the- backfill loop would otherwise retry "no such table" forever."""+ """Ensure the v23 base + trigram tables under the lock (IF NOT EXISTS, cheap); raise+ *failure_message* without the base table, since the backfill loop would+ otherwise retry "no such table" forever."""with self._lock:base_ok = self._ensure_fts_schema(self._conn, "messages_fts", FTS_SQL)trigram_ok = self._ensure_fts_schema(self._conn, "messages_fts_trigram", FTS_TRIGRAM_SQL)@@ -560,9 +552,9 @@ class SessionSearchMixin:self._conn.commit()def _optimize_unsettled_reason(self, conn) -> Optional[str]:- """Refusal reason while optimize work remains, else None. Settling after- a no-op backfill meant permanent search-index loss for historical rows,- so an empty base index against non-empty messages also refuses."""+ """Refusal reason while optimize work remains, else None. An empty base index+ against non-empty messages also refuses (settling after a no-op backfill meant+ permanent search-index loss for historical rows)."""if _meta_row(conn, "fts_rebuild_high_water") is not None:return "backfill_incomplete"if self._has_fts_trash(conn):@@ -572,8 +564,8 @@ class SessionSearchMixin:return Nonedef _optimize_vacuum(self) -> bool:- """Phase 3: reclaim freed pages to the OS. False when VACUUM failed- (usually no free disk for its temp copy; a later VACUUM reclaims)."""+ """Phase 3: reclaim freed pages to the OS. False when VACUUM failed (usually no+ free disk for its temp copy; a later VACUUM reclaims)."""try:with self._lock:self._conn.execute("VACUUM")@@ -581,10 +573,9 @@ class SessionSearchMixin:except sqlite3.OperationalError as exc:logger.warning("VACUUM after FTS optimize failed: %s", exc)vacuum_ok = False- # Best-effort WAL fold-back, REFUSED (SQLITE_BUSY) while another- # connection holds a read-mark — so callers must size the result via- # logical_size_bytes, not stat(). PASSIVE, never TRUNCATE: a TRUNCATE- # reset from a transient CLI would race a live writer.+ # Best-effort WAL fold-back, REFUSED (SQLITE_BUSY) while another connection holds+ # a read-mark — callers size the result via logical_size_bytes, not stat().+ # PASSIVE, never TRUNCATE: a TRUNCATE reset from a transient CLI would race a live writer.try:with self._lock:self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)")@@ -593,11 +584,10 @@ class SessionSearchMixin:return vacuum_okdef _optimize_settle(self, conn) -> Optional[str]:- """Phase 4 (inside the write transaction, so a concurrent writer cannot- race a stamp past incomplete work): stamp the FTS layout — the source- of truth for "optimized" — clear the "available" flag, and advance- schema_version if pre-decoupling code left it behind. Returns a- refusal reason (nothing stamped) or None."""+ """Phase 4 (inside the write transaction, so a concurrent writer cannot race a+ stamp past incomplete work): stamp the FTS layout (source of truth for+ "optimized"), clear the "available" flag, advance schema_version if+ pre-decoupling code left it behind. Returns a refusal reason or None."""refusal = self._optimize_unsettled_reason(conn)if refusal is not None:return refusal@@ -612,11 +602,10 @@ class SessionSearchMixin:def optimize_fts_storage(self, *, progress_cb: Optional[Callable[[Dict[str, Any]], None]] = None, vacuum: bool = True) -> Dict[str, Any]:- """Migrate a legacy v22 inline-FTS DB to the v23 external-content- schema, foreground and to completion; re-running resumes an- interrupted attempt. ``progress_cb`` receives {"phase", "percent",- "indexed", "total"}. A missing trigram tokenizer is not fatal (CJK- falls back to LIKE, as at startup)."""+ """Migrate a legacy v22 inline-FTS DB to the v23 external-content schema,+ foreground and to completion; re-running resumes an interrupted attempt.+ ``progress_cb`` receives {"phase", "percent", "indexed", "total"}. A missing+ trigram tokenizer is not fatal (CJK falls back to LIKE, as at startup)."""if not self._fts_enabled:return {"ok": False, "reason": "fts5_unavailable"}if self.read_only:@@ -630,17 +619,15 @@ class SessionSearchMixin:if legacy and not pending:self._demote_legacy_fts_to_trash()elif pending and not legacy:- # Resume mid-demote: the process may have died between the staged- # demote commit and schema ensure.+ # Resume mid-demote: the process may have died between the staged demote+ # commit and schema ensure.self._ensure_v23_fts_tables("failed to re-create v23 messages_fts on optimize-storage resume")- # A stale CJK index can only be recovered from scratch; then ensure- # table + markers exist (a v23 DB gaining the cjk index for the first time).+ # A stale CJK index can only be recovered from scratch; then ensure table ++ # markers exist (a v23 DB gaining the cjk index for the first time).self._fts_cjk_reset_if_stale()if self._fts_cjk_loaded:- with self._lock:- self._ensure_fts_cjk_schema(self._conn)- self._conn.commit()+ self._ensure_cjk_schema_committed()def _emit(phase: str) -> None:if progress_cb is None:@@ -652,9 +639,9 @@ class SessionSearchMixin:})def _drive(phase: str, step) -> None:- """Run *step* to completion; the inter-chunk sleep is the single- place the duty cycle is enforced — back-to-back BEGIN IMMEDIATE- chunks starve a live gateway/CLI out of its lock retries."""+ """Run *step* to completion; the inter-chunk sleep is the single place the duty+ cycle is enforced — back-to-back BEGIN IMMEDIATE chunks starve a live+ gateway/CLI out of its lock retries."""while True:_t0 = time.monotonic()if not step():@@ -702,15 +689,14 @@ class SessionSearchMixin:self, session_id: str, around_message_id: int, window: int = 5, bookend: int = 3,keep_roles: Optional[Tuple[str, ...]] = ("user", "assistant"),) -> Dict[str, Any]:- """Anchored window (``get_messages_around``) plus session bookends, so a- hit anywhere in a long session yields the goal and the resolution in- one call. ``window`` is filtered to ``keep_roles`` EXCEPT the anchor,- which is always kept; ``bookend_start`` / ``bookend_end`` are the- first/last ``bookend`` messages with ids strictly outside the window- (empty when the window already overlaps the head/tail), skipping- empty-content rows (tool-call-only turns) so they don't crowd out- prose. Empty slices + zero counts when the anchor isn't in the- session. ``keep_roles=None`` disables role filtering."""+ """Anchored window (``get_messages_around``) plus session bookends, so a hit+ anywhere in a long session yields the goal and the resolution in one call.+ ``window`` is filtered to ``keep_roles`` EXCEPT the anchor (always kept);+ ``bookend_start`` / ``bookend_end`` are the first/last ``bookend`` messages with+ ids strictly outside the window (empty when the window already overlaps the+ head/tail), skipping empty-content rows (tool-call-only turns). Empty slices ++ zero counts when the anchor isn't in the session. ``keep_roles=None`` disables+ role filtering."""bookend = max(bookend, 0)primitive = self.get_messages_around(session_id, around_message_id, window=window)window_rows = primitive["window"]@@ -744,18 +730,7 @@ class SessionSearchMixin:bookend_end_rows = list(reversed(_bookend(">", window_rows[-1]["id"], "DESC")))def _hydrate(row) -> Dict[str, Any]:- msg = dict(row)- if "content" in msg:- msg["content"] = self._decode_content(msg["content"])- if msg.get("tool_calls"):- try:- msg["tool_calls"] = json.loads(msg["tool_calls"])- except (json.JSONDecodeError, TypeError):- logger.warning("Failed to deserialize tool_calls in get_anchored_view, falling back to []")- msg["tool_calls"] = []- if msg.get("display_metadata") is not None:- msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"])- return msg+ return self._row_to_message_dict(row, warn_context="get_anchored_view", summary_flag=False)return {"window": filtered_window, "messages_before": primitive["messages_before"],@@ -767,17 +742,13 @@ class SessionSearchMixin:def list_recent_user_messages(self, session_id: str, limit: int = 20, include_inactive: bool = False) -> List[Dict[str, Any]]:- """The *limit* most-recent real user turns, newest first, as- ``{id, timestamp, preview}`` (preview = first 80 chars, whitespace- collapsed). Used by /rewind and ``/undo [N]``.-- Bookkeeping timeline rows (``display_kind`` set) are excluded: no- client counts them as user turns, and including them made ``/undo``- soft-delete from a marker instead of the last real turn. Legacy- standalone compaction handoffs are role='user' rows with NO- display_kind — invisible to SQL — so fetch with headroom and drop them- in the decode loop; otherwise ``/undo N`` pairs an in-memory count that- excludes handoffs with a DB pick that includes them."""+ """The *limit* most-recent real user turns, newest first, as ``{id, timestamp,+ preview}`` (preview = first 80 chars, whitespace collapsed); used by /rewind and+ ``/undo [N]``. Bookkeeping timeline rows (``display_kind`` set) are excluded (no+ client counts them as user turns). Legacy standalone compaction handoffs are+ role='user' rows with NO display_kind — invisible to SQL — so fetch with headroom+ and drop them in the decode loop; otherwise ``/undo N`` pairs an in-memory count+ that excludes handoffs with a DB pick that includes them."""active_clause = "" if include_inactive else " AND active = 1"display_clause = " AND (display_kind IS NULL OR display_kind = '')"fetch_limit = int(limit) * 2 + 5@@ -815,15 +786,14 @@ class SessionSearchMixin:@staticmethoddef _sanitize_fts5_query(query: str) -> str:"""Sanitize user input for FTS5 MATCH (raw special characters raise- ``sqlite3.OperationalError``): preserve paired quoted phrases, strip- unmatched special characters, and quote hyphenated/dotted terms so- FTS5 matches them as phrases instead of splitting (``chat-send``,- ``P2.2``, ``my-app.config.ts``)."""+ ``sqlite3.OperationalError``): preserve paired quoted phrases, strip unmatched+ special characters, and quote hyphenated/dotted terms so FTS5 matches them as+ phrases instead of splitting (``chat-send``, ``P2.2``, ``my-app.config.ts``)."""# Cap before any regex processing so adversarial input stays bounded.query = query[:MAX_FTS5_QUERY_CHARS]- # 1. Protect balanced quoted phrases via numbered placeholders. Linear- # scan, not regex, so pathological quote runs cannot backtrack.+ # 1. Protect balanced quoted phrases via numbered placeholders. Linear scan, not+ # regex, so pathological quote runs cannot backtrack._quoted_parts: list = []pieces: list[str] = []i = 0@@ -854,40 +824,36 @@ class SessionSearchMixin:# 4. Drop dangling boolean operators at start/end (syntax errors).sanitized = re.sub(r"(?i)^(AND|OR|NOT)\b\s*", "", sanitized.strip())sanitized = re.sub(r"(?i)\s+(AND|OR|NOT)\s*$", "", sanitized.strip())- # 5. Quote dotted/hyphenated/underscored terms in ONE pass (sequential- # passes double-quote ``my-app.config``).+ # 5. Quote dotted/hyphenated/underscored terms in ONE pass (sequential passes+ # double-quote ``my-app.config``).sanitized = re.sub(r"\b(\w+(?:[._-]\w+)+)\b", r'"\1"', sanitized)# 6. Restore preserved quoted phrases.for i, quoted in enumerate(_quoted_parts):sanitized = sanitized.replace(f"\x00Q{i}\x00", quoted)return sanitized.strip()- # Unified Ideographs, Extension A, Extension B, CJK Symbols, Hiragana, Katakana, Hangul Syllables.- _CJK_RANGES = (- (0x4E00, 0x9FFF), (0x3400, 0x4DBF), (0x20000, 0x2A6DF), (0x3000, 0x303F), (0x3040, 0x309F),- (0x30A0, 0x30FF), (0xAC00, 0xD7AF),- )+ _CJK_RANGES = _CJK_RANGES@staticmethoddef _is_cjk_codepoint(cp: int) -> bool:- return any(lo <= cp <= hi for lo, hi in SessionSearchMixin._CJK_RANGES)+ return _is_cjk(cp)@staticmethoddef _contains_cjk(text: str) -> bool:- return any(SessionSearchMixin._is_cjk_codepoint(ord(ch)) for ch in text)+ return any(_is_cjk(ord(ch)) for ch in text)- @classmethod- def _count_cjk(cls, text: str) -> int:- return sum(1 for ch in text if cls._is_cjk_codepoint(ord(ch)))+ @staticmethod+ def _count_cjk(text: str) -> int:+ return sum(1 for ch in text if _is_cjk(ord(ch)))- @classmethod- def _has_lone_cjk_run(cls, query: str) -> bool:- """True when any maximal CJK run in the query is a single char: the- cjk-bigram index stores unigrams only for isolated chars, so such a- term can't match inside longer runs — those queries keep LIKE."""+ @staticmethod+ def _has_lone_cjk_run(query: str) -> bool:+ """True when any maximal CJK run in the query is a single char: the cjk-bigram+ index stores unigrams only for isolated chars, so such a term can't match+ inside longer runs — those queries keep LIKE."""run = 0for ch in query:- if cls._is_cjk_codepoint(ord(ch)):+ if _is_cjk(ord(ch)):run += 1else:if run == 1:@@ -897,26 +863,20 @@ class SessionSearchMixin:@staticmethoddef _trigram_eligible_tokens(query: str) -> bool:- """True when every non-operator token is >=3 chars: a shorter token- produces no trigrams, and with FTS5's implicit AND one such token- makes the whole MATCH return nothing."""- tokens = [t for t in query.strip('"').strip().split() if t.upper() not in _FTS_OPERATORS]+ """True when every non-operator token is >=3 chars: a shorter token produces no+ trigrams, and with FTS5's implicit AND one such token empties the whole MATCH."""+ tokens = _non_operator_tokens(query.strip('"').strip())return bool(tokens) and all(len(t) >= 3 for t in tokens)@classmethoddef _has_short_cjk_token(cls, raw_query: str) -> bool:- """True when any non-operator CJK token has fewer than 3 CJK chars —- the trigram tokenizer needs >=3 per token, so such a query returns- nothing there and must take the LIKE route."""- return any(- cls._count_cjk(t) < 3- for t in raw_query.split()- if t.upper() not in _FTS_OPERATORS and cls._contains_cjk(t)- )+ """True when any non-operator CJK token has fewer than 3 CJK chars — the trigram+ tokenizer needs >=3 per token, so such a query must take the LIKE route."""+ return any(cls._count_cjk(t) < 3 for t in _non_operator_tokens(raw_query) if cls._contains_cjk(t))def _trigram_route_ok(self, raw_query: str) -> bool:- """Per-token CJK length gate for the trigram index: ``广西 OR 桂林 OR- 漓江`` has 6 CJK chars total but 2 per token, so trigram returns 0."""+ """Per-token CJK length gate for the trigram index: ``广西 OR 桂林 OR 漓江`` has 6+ CJK chars total but 2 per token, so trigram returns 0."""return (self._count_cjk(raw_query) >= 3and not self._has_short_cjk_token(raw_query)@@ -975,14 +935,12 @@ class SessionSearchMixin:self, table: str, match_query: str, order_by_sql: str, *, fail_open: Optional[str] = None,operational_debug: Optional[str] = None, **kwargs,) -> Optional[List[Dict[str, Any]]]:- """Run one MATCH against *table*; ``None`` when the query cannot- execute (tokenizer unavailable / syntax) so the caller falls back.-- *fail_open* names the index for the substring-capable routes: a- corruption-class ``DatabaseError`` there detaches the derived indexes- (``_enter_fts_fail_open``) and answers from canonical rows — a live- search never performs the unbounded rebuild. Non-FTS corruption, or- any ``DatabaseError`` without *fail_open*, propagates."""+ """Run one MATCH against *table*; ``None`` when the query cannot execute (tokenizer+ unavailable / syntax) so the caller falls back. *fail_open* names the index for+ the substring-capable routes: a corruption-class ``DatabaseError`` there detaches+ the derived indexes (``_enter_fts_fail_open``) and answers from canonical rows —+ a live search never performs the unbounded rebuild. Non-FTS corruption, or any+ ``DatabaseError`` without *fail_open*, propagates."""sql, params = self._fts_match_sql(table, match_query, order_by_sql, **kwargs)try:return [dict(row) for row in self._read_all(sql, params)]@@ -1015,9 +973,9 @@ class SessionSearchMixin:@staticmethoddef _compile_like_boolean_query(query: str) -> Tuple[str, List[Any], Optional[str]]:- """Compile the supported FTS boolean subset into LIKE predicates:- terms within an OR group are ANDed (FTS5's implicit conjunction) and- ``NOT`` negates the following term rather than being discarded."""+ """Compile the supported FTS boolean subset into LIKE predicates: terms within an+ OR group are ANDed (FTS5's implicit conjunction) and ``NOT`` negates the+ following term rather than being discarded."""groups: List[List[Tuple[str, bool]]] = [[]]negate_next = Falsefor raw_token in _LIKE_TOKEN_RE.findall(query):@@ -1084,9 +1042,9 @@ class SessionSearchMixin:def _finalize_search_matches(self, matches: List[Dict[str, Any]], result_fields: Optional[Collection[str]] = None) -> List[Dict[str, Any]]:- """Attach neighboring messages (1 before + after, only when the- projection consumes ``context``) and trim full content. Each context- query takes its own read transaction, never a lock across N queries."""+ """Attach neighboring messages (1 before + after, only when the projection consumes+ ``context``) and trim full content. Each context query takes its own read+ transaction, never a lock across N queries."""if result_fields is None or "context" in result_fields:for match in matches:try:@@ -1112,10 +1070,9 @@ class SessionSearchMixin:role_filter: List[str] = None, limit: int = 20, offset: int = 0, sort: str = None,include_inactive: bool = False, fields: Optional[Collection[str]] = None,) -> List[Dict[str, Any]]:- """Instrumented wrapper around :meth:`_search_messages_impl`: logs one- line per slow search with the routing path taken so latency stays- attributable per query shape. Threshold HERMES_SEARCH_SLOW_MS- (default 1000; 0 logs every call)."""+ """Instrumented wrapper around :meth:`_search_messages_impl`: logs one line per slow+ search with the routing path taken. Threshold HERMES_SEARCH_SLOW_MS (default+ 1000; 0 logs every call)."""started = time.time()rows = Nonetry:@@ -1142,19 +1099,13 @@ class SessionSearchMixin:role_filter: List[str] = None, limit: int = 20, offset: int = 0, sort: str = None,include_inactive: bool = False, fields: Optional[Collection[str]] = None,) -> List[Dict[str, Any]]:- """FTS5 search across session messages (keywords, ``"phrases"``,- AND/OR/NOT, ``prefix*``).-- Returns snippet + session metadata + 1-message context per hit;- ``fields`` selects a projection (context is only loaded when it- consumes it). ``sort``: None = BM25 rank only; "newest"/"oldest" =- timestamp then rank. The short-CJK LIKE fallback orders by timestamp- DESC and ignores ``sort``.-- Rewound rows (``active=0, compacted=0``) are excluded by default;- compaction-archived rows (``compacted=1``) ARE included so the- pre-compaction transcript stays discoverable. ``include_inactive``- searches every row."""+ """FTS5 search across session messages (keywords, ``"phrases"``, AND/OR/NOT,+ ``prefix*``). Returns snippet + session metadata + 1-message context per hit;+ ``fields`` selects a projection (context only loaded when consumed). ``sort``:+ None = BM25 rank only; "newest"/"oldest" = timestamp then rank (the short-CJK+ LIKE fallback orders by timestamp DESC and ignores ``sort``). Rewound rows+ (``active=0, compacted=0``) are excluded by default; compaction-archived rows+ (``compacted=1``) ARE included; ``include_inactive`` searches every row."""result_fields = self._search_message_fields(fields)if not query or not query.strip():return []@@ -1187,16 +1138,15 @@ class SessionSearchMixin:except sqlite3.OperationalError:return [] # FTS5 syntax error despite sanitizationexcept sqlite3.DatabaseError as exc:- # Corruption parent class: detach the derived indexes and answer- # from canonical rows; repair paths own the rebuild.+ # Corruption parent class: detach the derived indexes and answer from+ # canonical rows; repair paths own the rebuild.if not self._enter_fts_fail_open(exc):raisematches = self._search_messages_like_fallback(query, limit=limit, offset=offset, sort=sort, **filters)- # Deferred-rebuild supplement: while the backfill is pending the FTS- # indexes miss the (progress, high_water] gap; top up with a bounded- # LIKE scan so old messages never vanish mid-rebuild. Cost decays to- # zero as the backfill advances.+ # Deferred-rebuild supplement: while the backfill is pending the FTS indexes miss+ # the (progress, high_water] gap; top up with a bounded LIKE scan so old messages+ # never vanish mid-rebuild. Cost decays to zero as the backfill advances.if self.fts_rebuild_status() is not None and len(matches) < limit:try:gap_matches = self._search_unindexed_gap(query, limit - len(matches), **filters)@@ -1205,12 +1155,11 @@ class SessionSearchMixin:except sqlite3.OperationalError as exc:logger.debug("Unindexed-gap supplement skipped: %s", exc)- # unicode61 puts no boundary between Latin and adjacent CJK ("修改youer服务端"- # is one token, so MATCH "youer" misses). On a zero-result Latin miss retry- # the substring-capable indexes: cjk first (exact ranked match), then- # trigram (>=3-char tokens). Gated on a miss so hits keep their ranking- # ("cat" may then match "concatenate"). Skipped for role='tool' (both- # indexes exclude tool rows).+ # unicode61 puts no boundary between Latin and adjacent CJK ("修改youer服务端" is+ # one token, so MATCH "youer" misses). On a zero-result Latin miss retry the+ # substring-capable indexes: cjk first (exact ranked match), then trigram (>=3-char+ # tokens). Gated on a miss so hits keep their ranking ("cat" may then match+ # "concatenate"). Skipped for role='tool' (both indexes exclude tool rows).if not matches and not is_cjk and not wants_tool_rows:fb_query = _quote_fts_tokens(query.strip('"').strip())if self._fts_cjk_available:@@ -1220,15 +1169,12 @@ class SessionSearchMixin:return self._finalize_search_matches(matches, result_fields=result_fields)def _search_cjk(self, query: str, wants_tool_rows: bool, route: Dict[str, Any]) -> List[Dict[str, Any]]:- """CJK routing: the unicode61 table splits CJK into single characters- ("大别山项目" -> "大 AND 别 AND ...": false positives, missed phrases).-- cjk-bigram serves every shape the legacy code split between trigram- and LIKE, except role='tool' queries and LONE 1-char CJK runs (the- index stores bigrams for runs >=2, so a single-char term only matches- isolated chars — LIKE is broader). Then trigram (>=3 CJK chars per- token), then a LIKE substring scan with one clause per non-operator- token so "广西 OR 桂林 OR 漓江" matches each term independently."""+ """CJK routing: the unicode61 table splits CJK into single characters ("大别山项目"+ -> "大 AND 别 AND ...": false positives, missed phrases). cjk-bigram serves every+ shape except role='tool' queries and LONE 1-char CJK runs (the index stores+ bigrams for runs >=2, so a single-char term only matches isolated chars — LIKE is+ broader). Then trigram (>=3 CJK chars per token), then a LIKE substring scan with+ one clause per non-operator token so "广西 OR 桂林 OR 漓江" matches each term."""raw_query = query.strip('"').strip()match_query = _quote_fts_tokens(raw_query)if self._fts_cjk_available and not wants_tool_rows and not self._has_lone_cjk_run(raw_query):@@ -1242,7 +1188,7 @@ class SessionSearchMixin:matches = self._match_rows("messages_fts_trigram", match_query, fail_open="Trigram", **route)if matches is not None:return matches- non_op_tokens = [t for t in raw_query.split() if t.upper() not in _FTS_OPERATORS] or [raw_query]+ non_op_tokens = _non_operator_tokens(raw_query) or [raw_query]like_params: list = []for tok in non_op_tokens:like_params += _like_params(tok)@@ -1256,10 +1202,9 @@ class SessionSearchMixin:)def _search_unindexed_gap(self, fts_query: str, limit: int, **filters) -> List[Dict[str, Any]]:- """LIKE-scan ids in (fts_rebuild_progress, fts_rebuild_high_water] —- the rows the deferred rebuild hasn't indexed yet. The FTS query is- degraded to AND-joined substring terms (quoted phrases kept whole):- deliberately recall-over-precision mid-rebuild."""+ """LIKE-scan ids in (fts_rebuild_progress, fts_rebuild_high_water] — the rows the+ deferred rebuild hasn't indexed yet. The FTS query is degraded to AND-joined+ substring terms (quoted phrases kept whole): recall-over-precision mid-rebuild."""status = self.fts_rebuild_status()if status is None or limit <= 0:return []@@ -1283,15 +1228,14 @@ class SessionSearchMixin:self, query: str, limit: int = 20, include_archived: bool = True, source: str = None,sources: List[str] = None, exclude_sources: List[str] = None,) -> List[Dict[str, Any]]:- """Search surfaced sessions by exact/prefix/substring session id (paste- an id from logs and jump to it). Also matches ``_lineage_root_id`` so- an old compression root id resolves to the live continuation row."""+ """Search surfaced sessions by exact/prefix/substring session id (paste an id from+ logs and jump to it). Also matches ``_lineage_root_id`` so an old compression+ root id resolves to the live continuation row."""needle = (query or "").strip().lower()if not needle or limit <= 0:return []- # list_sessions_rich pushes the id LIKE filter (own id + forward- # compression chain) into SQL; over-fetch so the in-Python ranking has- # candidates, then truncate.+ # list_sessions_rich pushes the id LIKE filter (own id + forward compression+ # chain) into SQL; over-fetch so the in-Python ranking has candidates.candidates = self.list_sessions_rich(source=source, sources=sources, exclude_sources=exclude_sources, limit=max(limit * 4, limit),offset=0, include_archived=include_archived, order_by_last_active=True, id_query=needle,@@ -1312,25 +1256,25 @@ class SessionSearchMixin:# ── FTS maintenance commands ───────────────────────────────────────────def _fts_table_exists(self, name: str) -> bool:- """True if an FTS5 virtual table is queryable in this DB ("no such- table" and "vtable constructor failed" — missing tokenizer /- mid-teardown — both count as not queryable)."""+ """True if an FTS5 virtual table is queryable ("no such table" and "vtable+ constructor failed" — missing tokenizer / mid-teardown — both count as not)."""try:self._conn.execute(f"SELECT 1 FROM {name} LIMIT 0")return Trueexcept sqlite3.DatabaseError:return False+ def _present_fts_tables(self) -> List[str]:+ """Queryable FTS tables (caller holds ``self._lock``)."""+ return [tbl for tbl in self._FTS_TABLES if self._fts_table_exists(tbl)]+def optimize_fts(self) -> int:- """Merge fragmented FTS5 segments into one per index (``'optimize'``).- Pure maintenance: changes neither results nor ``snippet()`` output,- only layout and speed; complementary to VACUUM, which then returns- the freed pages. Skips absent tables. Returns the number optimized."""+ """Merge fragmented FTS5 segments into one per index (``'optimize'``). Pure+ maintenance: changes neither results nor ``snippet()`` output, only layout and+ speed; VACUUM then returns the freed pages. Returns the number optimized."""optimized = 0with self._lock:- for tbl in self._FTS_TABLES:- if not self._fts_table_exists(tbl):- continue+ for tbl in self._present_fts_tables():try:self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('optimize')")optimized += 1@@ -1339,14 +1283,13 @@ class SessionSearchMixin:return optimizeddef rebuild_fts(self) -> int:- """Rebuild FTS5 indexes from ``messages`` (``'rebuild'``) — the- documented recovery for a corrupt index that rejects writes while- reads succeed. A full structural rebuild must never run concurrently- in two processes sharing one state.db (that interleaving corrupted- production DBs), so this admits through ``fts_rebuild_admission`` and- FAILS CLOSED, returning 0 on deferral (callers treat 0 as "no- progress" and fall back to the stale-FTS breadcrumb path). Skips- absent tables; returns the number of indexes rebuilt."""+ """Rebuild FTS5 indexes from ``messages`` (``'rebuild'``) — the recovery for a+ corrupt index that rejects writes while reads succeed. A full structural rebuild+ must never run concurrently in two processes sharing one state.db (that+ interleaving corrupted production DBs), so this admits through+ ``fts_rebuild_admission`` and FAILS CLOSED, returning 0 on deferral (callers+ treat 0 as "no progress" and fall back to the stale-FTS breadcrumb path).+ Returns the number of indexes rebuilt."""rebuilt = 0with fts_rebuild_admission(self.db_path) as admitted:if not admitted:@@ -1356,9 +1299,7 @@ class SessionSearchMixin:)return 0with self._lock:- for tbl in self._FTS_TABLES:- if not self._fts_table_exists(tbl):- continue+ for tbl in self._present_fts_tables():try:self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('rebuild')")self._conn.commit()@@ -1369,35 +1310,25 @@ class SessionSearchMixin:return rebuiltdef _merge_fts_incrementally(self, *, max_pages: int, max_commands: Optional[int] = None) -> int:- """Run bounded FTS5 ``'merge'`` commands against each present index.- A positive merge rank stops after ~that many output pages, so each- command holds the write lock for milliseconds regardless of index size- (``'optimize'`` takes 9-18 s per index on a 10 GB DB, exhausting a- competing writer's lock-retry patience). ``usermerge`` is lowered to- its minimum of 2 (persisted in ``%_config``, once per instance) so a- positive merge acts on ANY level with >= 2 segments; at the default 4 a- fragmented index cannot converge. Up to *max_commands* per index,- stopping on the no-progress signal ``total_changes`` delta < 2 (the- command's own INSERT is 1 change). Each command is its own implicit- transaction, so competing processes interleave mid-pass. Missing tables- are valid variants (optimize_fts_storage drops + backfills them live)- and are skipped; other SQLite errors propagate. Returns commands executed."""- if isinstance(max_pages, bool) or not isinstance(max_pages, int):- raise TypeError("max_pages must be an integer")- if max_pages <= 0:- raise ValueError("max_pages must be greater than zero")+ """Run bounded FTS5 ``'merge'`` commands against each present index. A positive+ merge rank stops after ~that many output pages, so each command holds the write+ lock for milliseconds regardless of index size (``'optimize'`` takes 9-18 s per+ index on a 10 GB DB). ``usermerge`` is lowered to its minimum of 2 (persisted in+ ``%_config``, once per instance) so a positive merge acts on ANY level with >= 2+ segments; at the default 4 a fragmented index cannot converge. Up to+ *max_commands* per index, stopping on the no-progress signal ``total_changes``+ delta < 2 (the command's own INSERT is 1 change). Each command is its own+ implicit transaction, so competing processes interleave mid-pass. Missing tables+ are valid variants (optimize_fts_storage drops + backfills them live) and are+ skipped; other SQLite errors propagate. Returns commands executed."""+ _positive_int("max_pages", max_pages)if max_commands is None:max_commands = self._FTS_MERGE_COMMANDS_PER_PASS- if isinstance(max_commands, bool) or not isinstance(max_commands, int):- raise TypeError("max_commands must be an integer")- if max_commands <= 0:- raise ValueError("max_commands must be greater than zero")+ _positive_int("max_commands", max_commands)executed = 0with self._lock:- for tbl in self._FTS_TABLES:- if not self._fts_table_exists(tbl):- continue+ for tbl in self._present_fts_tables():if not self._fts_usermerge_floor_applied:self._conn.execute(f"INSERT INTO {tbl}({tbl}, rank) VALUES('usermerge', 2)")for _ in range(max_commands):