Skip to content

The agent that grows with you

merge: integrate upstream catalog with PM publication

ethernete4cc7f09d99b
diff --cc .gitignore
index f545754285d,0407b5eb737..ea92770db47
--- a/.gitignore
+++ b/.gitignore
@@@ -1,389 -1,226 +1,392 @@@
-
- !apps/desktop/src/global.d.ts
- !apps/desktop/src/plugins/*/plugin.js
- !apps/desktop/src/vite-env.d.ts
- !hermes_cli/data/
- !hermes_cli/data/plugin_index.json
- # — ignore so `git status` stays clean and update's autostash skips them.
- # (launch-time stale-bytecode sweep). Runtime state, never a code change.
- # `data/` pattern above would otherwise swallow it.
- # `npm run sync-assets` (see web/package.json).
- # also created in-repo when an agent operates in this checkout). Plans, audit
- # and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
- # automation-blueprints-index.json is a build artifact emitted by
- # bootstrap installer. It is Hermes-managed runtime state, never a code change —
- # Bundled community plugin index seed (shipped as package data) — the bare
- # by `hermes update` / launch-time self-heal. Runtime state, never a code change
- # by accident via 3a69e34702, removed in the #72002 salvage).
- # Checkout fingerprint the __pycache__ tree was last validated against
- # CLI config (may contain sensitive SSH paths)
- # committed to the repo root. See the hermes-release skill.
- # Cross-process web UI build lock (flock target, always empty)
- # cut (passed to `gh release create --notes-file`); the GitHub Release itself
- # Desktop demo-run scratch output (hermes writes demo/*.txt during recorded
- # Desktop/bootstrap install marker written into the managed checkout root by the
- # e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx
- # every build).
- # EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,
- # git for the same reason as skills-index.json (large, generated, change
- # ignore it so `hermes update`'s `git stash push --include-untracked` does not
- # image-provider (fal.media) URL — they are NEVER committed to the repo. The
- # infographic-check CI job is what actually enforces this.
- # Installer-written method stamp in the managed checkout root (scripts/install.sh).
- # interrupted; consumed by launch-time recovery. Never commit it (was tracked
- # Interrupted-update breadcrumb + recovery lock written next to the shared venv
- # Local editor / agent tooling (machine-specific; keep in global config, not the repo)
- # logs, and per-session caches are never artifacts of the codebase.
- # Nix
- # No trailing slash: also matches node_modules SYMLINKS (worktrees often
- # Per-release changelog drafts. These exist only transiently during a release
- # Persistent dev sandbox dir (scripts/dev-sandbox.sh --persistent)
- # Playwright visual regression baselines — cached from main in CI, not committed
- # PR body is the archive. See the hermes-agent-dev skill's
- # PR infographics are rendered locally and embedded in PR descriptions via the
- # pr-infographic-workflow reference (storage rule + lapse #8 / #COMMIT-1).
- # Private keys
- # regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.
- # Release script temp files
- # Repo-root build/debug artifacts that must never be committed
- # resolves the stale .js OVER the .tsx — never track these)
- # Runtime marker written by hermes update when a lazy dependency refresh is
- # Runtime metadata only — never a code change. Ignore so `git status` stays clean
- # Sandbox dirs used by the install/update E2E (tests/install/). The suffix is
- # sibling exists, so the stale-shadow hazard above cannot apply.
- # sidestepped by an `infograficos/` directory (#70552). .gitignore is only
- # Skills Hub state (lives in ~/.hermes/skills/.hub/ at runtime, but just in case)
- # skills.json + skills-meta.json are build artifacts emitted by
- # slip into a commit and break `npm ci` on CI with ENOTDIR).
- # Spelling variants are listed because a single `infographic/` pattern was
- # stores the published notes. They are not a build artifact and must never be
- # symlink node_modules to the main checkout; the dir-only pattern let one
- # the first line of defence and cannot stop `git add -f` at all — the
- # the route name, so each route gets its own tree and two can run at once.
- # Tool Search live-test harness output — non-deterministic model transcripts,
- # treat it as a local edit and autostash it on every run (#38529).
- # tsc-emitted artifacts (a stray `tsc -b` compiles into src/, and vite then
- # walkthroughs). Throwaway artifacts, never part of the app.
- # Web UI assets — synced from @nous-research/ui at build time via
- # Web UI build output
- # website/scripts/extract-automation-blueprints.py during prebuild.
- # website/scripts/extract-skills.py during prebuild — keep them out of
- # Working directory for the Hermes Agent's session state (~/.hermes/ at runtime;
- #
- %SystemDrive%/
- *.pem
- *.ppk
- *.pyc*
- *.tsbuildinfo
- *-snapshots/
- .act-sandbox-agent.*
- .bytecode-fingerprint
- .bytecode-fingerprint.tmp
- .codex/
- .cursor/
- .direnv/
- .DS_Store
- .env
- .env.development
- .env.development.local
- .env.local
- .env.production.local
- .env.test
- .env.test.local
- .gemini/
- .hermes/
- .hermes-bootstrap-complete
- .hermes-docker/
- .hermes-sandbox/
- .hermes-sandbox-e2e*/
- .lazy-refresh-incomplete
- .mcp.json
- .nix-stamps/
- .notebooklm-cli-venv/
- .notebooklm-home/
- .notebooklm-playwright/
- .op.env
- .pip-cache/
- .pytest_cache/
- .pytest-cache/
- .release_notes.md
- .skills_prompt_snapshot.json
- .update-incomplete
- .update-incomplete.lock
- .uv-cache/
- .venv
- .venv/
- .vscode/
- .web_ui_build.lock
- .worktrees/
- .zed/
- /*.png.bak
- /.hermes-runtime/
- /.install_method
- /_pycache/
- /bin/
- /default.tar.gz
- /log.txt
- /sqlite_leak_fix.png
- /venv.old/
- /venv.stale.runtime-*/
- /venv/
- __pycache__/
- __pycache__/model_tools.cpython-310.pyc
- __pycache__/web_tools.cpython-310.pyc
- act/
- agent-browser/
- apps/desktop/build/
- apps/desktop/demo/
- apps/desktop/dist/
- apps/desktop/release/
- apps/desktop/src/**/*.d.ts
- apps/desktop/src/**/*.js
- apps/desktop/src/**/*.js.map
- apps/shared/src/**/*.d.ts
- apps/shared/src/**/*.js
- apps/shared/src/**/*.js.map
- browser-use/
- cli-config.yaml
- compose.hermes.local.yml
- config/mcporter.json
- data/
- data/*
- docs/superpowers/*
- environments/benchmarks/evals/
- examples/
- export*
- hermes-*/*
- hermes_agent.egg-info/
- hermes_cli/scripts/
- hermes_cli/tui_dist/*
- hermes_cli/web_dist/
- ignored/
- images/
- infografico/
- infograficos/
- infographic/
- infographics/
- logs/
- mini-swe-agent/
- models-dev-upstream/
- native/fts5_cjk/*.so
- node_modules
- opencode.json
- playwright-report/
- privvy*
- RELEASE_v*.md
- result
- run_datagen_kimik2-thinking.sh
- run_datagen_megascience_glm4-6.sh
- run_datagen_sonnet.sh
- source-data/*
- run_datagen_megascience_glm4-6.sh
- data/*
- # No trailing slash: also matches node_modules SYMLINKS (worktrees often
- # symlink node_modules to the main checkout; the dir-only pattern let one
- # slip into a commit and break `npm ci` on CI with ENOTDIR).
- node_modules
- browser-use/
- agent-browser/
- # Private keys
- *.ppk
- *.pem
- privvy*
- images/
- __pycache__/
- hermes_agent.egg-info/
- wandb/
- testlogs
- playwright-report/
- test-results/
- # Playwright visual regression baselines — cached from main in CI, not committed
- *-snapshots/
-
- # CLI config (may contain sensitive SSH paths)
- cli-config.yaml
-
- # Skills Hub state (lives in ~/.hermes/skills/.hub/ at runtime, but just in case)
- skills/.hub/
- ignored/
- .worktrees/
- environments/benchmarks/evals/
-
- # Web UI build output
- hermes_cli/web_dist/
- # Cross-process web UI build lock (flock target, always empty)
- .web_ui_build.lock
- apps/desktop/build/
- apps/desktop/dist/
-
- # tsc-emitted artifacts (a stray `tsc -b` compiles into src/, and vite then
- # resolves the stale .js OVER the .tsx — never track these)
- apps/desktop/src/**/*.js
- apps/desktop/src/**/*.js.map
- apps/desktop/src/**/*.d.ts
- # EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,
- # e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx
- # sibling exists, so the stale-shadow hazard above cannot apply.
- !apps/desktop/src/plugins/*/plugin.js
- !apps/desktop/src/global.d.ts
- !apps/desktop/src/vite-env.d.ts
-
- # Build/debug artifacts that must never be committed
- /log.txt
- /sqlite_leak_fix.png
- /*.png.bak
- *.tar.gz
- *.tgz
- apps/shared/src/**/*.js
- apps/shared/src/**/*.js.map
- apps/shared/src/**/*.d.ts
- apps/desktop/release/
- # stage-and-swap Desktop rebuild output (#86443); removed after the swap, but
- # a killed build must not leave the checkout dirty
- apps/desktop/.staging-*/
- *.tsbuildinfo
-
- # Web UI assets — synced from @nous-research/ui at build time via
- # `npm run sync-assets` (see web/package.json).
- web/public/fonts/
- web/public/ds-assets/
-
- # Release script temp files
- .release_notes.md
- mini-swe-agent/
-
- # Nix
- .direnv/
- .nix-stamps/
- result
- website/static/api/skills-index.json
- # skills.json + skills-meta.json are build artifacts emitted by
- # website/scripts/extract-skills.py during prebuild — keep them out of
- # git for the same reason as skills-index.json (large, generated, change
- # every build).
- website/static/api/skills.json
- website/static/api/skills-meta.json
- # automation-blueprints-index.json is a build artifact emitted by
- # website/scripts/extract-automation-blueprints.py during prebuild.
- website/static/api/automation-blueprints-index.json
- models-dev-upstream/
-
- # Local editor / agent tooling (machine-specific; keep in global config, not the repo)
- .codex/
- .cursor/
- .gemini/
- .zed/
- .mcp.json
- opencode.json
- config/mcporter.json
-
- hermes_cli/tui_dist/*
- hermes_cli/scripts/
- docs/superpowers/*
- # Working directory for the Hermes Agent's session state (~/.hermes/ at runtime;
- # also created in-repo when an agent operates in this checkout). Plans, audit
- # logs, and per-session caches are never artifacts of the codebase.
- .hermes/
-
- # Desktop/bootstrap install marker written into the managed checkout root by the
- # bootstrap installer. It is Hermes-managed runtime state, never a code change —
- # ignore it so `hermes update`'s `git stash push --include-untracked` does not
- # treat it as a local edit and autostash it on every run (#38529).
- .hermes-bootstrap-complete
-
- # Persistent dev sandbox dir (scripts/dev-sandbox.sh --persistent)
- .hermes-sandbox/
- # Sandbox dirs used by the install/update E2E (tests/install/). The suffix is
- # the route name, so each route gets its own tree and two can run at once.
- .hermes-sandbox-e2e*/
-
- # Interrupted-update breadcrumb + recovery lock written next to the shared venv
- # by `hermes update` / launch-time self-heal. Runtime state, never a code change
- # — ignore so `git status` stays clean and update's autostash skips them.
- .update-incomplete
- .update-incomplete.lock
-
- # Checkout fingerprint the __pycache__ tree was last validated against
- # (launch-time stale-bytecode sweep). Runtime state, never a code change.
- .bytecode-fingerprint
- .bytecode-fingerprint.tmp
-
- # Installer-written method stamp in the managed checkout root (scripts/install.sh).
- # Runtime metadata only — never a code change. Ignore so `git status` stays clean
- # and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
- /.install_method
-
- # Tool Search live-test harness output — non-deterministic model transcripts,
- # regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.
-
- scripts/out/
-
- # Per-release changelog drafts. These exist only transiently during a release
- # cut (passed to `gh release create --notes-file`); the GitHub Release itself
- # stores the published notes. They are not a build artifact and must never be
- # committed to the repo root. See the hermes-release skill.
-
- # Desktop demo-run scratch output (hermes writes demo/*.txt during recorded
- # walkthroughs). Throwaway artifacts, never part of the app.
-
- # PR infographics are rendered locally and embedded in PR descriptions via the
- # image-provider (fal.media) URL — they are NEVER committed to the repo. The
- # PR body is the archive. See the hermes-agent-dev skill's
- # pr-infographic-workflow reference (storage rule + lapse #8 / #COMMIT-1).
- #
- # Spelling variants are listed because a single `infographic/` pattern was
- # sidestepped by an `infograficos/` directory (#70552). .gitignore is only
- # the first line of defence and cannot stop `git add -f` at all — the
- # infographic-check CI job is what actually enforces this.
- # Runtime marker written by hermes update when a lazy dependency refresh is
- # interrupted; consumed by launch-time recovery. Never commit it (was tracked
- # by accident via 3a69e34702, removed in the #72002 salvage).
-
- # Disposable profile created by scripts/probe_active_session_exclusivity.py
- .probe-home/
- skills/.hub/
- source-data/*
- temp_vision_images/
- test_durations.json
- testlogs
- test-results/
- tests/quick_test_dataset.jsonl
- tests/sample_dataset.jsonl
- tmp/
- wandb/
- web/public/ds-assets/
- web/public/fonts/
- website/static/api/automation-blueprints-index.json
- website/static/api/skills.json
- website/static/api/skills-index.json
-.DS_Store
-/venv/
-/venv.old/
-/venv.stale.runtime-*/
-/bin/
-/.hermes-runtime/
-/_pycache/
++
++!apps/desktop/src/global.d.ts
++!apps/desktop/src/plugins/*/plugin.js
++!apps/desktop/src/vite-env.d.ts
++!hermes_cli/data/
++# — ignore so `git status` stays clean and update's autostash skips them.
++# (launch-time stale-bytecode sweep). Runtime state, never a code change.
++# `data/` pattern above would otherwise swallow it.
++# `npm run sync-assets` (see web/package.json).
++# also created in-repo when an agent operates in this checkout). Plans, audit
++# and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
++# automation-blueprints-index.json is a build artifact emitted by
++# bootstrap installer. It is Hermes-managed runtime state, never a code change —
++# Bundled community plugin index seed (shipped as package data) — the bare
++# by `hermes update` / launch-time self-heal. Runtime state, never a code change
++# by accident via 3a69e34702, removed in the #72002 salvage).
++# Checkout fingerprint the __pycache__ tree was last validated against
++# CLI config (may contain sensitive SSH paths)
++# committed to the repo root. See the hermes-release skill.
++# Cross-process web UI build lock (flock target, always empty)
++# cut (passed to `gh release create --notes-file`); the GitHub Release itself
++# Desktop demo-run scratch output (hermes writes demo/*.txt during recorded
++# Desktop/bootstrap install marker written into the managed checkout root by the
++# e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx
++# every build).
++# EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,
++# git for the same reason as skills-index.json (large, generated, change
++# ignore it so `hermes update`'s `git stash push --include-untracked` does not
++# image-provider (fal.media) URL — they are NEVER committed to the repo. The
++# infographic-check CI job is what actually enforces this.
++# Installer-written method stamp in the managed checkout root (scripts/install.sh).
++# interrupted; consumed by launch-time recovery. Never commit it (was tracked
++# Interrupted-update breadcrumb + recovery lock written next to the shared venv
++# Local editor / agent tooling (machine-specific; keep in global config, not the repo)
++# logs, and per-session caches are never artifacts of the codebase.
++# Nix
++# No trailing slash: also matches node_modules SYMLINKS (worktrees often
++# Per-release changelog drafts. These exist only transiently during a release
++# Persistent dev sandbox dir (scripts/dev-sandbox.sh --persistent)
++# Playwright visual regression baselines — cached from main in CI, not committed
++# PR body is the archive. See the hermes-agent-dev skill's
++# PR infographics are rendered locally and embedded in PR descriptions via the
++# pr-infographic-workflow reference (storage rule + lapse #8 / #COMMIT-1).
++# Private keys
++# regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.
++# Release script temp files
++# Repo-root build/debug artifacts that must never be committed
++# resolves the stale .js OVER the .tsx — never track these)
++# Runtime marker written by hermes update when a lazy dependency refresh is
++# Runtime metadata only — never a code change. Ignore so `git status` stays clean
++# Sandbox dirs used by the install/update E2E (tests/install/). The suffix is
++# sibling exists, so the stale-shadow hazard above cannot apply.
++# sidestepped by an `infograficos/` directory (#70552). .gitignore is only
++# Skills Hub state (lives in ~/.hermes/skills/.hub/ at runtime, but just in case)
++# skills.json + skills-meta.json are build artifacts emitted by
++# slip into a commit and break `npm ci` on CI with ENOTDIR).
++# Spelling variants are listed because a single `infographic/` pattern was
++# stores the published notes. They are not a build artifact and must never be
++# symlink node_modules to the main checkout; the dir-only pattern let one
++# the first line of defence and cannot stop `git add -f` at all — the
++# the route name, so each route gets its own tree and two can run at once.
++# Tool Search live-test harness output — non-deterministic model transcripts,
++# treat it as a local edit and autostash it on every run (#38529).
++# tsc-emitted artifacts (a stray `tsc -b` compiles into src/, and vite then
++# walkthroughs). Throwaway artifacts, never part of the app.
++# Web UI assets — synced from @nous-research/ui at build time via
++# Web UI build output
++# website/scripts/extract-automation-blueprints.py during prebuild.
++# website/scripts/extract-skills.py during prebuild — keep them out of
++# Working directory for the Hermes Agent's session state (~/.hermes/ at runtime;
++#
++%SystemDrive%/
++*.pem
++*.ppk
+ *.pyc*
-__pycache__/
-act/
++*.tsbuildinfo
++*-snapshots/
+ .act-sandbox-agent.*
-.venv/
-.venv
-.vscode/
++.bytecode-fingerprint
++.bytecode-fingerprint.tmp
++.codex/
++.cursor/
++.direnv/
++.DS_Store
+ .env
-.op.env
-.env.local
++.env.development
+ .env.development.local
-.env.test.local
++.env.local
+ .env.production.local
-.env.development
+ .env.test
++.env.test.local
++.gemini/
++.hermes/
++.hermes-bootstrap-complete
+ .hermes-docker/
-.notebooklm-home/
++.hermes-sandbox/
++.hermes-sandbox-e2e*/
++.lazy-refresh-incomplete
++.mcp.json
++.nix-stamps/
+ .notebooklm-cli-venv/
++.notebooklm-home/
+ .notebooklm-playwright/
++.op.env
+ .pip-cache/
++.pytest_cache/
++.pytest-cache/
++.release_notes.md
++.skills_prompt_snapshot.json
++.update-incomplete
++.update-incomplete.lock
+ .uv-cache/
-compose.hermes.local.yml
-export*
++.venv
++.venv/
++.vscode/
++.web_ui_build.lock
++.worktrees/
++.zed/
++/*.png.bak
++/.hermes-runtime/
++/.install_method
++/_pycache/
++/bin/
++/default.tar.gz
++/log.txt
++/sqlite_leak_fix.png
++/venv.old/
++/venv.stale.runtime-*/
++/venv/
++__pycache__/
+ __pycache__/model_tools.cpython-310.pyc
+ __pycache__/web_tools.cpython-310.pyc
-logs/
++act/
++agent-browser/
++apps/desktop/build/
++apps/desktop/demo/
++apps/desktop/dist/
++apps/desktop/release/
++apps/desktop/src/**/*.d.ts
++apps/desktop/src/**/*.js
++apps/desktop/src/**/*.js.map
++apps/shared/src/**/*.d.ts
++apps/shared/src/**/*.js
++apps/shared/src/**/*.js.map
++browser-use/
++cli-config.yaml
++compose.hermes.local.yml
++config/mcporter.json
+ data/
-# Bundled community plugin index seed (shipped as package data) — the bare
-# `data/` pattern above would otherwise swallow it.
-!hermes_cli/data/
-.pytest_cache/
-test_durations.json
-.pytest-cache/
-tmp/
-temp_vision_images/
-hermes-*/*
++data/*
++docs/superpowers/*
++environments/benchmarks/evals/
+ examples/
-tests/quick_test_dataset.jsonl
-tests/sample_dataset.jsonl
++export*
++hermes-*/*
++hermes_agent.egg-info/
++hermes_cli/scripts/
++hermes_cli/tui_dist/*
++hermes_cli/web_dist/
++ignored/
++images/
++infografico/
++infograficos/
++infographic/
++infographics/
++logs/
++mini-swe-agent/
++models-dev-upstream/
++native/fts5_cjk/*.so
++node_modules
++opencode.json
++playwright-report/
++privvy*
++RELEASE_v*.md
++result
+ run_datagen_kimik2-thinking.sh
+ run_datagen_megascience_glm4-6.sh
+ run_datagen_sonnet.sh
+ source-data/*
+ run_datagen_megascience_glm4-6.sh
+ data/*
+ # No trailing slash: also matches node_modules SYMLINKS (worktrees often
+ # symlink node_modules to the main checkout; the dir-only pattern let one
+ # slip into a commit and break `npm ci` on CI with ENOTDIR).
+ node_modules
+ browser-use/
+ agent-browser/
+ # Private keys
+ *.ppk
+ *.pem
+ privvy*
+ images/
+ __pycache__/
+ hermes_agent.egg-info/
+ wandb/
+ testlogs
+ playwright-report/
+ test-results/
+ # Playwright visual regression baselines — cached from main in CI, not committed
+ *-snapshots/
+
+ # CLI config (may contain sensitive SSH paths)
+ cli-config.yaml
+
+ # Skills Hub state (lives in ~/.hermes/skills/.hub/ at runtime, but just in case)
+ skills/.hub/
+ ignored/
+ .worktrees/
+ environments/benchmarks/evals/
+
+ # Web UI build output
+ hermes_cli/web_dist/
+ # Cross-process web UI build lock (flock target, always empty)
+ .web_ui_build.lock
+ apps/desktop/build/
+ apps/desktop/dist/
+
+ # tsc-emitted artifacts (a stray `tsc -b` compiles into src/, and vite then
+ # resolves the stale .js OVER the .tsx — never track these)
+ apps/desktop/src/**/*.js
+ apps/desktop/src/**/*.js.map
+ apps/desktop/src/**/*.d.ts
+ # EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,
+ # e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx
+ # sibling exists, so the stale-shadow hazard above cannot apply.
+ !apps/desktop/src/plugins/*/plugin.js
+ !apps/desktop/src/global.d.ts
+ !apps/desktop/src/vite-env.d.ts
+
+ # Build/debug artifacts that must never be committed
+ /log.txt
+ /sqlite_leak_fix.png
+ /*.png.bak
+ *.tar.gz
+ *.tgz
+ apps/shared/src/**/*.js
+ apps/shared/src/**/*.js.map
+ apps/shared/src/**/*.d.ts
+ apps/desktop/release/
+ # stage-and-swap Desktop rebuild output (#86443); removed after the swap, but
+ # a killed build must not leave the checkout dirty
+ apps/desktop/.staging-*/
+ *.tsbuildinfo
+
+ # Web UI assets — synced from @nous-research/ui at build time via
+ # `npm run sync-assets` (see web/package.json).
+ web/public/fonts/
+ web/public/ds-assets/
+
+ # Release script temp files
+ .release_notes.md
+ mini-swe-agent/
+
+ # Nix
+ .direnv/
+ .nix-stamps/
+ result
+ website/static/api/skills-index.json
+ # skills.json + skills-meta.json are build artifacts emitted by
+ # website/scripts/extract-skills.py during prebuild — keep them out of
+ # git for the same reason as skills-index.json (large, generated, change
+ # every build).
+ website/static/api/skills.json
+ website/static/api/skills-meta.json
-# plugins.json + plugins-meta.json are build artifacts emitted by
-# website/scripts/extract-plugins.py during prebuild (Plugin Catalog page).
++# Plugin catalog JSON is generated from plugin-catalog/ during prebuild.
+ website/static/api/plugins.json
+ website/static/api/plugin-catalog.json
+ website/static/api/plugins-meta.json
+ # automation-blueprints-index.json is a build artifact emitted by
+ # website/scripts/extract-automation-blueprints.py during prebuild.
+ website/static/api/automation-blueprints-index.json
+ models-dev-upstream/
+
+ # Local editor / agent tooling (machine-specific; keep in global config, not the repo)
+ .codex/
+ .cursor/
+ .gemini/
+ .zed/
+ .mcp.json
+ opencode.json
+ config/mcporter.json
+
+ hermes_cli/tui_dist/*
+ hermes_cli/scripts/
+ docs/superpowers/*
+ # Working directory for the Hermes Agent's session state (~/.hermes/ at runtime;
+ # also created in-repo when an agent operates in this checkout). Plans, audit
+ # logs, and per-session caches are never artifacts of the codebase.
+ .hermes/
+
+ # Desktop/bootstrap install marker written into the managed checkout root by the
+ # bootstrap installer. It is Hermes-managed runtime state, never a code change —
+ # ignore it so `hermes update`'s `git stash push --include-untracked` does not
+ # treat it as a local edit and autostash it on every run (#38529).
+ .hermes-bootstrap-complete
+
+ # Persistent dev sandbox dir (scripts/dev-sandbox.sh --persistent)
+ .hermes-sandbox/
+ # Sandbox dirs used by the install/update E2E (tests/install/). The suffix is
+ # the route name, so each route gets its own tree and two can run at once.
+ .hermes-sandbox-e2e*/
+
+ # Interrupted-update breadcrumb + recovery lock written next to the shared venv
+ # by `hermes update` / launch-time self-heal. Runtime state, never a code change
+ # — ignore so `git status` stays clean and update's autostash skips them.
+ .update-incomplete
+ .update-incomplete.lock
+
+ # Checkout fingerprint the __pycache__ tree was last validated against
+ # (launch-time stale-bytecode sweep). Runtime state, never a code change.
+ .bytecode-fingerprint
+ .bytecode-fingerprint.tmp
+
+ # Installer-written method stamp in the managed checkout root (scripts/install.sh).
+ # Runtime metadata only — never a code change. Ignore so `git status` stays clean
+ # and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
+ /.install_method
+
+ # Tool Search live-test harness output — non-deterministic model transcripts,
+ # regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.
++
+ scripts/out/
+
+ # Per-release changelog drafts. These exist only transiently during a release
+ # cut (passed to `gh release create --notes-file`); the GitHub Release itself
+ # stores the published notes. They are not a build artifact and must never be
+ # committed to the repo root. See the hermes-release skill.
-RELEASE_v*.md
+
+ # Desktop demo-run scratch output (hermes writes demo/*.txt during recorded
+ # walkthroughs). Throwaway artifacts, never part of the app.
-apps/desktop/demo/
+
+ # PR infographics are rendered locally and embedded in PR descriptions via the
+ # image-provider (fal.media) URL — they are NEVER committed to the repo. The
+ # PR body is the archive. See the hermes-agent-dev skill's
+ # pr-infographic-workflow reference (storage rule + lapse #8 / #COMMIT-1).
+ #
+ # Spelling variants are listed because a single `infographic/` pattern was
+ # sidestepped by an `infograficos/` directory (#70552). .gitignore is only
+ # the first line of defence and cannot stop `git add -f` at all — the
+ # infographic-check CI job is what actually enforces this.
-infographic/
-infographics/
-infograficos/
-infografico/
-native/fts5_cjk/*.so
+ # Runtime marker written by hermes update when a lazy dependency refresh is
+ # interrupted; consumed by launch-time recovery. Never commit it (was tracked
+ # by accident via 3a69e34702, removed in the #72002 salvage).
-.lazy-refresh-incomplete
-.skills_prompt_snapshot.json
+
+ # Disposable profile created by scripts/probe_active_session_exclusivity.py
+ .probe-home/
++skills/.hub/
++source-data/*
++temp_vision_images/
++test_durations.json
++testlogs
++test-results/
++tests/quick_test_dataset.jsonl
++tests/sample_dataset.jsonl
++tmp/
++wandb/
++web/public/ds-assets/
++web/public/fonts/
++website/static/api/automation-blueprints-index.json
++website/static/api/skills.json
++website/static/api/skills-index.json
+website/static/api/skills-meta.json
+# ── generated icon assets (see scripts/generate_icons.py) ──────────────────
+# Regenerated on demand by every consuming pipeline (website/desktop/
+# installer/web prebuild via scripts/generate-icons.mjs). Sources of truth:
+# assets/nous-girl-*.svg + assets/backgrounds/.
+assets/icon-master.svg
+assets/icon-master-dark.svg
+apps/desktop/assets/icon.png
+apps/desktop/assets/icon.ico
+apps/desktop/assets/icon.icns
+apps/desktop/assets/icon-dark.png
+apps/desktop/assets/icon-dark.ico
+apps/desktop/assets/icon-dark.icns
+apps/desktop/assets/appx/*.png
+apps/desktop/public/apple-touch-icon.png
+apps/desktop/public/nous-girl.png
+apps/desktop/public/nous-girl-dark.png
+apps/bootstrap-installer/src-tauri/icons/*.png
+apps/bootstrap-installer/src-tauri/icons/icon.ico
+apps/bootstrap-installer/src-tauri/icons/icon.icns
+apps/bootstrap-installer/public/nous-girl.png
+website/static/img/logo.png
+website/static/img/logo-dark.png
+website/static/img/nous-logo.png
+website/static/img/nous-logo-dark.png
+website/static/img/favicon-16x16.png
+website/static/img/favicon-32x32.png
+website/static/img/apple-touch-icon.png
+website/static/img/favicon.ico
+website/static/img/favicon.svg
+web/public/favicon.ico
diff --cc hermes_cli/backup.py
index b4b57b3bdda,fda440d66ef..49cbecd6128
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@@ -408,114 -404,186 +408,116 @@@ def verify_sqlite_integrity
return _done("header check passed", valid=True, size=size)
-def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:
- """PIDs of OTHER processes holding *db_path* or its WAL/SHM open (Linux ``/proc`` scan).
+# --- Backup ---
- An already-unlinked ``(deleted)`` sidecar — the #90950 split-brain fingerprint — still
- counts as held. None off-Linux or when /proc fails.
- """
- if not sys.platform.startswith("linux"):
- return None
++_RUN_BACKUP_PREFIX = "hermes-backup-"
+
- def _canonical(path: str) -> str:
- return os.path.normcase(os.path.abspath(path.removesuffix(" (deleted)")))
- def _holds_watched(fds: List[str], fd_dir: str) -> bool:
- for fd in fds:
- try:
- target = os.readlink(f"{fd_dir}/{fd}")
- except OSError:
- continue
- if _canonical(target) in watched:
- return True
- return False
+# --- Import ---
- canonical_db = _canonical(os.fspath(db_path))
- watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}
- pids: List[int] = []
- try:
- own_pid = os.getpid()
- for pid_str in os.listdir("/proc"):
- if not pid_str.isdigit() or int(pid_str) == own_pid:
- continue
- fd_dir = f"/proc/{pid_str}/fd"
- try:
- fds = os.listdir(fd_dir)
- except OSError:
- continue
- if _holds_watched(fds, fd_dir):
- pids.append(int(pid_str))
- except OSError:
- return None
- return pids
+# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---
+
+# Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is
+# regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR
+# directories (recursive); missing entries are skipped. Pairing data lives in platform JSON blobs
+# outside state.db, so it is listed explicitly — ``hermes update`` snapshots this set (#15733).
+_QUICK_STATE_FILES = (
+ "state.db", "config.yaml", ".env", "auth.json", "cron/jobs.json", "cron/executions.db",
+ "gateway_state.json", "channel_directory.json", "channel_aliases.json", "processes.json",
+ "gateway/discord_message_recovery.db", # Discord reconnect replay ledger
+ # Per-profile user stores, destroyed if the update flow replaces the file and the post-update
+ # schema-init re-creates an empty one (#52889). Skipped when outside HERMES_HOME.
+ "projects.db", # per-profile project store
+ "response_store.db", # gateway conversation history / tool payloads
+ "memory_store.db", # holographic memory facts/entities
+ "verification_evidence.db", # agent verification audit trail
+ "kanban.db", # default board (back-compat <root>/kanban.db)
+ "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)
+ # Pairing stores (generic + per-platform JSONs outside state.db)
+ "pairing", # legacy location (gateway/pairing.py)
+ "platforms/pairing", # new location (gateway/pairing.py)
+ "feishu_comment_pairing.json", # Feishu comment subscription pairings
+)
-def _safe_restore_db(src: Path, dst: Path) -> bool:
- """Restore snapshot *src* into live *dst* through the backup() API; unlink+move fallback.
+_QUICK_DEFAULT_KEEP = 20
- Writing pages into the live file preserves its inode and WAL state, so other holders (gateway,
- dashboard, another CLI) see the restored data instead of stale pages from a replaced inode.
- The fallback runs ONLY when no other process or in-process connection holds the file
- (replacing the inode under a live holder is the #90950 split-brain); otherwise it fails closed
- (``False``) and the caller reports the file as skipped.
- """
- try:
- dst_conn = sqlite3.connect(str(dst))
- # Checkpoint first so the backup starts clean rather than writing on top of a deep WAL.
- with suppress(Exception):
- dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
- with closing(sqlite3.connect(f"file:{src}?mode=ro", uri=True)) as src_conn:
- src_conn.backup(dst_conn)
- dst_conn.close()
- with suppress(Exception):
- dst.chmod(src.stat().st_mode)
- return True
- except Exception as exc:
- logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)
- return _unlink_move_restore_db(src, dst)
+def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:
+ home = hermes_home or get_hermes_home()
+ return home / _QUICK_SNAPSHOTS_DIR
-def _unlink_move_restore_db(src: Path, dst: Path) -> bool:
- """Fallback restore: unlink+move. Only safe when no process holds the DB open.
- Replacing the inode under a live holder is the #90950 corruption class (the holder keeps
- writing through a deleted-inode fd and loses its WAL index), so fail closed. The foreign-pid
- scan excludes THIS process, so ``offline_file_access`` also fails CLOSED on any live
- in-process connection to *dst* and holds the connection-lifecycle lock across the swap.
- """
- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
- try:
- holders = _foreign_db_holder_pids(dst)
- if holders:
- logger.error("Refusing unlink+move restore of %s: process(es) %s still "
- "hold the database or its WAL open. Stop them and retry.", dst, holders)
- return False
- with offline_file_access(dst, what="unlink+move restore of"):
- tmp = dst.parent / f".{dst.name}.snap_restore"
- shutil.copy2(src, tmp)
- dst.unlink(missing_ok=True)
- # The snapshot owns no WAL, so any -wal/-shm here belongs to the DB just unlinked (a
- # killed gateway leaves them — exactly when a restore runs); SQLite would replay that
- # foreign WAL over the restored file: "malformed" or resurrected post-snapshot rows.
- for _sidecar_suffix in ("-wal", "-shm", "-journal"):
- dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)
- shutil.move(str(tmp), str(dst))
- return True
- except LiveConnectionError as exc2:
- logger.error("Refusing unlink+move restore of %s: %s Close the in-process "
- "database handles (or restart Hermes) and retry.", dst, exc2)
- return False
- except Exception as exc2:
- logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)
- return False
+def _newest_first(root: Path, keep_entry) -> List[Path]:
+ """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""
+ if not root.exists():
+ return []
+ return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)
-def _zip_sqlite_snapshot(zf: zipfile.ZipFile, abs_path: Path, rel_path: Path, out_path: Path) -> Optional[int]:
- """Add a WAL-safe snapshot of *abs_path* to *zf*; return its byte size, or None on failure.
+# Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.
+_CRON_JOBS_REL = "cron/jobs.json"
- Staged beside the output zip: /tmp may be a small tmpfs that cannot hold large databases.
- """
- with tempfile.NamedTemporaryFile(suffix=".db", delete=False, dir=str(out_path.parent)) as tmp:
- tmp_db = Path(tmp.name)
- try:
- if not _safe_copy_db(abs_path, tmp_db):
- return None
- zf.write(tmp_db, arcname=str(rel_path))
- return tmp_db.stat().st_size
- finally:
- tmp_db.unlink(missing_ok=True)
+# Config paths the update flow must never change (#64160): model routing and the MoA section are
+# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid
+# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.
+_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (
+ ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),
+ ("moa",))
-def _write_zip_entries(
- zf: zipfile.ZipFile, files_to_add: List[Tuple[Path, Path]], out_path: Path,
- *, on_db_failure, on_error, on_progress, track_bytes: bool) -> int:
- """Add every ``(abs_path, rel_path)`` to *zf*, WAL-safe for ``*.db``; return bytes archived.
- ``on_db_failure(rel_path)`` runs when a SQLite snapshot fails (may raise to abort);
- ``on_error(rel_path, exc)`` records a read failure; ``on_progress(i)`` fires every 500 files;
- ``track_bytes`` stats plain files for the size total.
- """
- total_bytes = 0
- for i, (abs_path, rel_path) in enumerate(files_to_add, 1):
+def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:
+ """``remove(path)`` every entry past the first *keep*; return how many succeeded."""
+ deleted = 0
+ for p in newest_first[keep:]:
try:
- if abs_path.suffix == ".db":
- size = _zip_sqlite_snapshot(zf, abs_path, rel_path, out_path)
- if size is None:
- on_db_failure(rel_path)
- continue
- total_bytes += size
- else:
- zf.write(abs_path, arcname=str(rel_path))
- if track_bytes:
- total_bytes += abs_path.stat().st_size
- except (PermissionError, OSError, ValueError) as exc:
- on_error(rel_path, exc)
- continue
- if i % 500 == 0:
- on_progress(i)
- return total_bytes
+ remove(p)
+ deleted += 1
+ except OSError as exc:
+ logger.warning("Failed to prune %s %s: %s", what, p.name, exc)
+ return deleted
-def _print_capped(header: str, lines: List[str], indent: str) -> None:
- """Print *header*, then at most 10 of *lines* (each prefixed by *indent*) and a "... and N more" tail."""
- print(header)
- for line in lines[:10]:
- print(f"{indent}{line}")
- if len(lines) > 10:
- print(f"{indent}... and {len(lines) - 10} more")
+# --- Shared full-zip backup helper ---
-# --- Backup ---
+# --- Pre-update / pre-migration auto-backups ---
-_RUN_BACKUP_PREFIX = "hermes-backup-"
+_PRE_UPDATE_BACKUPS_DIR = "backups"
+_PRE_UPDATE_PREFIX = "pre-update-"
+_PRE_UPDATE_DEFAULT_KEEP = 5
+_PRE_MIGRATION_PREFIX = "pre-migration-"
+_PRE_MIGRATION_DEFAULT_KEEP = 5
-def _resolve_backup_output_path(output: Optional[str]) -> Path:
- """Turn ``--output`` (file, directory, or None) into a ``.zip`` path whose parent exists;
- an unwritable path exits with a one-line error, not a traceback."""
- out_path = None
- default_name = f"{_RUN_BACKUP_PREFIX}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"
+def _prune_prefixed_zips(backup_dir: Path, prefix: str, keep: int, what: str) -> int:
+ """Remove oldest ``<prefix>*.zip`` in *backup_dir* beyond *keep*; return count deleted.
+
+ Only prefix-matched files are touched, so hand-made zips or other backup kinds survive.
+ """
+ backups = _newest_first(backup_dir, lambda p: p.is_file() and p.name.startswith(prefix)
+ and p.suffix.lower() == ".zip")
+ return _prune_oldest(backups, keep, Path.unlink, what)
+
+
+def _create_prefixed_full_backup(
+ hermes_home: Optional[Path], prefix: str, keep: int, what: str, prune_what: str) -> Optional[Path]:
+ """Write ``<HERMES_HOME>/backups/<prefix><timestamp>.zip`` and prune older same-prefix zips.
+ Returns the path, or ``None`` if nothing to back up or the write failed. Never raises."""
+ hermes_root = hermes_home or get_default_hermes_root()
+ if not hermes_root.is_dir():
+ return None
+ backup_dir = hermes_root / _PRE_UPDATE_BACKUPS_DIR
try:
- if output:
- out_path = Path(output).expanduser().resolve()
- if out_path.is_dir():
- out_path = out_path / default_name
- else:
- out_path = Path.home() / default_name
- if out_path.suffix.lower() != ".zip":
- out_path = out_path.with_suffix(out_path.suffix + ".zip")
- out_path.parent.mkdir(parents=True, exist_ok=True)
+ backup_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
- print(f"Error: cannot write backup to {output or out_path}: {exc}")
- raise SystemExit(1) from exc
+ logger.warning("Could not create %s backup dir %s: %s", what, backup_dir, exc)
+ return None
+ out_path = backup_dir / f"{prefix}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"
+ if _write_full_zip_backup(out_path, hermes_root) is None:
+ return None
+ _prune_prefixed_zips(backup_dir, prefix, keep, prune_what)
return out_path
@@@ -587,34 -624,7 +589,34 @@@ def run_backup(args) -> None
def _run_backup_locked(args, hermes_root: Path) -> None:
"""Write a full backup while the cross-process backup slot is held."""
- out_path = _resolve_backup_output_path(args.output)
+
+ # Determine output path
+ out_path = None
+ try:
+ if args.output:
+ out_path = Path(args.output).expanduser().resolve()
+ # If user gave a directory, put the zip inside it
+ if out_path.is_dir():
+ stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- out_path = out_path / f"hermes-backup-{stamp}.zip"
++ out_path = out_path / f"{_RUN_BACKUP_PREFIX}{stamp}.zip"
+ else:
+ stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- out_path = Path.home() / f"hermes-backup-{stamp}.zip"
++ out_path = Path.home() / f"{_RUN_BACKUP_PREFIX}{stamp}.zip"
+
+ # Ensure the suffix is .zip
+ if out_path.suffix.lower() != ".zip":
+ out_path = out_path.with_suffix(out_path.suffix + ".zip")
+
+ # Ensure parent directory exists
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ # A bad/unwritable output path (permission denied, unreadable parent,
+ # etc.) should give a clean one-line error, not a raw traceback
+ # (round-3 QA SUB-01). is_dir() and mkdir() both hit the filesystem.
+ print(f"Error: cannot write backup to {args.output or out_path}: {exc}")
+ raise SystemExit(1) from exc
+
+ # Collect files
scan_started = time.monotonic()
logger.info("backup phase=scan status=started")
print(f"Scanning {display_hermes_home()} ...")
@@@ -716,204 -661,227 +718,209 @@@
zf.write(abs_path, arcname=arcname)
total_bytes += abs_path.stat().st_size
except (PermissionError, OSError, ValueError) as exc:
- errors.append(f"{arcname}: {exc}")
+ errors.append(f" {arcname}: {exc}")
+ continue
+
elapsed = time.monotonic() - t0
zip_size = out_path.stat().st_size
- logger.info("backup phase=archive status=complete duration_ms=%.1f files=%d errors=%d bytes=%d",
- elapsed * 1000, file_count, len(errors), zip_size)
- print(f"\nBackup {'incomplete' if errors else 'complete'}: {out_path}\n"
- f" Files: {file_count}\n"
- f" Original: {_format_size(total_bytes)}\n"
- f" Compressed: {_format_size(zip_size)}\n"
- f" Time: {elapsed:.1f}s")
+ logger.info(
+ "backup phase=archive status=complete duration_ms=%.1f files=%d errors=%d bytes=%d",
+ elapsed * 1000,
+ file_count,
+ len(errors),
+ zip_size,
+ )
+
+ # Summary
+ print()
+ if errors:
+ print(f"Backup incomplete: {out_path}")
+ else:
+ print(f"Backup complete: {out_path}")
+ print(f" Files: {file_count}")
+ print(f" Original: {_format_size(total_bytes)}")
+ print(f" Compressed: {_format_size(zip_size)}")
+ print(f" Time: {elapsed:.1f}s")
+
if external_to_add:
- print(f"\n Included {len(external_to_add)} memory-provider file(s) stored outside {display_hermes_home()}.")
+ print(
+ f"\n Included {len(external_to_add)} memory-provider file(s) "
+ f"stored outside {display_hermes_home()}."
+ )
+
if skipped_external:
- print(f"\n Skipped {len(skipped_external)} memory-provider path(s) outside your home directory "
- "(not portable):\n" + "\n".join(f" {p}" for p in sorted(skipped_external)[:10]))
+ print(
+ f"\n Skipped {len(skipped_external)} memory-provider path(s) "
+ f"outside your home directory (not portable):"
+ )
+ for p in sorted(skipped_external)[:10]:
+ print(f" {p}")
+
if skipped_dirs:
- print("\n Excluded directories:\n" + "\n".join(f" {d}/" for d in sorted(skipped_dirs)))
+ print("\n Excluded directories:")
+ for d in sorted(skipped_dirs):
+ print(f" {d}/")
+
if errors:
- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")
- else:
+ print(f"\n Warnings ({len(errors)} files skipped):")
+ for e in errors[:10]:
+ print(e)
+ if len(errors) > 10:
+ print(f" ... and {len(errors) - 10} more")
+
+ if not errors:
print(f"\nRestore with: hermes import {out_path.name}")
- keep = getattr(args, "keep", 0) # 0 / absent: never prune (non-CLI callers)
- if keep and out_path.name.startswith(_RUN_BACKUP_PREFIX):
- pruned = _prune_prefixed_zips(out_path.parent, _RUN_BACKUP_PREFIX, keep, "backup")
- if pruned:
- print(f" Pruned {pruned} older {_RUN_BACKUP_PREFIX}*.zip (keeping {keep}).")
++ keep = getattr(args, "keep", 0)
++ if keep and out_path.name.startswith(_RUN_BACKUP_PREFIX):
++ pruned = _prune_prefixed_zips(out_path.parent, _RUN_BACKUP_PREFIX, keep, "backup")
++ if pruned:
++ print(f" Pruned {pruned} older {_RUN_BACKUP_PREFIX}*.zip (keeping {keep}).")
-# --- Import ---
+# ---------------------------------------------------------------------------
+# Import
+# ---------------------------------------------------------------------------
-def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:
- """Check that a zip looks like a Hermes backup."""
- names = zf.namelist()
- if not names:
- return False, "zip archive is empty"
- # Telltale files a hermes home has — at the root or one level deep (zipped directory).
- if not any(Path(n).name in {"config.yaml", ".env", "state.db"} for n in names):
- return False, "zip does not appear to be a Hermes backup (no config.yaml, .env, or state databases found)"
- return True, ""
+def run_import(args) -> None:
+ """Restore a Hermes backup from a zip file."""
+ zip_path = Path(args.zipfile).expanduser().resolve()
+ if not zip_path.is_file():
+ print(f"Error: File not found: {zip_path}")
+ sys.exit(1)
-def _detect_prefix(zf: zipfile.ZipFile) -> str:
- """Detect if the zip has a common directory prefix wrapping all entries."""
- names = [n for n in zf.namelist() if not n.endswith("/")]
- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}
- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:
- return first_parts.pop() + "/"
- return ""
+ if not zipfile.is_zipfile(zip_path):
+ print(f"Error: Not a valid zip file: {zip_path}")
+ sys.exit(1)
+ # The restore target must be the home the command operates under — the
+ # same path printed as "Target:" via display_hermes_home(). Resolving
+ # through get_default_hermes_root() instead maps a profile home
+ # (<root>/profiles/<name>) back to <root>, silently retargeting the
+ # restore at the live root while the profile directory stays empty.
+ hermes_root = get_hermes_home()
-def _default_new_file_mode() -> Optional[int]:
- """The mode ``open(path, "wb")`` gives a file it has to create.
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ # Validate
+ ok, reason = _validate_backup_zip(zf)
+ if not ok:
+ print(f"Error: {reason}")
+ sys.exit(1)
- ``mkstemp`` always creates at 0600, so staging an import through a temp file would tighten
- every *newly created* file to owner-only — the Docker/NAS volume-mount hazard
- ``utils._restore_file_mode`` documents.
- """
- try:
- current = os.umask(0o077)
- os.umask(current)
- except OSError:
- return None
- return 0o666 & ~current
+ prefix = _detect_prefix(zf)
+ members = [n for n in zf.namelist() if not n.endswith("/")]
+ file_count = len(members)
+ print(f"Backup contains {file_count} files")
+ print(f"Target: {display_hermes_home()}")
-def _extract_member_atomically(
- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:
- """Restore one zip member onto *target* with no truncation window.
+ if prefix:
+ print(f"Detected archive prefix: {prefix!r} (will be stripped)")
- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.
- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a
- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink
- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.
- """
- # Mode is None when the target does not exist: the umask-derived create-mode applies.
- mode = _preserve_file_mode(target)
- owner = _preserve_file_owner(target)
- if mode is None:
- mode = new_file_mode
- else:
- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the
- # archive, so carrying elevated bits would hand the zip's author the identity an existing
- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.
- mode &= ~(stat.S_ISUID | stat.S_ISGID)
- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.
- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")
- try:
- with os.fdopen(fd, "wb") as dst:
- if mode is not None:
- # Apply the mode BEFORE the replace so the target never transits through mkstemp's
- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.
- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod
- os.fchmod(dst.fileno(), mode)
- else:
- os.chmod(tmp_name, mode)
- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.
- with zf.open(member) as src:
- shutil.copyfileobj(src, dst)
- dst.flush()
- os.fsync(dst.fileno())
- real_path = Path(atomic_replace(tmp_name, target))
- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and
- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.
- _restore_file_owner(real_path, owner)
- _restore_file_mode(real_path, mode)
- except BaseException:
- with suppress(OSError):
- os.unlink(tmp_name)
- raise
-
-
-def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:
- """``(sessions, messages)`` in session database *path*; read-only, best effort.
-
- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":
- acting on an unreadable database would mask the very loss this count exists to surface.
- Same contract as :func:`_count_cron_jobs`.
- """
- if not path.is_file():
- return None
- try:
- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
- except sqlite3.Error:
- return None
- try:
- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]
- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
- return int(sessions), int(messages)
- except (sqlite3.Error, TypeError, ValueError):
- return None
- finally:
- conn.close()
+ # Check for existing installation
+ has_config = (hermes_root / "config.yaml").exists()
+ has_env = (hermes_root / ".env").exists()
+ if (has_config or has_env) and not args.force:
+ print()
+ print("Warning: Target directory already has Hermes configuration.")
+ print("Importing will overwrite existing files with backup contents.")
+ print()
+ try:
+ answer = input("Continue? [y/N] ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ print("\nAborted.")
+ sys.exit(1)
+ if answer not in {"y", "yes"}:
+ print("Aborted.")
+ return
+
+ # Extract
+ print(f"\nImporting {file_count} files ...")
+ hermes_root.mkdir(parents=True, exist_ok=True)
-def _import_db_member(
- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:
- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.
+ errors = []
+ restored = 0
+ restored_external = 0
+ skipped_runtime: list[str] = []
+ # (rel, live_counts, imported_counts) for every session database the
+ # import replaced with one holding fewer rows. A restore is allowed to
+ # do that — it just must not do it silently (issue #100960).
+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
+ home_dir = Path.home().resolve()
+ # Resolved once: every member is published via a temp file, and mkstemp
+ # would otherwise create newly restored files as 0600.
+ new_file_mode = _default_new_file_mode()
+ t0 = time.monotonic()
- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,
- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no
- other process will see, and a sidecar WAL beside the new file describes the old database —
- nothing fails, the sessions are simply gone (#100960). Route the member through the same
- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and
- every open connection converges. A target that does not exist yet has no holders, so it takes
- the ordinary atomic publish. Raises ``OSError`` when the database could not be replaced
- safely, so the caller reports a skipped file instead of a silent success.
- """
- if not target.exists():
- _extract_member_atomically(zf, member, target, new_file_mode)
- return
- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.
- mode = _preserve_file_mode(target)
- owner = _preserve_file_owner(target)
- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")
- try:
- with os.fdopen(fd, "wb") as dst:
- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory
- shutil.copyfileobj(src, dst)
- dst.flush()
- os.fsync(dst.fileno())
- if not _safe_restore_db(Path(tmp_name), target):
- raise OSError(
- "live-safe restore refused or failed; the existing database was "
- "left untouched. Stop the gateway/dashboard processes holding it "
- "open and re-run the import."
- )
- _restore_file_owner(target, owner)
- _restore_file_mode(target, mode)
- finally:
- with suppress(OSError):
- os.unlink(tmp_name)
+ for member in members:
+ # External memory-provider state captured under the reserved
+ # ``_external/`` arc prefix restores to its original home-relative
+ # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.
+ if member.startswith(_EXTERNAL_PREFIX):
+ ext_rel = member[len(_EXTERNAL_PREFIX):]
+ if not ext_rel:
+ continue
+ target = home_dir / ext_rel
+ # Security: the resolved target must stay under the home dir.
+ try:
+ target.resolve().relative_to(home_dir)
+ except ValueError:
+ errors.append(f" {member}: path traversal blocked")
+ continue
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _extract_member_atomically(zf, member, target, new_file_mode)
+ # External provider configs commonly hold credentials.
+ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:
+ try:
+ os.chmod(target, 0o600)
+ except OSError:
+ pass
+ restored += 1
+ restored_external += 1
+ except (PermissionError, OSError) as exc:
+ errors.append(f" {member}: {exc}")
+ if restored % 500 == 0:
+ print(f" {restored}/{file_count} files ...")
+ continue
+ # Strip prefix if detected
+ if prefix and member.startswith(prefix):
+ rel = member[len(prefix):]
+ else:
+ rel = member
-def _confirm_import_overwrite(hermes_root: Path) -> bool:
- """Prompt before importing over an existing installation; True when import may proceed."""
- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):
- return True
- print("\nWarning: Target directory already has Hermes configuration.\n"
- "Importing will overwrite existing files with backup contents.\n")
- try:
- answer = input("Continue? [y/N] ").strip().lower()
- except (EOFError, KeyboardInterrupt):
- print("\nAborted.")
- sys.exit(1)
- if answer in {"y", "yes"}:
- return True
- print("Aborted.")
- return False
+ if not rel:
+ continue
+ try:
+ parts = tuple(normalize_archive_parts(rel))
+ except ValueError:
+ errors.append(f" {rel}: path traversal blocked")
+ continue
-def _import_members(
- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int
-) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:
- """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.
+ # Never overwrite volatile gateway/process runtime state. These are
+ # namespaced to the machine/container the backup was taken on;
+ # clobbering them (especially gateway_state.json) breaks the gateway
+ # reconciler on the target and disconnects hosted instances from the
+ # Nous portal. Matched by basename so both the root profile and
+ # named profiles (profiles/<name>/gateway_state.json) are covered.
+ if parts[-1] in _IMPORT_SKIP_NAMES:
+ skipped_runtime.append(rel)
+ continue
- ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the
- import replaced with one holding fewer rows — allowed, but never silent (#100960).
- """
- errors: list[str] = []
- skipped_runtime: list[str] = []
- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
- restored = restored_external = 0
- home_dir = Path.home().resolve()
- new_file_mode = _default_new_file_mode() # once: every member is published via mkstemp (0600)
- for member in members:
- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),
- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.
- external = member.startswith(_EXTERNAL_PREFIX)
- if external:
- rel = member[len(_EXTERNAL_PREFIX):]
- target = home_dir / rel
- root = home_dir
- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES
- else:
- rel = member[len(prefix):] if prefix and member.startswith(prefix) else member
- if rel and Path(rel).name in _IMPORT_SKIP_NAMES: # see ``_IMPORT_SKIP_NAMES``
+ # Older archives may contain PM selections pointing at another machine.
+ # Match their home-root paths; a plugin's own facts.json is user data.
+ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:
skipped_runtime.append(rel)
continue
- # A ``.db`` member is page-restored into the live file; an archived WAL/SHM/journal
- # describes a different database image and installed beside it (over a live sidecar)
- # would replay a foreign WAL on next open. Current backups never ship these
+
+ # A ``.db`` member is page-restored into the live file below; a
+ # WAL/SHM/journal member from the archive describes a different
+ # database image, and installing it beside the restored file (over
+ # a live sidecar, via os.replace) would replay a foreign WAL on
+ # the next open. Current backups never ship these
# (_EXCLUDED_SUFFIXES); older or hand-built archives might.
if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):
skipped_runtime.append(rel)
diff --cc hermes_cli/models.py
index 3eb4ff12a11,2ac20e73489..e39d2494cf0
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@@ -2098,6 -2162,26 +2154,26 @@@ def github_model_reasoning_efforts
return _github_reasoning_efforts_for_model_id(str(model_id or normalized))
-# Negative cache: monotonic timestamp of the last fully-failed probe, keyed
++# Negative cache: monotonic timestamp of the last timed-out probe, keyed
+ # by ``host:port`` so both URL candidates (``/v1`` + root) share one entry.
+ # Without this, an unreachable endpoint (TCP blackhole — SYN draws no reply,
+ # so every attempt burns its full connect timeout) makes every picker open /
+ # chat turn re-pay the timeout per candidate, and the sequential stalls stack
+ # past 10s while the Desktop sits on a spinner with no error (#81123). Short
+ # TTL collapses the burst but still picks up recovery without a restart.
+ # Mirrors _deepinfra_catalog_neg_cache.
+ _probe_neg_cache: dict[str, float] = {}
+ _PROBE_NEG_TTL = 60.0 # seconds
+
+
+ def _probe_neg_key(base_url: str) -> Optional[str]:
+ """``host:port`` for *base_url* (both URL candidates share one entry), or None without a host."""
+ from utils import base_url_origin
+
+ _, host, port = base_url_origin(base_url)
+ return f"{host}:{port}" if host else None
+
+
def _probe_result(
models, probed_url, resolved_base_url, suggested_base_url=None, used_fallback=False
) -> dict[str, Any]:
@@@ -2151,16 -2242,27 +2234,25 @@@ def probe_api_models
_ssl_context = _custom_provider_ssl_context(normalized)
if _ssl_context is not None:
_open_kwargs["ssl_context"] = _ssl_context
- reachable = False
++ all_timed_out = True
for candidate_base, is_fallback in candidates:
url = candidate_base.rstrip("/") + "/models"
tried.append(url)
try:
data = _get_json(url, timeout=timeout, headers=headers, **_open_kwargs)
- except urllib.error.HTTPError:
- # The host answered: an auth/404 failure is not unreachability, and a user fixing
- # their key must not be served a cached "no models" for the next TTL window.
- reachable = True
- continue
-- except Exception:
++ except Exception as exc:
++ # TLS, authentication and parsing failures must not hide corrected settings.
++ cause = exc.reason if isinstance(exc, urllib.error.URLError) else exc
++ all_timed_out = all_timed_out and isinstance(cause, TimeoutError)
continue
+ if _neg_key is not None:
+ _probe_neg_cache.pop(_neg_key, None)
return _probe_result(
[m.get("id", "") for m in data.get("data", [])], url, candidate_base.rstrip("/"),
alternate_base if alternate_base != candidate_base else normalized, is_fallback)
+
- if _neg_key is not None and not reachable:
++ if _neg_key is not None and all_timed_out:
+ _probe_neg_cache[_neg_key] = time.monotonic()
return _probe_result(
None, tried[0] if tried else normalized.rstrip("/") + "/models", normalized,
alternate_base if alternate_base != normalized else None)
diff --cc hermes_cli/plugins_cmd.py
index 98db1b68e8f,532b55cb423..628c71c0927
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@@ -159,10 -158,10 +159,6 @@@ def _scan_plugin_tree(plugin_dir: Path
return result
--# Highest ``manifest_version`` this installer understands; breaking schema changes bump it.
--_SUPPORTED_MANIFEST_VERSION = 1
--
--
def _plugins_dir() -> Path:
"""Return the user plugins directory, creating it if needed."""
plugins = get_hermes_home() / "plugins"
@@@ -589,6 -522,6 +585,11 @@@ def _scrub_cloned_origin(repo: Path, gi
def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
"""Reject manifests declaring a newer ``manifest_version`` than this installer supports."""
++ from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION, requires_hermes_error
++
++ reason = requires_hermes_error(manifest)
++ if reason:
++ raise PluginOperationError(f"Plugin '{plugin_name}' {reason}")
mv = manifest.get("manifest_version")
if mv is None:
return
@@@ -598,11 -531,11 +599,11 @@@
raise PluginOperationError(
f"Plugin '{plugin_name}' has invalid manifest_version '{mv}' (expected an integer).",
) from None
-- if mv_int > _SUPPORTED_MANIFEST_VERSION:
++ if mv_int > SUPPORTED_MANIFEST_VERSION:
from hermes_cli.config import recommended_update_command
raise PluginOperationError(
f"Plugin '{plugin_name}' requires manifest_version {mv}, "
-- f"but this installer only supports up to {_SUPPORTED_MANIFEST_VERSION}. "
++ f"but this installer only supports up to {SUPPORTED_MANIFEST_VERSION}. "
f"Run {recommended_update_command()} to update Hermes.",
) from None
@@@ -629,10 -562,10 +630,18 @@@ def _clone_plugin_repo(tmp_clone: Path
def _read_manifest_for_install(plugin_dir: Path) -> dict:
-- """Manifest of a freshly cloned tree. Unlike :func:`_read_manifest`, a broken portable
-- ``plugin.json`` is an install error (not a silent ``{}``) and its diagnostics are logged."""
-- if _native_manifest_file(plugin_dir) is not None or not _has_portable_manifest(plugin_dir):
-- return _read_manifest(plugin_dir)
++ """A candidate's unreadable or malformed manifest must stop publication."""
++ native = _native_manifest_file(plugin_dir)
++ if native is not None:
++ try:
++ manifest = _load_yaml_manifest(native)
++ except Exception as exc:
++ raise PluginOperationError(f"Could not read plugin manifest {native}: {exc}") from exc
++ if not isinstance(manifest, dict):
++ raise PluginOperationError(f"Plugin manifest must be a mapping: {native}")
++ return manifest
++ if not _has_portable_manifest(plugin_dir):
++ return {}
try:
from hermes_cli.agent_plugins import read_agent_plugin_manifest
manifest, diagnostics = read_agent_plugin_manifest(plugin_dir)
@@@ -643,33 -576,33 +652,13 @@@
return manifest
--def _swap_in_plugin(tmp_target: Path, target: Path, backup: Path, old_metadata: dict, new_metadata: dict) -> None:
-- """Move the validated clone into place and persist metadata; on any failure restore the
-- previous tree (if one was replaced) and the previous metadata sidecar, then re-raise."""
-- replaced_existing = target.exists()
-- if replaced_existing:
-- os.replace(target, backup)
-- try:
-- os.replace(tmp_target, target)
-- _write_install_metadata(new_metadata)
-- except Exception:
-- if target.exists():
- _rmtree_force(target)
- shutil.rmtree(target)
-- if replaced_existing and backup.exists():
-- os.replace(backup, target)
-- if old_metadata:
-- _write_install_metadata(old_metadata)
-- else:
-- _install_metadata_path().unlink(missing_ok=True)
-- raise
--
--
def _install_plugin_core(
identifier: str,
*,
force: bool,
ref: Optional[str] = None,
scan_decision_cb=None,
++ catalog_entry=None,
) -> tuple[Path, dict, str]:
"""Clone a Git plugin and atomically record its source and exact revision."""
requested_revision = _normalize_exact_revision(ref) if ref is not None else None
@@@ -718,18 -651,7 +707,26 @@@
**old_metadata,
plugin_name: {"pinned": requested_revision is not None, "revision": installed_revision, "source": source},
}
- _swap_in_plugin(tmp_target, target, Path(tmp) / "previous-plugin", old_metadata, new_metadata)
+ # 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.
+ try:
+ manifest = _read_manifest(Path(tmp_target))
+ update_url = (manifest or {}).get("update_url")
+ if isinstance(update_url, str) and update_url.strip():
+ new_metadata[plugin_name]["update_url"] = update_url.strip()
+ except Exception:
+ pass
- _swap_in_plugin(tmp_target, target, Path(tmp) / "previous-plugin", old_metadata, new_metadata)
++ if catalog_entry is not None:
++ new_metadata[plugin_name]["catalog_name"] = catalog_entry.name
++ new_metadata[plugin_name]["catalog_tier"] = catalog_entry.tier
++ from hermes_cli.plugins_transaction import publish_plugin
++
++ try:
++ publish_plugin(tmp_target, target, old_metadata, new_metadata)
++ except Exception as exc:
++ raise PluginOperationError(f"Plugin '{plugin_name}' was not published: {exc}") from exc
if not _looks_like_plugin_dir(target):
logger.warning("%s has no plugin.yaml / __init__.py; may not be a valid plugin", plugin_name)
@@@ -782,17 -665,29 +740,29 @@@ def cmd_install
force: bool = False,
enable: Optional[bool] = None,
ref: Optional[str] = None,
+ allow_removed: bool = False,
) -> None:
- """Install a plugin from a Git URL, owner/repo shorthand, or index name.
+ """Install a plugin from the curated catalog (bare name), a Git URL, or owner/repo shorthand.
- Bare names resolve through the community index (an explicit ``--ref`` beats the index pin).
- A catalog hit installs the reviewed pinned SHA (an explicit ``--ref`` wins) and records provenance in
- a ``.hermes-catalog.json`` sidecar; URLs/shorthand are flagged as custom (unreviewed) sources. Every
++ A catalog hit installs the reviewed pinned SHA and records catalog membership in the shared install
++ metadata. An explicit different ``--ref`` is a custom pin. URLs/shorthand are custom sources. Every
+ install is checked against the catalog kill list unless *allow_removed*.
*enable* None prompts "Enable now? [y/N]"; True/False skip the prompt.
"""
+ from hermes_cli import plugins_cmd_catalog as catalog
console = _console()
- if _looks_like_bare_index_name(identifier):
- identifier, index_ref = _resolve_index_name(identifier, console)
- if ref is None:
- ref = index_ref
+ entry = None
+ if catalog.looks_like_catalog_name(identifier):
+ entry = catalog.resolve_catalog_name(identifier, console)
+ identifier = entry.install_identifier
+ console.print(f"[bold]{entry.name}[/bold] [cyan]\\[{entry.tier}][/cyan] [dim]pinned @ {entry.sha[:8]}[/dim]")
+ console.print(catalog.entry_capability_summary(entry))
+ else:
+ console.print("[yellow]Warning:[/yellow] custom (unreviewed) source — not from the Hermes catalog.")
+ if allow_removed:
+ console.print(
+ "[bold red]WARNING:[/bold red] [red]--allow-removed set — skipping the catalog kill-list check. "
+ "This plugin may have been removed for security reasons.[/red]")
try:
git_url, _subdir = _resolve_git_url(identifier)
@@@ -900,23 -758,28 +876,21 @@@ def _pull_plugin_update(target: Path, p
raise PluginOperationError(not_git_msg())
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
-
-
-def cmd_update(name: str) -> None:
++ from hermes_cli.plugins_transaction import update_plugin
++
++ return update_plugin(target)
+
+
+def cmd_update(name: str, *, interactive: bool = True) -> None:
"""Update an installed plugin by pulling latest from its git remote."""
from rich.markup import escape
+ from hermes_cli import plugins_cmd_catalog as catalog
console = _console()
target = _require_installed_plugin(name, _plugins_dir(), console)
- sidecar = catalog.read_catalog_sidecar(target)
++ sidecar = catalog.catalog_install_record(target)
+ if sidecar: # catalog installs re-pin to the reviewed SHA — never `git pull`
+ catalog.cmd_update_catalog(name, target, sidecar, console)
+ return
try:
output = _pull_plugin_update(
target,
@@@ -928,36 -791,12 +902,13 @@@
before_pull=lambda: console.print(f"[dim]Updating {name}...[/dim]"))
except PluginOperationError as exc:
_fail(console, f"[red]Error:[/red] {exc}")
-- _rescan_after_update(target, name, console)
_post_pull_housekeeping(target, console)
- # Member-manifest plugins: the pull may have changed its pyproject
- # pins — re-sync the union so new deps land (Task 5, plugin
- # auto-update plan). The venv stamp now includes member pyproject
- # CONTENT (Task 4), so a pins change forces the re-lock; a
- # content-identical pull is a no-op stamp match. Failures surface
- # the resolver's message (conflict = loud refusal, bisect +
- # write-back ride the shipped sync path) but never fail the update
- # itself — the plugin code is already updated.
- if (target / "pyproject.toml").is_file():
- try:
- import pm
- pm.sync_venv(explicit=True)
- except Exception as exc:
- console.print(
- f"[yellow]⚠[/yellow] Dependency re-sync failed for "
- f"{name}: {exc}"
- )
- console.print(
- "[dim]The plugin code updated; run `hermes pm install` "
- "to retry the dependency sync.[/dim]"
- )
-
- # Re-consent when the new version declares capabilities the granted set lacks or the
- # declared set changed; additions stay ungranted until the user says yes (fail closed).
- # See #64228.
+ # Update-time re-consent (#64228): if the new version declares
+ # capabilities the granted set lacks, surface the diff and require
+ # re-consent for the additions. The stored consent hash detects a
+ # changed declaration; additions stay ungranted until the user says yes
+ # (non-interactive updates leave them ungranted — fail closed).
updated_manifest = _read_manifest(target)
plugin_id = updated_manifest.get("name") or target.name
declared_caps = _declared_capabilities_from_manifest(updated_manifest, plugin_id)
@@@ -977,27 -813,27 +928,6 @@@
console.print(f"[dim]{out}[/dim]")
--def _rescan_after_update(target: Path, name: str, console) -> None:
-- """Re-scan after ``git pull``: the tree is already mutated, so a dangerous verdict disables
-- the plugin rather than leaving it active."""
-- if not _scan_on_install_enabled():
-- return
-- from tools.plugin_guard import format_scan_report, scan_plugin, should_allow_plugin_install
-- scan_result = scan_plugin(target, source=name)
-- allowed, reason = should_allow_plugin_install(scan_result)
-- if allowed is True:
-- return
-- console.print()
-- console.print(f"[yellow]⚠ Security scan flagged the updated plugin:[/yellow] {reason}")
-- console.print(format_scan_report(scan_result))
-- if scan_result.verdict == "dangerous":
-- if name in _get_enabled_set() or name not in _get_disabled_set():
-- _set_plugin_enabled(name, enable=False)
-- console.print(
-- f"[red]Plugin '{name}' has been disabled.[/red] Review the "
-- f"findings, then re-enable with `hermes plugins enable {name}` "
-- f"if you trust them.")
--
def _post_pull_housekeeping(target: Path, console) -> None:
"""After ``git pull``: drop stale ``__pycache__`` and copy any new ``.example`` files."""
@@@ -1660,25 -1330,17 +1593,31 @@@ def cmd_list(args: Any | None = None) -
table = _table(
(("Name", "bold"), ("Status", None), ("Version", "dim"), ("Description", None), ("Source", "dim")),
title="Plugins", show_lines=False)
+ # provenance class per user-installed dir (bundled entries show '-')
+ from hermes_cli.plugins_provenance import plugins_provenance
+
+ prov_classes = {
+ p.name: p.klass.value for p in plugins_provenance(_plugins_dir())
+ }
+
- for name, status_name, version, description, source in rows:
+ removed_lines = []
+ for name, status_name, version, description, source, removed in rows:
++ klass = prov_classes.get(name)
status = _STATUS_MARKUP.get(status_name, "[yellow]not enabled[/yellow]")
+ if removed:
+ name = f"[red]{name} ✗[/red]"
+ removed_lines.append(f"[red]✗ {name}[/red] was removed from the plugin catalog: {removed}")
table.add_row(name, status, version, description, source)
+ # class line rides the Source column for user plugins
+ if source in {"user", "git"}:
- klass = prov_classes.get(name)
+ if klass and klass != "git":
+ table.add_row(
+ "", "", "", f"[dim]provenance: {klass}[/dim]", ""
+ )
console.print()
console.print(table)
+ for line in removed_lines:
+ console.print(line)
console.print()
console.print("[dim]Compact view:[/dim] hermes plugins list --plain --no-bundled")
console.print("[dim]Interactive toggle:[/dim] hermes plugins")
@@@ -2028,27 -1677,36 +1967,47 @@@ def _run_composite_fallback(plugin_keys
print()
+def _save_plugin_selection_fallback(plugin_keys, chosen, disabled) -> None:
+ """The text fallback's save: same admission authority, refusal printed."""
+ from hermes_cli.plugins_admission import AdmissionRefused
+
+ try:
+ _persist_plugin_selection(plugin_keys, chosen, disabled)
+ except AdmissionRefused as exc:
+ print(f" Plugin selection refused, not saved: {exc}")
+ print(" config.yaml and the active environment are unchanged.")
+
+
- def dashboard_install_plugin(identifier: str, *, force: bool, enable: bool) -> dict[str, Any]:
- """Non-interactive install for the web dashboard. Returns a JSON-serializable dict."""
+ def dashboard_install_plugin(
+ identifier: str, *, force: bool, enable: bool, catalog_name: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Non-interactive install for the dashboard/TUI. *catalog_name* installs a curated entry at its
+ pinned SHA (identifier may be empty); every path enforces the kill list (no GUI bypass)."""
+ from hermes_cli import plugins_cmd_catalog as catalog
warnings: list[str] = []
+ entry = None
+ if catalog_name:
+ entry = catalog.get_live_catalog_entry(catalog_name)
+ if entry is None:
+ return {"ok": False, "error": f"'{catalog_name}' is not in the Hermes plugin catalog."}
+ identifier = entry.install_identifier
+ else:
+ warnings.append("Custom (unreviewed) source — not from the Hermes catalog.")
try:
- if _resolve_git_url(identifier)[0].startswith(("http://", "file://")):
+ git_url = _resolve_git_url(identifier)[0]
+ if git_url.startswith(("http://", "file://")):
warnings.append("Insecure URL scheme; prefer https:// or git@ for production installs.")
+ catalog.raise_if_removed(identifier, git_url, *((entry.name,) if entry else ()))
except ValueError:
pass
+ except PluginOperationError as exc:
+ return {"ok": False, "error": str(exc)}
try:
- target, installed_manifest, installed_name = _install_plugin_core(identifier, force=force)
+ if entry is not None:
+ target, installed_manifest, installed_name = catalog.install_catalog_entry(
+ entry, force=force, allow_removed=True)
+ else:
+ target, installed_manifest, installed_name = _install_plugin_core(identifier, force=force)
except PluginScanBlocked as exc:
fields = ("pattern_id", "severity", "category", "file", "line", "description")
return {
@@@ -2170,7 -1816,11 +2130,11 @@@ 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:
+ sha, changed = catalog.repin_catalog_plugin(target, sidecar)
+ return {"ok": True, "name": name, "sha": sha, "unchanged": not changed}
msg = _pull_plugin_update(
target,
lambda rec: (
@@@ -2407,17 -2029,13 +2343,17 @@@ _PLUGIN_ACTIONS =
args.identifier,
force=getattr(args, "force", False),
enable=_tri_state_flag(args, "enable", "no_enable"),
- ref=getattr(args, "ref", None)),
- "search": lambda args: cmd_search(
- getattr(args, "term", "") or "",
- json_output=getattr(args, "json", False),
- capability=getattr(args, "capability", None),
- refresh=getattr(args, "refresh", False)),
+ ref=getattr(args, "ref", None),
+ allow_removed=getattr(args, "allow_removed", False)),
+ "search": lambda args: _catalog().cmd_search(
+ getattr(args, "term", "") or "", json_output=getattr(args, "json", False)),
+ "browse": lambda args: _catalog().cmd_search(""),
+ "validate": lambda args: _catalog().cmd_validate(args.path, as_json=getattr(args, "json", False)),
"update": lambda args: cmd_update(args.name),
+ "adopt": lambda args: cmd_adopt(args.name),
+ "trust-update-url": lambda args: cmd_trust_update_url(args.name),
+ "check-updates": lambda args: cmd_check_updates(args),
+ "check": lambda args: cmd_check_updates(args),
"remove": lambda args: cmd_remove(args.name),
"rm": lambda args: cmd_remove(args.name),
"uninstall": lambda args: cmd_remove(args.name),
diff --cc hermes_cli/plugins_cmd_catalog.py
index 00000000000,346f93441a3..836622e05db
mode 000000,100644..100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@@ -1,0 -1,299 +1,285 @@@
+ """``hermes plugins`` catalog surface: resolution, provenance sidecar, search/browse/info/validate,
+ catalog-aware update, plus the dashboard/TUI-facing catalog payload helpers.
+
+ Sibling of :mod:`hermes_cli.plugins_cmd` (the installer core, enable/disable state and console helpers
+ live there and are imported late — this module is imported BY ``plugins_cmd``).
+ """
+
+ from __future__ import annotations
+
+ import datetime
+ import json
+ import logging
+ import sys
+ from pathlib import Path
+ from typing import Any, Dict, List, Optional
+
+ from hermes_cli.plugin_catalog import (
+ PluginCatalogEntry, entry_capability_summary, filter_entries, find_removed, get_live_catalog_entry,
+ load_catalog_live, load_removed_list, _NAME_RE,
+ )
+
+ logger = logging.getLogger(__name__)
+
-CATALOG_SIDECAR = ".hermes-catalog.json"
-
-
+ # ── Resolution / provenance ──────────────────────────────────────────────────
+
+ def looks_like_catalog_name(identifier: str) -> bool:
+ """Bare ``[a-z0-9_-]`` token — not a URL, ``owner/repo`` or path."""
+ from hermes_cli.plugins_cmd import _URL_SCHEMES
+ return bool(identifier) and "/" not in identifier and "\\" not in identifier \
+ and not identifier.startswith(_URL_SCHEMES) and bool(_NAME_RE.match(identifier))
+
+
+ def raise_if_removed(*candidates: str) -> None:
+ """``PluginOperationError`` when any candidate (name or repo URL) is on the kill list."""
+ from hermes_cli.plugins_cmd import PluginOperationError
+ for candidate in candidates:
+ removed = find_removed(candidate)
+ if removed is not None:
+ detail = removed.reason or "no reason recorded"
+ if removed.date:
+ detail += f" (removed {removed.date})"
+ raise PluginOperationError(
+ f"Plugin '{removed.name}' was removed from the Hermes plugin catalog and is blocked from "
+ f"installation: {detail}")
+
+
+ def resolve_catalog_name(identifier: str, console) -> PluginCatalogEntry:
+ """Bare name → live catalog entry, or exit 1 with a pointer to ``search``."""
+ from hermes_cli.plugins_cmd import _fail
+ entry = get_live_catalog_entry(identifier)
+ if entry is None:
+ _fail(console, (
+ f"[red]Error:[/red] '{identifier}' is not in the Hermes plugin catalog and is not a Git URL or "
+ "owner/repo shorthand. Browse entries with `hermes plugins search`."))
+ raise SystemExit(1) # _fail exits; keeps type-checkers honest
+ return entry
+
+
-def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry) -> None:
- """``.hermes-catalog.json`` inside the install dir — how ``update``/``list``/dashboards know the plugin
- came from the catalog and at which pin."""
- sidecar = {
- "catalog_name": entry.name, "repo": entry.repo, "sha": entry.sha, "tier": entry.tier,
- "installed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
- .replace("+00:00", "Z"),
- }
- try:
- (target / CATALOG_SIDECAR).write_text(json.dumps(sidecar, indent=2) + "\n", encoding="utf-8")
- except OSError as exc:
- logger.warning("Failed to write catalog sidecar in %s: %s", target, exc)
-
++def catalog_install_record(plugin_dir) -> Optional[dict]:
++ """Project catalog fields from the one authoritative install record."""
++ from hermes_cli.plugins_provenance import read_sidecar_rows
+
-def read_catalog_sidecar(plugin_dir) -> Optional[dict]:
- """Parsed sidecar, or ``None`` (absent/corrupt = a non-catalog install)."""
- path = Path(plugin_dir) / CATALOG_SIDECAR if plugin_dir else None
- if path is None or not path.is_file():
++ if plugin_dir is None:
+ return None
- try:
- data = json.loads(path.read_text(encoding="utf-8"))
- except Exception:
++ path = Path(plugin_dir)
++ row = read_sidecar_rows(path.parent).get(path.name, {})
++ if not row.get("catalog_name"):
+ return None
- return data if isinstance(data, dict) and data.get("catalog_name") else None
++ return {"catalog_name": row["catalog_name"], "sha": row["revision"],
++ "repo": str(row["source"]).split("#", 1)[0], "tier": row.get("catalog_tier", "community")}
+
+
+ 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 None
+ return f"catalog:{sidecar.get('tier') or 'community'}@{str(sidecar.get('sha') or '')[:8]}"
+
+
+ def removed_annotation(name: str, dir_path) -> Optional[str]:
+ """Kill-list reason when an INSTALLED plugin matches by name, catalog name or repo, else ``None``."""
- sidecar = read_catalog_sidecar(dir_path) or {}
++ sidecar = catalog_install_record(dir_path) or {}
+ for candidate in (name, sidecar.get("catalog_name"), sidecar.get("repo")):
+ removed = find_removed(str(candidate)) if candidate else None
+ if removed is not None:
+ return removed.reason or "no reason recorded"
+ return None
+
+
+ # ── Catalog-aware install / update ───────────────────────────────────────────
+
+ def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optional[str] = None,
+ allow_removed: bool = False, scan_decision_cb=None) -> tuple:
- """``_install_plugin_core`` at the catalog pin (an explicit *ref* wins) + provenance sidecar.
++ """Install the catalog pin with provenance in the shared install record.
+ Returns the core's ``(target, manifest, installed_name)``."""
+ from hermes_cli.plugins_cmd import _install_plugin_core
+ if not allow_removed:
+ raise_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)
- write_catalog_sidecar(target, entry)
++ entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,
++ catalog_entry=entry if ref is None or ref == entry.sha else None)
+ return target, manifest, installed_name
+
+
+ def repin_catalog_plugin(target: Path, sidecar: dict) -> tuple[str, bool]:
+ """Re-pin a catalog install to the current catalog SHA (never ``git pull``). Returns
+ ``(new_sha, changed)``; raises ``PluginOperationError`` when the entry left the catalog."""
- from hermes_cli.plugins_cmd import PluginOperationError, _get_enabled_set, _save_enabled_set
++ from hermes_cli.plugins_cmd import PluginOperationError
+ 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.")
++ raise_if_removed(catalog_name, entry.repo)
+ if str(sidecar.get("sha") or "").strip().lower() == entry.sha:
+ return entry.sha, False
- was_enabled = _get_enabled_set() # the force reinstall must not flip activation state
- install_catalog_entry(entry, force=True)
- _save_enabled_set(was_enabled)
++ from hermes_cli.plugins_transaction import update_plugin
++
++ update_plugin(target, catalog_entry=entry)
+ return entry.sha, True
+
+
+ def cmd_update_catalog(name: str, target: Path, sidecar: dict, console) -> None:
+ from hermes_cli.plugins_cmd import PluginOperationError, _fail
+ console.print(f"[dim]Checking catalog pin for {name}...[/dim]")
+ try:
+ sha, changed = repin_catalog_plugin(target, sidecar)
+ except PluginOperationError as exc:
+ _fail(console, f"[red]Error:[/red] {exc}")
+ raise SystemExit(1)
+ verb = "updated to" if changed else "is already at catalog pin"
+ console.print(f"[green]✓[/green] Plugin [bold]{name}[/bold] {verb} {sha[:8]}.")
+
+
+ # ── search / browse / info / validate ────────────────────────────────────────
+
+ def _capability_counts(entry: PluginCatalogEntry) -> str:
+ caps = entry.capabilities
+ parts = [f"{len(items)} {label}{'s' if len(items) != 1 and label != 'middleware' else ''}"
+ for items, label in ((caps.provides_tools, "tool"), (caps.provides_hooks, "hook"),
+ (caps.provides_middleware, "middleware")) if items]
+ if caps.requires_env:
+ parts.append(f"{len(caps.requires_env)} env")
+ return ", ".join(parts) or "—"
+
+
+ def _render_entries(entries: List[PluginCatalogEntry], console) -> None:
+ from hermes_cli.plugins_cmd import _table
+ table = _table(((("Name", "bold")), ("Tier", None), ("Description", None), ("Pinned", "dim"),
+ ("Capabilities", "dim")), title="Hermes Plugin Catalog (curated)")
+ for e in entries:
+ tier = "[cyan]official[/cyan]" if e.tier == "official" else "[magenta]community[/magenta]"
+ desc = e.description if len(e.description) <= 60 else e.description[:57] + "..."
+ table.add_row(e.name, tier, desc, e.sha[:8], _capability_counts(e))
+ console.print()
+ console.print(table)
+ console.print()
+ console.print("[dim]Details:[/dim] hermes plugins info <name> [dim]Install:[/dim] hermes plugins install <name>")
+
+
+ def cmd_search(term: str = "", *, json_output: bool = False) -> None:
+ """Search the curated catalog (name/description/declared tools); empty term = browse everything."""
+ from hermes_cli.plugins_cmd import _console
+ matches = filter_entries(load_catalog_live(), term)
+ if json_output:
+ print(json.dumps({"query": term, "results": [e.to_dict() for e in matches]}, indent=2))
+ return
+ console = _console()
+ if not matches:
+ console.print(f"[yellow]No catalog entries matched '{term}'[/yellow]" if term
+ else "[dim]No catalog entries available.[/dim]")
+ return
+ _render_entries(matches, console)
+
+
+ def cmd_info(name: str) -> None:
+ """Full catalog entry for *name*; falls back to installed-plugin details for non-catalog names."""
+ from hermes_cli.plugins_cmd import _console, cmd_show
+ entry = get_live_catalog_entry(name)
+ if entry is None:
+ cmd_show(name)
+ return
+ console = _console()
+ caps = entry.capabilities
+ console.print()
+ console.print(f"[bold]{entry.name}[/bold] [cyan]\\[{entry.tier}][/cyan]")
+ if entry.description:
+ console.print(entry.description)
+ console.print()
+ rows = [("Repo", entry.repo), ("Subdir", entry.subdir), ("Pinned SHA", entry.sha),
+ ("Maintainer", entry.maintainer), ("Requires", f"hermes {entry.requires_hermes}" if entry.requires_hermes else ""),
+ ("Platforms", ", ".join(entry.platforms)), ("Docs", entry.docs_url)]
+ for label, value in rows:
+ if value:
+ console.print(f"[dim]{label + ':':<12}[/dim] {value}")
+ console.print()
+ for label, items in (("Tools", caps.provides_tools), ("Hooks", caps.provides_hooks),
+ ("Middleware", caps.provides_middleware), ("Env vars", caps.requires_env)):
+ console.print(f"[dim]{label + ':':<12}[/dim] {', '.join(items) or '(none)'}")
+ console.print()
+ removed = find_removed(entry.name) or find_removed(entry.repo)
+ if removed is not None:
+ console.print(f"[red bold]✗ REMOVED from catalog: {removed.reason or 'no reason recorded'}"
+ f"{f' ({removed.date})' if removed.date else ''}[/red bold]")
+ console.print()
+ console.print(f"[dim]Install:[/dim] hermes plugins install {entry.name}")
+ console.print()
+
+
+ def cmd_validate(path: str, as_json: bool = False) -> None:
+ """Catalog-admission validation of a plugin directory (the CI gate); exits 0/1."""
+ from hermes_cli.plugin_validate import validate_plugin_dir
+ from hermes_cli.plugins_cmd import _console
+ report = validate_plugin_dir(Path(path))
+ if as_json:
+ print(json.dumps(report.to_dict(), indent=2))
+ sys.exit(report.exit_code)
+ console = _console()
+ console.print()
+ for check_name, ok, detail in report.checks:
+ console.print(f"{'[green]✓[/green]' if ok else '[red]✗[/red]'} {check_name}"
+ + (f" [dim]— {detail}[/dim]" if detail else ""))
+ for warning in report.warnings:
+ console.print(f"[yellow]⚠ {warning}[/yellow]")
+ console.print()
+ console.print("[green bold]Validation passed.[/green bold]" if report.ok else "[red bold]Validation failed.[/red bold]")
+ sys.exit(report.exit_code)
+
+
+ # ── Dashboard / TUI payloads ─────────────────────────────────────────────────
+
+ def installed_catalog_state(installed: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
+ """Catalog entries merged with local state for the dashboard. *installed* maps every alias (name
+ and registry key) of a discovered plugin to ``{"dir", "runtime_status"}``. A catalog name rarely
+ equals the manifest name (``hermes-plugin-x`` vs ``x``), so installs are matched through the
+ sidecar's ``catalog_name`` first and by name only as a fallback."""
+ by_catalog_name: Dict[str, Dict[str, Any]] = {}
+ for local in installed.values():
- sidecar = read_catalog_sidecar(local["dir"])
++ sidecar = catalog_install_record(local["dir"])
+ if sidecar:
+ by_catalog_name[str(sidecar["catalog_name"])] = {**local, "sidecar": sidecar}
+ entries = []
+ for entry in load_catalog_live():
+ local = by_catalog_name.get(entry.name) or installed.get(entry.name)
+ sidecar = local.get("sidecar") if local else None
+ installed_sha = str(sidecar["sha"]) if sidecar and sidecar.get("sha") else None
+ entries.append({
+ **entry.to_dict(), "sha_short": entry.sha[:7],
+ "capability_summary": entry_capability_summary(entry),
+ "installed": local is not None, "installed_sha": installed_sha,
+ "update_available": bool(installed_sha) and installed_sha != entry.sha,
+ "runtime_status": local["runtime_status"] if local else None,
+ })
+ return {
+ "entries": entries,
+ "removed": [{"name": r.name, "repo": r.repo, "reason": r.reason, "date": r.date} for r in load_removed_list()],
+ "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
+ }
+
+
+ def catalog_row_fields(dir_path, pins: Dict[str, str]) -> Dict[str, Any]:
+ """Provenance fields for one installed-plugin row (TUI/desktop ``plugins.manage list``): catalog
+ name/tier/installed SHA and, when *pins* has the entry, the current pin + ``update_available``."""
- sidecar = read_catalog_sidecar(dir_path)
++ sidecar = catalog_install_record(dir_path)
+ if not sidecar:
+ return {}
+ installed_sha = str(sidecar.get("sha") or "").lower()
+ row: Dict[str, Any] = {
+ "catalog_name": sidecar["catalog_name"], "catalog_tier": str(sidecar.get("tier") or "community"),
+ "installed_sha": installed_sha}
+ pin = pins.get(str(sidecar["catalog_name"]))
+ if pin:
+ row["catalog_sha"] = pin
+ row["update_available"] = bool(installed_sha) and installed_sha != pin
+ return row
+
+
+ def catalog_pins() -> Dict[str, str]:
+ """``{catalog_name: pinned_sha}`` from the live catalog; empty on failure (best effort)."""
+ try:
+ return {e.name: e.sha for e in load_catalog_live()}
+ except Exception:
+ return {}
diff --cc hermes_cli/plugins_manifest.py
index d555632ee35,ce5c34e40a8..184adfb75ec
--- a/hermes_cli/plugins_manifest.py
+++ b/hermes_cli/plugins_manifest.py
@@@ -364,6 -370,55 +370,56 @@@ class PluginManifest
listens: List[str] = field(default_factory=list)
+ # ── requires_hermes version gate ─────────────────────────────────────────────
+ _VERSION_COMPARATOR_RE = re.compile(r"^\s*(>=|<=|==|!=|>|<)\s*(.+?)\s*$")
+
+
+ def running_hermes_version() -> str:
+ """Installed ``hermes-agent`` distribution version, else ``hermes_cli.__version__`` (source checkout)."""
+ try:
+ return importlib.metadata.version("hermes-agent")
+ except Exception:
+ from hermes_cli import __version__
+ return __version__
+
+
+ def _version_tuple(v: str) -> Optional[tuple]:
+ """``v1.2.3-rc1`` → ``(1, 2, 3)``; ``None`` when a segment is non-numeric."""
+ parts = re.split(r"[-+]", str(v).strip().lstrip("v"), 1)[0].split(".")
+ parts += ["0"] * (3 - len(parts))
+ try:
+ return tuple(int(x) for x in parts[:3])
+ except ValueError:
+ return None
+
+
+ def version_satisfies(spec: str, current: str) -> bool:
+ """``>=``/``>``/``<=``/``<``/``==``/``!=`` clauses (comma = AND; bare version = ``>=``). Unparseable
+ versions are permissive — no PEP 440 dependency for a one-field manifest gate."""
+ cur = _version_tuple(current)
+ if cur is None:
+ return True
+ ops = {">=": cur.__ge__, "<=": cur.__le__, "==": cur.__eq__, "!=": cur.__ne__, ">": cur.__gt__, "<": cur.__lt__}
+ for clause in filter(None, (c.strip() for c in spec.split(","))):
+ m = _VERSION_COMPARATOR_RE.match(clause)
+ op, target = (m.group(1), m.group(2)) if m else (">=", clause)
+ tgt = _version_tuple(target)
+ if tgt is not None and not ops[op](tgt):
+ return False
+ return True
+
+
+ def requires_hermes_error(manifest: "PluginManifest") -> Optional[str]:
+ """Load-blocking reason when the manifest's ``requires_hermes`` rejects the running version."""
- if not manifest.requires_hermes:
++ spec = manifest.get("requires_hermes", "") if isinstance(manifest, Mapping) else manifest.requires_hermes
++ if not spec:
+ return None
+ current = running_hermes_version()
- if version_satisfies(manifest.requires_hermes, current):
++ if version_satisfies(spec, current):
+ return None
- return f"requires hermes {manifest.requires_hermes}, running {current}"
++ return f"requires hermes {spec}, running {current}"
+
+
def portable_plugin_manifest(child: Path, source: str, prefix: str) -> PluginManifest:
"""Build the manifest for a portable Agent Plugin directory (``plugin.json``); diagnostics warn."""
from hermes_cli.agent_plugins import read_agent_plugin_manifest
diff --cc hermes_cli/plugins_transaction.py
index 00000000000,00000000000..cacdc563b07
new file mode 100644
--- /dev/null
+++ b/hermes_cli/plugins_transaction.py
@@@ -1,0 -1,0 +1,204 @@@
++"""Publish plugin code and its dependency selection through one recoverable handoff."""
++from __future__ import annotations
++
++import base64
++import json
++import os
++from pathlib import Path
++import shutil
++import uuid
++
++
++def recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:
++ from hermes_cli.fs_utils import rmtree_force
++ from hermes_cli.runtime_paths import dependency_home_root, runtime_facts_path
++ from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest
++
++ target, backup, metadata = (Path(row[key]) for key in ("target", "backup", "metadata"))
++ home = dependency_home_root().resolve()
++ if (not target.resolve().is_relative_to(home) or target.parent.name != "plugins"
++ or backup.parent != target.parent or not backup.name.startswith(".previous-")
++ or metadata != target.parent / ".install-metadata.json"):
++ raise ValueError("plugin publication paths escape their home")
++ committed = row.get("committed") or _digest(runtime_facts_path(project)) != row["facts_before"]
++ if committed:
++ if backup.exists():
++ rmtree_force(backup)
++ else:
++ old = base64.b64decode(row["metadata_before"], validate=True) if row["metadata_before"] is not None else None
++ current = _bytes(metadata)
++ new = base64.b64decode(row["metadata_after"], validate=True)
++ if current not in (old, new):
++ raise ValueError("plugin metadata changed after publication; preserve it for manual recovery")
++ if backup.exists():
++ if target.exists():
++ rmtree_force(target)
++ os.replace(backup, target)
++ elif not row["target_existed"] and target.exists():
++ rmtree_force(target)
++ if old is None:
++ metadata.unlink(missing_ok=True)
++ else:
++ _atomic_bytes(metadata, old)
++ journal.unlink()
++
++
++class PluginPublication:
++ def __init__(self, project: Path, staged: Path, target: Path, metadata: dict):
++ from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path
++ from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest
++
++ self.project = project
++ self.journal = install_state_dir(project) / "publication.json"
++ backup = target.parent / f".previous-{uuid.uuid4().hex}"
++ metadata_path = target.parent / ".install-metadata.json"
++ previous = _bytes(metadata_path)
++ proposed = (json.dumps(metadata, indent=2, sort_keys=True) + "\n").encode("utf-8")
++ self.row = {
++ "kind": "plugin", "target": str(target), "backup": str(backup), "metadata": str(metadata_path),
++ "target_existed": target.exists(), "facts_before": _digest(runtime_facts_path(project)),
++ "metadata_before": base64.b64encode(previous).decode() if previous is not None else None,
++ "metadata_after": base64.b64encode(proposed).decode(),
++ }
++ _atomic_bytes(self.journal, json.dumps(self.row).encode())
++ try:
++ if target.exists():
++ os.replace(target, backup)
++ os.replace(staged, target)
++ _atomic_bytes(metadata_path, proposed)
++ except BaseException:
++ self()
++ raise
++
++ def __call__(self) -> None:
++ recover_plugin_publication(self.project, self.row, self.journal)
++
++ def finish(self) -> None:
++ from hermes_cli.runtime_state import _atomic_bytes
++
++ # A code-only update has no new environment fact to mark its commit.
++ self.row["committed"] = True
++ _atomic_bytes(self.journal, json.dumps(self.row).encode())
++ recover_plugin_publication(self.project, self.row, self.journal)
++
++
++def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict) -> None:
++ from hermes_cli import plugins_cmd
++ from hermes_cli.runtime_state import recover_publication, runtime_lock
++ from pm import paths
++ from pm.ensure import sync_venv
++ from pm.workspace import _is_member_candidate, enabled_plugin_dirs, member_sources
++
++ project = paths.repo_root()
++
++ def candidate_members():
++ if plugins_cmd._read_install_metadata() != old_metadata:
++ raise plugins_cmd.PluginOperationError("Plugin install metadata changed while preparing the update; retry.")
++ sources = member_sources(enabled_plugin_dirs())
++ active = target.resolve() in sources
++ if active:
++ sources[target.resolve()] = staged
++ for source in sources.values():
++ plugins_cmd._check_manifest_version(plugins_cmd._read_manifest_for_install(source), source.name)
++ return {identity: source for identity, source in sources.items() if _is_member_candidate(source)}
++
++ # Validate all active dependencies. The installed identity remains stable while
++ # PM snapshots the staged inputs into the candidate generation's workspace.
++ active = target.resolve() in member_sources(enabled_plugin_dirs())
++ if active:
++ sync_venv(explicit=True, plugin_dirs=candidate_members,
++ before_publish=lambda: PluginPublication(project, staged, target, new_metadata))
++ else:
++ with runtime_lock(project):
++ recover_publication(project)
++ if target.resolve() in member_sources(enabled_plugin_dirs()):
++ raise plugins_cmd.PluginOperationError("Plugin enablement changed while preparing the install; retry.")
++ if plugins_cmd._read_install_metadata() != old_metadata:
++ raise plugins_cmd.PluginOperationError("Plugin install metadata changed while preparing the install; retry.")
++ PluginPublication(project, staged, target, new_metadata).finish()
++
++
++def update_plugin(target: Path, *, catalog_entry=None) -> str:
++ """Prepare a catalog re-pin or custom Git pull without changing the live tree."""
++ import tempfile
++
++ from hermes_cli import plugins_cmd as pc
++ from hermes_cli.plugins_cmd_catalog import raise_if_removed
++ from pm.store import tree_digest
++
++ target = target.resolve()
++ metadata = pc._read_install_metadata()
++ record = dict(metadata.get(target.name, {}))
++ if catalog_entry is None and record.get("pinned"):
++ raise pc.PluginOperationError(f"Plugin '{target.name}' is pinned; reinstall with an explicit --ref to change it.")
++ source = catalog_entry.install_identifier if catalog_entry else str(record.get("source") or "")
++ if not source or (catalog_entry is None and not (target / ".git").is_dir()):
++ raise pc.PluginOperationError(f"Plugin '{target.name}' has no owned Git checkout; reinstall from its source.")
++ feed_revision = None
++ if catalog_entry is None:
++ from hermes_cli.plugins_provenance import Provenance, ProvenanceClass
++ from hermes_cli.plugins_updates import check_local_provenance, default_fetch, parse_feed_yml
++
++ checked = check_local_provenance(Provenance(target.name, ProvenanceClass.GIT, target, record))
++ if checked.needs_fixing:
++ raise pc.PluginOperationError(checked.needs_fixing)
++ if record.get("update_url"):
++ feed = parse_feed_yml(default_fetch(record["update_url"]))
++ proposed = (feed.get("artifacts") or {}).get("git", "")
++ if pc._EXACT_COMMIT_RE.fullmatch(proposed):
++ feed_revision = proposed.lower()
++ elif proposed not in (source, source.split("#", 1)[0]):
++ raise pc.PluginOperationError("Update feed must select a commit or the recorded Git source.")
++ if feed.get("min_hermes"):
++ pc._check_manifest_version({"requires_hermes": feed["min_hermes"]}, target.name)
++ raise_if_removed(target.name, source.split("#", 1)[0])
++ before = tree_digest(target)
++ with tempfile.TemporaryDirectory(prefix=".update-", dir=target.parent) as directory:
++ staged = Path(directory) / "plugin"
++ try:
++ if catalog_entry:
++ git_url, subdir = pc._resolve_git_url(source)
++ revision = pc._clone_plugin_repo(staged, git_url, catalog_entry.sha)
++ staged = pc._resolve_subdir_within(staged, subdir) if subdir else staged
++ # Catalog re-pins cannot discard edits to a currently installed tree.
++ if (target / ".git").is_dir():
++ git = pc._resolve_git_executable()
++ changed = pc._git_or_raise(git, target, "status", "--porcelain", "--untracked-files=normal",
++ failure_prefix="Could not inspect plugin edits: ")
++ if changed.stdout.strip():
++ raise pc.PluginOperationError("Catalog plugin has local changes; save them before updating.")
++ output = f"Updated to catalog pin {revision}"
++ record.update(catalog_name=catalog_entry.name, catalog_tier=catalog_entry.tier,
++ pinned=True, source=pc._canonical_source(git_url, subdir))
++ else:
++ # Copy Git metadata and local changes. Autostash only ever touches the copy.
++ shutil.copytree(target, staged, symlinks=True, ignore=shutil.ignore_patterns("__pycache__"))
++ if feed_revision:
++ git = pc._resolve_git_executable()
++ status = pc._git_or_raise(git, target, "status", "--porcelain", failure_prefix="Could not inspect plugin edits: ")
++ if status.stdout.strip():
++ raise pc.PluginOperationError("Pinned feed update has local changes; save them before updating.")
++ pc._checkout_exact_revision(staged, git, feed_revision)
++ output = f"Updated to feed commit {feed_revision}"
++ else:
++ ok, output = pc._git_pull_plugin_dir(staged)
++ if not ok:
++ raise pc.PluginOperationError(output)
++ revision = pc._git_head_revision(staged, pc._resolve_git_executable())
++ manifest = pc._read_manifest_for_install(staged)
++ if manifest.get("name", target.name) != target.name:
++ raise pc.PluginOperationError("The updated plugin changed its installed name; reinstall it explicitly.")
++ pc._check_manifest_version(manifest, target.name)
++ pc._scan_plugin_tree(staged, source, force=False)
++ pc._copy_example_files(staged, pc._console())
++ if tree_digest(target) != before:
++ raise pc.PluginOperationError("Plugin files changed while preparing the update; retry.")
++ record["revision"] = revision
++ if tree_digest(staged) == before:
++ return output
++ publish_plugin(staged, target, metadata, {**metadata, target.name: record})
++ return output
++ except pc.PluginOperationError:
++ raise
++ except Exception as exc:
++ raise pc.PluginOperationError(f"Plugin '{target.name}' update was not published: {exc}") from exc
diff --cc hermes_cli/plugins_updates.py
index 90f6e11a77f,00000000000..238f675713d
mode 100644,000000..100644
--- a/hermes_cli/plugins_updates.py
+++ b/hermes_cli/plugins_updates.py
@@@ -1,389 -1,0 +1,405 @@@
+"""Plugin update checks — the standard, read-only 'is it outdated?' verb.
+
+Address resolution per plugin, in order, no derivation ever (settled
+2026-09-03, plugin-auto-update plan):
+ 1. saved sidecar tag + matching manifest update_url → fetch the feed yml
+ 2. manifest update_url differs from the saved tag (or appeared where
+ none was saved) → NEEDS-FIXING: fetch refused, tag untouched
+ 3. no update_url anywhere + git row → git ls-remote vs revision
+ 4. neither → manual/unupdatable
+Plus the pip world, stateless: entry-point discovery → installed version
+vs PyPI latest. NEVER mutates anything — no pulls, no row writes, no
+saved-tag changes.
+"""
+
+from __future__ import annotations
+
+import importlib.metadata
+import json
+import re
+import subprocess
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from hermes_cli.plugins_provenance import (
+ Provenance,
+ ProvenanceClass,
+ plugins_provenance,
+ read_sidecar_rows,
+)
+
+_FETCH_TIMEOUT = 10.0
+_MAX_FEED_BYTES = 1 * 1024 * 1024
+_FULL_GIT_SHA_RE = re.compile(r"[0-9a-fA-F]{40}")
+
+
+@dataclass
+class CheckResult:
+ name: str
+ klass: str # provenance class value ('git', ...)
+ current: Optional[str] = None
+ latest: Optional[str] = None
+ update_available: Optional[bool] = None # None = unknown/uncheckable
+ needs_fixing: Optional[str] = None # mismatch reason when set
+ min_hermes: Optional[str] = None # feed's version floor, if any
+ reason: str = ""
+
+ def to_json(self) -> dict:
+ return {
+ "name": self.name,
+ "class": self.klass,
+ "current": self.current,
+ "latest": self.latest,
+ "update_available": self.update_available,
+ "needs_fixing": self.needs_fixing,
+ "min_hermes": self.min_hermes,
+ "reason": self.reason,
+ }
+
+
+def _read_manifest_field(plugin_dir: Path, key: str) -> Optional[str]:
+ """One field from the installed plugin.yaml (claims, not provenance)."""
+ import yaml
+
+ manifest = plugin_dir / "plugin.yaml"
+ if not manifest.is_file():
+ return None
+ try:
+ with manifest.open(encoding="utf-8-sig") as f:
+ data = yaml.safe_load(f) or {}
+ except Exception:
+ return None
+ if not isinstance(data, dict):
+ return None
+ value = data.get(key)
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+def check_local_provenance(prov: Provenance) -> CheckResult:
+ """Check installed provenance without fetching remote metadata."""
+ result = CheckResult(name=prov.name, klass=prov.klass.value)
+
+ if prov.klass is ProvenanceClass.MANUAL:
+ result.reason = "no provenance; not auto-updatable"
+ return result
+ if prov.klass is ProvenanceClass.DRIFT:
+ result.reason = (
+ f"provenance drift — sidecar records {prov.row.get('source')!r} "
+ "but the dir has no .git; reinstall from the recorded source"
+ )
+ return result
+ if prov.klass is ProvenanceClass.SELF_CLONED:
+ result.reason = "self-cloned; run `hermes plugins adopt` first"
+ return result
+
+ row = prov.row or {}
+ result.current = row.get("revision") or None
+ if row.get("pinned") is True:
+ result.update_available = False
+ result.reason = f"pinned @ {(result.current or '')[:12] or 'sha'}"
+ return result
+
+ # ── the saved-tag comparison (the security heart) ──────────────
+ saved = row.get("update_url") or None
+ claimed = _read_manifest_field(prov.path, "update_url")
+ if saved is None and claimed is not None:
+ # a pulled commit introduced a url where none was saved — same
+ # threat class as a swap; never adopt silently
+ result.needs_fixing = (
+ f"manifest declares update_url {claimed!r} but no url was saved "
+ "at install; run `hermes plugins trust-update-url` after review"
+ )
+ return result
+ if saved is not None and claimed != saved:
+ result.needs_fixing = (
+ f"update_url mismatch: saved {saved!r}, manifest declares "
+ f"{claimed!r}; run `hermes plugins trust-update-url` after review"
+ )
+ return result
+
+ return result
+
+
+def check_provenanced(
+ prov: Provenance,
+ *,
+ fetch: Callable[[str], str],
+ ls_remote: Callable[[str], str],
+) -> CheckResult:
+ """Check local provenance before contacting its approved update source."""
++ if (prov.row or {}).get("catalog_name"):
++ from hermes_cli.plugin_catalog import find_removed, get_live_catalog_entry
++
++ row = prov.row
++ result = CheckResult(name=prov.name, klass="catalog", current=row.get("revision"))
++ removed = find_removed(row["catalog_name"]) or find_removed(str(row.get("source", "")).split("#", 1)[0])
++ if removed:
++ result.reason = f"removed from catalog: {removed.reason}"
++ return result
++ entry = get_live_catalog_entry(row["catalog_name"])
++ if entry is None:
++ result.reason = "catalog entry is unavailable; installed pin retained"
++ return result
++ result.latest = entry.sha
++ result.update_available = result.current != entry.sha
++ return result
+ result = check_local_provenance(prov)
+ if result.reason or result.needs_fixing:
+ return result
+ row = prov.row or {}
+ saved = row.get("update_url") or None
+
+ # ── 1. matching saved tag → fetch the feed ─────────────────────
+ if saved is not None:
+ try:
+ feed_text = fetch(saved)
+ except Exception as exc:
+ result.reason = f"feed fetch failed: {exc}"
+ return result
+ try:
+ feed = parse_feed_yml(feed_text)
+ except ValueError as exc:
+ result.reason = f"feed unparseable: {exc}"
+ return result
+ result.latest = feed.get("version")
+ result.min_hermes = feed.get("min_hermes")
+ # Like-for-like identity only (audit C17): a feed that ships a full
+ # git SHA compares SHA vs recorded revision; otherwise the feed's
+ # semantic version compares against the installed manifest's
+ # version. A SHA is never compared to a semantic version, and an
+ # uncomparable pair reads as unknown — not as an update.
+ feed_git = (feed.get("artifacts") or {}).get("git")
+ if feed_git and _FULL_GIT_SHA_RE.fullmatch(feed_git):
+ if not result.current or not _FULL_GIT_SHA_RE.fullmatch(
+ str(result.current)
+ ):
+ result.update_available = None
+ result.reason = (
+ "feed declares a git sha but the install records no "
+ "full revision sha to compare"
+ )
+ return result
+ # Case-equivalent hex only after format validation.
+ result.latest = feed_git.lower()
+ result.update_available = feed_git.lower() != result.current.lower()
+ return result
+ installed_version = _read_manifest_field(prov.path, "version")
+ if installed_version is None:
+ result.update_available = None
+ result.reason = (
+ f"feed declares version {result.latest!r} but the installed "
+ "plugin.yaml records no version to compare"
+ )
+ return result
+ # Like-for-like fields: the semantic branch compares version vs
+ # version, so `current` reports the installed version, not the
+ # recorded revision sha.
+ result.current = installed_version
+ result.update_available = result.latest != installed_version
+ return result
+
+ # ── 3. no update_url anywhere + git row → ls-remote ────────────
+ source = row.get("source") or ""
+ if not source:
+ result.reason = "no recorded source"
+ return result
+ try:
+ head = ls_remote(source)
+ except Exception as exc:
+ result.reason = f"ls-remote failed: {exc}"
+ return result
+ result.latest = head
+ result.update_available = bool(head) and head != result.current
+ return result
+
+
+def parse_feed_yml(text: str) -> dict:
+ """The electron-updater-derived feed shape: version, released,
+ min_hermes, artifacts{git,bundle,bundle_sha256}, notes_url."""
+ import yaml
+
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError as exc:
+ raise ValueError(f"invalid feed YAML: {exc}") from exc
+ if not isinstance(data, dict):
+ raise ValueError("feed must be a YAML mapping")
+ version = data.get("version")
+ if not isinstance(version, str) or not version.strip():
+ raise ValueError("feed missing 'version'")
+ out: dict[str, Any] = {"version": version.strip()}
+ for key in ("min_hermes", "notes_url"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ out[key] = value.strip()
+ artifacts = data.get("artifacts")
+ if isinstance(artifacts, dict):
+ git = artifacts.get("git")
+ if git is not None and not isinstance(git, str):
+ raise ValueError("feed artifacts.git must be a string")
+ out["artifacts"] = {
+ k: v for k, v in artifacts.items() if isinstance(v, str)
+ }
+ return out
+
+
+def _owning_distribution(ep) -> Optional[str]:
+ """The name of the distribution the entry point belongs to — metadata,
+ never a guess derived from the import module (audit C17)."""
+ dist = getattr(ep, "dist", None)
+ if dist is None:
+ return None
+ try:
+ return dist.metadata.get("Name") or None
+ except Exception:
+ return None
+
+
+def check_pip_plugins(
+ *,
+ installed_version: Callable[[str], str], # dist name -> version
+ pypi_latest: Callable[[str], Optional[str]], # dist name -> latest
+ entry_points: Optional[list] = None, # injectable for tests
+) -> list[CheckResult]:
+ """The pip world, stateless: entry-point dists vs PyPI. Nothing
+ recorded, nothing to drift."""
+ if entry_points is None:
+ entry_points = list(
+ importlib.metadata.entry_points().select(group="hermes_agent.plugins")
+ )
+ results: list[CheckResult] = []
+ for ep in entry_points:
+ dist_name = getattr(ep, "dist_name", None) or _owning_distribution(ep)
+ if not dist_name:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ reason=(
+ "entry point has no owning distribution metadata; "
+ "cannot determine what to check"
+ ),
+ )
+ )
+ continue
+ try:
+ current = installed_version(dist_name)
+ except importlib.metadata.PackageNotFoundError:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ reason=f"distribution {dist_name!r} not importable",
+ )
+ )
+ continue
+ latest = pypi_latest(dist_name)
+ # None (unknown / not on PyPI) must read as unknown — not False
+ if latest is None:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ current=current,
+ latest=None,
+ update_available=None,
+ reason="unknown (not on PyPI)",
+ )
+ )
+ continue
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ current=current,
+ latest=latest,
+ update_available=latest != current,
+ )
+ )
+ return results
+
+
+def default_fetch(url: str) -> str:
+ """The real feed fetcher: url -> text (raises on failure).
+
+ ONE implementation shared by the manual ``hermes plugins
+ check-updates`` and the cadence tick — callers never re-derive it.
+ """
+ import urllib.request
+
+ with urllib.request.urlopen(url, timeout=_FETCH_TIMEOUT) as resp:
+ data = resp.read(_MAX_FEED_BYTES)
+ return data.decode("utf-8", errors="replace")
+
+
+def default_ls_remote(source: str) -> str:
+ """The real git probe: source -> HEAD sha (raises on failure).
+
+ Uses the same resolved git executable the CLI path resolves. Lazily
+ imports plugins_cmd (which lazily imports this module) — no import
+ cycle at module load.
+ """
+ from hermes_cli.plugins_cmd import _resolve_git_executable
+
+ proc = subprocess.run(
+ [_resolve_git_executable() or "git", "ls-remote", source, "HEAD"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if proc.returncode != 0:
+ raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])
+ # 'sha\trefs/heads/...' or empty
+ out = (proc.stdout or "").strip()
+ return out.split("\t")[0] if out else ""
+
+
+def run_checks(
+ plugins_dir: Path,
+ *,
+ fetch: Optional[Callable[[str], str]] = None,
+ ls_remote: Optional[Callable[[str], str]] = None,
+ include_pip: bool = True,
+ pip_installed_version: Callable[[str], str] = importlib.metadata.version,
+ pip_pypi_latest: Optional[Callable[[str], Optional[str]]] = None,
+ pip_entry_points: Optional[list] = None,
+) -> list[CheckResult]:
+ """All checks for one plugins dir. NEVER mutates anything.
+
+ ``fetch``/``ls_remote`` default to :func:`default_fetch` /
+ :func:`default_ls_remote` — the single shared network implementation
+ the manual command and the cadence tick both ride.
+ """
+ if fetch is None:
+ fetch = default_fetch
+ if ls_remote is None:
+ ls_remote = default_ls_remote
+ results = [
+ check_provenanced(p, fetch=fetch, ls_remote=ls_remote)
+ for p in plugins_provenance(plugins_dir)
+ ]
+ if include_pip:
+ if pip_pypi_latest is None:
+ pip_pypi_latest = _default_pypi_latest
+ results.extend(
+ check_pip_plugins(
+ installed_version=pip_installed_version,
+ pypi_latest=pip_pypi_latest,
+ entry_points=pip_entry_points,
+ )
+ )
+ return results
+
+
+def _default_pypi_latest(dist: str) -> Optional[str]:
+ """PyPI JSON API — the real fetcher (injectable in tests)."""
+ import urllib.request
+
+ url = f"https://pypi.org/pypi/{dist}/json"
+ try:
+ with urllib.request.urlopen(url, timeout=_FETCH_TIMEOUT) as resp:
+ data = json.loads(resp.read(_MAX_FEED_BYTES))
+ return (data.get("info") or {}).get("version")
+ except Exception:
+ return None
diff --cc hermes_cli/runtime_state.py
index c94db18ef1e,00000000000..42a17a0c9fe
mode 100644,000000..100644
--- a/hermes_cli/runtime_state.py
+++ b/hermes_cli/runtime_state.py
@@@ -1,182 -1,0 +1,187 @@@
+"""Stdlib-only recovery and lifetime protection for dependency generations."""
+from __future__ import annotations
+
+import atexit
+import errno
+import base64
+from contextlib import contextmanager
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import tempfile
+import time
+import uuid
+
+from hermes_cli.runtime_paths import dependency_home_root, install_state_dir, runtime_facts_path
+
+
+def _lock(fd: int, *, wait: bool) -> bool:
+ if os.name == "nt":
+ import msvcrt
+ while True:
+ try:
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ return True
+ except OSError as exc:
+ if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
+ raise
+ if not wait:
+ return False
+ time.sleep(0.05)
+ else:
+ import fcntl
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
+ return True
+ except BlockingIOError:
+ return False
+
+
+@contextmanager
+def runtime_lock(project: Path):
+ state = install_state_dir(project)
+ state.mkdir(parents=True, exist_ok=True)
+ fd = os.open(state / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ _lock(fd, wait=True)
+ yield
+ finally:
+ os.close(fd)
+
+
+def _bytes(path: Path) -> bytes | None:
+ try:
+ return path.read_bytes()
+ except FileNotFoundError:
+ return None
+
+
+def _digest(path: Path) -> str | None:
+ data = _bytes(path)
+ return hashlib.sha256(data).hexdigest() if data is not None else None
+
+
+def _atomic_bytes(path: Path, data: bytes):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".publish-")
+ try:
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ if os.name != "nt":
+ directory = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def recover_publication(project: Path) -> None:
+ """Recover while holding runtime_lock, before activation or another write."""
+ journal = install_state_dir(project) / "publication.json"
+ data = _bytes(journal)
+ if data is None:
+ return
+ try:
+ row = json.loads(data)
++ if row.get("kind") == "plugin":
++ from hermes_cli.plugins_transaction import recover_plugin_publication
++
++ recover_plugin_publication(project, row, journal)
++ return
+ config = Path(row["config"])
+ if config.name != "config.yaml" or not config.resolve().is_relative_to(dependency_home_root().resolve()):
+ raise ValueError("config path is outside Hermes state")
+ previous = base64.b64decode(row["previous"], validate=True) if row["previous"] is not None else None
+ if _digest(runtime_facts_path(project)) == row["facts_before"]:
+ current = _digest(config)
+ prior = hashlib.sha256(previous).hexdigest() if previous is not None else None
+ if current not in (prior, row.get("config_after")):
+ raise ValueError("config changed after publication began; preserve it for manual recovery")
+ # No selection was published. Roll back before any plugin is loaded.
+ if previous is None:
+ config.unlink(missing_ok=True)
+ else:
+ _atomic_bytes(config, previous)
+ journal.unlink()
+ except (ValueError, KeyError, TypeError, OSError) as exc:
+ raise RuntimeError(f"cannot recover dependency publication: {journal}: {exc}") from exc
+
+
+class Publication:
+ def __init__(self, project: Path, config: Path, proposed: bytes | None = None):
+ self.project = project
+ self.journal = install_state_dir(project) / "publication.json"
+ previous = _bytes(config)
+ row = {"config": str(config.resolve()), "previous": base64.b64encode(previous).decode() if previous is not None else None,
+ "facts_before": _digest(runtime_facts_path(project)),
+ "config_after": hashlib.sha256(proposed).hexdigest() if proposed is not None else None}
+ _atomic_bytes(self.journal, json.dumps(row).encode())
+
+ def __call__(self) -> None:
+ recover_publication(self.project)
+
+ def finish(self) -> None:
+ self.journal.unlink(missing_ok=True)
+
+
+def begin_publication(project: Path, config: Path, proposed: bytes | None = None) -> Publication:
+ recover_publication(project)
+ return Publication(project, config, proposed)
+
+
+def lease_generation(environment: Path) -> None:
+ """Hold a kernel lock until process exit; call under runtime_lock at boot."""
+ generation = environment.parent
+ if not (generation / ".lease-managed").is_file():
+ return # Generations produced before leases stay conservatively retained.
+ leases = generation / ".leases"
+ leases.mkdir(exist_ok=True)
+ fd = os.open(leases / uuid.uuid4().hex, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
+ try:
+ _lock(fd, wait=True)
+ except BaseException:
+ os.close(fd)
+ raise
+ atexit.register(os.close, fd)
+
+
+def collect_generations(project: Path, *, min_age_seconds: float = 86400) -> list[Path]:
+ """Remove unselected lease-managed generations after their readers exit."""
+ from hermes_cli.runtime_paths import selected_venv
+ removed = []
+ root = install_state_dir(project)
+ if not root.exists():
+ return removed
+ with runtime_lock(project):
+ recover_publication(project)
+ selected = selected_venv(project).parent.resolve()
+ generations = root / "environments"
+ if not generations.is_dir():
+ return removed
+ for generation in generations.iterdir():
+ if generation.is_symlink() or not generation.is_dir() or generation.resolve() == selected:
+ continue
+ marker = generation / ".lease-managed"
+ if not marker.is_file() or time.time() - marker.stat().st_mtime < min_age_seconds:
+ continue
+ active = False
+ for lease in (generation / ".leases").glob("*"):
+ fd = os.open(lease, os.O_RDWR)
+ try:
+ if not _lock(fd, wait=False):
+ active = True
+ break
+ finally:
+ os.close(fd)
+ if not active:
+ shutil.rmtree(generation)
+ removed.append(generation)
+ return removed
diff --cc plugins/memory/mem0/__init__.py
index cba45a5bda6,cfe97916d6d..8cba806523c
--- a/plugins/memory/mem0/__init__.py
+++ b/plugins/memory/mem0/__init__.py
@@@ -235,28 -153,21 +153,21 @@@ class Mem0MemoryProvider(MemoryProvider
from ._setup import post_setup
post_setup(hermes_home, config)
+ def _oss_hint(self, template: str, default: str = "vector store") -> str:
+ """OSS-only hint; ``{vs}`` is the configured vector-store provider. "" in other modes."""
+ return template.format(vs=self._config.get("oss", {}).get("vector_store", {}).get("provider", default)) if self._mode == "oss" else ""
+
def _create_backend(self):
- # Lazy-install the mem0 SDK on demand before either backend imports
- # it. ensure() honors security.allow_lazy_installs (default true) and,
- # on a sealed Docker venv, redirects the install to the durable
- # target. On failure we fall through so the import inside the backend
- # produces the canonical error, captured below.
- try:
- from pm import ensure_import as _lazy_ensure
- _lazy_ensure("mem0")
- except ImportError:
- pass
- except Exception:
- pass
+ # Lazy-install the mem0 SDK before the backend imports it (honors security.allow_lazy_installs);
+ # on failure the backend import raises the canonical error, captured below.
+ with suppress(Exception):
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("memory.mem0", prompt=False)
++ from pm import ensure_import
++ ensure_import("mem0")
try:
+ from . import _backend
if self._mode == "oss":
- from ._backend import OSSBackend
- return OSSBackend(self._config.get("oss", {}))
- if self._host:
- from ._backend import SelfHostedBackend
- return SelfHostedBackend(self._api_key, self._host)
- from ._backend import PlatformBackend
- return PlatformBackend(self._api_key)
+ return _backend.OSSBackend(self._config.get("oss", {}))
+ return _backend.SelfHostedBackend(self._api_key, self._host) if self._host else _backend.PlatformBackend(self._api_key)
except Exception as e:
logger.error("Mem0 backend failed to initialize (%s mode): %s", self._mode, e)
self._init_error = str(e)
diff --cc pm/workspace.py
index ba4bf561c39,00000000000..1f0f321592a
mode 100644,000000..100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@@ -1,445 -1,0 +1,493 @@@
+"""Resolve core plus plugin requirements in a writable build snapshot.
+
+Shipped source and locks are inputs, never mutation targets. Candidate
+failure propagates without changing plugin configuration or the live venv.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import subprocess
++from collections.abc import Mapping
+from pathlib import Path
+from typing import Optional
+
+from pm import paths
+from pm.package import InstallError
+
+WORKSPACE_DIRNAME = ".pm-workspace"
++_MEMBER_EXCLUDE = frozenset({".git", ".venv", "venv", "node_modules", "__pycache__"})
++
++
++def _member_ignored(directory, names):
++ return [name for name in names if name in _MEMBER_EXCLUDE or name.endswith(".egg-info")]
+
+
+class ResolutionConflict(InstallError):
+ """uv's resolver proved the union has no valid solution."""
+
+
+# Markers uv prints ONLY when the resolver itself proves no solution
+# exists (its conflict report: "Because ...", "no solution found").
+# Deliberately narrow: a fetch timeout or index outage must not be
+# misread as a conflict — and regardless of classification, nothing
+# here ever disables a plugin; the caller decides.
+_RESOLVER_MARKERS = (
+ "no solution found",
+ "conflicting requirements",
+ "conflicting urls",
+ "because only the following versions",
+ "and your pyproject depends on",
+)
+
+
+def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallError:
+ """Turn a failed `uv <stage>` into the right classified error.
+
+ Resolver-conflict output → ResolutionConflict; anything else (fetch,
+ build, tooling) → plain InstallError with the tail of the output.
+ """
+ cause = f"uv {stage} exited {returncode}: {output.strip()[-600:]}"
+ lowered = output.lower()
+ if any(marker in lowered for marker in _RESOLVER_MARKERS):
+ return ResolutionConflict("venv", cause)
+ return InstallError("venv", cause)
+
+
+def workspace_root() -> Path:
+ """Default preparation root; callers can supply a fresh transaction root."""
+ from hermes_cli.runtime_paths import install_state_dir
+ return install_state_dir(paths.repo_root()) / WORKSPACE_DIRNAME
+
+
+def _member_rel(root: Path, plugin_dir: Path) -> str:
- """Workspace member string: relative path from the root to the plugin
- dir, always escaping the root (``../…``) — probed to resolve."""
++ """Use portable separators for a member inside the generated workspace."""
+ return os.path.relpath(plugin_dir.resolve(), root.resolve()).replace("\\", "/")
+
+
- def members_stamp(plugin_dirs: list[Path]) -> str:
- """Content hash of the member SET — order-independent, so venv stamps
- compare the set of unioned plugins, not the discovery order.
++def member_sources(plugin_dirs) -> dict[Path, Path]:
++ """Map installed identities to build inputs, including staged plugin updates."""
++ rows = plugin_dirs.items() if isinstance(plugin_dirs, Mapping) else ((path, path) for path in plugin_dirs)
++ return {Path(identity).resolve(): Path(source).resolve() for identity, source in rows}
++
+
- Includes each member's pyproject.toml CONTENT: a plugin update that
- changes its pins must re-sync the union even when the member set is
- unchanged (Task 4 of the plugin auto-update plan — path-only hashing
- left pulled-plugin dep bumps invisible to expected_stamp)."""
- resolved = sorted({p.resolve() for p in plugin_dirs})
++def members_stamp(plugin_dirs) -> str:
++ """Hash the member inputs copied into a generation, independent of staging paths."""
+ h = hashlib.sha256()
- for entry in resolved:
- h.update(str(entry).encode("utf-8"))
++ for identity, entry in sorted(member_sources(plugin_dirs).items()):
++ h.update(str(identity).encode("utf-8"))
+ h.update(b"\0")
+ for name in ("pyproject.toml", "plugin.yaml"):
+ source = entry / name
+ if source.is_file():
+ h.update(source.read_bytes())
+ h.update(b"\0")
++ if (entry / "pyproject.toml").is_file():
++ for directory, dirs, files in os.walk(entry):
++ dirs[:] = sorted(set(dirs) - set(_member_ignored(directory, dirs)))
++ for name in sorted(set(files) - set(_member_ignored(directory, files))):
++ path = Path(directory) / name
++ h.update(path.relative_to(entry).as_posix().encode())
++ h.update(b"\0")
++ h.update(os.readlink(path).encode() if path.is_symlink() else path.read_bytes())
++ h.update(b"\0")
+ return h.hexdigest()
+
+
+def _copy_core_inputs(source: Path, destination: Path) -> None:
+ """Build from a writable snapshot, never from signed/read-only source."""
+ import shutil
+
+ import fnmatch
+ import tomllib
+
+ metadata = tomllib.loads((source / "pyproject.toml").read_text(encoding="utf-8-sig"))
+ project = metadata.get("project", {})
+ setuptools = metadata.get("tool", {}).get("setuptools", {})
+ patterns = setuptools.get("packages", {}).get("find", {}).get("include", ["*"])
+ package_roots = {pattern.split(".", 1)[0] for pattern in patterns}
+ files = {"pyproject.toml", "setup.py", "setup.cfg"}
+ readme = project.get("readme")
+ if isinstance(readme, str):
+ files.add(readme)
+ elif isinstance(readme, dict) and "file" in readme:
+ files.add(readme["file"])
+ for pattern in project.get("license-files", []):
+ files.update(str(p.relative_to(source)) for p in source.glob(pattern))
+ files.update(p.name for p in source.glob("*.py"))
+
+ excluded = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist", "release", "uv.lock"}
+ def ignore(directory, names):
+ return [name for name in names if name in excluded or name.startswith(".")
+ or name.endswith(".egg-info") or (Path(directory) / name).is_symlink()]
+
+ for entry in source.iterdir():
+ if (entry.is_dir() and not entry.is_symlink() and entry.name not in excluded
+ and not entry.name.startswith(".") and entry.resolve() != destination.resolve()
+ and any(fnmatch.fnmatchcase(entry.name, pattern) for pattern in package_roots)):
+ target = destination / entry.name
+ if target.exists():
+ shutil.rmtree(target)
+ shutil.copytree(entry, target, ignore=ignore)
+ for name in files:
+ entry = source / name
+ if not entry.is_file() or entry.is_symlink():
+ continue
+ if not entry.resolve().is_relative_to(source.resolve()):
+ raise InstallError("venv", f"build input escapes the core project: {name}")
+ target = destination / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(entry, target)
+
+
+def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None) -> tuple[Path, bool]:
+ """(Re)generate the workspace root's pyproject.toml from core's
+ pyproject + the enabled plugin members. Idempotent — same inputs,
+ same bytes. Returns (root, changed): changed is True when the member
+ surface moved (member set or a member's pyproject content), which is
+ the signal to re-seed the resolution from the committed lock."""
+ if root is None:
+ root = workspace_root()
+ source = paths.repo_root().resolve()
+ if root.resolve() == source or source.is_relative_to(root.resolve()):
+ raise InstallError("venv", "workspace must not replace the core source")
+ root.mkdir(parents=True, exist_ok=True)
+
+ core_pyproject = paths.repo_root() / "pyproject.toml"
+ core_text = core_pyproject.read_text(encoding="utf-8-sig")
+
- members = [_member_rel(root, _workspace_member(Path(p), root))
- for p in {str(Path(p).resolve()) for p in plugin_dirs}]
++ members = [_member_rel(root, _workspace_member(source, root, identity=identity))
++ for identity, source in member_sources(plugin_dirs).items()]
+
+ lines = [core_text.rstrip("\n")]
+ if members:
+ lines.append("")
+ lines.append("[tool.uv.workspace]")
+ lines.append("members = [" + ", ".join(f'"{m}"' for m in sorted(members)) + "]")
+
+ text = "\n".join(lines) + "\n"
+ target = root / "pyproject.toml"
+ try:
+ changed = target.read_text(encoding="utf-8") != text
+ except OSError:
+ changed = True
+ _copy_core_inputs(paths.repo_root(), root)
+ target.write_text(text, encoding="utf-8")
+ return root, changed
+
+
+def build_root(plugin_dirs: list[Path], root: Optional[Path] = None) -> Path:
+ """(Re)generate the workspace root's pyproject.toml. ``root`` pins a
+ parent-supplied STAGING workspace (tests, staged syncs); default is
+ the per-install generated root beside the byte store."""
+ generated, _changed = _generate_pyproject(plugin_dirs, root)
+ return generated
+
+
+def _seed_lock(root: Path, seed_lock: Optional[Path] = None) -> None:
+ """Seed the generated root's uv.lock with the CURRENT resolution.
+
+ Seed precedence: the parent-supplied ``seed_lock`` path first, then
+ the root's own existing uv.lock (the current EXTENDED resolution from
+ the previous sync), then the committed core lock — so a plugin-driven
+ extension keeps every compatible selection it already made, and a
+ fresh root extends the committed resolution. uv preserves compatible
+ selections from the seed (a plugin's range spec does not move core
+ pins); explicit exact requirements stay binding as declared
+ constraints. The lock is COPIED — shipped/extended source bytes are
+ never rewritten; only the staging root receives the copy.
+
+ Called only when the member surface changed; an unchanged root keeps
+ its lock untouched, so repeated syncs are stable. Seed failures
+ SURFACE (they would silently degrade the resolution otherwise)."""
+ if seed_lock is None:
+ existing = root / "uv.lock"
+ if existing.is_file():
+ seed_lock = existing
+ else:
+ seed_lock = paths.repo_root() / "uv.lock"
+ if not seed_lock.is_file():
+ return # nothing committed to seed from; uv resolves from scratch
+ (root / "uv.lock").write_bytes(seed_lock.read_bytes())
+
+
+def _is_member_candidate(plugin_dir: Path) -> bool:
+ """A plugin dir is a workspace-member candidate when it declares python
+ deps: a pyproject.toml (modern), or legacy pip_dependencies/
+ python_dependencies in plugin.yaml (the bridge materializes those)."""
+ import stat
+
+ for name in ("pyproject.toml", "plugin.yaml"):
+ path = plugin_dir / name
+ try:
+ mode = path.stat().st_mode
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ raise ValueError(f"could not inspect plugin metadata: {path}") from exc
+ if not stat.S_ISREG(mode):
+ continue
+ if name == "pyproject.toml":
+ return True
+ try:
+ text = path.read_text(encoding="utf-8-sig")
+ except (OSError, UnicodeError) as exc:
+ raise ValueError(f"could not read plugin metadata: {path}") from exc
+ return "pip_dependencies" in text or "python_dependencies" in text
+ return False
+
+
- def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
- """Dependency members from the same effective plugin selection on every path."""
++def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
++ """Resolve the effective plugin selection without filtering dependency declarations."""
+ from pm.plugins_state import _is_directory, enabled_plugins_ordered
+
+ selection = enabled_plugins_ordered() if proposed_home is None else enabled_plugins_ordered(
+ proposed_home=proposed_home, enabled=enabled, disabled=disabled,
+ )
+ members = []
+ for plugins_dir, names in selection.items():
+ for name in names:
+ relative = Path(name)
+ if relative.is_absolute() or ".." in relative.parts:
+ raise InstallError("venv", f"invalid plugin key: {name}")
+ plugin_dir = plugins_dir / relative
+ if not _is_directory(plugin_dir):
+ plugin_dir = paths.repo_root() / "plugins" / relative
- if _is_directory(plugin_dir) and _is_member_candidate(plugin_dir):
++ if _is_directory(plugin_dir):
+ members.append(plugin_dir)
+ return list(dict.fromkeys(members))
+
+
++def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
++ """Keep every selected member or refuse an incompatible selection."""
++ from hermes_cli.plugins_cmd import _check_manifest_version, _read_manifest_for_install
++
++ selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled)
++ for path in selected:
++ _check_manifest_version(_read_manifest_for_install(path), path.name)
++ return [path for path in selected if _is_member_candidate(path)]
++
++
+def _legacy_requirements(plugin_dir: Path) -> list[str]:
+ from utils import fast_safe_load
+
+ manifest = plugin_dir / "plugin.yaml"
+ if not manifest.is_file():
+ return []
+ data = fast_safe_load(manifest.read_text(encoding="utf-8-sig"))
+ if not isinstance(data, dict):
+ raise InstallError("venv", f"invalid plugin manifest: {manifest}")
+ specs = []
+ for key in ("pip_dependencies", "python_dependencies"):
+ values = data.get(key, [])
+ if not isinstance(values, list) or any(not isinstance(v, str) for v in values):
+ raise InstallError("venv", f"invalid {key}: {manifest}")
+ specs.extend(values)
+ return list(dict.fromkeys(specs))
+
+
- def _workspace_member(plugin_dir: Path, root: Path) -> Path:
- """Legacy dependency declarations become virtual members in staging only."""
++def _workspace_member(plugin_dir: Path, root: Path, *, identity: Path | None = None) -> Path:
++ """Keep workspace members with their generation, not a temporary install clone."""
+ import json
++ import shutil
++ import tomllib
+
++ key = hashlib.sha256(str((identity or plugin_dir).resolve()).encode()).hexdigest()[:16]
+ pyproject = plugin_dir / "pyproject.toml"
+ if pyproject.is_file() and "GENERATED by pm" not in pyproject.read_text(encoding="utf-8-sig"):
- return plugin_dir
++ member = root / "plugin-sources" / key
++ if member.exists():
++ shutil.rmtree(member)
++ shutil.copytree(plugin_dir, member, symlinks=True,
++ ignore=_member_ignored)
++ document = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))
++ changed = False
++ for sources in document.get("tool", {}).get("uv", {}).get("sources", {}).values():
++ for spec in sources if isinstance(sources, list) else [sources]:
++ if not isinstance(spec, dict) or "path" not in spec:
++ continue
++ relative = Path(spec["path"])
++ if relative.is_absolute():
++ continue
++ resolved = (plugin_dir / relative).resolve()
++ if resolved.is_relative_to(plugin_dir.resolve()):
++ continue # The referenced tree was copied with this member.
++ spec["path"] = ((identity or plugin_dir) / relative).resolve().as_posix()
++ changed = True
++ if changed:
++ import tomli_w
++
++ (member / "pyproject.toml").write_text(tomli_w.dumps(document), encoding="utf-8")
++ return member
+ specs = _legacy_requirements(plugin_dir)
- identity = hashlib.sha256(str(plugin_dir.resolve()).encode()).hexdigest()[:16]
- member = root / "plugin-deps" / identity
++ member = root / "plugin-deps" / key
+ member.mkdir(parents=True, exist_ok=True)
+ (member / "pyproject.toml").write_text(
- f'[project]\nname = "hermes-plugin-{identity}"\nversion = "0.0.0"\n'
++ f'[project]\nname = "hermes-plugin-{key}"\nversion = "0.0.0"\n'
+ 'requires-python = ">=3.11"\n'
+ f'dependencies = {json.dumps(specs)}\n[tool.uv]\npackage = false\n',
+ encoding="utf-8",
+ )
+ return member
+
+
+def scan_plugin(plugin_dir: Path) -> dict:
+ """Auto-pickup scan of one plugin dir: which dep surfaces it declares.
+ Priority (settled): pyproject (python), package.json (node sidecar),
+ packages.py (pm store binaries), legacy manifest deps (bridge)."""
+ found: dict = {
+ "pyproject": (plugin_dir / "pyproject.toml").is_file(),
+ "package_json": (plugin_dir / "package.json").is_file(),
+ "packages_py": (plugin_dir / "packages.py").is_file(),
+ "legacy_deps": _is_member_candidate(plugin_dir)
+ and not (plugin_dir / "pyproject.toml").is_file(),
+ "dir": plugin_dir,
+ }
+ return found
+
+
+def install_node_sidecar(
+ plugin_dir: Path,
+ *,
+ npm_bin: Optional[str] = None,
+ runner=subprocess.run,
+) -> Optional[str]:
+ """`npm ci` the plugin's package.json into ITS OWN node_modules —
+ the declared sidecar install (plugin-deps plan §B item 2; wired here).
+
+ Plugin-local (never a global npm prefix), pm's pinned npm when the
+ store has one (ambient PATH npm otherwise), gated by the lazy-install
+ policy, receipt-noted. Returns None on success, else why not.
+ """
+ package_json = plugin_dir / "package.json"
+ if not package_json.is_file():
+ return None # nothing to install
+
+ from pm.ensure import lazy_installs_allowed
+
+ if not lazy_installs_allowed():
+ return "lazy installs are disabled — run `hermes pm install` after enabling"
+
+ # a lockfile means reproducible `npm ci`; plain `npm install` otherwise
+ install_cmd = ["ci"] if (plugin_dir / "package-lock.json").is_file() else ["install"]
+ if npm_bin is None:
+ npm_bin = _node_npm_binary("npm")
+ if npm_bin is None:
+ return "npm not found (pm store or PATH)"
+
+ try:
+ proc = runner(
+ [npm_bin, *install_cmd, "--no-audit", "--no-fund"],
+ cwd=str(plugin_dir),
+ capture_output=True,
+ text=True,
+ timeout=900,
+ )
+ except Exception as exc:
+ return f"npm {install_cmd[0]} failed to run: {exc}"
+ if proc.returncode != 0:
+ tail = (proc.stderr or proc.stdout or "").strip()[-300:]
+ return f"npm {install_cmd[0]} exited {proc.returncode}: {tail}"
+ return None
+
+
+def _node_npm_binary(name: str) -> Optional[str]:
+ """pm's pinned npm from the store (store-first), PATH second."""
+ from pm.ensure import env_for
+
+ try:
+ env = env_for("npm")
+ except Exception:
+ env = None
+ if env:
+ path_value = env.get("PATH", "")
+ import shutil as _shutil
+
+ for d in path_value.split(os.pathsep):
+ if d:
+ candidate = Path(d) / ("npm.cmd" if os.name == "nt" else name)
+ if candidate.is_file():
+ return str(candidate)
+ import shutil as _shutil
+
+ return _shutil.which(name)
+
+
+def lock_and_sync(
+ plugin_dirs: list[Path],
+ extras: Optional[list[str]] = None,
+ *,
+ venv_dir: Path,
+ root: Optional[Path] = None,
+ env: Optional[dict] = None,
+ seed_lock: Optional[Path] = None,
+ frozen: bool = False,
+ replay: Optional[Path] = None,
+) -> None:
+ """Build the root, then `uv lock` + `uv sync --frozen --extra ...`.
+
+ Everything resolves into a parent-supplied STAGING surface: ``root``
+ pins the generated workspace dir, ``venv_dir`` pins
+ UV_PROJECT_ENVIRONMENT and ``seed_lock`` (optional) pins which
+ existing lock seeds the extension (default: the root's current
+ extended lock, else the committed core lock). ``env`` replaces the
+ ambient base environment when supplied; either way the subprocess
+ gets a COPY — the live process environment is never mutated. ``replay``
+ copies a recorded sibling workspace and uses its lock without resolution
+ or plugin discovery; it is reserved for restoring an existing selection.
+
+ Raises a CLASSIFIED InstallError on failure: ResolutionConflict only
+ for a confirmed resolver conflict; network, build and tool failures
+ stay generic InstallError — they are not evidence of a dependency
+ conflict and must not disable plugins.
+ """
+ from pm.ensure import uv as pm_uv
+
+ if replay is None:
+ generated, changed = _generate_pyproject(plugin_dirs, root)
+ if changed:
+ _seed_lock(generated, seed_lock)
+ else:
+ import shutil
+
+ if root is None or not (replay / "pyproject.toml").is_file() or not (replay / "uv.lock").is_file():
+ raise InstallError("venv", f"recorded workspace is missing: {replay}")
+ # Generation workspaces are siblings at the same depth. External
+ # member paths still resolve. Generated members move with the copy.
+ shutil.copytree(replay, root, ignore=shutil.ignore_patterns("__pycache__", ".venv", "build", "*.egg-info"))
+ generated = root
+ frozen = True
+
+ uv_bin, run_env = pm_uv(base_env=env)
+ if uv_bin is None:
+ raise InstallError("venv", "PM's uv and Python are required; run `hermes pm install`")
+ run_env.pop("UV_NO_CONFIG", None)
+ run_env["UV_PROJECT_ENVIRONMENT"] = str(venv_dir)
+
+ import subprocess
+
+ if not frozen:
+ lock = subprocess.run(
+ [uv_bin, "lock"], cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800
+ )
+ if lock.returncode != 0:
+ raise classify_uv_failure("lock", lock.returncode, lock.stderr or lock.stdout)
+
+ # --all-packages is REQUIRED: plain `uv sync --frozen` installs only the
+ # ROOT project's deps — workspace-member deps are locked by `uv lock`
+ # but silently never reach site-packages (probed live 2026-09-03: a
+ # member's pyfiglet stayed absent from site-packages under plain
+ # --frozen, present under --all-packages). The union's whole contract
+ # is that plugin deps ride the venv; without this flag every member
+ # install is a silent no-op.
+ cmd = [uv_bin, "sync", "--frozen", "--all-packages"]
+ for extra in sorted(set(extras or [])):
+ cmd += ["--extra", extra]
+ sync = subprocess.run(cmd, cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800)
+ if sync.returncode != 0:
+ # --frozen means the lock already resolved; a sync failure here is
+ # install/download/tooling, never a NEW resolution conflict.
+ raise classify_uv_failure(
+ "sync", sync.returncode, sync.stderr or sync.stdout
+ )
diff --cc pyproject.toml
index 44a69cc4d4a,d5e7131e763..f17f9c3b9db
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -49,6 -45,6 +49,7 @@@ dependencies =
"rich==14.3.3",
"tenacity==9.1.4",
"pyyaml==6.0.3",
++ "tomli-w==1.2.0", # Preserve relative dependency paths in staged plugin metadata.
"ruamel.yaml==0.18.17",
"requests==2.33.0", # CVE-2026-25645
"jinja2==3.1.6",
diff --cc tests/conftest.py
index e1471f456e8,bac63348691..fa83736e7cb
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -1012,11 -1001,9 +1012,12 @@@ def _ensure_current_event_loop(request)
# delivery is harmless.
_LIVE_SYSTEM_GUARD_BYPASS_MARK = "live_system_guard_bypass"
+ _GATEWAY_LOOKALIKE_MARK = "spawns_gateway_lookalike"
_REQUIRES_WAL_MARK = "requires_wal"
+# Tests may designate a temporary repo to exercise the real guard safely.
+_LIVE_GUARD_PROTECTED_GIT_ROOTS = (PROJECT_ROOT,)
+
def _wal_is_usable() -> bool:
"""True when Hermes will actually put a database into WAL mode here.
@@@ -1225,9 -1154,12 +1226,15 @@@ def pytest_configure(config): # noqa:
"(only for tests that genuinely need real os.kill / subprocess "
"behaviour — e.g. PTY tests that signal their own child).",
)
+ config.addinivalue_line(
+ "markers", "allow_real_home_io: explicitly bypass the test-only home I/O guard."
+ )
+ config.addinivalue_line(
+ "markers",
+ f"{_GATEWAY_LOOKALIKE_MARK}: the test spawns and reaps its own stub "
+ "child whose argv matches the gateway runtime matcher; only the "
+ "real-gateway spawn check is lifted, os.kill stays guarded.",
+ )
config.addinivalue_line(
"markers",
f"{_REQUIRES_WAL_MARK}: test needs the runtime to actually enable "
diff --cc tests/gateway/test_peer_dm_hidden_e2e.py
index 166697603f6,eed9ce45d38..ce216fa00a3
--- a/tests/gateway/test_peer_dm_hidden_e2e.py
+++ b/tests/gateway/test_peer_dm_hidden_e2e.py
@@@ -141,3 -141,40 +141,39 @@@ def test_hidden_lookup_requires_title_f
ids = [s["id"] for s in listing["data"]]
assert peer_gateway.hidden_id not in ids
assert "ordinary_1" in ids
+
+
+ @pytest.fixture()
+ def peer_gateway_compressed_hidden(peer_gateway):
+ """Aged Bot Mode footprint: the hidden canonical Bot Chat has a live
+ compression tip (issue #106165). The tip is untitled and hidden via the
+ lineage; the title lives only on the ended root."""
+ db = peer_gateway.db
+ tip_id = db.create_session(
+ "botchat_tip_1", "gateway_botmode", parent_session_id=peer_gateway.hidden_id)
+ db.end_session(peer_gateway.hidden_id, "compression")
+ db.set_session_hidden(peer_gateway.hidden_id, True) # lineage-hide root+tip
+ peer_gateway.tip_id = tip_id
+ return peer_gateway
+
+
+ def test_peer_dm_reaches_compressed_hidden_bot_chat_e2e(
+ peer_gateway_compressed_hidden, monkeypatch, capsys):
+ """Hidden canonical Bot Chat under compression: the peer lookup must still
+ resolve (to the live tip) instead of missing it and colliding with
+ UNIQUE(title) on create (HTTP 400, issue #106165)."""
+ gw = peer_gateway_compressed_hidden
+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": gw.url}})
+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: API_KEY)
+
+ rc = peer_cmd.cmd_peer(
+ SimpleNamespace(peer_action="dm", target="spark", message="disk status?", json=True)
+ )
+
+ assert rc == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["reply"] == "e2e reply to: disk status?"
+ assert payload["session_id"] == gw.tip_id
+
+ # No duplicate "Bot Chat" row was minted; the title still lives on the root.
+ assert gw.db.get_session_by_title("Bot Chat")["id"] == gw.hidden_id
-
diff --cc tests/hermes_cli/test_plugin_update_recovery.py
index 00000000000,00000000000..eb89e35d45a
new file mode 100644
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_update_recovery.py
@@@ -1,0 -1,0 +1,59 @@@
++"""Process death cannot leave new plugin code paired with the old dependency selection."""
++from __future__ import annotations
++
++import json
++import os
++from pathlib import Path
++import subprocess
++import sys
++
++import pytest
++
++
[email protected]("committed", [False, True])
++def test_boot_recovers_plugin_publication_after_process_death(tmp_path, committed):
++ home = tmp_path / "home"
++ target = home / "plugins" / "example"
++ target.mkdir(parents=True)
++ (target / "__init__.py").write_text("old code", encoding="utf-8")
++ metadata = target.parent / ".install-metadata.json"
++ metadata.write_text('{"example":{"revision":"old"}}\n', encoding="utf-8")
++ previous = metadata.read_bytes()
++ staged = tmp_path / "staged"
++ staged.mkdir()
++ (staged / "__init__.py").write_text("new code", encoding="utf-8")
++ project = tmp_path / "project"
++ project.mkdir()
++ env = {**os.environ, "HERMES_HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[2])}
++ program = '''
++from pathlib import Path
++import os,sys
++from hermes_cli.plugins_transaction import PluginPublication
++from hermes_cli.runtime_paths import runtime_facts_path
++from pm.lock import Facts
++project,staged,target = map(Path,sys.argv[1:4])
++pub = PluginPublication(project,staged,target,{"example":{"revision":"new"}})
++if sys.argv[4] == "True":
++ Facts(runtime_facts_path(project)).record_state("venv","new",[])
++os._exit(17)
++'''
++ child = subprocess.run([sys.executable, "-c", program, str(project), str(staged), str(target), str(committed)],
++ env=env, cwd=tmp_path, capture_output=True, text=True, timeout=30)
++ assert child.returncode == 17, child.stderr
++ recovery = '''
++from pathlib import Path
++import sys
++from hermes_cli.runtime_state import runtime_lock,recover_publication
++project=Path(sys.argv[1])
++with runtime_lock(project):
++ recover_publication(project)
++ recover_publication(project)
++'''
++ result = subprocess.run([sys.executable, "-c", recovery, str(project)], env=env, cwd=tmp_path,
++ capture_output=True, text=True, timeout=30)
++ assert result.returncode == 0, result.stderr
++ assert (target / "__init__.py").read_text(encoding="utf-8") == ("new code" if committed else "old code")
++ assert json.loads(metadata.read_text(encoding="utf-8"))["example"]["revision"] == ("new" if committed else "old")
++ if not committed:
++ assert metadata.read_bytes() == previous
++ assert not list(target.parent.glob(".previous-*"))
diff --cc tests/hermes_cli/test_plugin_update_transaction.py
index 00000000000,00000000000..b29a646d2f6
new file mode 100644
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_update_transaction.py
@@@ -1,0 -1,0 +1,159 @@@
++"""Catalog pins and custom Git updates publish only a validated dependency set."""
++from __future__ import annotations
++
++import json
++import os
++from pathlib import Path
++import subprocess
++
++import pytest
++
++from tests.pm.test_plugin_survival_contract import admission_env # noqa: F401
++
++
++def _commit(repo, message):
++ env = {**os.environ, "GIT_AUTHOR_NAME": "fixture", "GIT_AUTHOR_EMAIL": "[email protected]",
++ "GIT_COMMITTER_NAME": "fixture", "GIT_COMMITTER_EMAIL": "[email protected]"}
++ subprocess.run(["git", "add", "--all"], cwd=repo, env=env, check=True, capture_output=True)
++ subprocess.run(["git", "commit", "-qm", message], cwd=repo, env=env, check=True, capture_output=True)
++ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
++
++
++def _version(repo, version, *, broken=False, minimum=""):
++ from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION
++
++ (repo / "plugin.yaml").write_text(
++ f"name: transactional\nversion: {version}\nmanifest_version: {SUPPORTED_MANIFEST_VERSION}\n"
++ f"requires_hermes: '{minimum}'\n", encoding="utf-8")
++ (repo / "__init__.py").write_text(f"VERSION = {version!r}\ndef register(ctx):\n pass\n", encoding="utf-8")
++ deps = '["impossible-plugin-dep==1", "impossible-plugin-dep==2"]' if broken else '[]'
++ library = repo.parent / "shared-library"
++ library.mkdir(exist_ok=True)
++ (library / "pyproject.toml").write_text(
++ '[project]\nname="shared-library"\nversion="1"\nrequires-python=">=3.14"\n'
++ '[tool.uv]\npackage=false\n', encoding="utf-8")
++ if not broken:
++ deps = '["shared-library"]'
++ (repo / "pyproject.toml").write_text(
++ f'[project]\nname="transactional"\nversion="{version}"\nrequires-python=">=3.14"\n'
++ f'dependencies={deps}\n[tool.uv]\npackage=false\n'
++ '[tool.uv.sources]\nshared-library={path="../shared-library"}\n', encoding="utf-8")
++ return _commit(repo, version)
++
++
++def installed(admission_env, monkeypatch, request):
++ from hermes_cli import plugin_catalog, plugins_cmd, plugins_cmd_catalog
++
++ root, home = admission_env
++ repo = root / "plugin-origin"
++ repo.mkdir()
++ subprocess.run(["git", "init", "-qb", "main"], cwd=repo, check=True, capture_output=True)
++ first = _version(repo, "1.0.0")
++ catalog = request.param == "catalog"
++ state = {"sha": first}
++
++ def entry():
++ return plugin_catalog.PluginCatalogEntry(
++ name="transactional", repo=repo.as_uri(), sha=state["sha"], description="fixture", maintainer="fixture")
++
++ monkeypatch.setattr(plugin_catalog, "fetch_live_catalog", lambda **kwargs: None)
++ monkeypatch.setattr(plugin_catalog, "load_catalog", lambda catalog_dir=None: [entry()])
++ monkeypatch.setattr(plugin_catalog, "load_removed_list", lambda catalog_dir=None: [])
++ monkeypatch.setattr(plugins_cmd, "_scan_on_install_enabled", lambda: False)
++ if catalog:
++ target, _, _ = plugins_cmd_catalog.install_catalog_entry(entry(), force=False)
++ else:
++ target, _, _ = plugins_cmd._install_plugin_core(repo.as_uri(), force=False)
++ import shutil
++
++ shutil.copytree(repo.parent / "shared-library", target.parent / "shared-library")
++ plugins_cmd._set_plugin_enabled("transactional", enable=True)
++ return root, home, repo, target, state
++
++
[email protected]("installed", ["catalog", "custom"], indirect=True)
[email protected]("failure", ["dependencies", "version", "publication", "manifest"])
++def test_failed_update_keeps_code_metadata_config_and_environment(installed, monkeypatch, failure):
++ from hermes_cli import plugins_cmd
++ from hermes_cli.runtime_paths import selected_venv
++ from pm import paths
++ from pm.lock import Facts
++
++ root, home, repo, target, state = installed
++ selected = selected_venv(root / "core")
++ watched = [target / "plugin.yaml", target / "__init__.py", target / "pyproject.toml",
++ home / "config.yaml", home / "plugins/.install-metadata.json", paths.runtime_facts_path()]
++
++ before = {path: path.read_bytes() for path in watched}
++ old_head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip()
++ state["sha"] = _version(repo, "2.0.0", broken=failure == "dependencies",
++ minimum=">=999.0.0" if failure == "version" else "")
++ if failure == "manifest":
++ (repo / "plugin.yaml").write_text("name: [broken", encoding="utf-8")
++ state["sha"] = _commit(repo, "invalid manifest")
++ if failure == "publication":
++ def deny(*args, **kwargs):
++ raise OSError("fixture refuses environment publication")
++ monkeypatch.setattr(Facts, "record_state", deny)
++ result = plugins_cmd.dashboard_update_user_plugin("transactional")
++ assert result["ok"] is False, result
++ assert result.get("error")
++ assert selected_venv(root / "core") == selected
++ assert {path: path.read_bytes() for path in watched} == before
++ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == old_head
++
++
[email protected]("installed", ["catalog", "custom"], indirect=True)
++def test_successful_update_publishes_matching_code_and_durable_workspace(installed):
++ import tomllib
++ from hermes_cli import plugins_cmd
++ from hermes_cli.runtime_paths import selected_venv
++ from pm import paths
++ from pm.lock import Facts
++ from pm.packages import Venv
++
++ root, home, repo, target, state = installed
++ before = selected_venv(root / "core")
++ config = (home / "config.yaml").read_bytes()
++ state["sha"] = _version(repo, "2.0.0")
++ result = plugins_cmd.dashboard_update_user_plugin("transactional")
++ assert result["ok"] is True, result
++ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == state["sha"]
++ assert 'VERSION = \'2.0.0\'' in (target / "__init__.py").read_text(encoding="utf-8")
++ assert (home / "config.yaml").read_bytes() == config
++ fact = Facts(paths.runtime_facts_path()).get("venv")
++ assert selected_venv(root / "core") != before
++ assert fact["stamp"] == Venv().expected_stamp(fact["extras"])
++ workspace = Path(fact["resolved_lock"]).parent
++ document = tomllib.loads((workspace / "pyproject.toml").read_text(encoding="utf-8"))
++ members = document["tool"]["uv"]["workspace"]["members"]
++ assert members
++ for member in members:
++ path = (workspace / member).resolve()
++ assert path.is_relative_to(workspace)
++ assert (path / "pyproject.toml").is_file()
++ record = json.loads((home / "plugins/.install-metadata.json").read_text(encoding="utf-8"))["transactional"]
++ assert record["revision"] == state["sha"]
++
++ # A packaged member's source changes even when its dependency metadata does not.
++ previous_stamp = fact["stamp"]
++ (repo / "__init__.py").write_text("VERSION = 'code-only'\ndef register(ctx):\n pass\n", encoding="utf-8")
++ state["sha"] = _commit(repo, "code-only update")
++ result = plugins_cmd.dashboard_update_user_plugin("transactional")
++ assert result["ok"], result
++ record = json.loads((home / "plugins/.install-metadata.json").read_text(encoding="utf-8"))["transactional"]
++ assert Facts(paths.runtime_facts_path()).get("venv")["stamp"] != previous_stamp
++
++ from hermes_cli.plugins_updates import run_checks
++
++ def no_network(*args):
++ raise AssertionError("catalog pin must not consult a custom update source")
++
++ if record.get("catalog_name"):
++ state["sha"] = _version(repo, "3.0.0")
++ check = next(row for row in run_checks(home / "plugins", include_pip=False,
++ fetch=no_network, ls_remote=no_network)
++ if row.name == "transactional")
++ assert check.klass == "catalog" and check.update_available is True
++ assert check.current == record["revision"] and check.latest == state["sha"]
diff --cc tests/hermes_cli/test_plugins_cmd.py
index 7401d263622,4002698b0e7..1102b7c4b4a
--- a/tests/hermes_cli/test_plugins_cmd.py
+++ b/tests/hermes_cli/test_plugins_cmd.py
@@@ -399,29 -397,29 +399,18 @@@ class TestCmdInstall
class TestCmdUpdate:
"""Test the update command."""
-- @patch("hermes_cli.plugins_cmd._sanitize_plugin_name")
-- @patch("hermes_cli.plugins_cmd._plugins_dir")
-- @patch("hermes_cli.plugins_cmd.subprocess.run")
-- def test_update_git_pull_success(self, mock_run, mock_plugins_dir, mock_sanitize):
-- from hermes_cli.plugins_cmd import cmd_update
--
-- mock_plugins_dir_val = MagicMock()
-- mock_plugins_dir.return_value = mock_plugins_dir_val
-- mock_target = MagicMock()
-- mock_target.exists.return_value = True
-- mock_target.__truediv__ = lambda self, x: MagicMock(
-- exists=MagicMock(return_value=True)
-- )
-- mock_sanitize.return_value = mock_target
--
-- mock_run.side_effect = [
-- MagicMock(returncode=0, stdout="", stderr=""), # status: clean
-- MagicMock(returncode=0, stdout="Updated", stderr=""), # pull
-- ]
-
- cmd_update("test-plugin")
-
- assert mock_run.call_count == 2
++ def test_update_uses_the_shared_transaction(self, tmp_path, monkeypatch):
++ from hermes_cli import plugins_cmd as pc, plugins_transaction
+
- cmd_update("test-plugin")
-
- assert mock_run.call_count == 2
++ home = tmp_path / "home"
++ target = home / "plugins" / "test-plugin"
++ (target / ".git").mkdir(parents=True)
++ monkeypatch.setenv("HERMES_HOME", str(home))
++ seen = []
++ monkeypatch.setattr(plugins_transaction, "update_plugin", lambda path:
++ seen.append(path) or "Already up to date")
++ pc.cmd_update("test-plugin")
++ assert seen == [target]
@patch("hermes_cli.plugins_cmd._sanitize_plugin_name")
@patch("hermes_cli.plugins_cmd._plugins_dir")
@@@ -720,8 -722,8 +709,10 @@@ class TestSubdirInstallE2E
repo_root = tmp_path / "monorepo"
self._make_repo_with_subdir_plugin(repo_root)
-- plugins_dir = tmp_path / "installed"
-- plugins_dir.mkdir()
++ home = tmp_path / "home"
++ plugins_dir = home / "plugins"
++ plugins_dir.mkdir(parents=True)
++ monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)
identifier = f"file://{repo_root}#my-plugin"
@@@ -780,8 -782,8 +771,10 @@@
sp.run(["git", "init", "-q"], cwd=repo_root, check=True, env=env)
sp.run(["git", "add", "-A"], cwd=repo_root, check=True, env=env)
sp.run(["git", "commit", "-q", "-m", "init"], cwd=repo_root, check=True, env=env)
-- plugins_dir = tmp_path / "installed"
-- plugins_dir.mkdir()
++ home = tmp_path / "home"
++ plugins_dir = home / "plugins"
++ plugins_dir.mkdir(parents=True)
++ monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)
target, manifest, name = pc._install_plugin_core(
diff --cc tests/hermes_cli/test_plugins_cmd_catalog.py
index 00000000000,f42f1d01657..37dcb5f6e4f
mode 000000,100644..100644
--- a/tests/hermes_cli/test_plugins_cmd_catalog.py
+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py
@@@ -1,0 -1,98 +1,100 @@@
+ """Catalog-aware ``hermes plugins`` surface (hermes_cli/plugins_cmd_catalog.py): a bare catalog name installs
+ the PINNED sha and records provenance; the kill list blocks every install path (CLI needs an explicit
+ bypass, dashboard/TUI have none); ``update`` re-pins instead of pulling. Real git, file:// repos."""
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import shutil
+ import subprocess as sp
+ from pathlib import Path
+
+ import pytest
+
+ from hermes_cli import plugin_catalog as pc_cat
+ from hermes_cli import plugins_cmd as pc
+ from hermes_cli import plugins_cmd_catalog as cat
+
+ pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git not available")
+
+ _GIT_ENV = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",
+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}
+
+
+ def _commit(repo: Path, msg: str) -> str:
+ sp.run(["git", "add", "-A"], cwd=repo, check=True, env=_GIT_ENV)
+ sp.run(["git", "commit", "-q", "-m", msg], cwd=repo, check=True, env=_GIT_ENV)
+ return sp.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True).stdout.strip()
+
+
+ @pytest.fixture
+ def world(tmp_path, monkeypatch):
+ """A file:// plugin repo with two commits, a catalog pinned to the FIRST, an isolated plugins dir."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "plugin.yaml").write_text("name: cat-plugin\nversion: 1.0.0\ndescription: d\n")
+ (repo / "__init__.py").write_text("def register(ctx):\n pass\n")
+ sp.run(["git", "init", "-q"], cwd=repo, check=True, env=_GIT_ENV)
+ sha1 = _commit(repo, "v1")
+ (repo / "__init__.py").write_text("def register(ctx):\n pass # v2\n")
+ sha2 = _commit(repo, "v2")
+
- plugins_dir = tmp_path / "plugins"
- plugins_dir.mkdir()
++ home = tmp_path / "home"
++ plugins_dir = home / "plugins"
++ plugins_dir.mkdir(parents=True)
++ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)
+ monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: False)
+ monkeypatch.setattr(pc, "_console", lambda: type("C", (), {"print": lambda *a, **k: None})())
+
+ # Catalog: one entry pinned to sha1, mutable via state["pin"]; kill list via state["removed"]. The
+ # real loader is https-only, so the fixture entry is built directly (file:// repo).
+ state = {"pin": sha1, "removed": []}
+
+ def _entries():
+ return [pc_cat.PluginCatalogEntry(name="cat-plugin", repo=repo.as_uri(), sha=state["pin"],
+ description="d", maintainer="t")]
+
+ monkeypatch.setattr(pc_cat, "load_catalog", lambda catalog_dir=None: _entries())
+ monkeypatch.setattr(pc_cat, "fetch_live_catalog", lambda **_: None) # in-tree only, no network
+ monkeypatch.setattr(pc_cat, "load_removed_list", lambda catalog_dir=None: list(state["removed"]))
+ return {"repo": repo, "sha1": sha1, "sha2": sha2, "plugins_dir": plugins_dir, "state": state}
+
+
+ def _head(path: Path) -> str:
+ return sp.run(["git", "rev-parse", "HEAD"], cwd=path, capture_output=True, text=True).stdout.strip()
+
+
+ def test_catalog_name_installs_pinned_sha_with_sidecar_then_update_repins(world, monkeypatch):
+ entry = pc_cat.get_live_catalog_entry("cat-plugin")
+ assert entry is not None
+ target, _m, name = cat.install_catalog_entry(entry, force=False)
+ assert name == "cat-plugin"
+ assert _head(target) == world["sha1"] != world["sha2"] # pinned, not HEAD
- sidecar = json.loads((target / cat.CATALOG_SIDECAR).read_text())
++ sidecar = cat.catalog_install_record(target)
+ assert (sidecar["catalog_name"], sidecar["sha"]) == ("cat-plugin", world["sha1"])
+ assert cat.catalog_annotation(target) == f"catalog:community@{world['sha1'][:8]}"
+
+ # Dashboard update on a catalog install = re-pin. Pin unchanged → no-op.
+ assert pc.dashboard_update_user_plugin("cat-plugin") == {
+ "ok": True, "name": "cat-plugin", "sha": world["sha1"], "unchanged": True}
+ # Bump the catalog pin → the checkout moves to exactly that sha.
+ world["state"]["pin"] = world["sha2"]
+ assert pc.dashboard_update_user_plugin("cat-plugin")["unchanged"] is False
+ assert _head(world["plugins_dir"] / "cat-plugin") == world["sha2"]
+
+
+ def test_kill_list_blocks_cli_dashboard_and_tui_paths(world, monkeypatch):
+ world["state"]["removed"].append(
+ pc_cat.RemovedEntry(name="cat-plugin", repo=world["repo"].as_uri(), reason="malware"))
+ # Dashboard/TUI: catalog name AND raw repo URL both refused, no bypass parameter exists.
+ assert "malware" in pc.dashboard_install_plugin("", force=False, enable=False, catalog_name="cat-plugin")["error"]
+ assert "malware" in pc.dashboard_install_plugin(world["repo"].as_uri(), force=False, enable=False)["error"]
+ assert not (world["plugins_dir"] / "cat-plugin").exists()
+ # CLI: refused by default, `--allow-removed` installs anyway.
+ with pytest.raises(SystemExit):
+ pc.cmd_install("cat-plugin", enable=False)
+ pc.cmd_install("cat-plugin", enable=False, allow_removed=True)
- assert (world["plugins_dir"] / "cat-plugin" / cat.CATALOG_SIDECAR).exists()
++ assert cat.catalog_install_record(world["plugins_dir"] / "cat-plugin") is not None
+ assert cat.removed_annotation("cat-plugin", world["plugins_dir"] / "cat-plugin") == "malware"
diff --cc tests/hermes_cli/test_plugins_update_sync.py
index b41288cc6b5,00000000000..51c5620a955
mode 100644,000000..100644
--- a/tests/hermes_cli/test_plugins_update_sync.py
+++ b/tests/hermes_cli/test_plugins_update_sync.py
@@@ -1,105 -1,0 +1,85 @@@
- """Tests: cmd_update post-pull union re-sync for member-manifest plugins.
-
- Task 5 of the plugin auto-update plan: a plugin update whose pull changed
- its pyproject pins must re-sync the venv union (new deps land); a sync
- failure surfaces the resolver reason but never fails the update — the
- plugin code is already updated.
- """
-
++"""Every update surface validates staged code before changing an active plugin."""
+from __future__ import annotations
+
- import json
- from pathlib import Path
- from unittest.mock import patch
++import importlib
++import subprocess
+
+import pytest
+
- import hermes_cli.plugins_cmd as pc
-
-
- @pytest.fixture
- def plugin_env(tmp_path, monkeypatch):
- """An installed, provenanced, enabled plugin + injectable seams."""
- home = tmp_path / "home"
- plugins = home / "plugins"
- plug = plugins / "plug"
- (plug / ".git").mkdir(parents=True)
- (plug / "plugin.yaml").write_text("name: plug\n", encoding="utf-8")
- (home / "config.yaml").write_text("plugins:\n enabled: [plug]\n", encoding="utf-8")
- plugins.mkdir(parents=True, exist_ok=True)
- (plugins / ".install-metadata.json").write_text(
- json.dumps({"plug": {"pinned": False, "revision": "a" * 40,
- "source": "https://example/o/r"}}),
- encoding="utf-8",
- )
- monkeypatch.setenv("HERMES_HOME", str(home))
- import hermes_constants
-
- monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)
- monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins)
- monkeypatch.setattr(
- pc, "_scan_on_install_enabled", lambda: False
- )
- monkeypatch.setattr(
- pc, "_git_pull_plugin_dir",
- lambda target: (True, "ok"),
- )
- monkeypatch.setattr(pc, "_resolve_git_executable", lambda: None)
- monkeypatch.setattr(pc, "_read_install_metadata", lambda: {
- "plug": {"pinned": False, "revision": "a" * 40,
- "source": "https://example/o/r"}
- })
- monkeypatch.setattr(pc, "_write_install_metadata", lambda m: None)
- monkeypatch.setattr(pc, "_get_enabled_set", lambda: {"plug"})
- monkeypatch.setattr(pc, "_get_disabled_set", lambda: set())
- monkeypatch.setattr(pc, "_copy_example_files", lambda t, c: None)
- return plug
-
-
- def test_member_plugin_triggers_post_pull_sync(plugin_env, monkeypatch):
- (plugin_env / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- synced = []
- import pm
-
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, **k: synced.append(extras))
- pc.cmd_update("plug")
- assert synced == [None] # explicit sync with recorded extras
-
-
- def test_update_scans_once_after_pull(plugin_env, monkeypatch):
- """C04: exactly ONE post-pull security scan — the rescan pipeline's, not a
- duplicated inline copy (which crashed with NameError on an undefined name)."""
- import tools.plugin_guard as guard
-
- scans = []
- monkeypatch.setattr(
- guard, "scan_plugin", lambda target, source: scans.append(source)
- )
- monkeypatch.setattr(
- guard, "should_allow_plugin_install", lambda result, **k: (True, "")
- )
- monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: True)
- pc.cmd_update("plug")
- assert scans == ["plug"]
-
-
- def test_plain_plugin_skips_sync(plugin_env, monkeypatch):
- # no pyproject.toml — nothing to union
- import pm
++from tests.hermes_cli.test_plugin_update_transaction import installed, _version # noqa: F401
++from tests.pm.test_plugin_survival_contract import admission_env # noqa: F401
+
- synced = []
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, **k: synced.append(extras))
- pc.cmd_update("plug")
- assert synced == []
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
++def test_cli_update_scan_refusal_keeps_the_installed_tree(installed, monkeypatch):
++ from hermes_cli import plugins_cmd as pc
+
- def test_sync_failure_surfaces_but_update_succeeds(plugin_env, monkeypatch, capsys):
- (plugin_env / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- import pm
-
- def boom(extras=None, **k):
- raise pm.InstallError("venv", "uv lock exited 1: unsatisfiable")
++ _, home, repo, target, state = installed
++ old = (target / "__init__.py").read_bytes()
++ before = (home / "config.yaml").read_bytes()
++ state["sha"] = _version(repo, "2.0.0")
++ scans = []
+
- monkeypatch.setattr(pm, "sync_venv", boom)
- # must NOT raise — the plugin code is already updated
- pc.cmd_update("plug")
++ def refuse(staged, source, **kwargs):
++ scans.append(staged)
++ assert staged != target
++ assert (target / "__init__.py").read_bytes() == old
++ raise pc.PluginScanBlocked("fixture refuses candidate")
++
++ monkeypatch.setattr(pc, "_scan_plugin_tree", refuse)
++ with pytest.raises(SystemExit):
++ pc.cmd_update("transactional", interactive=False)
++ assert len(scans) == 1
++ assert (target / "__init__.py").read_bytes() == old
++ assert (home / "config.yaml").read_bytes() == before
++
++
[email protected]("installed", ["catalog", "custom"], indirect=True)
++def test_disabled_update_does_not_change_dependencies_or_enablement(installed, monkeypatch):
++ from hermes_cli import plugins_cmd as pc
++ from pm import paths
++
++ _, home, repo, target, state = installed
++ pc._set_plugin_enabled("transactional", enable=False)
++ config = (home / "config.yaml").read_bytes()
++ facts = paths.runtime_facts_path().read_bytes()
++ state["sha"] = _version(repo, "2.0.0")
++ monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv",
++ lambda **kwargs: pytest.fail("disabled plugin changed the dependency selection"))
++ result = pc.dashboard_update_user_plugin("transactional")
++ assert result["ok"], result
++ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == state["sha"]
++ assert (home / "config.yaml").read_bytes() == config
++ assert paths.runtime_facts_path().read_bytes() == facts
++
++
[email protected]("installed", ["catalog", "custom"], indirect=True)
++def test_enablement_before_lock_acquisition_cannot_skip_validation(installed, monkeypatch):
++ from contextlib import contextmanager
++ from hermes_cli import plugins_cmd as pc, runtime_state
++ from pm import paths
++
++ _, home, repo, target, state = installed
++ pc._set_plugin_enabled("transactional", enable=False)
++ watched = [target / "__init__.py", target / "pyproject.toml", home / "plugins/.install-metadata.json"]
++ before = {path: path.read_bytes() for path in watched}
++ state["sha"] = _version(repo, "2.0.0", broken=True)
++ lock = runtime_state.runtime_lock
++ enabled = {}
++
++ @contextmanager
++ def enable_before_acquiring_lock(project):
++ if not enabled:
++ enabled["begun"] = True
++ pc._set_plugin_enabled("transactional", enable=True)
++ enabled["config"] = (home / "config.yaml").read_bytes()
++ enabled["facts"] = paths.runtime_facts_path().read_bytes()
++ with lock(project):
++ yield
++
++ monkeypatch.setattr(runtime_state, "runtime_lock", enable_before_acquiring_lock)
++ result = pc.dashboard_update_user_plugin("transactional")
++ assert result["ok"] is False, result
++ assert {path: path.read_bytes() for path in watched} == before
++ assert (home / "config.yaml").read_bytes() == enabled["config"]
++ assert paths.runtime_facts_path().read_bytes() == enabled["facts"]
diff --cc tests/hermes_cli/test_web_plugins_catalog.py
index 00000000000,26c80aa440c..f925acf7778
mode 000000,100644..100644
--- a/tests/hermes_cli/test_web_plugins_catalog.py
+++ b/tests/hermes_cli/test_web_plugins_catalog.py
@@@ -1,0 -1,77 +1,80 @@@
+ """Dashboard plugin-catalog surface: GET /api/dashboard/plugins/catalog merges installed state (via the
-``.hermes-catalog.json`` sidecar) and the install endpoint has NO kill-list bypass."""
++shared install record) and the install endpoint has NO kill-list bypass."""
+
+ from __future__ import annotations
+
+ import json
+
+ import pytest
+ import yaml
+
+ from hermes_cli import plugin_catalog as pc_cat
+
+ VALID_SHA = "38fe0fb53eff98d477f807432e965429e665ca33"
+ OTHER_SHA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+
+
+ @pytest.fixture
+ def client(monkeypatch, tmp_path, _isolate_hermes_home):
+ try:
+ from starlette.testclient import TestClient
+ except ImportError:
+ pytest.skip("fastapi/starlette not installed")
+ import hermes_state
+ from hermes_constants import get_hermes_home
+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
+
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
+ catalog_dir = tmp_path / "catalog"
+ catalog_dir.mkdir()
+ (catalog_dir / "alpha-plugin.yaml").write_text(yaml.safe_dump({
+ "name": "alpha-plugin", "repo": "https://github.com/example/alpha-plugin", "sha": VALID_SHA,
+ "description": "d", "maintainer": "Example", "tier": "official",
+ "capabilities": {"provides_tools": ["tool_a"], "requires_env": ["EXAMPLE_API_KEY"]}}))
+ (catalog_dir / "removed.yaml").write_text(yaml.safe_dump({"removed": [
+ {"name": "bad-plugin", "repo": "https://github.com/evil/bad-plugin", "reason": "exfiltrated env vars"}]}))
+ monkeypatch.setattr(pc_cat, "get_catalog_dir", lambda: catalog_dir)
+ monkeypatch.setattr(pc_cat, "fetch_live_catalog", lambda **_: None)
+
+ c = TestClient(app)
+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ return c
+
+
+ def _install(name: str, sidecar: dict | None):
+ from hermes_constants import get_hermes_home
+ d = get_hermes_home() / "plugins" / name
+ d.mkdir(parents=True)
+ (d / "plugin.yaml").write_text(yaml.safe_dump({"name": name, "version": "1.0", "description": "x"}))
+ if sidecar:
- (d / ".hermes-catalog.json").write_text(json.dumps(sidecar))
++ (d.parent / ".install-metadata.json").write_text(json.dumps({name: {
++ "catalog_name": sidecar["catalog_name"], "revision": sidecar["sha"],
++ "catalog_tier": sidecar["tier"], "source": "https://github.com/example/alpha-plugin",
++ }}), encoding="utf-8")
+
+
+ def test_catalog_endpoint_merges_installed_state_from_sidecar(client):
+ from starlette.testclient import TestClient
+ from hermes_cli.web_server import app
+ assert TestClient(app).get("/api/dashboard/plugins/catalog").status_code == 401
+
+ # Manifest name differs from the catalog name (the common case): matched through the sidecar.
+ _install("alpha", {"catalog_name": "alpha-plugin", "sha": OTHER_SHA, "tier": "official"})
+ data = client.get("/api/dashboard/plugins/catalog").json()
+ [entry] = data["entries"]
+ assert (entry["name"], entry["sha_short"], entry["capabilities"]["provides_tools"]) == ("alpha-plugin", VALID_SHA[:7], ["tool_a"])
+ assert "tool_a" in entry["capability_summary"]
+ assert (entry["installed"], entry["installed_sha"], entry["update_available"]) == (True, OTHER_SHA, True)
+ assert entry["runtime_status"] == "inactive"
+ assert data["removed"][0]["reason"] == "exfiltrated env vars"
+
+
+ def test_install_endpoint_refuses_removed_plugins_with_no_bypass(client, monkeypatch):
+ from hermes_cli import plugins_cmd
+ monkeypatch.setattr(plugins_cmd, "_install_plugin_core", lambda *a, **k: pytest.fail("kill-listed install ran"))
+ for body in ({"identifier": "https://github.com/evil/bad-plugin.git"},
+ {"identifier": "", "catalog_name": "bad-plugin"}, {"identifier": "evil/bad-plugin"}):
+ resp = client.post("/api/dashboard/agent-plugins/install", json=body)
+ assert resp.status_code == 400, body
+ assert "removed" in resp.json()["detail"] or "not in the Hermes plugin catalog" in resp.json()["detail"]
+ assert client.post("/api/dashboard/agent-plugins/install", json={"identifier": ""}).status_code == 400
diff --cc tests/pm/test_workspace.py
index 763102f04f6,00000000000..6a361b7f02a
mode 100644,000000..100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@@ -1,371 -1,0 +1,375 @@@
+"""pm.workspace: the generated uv-workspace root for plugin deps.
+
+The workspace root is a pm-GENERATED project (never the committed
+pyproject.toml — sealed installs are read-only and member lists are
+machine-specific). Its pyproject = core's pyproject verbatim +
+``[tool.uv.workspace] members`` pointing at each enabled plugin dir via
+relative ``../``-escaping paths (proven to resolve). ``uv lock`` unions
+core + plugin deps into ONE lock; conflict = loud refusal.
+"""
+
+from __future__ import annotations
+
+import importlib
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import pm.workspace as ws
+
+
+def layout(tmp_path, monkeypatch):
+ """A fake install: core repo with pyproject, plugin dirs, store."""
+ core = tmp_path / "core"
+ core.mkdir()
+ (core / "pyproject.toml").write_text(
+ "[project]\n"
+ 'name = "hermes-agent"\n'
+ 'version = "0.1.0"\n'
+ 'requires-python = ">=3.11"\n'
+ 'dependencies = ["httpx==0.28.1"]\n',
+ encoding="utf-8",
+ )
+ plugins = tmp_path / "home" / "plugins"
+ plug_a = plugins / "plug-a"
+ plug_a.mkdir(parents=True)
+ (plug_a / "plugin.yaml").write_text("name: plug-a\n", encoding="utf-8")
+ (plug_a / "pyproject.toml").write_text(
+ "[project]\nname = \"plug-a\"\nversion = \"0.1.0\"\n"
+ 'requires-python = ">=3.11"\ndependencies = ["rich==13.9.4"]\n',
+ encoding="utf-8",
+ )
+ store = tmp_path / "store"
+ store.mkdir()
+ monkeypatch.setattr(ws.paths, "repo_root", lambda: core)
+ monkeypatch.setattr(ws.paths, "store_root", lambda: store)
+ return tmp_path, core, plug_a, store
+
+
+def test_workspace_root_is_per_install_not_in_the_store(layout):
+ from hermes_cli.runtime_paths import install_state_dir
+ _, core, _, store = layout
+ assert ws.workspace_root() == install_state_dir(core) / ".pm-workspace"
+ assert not ws.workspace_root().is_relative_to(store)
+
+
+def test_build_writes_core_pyproject_verbatim(layout):
+ _, core, plug_a, _ = layout
+ root = ws.build_root([plug_a])
+ text = (root / "pyproject.toml").read_text(encoding="utf-8")
+ core_text = (core / "pyproject.toml").read_text(encoding="utf-8")
+ # core's project table is carried verbatim (name, deps, requires-python)
+ assert 'name = "hermes-agent"' in text
+ assert 'dependencies = ["httpx==0.28.1"]' in text
+ assert 'requires-python = ">=3.11"' in text
+ # nothing else was invented
+ for line in core_text.strip().splitlines():
+ assert line in text
+
+
- def test_members_are_relative_paths_escaping_the_root(layout):
++def test_members_keep_their_source_with_the_generation(layout):
++ import tomllib
++
+ _, _, plug_a, _ = layout
+ root = ws.build_root([plug_a])
- text = (root / "pyproject.toml").read_text(encoding="utf-8")
- assert "[tool.uv.workspace]" in text
- # member must be the relative path from the root to the plugin dir
- expected = ws._member_rel(root, plug_a)
- assert f'"{expected}"' in text
- assert expected.startswith(".."), "member must escape the generated root"
++ document = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
++ [relative] = document["tool"]["uv"]["workspace"]["members"]
++ copied = root / relative / "pyproject.toml"
++ assert copied.resolve().is_relative_to(root.resolve())
++ before = copied.read_bytes()
++ assert before == (plug_a / "pyproject.toml").read_bytes()
++ (plug_a / "pyproject.toml").write_bytes(b"changed after publication")
++ assert copied.read_bytes() == before
+
+
+def test_build_is_idempotent(layout):
+ _, _, plug_a, _ = layout
+ ws.build_root([plug_a])
+ first = (ws.workspace_root() / "pyproject.toml").read_text(encoding="utf-8")
+ ws.build_root([plug_a])
+ second = (ws.workspace_root() / "pyproject.toml").read_text(encoding="utf-8")
+ assert first == second
+
+
+def test_zero_plugins_still_builds_a_root_with_no_members(layout):
+ _, _, _, _ = layout
+ root = ws.build_root([])
+ text = (root / "pyproject.toml").read_text(encoding="utf-8")
+ assert 'name = "hermes-agent"' in text
+ assert "[tool.uv.workspace]" not in text or "members = []" in text
+
+
+def test_member_stamp_hash_changes_with_plugin_set(layout):
+ _, _, plug_a, _ = layout
+ stamp_empty = ws.members_stamp([])
+ stamp_a = ws.members_stamp([plug_a])
+ stamp_b = ws.members_stamp([plug_a, plug_a]) # dedupes to same set
+ assert stamp_empty != stamp_a
+ assert stamp_a == stamp_b
+
+
+def test_member_stamp_changes_when_pyproject_content_changes(tmp_path):
+ """Task 4 contract: a pulled plugin with changed pins must move the
+ stamp — path-only hashing left dep bumps invisible to the venv sync."""
+ plug = tmp_path / "plug"
+ plug.mkdir()
+ (plug / "pyproject.toml").write_text(
+ 'dependencies = ["pkg==1.0.0"]\n', encoding="utf-8"
+ )
+ before = ws.members_stamp([plug])
+ # the plugin update: same dir, new pins
+ (plug / "pyproject.toml").write_text(
+ 'dependencies = ["pkg==2.0.0"]\n', encoding="utf-8"
+ )
+ after = ws.members_stamp([plug])
+ assert before != after
+ # no pyproject at all: still hashable (the dir identity carries it)
+ bare = tmp_path / "bare"
+ bare.mkdir()
+ assert ws.members_stamp([bare]) != before
+
+
+def test_member_stamp_missing_pyproject_does_not_crash(tmp_path):
+ """A member dir whose pyproject vanished mid-scan hashes on path only."""
+ plug = tmp_path / "ghost"
+ plug.mkdir()
+ (plug / "pyproject.toml").write_text("x\n", encoding="utf-8")
+ first = ws.members_stamp([plug])
+ (plug / "pyproject.toml").unlink()
+ second = ws.members_stamp([plug])
+ assert first != second # content term dropped out, stamp moved
+
+
+def test_enabled_member_dirs_finds_enabled_dep_plugins(tmp_path, monkeypatch):
+ plugins = tmp_path / "plugins"
+ plugins.mkdir(parents=True)
+
+ # modern plugin: pyproject.toml
+ modern = plugins / "modern-plug"
+ modern.mkdir()
+ (modern / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+
+ # legacy plugin: pip_dependencies in plugin.yaml, no pyproject
+ legacy = plugins / "legacy-plug"
+ legacy.mkdir()
+ (legacy / "plugin.yaml").write_text(
+ "name: legacy-plug\npip_dependencies:\n - \"requests>=2\"\n",
+ encoding="utf-8",
+ )
+
+ # dep-less plugin: neither — not a member even when enabled
+ plain = plugins / "plain-plug"
+ plain.mkdir()
+ (plain / "plugin.yaml").write_text("name: plain-plug\n", encoding="utf-8")
+
+ # dep-carrying but NOT-ENABLED plugin — must not join the union
+ orphan = plugins / "orphan-plug"
+ orphan.mkdir()
+ (orphan / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+
+ # enabled order = enable recency (legacy enabled first/older, modern
+ # newest LAST) — order must carry through for the bisect tiebreak.
+ monkeypatch.setattr(
+ "pm.plugins_state.enabled_plugins_ordered",
+ lambda: {plugins: ["legacy-plug", "modern-plug", "plain-plug"]},
+ )
+ found = ws.enabled_member_dirs()
+ names = [p.name for p in found]
+ assert names == ["legacy-plug", "modern-plug"]
+ assert "orphan-plug" not in names
+
+
+def test_enabled_member_dirs_empty_when_nothing_enabled(tmp_path, monkeypatch):
+ plugins = tmp_path / "plugins"
+ plugins.mkdir(parents=True)
+ member = plugins / "member"
+ member.mkdir()
+ (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+
+ monkeypatch.setattr(
+ "pm.plugins_state.enabled_plugins_ordered", lambda: {}
+ )
+ assert ws.enabled_member_dirs() == []
+
+
+def test_scan_plugin_classifies_dep_surfaces(tmp_path):
+ full = tmp_path / "full-plug"
+ full.mkdir()
+ for name in ("pyproject.toml", "package.json", "packages.py", "plugin.yaml"):
+ (full / name).write_text("x\n", encoding="utf-8")
+ scan = ws.scan_plugin(full)
+ assert scan["pyproject"] and scan["package_json"] and scan["packages_py"]
+ assert not scan["legacy_deps"]
+
+ legacy = tmp_path / "legacy-plug"
+ legacy.mkdir()
+ (legacy / "plugin.yaml").write_text(
+ "name: legacy\npip_dependencies:\n - \"x>=1\"\n", encoding="utf-8"
+ )
+ scan = ws.scan_plugin(legacy)
+ assert scan["legacy_deps"] and not scan["pyproject"]
+
+
+def test_enabled_member_dirs_ignores_non_profile_entries(tmp_path, monkeypatch):
+ import pm.plugins_state as pstate
+
+ home = tmp_path / "home"
+ profiles = home / "profiles"
+ profiles.mkdir(parents=True)
+ member = profiles / "work" / "plugins" / "member"
+ member.mkdir(parents=True)
+ (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ (profiles / "work" / "config.yaml").write_text(
+ "plugins:\n enabled: [member]\n", encoding="utf-8",
+ )
+ (profiles / "README.txt").write_text("not a profile", encoding="utf-8")
+ monkeypatch.setattr("hermes_cli.runtime_paths.dependency_home_root", lambda: home)
+
+ assert pstate._all_homes() == [home, profiles / "work"]
+ assert ws.enabled_member_dirs() == [member]
+
+
+# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---
+
+
+def test_classify_resolver_conflict_is_resolutionconflict():
+ from pm.package import InstallError
+ from pm.workspace import ResolutionConflict, classify_uv_failure
+
+ err = classify_uv_failure(
+ "lock", 1,
+ " x No solution found for `hermes-agent>=0.1.0` because only the "
+ "following versions are available:\n",
+ )
+ assert isinstance(err, ResolutionConflict)
+ assert isinstance(err, InstallError)
+ assert "no solution found" in str(err).lower()
+
+
+def test_classify_network_failure_stays_generic():
+ from pm.workspace import ResolutionConflict, classify_uv_failure
+
+ err = classify_uv_failure("lock", 1, "error: Failed to fetch https://pypi.org (timed out)")
+ assert not isinstance(err, ResolutionConflict)
+
+
+def test_sync_failure_is_never_a_conflict(tmp_path, monkeypatch):
+ """--frozen: the lock already resolved, so a sync failure (download,
+ build, tooling) must stay generic — it must not disable plugins."""
+ from pm.package import InstallError
+ from pm.workspace import ResolutionConflict
+
+ class FakeProc:
+ returncode = 1
+ stderr = "error: Failed to download wheel (connection reset)"
+ stdout = ""
+
+ monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (Path("/x/ws"), False))
+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
+ lambda **kwargs: ("uv", {"UV_CACHE_DIR": "/x/cache", "UV_PYTHON": "pm-python"}))
+
+ captured = {}
+
+ def fake_run(cmd, **kwargs):
+ captured["cmd"] = cmd
+ return FakeProc()
+
+ monkeypatch.setattr(ws.subprocess, "run", fake_run)
+ with pytest.raises(InstallError) as excinfo:
+ ws.lock_and_sync([], [], venv_dir=tmp_path / "candidate")
+ assert not isinstance(excinfo.value, ResolutionConflict)
+
+
+def test_staging_root_and_env_are_honored_without_live_mutation(monkeypatch, tmp_path):
+ """lock_and_sync must resolve into the PARENT-SUPPLIED staging root +
+ venv, pass a COPY of the environment (never mutate the live one), and
+ leave the default generated root untouched."""
+ staging = tmp_path / "staging-ws"
+ staging.mkdir()
+
+ seen = {}
+
+ class FakeProc:
+ returncode = 0
+ stderr = ""
+ stdout = ""
+
+ def fake_run(cmd, cwd=None, env=None, **kwargs):
+ seen["cwd"] = cwd
+ seen["env"] = env
+ return FakeProc()
+
+ monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (staging, False))
+ monkeypatch.setattr(
+ importlib.import_module("pm.ensure"), "uv",
+ lambda **kwargs: ("uv", {**(kwargs.get("base_env") or {}),
+ "UV_CACHE_DIR": "/x/cache", "UV_PYTHON": "pm-python"}),
+ )
+ monkeypatch.setattr(ws.subprocess, "run", fake_run)
+
+ live_key = "PM_WORKSPACE_TEST_SENTINEL"
+ os.environ[live_key] = "live"
+ try:
+ ws.lock_and_sync(
+ [], [], venv_dir=tmp_path / "staging-venv", root=staging,
+ env={"PATH": "/staged/bin", live_key: "staged"},
+ )
+
+ assert Path(seen["cwd"]) == staging
+ assert seen["env"][live_key] == "staged" # staged env wins
+ assert seen["env"]["UV_CACHE_DIR"] == "/x/cache" # uv_env layered on top
+ assert seen["env"]["UV_PROJECT_ENVIRONMENT"] == str(tmp_path / "staging-venv")
+ assert seen["env"]["UV_PYTHON"] == "pm-python"
+ assert os.environ[live_key] == "live" # live env untouched
+ finally:
+ del os.environ[live_key]
+
+
+def test_changed_root_seeds_from_committed_lock_unchanged_keeps_extended(
+ layout, monkeypatch, tmp_path
+):
+ """Seed the CURRENT resolution without writing shipped bytes: a fresh
+ root seeds from the committed lock; an existing root seeds from its
+ own extended lock; an explicit parent-supplied seed_lock wins."""
+ _, core, plug_a, store = layout
+ (core / "uv.lock").write_bytes(b"committed-bytes\n")
+
+ class FakeProc:
+ returncode = 0
+ stderr = ""
+ stdout = ""
+
+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
+ lambda **kwargs: ("uv", {"UV_PYTHON": "pm-python"}))
+ monkeypatch.setattr(ws.subprocess, "run", lambda cmd, **k: FakeProc())
+
+ root = ws.workspace_root()
+ venv = tmp_path / "venv"
+
+ # First sync: fresh root -> seeded from the COMMITTED lock.
+ ws.lock_and_sync([plug_a], [], venv_dir=venv)
+ assert (root / "uv.lock").read_bytes() == b"committed-bytes\n"
+
+ # Changed surface (new member), root's own EXTENDED lock present ->
+ # the current extended resolution is the seed, not the committed one.
+ (root / "uv.lock").write_bytes(b"extended-bytes\n")
+ plug_b = layout[0] / "home" / "plugins" / "plug-b"
+ plug_b.mkdir(parents=True)
+ (plug_b / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ ws.lock_and_sync([plug_a, plug_b], [], venv_dir=venv)
+ assert (root / "uv.lock").read_bytes() == b"extended-bytes\n"
+
+ # Parent-supplied seed_lock wins over both.
+ other = tmp_path / "parent-extended.lock"
+ other.write_bytes(b"parent-bytes\n")
+ plug_c = layout[0] / "home" / "plugins" / "plug-c"
+ plug_c.mkdir(parents=True)
+ (plug_c / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ ws.lock_and_sync([plug_a, plug_b, plug_c], [], venv_dir=venv, seed_lock=other)
+ assert (root / "uv.lock").read_bytes() == b"parent-bytes\n"
+
+ # Shipped core lock untouched throughout.
+ assert (core / "uv.lock").read_bytes() == b"committed-bytes\n"
diff --cc tests/run_agent/test_multimodal_tool_content_recovery.py
index e2c91e3fb23,7119310e808..a8ebb279b85
--- a/tests/run_agent/test_multimodal_tool_content_recovery.py
+++ b/tests/run_agent/test_multimodal_tool_content_recovery.py
@@@ -196,3 -196,42 +196,41 @@@ class TestRecoveryEndToEndClassificatio
)
result = classify_api_error(err, provider="alibaba", model="qwen3.5-plus")
assert result.reason == FailoverReason.multimodal_tool_content_unsupported
+
+ def test_opencode_go_422_console_go_classifies(self):
+ """Regression test for #104731: Console Go relay HTTP 422 on list-type tool content."""
+ err = _FakeApiError(
+ status_code=422,
+ message=(
+ "Error code: 422 - {'error': {'param': 'messages.67.tool.content.str', "
+ "'type': 'invalid_request_error', 'message': 'Error from provider (Console Go): "
+ "Upstream request failed: [invalid_request_error] Input should be a valid string'}}"
+ ),
+ )
+ result = classify_api_error(err, provider="opencode-go", model="deepseek-v4-flash-vision-exp")
+ assert result.reason == FailoverReason.multimodal_tool_content_unsupported
+ assert result.retryable is True
+
+
+ class TestOpenCodeGoProactiveToolResultDowngrade:
+ def _multimodal_result(self, png_b64: str = "iVBORw0KGgoAAAA"):
+ return {
+ "_multimodal": True,
+ "content": [
+ {"type": "text", "text": "detected 2 objects"},
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{png_b64}"}},
+ ],
+ "text_summary": "detected 2 objects",
+ "meta": {"png_bytes": 1024},
+ }
+
+ def test_returns_text_summary_for_opencode_go_proactively(self, monkeypatch):
+ """OpenCode Go rejects list-type tool content, so _tool_result_content_for_active_model
+ should proactively downgrade to a text summary (#104731)."""
+ agent = _make_agent(provider="opencode-go", model="deepseek-v4-flash-vision-exp")
+ agent._no_list_tool_content_models = set()
+ monkeypatch.setattr(agent, "_model_supports_vision", lambda: True)
+ out = agent._tool_result_content_for_active_model("vision_analyze", self._multimodal_result())
+ assert isinstance(out, str)
+ assert "data:image" not in out
+ assert "image_url" not in out
-
diff --cc tests/tools/test_browser_use_cli.py
index ee4051d8549,8109b5d58d7..42258da0f97
--- a/tests/tools/test_browser_use_cli.py
+++ b/tests/tools/test_browser_use_cli.py
@@@ -14,7 -14,8 +14,9 @@@ Covers the three seams the integration
import json
import os
import stat
+import shutil
+ import subprocess
+ import sys
import time
import pytest
@@@ -265,40 -262,7 +267,40 @@@ class TestFindCli
)
assert bu_cli._find_cli_unpatched() == ["/usr/local/bin/browser-use"]
- def test_falls_back_to_uvx(self, monkeypatch):
+ def test_falls_back_to_uvx(self, monkeypatch, tmp_path):
+ """PM owns the executable spelling and the interpreter environment."""
+ import pm
+ import subprocess
+
+ executable = str(tmp_path / "chosen-by-pm.bin")
+ calls = []
+ def managed(command="uv", *, realize=True, base_env=None):
+ calls.append((command, realize))
+ return executable, {**(base_env or {}), "UV_PYTHON": "pm-python"}
+ monkeypatch.setattr(pm, "uv", managed)
+ monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: None)
+ assert bu_cli._find_cli_unpatched() == [executable, "browser-use"]
+ assert calls == [("uvx", False)]
+ monkeypatch.setattr(bu_cli, "_find_cli", bu_cli._find_cli_unpatched)
+ monkeypatch.setattr(bu_cli, "_base_subprocess_env", lambda: {"BROWSER_SETTING": "preserved"})
+ monkeypatch.setattr(bu_cli, "_route_backend", lambda *args: None)
+ seen = {}
- def run(cmd, **kwargs):
- seen.update(cmd=cmd, env=kwargs["env"], input=kwargs["input"])
++ def run(cmd, code, env, timeout):
++ seen.update(cmd=cmd, env=env, input=code)
+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
- monkeypatch.setattr(bu_cli.subprocess, "run", run)
++ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", run)
+ result = json.loads(bu_cli.browser_exec("print(1)"))
+ assert result["success"] is True
+ assert calls[-1] == ("uvx", True)
+ assert seen["cmd"] == [executable, "browser-use"]
+ assert seen["env"]["UV_PYTHON"] == "pm-python"
+ assert seen["env"]["BROWSER_SETTING"] == "preserved"
+ assert seen["input"] == "print(1)"
+
+ def test_bare_path_uvx_not_consulted(self, monkeypatch):
+ """Kill the PATH probe: a uvx reachable only via bare PATH is not
+ used — without the pinned pm uvx there is no zero-install rung."""
+ monkeypatch.setattr(bu_cli, "_pinned_uvx", lambda: None)
monkeypatch.setattr(
bu_cli.shutil, "which",
lambda name, path=None: "/usr/local/bin/uvx" if name == "uvx" and path is None else None,
@@@ -599,11 -560,10 +601,12 @@@ class TestOwnTabPreamble
else:
monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
# fake CLI echoes stdin back so we can inspect what code was sent
-- cli = _fake_cli(tmp_path, "cat\n")
-- monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
++ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["test-browser-use"])
++ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, code, env, timeout:
++ subprocess.CompletedProcess(cmd, 0, code, ""))
return json.loads(bu_cli.browser_exec("print('payload')", session=session))
+ @pytest.mark.platforms("linux")
def test_named_shared_browser_gets_preamble(self, tmp_path, monkeypatch):
result = self._run(tmp_path, monkeypatch, session="r7k2", shared_cdp="http://127.0.0.1:9222")
assert result["success"] is True
@@@ -1280,8 -1227,8 +1283,9 @@@ class TestLightpandaPreamble
monkeypatch.setattr(
bt_session, "_get_session_info", lambda key: {"cdp_url": "http://127.0.0.1:43111"}
)
-- cli = _fake_cli(tmp_path, "cat\n")
-- monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
++ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["test-browser-use"])
++ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, code, env, timeout:
++ subprocess.CompletedProcess(cmd, 0, code, ""))
result = json.loads(bu_cli.browser_exec("print('payload')", session="r7k2"))
assert result["success"] is True
assert "_hermes_ensure_own_tab" not in result["output"]
diff --cc tui_gateway/methods_tools.py
index 1570f9b21f4,0c8058950f7..2498b1af18f
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@@ -1372,7 -1377,25 +1378,25 @@@ def _plugins_install(rid, params)
return _ok(rid, result) if result.get("ok") else _err(rid, 5026, result.get("error") or "install failed")
- _PLUGINS_ACTIONS = {"list": _plugins_list, "toggle": _plugins_toggle, "install": _plugins_install}
+ def _plugins_update(rid, params):
+ """Catalog installs only: re-pin to the current catalog SHA (non-catalog installs update via the CLI)."""
+ name = (params.get("name") or "").strip()
+ if not name:
+ return _err(rid, 4019, "plugins.update requires a 'name'")
+ pc, cat = _tools_mod("hermes_cli.plugins_cmd"), _tools_mod("hermes_cli.plugins_cmd_catalog")
+ target = pc._plugins_dir() / name
- sidecar = cat.read_catalog_sidecar(target) if target.is_dir() else None
++ sidecar = cat.catalog_install_record(target) if target.is_dir() else None
+ if not sidecar:
+ return _err(rid, 4020, f"'{name}' is not a catalog install — update it via the CLI")
+ try:
+ sha, changed = cat.repin_catalog_plugin(target, sidecar)
+ except pc.PluginOperationError as e:
+ return _err(rid, 4021, str(e))
+ return _ok(rid, {"ok": True, "unchanged": not changed, "sha": sha})
+
+
+ _PLUGINS_ACTIONS = {"list": _plugins_list, "toggle": _plugins_toggle, "install": _plugins_install,
+ "update": _plugins_update}
@_scoped_rpc("plugins.manage", 5026, catch_resolve=False)
diff --cc uv.lock
index 7593eb69d40,148f151daf7..b574dd277bf
--- a/uv.lock
+++ b/uv.lock
@@@ -1599,7 -1703,6 +1599,8 @@@ dependencies =
{ name = "ruamel-yaml" },
{ name = "snowballstemmer" },
{ name = "tenacity" },
++ { name = "tomli-w" },
+ { name = "truststore" },
{ name = "tzdata", marker = "sys_platform == 'win32'" },
{ name = "urllib3" },
{ name = "uvicorn", extra = ["standard"] },
@@@ -1993,7 -2042,6 +1994,8 @@@ requires-dist =
{ name = "starlette", marker = "extra == 'web'", specifier = "==1.3.1" },
{ name = "supermemory", marker = "extra == 'supermemory'", specifier = "==3.50.0" },
{ name = "tenacity", specifier = "==9.1.4" },
++ { name = "tomli-w", specifier = "==1.2.0" },
+ { name = "truststore", specifier = ">=0.10.4,<0.11" },
{ name = "ty", marker = "extra == 'dev'", specifier = "==0.0.21" },
{ name = "tzdata", marker = "sys_platform == 'win32'", specifier = "==2025.3" },
{ name = "urllib3", specifier = ">=2.7.0,<3" },
@@@ -4074,21 -4568,21 +4076,30 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b", size = 16588, upload-time = "2020-11-01T01:40:20.672Z" },
]
++[[package]]
++name = "tomli-w"
++version = "1.2.0"
++source = { registry = "https://pypi.org/simple" }
++sdist = { url = "https://files.pythonhosted.org/packages/19/75/241269d1da26b624c0d5e110e8149093c759b7a286138f4efd61a60e75fe/tomli_w-1.2.0.tar.gz", hash = "sha256:2dd14fac5a47c27be9cd4c976af5a12d87fb1f0b4512f81d69cce3b35ae25021", size = 7184, upload-time = "2025-01-15T12:07:24.262Z" }
++wheels = [
++ { url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675, upload-time = "2025-01-15T12:07:22.074Z" },
++]
++
[[package]]
name = "tornado"
-version = "6.5.7"
+version = "6.5.8"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/64/24/95ec527ad67b76d59299e5465b3935d05e4294b7e0290a3924b7487df30b/tornado-6.5.7.tar.gz", hash = "sha256:66c513a76cda70d53907bc27cf1447557699c2e95aa48ba27a442ff61c3ddfc2", size = 519252, upload-time = "2026-06-08T17:34:51.232Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/10/d3/343e5bb989d6515b1646cf3d40135d73f3d5e45339bded401b56cdac24dd/tornado-6.5.8.tar.gz", hash = "sha256:9452e1b208a8bd771e2cb1f2ff564985b9b214bdebbe622793e1799e0a6bd23f", size = 520493, upload-time = "2026-08-07T02:12:42.971Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/02/dc/c7043cab6fed8ae159fc1923ce829ada35c4dbd797d408a43858ffaf9639/tornado-6.5.7-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:148b2eb15c2c765a50796172c1e499649b35f30d2e3c3d3e15913cfa56bfb163", size = 448543, upload-time = "2026-06-08T17:34:38.052Z" },
- { url = "https://files.pythonhosted.org/packages/92/4f/090b1431e5a43df696feceffc268c5383cc079ecb5f08ce58f917109aafe/tornado-6.5.7-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9da38de27f1da3b78a966f0dae12b5a1ea9afe72ca805d84ff06508272ddf100", size = 446707, upload-time = "2026-06-08T17:34:39.594Z" },
- { url = "https://files.pythonhosted.org/packages/37/d8/ef374952fd5da67d4463122c2b8e5a96536ec10b4b339254c6dcde81d01c/tornado-6.5.7-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8d759e71906ee783f8867b93bf26a265743da4c1e2f4a018464c1ba019862972", size = 449774, upload-time = "2026-06-08T17:34:41.204Z" },
- { url = "https://files.pythonhosted.org/packages/35/37/d434c73f4c6e014b745b9b37085f34f40c022f007efff3d7fe65991899f3/tornado-6.5.7-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a46347a18f23fb92b396beebe0fb78f61dda0cc302445202c16203d8a18848b", size = 450745, upload-time = "2026-06-08T17:34:42.531Z" },
- { url = "https://files.pythonhosted.org/packages/b6/2b/56b9aff361d7f1ab728a805ec7d7ea835f8807afa9f5cc690ea0e630efb9/tornado-6.5.7-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7778b30bef919231265e91c69963ce0f49a1e9c07ac900bbe75b19ce2575ba92", size = 450578, upload-time = "2026-06-08T17:34:43.787Z" },
- { url = "https://files.pythonhosted.org/packages/02/30/a7444fb23aa76860a14198fab96ac79f1866b0a6e19e26c4381b0938e50f/tornado-6.5.7-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e726f0c75da7726eec023aa62751ff8878bd2737e34fbdd33b1ae5897d2200f5", size = 449985, upload-time = "2026-06-08T17:34:45.326Z" },
- { url = "https://files.pythonhosted.org/packages/5c/42/5f0e56c01e8d9d36f4e23f367b85ae6cae0c1ecddd5e6977d8388ad27488/tornado-6.5.7-cp39-abi3-win32.whl", hash = "sha256:f8de3bf12d3efdd0cbe7c8887868198f8a91415e3f29fcf258d9b8eb7b1d9ae4", size = 451047, upload-time = "2026-06-08T17:34:46.784Z" },
- { url = "https://files.pythonhosted.org/packages/c9/a4/b393076ffb21b469eec5b328a0534cf03a3b90bfc6b1f09507cdd075d938/tornado-6.5.7-cp39-abi3-win_amd64.whl", hash = "sha256:de942f843533a039ef9fa3d9c88c7cd8a7c94553fb5ad0154270989b3d99a2c4", size = 451485, upload-time = "2026-06-08T17:34:48.248Z" },
- { url = "https://files.pythonhosted.org/packages/71/2e/7b1c769803121b809112cf9a00681c472eae1d80e32d7ec0e0bd61d0d0e1/tornado-6.5.7-cp39-abi3-win_arm64.whl", hash = "sha256:ff934fce95643af5f11efdae618eaa73d469dc588641e5c8d19295a0c65c4796", size = 450506, upload-time = "2026-06-08T17:34:49.702Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/d5/007086fd8df5489338e204f65adce33fd4f21a4999dbb2b9cff2f897b5f4/tornado-6.5.8-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc6aa787d7cfab7c3d35189dc7a56fbd2399a569624c730c6b55b3d6531d0403", size = 449487, upload-time = "2026-08-07T02:12:28.682Z" },
+ { url = "https://files.pythonhosted.org/packages/70/c8/5a24a99495903f594f6a199dd7beead1cbc0a13e2cb9102727bcaaf2a997/tornado-6.5.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9715b5eb79735b2bcd454ce216a9275b7c0470e64ea1bf5742f78b2f72b26eeb", size = 447649, upload-time = "2026-08-07T02:12:30.306Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/de/f2e733f386b85962d1b1dc82cd63d169b5b4580062b35397eac9244a41fe/tornado-6.5.8-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:547d63f450d570c14fe0e8db2cfb14c9bbd1c2503b4a6612586267955aa47b58", size = 450707, upload-time = "2026-08-07T02:12:31.95Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/94/20efeee9a01c141e9ac47c397f81679dfda24b32768fc4fff24e76d36c2c/tornado-6.5.8-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e2360a0ffbe145eca8af0b19cb7203d79b1a98dd4cccdd6b368f6f49c2e3808", size = 451677, upload-time = "2026-08-07T02:12:33.512Z" },
+ { url = "https://files.pythonhosted.org/packages/42/ec/a96ccb8ccf0de2b7bc2c5fa1608a4803735018242e90c4882365a9fd418f/tornado-6.5.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5d242290bdf7ab3151bc1065fdd75c0dcc21cbc7b49f22a4c56329c2d6566d22", size = 451510, upload-time = "2026-08-07T02:12:35.346Z" },
+ { url = "https://files.pythonhosted.org/packages/29/b5/93185859245ad3f00e62175f29607346788b696369347f0146e0421286bb/tornado-6.5.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7b94ff0e128fe0542f3bd331fb44d06260fc4ac16881545159f34ef08aad4195", size = 450917, upload-time = "2026-08-07T02:12:36.963Z" },
+ { url = "https://files.pythonhosted.org/packages/97/cf/fe33cf062834487d34d1559746a4a12521033c22645b6d74d4bca702e018/tornado-6.5.8-cp39-abi3-win32.whl", hash = "sha256:67832909c4779c64942380cb5f044a5c6163d00831472d80e25e115de9917836", size = 451952, upload-time = "2026-08-07T02:12:38.512Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/e1/468ad54333e92ccb62627e62cb88e5fc14a2171daa67ed47b1b8542d5b86/tornado-6.5.8-cp39-abi3-win_amd64.whl", hash = "sha256:11881db6b7c168494be2c2d12e65931451bdf7ee718535418ae1d8855dd5a0ee", size = 452391, upload-time = "2026-08-07T02:12:39.971Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/3e/cd5e4f06e34cde33b8ef66cf36aa2b5ad46354cc1af7d2136bbe365fee1d/tornado-6.5.8-cp39-abi3-win_arm64.whl", hash = "sha256:68a7468c7e289f8514d7d664101753903217eff1bb6822c6b5994a0b5f5bcb26", size = 451411, upload-time = "2026-08-07T02:12:41.469Z" },
]
[[package]]
diff --cc website/docs/reference/cli-commands.md
index 4f40a8f6650,c70aa7bc2d6..87362ac6a3a
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@@ -1461,9 -1462,9 +1462,9 @@@ Unified plugin management — general p
| Subcommand | Description |
|------------|-------------|
| *(none)* | Composite interactive UI — general plugin toggles + provider plugin configuration. |
- | `install <identifier> [--force] [--ref COMMIT_SHA]` | Install a plugin from a Git URL, `owner/repo`, or a bare index name. Bare names (no slash) are resolved through the community plugin index to `owner/repo` plus the index-pinned commit; ambiguous names list candidates and exit. `--ref` accepts only a full 40-character commit SHA, installs that exact immutable revision, and overrides any index pin. |
- | `search [term] [--json] [--capability CAP] [--refresh]` | Search the community plugin index (fuzzy match on name/description/tags; omit `term` to browse). Fetched from `plugins.index_url` (default: the NousResearch plugin index), cached under `~/.hermes/cache/` for 24h, falling back to the stale cache and then the bundled seed when offline. Indexed ≠ audited — inclusion is a metadata review only. |
- | `update <name>` | Pull latest changes for an unpinned installed plugin. Pinned plugins must be reinstalled with `--force --ref <new-commit>` to move. |
-| `install <identifier> [--force] [--ref COMMIT_SHA] [--allow-removed]` | Install a plugin from the Hermes plugin catalog (bare entry name), a Git URL, or `owner/repo` shorthand. Catalog names resolve to the entry's repo at its pinned 40-hex commit SHA, show the declared capability summary, and record catalog provenance in a `.hermes-catalog.json` sidecar. Raw URLs are flagged as custom (unreviewed) sources; `--ref` (full 40-character commit SHA) pins them. `--allow-removed` (DANGEROUS) bypasses the removed-plugin blocklist. |
++| `install <identifier> [--force] [--ref COMMIT_SHA] [--allow-removed]` | Install a plugin from the Hermes plugin catalog (bare entry name), a Git URL, or `owner/repo` shorthand. Catalog names select the reviewed 40-hex commit SHA. Source, revision, and catalog membership share `plugins/.install-metadata.json`. An explicit different `--ref` selects a custom pin. `--allow-removed` (DANGEROUS) bypasses the removed-plugin blocklist. |
+ | `search [term] [--json]` | Search the Hermes plugin catalog (matches entry names, descriptions, and declared tools; omit `term` to list everything). The catalog is curated in-repo (`plugin-catalog/`), refreshed from the live repo with a 6-hour cache, and falls back to the in-tree copy offline. Cataloged ≠ audited — admission reviews the entry, not the code. |
-| `update <name>` | Pull latest changes for an unpinned installed plugin. Pinned plugins must be reinstalled with `--force --ref <new-commit>` to move. |
++| `update <name>` | Re-pin catalog installs to the reviewed catalog SHA, or update a custom Git install from its recorded source/feed. PM validates active-plugin dependencies before code publication. Explicit custom pins move only with `install --force --ref <new-commit>`. |
| `remove <name>` (aliases: `rm`, `uninstall`) | Remove an installed plugin. |
| `enable <name>` | Enable a disabled plugin. |
| `disable <name>` | Disable a plugin without removing it. |
diff --cc website/docs/user-guide/features/plugin-catalog.md
index 00000000000,1f5c66fab8c..5a2e1ff8cde
mode 000000,100644..100644
--- a/website/docs/user-guide/features/plugin-catalog.md
+++ b/website/docs/user-guide/features/plugin-catalog.md
@@@ -1,0 -1,143 +1,150 @@@
+ ---
+ sidebar_position: 13
+ sidebar_label: "Plugin Catalog"
+ title: "Plugin Catalog"
+ description: "Browse and install reviewed, SHA-pinned Hermes plugins from the curated catalog"
+ ---
+
+ # Plugin Catalog
+
+ The plugin catalog is a curated, human-reviewed directory of Hermes plugins you
+ can install by name with a single command:
+
+ ```bash
+ hermes plugins install <name>
+ ```
+
+ Browse it visually at **[/docs/plugins](/plugins)** — search, tier filters
+ (Official / Community), capability chips, and copyable install commands for
+ every entry.
+
+ The catalog complements — it does not replace — the existing
+ [plugin system](plugins.md). Anything you can install from the catalog is a
+ normal plugin under the hood; the catalog just adds discovery and a review
+ layer on top.
+
+ ## What's in an entry
+
+ Each catalog entry is a small YAML file in the
+ [`plugin-catalog/`](https://github.com/NousResearch/hermes-agent/tree/main/plugin-catalog)
+ directory of the hermes-agent repository, declaring:
+
+ | Field | Meaning |
+ |---|---|
+ | `name` | The catalog key you pass to `hermes plugins install` |
+ | `repo` | The plugin's public git repository |
+ | `sha` | The **exact 40-hex commit** that was reviewed — installs check out this pin, not a branch tip |
+ | `tier` | `official` (maintained by NousResearch) or `community` |
+ | `maintainer` | Who owns the plugin |
+ | `capabilities` | Declared tools, hooks, middleware, and required env vars |
+ | `requires_hermes` | Minimum Hermes version, e.g. `>=0.19` (optional) |
+ | `platforms` | OS restrictions, empty = all (optional) |
+ | `docs_url` | External documentation link (optional) |
+
+ ## Trust model
+
+ The catalog is designed so you know exactly what you're installing:
+
+ - **Human-merged admission.** Every entry (and every pin update) lands via a
+ pull request reviewed by a maintainer. Nothing enters the catalog
+ automatically.
+ - **Exact SHA pins.** Entries pin a specific commit, not a branch. A plugin
+ author pushing new code to their repo does **not** change what the catalog
+ installs — updating the pin requires another reviewed PR.
+ - **Capability declarations.** Entries state up front which tools, hooks, and
+ middleware the plugin provides and which environment variables (API keys
+ etc.) it needs, so you can judge its blast radius before installing.
+ - **Removed list.** Plugins pulled from the catalog (for example after a
+ security incident) go on `plugin-catalog/removed.yaml` with a reason and
+ date. The installer refuses to install anything on the removed list.
+ - **Installed ≠ enabled.** Installing a catalog plugin puts it on disk; like
+ any plugin it must still be enabled before it loads. See
+ [Plugins → Enabling and disabling](plugins.md).
+
+ :::warning Catalog review is a point-in-time review
+ A catalog entry means the pinned commit was looked at by a human, capability
+ declarations were checked, and the repo met the submission bar. It is not a
+ security audit, and it says nothing about other commits in the same
+ repository. Review the code of anything you give credentials to.
+ :::
+
+ ## Installing from the catalog
+
+ ```bash
+ # Install a reviewed catalog entry by name (checks out the pinned SHA)
+ hermes plugins install <name>
+
+ # Then enable it, as with any plugin
+ hermes plugins enable <name>
+ ```
+
+ The install prompt shows the entry's capability summary — declared tools,
+ hooks, and required env vars — before anything is cloned.
+
+ ### Updating a catalog install
+
+ `hermes plugins update <name>` never runs `git pull` for catalog installs —
+ it compares your installed pin against the current catalog pin and, when the
-catalog moved (via a reviewed PR), force-reinstalls at the new SHA. Your
++catalog moved (via a reviewed PR), prepares the new SHA before publication. Your
+ enabled/disabled state is preserved. `hermes plugins list` shows catalog
+ installs as `catalog:<tier>@<sha>` so you can see provenance at a glance.
+
++PM validates the dependencies of an active plugin before its new code replaces
++the installed version. A version, scan, dependency, or publication failure keeps
++the working code and dependency selection. Disabled plugins stay disabled.
++Catalog membership, installed revision, and source share the profile's
++`plugins/.install-metadata.json` record. Custom Git plugins retain their recorded
++Git/feed update policy but use the same PM validation and publication path.
++
+ ### Names not in the catalog
+
+ A bare name that isn't a catalog entry is an error: there is no second,
+ unreviewed name index. Install such plugins by `owner/repo` or Git URL instead
+ (custom source, see below), or submit them to the catalog.
+
+ ### Live refresh
+
+ The docs build publishes the catalog as one JSON document
+ (`https://hermes-agent.nousresearch.com/docs/api/plugin-catalog.json`).
+ `search`/`install`/`update` fetch it at most every six hours and cache it under
+ `~/.hermes/cache/`, so new entries and removals reach installed clients without
+ updating Hermes. Offline, the copy shipped with your checkout is used. Removals
+ from the in-tree list and the live list are always both enforced.
+
+ ### Custom git URLs are different
+
+ `hermes plugins install <git-url>` still works for any repository, but it
+ bypasses the catalog entirely:
+
+ - **No review** — you get whatever is at the branch tip, not a reviewed pin.
+ - **A warning banner** is shown to make clear the code is unvetted.
+ - The removed list is still consulted (a known-bad repo is refused by URL).
+
+ Use the git-URL path for your own plugins and repos you already trust; use the
+ catalog for discovery.
+
+ ## Submitting a plugin to the catalog
+
+ Submissions are pull requests that add one `plugin-catalog/<name>.yaml` file.
+ The full checklist lives in the
+ [plugin-catalog README](https://github.com/NousResearch/hermes-agent/tree/main/plugin-catalog);
+ in short, an entry must be:
+
+ 1. **Owner-submitted** — the PR author owns or maintains the plugin repo.
+ 2. **A public repository** — the `repo` URL is publicly cloneable.
+ 3. **Released** — the repo has real releases/tags, not just a default branch.
+ 4. **Passing validation** — the catalog validation GitHub Action is green on
+ the PR (schema, SHA format, reachability).
+ 5. **Pinned to settled code** — the pinned SHA is at least **2 weeks old**, so
+ the catalog never points at code pushed moments before review.
+
+ Pin updates (bumping `sha` to a newer commit) follow the same PR + review
+ process.
+
+ ## See also
+
+ - [Plugins](plugins.md) — the plugin system itself: manifest format, enabling,
+ configuration
+ - [Built-in Plugins](built-in-plugins.md) — plugins that ship with Hermes
+ - [Build a Hermes Plugin](/developer-guide/plugins) — write your own
+ - [Plugin Catalog page](/plugins) — the browsable catalog
diff --cc website/docs/user-guide/features/plugins.md
index 72968993578,c208f76bb76..f6a2560baf1
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@@ -340,10 -340,10 +340,10 @@@ Declarative plugins are symlinked with
```bash
hermes plugins # unified interactive UI
hermes plugins list # table: enabled / disabled / not enabled
- hermes plugins search <term> # search the community plugin index
- hermes plugins install <name> # install by index name (resolved to repo @ pinned ref)
+ hermes plugins search <term> # search the Hermes plugin catalog
+ hermes 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 applies
hermes 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
diff --cc website/scripts/prebuild.mjs
index 7d7f29fcbe7,44ab2079587..48b258b0533
--- a/website/scripts/prebuild.mjs
+++ b/website/scripts/prebuild.mjs
@@@ -33,8 -32,10 +33,11 @@@ const repoRoot = resolve(websiteDir, ".
const extractScript = join(scriptDir, "extract-skills.py");
const llmsScript = join(scriptDir, "generate-llms-txt.py");
const cronBlueprintsScript = join(scriptDir, "extract-automation-blueprints.py");
+const iconGenScript = join(repoRoot, "scripts", "generate-icons.mjs");
+ const pluginsScript = join(scriptDir, "extract-plugins.py");
const outputFile = join(websiteDir, "static", "api", "skills.json");
+ const pluginsOutputFile = join(websiteDir, "static", "api", "plugins.json");
+ const pluginsMetaOutputFile = join(websiteDir, "static", "api", "plugins-meta.json");
const unifiedIndexFile = join(websiteDir, "static", "api", "skills-index.json");
const UNIFIED_INDEX_URL =
"https://hermes-agent.nousresearch.com/docs/api/skills-index.json";