tools/ holds model tools. These six files register none: they snapshot and
restore a working directory for the agent loop, /rollback, /undo's
changed-files line and `hermes checkpoints`. They move next to the agent
loop that takes the checkpoints:
tools/checkpoint_manager.py -> agent/checkpoints/manager.py
tools/checkpoint_maintenance.py -> agent/checkpoints/maintenance.py
tools/checkpoint_pruning.py -> agent/checkpoints/pruning.py
tools/checkpoint_refs.py -> agent/checkpoints/refs.py
tools/checkpoint_undo_hint.py -> agent/checkpoints/undo_hint.py
tools/checkpoint_manager_profile_rename.py -> agent/checkpoints/manager_profile_rename.py
agent/checkpoints/__init__.py is a docstring only. Nine test files move to
tests/agent/checkpoints/. Every importer changes its import line in place,
inside the same function. Nothing stays at the old paths: none of the six
names is on the plugin API list, the shipped-release list or the
old-updater list.
Behaviour is unchanged. The four loggers keep their tools.checkpoint_*
names, so the lines stay under `hermes logs --component tools`. The folder
is not a root checkpoints/ package because the checkpoint store is
HERMES_HOME/checkpoints, which is the same directory as such a package on an
install whose checkout root is HERMES_HOME. agent.* is already packaged, so
pyproject.toml and the lists of root packages do not change.
The import and docs rewrites were made by scripts/move/rewrite_imports.py
and rewrite_docs.py.
Five review rounds each found a new way the printed `/rollback <hash>` could name the wrong
checkpoint (another chat's take in the same second, pruning rewriting hashes, files safe restore
skips). An exact command cannot be proven without a per-turn identity on every surface, so the
line no longer names one:
↶ Files changed in the undone turns: app.js, notes.md. Run /rollback to see checkpoints and restore them.
The list is best effort ("changed", never "will be restored"): the working tree diffed against the
newest retained snapshot at or before the span start (else the oldest), through the existing
no-write throwaway index, printed only when a snapshot was taken in the span.
Removed: tools/checkpoint_takes.py (the take ledger), the turn-key bind in agent/turn_context.py,
the CheckpointManager hooks that fed it, unique/stored turn keys, `undo_turn` and `first_turn`
plumbing, the `ref`/`more` fields of UndoRollbackHint (contracts regenerated), the `restore` locale
key, and the take/turn-key/collision/hash-target tests.
Kept: hash acceptance on every /rollback (tools/checkpoint_refs.py), the sidecar rollback profile
scope, and the kept-turn fix, which now orders by the checkpoint's git second (a turn in that same
second is kept).
Round-3 review P1: turn_key is the user row's stamp, and platform event times
(Telegram message.date) are whole seconds. Two same-second turns shared a key,
so a first undone turn that took nothing was credited with the next turn's
take and the printed /rollback restored a state already holding its edits.
Detect and refuse, on every surface:
- bind time: a key the manager already bound for an earlier turn binds "",
so the later turn's takes prove no turn;
- hint time: unique_turn_key / stored_turn_key return "" when more than one
user row the surface knows maps to the first undone turn's key (CLI and TUI
sidecar: the pre-undo history; owner rollback.list and messaging /undo: the
stored lineage, rewound rows included).
Round-2 review F1: a first undone turn whose checkpoint attempt met a busy
store lock (never waited for) or that edited through a tool taking no
checkpoint left no take, so the hint picked the NEXT turn's take, which
already holds the first turn's edits; pasting it restored the wrong state.
Each take row now carries the turn that made it (its user row's stamp,
bound at turn start in agent/turn_context.py), and the hint names a hash
only when the span's first take belongs to the first undone user row.
A busy or failed attempt is noted as unrecorded so the record is visibly
incomplete. The lock stays non-blocking. The first-take had-history git log
now runs only for a project's first recorded take.
/undo only rewinds the conversation and never touches files. With checkpoints
on, the snapshot taken before an undone turn's first write is still in the
store, but nothing told the user it was there or which /rollback number
restores it.
/undo now adds one read-only line after its normal output when checkpoints
are on and a checkpoint was taken during the undone span: the files changed
since that checkpoint (first 8, then "+N more") and the exact /rollback N.
N is the 1-based position in list_checkpoints(cwd), the list every surface's
/rollback indexes. /undo N uses the oldest checkpoint in the span. The span
starts at the undone user message's stamp, or the newest kept message's
when later (a gateway stamps platform send time). A checkpoint in the same
second as that start, or a span reaching the oldest retained checkpoint of a
full list, drops the number and says to run /rollback to list them.
One shared helper, tools/checkpoint_undo_hint.py, does one git log plus one
name-only diff (the same staging /rollback diff uses). Nothing is written.
Checkpoints off: no extra work and output identical to main.
Surfaces: classic CLI (in-process and gateway-backed), messaging gateway,
TUI sidecar (session.undo + command.dispatch), the shared owner's
rollback.list (new optional undo_since param, undo_hint result) which the
canonical Ink TUI, the gateway CLI view, ACP and Desktop call after their
rewind. Contracts regenerated.
Greptile #149708 P1 4486245746 / P2 4486245713 / P2 4486245788.
- 746: retain_refused_turn_for_display now accepts the refused run's original durable
boundary row and rewinds from it, instead of guessing the newest user turn. The newest
turn is wrong when a mid-turn redirect appended a later user row (dropping only the
redirect left the original ask + tool rounds live, re-tripping the filter) or when the
refused input was a hidden/internal, non-user-originated row (-1 dropped a prior accepted
turn). Falls back to the newest turn when no boundary is supplied.
- 713: the model-side soft-delete and the display re-surface now run in ONE _execute_write
(rewind_in_transaction + the display tag before commit), so a crash can't drop the user's
message from both views (no half-applied retention).
- 788: a refused ask embedded in a compaction carrier keeps its content_refused tag through
project_compaction_message_for_display and the REST view unwrap, so a reopened chat still
renders the greyed refused block instead of a plain user bubble.
Replace the durable ERASE of a content-policy-refused turn with a RETAIN-for-display:
the whole refused turn (user row + any tool rounds + the refusal) still leaves the
MODEL's context exactly as /undo does — so the deterministic safety filter can't
re-trip and lock the chat — but the user's own message now STAYS VISIBLE in the chat
surfaces as a greyed "refused, try a different query" block that survives a close+reopen.
Teknium's directive: wipe the refused turn forward out of the model conversation, but
keep showing it in the surfaces (Desktop primary, then CLI/TUI), collapsing the raw tool
actions + refusal detail into a short notice.
Mechanism (verified via the store's own model vs display reads): the refused turn head
(the user row) is kept in the DISPLAY projection as active=0, compacted=1 — the same way
compaction-archived rows stay visible — and tagged display_kind='content_refused' with a
stored CONTENT_REFUSED_NOTICE; the tool rounds + refusal stay soft-deleted (removed) so
only one greyed notice renders. The model read is active=1, so it sees none of it.
- agent/turn_failure_copy.py: CONTENT_REFUSED_DISPLAY_KIND / _NOTICE / _METADATA_KEY.
- hermes_state_rewind.py: SessionDB.retain_refused_turn_for_display (reuses the /undo
rewind for the model side, then re-surfaces + tags the user row); the owner helper
retain_refused_turn_for_display replaces erase_refused_turn_from_transcript.
- gateway/session_transcript.py + run_turn_persistence.py: async-store retain + owner call.
- hermes_cli/cli_chat_turn_mixin.py, acp_adapter/server.py: call the retain helper.
Tests (red on base — base full-rewind drops the ask from the display read): the refused
turn leaves the model but stays in the display tagged content_refused, survives a
simulated reopen, and the best-effort no-ops. Existing ACP + gateway model-exclusion
tests stay green (active-only reads unchanged).
is_row_rejection treated every sqlite3.InterfaceError as a bad row, but SessionDB retries InterfaceError('no more rows available') as WAL contention and re-raises it once its patience runs out, so a valid row could be moved out of replay for good. Among sqlite errors only a 'binding parameter' message now counts; OverflowError does too. _bindable_text also passed ints outside sqlite's 64-bit range, which raise OverflowError even for a TEXT column and stalled the session the same way a dict did; they are now stored as text.
transcript_append_kwargs passed tool_call_id, tool_name, role, reasoning and platform_message_id to sqlite as they were, so a spooled dict or list in one of them failed to bind on every replay. With live writes now waiting behind a failing spool, that one row stopped the whole session persisting, across restarts too. Those fields are now made bindable, and a row the database still rejects on its own values is moved to *.json.bad and logged once instead of holding the session back, both at boot and in the live drain.
Also from the same review: the live drain and the restart pass share one sort key (_spool_sort_key), so a string or NaN ts no longer raises in the live drain; boot recovery returns the sessions it held back and the store marks them under its lock (mark_spooled_drop_sessions) instead of handing out its set; _recover_pending_flushes moves out of gateway/run.py as shutdown_flush.recover_gateway_pending; the transcript_append_kwargs import sits outside the try; blocked_sessions is required; the agent-history reason is a constant; the recovery tests share one store fixture and compare replayed rows with the live writer's.
Review findings by @kshitijk4poor.
Gating the live write on a pending spool raised a generic RuntimeError, hiding the replay's real failure from the FTS-rebuild, replaced-database and compression handlers, so a repairable FTS fault became a permanent stall. _drain_spooled_drops now returns the replay's own exception, the caller raises it, and after a successful FTS rebuild the loop drains the older spool again before writing the live row.
Found in independent review.
The live writer replayed a session's spool before each write but ignored a failed replay and wrote the new row anyway, so a second failure (boot hold-back, then the pre-write drain) gave the live row a lower row id than the older spooled rows. _drain_spooled_drops now reports files left on disk, and the write takes the existing retry path instead, leaving the row queued in memory behind them.
Review finding by @ehz0ah.
recover_pending_to_db held back a session's later spool files after a failed replay, but never told the running gateway. The live writer drains the spool only for sessions in SessionStore._spooled_drop_sessions, which only this process's own spooling filled, so the session's next live row landed ahead of the held-back files until the next restart.
recover_pending_to_db now adds the sessions it held back to a caller-supplied set, and _recover_pending_flushes passes the store's own drain set (exposed as spooled_drop_sessions()), so the next live write replays them first.
Found in review by @BearHuddleston.
Review follow-ups (teknium1):
- One kwargs builder, two callers. transcript_append_kwargs() in
gateway/session_transcript.py builds the append_message kwargs, and both
_append_transcript_message and the spool's restart replay call it, so the
restart writer cannot lag the live writer again (display_kind and
display_metadata were added after #84785 was written). fallback_ts applies
only to a message with no timestamp; the live writer passes none, so its
rows are byte-identical.
- A failed replay says what it held back: one INFO line per pass with the
file count per blocked session, so a spool dir that never empties has a
reason in the log.
- seq is per process and ts has one-second resolution; the sort key now
says so where it reads seq.
- Tests fold to three invariants: drop order beats name order (seq breaks a
same-second tie), a replayed row is the row the live writer writes, and a
failed replay holds back that session's later messages only. The two that
already passed on main (a corrupt file is kept; the payload-clock
fallback) are dropped; the fallback is asserted inside the fidelity test.
(cherry picked from commit e2bacb06b3311b00aa354ffce7d53fc15ba44d04)
Gate reuse + quality (BS02 r1, Low, convergent): hygiene (run_turn.py) and
manual /compress (slash_commands_session.py) each inlined the same
"published child? else rewrite" decision with different control flow, plus a
temp flag (_hyg_new_sid_persisted) and two 5-6 line comments restating the
probe docstring. SessionTranscriptMixin now owns the decision; both sites
branch on its bool (AsyncSessionStore proxies mixin methods, no facade change).
Call-site comments shrink to one line and the docstring drops the "used to"
history. No behaviour change.
Gate 2c (BS02 r1, Medium): is_published_compression_child looked the child up
via _db_for_session_id(child). At both call sites the child id is not in the
routing index yet (the repoint happens after the probe) and has no owner hint,
so under multiplex_profiles the lookup fell back to the routing-home state.db.
For a named-profile chat the child lives in profiles/<name>/state.db, the probe
returned False, and the old wrong-store rewrite ran again: the false "failed to
persist compressed transcript" and the foreign-tail DELETE stayed unfixed.
The parent is indexed and was ended in the same publish transaction, so its
store is the child's store. The rotated /compress test gains a multiplexed
named-profile row (red before this change, green after).
Rotation already writes the compressed child (handoff + cloned foreign-tail
rows) atomically via publish_compression_child(); the follow-up
rewrite_transcript(active_only=False) was redundant and destructive, and any
DB hiccup in it surfaced as a hard /compress failure over an already-committed
compression. Add a fail-open is_published_compression_child() probe on
SessionStore; /compress and hygiene skip the second rewrite when the durable
child is verified, otherwise the original guard runs unchanged.
Regression tests cover the main/sean session shapes plus the fail-open
fallback; patch applies cleanly on origin/main.
(cherry picked from commit 7e023fae829d57e153ef77f7796fd7ce7831af51)
Once a stalled session's backlog is spooled (#114266), the order-preserving
replay attempt before each write hit the still-dead DB and logged a
gateway.shutdown_flush 'Replay of spooled transcript message ... failed'
WARNING per append, on top of the per-append ERROR escalation that already
reports the outage. When the session already has recorded append failures the
replay failure is expected and now logs at DEBUG; the first drain (no recorded
failure yet) still warns, and a recovered DB still replays the spool in order.
A SessionStore whose state.db is unavailable (_db is None) early-returned from
append_to_transcript: no failure counter, no log, and the turn was gone. The
missing store now flows through the same serialized path (RuntimeError
'no owning session store ... deferring' is counted), so the WARNING->ERROR
escalation covers the reporter's outage shape.
Once a session hits the escalation threshold its in-memory backlog is moved to
the on-disk pending spool (recover_pending_to_db replays it at boot) instead of
sitting in memory until the 200-message cap or a crash. The spool is drained
BEFORE the next live write so recovery preserves transcript order.
Part of the 'best-effort durable write' atom of #114266.
Addresses review finding on PR #114301: _rebuild_fts_once was stamping
_fts_rebuild_last_attempt_at before the 'db is None or no rebuild_fts'
early-return guard, so a call with no usable DB burned the 5-minute
cooldown window without attempting anything. Move the stamp below the
guard so only real rebuild attempts start the cooldown.
Adds a regression test covering: no DB, DB without rebuild_fts, and the
follow-up real attempt succeeding immediately once a usable DB appears
(not blocked by a phantom cooldown). Full gateway/test_session.py suite:
67 passed.
When the session FTS (full-text search) index rebuild fails, the
gateway previously entered a cooldown and then permanently stopped
retrying once the cooldown expired, leaving search silently broken
for the rest of the process lifetime. This adds a proper retry after
the cooldown window elapses, and escalates to ERROR-level logging
(previously missing 'import logging' meant this path could not even
log the failure) so repeated rebuild failures are visible to
operators instead of being swallowed.
Related but out of scope: while testing the fallback paths we
observed that the JSONL transcript fallback writer can write zero
bytes when the primary DB write path fails partway through - flagging
this for maintainers as a separate follow-up, not fixed here.
Fixes#114266
CLI `_rewind_persisted_user_turn`, TUI `_rewind_active_session_history` and gateway
`rewind_session` each re-ran get_active_message_ids -> get_messages_as_conversation ->
split_user_originated_turn -> rewind_to_message with their own warm/durable comparison
helpers and three different out-of-range contracts (RuntimeError / ValueError / None).
The durable transcript is the authority for a rewind, so the implementation now lives
with the data: `SessionDB.rewind_user_turn` (hermes_state_rewind.py) with one typed
out-of-range error (`RewindTargetUnavailableError`). Surfaces keep only lock, eviction
and rendering glue and map that error to their own message.
Review findings on the salvage (all reproduced with a real SessionStore):
1. Primary persisted-agent path skipped the boundary. The agent's turn-start
flush already persists the user row stamped with the inbound platform id, so
`has_platform_message_id` saw THIS turn's own row, took the "duplicate" branch
and skipped the whole block — including the new assistant boundary. The
transcript stayed `[..., 'user']`, exactly the open tail #107070 is about.
Fresh sessions hid it a second way: `session_meta` is appended after the
agent-flushed user row, so a naive "newest row" tail read sees `session_meta`.
2. The exception fallback appended the boundary unconditionally; a redelivery of
an already-closed turn produced `['user', 'assistant', 'assistant']`.
3. The exception fallback wrote the user row + boundary before classifying a
400/500-on-long-session as overflow, growing a session that is already too
large (the #1630 no-grow rule the persist path honours).
Fix: `SessionDB.latest_conversation_role()` (newest active row excluding the
`session_meta`/`system` bookkeeping rows the model never sees) behind
`SessionStore.transcript_tail_role()`, which resolves the same route
`load_transcript` reads via the existing `_compression_tip_for_session_id`.
One `_hmwa_close_failed_turn()` appends the boundary iff that tail is an open
user row; both the persist path and the exception fallback call it, so the
user-row dedupe no longer gates the boundary and a redelivery never stacks.
The overflow verdict in `_hmwa_agent_error_reply` is an early return ahead of
every transcript write. The `failed_turn_notice` kwarg and its dead
`or _hmwa_failed_turn_notice(...)` fallback are gone; the notice is derived
where each consumer needs it.
Tests (each red with the production change reverted, green here): boundary
keyed on the durable tail with the user write deduped (agent-flushed row →
closed; redelivery → nothing); fresh-session agent-flushed failed first turn
closed despite `session_meta` (real store); exception-path redelivery adds no
second boundary (real store, every lineage location, contract asserted from
store state); exception-path overflow persists nothing. Live E2E:
`evals/gateway_failure_ownership/probe.py` (real AIAgent + fixture provider)
20/20; the two `failed provider input` turns that previously left an open user
tail now close with the "not processed" row.
Namespace delivery markers and assign fresh keyless turn identities instead
of inferring ownership from IDs or process-local row baselines. Query only
marker existence on the canonical live compression continuation and ancestors.
Preserve raw reply IDs and exclude metadata from provider wire messages.
Expand the two existing invariants with resumed cross-chat ID collisions,
a real independent SQLite writer, reaped siblings, and archived-history
allocation controls. All 20 full-handler checkpoints and 63 targeted tests pass.
hermes_state.py: delete every '# noqa: F401 (re-exported...)' import block (hermes_state_common/errors/guard/
readpool/sessions/fts/dbfile/wal/repair/registry + agent.context_compressor _DB_PERSISTED_MARKER_KEY); keep
only the names hermes_state.py itself uses, without noqa.
hermes_state_registry.py: drop get_shared_session_db/release_shared_session_db/close_shared_session_dbs
aliases; every caller (gateway/, tools/, tui_gateway/, cron/, mcp_serve, run_agent, tests) now imports
acquire/release/close_all/release_or_close from hermes_state_registry.
hermes_state_titles.py: drop set_auto_title_if_empty shim (title_generator keeps its getattr fallback).
Re-remove shim-only names restored by 34abf954bd: latest_user_message_row_id (tests call
latest_message_row_id(key, role='user'); role-targeting assertions kept) and get_session_activity (tests
build the snapshot via agent.session_activity.build_activity_snapshot over db.get_session(sid)).
hermes_state_wal._log_once resolves its dedupe sets as module globals instead of via hermes_state;
hermes_state_repair helpers call module globals directly (tests patch hermes_state_repair.<name>).
Frozen updater surface untouched (update_cmd_maint imports only SessionDB from hermes_state).
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.