# Local query contract

SQLite 3.35+ with FTS5 is required. Install/runtime fail with
`sqlite_fts5_unsupported` when unavailable, and `doctor` reports the capability.
There is no capped-scan fallback. Schema 13 adds query indexes, a derived
search table, transactional insert/update/delete triggers, and validated
backfill without rewriting canonical events or earlier migration checksums.

## Filters and order

Events default to ascending sequence; tail/context default to newest matching
sequence first. `--order asc|desc` (SDK `order=`) overrides local event order.
Ledger list/watch/stream remain ascending. Actor, event/entity type/ID,
workflow namespace/version, sequence and timestamp predicates run in SQL
before LIMIT. `events --event-id` filters by ID and direct `query event <id>`
uses the unique ID index. `--since` is an exclusive sequence lower bound even
when output is descending. `--since-at` is an inclusive timestamp bound and
requires an explicit timezone.
Timestamp comparisons normalize ISO values to exact integer microseconds;
subsecond bounds are not rounded to SQLite's date-function precision. Stored
timestamps without an offset are interpreted as UTC; invalid stored timestamp
text does not match a time-bound query. This is a connection-local read function,
not a new schema dependency or rewrite of historical event timestamps.

Cloud `--namespace`, ledger and source selectors are not aliases for local
workflow. In `scope=all`, local cursor/order options affect only the local
component; Cloud preserves its own query/checkpoint behavior. There is no
combined cross-scope cursor.

## Pages and concurrency

The first page captures `snapshot_sequence`, the current maximum sequence.
Continuation excludes subsequent appends and binds normalized filters,
direction and the search query. New page sizes are allowed (1–1000 per page,
not a total cap). Malformed or cross-filter/order cursor reuse fails
with `query_cursor_invalid`. Start a new query to see newer events.

This high-water guarantee assumes append-only events. External SQL changes,
deletions or state replacement invalidate the traversal. Cursors are opaque
routing metadata, not signatures or authorization. Ordinary pages expose
`events`, `next_cursor`, `has_more`, `limit`, `order`, `filters`,
`snapshot_sequence` and bounded `candidate_count`; context adds these to its
context block. A `limit + 1` lookahead determines whether another page exists.

## Search

Search is Unicode word/phrase matching, not arbitrary substring matching.
Whitespace-separated literal groups must all match. Quoted text keeps a
contiguous phrase; punctuation splits tokens. Operator-looking FTS text is
literal data, never executable query syntax. Blank input is rejected;
punctuation-only input returns no matches. Searchable fields are event/entity
IDs/types, actor, workflow namespace/version, and deterministic source JSON
text for payload/causal fields, including scalar/list/object JSON.

Only actual FTS matches are included. Ranking uses weighted presence in
matching fields: event/entity IDs 20, event type 8, entity type/actor/workflow
namespace 5, workflow version/payload 3, causal fields 1. Matching-field
reasons come from the FTS result. Positive text score sorts first, followed by
sequence descending and event ID. This corpus-independent score does not
change when other events are appended. Numeric scores are not a stable API
contract. SQLite's matching/highlight behavior is described in its
[FTS5 documentation](https://www.sqlite.org/fts5.html).

Local search returns compact `items` with `score`, positive `text_score`,
`score_reasons`, `summary` and event identifiers. `candidate_count` counts
fetched matches, including at most one lookahead, not all matching rows;
`candidate_count_is_total=false` makes this explicit. `result_count` counts
emitted items. `has_more` and `truncated` include both lookahead and the
`max_text_chars` item-text budget. Continue after the last emitted item using
`next_cursor`, not after the last fetched candidate. Local follow-up tools are
`op_sys_event_get` and `op_sys_events_query`.

The budget measures the compact item-text representation, not the entire
response envelope. If even one compact event cannot fit, increase the budget
after `query_text_budget_too_small`; the page is not silently skipped. The
canonical event write API still requires an object payload, with scalar,
list and object values within it; historical migration validation is unchanged.

## Derived index integrity and recovery

`doctor` checks schema structure and source/search-content counts and values
read-only. It does not repair. `CoordinationStore.rebuild_event_search_index()`
rebuilds derived rows transactionally and performs FTS internal-integrity and
source/content checks. Canonical events are untouched. This repairs derived
content, not an unknown schema, corrupted canonical events, or a production
rollout. Existing private-state, migration, backup/restore and writer-fencing
requirements still apply. Do not drop the FTS schema or downgrade the DB;
prefer a patch-forward binary. Valuable/live-state recovery requires its own
target-specific authorization and independently verified recovery evidence.
