Review of #144840 (F1): /new, /resume and /branch detached the conversation a chat moved past, but
the compression-exhaustion auto-reset (reset_and_rehome_messages) and a CLI /handoff rotated the
route without it, so the app's next prompt on the old conversation ran in the new one and its reply
reached the chat.
The session store now announces each conversation a route comes to name (reset_session,
switch_session, a get_or_create transition: SessionStore.route_named), and the owner wires that once
(session_detached.watch_routes) to the owning authority's name_lane, on its loop, ahead of the
writer's own resumption. The per-command _name_lane calls are gone. The exhaustion reset's fresh
session takes the chat's source as it was, not the old conversation's detached one.
Teknium's ruling: "I dont want to lock out desktop / mobile app users from a session. Please just
make it so that telegram doesn't get responses from A if they are on a /new'd convo".
When a messaging chat names another conversation (/new, /resume, /branch, a handoff, its next
inbound), every other live session on its route used to go read-only (session_superseded, cold
mounts since 7ba53f4756, handed-off chats since #144708, warm views in this PR's first commit).
Now they DETACH instead (gateway/session_detached.py): the live session moves off the chat's route
onto a key naming the conversation (agent:<ns>:detached:<sid>), pinned on a copy of its source
(SessionSource.detached_route, wire-invisible). Its turns then run on the ordinary messaging path:
- build_session_key answers the pinned key, so the running slot, agent cache, busy guard and the
agent a Stop reaches are the conversation's own, never the chat's;
- SessionStore.get_or_create_session resolves it to the conversation itself (its compression tip),
never creating or persisting a route;
- _delivery_adapter_for answers the profile's LocalSessionAdapter, the local sessions' delivery:
sends publish nothing, viewers read the canonical event stream (local_viewer_turn covers it, so
status, notices and approvals go there too). session_local_recovery.local_adapter creates it on
first use, since a messaging-only gateway has none until a local session restores.
The key has no platform slot, so a key parser (_parse_session_key) finds no chat to deliver to.
The chat naming the conversation again (/resume) moves it back onto its route (name_lane), and
its next turn delivers to the chat again. A cold open of a row the lane moved past mounts detached.
/new, /resume and /branch name the lane at once (_name_lane), not at the chat's next message, and
_publish_route does on every publish, so a warm view detaches the moment its chat moves on.
History mounts keep their own read-only gate (require_history_access). LiveSession.superseded,
history_mount and handed_off are gone (with route_recovery.mount/moved_local, which only fed them);
LiveSession.detached says what it means.
Review follow-up. An id entered _rows_pending before a save that can raise, and the fresh-route
path only cleared it inside _finish_route_transition, so a failed save left the id pending for
good and _is_session_ended_in_db would never call that row ended again. Every publisher now
clears its own id in a finally (get_or_create's create path, reset_session, switch_session),
_replace_route_locked marks the id only after its save returns, and the create kwargs are
computed before the entry is published. The test uses tests.waiting.async_wait_until.
SessionStore publishes a route transition in two halves: the new entry under _lock, then the
state.db row (insert for /new and a fresh route, reopen for /resume) after releasing it. Anything
that resolved the route in between saw the named conversation's row missing or still ended and
took the #54878 stale-route self-heal: drop the entry and recover the newest open row, which is
the conversation the user just left. A Desktop/Webapp turn finishing on a chat's previous
conversation does exactly that (its post-turn bookkeeping calls get_or_create_session), so after
/new the chat's route named A again and its next message could land there.
The store now remembers the ids it published whose row is not live yet, and
_is_session_ended_in_db does not call those ended. Every reader of that check (the routing
self-heal, the reaped-run eviction, the cached-agent liveness check) gets the fix.
A remote viewer of a Desktop session disconnected mid-turn, and the conversation was stuck
for good (#140642). Three links, all reproduced on main through the real SessionStore,
authority and SQLite:
1. The viewer's ws-orphan reaper (tui_gateway _finalize_session) stamped the row
`ws_orphan_reap` while the owning gateway still ran its admitted turn. The stamp now
shares one write txn with a check of the canonical ledger (session_admissions /
worker_executions under the physical id, the key and the local logical id), and a
busy ledger keeps the row open (agent.close() is told not to end it either).
2. The SessionStore's #54878 stale-route self-heal treated that stamped local row as stale,
minted a replacement id and inserted its row, then the authority refused its peer record
(`admission_conflict`). A local route the authority holds by receipt is never stale now:
only the authority advances it, and its first admitted turn reopens a stamped row
(reopen_local_session).
3. The restart prune repointed sessions.json at that empty, never-admitted row. For a
receipt-held local route the prune now keeps the route, or follows the receipt's own
target (a compression child), never a peer row. Installs already wedged heal on the next
resume: restore_local_session drops a route entry naming an empty, never-admitted row
outside the receipt's lineage, instead of answering `admission_conflict` forever.
Tests: tests/gateway/test_local_route_orphan_reap_stamp.py (3) and
tests/tui_gateway/test_reap_respects_canonical_ledger.py (5), red on main.
Refs #140642
Refs #134889 (RT-43)
Refs #140719
Main made the strict ruff config the default (`ruff check .`, blocking), and
the branch's code carried 278 findings under it (main itself is clean). Fixed:
- PLW1510 (86): `check=False` on each subprocess.run, preserving behaviour,
as main's own sweep (0006a5e229) did.
- ASYNC220 (9, test fixtures only): `noqa` with the reason, main's convention
for a Popen that returns at once and whose handle the test drives.
- ruff's safe autofixes plus the narrow unsafe ones (UP006/UP037/RUF100/RUF013/
PLR0402/RUF059 underscore renames/UP031/UP041/UP017/FURB167/PIE807/RUF007/
RUF015/RUF022/FURB162), and by hand: four %-formats to f-strings, three
unused unpacked names, one fixture loop over `.items()`.
No behaviour change. `ruff check .` passes; scripts/check passes; the 412 test
files mirroring every edited file pass (3 tests/pm files that fail only under
that batch's uv lookup pass solo, before and after this commit).
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
(cherry picked from commit 7091436b76e7dd51f2d350b2780fda231103eac6)
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
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).
90219bdb40e5 restores the persisted routing value, OFF included, before the frozen `--yolo` launch
policy can seed. That fixed a revived revocation. But `SessionEntry.yolo` defaulted to False, and
every entry nobody toggled stores False: branch, reset, legacy migration, cron, new sessions,
every pre-upgrade row, and the /new boundary funnel (which wrote False). All of those now read as
"owner turned it off". So a `--yolo` launch was lost after an owner restart, on /branch, and after
/new. That breaks `apply_launch_yolo`'s "seeded once per session boundary" contract. It fails safe
(approvals are asked again), but it is a behaviour change.
`SessionEntry.yolo` is now Optional[bool]:
- True/False = an explicit /yolo toggle. An explicit OFF still beats a `--yolo` launch across
restarts, so an owner /yolo OFF is never revived.
- None = nobody toggled it, so the launch policy applies. `restore_gateway_yolo(key, None,
launch=...)` seeds it through `apply_launch_yolo` (once per boundary).
- The boundary funnel resets the toggle to None instead of False.
- `create_local_session` no longer copies the launch policy into the toggle.
Wire format: `yolo_toggle` carries the tri-state. `yolo` keeps its old meaning (True only when
ON), so older readers see the same value. Rows without `yolo_toggle` (written before this change)
map ON to True and False to None. False was the default for "never toggled" there, and it followed
the launch policy before 90219bdb40e5.
Tests (tests/gateway/test_yolo_launch_tristate.py, dA2's probes):
- An untoggled entry keeps launch yolo in a fresh interpreter, while an explicit OFF stays off.
- Launch yolo is re-seeded after a real `_clear_session_boundary_security_state`, but not after a
plain owner OFF.
Both fail on r5-picked. His test_yolo_restart_revocation, test_yolo_command, tools/test_approval_yolo,
managed-worker flags and busy-controls tests stay green.
Follow-up to 90219bdb40e5 (#135061)
Review: https://github.com/NousResearch/hermes-agent/pull/135061
Storage modules imported gateway/ to compute their own identities:
hermes_state_runtime -> gateway.session_admission (module level, so importing
any canonical-store module loaded the gateway package), and function-level
hermes_state_worker_compression -> gateway.session_admission,
hermes_state_local_lineage / hermes_state_mutation_branch ->
gateway.session_local_recovery.local_identity (a module that itself imports
gateway.session/config), hermes_state_mutation_branch ->
SessionStore._profile_from_session_key, hermes_state_profile_repair ->
gateway.session.profile_from_session_key_namespace. The gateway imports the
store, so each edge is a latent import cycle.
New stdlib-only hermes_state_keys holds the pure helpers (admission_fingerprint,
local_identity, profile_from_session_key_namespace, profile_from_session_key).
The gateway modules re-export the same objects under their historical names
(SessionStore._profile_from_session_key delegates), so every gateway caller and
test is unchanged. The branch mutation still late-imports the gateway routing
types it publishes (SessionEntry/SessionSource/build_session_key), now with
the reason stated.
Red/green: test_storage_import_boundary asserts importing the runtime storage
modules loads no gateway module; on the parent it reports
['gateway', 'gateway.session_admission'].
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5456384314
Brings #134209 onboarding (setup chat, /initiate-setup, setup_choose/start_chat cards) and
889eddcd86 (/yolo survives a gateway restart).
Conflicts (6):
- gateway/run_turn.py, tui_gateway/server.py: the branch moved these blocks into siblings;
main's edits ported there (run_turn_prepare: first-contact `message`/setup_command, the
_restore_session_yolo call after _hmwa_open_session; agent_factory: coding_selection
session-platform toolsets, setup_choose/start_chat lifecycle tools; session_registry:
_lazy_resume_info default route).
- tests/gateway/test_yolo_command.py: both tests kept.
- Desktop composer submit / slash / wiring: main's parked-card answering and submitWhileBusy
with the branch's busy-input policy in its steer branch; slash `hidden` folds into the
prepared-submission journal; wiring keeps main's onboarding chain without the removed pool.
Semantic fixes:
- gateway/session_busy_controls.yolo_config writes main's persisted SessionEntry.yolo before
the live flag, so an owner `/yolo` OFF is not revived by _restore_session_yolo next turn
(new test test_owner_yolo_off_is_not_revived_by_the_persisted_restore).
- wiring runKickoffSlash awaits the branch's Promise<boolean> slash dispatcher.
- de/es/fr/ja/zh-hant: translate the branch's composer keys main's overlay-completeness test
now requires.
/yolo on a messaging platform only flipped tools.approval's in-memory
set, so any gateway restart (hermes update, crash, systemd restart,
Desktop reopen) silently put the chat back on manual approvals while
the user still believed YOLO was on.
The flag now lives on the chat's routing entry (SessionEntry.yolo,
persisted in gateway_routing like the /model override). /yolo writes it
before flipping the live flag, materializing the entry for a
first-message toggle; every turn re-arms the live flag from the entry it
already resolved; switch_session carries it across compression-tip and
binding repoints; the conversation-boundary security funnel (/new,
/resume, /branch, auto-reset) clears the persisted copy with the
in-memory one so a restart can never revive a bypass the user dropped.
Also corrects the security docs, which still claimed /yolo sets
HERMES_YOLO_MODE.
With the discord toolset loaded, a typed turn rendered the per-turn
triggering-message line and keyed the agent cache on message_id presence,
while slash, /thread and voice turns (no triggering message) did not, so
the pinned session-context prompt re-rendered on every switch between
them. The line is now static and the presence bit is out of the key; the
real id still rides the user message when there is one.
Reported by teknium1 in the #132758 review; fix shape from andrexibiza's #132758.
Co-authored-by: Andrex Ibiza, MBA <andrexibiza@gmail.com>
(cherry picked from commit 2a3f04a67d1aa6dc43628ce0959ddb699baa84f8)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule
The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:
- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
names, restored dead definitions) and the three re-export stub modules
(gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
`plugins.allow_deprecated_imports` escape hatch
An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.
hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).
In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.
* chore: retrigger CI (zero-job startup_failure phantom)
* test: drop resolution allowlist rows for the two deleted which() sites
hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
gateway/session.py is the SessionStore facade assembled from session_*
mixins; new behaviour belongs in a topical sibling, not the facade.
PROMPT_PIN_VERSION, sanitize_prompt_pin and get/set_prompt_pin move
verbatim to gateway/session_prompt_pin.py (SessionPromptPinMixin).
SessionEntry keeps only the field and its (de)serialization; the agent
cache imports the schema from the defining module. No behaviour change.
The persisted pin carried rendered session-context bytes but not the
privacy.redact_pii they were rendered under. After a restart, the first
internal event restored and reused them verbatim, so bytes rendered with
redaction off reached the model after redaction was switched on. Base
re-rendered under the current setting after a restart.
The pin now records redact_pii (the in-memory ephemeral_pin becomes
(change_key, text, redact_pii); the durable schema requires the flag).
Bytes from a different policy are never reused, including by internal
events in the same process, which had the same bypass until the next
human turn.
Simplified on the way:
- sanitize_prompt_pin is the one validator; the snapshot builder and
rehydrate no longer re-check the shape by hand, and use
PROMPT_PIN_VERSION instead of a literal.
- Rehydrate runs once, from the context path, and only when this process
holds no pins for the key (a restart). Eviction clears only the context
pin, so an evicted agent still re-renders instead of reviving the
snapshot. The channel path no longer rehydrates or takes a session id.
- _persist_prompt_pins drops its synchronous get_prompt_pin pre-check,
which took the store lock on the event loop; set_prompt_pin already
no-ops an unchanged snapshot. Its call-count test goes with it.
- set_prompt_pin builds its candidate with dataclasses.replace like
set_model_override, and no longer accepts None (no caller cleared).
- The read-fence test folds into the restart/reset test.
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).
DELETE /api/sessions/<id> removed only the state.db rows: the durable
channel->session routing index (gateway_routing table + sessions.json
mirror) survived, so the next Discord/Telegram message routed to the SAME
id and resurrected the deleted row, and the on-disk .json/.jsonl
transcripts plus request_dump files were never scrubbed because
sessions_dir was not passed to delete_session (#42422).
- SessionStore.remove_by_session_id: drop every entry pointing at the id
(one channel can hold several) and persist the drop to both durable
copies; the index is written back by the gateway process, so removing
only DB rows elsewhere is undone by the next whole-index save.
- The API delete handler now passes the request-scoped sessions_dir and
clears the routing entries through the runner's SessionStore.
- Deletes made out of the gateway process self-heal at routing time via the
stale-route guard once a missing row counts as ended.
Fixes https://github.com/NousResearch/hermes-agent/issues/42422
_slack_tools_loaded/_discord_tools_loaded run per turn via _ephemeral_change_key and
_get_platform_tools only reads the config, so the deepcopy in load_config() is pure
overhead on the event loop. Use load_config_readonly().
Partial salvage of #117993: kept the two gateway/session.py hunks, dropped
TestCapabilityProbeConfigLoader because it monkeypatched cfg.load_config to raise —
a change-detector on the symbol read, not an invariant.
(cherry picked from commit a487903180090c5a2fccd4749b05d302cf2740b1)
Eight secret readers wrapped the scoped get_secret() call in a broad
except Exception / contextlib.suppress and fell through to os.environ.
Under multiplex that env holds the default profile's value, so a bound
scope whose resolution fails silently borrowed another profile's
credential: the pairing allowlist reader could then persist the foreign
list into the served profile's .env, and the proxy key, tool gateway
token, OpenRouter and aux provider keys, ElevenLabs key, and Slack token
probe had the same shape.
Keep the deliberate UnscopedSecretError -> os.environ fallback (the
unscoped default-profile path legitimately reads its own env) and let
every other scoped-read failure propagate; the two availability probes
fail closed instead. config._scoped_environ_get now propagates as its
docstring already claimed.
SessionStore.switch_session re-points a session key at another session id
for non-boundary reasons too (async-delegation re-pin, compression-tip
binding heal, CLI handoff, /branch), but _replace_route_locked built the
new SessionEntry without model_override, so the user's /model pin silently
reset to None on every such re-point (#119864).
Scoped to switch_session's kwargs, not the shared helper: reset_session
(/new) uses the same helper and is a deliberate boundary (30e947e0a0) that
must keep dropping the persisted pin, or the next turn's
_rehydrate_session_model_override resurrects it.
Salvaged from #119868 (moved from _replace_route_locked into switch_session).
Resolved toward the branch: PM provisions uv/python (main's install.ps1 uv-shim
salvage + its test and workflow steps dropped), the shim re-exec stays retired,
package.json carries no electron-builder block (afterExtract identity stamp wired
into electron-builder.config.cjs instead; after-pack.mjs keeps signing only),
Desktop workspace-deps helpers stay retired. Main's scratch-dir bootstrap
(export_scratch_tmp_env) is taken and re-run after profile resolution.
After a restart the routing index rebuilt every lane from `SessionEntry.origin`,
which carries the runtime profile (key namespace) but not the bot that received
the conversation. Delivery then fell to `_is_shared_bot_satellite`: a lane owned
by a secondary bot whose runtime profile is ALSO a satellite of the default bot
was handed to the default bot, and authorization read the wrong allowlist.
- `SessionEntry.transport_profile` (routing JSON) + nullable
`sessions.transport_profile` (SCHEMA_SQL, reconciled by the existing column
path; `agent:main` keys untouched, standalone gateways write nothing). Stamped
from the pinned `RoutingIdentity` at create, reset/switch, DB recovery and
every peer refresh; compression forks inherit it like the other routing columns.
- `session_identity.restore_identity()` re-pins a `RoutingIdentity(transport=None)`
from the persisted transport profile; `authz_mixin._restored_source(entry)` is
the one seam every revive path uses (auto-resume, heartbeat restore, plugin
injection, background-process events).
- `_adapter_for_source` / `_adapter_profile_for_source` honour a restored identity:
the persisted bot's adapter or None — never the default bot by heuristic.
Entries written before the column exist keep the old chain.
Phase 5 of #88715.
- 15 `MERGE-CHECK:` conflict-resolution comments removed from prod code (two were
TODOs already done: the utf-8-sig sessions.json read lives in session_persistence,
the pm-aware cron script helpers in scheduler_script).
- 49 imports the branch left unused (ruff F401, none present at the merge base,
none inside PLUGIN-COMPAT blocks). update_cmd's frozen-surface re-exports are
trimmed to the names tests/compat/old_updater_surface.json actually lists under
hermes_cli.update_cmd; the rest resolve through hermes_cli.main.__getattr__.
- tools/environments/local_gitbash_probe.py: nothing imported it once _find_bash
delegated to pm.shell().
- Three try/except wrappers around calls that cannot raise (install_truststore,
get_hermes_home, and a duplicated except clause in supermemory).
When the session FTS (full-text search) index rebuild fails, the
gateway previously entered a cooldown and then permanently stopped
retrying once the cooldown expired, leaving search silently broken
for the rest of the process lifetime. This adds a proper retry after
the cooldown window elapses, and escalates to ERROR-level logging
(previously missing 'import logging' meant this path could not even
log the failure) so repeated rebuild failures are visible to
operators instead of being swallowed.
Related but out of scope: while testing the fallback paths we
observed that the JSONL transcript fallback writer can write zero
bytes when the primary DB write path fails partway through - flagging
this for maintainers as a separate follow-up, not fixed here.
Fixes#114266
The non-compression branch of _resolve_async_delegation_session awaited the
spawning-session row lookup and then unconditionally called switch_session(),
so a run invalidated (/stop) or a route replaced (/new, /resume) while the
lookup was pending was overwritten by the stale completion's pin.
- Snapshot the routing key's run generation before the await and re-check it
before mutating the route; invalidated -> drop the injection, route untouched.
- switch_session(expected_session_id=...) turns the /resume primitive into a
CAS for this caller, mirroring advance_compression_session: a route that
moved past the snapshot wins over the late completion.
- _current_session_run_generation extracted from _is_session_run_current.
Slimmer redo of #113692 (@KoNit-K) and #113716 (@wangtaotaotao95): same
direction, without the second routing-authority lock and authorize callbacks.
Fixes#113690
Co-authored-by: KoNit-K <konit.block@protonmail.com>
Co-authored-by: wangtaotaotao95 <wangtaotaotao95@users.noreply.github.com>
Reconcile plugin declarations and validation through PM's atomic generation publication; preserve external runtimes, target markers, and conflict refusal. Keep one source-update completion owner and port upstream lifecycle changes to the PM desktop/runtime paths.
`hermes profile delete` removes the profile directory and tears its runtime down, but the name is
also baked into durable identity the delete path never touches — `agent:<name>:*` routing keys,
`gateway_heartbeats.profile` and `delivery_obligations`. An inbound event on a chat keyed to the
dead name then enters the routing index, resolves a profile whose directory is gone, and logs
`Profile '<name>' does not exist` on every event for the life of the store (the #111926 flood,
reached from a *deleted* rather than a renamed profile). The delete side is now symmetric with the
rename rekey (`rekey_profile_state` / `rekey_profile_routing` / `migrate-profile-identity`), with
the same ownership rule:
- `SessionDB.purge_profile_state(name)` — the mirror of `rekey_profile_state`, in one
`_execute_write` transaction. Routing keys, heartbeat rows and the telegram topic rows the rekey
also owns are hard-deleted (a binding is matched by `profile_name` OR its `session_key`
namespace, because the rename rewrites both); `delivery_obligations` rows are terminalized
(`state='abandoned'`) rather than dropped, so pending delivery state is not lost silently.
- `SessionStore.purge_profile_routing(name)` — the mirror of `rekey_profile_routing`: drops the
in-memory entries and persists the drop. Mandatory, not belt-and-braces — the owning process
writes its in-memory copy back, so a durable delete made elsewhere is undone by its next save.
- A delete-only control verb `purge-profile-identity`, deliberately NOT inside
`_unserve_profile()`: that hook also unserves a rename's old name, whose identity the rekey still
has to migrate. `hermes profile delete` requires the owner's `{"ok": true}` answer and reports a
partial settlement (naming the retry) instead of a clean success.
- The retry is the new `hermes profile purge-identity <name>`. It refuses a name that is a live
profile again: the purge keys off the name alone, so `delete foo` (settlement pending) →
`create foo` → `purge-identity foo` would otherwise delete the NEW incarnation's identity. The
delete path tombstones the directory before it purges, so the guard never blocks the delete.
- `sessions` rows are not deleted by the purge: it settles identity, not history. What a delete
leaves of a profile's conversation record is `delete_profile`'s business — it removes the
profile's own home, `state.db` included.
Tests (`scripts/run_tests.sh`, red on base → green): `tests/hermes_state/test_purge_profile_state.py`,
`tests/gateway/test_purge_profile_routing.py`, `tests/gateway/test_profile_identity_purge.py`,
`tests/hermes_cli/test_profile_identity_purge_cmd.py` and `TestDeleteProfile` in
`tests/hermes_cli/test_profiles.py` — 95 passed, 0 failed across those five files.
Renaming a profile moved profiles/<old>/ to profiles/<new>/, so the row DATA
travelled with the directory, but the profile name is also baked into
keys/values the move left untouched: session keys (agent:<old>:* namespace),
sessions.profile_name (fail-closed owner ladder / Desktop sidebar scope /
@session: deep links), sessions.origin_json.profile,
gateway_heartbeats.profile, delivery_obligations (session_key +
adapter_profile), telegram_dm_topic_* profile_name bindings, and the
gateway_routing index. Left stale, every inbound event on a chat keyed to the
old name resolved to a profile that no longer exists — flooding errors.log
with "Profile <old> does not exist ... falling back to global HERMES_HOME"
every few seconds — and renamed sessions dropped out of the sidebar / broke
their deep links.
The routing index is held in memory by a live multiplexer and written back
periodically, so a CLI-side DB rewrite alone is clobbered. Fix in layers:
- SessionDB.rekey_profile_state: atomic durable rewrite of the state.db
tables, matching the agent:<name>: namespace by exact prefix (substr, not
LIKE — '_' is a legal profile-name character and a LIKE wildcard), rewriting
the profile inside routing/origin JSON, and REFUSING on a target collision
(routing rows or telegram bindings) instead of silently merging.
- SessionStore.rekey_profile_routing: rekey the in-memory routing index
(keys + origin.profile) then persist — the half a DB write cannot reach.
Raises on a target-key collision before mutating.
- Control verb migrate-profile-identity (params-carrying; the socket passes
params only to handlers that declare them, bare handlers unchanged) so a
live gateway rekeys its in-memory copy AND both durable stores (routing home
+ the renamed profile's own state.db).
- rename_profile calls the verb when a multiplexer is live and, if it fails,
does NOT fall back to a racing CLI-side write: it prints a warning telling
the operator to restart the gateway and retry. With no live gateway it
performs the durable rewrite itself (safe: nothing else holds the store
open).
Checkpoints keyed by the profile's workdir path are a known related gap,
tracked separately, not addressed here.
Tests: rekey_profile_state (all tables, routing/origin JSON, collisions,
idempotent, no-op), rekey_profile_routing (namespace + origin, no-op, no
overwrite), control verb param passing, and rename end-to-end for both the
live-gateway (delegates, refuses unsafe fallback) and no-gateway (durable
rewrite) paths.