The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernetc13287c915e6
diff --cc .github/workflows/lint.ymlindex 9056185d275,a5b0c90f62c..65305674355--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@@ -182,8 -193,13 +182,13 @@@ jobs- name: Forbid literal /tmp paths outside the baselinerun: python scripts/check_no_tmp_literals.py+ # config.yaml is hand-edited and commented; a PyYAML dump of it destroys every comment+ # (#92554, regressed repeatedly). All writers go through hermes_cli.config.atomic_config_write.+ - name: Forbid config.yaml writers that bypass the comment-preserving writer+ run: python scripts/check_config_yaml_writers.py+# The OS lanes import only files carrying the matching marker, so a test that fakes- # macOS (is_macos -> True, sys.platform -> "darwin") without `macos_only` is green on+ # macOS (is_macos -> True, sys.platform -> "darwin") without `platforms("macos")` is green on# Linux over a faked branch and never runs on macOS (#111866, AGENTS.md § Don't fake the host OS).- name: Forbid unmarked macOS fakes in testsrun: python scripts/ci/check_os_marker_fakes.pydiff --cc apps/desktop/electron/main.tsindex 4ec40c4f6b5,6779b7ac93b..41e03aafbf8--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -12140,14 -13135,13 +12140,14 @@@ function releaseHostSpawnReservation()hostSpawnReservation = null}- function startHermes(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {-function startHermes({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}) {++function startHermes({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {primaryRecoverySuppressed = falseprimaryStartsInFlight += 1- const start = localBackendLifecycle.start(() => runHermesStart({ supervisorRecovery }))+ const start: Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> =- localBackendLifecycle.start(runHermesStart)++ localBackendLifecycle.start(() => runHermesStart({ supervisorRecovery }))- const releaseStart = () => {+ const releaseStart = (): void => {primaryStartsInFlight -= 1}@@@ -12156,6 -13157,56 +12163,58 @@@return start}+ function primaryRecoveryState() {+ return {+ hasCurrentOwner: backendConnectionState.getProcess() !== null || backendConnectionState.getPromise() !== null,+ hasPendingStart: primaryStartsInFlight > 0,+ intentionalTeardown: primaryRecoverySuppressed || isQuittingForHandoff || backendShutdown.hasStarted()+ }+ }++ function reportPrimaryRecoveryCrashLoop(code: number | null, signal: string | null): boolean {+ if (!primaryExitRecovery.isCrashLooping()) {+ return false+ }++ const message =+ 'Hermes backend keeps crashing right after it restarts; not restarting it again. Relaunch Hermes Desktop.'++ rememberLog(`[supervisor] ${message}`)+ sendBackendExit({ code, signal, error: message })++ return true+ }+++const firstLine = (text: string): string => (text || '').split('\n').find(Boolean) || ''+++ function runPrimaryRecoverySpawn(code: number | null, signal: string | null) {+ startHermes({ supervisorRecovery: true }).catch(respawnError => {+ rememberLog(`[supervisor] backend respawn failed: ${firstLine(respawnError.message)}`)++ // Terminal boot failures still own their existing recovery UI. Only a+ // supervisor-owned respawn that failed transiently before ready may spend+ // another bounded recovery slot.+ const latched = latchedBootFailure()++ if (latched) {+ rememberLog(`[supervisor] respawn refused: boot failure latched: ${firstLine(latched.message)}`)++ return+ }++ // releaseStart (startHermes) already ran: same-promise reaction order, so+ // hasPendingStart is false here. See the ordering contract in startHermes.+ if (primaryExitRecovery.retryAfterFailedStart(primaryRecoveryState())) {+ rememberLog('[supervisor] backend respawn failed before ready; retrying within crash-loop budget')+ runPrimaryRecoverySpawn(code, signal)++ return+ }++ reportPrimaryRecoveryCrashLoop(code, signal)+ })+ }+// A ready primary child died. When its exit leaves the primary slot with no// owner and no start in flight (outside an intentional teardown), the// supervisor owns the respawn (#112344): the stale-classified exit used to@@@ -12199,7 -13236,18 +12244,18 @@@ function scheduleUnexpectedPrimaryRecovreturn true}- async function runHermesStart(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {+ /**+ * The terminal boot failure currently latched in this process, if any. These+ * latches are cleared only by an explicit recovery path (reset, repair,+ * apply-config, confirmed sign-in, or the child 'exit' handler), never by a+ * retry, so both the per-request short-circuit in runHermesStart and the+ * supervisor's respawn refusal must consult the same trio in the same order.+ */+ function latchedBootFailure(): Error | null {+ return bootstrapFailure ?? backendStartFailure ?? remoteReauthFailure ?? null+ }+-async function runHermesStart({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}) {++async function runHermesStart({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {// Only the single-instance lock holder may reap/spawn/claim the desktop// backend. A lock-losing instance must stay inert even if some path reaches// here (e.g. the deferred-quit window before `ready`): its reapOrphans()diff --cc apps/desktop/src/store/notifications.tsindex 87950e4e23c,00fd7c22243..ddccd7faac3--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@@ -247,24 -257,13 +257,28 @@@ export function notify(input: Notificatreturn id}+// Toast copy can omit the stack or shorten the message. Keep both in desktop.log.+function logErrorToDesktopLog(error: unknown, fallback: string): void {+ try {+ const label: string = new URLSearchParams(window.location.search).get('win') ?? 'main'++ const raw: string =+ error instanceof Error ? (error.stack ?? error.message) : typeof error === 'string' ? error : fallback++ window.hermesDesktop?.logLine?.(`[renderer error:${label}] ${fallback}: ${raw}`)+ } catch {+ // A missing or closed IPC bridge must not prevent the error toast.+ }+}+- export function notifyError(error: unknown, fallback: string, options: { action?: NotificationAction } = {}): string {+ export function notifyError(+ error: unknown,+ fallback: string,+ options: { action?: NotificationAction; id?: string } = {}+ ): string {const readable = readableError(error, fallback)const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)+ logErrorToDesktopLog(error, fallback)return notify({action: poolSlotTimeoutdiff --cc hermes_cli/AGENTS.mdindex 2ddf601bf35,421af5da92e..a5d6d4d35de--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@@ -84,9 -84,17 +84,17 @@@ archive_after_days, backup.*`Non-secret settings go in config.yaml; if internal code needs an env mirror, bridge it in code(`gateway_timeout`; `terminal.cwd` → `TERMINAL_CWD`). `MESSAGING_CWD` is removed and `TERMINAL_CWD`in `.env` is deprecated — the loader warns; canonical is `terminal.cwd`. `hermes config- set/get/unset <NAME>` route any bare name registered in `OPTIONAL_ENV_VARS` / `_EXTRA_ENV_KEYS`+set/get/unset <NAME>` route any bare name registered in `OPTIONAL_ENV_VARS` / `_EXTRA_ENV_KEYS`(or carrying a `setup_hidden_env` platform suffix) to `.env` via `config_env_routing.py` — thefile the platform setup flows write — never to the top level of config.yaml.+ - **One writer.** Every write of a `config.yaml` (main or profile) goes through+ `hermes_cli.config.atomic_config_write` (→ `utils.atomic_roundtrip_yaml_save`, ruamel+ round-trip merge): comments, key order, quoting and blank lines survive, absent keys are+ deleted, and the fail-closed unreadable-file guard runs first. `save_config`, `config set/unset`,+ migrations, plugin bookkeeping, gateway/TUI RPCs and auth resets all reach it; never call+ `atomic_yaml_write` / `yaml.dump` / `yaml.safe_dump` on a config path — `scripts/check_config_yaml_writers.py`+ (CI lint) rejects it, and `tests/hermes_cli/test_config_yaml_comment_preservation.py` guards each+ path (#92554). The commented example blocks are appended only when the file is created.- **Three loaders — know which you're in:** `load_cli_config()` (CLI, `cli.py`); `load_config()`(`hermes tools/setup`, most subcommands, `hermes_cli/config.py`, merges `DEFAULT_CONFIG`);`hermes_cli/config_effective.py::load_user_config_effective()` (gateway runtime viadiff --cc hermes_cli/backup.pyindex d83e0673e2c,16e7923db65..38cf0edc260--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -1734,33 -1529,20 +1734,33 @@@ def restore_config_model_settings_if_resnap_val = _get_config_path_value(snap, dotted)if snap_val in (None, "", {}, []):continue # user never set it — nothing to protect- if _get_config_path_value(live, dotted) != snap_val:- _set_config_path_value(live, dotted, snap_val)- restored_keys.append(".".join(dotted))+ live_val = _get_config_path_value(live, dotted)+ if live_val == snap_val:+ continue+ _set_config_path_value(live, dotted, snap_val)+ restored_keys.append(".".join(dotted))+if not restored_keys:return None+try:- from utils import atomic_yaml_write+ from hermes_cli.config import atomic_config_write+- atomic_yaml_write(live_path, live)+ atomic_config_write(live_path, live)except (OSError, PermissionError) as exc:- logger.error("config.yaml model settings were rewritten during update but auto-restore failed: %s", exc)+ logger.error(+ "config.yaml model settings were rewritten during update but "+ "auto-restore failed: %s",+ exc,+ )return None+logger.warning("Restored user config value(s) %s from pre-update snapshot %s — "- "the update flow rewrote them (#64160)", ", ".join(restored_keys), snapshot_id)+ "the update flow rewrote them (#64160)",+ ", ".join(restored_keys),+ snapshot_id,+ )return {"restored": True, "keys": restored_keys, "snapshot_id": snapshot_id}diff --cc hermes_cli/config.pyindex 3786917a631,509cbc52fcc..a8c996898b4--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@@ -3898,21 -3924,31 +3952,31 @@@ _inject_profile_env_vars(def _platform_plugin_manifests():- """Yield ``(dir_name, manifest_dict)`` for every bundled ``plugins/platforms/*/plugin.y(a)ml``."""- platforms_dir = get_project_root() / "plugins" / "platforms"- if not platforms_dir.is_dir():- return- for child in platforms_dir.iterdir():- manifest_path = next(- (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)- if manifest_path is None:- continue- try:- with open(manifest_path, "r", encoding="utf-8-sig") as f:- manifest = fast_safe_load(f) or {}- except Exception:+ """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest: bundled+ ``plugins/platforms/*``, the user's ``<HERMES_HOME>/plugins/platforms/*`` category dir, and flat+ user installs ``<HERMES_HOME>/plugins/*`` that declare ``kind: platform`` (#46600)."""+ user_plugins = get_hermes_home() / "plugins"+ roots = (+ (get_project_root() / "plugins" / "platforms", False),+ (user_plugins / "platforms", False),+ (user_plugins, True), # flat layout: only manifests that say they are platforms+ )+ for root, require_kind in roots:+ if not root.is_dir():continue- yield child.name, manifest+ for child in root.iterdir():+ manifest_path = next(+ (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)+ if manifest_path is None:+ continue+ try:- with open(manifest_path, "r", encoding="utf-8") as f:++ with open(manifest_path, "r", encoding="utf-8-sig") as f:+ manifest = fast_safe_load(f) or {}+ except Exception:+ continue+ if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):+ continue+ yield child.name, manifestdef _inject_platform_plugin_env_vars() -> None:diff --cc hermes_cli/plugin_catalog.pyindex f1ce5503370,6a0d15a4cf1..96bd0c633ac--- a/hermes_cli/plugin_catalog.py+++ b/hermes_cli/plugin_catalog.py@@@ -8,8 -8,8 +8,8 @@@ the human-merged approval gate; SHA bumLive refresh: the docs build publishes the same data as ONE JSON document(``website/scripts/extract-plugins.py`` → ``/docs/api/plugin-catalog.json``, like the skills index), so--an installed Hermes sees new entries and removals without updating. Any fetch failure falls back to the--in-tree copy silently.++an installed Hermes sees new entries and removals without updating. A fetch failure reuses the last valid++cached copy regardless of age, then falls back to the in-tree copy when no valid cache exists."""from __future__ import annotationsdiff --cc hermes_cli/plugins_cmd.pyindex 8dec5b90086,a9bd2ad11f0..0bcd63f4381--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -776,11 -734,15 +777,15 @@@ def _install_plugin_core"""Clone a Git plugin and atomically record its source and exact revision.*reviewed_pin* is the curated-catalog sha for this install; the scan trusts the tree- only when the checked-out revision is exactly that sha. *python_deps* False refuses- active replacements; it never bypasses PM dependency admission. *catalog*+ only when the checked-out revision is exactly that sha (an annotated-tag pin is peeled to- its commit first — HEAD can only ever be the commit). *python_deps* False skips the- dependency conflict gate (``--no-deps``: the user installs them by hand). *catalog*++ its commit first — HEAD can only ever be the commit). *python_deps* False refuses active++ replacements; it never bypasses PM dependency admission. *catalog*(``{"name", "repo", "tier", "pin"}``) is recorded on the install-metadata record with the- checked-out sha — provenance lives OUTSIDE the plugin tree, so a repo cannot forge it.- *allow_removed* records that the user knowingly bypassed the kill list."""+ checked-out sha — provenance lives OUTSIDE the plugin tree, so a repo cannot forge it;+ its ``pin`` is kept only when the checkout satisfies it (a ``--ref`` install is off-pin).+ *allow_removed* records that the user knowingly bypassed the kill list.+ *before_swap(manifest, tree)* runs on the validated clone before anything moves into place+ and may raise :class:`PluginOperationError` to abort (re-pin consent)."""requested_revision = _normalize_exact_revision(ref) if ref is not None else Nonetry:git_url, subdir = _resolve_git_url(identifier)@@@ -813,14 -778,11 +821,16 @@@_check_manifest_version(manifest, plugin_name)# Scan BEFORE anything is moved into place; raises PluginScanBlocked when blocked._scan_plugin_tree(tmp_target, identifier, force=force, scan_decision_cb=scan_decision_cb,- reviewed_pin=bool(reviewed_pin) and installed_revision == reviewed_pin)+ reviewed_pin=at_reviewed_pin)- if python_deps:- _refuse_conflicting_python_deps(tmp_target, plugin_name)+ if not python_deps:+ from pm.workspace import enabled_plugin_dirs++ if target.resolve() in enabled_plugin_dirs(installing=target):+ raise PluginOperationError(+ "--no-deps cannot replace an active plugin. Retry without --no-deps; "+ "PM must prepare its dependencies before publication.")+ if before_swap is not None:+ before_swap(manifest, tmp_target)if target.exists() and not force:raise PluginOperationError(@@@ -833,24 -795,11 +843,30 @@@"--ref <40-character commit SHA> to change its source or revision.")record: dict[str, object] = {- "pinned": requested_revision is not None, "revision": installed_revision, "source": source}+ "pinned": requested_revision is not None,+ "revision": installed_revision,+ "source": source,+ }+ # Saved update_url tag (settled: claims vs provenance): the+ # manifest's update_url is COPIED into the row at install. Check+ # time compares manifest vs tag; a mismatch is needs-fixing and+ # only `hermes plugins trust-update-url` moves the tag.+ if manifest.get("update_url"):+ from hermes_cli.plugins_updates import https_update_url+ try:+ record["update_url"] = https_update_url(manifest["update_url"])+ except ValueError as exc:+ raise PluginOperationError(f"Plugin '{plugin_name}' {exc}") from excif catalog:- record["catalog"] = {**catalog, "sha": installed_revision}+ # ``sha`` = the commit checked out; ``pin`` = the reviewed catalog sha it satisfies (the+ # annotated-tag object for a tag pin), empty when installed off-pin via ``--ref``.- record["catalog"] = {**catalog, "sha": installed_revision, "pin": reviewed_pin if at_reviewed_pin else ""}++ record["catalog"] = {++ **catalog,++ "sha": installed_revision,++ "pin": reviewed_pin if at_reviewed_pin else "",++ }+ from hermes_cli.plugins_cmd_catalog import write_catalog_sidecar_record+ write_catalog_sidecar_record(tmp_target, catalog, installed_revision)if allow_removed:record["allow_removed"] = Truenew_metadata = {**old_metadata, plugin_name: record}@@@ -999,27 -901,53 +1015,47 @@@ def cmd_installconsole.print()-def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None) -> str:+def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None, *, interactive: bool = False) -> str:- """Shared ``update`` core: refuse pinned / non-git checkouts, ``git pull``, record the new+ """Shared ``update`` core: refuse pinned checkouts, ``git pull`` (or re-install from the+ recorded source when the tree carries no ``.git`` — subdirectory installs), record the newrevision. Returns the pull output; raises :class:`PluginOperationError` on any refusal.*pinned_msg(install_record)* / *not_git_msg()* build the caller-specific error text."""metadata = _read_install_metadata()install_record = metadata.get(target.name, {})if install_record.get("pinned") is True:raise PluginOperationError(pinned_msg(install_record))- if not (target / ".git").exists():- raise PluginOperationError(not_git_msg())- # A URL install whose name/repo later landed on the kill list must not keep pulling new code.++ # A URL install whose name/repo later landed on the kill list must not keep pulling or++ # re-cloning new code, including subdirectory installs that carry no local .git directory.+ from hermes_cli import plugins_cmd_catalog as catalog+ catalog.refuse_if_installed_removed(target.name, target)+ if not (target / ".git").exists():+ source = install_record.get("source")+ if not isinstance(source, str) or not source:+ raise PluginOperationError(not_git_msg())+ if before_pull is not None:+ before_pull()+ return _reclone_plugin_update(source, install_record.get("revision"))- # A URL install whose name/repo later landed on the kill list must not keep pulling new code.- from hermes_cli import plugins_cmd_catalog as catalog- catalog.refuse_if_installed_removed(target.name, target)if before_pull is not None:before_pull()- ok, output = _git_pull_plugin_dir(target)- if not ok:- raise PluginOperationError(output)- # Store the new HEAD in the plugin's install-metadata record (if it has one).- git_exe = _resolve_git_executable() if install_record else None- if git_exe:- install_record["revision"] = _git_head_revision(target, git_exe)- metadata[target.name] = install_record- _write_install_metadata(metadata)- return output+ from hermes_cli.plugins_transaction import update_plugin++ return update_plugin(target, interactive=interactive)+ def _reclone_plugin_update(source: str, previous_revision: object) -> str:+ """Update a plugin whose tree is not a git checkout: a subdirectory install ships only+ ``<clone>/<subdir>``, so the ``.git`` stays in the temp clone (#65314). Re-run the install+ from the recorded source (same URL, same subdir) and swap the fresh tree in; the metadata+ revision is rewritten by the installer. Returns pull-shaped output for the callers."""+ new_target, _manifest, _name = _install_plugin_core(source, force=True)+ revision = str(_read_install_metadata().get(new_target.name, {}).get("revision") or "")+ previous = previous_revision if isinstance(previous_revision, str) else ""+ if revision and revision == previous:+ return "Already up to date."+ return f"Re-installed from {source}: {previous[:8]}..{revision[:8]}"++-def cmd_update(name: str) -> None:+def cmd_update(name: str, *, interactive: bool = True) -> None:"""Update an installed plugin by pulling latest from its git remote."""from rich.markup import escapefrom hermes_cli import plugins_cmd_catalog as catalog@@@ -1182,22 -1128,68 +1242,78 @@@ def _discard_key_and_leaf(names: set, knames.discard(key.split("/")[-1])+ def _plugin_aliases(key: str) -> set:+ """Every spelling a config list may hold for *key*: the key, its bare leaf and the manifest name.+ The loader matches BOTH the canonical key (``web/firecrawl``) and the manifest name+ (``web-firecrawl``), so a stale entry under any form vetoes an enable ("explicit disable wins")."""+ names = {key, key.split("/")[-1]}+ names.update(e[0] for e in _discover_all_plugins() if e[5] == key)+ return names++-def _activate_key(key: str, *, enable: bool) -> bool:- """Persist canonical *key* as enabled/disabled, purging every alias from the opposing list.- False when the lists already say so (nothing written)."""++def _activate_key(key: str, *, enable: bool, console=None) -> bool:++ """Transactionally persist canonical *key*, purging aliases from the opposing list.++++ False when the lists already say so (nothing written). PM owns the selection and dependency++ publication together, so every CLI/dashboard activation surface goes through the same admission++ transaction instead of writing ``config.yaml`` directly."""+ enabled, disabled = _get_enabled_set(), _get_disabled_set()+ aliases = _plugin_aliases(key)+ target, other = (enabled, disabled) if enable else (disabled, enabled)+ if key in target and not (aliases & other):+ return False- target.add(key)- other.difference_update(aliases)- _save_plugin_sets(enabled, disabled)++ _set_plugin_enabled(key, enable=enable, aliases=aliases, console=console)+ return True+++ def _forget_plugin_config(aliases: set) -> dict[str, Any]:+ """Drop every trace of a removed plugin (its :func:`_plugin_aliases`, taken BEFORE the tree went)+ from config.yaml: allow/deny-list entries, ``plugins.entries.<id>`` grants and a ``memory.provider``+ selection naming it. A later reinstall under the same name must start from the "Enable now?"+ decision, not inherit a stale enable or grant (#54336); a dangling ``memory.provider`` would make+ the next agent init re-clone the plugin from the catalog, silently undoing the uninstall.+ Returns ``{"cleared_memory_provider": True}`` when the selection was reset."""+ from hermes_cli.config import load_config, save_config+ config = load_config()+ changed = False+ result: dict[str, Any] = {}+ plugins_cfg = config.get("plugins")+ if isinstance(plugins_cfg, dict):+ for list_key in ("enabled", "disabled"):+ names = plugins_cfg.get(list_key)+ if isinstance(names, list) and aliases & set(names):+ plugins_cfg[list_key] = sorted(set(names) - aliases)+ changed = True+ entries = plugins_cfg.get("entries")+ if isinstance(entries, dict) and aliases & set(entries):+ for alias in aliases & set(entries):+ del entries[alias]+ changed = True+ memory_cfg = config.get("memory")+ if isinstance(memory_cfg, dict) and str(memory_cfg.get("provider") or "").strip() in aliases:+ memory_cfg["provider"] = ""+ changed, result = True, {"cleared_memory_provider": True}+ if changed:+ save_config(config)+ return result++-def _set_plugin_enabled(name: str, *, enable: bool) -> None:- """Move *name* between the enabled allow-list and the disabled deny-list and persist both."""- enabled = _get_enabled_set()- disabled = _get_disabled_set()- (enabled.add if enable else enabled.discard)(name)- (disabled.discard if enable else disabled.add)(name)- _save_plugin_sets(enabled, disabled)+def _set_plugin_enabled(name: str, *, enable: bool, aliases=(), console=None) -> None:+ """Submit the command's delta with the version of the selection it read."""+ from pm.plugins_state import read_home_selection++ expected_config = _plugin_selection_version()+ config = read_home_selection(get_hermes_home()) or {}+ plugins = config.get("plugins") or {}+ enabled = set(plugins.get("enabled") or ())+ disabled = set(plugins.get("disabled") or ())+ removed = disabled if enable else enabled+ _discard_key_and_leaf(removed, name)+ removed.difference_update(aliases)+ (enabled if enable else disabled).add(name)+ _admit_and_save_plugin_sets(enabled, disabled, console=console,+ action=f"{'Enable' if enable else 'Disable'} '{name}'",+ expected_config=expected_config)def _resolve_plugin_key(name: str) -> Optional[str]:@@@ -1264,17 -1256,10 +1380,10 @@@ def cmd_enable(name: str, allow_tool_ovexcept PluginOperationError as exc:_fail(console, f"[red]Error:[/red] {exc}")- enabled = _get_enabled_set()- disabled = _get_disabled_set()- if key in enabled and key not in disabled:- console.print(f"[dim]Plugin '{key}' is already enabled.[/dim]")- else:- # The loader's disable check matches BOTH the canonical key (``web/firecrawl``) and the- # manifest name (``web-firecrawl``); a stale entry under either form would silently veto- # this enable ("explicit disable wins"), so drop the key, its bare leaf, and the name.- manifest_name = next((e[0] for e in _discover_all_plugins() if e[5] == key), None)- _set_plugin_enabled(key, enable=True, aliases=(() if manifest_name is None else (manifest_name,)), console=console)- if _activate_key(key, enable=True):++ if _activate_key(key, enable=True, console=console):console.print(f"[green]✓[/green] Plugin [bold]{key}[/bold] enabled. Takes effect on next session.")+ else:+ console.print(f"[dim]Plugin '{key}' is already enabled.[/dim]")# Built-in tool override is a privileged grant; bundled plugins are trusted.if source == "bundled":@@@ -1439,12 -1425,9 +1548,9 @@@ def cmd_disable(name: str) -> Nonekey = _resolve_plugin_key(name)if key is None:_fail(console, _unknown_plugin_message(name))- enabled = _get_enabled_set()- disabled = _get_disabled_set()- if key not in enabled and key in disabled:- if not _activate_key(key, enable=False):++ if not _activate_key(key, enable=False, console=console):console.print(f"[dim]Plugin '{key}' is already disabled.[/dim]")return- _set_plugin_enabled(key, enable=False, console=console)console.print(f"[yellow]\u2298[/yellow] Plugin [bold]{key}[/bold] disabled. Takes effect on next session.")@@@ -2282,21 -2081,19 +2408,30 @@@ def _toggle_plugin_toolset(name: str, *def dashboard_set_agent_plugin_enabled(name: str, *, enabled: bool) -> dict[str, Any]:- """Enable or disable a plugin in ``config.yaml`` (runtime allow/deny lists)."""- if _resolve_plugin_key(name) is None:+ """Enable or disable a plugin in ``config.yaml`` (runtime allow/deny lists). *name* may be the+ canonical key, the manifest name or a unique bare leaf; the canonical key is what gets written+ (the loader never matches a bare leaf, and a stale key in ``disabled`` outranks a manifest-name+ entry in ``enabled`` — so writing the raw identifier reported success while the plugin stayed off)."""+ key = _resolve_plugin_key(name)+ if key is None:return {"ok": False, "error": f"Plugin '{name}' is not installed or bundled."}- en = _get_enabled_set()- dis = _get_disabled_set()- if ((name in en and name not in dis) if enabled else (name not in en and name in dis)):- return {"ok": True, "name": name, "unchanged": True}- changed = _activate_key(key, enable=enabled)+ from hermes_cli.plugins_admission import AdmissionRefused++ try:- _set_plugin_enabled(name, enable=enabled)++ changed = _activate_key(key, enable=enabled)+ except AdmissionRefused as exc:- return {"ok": False, "error": str(exc), "name": name, "unchanged": True}- _toggle_plugin_toolset(name, enable=enabled)- return {"ok": True, "name": name, "unchanged": False}++ return {++ "ok": False,++ "error": str(exc),++ "name": key,++ "unchanged": True,++ "restart_required": False,++ }+ if changed:+ _toggle_plugin_toolset(key, enable=enabled)+ # Config-only change: a running gateway/TUI scanned plugins once at start and will not pick it+ # up, so every UI can say so (the CLI prints "Takes effect on next session") — #71595/#54941.+ return {"ok": True, "name": key, "unchanged": not changed, "restart_required": changed}def _user_installed_plugin_dir(name: str) -> Optional[Path]:@@@ -2314,13 -2113,14 +2451,14 @@@ def dashboard_update_user_plugin(name:target = _user_installed_plugin_dir(name)if target is None:return {"ok": False, "error": f"Plugin '{name}' was not found under {_plugins_dir()}."}- sidecar = catalog.read_catalog_sidecar(target)+ sidecar = catalog.catalog_install_record(target)try:if sidecar:- result = catalog.repin_catalog_plugin(target, sidecar)+ result = catalog.repin_catalog_plugin(+ target, sidecar, consent_cb=(lambda _delta: True) if accept_capabilities else None)warnings = list(result.warnings)new_target = target.parent / result.installed_name- deps = _install_python_dependencies_quietly(new_target, warnings) if result.changed else []+ deps = _python_dependency_summary(new_target, warnings) if result.changed else []return {"ok": True, "name": result.installed_name, "sha": result.sha, "unchanged": not result.changed,"python_dependencies": deps, "warnings": warnings}msg = _pull_plugin_update(diff --cc hermes_cli/plugins_cmd_catalog.pyindex 35fe6ffa6bb,d831b32d02a..3b4b65682de--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@@ -168,14 -135,17 +168,22 @@@ def read_catalog_sidecar(plugin_dir) -"tier": block.get("tier") or "community", "pin": block.get("pin", "")}+ def at_catalog_pin(sidecar: dict, entry_sha: str) -> bool:+ """The install satisfies the catalog pin *entry_sha*: HEAD is that commit, or the pin is an+ annotated tag whose commit was checked out (``sha`` records the peeled commit, ``pin`` the tag+ object the installer verified). Neither matches after a re-pin or for an off-pin ``--ref`` install."""+ return bool(entry_sha) and entry_sha in (+ str(sidecar.get("sha") or "").lower(), str(sidecar.get("pin") or "").lower())+++def catalog_install_record(plugin_dir) -> Optional[dict]:+ """Catalog fields from the authoritative installer-owned record."""+ return read_catalog_sidecar(plugin_dir)++def catalog_annotation(dir_path) -> Optional[str]:"""``catalog:<tier>@<sha8>`` for a catalog install (``list`` Source column), else ``None``."""- sidecar = read_catalog_sidecar(dir_path)+ sidecar = catalog_install_record(dir_path)if not sidecar:return Nonereturn f"catalog:{sidecar.get('tier') or 'community'}@{str(sidecar.get('sha') or '')[:8]}"@@@ -208,8 -179,9 +217,8 @@@ def install_catalog_entry(entry: Pluginraise_if_removed(entry.name, entry.repo)target, manifest, installed_name = _install_plugin_core(entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,- reviewed_pin=entry.sha, python_deps=python_deps, allow_removed=allow_removed,+ reviewed_pin=entry.sha, python_deps=python_deps, allow_removed=allow_removed, before_swap=before_swap,catalog={"name": entry.name, "repo": entry.repo, "tier": entry.tier, "pin": entry.sha})- write_catalog_sidecar(target, entry, sha=pinned_revision(target.name))return target, manifest, installed_name@@@ -286,45 -258,92 +295,137 @@@ class RepinResult(NamedTuple)warnings: list[str]- def repin_catalog_plugin(target: Path, sidecar: dict, *, interactive: bool = False) -> RepinResult:- """Re-pin a catalog install to the current catalog SHA (never ``git pull``). The force reinstall- replaces the whole tree, so the user's untracked/ignored files (installer-created ``config.yaml``,- data) are carried into the new tree and edits to TRACKED files are saved under- ``<HERMES_HOME>/plugins-backup/<name>-<sha8>/`` with a warning. A manifest rename between pins moves the- enabled flag and removes the stale dir. Raises ``PluginOperationError`` when the entry left the catalog."""- from hermes_cli.plugins_cmd import PluginOperationError, _plugins_dir+ # Surfaces a re-pin can widen without the user seeing a diff: each is a list of identifiers the+ # new manifest adds (``desktop`` = a Desktop half appeared). Compared as sets — removals are not consent events.+ _SURFACE_LABELS = {"capabilities": "host capabilities", "tools": "tools", "hooks": "hooks",+ "python_dependencies": "Python dependencies", "desktop": "Desktop UI half"}+++ def plugin_surface(manifest: dict, tree: Path) -> Dict[str, set]:+ """What an installed tree exposes: declared host capabilities, tools, hooks, Python deps, Desktop half."""+ from hermes_cli.plugins_cmd import _declared_capabilities_from_manifest+ manifest = manifest or {}++ def _list(key: str, *alts: str) -> set:+ for k in (key, *alts):+ raw = manifest.get(k)+ if isinstance(raw, list):+ return {str(x) for x in raw if isinstance(x, (str, int, float))}+ return set()++ return {+ "capabilities": set(_declared_capabilities_from_manifest(manifest, str(manifest.get("name") or "?"))),+ "tools": _list("provides_tools"), "hooks": _list("provides_hooks", "hooks"),+ "python_dependencies": _list("python_dependencies"),+ "desktop": {"desktop/plugin.js"} if (tree / "desktop" / "plugin.js").is_file() else set(),+ }+++ def surface_delta(old: Dict[str, set], new: Dict[str, set]) -> Dict[str, List[str]]:+ """``{surface: [added...]}`` for every surface the new tree widens; empty when nothing widened."""+ return {k: sorted(new.get(k, set()) - old.get(k, set())) for k in _SURFACE_LABELS+ if new.get(k, set()) - old.get(k, set())}+++ def surface_delta_lines(delta: Dict[str, List[str]]) -> List[str]:+ return [f"{_SURFACE_LABELS[k]}: {', '.join(v)}" for k, v in delta.items()]+++ class RepinConsentRequired(Exception):+ """The new pin widens the plugin's surface and no consent was given; nothing was changed on disk.+ ``delta`` is :func:`surface_delta`'s mapping — surfaces hand it to the user and retry with consent."""++ def __init__(self, name: str, sha: str, delta: Dict[str, List[str]]):+ self.name, self.sha, self.delta = name, sha, delta+ super().__init__(+ f"Updating '{name}' to {sha[:8]} adds {'; '.join(surface_delta_lines(delta))}. Confirm to continue.")++-def repin_catalog_plugin(target: Path, sidecar: dict, *, consent_cb=None) -> RepinResult:- """Re-pin a catalog install to the current catalog SHA (never ``git pull``). The force reinstall- replaces the whole tree, so the user's untracked/ignored files (installer-created ``config.yaml``,- data) are carried into the new tree and edits to TRACKED files are saved under- ``<HERMES_HOME>/plugins-backup/<name>-<sha8>/`` with a warning. A manifest rename between pins moves the- enabled flag and removes the stale dir. Raises ``PluginOperationError`` when the entry left the catalog.-- A new pin that WIDENS the plugin (new tools, hooks, Python deps, host capabilities or a Desktop half- vs the installed manifest) is a new grant, not a refresh: ``consent_cb(delta) -> bool`` decides- before anything moves; absent or declined → :class:`RepinConsentRequired`, tree untouched."""++def repin_catalog_plugin(++ target: Path,++ sidecar: dict,++ *,++ interactive: bool = False,++ consent_cb=None,++) -> RepinResult:++ """Re-pin a catalog install to the current catalog SHA (never ``git pull``).++++ Publication stays PM-owned and recoverable. Untracked/ignored user files are copied into the++ staged replacement before publication; tracked edits are backed up under++ ``<HERMES_HOME>/plugins-backup/<name>-<sha8>/``. A manifest rename moves the selection and removes++ the stale directory.++++ A pin that widens the plugin (new tools, hooks, Python deps, host capabilities or a Desktop half)++ is a new grant. ``consent_cb(delta) -> bool`` decides before publication; absent or declined raises++ :class:`RepinConsentRequired` with the installed tree untouched. The immutable catalog pin is++ previewed separately because the PM update transaction owns and publishes its own staged clone.++ """+ from hermes_cli.plugins_cmd import (- PluginOperationError, _get_enabled_set, _plugins_dir, _read_manifest, _remove_plugin_core,- _save_enabled_set)++ PluginOperationError,++ _clone_plugin_repo,++ _plugins_dir,++ _read_install_metadata,++ _read_manifest,++ _read_manifest_for_install,++ _resolve_git_url,++ _resolve_subdir_within,++ )++catalog_name = str(sidecar["catalog_name"])entry = get_live_catalog_entry(catalog_name)if entry is None:raise PluginOperationError(f"Plugin '{catalog_name}' is no longer in the catalog — it may have been removed. ""See `hermes plugins info` and the removed blocklist.")+ refuse_if_installed_removed(catalog_name, target)- if str(sidecar.get("sha") or "").strip().lower() == entry.sha:+ if at_catalog_pin(sidecar, entry.sha):return RepinResult(entry.sha, False, target.name, [])- was_enabled = _get_enabled_set() # the force reinstall must not flip activation state++local, modified = _local_changes(target)old_sha8 = str(sidecar.get("sha") or "old")[:8]+ installed_surface = plugin_surface(_read_manifest(target), target)++ def _consent_gate(manifest: dict, tree: Path) -> None:+ delta = surface_delta(installed_surface, plugin_surface(manifest, tree))+ if delta and not (consent_cb is not None and consent_cb(delta)):+ raise RepinConsentRequired(catalog_name, entry.sha, delta)+++ # The catalog pin is immutable. Preview it before PM begins publication so a widened surface can++ # be declined without touching the live tree or writing a backup; update_plugin clones the same pin++ # again and owns validation, dependency preparation, metadata and code publication as one handoff.++ with tempfile.TemporaryDirectory(prefix=".repin-preview-", dir=_plugins_dir()) as preview_tmp:++ preview_root = Path(preview_tmp) / "plugin"++ git_url, subdir = _resolve_git_url(entry.install_identifier)++ _clone_plugin_repo(preview_root, git_url, entry.sha)++ preview_target = _resolve_subdir_within(preview_root, subdir) if subdir else preview_root++ _consent_gate(_read_manifest_for_install(preview_target), preview_target)++with tempfile.TemporaryDirectory(prefix=".repin-", dir=_plugins_dir()) as tmp:stash = Path(tmp) / "local"_stash_local_files(target, local, stash)# Outside the plugins dir: the discovery scanners recurse into every subdirectory there.backup = _plugins_dir().parent / "plugins-backup" / f"{target.name}-{old_sha8}"_stash_local_files(target, modified, backup)- new_target, _manifest, installed_name = install_catalog_entry(entry, force=True, before_swap=_consent_gate)- if stash.exists():- shutil.copytree(stash, new_target, dirs_exist_ok=True)+ from hermes_cli.plugins_transaction import update_plugin+++ update_plugin(target, catalog_entry=entry, interactive=interactive, preserved_files=stash)- from hermes_cli.plugins_cmd import _read_install_metadata+ matches = []- for name, row in _read_install_metadata().items():++ for installed_name, row in _read_install_metadata().items():+ if not isinstance(row, dict):+ continue+ block = row.get("catalog")- if isinstance(block, dict) and block.get("name") == entry.name and row.get("revision") == entry.sha:- matches.append(name)++ if (++ isinstance(block, dict)++ and block.get("name") == entry.name++ and at_catalog_pin(block, entry.sha)++ ):++ matches.append(installed_name)+ if len(matches) != 1:+ raise PluginOperationError(- f"Catalog update published but its install record is ambiguous: {matches or 'missing' }.")++ f"Catalog update published but its install record is ambiguous: {matches or 'missing'}."++ )+ installed_name = matches[0]+ new_target = target.parent / installed_namewarnings: list[str] = []if modified:warnings.append(f"Local edits to {len(modified)} tracked file(s) were not carried over; copies are under "@@@ -347,11 -356,28 +448,32 @@@return RepinResult(entry.sha, True, installed_name, warnings)-def cmd_update_catalog(name: str, target: Path, sidecar: dict, console) -> None:+def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, interactive: bool = True) -> None:- from hermes_cli.plugins_cmd import PluginOperationError, _fail+ from hermes_cli.plugins_cmd import (+ PluginOperationError, _ask_yes, _declared_capabilities_from_manifest, _fail, _is_tty, _read_manifest,+ _run_capability_consent)console.print(f"[dim]Checking catalog pin for {name}...[/dim]")++ def _confirm_widening(delta: Dict[str, List[str]]) -> bool:+ console.print(f"\n [yellow]The new pin of [bold]{name}[/bold] adds:[/yellow]")+ for line in surface_delta_lines(delta):+ console.print(f" {line}")- if not _is_tty():++ if not interactive or not _is_tty():+ console.print(" [yellow]Non-interactive session: update NOT applied (fail closed). "+ "Re-run `hermes plugins update` in a terminal to review and confirm.[/yellow]")+ return False+ return _ask_yes(" Apply this update? [y/N]: ")+try:- result = repin_catalog_plugin(target, sidecar, interactive=interactive)- result = repin_catalog_plugin(target, sidecar, consent_cb=_confirm_widening)++ result = repin_catalog_plugin(++ target,++ sidecar,++ interactive=interactive,++ consent_cb=_confirm_widening,++ )+ except RepinConsentRequired as exc:+ _fail(console, f"[yellow]Update of {name} not applied:[/yellow] {exc}")+ raise SystemExit(1)except PluginOperationError as exc:_fail(console, f"[red]Error:[/red] {exc}")raise SystemExit(1)@@@ -359,7 -385,17 +481,21 @@@console.print(f"[green]✓[/green] Plugin [bold]{result.installed_name}[/bold] {verb} {result.sha[:8]}.")for warning in result.warnings:console.print(f"[yellow]⚠ {warning}[/yellow]")+ if result.changed:- from hermes_cli.plugins_cmd import _install_python_dependencies++ # PM admitted Python dependencies before publishing the replacement. Host capabilities use++ # their separate grant store, so additions stay ungranted until the user consents here.+ new_target = target.parent / result.installed_name- _install_python_dependencies(new_target, console)- # Same grant path as the git-pull ``update``: host capabilities the new pin declares stay- # ungranted (fail closed) until the user says yes here.+ declared = _declared_capabilities_from_manifest(_read_manifest(new_target), result.installed_name)+ if declared:+ from hermes_cli.plugin_capabilities import declared_set_changed, pending_capabilities+ if pending_capabilities(result.installed_name, declared) or declared_set_changed(result.installed_name, declared):- _run_capability_consent(console, result.installed_name, declared, context="update")++ if interactive:++ _run_capability_consent(console, result.installed_name, declared, context="update")++ else:++ console.print(++ f"[yellow]Plugin {result.installed_name} has new capabilities; review them with "++ f"`hermes plugins capabilities {result.installed_name}`.[/yellow]")+# ── search / browse / info / validate ────────────────────────────────────────diff --cc hermes_cli/plugins_discovery.pyindex 9bf209e8bc7,e7013a9efab..e9645e51f0e--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@@ -112,9 -119,20 +119,20 @@@ def scan_directorytry:children = sorted(path.iterdir())except OSError as exc:- logger.warning("Failed to scan plugin directory %s: %s", path, exc)+ logger.warning("Skipping unreadable plugin directory %s: %s", path, exc)return manifestsfor child in children:+ # Cache/dunder dirs (__pycache__, __MACOSX__, …) are never+ # plugins. Walking them can raise PermissionError and take+ # down every subsequent tool call (#86996).+ if child.name.startswith("__") and child.name.endswith("__"):+ logger.debug("Skipping dunder plugin path %s", child)+ continue+ if child.name in _FOREIGN_HARNESS_MANIFEST_DIRS:+ logger.debug("Skipping %s (foreign-harness manifest convention)", child)+ continue+ # pathlib.Path.is_dir() swallows OSError, but injected Path-likes+ # and test doubles can still raise. Fail closed per child.try:if not child.is_dir() or (depth == 0 and skip_names and child.name in skip_names):continuediff --cc hermes_cli/plugins_manifest.pyindex 656a60d2a7b,dc49fbe6cdb..0b534c5b40e--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@@ -462,9 -479,13 +480,13 @@@ def parse_manifest_file"""Parse one ``plugin.yaml`` into a :class:`PluginManifest`; ``None`` (warned) on failure."""try:if yaml is None:- logger.warning("PyYAML not installed – cannot load %s", manifest_file)+ logger.warning("ruamel.yaml not installed – cannot load %s", manifest_file)return None- data = fast_safe_load(manifest_file.read_text(encoding="utf-8")) or {}+ data = fast_safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}+ if not isinstance(data, Mapping):+ logger.warning("Failed to parse %s: top level must be a mapping, got %s (#14066)",+ manifest_file, type(data).__name__)+ return Nonename = data.get("name", plugin_dir.name)key = f"{prefix}/{plugin_dir.name}" if prefix else namekind = _manifest_kind(data, key, plugin_dir)diff --cc hermes_cli/plugins_settings.pyindex 00000000000,d6aac25adcb..165fcc8c873mode 000000,100644..100644--- a/hermes_cli/plugins_settings.py+++ b/hermes_cli/plugins_settings.py@@@ -1,0 -1,140 +1,140 @@@+ """Plugin-declared settings fields for the Desktop/TUI Plugins hub (#46600, #87934).++ A ``plugin.yaml`` ``config_schema`` describes the keys under ``plugins.entries.<id>.settings``.+ This module turns that schema into renderable form fields (type, current value, choices) and+ writes edits back through :func:`hermes_cli.plugins_state.save_plugin_setting` — the same writer+ ``ctx.set_config`` uses, so the CLI, the plugin and the Desktop never disagree on where a+ setting lives. Secrets are declared with ``type: secret`` and never touch ``config.yaml``: the+ field carries the ``.env`` name (``env:`` or ``<PLUGIN>_<KEY>``) plus a presence flag, and the+ client writes the value through the existing ``PUT /api/env`` credential route.+ """++ from __future__ import annotations++ import logging+ import re+ from pathlib import Path+ from typing import Any, Dict, List, Mapping, Optional++ from hermes_cli.plugins_state import _plugin_relative_segments, _plugin_settings_entry, save_plugin_setting++ logger = logging.getLogger(__name__)++ # manifest ``type`` → wire field type the renderer keys its component table on.+ _FIELD_TYPES: Dict[str, str] = {+ "str": "string", "string": "string",+ "int": "number", "integer": "number", "float": "number", "number": "number",+ "bool": "boolean", "boolean": "boolean",+ "list": "json", "array": "json", "dict": "json", "object": "json",+ "secret": "secret",+ }+ # wire field type → Python types a saved value must have (bool is excluded from number on purpose).+ _VALUE_TYPES: Dict[str, tuple] = {+ "string": (str,), "enum": (str,), "number": (int, float), "boolean": (bool,), "json": (list, dict),+ }+ _ENV_NAME_CLEAN_RE = re.compile(r"[^A-Z0-9]+")+++ def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[str, Any]]:+ """``config_schema`` mapping from ``<plugin_dir>/plugin.yaml``; ``{}`` when absent or malformed+ (the loader already warned about malformed entries at load time)."""+ if plugin_dir is None:+ return {}+ manifest = Path(plugin_dir) / "plugin.yaml"+ if not manifest.is_file():+ return {}+ try:+ from utils import fast_safe_load- data = fast_safe_load(manifest.read_text(encoding="utf-8")) or {}++ data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}+ except Exception as exc: # unreadable manifest: no settings surface, never a failed list+ logger.debug("plugin settings: cannot read %s: %s", manifest, exc)+ return {}+ raw = data.get("config_schema") if isinstance(data, Mapping) else None+ if not isinstance(raw, Mapping):+ return {}+ return {str(k): v for k, v in raw.items() if isinstance(v, Mapping)}+++ def secret_env_name(plugin_id: str, key: str, spec: Mapping[str, Any]) -> str:+ """``.env`` variable a ``type: secret`` field is stored under: the manifest's ``env:`` or+ ``<PLUGIN_ID>_<KEY>`` upper-snaked (``image_gen/fal`` + ``api_key`` → ``IMAGE_GEN_FAL_API_KEY``)."""+ declared = str(spec.get("env") or "").strip()+ if declared:+ return declared+ return _ENV_NAME_CLEAN_RE.sub("_", f"{plugin_id}_{key}".upper()).strip("_")+++ def _field_type(spec: Mapping[str, Any]) -> str:+ if spec.get("secret") is True:+ return "secret"+ kind = _FIELD_TYPES.get(str(spec.get("type") or "str").lower(), "string")+ choices = spec.get("choices", spec.get("enum"))+ if kind == "string" and isinstance(choices, list) and choices:+ return "enum"+ return kind+++ def plugin_settings_fields(plugin_id: str, plugin_dir: Optional[Path]) -> List[Dict[str, Any]]:+ """Renderable settings fields for one plugin: schema + the current value of each key.++ Secret fields never carry the value — only ``env`` (where it lives) and ``has_value``.+ """+ schema = _manifest_config_schema(plugin_dir)+ if not schema:+ return []+ from hermes_cli.config import get_env_value, load_config_readonly+ entry = _plugin_settings_entry(load_config_readonly() or {}, plugin_id) or {}+ raw_current = entry.get("settings")+ current: Mapping[str, Any] = raw_current if isinstance(raw_current, Mapping) else {}+ fields: List[Dict[str, Any]] = []+ for key, spec in schema.items():+ try:+ _plugin_relative_segments(key)+ except ValueError:+ continue # a key the plugin could never read through ctx.get_config+ kind = _field_type(spec)+ field: Dict[str, Any] = {+ "key": key, "type": kind,+ "label": str(spec.get("label") or spec.get("title") or key),+ "description": str(spec.get("description") or ""),+ "required": bool(spec.get("required")),+ }+ if kind == "secret":+ env = secret_env_name(plugin_id, key, spec)+ field.update({"env": env, "has_value": get_env_value(env) is not None})+ else:+ choices = spec.get("choices", spec.get("enum"))+ if kind == "enum":+ field["choices"] = [str(c) for c in choices]+ if "default" in spec:+ field["default"] = spec["default"]+ field["value"] = current.get(key, spec.get("default"))+ fields.append(field)+ return fields+++ def save_plugin_settings(plugin_id: str, plugin_dir: Optional[Path], values: Mapping[str, Any]) -> List[str]:+ """Write ``values`` (``{key: value}``) for the plugin's schema keys; returns the keys written.++ Raises ``ValueError`` on an unknown key, a type mismatch, an enum value outside ``choices`` or a+ secret (secrets go to ``.env`` through the credential route, never ``config.yaml``);+ ``PermissionError`` propagates from the shared writer (managed installs / managed keys).+ """+ schema = _manifest_config_schema(plugin_dir)+ plan: List[tuple] = []+ for key, value in values.items():+ spec = schema.get(str(key))+ if spec is None:+ raise ValueError(f"{key!r} is not declared in the plugin's config_schema")+ kind = _field_type(spec)+ if kind == "secret":+ raise ValueError(f"{key!r} is a secret; it is stored in .env, not config.yaml")+ expected = _VALUE_TYPES[kind]+ if not isinstance(value, expected) or (isinstance(value, bool) and bool not in expected):+ raise ValueError(f"{key!r} should be {kind} (got {type(value).__name__})")+ if kind == "enum" and value not in [str(c) for c in spec.get("choices", spec.get("enum"))]:+ raise ValueError(f"{key!r} must be one of the declared choices")+ plan.append((str(key), _plugin_relative_segments(str(key)), value))+ for key, segments, value in plan:+ save_plugin_setting(plugin_id, segments, value)+ return [key for key, _segments, _value in plan]diff --cc hermes_cli/update_cmd_stash.pyindex 8b785523ab6,b2971858a60..8c78f5c6bd3--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@@ -123,7 -124,11 +124,11 @@@ def _stash_local_changes_if_needed(git_def _resolve_stash_selector(git_cmd: list[str], cwd: Path, stash_ref: str) -> Optional[str]:+ """Selector for the stash entry whose commit is *stash_ref*, as the bare index ``N``+ (git accepts it wherever ``stash@{N}`` is valid). Never ``stash@{N}`` itself: on native+ Windows the MSYS runtime strips the braces from git.exe's argv, so ``stash@{0}`` reaches git+ as ``stash@0`` and the drop fails (#87542)."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runstash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %H"], cwd, check=True)for line in stash_list.stdout.splitlines():selector, _, commit = line.partition(" ")diff --cc hermes_cli/web_server_memory.pyindex 29415673f96,6902a93579c..f2ce274ab29--- a/hermes_cli/web_server_memory.py+++ b/hermes_cli/web_server_memory.py@@@ -13,9 -15,18 +13,10 @@@ from typing import Any, Dict, List, Opt# Same logger the code used before extraction (record parity)._log = logging.getLogger("hermes_cli.web_server")-_MEMORY_PROVIDER_IMPORT_NAMES = {- "honcho-ai": "honcho",- "mem0ai": "mem0",- "hindsight-client": "hindsight_client",- "hindsight-all": "hindsight",-}--def _normalize_memory_provider_name(name: Any) -> str:+ from agent.memory_provider import is_core_memory_providerprovider = str(name or "").strip()- return "" if provider.lower() in {"built-in", "builtin", "none"} else provider+ return "" if is_core_memory_provider(provider) else providerdef _load_memory_provider(name: str):diff --cc plugins/context_engine/__init__.pyindex dee2c5da372,9468a3827f0..c1bc62c858f--- a/plugins/context_engine/__init__.py+++ b/plugins/context_engine/__init__.py@@@ -13,6 -15,29 +15,29 @@@ from plugins import plugin_loader as _llogger = logging.getLogger(__name__)_CONTEXT_ENGINE_PLUGINS_DIR = Path(__file__).parent+ # Synthetic parent package for user-installed engines (keeps them out of the bundled namespace).+ _USER_NAMESPACE = "_hermes_user_context_engine"+++ def _is_context_engine_dir(path: Path) -> bool:+ """Cheap text heuristic: ``__init__.py`` mentions the context engine contract."""+ init_file = path / "__init__.py"+ try:- source = init_file.read_text(errors="replace", encoding="utf-8")[:8192]++ source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]+ except OSError:+ return False+ return "register_context_engine" in source or "ContextEngine" in source+++ def _iter_engine_dirs() -> List[Tuple[str, Path]]:+ """``(name, path)`` for bundled then user engines; bundled wins on collisions."""+ dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)]+ seen = {name for name, _ in dirs}+ user_dir = _loader.user_plugins_dir()+ if user_dir:+ dirs.extend((child.name, child) for child in _loader.iter_plugin_dirs(user_dir)+ if child.name not in seen and _is_context_engine_dir(child))+ return dirsdef discover_context_engines() -> List[Tuple[str, str, bool]]:diff --cc plugins/memory/hindsight/plugin.yamlindex a72380e54bc,3495aa63cc9..99b4000b8e8--- a/plugins/memory/hindsight/plugin.yaml+++ b/plugins/memory/hindsight/plugin.yaml@@@ -1,7 -1,6 +1,5 @@@name: hindsightversion: 1.0.0description: "Hindsight — long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval."-pip_dependencies:- - "hindsight-client>=0.6.1"+extra: hindsightrequires_env: []- hooks:- - on_session_enddiff --cc plugins/memory/honcho/plugin.yamlindex f8347d67945,8717aa2a391..49cc14efe6b--- a/plugins/memory/honcho/plugin.yaml+++ b/plugins/memory/honcho/plugin.yaml@@@ -1,6 -1,5 +1,4 @@@name: honchoversion: 1.0.0description: "Honcho AI-native memory — cross-session user modeling with dialectic Q&A, semantic search, and persistent conclusions."-pip_dependencies:- - honcho-ai+extra: honcho- hooks:- - on_session_enddiff --cc plugins/memory/openviking/plugin.yamlindex a0b66f498fe,faa1b690744..5d0ef8a7d25--- a/plugins/memory/openviking/plugin.yaml+++ b/plugins/memory/openviking/plugin.yaml@@@ -1,6 -1,6 +1,4 @@@name: openvikingversion: 2.0.0description: "OpenViking context database — session-managed memory with automatic extraction, tiered retrieval, and filesystem-style knowledge browsing."-pip_dependencies:- - httpxrequires_env: []- hooks:- - on_session_enddiff --cc scripts/check_config_yaml_writers.pyindex 00000000000,217ea2017e1..fc416d4bfe6mode 000000,100755..100755--- a/scripts/check_config_yaml_writers.py+++ b/scripts/check_config_yaml_writers.py@@@ -1,0 -1,118 +1,118 @@@+ #!/usr/bin/env python3+ """Fail when a ``config.yaml`` is written by anything but the comment-preserving writer.++ Every writer of ``~/.hermes/config.yaml`` (and ``profiles/*/config.yaml``) must go through+ ``hermes_cli.config.atomic_config_write`` → ``utils.atomic_roundtrip_yaml_save`` (ruamel+ round-trip). A PyYAML dump (``yaml.dump`` / ``yaml.safe_dump`` / ``utils.atomic_yaml_write``)+ of a config path re-serialises the parsed dict and destroys every user comment — the #92554+ class, which regressed several times because each new writer picked the plain dumper again.++ Flags, in the scanned trees:++ * a call to ``atomic_yaml_write`` / ``yaml.dump`` / ``yaml.safe_dump`` / ``safe_dump`` whose+ first argument names a config path (``config_path``, ``cfg_path``, ``config.yaml``,+ ``get_config_path()``, ``_active_config_path()``, ``live_path``);+ * ``<config path>.write_text(... dump(...) ...)``;+ * any ``yaml.dump`` / ``yaml.safe_dump`` / ``atomic_yaml_write`` call inside ``hermes_cli/config.py``+ or ``hermes_cli/config_*.py`` (the config system has exactly one writer).++ Suppress a true false positive with ``# config-writer: ok — <why>`` on the call's line.++ Usage: python3 scripts/check_config_yaml_writers.py [paths...]+ """+ from __future__ import annotations++ import ast+ import re+ import sys+ from pathlib import Path++ ROOT = Path(__file__).resolve().parent.parent+ DEFAULT_TREES = ("hermes_cli", "agent", "gateway", "tui_gateway", "cron", "plugins", "tools", "cli.py", "utils.py")+ # The writer module itself and the on-disk primitive it wraps.+ ALLOWED_FILES = {ROOT / "utils.py"}+ DUMPERS = {"atomic_yaml_write", "safe_dump", "dump"}+ CONFIG_PATH_RE = re.compile(+ r"config_path|cfg_path|config\.yaml|get_config_path\(\)|_active_config_path\(\)|\blive_path\b")+ CONFIG_MODULE_RE = re.compile(r"^hermes_cli/config(_[a-z_]+)?\.py$")+ SUPPRESS = "# config-writer: ok"+++ def _func_name(node: ast.AST) -> str | None:+ if isinstance(node, ast.Attribute):+ return node.attr+ if isinstance(node, ast.Name):+ return node.id+ return None+++ def _is_yaml_dump(call: ast.Call, src: str) -> bool:+ name = _func_name(call.func)+ if name == "atomic_yaml_write":+ return True+ if name in ("safe_dump", "dump"):+ # ``yaml.dump`` / ``yaml.safe_dump`` / ``yaml_rt.dump``; plain ``json.dump`` is not YAML.+ receiver = ast.get_source_segment(src, call.func.value) if isinstance(call.func, ast.Attribute) else ""+ return "yaml" in (receiver or "").lower() or name == "safe_dump"+ return False+++ def scan_file(path: Path) -> list[str]:- src = path.read_text(encoding="utf-8")++ src = path.read_text(encoding="utf-8-sig")+ try:+ tree = ast.parse(src)+ except SyntaxError:+ return []+ lines = src.splitlines()+ rel = path.relative_to(ROOT).as_posix()+ in_config_module = bool(CONFIG_MODULE_RE.match(rel))+ problems: list[str] = []++ def flag(node: ast.Call, why: str) -> None:+ line = lines[node.lineno - 1]+ if SUPPRESS in line:+ return+ problems.append(f"{rel}:{node.lineno}: {why} — route it through hermes_cli.config.atomic_config_write")++ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ if _is_yaml_dump(node, src):+ if in_config_module:+ flag(node, "PyYAML dump inside the config system")+ continue+ first = ast.get_source_segment(src, node.args[0]) if node.args else ""+ if first and CONFIG_PATH_RE.search(first):+ flag(node, f"PyYAML dump of a config path ({first})")+ elif _func_name(node.func) == "write_text" and isinstance(node.func, ast.Attribute):+ receiver = ast.get_source_segment(src, node.func.value) or ""+ body = ast.get_source_segment(src, node) or ""+ if CONFIG_PATH_RE.search(receiver) and "dump(" in body:+ flag(node, f"write_text of a YAML dump onto a config path ({receiver})")+ return problems+++ def main(argv: list[str]) -> int:+ targets = [ROOT / a for a in argv] or [ROOT / t for t in DEFAULT_TREES]+ files: list[Path] = []+ for t in targets:+ if t.is_dir():+ files.extend(p for p in t.rglob("*.py") if "node_modules" not in p.parts)+ elif t.suffix == ".py" and t.exists():+ files.append(t)+ problems: list[str] = []+ for f in sorted(set(files)):+ if f.resolve() in ALLOWED_FILES:+ continue+ problems.extend(scan_file(f))+ if problems:+ print("config.yaml must only be written through the comment-preserving writer:", file=sys.stderr)+ for p in problems:+ print(f" {p}", file=sys.stderr)+ return 1+ print(f"check_config_yaml_writers: OK ({len(files)} files)")+ return 0+++ if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --cc tests/hermes_cli/test_plugin_catalog.pyindex 5b136f5eebc,df806958b80..8d55d02dfd3--- a/tests/hermes_cli/test_plugin_catalog.py+++ b/tests/hermes_cli/test_plugin_catalog.py@@@ -113,19 -97,73 +113,70 @@@ def test_live_catalog_falls_back_to_in_assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]cache.parent.mkdir(parents=True)- cache.write_text(json.dumps({"entries": [_entry("live-only")],- "removed": [{"name": "pulled-live", "reason": "cve"}]}))- assert [e.name for e in pc.load_catalog_live()] == ["live-only"]+ cache.write_text(json.dumps({"entries": [_entry("live-only", description="café")],+ "removed": [{"name": "pulled-live", "reason": "cve"}]},+ ensure_ascii=False), encoding="utf-8-sig")+ if stale:+ os.utime(cache, (1, 1))+ requests.clear()+ # The unreachable fetch above armed the failure window; a stale cache must still+ # trigger a real retry once that window has passed.+ monkeypatch.setattr(pc, "_live_fetch_failed_until", 0.0)+ entries = pc.load_catalog_live()+ assert [e.name for e in entries] == ["live-only"]+ assert entries[0].description == "café"+ assert bool(requests) is staleassert pc.find_removed("pulled-live").reason == "cve"+ cache.write_text("{", encoding="utf-8-sig")+ assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]+++ def _fresh_cache(tmp_path, monkeypatch, doc: dict):+ cache = tmp_path / "cache" / "plugin-catalog.json"+ cache.parent.mkdir(parents=True, exist_ok=True)+ cache.write_text(json.dumps(doc))+ monkeypatch.setattr(pc, "_live_cache_path", lambda: cache)+ monkeypatch.setattr(pc, "LIVE_CATALOG_URL", "http://127.0.0.1:9/nope") # never reached / unreachable+ return cache+++ def test_newer_in_tree_pin_outranks_a_fresh_live_cache(tmp_path, monkeypatch):+ """Right after `hermes update` bumps an in-tree pin, a live cache fetched BEFORE the bump must not+ re-install the old sha: for the same entry the newer catalog wins (checkout catalog commit time vs+ the doc's generated_at). Live-only entries survive; an older checkout still defers to the doc."""+ old, new = SHA, "a" * 40+ _fresh_cache(tmp_path, monkeypatch, {"generated_at": "2026-09-22T10:00:00Z",+ "entries": [_entry("shared", sha=old), _entry("live-only")], "removed": []})+ monkeypatch.setattr(pc, "load_catalog", lambda catalog_dir=None: [pc.entry_from_mapping(_entry("shared", sha=new), "t")])+ bump_time = pc._live_generated_time({"generated_at": "2026-09-22T10:00:00Z"}) + 3600+ monkeypatch.setattr(pc, "in_tree_catalog_time", lambda: bump_time)+ by_name = {e.name: e for e in pc.load_catalog_live()}+ assert by_name["shared"].sha == new and "live-only" in by_name+ # Control: a checkout whose catalog predates the doc takes the live pin.+ monkeypatch.setattr(pc, "in_tree_catalog_time", lambda: bump_time - 7200)+ assert {e.name: e.sha for e in pc.load_catalog_live()}["shared"] == old++-def test_live_cache_past_max_stale_age_stops_supplying_pins_but_keeps_removals(tmp_path, monkeypatch):- """Offline for days: a 25-hour-old cache no longer outranks the in-tree catalog (its pins may be- older than the checkout's), while its kill-list entries still block."""- import os- import time- cache = _fresh_cache(tmp_path, monkeypatch, {"entries": [_entry("live-only")],- "removed": [{"name": "pulled-live", "reason": "cve"}]})- stale = time.time() - pc.LIVE_CATALOG_MAX_STALE_SECONDS - 3600- os.utime(cache, (stale, stale))- pc._live_fetch_failed_until = 0.0- assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]- assert pc.find_removed("pulled-live").reason == "cve"- assert pc.cached_removed_entries()[-1].name == "pulled-live"--+ def test_live_cache_write_never_truncates_the_previous_copy(tmp_path, monkeypatch):+ """The cache is replaced atomically: a reader racing the writer (or a write that dies half-way)+ sees the whole previous document, never a truncated one."""+ cache = _fresh_cache(tmp_path, monkeypatch, {"entries": [_entry("previous")], "removed": []})+ previous = cache.read_text()++ class _Resp:+ content = json.dumps({"entries": [_entry("fresh")], "removed": []}).encode()+ def raise_for_status(self): pass+ def json(self): return json.loads(self.content)++ import httpx+ import utils+ monkeypatch.setattr(httpx, "get", lambda *a, **k: _Resp())+ pc._live_fetch_failed_until = 0.0++ def _dies(*_a, **_k):+ raise OSError("disk full")++ monkeypatch.setattr(utils, "atomic_replace", _dies)+ pc.fetch_live_catalog(force=True) # the failed write is swallowed like any other fetch failure+ assert cache.read_text() == previous+ assert not list(cache.parent.glob("*.tmp*")) # no leftover temp file eitherdiff --cc tests/hermes_cli/test_plugins_cmd.pyindex c86a30de11b,285dbf14cda..22f8eab1042--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@@ -262,8 -294,35 +262,36 @@@ class TestGitPullPluginDirAutostashok, msg = pc._git_pull_plugin_dir(checkout)assert ok is Trueassert "Already up to date" in msg+ assert git(checkout, "stash", "list").strip() == ""+ def test_autostash_addresses_git_by_sha_never_brace_selector(self, tmp_path, monkeypatch):+ """Native Windows: MSYS strips the braces from ``stash@{0}`` in git.exe's argv, so the+ apply and the drop must target the autostash by its commit sha / positionally (#87542)."""+ import hermes_cli.plugins_cmd as pc++ if not pc._resolve_git_executable():+ pytest.skip("git not available")+ origin, checkout, git = self._make_repos(tmp_path)+ self._set_line(origin, "VALUE", "VALUE = 2")+ git(origin, "commit", "-qam", "bump value")+ self._set_line(checkout, "OTHER", "OTHER = 'local'")++ argv_log: list[tuple[str, ...]] = []+ real_run = pc._run_plugin_git++ def recording_run(git_exe, target, *args, **kwargs):+ argv_log.append(args)+ return real_run(git_exe, target, *args, **kwargs)++ monkeypatch.setattr(pc, "_run_plugin_git", recording_run)+ ok, msg = pc._git_pull_plugin_dir(checkout)++ assert ok is True and "re-applied" in msg+ assert git(checkout, "stash", "list").strip() == ""+ assert not any("{" in arg or "}" in arg for args in argv_log for arg in args), argv_log+ applied = [args for args in argv_log if args[:2] == ("stash", "apply")]+ assert len(applied) == 1 and len(applied[0][2]) == 40, applied # by commit sha+# ── _repo_name_from_url ──────────────────────────────────────────────────@@@ -573,14 -702,19 +601,14 @@@ class TestProviderDiscovery# ── Auto-activation fix ──────────────────────────────────────────────────-class TestNoAutoActivation:- """Verify that plugin engines don't auto-activate when config says 'compressor'."""-- def test_compressor_default_ignores_plugin(self):- """When context.engine is 'compressor', a plugin-registered engine should NOT- be used — only explicit config triggers plugin engines."""- # This tests the run_agent.py logic indirectly by checking that the- # code path for default config doesn't call get_plugin_context_engine.- import run_agent as ra_module- source = Path(ra_module.__file__).read_text(encoding="utf-8")- # The old code had: "Even with default config, check if a plugin registered one"- # The fix removes this. Verify it's gone.- assert "Even with default config, check if a plugin registered one" not in source+def test_default_compressor_does_not_activate_an_offered_plugin(monkeypatch):+ from agent.agent_init import _select_context_engine+ from types import SimpleNamespace- candidate = SimpleNamespace(name='offered')++ candidate = SimpleNamespace(name='offered', clone_for_agent=lambda: candidate)+ monkeypatch.setattr('plugins.context_engine.load_context_engine', lambda _: None)+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_context_engine', lambda: candidate)+ assert _select_context_engine({'context': {'engine': 'compressor'}}) is None+ assert _select_context_engine({'context': {'engine': 'offered'}}).name == 'offered'# ── End-to-end subdirectory install ──────────────────────────────────────────@@@ -671,6 -806,39 +699,37 @@@ class TestSubdirInstallE2Ewith pytest.raises(PluginOperationError, match="does not exist"):pc._install_plugin_core(identifier, force=False)+ def test_subdir_install_stays_updatable(self, tmp_path, monkeypatch):+ """A subdir install ships no ``.git`` (it stays in the temp clone), so ``plugins update``+ must re-install from the recorded source instead of refusing (#65314)."""+ if shutil.which("git") is None:+ pytest.skip("git not available")+ import subprocess as sp++ from hermes_cli import plugins_cmd as pc++ repo_root = tmp_path / "monorepo"+ self._make_repo_with_subdir_plugin(repo_root)- plugins_dir = tmp_path / "installed"- plugins_dir.mkdir()- monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)- monkeypatch.setattr(pc, "_install_metadata_path", lambda: plugins_dir / ".install-metadata.json")++ plugins_dir = tmp_path / "home/plugins"++ monkeypatch.setenv("HERMES_HOME", str(plugins_dir.parent))+ target, _manifest, _name = pc._install_plugin_core(f"file://{repo_root}#my-plugin", force=False)+ assert not (target / ".git").exists()++ (repo_root / "my-plugin" / "__init__.py").write_text("VERSION = 2\n", encoding="utf-8")+ env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}+ sp.run(["git", "commit", "-qam", "v2"], cwd=repo_root, check=True, env=env)+ new_sha = sp.run(["git", "rev-parse", "HEAD"], cwd=repo_root, check=True,+ capture_output=True, text=True).stdout.strip()++ output = pc._pull_plugin_update(target, lambda rec: "pinned", lambda: "not git")++ assert "VERSION = 2" in (target / "__init__.py").read_text(encoding="utf-8")+ assert pc._read_install_metadata()["my-plugin"]["revision"] == new_sha+ assert "Already up to date" not in output+ # A second update with nothing new upstream reports up to date, like `git pull`.+ assert "Already up to date" in pc._pull_plugin_update(target, lambda rec: "pinned", lambda: "not git")+def test_installs_portable_root_package_disabled(self, tmp_path, monkeypatch):if shutil.which("git") is None:pytest.skip("git not available")diff --cc tests/hermes_cli/test_update_autostash.pyindex e04ae5cd73e,47db53b97ea..19f35fe22f8--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@@ -279,7 -736,353 +279,36 @@@ def test_update_autostash_survives_undeos.chmod(pkg, 0o755)+ def test_stash_selector_is_a_bare_index_never_a_brace_selector(tmp_path):+ """The updater drops its autostash through a selector read back from ``git stash list``; on+ native Windows MSYS strips the braces from ``stash@{N}`` in git.exe's argv, so the selector+ must be the bare index git accepts everywhere (#87542)."""+ import subprocess++ import hermes_cli.update_cmd_stash as stash_mod++ def git(*args):+ return subprocess.run(["git", *args], cwd=tmp_path, capture_output=True, text=True, check=True)++ git("init", "-q", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ (tmp_path / "f.txt").write_text("v1\n")+ git("add", "-A")+ git("commit", "-qm", "init")+ (tmp_path / "f.txt").write_text("older\n")+ git("stash", "push", "-q", "-m", "older")+ target_sha = git("rev-parse", "refs/stash").stdout.strip()+ (tmp_path / "f.txt").write_text("newer\n")+ git("stash", "push", "-q", "-m", "newer")++ selector = stash_mod._resolve_stash_selector(["git"], tmp_path, target_sha)++ assert selector == "1"+ git("stash", "drop", selector)+ assert target_sha not in git("stash", "list", "--format=%H").stdout+-def test_autostash_survives_intent_to_add_entries(tmp_path):- """An index entry from `git add -N` must not block the update autostash.-- Reported: `hermes update` aborted with "Entry 'tests/...' not uptodate. Cannot merge." because- `git add -N` records a path with the empty blob and zeroed stat data, which `git stash push`- refuses outright. Editors that show new files in diffs leave exactly that state behind, and the- update must not require the user to repair their index by hand.- """- import subprocess-- def git(*args, check=True):- return subprocess.run(- ["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- (tmp_path / "tracked.txt").write_text("v1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- # The reported shape: a new local file recorded with `git add -N`, alongside a normal edit.- (tmp_path / "tracked.txt").write_text("v2 local\n", encoding="utf-8")- local_test = tmp_path / "tests" / "test_live_custom_provider_poll.py"- local_test.parent.mkdir()- body = "def test_poll():\n assert True\n"- local_test.write_text(body, encoding="utf-8")- git("add", "-N", "tests/test_live_custom_provider_poll.py")- # Precondition: git reports it as " A" (present in the worktree, absent from the index) - the- # intent-to-add shape that `git stash push` refuses.- assert " A tests/test_live_custom_provider_poll.py" in git("status", "--porcelain").stdout.splitlines()-- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)-- assert stash_ref, "the update must be able to stash an intent-to-add entry"- # The stash must have taken everything, so the pull cannot be blocked by a dirty tree.- assert git("status", "--porcelain").stdout == ""- assert hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)- assert local_test.read_text(encoding="utf-8") == body- assert (tmp_path / "tracked.txt").read_text(encoding="utf-8") == "v2 local\n"---def test_restore_rejects_invalid_python_and_keeps_clean_updated_tree(- monkeypatch, tmp_path, capsys-):- """A cleanly-applied stash must not be allowed to brick every agent turn."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- source = tmp_path / "tools" / "terminal_tool.py"- source.parent.mkdir()- source.write_text("VALUE = 1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- source.write_text("<<<<<<< Updated upstream\nVALUE = 2\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ())- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ())-- with pytest.raises(SystemExit) as exc_info:- hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )-- assert exc_info.value.code == 1- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"- assert git("status", "--porcelain").stdout == ""- assert git("stash", "list").stdout.strip()- output = capsys.readouterr().out- assert "made the Hermes agent unexecutable" in output- assert "gateway was not restarted" in output- assert f"git stash apply {stash_ref}" in output---def test_restore_rejects_new_import_time_failure_and_preserves_stash(- monkeypatch, tmp_path, capsys-):- """A valid-Python stash must not introduce a critical import failure."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- source = tmp_path / "consumer.py"- source.write_text("VALUE = 1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- source.write_text("raise RuntimeError('restored local failure')\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- with pytest.raises(SystemExit) as exc_info:- hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )-- assert exc_info.value.code == 1- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"- assert git("status", "--porcelain").stdout == ""- assert git("stash", "list").stdout.strip()- output = capsys.readouterr().out- assert "agent import consumer" in output- assert "restored local failure" in output- assert "gateway was not restarted" in output---def test_restore_allows_preexisting_import_time_failure(monkeypatch, tmp_path):- """A restore may proceed when it does not worsen an environment failure."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- (tmp_path / "consumer.py").write_text(- "raise RuntimeError('missing local config')\n", encoding="utf-8"- )- local_file = tmp_path / "local.txt"- local_file.write_text("original\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- local_file.write_text("restored\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- assert hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )- assert local_file.read_text(encoding="utf-8") == "restored\n"- assert git("stash", "list").stdout.strip() == ""---def test_restore_rejects_later_failure_masked_by_preexisting_failure(- monkeypatch, tmp_path, capsys-):- """Every critical module must be compared, not only the first failure."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- (tmp_path / "first.py").write_text(- "raise RuntimeError('missing local config')\n", encoding="utf-8"- )- second = tmp_path / "second.py"- second.write_text("VALUE = 1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- second.write_text("raise RuntimeError('restored later failure')\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second"))- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("first", "second"))-- with pytest.raises(SystemExit) as exc_info:- hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )-- assert exc_info.value.code == 1- assert second.read_text(encoding="utf-8") == "VALUE = 1\n"- assert git("status", "--porcelain").stdout == ""- assert git("stash", "list").stdout.strip()- output = capsys.readouterr().out- assert "agent import second" in output- assert "restored later failure" in output- assert "gateway was not restarted" in output---def test_restore_rejects_system_exit_masked_by_preexisting_failure(- monkeypatch, tmp_path, capsys-):- """A terminating import must be compared instead of hiding the marker."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- (tmp_path / "first.py").write_text(- "raise RuntimeError('missing local config')\n", encoding="utf-8"- )- second = tmp_path / "second.py"- second.write_text("VALUE = 1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- second.write_text("raise SystemExit('restored exit')\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second"))- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("first", "second"))-- with pytest.raises(SystemExit) as exc_info:- hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )-- assert exc_info.value.code == 1- assert second.read_text(encoding="utf-8") == "VALUE = 1\n"- assert git("status", "--porcelain").stdout == ""- assert git("stash", "list").stdout.strip()- output = capsys.readouterr().out- assert "agent import second" in output- assert "restored exit" in output- assert "gateway was not restarted" in output---def test_restore_rejects_probe_termination(monkeypatch, tmp_path, capsys):- """A stash cannot bypass import validation by terminating the probe."""- import subprocess- from hermes_cli import update_cmd- import hermes_cli.update_cmd_deps as update_cmd_deps-- def git(*args, check=True):- return subprocess.run(- ["git", *args],- cwd=tmp_path,- capture_output=True,- text=True,- check=check,- )-- git("init", "-q", "-b", "main")- git("config", "user.email", "[email protected]")- git("config", "user.name", "t")- source = tmp_path / "consumer.py"- source.write_text("VALUE = 1\n", encoding="utf-8")- git("add", "-A")- git("commit", "-qm", "init")-- source.write_text("import os\nos._exit(7)\n", encoding="utf-8")- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)- assert stash_ref- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- with pytest.raises(SystemExit) as exc_info:- hermes_main._restore_stashed_changes(- ["git"], tmp_path, stash_ref, prompt_user=False- )-- assert exc_info.value.code == 1- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"- assert git("status", "--porcelain").stdout == ""- assert git("stash", "list").stdout.strip()- output = capsys.readouterr().out- assert "critical-module probe" in output- assert "exit code 7" in output- assert "gateway was not restarted" in output--def test_restore_stays_parked_when_untracked_baseline_is_unknown(monkeypatch, tmp_path, capsys):diff --cc tests/plugins/test_security_guidance_plugin.pyindex 78e7dfed129,47d7dab640e..73b669fb0ba--- a/tests/plugins/test_security_guidance_plugin.py+++ b/tests/plugins/test_security_guidance_plugin.py@@@ -265,10 -284,12 +284,12 @@@ class TestPluginDiscoverydef test_loads_via_plugin_manager(self, _isolate_env, monkeypatch):"""End-to-end: enable in config.yaml and verify the PluginManagerpicks it up via the standard discovery path."""- import yaml+ import hermes_yaml as yamlconfig = {"plugins": {"enabled": ["security-guidance"]}}- (_isolate_env / "config.yaml").write_text(yaml.safe_dump(config))+ (_isolate_env / "config.yaml").write_text(+ yaml.safe_dump(config), encoding="utf-8"+ )# Wipe any cached plugin state from earlier tests in this worker.for k in list(sys.modules):diff --cc tools/skill_ledger.pyindex c5099867a98,5e3831980e9..e211d2f1fef--- a/tools/skill_ledger.py+++ b/tools/skill_ledger.py@@@ -296,6 -296,19 +296,20 @@@ def append_entryreturn None+ def _read_ledger(what: str, *, quiet_missing: bool = False) -> Optional[bytes]:+ """Raw ledger bytes, or ``None`` (after a warning) when the file cannot be read or is not UTF-8.+ ``quiet_missing`` keeps a merely absent ledger silent — normal for a fresh install."""+ try:+ raw = ledger_path().read_bytes()- raw.decode("utf-8")- return raw++ # Windows editors may prepend a UTF-8 BOM. Normalize it away so every++ # consumer can decode ordinary UTF-8 without treating the first row as malformed.++ return raw.decode("utf-8-sig").encode("utf-8")+ except (OSError, UnicodeError) as exc:+ if not (quiet_missing and isinstance(exc, FileNotFoundError)):+ logger.warning("skill_ledger: ledger unreadable (%s); %s", exc, what)+ return None++def compact_ledger() -> Tuple[int, int, int]:"""Rewrite the ledger with every entry's unchanged paths dropped (see ``_delta``); ids, order androllback semantics are preserved. Returns ``(entries, bytes_before, bytes_after)``. Atomic: thediff --cc website/docs/developer-guide/plugins/index.mdindex 3e437a0721e,874e0666e59..971ca9997c4--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@@ -300,9 -300,9 +300,9 @@@ this Hermes understands still loads wit| `manifest_version` | int | Manifest **file-format** version. Absent = `1`. Current max: `2`. Independent from `api_version`. || `api_version` | int | Runtime **plugin API generation** the plugin targets (ctx surface / hook signatures). Deliberately a separate axis from `manifest_version` — an `api_version: 1` plugin can use a v2 manifest. || `requires_plugins` | list | Inter-plugin dependencies: `- id: other-plugin` with optional `version_range: ">=1.0,<2"`. **Advisory**: a missing dependency logs a clear warning but the plugin still loads — probe at runtime with `ctx.has_plugin("other-plugin")`. Load **order** honors these edges: when A requires B, B's `register()` runs before A's (topological sort, alphabetical tiebreak; cycles warn and fall back to alphabetical order). |-| `python_dependencies` | list of str | PEP 508 requirements (e.g. `"requests>=2.0,<3"`). Installed into Hermes' venv on `hermes plugins install` / `enable` and **re-applied after every `hermes update`** (see [Python dependencies](#python-dependencies)). A `pyproject.toml` beside `plugin.yaml` with `[project].dependencies` is the equivalent, preferred form. |+| `python_dependencies` | list of str | Declared Python requirements (e.g. `"requests>=2.0,<3"`). Installation requests consent; enabling admits the candidate through PM with the existing core, extras, and enabled-plugin union. Successful preparation publishes the environment and configuration transactionally; failure preserves the previous selection and enabled set. Declining leaves the installed plugin disabled. Pin upper bounds. || `python_runtime` | str | `external` — the plugin manages its own interpreter/venv (sidecar pattern); Hermes installs nothing and leaves any `pyproject.toml` alone. |- | `config_schema` | mapping | JSON-schema-ish description of keys under `plugins.entries.<id>.settings`: `api_url: {type: str, default: "", description: "...", required: false}`. Validated at load; mismatches log actionable warnings naming the key and expected type — never load failures. Types: `str`, `int`, `float`, `bool`, `list`, `dict` (plus JSON-schema aliases). |+ | `config_schema` | mapping | JSON-schema-ish description of keys under `plugins.entries.<id>.settings`: `api_url: {type: str, default: "", description: "...", required: false}`. Validated at load; mismatches log actionable warnings naming the key and expected type — never load failures. Types: `str`, `int`, `float`, `bool`, `list`, `dict` (plus JSON-schema aliases) and `secret`. Also drives the settings form in the Desktop Plugins tab — see [Settings form in the Desktop](#settings-form-in-the-desktop). || `license` | str | SPDX-style license id (e.g. `MIT`). || `homepage` | str | Project URL. || `tags` | list of str | Free-form discovery tags (e.g. `[gateway, telegram]`). |diff --cc website/docs/user-guide/features/plugins.mdindex a4e9d0ab6a1,1d6a1a49e4f..6af3b35598d--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@@ -375,68 -387,17 +387,70 @@@ hermes plugins lishermes plugins search <term> # search the Hermes plugin cataloghermes plugins install <name> # install a catalog entry (repo @ reviewed pinned SHA)hermes plugins install user/repo # install from Git, then prompt Enable? [y/N]-hermes plugins install user/repo --enable # install AND enable (no prompt)+hermes plugins install user/repo --enable # request enable; dependency consent still applieshermes plugins install user/repo --no-enable # install but leave disabled (no prompt)hermes plugins update my-plugin # pull latest (local edits are autostashed and re-applied)- hermes plugins remove my-plugin # uninstall+ hermes plugins remove my-plugin # uninstall; also drops it from plugins.enabled/disabled/entries+ # and resets memory.provider when it was the live providerhermes plugins enable my-plugin # add to allow-list- hermes plugins disable my-plugin # remove from allow-list + add to disabled+ hermes plugins disable my-plugin # remove from allow-list + add to disabled (bundled platforms:+ # either spelling works, e.g. photon-platform or platforms/photon)hermes plugins capabilities [my-plugin] # declared vs granted capabilities+hermes plugins check-updates # read-only: is any installed plugin outdated?+hermes plugins adopt my-plugin # track a self-cloned plugin dir (read its git origin)+hermes plugins trust-update-url my-plugin # confirm a changed update_url after review```+### Update checks and provenance++Hermes records Git install source and revision in `.install-metadata.json`.+Unpinned tracked installs compare the saved source's remote HEAD, or a matching+saved `update_url` feed. Pinned installs remain pinned. Self-cloned directories+need `hermes plugins adopt NAME` before they become tracked installations.+Manually copied or provenance-drifted directories receive diagnostic guidance.+Pip entry-point plugins can report an owning distribution's available version;+that check does not turn them into Git-managed installs.++`hermes plugins check-updates` leaves plugin files unchanged. A scheduled gateway+check runs when `plugins.auto_update_check_hours` is due: default 24 hours,+`0` disables it. Its receipt is available through `hermes pm status` and the+desktop sync-status view. This is not a hard once-per-day limit if you configure+a different interval.++By default, updates require `hermes plugins update NAME`. Setting+`plugins.auto_apply: true` opts tracked Git plugins into unattended updates.+Both routes use the update security scan. Auto-apply does not manage pinned,+manual, drifted, or pip-distribution rows.++If a manifest changes or introduces `update_url`, Hermes refuses the new address+until you approve it with `hermes plugins trust-update-url NAME`. This is a+feed-source check, not a sandbox against already trusted plugin code.++### Dependency preparation and preservation++Python dependency installation has a separate consent/admission step.+`plugins install --enable` does not bypass that step. A declined or+non-interactive dependency install can leave the plugin installed but disabled.+Node sidecar dependencies have a separate prompt and remain plugin-local.++PM prepares Python dependencies with core and the enabled plugin set before+publishing the new environment and configuration. A resolution failure preserves+the previous selection. Restart Hermes when a new selected environment is not+yet active in the running process.++The enabled set is the union over the default home **and every profile** under+`profiles/`, read from each `config.yaml` (`plugins.enabled`, `plugins.disabled`,+`memory.provider`). PM refuses to guess at a home it cannot read: a+`config.yaml` that is not valid YAML, is not a mapping, or has a non-list+`plugins.enabled`/`plugins.disabled` or non-string `memory.provider` fails+dependency preparation for **all** homes (`could not parse plugin selection:+<path>`), rather than silently dropping that profile's plugins from the next+environment. Fix or remove the offending file; an empty `config.yaml` is fine.++Ordinary Hermes application updates preserve user plugin directories, including+wrapper files and external sidecar links. Explicit plugin updates or removals+can change those files. See [Package management](../../reference/package-management.md)+and the [plugin authoring guide](../../developer-guide/plugins/index.md#lazy-install-optional-python-dependencies).### One-click install links (Desktop)Hermes Desktop registers the `hermes://` URL scheme, so a website, README, ordiff --cc website/docs/user-guide/security.mdindex 562ee58af63,02fb4cd8c7a..db9f86be7ce--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@@ -918,39 -906,16 +918,49 @@@ TERMINAL_SSH_KEY=~/.ssh/hermes_agent_keThe SSH connection details live in `.env` (not `config.yaml`) so they aren't checked in or shared along with profile exports. This keeps the gateway's messaging connections separate from the agent's command execution.+## TLS certificate trust++Hermes initializes the platform verifier through `truststore`. Windows uses+its certificate store, macOS uses its system trust services, and Linux uses+the OpenSSL system trust paths. If initialization fails, Hermes logs the+failure and falls back to OpenSSL defaults.++For a corporate TLS proxy, install its root through your organization's+operating-system trust procedure. Hermes' provider resolver no longer selects+trust through `HERMES_CA_BUNDLE` or the old CA-environment-variable ladder.+Sandboxed subprocesses can have their own separate CA configuration.++The former startup certificate guard is gone with it: Hermes no longer+validates `HERMES_CA_BUNDLE` / `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` /+`CURL_CA_BUNDLE` at launch, so there is no `SSLConfigurationError` and the+`HERMES_SKIP_SSL_GUARD` escape hatch has no effect. `HERMES_CA_BUNDLE` is+still honoured by the Nous Portal login flow only (`hermes login`, or its+`--ca-bundle` flag); the standard `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `CURL_CA_BUNDLE` variables+are still read by the plain `requests`/`urllib` calls some tools make (and by+`pip`, `uv`, `curl`, Node), so a stale path in one of them now fails at the+call that uses it rather than at startup. Fix or unset the variable there.++A custom provider can declare `ssl_ca_cert` for its endpoint. That bundle+replaces platform trust for chat, model metadata, and model catalog probes.+A missing file produces a warning and falls back to platform trust.+`ssl_verify: false` disables certificate verification and is unsafe for+untrusted networks. Do not use it as a permanent fix for a missing corporate root.++Provider HTTP clients keep proxy configuration separate from certificate+selection. A stale ambient CA-file path cannot prevent those clients from+starting. PM index credentials are sent only to their exact HTTPS origin;+redirects to another origin do not receive them.++ ## Trusted-by-placement extension points {#trusted-by-placement}++ Most third-party code Hermes can run is gated by an explicit allow-list: general plugins need `plugins.enabled`, shell hooks need a first-use approval (or `hooks_auto_accept`), MCP servers are listed in config. One surface is deliberately different:++ | Extension point | Loaded from | Loaded when | Opt-in |+ |-----------------|-------------|-------------|--------|+ | [Gateway event hooks](./features/hooks.md#gateway-event-hooks) | `<profile home>/hooks/<name>/` (`HOOK.yaml` + `handler.py`) | Gateway startup (`HookRegistry.discover_and_load()`), per served profile | **Placing the directory.** No `plugins.enabled` entry, no prompt; `HERMES_SAFE_MODE` does not skip it. |++ The gateway imports every valid hook directory in-process, with the gateway's own privileges. This is the documented contract (since `3988c3c245f`), not an oversight: the profile home is operator-owned configuration, and anyone who can write into it can already run code as you through `config.yaml` shell hooks or by editing `plugins.enabled`, so a separate consent gate for `hooks/` would add friction without moving the trust boundary. Treat the contents of `~/.hermes/hooks/` like the contents of `config.yaml` — review a `handler.py` before you place it, and include `ls ~/.hermes/hooks/` whenever you audit the rest of the profile home (the directory is not on the [protected-paths denylist](#file-write-safety), so it is ordinary writable state). Full details: [gateway hook trust model](./features/hooks.md#gateway-hook-trust).+## Supply-chain advisory checkingHermes ships with a built-in advisory scanner that flags Python packages in the active venv that match a curated catalog of known-compromised versions (supply-chain worms like the May 2026 `mistralai 2.4.6` poisoning). Implementation lives in `hermes_cli/security_advisories.py`.