#!/usr/bin/env python3
"""Session Search Tool - long-term conversation recall over the SQLite session DB.

Single-shape tool; the mode is inferred from the args: DISCOVERY (``query``;
FTS5 deduped by lineage, adaptive detail hydrates only the top result),
SCROLL (``session_id`` + ``around_message_id``; ±window around the anchor),
SEARCH-IN-SESSION (``query`` + ``session_id``; FTS5 scoped to that session's
compression lineage, one result per matching message), READ (``session_id``
alone; whole session or head/tail), BROWSE (no args).
No LLM calls — every shape returns actual DB messages.
"""

import heapq
import json
import logging
import re
import time
from contextlib import ExitStack
from itertools import islice, zip_longest
from pathlib import Path
from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Union

from agent.redact import redact_derived_text
from hermes_time import safe_strftime
from persistence import MessageId, RowVisibility
from persistence.conversation.messages import MessageRecord, MessageStorageState, TranscriptRead, TranscriptRow, TranscriptView
from persistence.conversation.search import SearchHit, SearchSort
from persistence.conversation.sessions import BOUNDARY_END_REASONS, RecentBrowseQuery, SessionRecord
from persistence.sqlite._state.common import _PREVIEW_MAX_CHARS

# Hidden from browsing/searching — integrations (HERMES_SESSION_SOURCE=tool), delegate
# subagent runs, kanban workers are not the user's history.
_HIDDEN_SESSION_SOURCES = ("kanban", "subagent", "tool")
# Searchable but DEMOTED below interactive sessions: cron vocabulary dominates bare
# BM25 and starves out the user's own sessions ("recall blindness").
# Automation sources that are kept searchable but DEMOTED below interactive sessions in discover ranking.
# Cron jobs run on a schedule and accumulate large volumes of repetitive vocabulary (recurring project
# names, dates, "session", summaries); under bare BM25 they dominate the top-N FTS rows and starve out the
# user's own interactive sessions, producing "recall blindness" where only cron sessions surface (#19434).
# Demoting — not excluding — keeps cron content reachable when it's the only match, while interactive
# sessions always win when both match.
_DEMOTED_SESSION_SOURCES = ("cron",)

# Read-shape per-message content cap. #69334 capped discovery bookends (1200) and
# scroll windows (4000) but left ``_read_session`` returning whole messages, so a
# single archived tool result stored as a message could come back verbatim - one
# read returned 74K chars and took a request from ~50K to ~89K tokens in a step.
# Bounding message COUNT (head/tail) is not enough when content per message is
# unbounded; the agent can scroll around a message for detail (#114344).
_READ_MAX_CONTENT = 2000
# Scroll caps (#147548): a window=10 scroll on a real 440K-message store ran p90 100K chars, half of
# it tool output, and past the tool-result budget it spilled to a preview without the anchor.
_SCROLL_TOOL_ROW_MAX, _SCROLL_TEXT_MAX = 1500, 8000
# Stored tool-call arguments (whole file bodies, heredocs) are uncapped: one 8-result discovery
# returned 152K chars, 118K of it tool_calls JSON. The anchor row keeps more of its own call.
_TOOL_ARGS_PREVIEW, _ANCHOR_TOOL_ARGS_MAX = 200, 2000
# Asked for "the resume command" in 7 of 81 recall requests; agents then queried state.db for the
# compression children because nothing said a resume follows the lineage (resolve_resume_target).
_RESUME_HINT = ("To resume one: `hermes --resume <session_id>`; it opens the latest continuation, "
                "so any session_id from its lineage works.")
# FTS rows scanned before dedup-by-lineage — well above the distinct sessions a query
# returns, so interactive matches buried under cron hits survive the demotion pass.
_DISCOVER_SCAN_LIMIT = 300
# exclude_session_ids: ids already inspected this task; capped so a runaway list can't fan out lineage walks.
_EXCLUDE_SESSION_IDS_CAP = 20
# Relative time bounds: "7d" / "24h" / "2w" = now minus N hours/days/weeks.
_RELATIVE_BOUND_RE = re.compile(r"^(\d+)\s*(h|d|w)$", re.IGNORECASE)
_RELATIVE_UNIT_SECONDS = {"h": 3600, "d": 86400, "w": 604800}
# Raw FTS rows are only a plan input; the response hydrates its own window/bookends.
_DISCOVER_SEARCH_FIELDS = ("id", "session_id", "role", "snippet", "timestamp", "source", "model", "session_started")
# Compaction handoff summaries (agent/context_compressor.py); excluded from bookends.
_COMPACTION_PREFIXES = ("[CONTEXT COMPACTION", "[CONTEXT SUMMARY]:")
# /new, /reset, idle/daily expiry and CLI /new ("new_session") end the predecessor WITHOUT
# carrying its transcript forward — unlike compression continuations and live delegation
# children. The store's boundary set, so the two cannot drift.
_FRESH_RESET_END_REASONS = BOUNDARY_END_REASONS


def _quiet(fn, default, msg, *log_args, with_exc: bool = False):
    """``fn()``, or *default* after debug-logging *msg* (+ the exception when *with_exc*)."""
    try:
        return fn()
    except Exception as e:
        logging.debug(msg, *(log_args + (e,) if with_exc else log_args), exc_info=True)
        return default


def _loud(fn, log_msg, error_prefix, *log_args):
    """``(fn(), None)``, or ``(None, tool_error_json)`` after an error-level log — for DB
    calls whose failure the model must see."""
    try:
        return fn(), None
    except Exception as e:
        logging.error(log_msg, *log_args, e, exc_info=True)
        return None, tool_error(f"{error_prefix}: {e}", success=False)


def _format_timestamp(ts: float | str | None) -> str:
    """Unix timestamp -> readable date; ISO strings pass through; "unknown" for None."""
    if ts is None:
        return "unknown"
    if isinstance(ts, str) and not ts.replace(".", "").replace("-", "").isdigit():
        return ts
    return _quiet(lambda: safe_strftime(datetime.fromtimestamp(float(ts)), "%B %d, %Y at %I:%M %p"), str(ts),
                  "Failed to format timestamp %s: %s", ts, with_exc=True)


def _get_session_meta(persistence, session_id: str) -> Optional[SessionRecord]:
    """``sessions.get`` that degrades to None on error."""
    return _quiet(lambda: persistence.sessions.get(session_id), None,
                  "get_session failed for %s: %s", session_id, with_exc=True)


def _session_meta_block(meta: SessionRecord) -> dict[str, Any]:
    return {"when": _format_timestamp(meta.started_at), "source": meta.source,
            "model": meta.model, "title": redact_derived_text(meta.title)}


def _ok(**payload) -> str:
    return json.dumps({"success": True, **payload}, ensure_ascii=False)


def _is_compaction_summary(content: str) -> bool:
    return bool(content) and content.lstrip().startswith(_COMPACTION_PREFIXES)


def _resolve_to_parent(persistence, session_id: str) -> tuple[str, bool]:
    """Walk parent_session_id to the root -> ``(root_id, has_compression_hop)``; the flag
    separates a compression-split lineage (parent summarised away) from a delegation
    lineage (child still visible to the parent)."""
    visited: set[str] = set()
    cur, has_compression = session_id, False
    while cur and cur not in visited:
        visited.add(cur)
        s = _get_session_meta(persistence, cur)
        has_compression = has_compression or (s is not None and s.end_reason == "compression")
        if s is None or not s.parent_session_id:
            break
        cur = s.parent_session_id
    return cur, has_compression


def _resolve_lineage(persistence, session_id: str) -> str:
    return _resolve_to_parent(persistence, session_id)[0]


def _parse_iso_bound(value: Optional[str]) -> Optional[int]:
    """Parse an ISO date/datetime OR a relative duration into a UTC unix timestamp.

    ISO: a date-only value (``YYYY-MM-DD``) is midnight UTC on that day (the SQL
    ``before`` predicate is exclusive, so ``before=2026-07-01`` keeps June and drops
    July 1 00:00). Relative: ``"7d"``, ``"24h"``, ``"2w"`` = now minus N
    hours/days/weeks, so ``after="7d"`` is the last week and ``before="7d"`` is
    everything older than a week.
    """
    if value is None:
        return None
    text = str(value).strip()
    if not text:
        return None
    if rel := _RELATIVE_BOUND_RE.match(text):
        return int(time.time()) - int(rel.group(1)) * _RELATIVE_UNIT_SECONDS[rel.group(2).lower()]
    try:
        parsed = datetime.fromisoformat(text)
    except ValueError:
        raise ValueError(f"invalid time bound: {value!r} (expected ISO date/datetime like "
                         "2026-07-01, or a relative duration like 7d, 24h, 2w)") from None
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=UTC)
    return int(parsed.timestamp())


def _coerce_started_ts(value: Any) -> Optional[int]:
    """``sessions.started_at`` as an int unix timestamp (numeric or ISO text); None if unusable."""
    if value is None or value == "" or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return int(value)
    text = str(value).strip()
    try:
        return int(float(text))
    except (TypeError, ValueError):
        pass
    try:
        return _parse_iso_bound(text)
    except ValueError:
        return None


def _in_time_window(started_ts: Optional[int], after_ts: Optional[int], before_ts: Optional[int]) -> bool:
    """``after_ts <= started_ts < before_ts``; an unknown start fails any bound."""
    if after_ts is None and before_ts is None:
        return True
    if started_ts is None:
        return False
    return (after_ts is None or started_ts >= after_ts) and (before_ts is None or started_ts < before_ts)


def _normalize_exclude_session_ids(raw: Any) -> list[str]:
    """Deduped, stripped session ids from a str or list, capped at ``_EXCLUDE_SESSION_IDS_CAP``."""
    items = [raw] if isinstance(raw, str) else list(raw) if isinstance(raw, (list, tuple)) else []
    out: list[str] = []
    for item in items:
        sid = item.strip() if isinstance(item, str) else ""
        if sid and sid not in out:
            out.append(sid)
        if len(out) >= _EXCLUDE_SESSION_IDS_CAP:
            break
    return out


def _excluded_lineage_roots(persistence, exclude_session_ids: list[str]) -> set[str]:
    """The excluded ids plus their lineage roots, so a child id also hides its parent chain."""
    roots: set[str] = set()
    for sid in exclude_session_ids:
        roots.add(sid)
        roots.add(_resolve_lineage(persistence, sid) or sid)
    return roots


def _same_lineage(persistence, a: str, b: str) -> bool:
    a_root = _resolve_lineage(persistence, a)
    return bool(a_root and a_root == _resolve_lineage(persistence, b))


def _session_left_live_context(persistence, session_id: str) -> bool:
    """True when the transcript left everyone's live context: ``compression``
    (summarised into the child) or a fresh reset (child starts empty). Live delegation
    children (``end_reason is None``) and ``branched`` parents (copied verbatim into
    the branch) ARE the current context, so they stay excluded from recall."""
    meta = session_id and _get_session_meta(persistence, session_id)
    end_reason = (meta and meta.end_reason) or None
    return end_reason == "compression" or end_reason in _FRESH_RESET_END_REASONS


def _get_message_storage_state(persistence, message_id) -> Optional[MessageStorageState]:
    """Owning session and visibility of *message_id* (None if missing/error)."""
    return (message_id and _quiet(lambda: persistence.messages.message_storage_state(message_id), None,
                                  "message storage-state lookup failed for %s", message_id)) or None


_RECALL_TOOL_NAMES = frozenset({"session_search", "tool_search"})


def _json_or_value(value: Any) -> Any:
    """``value`` decoded when it is a JSON string (tool-call arguments are stored either way)."""
    return json.loads(value) if isinstance(value, str) else value


def _is_recall_only_call(call: Any) -> bool:
    """True for a ``session_search``/``tool_search`` call, or a ``tool_call`` bridge whose nested
    calls are all such lookups. The bridge also runs real deferred work (``write_file``…), so any
    other nested name keeps the row as history."""
    fn = call.get("function") if isinstance(call, dict) else None
    name = fn.get("name") if isinstance(fn, dict) else None
    if not isinstance(name, str):  # malformed stored call: history, not an echo
        return False
    if name in _RECALL_TOOL_NAMES:
        return True
    if name != "tool_call":
        return False
    try:
        args = _json_or_value(fn.get("arguments"))
        nested = _json_or_value(args.get("calls")) if isinstance(args, dict) else None
    except (TypeError, ValueError):
        return False
    return isinstance(nested, list) and bool(nested) and all(
        isinstance(inner, dict) and isinstance(inner.get("name"), str) and inner["name"] in _RECALL_TOOL_NAMES
        for inner in nested)


def _is_search_echo(persistence, hit: SearchHit) -> bool:
    """True for a text-less assistant row whose tool calls are only recall lookups: it holds the
    query words because an earlier agent *searched* for them, not because it did the work."""
    if hit.role != "assistant" or not hit.session_id or not hit.message_id:
        return False
    view = _quiet(lambda: persistence.messages.read_around(hit.session_id, hit.message_id, window=0), None,
                  "search-echo lookup failed for %s", hit.message_id)
    row = next((m for m in (view.window if view else ()) if m.id == hit.message_id), None)
    if row is None or _content_text(row.content).strip() or not row.tool_calls:
        return False
    return all(_is_recall_only_call(call) for call in row.tool_calls)


def _is_compacted_state(state: Optional[MessageStorageState]) -> bool:
    """Rows compaction took out of live context: archived rows and superseded originals (a demoted tool
    result's full text). Plain rewound (rewind/undo) rows must stay hidden."""
    return state is not None and (state.visibility is RowVisibility.COMPACTION_ARCHIVED or state.superseded)


def _is_compacted_message(persistence, message_id) -> bool:
    """True for a compaction-archived row: no longer in live context, so discoverable
    even on the current session. False on any error."""
    return _is_compacted_state(_get_message_storage_state(persistence, message_id))


def _redact_tool_calls(tool_calls: Any) -> Any:
    """Strictly redact each call's ``function.arguments`` (field-wise, so the JSON shape survives)."""
    if not isinstance(tool_calls, (list, tuple)):
        return _redact_derived_value(tool_calls)
    out = []
    for call in tool_calls:
        fn = call.get("function") if isinstance(call, dict) else None
        if isinstance(fn, dict) and fn.get("arguments") is not None:
            call = {**call, "function": {**fn, "arguments": _redact_derived_value(fn["arguments"])}}
        out.append(call)
    return out


_DATA_URL_PLACEHOLDER = "[inline data omitted]"
_DATA_URL_RE = re.compile(r"data:[^\s,]*;base64,")


def _redact_derived_value(value: Any) -> Any:
    """Strictly redact every string leaf of stored message structure (str content, multimodal
    part lists, tool_calls), keeping the shape. Inline ``data:`` URLs (base64 images) are
    replaced outright: they are opaque to the redactor and never useful in recall output."""
    if isinstance(value, str):
        return _DATA_URL_PLACEHOLDER if _DATA_URL_RE.match(value) else redact_derived_text(value)
    if isinstance(value, (list, tuple)):
        return [_redact_derived_value(v) for v in value]
    if isinstance(value, dict):
        return {k: _redact_derived_value(v) for k, v in value.items()}
    return value


def _content_text(content: Any) -> str:
    """Searchable text of a message body: str as-is, a multimodal part list's text parts joined."""
    if isinstance(content, list):
        return " ".join(p["text"] for p in content if isinstance(p, dict) and isinstance(p.get("text"), str))
    return "" if content is None else str(content)


def _slim_tool_calls(tool_calls: Any, cap: int) -> Any:
    """Each call's ``function.arguments`` cut to *cap* chars, keeping the stored call shape. Runs after
    redaction, so a cut can never split a secret the redactor would otherwise have matched."""
    if not isinstance(tool_calls, (list, tuple)):
        return tool_calls
    out = []
    for call in tool_calls:
        fn = call.get("function") if isinstance(call, dict) else None
        args = fn.get("arguments") if isinstance(fn, dict) else None
        if args is not None and not isinstance(args, str):
            args = json.dumps(args, ensure_ascii=False)
        if isinstance(fn, dict) and args is not None and len(args) > cap:
            call = {**call, "function": {**fn, "arguments": args[:cap] + "…"}}
        out.append(call)
    return out


def _shape_message(m: TranscriptRow | MessageRecord, anchor_id: Optional[int] = None,
                   max_content_len: Optional[int] = None, derived: bool = False,
                   anchor_args_max: Optional[int] = _ANCHOR_TOOL_ARGS_MAX) -> dict[str, Any]:
    """Slim a stored row; keeps ``content`` even when empty (tool-call-only turns).

    ``derived`` marks rows surfaced by a discovery query rather than an explicit
    ``session_id`` read: those resurface across sessions, so they get the same
    strict redaction as compaction summaries (#113165)."""
    content = m.content
    if isinstance(content, str) and "\x1b" in content:  # archived terminal output carries ANSI
        from tools.ansi_strip import strip_ansi
        content = strip_ansi(content)
    if derived:
        content = _redact_derived_value(content)
    entry = {"id": m.id, "role": m.role, "content": content, "timestamp": m.timestamp}
    entry.update({k: getattr(m, k) for k in ("tool_name", "tool_calls", "tool_call_id") if getattr(m, k)})
    if derived and entry.get("tool_calls"):
        entry["tool_calls"] = _redact_tool_calls(entry["tool_calls"])
    is_anchor = anchor_id is not None and m.id == anchor_id
    if entry.get("tool_calls"):
        cap = anchor_args_max if is_anchor else _TOOL_ARGS_PREVIEW
        if cap is not None:
            entry["tool_calls"] = _slim_tool_calls(entry["tool_calls"], cap)
    if is_anchor:
        entry["anchor"] = True
    if max_content_len and content and len(content) > max_content_len:
        entry.update(content=content[:max_content_len] + "…", content_truncated=True,
                     original_content_chars=len(content))
    return {k: v for k, v in entry.items() if v is not None or k == "content"}


def _session_link(session_id: str, profile: str | None = None) -> str:
    """The reference the agent writes for a session — same value the desktop composer
    emits, so it renders as a titled link. The profile segment is omitted when it
    can't be named confidently (a bare id still resolves, just not across profiles)."""
    def _active():
        from hermes_cli.profiles import get_active_profile_name
        resolved = get_active_profile_name()
        return "" if resolved == "custom" else resolved
    name = (profile or "").strip() or _quiet(_active, "", "get_active_profile_name failed for session link")
    return f"@session:{name}/{session_id}" if name else f"@session:{session_id}"


def _discovery_entry(lineage_root: Optional[str], **fields) -> dict[str, Any]:
    """Canonical key order; ``parent_session_id`` set when the hit lives in a child."""
    entry = {k: fields[k] for k in (
        "session_id", "when", "source", "model", "title", "matched_role", "match_message_id", "snippet",
        "bookend_start", "messages", "bookend_end", "messages_before", "messages_after", "detail")}
    if lineage_root and lineage_root != entry["session_id"]:
        entry["parent_session_id"] = lineage_root
    return entry


def _title_match_result(persistence, query: str, current_lineage_root: Optional[str]) -> Optional[dict[str, Any]]:
    """Discovery-shaped result when the query matches a session title, else None."""
    title_query = query.strip().strip("`'\"")  # models often quote a remembered title
    session_id = title_query and _quiet(lambda: persistence.sessions.resolve_by_title(title_query), None,
                                        "resolve_session_by_title failed for %r", title_query)
    if not session_id:
        return None
    lineage_root = _resolve_lineage(persistence, session_id)
    # Same-lineage title hits are in-context only while the session is live;
    # /new-reset and compression-ended parents are not.
    if current_lineage_root and lineage_root == current_lineage_root and not _session_left_live_context(persistence, session_id):
        return None
    # Title-hit metadata also comes from the matched session, not the lineage root (#103184).
    session_meta = _quiet(lambda: persistence.sessions.get(session_id) or persistence.sessions.get(lineage_root), None,
                          "get_session failed for title match %s", session_id)
    if session_meta is not None and session_meta.source in _HIDDEN_SESSION_SOURCES:
        return None
    messages = _quiet(lambda: persistence.messages.read_transcript(session_id), (),
                      "get_messages failed for title match %s", session_id)
    anchor_id = messages[0].id if messages else None
    view = None if anchor_id is None else _quiet(
        lambda: persistence.messages.read_anchored_view(session_id, anchor_id, window=5, bookend=3), None,
        "get_anchored_view failed for title match %s/%s", session_id, anchor_id)
    title = redact_derived_text((session_meta and session_meta.title) or title_query)
    # Same caps as FTS hits (_bookend / _hydrate_hit): a title match is a discovery entry too.
    def shape(rows, fallback, anchor=None, max_content_len=1200):
        return [_shape_message(m, anchor_id=anchor, max_content_len=max_content_len, derived=True)
                for m in (rows or fallback)]
    return {**_discovery_entry(
        lineage_root, session_id=session_id,
        when=_format_timestamp(session_meta.started_at if session_meta else None),
        source=session_meta.source if session_meta else "unknown",
        model=(session_meta and session_meta.model) or "unknown",
        title=title, matched_role="session_title", match_message_id=anchor_id,
        snippet=f"Session title matched: {title}",
        bookend_start=shape(view and view.bookend_start, messages[:3]),
        messages=shape(view and view.window, messages[:5], anchor_id, max_content_len=4000),
        bookend_end=shape(view and view.bookend_end, messages[-3:]), messages_before=view.before if view else 0,
        messages_after=view.after if view else max(len(messages) - 5, 0), detail="full"),
        "_lineage_root": lineage_root}


def _discover_payload(persistence, query: str, detail: str, results: list, **extra) -> str:
    """Discovery response; notes FTS backfill progress so the agent can explain thin
    results instead of treating them as ground truth."""
    status = _quiet(lambda: persistence.search.search_index_rebuild_status(), None, "fts_rebuild_status failed")
    rebuild = {} if status is None else {"index_rebuild": {"percent": status.percent, "note": (
        f"The search index is rebuilding in the background ({status.percent}% done, "
        f"{status.indexed:,} of {status.total:,} messages). Results from older messages "
        f"may be incomplete until it finishes.")}}
    return _ok(mode="discover", query=query, detail=detail, results=results, count=len(results), **extra, **rebuild)


def _bookend(rows: tuple[MessageRecord, ...]) -> list[dict[str, Any]]:
    return [_shape_message(m, max_content_len=1200, derived=True) for m in rows
            if not _is_compaction_summary(m.content)]


_SNIPPET_MARK_RE = re.compile(r">>>(.*?)<<<", re.DOTALL)
_SNIPPET_BEFORE, _SNIPPET_AFTER = 100, 200


def _derived_snippet(fts_snippet: Any, anchor: Optional[MessageRecord]) -> str:
    """Rebuild the hit snippet from the strictly-redacted anchor message.

    FTS ``snippet()`` output can't be redacted after the fact: a highlight marker inside a
    token (``>>>ghp<<<_...``) or the window crop (``...<token body>``) breaks the vendor-prefix
    patterns. So the FTS row only contributes its highlighted terms; the text comes from the
    redacted anchor body (or tool-call arguments), windowed and re-highlighted here (#113165).
    """
    if not anchor:
        return ""
    terms = [t for t in dict.fromkeys(_SNIPPET_MARK_RE.findall(str(fts_snippet or ""))) if t.strip()]
    sources = [_content_text(_redact_derived_value(anchor.content))]
    calls = anchor.tool_calls
    if calls:
        calls = _redact_tool_calls(calls)
        sources.append(calls if isinstance(calls, str) else json.dumps(calls, ensure_ascii=False))
    # LIKE-fallback snippets carry no markers: locate by their leading text instead.
    probes = terms or [str(fts_snippet or "").strip(". ")[:20]]
    text, pos = sources[0], -1
    for candidate in sources:
        lowered = candidate.lower()
        pos = min((i for i in (lowered.find(t.lower()) for t in probes if t) if i >= 0), default=-1)
        if pos >= 0:
            text = candidate
            break
    start = max(0, pos - _SNIPPET_BEFORE) if pos >= 0 else 0
    end = min(len(text), max(pos, 0) + _SNIPPET_AFTER)
    window = text[start:end]
    if terms:
        window = re.sub("|".join(re.escape(t) for t in sorted(terms, key=len, reverse=True)),
                        lambda m: f">>>{m.group(0)}<<<", window, flags=re.IGNORECASE)
    return ("..." if start else "") + window + ("..." if end < len(text) else "")


def _hydrate_hit(persistence, lineage_root: str, hit: SearchHit, result_detail: str) -> Optional[dict[str, Any]]:
    """Discovery result from a surviving FTS row; None (dropped) if the view can't load."""
    hit_sid, msg_id = hit.session_id or lineage_root, hit.message_id
    try:
        view = persistence.messages.read_anchored_view(hit_sid, msg_id, window=5, bookend=3)
    except Exception as e:
        logging.warning("get_anchored_view failed for %s/%s: %s", hit_sid, msg_id, e, exc_info=True)
        return None
    # Hydrate when/title from the session that owns the hit — a long-lived gateway
    # lineage's root can be months older than the matched conversation (#103184).
    session_meta, full = (_get_session_meta(persistence, hit_sid) or _get_session_meta(persistence, lineage_root),
                          result_detail == "full")
    anchor = next((m for m in view.window if m.id == msg_id), None)
    return _discovery_entry(
        lineage_root, session_id=hit_sid,
        when=_format_timestamp((session_meta and session_meta.started_at) or hit.session_started),
        source=(session_meta and session_meta.source) or hit.source,
        model=(session_meta and session_meta.model) or hit.model or "unknown",
        title=redact_derived_text(session_meta.title if session_meta else None) or None,
        matched_role=hit.role, match_message_id=msg_id,
        snippet=_derived_snippet(hit.snippet, anchor),
        bookend_start=_bookend(view.bookend_start) if full else [],
        messages=[_shape_message(m, anchor_id=msg_id, max_content_len=4000, derived=True)
                  for m in view.window if full or m.id == msg_id],
        bookend_end=_bookend(view.bookend_end) if full else [],
        messages_before=view.before, messages_after=view.after,
        detail=result_detail)


def _search_rows(persistence, query: str, role_filter: Optional[list[str]], scan_limit: int, sort: Optional[str],
                 after_ts: Optional[int], before_ts: Optional[int], **narrow) -> list[SearchHit]:
    """The search every query shape runs: ``role_filter`` (default user/assistant), the discovery projection.

    A tool role sends a search down the stored-row substring route, which can't read structured content (an image
    turn's caption), so conversation roles search the word index separately. A date sort merges the two legs by
    timestamp; relevance (no score shared across the two routes) interleaves them."""
    roles = role_filter or ["user", "assistant"]
    groups = [g for g in ([r for r in roles if r != "tool"], [r for r in roles if r == "tool"]) if g]
    order = SearchSort(sort) if sort else SearchSort.RELEVANCE
    legs = [persistence.search.search_messages(
        query=query, role_filter=group, limit=scan_limit, offset=0, sort=order, fields=_DISCOVER_SEARCH_FIELDS,
        after_ts=after_ts, before_ts=before_ts, **narrow) for group in groups]
    if order is SearchSort.RELEVANCE:
        merged = (hit for pair in zip_longest(*legs) for hit in pair if hit is not None)
    else:
        merged = heapq.merge(*legs, key=lambda hit: (hit.timestamp or 0.0, hit.message_id),
                             reverse=order is SearchSort.NEWEST)
    return list(islice(merged, scan_limit))


def _discover(persistence, query: str, role_filter: Optional[list[str]], limit: int, sort: Optional[str],
              detail: str, current_session_id: str | None = None, link_profile: str | None = None,
              after_ts: Optional[int] = None, before_ts: Optional[int] = None,
              exclude_session_ids: Optional[list[str]] = None, relaxed_from: Optional[str] = None) -> str:
    """Discovery shape: FTS5 plus adaptive or full result hydration. ``relaxed_from`` is set on the
    one any-term retry and names the query that matched only rows already in context."""
    current_lineage_root = _resolve_lineage(persistence, current_session_id) if current_session_id else None
    excluded_roots = _excluded_lineage_roots(persistence, exclude_session_ids or [])
    title_result = _title_match_result(persistence, query, current_lineage_root)
    # FTS rows are time-bounded in SQL (_search_filter_clauses); the title match bypasses that
    # query, so it is the one place the window is re-checked in Python.
    if title_result:
        title_sid, title_root = title_result["session_id"], title_result.get("_lineage_root") or title_result["session_id"]
        title_meta = _get_session_meta(persistence, title_root) or _get_session_meta(persistence, title_sid)
        title_started = _coerce_started_ts(title_meta.started_at if title_meta else None)
        if {title_sid, title_root} & excluded_roots or not _in_time_window(title_started, after_ts, before_ts):
            title_result = None
    raw_results, err = _loud(lambda: _search_rows(
        persistence, query, role_filter, _DISCOVER_SCAN_LIMIT, sort, after_ts, before_ts,
        exclude_sources=list(_HIDDEN_SESSION_SOURCES)), "FTS5 search failed: %s", "Search failed")
    if err:
        return err
    # Demote cron rows below interactive ones BEFORE dedup so a high-volume cron corpus
    # can't starve the user's own sessions out of the top `limit`; stable sort keeps BM25
    # order within each class.
    raw_results = sorted(raw_results, key=lambda r: (r.source or "") in _DEMOTED_SESSION_SOURCES)
    # See #19434.
    if not raw_results and not title_result:
        return _discover_payload(persistence, query, detail, [], message=(
            "No matching sessions found. FTS5 ANDs all terms by default — "
            "broaden with OR (`alpha OR beta`), exact-match with quoted "
            "phrases, exclude with NOT, or prefix-match with `deploy*`."),
            **({"relaxed_from": relaxed_from} if relaxed_from is not None else {}))
    seen_sessions: dict[str, Optional[SearchHit]] = {}
    results = [title_result] if title_result else []
    if title_result and (title_lineage := title_result.pop("_lineage_root", None)):
        seen_sessions[title_lineage] = None  # the title match holds this lineage
    # Same-lineage rows dropped by the live-context skip below (#103184): counted per
    # FTS row and deduped per session so the payload can disclose the hiding instead of
    # returning 0 results with no signal.
    hidden_rows, hidden_sessions = 0, {}
    # Dedupe by lineage (lineage_root -> first surviving FTS row) up to `limit`. The raw
    # owning session_id stays on the row — only it pairs validly with the FTS match id.
    # Current-lineage hits are skipped UNLESS the transcript left live context
    # (compression-ended, /new-reset predecessor, or an in-place compacted row on the
    # SAME session); a live delegation child (end_reason=None) stays excluded.
    for r in raw_results:
        if len(seen_sessions) >= limit:
            break
        raw_sid, resolved_sid = r.session_id, _resolve_lineage(persistence, r.session_id)
        if raw_sid in excluded_roots or resolved_sid in excluded_roots:
            continue
        # Skip the current session lineage — UNLESS the hit's transcript has left live context. Three
        # sub-cases: Legacy compression rotation: the FTS hit lives in a session that itself ended with
        # end_reason='compression'. That session's content has been replaced by a summary in the
        # continuation child, so it must stay discoverable. /new-reset (and idle/daily/CLI new_session): the
        # predecessor was ended without carrying any transcript into the child. Same lineage root, but the
        # prior conversation is NOT in the active context — hiding it made gateway recall go blind after
        # every /new (#85756). A live delegation child has end_reason=None, so it stays excluded. In-place
        # compaction: the FTS hit lives on the SAME session_id as the current session, but the matched
        # message row is an archived (active=0, compacted=1) row. The live-context load filters active=1, so
        # that content is no longer in context — let it through.
        is_compacted_hit = _is_compacted_message(persistence, r.message_id)
        if current_lineage_root and resolved_sid == current_lineage_root and not (
                _session_left_live_context(persistence, raw_sid) or is_compacted_hit):
            # An unended same-lineage row (e.g. a gateway predecessor whose end-write was
            # lost across a restart) is dropped here with no signal, so the agent
            # concludes the conversation never existed (#103184). Disclose it; the
            # current session's own live rows are not counted — they are already in
            # context (the same-session skip below) and hiding them is expected.
            # A predecessor row that only *searched* holds no evidence (same rule as below).
            if raw_sid != current_session_id and not _is_search_echo(persistence, r):
                hidden_rows += 1
                if raw_sid not in hidden_sessions:
                    meta = _get_session_meta(persistence, raw_sid)
                    hidden_sessions[raw_sid] = {"session_id": raw_sid,
                                                "end_reason": meta.end_reason if meta else None,
                                                "last_activity": _format_timestamp(meta.last_activity_at if meta else None)}
            continue
        if current_session_id and raw_sid == current_session_id and not is_compacted_hit:
            continue
        if resolved_sid not in seen_sessions and _is_search_echo(persistence, r):
            continue
        seen_sessions.setdefault(resolved_sid, r)
    # The asking session's own rows (its prompt, the query it just wrote) and earlier recall
    # calls often hold the only all-terms match. They are skipped above, but their presence kept
    # the store's any-term fallback (which runs only on zero rows) from firing, so a fresh
    # question found nothing. Retry once with an explicit OR query: the retry's query contains
    # OR, so the store's any_term_query returns None for it and it cannot recurse again. A hidden-lineage
    # disclosure is kept as the answer instead: those rows ARE the match.
    if not seen_sessions and not title_result and not hidden_rows and relaxed_from is None and (
            any_term := _quiet(lambda: persistence.search.any_term_query(query), None, "any-term rewrite failed")):
        return _discover(persistence, any_term, role_filter, limit, sort, detail, current_session_id,
                         link_profile, after_ts, before_ts, exclude_session_ids, relaxed_from=query)
    for lineage_root, hit in seen_sessions.items():
        if hit is None:
            continue
        # Adaptive: only the top-ranked result is fully hydrated.
        entry = _hydrate_hit(persistence, lineage_root, hit, "full" if detail == "full" or not results else "compact")
        if entry is not None:
            results.append(entry)
    for entry in results:
        entry["link"] = _session_link(entry["session_id"], link_profile)
    return _discover_payload(persistence, query, detail, results, sessions_searched=len(seen_sessions),
        **({"relaxed_from": relaxed_from, "message": (
            "No other session matched every term; showing sessions that match any term.")}
           if relaxed_from is not None else {}),
        **({"hidden_same_lineage": {"count": hidden_rows, "sessions": list(hidden_sessions.values()),
            "note": f"{hidden_rows} matching message(s) in {len(hidden_sessions)} same-lineage session(s) "
            "were hidden because they are still treated as live context (unended). This can be a gateway "
            "session whose end-write was lost. To read one anyway, pass only its session_id: "
            "session_search(session_id=...)."}} if hidden_rows else {}),
        link_hint=(
        "When referring the user to a session, write its `link` value "
        "verbatim inline mid-sentence (it renders as a titled link) — never "
        "as markdown, in backticks, on its own line, or next to the "
        "title/id/date. To read more around a compact result, scroll: "
        "session_search(session_id=..., around_message_id=match_message_id). " + _RESUME_HINT))


def _search_session(persistence, session_id: str, query: str, role_filter: Optional[list[str]], limit: int,
                    sort: Optional[str], detail: str, current_session_id: str | None = None,
                    profile: str | None = None, after_ts: Optional[int] = None,
                    before_ts: Optional[int] = None) -> str:
    """Search-in-session shape: message search scoped in SQL to ``session_id``'s compression lineage.

    One result per matching message (no per-session dedup), each with a
    ``match_message_id``. Inside the caller's own session only rows that left its live
    transcript match (compaction-archived rows, and the superseded original of a tool
    result demoted at compaction), selected in SQL so live rows can't fill the scan;
    those lead, then the other lineage sessions under the scroll guard's live-context rule.
    """
    if not _get_session_meta(persistence, session_id):
        return _read_scoped(persistence, session_id, profile)  # same not-found error + cross-profile hint
    scope = list(_quiet(lambda: persistence.lineage.lineage(session_id), (),
                        "compression lineage lookup failed for %s", session_id)) or [session_id]

    def _search(scan_limit: int, **narrow):
        return _search_rows(persistence, query, role_filter, scan_limit, sort, after_ts, before_ts, **narrow)
    # The own leg needs no Python filtering, so `limit` rows suffice; the other leg over-fetches for the guard.
    own_sid = current_session_id if current_session_id in scope else None
    own, err = (_loud(lambda: _search(limit, compacted_in_session=own_sid), "FTS5 search failed: %s", "Search failed")
                if own_sid else ((), None))
    if err:
        return err
    others = [sid for sid in scope if sid != own_sid]
    raw_results, err = (_loud(lambda: _search(_DISCOVER_SCAN_LIMIT, session_ids=others), "FTS5 search failed: %s",
                              "Search failed") if others and len(own) < limit else ((), None))
    if err:
        return err
    # The default visibility hides a demoted tool result's superseded original (its full text), so a
    # compression continuation or another caller would lose it: add each other session's left-live rows.
    seen_ids = {r.message_id for r in (*own, *raw_results)}
    for sid in others if len(own) < limit else ():
        archived = _quiet(lambda sid=sid: _search(limit, compacted_in_session=sid), (),
                          "left-live search failed for %s", sid)
        raw_results = (*raw_results, *(r for r in archived if r.message_id not in seen_ids))
        seen_ids.update(r.message_id for r in archived)
    if sort in ("newest", "oldest"):  # the added originals join the date order before `limit` applies
        raw_results = sorted(raw_results, key=lambda hit: (hit.timestamp or 0.0, hit.message_id), reverse=sort == "newest")
    hits, live_skipped = list(own), 0
    for r in raw_results:
        if len(hits) >= limit:
            break
        if current_session_id and _anchor_in_live_context(
                persistence, _get_message_storage_state(persistence, r.message_id), r.session_id, current_session_id):
            live_skipped += 1
            continue
        hits.append(r)
    results = [entry for i, r in enumerate(hits) if (entry := _hydrate_hit(
        persistence, scope[0], r, "full" if detail == "full" or i == 0 else "compact")) is not None]
    for entry in results:
        entry["link"] = _session_link(entry["session_id"], profile)
    extra: dict[str, Any] = {"session_id": session_id}
    if not results:
        extra["message"] = ("Matches exist only in your active context; nothing earlier in this session matched."
                            if live_skipped else "No matching messages in this session. FTS5 ANDs all terms by "
                            "default — broaden with OR (`alpha OR beta`) or prefix-match with `deploy*`.")
    return _discover_payload(persistence, query, detail, results, **extra, link_hint=(
        "Results are matching messages inside this session. To read around one, scroll: "
        "session_search(session_id=<result session_id>, around_message_id=match_message_id)."))


def _cross_profile_reads_confined() -> bool:
    """True when the calling task may read only its own profile's store.

    One process serving several profiles (multiplexed gateway, a pooled or ``--isolated`` backend
    on a multi-profile host, a routed turn) makes each secondary profile a tenant: its allowlisted
    users must not reach the root profile's transcripts by naming it (#87779). The root profile
    keeps cross-profile reads, which is how its ``@session:<profile>/<id>`` links resolve. A
    standalone process for one profile has no such boundary, and neither does the operator's own
    CLI/TUI/Desktop/ACP session (its frozen launch policy), whose All-profiles sidebar offers
    ``@session:`` chips from every profile; A2A peers, hosted rooms, cron and messaging stay confined.
    The caller is the active scope (``get_hermes_home()``), never ``os.environ``, which holds the
    launch profile's home.
    """
    from agent.secret_scope import serves_routed_profile
    from hermes_cli.profiles import get_profile_dir
    from hermes_constants import get_hermes_home, hermes_home_key
    from tools.approval_context import is_local_interactive_session
    if not serves_routed_profile() or is_local_interactive_session():
        return False
    return hermes_home_key(get_hermes_home()) != hermes_home_key(get_profile_dir("default"))


def _resolve_profile_db(profile: str, handles: ExitStack):
    """Another profile's store opened read-only (safe on a live DB) and closed with *handles*; None = current."""
    if profile is None or not str(profile).strip():
        return None
    from hermes_cli import profiles as profiles_mod
    from hermes_constants import get_hermes_home, hermes_home_key
    from persistence_assembly import open_persistence_reader
    canon = profiles_mod.normalize_profile_name(profile)
    profiles_mod.validate_profile_name(canon)
    target = profiles_mod.get_profile_dir(canon)
    if hermes_home_key(target) != hermes_home_key(get_hermes_home()) and _cross_profile_reads_confined():
        raise PermissionError("this profile may only search its own sessions; reading another "
                              "profile's sessions is limited to the default profile")
    if not profiles_mod.profile_exists(canon):
        raise ValueError(f"profile '{canon}' does not exist")
    reader = handles.enter_context(open_persistence_reader(target))
    reader.ready()
    return reader


def _read_session(persistence, session_id: str, head: int = 20, tail: int = 10, link_profile: str | None = None) -> str:
    """Read shape: whole session, or ``head`` + ``tail`` messages with a scroll pointer."""
    meta = _get_session_meta(persistence, session_id)
    if not meta:
        return tool_error(f"session_id not found: {session_id}", success=False)
    rows, err = _loud(lambda: persistence.messages.read_transcript(session_id), "get_messages failed for %s: %s", "failed to load session",
                      session_id)
    if err:
        return err
    shaped = [_shape_message(m, max_content_len=_READ_MAX_CONTENT) for m in rows]
    total, truncated = len(shaped), len(shaped) > head + tail
    return _ok(mode="read", session_id=session_id, link=_session_link(session_id, link_profile),
               session_meta=_session_meta_block(meta), message_count=total, truncated=truncated,
               messages=shaped[:head] + shaped[-tail:] if truncated else shaped,
               **({"message": (f"Session has {total} messages; showing first {head} + last {tail}. "
                               "Pass around_message_id (any id above) to scroll the middle.")} if truncated else {}))


def _read_scoped(persistence, sid: str, profile: Optional[str]) -> str:
    """Read shape scoped to ONE store: the caller's profile, or the profile it named.

    A miss is a miss. Profiles are isolated islands, so a bare id never falls through to
    a scan of every other profile's ``state.db`` — that returned another profile's full
    transcript to any caller holding the id (#106761). The hint tells the model how to
    ask properly: ``@session:<profile>/<id>`` or ``profile=``.
    """
    result = _read_session(persistence, sid, link_profile=profile)
    if json.loads(result).get("success") is not False or profile:
        return result
    if _cross_profile_reads_confined():
        return tool_error(f"session_id not found in this profile: {sid}", success=False)
    return tool_error(f"session_id not found in this profile: {sid}. If it belongs to another "
                      "profile, pass profile=<name> (or the @session:<profile>/<id> link).", success=False)


def _derived_preview(preview: Any) -> str:
    """Strictly redacted browse preview. ``_shape_preview`` cut it at ``_PREVIEW_MAX_CHARS``, which can
    leave a fixed-length key (``AKIA…``, ``AIza…``) too short for its pattern: drop the cut word first."""
    text = "" if preview is None else str(preview)
    if len(text) == _PREVIEW_MAX_CHARS + 3 and text.endswith("..."):
        text = re.sub(r"\S*$", "", text[:-3]) + "..."
    return redact_derived_text(text)


def _list_recent_sessions(persistence, limit: int, current_session_id: str | None = None, link_profile: str | None = None) -> str:
    """Browse shape: metadata for the most recent sessions (no LLM, no FTS5)."""
    def _browse():
        # Never use the rich session listing ordered by last activity here: it walks every
        # compression chain and derives activity/previews before LIMIT, which can
        # monopolise a gateway callback for minutes on a multi-GB state.db. The
        # bounded browse query preselects an indexed candidate set and carries a
        # cooperative SQLite VM cancellation deadline.
        sessions = persistence.sessions.list_recent_sessions(RecentBrowseQuery(
            limit=limit + 15,  # extra so we can skip current / compression roots
            exclude_sources=_HIDDEN_SESSION_SOURCES, timeout_seconds=3.0))
        current_root, has_compression_hop = (
            _resolve_to_parent(persistence, current_session_id) if current_session_id else (None, False))
        # Compression continuation: the root was summarised into the live child, so hide
        # it. /new-reset children carry no transcript — keep that root browsable.
        hidden = {current_session_id, current_root if has_compression_hop and current_root else None}
        results = [{
            "session_id": s.session_id, "link": _session_link(s.session_id, link_profile),
            "title": redact_derived_text(s.title) or None,
            "source": s.source, "started_at": s.started_at, "last_active": s.last_active,
            "message_count": s.message_count,
            "preview": _derived_preview(s.preview)}
            for s in [x for x in sessions if x.session_id not in hidden][:limit]]
        return _ok(mode="browse", results=results, count=len(results), message=(
            f"Showing {len(results)} most recent sessions. Pass a query= to search, "
            "or session_id+around_message_id to scroll. " + _RESUME_HINT))

    out, err = _loud(_browse, "Error listing recent sessions: %s", "Failed to list recent sessions")
    return err or out


def _clamp_int(value, default: int, lo: int, hi: int) -> int:
    try:
        value = int(value)
    except (TypeError, ValueError):
        value = default
    return max(lo, min(value, hi))


def _anchor_in_live_context(persistence, anchor_state, anchor_sid: str, current_session_id: str) -> bool:
    """True when the scroll anchor is still in the caller's active context (reject).
    Same-lineage history that LEFT live context (compacted rows, compression-ended
    parents, /new-reset predecessors) passes, so scroll never rejects a discovery result.
    Rewind/undo rows (active=0, compacted!=1) never count as out-of-context history."""
    if not _same_lineage(persistence, anchor_sid, current_session_id) or _is_compacted_state(anchor_state):
        return False
    return (anchor_state is not None and anchor_state.visibility is not RowVisibility.ACTIVE) or not _session_left_live_context(persistence, anchor_sid)


def _snap_to_nearest(persistence, session_id: str, anchor: int, window: int, current_session_id: str | None):
    """``(nearest_id, view)`` for an anchor that is not in *session_id*, or None.

    Message ids are global and increasing, so a guessed id between two of this session's ids (models
    pick one to reach the middle of a truncated read) still names a position: scroll there instead of
    failing and inviting another guess. The snapped row passes the same live-context guard."""
    def _first(request):
        rows = persistence.messages.read_transcript(session_id, request)
        return rows[0].id if rows else None
    nearest = _quiet(lambda: _first(TranscriptRead(view=TranscriptView.ALL, after_id=MessageId(anchor), limit=1)), None,
                     "nearest-anchor lookup failed for %s", session_id) or _quiet(
        lambda: _first(TranscriptRead(view=TranscriptView.ALL, latest=True, limit=1)), None,
        "nearest-anchor lookup failed for %s", session_id)
    if not nearest or (current_session_id and _anchor_in_live_context(
            persistence, _get_message_storage_state(persistence, nearest), session_id, current_session_id)):
        return None
    view = _quiet(lambda: persistence.messages.read_around(session_id, nearest, window=window), None,
                  "nearest-anchor get_messages_around failed for %s", session_id)
    return (nearest, view) if view and view.window else None


def _scroll(persistence, session_id: str, around_message_id: int, window: int = 5,
            current_session_id: str | None = None) -> str:
    """Scroll shape: a window centered on an anchor (no FTS5, no bookends)."""
    try:
        around_message_id = int(around_message_id)
    except (TypeError, ValueError):
        return tool_error("scroll requires integer around_message_id", success=False)
    window = _clamp_int(window, 5, 1, 20)
    # Locate the anchor BEFORE the current-lineage guard (see _anchor_in_live_context).
    anchor_state = _get_message_storage_state(persistence, around_message_id)
    owning = anchor_state.session_id if anchor_state else None
    if current_session_id and _anchor_in_live_context(persistence, anchor_state, owning or session_id, current_session_id):
        return tool_error("scroll rejected: anchor lives in the current session lineage (already in your active context)", success=False)
    session_meta = _get_session_meta(persistence, session_id)
    if not session_meta:
        return tool_error(f"session_id not found: {session_id}", success=False)
    view, err = _loud(lambda: persistence.messages.read_around(session_id, around_message_id, window=window),
                      "get_messages_around failed: %s", "failed to load messages")
    if err:
        return err
    messages = view.window
    extra = {}
    if not messages and owning and owning != session_id:
        # Lineage rebind: the caller paired a parent session_id with a message id
        # living in a descendant — serve the owner's window transparently.
        rebind_view = _same_lineage(persistence, session_id, owning) and _quiet(
            lambda: persistence.messages.read_around(owning, around_message_id, window=window),
            None, "rebind get_messages_around failed: %s", with_exc=True)
        if rebind_view and rebind_view.window:
            extra["warning"] = (f"around_message_id {around_message_id} lives in {owning} "
                                f"(child of {session_id}); rebound transparently")
            view, messages, session_id = rebind_view, rebind_view.window, owning
            session_meta = _get_session_meta(persistence, owning) or session_meta
    if not messages and (snapped := _snap_to_nearest(persistence, session_id, around_message_id, window, current_session_id)):
        extra["warning"] = (f"around_message_id {around_message_id} is not in {session_id}; "
                            f"scrolled to its nearest message, {snapped[0]}")
        around_message_id, view = snapped
        messages = view.window
    if not messages:
        return tool_error(f"around_message_id {around_message_id} not in session_id {session_id}", success=False)
    return _ok(
        mode="scroll", session_id=session_id, around_message_id=around_message_id,
        session_meta=_session_meta_block(session_meta), window=window,
        # Neighbours are bounded: tool output is most of a window and rarely the answer (1,500 chars),
        # user/assistant text keeps 8,000 (that held every answer keyword on a real recall set, #147548).
        # The anchor itself comes back whole, content and tool-call arguments: scroll is the one shape
        # that retrieves a full message, and an oversized one spills to a file the model can read.
        messages=[_shape_message(m, anchor_id=around_message_id, anchor_args_max=None,
                                 max_content_len=None if m.id == around_message_id
                                 else _SCROLL_TOOL_ROW_MAX if m.role == "tool" else _SCROLL_TEXT_MAX)
                  for m in messages],
        messages_before=view.before, messages_after=view.after,
        hint=("Scroll forward: re-call with around_message_id = the LAST message's "
              "id; backward: the FIRST message's id (the boundary message repeats "
              "as an orientation marker). messages_before/messages_after < window "
              "means you've hit that end of the session."), **extra)


def _dispatch(query, role_filter, limit, persistence, current_session_id, session_id,
              around_message_id, window, sort, profile, detail,
              after=None, before=None, exclude_session_ids=None) -> str:
    """Mode dispatch (see module docstring); scroll wins when an anchor is set, and a
    query with a session_id searches inside that session instead of reading it whole."""
    sid = session_id.strip() if isinstance(session_id, str) else ""
    has_query = isinstance(query, str) and bool(query.strip())
    if sid and around_message_id is not None:
        return _scroll(persistence, sid, around_message_id, window, current_session_id)
    if sid and not has_query:
        return _read_scoped(persistence, sid, profile)
    # Browse lists enough recent sessions to pick from; discovery returns a few ranked hits.
    limit = _clamp_int(limit, 3 if has_query else 10, 1, 10)
    if not has_query:
        return _list_recent_sessions(persistence, limit, current_session_id, link_profile=profile)
    sort_norm = sort.strip().lower() if isinstance(sort, str) else None
    try:
        after_ts, before_ts = _parse_iso_bound(after), _parse_iso_bound(before)
    except ValueError as e:
        return tool_error(str(e), success=False)
    sort_norm = sort_norm if sort_norm in ("newest", "oldest") else None
    roles = ([r.strip() for r in role_filter.split(",") if r.strip()] or None) if isinstance(role_filter, str) else None
    detail = "full" if isinstance(detail, str) and detail.strip().lower() == "full" else "adaptive"
    if sid:
        return _search_session(persistence, sid, query.strip(), roles, limit, sort_norm, detail, current_session_id,
                               profile, after_ts=after_ts, before_ts=before_ts)
    return _discover(
        persistence=persistence, query=query.strip(), limit=limit, sort=sort_norm, role_filter=roles, detail=detail,
        current_session_id=current_session_id, link_profile=profile, after_ts=after_ts, before_ts=before_ts,
        exclude_session_ids=_normalize_exclude_session_ids(exclude_session_ids))


def session_search(query: str = "", role_filter: str | None = None, limit: int | None = None, db=None,
                   current_session_id: str | None = None, session_id: str | None = None, around_message_id: int | None = None,
                   window: int = 5, sort: str | None = None, profile: str | None = None, detail: str = "adaptive",
                   after: str | None = None, before: str | None = None, exclude_session_ids: Optional[list[str]] = None,
                   persistence=None) -> str:
    """Run session search through the ``persistence`` handle, or a reader over ``db``'s file without one, closing
    stores opened here. Positional order is frozen for old callers; new parameters are appended after ``detail``."""
    from hermes_constants import get_hermes_home
    from storage_user_copy import format_session_db_unavailable
    from persistence_assembly import open_persistence_reader
    # A raw `@session:<profile>/<id>` link as session_id: ids never contain "/", so
    # split on it and adopt the embedded profile only when none was passed.
    if isinstance(session_id, str) and "/" in session_id:
        emb_profile, _, emb_id = session_id.partition("/")
        if emb_id:
            session_id = emb_id
            if emb_profile and (profile is None or not str(profile).strip()):
                profile = emb_profile
    handles = ExitStack()
    try:
        # Cross-profile: swap in the named profile's store (read-only) for every shape;
        # current-lineage guards key off ids that won't collide, so they stay inert.
        try:
            profile_store = _resolve_profile_db(profile, handles)
        except Exception as e:
            logging.debug("session_search: cannot open profile %r", profile, exc_info=True)
            return tool_error(f"profile '{profile}': {e}", success=False)
        if profile_store is not None:
            persistence, current_session_id = profile_store, None
        # No handle: recall reads the store file ``db`` holds through its own read-only handle, or the home's
        # store when ``db`` has no file (a managed worker's RuntimeSessionStore, whose every read is an owner
        # RPC without the FTS read API, #141705).
        if persistence is None:
            db_path = getattr(db, "db_path", None)
            target = Path(db_path) if isinstance(db_path, (str, Path)) else get_hermes_home()

            def _open_own():
                reader = handles.enter_context(open_persistence_reader(target))
                reader.ready()
                return reader
            persistence = _quiet(_open_own, None, "session store unavailable for session_search")
            if persistence is None:
                return tool_error(format_session_db_unavailable(), success=False)
        return _dispatch(query, role_filter, limit, persistence, current_session_id, session_id,
                         around_message_id, window, sort, profile, detail,
                         after=after, before=before, exclude_session_ids=exclude_session_ids)
    finally:
        _quiet(handles.close, None, "Failed to close the session_search store")


def check_session_search_requirements() -> bool:
    """Requires the SQLite state database."""
    try:
        from persistence_assembly import profile_scope
        return profile_scope().profile_dir.exists()
    except ImportError:
        return False


SESSION_SEARCH_SCHEMA = {
    "name": "session_search",
    "description": (
        "Search or read past Hermes conversations (FTS5), or scroll inside one. Five shapes, picked by args: `query` = discovery "
        "(top-N matching sessions, top result fully hydrated); `session_id` + "
        "`around_message_id` = scroll (window of messages around an anchor); "
        "`query` + `session_id` = search inside that session's compression lineage (matching messages, "
        "with ids to scroll around); "
        "`session_id` alone = read a whole session — how you resolve an "
        "`@session:<profile>/<id>` link (split on '/' into profile + id); no "
        "args = browse recent sessions. Results are actual DB messages, no LLM. "
        "Searches conversation history ONLY — when the user gave a direct "
        "source (URL, file, contact, live system), inspect that first; never "
        "conclude 'not found' from history alone. Use for questions about past "
        "conversations: 'what did we do about X', 'where did we leave Y'. When "
        "referring the user to a session, write its `link` value verbatim "
        "inline (it renders as a titled link)."
    ),
    "parameters": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": (
                    "Search query (discovery shape). Keywords, phrases, or boolean "
                    "expressions to find in past sessions. With session_id, searches "
                    "inside that session's compression lineage. Omit to browse recent "
                    "sessions. Ignored when session_id + around_message_id are set "
                    "(scroll shape)."
                ),
            },
            "limit": {
                "type": "integer",
                "description": (
                    "Max sessions to return. Discovery defaults to 3; browse/no-args "
                    "defaults to 10. Max 10. Bump discovery to 5–10 when the topic "
                    "likely spans several sessions and you want to pick the right one "
                    "to scroll into."
                ),
            },
            "sort": {
                "type": "string",
                "enum": ["newest", "oldest"],
                "description": (
                    "Discovery shape only. Temporal bias on top of FTS5 ranking: omit "
                    "for relevance-only (exploratory recall), 'newest' for "
                    "\"where did we leave X\", 'oldest' for \"how did X start\"."
                ),
            },
            "detail": {
                "type": "string",
                "enum": ["adaptive", "full"],
                "description": (
                    "Discovery shape only. 'adaptive' (default) fully hydrates the "
                    "top-ranked result and returns only the exact anchor message for "
                    "lower-ranked results. 'full' returns bookends and the complete "
                    "anchored window for every result."
                ),
                "default": "adaptive",
            },
            "after": {
                "type": "string",
                "description": (
                    "Discovery shape only. Inclusive lower bound on session start "
                    "time. ISO date/datetime (e.g. 2026-06-01) or relative duration "
                    "(7d, 24h, 2w = within the last N). Use only when the user names "
                    "a time frame. sort is a ranking bias, not a bound."
                ),
            },
            "before": {
                "type": "string",
                "description": (
                    "Discovery shape only. Exclusive upper bound on session start "
                    "time. ISO date/datetime (a date-only value is midnight UTC that "
                    "day) or relative duration (7d = older than a week). Use only "
                    "when the user names a time frame."
                ),
            },
            "exclude_session_ids": {
                "type": "array",
                "items": {"type": "string"},
                "description": (
                    "Discovery shape only. Session ids already inspected this task. "
                    "Those sessions and their lineage are omitted so a later query "
                    "explores instead of repeating the same hit. Cap 20."
                ),
            },
            "session_id": {
                "type": "string",
                "description": (
                    "Session to scroll, search, or read. Use the session_id returned "
                    "from a prior discovery call. With around_message_id: scroll. "
                    "With query: search its compression lineage; each hit's session_id is the one to scroll. "
                    "Alone: read it whole."
                ),
            },
            "around_message_id": {
                "type": "integer",
                "description": (
                    "Scroll shape. Message id to center the window on — use "
                    "match_message_id from a discovery result, or any id from a "
                    "prior window."
                ),
            },
            "window": {
                "type": "integer",
                "description": (
                    "Scroll shape only. Messages to return on each side of the anchor "
                    "(anchor itself always included). Clamped to [1, 20]. Default 5."
                ),
                "default": 5,
            },
            "role_filter": {
                "type": "string",
                "description": (
                    "Optional. Comma-separated roles to include. Discovery defaults to "
                    "'user,assistant' (tool output is usually noise). Pass "
                    "'user,assistant,tool' to include tool output (debugging tool "
                    "behaviour) or 'tool' to search tool output only."
                ),
            },
            "profile": {
                "type": "string",
                "description": (
                    "Optional. Read sessions from another Hermes profile's database "
                    "(read-only). Use when resolving an `@session:<profile>/<id>` link: "
                    "pass the profile segment here with session_id as the id segment. "
                    "Omit to use the current profile."
                ),
            },
        },
        "required": [],
    },
}


from tools.registry import registry, tool_error

registry.register(
    name="session_search",
    toolset="session_search",
    schema=SESSION_SEARCH_SCHEMA,
    handler=lambda args, **kw: session_search(
        query=args.get("query") or "", limit=args.get("limit"), window=args.get("window", 5),
        detail=args.get("detail", "adaptive"), db=kw.get("db"), current_session_id=kw.get("current_session_id"),
        **{k: args.get(k) for k in ("role_filter", "session_id", "around_message_id", "sort", "profile",
                                    "after", "before", "exclude_session_ids")}),
    check_fn=check_session_search_requirements,
    emoji="🔍")
