The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
docs: root AGENTS.md becomes a hub; area rules move where they load
Tekniuma4140eebb170
diff --git a/AGENTS.md b/AGENTS.mdindex 1804f99afdc..4c4ce5c0452 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,9 +1,9 @@# Hermes Agent - Development Guide-Instructions for AI coding assistants and developers working on the hermes-agent codebase.-This root file holds only what applies everywhere. Each area has its own `AGENTS.md` (aim for-~8k chars; `agent/subdirectory_hints.py` delivers up to 32k and truncates head/tail with a warning-past that); see the **routing table** at the end and read the area file before editing in that area.+For AI coding assistants and developers working on hermes-agent. This root file is a hub: what+applies everywhere, then a routing table. Each area's `AGENTS.md` loads automatically when you work+in that directory; read it before editing there. `python scripts/check` caps this file at 12k chars+and every root-to-area chain at 30k, so it loads whole on 128k+ models: long form goes in the guide.**Never give up on the right solution.**@@ -17,200 +17,56 @@ not by growing the core.Two invariants shape almost every design decision and are the lens for reviewing any change:-- **Per-conversation prompt caching is sacred.** A long-lived conversation reuses a cached- prefix every turn. Anything that mutates past context, swaps toolsets, reloads memories, or- rebuilds the system prompt mid-conversation invalidates that cache and multiplies the user's- cost. We do not do it; the ONE exception is context compression. Slash commands that mutate- system-prompt state (skills, tools, memory) must be **cache-aware**: default to deferred- invalidation (takes effect next session) with an opt-in `--now` flag (`/skills install --now`- is the canonical pattern).+- **Per-conversation prompt caching is sacred.** Mutating past context, swapping toolsets,+ reloading memories or rebuilding the system prompt mid-conversation breaks the cached prefix and+ multiplies the user's cost; the ONE exception is context compression. Slash commands that change+ system-prompt state defer to the next session, with an opt-in `--now` (`/skills install --now`).- **The core is a narrow waist; capability lives at the edges.** Every model tool is sent onevery API call, so the bar for a new *core* tool is high. New capability should arrive as aCLI command + skill, a service-gated tool, or a plugin — not as core surface.-## Contribution Rubric — What We Want / What We Don't+## Contribution rubric-The project's intent layer. It serves humans aiming a contribution AND the automated triage-sweeper, which may only close on `implemented_on_main`, `cannot_reproduce`, or `incoherent`.-Taste-based "out of scope" closes are a human maintainer's call; the sweeper's job is to-recognize design intent and *avoid wrongly closing a legitimate contribution*.+The project's intent layer, for contributors and for the triage sweeper (which may only close on+`implemented_on_main`, `cannot_reproduce` or `incoherent`; taste-based closes are a maintainer's+call, and when in doubt a PR stays open). Long form with examples:+`website/docs/developer-guide/contributing.md` § Contribution rubric.-Read the balance right: Hermes ships a **lot**. Most merges are bug fixes to reported-behavior, and the product surface (platforms, providers, models, desktop/TUI features)-expands aggressively on purpose. The restraint below targets the **core agent + model tool-schema**, the one place where every addition is paid for on every API call. "Smallest-footprint" governs *how a capability is wired into the core*, not whether the product may-grow: expansive at the edges, conservative at the waist.+**Wanted:** real bug fixes (repro on `main`, the exact line, the whole class incl. sibling paths);+reach at the edges (adapters, providers, models, UI features) wired into the existing setup UX;+god-file → module refactors; extending before duplicating (3+ PRs in one category → an ABC ++orchestrator); behaviour-contract tests; E2E with real imports against a temp `HERMES_HOME` for+resolution, config, security and I/O changes; salvage by cherry-pick so authorship survives.-### What we want+**Rejected even when well-built:** hooks with no concrete consumer; new `HERMES_*` env vars for+non-secret config (`.env` is secrets only, behaviour goes in `config.yaml`); a new core tool when+terminal + file or a skill already does the job; `offset`/`limit` pagination on instructional tools;+"fixes" that destroy the feature they secure; outbound telemetry without an opt-in gate;+change-detector tests; plugins that touch core files; third-party products in the core tree (ship a+standalone plugin repo).-- **Fix real bugs, well.** Reproduce the symptom on current `main`, point to the exact line- where it manifests, and fix the whole bug class — sibling call paths included.-- **Expand reach at the edges.** New adapters, channels, providers, models, desktop/TUI/- dashboard features land routinely, including large ones — as long as they integrate with- the existing setup/config UX (`hermes tools`, `hermes setup`, auto-install) rather than- bolting on a raw env var.-- **Refactor god-files into clean modules.** Huge mechanical `+N/-N` extraction PRs are- wanted work. "Every line traces to the request" applies to *feature* PRs; a declared- refactor's request IS the extraction.-- **Keep the core narrow.** Prefer, in order: extend existing code → CLI command + skill →- service-gated tool (`check_fn`) → plugin → MCP server in the catalog → new core tool (last- resort). See the Footprint Ladder.-- **Extend, don't duplicate.** Check whether existing infrastructure covers the use case- before adding a module/manager/hook. When 3+ open PRs integrate the same *category*- (memory backends, providers, notifiers), design an ABC + orchestrator, wrap the existing- built-in as the first provider, and turn the competing PRs into plugins against it.-- **Behavior contracts over snapshots.** Tests assert how two pieces of data relate, never- freeze a current value (see Testing).-- **E2E validation, not just green unit mocks.** Anything touching resolution chains, config- propagation, security boundaries, remote backends, or file/network I/O must exercise the- real path with real imports against a temp `HERMES_HOME` — two of them (A→B→A) when the- change touches profile scope. Mocks hide integration bugs.-- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict role- alternation (never two same-role messages in a row; never a synthetic user message injected- mid-loop), and a system prompt byte-stable for the life of a conversation.-- **Contributor credit preserved.** Salvage external work by cherry-picking (rebase-merge) so- authorship survives; build on top rather than reimplementing.+**Before you call it a bug,** verify the claim AND the intent (`git log -p -S "<symbol>"`): the+isolation is often the design (profiles are islands on purpose), an absence can be load-bearing,+and a fix that cannot point to the line where the bug manifests has an unverified premise.-### What we don't want (rejected even when well-built)+**Security:** `SECURITY.md` is the scope authority. A §3.1 finding goes private (GitHub Security+Advisories or [email protected]), never into a public issue, PR, commit or comment; §3.2+hardening is ordinary public work. Name the §2 boundary crossed, with a repro on `main`.-- **Speculative infrastructure.** Hooks/callbacks/extension points with no concrete consumer.- Adding a hook is easy; removing one after plugins depend on it is hard. A hook with a real,- stated use case is NOT speculative even if the consumer ships separately.-- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets only. Behavioral- settings (timeouts, thresholds, flags, display prefs) go in `config.yaml`; bridge to an- internal env var in code if the mechanism needs one. Reject "set X in your .env" docs- unless X is a credential.-- **A new core tool when terminal + file (or a skill) already do the job.** If the only- barrier is file visibility on a remote backend, fix the mount, not the toolset.-- **Lazy-reading escape hatches on instructional tools.** No `offset`/`limit` pagination on- tools that load content the agent must read fully (skills, prompts, playbooks) — models- read page 1 and skip the rest.-- **"Fixes" that destroy the feature they secure.** Read the original intent- (`git log -p -S`) before restricting behavior; find a fix that preserves the feature.-- **Outbound telemetry / usage attribution without opt-in gating.** No analytics,- third-party identifier tagging, or attribution tags until a generic user-facing opt-in- (config gate + setup prompt + `hermes tools` toggle) exists. Park behind a label.-- **Change-detector tests, cache-breaking mid-conversation, dead code wired in without E2E- proof, plugins that touch core files.** Plugins work within the ABCs/hooks we provide; if- one needs more, widen the generic plugin surface, never special-case it in core.-- **Third-party products integrated into the core tree.** Observability backends, vendor- SaaS connectors, analytics dashboards, and other "someone else's product" plugins do NOT- land under `plugins/` — every one becomes our burden against a fast-moving core for a- backend we don't own. Ship as a **standalone plugin repo** (`~/.hermes/plugins/` or pip- entry point), promoted in the Nous Research Discord `#plugins-skills-and-skins`. This is a- coupling decision, not a quality bar; such PRs are closed with a pointer to publish.--### Before you call it a bug — verify the premise (and when NOT to close)--The most common reason a well-written PR is closed is a **wrong premise** or treating an-**intentional design as a gap**. These patterns tell a reviewer what to scrutinize and tell-the sweeper when a PR is NOT safe to close (when in doubt, leave it open for a human):--- **"Intentional design, not a gap."** Ask whether the isolation IS the design. Profiles are- independent islands on purpose: a PR adding live config inheritance from the default- profile was closed because coupling profiles is exactly what the design prevents (`--clone`- already covers "start from my default"). Read `git log -p -S "<symbol>"` before assuming- something is unfinished.-- **"The premise doesn't hold against how X actually works."** Trace the real runtime before- accepting a rationale. Real closes: a rate-limit "re-probe during cooldown" PR (the breaker- trips only on a *confirmed-empty* bucket, so re-probing hammers a bucket proven empty); a- usage fix whose new branch **never executes** because an earlier guard already popped the- state. If you can't point to the exact line where the bug manifests AND show the fix changes- that line's behavior, the premise is unverified.-- **"The absence was deliberate."** Restoring "missing" `__init__.py` files made a test tree- importable as a dotted package that shadowed the real plugin and deleted its `register()`- at import time. The omission was load-bearing.-- **"Overreached / resurrected an approach we moved past."** Scope creep beyond the agreed- base, or reviving a direction maintainers closed, is rejected even when it works. Offer the- rest as a focused follow-up.--Throughline: **verify the claim AND the intent against the codebase before writing or merging-a fix.** A reproduction on current `main` plus a line-level account beats a plausible-rationale. When unsure about intent, asking is cheaper than shipping a fix that fights the-design.--### Security reports and fixes — follow `SECURITY.md`--Read `SECURITY.md` before filing an issue or opening a PR with a security angle. It is the-scope authority; these are the rules that matter at submission time:--- **Undisclosed vulnerabilities go private, never public.** If a finding is in scope under- `SECURITY.md` §3.1 (isolation escape, unauthorized external-surface access, credential- exfiltration, trust-model documentation violation), report it via- [GitHub Security Advisories](https://github.com/NousResearch/hermes-agent/security/advisories/new)- or [email protected]. Do not open a public issue or PR for it, and keep- reproduction or exploit details out of commit messages, PR bodies, and comments.-- **Out-of-scope hardening is ordinary public work.** §3.2 items — approval-gate, redaction,- or Skills Guard bypasses; prompt injection without a chained §3.1 outcome; consequences of- the chosen isolation posture; break-glass settings; third-party skills/plugins — are not- vulnerabilities. File them as regular issues/PRs; don't route them through the private- channel or describe them as vulnerabilities.-- **Name the boundary.** A security issue or PR states which §2 trust boundary is crossed,- with `path/to/file.py:line` references and a reproduction on current `main`.-- **Sweeper:** a public issue or PR that discloses an apparent §3.1 vulnerability is never a- sweeper close or merge candidate; leave it for a maintainer.--### The Footprint Ladder (new capability decision)--Choose the highest (least-footprint) rung that correctly solves the problem:--1. **Extend existing code** — a variation of something that exists. Zero new surface.-2. **CLI command + skill** — config/state/infra expressible as shell commands; the agent runs- `hermes <subcommand>` guided by a skill. Default for subscriptions, scheduled tasks,- service setup (`hermes webhook`, `hermes cron`, `hermes tools`).-3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND only appears when- a prerequisite is configured (Home Assistant tools, memory-provider tools). This rung gates- reachability/opt-in process-wide; a capability that varies per SESSION (who is watching) is- a named toolset folded in by the toolset resolver, not a `check_fn` — see "Surface capability- is a property of the SESSION" below.-4. **Plugin** — third-party/niche/user-specific; lives in `~/.hermes/plugins/` or a pip- package, discovered at runtime.-5. **MCP server (in the catalog)** — genuinely a tool but not core-fundamental. Zero permanent- core-schema footprint, reusable by any MCP host, reached via the built-in MCP client.-6. **New core tool** — only when fundamental, broadly useful to nearly every user, and- unreachable via terminal + file or an MCP server (terminal, read_file, web_search,- browser_navigate).--### Surface capability is a property of the SESSION, never of the process env--A tool that works only because of *who is on the other end* (desktop panes, in-app browser,-message reactions, Projects) must resolve availability from the **session's own source**, not-from an env var on the backend. Client and backend are separate machines: the desktop app may-drive a locally spawned backend, one over SSH, one behind URL + token, or Hermes Cloud, and-only the first two carry `HERMES_DESKTOP=1`. An env-keyed gate is a silent no-op on the other-topologies — the tool is stripped from the schema while the platform hint tells the model it-is "inside the Hermes desktop app". The pattern:--- **The toolset is the surface gate.** Keep such tools off `_HERMES_CORE_TOOLS` and in a named- toolset (`desktop_ui`, `project`); the GUI gateway's `_load_enabled_toolsets(platform)`- folds it in when the session's platform says GUI. One resolver, every topology.-- **`check_fn` answers reachability or opt-in, not surface.** "Is the bridge wired?" — fine.- "Was I spawned by Electron?" — not. `check_fn` results are TTL-cached process-wide- (`tools/registry.py`); a per-session answer does not belong there.-- **Ask which identity you mean.** `HERMES_DESKTOP=1` legitimately means "this backend was- spawned by the app" (cron ticker, web-dist handling). It does NOT mean "a GUI is watching";- the embedded terminal pane (`hermes --tui` against that backend) is the counterexample.--Test: if the capability still makes sense with the client on another machine, it is-session-scoped. Assert the GUI session gets the tool **with the env var absent**.+**Footprint ladder** (take the highest rung that solves it): extend existing code → CLI command ++skill → service-gated tool (`check_fn` answers reachability/opt-in, never per-session surface:+`tools/AGENTS.md`) → plugin → MCP server in the catalog → new core tool (fundamental, broadly useful,+unreachable otherwise).## Development Environment-```bash-source ./activate # provisions/syncs PM tools + dependencies, then activates-```-Select an isolated development `HERMES_HOME` and `HERMES_RUNTIME_DIR` first;-see `website/docs/reference/package-management.md#developer-workflow`.-fish: `source ./activate.fish`; PowerShell: `. .\activate.ps1`. `deactivate` restores the prior-environment. Non-interactive callers run under `scripts/run-in-hermes-env CMD...` instead of sourcing.-For tests, use the independent test environment in `CONTRIBUTING.md` (or Nix);-PM activation's `PYTHONPATH` does not survive the test runner's environment scrub.-`scripts/run_tests.sh` probes `.venv`, then `venv`, then `$HOME/.hermes/hermes-agent/venv`-(worktrees sharing the main checkout's venv). **`python scripts/check`** runs every blocking lint-check CI runs, with CI's pinned tools; run it before pushing (`--install-hook pre-push` runs it on-every push; re-run it after pulling to refresh the hook). `# noqa` does not waive a ratchet finding:-use `# health: allow <RULE> -- <why>`.+`source ./activate` (fish: `activate.fish`, PowerShell: `activate.ps1`) provisions and activates the+PM environment; pick an isolated `HERMES_HOME`/`HERMES_RUNTIME_DIR` first+(`website/docs/reference/package-management.md#developer-workflow`). Tests need the separate test+environment in `CONTRIBUTING.md`. **`python scripts/check`** runs every blocking lint check CI+runs, with CI's pinned tools; `--install-hook pre-push` runs it on every push (re-run after+pulling to refresh the hook). `# noqa` does not waive a ratchet finding:+`# health: allow <RULE> -- <why>` does.## Project Structure@@ -224,327 +80,90 @@ hermes-agent/├── cli.py # HermesCLI (REPL, slash dispatch) + hermes_cli/cli_*_mixin.py├── hermes_state.py # SessionDB facade; hermes_state_*.py siblings├── hermes_constants.py # get_hermes_home(), display_hermes_home() — profile-aware paths-├── hermes_logging.py # agent.log / errors.log / gateway.log (profile-aware)-├── batch_runner.py # Parallel batch processing-├── agent/ # turn_*.py loop phases, providers, memory, compression, prompt builder-├── hermes_cli/ # CLI subcommands, setup, config, plugins loader, skins, updater-│ └── web_routers/ # Dashboard FastAPI routers (one per surface); web_server.py mounts them-├── tools/ # Tool implementations, auto-discovered via tools/registry.py-│ └── environments/ # Terminal backends (local, docker, ssh, modal, daytona, singularity)+├── agent/ # turn loop phases, providers, memory, compression, prompt builder+├── hermes_cli/ # CLI subcommands, setup, config, plugins loader, updater, web_routers/+├── tools/ # Tool implementations (tools/registry.py) + environments/ backends├── gateway/ # run.py facade + run_*.py phases + session*.py + platforms/-│ ├── platforms/ # One adapter per platform; see platforms/ADDING_A_PLATFORM.md-│ └── builtin_hooks/ # Always-registered gateway hooks (extension point; none shipped)├── plugins/ # memory/, context_engine/, model-providers/, kanban/, image_gen/, ...├── skills/ # Built-in skills (by category) optional-skills/: shipped, not active-├── ui-tui/ # Ink (React) terminal UI — `hermes --tui`-├── tui_gateway/ # Python JSON-RPC backend for TUI + Desktop — server.py + methods_*.py-├── apps/desktop/ # Electron desktop app (+ apps/shared JSON-RPC client) web/: dashboard SPA-├── acp_adapter/ # ACP server (VS Code / Zed / JetBrains)+├── ui-tui/, tui_gateway/ # Ink terminal UI + its Python JSON-RPC backend (also serves Desktop)+├── apps/desktop/ # Electron desktop app (+ apps/shared) web/: dashboard SPA├── cron/ # jobs.py + scheduler.py (+ scheduler_*.py)-├── evals/ # Offline benchmarks (codebase_navigability/, compaction/, ...)-├── scripts/ # run_tests.sh, release.py, ci/+├── pm/, hermes_platform/ # dependency/environment manager; machine facts + executable lookup+├── scripts/ # check, run_tests.sh, code_health/, ci/├── website/ # Docusaurus docs (developer-guide/ holds the long-form area docs)-└── tests/ # Pytest suite (~39k tests / ~3.7k files, Sep 2026)+└── tests/ # Pytest suite, mirrors the source tree```-**User state:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (secrets only),-`~/.hermes/logs/` (`agent.log` INFO+, `errors.log` WARNING+, `gateway.log`); all-profile-aware via `get_hermes_home()`. Browse logs with `hermes logs [--follow] [--level] [--session]`.--**Dependency chain:** `tools/registry.py` (no deps) ← `tools/*.py` (register at import) ←-`model_tools.py` (discovery) ← `run_agent.py`, `cli.py`, `batch_runner.py`, `environments/`.--### Facade + siblings layout (Sep 2026 decomposition)--Every former god file is a **facade** (public entry points + the names other packages import)-plus **siblings** `<stem>_<topic>.py` in the same directory, each owning one topic. Largest-families: `hermes_state.py` (21), `gateway/run.py` (15), `tools/mcp_tool.py` (15),-`hermes_cli/kanban.py` (14), `hermes_cli/web_server.py` (13 + 24 routers), `hermes_cli/auth.py`-(12), `tools/browser_tool.py` (11), `cli.py` (12 `hermes_cli/cli_*_mixin.py`), `run_agent.py`-(`agent/turn_*.py`, `agent_init.py`, `conversation_loop.py`).--- **Find code by topic, not by facade:** `grep -rn "def name" <dir>/<stem>_*.py`. Reading the- facade first is the expensive way (`evals/codebase_navigability/`).-- **Siblings may import each other and late-import the facade** inside functions. A facade- never imports a sibling at module level *and* gets imported by that sibling at module level.-- **Patch where production reads.** Siblings often do `from <facade> import name` inside the- function so `monkeypatch.setattr(facade, "name", ...)` is the seam; a patch on the defining- module passes silently. Check the call site's binding before writing a patch target- (blind repointing to defining modules broke 130+ tests).-- **Size and complexity are ratcheted per unit** (`scripts/code_health/config.py`): new- functions CC ≤ 20, ≤ 300 lines, nesting ≤ 6; files ≤ 2,000 lines; units already over may only- go down (a file already past 2,000 lines may not grow: move a function out to offset, or put new- tests in a new test file). Split along `<stem>_<topic>` first, in its own- commit (moved code keeps its cap and existing findings; a copy is new code); behaviour goes in a sibling,- never a facade; name ladders become a dict → handler (`_SLASH_DISPATCH`).-- **No re-export shims for internal moves** ("keep the old name importable"). Internal paths- are not API: plugins build on `ctx` and the documented ABCs. The one-time Sep 2026- decomposition compat layer for external plugins has been removed; never reintroduce one.-- **Moving a symbol means fixing its docs in the same PR:** grep `website/docs`,- `skills/`, and every `AGENTS.md` for the old `path.py` + symbol (23 doc files went stale- after the refactor). `evals/codebase_navigability/static_metrics.py <tree> <label>` measures- file/function/CC/elif distributions before/after a large PR in ~2 min.--## Code Shape Rules (all languages)--- No "defense-in-depth" wrappers, `try/except: pass` around code that cannot fail, or flags- nobody sets. Docstrings/comments keep the WHY, cut the WHAT.-- **Never infer process identity from argv substrings** (`"serve" in cmdline`; ~10 fleet-update- bugs, #90778). Use the canonical- matchers `gateway.status.looks_like_gateway_command_line` and- `hermes_cli.update_cmd._hermes_holder_subcommand`; flag sets are DERIVED from the parser- (`_holder_value_flags()`), never hand-written; match FULL cmdlines and truncate only for- display. Details: `hermes_cli/AGENTS.md`. Ratcheted (HX003).-- **Never hardcode `~/.hermes`.** `get_hermes_home()` for code paths, `display_hermes_home()`- for user-facing text (`hermes_constants`); ratcheted (HX001). `_get_profiles_root()` is- HOME-anchored on purpose, so `hermes -p x profile list` sees all profiles.-- **One process may serve many profiles; code that runs outside a turn binds the owning- profile scope explicitly.** A profile = home + secret scope + terminal scope, bound by- `gateway/run.py::_profile_runtime_scope` (turn), `tui_gateway/server.py::@_profile_scoped` +- `model_switch.py::_session_profile_runtime_scope` (RPC, teardown), `cron/scheduler_provider.py::- _profile_cron_scope` (ticker), `gateway/run_agent_cache.py::_run_release_in_profile_scope`- (eviction). `os.environ`, module globals and import-time values hold the *launch* profile's, so- an unbound read is a silent default-profile leak, never an error: home/config/`.env`-derived- module constants are a bug class — key slots by `hermes_home_key()` or resolve at call time.- Needs a binding: boot probes (`check_fn`, MCP discovery, hooks), session end/eviction, tickers,- deferred callbacks, RPC methods, config readers, thread hops (`spawn_context_thread`), child- spawns (`served_profile_child_env`, never `os.environ.copy()`). Fail-closed reads exist only after- `set_multiplex_active(True)`. Prove live with two homes (A→B→A) under multiplex, not one temp- `HERMES_HOME`. Ratcheted: HX002/HX004/HX005/HX012, PS-P05/P06; the full shape list is the- advisory `scripts/check_profile_scope_patterns.py`.-- **Machine facts and resource lookup go through `hermes_platform`.** `hermes_platform.host` is the- one answer for OS family, native architecture (`IsWow64Process2` → `platform.machine()`; never- `PROCESSOR_ARCHITECTURE` alone, it reads AMD64 under x64-on-ARM64 emulation), CPU identity, and- WSL/container/Termux. Facts are cached per process and take **no environment-variable input**, so- a hardware recognizer (`host/products.py`) cannot be set from a shell. Distinguish the control- host (where this Python runs) from the terminal execution target (SSH/container) and the Desktop- client (another machine): `host.*` answers only the first. A new bare `shutil.which` or a- hand-written known-path table outside `hermes_platform/` fails- `tests/test_managed_runtime_resolution.py` unless allowlisted with a reason; resolvers land in- `hermes_platform/resolver/`. Lookup never installs, downloads, or starts anything.-- **Argparse alias dispatch:** `add_parser("list", aliases=["ls"])` sets `dest` to the literal- the user typed (`"ls"`). Dispatch must accept both (caught PTY-testing `hermes webhook ls`).-- **Don't wire in dead code without E2E validation.** Unshipped code was dead for a reason;- E2E the real resolution chain with real imports against a temp `HERMES_HOME` first.--### TypeScript style (desktop, TUI, website, future TS packages)--Small nanostores over component state when state is shared or read by distant UI; each-feature owns its atoms (chat near chat, shared in `src/store`); rendering components use-`useStore`, non-rendering actions read `$atom.get()`; never thread state through three-components when the leaf can subscribe; persistence sits beside the atom that owns it. Route-roots stay thin (compose routes + shell, never controllers). No monolithic hooks — one narrow-job each; colocated action modules over god hooks. Pure side-effect callbacks use the terse-void form `onState={st => void setGatewayState(st)}`; async handlers make intent explicit-`onClick={() => void save()}`. Interfaces for public props and shared object shapes (not-`type X = {...}`); extend React primitives (`React.ComponentProps<'button'>`, `Omit`, `Pick`).-Table-driven beats condition ladders for ids/routes/views. `src/app` owns routes/pages,-`src/store` shared atoms, `src/lib` pure helpers.--## Dependency Pinning Policy--All dependencies carry upper bounds (litellm compromise #2796/#2810; Mini Shai-Hulud worm,-May 2026). PyPI: `>=floor,<next_major` (`"httpx>=0.28.1,<1"`); pre-1.0: `<0.(minor+2)`-(`>=0.29,<0.32`). Git URLs: 40-char commit SHA. GitHub Actions: SHA + `# vN` comment. CI-only-Python requirements: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers.-After changing `pyproject.toml`, run `hermes pm lock`, re-source `./activate`, and commit-`pyproject.toml` with `uv.lock`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).--PM owns Hermes Python dependency changes. Use `pm.sync_venv(['extra'], explicit=True)`-for declared runtime extras, `hermes pm install` for setup/sync, and `hermes pm repair`-for damaged dependencies. Do not mutate Hermes environments with raw pip or uv.-Use `pm.build_environment` for fresh build outputs and `pm.ensure_environment` for-isolated tool environments. Callers receive an interpreter or tool path, not uv.-Nix's declarative uv2nix builds and unrelated user projects remain independently owned.--The `[tool.uv] exclude-newer = "14 days"` quarantine covers **Hermes's own dependencies only**-(every registry package in core's `uv.lock`). Plugin `python_dependencies` follow the plugin's own-policy: when PM generates the plugin workspace (`pm/workspace.py::_core_release_quarantine`) the-global cutoff moves onto each core-locked package, so plugin-only packages are not filtered and a-plugin still cannot drag a core package past the window. Teknium's ruling: "plugins dont have to-abide by our 14 day rule … Only hermes' dependencies themselves have to." We recommend (not require)-plugin authors adopt their own quarantine — the developer guide and `plugin-catalog/README.md` carry-that guidance.--## Commits, Merges, PRs--- **Squash merges from stale branches silently revert recent fixes.** Before squash-merging,- bring the branch to `main` (`git fetch origin main && git reset --hard origin/main`, re-apply- the PR's commits). Verify with `git diff HEAD~1..HEAD` after merging — unexpected deletions- are a red flag.-- Salvage by cherry-pick so contributor authorship survives (see rubric).-- Tests per fix: 1–2 INVARIANT tests (behaviour contract, proven red on base), never- change-detectors; ≤ 2 tests is the salvage bar too. Reject/rewrite in salvaged diffs:- appendages to facades, new god helpers, compat aliases, wrappers.--## Testing (applies everywhere)--**ALWAYS use `scripts/run_tests.sh`**, never bare `pytest`. It enforces CI parity: credential-vars unset, `TZ=UTC`, `LANG=C.UTF-8`, `HERMES_HOME` → temp dir, and per-file subprocess-isolation via `scripts/run_tests_parallel.py` (no xdist; workers scale with CPU count) so-module-level dicts/ContextVars cannot leak between files. Direct `pytest` on a big machine-with API keys set has caused repeated "works locally, fails in CI" incidents (and the reverse).--Prepare a test interpreter with the checkout's bootstrapped Python:--```bash-python -m pm.build_env --source . --out .venv --group dev --group test-```--This is a fresh build, not an in-place sync. If the disposable output exists,-stop its processes and intentionally remove it before regeneration. The runner-clears `PYTHONPATH`, so PM shell activation alone does not supply pytest. For a-fresh output outside the checkout, set `HERMES_PYTHON` to its interpreter.--```bash-scripts/run_tests.sh # full suite-scripts/run_tests.sh tests/gateway/ # one directory-scripts/run_tests.sh tests/agent/test_foo.py -k test_x # runner is file-granular; -k narrows-scripts/run_tests.sh -v --tb=long # pytest flags pass through-```--- **Flake policy:** a failing FILE is retried once in a fresh subprocess (`--file-retries`;- `HERMES_TEST_FILE_RETRIES=0` disables); a worker killed by signal or the file timeout is never- retried (relaunching a runaway doubles the damage). Pass-on-retry is green but printed under `⚠ FLAKY`- with both outputs — a bug to fix, not noise. Timing tests must not assume a quiet runner:- wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)` races.-- **Placement mirrors the source tree.** A test lives in `tests/<top-level source dir>/` (`tests/hermes_cli/`,- `tests/agent/`, `tests/hermes_state/`, `tests/gateway/relay/`, ...); installer/updater script tests- under `tests/scripts/{install,desktop_update}/`. Only tests of root-level modules (`batch_runner`,- `utils`, `hermes_constants`, packaging) sit directly in `tests/`. No issue numbers in filenames —- cite the issue in the module docstring (`test_89315_x.py` → `test_x.py`, "Regression for #89315").-- **Placement (CI lanes):** `scripts/ci/classify_changes.py` picks jobs by changed files. A Python test- asserting about `package.json`, `package-lock.json`, `tsconfig.json`, or `.ts/.tsx/.js/- .mjs/.cjs` sources will not run on a JS-only PR (green on PR, red on `main` where the- classifier fails open). Such tests belong in the vitest suite, not `tests/*.py`.-- **Tests must not write to `~/.hermes/`.** The autouse `_isolate_hermes_home` fixture in- `tests/conftest.py` redirects `HERMES_HOME`; never hardcode `~/.hermes/` in tests. Profile- tests also mock `Path.home()` so `_get_profiles_root()` / `_get_default_hermes_home()` stay- in the temp dir (pattern: `tests/hermes_cli/test_profiles.py`):- ```python- @pytest.fixture- def profile_env(tmp_path, monkeypatch):- home = tmp_path / ".hermes"; home.mkdir()- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(home))- return home- ```- Tests that `patch.object(Path, "home", ...)` must ALSO set `HERMES_HOME` — code reads the- env var, not `Path.home()/.hermes`.--### Don't fake the host OS--Behaviour that genuinely differs per host is tested ON that host with `@pytest.mark.platforms("linux")`-/ `platforms("macos")` / `platforms("windows")`, never by patching `sys.platform`. Host-independent things stay-unmarked: pure functions that take the platform as data (`hidden_windows_child_options(opts,-is_windows=True)`) and declaration/packaging invariants ("pyproject declares `tzdata` with a-`sys_platform == 'win32'` marker"). Setting a module-level `IS_WINDOWS` flag and calling-`windows_detach_flags()` IS a fake. The line: **if the test needs the interpreter to believe it-is on another OS to pass, it belongs on that OS.** A test that walks several platforms in-sequence is split — host-native arm on Linux, other arms as their own marked tests.--One marker per test, with any number of spec strings (any-of semantics) plus-optional arch filters. To gate on several OSes, pass several specs to ONE-marker — never stack several `platforms()` decorators on one test (the-conftest rejects that at collection):--```python[email protected]("linux", "macos") # ONE marker, two specs: runs on either-def test_posix_signal_path(): ...-```--Other single-marker forms (each is a complete marker on its own):-`platforms("windows")` (native Windows only), `platforms("not macos")`-(anywhere except macOS), `platforms("windows", arch="arm64")` (native Windows-on arm64), `platforms("posix")` (Linux or macOS).--Specs: `linux`, `macos`, `windows`, `posix`, `any`, and `not <spec>`.-The historic `linux_only` / `macos_only` / `windows_only` markers have been-fully replaced — `platforms` is the only host-gating marker in the tree.--**Live Windows process-topology E2E: the `wine2e` lane.** For claims about-real Windows process behavior that mocks cannot reproduce (venv-holder-scans, process-tree parentage, launcher/worker chains, detach semantics),-there is an on-demand workflow `windows-venv-e2e.yml` that runs-`tests/hermes_cli/test_venv_holder_windows_live.py` on a real-`windows-latest` runner — spawning actual processes and driving the real-detection code, no mocked psutil. It fires ONLY on pushes to `wine2e/**`-branches (inert on PRs and main; costs nothing on normal work). The proven-workflow: write probes that pin CORRECT behavior, push to a `wine2e/`-branch to reproduce the bugs live on unfixed code, build the fix, iterate-until the lane is green, then open the PR — the live receipt on the exact-head is the Windows proof reviewers ask for. Extend the live suite when-touching that subsystem; assert against the gateway ANCESTOR found by-argv, not the direct parent (the venv shim makes every spawn a-launcher/worker chain).--**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`-decides which files an OS lane imports by resolving the quoted specs inside-`platforms(...)` (`"posix"` reaches the macOS lane, `"not linux"` reaches-both others), and the lane then selects with `-m platforms` while the-conftest's per-test host skips do the actual gating. A test gated with-`@pytest.mark.skipif(sys.platform != "win32")` therefore runs on no host at-all, silently — it is never imported by the lane that would run it, and the-full-suite lanes skip it. `skipif(sys.platform == "win32")` becomes-`platforms("posix")`; a non-host condition (`os.geteuid() == 0`) stays a-separate `skipif` beside the marker. A misspelt spec is a collection error,-not a skip. Don't stack a module-level `pytestmark =-platforms(...)` on a file whose tests carry their own host marker — the-conftest hard-rejects tests carrying two `platforms()` markers (a test-skipped on every host, reported green everywhere).-Equally, don't `pytest.skip()` the non-host rows of a `@parametrize` over-platforms — split it into one marked test per OS, or only the host's row ever-executes.--### Don't write change-detector tests--A change-detector fails whenever data *expected to change* is updated — model catalogs,-`_config_version`, enumeration counts, hardcoded model lists. It adds no coverage and taxes-every routine update. Don't: `assert "gemini-2.5-pro" in _PROVIDER_MODELS["gemini"]`,-`assert DEFAULT_CONFIG["_config_version"] == 21`, `assert len(models) == 8`. Do: `assert-"gemini" in _PROVIDER_MODELS and len(_PROVIDER_MODELS["gemini"]) >= 1` (plumbing works);-`assert raw["_config_version"] == DEFAULT_CONFIG["_config_version"]` (migration reaches-latest); `assert not (set(moonshot_models) & coding_plan_only_models)` (no leak); every-catalog model has a context-length entry (relationship). If it reads like a snapshot, delete-it; if it reads like a contract between two pieces of data, keep it. Reviewers reject new-change-detectors; authors convert them before re-review.--### Never read source code in tests--A test that reads a `.py`/`.ts`/`.tsx` file's text tests the *shape of the source*, not-behavior — banned outright. It passes when the implementation is subtly broken (regex matches-a mis-wired call site) and fails on correct refactors; it can't run against bundled/minified-artifacts; it blocks structural cleanup; it gives false confidence. Don't-`fs.readFileSync('main.ts')` + `assert.match(source, /spawn\(...hiddenWindowsChildOptions/)`.-Do extract the logic into a pure/DI-testable function and call it:-```ts-export function hiddenWindowsChildOptions(options = {}, isWindows = process.platform === 'win32') {- if (!isWindows || 'windowsHide' in options) return options- return { ...options, windowsHide: true }-}-```-If the logic lives inline in a god-file and extraction feels disruptive, that is the signal to-extract, not to regex around it.+**User state:** `~/.hermes/config.yaml` (settings), `.env` (secrets only), `logs/` (`hermes logs`);+all profile-aware via `get_hermes_home()`.++### Facade + siblings layout++Every former god file is a **facade** (public entry points + the names other packages import) plus+**siblings** `<stem>_<topic>.py`, each owning one topic (`hermes_state.py`, `gateway/run.py`,+`tools/mcp_tool.py`, `hermes_cli/kanban.py`, `hermes_cli/web_server.py`, `cli.py` →+`hermes_cli/cli_*_mixin.py`, `run_agent.py` → `agent/turn_*.py`).++- **Find code by topic:** `grep -rn "def name" <dir>/<stem>_*.py`, not by reading the facade.+- **Siblings late-import the facade** inside functions; never a module-level cycle.+- **Patch where production reads:** a sibling doing `from <facade> import name` inside the function+ makes the facade the seam; a patch on the defining module passes silently.+- **Size and complexity are ratcheted per unit** (`scripts/code_health/config.py`): new functions+ CC ≤ 20, ≤ 300 lines, nesting ≤ 6; files ≤ 2,000 lines; units already over may only go down (move+ a function into a sibling to offset growth, or put new tests in a new test file). Behaviour goes+ in a sibling, never a facade; name ladders become a dict → handler.+- **No re-export shims for internal moves;** internal paths are not API. Moving a symbol means+ fixing its docs in the same PR (grep `website/docs`, `skills/`, every `AGENTS.md`).++## Rules that apply everywhere++- **No defensive clutter:** no wrappers or `try/except: pass` around code that cannot fail, no flags+ nobody sets, no dead code wired in without E2E proof. Comments keep the WHY, cut the WHAT.+- **Never infer process identity from argv substrings;** use+ `gateway.status.looks_like_gateway_command_line` / `hermes_cli.update_cmd._hermes_holder_subcommand`+ (HX003; details `hermes_cli/AGENTS.md`).+- **Never hardcode `~/.hermes`:** `get_hermes_home()` for paths, `display_hermes_home()` for text+ (HX001). `_get_profiles_root()` is HOME-anchored on purpose.+- **One process serves many profiles.** Code that runs outside a turn (boot probes, eviction,+ tickers, deferred callbacks, RPC methods, thread hops, child spawns) binds the owning profile scope+ explicitly; `os.environ`, module globals and import-time values hold the launch profile's, so an+ unbound read is a silent default-profile leak. Binding points and seams: `gateway/AGENTS.md`+ § Profile scope (HX002/HX004/HX005/HX012, PS-P05/P06).+- **Machine facts and executable lookup go through `hermes_platform`** (`hermes_platform/AGENTS.md`).+- **Dependencies carry upper bounds** (`>=floor,<next_major`; git URLs and Actions pinned to a SHA);+ after editing `pyproject.toml` run `hermes pm lock` and commit `uv.lock`; never mutate a Hermes+ environment with raw pip/uv. Full policy: `pm/AGENTS.md`.+- **TypeScript (desktop, TUI, website):** feature-owned nanostores over threaded state, thin route+ roots, narrow hooks and colocated action modules, `interface` for props and shared shapes,+ table-driven dispatch over condition ladders; `src/app` routes, `src/store` atoms, `src/lib` pure+ helpers.+- **Commits and PRs:** rebase onto `main` before merging (a squash from a stale branch silently+ reverts newer fixes); 1–2 invariant tests per fix, proven red on the base.+- **Tests:** always `scripts/run_tests.sh`, never bare `pytest`; behaviour contracts, never+ change-detectors or source-reading tests; host-specific behaviour is tested on that host with+ `@pytest.mark.platforms(...)`, never by faking `sys.platform`; tests never write to `~/.hermes/`.+ Everything else: `tests/AGENTS.md`.## Routing Table — working in X → read X/AGENTS.md| Area | Read | Covers ||---|---|---|-| `run_agent.py`, `agent/` | `agent/AGENTS.md` | AIAgent + mixins, turn phases, caching integrity, message-flow invariants, compression, model/aux resolution |-| `cli.py`, `hermes_cli/`, `main.py` | `hermes_cli/AGENTS.md` | CLI mixins, `_SLASH_DISPATCH`, slash registry, config system + loaders, skins, `hermes update` pipeline, profiles / multiplex |-| `gateway/` | `gateway/AGENTS.md` | Adapters, two message guards, streaming contract, background notifications, gateway vs desktop lifecycle, token locks, scoped secrets |-| `tools/`, `toolsets.py`, `model_tools.py` | `tools/AGENTS.md` | Adding tools, registry, toolsets, delegation, cross-tool references, backends |-| `plugins/`, `hermes_cli/plugins*.py` | `plugins/AGENTS.md` | Plugin kinds, native compat contract, in-tree policy |-| `plugin-catalog/` entries, catalog reviews | `plugin-catalog/README.md` (canonical admission rules), `website/docs/developer-guide/plugins/catalog-submission.md` (mirror + submission guide) | What a listed plugin may do; keep the two rule blocks identical |-| `tui_gateway/`, `ui-tui/` | `tui_gateway/AGENTS.md` | Process model, JSON-RPC transport, key surfaces, slash flow, dev commands |-| `web/`, `hermes_cli/web_routers/` | `web/AGENTS.md` | Dashboard embeds the real TUI; what React may and may not rebuild |-| `apps/desktop/` | `apps/desktop/AGENTS.md`, `apps/desktop/src/AGENTS.md` | Desktop judgment guide; `serve` backend, slash palette curation, Bot Mode canonical chat |-| `skills/`, `optional-skills/`, `agent/curator*.py` | `skills/AGENTS.md` | Frontmatter, HARDLINE authoring standards, curator |-| `cron/`, kanban (`hermes_cli/kanban*.py`, `tools/kanban_tools.py`, `plugins/kanban/`) | `cron/AGENTS.md` | Scheduler invariants, job fields, kanban board/dispatcher |-| `gateway/platforms/` new adapter | `gateway/platforms/ADDING_A_PLATFORM.md` | Step-by-step adapter guide |-| profiles / multiplex / secret scope (any area) | `gateway/AGENTS.md` § Profile scope, `website/docs/user-guide/multi-profile-gateways.md` § What is isolated per profile | which execution points bind scope, what is isolated per profile |--Long-form background lives in `website/docs/developer-guide/` (agent-loop, prompt-assembly,-context-compression-and-caching, gateway-internals, tools-runtime, plugins/, cron-internals,-session-storage, ...). Workflow rules (PR/issue/review/salvage process) live in the-`hermes-agent-dev` skill, not here.+| `run_agent.py`, `agent/` | `agent/AGENTS.md` | turn phases, caching and message-flow invariants, compression, model/aux resolution |+| `cli.py`, `hermes_cli/` | `hermes_cli/AGENTS.md` | CLI mixins, slash registry, config system, skins, `hermes update`, profiles / multiplex |+| `gateway/` | `gateway/AGENTS.md` | adapters, message guards, streaming, notifications, token locks, § Profile scope |+| `gateway/platforms/` new adapter | `gateway/platforms/ADDING_A_PLATFORM.md` | step-by-step adapter guide |+| `tools/`, `toolsets.py`, `model_tools.py` | `tools/AGENTS.md` | adding tools, registry, toolsets, delegation, session-scoped surface tools |+| `plugins/`, `hermes_cli/plugins*.py` | `plugins/AGENTS.md` | plugin kinds, native compat contract, in-tree policy |+| `plugin-catalog/` | `plugin-catalog/README.md` | catalog admission rules (mirrored in the developer guide; keep identical) |+| `tui_gateway/`, `ui-tui/` | `tui_gateway/AGENTS.md` | process model, JSON-RPC transport, slash flow |+| `web/`, `hermes_cli/web_routers/` | `web/AGENTS.md` | dashboard embeds the real TUI |+| `apps/desktop/` | `apps/desktop/AGENTS.md`, `apps/desktop/src/AGENTS.md` | `serve` backend, slash palette, Bot Mode |+| `skills/`, `optional-skills/`, `agent/curator*.py` | `skills/AGENTS.md` | frontmatter, authoring standards, curator |+| `cron/`, kanban | `cron/AGENTS.md` | scheduler invariants, job fields, kanban dispatcher |+| `tests/` | `tests/AGENTS.md` | runner, placement, OS markers, `wine2e`, banned test shapes |+| `pm/`, `pyproject.toml` | `pm/AGENTS.md` | pinning policy, PM-owned environments, plugin quarantine |+| `hermes_platform/` | `hermes_platform/AGENTS.md` | host facts, resolvers |++Long-form background: `website/docs/developer-guide/`. Workflow rules (PR/issue/review/salvage+process) live in the `hermes-agent-dev` skill, not here.diff --git a/apps/desktop/src/lib/keybinds/combo.test.ts b/apps/desktop/src/lib/keybinds/combo.test.tsindex 73b95b206d7..f79e6581be0 100644--- a/apps/desktop/src/lib/keybinds/combo.test.ts+++ b/apps/desktop/src/lib/keybinds/combo.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'// Host-native: jsdom never reports a Mac platform, so `IS_MAC` is false here.-// Mac-only Control/Cmd branches are not faked (AGENTS.md "Don't fake the host OS").+// Mac-only Control/Cmd branches are not faked (tests/AGENTS.md "Don't fake the host OS").import { actionAllowedInInput, canonicalizeCombo, comboFromEvent } from './combo'function keydown(init: KeyboardEventInit): KeyboardEvent {diff --git a/hermes_platform/AGENTS.md b/hermes_platform/AGENTS.mdnew file mode 100644index 00000000000..fea421b735f--- /dev/null+++ b/hermes_platform/AGENTS.md@@ -0,0 +1,14 @@+# hermes_platform/ — machine facts and resource lookup++Applies on top of the root `AGENTS.md`.++**Machine facts and resource lookup go through `hermes_platform`.** `hermes_platform.host` is the+one answer for OS family, native architecture (`IsWow64Process2` → `platform.machine()`; never+`PROCESSOR_ARCHITECTURE` alone, it reads AMD64 under x64-on-ARM64 emulation), CPU identity, and+WSL/container/Termux. Facts are cached per process and take **no environment-variable input**, so+a hardware recognizer (`host/products.py`) cannot be set from a shell. Distinguish the control+host (where this Python runs) from the terminal execution target (SSH/container) and the Desktop+client (another machine): `host.*` answers only the first. A new bare `shutil.which` or a+hand-written known-path table outside `hermes_platform/` fails+`tests/test_managed_runtime_resolution.py` unless allowlisted with a reason; resolvers land in+`hermes_platform/resolver/`. Lookup never installs, downloads, or starts anything.diff --git a/pm/AGENTS.md b/pm/AGENTS.mdnew file mode 100644index 00000000000..34f095f7eb6--- /dev/null+++ b/pm/AGENTS.md@@ -0,0 +1,28 @@+# pm/ — dependencies and Hermes environments++Applies on top of the root `AGENTS.md` (which carries the short form of the pinning rule).++## Dependency pinning policy++All dependencies carry upper bounds (litellm compromise #2796/#2810; Mini Shai-Hulud worm,+May 2026). PyPI: `>=floor,<next_major` (`"httpx>=0.28.1,<1"`); pre-1.0: `<0.(minor+2)`+(`>=0.29,<0.32`). Git URLs: 40-char commit SHA. GitHub Actions: SHA + `# vN` comment. CI-only+Python requirements: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers.+After changing `pyproject.toml`, run `hermes pm lock`, re-source `./activate`, and commit+`pyproject.toml` with `uv.lock`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).++PM owns Hermes Python dependency changes. Use `pm.sync_venv(['extra'], explicit=True)`+for declared runtime extras, `hermes pm install` for setup/sync, and `hermes pm repair`+for damaged dependencies. Do not mutate Hermes environments with raw pip or uv.+Use `pm.build_environment` for fresh build outputs and `pm.ensure_environment` for+isolated tool environments. Callers receive an interpreter or tool path, not uv.+Nix's declarative uv2nix builds and unrelated user projects remain independently owned.++The `[tool.uv] exclude-newer = "14 days"` quarantine covers **Hermes's own dependencies only**+(every registry package in core's `uv.lock`). Plugin `python_dependencies` follow the plugin's own+policy: when PM generates the plugin workspace (`pm/workspace.py::_core_release_quarantine`) the+global cutoff moves onto each core-locked package, so plugin-only packages are not filtered and a+plugin still cannot drag a core package past the window. Teknium's ruling: "plugins dont have to+abide by our 14 day rule … Only hermes' dependencies themselves have to." We recommend (not require)+plugin authors adopt their own quarantine — the developer guide and `plugin-catalog/README.md` carry+that guidance.diff --git a/scripts/check_profile_scope_patterns.py b/scripts/check_profile_scope_patterns.pyindex d7d41afcc4b..c57245ef054 100644--- a/scripts/check_profile_scope_patterns.py+++ b/scripts/check_profile_scope_patterns.py@@ -6,7 +6,7 @@ One Hermes process may serve many profiles (multiplex gateway, Desktop/dashboard``scripts/ci/profile_scope_patterns.json`` is a call-site shape that turned out to beprofile-sensitive at least once — a child env built from ``os.environ``, a raw ``os.getenv`` of aplatform credential, an RPC decorator that binds the home but not the secret scope, a bare PID-liveness check. The invariant itself is in the root ``AGENTS.md`` (§ Code Shape Rules).+liveness check. The invariant itself is in the root ``AGENTS.md`` (§ Rules that apply everywhere).Advisory by construction: it prints ``file:line <id>/<class> why`` for every hit and ALWAYSexits 0, because most patterns have legitimate sites (a standalone ``hermes -p x`` process where@@ -149,7 +149,7 @@ def main(argv: list[str] | None = None) -> int:print("profile-scope patterns: 0 findings")return 0print(f"profile-scope patterns: {len(findings)} finding(s) — ADVISORY, read each against its scope hint "- f"(root AGENTS.md § Code Shape Rules; scripts/ci/profile_scope_patterns.json)")+ f"(root AGENTS.md § Rules that apply everywhere; scripts/ci/profile_scope_patterns.json)")for f in findings:print(f"{f.path}:{f.line} {f.pattern_id}/{f.pattern_class} {f.why}")print(f" | {f.text}")diff --git a/scripts/ci/check_os_marker_fakes.py b/scripts/ci/check_os_marker_fakes.pyindex e6fd6ca7695..2a88182297c 100644--- a/scripts/ci/check_os_marker_fakes.py+++ b/scripts/ci/check_os_marker_fakes.py@@ -7,7 +7,7 @@ and then runs ``-m platforms("macos")``. A file whose tests only pass because ththe interpreter believe it is on macOS (``is_macos`` patched to ``True``,``sys.platform`` set to ``"darwin"``) but that carries no marker is invisible tothat lane: it is green on Linux over a faked branch and never imported on the-host it exists for (#111866). Root ``AGENTS.md`` § "Don't fake the host OS" is+host it exists for (#111866). ``tests/AGENTS.md`` § "Don't fake the host OS" isthe rule; this check makes a violation a red job instead of a review catch.Flags, per ``tests/**/test_*.py`` without a whole-word ``platforms("macos")``:@@ -108,7 +108,7 @@ def main(argv: list[str]) -> int:if new:print(f"\n{len(new)} test file(s) make the interpreter believe it is on macOS but carry no "- f"`{MARKER}` marker, so the macOS lane never imports them (AGENTS.md § Don't fake the "+ f"`{MARKER}` marker, so the macOS lane never imports them (tests/AGENTS.md § Don't fake the "f"host OS). Split the macOS arm into its own `@pytest.mark.{MARKER}` test that runs the "f"real branch, or mark `# {OPT_OUT} — <why>` on a host-independent line.",file=sys.stderr,diff --git a/tests/AGENTS.md b/tests/AGENTS.mdnew file mode 100644index 00000000000..175ba94d361--- /dev/null+++ b/tests/AGENTS.md@@ -0,0 +1,152 @@+# tests/ — how Hermes tests are written and run++Applies on top of the root `AGENTS.md`. Read it before adding or changing any test.++## Running tests++**ALWAYS use `scripts/run_tests.sh`**, never bare `pytest`. It enforces CI parity: credential+vars unset, `TZ=UTC`, `LANG=C.UTF-8`, `HERMES_HOME` → temp dir, and per-file subprocess+isolation via `scripts/run_tests_parallel.py` (no xdist; workers scale with CPU count) so+module-level dicts/ContextVars cannot leak between files. Direct `pytest` on a big machine+with API keys set has caused repeated "works locally, fails in CI" incidents (and the reverse).++Prepare a test interpreter with the checkout's bootstrapped Python:++```bash+python -m pm.build_env --source . --out .venv --group dev --group test+```++This is a fresh build, not an in-place sync. If the disposable output exists,+stop its processes and intentionally remove it before regeneration. The runner+clears `PYTHONPATH`, so PM shell activation alone does not supply pytest. For a+fresh output outside the checkout, set `HERMES_PYTHON` to its interpreter.++```bash+scripts/run_tests.sh # full suite+scripts/run_tests.sh tests/gateway/ # one directory+scripts/run_tests.sh tests/agent/test_foo.py -k test_x # runner is file-granular; -k narrows+scripts/run_tests.sh -v --tb=long # pytest flags pass through+```++- **Flake policy:** a failing FILE is retried once in a fresh subprocess (`--file-retries`;+ `HERMES_TEST_FILE_RETRIES=0` disables); a worker killed by signal or the file timeout is never+ retried (relaunching a runaway doubles the damage). Pass-on-retry is green but printed under `⚠ FLAKY`+ with both outputs — a bug to fix, not noise. Timing tests must not assume a quiet runner:+ wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)` races.+- **Placement mirrors the source tree.** A test lives in `tests/<top-level source dir>/` (`tests/hermes_cli/`,+ `tests/agent/`, `tests/hermes_state/`, `tests/gateway/relay/`, ...); installer/updater script tests+ under `tests/scripts/{install,desktop_update}/`. Only tests of root-level modules (`batch_runner`,+ `utils`, `hermes_constants`, packaging) sit directly in `tests/`. No issue numbers in filenames —+ cite the issue in the module docstring (`test_89315_x.py` → `test_x.py`, "Regression for #89315").+- **Placement (CI lanes):** `scripts/ci/classify_changes.py` picks jobs by changed files. A Python test+ asserting about `package.json`, `package-lock.json`, `tsconfig.json`, or `.ts/.tsx/.js/+ .mjs/.cjs` sources will not run on a JS-only PR (green on PR, red on `main` where the+ classifier fails open). Such tests belong in the vitest suite, not `tests/*.py`.+- **Tests must not write to `~/.hermes/`.** The autouse `_isolate_hermes_home` fixture in+ `tests/conftest.py` redirects `HERMES_HOME`; never hardcode `~/.hermes/` in tests. Profile+ tests also mock `Path.home()` so `_get_profiles_root()` / `_get_default_hermes_home()` stay+ in the temp dir (pattern: `tests/hermes_cli/test_profiles.py`):+ ```python+ @pytest.fixture+ def profile_env(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"; home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+ ```+ Tests that `patch.object(Path, "home", ...)` must ALSO set `HERMES_HOME` — code reads the+ env var, not `Path.home()/.hermes`.++## Don't fake the host OS++Behaviour that genuinely differs per host is tested ON that host with `@pytest.mark.platforms("linux")`+/ `platforms("macos")` / `platforms("windows")`, never by patching `sys.platform`. Host-independent things stay+unmarked: pure functions that take the platform as data (`hidden_windows_child_options(opts,+is_windows=True)`) and declaration/packaging invariants ("pyproject declares `tzdata` with a+`sys_platform == 'win32'` marker"). Setting a module-level `IS_WINDOWS` flag and calling+`windows_detach_flags()` IS a fake. The line: **if the test needs the interpreter to believe it+is on another OS to pass, it belongs on that OS.** A test that walks several platforms in+sequence is split — host-native arm on Linux, other arms as their own marked tests.++One marker per test, with any number of spec strings (any-of semantics) plus+optional arch filters. To gate on several OSes, pass several specs to ONE+marker — never stack several `platforms()` decorators on one test (the+conftest rejects that at collection):++```python[email protected]("linux", "macos") # ONE marker, two specs: runs on either+def test_posix_signal_path(): ...+```++Other single-marker forms (each is a complete marker on its own):+`platforms("windows")` (native Windows only), `platforms("not macos")`+(anywhere except macOS), `platforms("windows", arch="arm64")` (native Windows+on arm64), `platforms("posix")` (Linux or macOS).++Specs: `linux`, `macos`, `windows`, `posix`, `any`, and `not <spec>`.+The historic `linux_only` / `macos_only` / `windows_only` markers have been+fully replaced — `platforms` is the only host-gating marker in the tree.++**Live Windows process-topology E2E: the `wine2e` lane.** For claims about+real Windows process behavior that mocks cannot reproduce (venv-holder+scans, process-tree parentage, launcher/worker chains, detach semantics),+there is an on-demand workflow `windows-venv-e2e.yml` that runs+`tests/hermes_cli/test_venv_holder_windows_live.py` on a real+`windows-latest` runner — spawning actual processes and driving the real+detection code, no mocked psutil. It fires ONLY on pushes to `wine2e/**`+branches (inert on PRs and main; costs nothing on normal work). The proven+workflow: write probes that pin CORRECT behavior, push to a `wine2e/`+branch to reproduce the bugs live on unfixed code, build the fix, iterate+until the lane is green, then open the PR — the live receipt on the exact+head is the Windows proof reviewers ask for. Extend the live suite when+touching that subsystem; assert against the gateway ANCESTOR found by+argv, not the direct parent (the venv shim makes every spawn a+launcher/worker chain).++**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`+decides which files an OS lane imports by resolving the quoted specs inside+`platforms(...)` (`"posix"` reaches the macOS lane, `"not linux"` reaches+both others), and the lane then selects with `-m platforms` while the+conftest's per-test host skips do the actual gating. A test gated with+`@pytest.mark.skipif(sys.platform != "win32")` therefore runs on no host at+all, silently — it is never imported by the lane that would run it, and the+full-suite lanes skip it. `skipif(sys.platform == "win32")` becomes+`platforms("posix")`; a non-host condition (`os.geteuid() == 0`) stays a+separate `skipif` beside the marker. A misspelt spec is a collection error,+not a skip. Don't stack a module-level `pytestmark =+platforms(...)` on a file whose tests carry their own host marker — the+conftest hard-rejects tests carrying two `platforms()` markers (a test+skipped on every host, reported green everywhere).+Equally, don't `pytest.skip()` the non-host rows of a `@parametrize` over+platforms — split it into one marked test per OS, or only the host's row ever+executes.++## Don't write change-detector tests++A change-detector fails whenever data *expected to change* is updated — model catalogs,+`_config_version`, enumeration counts, hardcoded model lists. It adds no coverage and taxes+every routine update. Don't: `assert "gemini-2.5-pro" in _PROVIDER_MODELS["gemini"]`,+`assert DEFAULT_CONFIG["_config_version"] == 21`, `assert len(models) == 8`. Do: `assert+"gemini" in _PROVIDER_MODELS and len(_PROVIDER_MODELS["gemini"]) >= 1` (plumbing works);+`assert raw["_config_version"] == DEFAULT_CONFIG["_config_version"]` (migration reaches+latest); `assert not (set(moonshot_models) & coding_plan_only_models)` (no leak); every+catalog model has a context-length entry (relationship). If it reads like a snapshot, delete+it; if it reads like a contract between two pieces of data, keep it. Reviewers reject new+change-detectors; authors convert them before re-review.++## Never read source code in tests++A test that reads a `.py`/`.ts`/`.tsx` file's text tests the *shape of the source*, not+behavior — banned outright. It passes when the implementation is subtly broken (regex matches+a mis-wired call site) and fails on correct refactors; it can't run against bundled/minified+artifacts; it blocks structural cleanup; it gives false confidence. Don't+`fs.readFileSync('main.ts')` + `assert.match(source, /spawn\(...hiddenWindowsChildOptions/)`.+Do extract the logic into a pure/DI-testable function and call it:+```ts+export function hiddenWindowsChildOptions(options = {}, isWindows = process.platform === 'win32') {+ if (!isWindows || 'windowsHide' in options) return options+ return { ...options, windowsHide: true }+}+```+If the logic lives inline in a god-file and extraction feels disruptive, that is the signal to+extract, not to regex around it.diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 8662aa239db..e6b302e9517 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -153,3 +153,26 @@ interrupted entry's `summary` is the child's last real assistant text (`_build_rassert contracts ("every registered tool has a toolset", "no schema description names a tool fromanother toolset") rather than tool counts. Approval/security-boundary tools are E2E'd with realimports against a temp `HERMES_HOME` (see `tests/tools/test_approval_config_readonly.py`).++## Surface capability is a property of the SESSION, never of the process env++A tool that works only because of *who is on the other end* (desktop panes, in-app browser,+message reactions, Projects) must resolve availability from the **session's own source**, not+from an env var on the backend. Client and backend are separate machines: the desktop app may+drive a locally spawned backend, one over SSH, one behind URL + token, or Hermes Cloud, and+only the first two carry `HERMES_DESKTOP=1`. An env-keyed gate is a silent no-op on the other+topologies — the tool is stripped from the schema while the platform hint tells the model it+is "inside the Hermes desktop app". The pattern:++- **The toolset is the surface gate.** Keep such tools off `_HERMES_CORE_TOOLS` and in a named+ toolset (`desktop_ui`, `project`); the GUI gateway's `_load_enabled_toolsets(platform)`+ folds it in when the session's platform says GUI. One resolver, every topology.+- **`check_fn` answers reachability or opt-in, not surface.** "Is the bridge wired?" — fine.+ "Was I spawned by Electron?" — not. `check_fn` results are TTL-cached process-wide+ (`tools/registry.py`); a per-session answer does not belong there.+- **Ask which identity you mean.** `HERMES_DESKTOP=1` legitimately means "this backend was+ spawned by the app" (cron ticker, web-dist handling). It does NOT mean "a GUI is watching";+ the embedded terminal pane (`hermes --tui` against that backend) is the counterexample.++Test: if the capability still makes sense with the client on another machine, it is+session-scoped. Assert the GUI session gets the tool **with the env var absent**.diff --git a/ui-tui/src/__tests__/platform.test.ts b/ui-tui/src/__tests__/platform.test.tsindex 4c292d1766e..6129946e0f1 100644--- a/ui-tui/src/__tests__/platform.test.ts+++ b/ui-tui/src/__tests__/platform.test.ts@@ -13,7 +13,7 @@ import {// These cover the non-macOS (host-native on the Linux CI lane) arms. The// macOS arms key off a module-level `isMac` and would need the interpreter to-// believe it is on darwin — see AGENTS.md "Don't fake the host OS".+// believe it is on darwin — see tests/AGENTS.md "Don't fake the host OS".const describeHost = describe.skipIf(isMac)describeHost('platform action modifier', () => {diff --git a/website/docs/developer-guide/contributing.md b/website/docs/developer-guide/contributing.mdindex 3f75485348a..aed4c50fd66 100644--- a/website/docs/developer-guide/contributing.md+++ b/website/docs/developer-guide/contributing.md@@ -20,6 +20,123 @@ We value contributions in this order:6. **New tools** — rarely needed; most capabilities should be skills7. **Documentation** — fixes, clarifications, new examples+## Contribution rubric++The project's intent layer, summarised in the root `AGENTS.md`; this is the long form with the+examples. Hermes ships a lot: most merges are bug fixes and the product surface (platforms,+providers, models, desktop/TUI features) expands on purpose. The restraint targets the core agent+and the model tool schema, where every addition is paid for on every API call: expansive at the+edges, conservative at the waist.++### What we want++- **Fix real bugs, well.** Reproduce the symptom on current `main`, point to the exact line+ where it manifests, and fix the whole bug class — sibling call paths included.+- **Expand reach at the edges.** New adapters, channels, providers, models, desktop/TUI/+ dashboard features land routinely, including large ones — as long as they integrate with+ the existing setup/config UX (`hermes tools`, `hermes setup`, auto-install) rather than+ bolting on a raw env var.+- **Refactor god-files into clean modules.** Huge mechanical `+N/-N` extraction PRs are+ wanted work. "Every line traces to the request" applies to *feature* PRs; a declared+ refactor's request IS the extraction.+- **Keep the core narrow.** Prefer, in order: extend existing code → CLI command + skill →+ service-gated tool (`check_fn`) → plugin → MCP server in the catalog → new core tool (last+ resort). See the Footprint Ladder below.+- **Extend, don't duplicate.** Check whether existing infrastructure covers the use case+ before adding a module/manager/hook. When 3+ open PRs integrate the same *category*+ (memory backends, providers, notifiers), design an ABC + orchestrator, wrap the existing+ built-in as the first provider, and turn the competing PRs into plugins against it.+- **Behavior contracts over snapshots.** Tests assert how two pieces of data relate, never+ freeze a current value (see `tests/AGENTS.md`).+- **E2E validation, not just green unit mocks.** Anything touching resolution chains, config+ propagation, security boundaries, remote backends, or file/network I/O must exercise the+ real path with real imports against a temp `HERMES_HOME` — two of them (A→B→A) when the+ change touches profile scope. Mocks hide integration bugs.+- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict role+ alternation (never two same-role messages in a row; never a synthetic user message injected+ mid-loop), and a system prompt byte-stable for the life of a conversation.+- **Contributor credit preserved.** Salvage external work by cherry-picking (rebase-merge) so+ authorship survives; build on top rather than reimplementing.++### What we don't want (rejected even when well-built)++- **Speculative infrastructure.** Hooks/callbacks/extension points with no concrete consumer.+ Adding a hook is easy; removing one after plugins depend on it is hard. A hook with a real,+ stated use case is NOT speculative even if the consumer ships separately.+- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets only. Behavioral+ settings (timeouts, thresholds, flags, display prefs) go in `config.yaml`; bridge to an+ internal env var in code if the mechanism needs one. Reject "set X in your .env" docs+ unless X is a credential.+- **A new core tool when terminal + file (or a skill) already do the job.** If the only+ barrier is file visibility on a remote backend, fix the mount, not the toolset.+- **Lazy-reading escape hatches on instructional tools.** No `offset`/`limit` pagination on+ tools that load content the agent must read fully (skills, prompts, playbooks) — models+ read page 1 and skip the rest.+- **"Fixes" that destroy the feature they secure.** Read the original intent+ (`git log -p -S`) before restricting behavior; find a fix that preserves the feature.+- **Outbound telemetry / usage attribution without opt-in gating.** No analytics,+ third-party identifier tagging, or attribution tags until a generic user-facing opt-in+ (config gate + setup prompt + `hermes tools` toggle) exists. Park behind a label.+- **Change-detector tests, cache-breaking mid-conversation, dead code wired in without E2E+ proof, plugins that touch core files.** Plugins work within the ABCs/hooks we provide; if+ one needs more, widen the generic plugin surface, never special-case it in core.+- **Third-party products integrated into the core tree.** Observability backends, vendor+ SaaS connectors, analytics dashboards, and other "someone else's product" plugins do NOT+ land under `plugins/` — every one becomes our burden against a fast-moving core for a+ backend we don't own. Ship as a **standalone plugin repo** (`~/.hermes/plugins/` or pip+ entry point), promoted in the Nous Research Discord `#plugins-skills-and-skins`. This is a+ coupling decision, not a quality bar; such PRs are closed with a pointer to publish.++### Before you call it a bug — verify the premise (and when NOT to close)++The most common reason a well-written PR is closed is a **wrong premise** or treating an+**intentional design as a gap**. These patterns tell a reviewer what to scrutinize and tell+the sweeper when a PR is NOT safe to close (when in doubt, leave it open for a human):++- **"Intentional design, not a gap."** Ask whether the isolation IS the design. Profiles are+ independent islands on purpose: a PR adding live config inheritance from the default+ profile was closed because coupling profiles is exactly what the design prevents (`--clone`+ already covers "start from my default"). Read `git log -p -S "<symbol>"` before assuming+ something is unfinished.+- **"The premise doesn't hold against how X actually works."** Trace the real runtime before+ accepting a rationale. Real closes: a rate-limit "re-probe during cooldown" PR (the breaker+ trips only on a *confirmed-empty* bucket, so re-probing hammers a bucket proven empty); a+ usage fix whose new branch **never executes** because an earlier guard already popped the+ state. If you can't point to the exact line where the bug manifests AND show the fix changes+ that line's behavior, the premise is unverified.+- **"The absence was deliberate."** Restoring "missing" `__init__.py` files made a test tree+ importable as a dotted package that shadowed the real plugin and deleted its `register()`+ at import time. The omission was load-bearing.+- **"Overreached / resurrected an approach we moved past."** Scope creep beyond the agreed+ base, or reviving a direction maintainers closed, is rejected even when it works. Offer the+ rest as a focused follow-up.++Throughline: **verify the claim AND the intent against the codebase before writing or merging+a fix.** A reproduction on current `main` plus a line-level account beats a plausible+rationale. When unsure about intent, asking is cheaper than shipping a fix that fights the+design.++### The Footprint Ladder (new capability decision)++Choose the highest (least-footprint) rung that correctly solves the problem:++1. **Extend existing code** — a variation of something that exists. Zero new surface.+2. **CLI command + skill** — config/state/infra expressible as shell commands; the agent runs+ `hermes <subcommand>` guided by a skill. Default for subscriptions, scheduled tasks,+ service setup (`hermes webhook`, `hermes cron`, `hermes tools`).+3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND only appears when+ a prerequisite is configured (Home Assistant tools, memory-provider tools). This rung gates+ reachability/opt-in process-wide; a capability that varies per SESSION (who is watching) is+ a named toolset folded in by the toolset resolver, not a `check_fn` — see `tools/AGENTS.md` § "Surface+ capability is a property of the SESSION".+4. **Plugin** — third-party/niche/user-specific; lives in `~/.hermes/plugins/` or a pip+ package, discovered at runtime.+5. **MCP server (in the catalog)** — genuinely a tool but not core-fundamental. Zero permanent+ core-schema footprint, reusable by any MCP host, reached via the built-in MCP client.+6. **New core tool** — only when fundamental, broadly useful to nearly every user, and+ unreachable via terminal + file or an MCP server (terminal, read_file, web_search,+ browser_navigate).+## Common contribution paths- Building a custom/local tool without modifying Hermes core? Start with [Build a Hermes Plugin](../developer-guide/plugins/index.md)diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.mdindex 8d245291e92..664219778b6 100644--- a/website/docs/reference/package-management.md+++ b/website/docs/reference/package-management.md@@ -431,7 +431,7 @@ before starting another Python process.### Syncing after you edit pyproject.toml1. Edit `pyproject.toml`. Pin every dependency as the- [Dependency Pinning Policy](https://github.com/NousResearch/hermes-agent/blob/main/AGENTS.md#dependency-pinning-policy)+ [Dependency Pinning Policy](https://github.com/NousResearch/hermes-agent/blob/main/pm/AGENTS.md#dependency-pinning-policy)requires. Express platform limits with PEP 508 markers, or gate a wholeextra in `[tool.hermes.extras-platforms]`.2. Relock: