Commit Graph

56951 Commits

Author SHA1 Message Date
Teknium
401de3bf64 refactor(state): keep hermes_state_sessions.py under the file cap after the rebase
Main grew the facade by 12 lines; the list-row docstring folds to one line.
2026-10-20 03:08:06 -07:00
Teknium
2e6b6ad339 chore: map salvaged contributor email (hxy91819) 2026-10-20 03:08:06 -07:00
Teknium
b807443f7e fix(gateway): log the host-hint probe failure; write the boot config as UTF-8
Health gate (BLE001) on the folded stop hint, and the Windows encoding footgun on the
host-boot test fixture added by the fold.
2026-10-20 03:08:06 -07:00
Teknium
38ec5e4284 fix(gateway): read the held MCP policy on the loop, hash it off the loop
_held_mcp_rev ran policy_for_source on a worker thread; it walks authority.sessions and the local
adapter's maps, which only the loop mutates. The policy is now read on the loop and only the
config read and hash go to a thread.
2026-10-20 03:08:06 -07:00
Teknium
835b0fa4d7 fix(gateway): the store-park reason reports the recorded open failure, never reopens
_store_open_failure reopened <home>/state.db through the registry to learn why it had no handle:
a real open that could create a missing store or run its migration, and skipped the handle
caches' backoff. RecoverableHandleCache now records the exception of the latest failed open
(last_error), and the park reason reads it from the runner's caches.
2026-10-20 03:08:06 -07:00
Teknium
d2be5394dc fix(gateway): a live listing drops the batch of a profile parked during its off-loop read
The per-batch store read is an await; a park (unserve) can retire the authority while it runs, and
that batch then belongs to the home's next owner. The listing returns nothing for a retiring or
retired authority after each read.
2026-10-20 03:08:06 -07:00
Teknium
180ab5e20c fix(skills): lock the raw-config cache's publish, evict and clear
_load_raw_config published into, iterated and popped a module dict shared by every thread (one
gateway serves many profiles, each with its own config.yaml): concurrent eviction raised
RuntimeError('dictionary changed size during iteration') or KeyError. A module lock now guards
lookup, publish+evict and clear; the stat and YAML read stay outside it.
2026-10-20 03:08:06 -07:00
Teknium
34133f2740 fix(update): a flapping relaunch replacement cannot renew its liveness budget forever
_poll_until_ready dropped since[key] on a missed probe, so every reappearance counted as a first
sighting and granted another respawn_window: a replacement that kept dying before the confirmation
window kept the update polling indefinitely. First sighting is now tracked apart from the
confirmation streak (the extension is granted once per target), and an overall bound computed on
entry ends the poll regardless.
2026-10-20 03:08:06 -07:00
Teknium
20eef53819 fix(gateway): owned_gateway_pid is the one ownership gate; sticky --force stays stoppable
Folds #141203 (@hxy91819) into the lifecycle fix: find_gateway_pids() reads the recorded pid through
owned_gateway_pid(), so every caller (stop, uninstall's kill, service_manager.is_running, cron
readiness, Windows start polls) stops treating the host multiplexer as a served profile's own gateway.
The separate_gateway_pids() patch this PR had added is now redundant and removed.

Two gaps in the folded gate, from review:
- A `gateway run --force` launched without -p through the sticky active_profile has no launch
  identity in argv/env, so the gate refused it and `gateway stop` exited 1 with the gateway alive.
  Its own <home>/gateway.pid (pid + start time + home, written once by that process about its
  launch home; the host never writes one into a served profile) is now accepted as proof.
- The gate dialled the host control socket on every find_gateway_pids() call (gateway status asks
  once per profile). The host record (file read + incarnation check) now settles a pid that is not
  the host's, or the host's from another home, without a dial; the socket is asked only for the
  host's own pid when no launch record vouches for it.

report_profile_stop_failure names the host when the refused pid is the host gateway serving this
profile, keeping the "stop the host instead: hermes gateway stop --all" hint.
2026-10-20 03:08:06 -07:00
hxy91819
fa0fc39ee5 fix(gateway): accept verified host ownership and report refused stops 2026-10-20 03:08:06 -07:00
hxy91819
747ab06430 fix(gateway): never authorize termination from a mutable sticky profile 2026-10-20 03:08:06 -07:00
hxy91819
db3f202099 fix(gateway): require fresh positive ownership before stopping a PID 2026-10-20 03:08:06 -07:00
hxy91819
d516ce878d fix(gateway): keep satellite stops off the shared host process 2026-10-20 03:08:06 -07:00
Teknium
f1e446969c chore: map salvaged contributor emails (kouyichi, wkwee) 2026-10-20 03:08:06 -07:00
Teknium
de0b2d4a12 fix(tui): a refused MCP reload revision backs off instead of retrying every poll
The TUI's config poll re-sent `reload.mcp` for an unacknowledged revision on every 5 s tick. With
one MCP server parked after a gateway restart the gateway refused each one, so every open TUI
produced a WARNING and a full reconcile every 5 s forever (1,897 lines in 52 min with three TUIs).
The salvaged gateway change answers a reload naming the held revision as success; this is the
client half for the reloads that are still refused: the same revision now retries after a doubling
backoff capped at 5 minutes, and a new revision retries at once.

Refs #141769
2026-10-20 03:08:06 -07:00
Teknium
adbc7cd0b5 fix(gateway): a profile parked for an unusable store names the open failure
`_build_profile_authority` read every missing store handle as "session authority database does
not belong to the reserved profile". The scoped handle cache returns None for a failed open (and
during its backoff), so a legacy store whose v32 backfill crashed on every open was parked under
an ownership reason that sent the operator after the wrong problem. A None handle now re-tries the
open once off the loop and parks with the real exception (`<home>/state.db did not open: ...`); the
ownership message stays for a handle that genuinely resolves elsewhere.

Fixes #141467
2026-10-20 03:08:06 -07:00
Teknium
4a99d8e2ce fix(gateway): every "separate gateway?" check under -p drops the serving host's pid
Completes the salvaged #141133 fix. The host pid in a served profile's gateway.lock was excluded
only in profile_lifecycle's stop/restart gate; `_cmd_stop`'s own "the host serves this profile"
refusal and the parked-restart unpark check still read `find_gateway_pids()` raw, so a stop that
skips the park path (`--force`, or a profile_lifecycle stand-down) fell through to SIGTERM the
host. One helper, `separate_gateway_pids()`, now answers that question for all three checks; the
salvaged `stop_profile_gateway` refusal stays as the last line before the kill.

Fixes #141133
2026-10-20 03:08:06 -07:00
Teknium
45e7f7dd22 fix(gateway): the live session listings read the store off the loop, one query per batch
Builds on the salvaged yield/light-row change. The live walk still did its store work on the loop
thread: `resolve()` -> `_handle()` hydrated a full row and read admissions per session, and the
close test parsed a ~26 KB receipt per session. With ~900 live (mostly cron) rows each idle TUI
poll cost 0.4-0.5 s of loop CPU and every gateway request waited ~3 s (#141236 comments).

`gateway/session_live_listing.py` now owns the walk for both `session.list` (live) and
`session.active_list`: authorization stays on the loop (in-memory), and per batch of 256 sessions
ONE worker-thread read returns the picker columns, runtime revision/generation, pending admissions
and the receipt target's `ended_at` (SQLite extracts the target, so no receipt is parsed in Python).
A session retired during the read is dropped and never restored. `closed_and_unviewed`'s rule is
shared through `closed_idle_unviewed`, so both paths read the same verdict.

Fixes #141236
2026-10-20 03:08:06 -07:00
686f6c61
11ff2c978c fix(gateway): never SIGTERM the pid of the host that serves this profile
Second blind spot of #141133, past the lifecycle gate: when the host probe
returns None or the control socket does not answer, `_served_by_another_host_gateway()`
and `named_profile_served_by_running_multiplexer()` both say no, `profile_lifecycle()`
stands down, and `_cmd_stop()`'s own guard requires `find_gateway_pids()` to be
empty — but the profile's `gateway.lock` names the host pid, so it is not. The
command fell through to `stop_profile_gateway()`, which read that pid and
SIGTERMed the multiplexer: every served profile offline.

`stop_profile_gateway()` is the last place before the signal, so the refusal
lives there: a pid that belongs to the live host multiplexer is never this
profile's gateway to stop, and the message names the verb that does stop the
host. A home that launched the host itself keeps its normal stop — the guard is
the home comparison, not "the pid is a gateway".

`_mark_planned_stop` moves to `gateway_profile_lifecycle` (re-exported at its
old name) so the 5710-line facade does not grow: the health ratchet only lets
`hermes_cli/gateway.py` go down.

Tests: `tests/hermes_cli/test_gateway_host_stop_refusal.py` — the socket-down
path refuses (red on the parent: the planned-stop marker was written and the
kill reached the host pid), and the owner's own home still stops its gateway.
2026-10-20 03:08:06 -07:00
686f6c61
de7479fbf0 fix(gateway): park a served profile without stopping the host multiplexer
`hermes -p <name> gateway stop` on a profile the host multiplexer serves
stopped the host: every served profile went offline and the next
`hermes gateway status` found a stale `gateway_state.json`.

The host publishes its own pid into the served profile's runtime record
(`profiles/<name>/gateway.lock`), so `find_gateway_pids()` answers with the
host pid. `profile_lifecycle()` treated any pid as a separate `--force`
gateway and stood down, and `_cmd_stop()`'s own guard also requires an empty
`find_gateway_pids()`, so the command fell through to
`stop_profile_gateway()` and terminated the host pid read from that record.

Exclude the pid of the host multiplexer that serves this profile from the
"separate gateway" check. Any other pid is still a separate gateway and
keeps its normal process/service lifecycle, so an explicit `--force` gateway
beside the host is untouched.

Test: a served profile whose runtime record names the host pid parks
instead of reaching `stop_profile_gateway()`, and the profile's own gateway
beside the host still owns its lifecycle.
2026-10-20 03:08:06 -07:00
wkwee
0d60056729 fix(update): charge the Windows relaunch wait to the process being replaced
The Desktop dialog "The update finished, but needs one more step (gateway_restart)" fires on a
false verdict. `_verify_relaunched_gateways_alive` gives a relaunched gateway a single shared
30 s budget computed when the resume starts, but `_spawn_gateway_restart_watcher` only spawns
the replacement once the paused PID is gone. That exit takes 25-35 s of the budget on a busy
update, so the replacement is first seen 6-7 s before the deadline expires or after it - and a
cold gateway then needs >11 s before its control socket answers. Verification raises, the
`gateway_restart` follow-up is committed, the in-run retry 20 s later succeeds, nothing revisits
the verdict, and the desktop replays the stale debt as a manual action at the next boot gate.

Charge that wait to the process being replaced instead of to its successor: a target first seen
late gets its own budget counted from the sighting, and a target the deadline expires on without
ever being seen gets one extra window, because the spawn it is waiting for may not have happened
yet. Both are bounded, so a relaunch that truly never happens still fails closed.

Observed on the reporting host (Windows 11, git checkout, 2026-10-19), restart stage 04:50:30 ->
first `gateway.start` 04:51:03 -> follow-up recorded 04:51:10 (was 18:24:30 / 18:25:00 / 18:25:06
the previous day), retry spawn 04:51:33, "already running" at 04:51:44 while the same run's fleet
matrix reported `pid 20720 @ 5fc490e2 state=current`.
2026-10-20 03:08:06 -07:00
qby
c14952a93f fix(gateway): a reload naming the revision the session holds is not refused
reload.mcp refuses with mcp_servers_unavailable whenever a configured MCP
server is not connected and the call itself applied nothing. That conflates
"this reload's work did not take effect" with "this reload had nothing left
to do": after a gateway restart, startup discovery has already connected
everything it can, so one parked server (an OAuth server waiting for
re-authorization) makes every later reload a refusal — even though the
calling session's policy was already refreshed by its own session.resume.

The TUI poller advances its accepted revision only on `status: reloaded`
(deliberately: a lost revision would never be applied), and polls every 5 s,
so a refusal means it retries the same revision forever. Every retry is a
WARNING, and each one re-reads the config, reconciles, refreshes every cached
agent and attempts a commit: 1,897 refusal lines in 52.6 minutes with three
TUIs attached.

A reload may name `rev`, the revision `config.get mtime` shipped that client.
The gateway accepted the parameter but never read it. It now compares it with
the revision the calling session's committed policy already holds — the same
hash config.get ships, extracted into gateway/session_config.py::mcp_revision
so the two sides cannot drift — and answers the existing success shape when
they match: nothing is left to load, so `unavailable` names the server that is
down and `loaded_rev` lets the client advance. A call that names another
revision, or none, keeps the named refusal: that is a reload which had work to
do and did not apply it.

Tests: tests/gateway/test_mcp_reload_held_revision.py drives the real
reload.mcp over a session (config.get mtime, then reload.mcp) and pins both
halves — the held revision answers reloaded/unavailable/loaded_rev, while the
same call without rev, and with a rev the session does not hold, is still the
mcp_servers_unavailable refusal naming the server.

Refs #141769
2026-10-20 03:08:06 -07:00
qby
2d7f9b5f2a fix(gateway): let the live session listing give the loop a turn, and stop hydrating a row per session
session.list's live lane walks the authority's sessions in one request on the gateway's loop.
Every step was synchronous DB work with no suspension point, so the whole walk ran as one
uninterruptible block: on a 4,049-row store the loop stalled past 10 s, the Telegram adapter's
updater.stop() missed its deadline and the adapter was declared fatal and rebuilt (#141236).

- yield once per LISTING_YIELD_EVERY sessions, in both live listings (session.list,
  session.active_list), so platform I/O, WS dispatch and the adapter stop path interleave
- read the picker's own columns (SessionDB.get_session_list_row) instead of get_session's
  prompt/tool JOIN plus flush_token_counts() per session, here and in closed_and_unviewed
2026-10-20 03:08:06 -07:00
liuhao1024
932b20df09 fix(skills): keep every profile's raw config cache entry across a miss
_load_raw_config() cleared the whole keyed cache on every miss, leaving
one live entry at a time. A multiplexed gateway's skill watcher rotates
through up to ~32 published profile/project scopes plus the ambient one
per pass, so each pass re-read and re-parsed every other profile's
unchanged config.yaml (#141610). A miss now inserts only its own key,
with a 128-entry bound retiring the stale signatures a config's own
edits leave behind.
2026-10-20 03:08:06 -07:00
liuhao1024
ac33a01627 fix(state): walk the message_uid backfill by rowid so TEXT-id legacy stores open
A store converted from JSONL still has `messages.id TEXT` with no PRIMARY KEY:
`_reconcile_columns` adds the declared columns (so `message_uid` exists) but
never rebuilds the key. On that shape `SELECT MAX(id)` returns a str, so
`_advance_message_uid_backfill` raised `TypeError: '<' not supported between
instances of 'int' and 'str'` on every open. The store fell back to JSONL and a
multiplexed profile was parked behind a misleading "session store unusable"
reason.

Even with `high` coerced to int, an `id > ? AND id <= ?` range on a TEXT column
compares lexicographically, so the chunk walk would mint the wrong rows. Key the
walk on `rowid` instead: on the declared table `id INTEGER PRIMARY KEY` is the
rowid alias (identical plan, existing cursors stay valid), and on the legacy
shape rowid is the one integer key the range semantics hold for.

Fixes #141467
2026-10-20 03:08:06 -07:00
kshitijk4poor
ce28ca328d fix(gateway): list sessions compressed before created_source stamping
Symptom: a conversation compressed before write-time created_source
stamping, and not written since, stays out of `hermes sessions list
--source cli` (and tui/gui/acp) and browse. Its root still has a NULL,
'unknown' or 'local' created_source, while its tip carries the real
surface.

Root cause: #140678 stamps a chain's unset ancestors only when the
chain is written again: on the next usage write or compression publish.
A finished conversation never gets that write, so its root stays
hidden.

Change: the owner runs a one-time repair at authority start-up, next to
the legacy owner backfill. In one write transaction it finds each
compression edge with an unset parent and a stamped continuation child
(branch, delegate, reset and tool children are skipped, as in prune),
and stamps that chain through #140678's stamp_compression_ancestors.
The same preferred-continuation and same-surface checks apply, and a
known value is never replaced. Like #140678's write-time stamp, the
repair copies the nearest stamped value onto unset rows, even a wrong
one. A chain with no stamped segment has no surface to copy and is left
as it is.

Guard: the repair is idempotent, so every start runs it without a
marker. On a store with nothing to repair it costs one join query (a
sessions scan probing the parent index) under the write lock. A stamped
child the walk does not follow (a non-preferred sibling, or one with an
inherited fork marker) still matches, and each start re-walks it one
hop.

Why at start-up: the gateway is the only writer of state.db, and a
list-time tip fallback would bring back list cost on legacy stores.
Measured on a synthetic 30k-row store (10k three-row chains, a third of
them legacy): the first start stamps 6668 rows in about 180 ms; later
starts take about 4 ms. The scan grows with the table's size on disk:
about 65 ms with 8 KB of system prompt per row, and the query reads a
real 23k-row store in about 16 ms.

Refs #134889
Refs #139158
Refs #140678
2026-10-20 15:15:42 +05:30
kshitijk4poor
22c9cf36a7 perf(state): the ancestor stamp's unset probe reads only the walked rows
Symptom: on a 30k-row store, every usage write of a stamped compression
child took about 4.8 ms in stamp_compression_ancestors, even when the
chain had nothing left to stamp.

Root cause: the final lookup of _UNSET_ANCESTOR_SQL (the fast path added
in #140678) joins the recursive ``up`` rows to sessions. Without ANALYZE
stats SQLite picks sessions as the outer loop: it scans the whole table
and probes an automatic index on ``up`` for each row.

Change: CROSS JOIN pins ``up`` as the outer loop, so each walked id is a
primary-key lookup. Same rows, same result. Measured on a synthetic
30k-row stamped store: 4822 us -> 22 us per stamped-tip write.

Test: the probe's query plan has no table scan other than ``up``.

Refs #134889
Refs #139158
Refs #140678
2026-10-20 15:15:42 +05:30
kshitijk4poor
26409f994c fix(cli): a classic -w session gets its clean tree back on resume
`hermes -w` (classic, not `--tui -w`) runs its session's tools in the
new worktree: the gateway policy freezes the tree as the session's cwd.
Quit removes a clean tree, and a later `hermes -c` / `--resume` of that
session then had every turn refused `workspace_unavailable`: the owner
refuses a missing directory.

The `--tui -w` resume fix (N8) already recreates a missing tree on
resume, but only one its launcher recorded, and it looked for it in
the session row's cwd. A classic `-w` launcher recorded nothing, and
its row keeps main's stamp, the repo root (e504e030e3, @teknium1,
2026-10-12), not the tree its tools run in.

- The classic launcher passes the profile's state.db to
  `_setup_worktree`, as `--tui -w` does: the tree is recorded for
  resume, and its lock names the store. The row's cwd stays the repo
  root, so a reaped clean classic `-w` tree is not kept; it is
  recreated on resume.
- The resume step reads the session's frozen policy cwd (its local
  receipt; a read) before the row's cwd, since that is the directory
  the owner checks. A store error on that read falls back to the row's
  cwd.

Trees are still removed on quit.

Refs #134889 (CLI-15)
Refs #139158
2026-10-20 15:08:20 +05:30
kshitijk4poor
11d48c7af4 fix(cli): /worktree new's failure lines say what actually happened
Two paths printed "Created worktree but could not enter it" when that
was not the whole story:

- The gateway refused the move (e.g. session_busy). Nothing moved, but
  the fresh tree stayed on disk, unlisted by /worktree, until quit
  removed it. It is now removed right away (an earlier active tree
  stays active), and the refusal carries the check that fired.
- The gateway accepted the move but this process could not chdir into
  the tree. The session's tools do run in the tree, so the tree is now
  the active one, the success lines print, and the warning is the
  existing "could not enter session's working directory" line.

The step lives in a new hermes_cli/cli_commands_worktree.py, since
cli_commands_mixin.py may not grow.

Refs #134889 (CLI-15)
2026-10-20 15:08:20 +05:30
kshitijk4poor
0befbd00d3 fix(cli): a /worktree new session gets its clean tree back on resume
/worktree new now moves the gateway session into the tree, so the
session's policy and rows keep that cwd. Quit still removes a clean
tree, and a later resume (`hermes -c`, `--resume`) then had every turn
refused `workspace_unavailable`: the owner refuses a missing directory.

Record the tree once the gateway accepted the move, with the same
record `hermes --tui -w` writes (N8). The shared resume step already
recreates a recorded tree at the same path before attaching, from its
branch when it survived, so the resumed session runs its turns. Trees
are still removed on quit, so they don't accumulate.

Refs #134889 (CLI-15)
2026-10-20 15:08:20 +05:30
kshitijk4poor
d681773682 fix(cli): move the gateway session into the tree on /worktree new
Symptom: `/worktree new` printed "Terminal and file tools now operate in
the worktree", but the next terminal call still ran in the original
checkout (`pwd` returned the repo root). The agent edited and committed in
the main tree, and the untouched worktree was then removed on exit.

Root cause: since the one-gateway runtime (#106742, merged 2026-10-14) the
tools run in the gateway session, under the cwd and TERMINAL_CWD frozen in
its policy and re-bound every turn. The handler still only chdir'd the CLI
process and set TERMINAL_CWD there, the pre-gateway way of retargeting
in-process tools. The gateway already has the verb for this,
`session.mutate operation=workspace` (Desktop's Move to project), but the
classic CLI never called it.

Change: `/worktree new` now goes through a new
`gateway_session_store.move_cli_workspace`. When the CLI is attached to a
gateway session (`gateway_connection`), it first sends
`session.mutate workspace {cwd: <tree>}`; the owner's projection drops the
session's live terminal (previous commit), so the next terminal call runs
in the tree even after earlier ones ran in the checkout. Then this process
follows (chdir, then TERMINAL_CWD), so a later /new creates its session
from the tree. `workspace` joins the store's generation-fenced operations,
because the owner refuses a policy edit without `expected_generation`.

If the owner refuses (e.g. `session_busy` mid-turn), the command prints
the reason and leaves this process, its TERMINAL_CWD and the
active-worktree marker where they were, so it never claims the tools
moved. A failed chdir now also leaves TERMINAL_CWD and the marker unset
and prints the failure (before, both were set and the success lines
printed anyway). The tree keeps its exit-cleanup registration either way.

Why: one gateway owns the session's policy. The client asks the owner to
change it and adds no client-side cwd state.

Refs #134889 (CLI-15)
2026-10-20 15:08:20 +05:30
kshitijk4poor
640d6afb4c fix(gateway): a workspace move drops the session's live terminal
Symptom: after Move to project (Desktop), or the classic CLI's
/worktree new, a session whose terminal had already run kept running
its commands in the old folder. The policy and the session row moved,
but `pwd` still printed the previous checkout.

Root cause: the workspace projection in `_project_committed`, added in
3cd782be3e ("typed /reasoning and Move to project edit the owner's
frozen policy"), called `cleanup_vm` with the bare session ids. A
turn's terminal environment is keyed by the session's route
(`session:<route>`, qualified per owner), so nothing was dropped and
the cached environment kept its old cwd. The directory the session's
commands recorded (`_session_cwd`) also survived, and the terminal tool
prefers it over the binding's cwd. The move only took effect when the
session had never used its terminal.

Change: a workspace move now runs the teardown a terminal binding
refresh already uses (renamed `drop_session_terminal`, since it is now
shared across modules). It drops the route-keyed and id-keyed
environments and clears the recorded cwd, while a profile-shared
environment stays. Like the refresh, it runs off the owner's event loop
(an ssh or modal teardown takes seconds and would stall every client)
and before the policy is published and the queue scheduled, so no
queued turn starts on the old environment. The teardown is
best-effort: the move is already committed, so a failing teardown is
logged and the policy is still published and the queue scheduled,
rather than leaving the stored cwd ahead of the live one with every
later turn stuck queued.

Test: a gateway-level test runs a terminal command, moves the
workspace through `session.mutate`, and asserts that the next command
runs in the new folder and that a slow teardown does not block the
loop; a teardown that raises still publishes the moved policy. It
fails without this change.

Refs #134889 (CLI-15)
2026-10-20 15:08:20 +05:30
kshitijk4poor
51cfd92ff9 fix(cli): /compress prints the gateway's report and counts only a commit
Symptom: in the classic CLI, a /compress whose summary call fails printed
"✅ Compressed: 8 → 8 messages" with no reason, and the status bar and
/usage counted one more compression, though nothing was compressed.

Root cause: GatewayAgent._compress_context (4a4114ac5a, the classic CLI's
move onto session.mutate compress) threw away the session.mutate result.
That result carries the owner's own report (aborted, refused, fallback,
reason) and status "noop" when nothing was committed. The owner runs its
compressor with abort_on_summary_failure=True, so a failed summary comes
back as "noop" with aborted set. compress_now then rebuilt the report from
the CLI's _CompressorView, which has none of those flags, and the stand-in
added to compression_count on every call.

Change: keep the result's summary on the agent for compress_now, which
uses it in place of a locally derived one. A "noop" answer returns the
input history unchanged: no re-read, no verbatim-tail stamp, no count.

Why: the gateway owns the session and its compressor, so its report is the
only one that knows why a compression did not happen; the client reads it
instead of guessing from a view that cannot see it.
2026-10-20 15:08:00 +05:30
kshitijk4poor
e3fbd32d26 fix(cli): /toolsets reads the gateway session's report
Symptom: classic CLI `/toolsets` on the shared gateway lists only this
process's registry (no MCP or gateway-loaded plugin toolsets), with
the launch flags marked instead of the session's toolsets (#134889
CLI-22).

Root cause: #106742 (5707483e83) gave the gateway a `/toolsets` read
through `slash.exec` (gateway/session_info_reads.py) for Ink and
Desktop. The classic CLI kept its local `show_toolsets`, which calls
`toolsets_lines` in the client process.

Change: `/toolsets` joins the classic CLI's `slash.exec` commands
(`gateway_setting_commands`). The owner's lines are printed as they
come, since that report is already laid out by main's builder.
Off the gateway the local report still runs.

Why: one report on every surface, read where the session's tools live.

Refs #134889 (CLI-22)
2026-10-20 15:05:14 +05:30
kshitijk4poor
2267d3b961 fix(cli): /clear redraws the banner from the new gateway session
Symptom: in the classic CLI on the shared gateway, `/clear` redraws a
banner without the session's MCP tools and shows the full 70-character
`local-<64 hex>` id where the startup banner shows the 8-character
label (#134889 CLI-22).

Root cause: the gateway seams of #106742 (9748e38caa, 7e93de19bd) moved
the startup banner (`show_banner`) onto the gateway session's snapshot
(`banner_inventory`, `session_label`), but the in-app `/clear` path in
`_cmd_clear` kept its own copy of the banner setup and still walked
this process's own registry with `get_tool_definitions`. The CLI
process starts no MCP servers, and the raw session id went straight to
the banner.

Change: the banner setup both paths need (gateway store, the session's
`banner_inventory`, compact-or-full, and the common
`build_welcome_banner` kwargs) moves into one `banner_plan` helper in
cli_info_mixin.py, returning a `BannerPlan` named tuple, used by
`show_banner` and `/clear`. `/clear` renders
a gateway session's snapshot through `_show_gateway_banner`, as startup
does; a gateway session without a snapshot gets the compact banner. The
local registry is walked only off the gateway. `_show_gateway_banner`
no longer sets `_defer_tool_warnings`: that flag is read only off the
gateway, so setting it on this path did nothing.

Why: the gateway owns the session's tools; the client only reads them.
With one shared plan, startup and `/clear` show the same tools and
label and cannot drift apart again.

Refs #134889 (CLI-22)
2026-10-20 15:05:14 +05:30
kshitijk4poor
8215a3eab2 fix(cli): drop archived rows from the snapshot rejoin's history
The rejoin rebuilt the warm history from every stored row, including
the ones compaction archived. Undo and retry compare that view with
the gateway's live rows and refused after restoring a compressed
session. Skip archived rows, as the rollback and resume paths do.
2026-10-20 15:03:19 +05:30
kshitijk4poor
73506be8bd fix(cli): park a secondary profile during the snapshot handoff
Unserving a secondary profile wrote no parked marker, so the host's
periodic rescan could serve it again between the unserve and the
restore, and the restore then refused with an ownership conflict.
Touch gateway.parked before the unserve, as "gateway stop" does, and
drop it before serving the profile again on every exit path. A profile
the user had already parked stays parked and is not served again.
2026-10-20 15:03:19 +05:30
kshitijk4poor
fcbacdea6b fix(cli): re-supply the launch key on the snapshot rejoin's new connection
Since 7209c7accf (David Dudok de Wit, 2026-10-17, "re-supply the launch key
when the classic CLI resumes a session"), the session store's attach
resumes through GatewayConnection.resume, which re-supplies the CLI's
launch-only key (--api-key or a keyed startup alias) because an owner
restart revokes it. The snapshot handoff relaunches or re-serves the owner
and then rejoins on a fresh GatewayConnection.shared(), which starts with no
key, so a keyed CLI's restored session lost its credential.

Carry launch_api_key from the drained connection to the new one before the
rejoin. The guard table now checks that the key survives every drained case.
2026-10-20 15:03:19 +05:30
kshitijk4poor
c1152fb53a fix(gateway): keep a terminal's systemd markers out of the unmanaged daemon
A shell started under a systemd service (gnome-terminal-server.service, a
user unit) carries INVOCATION_ID and JOURNAL_STREAM. spawn_unmanaged_gateway
copied them into the daemon a chat auto-starts, so the gateway reported its
launch supervisor as systemd and /snapshot restore refused it with "stop its
systemd unit", naming a unit that does not exist. Strip both, as the update
resume spawn already does; a real unit's gateway is launched by the unit,
not by this spawn.
2026-10-20 15:03:19 +05:30
kshitijk4poor
d5356b76d0 refactor(gateway): make the profile lifecycle ack helpers public
cli_snapshot imported _confirmed and _failure from
gateway_profile_lifecycle across modules. Rename them to ack_confirmed and
ack_failure, as pause_acked and manual_gateway_identity were made public
for the same sharing. No behaviour change.
2026-10-20 15:03:19 +05:30
kshitijk4poor
54c23c88f9 fix(cli): report a corrupt snapshot manifest instead of raising
A snapshot whose manifest.json is not valid JSON raised JSONDecodeError
out of the /snapshot restore handler after the gateway had already been
drained. Catch ValueError with the other restore failures so the reply is
"not fully restored" with the error, and the rejoin still runs.
2026-10-20 15:03:19 +05:30
kshitijk4poor
7a9e1ed4f4 fix(cli): keep the offline snapshot restore for a remote gateway's chat
On main, /snapshot restore in a chat attached to a remote gateway restores
this host's own snapshot offline under its exclusive_maintenance gate, keeps
the remote connection open and prints the restart hint. The gateway handoff
refused every remote chat with "Snapshot restore needs the local gateway",
although the snapshots /snapshot list shows are this host's and the remote
gateway's state is not on this host.

Take the handoff only for a local gateway chat; a remote chat takes main's
offline path again, and its session store is never closed.
2026-10-20 15:03:19 +05:30
kshitijk4poor
e9f3ef7ad5 fix(cli): hand the CLI lease over while the snapshot rejoin re-imports a row
A snapshot taken before the gateway imported a legacy (pre-authority)
session removes that import when it is restored, so the rejoin's
session.resume has to adopt the row again. The gateway imports under the
active-session registry lock and refuses with runtime_coordination_required
while any live lease holds the id, and _rejoin_cli attached while the
interactive CLI still held its own lease: the files were restored but the
chat could not reconnect.

The startup attach in _ensure_gateway_session already released the lease
around the attach and re-claimed it for the returned id. Move that handoff
into one lease_handed_over() context manager, used by both, that also
re-claims the unchanged id when the attach raises.

The live restore test gains a case with a real lease and a legacy row the
snapshot predates; it fails with runtime_coordination_required without the
handoff.
2026-10-20 15:03:19 +05:30
kshitijk4poor
c08ee526be refactor(cli): import the lifecycle ack helpers once in snapshot restore
cli_snapshot imported the private _confirmed (and _failure) helpers from
gateway_profile_lifecycle function-locally in two places. That module
only imports hermes_constants and hermes_cli.profiles, so there is no
cycle to dodge: import both once at module top.

_pause_owner also re-tested `control_home != home` to pick the retry
hint after already branching on it; compute `satellite` once and reuse
it. No behaviour change.
2026-10-20 15:03:19 +05:30
kshitijk4poor
3a50aa9094 fix(cli): tell a secondary profile to park itself, not stop the host gateway
When the host refuses to unserve a multiplexed secondary profile, the
refusal said "Stop the gateway and retry". That takes down every profile
the host serves, which contradicts the documented behaviour of this
restore (a secondary profile is re-served without restarting the others).
On the satellite branch, point at `hermes -p <name> gateway stop` (park
just this profile) instead; the launch-profile text is unchanged.

The guard table's unserve-error row now asserts the park hint.
2026-10-20 15:03:19 +05:30
kshitijk4poor
942f2900cc refactor(cli): share the pause-ack check between snapshot restore and data cleanup
The snapshot handoff re-implemented the data-cleanup drain's acceptance
test for a pause reply (`pausing`/`already_stopping` from the same pid the
identify call returned). Extract `pause_acked(response, identity)` next to
`manual_gateway_identity` and call it from both sites so the two drains
cannot drift apart. Behaviour is unchanged; each caller keeps its own
pause timeout.
2026-10-20 15:03:19 +05:30
kshitijk4poor
1c4b47a020 fix(cli): refuse an unserve ack that carries an error before the restore
The satellite handoff judged the host's unserve reply by hand
(`unserved == name or pending`) and ignored an `error` field, so a reply
like `{"unserved": name, "error": ...}` let the offline restore proceed
while the host still reported a failed teardown. Use the canonical
`_confirmed(ack, "unserved", name)` check that `hermes -p <name> gateway
stop` applies to the same request (and that the re-serve half of this
handoff already uses); a `pending` reply is still accepted only without
an error, and wait_profile_unowned still gates the restore.

Adds one row to the guard table: an unserve ack with an error is refused
and nothing is restored (fails before this change).
2026-10-20 15:03:19 +05:30
kshitijk4poor
61b88bfbd0 test(cli): trim CLI-16 snapshot restore tests to the salvage bar
Keep two live cases that drive a real gateway daemon (standalone owner,
resume-restored; multiplexed satellite, create-missing): they exercise the
whole handoff, the SQLite handle release and the rejoin, and caught every
teardown mutation. They now also assert the success reply, and that the
gateway process view (`/agents`, `/stop`, status bar) is re-bound to the
new connection (bind_session after the restore).

Replace the 10 parametrized guard cases with one table test over the new
follow-up behaviour: the restore's own result or error decides the reply
when the rejoin fails, a supervised owner is refused before the viewer is
torn down, an unconfirmed satellite re-serve is shown to the user, and an
invalid id never drains the gateway (negative control for the shared
quick_snapshot_dir pre-check; main gives the same reply); a pause ack from
a different pid is refused.
2026-10-20 15:03:19 +05:30
kshitijk4poor
1442477c56 refactor(backup): share quick-snapshot id validation with the CLI pre-check
`_local_snapshot_exists` in cli_snapshot copied the snapshot-id checks of
`_restore_quick_snapshot_exclusive` (separator/traversal rejection,
containment, manifest) and imported the private `_quick_snapshot_root`.
The two copies could drift, letting the pre-check accept an id the restore
then refuses after the gateway was already drained.

Move those checks, unchanged, into a public `quick_snapshot_dir(id, home)`
in backup.py that returns the snapshot directory or None; the restore and
the CLI pre-check both use it. Invalid or missing ids still never drain
the gateway.
2026-10-20 15:03:19 +05:30
kshitijk4poor
23cf772f8d fix(cli): refuse a supervised gateway before the snapshot handoff
`/snapshot restore` drained a standalone owner with `pause-for-update`,
whose handler restarts via the service manager. Under launchd, systemd or
Desktop the supervisor relaunches the gateway, it takes the lock back, and
the CLI waited the full 60 s in wait_profile_unowned before failing (plus
a reconnect).

Reuse main's guard from the data-wipe drain instead of copying it: the
identity/supervisor check in data_cleanup_holders._drain_manual_gateway is
extracted, unchanged, into `manual_gateway_identity(home)`, which both
callers now use. The restore runs it up front, before closing the reader
or the connection, and refuses a non-manual owner with the same "stop its
unit/LaunchAgent/desktop app" hint. Like the data-wipe drain, the pause ack
must name the identified pid, and `already_stopping` is accepted.
2026-10-20 15:03:19 +05:30