HERMES_CONFIG_BACKEND=<kind> now resolves to plugins.config_backends.<kind>.get_backend() (a
direct import, never the general plugin loader, D11), with the kind checked against a package-name
pattern before any import. What core read from the remote plugin's internals is a protocol method
with a no-op FileBackend version: bootstrap_env_names() (env_loader's .env bootstrap),
preserve_read_base() (keeping_read_base) and doctor_warnings() (hermes doctor).
Addresses teknium1's P2-1 on #122509.
1. A document save is diffed against the base the saving context READ (per-context
_READ_BASE recorded by read_user_layer / read_user_doc_readonly / version and after the
context's own acknowledged write), not against whatever a poll installed between the read and
the save. save_config's fail-closed guard read keeps the caller's read base. A poll before save
no longer turns its changes into our unsets/sets with the current expectedVersion.
2. persist_model_selection (remote): a key the switch clears that the effective model block
still holds is stored as null ("no value", contract 5.4), not unset at the profile level, so
an upper-level old-endpoint api_key/key_env/api_key_env/context_length stops applying at the
new endpoint. New config_backend.write_changes carries explicit nulls.
3. profiles.configure: skills / toolsets / MCP sections report applied only when the section
reads back as written; a bulk save that dropped a locked key is no longer acknowledged.
4. _dotenv_assignments decodes UTF-16 (BOM) and strips NULs as the runtime sanitizer does, so
stage2 / first-read selection agrees with the backend the runtime boots.
Regressions (each fails with the production change reverted):
test_poll_between_read_and_save_sends_only_the_callers_edit,
test_model_switch_masks_inherited_endpoint_credentials,
test_profile_editor_reports_a_locked_skills_edit_as_not_applied,
test_stage2_decides_like_the_runtime_for_utf16_dotenv[utf16-bom|utf16-no-bom].
apply_config_bootstrap_env returns early under worker_config_snapshot(), as load_hermes_dotenv
does, so a frozen-policy worker's first config read no longer opens <profile>/.env or .op.env
(tests/hermes_cli/test_corelane_frozen_worker_skill_env.py[config]).
load_hermes_dotenv re-publishes the deployment names via bootstrap_deployment before boot instead
of applying the full managed overlay early, so the managed overlay keeps running once, after
external secret sources (tests/agent/test_safe_worker_policy.py[ordinary] callback order);
the managed instance id still reaches the boot (test_instance_id_from_the_managed_dotenv_boots).
The ratchet (scripts/check --only health, new on main) freezes every
file over 2,000 lines at its main size and blocks blind excepts.
- Facades back at or below their main size: the backend seam's local
imports become module-level ones (config_exists via hermes_cli.config
where that is already imported), and unrelated pure helpers move to
topical siblings: _job_doc_header -> cron/scheduler_prompt.py,
_csv_or_list_to_set -> gateway/run_common.py, the dotted config-path
pair -> hermes_cli/backup_restore.py, voice/timezone/web checks ->
hermes_cli/config_value_checks.py, a new profile's config document
(seed, migrate, backend read) -> hermes_cli/profiles_config.py, pet
spritesheet helpers -> tui_gateway/pet_sheet.py. Callers import from
the defining module (no re-export).
- BLE001: _load_config_dict catches YAMLError/OSError/UnicodeError;
run_migrations inlines the step loop again (the moved blind except
keeps main's identity); the two intentional fail-opens carry
'# health: allow' with their reason.
- env_loader: secret sources apply into a private staging copy of the
environment; the D32 protected-name check runs before anything is
published to os.environ, so a refused plane URL/credential is never
visible to a concurrent request (the poller reads them live).
- remote backend: the doc's schema version and generation are captured
together under st.lock; a migration whose doc was replaced before it
starts (or at any step/commit) never touches the replacement.
- remote backend: plane value refusals (config_value_invalid,
config_path_invalid/reserved, config_secret_literal, 413 too_large)
become ConfigValueError; the dashboard maps them to 400/413 with the
plane's message; config_request_invalid and others stay opaque.
- stub plane enforces the contract §11.1 depth limit; bulk-save test
asserts the exact PATCH.
1. Secret sources can no longer switch remote mode off. The backend is selected BEFORE
apply_all and the protected-name check judges by that backend; HERMES_CONFIG_BACKEND is
never a source's to set (reverted; remote mode exits, file mode warns and drops it).
2. A poll GET that a write (or a newer fetch) overtook is dropped instead of installed: every
install bumps a sequence the GET captured when it started. profileVersion alone cannot tell
(an upper-level change keeps it equal).
3. Writes diff against the doc readers got, i.e. migrated in memory (D12), also after the CAS
re-read: an unrelated edit no longer sends the migration's unsets. A migration step for a
doc a poll replaced mid-migration is dropped.
4. Dashboard: expected config refusals keep their message (lock 403, value 400, conflict 409)
through http_failure; anything else stays an opaque 500.
5. Conformance: the fixture digest is pinned to a literal (contract §13.4).
Stub plane: deep_merge now ignores null over a mapping (contract §6.2); docstring says it is a
test double, not server-conformance evidence.
plugins/config_backends/remote serves each profile's user layer from the
config plane: boot fetch inside load_hermes_dotenv with bounded retry and
fail-closed exit (D2), per-process ETag poller (D9), key-level diff writes
with CAS and one conflict retry (D10), client-side lock and secret-literal
checks (D7, D17), in-memory migrations (D12), managed config.yaml ignored
(D18), plane credential from auth.json or IdP client credentials only and
never from a secrets: source (D26, D32). Vendored gg conformance fixtures
run against the lock matcher, secret rule and _deep_merge.
`hermes update` restarts a non-service gateway (and replays `hermes serve`)
with its full env, which carries the Desktop's HERMES_UPDATE_SYSTEM_PROXY
marker. That process loads ~/.hermes/.env with override at import, and the
restore at start_gateway()/start_server() then popped every marked key,
including an HTTPS_PROXY the user set in .env (same value as the Desktop's
or a different one). The user's configured proxy was gone until a restart.
The restore now keeps a marked key while it still holds the value a dotenv
load in this process published, and does not put a saved NO_PROXY back over
a NO_PROXY the .env set. Names match case-insensitively: on Windows a
.env `https_proxy` and the inherited `HTTPS_PROXY` are one variable. The
Desktop and the hand-off scripts never load
.env into their env, so entry.ts, posix.sh and windows.ps1 are unchanged.
Conflict: hermes_cli/env_loader.py import block. Kept the branch's
left_core_migration.profile_env_names import and main's ConfigBackend
switch (load_yaml_file_readonly no longer imported; _load_secrets_config
reads through config_backend.read_config_doc_readonly).
No main commit since 0c771d7a5b touches Copilot code; nothing to port.
LEFT_CORE rows gain three generic fields for a model-provider plugin:
- providers: the ids and aliases the plugin's profiles register. A name
nothing resolves to gets the install line appended on every "unknown
provider" surface (runtime resolution / Desktop error text via
auth.resolve_provider, /model, `hermes model`, `hermes auth add`);
resolve_runtime_provider installs the plugin first for a home that uses it
(the CLI and Desktop resolve the provider before the agent whose start runs
the migration exists); and hermes_cli.providers.get_provider never lets the
models.dev catalog stand in for such a name while the plugin is not loaded
(models.dev lists `github-copilot` at api.githubcopilot.com with
GITHUB_TOKEN: it would have sent a raw GitHub token there).
- profile_env: env names core kept profile-managed. env_loader's
_PROFILE_MANAGED_ENV_KEYS and config._EXTRA_ENV_KEYS read them statically
(env_loader runs before discovery), and the generic env writers refuse them
while the plugin is absent (the executable/argv authority its profile
declares once installed).
- notice: one more per-home sentence on every migration outcome.
First consumer: the github-copilot row (providers copilot + copilot-acp and
every alias). It is in use when copilot/copilot-acp is a provider the home
routes through: model, fallback chain, auxiliary tasks, delegation and its
fallback chain, MoA presets, cron job pins, auth.json active_provider, or
HERMES_INFERENCE_PROVIDER. A GH_TOKEN alone is not use. COPILOT_GITHUB_TOKEN
and the two base-URL overrides stay out of children as provider env (Tier 2),
as when core shipped Copilot. Its notice tells a profile with no token the
plugin reads (no COPILOT_GITHUB_TOKEN/GH_TOKEN/GITHUB_TOKEN, no `manual`
credential-pool row or providers.copilot login: a gh_cli pool row was seeded
from `gh auth token`) to run `hermes auth add copilot`; the plugin no longer
reads gh or the Copilot CLI's token files. Read-only, never runs gh.
The unknown-provider hint helper moves out of auth.py (over the size cap)
into auth_error_copy.unknown_provider_hint.
The seam had a selector and reserved members that nothing in this PR
uses: HERMES_CONFIG_BACKEND accepted only `file` (every other value
exited), the .env override existed only to decide when to refuse,
UserLayer.locks/provenance and ConfigBackend.locked() were always empty,
and the supports_file_tooling()/require_file_tooling() checks at ten
file-copy sites were always true. All of it is for the remote backend
(#122509), so it lands there with the code that makes it real.
get_config_backend() now returns the file backend. The env var, its
docs row, the dotenv override, ConfigBackendUnavailable and the
file-tooling gates are gone, with the tests that covered them. The
explicit-file routing test now proves a non-config.yaml path never
consults the backend.
probe_config_readable() calls a probe_readable() protocol method
instead of an isinstance(FileBackend) check, and version_token()
documents how it treats an int-led version.
Add hermes_cli/config_backend.py (config-config design §4.1, D10/D11): a
ConfigBackend protocol, the FileBackend (today's behaviour), selection by
HERMES_CONFIG_BACKEND only (default file; 'remote' and unknown values fail
closed with ConfigBackendUnavailable), and path-level helpers
(read_config_doc, read_config_doc_readonly, config_version, config_exists,
write_config_key, write_config_document, supports_file_tooling).
Migrate every direct reader/stat/exists/bypass writer of a user config.yaml
to the helpers (config.py loaders + caches, config_effective, env_loader,
gateway, TUI, CLI watchers, cron, tools, profiles, logging, time). File
tooling (config edit, backups, xAI migration rewrite, raw dashboard editor)
checks supports_file_tooling() first; migrations skip write-back without it.
Add scripts/check_config_yaml_readers.py (CI lint next to the writers gate)
that rejects a direct read of a config path outside the backend.
load_hermes_dotenv expands ${VAR} / ${VAR:-default} before TERMINAL_ENV picks
the backend, so `HPC_BACKEND=singularity` + `TERMINAL_ENV=${HPC_BACKEND}` runs
Singularity. The predicate compared the raw text, said no, and the non-empty
reference also blocked the startup process-env fallback: update and startup
both skipped the plugin.
env_loader.resolve_home_dotenv returns what load_hermes_dotenv would publish
from a home's dotenv layers (home .env, then managed .env, both override),
read-only, through the same parser and resolution step the loader now shares
(_parse_dotenv_file, _dotenv_lookup_env, _resolve_dotenv_assignments).
Review: https://github.com/NousResearch/hermes-agent/pull/142561#discussion_r4343427764
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.
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).
Five writers (cron jobs store, utils._atomic_write, config._write_env_lines,
the env_loader sanitize rewrite, backup _extract_member_atomically) each
hand-rolled "stage beside the resolved symlink target", and only cron kept the
PermissionError fallback. A symlink into another filesystem whose real
directory is read-only to us therefore made utils/config/backup raise and the
.env sanitize silently skip (NUL bytes left on disk), where base saved by copy.
mkstemp_beside picks the same directory atomic_replace renames into (resolved
only when the target is a link) and, on PermissionError, retries beside the
link so the base EXDEV -> copy fallback still saves. One rule, one docstring,
one place to test.
Same class as the jobs.json fix: atomic_replace renames onto the
symlink's real target, but the shared writers staged the temp beside the
link. When the link points into another filesystem the rename fails with
EXDEV and atomic_replace degrades to its copy fallback, which rewrites the
target in place and can tear it on a crash.
Stage beside os.path.realpath(target) in utils._atomic_write (all
atomic_*_write helpers), hermes_cli/config._write_env_lines,
hermes_cli/env_loader's .env sanitize rewrite, and
backup_restore._extract_member_atomically. utils keeps creating only the
link's own parent via mkdir_under_hermes_home (no mkdir of the real
parent), so the deleted-profile tombstone guard is unchanged.
Removing or disabling the last plugin secret source rebuilt the per-home
snapshot but left the value it injected in os.environ, so single-profile
get_secret() kept serving it through its os.environ fallback until
restart.
The process-global apply path now records what each source wrote (and
the value it replaced). A later pass revokes writes whose source is no
longer registered/enabled, or that an enabled source stopped supplying,
but only while os.environ still holds exactly the written value: a value
another owner replaced (profile .env, managed .env, shell, later source)
stays. A source whose fetch failed keeps its last value (fail-open).
The dashboard's manual Run now binds the sibling profile via
web_server_cron._cron_store_scope, not the ticker's _profile_cron_scope,
so the marker-based routed_profile_fire() stayed False there: the routed
profile's .env was reloaded into the shared os.environ and the managed
external-worker handoff serialized multiplex_active=False.
routed_profile_fire() now compares the fire's active HERMES_HOME with
get_routing_process_hermes_home(), so every entry point (ticker,
dashboard Run now, CLI, gateway forward) and the external-worker handoff
share one answer. Regression test drives the real dashboard fire path
A -> B -> A with no_agent jobs.
Widening secret_source_names() to include skipped_existing names silently changed
tools/mcp_tool_config.py::_build_safe_env, an untouched consumer that forwards every
returned name into MCP stdio child envs. That consumer wants only names a source
actually APPLIED (pre-stack semantics), so secret_source_names() goes back to
tuple(_SECRET_SOURCES).
The routed-child scrub in strip_launch_profile_env is the one site that must also see
names a source supplied but lost to a pre-existing process value, so it reads the new
source_supplied_names() accessor instead. tools/mcp_tool_config.py is byte-identical to
origin/main.
(cherry picked from commit dcdbcb8a2b)
(cherry picked from commit b1b07b03440e1e35a2a2c8e33738618399c8b900)
_hydrate_profile_secret_sources and _apply_external_secret_sources each
rebuilt the same "applied + skipped_existing" set and pushed it into
_SOURCE_SUPPLIED_NAMES; the routed-child scrub depends on both sites
agreeing, so give them one helper.
refresh_installed_secret_scope cleared the installed scope before
refilling it, which left a window where a concurrent reader of the same
fire saw no credentials at all. Update first, then pop the names the
rebuild no longer supplies; stale values still disappear.
(cherry picked from commit 0916191ca1)
(cherry picked from commit 5b28b2b54f4f5020c0da00fa18ac735e479a9418)
Review findings on f5f88d5058. Three are defects the previous round introduced.
Managed keys were stripped as launch residue. Recording every dotenv load as
residue swept in the administrator-managed `.env`, which `_apply_managed_env`
applies LAST with override precisely so it beats the user's own `.env`. A
routed child then lost `ORG_POLICY_FLAG=managed-value` to the routed user's
`user-value`. Managed keys are now recorded separately, never enter the
residue set, and are re-applied over the routed scope in both child builders
(`scheduler_script`, the restart-safe handoff) so the child sees the same
precedence the launch process does. `kanban_db_dispatch` and
`scheduler_delivery` strip without any overlay, so for them the exclusion
alone is the guarantee; the test pins the case that exercises it — the same
key defined in both the user and the managed file.
Private hydration did not record supplied names. `_hydrate_profile_secret_sources`
now feeds `provenance` plus `skipped_existing` into the same ownership set the
process-global path uses; the provenance label map stays applied-only.
Removal cleanup cleared its marker before the fallible work. A raising
reload left the removed plugin's credential active with no retry, because the
next no-source discovery saw the flag already false. The marker is cleared
only after reset, reload and installed-scope refresh succeed.
Routed fire not multiplexed at the handoff. `run_one_job` enables the
context in `_install_fire_secret_scope`, which runs AFTER
`_launch_external_cron_worker`, so a routed desktop fire on the managed path
serialized `multiplex_active=False` and built the worker env with launch
residue and no scrub. The handoff now treats `routed_profile_fire()` as
multiplexed for exactly its own span; the worker re-establishes the state from
the payload as before.
Each fix was checked by reverting it and confirming its regression fails,
including the overlay half and the exclusion half of the managed fix
separately.
(cherry picked from commit 329cbd8963d68c45b425e95a5b11ade59f513960)
(cherry picked from commit 62b4488cb5)
(cherry picked from commit d3319102a7e4dcce35ec2676fe22aed41613e893)
Review findings on d8c467f223, each reproduced through its production path.
Stale launch key. `strip_launch_profile_env` built its residue set from a
re-parse of the launch `.env`. A key removed or renamed in that file after
boot is still in `os.environ` with the old value (dotenv never unsets), and
the current file no longer names it, so it survived into the routed child.
`_load_dotenv_with_fallback` — the one chokepoint every dotenv load goes
through — now records the KEY names it put into the process env, additive for
the process lifetime (`launch_dotenv_keys()`), and the strip unions that record
with the current file.
Source name that lost to the process env. `_apply_external_secret_sources`
snapshots every name a source SUPPLIED (`provenance` + `skipped_existing`),
but `secret_source_names()` only exposed `_SECRET_SOURCES`, which is
provenance metadata and names applied values alone. A launch-profile source
that supplied `CUSTOM_VAULT_SECRET` while the process already had it was
therefore invisible to the scrub, and a routed child with an empty scope got
the launch value. Supplied names are tracked separately
(`_SOURCE_SUPPLIED_NAMES`) so the provenance labels stay honest, and
`secret_source_names()` returns the union.
Last plugin source removed. `_refresh_secret_sources_after_discovery`
returned before the cache reset and the installed-scope refresh whenever no
plugin source was enabled — and `discover_and_load(force=True)` unloads the
old registration first, so removing the final plugin source hit exactly that
return with the removed plugin's names still in the per-home snapshot and the
current scope. The manager now remembers that a discovery re-applied plugin
sources and, on the next discovery that finds none, reconciles once. A home
that never had a plugin source is still a no-op (pinned by the existing tests).
Regressions: the stale-key lifecycle and the skipped-existing case through
`_run_job_script` against a real routed child, and the removal case through
the manager. Each checked by reverting its fix and confirming the test fails.
(cherry picked from commit d464f5f6126a394cfb47937f683d3a5e2f141840)
(cherry picked from commit 9d7de6c140)
(cherry picked from commit b0beb731b18edd884e36a30ab91c91687bc7a965)
The desktop backend ticks EVERY local profile's cron store from one process — its own docstring
says "like a multiplex gateway" (hermes_cli/web_server.py) — but never sets the process-global
multiplex flag, and cannot: its own chat turns are unscoped and would fail closed. Every
isolation in the tree keys on that flag — the guard that keeps a routed `.env` out of the shared
`os.environ`, `get_secret`'s fail-closed miss, passthrough resolution, the MCP and kanban
subprocess scrubs — so all of it was inert for a sibling profile's fire. Verified: a secondary
profile's API keys replaced the launch profile's in `os.environ` with `override=True` and stayed
there after the tick, and a scope miss read the launch profile's tokens (#107692).
Give multiplex mode a context-local counterpart. `set_multiplex_context` (agent/secret_scope.py)
is OR'd into `is_multiplex_active()`. `_profile_cron_scope` only MARKS a fire whose home is not
the process's own (`routed_profile_fire`, decided against `get_process_hermes_home()`, the
override-immune resolver); `_install_fire_secret_scope` in cron/scheduler.py installs the
profile's hydrated secret scope and, for a marked fire, the multiplex context — for exactly that
span, dropped again before the scope by `_reset_fire_secret_scope`. Multiplex semantics are
therefore never active in cron without a scope to read: `run_one_job`'s restart-safe handoff runs
before the body's scope and keeps today's semantics (its own scope is #107413 / #106050's seam,
left untouched so this composes with whichever lands). Every existing multiplex-keyed isolation
applies inside the routed fire with no per-site patching; the launch profile's own fires and the
backend's turns keep single-profile semantics; marker and override both reach the pool worker via
`copy_context()`. `get_secret` read the raw global in its miss branch; it now goes through
`is_multiplex_active()`. The dotenv guard keeps its pinned flag-only form (#77970).
Two consequences of suppressing the write are handled rather than left as regressions:
- a `no_agent` script's env is `os.environ.copy()`, which no longer carries the routed `.env`;
the runner overlays the installed scope onto the base BEFORE sanitizing, so the same scrub /
passthrough rules apply to those values and the parent process is never mutated;
- plugin secret sources are discovered on the fire's first agent build, after the scope froze,
and the post-discovery reload is hydrate-only under multiplex semantics; the refresh now folds
the values into the installed scope in place (`refresh_installed_secret_scope`, the pattern
`_publish_env_value` already uses for `.env` writes under multiplex).
And the profile's external secret sources are hydrated before the scope is frozen, the order
gateway/run.py and the external cron worker already use.
Tests pin each direction: the marker without the semantics before the scope, the semantics on and
off exactly with it, the marker reaching a copy_context worker; the process's own profile staying
single-profile; the restart-safe handoff's child env building without raising under a routed tick
with a passthrough key registered; a real child process receiving the routed values while
`os.environ` keeps the launch value; a source registered after the freeze reaching the fire
through the real PluginManager refresh. Reverting any one direction fails a distinct test.
(cherry picked from commit 2f87677425d2cca19286ac83bc45cab23e546669)
(cherry picked from commit dbede34f6e)
(cherry picked from commit a7ac197ff12710e045e3f75d960b20be952960f3)
The #125530 guard let any load whose TARGET was the launch home through while a
routed override was active. Inside a foreign profile's turn that load ends in
_reapply_terminal_config_bridge(launch), whose read_raw_config()/load_config_readonly()
follow the override, so the ROUTED profile's terminal.cwd was bridged into the shared
TERMINAL_CWD and the launch profile's next turn and cron job ran in the other tenant's
workdir (tests/e2e/core/tenancy/test_two_tenant_gateway.py red on CI). Require both the
target and the active home to be the launch home; the launch profile's own scoped bodies
(override naming the launch home) still load, a routed profile's .env still never does.
tests/agent/test_skip_background_review.py: the fixture pointed HERMES_HOME at a named
profile dir that never existed and built an AIAgent inside it; that only worked because
setup_logging() used run_agent's import-time home. It now logs under the ACTIVE home, and
mkdir_under_hermes_home() refuses to materialize a missing named profile by design
(load_config()'s ensure_hermes_home() and SessionDB refuse the same home, #94590), so the
test creates the profile dir. No assertion changed.
The salvaged test wrote the live process home's .env; the replacement uses two tmp homes (launch loads, routed does not, launch loads again) under set_multiplex_active(True).
The multiplex guard in load_hermes_dotenv() skipped the dotenv load whenever
a routed profile-home override was active AND multiplexing was on, even when
the load's target home IS the process launch home. Under the desktop/serve
backend the launch profile's own scoped bodies bind an override naming the
launch home (tui_gateway.model_switch._profile_runtime_scope_tokens(None)),
so its .env never loaded: 'No .env file found. Using system environment
variables.' and launch-profile-only credentials (e.g. an OPENROUTER_API_KEY
backing fallback_providers) were invisible to the process, silently breaking
failover.
Restrict the skip to loads whose target is a FOREIGN (routed) profile home,
using the same override-immune launch-home comparator _reapply_terminal_config_bridge
already uses in this file. The routed profile's .env is still never copied
into the shared os.environ (isolation intent of 1aa62ceb45 preserved).
(cherry picked from commit 0c71a329f48195a5c242d09ca6e92bb1c2842640)
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).
Symptom: a host that serves several profiles from one process and mirrors
the active turn's profile into `os.environ["HERMES_HOME"]` for legacy
readers (Hermes WebUI does this on every chat turn, next to the
context-local override) makes every launch-home decision see the served
profile as the launch profile. Two profiles that both configure `atlassian`
with different credentials share whichever MCP connection came first: a
READ_ONLY_MODE=false profile ends up calling a read-only server
(nesquena/hermes-webui#7721). The same misjudgement leaves the launch
residue in the served profile's child env, seeds the launch profile's
bridged allow-all grant into the served profile's secret scope, and lets
the served profile's `terminal.*` config bridge into the shared process env.
Cause: four launch-home checks compare the task's override with
`get_process_hermes_home()`, which reads `HERMES_HOME` live:
`agent.secret_scope.serves_routed_profile` (keys the MCP ledger via
`_mcp_registry_scope`, #108352 / #111481, and the check_fn cache, #111151),
`agent.secret_scope._is_process_home`, `tools.environments.local._is_routed_home`
and `hermes_cli.env_loader._process_hermes_home`. Under the mirror the two
sides are equal for every turn.
Change: `hermes_constants.pin_process_hermes_home(path | None)` lets the
host record the home it serves as its own; `get_routing_process_hermes_home()`
returns the pin when set, else `get_process_hermes_home()`; the four checks
compare against it. The pin is deliberately NOT folded into
`get_process_hermes_home()`: `get_hermes_home()` falls back to it for tasks
carrying no override (MCP loop, spawners), and the host's mirror exists
precisely so those readers see the served profile. Only "is this task
routed / is this the launch home" changes. Unpinned, behaviour is
byte-for-byte the old one; hosts that never mutate `HERMES_HOME` need not
call it. `activate_multi_profile_hosting()` is not the seam for this: it
flips `get_secret` fail-closed process-wide and freezes the launch env,
which an embedding host cannot adopt as a bug fix.
Tests (2 invariants, parametrized over the four checks plus the MCP ledger
key; red on main, green here): pinned + mirrored env -> the served home is
routed and the launch home is not, the MCP key is `(home_key, name)`,
`get_process_hermes_home()` still follows the env var; never pinned or
pinned-then-cleared -> old semantics, including "a mirrored env var IS the
launch home". `tests/conftest.py` resets the pin per test so the
module-global cannot leak between files.
Live repro (WebUI + a stdio FastMCP server named `atlassian` in two
profiles, one gated by READ_ONLY_MODE): base -> one ledger key
`'atlassian'`, the write profile lists only the read-only tools; fixed ->
`(<read_home_key>, 'atlassian')` and `(<write_home_key>, 'atlassian')`,
each profile lists its own tools.
Docs: `gateway/AGENTS.md` § Profile scope (one launch-home identity) and the
isolation table in `website/docs/user-guide/multi-profile-gateways.md`.
Also maps the author e-mail under contributors/emails/ (attribution check).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
restore_heartbeat_watches entered _profile_scope_for_source for every routed
session on every poll. Each entry hydrated the profile secret scope and rebuilt
the terminal policy, and both re-parsed the profile config.yaml from disk, so N
routed sessions cost 2N YAML parses per poll even though nothing changed.
- Group entries by resolved profile home and enter the scope once per group.
- Add utils.load_yaml_file_readonly (file_signature-keyed cache) and use it in
env_loader._load_secrets_config and terminal_scope.build_profile_terminal_scope,
which were both open()+fast_safe_load per scope entry. Present-but-unparseable
still fails closed: parse errors propagate and are never cached.
Measured on a 3-profile host: one _profile_runtime_scope enter/exit 1.80 ms -> 0.11 ms.
(cherry picked from commit c6b16629bd38799bbf166206c73a6140a9559a61)
Branch semantics kept where main and PM disagree: update_cmd_deps.py,
constraints-termux.txt, the Electron update-api-check module and the
post-swap hand-off test stay deleted; the pending-fleet-restart catch-up
and the local_runtime tag/download ladder stay retired (PM owns engines).
Ported from main onto the branch's shape: profile_scoped_chore for the
auto-archive and plugin-update housekeeping chores, the local-runtime
cross-process boot lock and residency cap, the checkpoint tmp_pack sweep,
the cua daemon-liveness status probe, the remote-served Desktop update
flag (posix.sh / windows.ps1), sign-in for env-pinned remote gateways
(urlDisabled on RemoteSetupFields), the uvloop extra split (uvicorn
without [standard]), and the umask-scoping spawn test.
uv.lock regenerated with pm.build_env --lock-only; new utf-8 reads from
main switched to utf-8-sig (check-windows-footguns).
A launcher that spawns `hermes dashboard` (Desktop shell, link-style
integrations) mints HERMES_DASHBOARD_SESSION_TOKEN into the child's
environment and keeps the same token for its own /api probes. Every
dotenv layer in load_hermes_dotenv() loads with override=True, so a
persisted HERMES_DASHBOARD_SESSION_TOKEN line in ~/.hermes/.env replaced
the injected token: the child authenticated with the persisted value and
the parent got HTTP 401 from its own child.
Treat the token as a spawn credential in the dotenv publisher: a value
that dotenv did not put into os.environ (tracked by _DOTENV_PUBLISHED)
is left alone, while a value an earlier pass published still reloads,
so .env edits and home switches behave as before. Other keys, including
the documented HERMES_DASHBOARD_PUBLIC_URL, keep .env-wins precedence.
Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Co-authored-by: fangliquan <fangliquan@qq.com>
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.
The per-home snapshot (`_SECRET_SOURCE_VALUES_BY_HOME`) deliberately also holds names the source
supplied but .env/shell WON (`skipped_existing`, #102041) — `build_profile_secret_scope` needs them.
Re-asserting the whole snapshot on a dotenv reload therefore froze a gap-filled or preserve-listed
name at its first-load value and a later .env edit lost, where a cold start would have honoured it.
`AppliedVar.authoritative` (= `override_existing` and not `preserve_existing`, computed where the
precedence is decided) feeds a per-home restore subset `_SECRET_SOURCE_RESTORE_BY_HOME`; the reload
re-asserts only that. The contributor's pre-load snapshot is dropped: nothing between the dotenv loads
writes the module dict, so reading the subset at the restore site is equivalent and skips the copy.
load_hermes_dotenv() snapshots the values that an external secret source
(Bitwarden, 1Password, ...) already resolved for THIS home before
load_dotenv(override=True) below can write a raw .env placeholder back
over them. After the dotenv loads, restore those values so BSM-resolved
secrets survive every reload (#74265).
Snapshot must come from the per-home get_secret_source_values(home_path)
and not from the process-global _SECRET_SOURCES map. The global map
records the latest source label for each key, but a value is only safe
to restore for the home that actually resolved it. In a multiplex
gateway, restoring from the global map would replace home B's freshly
loaded dotenv value with home A's external-secret snapshot, defeating
the per-HERMES_HOME isolation introduced in 0583692c2d (#74283).
Restore ordering follows get_secret_source_values()'s dict iteration
order so the protection is deterministic. Managed scope (applied last
by _apply_managed_env with override=True) still intentionally beats an
external-source value -- this only undoes the dotenv clobber.
Adds two focused regressions:
* test_multiplex_dotenv_value_not_clobbered_by_other_profile_external_secret
seeds home A's external snapshot and verifies home B's dotenv
value (a different key value) is preserved.
* test_multiplex_external_secret_survives_reload_for_own_home
proves the original #74265 protection still holds for the home
that actually resolved the secret, while a sibling home's dotenv
load does not clobber that home's value.
Scope: hermes_cli/env_loader.py, tests/test_env_loader_secret_sources.py.
Ported the useful logical behavior from the original PR onto the current
pinned-base architecture.
Gateway tests replace sys.modules["dotenv"] with a bare module exposing only
load_dotenv; gateway.run imports env_loader at import time, so the module-level
dotenv.main / dotenv.variables imports broke every one of those files in CI.
load_hermes_dotenv() runs per gateway turn, per cron fire, and from plugins /
MCP config / `hermes send`, each time re-applying .env with override. dotenv
interpolates `${VAR}` against the live os.environ, which already holds the
previous load's output, so `PATH=/x:${PATH}` gains one `/x:` per reload until
child spawns fail with E2BIG (#109902).
Resolve inside _load_dotenv_with_fallback — the one seam every caller goes
through — against a private copy of os.environ in which this process's own
earlier dotenv output is peeled back to the value the variable had before we
first published it. The record is one process-wide per-variable table, not a
per-home/per-project scope: os.environ is process-wide, so a gateway reload
(project .env) alternating with a cron reload (none), or home A then B, must
peel each other's output too. Only values that still hold exactly what we
published are peeled, so shell exports, the terminal config bridge, and
external secret sources changing a value between reloads are honoured, not
frozen. Layers within one load_hermes_dotenv share a pass so the project and
managed .env still build on the user .env as before.
Co-authored-by: Hukla <129692708+huklaa@users.noreply.github.com>
Co-authored-by: Sahilvishnaliya <141555468+salch-cred@users.noreply.github.com>
Squashed integration of the user-facing message audit for this surface set.
Full per-finding receipts: /tmp/ux-audit/lanes/*-receipt.md (campaign artifacts).
Widening secret_source_names() to include skipped_existing names silently changed
tools/mcp_tool_config.py::_build_safe_env, an untouched consumer that forwards every
returned name into MCP stdio child envs. That consumer wants only names a source
actually APPLIED (pre-stack semantics), so secret_source_names() goes back to
tuple(_SECRET_SOURCES).
The routed-child scrub in strip_launch_profile_env is the one site that must also see
names a source supplied but lost to a pre-existing process value, so it reads the new
source_supplied_names() accessor instead. tools/mcp_tool_config.py is byte-identical to
origin/main.
_hydrate_profile_secret_sources and _apply_external_secret_sources each
rebuilt the same "applied + skipped_existing" set and pushed it into
_SOURCE_SUPPLIED_NAMES; the routed-child scrub depends on both sites
agreeing, so give them one helper.
refresh_installed_secret_scope cleared the installed scope before
refilling it, which left a window where a concurrent reader of the same
fire saw no credentials at all. Update first, then pop the names the
rebuild no longer supplies; stale values still disappear.