A continuing session replays its stored system prompt verbatim on every turn
so the provider prefix cache stays warm. The gateway restores that prompt from
the session row on each fresh agent, and warm cached agents keep it in memory,
so SOUL.md edits, new or edited skills and project-context changes never
reach a long-running conversation until /new, which also drops the history.
Operators who push profile updates and restart the gateway had no way to make
existing conversations pick them up.
`hermes sessions refresh-prompts [--session ID] [--json]` records a refresh
epoch in the profile's state.db (state_meta, one counter orders profile-wide
and per-session requests). At the start of a continuing session's next turn,
_restore_or_build_system_prompt compares that epoch with the one stamped in
the session's model_config when its prompt was built. When the stored prompt
is older it follows the Bot Chat capability-refresh precedent in the same
function: tools[] pin restored first, skills prompt cache and snapshot
cleared, prompt rebuilt through _build_system_prompt (memory reloaded and
plugin sections re-rendered, as at a compaction boundary), cache break
recorded, on_session_start not fired, new bytes and epoch persisted so the
following turns restore them verbatim. One cache break per request.
Warm agents (gateway agent cache, TUI/Desktop) run the same check from
build_turn_context against the epoch they saw when their prompt was set, so
the verb works with the gateway running. A session first built after a
request is stamped with it and does not rebuild again.
With no request recorded, the stored prompt is reused byte-identically. The
only added work per continuing turn is one state_meta point read. No file
scanning, no config key, no watcher, no mid-turn mutation.
The tools[] pin is kept on purpose: the refresh is about instructions, and
tool changes already reach long sessions at the compaction boundary. The
cache break is recorded as the existing system_prompt_rebuild cause rather
than a new one, which would change the shared-metrics contract and schemas.
Related: #141154 (per-turn source hashing, alternative design), #74622.
* fix(sessions): proactive prune rewrites only the changed rows, in place
A prune edits the content of a few existing messages and never adds, drops or
reorders one, yet every commit went through archive_and_compact, which
archives all active rows and re-inserts the full list: state.db grew by the
whole live transcript per commit (#124102).
SessionDB.rewrite_pruned_rows resolves each changed message to its live row
(_row_id, else its tool call id or tool-call ids, else the single active row
with the same role and stored content), checks the row still holds the
original, inserts one archived twin of the pre-prune row (active=0,
compacted=1, still searchable) and updates the changed columns under the same
id. The prune tries it after the stale-history watermark check and falls back
to archive_and_compact when a row cannot be named exactly or an unwritten
message sits before durable ones.
Fixes#124102
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sessions): in-place prune twin keeps the live row's display slot
The content UPDATE fires messages_display_identity_update, which nulls
display_identity/display_order on the live row and on its freshly inserted
twin. The lazy backfill then gives the twin its own id as display_order, so
every demoted full body renders at the END of the transcript page, after the
newest user turn (3 x 24 KB bodies below "from desktop" in the probe).
Re-stamp both rows with the pre-update identity and order inside the same
transaction: the page projection shows one row per display_order (the live
stub, in place) and the twin stays a searchable archive. This is the same
stored-identity shape #117824 proposes for the archive writer (#117750), so
the resume projection collapses the pair once that lands.
Review-fix for #124273; one assertion added to the growth invariant
(red on the PR head: 20 page rows for 17 messages).
* fix(sessions): in-place prune keeps each display slot through later compaction and backfill
Review follow-up (ehz0ah): the rewritten live row kept the archived body's
identity, so a later archive_and_compact gave its copy a fresh slot and the
full body resurfaced in the old one. The live row now takes the identity of
what it stores and keeps the slot; the twin and any earlier generation's
copies (all nulled by the identity trigger) are restamped with their own
identity and slot, and the display backfill keeps a row's stored slot when
its stored identity is still correct. The prune pre-fills slots for legacy
rows so it never carries a missing one.
* fix(agent): fail closed when an in-place prune finds the row rewritten
rewrite_pruned_rows raised one PruneRowUnresolvedError for two different
conditions: the row cannot be named (ambiguity — the full writer handles it)
and the row IS named but its stored body changed. The second means another
surface already rewrote this generation, which is what StaleHeldHistory
exists to catch; the in-place prune preserves row ids, so
_archive_watermark_for cannot see it. Returning None there handed the stale
pruned_msgs to archive_and_compact, which archives rows it never compared
and republished the held text over a newer durable edit.
Split the stale case into a PruneRowStaleError subclass and raise
StaleHeldHistory from the in-place helper so the existing handler skips the
pass instead of committing. Ambiguity keeps the fallback.
Replaces the prune-fallback regression with the two cases review asked for:
a changed stored body skips the prune and leaves the newer body active; a
genuine ambiguity over current content still commits through the full writer.
* fix(agent): make an in-place prune visible to the other lease-less writer
rewrite_pruned_rows keeps every row id and activity flag, so the id/activity
staleness gate in held_archive_watermark cannot see that a prune already
committed. A second lease-less surface (micro-compaction) holding the pre-prune
transcript passes the gate and archive_and_compact republishes the pruned-away
bodies over the winner, undoing the prune.
stale_raises now also compares the held bodies against the stored ones via the
new SessionDB.rewritten_held_row_ids, so every lease-less writer sees the
in-place generation change, not just the prune caller that owns the exception.
* fix(state): compare durable row versions, not raw content, in the in-place stale guard
Reviewers on 631c897b converged on one root defect: the stale-write guard compared
raw SQLite bytes against a loaded/normalized view, which both missed real rewrites
and invented phantom ones.
- rewrite_pruned_rows._resolve: the staleness check is now the repo's stored-row CAS
digest (transcript_row_snapshot over a SELECT * row, covering every owned column
including assistant tool_calls arguments) when the held dict carries DB_ROW_SNAPSHOT,
and the loader-lens identity compare (_row_identity, the same representation
_stamp_kept_live_prefix uses) otherwise. Raw storage bytes are never compared
against a loaded view.
- The rewritten row's replacement dict is stamped with the row's new digest, and the
commit runs under _execute_transcript_write so a rollback restores the stamps.
- rewritten_held_row_ids takes full held dicts and applies the same two-leg compare;
only tool/assistant rows (the roles the in-place writer touches) are compared.
- held_archive_watermark(stale_raises=True) checks the durable prefix BEFORE the
ids[-1] is None early return, so an unstamped trailing message caps the watermark
but can no longer suppress version checks for the rows the caller holds exactly.
Closes the P0 stale tool_calls path, the P2 false-stale on freshly resumed
whitespace-padded rows, and the unstamped-tail blind spot (#124102).
* fix(state): gate the lease-less stale check on every role the fallback republishes
The staleness gate behind held_archive_watermark (rewritten_held_row_ids)
compared only tool/assistant held rows, but the fallback it guards —
archive_and_compact, reached whenever the in-place rewrite refuses (an
unwritten message before later durable rows, an unnamed row) — re-inserts
held rows of every model-transcript role verbatim. A user row another view
rewrote in place (set_user_message_content, the repair batch's in-place
rewrite) slipped the gate: the stale pre-edit body was republished active
and the newer edit left with zero active copies.
Compare every model-transcript role (user/assistant/tool); the per-row
comparison (DB_ROW_SNAPSHOT CAS, else the loader-lens identity) is already
role-agnostic. Bookkeeping roles stay excluded — they never reach the
model-facing list. Covers the prune fallback and micro-compaction, the two
lease-less callers of _archive_watermark_for (#124102).
Sabotage-run: reverting the role filter makes
test_a_concurrent_user_edit_stays_active_when_the_prune_falls_back fail
(stale body published); restored, the file is 22/22 green.
* style: use builtin generics in the in-place prune commit annotations
* refactor(compression): split the proactive prune and its commit into topical siblings
The code-health ratchet (CI) flags this PR's own growth: hermes_state_messages.py
(2190 > 2000), agent/context_compressor.py (5911 > its main value 5852) and
agent/conversation_compression.py (4585 > 4564). The remedy the repo prescribes:
move the PR's own code into topical siblings, keeping the facade as the seam.
- agent/context_compressor_prune.py: ProactivePruneMixin (prune_tool_results_only
+ _rewrite_pruned_rows_in_place), bound into ContextCompressor; origin-module
symbols read through _cc() at call time (the micro_compaction.py pattern) so
tests patching agent.context_compressor.X stay effective; logger keeps the
agent.context_compressor name for caplog parity.
- agent/conversation_compression_watermark.py: held_archive_watermark; the origin
module imports it and keeps _held_watermark (its only caller).
- hermes_state_prune_rewrite.py: SessionPruneRewriteMixin (rewrite_pruned_rows +
rewritten_held_row_ids), bound into SessionDB; every SessionDB call site and
test patch seam (db.rewrite_pruned_rows / db.rewritten_held_row_ids) unchanged.
Verified: scripts/check --only health --base origin/main -> 0 blocking; ruff clean;
prune/compaction batches green (test_proactive_prune_restart_safety 22/22,
test_micro_compaction 48/48, five proactive-prune files 25/25). The 4 failures in
test_compaction_prompt_rebuild / test_compression_review reproduce identically on
origin/main (pre-existing).
* fix(state): re-verify held rows inside the full writer's commit transaction
The lease-less stale gate (rewritten_held_row_ids) runs outside the write
transaction, so a second SessionDB connection that rewrites a covered row
AFTER the precheck but BEFORE archive_and_compact's BEGIN IMMEDIATE was
invisible to it: the commit archived the newer row and republished the stale
held text, leaving the newer edit with zero active copies (#124102, review
finding on 8c6da464).
- archive_and_compact takes held_for_cas: the caller's held dicts,
re-verified against the live rows INSIDE the commit's transaction before
any row moves; a mismatch raises HeldRowRewrittenError, which the two
lease-less callers (proactive prune fallback, micro-compaction sync)
treat exactly like StaleHeldHistory - nothing written, the pass is a
no-op and the newer generation keeps the session. The lease path leaves
it None: its lease rules out an overlapping rewrite.
- held_row_mismatches(conn, ...) is the compare lifted out of
rewritten_held_row_ids so both the read-path precheck and the
in-transaction fence share one implementation. It now chunks the id IN
query via _id_chunks (a history past SQLite's host-parameter limit
failed the pass instead of reclaiming) and resolves rows that have no
_row_id but do carry the persist marker + CAS snapshot by their logical
message_uid (idx_messages_session_uid) - the unaddressed live-replay
loader shape, whose rows were previously exempt from the fence entirely.
- regression: test_a_user_edit_landing_after_the_precheck_stays_active_in_the_commit
drives a second SessionDB connection's set_user_message_content at the
archive_and_compact call boundary; sabotage (gate disabled) makes it
fail exactly as the finding predicts.
* refactor(compression): drop the duplicate _held_watermark from the module split
The 8c6da464 sibling extraction left two identical _held_watermark
definitions back to back in agent/conversation_compression.py; Python
silently kept only the second, so editing the first had no effect (dead
code, root AGENTS.md). Remove the added copy.
* refactor(state): split the api_content sidecar writers into a topical sibling
hermes_state_messages.py crossed the FILE_LINES ratchet (2010 > 2000) after
the commit-window fence landed in it. Move set_latest_user_api_content /
set_message_api_content into hermes_state_api_content.py
(SessionApiContentMixin, bound into SessionDB in the same MRO slot): the
two row-addressed api_content sidecar UPDATEs are one topic, no behaviour
change, every call site and test patch seam unchanged.
* fix(state): flatten _archive_and_compact_on_conn onto the caller's transaction after the main merge
Main flattened this helper to run directly on the caller's write connection
(no nested _execute_transcript_write); the merge resolution had kept the old
nested shape, which opened a second BEGIN IMMEDIATE inside the live one and
deadlocked every archive_and_compact. Re-flattened while keeping the #124102
held_for_cas in-transaction CAS fence.
* fix(state): carry the held-row CAS fence through the worker RPC path
RuntimeSessionCompressionMixin.archive_and_compact rejected held_for_cas,
so a worker-side micro-compaction commit raised TypeError inside the mixin's
generic except and silently skipped the whole persist (unstamped marker,
durable transcript left un-compacted). Accept held_for_cas, project it onto
the closed handoff fields plus the persistence marker the CAS compare reads,
validate it in worker_archive, and thread it into
archive_on_connection -> _archive_and_compact_on_conn (#124102).
* test(micro): a stale held generation without row ids aborts the micro-compact
Review follow-up (ehz0ah/greptile-apps, PR #124273): ACP restore and OpenAI
session continuation load through the unaddressed live-replay projection
(get_messages_as_conversation without include_row_ids=True) — the persist
marker, durable message_uid and the stored-row CAS digest, but no _row_id.
held_row_mismatches already resolves that shape by logical message_uid, so
the lease-less fence still sees another surface's in-place prune. Pin it with
the regression both reviewers asked for: after another surface prunes in
place, micro-compaction from that stale no-row-id history is a true no-op —
the pruned stubs stay the only live generation and the pre-prune bodies are
not republished (#124102).
Sabotage: disabling the by-uid branch in held_row_mismatches fails this
test (the sync republishes the stale bodies); restored, 49/49 pass.
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
* fix(sessions): the uid-resolved stale fence CASes the newest active row
held_row_mismatches resolved an id-less held dict by its logical
message_uid with a bare fetchone(): when a carried or concurrent
compaction has cloned the row back beside its archived twin, one uid
names several active physical rows, and the uid index returns them
oldest-first. The fence then CASed the oldest copy — which still held
the payload the held digest was stamped from — and cleared a held
generation as current although another writer had rewritten the newest
row; the lease-less fallback republished the stale held payload over
that newer generation (#124102).
Resolve with the same newest-active rule as the loader's
_active_logical_message_row (ORDER BY id DESC LIMIT 1). Two
regressions pin it: two active rows sharing a uid where only the
newest was rewritten in place must abort the micro-compact naming the
newest row id, and where only an older duplicate moved the held
digest must stay current.
Review follow-up to greptile-apps' 2026-10-17 P1 on PR #124273.
---------
Co-authored-by: defurniture2025 <301948806+defurniture2025@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: teknium1 <127238744+teknium1@users.noreply.github.com>
Co-authored-by: Austin Pickett <pickett.austin@gmail.com>
Co-authored-by: Austin Pickett <austinpickett@users.noreply.github.com>
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
An elevated Hermes (install, `hermes update` as admin, a gateway started from an
admin prompt) creating a dir with mode=0o700 gets CPython's protected
SYSTEM + Administrators + OWNER RIGHTS DACL, owned by Administrators. The same
user's non-elevated Desktop/gateway/CLI then gets WinError 5 inside it (#139845).
- hermes_dir_acl.make_user_dir: Path.mkdir that, only when the process is
elevated on Windows, adds an inheriting full-control ACE for the token's user
SID to every dir it created and to an existing leaf (repairs a dir an earlier
elevated run left). No-op off Windows / unelevated. Routed through it: the
gateway lock dir (scoped token locks, host rendezvous, update host
obligation), bot mailbox, gateway.lock homes, pending_messages, media/attachment
roots, process logs, spill dirs, vault, outbox, backups, home skeleton and
mkdir_under_hermes_home (logs).
- W2: acquire_scoped_lock raises ScopedLockDirUnusable when this token may not
use gateway-locks (or read a stale lock in it), logged WARNING once per dir with
the repair (`icacls DIR /reset /t`). _acquire_platform_lock parks the adapter
as non-retryable `lock_dir_unusable` naming the dir and the fix, instead of a
raw PermissionError that Telegram retried forever.
- Builds on @KoNit-K's update-time ACL repair (#139870), which re-grants the
whole home after an elevated update.
No Windows host was available: the ACL behavior is covered by
tests/test_hermes_dir_acl_windows.py (Windows CI) and needs a live retest.
Refs #134889 (W8, W2)
Refs #139845
Refs #140337
Moving the writability preflight under the quarantine lock (previous commit)
meant a missing/zeroed state.db in a read-only directory under HERMES_HOME
failed creating state.db.quarantine.lock before the preflight could chmod the
directory back to writable. Check (and repair) the directory first: it never
vanishes mid-quarantine, so this unlocked check is race-free; the file and
sidecar checks stay under the lock. Found by Greptile on #140511.
Two openers starting on a zeroed state.db (gateway + CLI, or the
test_concurrent_quarantine_no_clobber threads) raced: the preflight ran
before quarantine_cross_process_lock, so the second opener could list
state.db via is_file() just before the first renamed it aside, then
os.access() on the vanished path returned False and the preflight raised
"state.db is not writable ... read-only for this user" for a perfectly
writable DB (outside HERMES_HOME the chmod repair never runs, so nothing
masked it). That flaked main CI.
On the absent/invalid-header path the preflight now runs inside the same
lock as the quarantine, so it only ever sees the settled file. The normal
(valid-header) path keeps the unlocked preflight and its actionable
message for genuinely read-only files.
Deterministic Event-gated test forces the CI interleaving: red on main,
green here. 200x loop of the real two-thread open: 8/600 failed on main,
0/600 with the fix.
The Desktop asks profiles.list of the selected bot over its one host-scoped
socket. Since the unified gateway, only that bot's row carried session fields:
every other served profile was listed by name alone, so on a fleet every row
but one showed a hollow draft dot and no age, although the same socket may
already open each of those bots' sessions.
Each served sibling a host-scoped connection routes to now carries the same
canonical_session / last_session, read from that sibling's own authority with
the connection's subject and capabilities. The sibling set is snapshotted on
the owner loop, and no connection is built for it. A profile-bound ticket, a
retiring sibling, a row listed under a name that routes to another profile,
and a sibling whose read fails for any reason stay metadata-only; a failing
sibling is warned once, not on every poll. The owner-or-operator rule applies
per profile.
Each row is read on one connection that never reopens a closed store
(SessionDB._read_ctx(reopen=False)), so a roster poll racing an unserve cannot
reopen a writer into a home being deleted. last_session skips hidden rows
again, as the pre-unified roster did, and the rows are reused while a
profile's store has not moved, on the signature the pre-unified roster cache
used (#117257), keyed by reader. The adopted-binding predicate from the
previous commit becomes one SQL predicate for both lookups.
AuthorityConnection.host_scoped names the gate _sibling_for applies.
Fixes#139227
Refs #134889 (RT-24), #139161
(cherry picked from commit 714da8acbcafc41a0e6ebce0e490eaf5ad0e72a0)
tui_gateway loses the five setup-profile onboarding.* handlers
(ensure_setup_profile, ensure_setup_session, record_failed_start,
mark_seen, reset_setup_profile) and their lock and helpers from
methods_onboarding.py, which keeps the new onboarding.state, set_run,
start and skip. session.start_chat goes with its handoff body
(methods_start_chat.py, start_chat.py), and the long-handler entries go
with them. hermes_state_tool_retries.py and its SessionDB mixin go with
their only caller; no schema change, and old rows that carry
display_metadata.retried stay inert. The per-turn retry note in
prompt_turn goes with them.
The old contract sections are removed and the shared contract is
regenerated.
(cherry picked from commit 1acd64a69c86f5547f0dcea62a689e67a48d0218, adapted)
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
Voice replies had to come from the session's main model, so a heavy model made every spoken
answer slow (#83894). A new auxiliary slot, voice_chat, picks the model for voice turns:
- CLI/TUI voice mode, the Desktop voice conversation (prompt.submit voice_turn) and messaging
voice notes mark the turn; agent/voice_turn_route.py binds the route after the prompt, row and
preflight compaction were settled against the main model and undoes it before memory sync and
background review, so the next typed turn and the review run on the main model.
- A turn larger than the voice model's compression threshold stays on the main model with a
one-time notice: switching to voice never compacts the conversation.
- Usage lands in session_model_usage under task voice_chat; it never rewrites the session's
recorded model/route, so resume keeps the model the user picked.
- Slot appears in Desktop Settings -> Models, the dashboard, and `hermes model`; GPT-Live
delegations keep using the session model.
Brings the onboarding branch up to main 0c2ff854a5. Where a Wave A PR
already landed a reviewed version of a piece of this branch (free tier
#134049, keyless web #134048, app resolver #134050, bundle and uninstall
#134051, catalog card and toolsets #134052, built-in tour #134054, stdin
guard #134055, retired key #126146), main's version wins. The PM long-path
files also take main's version: that work lands through #130430.
Kept from the branch on top of main:
- the setup and start_chat toolsets, declared with main's platforms key
(desktop only), and the setup_choose server request contract;
- the setup-profile marker file (.setup-profile.json) instead of the
profile.yaml role, as c3f85bc54f decided;
- the first-contact note's message argument beside main's internal flag;
- the setup-profile gate on the shared-metrics consent dialog;
- window sizing (window-growth) in place of chat-onboarding-window.
Desktop i18n follows main's per-section sibling files. The onboarding
strings go into them (modelMenu.localSetup, handoffTour.localTitle and
localText) and setupChoose/startChat stay in en.ts. guidedGreeting is
gone. The shared-metrics copy uses the branch's rewrite in English, with
the pre-opt-in sentence corrected for the fresh-install note
(d3674513c8); locales keep main's translations, with installId and
consentWindow folded into the new sending key.
The built-in tour reads local-model eligibility from the local-setup
offer store, the one place that rule lives on this branch. The gateway
contract and the onboarding skill docs pages are regenerated.
Resuming a dispatcher-spawned Kanban worker session from the ordinary
CLI, /resume, /sessions, oneshot or the Desktop gateway would create a
write-capable writer the board cannot observe (and unblocking the card
can dispatch a competing worker into the same workspace).
- hermes_cli/kanban_resume_guard.py: kanban_resume_refusal() refuses a
session whose Kanban ownership markers are present; fails OPEN only
on probe errors. HERMES_KANBAN_TASK (the dispatcher's own env)
exempts the legitimate dispatcher-driven resume.
- SessionDB.is_kanban_owned_session() probes the transcript for the
worker markers without loading history.
- Wired into: CLI --resume/-c (falls back to a fresh session id),
/resume + /sessions (keep current session, print refusal), oneshot
quiet resume, gateway session.resume (error code 4132).
- locales: cli.resume.kanban_owned in en + 16 languages.
- Two latent F811 redefinitions fixed in moved handler code.
Fixes#68779
hermes_state_messages.py grew past the 2000-line shape gate (2215) with
the repair-accounting stack. The coverage-resolution helpers are one
topic: naming which durable rows the compressor held
(_tail_rows_after_watermark, _resolve_carried_row_ids,
_matching_active_ids, _matching_retired_ids, _merged_user_run,
_proved_coverage, _uncounted_merged_rows, _tail_originals). Move them
verbatim into hermes_state_coverage.py as SessionCoverageMixin (the
hermes_state_rewind.py / SessionRewindMixin pattern) and add it to
SessionDB's bases next to SessionMessagesMixin. Callers reach them via
self, so nothing else changes; no re-export shims, and no test patches
these names on hermes_state_messages.
hermes_state_messages.py is now 1967 lines.
Gate quality findings (Low): hermes_state_pidns is stdlib-only (os, re,
sys, typing), so the function-local imports guarded no cycle — verified
with fresh-interpreter imports of hermes_state, hermes_state_common,
agent.conversation_compression and agent.turn_facade_lease. Import it at
module level. Compare the namespace stamp as the str it already is,
make recorded_namespace private (no external user), and replace the
STRICT/LEGACY explanations repeated at each call site with one-line
pointers to the hermes_state_pidns module docstring that owns them.
conversation_compression.py stays at its base line count.
A pid=<n> holder (compression lock, session turn lease, flock holder
record) is namespace-relative: process siblings sharing one state.db from
different PID namespaces (gateway + webui containers on one volume,
systemd PrivatePIDs=) see disjoint PID sets, so a sibling's live pid=
reads as absent to the namespace-blind probe and its unexpired row is
reclaimed under it. For a turn lease that ends the sibling's in-flight
turn ('another Hermes process took over this session'); for a compression
lock it splits the lineage; for a flock record it breaks a live lock.
Stamp every structured holder with the writer's PID-namespace identity
(/proc/self/ns/pid inode, via hermes_state_pidns) and qualify each probe:
* TTL-bounded rows (compression locks, turn leases): strict — a foreign
or unstamped holder is never probed, it defers to its own expiry (at
most the remaining TTL). A false defer self-heals at TTL; a false
reclaim loses a reply. Strictness also stops the steal during a
mixed-version rollout as soon as the reader restarts (the reader is
the long-lived side of a container pair that restarts at different
times), before every writer has restarted to stamp.
* No-expiry flock holder records: legal rollout — a foreign-namespace
record is never probed, while an unstamped one keeps main's behavior
(refusing to probe it would permanently disable orphaned-lock cleanup,
the #100108 path). Protection begins as writers restamp.
Probe doubt already defers for the same reason (a wrongly-kept lease
self-heals; a wrongly-stolen one does not), so this extends an existing
contract rather than adding a new one.
(cherry picked from commit 4b1a29f63b8e6dec0a2724b5c2c4fac2bcc31c0e)
Why: the user-facing refusal lived in a separate export_too_large_message()
helper while str(exc) still said "active messages" — a stale count wording
(the guard counts every stored row) that any new caller using str(exc)
would surface. Moving the text into the exception makes str(exc) the one
refusal and drops the facade-level helper; CLI and console now use str(exc).
Also name the session in the resume refusal's CLI escape hatch:
`hermes sessions export --format md --session-id <id>` — without
--session-id the md export writes every session, not the one too big to
resume.
`hermes sessions export` and the console's `sessions export` each
re-implemented the per-session max_export_messages loop and carried a
near-identical refusal string, so a wording or limit-resolution fix had to
land twice. SessionDB.assert_exports_safe resolves the limit once and
asserts each id; export_too_large_message is the single refusal text.
The CLI now resolves the limit before the bare-export search_sessions
scan, so `max_export_messages: 0` skips that scan entirely instead of
listing every session only to check nothing. The round-trip test now
asserts the refusal names the config key, and the export-guard docs say
the cap counts every stored message, not just active ones.
The resume refusal told users to run plain `hermes sessions export`, but
that JSON/JSONL backup is now capped per session by
sessions.max_export_messages and counts archived rows too — exactly the
huge sessions that hit the resume guard get refused again. Recommend the
two paths that do not materialize the backup in memory: the dashboard
Sessions page's streaming Export action and `--format md` (display
transcript, which skips the export guard).
Stamping DB_ROW_SNAPSHOT on every repair_alternation load also moved the
include_row_ids=True resume loaders (resume conversations, rewind, TUI
gateway, turn lease) onto the CAS-match rewrite path. That path writes
every owned column from the live dict, and replay never decodes
token_count, so a rewrite of a resumed row nulled the stored
token_count. Only the unaddressed live replay needs the digest (it is
the proof that recovers a lost _row_id), so stamp it only when
repair_alternation and not include_row_ids.
The token_count column stays in _CONVERSATION_ROW_COLUMNS: the digest
hashes every owned column of these rows, so the projection must stay a
superset of _OWNED_COLUMNS; the comment now states that contract.
Also index (session_id, message_uid) over active rows so the logical
identity lookup, which runs inside the write lock, is a SEARCH instead
of a full-session scan; tighten the twin test so a copied uid without a
snapshot is still not adopted.
* fix(setup): pills are the only question layout, no key letters on setup pickers, no System theme tile
The focused pill shows its detail as one line under the pills. Setup cards no
longer bind letter or digit shortcuts; arrows and Enter still work. clarify
cards keep their key badges.
* feat(setup): handoff card shows the sidebar title and retries a failed start_chat
The card title follows the new chat's sidebar row. A rejected start_chat shows
"Couldn't start that chat." with Retry, which runs the same request again
through the new session.start_chat RPC from the calling session.
* fix(setup): Retry on the handoff card is durable, told to the model, and offered only when it can help
- start_chat rejections say whether the same arguments can succeed (retryable); the card offers Retry only then,
only while the chat is idle, and not once a later start_chat in the chat started.
- session.start_chat takes the rejected call's tool_call_id and needs an explicit session: a started retry is
recorded on that tool row's display_metadata (the model's replayed row is unchanged), a second Retry returns it,
a reload shows it, and the next user turn tells the model once (the reactions pattern).
- A chat that started but could not open toasts "Couldn't open the chat", not "Couldn't start that chat."
- The theme card drops System whoever supplies its options.
- Question pills: the cursor follows focus and hover, pills with a detail carry a dot, the detail line has a title.
Provider tool-call ids repeat: Hermes mints deterministic call_<12hex> ids for identical calls and models
reuse ids, so tool_call_id cannot identify an occurrence. An assistant row now carries
messages.tool_call_uids, a {tool_call_id: uuid4} map for its tool_calls, and each tool-result row carries
the matching messages.tool_call_uid. The provider-facing tool_calls JSON is untouched, so row identity,
display identity and the CAS digest are unchanged and nothing nested reaches the wire.
Minted at the assistant row's first insert; paired onto the result in the same batch, from the live list
when the result is flushed later, or on restore from the preceding assistant row; copied by every clone
and re-insert; restored as the live _tool_call_uids / _tool_call_uid; stripped from provider requests.
(cherry picked from commit aa49c0f59788676d4beca288181711c558fca165)
A merge survivor's _absorbed_message_uids lived only in memory, so an engine that restarted after a
merge was back to parsing "\n\n" to learn which stored messages a composite user row contains. Store
the list in messages.absorbed_message_uids (an owned column: the survivor's row-addressed rewrite and
every re-insert carry it), restore it as the live key, and round-trip it through export/import.
(cherry picked from commit 0bc05f2656229b1010f330e1998684b04d5f963f)
The physical messages.id is re-issued by every copy (in-place compaction generations and their
concurrent-tail clones, rotation children, replace_messages), and _row_id is opt-in on restore, so a
context engine that keeps its own per-message state had nothing stable to key on across a restart or a
compaction boundary and re-identified rows by content and timestamp.
Add messages.message_uid (uuid4 hex), minted once at a row's first insert and stamped on the caller's
dict, copied by every SQL clone, kept by every re-insert of the same dict, left alone by row-addressed
rewrites, restored on every projection, and stripped from provider requests. A consecutive-user merge
survivor keeps its own uid and records the absorbed uids in _absorbed_message_uids. Schema v31 backfills
a uid onto rows that predate the column.
(cherry picked from commit 20d67ffb5e50e0ed956e56ddc7f8e28d36059e2e)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule
The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:
- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
names, restored dead definitions) and the three re-export stub modules
(gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
`plugins.allow_deprecated_imports` escape hatch
An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.
hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).
In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.
* chore: retrigger CI (zero-job startup_failure phantom)
* test: drop resolution allowlist rows for the two deleted which() sites
hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
Salvage of PR #99679 by 686f6c61, rebased onto current main.
/new and idle/daily resets keep parent_session_id for durable lineage,
and the sidebar's flattenSessionsWithBranches nested on that field
alone — so a platform's chats collapsed into one growing nested chain
of branches even though none of them were /branch forks. The backend
records the distinction on disk already (model_config._reset_from vs
_branched_from, gateway/session_recovery.py:433) but list payloads
strip model_config before any UI can read it.
- forkParentId(): nest only genuine forks — _branched_from wins, a
_reset_from parent means top-level sibling, legacy/optimistic rows
with only parent_session_id keep nesting.
- _session_row_dict lifts _reset_from/_branched_from out of
model_config so compact list rows (which strip that heavy field)
carry the distinction; tui_gateway project-tree rows project the two
markers too.
- Optimistic desktop /branch rows stamp _branched_from so the flat
render stays correct before the authoritative row arrives.
Disk lineage is unchanged. Tests: a _reset_from chain renders flat,
a genuine fork still nests beside a reset sharing the same parent,
and list_sessions_rich promotes both markers (also under
compact_rows=True).
Closes#99648.
- tools/browser_tool_install.py: keep pm-clean's frozen old-updater stub; main's
UTF-8 decode fix touched only the npx prefetch body it replaces.
- tests/hermes_cli/test_update_scoped_reconciliation.py: keep pm-clean's test
subset (catch-up rides the PM completion owner) and take main's gateway-less
host evidence (#120740): the updated seed that holds the host at a running
gateway, and the two gateway-less matrices for the source change that merged
cleanly into update_cmd_fleet.py.
The FTS fail-open detach now waits up to the caller's write budget (20 s /
60 s) for the write lock, so the one-time quarantine check before the loop
left a long window: a sibling that quarantined the file meanwhile still got
its triggers dropped and the stale breadcrumb committed on the quarantined
handle. Re-check the handle flag and the process-wide storage latch at the
top of every attempt, via the same _raise_if_db_corrupt(storage=True) that
_execute_write runs per attempt.
Classify the retryable lock error with is_sqlite_lock_error (result code
first) instead of a locked/busy substring match, matching #120488.
When a canonical write trips a corrupt FTS index, SessionDB detaches the derived
indexes (breadcrumb + trigger drop) and retries the write. The detach ran one
BEGIN IMMEDIATE on the writer connection, whose busy timeout is only 1 s, and gave
up on "database is locked" — so the canonical write escaped as "database disk
image is malformed". The usual lock holder is a sibling writer (gateway + TUI)
detaching the same index, so under load the second writer's turn was lost.
The detach now waits out lock contention on the caller's write budget with the
same jittered retry as _execute_write (default _WRITE_PATIENCE_S for the search
fail-open callers).
Repro: a second process takes BEGIN IMMEDIATE the instant the corruption error
surfaces and holds it 2.5 s. Base: append raises after 1.02 s (3/3). Fixed: the
row lands after the holder releases, FTS detached (3/3). Found by the E2E sqlite
torture chamber (fts_corruption_fail_open) at load ~200.
Conflict resolutions and semantic fixups:
- utils.py / hermes_yaml.py: main widened ruamel's round-trip emitter so a long
double-quoted scalar is never folded after an escaped backslash. pm-clean builds
every rt emitter through hermes_yaml.roundtrip_yaml(), so the width lives there
(ROUNDTRIP_YAML_WIDTH moves with it); xai_retirement imports it from hermes_yaml.
- hermes_cli/banner.py: keep pm-clean's removal of the banner update check. Main's
GIT_NO_LAZY_FETCH fix for it applies to its replacement, source_check: every
read-only probe (source_git_env) now refuses promisor lazy fetches, and the
partial-clone test targets that probe (red without the flag).
- .github/workflows/tests.yml: keep setup-pm; main's uv pin bump does not apply.
Main's WAL-capable SQLite gates are kept, run against $HERMES_PYTHON (the
PM-pinned interpreter, SQLite 3.53.1). The e2e step takes main's
--include-integration invocation.
- apps/desktop: package.json has no build block here, so main's macOS locale-marker
restore joins the darwin branch of the existing after-pack.mjs, and its test
loads the hook from electron-builder.config.cjs and imports PlatformPackager
from app-builder-lib's root (electron-builder 27 exports no ./out paths). The
win32 row is dropped: this hook sanitizes and signs PE trees on win32 by design.
- reconciliation.ts: main's rowId hydration (#119326) was merged into the first of
pm-clean's split helpers only; the resolver is now one helper both halves use.
- en.ts: both sides' keys kept. tests/tools/test_lazy_deps.py stays deleted.
- Tests main added with `import yaml` use hermes_yaml, like the rest of the tree.
The session tools pin (sessions.tool_names) stored names only, so every fresh
process re-materialized the bytes from its own surface and every surface hop
of one durable session was a full prompt-cache miss:
* tool_search's deferred catalog is built per process ("Search 6 additional
tools" in the TUI gateway vs 5 in -q);
* a pinned tool missing from the fresh build (skill_manage under the -q
footprint) came back from the static registry schema, without its
dynamic_schema_overrides;
* a -q --resume that rebuilt the stored prompt (model switch, cwd drift)
persisted its own pruned array over the pin.
The pin now stores the full definitions and restore replays a pinned tool that
is still available byte-for-byte (deregistered tools drop, new ones append at
the tail, legacy name-only pins still work). A continuing session whose prompt
is rebuilt applies the pin before building it, matching the freeze policy
(tools[] only changes on /new, /reload-mcp, compaction). The array is
content-addressed in the existing system_prompts store like the prompt itself,
so identical arrays across sessions are stored once; get_session resolves it.
After #120386 raised the read-only busy timeout to 5 s, retrying a lock
inside _open_read_only multiplied the wait to ~20 s on blocking callers
(TUI profile loop, exit epilogue, hermes status). The connection already
waited the read budget; only transient disk-I/O errors are retried now.
Probe (30 s exclusive DELETE-mode lock): 20.17 s -> 5.0 s, still
classified as a transient lock.
In rollback-journal (DELETE) mode a sibling process can take the write lock
between schema load and the messages_fts probe. FTS5's xConnect then fails its
%_config read and SQLite reports SQLITE_BUSY with the text "vtable constructor
failed: messages_fts". Every state.db lock classifier matched on the words
"locked"/"busy", so:
- a writable SessionDB() failed after 1s instead of waiting out the lock with
_WRITE_PATIENCE_S, and callers disabled persistence for the run;
- a read-only open (dashboard, `hermes sessions list`, cross-profile readers)
failed on the first busy timeout with no retry at all;
- the error read as not transient (dashboard 500, not 503) and as persistence
cause "unknown" instead of "locked".
Add hermes_state_errors.is_sqlite_lock_error: SQLITE_BUSY/SQLITE_LOCKED by
result code when SQLite supplies one, text only when it does not (our own
re-raised messages, RPC-wrapped strings). Route the writer open patience loop,
the _execute_write retry, the reconcile re-raise, the WAL->DELETE flip, the
maintenance holder probe, is_transient_sqlite_error and
classify_persistence_error through it. The read-only open retries a lock
inside its existing bounded retry budget, next to the transient IOERR case.
Under rollback-journal (DELETE) mode a reader needs a SHARED lock, and
every commit from another process blocks it across its journal+db fsyncs.
Read-only SessionDB handles were opened with a 1 s busy timeout, and
writer handles serve DELETE-mode reads on the writer connection, whose
1 s timeout exists for writes (they retry at application level). Under a
busy gateway, readers gave up after 1 s:
- dashboard GET /api/sessions -> 503 "Session store is busy", or 500 when
the lock surfaced through the FTS5 vtable constructor during the
read-only open probe;
- `hermes sessions list` -> "Could not open your session history
database. Run: hermes sessions repair" (a healthy store) or a raw
`database is locked` traceback;
- in-process reads on a gateway/CLI writer handle -> `database is locked`.
Reads now get the same 5 s SQLite busy budget the WAL read pool already
used (_READ_BUSY_TIMEOUT_S): read-only handles are opened with it, and a
DELETE-mode read on the writer connection raises busy_timeout for the
read and restores it after, so writes keep their short timeout and the
jittered application-level retry.
* fix(state): publish structural state.db corruption as one profile-level state
A structurally corrupt state.db showed up differently on every surface: the
sidebar endpoint returned 200 with empty slices plus an errors row, /api/sessions
returned 500, /api/status said components.storage ok and readiness was green.
None of them said the store was damaged, so Desktop rendered it as deleted
history (#72046).
hermes_state_health is now the single latch, keyed by resolved state.db path:
- SessionDB._halt_db_corrupt, the SessionDB read helpers, the web profile
reader and the readiness probe publish into it, only for structural
corruption (not FTS-scoped damage, not the malformed-schema case the web
open path heals).
- gateway.readiness reports it (state_db degraded/corrupt, and session_store
unavailable/corrupt even when the handle cache says ok), which also feeds
/api/status components.storage (now with reason: corrupt).
- /api/sessions, /api/profiles/sessions and /api/profiles/sessions/sidebar
carry storage: {profile: "corrupt"}; /api/sessions returns 503
state_db_corrupt instead of 500.
- A peer SessionDB handle in the same process refuses writes on a latched
path with the existing StateDbCorruptError, so gateway/agent transcript
diversion and classify_persistence_error keep working unchanged.
The latch never clears on its own and resets on restart, the recovery boundary
StateDbCorruptError already documents.
Co-authored-by: konsisumer <konsisumer@users.noreply.github.com>
* fix(desktop): say the session store is damaged instead of an empty sidebar
The sidebar reads the list endpoints' new storage map into
$corruptSessionStores and renders a persistent destructive Alert above the
session list naming the affected profile(s). The copy says missing chats were
not deleted and points at the non-destructive path (quit Hermes, then
`hermes sessions recover --source <state.db> --inspect-only` or restore a
snapshot) plus the recovery guide; it does not recommend `sessions repair`
for structural damage.
Co-authored-by: konsisumer <konsisumer@users.noreply.github.com>
---------
Co-authored-by: konsisumer <konsisumer@users.noreply.github.com>
Branch semantics kept where main and PM disagree: update_cmd_deps.py,
constraints-termux.txt, the Electron update-api-check module and the
post-swap hand-off test stay deleted; the pending-fleet-restart catch-up
and the local_runtime tag/download ladder stay retired (PM owns engines).
Ported from main onto the branch's shape: profile_scoped_chore for the
auto-archive and plugin-update housekeeping chores, the local-runtime
cross-process boot lock and residency cap, the checkpoint tmp_pack sweep,
the cua daemon-liveness status probe, the remote-served Desktop update
flag (posix.sh / windows.ps1), sign-in for env-pinned remote gateways
(urlDisabled on RemoteSetupFields), the uvloop extra split (uvicorn
without [standard]), and the umask-scoping spawn test.
uv.lock regenerated with pm.build_env --lock-only; new utf-8 reads from
main switched to utf-8-sig (check-windows-footguns).
closes#116244
serialize _raise_if_db_replaced inside self._lock and handle reopen after close across optimize_fts, rebuild_fts, vacuum, _enter_fts_fail_open, and _execute_write error branch so a clean close never falsely poisons handles with deletedwalgenerationerror.
"database is locked (another Hermes process held the state.db write lock for
over 60s)" identified the victim only. The open-descriptor scan cannot single
out the writer because every Hermes process (gateway, CLI sessions, worktree
agents, cron) has the DB open, so an operator hit repeatedly by
session_persistence_failed:locked had nothing to act on.
SQLite's unix VFS takes fcntl byte-range locks whose offset encodes the lock
kind (state.db-shm byte 120 = WAL write, 121 = checkpoint; the pending-byte page
on state.db = PENDING/RESERVED), and the kernel exports them with the owning pid
in /proc/locks. hermes_state_lockowners reads that table at the moment the
patience budget runs out and logs one WARNING per write-class holder with
describe_holder_pid()'s argv summary, for both the transcript write path and
open+init lock patience. The holder stays out of the exception text on purpose:
classify_persistence_error() buckets by phrase and a holder argv such as a
worktree named fix-corrupt-db would flip the bucket.
Docs: the Write Contention section still described attempt-counted retries
(_WRITE_MAX_RETRIES = 15); updated to the time budgets in force and the new log line.
The per-profile store model (#88734), the parent-inheritance fence (#88381),
profile-stamped topic rows (#76423) and profile-prefixed voice keys (#75198)
are all forward-only: they put NEW state under the right profile and refuse to
widen existing damage, but nothing walks the stores and settles what earlier
releases left crossed. #113884 found 246 sessions stranded that way and could
only warn.
`hermes sessions repair-profiles` scans every profile's state.db plus the
gateway's voice-mode and sessions.json files and names six kinds of crossing:
1. `profile_name` disagreeing with the row's own session key -> relabel;
2. rows physically in another profile's store -> move (all message
generations, usage rows, system prompt) to the owning store, parents before
children so lineage survives, copy-then-delete so a crash leaves a duplicate
the next run settles;
3. `parent_session_id` crossing namespaces -> sever (own identity kept);
4. routing rows outside the default store under multiplexing -> move (an
existing row wins); routing rows for a profile that no longer exists -> drop;
5. Telegram topic bindings and voice-mode entries missing their bot's profile
-> relabel from the sessions that hold the chat (ambiguous chats reported);
6. sessions.json mirror entries for an unclaimed namespace -> drop (the legacy
import re-injects them into routing every boot).
Report-only by default. `--apply` refuses while a gateway owns any store, takes
a quick snapshot of every store first, and is idempotent. Two cases are
reported but never guessed: rows keyed to a profile that does not exist, and
`agent:main` rows inside a named profile's store (`--legacy-main rekey|move`
says which of the two histories they are).
Storage side lives in `hermes_state_profile_repair.py` (SessionDB mixin);
orchestration across stores in `hermes_cli/sessions_repair_profiles.py`; the
CLI face in `hermes_cli/sessions_cmd_repair_profiles.py` (pre-DB handler: it
opens every store itself).
Part of #88715 (PR-6). Closes the remediation gap #113884 only warns about.
_PathReadBudget.unregister() discards from a WeakSet, so close() can call it
unconditionally; a handle whose constructor raised was never registered and the
call is a no-op. Same fix as PR #113857, filed independently.
Co-authored-by: ClintonEmok <54935030+ClintonEmok@users.noreply.github.com>