ADR 0068 — A person searches their own threads: whole words by their start, the rules in the contract, a derived index in the commit of the event ​
- Status: proposed (2026-11-15), the design of slice 7 of ADR 0067 (wave 1), built in this change as 7a: the API, the store, the contract and the mock server; no web UI (7b, the box, is later; built 2026-11-15, see the amendment). Proposed, for the owner to confirm: every name, default and shape below, and the decisions the build settled. Builds on ADR 0039 (a person reads their own threads), ADR 0043 (what an erase leaves) and ADR 0065 (durable state written in the commit of the event, with a watermark and a backfill). It amends invariant 3 of
CLAUDE.mdand ADR 0001 with a dated note (decision 2), as ADR 0042, 0046 and 0065 did before it.
Context ​
A person with a few hundred threads cannot find one. The list is the only way in, and it holds titles and descriptions. ADR 0067 puts search in wave 1 and fixes the rule that governs it: every feature is implementable from docs/api/ alone (the server enforces, a client only offers), so a second client (the Flutter app) must be able to search from the contract, and two clients must show the same hits.
Verified 2026-11-15 by reading the code at d0a732f:
| What | Where |
|---|---|
listThreads answers a bare array of Thread, with before as a cursor that has rail meaning: there is no room for hits or a cursor object | docs/api/chat-api.yaml, list_threads in orchestrator/crates/api/src/routes.rs |
the request log writes the query string as it is (except the OAuth callback), so a GET ?q= would put a person's words in every access log | orchestrator/crates/api/src/trace.rs |
a thread's words are in events: user_message.text and agent_message.text; a partial message is logged (final: false) and a later final one with the same messageId replaces it; purpose: working marks words said while the agent works | orch_core::AgentMessageData, docs/api/thread-markdown-v1.md ("The answer") |
| a fork copies its parent's events up to the cut as they are, and the parent may be deleted afterwards | PgStore::create, ThreadStore::fork_thread (ADR 0029) |
there is no text-search extension in use (unaccent, pg_trgm) and none is needed below | git grep in orchestrator/crates/store-postgres/migrations |
Decision ​
A new route,
POST /api/search/threads(searchThreads). Not a parameter oflistThreads, which answers an array and has no room for hits; not aGET, because the query must not be in a URL or an access log (the route is a safe read that writes nothing;POSTonly keeps the words out of URLs). The request hasq,limit(1 to 50, default 20),cursor,archived(exclude,only,include; defaultinclude) andbranches. The answer is{query: {terms}, results: [{thread, rank, hits, messageHits}], next?}; ahithas afield(title,description,message), for a message itsseq,roleandat, and asnippetwithtext,cutStart,cutEndandmatchesas UTF-16 offsets (asMentionhas them), never markup.GET /api/configgainssearch: {maxQueryLength, maxTerms}: its presence is the capability (ADR 0067, rule 3).The index is durable state beside the log and amends invariant 3. "The search index of a person's threads (the folded words of their titles, descriptions and messages) is durable state beside the log, a function of it, written in the commit of the event, erased with the thread and rebuilt from the log by
orchestrator search backfill." Unlike the usage ledger, it holds content (folded words), which is why the amendment is stated and not implied. It is derived (the log is the truth; the table can be dropped and rebuilt), it is the owner's alone (every row names its owner, every read filters on it) and it goes in the transaction that deletes the thread, so an erase leaves no word (decision 8).What is searched: the title, the description, a person's
user_messages and an agent's finalagent_messages that are not working text, the last of eachmessageId. Not searched: partial messages, working text, reasoning (not the agent's words, ADR 0044), steps' input and output and tool results (shown on demand and redacted, ADR 0030; large and noisy), asked agents' text, surfaces and plans, a form's answers (they need the surface to be read), file names (a follow-up) and usage, checks and shares (not words). Forks are searched: each is the person's own conversation, but while the parent exists the events a fork copied give no message hit (the parent shows them); once it is deleted they are the fork's own.Whole words, matched by their start, defined by the contract and computed in Rust. A word is a run of letters, marks and numbers; its key is NFKD, no marks, lower case,
œ æ ßspelled out, the final sigma made a sigma, only letters and numbers. A query's terms are the keys of its words (at most 8, of 2 to 64 code points, distinct); a document matches when every term is a prefix of a key of one of its words. No stemming, no language, no segmentation: it serves English and French, and a run of Chinese letters is one word. Postgres is only the index: the store keeps the Rust keys as atsvectorbuilt byarray_to_tsvector(lexemes as given: no parser, no dictionary, no locale) and asks it atsquerymade of those keys with:*. So the candidates a database finds are the contract's whatever its collation, and a second client or a second store (the in-memory one) answers the same.Everything is deterministic and contractual: the hit set, the snippets, their offsets, the order (
rankdescending, then the thread'siddescending: 2 for a title hit, 1 for a description hit, 0 for messages only) andmessageHits. Nothing depends onts_rank,ts_headline, an extension or the database's version. Only the cursor's encoding is each server's own. The page isdocs/api/thread-search-v1.md, with vectors that the Rust core and the web's mock server both read.Written in the commit of the event. A new table
message_terms (thread_id, seq, owner, message_id, terms tsvector)with a GIN index, andthreads.title_terms,threads.description_termsandthreads.search_through(the seq the index has been through, as ADR 0065'susage_through):insert_eventswrites the rows in the transaction of the events, a fork copies its parent's rows next to the events, and each commit first indexes(search_through, last_seq], so a thread is complete whichever builds wrote and in whatever order. Migration0025adds columns and an empty table: nothing is rewritten and nothing locks a large table.orchestrator search backfillindexes the logs that predate it, per thread under its lock, in pages, idempotently (the same command shape asusage backfill).Amended 2026-11-15 (the review of pull request 322). Three rules were missing. (a) A fold version. The keys are made by three Unicode tables (Rust's
to_lowercase,regex-syntax's classes,unicode-normalization), so a dependency bump could split the stored keys from the query's with no error.orch_core::search::FOLD_VERSION(1) is stored per thread (threads.search_fold, in0025: it was not released) and must be raised whenever the folding rules or the tables behind them change; a unit test pins the fold on inputs chosen to move with those tables, and its failure message says "raise the version". A thread stored under another version is unindexed: it is not found (the choice: never found, rather than found by old keys), its next commit or the backfill indexes it again from the start replacing its rows, andsearch backfill --rebuilddoes that for every thread. (b) The operator is told. At startup the orchestrator logs one WARN with the count of unindexed threads (capped at 100,000) and the command; the count readsthreadsonce per process start (it stops at the cap, but reads the whole table when nearly every thread is indexed: there is no index on columns that change with every commit), andsearch backfillreports how manyremaining. (c) A commit's catch-up is bounded: at most 500 older events beside its own, the watermark moving only as far as it got (never past a gap), the commit's own events always indexed (above the watermark when the old log is not done: the upsert makes the later catch-up over them harmless), a message that a later final message replaces not indexed. A thread not caught up is found only for what is indexed.Authorization:
thread.read, which every role holds for its own threads, and no new permission; bothmessage_terms.ownerandthreads.ownerare the caller; no administrator reads more (ADR 0039); another person's thread is simply never a hit, by title or by content. What it finds is always a subset of whatlistThreadslists for the samearchivedandbranches(a test holds it). No search under/api/sharedor/api/public.Deletion (ADR 0043):
message_termshangs oneventswithON DELETE CASCADEand the title columns are on the thread row, so the delete's own transaction removes every word. Backups keep them, as ADR 0043 already says of everything else.Cost and abuse. A query has at most 8 prefix terms of at least 2 characters; the store runs it in a read transaction under one 2-second budget for all its statements (each statement's
SET LOCAL statement_timeoutis what the ones before it left; a timeout is503 search_unavailablewithRetry-After), and a process runs at most 8 searches at once, for everybody: the ninth is a 503 at once (no queue: a queue under a slow database holds connections longer); each person has a token bucket (a burst of 20, then 2 a second, in this process,429 rate_limitedwithRetry-After); the query is never in a URL, a trace or a log line (the log says the number of terms), and a test reads the captured log. What is not bounded: the cost of a prefix term over a very large shared index. The GIN index ontermsspans every owner, so a prefix such asabscans the postings of every person's messages that start with it before the owner filter applies, and the limits above bound the number and the time of searches, not that scan. If it is too slow at scale the follow-ups are a per-owner index (a partitioned or an owner-prefixed key) and a rule on the shortest prefix; neither is built here.
Consequences ​
- Easier: a second client searches from the contract; the same query shows the same hits on every client; no extension, no collation to configure, no ranking function to tune; the thread list keeps its shape.
- Harder: the index is a second place that holds words, written on every message (a few hundred bytes of keys a message, and a GIN insert); a person's words are in two tables until the thread is erased; a new Unicode version could change which characters are letters, so the contract's vectors use only Unicode 13 and earlier and a change of the fold raises
FOLD_VERSIONand needs a backfill (decision 6, amended). - Required elsewhere: the
ThreadSearchport is a supertrait ofThreadStore: every implementer ofThreadStoremust implement it (a breaking change for those who implement the store: the in-memory and Postgres stores do);GET /api/confighas the membersearch; the web's mock server has the route; 7b draws the box (built 2026-11-15). - A limit, stated: no stemming, no typo tolerance, no phrase query, no segmentation of Chinese, Japanese or Thai, only the first 3,000 words of a document.
Alternatives rejected ​
- Postgres full-text search with a language (
to_tsvector('english', …),websearch_to_tsquery,ts_rank,ts_headline): it ties the hits to the database's configuration and version, gives a stemmer for one language to a person who writes two, and makes the snippets, the offsets and the order the database's: a second client could not reproduce them, which ADR 0067's first rule forbids. pg_trgmorunaccent: an extension to install and keep in step on every database, for a prefix match this design does without.GET /api/threads?q=: the words in every access log and proxy, and a cursor that has rail meaning.- Searching the log with
ILIKE: no index; a person's every event for every keystroke. - Ordering by last activity: a cursor that must snapshot the order; by creation time the order is stable between pages.
What the build settled, for the owner to confirm ​
- The amendment of invariant 3 is text above, noted in
CLAUDE.mdand ADR 0001 with this date. - Order inside a rank: the newest created, because paging stays stable (last activity would need a snapshot).
- Prefix matching with no stemming for English and French.
- Searched: titles, descriptions, a person's messages and the agent's final answers; file names later; never step input or output or reasoning.
- Archived threads are included by default (the thread says it is archived); edit branches only when asked for, as in the list.
- A message that a fork copied is not a hit while its parent exists.
- A limit of 3,000 words a document, because a
tsvectoris limited to a megabyte and an unbounded one would fail a commit. - The query is cut, not refused, where it is long: a term over 64 code points is cut to them (a refusal would make a pasted URL an error).
Facts, and how far each is proven ​
Verified 2026-11-15 on a local PostgreSQL 16.15 (the version of compose.yaml) by psql and by the conformance suite of orch-ports run against PgStore (ORCH_TEST_DATABASE_URL, 186 cases, 14 of them this ADR's, plus tests/thread_search.rs and the binary's tests/search.rs):
array_to_tsvector(text[])keeps lexemes exactly as given (no stop word dropped, no stemming, no case folding), sorts and deduplicates them; Cyrillic, CJK, accented and digit lexemes round-trip.'key':* & 'key2':*cast from text totsqueryis a prefix match of every key, in onetsvector(never across two):'прив':*findsпривет,'ab':*findsabcand'bc':*does not.- A fork's copied range indexed from the fork's own log, a message the parent later replaced included, and the cascade of
eventsleaving no row of an erased thread. - A search that waits on a lock held on
message_termsends in57014after the 2 sstatement_timeout, which the store maps toUnavailable(the API's 503). - Removing the fork predicate from the query makes the fork cases fail (the suite bites), as does removing the delete of a replaced message.
Verified by running both implementations on the same vectors: orch_core::search (the regex crate's Unicode tables, unicode-normalization 0.1.25) and web/mock/search.ts (Node 22's ICU) agree on every vector, which use only characters of Unicode 13 and earlier; whether they agree beyond that is unverified.
Verified 2026-11-15, after the review, on the same PostgreSQL 16 by the conformance suite and tests/thread_search.rs: a thread under a lower fold version (with keys no query makes) is not found, is indexed again by its commit (rows replaced) or by the backfill, and --rebuild goes through every thread; a commit to a thread with 1,200 or 2,000 old events moves the watermark by exactly 500 and indexes its own events above it, the next commits do the next 500, the backfill finishes (rows written beyond the watermark are upserted, never doubled) and a message replaced beyond the part caught up is never indexed; a commit that fails after its index write (a trigger of the test) leaves no row; a later commit rewrites no old row (xmin); the backfill's message count is exact. Each of these was made to fail by the mutation that undoes it.
Unverified: the cost of a prefix term over a very large shared index (above: not bounded), and that the planner combines the GIN index on terms with the btree on owner (BitmapAnd) at the size of a real deployment (the query is written so that it can; no plan was read at scale: the plan at scale stays unverified); the cost of the index at a million messages; dev/search-e2e.sh (it has not run against the stack: no Docker where it was written); and the web (7b; built 2026-11-15, see the amendment).
Not done here ​
The web: the box, the results and the highlighting (7b; built 2026-11-15, see the amendment); the screens; the shortcut. Every Postgres claim is proven only where the conformance suite ran (see the pull request).
Amended 2026-11-15: the web's box is built (slice 7b) ​
The box, the results, the highlighting from the offsets and the shortcut are built in the web (web/src/features/search/, web/DESIGN.md "Search"), as one more client of this contract: it needed one thing that thread-search-v1.md did not say, now added to the contract (what a hit's seq names and where a client that can anchor only a person's messages goes for an agent's answer), and it added no route and no dependency. It reads search of GET /api/config (its presence is the capability, its numbers are the field's limit), sends the query in the body of a POST after a 250 ms debounce with an AbortController per request and a counter that drops a stale answer, tries a 429 again after its Retry-After, tells a 503, draws a snippet as plain and marked text nodes cut at the UTF-16 offsets (never dangerouslySetInnerHTML) and opens a message hit at /threads/<id>#m-<seq>. Two things the contract left to a client were decided in the web, and the first is now in the contract: an agent's answer has no element with the id m-<seq> (only a person's message has), so the page goes, once the transcript has been still for 600 ms, to the last person's message at or before the seq, the one that started the turn; and the shortcut is Ctrl or ⌘ with K (only ⌘ on an Apple platform). Added 2026-11-15 after review: a failed "Show more" keeps its hits, a 429 is tried again three times and then waits for the person, an answer of the wrong shape is an error, and a link to a message with no element of its own (any #m-<seq>, not only a search hit) goes to the last person's message before it. Proven on the mock in Chromium (unit, jsdom, Playwright on a desktop and a phone, axe in both schemes); unverified: against a real orchestrator, in Firefox or WebKit, and the browsers' own use of Ctrl+K.