Commit Graph

123 Commits

Author SHA1 Message Date
Teknium
0216b1a320 fix(sessions): refresh epoch survives compression rotation; --session targets the tip
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.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
e240d617e8 feat(sessions): refresh-prompts lets continuing sessions adopt updated prompt sources
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.
2026-10-28 19:30:48 -07:00
Teknium
46adcf7d40 fix(sessions): Windows NUL stdin is unattended, not a terminal decline
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.
2026-10-25 22:36:59 -07:00
Teknium
2dfe39361d fix(sessions): Ctrl-D at a terminal is a no; an over-cap export exits 1
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.
2026-10-25 22:36:59 -07:00
Teknium
b9e5df60fd fix(sessions): Ctrl-C at a sessions confirmation exits 130, not 0
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.
2026-10-25 22:36:59 -07:00
Teknium
30c096abcd fix(sessions): a confirmation nobody could answer exits 1
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.
2026-10-25 22:36:59 -07:00
John Paul Soliva
204ccada74 fix(sessions): export's refusals and failures exit non-zero too
_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>
2026-10-25 22:36:59 -07:00
John Paul Soliva
c479245a60 fix(sessions): repair, optimize and refused bulk actions exit non-zero on failure
`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.
2026-10-25 22:36:59 -07:00
Teknium
9a2fa5e406 fix(sessions): optimize-storage counts backfill rows from an index; no VACUUM over a live writer
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.
2026-10-25 18:25:29 -07:00
Teknium
d569365e87 fix(sessions): optimize-storage paces for a writer that opens state.db mid-run; failed runs exit 1
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.
2026-10-25 18:25:29 -07:00
Teknium
a85ffc0e24 fix(sessions): teardown progress survives a failed table count; backfill counter shows ids
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.
2026-10-25 18:25:29 -07:00
Teknium
ead7bedca6 fix(sessions): optimize-storage sizes chunks by rows, stops on a dead chunk, paces under --force
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.
2026-10-25 18:25:29 -07:00
Teknium
32494cdf03 fix(sessions): optimize-storage shows progress in every phase and stops idling between chunks
`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.
2026-10-25 18:25:29 -07:00
Bear Huddleston
b5eb5ee7a8 feat(webapp): carry the browser-hosted Desktop's server pieces from #93508
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>
2026-10-25 03:22:14 -07:00
Teknium
51d8010cf7 fix(sessions): repair-prompts leaves prompts healthy under the old skill guidance
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.
2026-10-24 17:31:52 -07:00
Teknium
c422d69189 fix(prompt): one-shot runs drop steering, clarify and delegate live-control; skill-safety rule moves to compaction
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.
2026-10-24 17:31:52 -07:00
David Dudok de Wit
1b3ad1f79b fix(cli): list, browse and stats read gateway rows by created surface
--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.
2026-10-20 14:13:35 +05:30
Teknium
6335bd74c8 fix(sessions): read-only store message, drift_only flag, honest v32 comment
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
2026-10-17 07:54:41 -07:00
funky-xamarin
af586e5aca fix(sessions): reconcile columns before dependent indexes on repair snapshots
(cherry picked from commit ea02bcf6e7d6d28c8a2dd5d678e657ace7d9e497)
2026-10-17 07:54:40 -07:00
funky-xamarin
49b42a8b2f fix(sessions): reconcile declarative drift during explicit repair
(cherry picked from commit fc1fba356c995b0de3f73ff3f3115ed9b92cc23f)
2026-10-17 07:54:39 -07:00
liuhao1024
00a0d64286 fix(cli): let archive reach never-ended sessions via --include-open
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)
2026-10-16 19:21:43 -07:00
Teknium
4857d1c035 fix(cli): hermes sessions delete on an unfinished turn points to discard
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
2026-10-10 05:52:02 -07:00
Teknium
c71e6c791b fix(sessions): hermes sessions prune runs through the live gateway instead of refusing
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)
2026-10-09 07:08:20 -07:00
Teknium
23dcf14bdb fix(cli): hermes sessions discard lets scripts recover a session after a gateway crash
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)
2026-10-09 02:10:47 -07:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
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).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
1e500ebce2 Merge origin/main (#16: 4,465 commits to 9dcab1e440) into feat/unified-gateway-runtime
99 conflicted files resolved in nine area lanes (Desktop composer, Desktop renderer/shared
client, Electron main, Ink, tui_gateway, gateway, state, CLI/config, cron/tools/CI). The
unified runtime's architecture wins where it deliberately replaced a mechanism (pool,
fallback lanes, claim poller, renderer queue); every orthogonal main change is kept, ported
into the <stem>_<topic> sibling that now owns relocated code.

Notable ports and repairs in this merge:
- tui_gateway/server.py relocated regions: atomic _attach_built_agent (#49852), slash ranking
  registry names, minted-key helpers methods_session.py calls, request_overrides, service tier.
- gateway/run_turn*.py: i18n accessors for the removed reply constants, first-contact
  internal/DM rule, rotated-compression persist, fast-mode tiers, prompt-pin rehydration.
- webhook: route_from_chat_id decodes main's opaque webhook:v2 chat ids (old ids still read).
- ws.py: main's per-connection dispatch queue with authority-first dispatch inside it.
- state: schema event for runtime revision renumbered to 31; worker mirrors updated for
  main's message uid/merge fields, on_contended lease arg, compression columns.
- config: branch's bot_chat_delivery_timeout removal renumbered v47 -> v50.
- Electron: primary-profile pin, redirect header scoping, remote fetchJsonForBackend, SSH
  teardown on profile delete, held-update dial gate restored (lost in earlier merges).
- Desktop: canonical clarify.request mapped to main's questions[] card; replay truncation vs
  snapshot_required; periodic secondary prune tick restored; DELETE already_absent restored.
- cron/tools: diagnostic category on cron failure notices restored; owner_holds_delivery
  ported onto the authority; admitted receipts can no longer be cancelled locally.
2026-10-06 14:24:24 -07:00
John Paul Soliva
9cb2fddee4 fix(sessions): /save json snapshots keep compaction-archived turns too
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)
2026-10-03 19:21:54 +05:30
kshitijk4poor
2dbe76a978 refactor(sessions): check an explicit export --session-id once in _cmd_export
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.
2026-10-03 16:36:00 +05:30
itsflownium
5b33f3128a fix(sessions): include protected rows in retention backups
(cherry picked from commit 891575265e657acf5d0b5e6179d11013407a7f8c)
2026-10-03 16:36:00 +05:30
kshitijk4poor
13cf8f2058 fix(state): report the never-active prune's exact skipped count
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).
2026-10-03 16:32:15 +05:30
kshitijk4poor
852179c09f fix(state): prune never-active keyed rows in one guarded transaction
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.
2026-10-03 16:32:15 +05:30
kshitijk4poor
f64c68a60d refactor(sessions): carry the export refusal text on SessionExportTooLargeError
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.
2026-10-03 16:32:10 +05:30
kshitijk4poor
2358519860 refactor(sessions): one export-guard helper and refusal text for CLI and console
`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.
2026-10-03 16:32:10 +05:30
Froraut
0f548a9cf9 fix(sessions): address review — guard the JSONL backup with max_export_messages; document it
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)
2026-10-03 16:32:10 +05:30
Froraut
92a6b252f5 fix(sessions): hermes sessions export JSONL backups keep compaction-archived turns
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)
2026-10-03 16:32:10 +05:30
kshitijk4poor
91c189bb33 refactor(sessions): one helper builds the not-pinned predicate
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.
2026-10-03 16:30:15 +05:30
kshitijk4poor
1aa8365017 fix(sessions): the pinned-skip note counts only rows that carry the pin
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>
2026-10-03 16:30:15 +05:30
teknium1
6f2aeb528f Merge origin/main (#10: 382 commits to 8f897d2d23) into feat/unified-gateway-runtime
Conflicts:
- hermes_state_sessions/maintenance: main's shared write-guard filter
  (_guarded_ids, delegate-child cascade guard) runs first, then the branch's
  mutation retirement (retire_sessions / retire_prunable).
- hermes_state_messages/compression: the branch's _append_messages_in_transaction
  split keeps main's serialize/decode repair hooks and runs under main's
  _execute_transcript_write (caller row state restored on rollback).
- web_routers/sessions delete: the gateway-executed canonical delete stays
  (busy sessions already answer 409 session_busy); docs keep that contract.
- web_server lifespan lives in web_server_app: main's orphan-reap startup
  grace (min_age_s, #122533) ported there.
- Desktop uninstall teardown: main's quiet 'quit' intent; its pool-PID seeding
  is dropped because attach-model pool entries own no child process.
- Desktop lifecycle/slash imports: union.
2026-09-27 12:42:14 -07:00
kshitijk4poor
230f89b47b fix(sessions): share the write-guard filter and trim repeated walks
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.
2026-09-27 20:49:04 +05:30
kshitijk4poor
907e3188da fix(sessions): report bulk-delete rows skipped for a live turn
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.
2026-09-27 20:49:04 +05:30
shali10
40523600b0 fix(sessions): refuse to delete a session row a live turn still owns (#123583)
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)
2026-09-27 20:49:04 +05:30
teknium1
c6dc7ab120 Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime
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).
2026-09-27 02:30:04 -07:00
Austin Pickett
f81bb4c485 fix(state): add immutable created_source provenance column (#56439)
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
2026-09-26 21:12:19 -04:00
kshitijk4poor
1d2b573739 refactor(sessions): drop dead whole_lineages from the open-session count
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.
2026-09-27 00:43:39 +05:30
kshitijk4poor
f1ad1934a4 fix(sessions): pinned-skip note counts pinned rows, not spared ancestors
_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.
2026-09-27 00:43:39 +05:30
kshitijk4poor
257f70db28 refactor(sessions): make whole_lineages an explicit prune keyword
_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.
2026-09-27 00:43:39 +05:30
John Paul Soliva
7d49b46e15 fix(sessions): prune keeps the compressed-away start of a chat still in use
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)
2026-09-27 00:43:39 +05:30
kshitijk4poor
92c90488f1 fix(sessions): say when a targeted repair-prompts row is already empty
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.
2026-09-27 00:40:21 +05:30
kshitijk4poor
3d245524dc refactor(sessions): name the repair-prompts detector after its check
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.
2026-09-27 00:40:21 +05:30