Files
gabrielvidalandClaude Opus 5.5 ccd8957eda fix(conversations): read searchMsgs from the store, not the summaries
13cb82d1 moved searchMsgs out of summary_json into search_json, and three
readers kept looking for them on all_summaries() / get_summary(), which have
none (0 of the live store's 6612 summaries carry them):

- short_title.for_subagents: a subagent was named from its 90-char title
  instead of its first prompt;
- refs.py _texts: the conv-ref cards had no opening prompt from the corpus
  and no last answer;
- past.py _excerpt: ai-agent past gave no excerpt.

Store.search_msgs(paths) reads just those rows (hidden ones left out, like
all_search_msgs, which now shares its decoding); the three take the message
list, not a summary. test_conv_refs and test_past now build a real db.Store
(their fake handed searchMsgs back inside the summary, so they passed);
test_parser_version pins that summaries carry none and that the servable
floor hides search_msgs too. test_short_title passes again: off the
known-failures list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:01:18 +01:00

164 lines
6.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Conversation references: what the conv-ref prompt hook (``cli/conv_ref.py``)
puts in front of an agent when a prompt names a conversation.
Why. Gabriel points at earlier work by pasting a conversation's id (``this conv
01a1e40a-…``), a viewer link, or an id prefix. In Nov 2026, on the workers,
none of the four prompts that carried a hub id got resolved directly
(``~/homelab/data/log/2026-11-22-check-conv-analysis.md``). The id is a UUIDv7
that no file is named after, so the runs ran ``find`` and ``grep`` on
``~/.claude``, then ``ssh homelab find /``: 20–29 tool calls each time. The hook
asks this module instead. The lab's hook calls ``GET /api/conversation-refs``,
and a worker's goes through its outbox (a ``lookup`` item carrying ``ids``,
:func:`conversations.past.outbox_lookup`). The answer is one small card per
conversation, scoped to what the asker may see.
* **A ref** is a conversation id (UUIDv7), a session id, a viewer link
(``…/conversation/<id>``), or a ≥ 6-character prefix of either id. A prefix
that names more than one conversation comes back under ``ambiguous``, with
the count; one that names none, under ``unknown``. The hook prints an
unknown ref only when the prompt called it a conversation, since an Orus
contract id is a UUIDv7 too.
* **A card** has the title, state, the machine it ran on, the account, the
dates, the opening prompt (≤ 400 chars) and the last answer (≤ 800 chars,
its ``searchMsgs``, read with ``Store.search_msgs``), plus its link. It carries no transcript path,
since paths never leave the backend (``tree._conv_id``). The hook finds the
file on its own machine itself.
"""
from __future__ import annotations
import os
import re
import urllib.parse
from typing import Callable
from conversations.tree import _conv_id
VIEW_URL = os.environ.get("AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/")
MAX_REFS = 5
MIN_PREFIX = 6
PROMPT_MAX = 400
ANSWER_MAX = 800
_HEX_ID = re.compile(r"^[0-9a-f-]+$")
def _clip(text: str | None, n: int) -> str | None:
if not text:
return None
text = text.strip()
return text if len(text) <= n else text[:n - 1].rstrip() + "…"
def parse_refs(raw) -> list[str]:
"""``a,b`` / a list / viewer links → the bare lowercase ids, deduplicated,
at most :data:`MAX_REFS`."""
items = raw if isinstance(raw, list) else re.split(r"[,\s]+", str(raw or ""))
out: list[str] = []
for item in items:
ref = str(item or "").strip()
if "/conversation/" in ref:
ref = urllib.parse.unquote(ref.split("/conversation/", 1)[1]).split("?")[0].split("#")[0]
ref = ref.strip().strip("/").lower()
if ref and _HEX_ID.match(ref) and ref not in out:
out.append(ref)
return out[:MAX_REFS]
def _machine(deps, worker: str | None) -> str:
"""The worker's name (``Orus Macbook``) — ``lab`` for the host."""
if not worker:
return "lab"
w = deps.worker_store.get(worker) if getattr(deps, "worker_store", None) else None
return ((w or {}).get("name") or worker).strip()
# The blocks the composer appends to a prompt (frontend composePrompt): the
# card's "asked" line is what Gabriel typed, not the hub's guidelines.
_COMPOSER_TAIL = re.compile(r"\n\s*(?:Attached files \(uploaded via the composer|Work in the following "
r"homelab location|Use the following in this task:|Conversations referenced:|"
r"Guidelines:)")
def _own(prompt: str | None) -> str | None:
if not prompt:
return prompt
m = _COMPOSER_TAIL.search(prompt)
return prompt[:m.start()] if m else prompt
def _texts(msgs: list[dict] | None) -> tuple[str | None, str | None]:
"""The opening prompt (its composer blocks cut) and the last answer, off
the conversation's searchMsgs (``Store.search_msgs``)."""
msgs = msgs or []
first = _own(next((m.get("text") for m in msgs if m.get("role") == "user" and (m.get("text") or "").strip()), None))
last = next((m.get("text") for m in reversed(msgs)
if m.get("role") == "assistant" and (m.get("text") or "").strip()), None)
return first, last
def _card(deps, c: dict, msgs: list[dict] | None) -> dict:
m = c.get("meta") or {}
first, last = _texts(msgs)
return {
"id": c["id"],
"sessionId": c.get("sessionId"),
"title": m.get("title") or m.get("resourceTitle") or c.get("title"),
"state": m.get("state"),
"machine": _machine(deps, m.get("worker")),
"account": m.get("account"),
"projects": list(m.get("projects") or []),
"startedAt": c.get("startedAt"),
"endedAt": c.get("endedAt"),
"url": f"{VIEW_URL}/conversation/{c['id']}",
"firstPrompt": _clip(first or _own(c.get("firstPrompt")), PROMPT_MAX),
"lastAnswer": _clip(last, ANSWER_MAX),
}
def _roots(deps) -> list[tuple[str, str | None]]:
"""``(conversation id, session id)`` of every root transcript, straight
off the summary store. The list's card memo (``catalog._conversation_cards``)
takes ~8 s to rebuild cold, longer than a prompt hook can wait."""
return [(_conv_id(path), s.get("sessionId")) for path, s in deps.store.all_summaries()
if s.get("messages") and not s.get("isSidechain")]
def _load(deps, cid: str) -> dict | None:
from conversations.card import conversation_card # cycle-free
return conversation_card(deps, cid)
def cards(deps, raw_refs, *, visible: Callable[[str], bool] | None = None,
session: str | None = None) -> dict:
"""``{cards, unknown, ambiguous}`` for the refs (:func:`parse_refs`).
``session``, the asking run, is never its own reference. Only the
matched conversations' cards are built (``card.conversation_card``)."""
refs = parse_refs(raw_refs)
out = {"cards": [], "unknown": [], "ambiguous": []}
if not refs:
return out
pool = [(cid, sid) for cid, sid in _roots(deps)
if not (session and sid == session) and (visible is None or visible(cid))]
picked: list[str] = []
for ref in refs:
exact = [cid for cid, sid in pool if ref in (cid, sid)]
hits = exact or ([cid for cid, sid in pool if cid.startswith(ref) or (sid or "").startswith(ref)]
if len(ref) >= MIN_PREFIX else [])
hits = list(dict.fromkeys(hits))
if len(hits) == 1:
if hits[0] not in picked:
picked.append(hits[0])
elif hits:
out["ambiguous"].append({"ref": ref, "count": len(hits)})
else:
out["unknown"].append(ref)
wanted = set(picked)
paths = {cid: p for cid, p in ((_conv_id(p), p) for p, _ in deps.store.all_summaries())
if cid in wanted} if wanted else {}
corpus = deps.store.search_msgs(paths.values()) if paths else {}
for cid in picked:
c = _load(deps, cid)
if c:
out["cards"].append(_card(deps, c, corpus.get(paths.get(cid))))
return out