The tool split the query into units with its own regex, a second reading of
search syntax that disagreed with the store's sanitizer (alpha%beta is two
terms to the store, one to the tool), so an own-echo match could still skip
the retry. SessionSearch now exposes any_term_query, the store's sanitizer plus
its OR-relaxation, and discovery retries with exactly that.
Three gaps in the recovery path (Greptile review on b2e4cc36cc):
- A demoted tool result's full original was matched only while its stub
was live. A later compaction archives the stub, so the original
(active=0, compacted=0) dropped out of every search. The superseded test
now accepts a live OR archived twin with the same message_uid and
different content (SUPERSEDED_ORIGINAL_SQL, shared by search and
message_storage_state).
- Scrolling to such an original was rejected as "already in your active
context". MessageStorageState gains `superseded`, and the scroll guard
treats a superseded original like an archived row.
- The footer's all-role search sent every role down the tool route's
stored-row LIKE scan, which can't read structured content, so a keyword
in an archived image turn's caption was unreachable. Conversation roles
and the tool role now search separately (word index vs full-body scan)
and interleave; discovery and the in-session shape share that helper.
Tests: re-compaction and scroll cases on the verbatim stub call, an image
turn on the verbatim footer call, and the contract case covers the
archived-twin original and the `superseded` flag on both backends.
The in-session search scanned 300 rows and dropped the caller's live rows
afterwards, so a session with more live matches than that reported
"Matches exist only in your active context" while an archived match
existed. Inside the caller's own session the search now selects, in SQL,
only rows that left its live transcript (compacted_in_session): the
compaction archive plus a superseded original whose live copy (same
message_uid) was rewritten, which is where a tool result demoted at
compaction keeps its only full text. Those lead; the lineage's other
sessions follow under the scroll guard's live-context rule.
Ports 055fe4ae92 ("the caller's own compaction archive leads discovery")
and a2ccbe606b ("the stub call recovers a demoted carried-tail tool
result") from #120403 onto the persistence interface, plus b6af8a92a0's
end-to-end test that runs each pointer's emitted call verbatim. The
original boosted one row (limit=1) into global discovery; with the pointers
on the scoped shape every archived match comes back, and the test now
checks two values from one session and 320 competing live rows.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
session_search(query=..., session_id=...) silently dropped the query and
read the whole session (head/tail), yet the context compressor's recovery
footer tells the model to call exactly that shape to recover compacted
detail.
query + session_id now searches inside that session's compression
lineage: search_messages() takes a session_ids scope applied in SQL on
every route (FTS5, CJK, trigram, LIKE fallback, rebuild gap), so hits
elsewhere cannot fill the limit. Results come back one per matching
message with match_message_id for the scroll shape. Rows still in the
caller's live context are skipped by the same rule the scroll guard
uses; compaction-archived rows and compression-ended ancestors stay
searchable. The schema text documents the new shape.
(Ported onto the persistence interface: be3d6affc8 removed hermes_state_search.py, so the session_ids scope now goes through SessionSearch.search_messages, the SQLite search store and the in-memory reference.)
Review follow-ups on the sessions list:
- min_message_count was applied to the compression ROOT before the walk to
its tip, so a root that rotated before its first flush (0 messages) hid its
populated tip. The floor now admits a compression-ended row when any
continuation in its lineage meets it (same continuation edge as the list
CTE; the recursive EXISTS runs only for compression rows under the floor).
The reference backend's filter follows the same lineage rule.
- The tip-title inheritance lookup bound every ancestor id in one IN (...);
six 180-deep chains exceed a 999-variable SQLite build. It now goes
through _id_chunks.
- `--all` dropped every exclusion except `tool`; it now lists every source.
- Gateway `/sessions` leaves cron runs out of its recents/search page, as
#140273 proposed; pinned listings are unchanged.
Co-authored-by: hbtjm9000 <260822553+hbtjm9000@users.noreply.github.com>
Bare `hermes sessions` printed argparse help. On a terminal it now opens the
existing `browse` picker (arrows + Enter resumes via `hermes --resume <id>`);
off a terminal it prints the list.
`hermes sessions list` ranked root rows by started_at and cut the page before
projecting compression tips. A cron tick writes a `local-<sha>` row every run
(most stay empty, untitled: "—"), so the newest-started rows were all cron and
every compacted human thread, whose root started days ago, fell off the page.
List and browse now use the Desktop recents shape: rank lineages by their
tip's last message (order_by_last_active), drop zero-message rows, and leave
out automated sources (cron, webhook, push, kanban, tool, oneshot). `--all`
or an explicit `--source` brings them back. Subagent children stay out.
A projected tip with no title of its own fell back only to the root's title;
it now takes the nearest titled segment of its lineage (a thread titled after
its first rotation carries the title on a middle segment).
Nine Python gates each re-declared `^[a-z0-9][a-z0-9_-]{0,63}$` instead of using
`hermes_constants.PROFILE_ID_RE`: the `-p` pre-parse, the gateway's session-key
parser, lock-owner and home labels, the SSH spawn argument, saved SSH
`remoteProfile`, service/launchd profile names, the session store's own-profile
derivation and the profile segment of the public `<profile>:<platform>` status
key. Five Desktop files did the same instead of the exported
`profile-id-guard.ts::PROFILE_ID_ARG_RE` (`DESKTOP_PROFILE_NAME_RE` is now
derived from it). A change to the owner would have left each copy accepting the
old set.
Each gate now reads the owner at call time. Accepted and refused names, the
`default`/`main`/`main~` aliases and the platform-segment grammar are unchanged:
a 23-input corpus over all nine Python gates and a real `hermes -p` run give the
same output on base and head. Same-shaped grammars for other identifiers
(peer names, case-insensitive remote handles, webhook names, s6 service names,
kanban slugs, plugin names) are deliberately left alone.
New guards swap the owner for a different grammar and assert every gate
follows it (Python: tests/hermes_cli/test_profile_id_grammar_owner.py; Electron:
apps/desktop/electron/profile-id-guard.test.ts); both fail on the base code.
Refs #155595 (state-24).
referenced_archive_refs read at most 20,001 rows and answered "unknown"
past 20,000, and the sweep then kept every file in cache/pruned and
cache/spillover. Every prune stub row counts toward that number, so a
busy home passed it and was never swept again.
Rows are now read one at a time with no cap; memory is bounded by the
reference set. Any database error still answers "unknown", so the sweep
still fails closed. Below the old cap the cost is unchanged (the filter
has no index, so the whole table was already scanned). Past it the read
used to stop at the 20,001st match and now runs to the end, so on a
large home it stays open longer. The docs sentence about the cap is
removed.
(cherry picked from commit a5bed1d2d9fb436f6129388b237330a509abb6aa)
Salvage of #136488 (kshitijk4poor), review findings from 100yenadmin and kvnloo.
- No information loss: before the proactive prune shortens a tool result, its
full original is written byte-verified to
$HERMES_HOME/cache/pruned/<session>_<UTC>_<tool>_<id>.<json|txt> and the stub
ends with " — full result: <path>", so read_file returns the exact output.
A result whose write fails stays whole and the reclaim gate is re-checked on
what is left (no commit -> the written files are removed).
- This also closes kvnloo's unflushed-original case without deferring the
prune: the original no longer depends on the store having seen the row.
- The running turn is never shortened: the post-tool site passes the turn's
user-row index (turn_start), and every row from it on is kept whole. Before,
the count-only tail let a long tool loop stub its own earlier calls.
- One sweeper: the spillover reference/retention machinery now covers
cache/pruned too (archive_refs_in_text / referenced_archive_refs; session
delete retires both). Pruned files follow sessions.retention_days and are
never deleted while state.db references them. cache/pruned is mounted for
sandboxed backends like cache/spillover, and the stub names the path the
backend sees.
- Cold-cache reading isolated in turn_proactive_prune.prompt_cache_is_cold so
the shared cache clock can replace it in one line.
- Two skill-safety fixtures pin the old 4096 reclaim gate (the shipped 64K
default made their ~7K-token transcripts no-ops).
From the final-head gate wave on b12ce8e275:
- Two openers that both saw the retired marker before rebuild admission each
ran the full rebuild in turn (about 130 s on a 1.35M-row store), because
the admitted callback did not re-check whether a peer had already
aligned. align_locked now re-reads the layout and the marker under
BEGIN IMMEDIATE and skips when there is nothing left to do. New test: the
opener admitted second runs no rebuild; red on b12ce8e275
(['second', 'first']).
- messages._display_set uses the shared sql_common._in_one_read instead of
its own copy of the same BEGIN/ROLLBACK wrapper.
- Docstrings corrected where they no longer matched the code: the probe's
IOERR may be persistent; _attribute_ranked_corruption raises it for a
replay; _fts_match_read publishes the unattributed error after the retry
budget; a writable write as well as a search detaches a damaged index;
the skip decision is re-read under the lock.
Second-model review of e468bba3ce: an exception's __context__ is not proof
that it came from the rank probe. A plain ranked-read IOERR raised while the
caller was handling an unrelated DatabaseError was treated as an exhausted
probe and latched that ambient error. The probe now raises _RankProbeIoerr,
an OperationalError (still retried by _read_retrying_ioerr) that carries the
corruption it was diagnosing, and only that type is restored after the
budget is spent.
Test: a plain ranked-read IOERR inside a handler for an unrelated corruption
error answers [] and latches nothing. Red on e468bba3ce.
The delta review of 6410cd3ca1 showed the probe re-raised every
OperationalError. "database is locked", "interrupted" or "no such function"
then replaced the bare SQLITE_CORRUPT, and the primary search route turned
it into an empty answer with nothing latched, where 5046fe2946 failed
closed. The probe now re-raises only disk I/O errors and keeps the original
error otherwise. An IOERR that outlasts the read retry budget restores the
unattributed corruption the probe was diagnosing (latched and raised)
instead of surfacing as the IOERR the search maps to [].
Test: a locked probe and a probe whose IOERR persists both leave
SQLITE_CORRUPT raised and latched, and only the IOERR case replays the read.
Both cases are red on 6410cd3ca1. The transient-IOERR test now asserts
exactly one failed probe.
Second-model review of 5046fe2946: the attribution probe caught every
DatabaseError, including a transient "disk I/O error" OperationalError, and
then returned the original bare SQLITE_CORRUPT. _read_retrying_ioerr retries
only IOERR, so it published the unattributed error to the storage-health
latch: the bug this PR fixes, reachable when index damage and the WAL
transition window coincide. The probe now re-raises OperationalError so the
holder replays the whole read.
Also from the gate wave:
- _in_one_read moves unchanged from stored_reads to sql_common, so search no
longer imports a private helper from the transcript module.
- The interrupted-realign test raises only after the FTS DDL, not after any
script the executor runs.
New test: a disk I/O error on the first probe replays the read, answers from
canonical rows and leaves storage ok. Red with the re-raise removed.
From the gate wave on 529797fa7c and BearHuddleston's re-review:
- The rank-only MATCH pins its snapshot through the existing
stored_reads._in_one_read instead of a local copy of the same
BEGIN/ROLLBACK wrapper.
- _migrate_misaligned_fts_source: one locked helper owns the population
recheck and the realign; the admitted callback is named instead of a
lambda returning an ignored value.
- New test: a realign interrupted after its DDL leaves the old index hit and
the retired marker in place, and the next open realigns. Red with the
BEGIN IMMEDIATE removed.
- Reopens in the realign tests assert FTS stays enabled instead of skipping.
- _search_messages_stale docstring narrowed to the Latin retries (Bear's
suggestion: a triggering CJK trigram failure still takes _search_cjk's
any-term fallback, as on main). The empty-store test no longer names a
savepoint.
From the gate wave and second-model review of 83d9fa65b3:
- A store whose FTS is detached now answers through one helper on the
triggering request and every later one: LIKE on the exact terms, then on
any term after a miss (CJK skipped, as the FTS OR-relaxed retry does). Before,
the triggering OR-relaxed request found a row the next identical request
did not. The primary-route detach returns that answer directly, which
removes the detached_before_retries flag.
- _mark_fts_detached owns the three in-memory flag writes shared by
writable fail-open, deferred admission, the cross-process stale refresh and
the read-only detach.
- Read-only detach: the warning and docstring no longer promise that the next
writable open repairs the index (nothing is persisted); they name the real
paths, a writable search or `hermes sessions optimize-storage`. The test
checks state_meta through a raw read-only connection instead of after a
writer open.
- Realign: the marker check is inlined with its rationale, the rebuild timer
starts inside do_align, and the warning states what is known (the marker
only pre-v3 releases write) instead of asserting the history.
- The injected-error latch test is named for what it injects.
From BearHuddleston's review of 8678b050ac (three inline patches):
- Realign: the unlocked message check only routes populated stores to
rebuild admission; the skip-rebuild decision, the DDL, any rebuild and the
marker removal now commit together under BEGIN IMMEDIATE. A peer insert
between the empty check and the old savepoint was indexed and then lost;
an interrupted rebuild now rolls back to the old index.
- Ranked MATCH: pin a read transaction for the rank-only route so the
diagnostic bm25 probe sees the same index generation as the failed read
(a peer rebuild in between otherwise let code 11 escape and latch a
healthy store). An existing transaction is left alone; the read-only
transaction is ended by ROLLBACK.
- Test: delete one cut tool row while the pre-v3 trigger is installed, so a
repair that only swaps triggers and keeps the old postings fails.
[Salvage: ported onto 83d9fa65b3 by kshitijk4poor; the _schema.py hunk was
re-applied by hand around the post-rebuild realign warning.]
Read-only handles (dashboard and TUI cross-profile browsing) cannot write
the stale breadcrumb, so _enter_fts_fail_open refused and the newly
index-scoped error propagated instead of answering from canonical rows.
Search now detaches FTS for that handle's own lifetime and serves LIKE,
leaving the persistent detach and the rebuild to the next writable open.
The pre-v3-marker realign now logs after the rebuild has run, with its
duration (130 s on a 1.35M-row / 8.9 GB store clone), instead of claiming a
rebuild before admission decides. A deferred open logs only the existing
deferral line.
The gate wave on 764c751 found that the `rescope` keyword threaded through
StoreHolder._read_all/_read_retrying_ioerr put FTS policy on the shared read
boundary, and that the diagnostic probe ran on a second pooled reader, after
the failing read had released its snapshot.
Search now owns one MATCH read (_fts_match_read) that runs inside
_read_retrying_ioerr's callback. It attributes a bare SQLITE_CORRUPT on the
rank-only route on the SAME connection before the error reaches the
storage-health latch. _holder.py is back to main, and both ranked call sites
share the read.
The genuine-corruption test now drives search_messages instead of the private
closure.
- Empty realigned store: the marker realign of a store with no messages runs
inside SAVEPOINT fts_align_empty; run its DDL through
_execute_ddl_script_transactional so executescript's implicit COMMIT no
longer ends the savepoint ("no such savepoint: fts_align_empty" on open).
- Trigram / OR-relaxed retry that detaches the indexes now answers the
triggering request from canonical rows (exact terms, then any term)
instead of returning an empty miss.
- _read_all passes rescope only when set, keeping the one-argument
_read_retrying_ioerr call shape other callers and test spies rely on.
- Rank detection compares against the rank-only ORDER BY constant instead
of a substring test on the SQL fragment.
Tests: empty-store reopen with the retired marker; trigram and OR-relaxed
retries return the stored row on the first request.
A dashboard search could take a whole profile's session storage down until restart
although state.db was intact (PRAGMA quick_check: ok).
FTS5 evaluates `ORDER BY rank` in a nested sorter statement and SQLite masks that
statement's error to the primary code, so index damage bm25 reports as
SQLITE_CORRUPT_VTAB (e.g. a posting whose _docsize row is gone) reached the read path as
bare SQLITE_CORRUPT. _read_retrying_ioerr published it before the search's existing
fail-open could run, it classified as structural, and the process-wide latch refused
every session.create/resume with storage_unavailable.
- StoreHolder._read_all/_read_retrying_ioerr take an optional `rescope` applied before
the storage-health latch. The ranked MATCH reads pass one that, only for bare
SQLITE_CORRUPT on a rank-ordered statement, re-asks the index alone (unsorted bm25
keeps the extended code). An index-scoped answer replaces the error, so the existing
fail-open answers from canonical rows and the error, if raised, maps to
SearchIndexCorrupt; anything else keeps the original and still fails closed.
- The zero-hit trigram retry now fails open like the other ranked routes.
- _migrate_misaligned_fts_source also realigns a store whose retired
fts_tool_full_content_high_water marker is back. A release before FTS storage v3
reopening a realigned store re-stamps it at MAX(id) and reinstalls id-gated triggers
whose 'delete' sends full content for tool rows the v3 rebuild indexed as the bounded
prefix; each such delete leaves the token cut at the boundary behind with no _docsize
row, which is the damage above.
Wire error codes are unchanged.
hermes_state.py becomes the stand-in plugins import, the rest of the legacy store and its test folder go, and the per-process modules the backend imported from main move under persistence/sqlite/_state/. The backend checks PID namespaces and lease holders through process_identity and its WAL setup through sqlite_support, and its error module takes the shared predicates and classification from storage_errors, so neither helper set has a second copy. The backend, sqlite_support.py and the tests that pin those modules reach their final imports, and the backend-import guard allows no file outside persistence/. The modules no caller imports any more go with it: the agent's onboarding rules (now in session_rules) and gateway/session_admission.py.
The stand-in's SessionDB releases its store on close() and, used again afterwards, opens it again with a warning, as the old class reopened its connection, unless the file at its path was replaced or the store is latched corrupt; a read-only one raises. A close during a call releases the store when the call returns. A named source wins over a source list in its session listing and count.
An agent given a writable stand-in SessionDB as session_db= and no persistence= takes the store handle that SessionDB forwards to as its persistence, so its turn flush, token counts, compression and session row writes go through the storage interface, as an agent given the old SessionDB wrote through it.
The backend-import guard also holds the backend's remaining reads of the process or task home, each with its reason, and refuses any other and any import of the stand-in inside persistence/sqlite/.
Plugin context engines get the agent's store as persistence= beside the deprecated session_db=, in each hook whose signature accepts that keyword, including the rebind after /new, /resume and /branch, and the context engine guide and the plugin guide's replacement table name it. A test fails once the running release reaches the stand-in's removal release, listing what goes with the stand-in.
release_unheld_media and collect_unheld_api_images take a store only: their SessionDB branches, which no caller reaches, go with the gateway's own copies of the admission and transcript queries.
Main's update_session_model writes gateway_runtime={**route, "model": model or None} (2fee28289b), so a resumed session pairs the switched provider with its model even after a fallback serving the first call rewrote the model column. The SQLite backend wrote the route without the model; it now writes main's patch, with main's comment, and the update_model contract case (model stamped, stale endpoint cleared) passes on SQLite.
Reported-by: alt-glitch
Reported-by: kshitijk4poor
Reported-by: teknium1
The interface's append and append_batch dropped compression_lock_holder, which fenced nothing: a live compression lock never blocks an ordinary append, on main as here. The SQLite backend's two verbs drop it too and stop passing it to the store-level append; the store helpers keep their own parameter for the compression writes that do check the lock. The contract case refusing the keyword now passes on SQLite.
Reported-by: kshitijk4poor
The plain-message branch of the listing preview SQL now left-trims the content before the 63-character head cut, as main's listing does, so leading whitespace no longer eats into the cut and every cut preview carries the ... marker.
The holder keys prompt_cache_clock like a route field, so queued deltas carrying different cache events apply in order and are never merged. The usage delta passes its clock to the token update, which writes the column only when a clock is given, with main's statement. The usage repository gains prompt_cache_clock (one statement: the stored clock, the resume fallback only for sessions whose cache counters are non-zero, and the archived-row generation, after draining the queue) and prompt_cache_generation, and the session record carries the column.
The SQLite backend's peer-recovery queries now exclude rows carrying _delegate_from unless the row is the chat's /new continuation (_reset_from) or a delegate the user resumed the chat onto (_chat_adopted), as main's store does. The session insert strips a delegate marker from a keyed /new continuation and from a config upserted onto a reset row, and a compression rotation carries _chat_adopted onto the new tip.
The conversation store modules imported one another at their ends, and the package preloaded compression so that the order happened to resolve: ten modules formed one module-level cycle. Each module now imports its peers at its head along one order (compaction_display, core, messages, compression, coverage, portability, write_guards, sessions, prune_rewrite, titles), and an import that runs against that order happens inside the function that uses it. The preload is gone, and every store module imports alone in a fresh interpreter.