With compression.in_place: false a rotation creates a child whose
model_config did not carry prompt_refresh_epoch, so after any past
profile-wide refresh-prompts request the child looked stale and rebuilt its
prompt (an extra prefix-cache break) on the first restore after eviction or
restart. Carry the key as conversation-wide state.
--session with a compressed conversation's original id wrote the request
for the ended root, which the live tip never reads: the CLI reported
success and nothing refreshed. Resolve to the compression tip first.
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.
The Windows CRT reports isatty() True for the NUL device, so
`hermes sessions delete s-old < NUL` read EOF as a Ctrl-D decline and
exited 0. EOF counts as a terminal decline only when the console API
confirms a real console (the gateway_windows check from #113977); else
it is nobody-could-answer and exits 1. A real stdin=DEVNULL child test
runs on every OS lane.
Independent review round:
- EOF at the prompt meant "nobody could answer" even on a real TTY,
so Ctrl-D printed the non-interactive --yes hint and exited 1. At a
terminal it is a decline again ("Cancelled.", exit 0, as on main);
/dev/null and empty pipes still exit 1.
- sessions export refusing a session over sessions.max_export_messages
printed an error and exited 0. It exits 1 on all three selection
paths. The backup round-trip test never asserted the exit code (its
helper serves the success legs too); its refusal leg now expects
SystemExit(1) alongside the existing assertions.
The shared prompt turned KeyboardInterrupt into a decline, so
`hermes sessions optimize-storage && next` ran `next` after the user
interrupted (main's inline optimize-storage prompt let Ctrl-C through).
An interrupt now says nothing was changed and exits 130 at every
sessions confirmation; an explicit "n" still exits 0.
Every `hermes sessions` confirmation (delete, prune, prune --never-active,
archive, optimize-storage, repair-routing --apply, repair-prompts --apply,
repair-profiles --apply) read EOF on a non-interactive stdin as "no",
printed "Cancelled." and exited 0. Run from cron, a wrapper or a
backgrounded shell, `hermes sessions optimize-storage` stopped at its
Proceed prompt, touched nothing and reported success (#123322 comment).
_confirm_prompt now returns None when no answer can be read, and the new
_confirm_or_exit_code turns that into exit 1 with "No answer on a
non-interactive stdin; nothing was changed. Pass --yes to run it
unattended." (--json for repair-prompts; repair-routing has no unattended
form). An explicit "n" still exits 0 as before; optimize-storage's inline
input() now goes through the same helper.
_cmd_export printed its usage errors, refusals (bulk export without a filter, --delete-after-verified without --yes or --session-id), not-found ids and failed verified deletes, then returned None, so hermes sessions export still exited 0 when it did nothing. Every such path now returns 1, as prune, archive, repair and optimize do; a --dry-run preview still exits 0.
Ported from #90970, which covers the same paths but targets the pre-split sessions_cmd.py.
Co-authored-by: pierrenode <298902573+pierrenode@users.noreply.github.com>
`hermes sessions repair` printed "Repair failed" and exited 0, so a
`hermes sessions repair && hermes gateway start` chain or a cron health
wrapper read a store that is still unopenable as fixed. `sessions optimize`
and `optimize-storage` did the same when VACUUM or the index rebuild failed,
when the disk preflight refused, or when FTS5 was unavailable, and
`sessions archive` with no filter and `prune --never-active` with an
unparsable --older-than refused the action but still exited 0.
aca40d1d63 moved delete/rename/prune/import to `return 1` and #103321 did
repair --check-only; these are the remaining maintenance paths that print a
failure and fall through to a bare return, which the dispatcher maps to 0.
From an independent re-review of the mid-run pacing change:
- The pre-backfill message count walked the messages table by rowid
range: 73 s cold on a 1.97M-message store with nothing printed, the
symptom this PR fixes. +id lets the planner count from a covering
index (1.9 s cold).
- A writer that appeared mid-run was still locked out by the
minutes-long VACUUM. VACUUM is skipped while another process holds
the store (vacuumed=False, vacuum_skipped=in_use) with a message to
re-run when it is closed.
- The "Not enough free disk" refusal exits 1, like the other failures.
Review round (@yoniebans) on #144630:
- Pacing was decided once at start, so a writer that opened state.db after the
run began (Desktop launched, gateway restarted) only got in through SQLite's
own gaps (one append waited 16.7 s with wal_autocheckpoint=0, next to
_execute_write's 20 s patience). _HolderWatch re-runs the same foreign-holder
scan the held-store refusal and --force use (foreign_state_db_holders, ~15 ms)
every 2 s on a side thread (copy_context, HX012); the chunk loop reads the flag
and switches to the paced cycle (~50 ms chunks + max(0.2 s, 4x cost) pause)
while a holder is there, back to unpaced when it leaves. A quiet run still
never sleeps. The CLI's one-shot scan and yield_to_writers go away; progress
lines say "paced: another process is using the database".
- A failed run (chunk kept failing, or "Could not optimize") now returns 1.
- Backfill progress counts messages (rows each window covered, total = rows at or
below the high water), not ids: a 100k id gap no longer reads 0% then 99%.
- The CJK backfill gets its own phase/line ("Building CJK index") instead of
overwriting the base pass's line with a lower percent.
- Teardown skips the per-table COUNT(*) when no progress callback is registered.
- Tests build the legacy store with both inline indexes (base + trigram), so the
trigram rebuild and all 10 reclaimed tables run; exit code 1 is asserted in the
disk-full test; one new test covers a holder appearing mid-run.
A COUNT that failed once left the new table published on the progress
state, so the retry skipped the start step and the table inherited the
previous table's totals (shown as 10,726/2,726). Count first, publish the
table last. The backfill counter is id-based, so drop the "messages"
label that misread on pruned stores.
Review round on #144630:
- CI: the VACUUM size probe read PRAGMA page_count/freelist_count under the
writer lock (TestNoPureReadersUnderWriterLock); it now reads on the pooled
reader, only when a progress callback exists.
- Progress state is typed: _TeardownProgress (owned by the teardown step, which
now picks the table, counts it on the reader and deletes in one place) and
_VacuumProgress. _drive's before/**step_kwargs hooks and the duplicate trash
lookup are gone.
- Backfill windows are the next N messages (LIMIT 1 OFFSET N-1 bounded by the
high water), not N ids: an id gap no longer ramps the window to 1M ids (gap
store: worst chunk 6.6 s -> 0.39 s). Max rows 1M -> 100k (dense trigram_data
teardown chunk 0.22 s at the cap). Each trash table restarts at 500 rows.
- Step engines no longer swallow OperationalError into "more work"; the drive
loop retries a failing chunk 3 times (lock failures already waited out
_execute_write's patience) and then raises, so SQLITE_FULL ends the run with
"No data was lost. Re-run to resume." instead of spinning.
- --force past a live holder (start-up scan finds one) passes
yield_to_writers: chunks near 50 ms plus max(0.2 s, 4x cost) pause, so the
holder's writes are not starved (writer p50 0.012 s, max 0.17 s). The
foreground default stays pause-free.
- VACUUM ticker is built only with a callback, via copy_context().run (HX012)
instead of importing agent.memory_provider into the storage layer; each
table's 100% line is drawn once; Ctrl-C prints "Interrupted — no data was
lost; re-run to resume." (exit 130) instead of a traceback.
`hermes sessions optimize-storage` printed only "Reclaiming old index…" for the whole
teardown (9+ minutes per shadow table on a 16 GB store), nothing at all during the
VACUUM, and a garbled "Rebuilding index: 100% (0/0)8,500/1,958,548)" line when a shorter
update overwrote a longer one.
It was also idle most of the time: every 500-row chunk was followed by
max(0.2 s, 4x chunk cost) of sleep. That duty cycle (#65798) let a live gateway take
the write lock between chunks, but the only driver of these steps is the foreground
CLI, which since #110054 refuses to run while any other process holds state.db
(held_store_refusal). There is no writer to yield to, so the sleeps were pure dead time
(>95% of the teardown, ~80% of the backfill).
- Backfill/teardown chunks run back to back; chunk size adapts toward ~0.25 s per
transaction (bounded WAL growth, resumable, a progress tick each), since one row
costs ~1000x more in trigram_data than in docsize.
- Teardown reports table k/n and rows drained / rows left (one COUNT per table on
the reader); VACUUM reports elapsed time every second plus size before → estimated
size after.
- The CLI draws one self-overwriting, space-padded line per phase/table (no ESC[K).
- Drop the test fixture that zeroed the removed throttle constants.
Carried from BearHuddleston's #93508 onto main. The Webapp relay and the
profile-incarnation fence stay out: carried code follows main's
named-profile rule and refuses a missing or deleted profile home.
- Webapp routes: one-use launch tickets, window handoff, and gateway
WebSocket tickets minted for the signed-in browser
- Browser surface policy and the SPA document policy
- A host terminal for the browser that survives reconnects
- Staged browser uploads and file tickets; file.attach takes a staged upload
- hermes sessions adopt
- Webapp bundle build helpers and the renderer freshness check
- Regenerated gateway contracts
Co-authored-by: emozilla <emozilla@nousresearch.com>
Greptile "Repair clears healthy older prompts": the check accepted only today's
SKILLS_GUIDANCE line, so a healthy prompt stored under an earlier opening line
(it still carries "## Skill Safety Rule") was flagged once its session pinned
skill_manage, and --apply cleared it, forcing a rebuild and a cache miss on the
next resume. Either marker now counts as healthy.
Maintainer-approved prompt-footprint trims (measured on the Nous endpoint, anthropic/claude-opus-5.5):
All sessions
- The [SKILL_PRUNED] "Skill Safety Rule" (126 tok) left the system prompt: markers only exist after a
compaction, so the compaction handoff now carries the rule whenever a marker survives in the
compacted transcript (context_compressor_tail.with_skill_safety_rule, applied in
_assemble_compressed for LLM and fallback summaries alike). The "## Pruned Skills" block drops
its own parenthetical, which the rule now covers. `hermes sessions repair-prompts` keyed its
"full build" detector on the rule's heading; it now keys on SKILLS_GUIDANCE (present in prompts
built before and after this change).
- The CLI/TUI cron "LOCAL-ONLY" caveat (154 tok) moved from the platform hints into
cronjob_manage's deliver description (a deferred tool: paid only when loaded).
- The Hermes help pointer no longer restates identity ("You run on Hermes Agent (by Nous
Research)") after SOUL.md's "You are Hermes Agent, built by Nous Research."; it now opens "For
help with Hermes Agent itself — ...", which still tells a custom persona what it runs on (22 tok).
One-shot sessions only (-q/--oneshot/-z, and gateway-owned `oneshot` policy sessions)
- No "## Mid-turn user steering" note (253 tok): nobody can steer a one-shot.
- No clarify tool (590 tok): ONESHOT_DISABLED_TOOLSETS is folded into session_disabled_toolsets
(oneshot=...), so the agent tool build, MCP refresh, the tool_search bridge, delegate children and
the gateway's session inventory / tool listings all drop it together. skill_manage stays.
- delegate_task without live control (425 tok): action/subagent_id/message and the
background-delivery paragraph are removed (children are joined inside the call), applied via
toolsets.agent_tool_surface at load and MCP refresh. The one-shot fact is frozen on the agent at
its first tool build so refreshes stay byte-stable.
Interactive tool schemas are byte-identical to main.
--source gui and --source desktop match the same rows, before and after
the peer refresh. --source acp matches ACP rows stored as local. The
groups come from session_policy.SURFACES. stats counts through the same
reader, including a read-only store from before the column existed.
Suggestions from the maintainer review:
- A read-only state.db (or its directory) on a lagging store got the generic
"could not be caught up ... run sessions repair" text, because the shared
column reconciler logs a readonly ALTER failure and continues. Browse now
checks writability under the lock before the DDL, and also maps a sqlite
`readonly` error. The 503 names the path and says to fix the permissions;
nothing was changed. Test:
test_read_only_lagging_store_gets_a_permissions_message (red -> green).
- `hermes sessions repair` branched three times on
`repair is repair_declarative_schema`; it now uses one explicit
`drift_only` flag. Behavior is unchanged
(test_sessions_repair_declarative.py, 13 passed).
- The SCHEMA_VERSION 32 comment claimed the bump makes drift detectable and
told future authors to bump again. Detection is probe-based, so the comment
now says so and drops the unenforced rule.
- test_sessions_repair_declarative.py stubs _live_writer_holds_db, the same
way test_state_db_repair_non_destructive.py does, so a developer machine
running Hermes cannot refuse its tmp_path repairs.
- Drop the duplicate `import logging` in _reconcile_snapshot.
Review finding by @alt-glitch on #140487 (Suggestions 3, 4, 5)
Refs #134889 (LC-21)
Refs #140337
Desktop sessions never set ended_at, so the prune/archive selector's
ended_at IS NOT NULL guard hid them from bulk archive entirely: explicit
filters printed 'No sessions match' for sessions visible in the desktop
sidebar (#139597).
Add an archive-only --include-open flag that lifts the guard in the
shared selector, and report open matches the default path skips. The
delete path refuses include_open fail-closed — pruning open sessions
stays impossible because deletion is not reversible.
Fixes#139597
(cherry picked from commit f6b123111ef137c9048e5d023a59f55021259b78)
The canonical ledger refuses to delete a session whose turn is queued/running
(session_busy) or was lost across a gateway restart (unknown_execution); the
CLI let that RuntimeStoreError escape as a traceback. It now exits 1 with what
to do: an unknown turn names `hermes sessions discard <id>`, a queued/running
one says to wait for (or stop) it. The session is left untouched.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5475590057
With one always-on gateway per host, `hermes sessions prune` always found
the owner holding state.db and refused (live smoke LS-F7). The only ways
past it were `gateway stop`, which the next client undoes by restarting
the gateway, or `--force`, which makes the CLI a second writer under the
owner. `hermes sessions delete` already worked against the same gateway.
Now, when a ready gateway serves the home (discovery only, it never
starts one), prune opens the store read-only for its preview (the pinned
note, the open-session note, `--dry-run`, the confirm prompt; all
unchanged). It then sends the filters it built to the owner as
`session.prune`. The owner deletes through `prune_sessions` /
`retire_prunable`, the path housekeeping uses, so busy sessions and the
logical owner of a retained reset child are skipped. It then drops the
deleted ids from its own memory (routes, launch secrets, live sessions,
cached agents) through the helper canonical delete now shares
(`retire_live_sessions`). `--never-active` goes the same way. With no
gateway running, prune is the local command it was, holder scan and
`--force` included.
`session.prune` deletes across every principal's rows, so it is open
only to the native local operator ticket from this host's private
control socket. A viewer or a remote/browser grant gets
`permission_denied`. The contract is declared and the generated TS and
OpenRPC files are regenerated. The CLI help and the two user-guide
passages that promised a refusal are updated.
Red on 30b63bda20 (all touched sources swapped back), green after:
tests/hermes_cli/test_sessions_prune_via_owner.py, 3 tests. A real
foreign process holds the store; prune applies through the owner with
the right rows, keeps the reset owner and its child's history, the CLI
opened only read-only, and non-operator grants are refused.
Live, a real `gateway run` in a fake HOME. Before: `prune --yes` printed
"Refusing ... PID <gateway>", rc=1. After: --source cron pruned 1; a bare
--older-than 0 pruned 2 and kept the reset owner and its open child; the
next turn on that session completed; strace shows the CLI opened
state.db O_RDONLY only. With no gateway the local prune still works and
does not start one.
The noqa on canonical.py's trailing import is removed. Neither ruff
config flags that import without it, and strict ruff's RUF100 rejected
the directive, which blocked the lefthook.
Review: https://github.com/NousResearch/hermes-agent/pull/106742
(cherry picked from commit 1e2dd5a49f04439b53a248aab24df9b10f4c7f9e)
When the gateway dies mid-turn, the session's started admission is fenced 'unknown' and blocks
the FIFO. `hermes chat --resume <id> -q` correctly refuses (exit 3, nothing submitted), but the
only way to clear it was interactive `/discard <admission>`, which piped input cannot reach. A
script was stuck on exit 3 forever.
`hermes sessions discard <session> [--admission ID ...] [--yes]` resolves the session by id or
title and calls the same fenced owner control as /discard (prompt.resolve_unknown with the
execution_generation the owner stamped on each unknown row). It never writes the store directly,
never replays the lost input and leaves queued inputs alone. It defaults to every unknown
admission. It asks for confirmation unless --yes is passed, and refuses (exit 2) on a non-TTY
stdin without --yes. The -q refusal now names the command. Documented in user-guide/sessions.md
and the upgrade notes.
Live probe (fake HOME, loopback stub that hangs on one prompt, gateway SIGKILLed mid-turn):
`chat --resume <id> -q` gives rc 3; `sessions discard <id>` with piped stdin gives rc 2; with
`--yes` it gives rc 0 ("Discarded <admission>", row now terminal); `chat --resume <id> -q` then
gives rc 0 and replies. No leftover gateway.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6073624820
(cherry picked from commit 55d1cd7d6b5e4298e85ee07ca70fb59945afee73)
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
The CLI and gateway /save json wrote the live rows only, the projection the
removed comment justified by import_sessions replaying archived turns as live
context. Import now restores the active/compacted flags, and the dashboard
import accepts a /save json file, so a snapshot of a compacted session lost
every turn the summary replaced. One export_projection() rule now picks the
display history for transcripts and every flagged row for JSON, shared by
`hermes sessions export` and both /save surfaces.
(cherry picked from commit 12f98c891cd70083d35dda9bcabe17459e4c7bb0)
Gate finding (BN06 r1 quality, Low): the missing-id check lived in three
places (_collect_sessions, _export_trace, _export_markdown_single), and
_collect_sessions had grown a list|int|None return with an isinstance
branch in _export_flat just to carry the exit code. Resolve the id once at
the top of _cmd_export and return _not_found's non-zero code there; the
per-format copies and the int return are now dead and reverted.
prune_never_active_keyed_sessions now returns (deleted, entries_dropped,
skipped) from its own guarded-row list. `sessions prune --never-active`
printed candidates-minus-deleted, which lumped rows that vanished
concurrently in with live-turn skips and needed an "or already gone"
hedge; it now reports only rows spared by a live turn or compression lock.
The docstring claimed a failed sweep rolls back whole; the row sweep is one
transaction but routing entries are dropped in a second write after it
commits, so say that.
The kept guard test now also covers a candidate that vanishes between
listing and the sweep: its routing entry must still be dropped (the r1
per-row loop left it behind, so the gateway would resume a nonexistent id).
The per-row delete_session loop ran N write transactions and N routing scans,
and a row that vanished between list and delete (concurrent delete) returned
False and kept its routing entry alive, pointing the gateway at a nonexistent
id. delete_sessions already has the exact delete_session semantics (delegate
cascade incl. guard scope over delegate children, branch orphaning, messages,
system-prompt GC, transcript files) in ONE transaction and reports guarded rows
via skipped_ids. Routing entries are now dropped once, after the commit, for
every candidate except the guarded ones; an aborted sweep rolls back whole, so
no route is stranded and the mid-loop abort test is obsolete.
`hermes sessions prune --never-active` now tells the user how many candidates
were skipped (mid-turn or already gone) instead of silently reporting less.
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 backup now loads every stored row, archived generations included,
but `_cmd_export` skipped the per-session `assert_export_safe` guard
that the console export applies. A heavily compacted session with a
small live tail could therefore load an unbounded archive into memory.
All three selection paths (`--session-id`, filters, bare export) now
run the `sessions.max_export_messages` guard over the stored row count
before loading anything, and print the refused session id. Transcript
views keep their display projection and are not guarded, as before.
website/docs/user-guide/sessions.md no longer says JSON/JSONL exports
are live-only. It now says they carry every stored row, including
compaction-archived and rewound or edited-away messages, with their
flags. It also says an import restores those rows as archived, and
that the guard applies to the backup.
(cherry picked from commit 36cdc89e342b7bda4e362294c1bd0ba5d44fed6d)
For --format jsonl/json (the documented "backups, machine round-trip"
format), _collect_sessions called export_all / export_session with
include_compacted=False and the default include_inactive=False — the
live-only projection. In-place compaction (on by default) archives
earlier turns as active=0, compacted=1, so a backup of any compacted
session held only the summary plus the live tail, and restoring it via
import_sessions (or the dashboard import) lost every archived turn.
Commit 85deb4553a (#122679) fixed exactly this, but only in
console_engine's export; the primary CLI sibling was missed.
The backup path now uses the transfer projection (include_inactive=True:
every row with its active/compacted flags, which import_sessions
restores as archived). Transcript views (md/--only) keep the display
projection.
(cherry picked from commit 9ecb273f17e098bdd497a228ed951c0802aa8fd8)
The sweep, the prune filter and the stale-archive pass each spelled out the
"not pinned and not a pinned segment's continuation" SQL; the sweep's copy
used a different alias and could drift from the other two. _not_pinned_sql()
now builds it for any alias. count_prune_matches(pinned_only=True) implies
include_pinned itself (a pinned-only count under the not-pinned filter is
always zero), so the CLI pinned-skip note no longer re-shapes the filters,
and the CLI FakeDB honours pinned_only like the real store.
Prune/archive now spare the unpinned continuations of a pinned segment,
so the old "matches with pins minus matches without" arithmetic reported
those protected segments as pinned sessions (one pinned chat split in two
read "2 pinned sessions"). Count the literally pinned matching rows
instead via count_prune_matches(pinned_only=True).
Fixes#126432
Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
prune_sessions hand-rolled the same "guarded by a live lease/lock"
comprehension as the new _guarded_ids helper, so the two could drift on
the next guard change. Move _guarded_ids next to _write_guards_reject in
the maintenance mixin and have prune call it.
delete_session walked the delegate tree up to three times in one write
transaction; compute the target ids once for both the guard check and the
expected-ids fence. delete_sessions ran a per-root guard walk for every
selected id; do one batched check over all roots and their children first
and only attribute per root when something is actually guarded.
The CLI export --delete message repeated "session 'X'" because the
exception text already names the session.
delete_sessions(exclude_active_write_guards=True) dropped guarded rows
silently: the web bulk-delete endpoint returned only a count and the
dashboard removed every selected row optimistically, so refused rows
reappeared on the next reload with no explanation.
The store now appends refused ids to an optional skipped_ids list inside
the same write transaction, the endpoint returns them as skipped_active,
and SessionsPage keeps those rows listed. Also hoists the
SessionActiveWriteGuardError imports to module top (hermes_state_errors
is stdlib-only) and drops the assertion-less lineage comment in the test.
Refactor entry-side deletion refusal to execute in-transaction via
`_write_guards_reject(conn, sid)` (#123583), per maintainer review:
- Underlying `delete_session` and `delete_sessions` now accept an opt-in
kwarg `exclude_active_write_guards=True` running inside `_do` write
transaction, eliminating the race condition where a turn acquires the lease
between check and delete.
- Raises `SessionActiveWriteGuardError` when refusing single delete, leaving
the row untouched; `delete_sessions` atomically skips active rows.
- Checks both active turn leases and compression locks via the existing
reclaim-aware `_write_guards_reject` helper.
- Covers all user-facing delete sinks:
* Web `DELETE /api/sessions/{id}` -> 409 Conflict
* Web `POST /api/sessions/bulk-delete` -> skips active rows
* Web / CLI `prune` -> passes `exclude_active_write_guards=True` so lineage
parents of active conversations are not pruned
* API Server `DELETE /api/sessions/{id}` -> 409 session_active_turn
* CLI `hermes sessions delete` & `export --delete-after-verified` -> exits 1
* CLI browse picker -> refuses active delete
* TUI Gateway `session.delete` -> 4023 error
- Conforms to rubric with 2 targeted invariant tests in
`tests/hermes_state/test_delete_session_write_guards.py`.
- Updates user guide and web dashboard docs for 409 / exit 1.
(cherry picked from commit 2c037a7a79dc211b49bacc72e3140951ccf900cf)
Merge #8: 2,771 commits from main (4b05f764fa). Ports main's moved code into the
unified runtime (run.py/run_turn.py splits, tui_gateway server, backup/restore
split), keeps the detached-daemon Desktop lifecycle, and adapts main's new tests
to the owner/authority contracts (canonical session deletes, retired-id
tombstones, zero-writer browsing, hermes_yaml, platforms() markers).
Gateway /resume rewrites sessions.source to the resuming platform, which is
correct routing behavior (source feeds find_latest_gateway_session_for_peer,
Telegram listings, and the TUI ghost pruner) but destroys creation
provenance. Add a separate immutable created_source column stamped once at
session creation and preserved by all upsert paths; surface it in
hermes sessions list as '<created>→<current>' when the two diverge.
Fixes#56439
whole_lineages only adds "AND s.id NOT IN (<continued ancestors>)", and
every id in that set is a parent with end_reason='compression'. Every
writer sets ended_at and end_reason together (and every reopen clears
both), so an open row is never in it: the flag could not change
count_open_prune_matches, it only added a recursive CTE and doubled the
bound params on each prune preview.
Remove the parameter and both call sites (CLI prune, dashboard prune),
and move the dashboard "preview lists what it deletes" comment to the
list_prune_candidates call it describes. Prune behaviour is unchanged.
_note_pinned_skipped diffed count_prune_matches(include_pinned=True/False)
with whole_lineages on for prune. Excluding a pinned tip turns it into an
unmatched continuation, so its unpinned compression ancestors drop out of
the "without" count too and the note reported them as pinned (chain
a -> a-2 -> a-3 with only a-3 pinned said "3 pinned sessions").
Count plain filter matches for the note; the delete itself is unchanged.
count_prune_matches has no other caller that needs whole_lineages, so the
keyword goes back to base's signature.
_prune_where popped whole_lineages out of **filters and prune_sessions
injected it by mutating that dict, so a filter-shaped kwarg silently
changed the SQL shape and a typo'd flag would be ignored rather than
rejected. It is now a keyword-only argument of _prune_where and the
list/count prune helpers; prune_sessions passes whole_lineages=True and
the CLI and dashboard previews pass it explicitly. Behaviour unchanged.
Retention prune (the default-on startup auto-prune, `hermes sessions prune`
and the dashboard prune) aged every session row on its own. A conversation
that rotating compression split into segments has an ended, old root by
construction, so once that root passed retention_days it was deleted while
the conversation's live tip was still being written: the pre-compression
turns vanished from the resume/Desktop history and from session_search, and
the tip was orphaned.
Prune now deletes a compression ancestor only together with every
continuation after it (`whole_lineages`), so a lineage ages through its
newest segment and goes as a unit once the whole conversation qualifies.
Branch, delegate, reset and tool children do not count as continuations.
The CLI and dashboard prune previews pass the same flag, so they list what
prune deletes; bulk export keeps its current selection.
(cherry picked from commit b082fc6ffa02607cba219a5dfa361d4f3bf4c266)
An explicit SESSION_ID whose stored prompt is already NULL used to print
"No degraded stored system prompts found.", which reads like a scan
result. Say the row already has no stored prompt and there is nothing to
clear. The SESSION_ID override assertions (memory-only clear, empty-row
message, unknown id -> exit 1) move into the memory-only scan test so the
stack keeps two invariant tests.
The helper now tests a single thing - whether a non-empty stored prompt
lacks the Skill Safety heading - so _repair_prompts_missing_skills_markers
(plural, "skills markers") misdescribed it. Rename to
_repair_prompts_lacks_skill_safety.