76901 Commits

Author SHA1 Message Date
Teknium
30db18aaad test(release): admission contract test forwards to the selected HERMES_PYTHON
Some checks are pending
Deploy Site / deploy-vercel (push) Waiting to run
Deploy Site / deploy-docs (push) Waiting to run
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Waiting to run
auto-fix lint issues & formatting / Apply patch (push) Blocked by required conditions
The counting wrapper exec'd a bare `python`, so a contributor who selects an
interpreter only through HERMES_PYTHON would fail before the cache is reached.
Forward to the same interpreter the other channel tests use, shell-quoted.
2026-11-26 00:11:23 -08:00
Teknium
9ea477a027 fix(release): validate an admitted channel request once per process
channelBuildRequest re-ran the authoritative Python validator (a fresh
interpreter importing hermes_cli.release_channels and
scripts.bundles.desktop_prepare) on every call, including repeated calls with
byte-identical request JSON. verifyBundleStamp admits the channel request on
each call, so the tests-js "channel smoke binds the complete admitted request"
test started 59 Python interpreters; on a loaded runner that alone passed its
15 s budget (CI run 45707403899: 17.2 s, timed out on a PR with no JS changes).

Remember the exact (interpreter, request bytes) pairs the validator accepted
in this process and skip only those repeats. Rejections are never cached, and
every distinct request (and every fresh CLI process) is still validated.

Measured locally, tests-js/bundle-smoke-metadata.test.mjs, channel smoke test:
  idle:                         3426 ms -> 811 ms
  taskset -c 0 + 4 cpu0 spinners: 16705-18642 ms (timeout) -> 3708 ms

The new contract test proves one validator run per distinct accepted request
and one per rejected attempt; it fails on the base (2 runs for 2 identical
admissions).
2026-11-26 00:11:23 -08:00
Teknium
5d3c913320 fix(sessions): deleting or expiring a session drops its held routes too
A held route (its platform's plugin not registered yet) is written back by
every full routing save, but remove_by_session_id, release_route, the
stale-entry prune, routing expiry and canonical-delete retirement only
looked at the live index. Deleting session S left S's held row in memory and
in sessions.json/state.db; with a live and a held route for S only the live
one went. One helper now finds a session's live and held keys (deduped) and
one drops a key from both, so a shadowed held copy cannot reappear either;
an idle held row expires on the same clock as a live one.
2026-11-26 00:08:24 -08:00
Teknium
fd312a3682 fix(sessions): a recovered DB load compares held rows too for rows that now parse
If state.db failed at startup and the plugin registered before it
recovered, the held mirror row was in the fallback baseline but not in the
live rows the merge compared against, so the merge read it as removed,
skipped the newer DB row, and the older mirror copy was promoted and saved
over it. The merge now compares against held and live rows alike, and an
unchanged held copy yields to the DB row.
2026-11-26 00:08:24 -08:00
Teknium
452e852443 fix(sessions): a recovered DB load keeps the boot's verdict on a held mirror row
When state.db could not be read at startup, a held route came from the
sessions.json mirror. The clean-startup marker discard cleared its marker,
but the save's DB retry then replaced the held row with the untouched DB
copy and wrote the old marker back; after the receipt was consumed, a later
crash could resume a finished turn.

The fallback baseline now records held rows too, and the recovered load
treats them as it treats live entries: a DB-only row is held, an unchanged
held mirror copy yields to the DB copy, a changed or removed one stays.
2026-11-26 00:08:24 -08:00
Teknium
4b6d36dcab fix(sessions): every full write and DB load keeps held routes; verdicts reach them on disk
Review follow-ups on the held-route fix:

- A turn-marker or prompt-pin write whose single-row upsert fails falls
  back to a full rewrite; that rewrite was built from the live entries
  alone and deleted every held row. Both full-write paths now build from
  one _routing_data_locked().
- When state.db cannot be read at startup and recovers later, the
  recovered load held nothing: an unregistered-platform row was skipped
  (and an older sessions.json copy kept instead). It is held there too,
  the state.db copy winning.
- A whole-index verdict (boot crash-turn recovery, the clean-startup
  marker discard) is applied to a held row right away through a stand-in
  platform, instead of queued until the plugin registers. The clean
  receipt is consumed right after the discard, so a queued discard was
  lost if the process exited before the plugin loaded, and the stale
  marker resumed a finished turn on the next unclean start.
2026-11-26 00:08:24 -08:00
Teknium
c3fdd7f658 test(sessions): pin held routes with Yuanbao, a plugin platform on main
The held-route tests used qqbot, a core Platform member on main, so they
parsed and exercised nothing here. Yuanbao is a Labs plugin platform on main
(not bundled), so a saved yuanbao route is exactly the row that main drops
on the next full save. Five of the seven are red on main.

The file gets its own name so the QQ Bot / Feishu moves, which add
tests/gateway/test_unparsed_route_survives_save.py, still merge cleanly.
2026-11-26 00:08:24 -08:00
Teknium
c33d2da147 fix(sessions): a held route joins the live index once its platform registers
A routing row held because its platform was not registered at load (a
multiplexed secondary profile's plugin registers after the index loaded)
never re-entered _entries, so the chat's next message recovered the session
from state.db without the route's own state: /stop's suspension and a
pending resume were lost after a restart. Profile delete and rename walked
only _entries, so the next save wrote a held row back (or left it under the
old profile).

- _ensure_loaded_locked promotes a held row once its platform is a Platform
  member and drops a held copy the live index already owns.
- purge_profile_routing / rekey_profile_routing handle held rows too.
- a promoted row gets every whole-index verdict it missed while held (the
  boot's recover_interrupted_turns / discard_active_turn_markers), so a
  crash-left turn marker becomes resume_pending or is cleared as the live
  rows' were.

Generic for every platform that registers late; not QQ-specific.

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-26 00:08:24 -08:00
Teknium
3110876020 fix(sessions): hold only routes whose platform is the one thing unparsed
A routing row is held for write-back only when its platform is the one thing
that fails to parse (it parses with a known platform in its place). A row
broken another way (a corrupt updated_at) stays skipped, so a valid
sessions.json copy still recovers it.

(Extracted from 56408aa0e62c, session hunks only.)
2026-11-26 00:08:24 -08:00
Teknium
22bd3f50b2 fix(sessions): a held route is not replaced by an older sessions.json copy
The legacy sessions.json import skips a key whose state.db row is held
unparsed, so an older mirror copy never replaces it (state.db stays primary).

(Extracted from 193406daaaa1, session hunks only.)
2026-11-26 00:08:24 -08:00
Teknium
2cc3906522 fix(sessions): hold a saved route whose platform is not registered yet
A gateway_routing row whose platform's plugin is not registered when the
store loads (a secondary profile's plugin platform, a plugin installed after
boot, one not installed yet) failed to parse and was dropped; the next full
save then deleted it from state.db, so the chat lost its session route.

The row is now held and written back on the next full save; a live entry
under the same key wins. Generic for every plugin platform.

(Extracted from the QQ Bot move, aa4cf2655d1d, session hunks only.)

Co-authored-by: BearHuddleston <bear@bearhuddleston.dev>
2026-11-26 00:08:24 -08:00
unsupportedpastels
93dd2a4efb fix(gateway): drop HERMES_WEBAPP_ADDRESS_WAIT, skip wait for idle-exit gateways, and pin teardown-stop guards
Address review findings from BearHuddleston on https://github.com/NousResearch/hermes-agent/pull/160232:
- Remove the HERMES_WEBAPP_ADDRESS_WAIT environment variable override and its
  HX002 waiver from gateway/run_runtime_listener.py; pass address_wait /
  wait_seconds explicitly to start_gateway_runtime_api and
  _start_gateway_api_waiting_for_address (keeping WEBAPP_ADDRESS_WAIT_SECONDS
  as the default), pass address_wait in tests/gateway/fixtures/webapp_fallback_peer.py
  instead of env_overrides, and update website/docs/getting-started/nix-setup.md
  for the 20s supervised wait.
- Skip the 20s address wait in gateway/run_bootstrap.py when idle_exit is True
  so TUI / chat -q idle-exit gateways (which Ink waits on with a hard 30s
  budget) fall back immediately, and add a parametrized test covering
  idle_exit=True vs supervised (idle_exit=False).
- Add a parametrized test pinning that a stop beginning while a Webapp
  listener binds, falls back to the private listener, or is refused publishes
  no listener after teardown and starts no fallback.
2026-11-26 00:58:05 -05:00
unsupportedpastels
126911ef00 refactor(gateway): remove run_runtime listener shims and abort stop signature inspection
Address Greptile re-review findings on https://github.com/NousResearch/hermes-agent/pull/160232:
- Remove the re-export shims from gateway/run_runtime.py and the reverse
  lookup (_webapp_address_poll_seconds) from gateway/run_runtime_listener.py;
  update gateway/run_bootstrap.py and all tests/fixtures to import and patch
  listener symbols directly on gateway.run_runtime_listener.
- Delete _stop_kwargs_for_abort in gateway/run_common.py, pass restart,
  detached_restart, and service_restart directly to runner.stop(...), and
  update startup-abort test doubles to match GatewayRunner.stop's signature.
2026-11-26 00:58:05 -05:00
unsupportedpastels
43c4d896eb refactor(gateway): extract runtime listener module and unify startup abort path
- Extract the Webapp address-wait, retry loop, private-listener fallback,
  and start_gateway_runtime_api into gateway/run_runtime_listener.py,
  re-exporting the public and test-imported symbols in gateway/run_runtime.py
  so gateway/run_runtime.py stays well under 1,000 lines (828 lines).
- Unify the startup-stop predicate and cleanup path into
  gateway/run_common.py (startup_should_abort and
  abort_startup_if_shutdown_requested), delegated from GatewayStartupMixin
  and reused directly by gateway/run_bootstrap.py (keeping only exit verdict
  and health-export cleanup in bootstrap) and gateway/run_runtime_listener.py.
- Guard optional runner attributes (_shutdown_event, _stop_task,
  _restart_detached) and inspect runner.stop() signature before forwarding
  restart kwargs so minimal test doubles (such as AbortedStartupRunner in
  tests/gateway/test_startup_restart_race.py) work identically to base.
2026-11-26 00:58:05 -05:00
unsupportedpastels
e678f6ecf6 refactor(gateway): extract listener-and-runner boot helper to keep _start_gateway_runtime complexity under cap 2026-11-26 00:58:05 -05:00
unsupportedpastels
d3d3a43b5e fix(gateway): abort webapp address wait on stop and scope retry to specific hosts
- Abort _start_gateway_api_waiting_for_address and start_gateway_runtime_api
  immediately when an operator stop, drain, or restart begins during startup,
  waking from the retry wait on runner._shutdown_event without rebinding the
  Webapp address or falling back to a private listener after teardown.
- Route an aborted startup in gateway/run_bootstrap.py through
  _abort_startup_before_runner instead of continuing into MCP discovery and
  runner.start().
- Restrict the EADDRNOTAVAIL retry loop strictly to enabled Webapps with a
  specific non-loopback, non-wildcard address (loopback_companion(host)), so
  private loopback listeners, 127.0.0.1 / ::1 / localhost, and 0.0.0.0 / ::
  fail immediately without waiting.
- Pass HERMES_WEBAPP_ADDRESS_WAIT=0 in permanent-EADDRNOTAVAIL specific-address
  tests via webapp_fallback_peer.run and add regression tests covering stop,
  restart, bootstrap abort, and immediate loopback/wildcard fallback.
2026-11-26 00:58:05 -05:00
unsupportedpastels
4ae5e9687b chore(contributors): map oxngon noreply email 2026-11-26 00:58:05 -05:00
unsupportedpastels
88ff664154 fix(gateway): log webapp address-wait warning once and reject non-finite wait
Guard the EADDRNOTAVAIL retry warning in _start_gateway_api_waiting_for_address
with a warned flag so each attempt batch logs once instead of repeating on every
0.5s poll. Reject non-finite HERMES_WEBAPP_ADDRESS_WAIT values (nan/inf/-inf)
so inf cannot hang startup, waive HX002 for the process-level boot override,
and add focused tests for single-warning logging, non-EADDRNOTAVAIL errors,
zero/negative/non-finite overrides, and task cancellation.
2026-11-26 00:58:05 -05:00
oxngon
3bafbb8cd0 fix(gateway): wait for a webapp.host address an interface is given after boot
A specific webapp.host (a LAN, Tailscale/Headscale or WireGuard address, or a DHCP
lease) can be assigned to its interface a moment after the gateway starts. The
first bind then fails with EADDRNOTAVAIL, and the gateway keeps running with the
Webapp off: nothing crashes, so no Restart= policy fires, and the address stays
dark until someone restarts the gateway by hand.

Wait, bounded, for the address to appear, then bind again. Only EADDRNOTAVAIL is
retried: a busy port, a refused bind and the loopback companion's own failure
(ListenerAddressError) are still reported at once. HERMES_WEBAPP_ADDRESS_WAIT
sets the wait in seconds (0 disables it).

(cherry picked from commit d0fea75346daca91a56246d9a7bf67af48b140ac)
2026-11-26 00:58:05 -05:00
unsupportedpastels
3e33ec2a9d fix(webapp): keep loopback Webapp launch-link-only and refuse cookie logins
Addresses the security blocker on PR https://github.com/NousResearch/hermes-agent/pull/160226
(issue https://github.com/NousResearch/hermes-agent/issues/159500):
RFC 6265 §8.5 does not isolate cookies on 127.0.0.1 by port, so accepting
browser login cookies on a loopback Webapp allows any other local port the
browser visits to capture and replay those cookies against REST and
/api/webapp/socket-ticket?socket=host-terminal, bypassing withhold_session_token.

Pivot to Direction 1 (launch-link-only on loopback Webapp):
- Restore middleware, web_server, webapp_sign_in, web_server_dashboard,
  web_routers/{webapp,status,files}, web_server_file_tickets, and
  apps/desktop/src/lib/{platform,browser-transport}.ts (removing
  browser-loopback-login.test.ts) back to base 3113542d64 so loopback
  Webapp never treats cookies as a credential.
- On private_launch(app.state), render a launch-link-only notice on
  GET /login directing the user to run `hermes webapp` (no login form,
  no provider buttons, no Set-Cookie), return {"providers": []} on
  GET /api/auth/providers, and refuse browser cookie sign-in on
  GET /auth/login, GET /auth/callback, and POST /auth/password-login
  with HTTP 403 and `hermes webapp` guidance while preserving RFC 8252
  native flows, gated non-loopback login, launch-link tokens, and
  standalone loopback dashboards.
- Rewrite tests/hermes_cli/test_webapp_loopback_login.py to verify
  Direction 1 and RFC 6265 §8.5 cookie-replay rejection.
2026-11-26 00:57:21 -05:00
unsupportedpastels
99c62807a1 fix(webapp): let tokenless loopback reload recover to /login after cookie expiry
On a loopback Webapp with interactive dashboard-auth providers configured,
reloading `/` after session cookies expire or clear previously emitted only
`window.__HERMES_AUTH_REQUIRED__=false;`, causing `browserBootstrap()` to enter
launch-link-only mode with an empty token. `browserFetch()` and `connectionFor()`
then threw `WEBAPP_LAUNCH_REQUIRED` before making any request, blocking the
structured 401 `login_url` response from reaching the browser.

Keep `GET /` non-redirecting and `_SESSION_TOKEN` withheld, emit
`window.__HERMES_LOGIN_AVAILABLE__=true;` when interactive providers are
registered on loopback Webapp, and let `browserBootstrap()` fall back to
cookie/login discovery when no launch-link `sessionStorage` token is present
while preserving launch-link tokens and launch-link-only installs.

Refs https://github.com/NousResearch/hermes-agent/pull/160226
Refs https://github.com/NousResearch/hermes-agent/issues/159500
Refs https://github.com/NousResearch/hermes-agent/issues/160209
2026-11-26 00:57:21 -05:00
unsupportedpastels
ffb217b79c fix(webapp): bind cookie file tickets to sign-in generation and emit login_url on expired loopback API 401
- Pass `webapp_sign_in.sign_in_of(request)` into `web_server_file_tickets.mint()`
  when issuing download and stream file tickets so browser cookie logins bind
  their file tickets to the current browser-credential generation and
  `hermes webapp --sign-out` purges them from the ticket store, while leaving
  native-grant and service-token file tickets independent.
- Return `_unauth_response(request, reason="no_cookie")` (401 JSON with
  `login_url`) for unauthenticated protected `/api/*` requests on a loopback
  Webapp when interactive auth providers are registered, so an existing
  cookie-mode tab whose cookies expired or were cleared navigates back to
  `/login` without redirecting HTML loads or affecting launch-link / standalone
  dashboard behavior.
- Add regression tests in `tests/hermes_cli/test_webapp_loopback_login.py`
  covering cookie file-ticket revocation (download and stream) vs native/service
  ticket survival and expired-cookie-jar 401 envelopes.
2026-11-26 00:57:21 -05:00
unsupportedpastels
723aed4042 fix(webapp): honor verified login cookies on loopback Webapp listeners
On a loopback gateway-hosted Webapp (`ui_surface="webapp"`,
`auth_required=False`, `withhold_session_token=True`) with a configured
dashboard auth provider (such as `dashboard.basic_auth`), `/login` and
`POST /auth/password-login` succeeded and set session cookies, but every
subsequent `/api/*` and `/api/webapp/socket-ticket` request returned 401
because `gated_auth_middleware` was a no-op when `auth_required` was
False and `auth_middleware` ran before it demanding `_SESSION_TOKEN`.

Verify Webapp session cookies on loopback Webapp listeners before
`auth_middleware` runs, with the same `webapp_sign_in` credential binding
and own-origin CSRF guard as gated mode:
- Run `_dashboard_auth_gate` before `auth_middleware` and honor
  `request.state.session` in `auth_middleware`, `_require_token`,
  `_plugin_api_runtime_gate`, and `_status_caller_verified`.
- Bind Webapp sign-in cookies to the browser credential on loopback
  Webapp too so `hermes webapp --sign-out` revokes cookie logins and
  their minted socket tickets.
- Emit `window.__HERMES_AUTH_REQUIRED__=true` in `_serve_index` when a
  loopback Webapp browser presents a verified cookie session while
  continuing to withhold `_SESSION_TOKEN` from HTML.
- Keep `POST /api/webapp/window-ticket` restricted to `_SESSION_TOKEN`
  holders so cookie sessions cannot extract `_SESSION_TOKEN`, and keep
  expired/revoked cookies on HTML loads non-redirecting so launch-link
  tabs are never trapped behind `/login`.

Fixes https://github.com/NousResearch/hermes-agent/issues/159500
Refs https://github.com/NousResearch/hermes-agent/issues/160209
2026-11-26 00:57:21 -05:00
unsupportedpastels
c46b08b206 fix(gateway): address review feedback on legacy unit removal
- Warn with the exact systemctl start command when legacy unit removal fails after stop already succeeded.
- Raise inside run_quietly in SystemHost.remove_legacy_units() so Gateway Move surfaces systemctl's failure reason.
- Add root and mixed-scope tests for systemd_install()'s legacy removal abort check.
- Remove the synthetic malformed-return-value test that exercised an unreachable None return.
2026-11-26 00:57:10 -05:00
unsupportedpastels
c22fd6769b fix(gateway): recover from SystemExit in multiplex migrate and unpack legacy removal result
Address Greptile review findings on https://github.com/NousResearch/hermes-agent/pull/160223:
- Convert SystemExit into RuntimeError inside gateway_migrate._service_op so
  a systemd_install() abort during `hermes gateway migrate --multiplex`
  triggers apply_migration() recovery and rollback_migration()'s detached
  fallback instead of exiting with zero gateways running.
- Unpack `_, remaining = remove_legacy_hermes_units(interactive=False)`
  directly in systemd_install() instead of silently treating non-tuple
  results as empty, and update the test double in test_gateway.py to return
  (0, []).
- Add regression tests covering both paths.
2026-11-26 00:57:10 -05:00
unsupportedpastels
15036db422 fix(gateway): abort systemd_install when legacy unit removal fails
When remove_legacy_hermes_units() catches a nonzero exit status or
subprocess.SubprocessError (such as TimeoutExpired) and retains an
eligible legacy unit in remaining, systemd_install() previously ignored
remaining and proceeded to write/enable the replacement unit, allowing
gateway_setup_service and CLI install to call systemd_start() alongside
a still-running legacy gateway.

Abort systemd_install() with sys.exit(1) whenever any eligible legacy
unit fails removal, while preserving base behavior when a non-root user
only has a skipped system-scope legacy unit or declines removal.
2026-11-26 00:57:10 -05:00
unsupportedpastels
73276cdd09 fix(gateway): handle systemctl SubprocessError in legacy unit removal and add unit tests
Catch subprocess.SubprocessError (such as TimeoutExpired) alongside
OSError and RuntimeError inside remove_legacy_hermes_units so a timed-out
stop or disable retains the legacy unit file and records it in remaining
instead of crashing CLI callers, while SystemHost.remove_legacy_units
still detects the retained unit and refuses removal.

Trim the truncated duplicate paragraph in _find_legacy_hermes_units's
docstring to offset the FILE_LINES ratchet on hermes_cli/gateway.py.

Add direct unit tests covering remove_legacy_hermes_units,
SystemHost.remove_legacy_units, _cmd_migrate_legacy, and systemd_install.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-2)
Fixes https://github.com/NousResearch/hermes-agent/issues/159419
2026-11-26 00:57:10 -05:00
Kevin Rajan
4fd4ac36e9 test(gateway): cover failed legacy unit shutdown during Move
(cherry picked from commit 577e9d952de674ff1152f994adba0fc82dde8c53)
2026-11-26 00:57:10 -05:00
Kevin Rajan
221078d630 fix(gateway): retain legacy unit when stop or disable fails
(cherry picked from commit 933da72530efe1baae1fe2eb99e444a36539e5ea)
2026-11-26 00:57:10 -05:00
unsupportedpastels
f10bfdbe1f gateway: address BearHuddleston review findings on parallel secondary connects
Address all five Should-fix findings and the docs update from
@BearHuddleston's review of
https://github.com/NousResearch/hermes-agent/pull/160236:

1. Photon sidecar install lock (`plugins/platforms/photon/adapter.py`,
   `plugins/platforms/photon/sidecar/.gitignore`): hold an exclusive
   flock/msvcrt lock in the shared sidecar directory across the deps
   checks and `npm ci`, preventing concurrent Photon profiles (each
   loaded under its own per-home module name) from clobbering
   `node_modules` or spawning against a half-installed tree.
2. Systemd boot-deadline renewal (`gateway/run_adapters.py`,
   `gateway/run_adapters_recovery.py`,
   `website/docs/user-guide/messaging/index.md`): renew systemd's
   `Type=notify` start timeout before every preparation step (each
   profile load and each enabled platform build), drop the 30 s
   throttle and `prep_renewed_at`, and update the messaging docs for
   wave-based secondary startup.
3. Remove test-only serial fallback (`gateway/run_adapters.py`): delete
   `_uses_default_profile_starter`, `_DEFAULT_START_ONE_PROFILE_ADAPTERS`,
   and the serial fallback branch, and update boot-sweep test stubs to
   `_prepare_one_profile_adapters` so boot tests cover the real
   parallel production path.
4. Serialize WhatsApp secondary connects one per wave
   (`gateway/run_adapters_recovery.py`): add `_ONE_PER_WAVE_PLATFORMS`
   for `Platform.WHATSAPP` and `wave_keys` on `_StagedProfileAdapter`
   so WhatsApp secondaries connect one per wave in profile order while
   other platforms still connect in the first wave.
5. Off-loop WhatsApp bridge deps install
   (`plugins/platforms/whatsapp/adapter.py`): run
   `_ensure_bridge_deps` via `asyncio.to_thread` so a cold/stale npm
   install does not block the event loop and time out sibling connects
   in the same wave.
2026-11-26 00:56:51 -05:00
unsupportedpastels
94c3d1ed37 gateway: renew systemd boot deadline between slow intra-profile platform preps
- Track monotonic prep_renewed_at on _SecondaryConnectBatch and check elapsed
  time (>= _SYSTEMD_BOOT_STEP_MARGIN_SECS) via _maybe_renew_systemd_boot_during_prep()
  before each enabled platform inside _prepare_one_profile_adapters() as well as
  between profiles in _start_secondary_profiles_parallel().
- Preserves zero extra prep notifications on fast normal boots while preventing
  multi-platform single-profile slow preparation (e.g. 3x35s = 105s) from
  exhausting systemd's default 90s start timeout.
- Add regression test covering 3x35s platform preparation inside one secondary
  profile in tests/gateway/test_multiplex_secondary_connect_parallel.py.
2026-11-26 00:56:51 -05:00
unsupportedpastels
899b68449c gateway: fix systemd boot extension parity, batch state object, and test barrier deadlines
- Fix test_systemd_boot_extend_timeout regression by extending systemd's start
  deadline with the wave's maximum connect budget directly before each adapter
  connect instead of double-notifying during fast 2-profile preparation and
  batch start, while still renewing during slow or multi-profile preparation
  (after 2+ profiles or >= 30s elapsed monotonic time).
- Introduce _StagedProfileAdapter and _SecondaryConnectBatch dataclasses in
  gateway/run_adapters_recovery.py to own staging, deferral, claim tracking,
  and checkpoint rollback instead of passing four mutable collections across
  preparation and wave-connect helpers.
- Raise all barrier and disconnect wait deadlines in
  tests/gateway/test_multiplex_secondary_connect_parallel.py to 2.5s (>= 2s
  per tests/AGENTS.md) and add a monotonic slow-preparation renewal test.
2026-11-26 00:56:51 -05:00
unsupportedpastels
394fe9ad05 gateway: harden parallel secondary-profile connect cleanup, deferral, and boot renewal
Address post-review regressions in parallel secondary-profile startup:
- Wrap preparation and concurrent wave execution in BaseException cleanup
  that distinguishes never-started adapters from started ones, disconnects
  started-but-untracked adapters under their own profile scopes, releases
  abandoned provisional holds, and preserves holds transferred to reconnect
  bridge tasks.
- Defer adapters colliding only with provisional in-batch holds instead of
  stamping them fatal upfront, connecting conflict-free waves concurrently
  so a healthy sibling connects when its predecessor fails permanently
  while still refusing duplicates after a predecessor succeeds or queues
  for retry.
- Renew systemd's Type=notify start deadline as sequential preparation
  stages each platform, then extend with the wave's max connect budget
  before the parallel connect batch.
- Bind a stable module-level reference to the original
  _start_one_profile_adapters function so class-level mixin monkeypatches
  are respected instead of bypassed.
- Move the new secondary staging/wave helpers into the existing
  GatewaySecondaryReconnectMixin in gateway/run_adapters_recovery.py so
  gateway/run_adapters.py stays under its FILE_LINES cap.
- Add permanent regression tests covering all four fixes.
2026-11-26 00:56:51 -05:00
unsupportedpastels
f7e13f152c gateway: parallelize secondary-profile adapter connections at startup
Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-8)

Split secondary-profile adapter startup in GatewayAdapterLifecycleMixin into:
1. A sequential preparation phase per profile (config load, secret hydration,
   plugin discovery, hook registration, MultiplexConfigError validation,
   adapter instantiation, duplicate credential/listener claim checks, and
   claim holds), preserving deterministic conflict ownership and fail-fast
   config errors.
2. A concurrent network connect() phase across all staged adapters via
   asyncio.gather, with each task entering its own ContextVar-backed
   _profile_runtime_scope and a single max-budget systemd start-timeout
   extension for the batch.

Single-adapter connects await directly without an extra task hop, and custom
monkeypatches on _start_one_profile_adapters continue to run through the
original seam.
2026-11-26 00:56:51 -05:00
unsupportedpastels
13e5c82616 fix(gateway,web): address PR #160225 review feedback on switching copy, comments, and tests
Address all six review items from @BearHuddleston on
https://github.com/NousResearch/hermes-agent/pull/160225:

- web/src/components/BackendMigrationCard.tsx: drop "for a few seconds" from
  the switching state and show the profile-qualified `--status` command
  immediately while keeping the 1830 s poll cutoff, with a regression test.
- web/src/lib/backend-migration.ts: clarify that UNREACHABLE_AFTER_SECONDS is
  an estimate of the migration's own caps rather than a launchd/unit bound.
- hermes_cli/gateway_migrate_backends_host.py: clarify in
  _gateway_verb_timeout that these are the migration's caps, not systemd unit
  TimeoutStopSec limits.
- tests/hermes_cli/gateway_migrate_backends_apply/test_engine.py: use the
  home fixture's 0 s handoff budget in the never-lands test to stop
  busy-spinning for 5 real seconds.
- tests/hermes_cli/gateway_migrate_backends_apply/test_restart_handoff.py:
  add _RequestedRestartHost test verifying handoff starts after
  gateway_verb("restart") and outlasts a missed (None) PID lookup.
- tests/hermes_cli/gateway_migrate_backends_host/test_gateway_verb_timeout.py,
  tests/hermes_cli/gateway_migrate_backends_apply/test_restart_handoff.py,
  tests/hermes_cli/test_gateway_migrate_backends_docs.py: assert relations
  against shared timeout constants rather than redundant hardcoded literals.

Co-authored-by: BearHuddleston <bear@bearhuddleston.dev>
2026-11-26 00:56:22 -05:00
unsupportedpastels
c30b7f31dd refactor(gateway): move migration timeout constants to leaf module
Eliminates the cyclic dependency between gateway_migrate_backends_plan,
gateway_migrate_backends_host, and gateway_migrate_backends_apply by
moving VERIFY_SECONDS, RESTART_HANDOFF_SECONDS, and
ROLLBACK_VERIFY_SECONDS into the leaf module
hermes_cli/gateway_migrate_backends_timeouts.py.

- Import gateway_migrate_backends_timeouts at module top in _plan,
  _host, and _apply (re-exporting the constants in _apply for existing
  callers and tests).
- Drop the deferred imports of gateway_migrate_backends_apply from
  BackendPlan.step_titles() and _gateway_verb_timeout().
- Update timeout-derivation tests and add subprocess import-order tests
  confirming _plan and _host never pull in _apply.
2026-11-26 00:56:22 -05:00
unsupportedpastels
fc9f9d9fa8 fix(gateway): derive migration plan verify copy from VERIFY_SECONDS
Read VERIFY_SECONDS lazily inside BackendPlan.step_titles() instead of
hardcoding "within 90 s", so pre-migration plan output matches the 300 s
verification budget enforced by cmd_apply without introducing a circular
import. Update the web dashboard guide, web plan fixture, and regression
tests accordingly.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-5)
2026-11-26 00:56:22 -05:00
unsupportedpastels
10282b6ab3 fix(web): extend UI poll timeout to cover worst-case sequential rollback
Raise UNREACHABLE_AFTER_SECONDS from 660 s to 1830 s so the mounted
BackendMigrationCard stays in the switching poll loop across the full
sequential backend timeout budget (port-free 30 s + gateway restart 540 s
+ handoff 240 s + verify 300 s + rollback stop 240 s + rollback gateway
start 300 s + listener-gone 30 s + old backend start 90 s + rollback
verify 60 s = 1830 s) and reports a late rollback recovery instead of
stopping early as unreachable.

Add a mounted-card regression test covering a 685 s slow restart + failed
verify + rollback recovery.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-6)
2026-11-26 00:56:22 -05:00
unsupportedpastels
f914fcb51e fix(gateway): align systemd gateway_verb timeout with handoff and verify budgets
Derive SystemHost.gateway_verb() systemd timeouts from
RESTART_HANDOFF_SECONDS (240s) and VERIFY_SECONDS (300s) instead of
hardcoding 90s:
- restart: max(90, int(RESTART_HANDOFF_SECONDS + VERIFY_SECONDS)) = 540s
- start: max(90, int(VERIFY_SECONDS)) = 300s
- stop: max(90, int(RESTART_HANDOFF_SECONDS)) = 240s
- enable/disable: 90s

Prevents systemctl --user restart/start from aborting start_gateway at
90s while the old gateway drains or a Type=notify startup finishes.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-7)
2026-11-26 00:56:22 -05:00
unsupportedpastels
f3a8c6bc08 fix(web): align backend migration UI unreachable timeout with backend budget
Raise UNREACHABLE_AFTER_SECONDS from 150 to 660 in
web/src/lib/backend-migration.ts so the Move card stays in the
"switching" state across the backend's 240s restart handoff, 300s
verify window, and 120s rollback/old-backend restart budget instead of
prematurely reporting unreachable.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-6)
2026-11-26 00:56:22 -05:00
unsupportedpastels
d109d286e6 fix(gateway): harden restart handoff when pre-restart PID is absent
Fall back to the manifest's preflight gateway running_pid if
host.gateway_pid() transiently returns None right before restart, so a
still-draining preflight PID is not mistaken for a replacement process.
When no pre-restart PID is known at all, omit "PID None" from the
advisory handoff warning and keep waiting for a live PID.

Refs https://github.com/NousResearch/hermes-agent/issues/160209 (BM-5)
2026-11-26 00:56:22 -05:00
Andre Hugo
4fda3e13e7 fix(gateway): verify a backend migration after the restart lands
`start_gateway` called host.gateway_verb("restart") and went straight on to the
verify step. A supervised restart only *requests* the restart: the gateway
drains in-band and keeps its API up, answering 503 gateway_draining until it
exits, so verification spent its whole budget probing the very process it was
replacing. Held open by the caller's own in-flight turn that was 376 s of
consecutive 503s and the move rolled back with "no HTTP 200" against an address
that was up throughout.

- record the pre-restart PID and wait for a replacement one before verify's
  clock starts (bounded by RESTART_HANDOFF_SECONDS; advisory, verify still
  decides)
- accept gateway_state "degraded": one parked adapter pins it permanently and
  the move only needs the Webapp to serve
- raise VERIFY_SECONDS 90 -> 300, the floor for a whole boot on a busy
  multi-profile home (banner to ready measured 56-92 s)

(cherry picked from commit 22a49ca50dd461315de93271884f7e8d2daef142)
2026-11-26 00:56:22 -05:00
unsupportedpastels
1cdc28e8ab fix(cli): derive secret_source_blocker URL from target and dial_origin
Address review feedback on https://github.com/NousResearch/hermes-agent/pull/160224:
- Derive _secret_source_address() from _target() so the example never names
  the old backend's port when the Webapp is already enabled elsewhere, and
  ignores --keep-webapp-address on by-hand moves (which refuse it).
- Omit the runnable `hermes ... config set` command when the target address
  is unknown/blocked so the <port> placeholder stays in prose only.
- Reuse gateway.webapp_listener.dial_origin() in _loopback_public_url().
- Read host.home and host.os_family() directly (removing stub-only getattr
  fallbacks and the stub-only test) and tighten the docs test assertions.
2026-11-26 00:55:58 -05:00
unsupportedpastels
924ef4d03c fix(cli): preserve localhost and detect managed homes in secret_source_blocker
Follow-up fixes for secret_source_blocker() in
hermes_cli/gateway_migrate_backends_plan.py:

- Preserve http://localhost:<port> when the old backend binds localhost
  (case-insensitive) instead of rewriting it to http://127.0.0.1:<port>,
  which would fail on IPv6-first localhost (::1).
- Check get_managed_system(host.home) in addition to Nix supervisors so
  managed homes (e.g. a .managed marker set to nixos/home-manager/empty
  or another package manager, even with a manually launched backend)
  receive declarative configuration guidance instead of `hermes config set`,
  which refuses to run on managed homes.
- Add regression tests in
  tests/hermes_cli/gateway_migrate_backends_plan/test_secret_source_blocker.py.

Refs https://github.com/NousResearch/hermes-agent/issues/160209
Refs https://github.com/NousResearch/hermes-agent/issues/159818
2026-11-26 00:55:58 -05:00
unsupportedpastels
ee5e2dd71e fix(cli): clarify webapp.public_url blocker copy for external secret sources
Clarify secret_source_blocker() in gateway_migrate_backends_plan.py so
local, LAN, and Desktop-only operators understand why webapp.public_url
is requested when secrets: is enabled, what "public" means here
(browser-facing http:// or https:// address for sign-in callbacks and
Host/Origin checks, not necessarily internet-routable), and how to
unblock cleanly with a valid loopback URL matching their backend's
port/IP family (or Nix configuration on Nix-managed installs).

Preserve the fail-closed invariant, the 1-arg secret_source_blocker(host)
call signature, and the existing "external secret source is enabled"
phrase. Update web-dashboard.md dry-run migration docs to match and add
focused regression tests.

Reported-by: Richard Ahlquist (@rahlquist)
Fixes https://github.com/NousResearch/hermes-agent/issues/159818
Refs https://github.com/NousResearch/hermes-agent/issues/160209
2026-11-26 00:55:58 -05:00
unsupportedpastels
cd62c2ef6e test(gateway): pin #160028 rescan sequence and isolate host user-bus env
Address reviewer feedback from @BearHuddleston on PR #160222:
- Replace test_headless_shell_populates_dbus_address_to_avoid_duplicate_user_unit
  with test_a_rescan_after_a_user_systemctl_call_finds_the_same_systemd_backend
  so the test pins the real #160028 sequence (bus-less first scan,
  gw._systemctl_cmd(), rescan) where real systemctl fails both show and
  list-unit-files without XDG_RUNTIME_DIR.
- Pin XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS absent (via
  monkeypatch.setenv + monkeypatch.delenv so teardown restores them) and
  stub _runtime_dir_is_ours/_path_exists_safe to False in the host
  fixture so other host tests never leak real /run/user/<uid> values
  into os.environ.
2026-11-26 00:55:20 -05:00
unsupportedpastels
73d7b0c21a test(gateway): use platforms marker instead of mocking os_family
Run test_non_linux_backend_scan_skips_user_systemd_env on native macOS
and Windows via @pytest.mark.platforms("macos", "windows") instead of
patching gmb.os_family(), matching tests/AGENTS.md.
2026-11-26 00:55:20 -05:00
unsupportedpastels
878d825468 test(gateway): isolate os.environ in headless dbus user-unit test 2026-11-26 00:55:20 -05:00
unsupportedpastels
1c645fc9bf test(gateway): guard non-Linux import and add user-bus env control tests
Defer importing `_ensure_user_systemd_env` from `hermes_cli.gateway` inside
the Linux guard in `collect_backends()` so macOS and Windows skip both the
call and the import, and add focused regression and control tests covering:
- DBUS_SESSION_BUS_ADDRESS population when `systemctl --user show` needs the
  bus while `list-unit-files` succeeds offline (preventing duplicate manual
  plus installed-unit rows),
- preservation of existing user-owned XDG_RUNTIME_DIR / DBUS_SESSION_BUS_ADDRESS
  and non-fabrication when no user runtime dir exists,
- skipping `_ensure_user_systemd_env` on macOS and Windows.
2026-11-26 00:55:20 -05:00
Ayham Joumran
bb8889f331 fix(gateway): find a user-unit dashboard from a shell without the user bus
gateway migrate --backends asks systemctl --user which unit's MainPID a running dashboard is. From a shell without XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS that query fails, so the user unit's dashboard was classified as a manual backend and then listed again as its installed unit, and the same PID blocked the migration as a competing backend. Backend discovery now sets up the user systemd environment first, as the gateway's other systemctl --user callers do.

Fixes #160028

(cherry picked from commit 60a1dc413eda30baf0f54511ebe4e0eee141f92c)
2026-11-26 00:55:20 -05:00