Skip to content

The agent that grows with you

docs(agents): split AGENTS.md into root + per-area files (≤8k each, the subdirectory-hint cap)

Teknium4441a2a28d21
diff --git a/AGENTS.md b/AGENTS.md
index 32d03139d78..aecd44860c6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,1833 +1,424 @@
# 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.
**Never give up on the right solution.**
## What Hermes Is
-Hermes is a personal AI agent that runs the same agent core across a CLI, a
-messaging gateway (Telegram, Discord, Slack, and ~20 other platforms), a TUI,
-and an Electron desktop app. It learns across sessions (memory + skills),
-delegates to subagents, runs scheduled jobs, and drives a real terminal and
-browser. It is extended primarily through **plugins and skills**, not by
-growing the core.
-
-Two properties 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, 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).
-- **The core is a narrow waist; capability lives at the edges.** Every model
- tool we add is sent on every API call, so the bar for a new *core* tool is
- high. Most new capability should arrive as a CLI command + skill, a
- service-gated tool, or a plugin — not as core surface.
+Hermes is a personal AI agent that runs the same agent core across a CLI, a messaging
+gateway (Telegram, Discord, Slack, ~20 platforms), a TUI, and an Electron desktop app. It
+learns across sessions (memory + skills), delegates to subagents, runs scheduled jobs, and
+drives a real terminal and browser. It is extended primarily through **plugins and skills**,
+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).
+- **The core is a narrow waist; capability lives at the edges.** Every model tool is sent on
+ every API call, so the bar for a new *core* tool is high. New capability should arrive as a
+ CLI command + skill, a service-gated tool, or a plugin — not as core surface.
## Contribution Rubric — What We Want / What We Don't
-This is the project's intent layer. Use it two ways:
-
-1. **For humans and for your own work** — what gets merged and what gets
- rejected, so a contribution aims at the target.
-2. **For automated review (the triage sweeper)** — guidance on when a PR is
- safe to close on the three allowed reasons (`implemented_on_main`,
- `cannot_reproduce`, `incoherent`) and, just as important, **when NOT to
- close** one. Taste-based "we don't want this / out of scope" closes are NOT
- an automated decision — those stay with a human maintainer. The sweeper's
- job here is to recognize design intent and *avoid wrongly closing a
- legitimate contribution*, not to make the won't-implement call itself.
+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*.
-Read the balance right: Hermes ships a **lot** — most merges are bug fixes to
-real reported behavior, and the product surface (platforms, channels,
-providers, models, desktop/TUI features) expands aggressively and on purpose.
-The restraint below is aimed squarely at the **core agent + the 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 is allowed to grow. We are expansive at the edges and
-conservative at the waist.
+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.
### What we want
-- **Fix real bugs, well.** The bulk of what lands is `fix(...)` against an
- actual reported symptom. A good fix reproduces the symptom on current
- `main`, points to the exact line where it manifests, and fixes the whole bug
- class — sibling call paths included — not just the one site the reporter hit.
-- **Expand reach at the edges.** New platform adapters, channels, providers,
- models, and desktop/TUI/dashboard features are welcome and land routinely,
- including large ones (a new messaging channel, a session-cap feature, a
- Windows PTY bridge). Breadth in the product is a goal, not a footprint
- concern — as long as it integrates 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.** Extracting a multi-thousand-line
- cluster out of `cli.py` / `run_agent.py` / `gateway/run.py` into a focused
- mixin or module is wanted work, even when the diff is huge and mechanical
- (large `+N/-N` refactors merge regularly). The "every line traces to the
- request" test applies to *feature* PRs; a declared refactor's request IS the
- extraction.
-- **Keep the core narrow.** New *model tools* are the expensive exception —
- every tool ships on every API call. 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.** Before adding a module/manager/hook, check
- whether existing infrastructure already covers the use case. When several PRs
- integrate the same *category*, design one shared interface instead of merging
- them one at a time (see the ABC + orchestrator note under the Footprint
- Ladder).
-- **Behavior contracts over snapshots.** Tests should assert how two pieces of
- data must relate (invariants), not freeze a current value (model lists,
- config version literals, enumeration counts). See "Don't write
- change-detector tests."
-- **E2E validation, not just green unit mocks.** For anything touching
- resolution chains, config propagation, security boundaries, remote
- backends, or file/network I/O, exercise the real path with real imports
- against a temp `HERMES_HOME`. Mocks hide integration bugs.
-- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict
- message role alternation (never two same-role messages in a row; never a
- synthetic user message injected mid-loop), and a system prompt that is
- byte-stable for the life of a conversation.
-- **Contributor credit preserved.** Salvage external work by cherry-picking
- (rebase-merge) so authorship survives in git history; don't reimplement from
- scratch when you can build on top.
+- **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`. 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, or extension points with no
- concrete consumer. Adding a hook is easy; removing one after plugins depend
- on it is hard. A hook is NOT speculative if a contributor has a real, stated
- use case — even if the consumer ships separately.
-- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets
- only (API keys, tokens, passwords). All behavioral settings — timeouts,
- thresholds, feature flags, display prefs — go in `config.yaml`. Bridge to an
- internal env var if the mechanism needs one, but user-facing docs point to
- `config.yaml`. Reject PRs that tell users to "set X in your .env" unless X
- is a credential.
-- **A new core tool when terminal + file already do the job, or when a skill
- would.** 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 will read page 1 and skip the rest.
-- **"Fixes" that destroy the feature they secure.** A mitigation that kills the
- feature's purpose is the wrong mitigation. Read the original commit's intent
- (`git log -p -S`) before restricting behavior; find a fix that preserves the
- feature.
-- **Outbound telemetry / usage attribution without opt-in gating.** No new
- 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, do not merge.
-- **Change-detector tests, cache-breaking mid-conversation, dead code wired in
- without E2E proof, and plugins that touch core files.** Plugins live in their
- own directory and work within the ABCs/hooks we provide; if a plugin needs
- more, widen the generic plugin surface, don't special-case it in core.
-- **Third-party products / other people's projects integrated into the core
- tree.** Observability backends, vendor SaaS integrations, analytics dashboards,
- and similar "someone else's product" plugins do NOT land under `plugins/` in
- this repo. They place an ongoing maintenance burden on us to keep them working
- against a fast-moving core, for a backend we don't own. Ship them as a
- **standalone plugin repo** users install into `~/.hermes/plugins/` (or via a
- pip entry point), and promote them in the Nous Research Discord
- (`#plugins-skills-and-skins`). This is a coupling-and-maintenance decision, not
- a quality bar — the plugin can be excellent and still be a close. PRs that add
- such a directory to the tree are closed with a pointer to publish it as its own
- repo.
+- **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 gets closed is not code quality — it
-is that the change is built on a **wrong premise**, or it treats an
-**intentional design as a gap**. These patterns cut both ways: they tell a
-human reviewer what to scrutinize, and they tell the automated sweeper when a
-PR is NOT safe to close as `implemented_on_main` / `cannot_reproduce` (when in
-doubt, leave it open for a human). They are distilled from real closes.
-
-- **"Intentional design, not a gap."** A limitation that looks like an
- oversight is often deliberate. Before "fixing" a missing link or a
- restriction, ask whether the isolation IS the design. Example: profiles are
- independent islands on purpose — a PR adding live config inheritance from the
- default profile was closed because coupling profiles together is exactly what
- the design prevents (the copy-at-creation `--clone` path already covers the
- legitimate "start from my default" case). Read the original commit's intent
- (`git log -p -S "<symbol>"`) before assuming something is unfinished.
-- **"The premise doesn't hold against how X actually works."** A PR's
- justification frequently rests on a wrong mental model of an existing
- mechanism. Trace the real code/runtime before accepting the rationale. Two
- real closes: a rate-limit "re-probe during cooldown" PR (the breaker only
- trips on a *confirmed-empty* account bucket, so re-probing just hammers a
- bucket we've already proven empty); a usage-accumulation fix whose new branch
- **never executes at runtime** because an earlier guard already popped the
- state it depended on. If you can't point to the exact line where the bug
- manifests AND show the fix changes that line's behavior, you haven't verified
- the premise.
-- **"This fix was wrong — the absence/omission was deliberate."** Adding the
- obvious-looking missing piece can break things the omission was protecting.
- Example: restoring "missing" `__init__.py` files made a test tree importable
- as a dotted package that shadowed the real plugin, deleting its `register()`
- at import time. The absence was load-bearing.
-- **"Overreached / resurrected an approach we'd moved past."** Scope creep that
- supersedes an agreed-on base, or revives a direction the maintainers
- deliberately closed, gets rejected even when the code works. Keep the change
- to the narrow piece that was actually agreed; offer the rest as a focused
- follow-up.
-
-The throughline: **verify the claim AND the intent against the codebase before
-writing or merging a fix.** A confirmed reproduction on current `main` plus a
-line-level account of where the fix acts beats a plausible-sounding rationale
-every time. When in doubt about intent, it is cheaper to ask than to ship a
-fix that fights the design.
+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)
-Each rung adds more permanent surface than the one above. Choose the highest
-(least-footprint) rung that correctly solves the problem:
-
-1. **Extend existing code** — the capability is a variation of something that
- already exists. Zero new surface.
-2. **CLI command + skill** — manages config/state/infra expressible as shell
- commands. The agent runs `hermes <subcommand>` guided by a skill. Zero
- model-tool footprint. Default choice for subscriptions, scheduled tasks,
- service setup. Examples: `hermes webhook`, `hermes cron`, `hermes tools`.
-3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND
- only appears when a prerequisite is configured. Zero footprint otherwise.
- Examples: Home Assistant tools (gated on token), memory-provider tools.
-4. **Plugin** — third-party/niche/user-specific capability that doesn't ship in
- core. Lives in `~/.hermes/plugins/` or a pip package, discovered at runtime.
-5. **MCP server (in the catalog)** — if the capability genuinely needs to be a
- tool (structured I/O the agent invokes) but isn't core-fundamental, prefer
- building it as an MCP server and adding it to the MCP catalog over growing
- the core toolset. The agent connects to it through the built-in MCP client;
- zero permanent core-schema footprint, and it's reusable by any MCP host.
-6. **New core tool** — only when the capability is fundamental, broadly useful
- to nearly every user, and unreachable via terminal + file (or an MCP server).
- Examples of correct core tools: terminal, read_file, web_search,
- browser_navigate.
-
-When 3+ open PRs try to integrate the same *category* of thing (memory
-backends, providers, notifiers), don't merge them one at a time — design an
-ABC + orchestrator, wrap the existing built-in as the first provider, and turn
-the competing PRs into plugins against that interface.
+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).
+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 only works because of *who is on the other end of the connection* —
-the desktop app's panes, the in-app browser, message reactions, Projects — must
-resolve its availability from the **session's own source**, not from an env var
-on the backend process.
-
-The client and the backend are separate machines on separate clocks. The
-desktop app can be driving a backend Electron spawned locally, one over SSH,
-one behind a plain URL + token, or Hermes Cloud. Only the first two are spawned
-by us and carry `HERMES_DESKTOP=1`. Every env-keyed GUI gate is therefore a
-silent no-op on the other half of the topologies, and the failure is invisible:
-the tool is stripped from the schema before the model ever sees it, on the same
-backend whose platform hint is telling the model it's *"chatting inside the
-Hermes desktop app."*
-
-The pattern that works:
-
-- **The toolset is the surface gate.** Keep the tools off `_HERMES_CORE_TOOLS`
- (nobody else should pay their schema) and put them in a named toolset —
- `desktop_ui`, `project`. The GUI gateway's `_load_enabled_toolsets(platform)`
- folds that toolset in when the session's platform says GUI. One resolver,
- every topology.
-- **`check_fn` answers reachability or user opt-in, not surface.** "Is the
- renderer bridge wired?", "did the user enable reactions?" — fine. "Was I
- spawned by Electron?" — not fine. `check_fn` results are also TTL-cached
- process-wide (`tools/registry.py`), so a per-session answer does not belong
- there at all: one process serves many sessions.
-- **Ask which identity you actually mean.** `HERMES_DESKTOP=1` legitimately
- marks *"this backend process was spawned by the app"* — it gates the cron
- ticker and web-dist handling correctly. It does NOT mean "a GUI is watching",
- and the embedded terminal pane (`hermes --tui` against that same backend) is
- the standing counterexample.
-
-Same test both ways: if the capability would still make sense with the client
-on another machine, it is session-scoped. Cover it with a test that asserts the
-GUI session gets the tool **with the env var absent** — that's the assertion
-the original gate could never have passed.
+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**.
## Development Environment
```bash
-# Prefer .venv; fall back to venv if that's what your checkout has.
source .venv/bin/activate # or: source venv/bin/activate
```
-
-`scripts/run_tests.sh` probes `.venv` first, then `venv`, then
-`$HOME/.hermes/hermes-agent/venv` (for worktrees that share a venv with the
-main checkout).
+`scripts/run_tests.sh` probes `.venv`, then `venv`, then `$HOME/.hermes/hermes-agent/venv`
+(worktrees sharing the main checkout's venv).
## Project Structure
-File counts shift constantly — don't treat the tree below as exhaustive.
-The canonical source is the filesystem. The notes call out the load-bearing
-entry points you'll actually edit.
+Counts shift constantly; the filesystem is canonical. Load-bearing entry points:
```
hermes-agent/
-├── run_agent.py # AIAgent class — public entry (~1.5k LOC); the turn loop lives in agent/turn_*.py
+├── run_agent.py # AIAgent facade; the turn loop lives in agent/turn_*.py
├── model_tools.py # Tool orchestration, discover_builtin_tools(), handle_function_call()
-├── toolsets.py # Toolset definitions, _HERMES_CORE_TOOLS list
-├── cli.py # HermesCLI class — interactive CLI orchestrator (~4.6k LOC + hermes_cli/cli_*_mixin.py)
-├── hermes_state.py # SessionDB facade (~1.4k LOC); implementation in hermes_state_*.py (21 siblings)
+├── toolsets.py # TOOLSETS dict, _HERMES_CORE_TOOLS
+├── 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 # setup_logging() — agent.log / errors.log / gateway.log (profile-aware)
+├── hermes_logging.py # agent.log / errors.log / gateway.log (profile-aware)
├── batch_runner.py # Parallel batch processing
-├── agent/ # Agent internals: turn_*.py (loop phases), provider adapters, memory, compression, ...
-├── hermes_cli/ # CLI subcommands, setup wizard, plugins loader, skin engine
-│ └── web_routers/ # Dashboard FastAPI routers (one file per surface); web_server.py mounts them
-├── tools/ # Tool implementations — auto-discovered via tools/registry.py
+├── 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)
-├── gateway/ # Messaging gateway — run.py facade + run_*.py phases + session*.py + platforms/
-│ ├── platforms/ # Adapter per platform (telegram, discord, slack, whatsapp,
-│ │ # homeassistant, signal, matrix, mattermost, email, sms,
-│ │ # dingtalk, wecom, weixin, feishu, qqbot, bluebubbles,
-│ │ # yuanbao, webhook, api_server, ...). See ADDING_A_PLATFORM.md.
-│ └── builtin_hooks/ # Extension point for always-registered gateway hooks (none shipped)
-├── plugins/ # Plugin system (see "Plugins" section below)
-│ ├── memory/ # Memory-provider plugins (honcho, mem0, supermemory, ...)
-│ ├── context_engine/ # Context-engine plugins
-│ ├── model-providers/ # Inference backend plugins (openrouter, anthropic, gmi, ...)
-│ ├── kanban/ # Multi-agent board dispatcher + worker plugin
-│ ├── hermes-achievements/ # Gamified achievement tracking
-│ ├── observability/ # Metrics / traces / logs plugin
-│ ├── image_gen/ # Image-generation providers
-│ └── <others>/ # disk-cleanup, google_meet, platforms, spotify,
-│ # strike-freedom-cockpit, ...
-├── optional-skills/ # Heavier/niche skills shipped but NOT active by default
-├── skills/ # Built-in skills bundled with the repo
+├── 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`
-│ └── src/ # entry.tsx, app.tsx, gatewayClient.ts + app/components/hooks/lib
-├── tui_gateway/ # Python JSON-RPC backend for the TUI — server.py + methods_*.py
-├── acp_adapter/ # ACP server (VS Code / Zed / JetBrains integration)
-├── cron/ # Scheduler — jobs.py, scheduler.py (+ scheduler_*.py)
-├── evals/ # Offline benchmarks (codebase_navigability/, compaction/, core_tool_deferral/, ...)
-├── scripts/ # run_tests.sh, release.py, check_compat_pointers.py, auxiliary scripts
-├── website/ # Docusaurus docs site
-└── tests/ # Pytest suite (~39k test functions across ~3.7k files as of Sep 2026)
-```
-
-### Facade + siblings layout (Sep 2026 decomposition)
-
-Every former god file is now a **facade** plus a family of **siblings** named `<stem>_<topic>.py`
-in the same directory. The facade keeps the public entry points and the names other packages
-import; each sibling owns one topic and is where the code actually lives. Families with the most
-siblings:
-
-| facade | siblings | topics |
-|---|---|---|
-| `hermes_state.py` | 21 `hermes_state_*.py` | schema, fts, search, compression, portability, gateway, errors, ... |
-| `gateway/run.py` | 15 `gateway/run_*.py` | startup, adapters, inbound, turn, busy, goals, notifications, shutdown, ... |
-| `tools/mcp_tool.py` | 15 `tools/mcp_tool_*.py` | config, discovery, transport, registration, content, errors, ... |
-| `hermes_cli/kanban.py` | 14 `hermes_cli/kanban_*.py` | boards, db, db_connect, db_dispatch, db_notify, workspace, ... |
-| `hermes_cli/web_server.py` | 13 `web_server_*.py` + 24 `web_routers/*.py` | one router file per dashboard surface |
-| `hermes_cli/auth.py` | 12 `auth_*.py` | device_flow, codex, minimax, model_picker, commands, ... |
-| `tools/browser_tool.py` | 11 `browser_tool_*.py` | cdp, cloud, install, lifecycle, session, real_profile, vision, ... |
-| `cli.py` | 12 `hermes_cli/cli_*_mixin.py` | commands, stream, status_bar, billing, ... — mixed into `HermesCLI` |
-| `run_agent.py` | `agent/turn_*.py`, `agent/agent_init.py`, `agent/conversation_loop.py` | turn phases: iteration_prep, api_call, api_error, overflow, truncation, recovery |
-
-Rules that follow from this layout:
-
-- **Find code by topic, not by facade.** `grep -rn "def name" <dir>/<stem>_*.py` lands on the
- definition; reading the facade first is the expensive way (see `evals/codebase_navigability/`).
-- **Siblings may import each other and late-import the facade** (inside functions) to avoid cycles.
- A facade never imports a sibling at module level *and* gets imported by that sibling at module level.
-- **Patch where production reads.** Many siblings deliberately do `from <facade> import name` inside
- the function so tests can `monkeypatch.setattr(facade, "name", ...)`. Before writing a patch target,
- check which binding the call site actually reads; a patch on the wrong module passes silently.
-- **`scripts/check_compat_pointers.py` runs in CI.** Old import paths kept alive for external plugins
- (`PLUGIN-COMPAT` blocks, `COMPAT_MANIFEST.md`, `compat_manifest.json`) are OFF LIMITS to in-tree code
- and tests; they are removed on schedule by reverting one commit. Import from the defining module.
-- **Don't recreate god files.** A sibling passing ~2,000 lines or a function passing ~300 is a signal
- to split again along the same `<stem>_<topic>` convention.
-
-**User config:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (API keys only).
-**Logs:** `~/.hermes/logs/` — `agent.log` (INFO+), `errors.log` (WARNING+),
-`gateway.log` when running the gateway. Profile-aware via `get_hermes_home()`.
-Browse with `hermes logs [--follow] [--level ...] [--session ...]`.
-
-## TypeScript Style
-
-Applies to TypeScript across Hermes: desktop, TUI, website, and future TS packages.
-
-- Prefer small nanostores over component state when state is shared, reused, or read by distant UI.
-- Let each feature own its atoms. Chat state belongs near chat, shell state near shell, shared state in `src/store`.
-- Components that render from an atom should use `useStore`. Non-rendering actions should read with `$atom.get()`.
-- Do not pass state through three components when the leaf can subscribe to the atom.
-- Keep persistence beside the atom that owns it.
-- Keep route roots thin. They compose routes and shell; they should not become controllers.
-- No monolithic hooks. A hook should own one narrow job.
-- Prefer colocated action modules over hidden god hooks.
-- If a callback is pure side effect, use the terse void form:
- `onState={st => void setGatewayState(st)}`.
-- Async UI handlers should make intent explicit:
- `onClick={() => void save()}`.
-- Prefer interfaces for public props and shared object shapes. Avoid `type X = { ... }` for object props.
-- Extend React primitives for props: `React.ComponentProps<'button'>`, `React.ComponentProps<typeof Dialog>`, `Omit<...>`, `Pick<...>`.
-- Table-driven beats condition ladders when mapping ids, routes, or views.
-- `src/app` owns routes, pages, and page-specific components.
-- `src/store` owns shared atoms.
-- `src/lib` owns shared pure helpers.
-
-## File Dependency Chain
-
-```
-tools/registry.py (no deps — imported by all tool files)
- ↑
-tools/*.py (each calls registry.register() at import time)
- ↑
-model_tools.py (imports tools/registry + triggers tool discovery)
- ↑
-run_agent.py, cli.py, batch_runner.py, environments/
-```
-
----
-
-## AIAgent Class (run_agent.py + agent/)
-
-`run_agent.py` is the public entry: the `AIAgent` class assembled from mixins
-(`agent/turn_facade.py`, `agent/client_lifecycle.py`, `agent/stream_delivery.py`,
-`agent/session_persistence.py`, `agent/compression_facade.py`, ...). Construction runs
-`agent/agent_init.py::init_agent`; the turn itself is `agent/conversation_loop.py::run_conversation`,
-which `AIAgent.run_conversation` forwards to after taking the session turn lease.
-
-The real `AIAgent.__init__` takes ~60 parameters (credentials, routing, callbacks,
-session context, budget, credential pool, etc.). The signature below is the
-minimum subset you'll usually touch — read `run_agent.py` for the full list.
-
-```python
-class AIAgent:
- def __init__(self,
- base_url: str = None,
- api_key: str = None,
- provider: str = None,
- api_mode: str = None, # "chat_completions" | "codex_responses" | ...
- model: str = "", # empty → resolved from config/provider later
- max_iterations: int = 500, # tool-calling iterations (shared with subagents)
- enabled_toolsets: list = None,
- disabled_toolsets: list = None,
- quiet_mode: bool = False,
- save_trajectories: bool = False,
- platform: str = None, # "cli", "telegram", etc.
- session_id: str = None,
- skip_context_files: bool = False,
- skip_memory: bool = False,
- credential_pool=None,
- # ... plus callbacks, thread/user/chat IDs, iteration_budget, fallback_model,
- # checkpoints config, prefill_messages, service_tier, reasoning_config, etc.
- ): ...
-
- def chat(self, message: str) -> str:
- """Simple interface — returns final response string."""
-
- def run_conversation(self, user_message: str, system_message: str = None,
- conversation_history: list = None, task_id: str = None) -> dict:
- """Full interface — returns dict with final_response + messages."""
+├── 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)
+├── cron/ # jobs.py + scheduler.py (+ scheduler_*.py)
+├── evals/ # Offline benchmarks (codebase_navigability/, compaction/, ...)
+├── scripts/ # run_tests.sh, release.py, check_compat_pointers.py, ci/
+├── website/ # Docusaurus docs (developer-guide/ holds the long-form area docs)
+└── tests/ # Pytest suite (~39k tests / ~3.7k files, Sep 2026)
```
-### Agent Loop
-
-The core loop is `agent/conversation_loop.py::run_conversation()` — entirely synchronous, with
-interrupt checks, budget tracking, and a one-turn grace call. Each phase of an iteration is its own
-module under `agent/turn_*.py` (`turn_iteration_prep`, `turn_request_assembly`, `turn_api_call`,
-`turn_api_error`, `turn_overflow`, `turn_truncation`, `turn_recovery`, `turn_usage`, ...), so a change
-to, say, overflow handling touches one ~600-line file. Schematically:
-
-```python
-while (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \
- or self._budget_grace_call:
- if self._interrupt_requested: break
- response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)
- if response.tool_calls:
- for tool_call in response.tool_calls:
- result = handle_function_call(tool_call.name, tool_call.args, task_id)
- messages.append(tool_result_message(result))
- api_call_count += 1
- else:
- return response.content
-```
-
-Messages follow OpenAI format: `{"role": "system/user/assistant/tool", ...}`.
-Reasoning content is stored in `assistant_msg["reasoning"]`.
-
----
-
-## CLI Architecture (cli.py + hermes_cli/cli_*_mixin.py)
-
-- `cli.py` holds `HermesCLI` (REPL loop, config, slash dispatch); behaviour is split into mixins in
- `hermes_cli/cli_commands_mixin.py`, `cli_stream_mixin.py`, `cli_status_bar_mixin.py`, `cli_billing_mixin.py`, ...
-- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete
-- **KawaiiSpinner** (`agent/display.py`) — animated faces during API calls, `┊` activity feed for tool results
-- `load_cli_config()` in cli.py merges hardcoded defaults + user config YAML
-- **Skin engine** (`hermes_cli/skin_engine.py`) — data-driven CLI theming; initialized from `display.skin` config key at startup; skins customize banner colors, spinner faces/verbs/wings, tool prefix, response box, branding text
-- `process_command()` on `HermesCLI` resolves the canonical name via `resolve_command()` from the central
- registry, then dispatches through the `_SLASH_DISPATCH` table (`canonical -> (method name, pass_arg)`),
- falling back to a `_handle_<name>_command` method by naming convention. There is no `elif` ladder.
-- Skill slash commands: `agent/skill_commands.py` scans `~/.hermes/skills/`, injects as **user message** (not system prompt) to preserve prompt caching
-
-### Slash Command Registry (`hermes_cli/commands.py`)
-
-All slash commands are defined in a central `COMMAND_REGISTRY` list of `CommandDef` objects. Every downstream consumer derives from this registry automatically:
-
-- **CLI** — `process_command()` resolves aliases via `resolve_command()`, dispatches on canonical name
-- **Gateway** — `GATEWAY_KNOWN_COMMANDS` frozenset for hook emission, `resolve_command()` for dispatch
-- **Gateway help** — `gateway_help_lines()` generates `/help` output
-- **Telegram** — `telegram_bot_commands()` generates the BotCommand menu
-- **Slack** — `slack_subcommand_map()` generates `/hermes` subcommand routing
-- **Autocomplete** — `COMMANDS` flat dict feeds `SlashCommandCompleter`
-- **CLI help** — `COMMANDS_BY_CATEGORY` dict feeds `show_help()`
-
-### Adding a Slash Command
-
-1. Add a `CommandDef` entry to `COMMAND_REGISTRY` in `hermes_cli/commands.py`:
-```python
-CommandDef("mycommand", "Description of what it does", "Session",
- aliases=("mc",), args_hint="[arg]"),
-```
-2. Add the handler on the CLI. Name it `_handle_mycommand_command(self, cmd_original)` on the
- relevant `hermes_cli/cli_*_mixin.py` and it is picked up by convention; or add an explicit entry to
- `HermesCLI._SLASH_DISPATCH` in `cli.py` when the method name or arg-passing differs:
-```python
-"mycommand": ("_handle_mycommand", True), # (method name, pass cmd_original?)
-```
-3. If the command is available in the gateway, add `_handle_mycommand_command(self, event)` on the
- matching `gateway/slash_commands_*.py` mixin and list `"mycommand"` in `_IDLE_COMMANDS` (or
- `_PLAIN_COMMANDS` if it must also work mid-run) in `gateway/run_busy.py`. Handlers are looked up
- by name through `_command_handler_table`; there is no `if canonical == ...` chain to extend.
-4. For persistent settings, use `save_config_value()` in `cli.py`
-
-**CommandDef fields:**
-- `name` — canonical name without slash (e.g. `"background"`)
-- `description` — human-readable description
-- `category` — one of `"Session"`, `"Configuration"`, `"Tools & Skills"`, `"Info"`, `"Exit"`
-- `aliases` — tuple of alternative names (e.g. `("bg",)`)
-- `args_hint` — argument placeholder shown in help (e.g. `"<prompt>"`, `"[name]"`)
-- `cli_only` — only available in the interactive CLI
-- `gateway_only` — only available in messaging platforms
-- `gateway_config_gate` — config dotpath (e.g. `"display.tool_progress_command"`); when set on a `cli_only` command, the command becomes available in the gateway if the config value is truthy. `GATEWAY_KNOWN_COMMANDS` always includes config-gated commands so the gateway can dispatch them; help/menus only show them when the gate is open.
-
-**Adding an alias** requires only adding it to the `aliases` tuple on the existing `CommandDef`. No other file changes needed — dispatch, help text, Telegram menu, Slack mapping, and autocomplete all update automatically.
-
----
-
-## TUI Architecture (ui-tui + tui_gateway)
-
-The TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`.
-
-### Process Model
-
-```
-hermes --tui
- └─ Node (Ink) ──stdio JSON-RPC── Python (tui_gateway)
- │ └─ AIAgent + tools + sessions
- └─ renders transcript, composer, prompts, activity
-```
-
-TypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic.
-
-### Transport
-
-Newline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog.
-
-### Key Surfaces
-
-| Surface | Ink component | Gateway method |
-|---------|---------------|----------------|
-| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` |
-| Tool activity | `thinking.tsx` | `tool.start/progress/complete` |
-| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` |
-| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` |
-| Session picker | `sessionPicker.tsx` | `session.list/resume` |
-| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` |
-| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |
-| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data |
-
-### Slash Command Flow
-
-1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx`
-2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback
-
-### Dev Commands
-
-```bash
-cd ui-tui
-npm install # first time
-npm run dev # watch mode (rebuilds hermes-ink + tsx --watch)
-npm start # production
-npm run build # full build (hermes-ink + tsc)
-npm run typecheck # typecheck only (tsc --noEmit)
-npm run lint # eslint
-npm run fmt # prettier
-npm test # vitest
-```
-
-### TUI in the Dashboard (`hermes dashboard` → `/chat`)
-
-The dashboard embeds the real `hermes --tui` — **not** a rewrite. See `hermes_cli/pty_bridge.py` + the `@app.websocket("/api/pty")` endpoint in `hermes_cli/web_server.py`.
-
-- Browser loads `web/src/pages/ChatPage.tsx`, which mounts xterm.js's `Terminal` with the WebGL renderer, `@xterm/addon-fit` for container-driven resize, and `@xterm/addon-unicode11` for modern wide-character widths.
-- `/api/pty?token=…` upgrades to a WebSocket; auth uses the same ephemeral `_SESSION_TOKEN` as REST, via query param (browsers can't set `Authorization` on WS upgrade).
-- The server spawns whatever `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL works, native Windows does not).
-- Frames: raw PTY bytes each direction; resize via `\x1b[RESIZE:<cols>;<rows>]` intercepted on the server and applied with `TIOCSWINSZ`.
-
-**Do not re-implement the primary chat experience in React.** The main transcript, composer/input flow (including slash-command behavior), and PTY-backed terminal belong to the embedded `hermes --tui` — anything new you add to Ink shows up in the dashboard automatically. If you find yourself rebuilding the transcript or composer for the dashboard, stop and extend Ink instead.
-
-**Structured React UI around the TUI is allowed when it is not a second chat surface.** Sidebar widgets, inspectors, summaries, status panels, and similar supporting views (e.g. `ChatSidebar`, `ModelPickerDialog`, `ToolCall`) are fine when they complement the embedded TUI rather than replacing the transcript / composer / terminal. Keep their state independent of the PTY child's session and surface their failures non-destructively so the terminal pane keeps working unimpaired.
-
-### Electron Desktop Chat App (`apps/desktop/`)
-
-A **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI entirely: `serve` sets `headless_backend=True`, so `cmd_dashboard` skips `_build_web_ui` AND exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists — only the JSON-RPC/WS/API surface is reachable). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.ts` + `backendSupportsServe()` in `electron/main.ts`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. For scoped Desktop architecture, state, resolver, transport, and testing rules, read `apps/desktop/AGENTS.md`.
-
-**Slash commands in the desktop app are curated client-side, then dispatched to the backend.** The pipeline:
-
-- **Backend already provides everything.** `tui_gateway/server.py` `commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) both include built-in commands, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` / `get_skill_commands()`). The desktop app does not need a new RPC to see skills.
-- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMAND_SPECS` (the built-ins and their Desktop surfaces) plus `NO_DESKTOP_SURFACE` block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover.
- - `isDesktopSlashCommand(name)` — gates **execution**. Returns true for built-ins AND for any non-built-in (skill / quick command), so typed extension commands run.
- - `isDesktopSlashSuggestion(name)` — gates **discovery/completion**. Used by BOTH completion paths in `app/chat/composer/hooks/use-slash-completions.ts` (empty-query catalog filter + typed-query `complete.slash` filter) and by `filterDesktopCommandsCatalog`.
- - `isDesktopSlashExtensionCommand(name)` — true when the command is NOT a known Hermes built-in (i.e. a skill or user quick command). Both suggestion and catalog-filter paths allow extensions through so skill commands surface in the palette. (Added when fixing "skill commands missing from the desktop slash palette" — the curated allow-list was silently dropping every skill/quick command from completions even though they executed fine when typed.)
-- **Dispatch** lives in `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: "skill", message}` and is submitted as a normal prompt.
-
-**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: from `apps/desktop`, run `npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace dependencies are installed at the repo root).
+**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/`.
-## Adding New Tools
-
-Before adding any tool, settle the footprint question first (see "The
-Footprint Ladder" in the Contribution Rubric): most capabilities should NOT
-be core tools. For custom or local-only tools, do **not** edit Hermes core.
-Use the plugin route instead: create `~/.hermes/plugins/<name>/plugin.yaml`
-and `~/.hermes/plugins/<name>/__init__.py`, then register tools with
-`ctx.register_tool(...)`. Plugin toolsets are discovered automatically and can be
-enabled or disabled without touching `tools/` or `toolsets.py`.
-
-Use the built-in route below only when the user is explicitly contributing a new
-core Hermes tool that should ship in the base system.
-
-Built-in/core tools require changes in **2 files**:
-
-**1. Create `tools/your_tool.py`:**
-```python
-import json, os
-from tools.registry import registry
-
-def check_requirements() -> bool:
- return bool(os.getenv("EXAMPLE_API_KEY"))
-
-def example_tool(param: str, task_id: str = None) -> str:
- return json.dumps({"success": True, "data": "..."})
-
-registry.register(
- name="example_tool",
- toolset="example",
- schema={"name": "example_tool", "description": "...", "parameters": {...}},
- handler=lambda args, **kw: example_tool(param=args.get("param", ""), task_id=kw.get("task_id")),
- check_fn=check_requirements,
- requires_env=["EXAMPLE_API_KEY"],
-)
-```
-
-**2. Add to `toolsets.py`** — either `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **This step is required:** auto-discovery imports the tool and registers its schema, but the tool is only *exposed to an agent* if its name appears in a toolset. `_HERMES_CORE_TOOLS` is not dead code — it's the default bundle every platform's base toolset inherits from.
-
-Auto-discovery: any `tools/*.py` file with a top-level `registry.register()` call is imported automatically — no manual import list to maintain. Wiring into a toolset is still a deliberate, manual step.
-
-The registry handles schema collection, dispatch, availability checking, and error wrapping. All handlers MUST return a JSON string.
-
-**Path references in tool schemas**: If the schema description mentions file paths (e.g. default output directories), use `display_hermes_home()` to make them profile-aware. The schema is generated at import time, which is after `_apply_profile_override()` sets `HERMES_HOME`.
-
-**State files**: If a tool stores persistent state (caches, logs, checkpoints), use `get_hermes_home()` for the base directory — never `Path.home() / ".hermes"`. This ensures each profile gets its own state.
-
-**Agent-level tools** (todo, memory): intercepted by `agent/tool_executor.py` (via the `INLINE_TOOL_EXECUTORS` table in `agent/inline_tool_executors.py`) before `handle_function_call()`. See `tools/todo_tool.py` for the pattern.
+### 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).
+- **Compat pointers are OFF LIMITS in-tree.** Old import paths kept alive for external plugins
+ (`PLUGIN-COMPAT` blocks, `COMPAT_MANIFEST.md`, `compat_manifest.json`) must not be used by
+ in-tree code or tests; `scripts/check_compat_pointers.py` runs in CI, and
+ `-W error::hermes_cli.plugin_compat.HermesPluginCompatWarning` catches them in the suite.
+ They are removed 2026-09-14 by reverting one commit. Import from the defining module.
+- **Don't recreate god files.** A file passing ~2,000 lines or a function passing ~300 lines /
+ cyclomatic complexity 30 is the signal to split along `<stem>_<topic>` FIRST, in its own
+ commit. New behaviour goes in a new or topical sibling — never appended to a facade.
+- **No `if/elif` ladders ≥ 4 branches keyed on a name/kind** — use a dict/table → handler
+ (`_SLASH_DISPATCH` in `cli.py`, `_command_handler_table` in the gateway are the shape).
+- **No re-export shims for internal moves** ("keep the old name importable"). Internal paths
+ are not API; external compat is handled ONCE by the compat layer, not per PR.
+- **Moving a symbol means fixing its docs in the same PR:** grep `website/docs`, `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`) — the bug class
+ behind ~10 fleet-update issues (#90778, #87594, #78089, #76129, #91964). 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`.
+- **Never hardcode `~/.hermes`.** `get_hermes_home()` for code paths, `display_hermes_home()`
+ for user-facing text (both from `hermes_constants`). Hardcoding breaks profiles (5 bugs in
+ PR #3575). Module-level constants are fine — they cache after `_apply_profile_override()`
+ sets `HERMES_HOME`. Profile operations themselves are HOME-anchored
+ (`_get_profiles_root()` = `Path.home()/.hermes/profiles`) so `hermes -p x profile list`
+ sees all profiles — intentional, not a bug.
+- **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 must have upper bounds to limit supply-chain attack surface.
-This policy was established after the litellm compromise (PR #2796, #2810) and
-reinforced after the Mini Shai-Hulud worm campaign (May 2026).
-
-| Source type | Treatment | Example |
-|---|---|---|
-| PyPI package | `>=floor,<next_major` | `"httpx>=0.28.1,<1"` |
-| Git URL | Commit SHA | `git+https://...@<40-char-sha>` |
-| GitHub Actions | Commit SHA + comment | `uses: actions/checkout@<sha> # v4` |
-| CI-only pip | `==exact` | `pyyaml==6.0.2` |
-
-**When adding a new dependency to `pyproject.toml`:**
-1. Pin to `>=current_version,<next_major` for post-1.0 (e.g. `>=1.5.0,<2`).
-2. For pre-1.0 packages, use `<0.(current_minor + 2)` (e.g. `>=0.29,<0.32`).
-3. Never commit a bare `>=X.Y.Z` without a ceiling — CI and reviewers will reject it.
-4. Run `uv lock` to regenerate `uv.lock` with hashes.
-
-Reference: #2810 (bounds pass), #9801 (SHA pinning + audit CI).
-
----
-
-## Adding Configuration
-
-### config.yaml options:
-1. Add to `DEFAULT_CONFIG` in `hermes_cli/config.py`
-2. Bump `_config_version` (check the current value at the top of `DEFAULT_CONFIG`)
- ONLY if you need to actively migrate/transform existing user config
- (renaming keys, changing structure). Adding a new key to an existing
- section is handled automatically by the deep-merge and does NOT require
- a version bump.
-
-### Top-level `config.yaml` sections (non-exhaustive):
-
-`model`, `agent`, `terminal`, `compression`, `display`, `stt`, `tts`,
-`memory`, `security`, `delegation`, `smart_model_routing`, `checkpoints`,
-`auxiliary`, `curator`, `skills`, `gateway`, `logging`, `cron`, `profiles`,
-`plugins`, `honcho`.
-
-`auxiliary` holds per-task overrides for side-LLM work (curator, vision,
-embedding, title generation, session_search, etc.) — each task can pin
-its own provider/model/base_url/max_tokens/reasoning_effort. See
-`agent/auxiliary_client.py::_resolve_auto_route` for resolution order.
-
-`curator` holds the background skill-maintenance config —
-`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,
-`archive_after_days`, `backup` (nested).
-
-### .env variables (SECRETS ONLY — API keys, tokens, passwords):
-1. Add to `OPTIONAL_ENV_VARS` in `hermes_cli/config.py` with metadata:
-```python
-"NEW_API_KEY": {
- "description": "What it's for",
- "prompt": "Display name",
- "url": "https://...",
- "password": True,
- "category": "tool", # provider, tool, messaging, setting
-},
-```
-
-Non-secret settings (timeouts, thresholds, feature flags, paths, display
-preferences) belong in `config.yaml`, not `.env`. If internal code needs an
-env var mirror for backward compatibility, bridge it from `config.yaml` to
-the env var in code (see `gateway_timeout`, `terminal.cwd` → `TERMINAL_CWD`).
-
-### Config loaders (three paths — know which one you're in):
-
-| Loader | Used by | Location |
-|--------|---------|----------|
-| `load_cli_config()` | CLI mode | `cli.py` — merges CLI-specific defaults + user YAML |
-| `load_config()` | `hermes tools`, `hermes setup`, most CLI subcommands | `hermes_cli/config.py` — merges `DEFAULT_CONFIG` + user YAML |
-| Direct YAML load | Gateway runtime | `gateway/run.py` + `gateway/config.py` — reads user YAML raw |
-
-If you add a new key and the CLI sees it but the gateway doesn't (or vice
-versa), you're on the wrong loader. Check `DEFAULT_CONFIG` coverage.
-
-### Working directory:
-- **CLI** — uses the process's current directory (`os.getcwd()`).
-- **Messaging** — uses `terminal.cwd` from `config.yaml`. The gateway bridges this
- to the `TERMINAL_CWD` env var for child tools. **`MESSAGING_CWD` has been
- removed** — the config loader prints a deprecation warning if it's set in
- `.env`. Same for `TERMINAL_CWD` in `.env`; the canonical setting is
- `terminal.cwd` in `config.yaml`.
-
----
-
-## Skin/Theme System
-
-The skin engine (`hermes_cli/skin_engine.py`) provides data-driven CLI visual customization. Skins are **pure data** — no code changes needed to add a new skin.
-
-### Architecture
-
-```
-hermes_cli/skin_engine.py # SkinConfig dataclass, built-in skins, YAML loader
-~/.hermes/skins/*.yaml # User-installed custom skins (drop-in)
-```
-
-- `init_skin_from_config()` — called at CLI startup, reads `display.skin` from config
-- `get_active_skin()` — returns cached `SkinConfig` for the current skin
-- `set_active_skin(name)` — switches skin at runtime (used by `/skin` command)
-- `load_skin(name)` — loads from user skins first, then built-ins, then falls back to default
-- Missing skin values inherit from the `default` skin automatically
-
-### What skins customize
-
-| Element | Skin Key | Used By |
-|---------|----------|---------|
-| Banner panel border | `colors.banner_border` | `banner.py` |
-| Banner panel title | `colors.banner_title` | `banner.py` |
-| Banner section headers | `colors.banner_accent` | `banner.py` |
-| Banner dim text | `colors.banner_dim` | `banner.py` |
-| Banner body text | `colors.banner_text` | `banner.py` |
-| Response box border | `colors.response_border` | `cli.py` |
-| Spinner faces (waiting) | `spinner.waiting_faces` | `display.py` |
-| Spinner faces (thinking) | `spinner.thinking_faces` | `display.py` |
-| Spinner verbs | `spinner.thinking_verbs` | `display.py` |
-| Spinner wings (optional) | `spinner.wings` | `display.py` |
-| Tool output prefix | `tool_prefix` | `display.py` |
-| Per-tool emojis | `tool_emojis` | `display.py` → `get_tool_emoji()` |
-| Agent name | `branding.agent_name` | `banner.py`, `cli.py` |
-| Welcome message | `branding.welcome` | `cli.py` |
-| Response box label | `branding.response_label` | `cli.py` |
-| Prompt symbol | `branding.prompt_symbol` | `cli.py` |
-
-### Built-in skins
-
-- `default` — Classic Hermes gold/kawaii (the current look)
-- `ares` — Crimson/bronze war-god theme with custom spinner wings
-- `mono` — Clean grayscale monochrome
-- `slate` — Cool blue developer-focused theme
-
-### Adding a built-in skin
-
-Add to `_BUILTIN_SKINS` dict in `hermes_cli/skin_engine.py`:
-
-```python
-"mytheme": {
- "name": "mytheme",
- "description": "Short description",
- "colors": { ... },
- "spinner": { ... },
- "branding": { ... },
- "tool_prefix": "┊",
-},
-```
-
-### User skins (YAML)
-
-Users create `~/.hermes/skins/<name>.yaml`:
-
-```yaml
-name: cyberpunk
-description: Neon-soaked terminal theme
-
-colors:
- banner_border: "#FF00FF"
- banner_title: "#00FFFF"
- banner_accent: "#FF1493"
-
-spinner:
- thinking_verbs: ["jacking in", "decrypting", "uploading"]
- wings:
- - ["⟨⚡", "⚡⟩"]
-
-branding:
- agent_name: "Cyber Agent"
- response_label: " ⚡ Cyber "
-
-tool_prefix: "▏"
-```
-
-Activate with `/skin cyberpunk` or `display.skin: cyberpunk` in config.yaml.
-
----
-
-## Plugins
-
-Hermes has two plugin surfaces. Both live under `plugins/` in the repo so
-repo-shipped plugins can be discovered alongside user-installed ones in
-`~/.hermes/plugins/` and pip-installed entry points.
-
-### General plugins (`hermes_cli/plugins.py` + `plugins/<name>/`)
-
-`PluginManager` discovers plugins from `~/.hermes/plugins/`, `./.hermes/plugins/`,
-and pip entry points. Each plugin exposes a `register(ctx)` function that
-can:
-
-- Register Python-callback lifecycle hooks:
- `pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`,
- `on_session_start`, `on_session_end`
-- Register new tools via `ctx.register_tool(...)`
-- Register CLI subcommands via `ctx.register_cli_command(...)` — the
- plugin's argparse tree is wired into `hermes` at startup so
- `hermes <pluginname> <subcmd>` works with no change to `main.py`
-
-Hooks are invoked from `model_tools.py` (pre/post tool) and `run_agent.py`
-(lifecycle). **Discovery timing pitfall:** `discover_plugins()` only runs
-as a side effect of importing `model_tools.py`. Code paths that read plugin
-state without importing `model_tools.py` first must call `discover_plugins()`
-explicitly (it's idempotent).
-
-#### Native plugin compatibility policy
-
-The canonical contract and deprecation policy live in
-`website/docs/developer-guide/plugins/index.md#native-plugin-compatibility-contract`.
-Compatibility is enforced as a behavior contract, not through a monolithic
-`PLUGIN_API_VERSION`, a manifest-wide native `api:` match, or version literals
-on unrelated payloads. Keep documented plugin surfaces additive:
-
-- add hook payload data as keyword fields; signature-inspect callbacks so old
- narrow signatures receive only fields they declare, while `**kwargs`
- callbacks receive the complete payload;
-- do not remove or rename `PluginContext` methods; make new parameters optional
- with defaults and keyword-only where possible;
-- ignore unknown native manifest fields;
-- give new provider methods default implementations, and signature-inspect
- optional callback kwargs rather than forwarding them unconditionally;
-- use a local schema version only for a capability with a wire or persisted
- contract, and preserve old state/config/session replay or ship a migration.
-
-Deprecations require a once-per-process warning, a documented replacement and
-migration note, and at least two subsequent minor releases before removal.
-Compatibility tests must load frozen plugins through the real discovery path
-and assert outcomes. Do not replace these with exact registry/catalog counts,
-source-reading tests, or assertions that a global version literal changed.
-
-### Memory-provider plugins (`plugins/memory/<name>/`)
-
-Separate discovery system for pluggable memory backends. Current built-in
-providers include **honcho, mem0, supermemory, byterover, hindsight,
-holographic, openviking, retaindb**.
-
-Discovery covers the same four sources as the general `PluginManager` —
-bundled, `$HERMES_HOME/plugins/`, `./.hermes/plugins/` (opt-in via
-`HERMES_ENABLE_PROJECT_PLUGINS`), and `hermes_agent.memory_providers` entry
-points — but with **bundled-first** precedence, the reverse of the general
-system's later-wins order: a memory provider is activated by name, so a
-dropped-in directory must not be able to shadow a shipped one. Discovery
-enumerates without importing; nothing runs until `memory.provider` names it.
-
-Each provider implements the `MemoryProvider` ABC (see `agent/memory_provider.py`)
-and is orchestrated by `agent/memory_manager.py`. Lifecycle hooks include
-`sync_turn(turn_messages)`, `prefetch(query)`, `shutdown()`, and optional
-`post_setup(hermes_home, config)` for setup-wizard integration.
-
-**CLI commands via `plugins/memory/<name>/cli.py`:** if a memory plugin
-defines `register_cli(subparser)`, `discover_plugin_cli_commands()` finds
-it at argparse setup time and wires it into `hermes <plugin>`. The
-framework only exposes CLI commands for the **currently active** memory
-provider (read from `memory.provider` in config.yaml), so disabled
-providers don't clutter `hermes --help`.
-
-**Rule (Teknium, May 2026):** plugins MUST NOT modify core files
-(`run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.).
-If a plugin needs a capability the framework doesn't expose, expand the
-generic plugin surface (new hook, new ctx method) — never hardcode
-plugin-specific logic into core. PR #5295 removed 95 lines of hardcoded
-honcho argparse from `main.py` for exactly this reason.
-
-**No new in-tree memory providers (policy, May 2026):** the set of
-built-in memory providers under `plugins/memory/` is closed. New memory
-backends must ship as **standalone plugin repos** that users install
-into `~/.hermes/plugins/` (or via pip entry points) — they implement
-the same `MemoryProvider` ABC, register through the same discovery
-path, and integrate via `hermes memory setup` / `post_setup()` without
-landing in this tree. PRs that add a new directory under
-`plugins/memory/` will be closed with a pointer to publish the
-provider as its own repo. Existing in-tree providers stay; bug fixes
-to them are welcome.
-
-**No new third-party-product plugins in-tree (policy, June 2026):** the
-same rule applies beyond memory providers. Plugins that integrate
-someone else's product or project — observability/metrics backends,
-vendor SaaS connectors, analytics dashboards, paid-service tie-ins —
-must ship as **standalone plugin repos** that users install into
-`~/.hermes/plugins/` (or via pip entry points). They register through
-the existing plugin discovery path and use the ABCs/hooks/ctx surface
-we expose; nothing special is needed in core. The reason is
-maintenance load: every product we absorb into the tree becomes our
-burden to keep working against a fast-moving core, for a backend we
-don't own. Promote standalone plugins in the Nous Research Discord
-(`#plugins-skills-and-skins`). PRs that add such a directory under
-`plugins/` are closed with a pointer to publish it as its own repo —
-this is a coupling decision, not a quality judgment. (The
-`observability/`, `kanban/`, `disk-cleanup/`, etc. directories already
-in the tree are existing precedent, not an invitation to add more
-third-party-product plugins alongside them.)
-
-### Model-provider plugins (`plugins/model-providers/<name>/`)
+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
+pip: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers. Run `uv lock` after
+changing `pyproject.toml`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).
-Every inference backend (openrouter, anthropic, gmi, deepseek, nvidia, …)
-ships as a plugin here. Each plugin's `__init__.py` calls
-`providers.register_provider(ProviderProfile(...))` at module load.
-`providers/__init__.py._discover_providers()` is a **lazy, separate
-discovery system** — scanned on first `get_provider_profile()` or
-`list_providers()` call, NOT by the general PluginManager.
+## Commits, Merges, PRs
-Scan order:
-1. Bundled: `<repo>/plugins/model-providers/<name>/`
-2. User: `$HERMES_HOME/plugins/model-providers/<name>/`
-3. Legacy: `<repo>/providers/<name>.py` (back-compat)
+- **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.
-User plugins of the same name override bundled ones — `register_provider()`
-is last-writer-wins. This lets third parties swap out any built-in
-profile without a repo patch.
+## Testing (applies everywhere)
-The general PluginManager records `kind: model-provider` manifests but does
-NOT import them (would double-instantiate `ProviderProfile`). Plugins
-without an explicit `kind:` get auto-coerced via a source-text heuristic
-(`register_provider` + `ProviderProfile` in `__init__.py`).
-
-Full authoring guide: `website/docs/developer-guide/model-provider-plugin.md`.
-
-### Dashboard / context-engine / image-gen plugin directories
-
-`plugins/context_engine/`, `plugins/image_gen/`, etc. follow the same
-pattern (ABC + orchestrator + per-plugin directory). Context engines
-plug into `agent/context_engine.py`; image-gen providers into
-`agent/image_gen_provider.py`. Reference / docs-companion plugins
-(`example-dashboard`, `strike-freedom-cockpit`, `plugin-llm-example`,
-`plugin-llm-async-example`) live in the
-[`hermes-example-plugins`](https://github.com/NousResearch/hermes-example-plugins)
-companion repo, not in this tree.
-
-### Bot Mode (`apps/desktop/src/plugins/hermes-bots/`)
-
-The desktop "Bots" experience ships bundled in-tree. Each bot is a Hermes
-agent **profile** with a persistent identity. Its design rests on one settled
-invariant that has been regressed repeatedly, cost users real conversation
-history each time, and is not open for re-litigation in a routine PR:
-
-**One bot = ONE canonical forever-chat, identified by NAME.** The chat's one
-and only identity is **(profile, session titled exactly "Bot Chat")** — the
-state DB's UNIQUE(title) index makes that pair an exact registry of at most
-one row. The full lifecycle when a bot row is clicked:
-
-1. **Resolve the registry, every time.** Look up the profile's `Bot Chat`
- session by exact title via `session.list {title, include_hidden: true}`
- (indexed, window-free; hidden rows resolve because canonical chats are
- always hidden; compression lineages resolve to the live tip). Row exists →
- open it. That is the entire happy path.
-2. **No row → create it,** titled `Bot Chat`, born hidden, kicked off with
- the bot's intro. Creation adopts-before-minting: it re-runs the registry
- lookup first, so a concurrent or pre-existing row is opened, never forked.
- (`set_session_title` silently drops conflicting titles — returns 0 rows —
- which is how the 2026-08 infinite fork loop started; adopt-before-mint is
- what kills it.)
-
-**There is NO session-id pin.** The previous design stored a pointer in
-`ui_meta['hermes-bots'].chat` and verified it per click; five hardening
-waves (#88690, #90732, #90751, the #91791 revert, #92042) each guarded a new
-way that pointer dangled or got stolen — rows[0] steals, `last_session`
-adoptions, transient clears, drifted-title welds (a pin re-anchored onto a
-cron session passed every guard). Name-as-identity removes the failure class:
-a name cannot dangle, and a corrupted historical pointer simply never gets
-read. Legacy `chat` keys in ui_meta are ignored and dropped from merges.
-
-Why recency must never win (the #91791 → #92042 lesson): canonical Bot
-Chats are **unconditionally hidden** from the Sessions sidebar, so the bot
-row is the ONLY door to the forever-chat. A "newest visible session wins"
-preference doesn't re-order two equivalent entry points — it walls the
-entire relationship off behind a row that previews one session and opens
-another, and any stray draft that catches a prompt captures the row.
-Side-chats started via "New chat with this agent" are not plumbing-titled,
-stay visible in the Sessions sidebar, and are reachable there; they are
-never the bot row's target.
-
-Corollaries for reviewers:
-
-- There is no per-bot session browser, by explicit design (removed in
- #90732). Do not add one back.
-- Reject any PR that reintroduces a stored session-id pointer as canonical
- identity — including "as a fallback tier" or "for verification". The
- registry lookup is the whole contract; pointers are how every prior
- incident started.
-- Reject any PR that consults recency, visibility, or "where the user left
- off" for the bot row's target — reports that motivate such a change are
- almost always about side-chats, and the fix belongs in the Sessions
- sidebar (hide-sweep false positives), not in the bot row's target.
-- The gateway reports the registry row per profile as `canonical_session`
- on `profiles.list` (resolved server-side by title); roster preview,
- activity signals, and the `/new`→`/compact` guard all read it, so preview
- identity and click identity are the same row by construction.
-
-Regression tests encoding this contract:
-`tests/canonical-chat-registry.test.mjs` (includes a tripwire asserting the
-open path never reads or writes a stored pointer),
-`tests/canonical-chat-creation.test.mjs`, `tests/hide-bot-chats.test.mjs`,
-and `tests/tui_gateway/test_profiles_list_canonical_session.py`.
-
----
-
-## Skills
-
-Two parallel surfaces:
-
-- **`skills/`** — built-in skills shipped and loadable by default.
- Organized by category directories (e.g. `skills/github/`, `skills/mlops/`).
-- **`optional-skills/`** — heavier or niche skills shipped with the repo but
- NOT active by default. Installed explicitly via
- `hermes skills install official/<category>/<skill>`. Adapter lives in
- `tools/skills_hub_official.py` (`OptionalSkillSource`). Categories include
- `autonomous-ai-agents`, `blockchain`, `communication`, `creative`,
- `devops`, `email`, `health`, `mcp`, `migration`, `mlops`, `productivity`,
- `research`, `security`, `web-development`.
-
-When reviewing skill PRs, check which directory they target — heavy-dep or
-niche skills belong in `optional-skills/`.
-
-### SKILL.md frontmatter
-
-Standard fields: `name`, `description`, `version`, `author`, `license`,
-`platforms` (OS-gating list: `[macos]`, `[linux, macos]`, ...),
-`metadata.hermes.tags`, `metadata.hermes.category`,
-`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml
-settings the skill needs — stored under `skills.config.<key>`, prompted
-during setup, injected at load time).
-
-Top-level `tags:` and `category:` are also accepted and mirrored from
-`metadata.hermes.*` by the loader.
-
-### Skill authoring standards (HARDLINE)
-
-Every new or modernized skill — bundled, optional, or contributed —
-must meet these standards before merge. Reviewers reject PRs that
-violate them.
-
-1. **`description` ≤ 60 characters, one sentence, ends with a period.**
- Long descriptions bloat skill listings and dilute the model's
- attention when many skills are loaded. State the capability, not
- the implementation. No marketing words ("powerful",
- "comprehensive", "seamless", "advanced"). Don't repeat the skill
- name. Verify with:
- ```python
- import re, pathlib
- m = re.search(r'^description: (.*)$',
- pathlib.Path('skills/<cat>/<name>/SKILL.md').read_text(),
- re.MULTILINE)
- assert len(m.group(1)) <= 60, len(m.group(1))
- ```
-
-2. **Tools referenced in SKILL.md prose must be native Hermes tools or
- MCP servers the skill explicitly expects.** When the skill needs a
- capability, point at the proper tool by name in backticks
- (`` `terminal` ``, `` `web_extract` ``, `` `read_file` ``,
- `` `patch` ``, `` `search_files` ``, `` `vision_analyze` ``,
- `` `browser_navigate` ``, `` `delegate_task` ``, etc.). Do NOT
- name shell utilities the agent already has wrapped — `grep` →
- `search_files`, `cat`/`head`/`tail` → `read_file`, `sed`/`awk` →
- `patch`, `find`/`ls` → `search_files target='files'`. If the skill
- depends on an MCP server, name the MCP server and document the
- expected setup in `## Prerequisites`. Anything else (third-party
- CLIs, shell pipelines, etc.) is fair game inside script files but
- should not be the headline interaction surface in the prose.
-
-3. **`platforms:` gating audited against actual script imports.**
- Skills that use POSIX-only primitives (`fcntl`, `termios`,
- `os.setsid`, `os.kill(pid, 0)` for liveness, `/proc`, `/tmp`
- hardcoded, `signal.SIGKILL`, bash heredocs, `osascript`, `apt`,
- `systemctl`) must declare their supported platforms. Default
- posture: try to fix it cross-platform first — `tempfile.gettempdir`,
- `pathlib.Path`, `psutil.pid_exists`, Python-level filtering instead
- of `grep`. Gate to a narrower set only when the dependency is
- genuinely platform-bound.
-
-4. **`author` credits the human contributor first.** For external
- contributions, the contributor's real name + GitHub handle goes
- first; "Hermes Agent" is the secondary collaborator. If the
- contributor's commit shows "Hermes Agent" as author (because they
- used Hermes to draft the skill), replace it with their actual name
- — credit the human, not the tool.
-
-5. **SKILL.md body uses the modern section order.** `# <Skill> Skill`
- title, 2-3 sentence intro stating what it does and doesn't do,
- `## When to Use`, `## Prerequisites`, `## How to Run`,
- `## Quick Reference`, `## Procedure`, `## Pitfalls`,
- `## Verification`. Target ~200 lines for a complex skill,
- ~100 lines for a simple one. Cut redundant intro fluff, marketing
- prose, and re-explanations of env vars already in
- `## Prerequisites`.
-
-6. **Scripts go in `scripts/`, references in `references/`,
- templates in `templates/`.** Don't expect the model to inline-write
- parsers, XML walkers, or non-trivial logic every call — ship a
- helper script. Reference it from SKILL.md by path relative to the
- skill directory.
-
-7. **Tests live at `tests/skills/test_<skill>_skill.py`** and use only
- stdlib + pytest + `unittest.mock`. No live network calls. Run via
- `scripts/run_tests.sh tests/skills/test_<skill>_skill.py -q`.
-
-8. **`.env.example` additions are isolated to a clearly delimited
- block.** Don't touch the surrounding file — contributor-supplied
- `.env.example` versions are usually stale and edits outside the
- skill's own block must be dropped during salvage.
-
-The full salvage / modernization checklist for external skill PRs
-lives in the `hermes-agent-dev` skill at
-`references/new-skill-pr-salvage.md` — load it before polishing
-contributor skill PRs.
-
----
-
-## Toolsets
-
-All toolsets are defined in `toolsets.py` as a single `TOOLSETS` dict.
-Each platform's adapter picks a base toolset (e.g. Telegram uses
-`"messaging"`); `_HERMES_CORE_TOOLS` is the default bundle most
-platforms inherit from.
-
-Current toolset keys: `browser`, `clarify`, `code_execution`, `cronjob`,
-`debugging`, `delegation`, `discord`, `discord_admin`, `feishu_doc`,
-`feishu_drive`, `file`, `homeassistant`, `image_gen`, `kanban`, `memory`,
-`messaging`, `moa`, `rl`, `safe`, `search`, `session_search`, `skills`,
-`spotify`, `terminal`, `todo`, `tts`, `video`, `vision`, `web`, `yuanbao`.
-
-Enable/disable per platform via `hermes tools` (the curses UI) or the
-`tools.<platform>.enabled` / `tools.<platform>.disabled` lists in
-`config.yaml`.
-
----
-
-## Delegation (`delegate_task`)
-
-`tools/delegate_tool.py` spawns a subagent with an isolated
-context + terminal session. By default the parent waits for the
-child's summary before continuing its own loop. With `background=true`,
-Hermes returns a delegation id immediately and the result re-enters the
-conversation later through the async-delegation completion queue.
-
-Two shapes:
-
-- **Single:** pass `goal` (+ optional `context`, `toolsets`).
-- **Batch (parallel):** pass `tasks: [...]` — each gets its own subagent
- running concurrently. Concurrency is capped by
- `delegation.max_concurrent_children` (default 3).
-
-Roles:
-
-- `role="leaf"` (default) — focused worker. Cannot call `delegate_task`,
- `clarify`, `memory`, `send_message`, `cronjob`. Retains `execute_code`
- (programmatic tool calling).
-- `role="orchestrator"` — retains `delegate_task` so it can spawn its
- own workers. Gated by `delegation.orchestrator_enabled` (default true)
- and bounded by `delegation.max_spawn_depth` (default 2).
-
-Key config knobs (under `delegation:` in `config.yaml`):
-`max_concurrent_children`, `max_spawn_depth`, `child_timeout_seconds`,
-`orchestrator_enabled`, `subagent_auto_approve`, `inherit_mcp_toolsets`,
-`max_iterations`.
-
-Durability rule: background `delegate_task` is detached from the current
-turn but still process-local. For work that must survive process restart, use
-`cronjob` or `terminal(background=True, notify_on_complete=True)` instead.
-
----
-
-## Curator (skill lifecycle)
-
-Background skill-maintenance system that tracks usage on agent-created
-skills and auto-archives stale ones. Users never lose skills; archives
-go to `~/.hermes/skills/.archive/` and are restorable.
-
-- **Core:** `agent/curator.py` (review loop, auto-transitions, LLM review
- prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots).
-- **CLI:** `hermes_cli/curator.py` wires `hermes curator <verb>` where
- verbs are: `status`, `run`, `pause`, `resume`, `pin`, `unpin`,
- `archive`, `restore`, `prune`, `backup`, `rollback`.
-- **Telemetry:** `tools/skill_usage.py` owns the sidecar
- `~/.hermes/skills/.usage.json` — per-skill `use_count`, `view_count`,
- `patch_count`, `last_activity_at`, `state` (active / stale /
- archived), `pinned`.
-
-Invariants:
-- Curator only touches skills with `created_by: "agent"` provenance —
- bundled + hub-installed skills are off-limits.
-- Never deletes; max destructive action is archive.
-- Pinned skills are exempt from every auto-transition and from the
- LLM review pass.
-- `skill_manage(action="delete")` refuses pinned skills; patch/edit/
- write_file/remove_file go through so the agent can keep improving
- pinned skills.
-
-Config section (`curator:` in `config.yaml`):
-`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,
-`archive_after_days`, `backup.*`.
-
-Full user-facing docs: `website/docs/user-guide/features/curator.md`.
-
----
-
-## Cron (scheduled jobs)
-
-`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop). Agents
-schedule jobs via the `cronjob` tool; users via `hermes cron <verb>`
-(`list`, `add`, `edit`, `pause`, `resume`, `run`, `remove`) or the
-`/cron` slash command.
-
-Supported schedule formats:
-- Duration: `"30m"`, `"2h"`, `"1d"`
-- "every" phrase: `"every 2h"`, `"every monday 9am"`
-- 5-field cron expression: `"0 9 * * *"`
-- ISO timestamp (one-shot): `"2026-06-01T09:00:00Z"`
-
-Per-job fields include `skills` (load specific skills), `model` /
-`provider` overrides, `script` (pre-run data-collection script whose
-stdout is injected into the prompt; `no_agent=True` turns the script
-into the entire job), `context_from` (chain job A's last output into
-job B's prompt), `workdir` (run in a specific directory with its
-`AGENTS.md`/`CLAUDE.md` loaded), and multi-platform delivery.
-
-Hardening invariants:
-- **3-minute hard interrupt** on cron sessions — runaway agent loops
- cannot monopolize the scheduler.
-- Catchup window: half the job's period, clamped to 120s–2h.
-- Grace window: 120s for one-shot jobs whose fire time was missed.
-- File lock at `~/.hermes/cron/.tick.lock` prevents duplicate ticks
- across processes.
-- Cron sessions pass `skip_memory=True` by default; memory providers
- intentionally do not run during cron.
-
-Cron deliveries are **not** mirrored into the target gateway session —
-they land in their own cron session with a header/footer frame so the
-main conversation's message-role alternation stays intact.
-
----
-
-## Kanban (multi-agent work queue)
-
-Durable SQLite-backed board that lets multiple profiles / workers
-collaborate on shared tasks. Users drive it via `hermes kanban <verb>`;
-workers spawned by the dispatcher drive it via a dedicated `kanban_*`
-toolset so their schema footprint is zero when they're not inside a
-kanban task.
-
-- **CLI:** `hermes_cli/kanban.py` wires `hermes kanban` with verbs
- `init`, `create`, `list` (alias `ls`), `show`, `assign`, `link`,
- `unlink`, `comment`, `attach`, `attachments`, `attach-rm`, `complete`,
- `request-review`, `request-changes`, `reopen-review`, `block`, `unblock`, `archive`,
- `tail`, plus less-commonly-used `watch`, `stats`, `runs`, `log`,
- `assignees`, `heartbeat`, `notify-*`, `dispatch`, `daemon`, `gc`.
-- **Worker/orchestrator toolset:** `tools/kanban_tools.py` exposes
- `kanban_show`, `kanban_complete`, `kanban_request_review`,
- `kanban_request_changes`, `kanban_block`,
- `kanban_heartbeat`, `kanban_comment`, `kanban_create`, `kanban_link`,
- `kanban_attach`, `kanban_attach_url`, `kanban_attachments`; profiles that
- explicitly enable the `kanban` toolset outside a dispatcher-spawned
- task also get `kanban_list` and `kanban_unblock` for board routing.
-- **Dispatcher:** long-lived loop that (default every 60s) reclaims
- stale claims, promotes ready tasks, atomically claims, and spawns
- assigned profiles. Runs **inside the gateway** by default via
- `kanban.dispatch_in_gateway: true`.
-- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) +
- `plugins/kanban/systemd/` (`hermes-kanban-dispatcher.service` for
- standalone dispatcher deployment).
-
-Isolation model:
-- **Board** is the hard boundary — workers are spawned with
- `HERMES_KANBAN_BOARD` pinned in their env so they can't see other
- boards.
-- **Tenant** is a soft namespace *within* a board — one specialist
- fleet can serve multiple businesses with workspace-path + memory-key
- isolation.
-- After `kanban.failure_limit` consecutive non-success attempts on the
- same task (default: 2), the dispatcher auto-blocks it to prevent spin
- loops.
-
-Full user-facing docs: `website/docs/user-guide/features/kanban.md`.
-
----
-
-## Update Pipeline (`hermes update`)
-
-The updater is transactional in shape (fleet-update campaign, #91277 —
-Aug 2026). Every stage exists because its absence was a real field
-failure; PRs that weaken a stage need to answer for the failure class it
-guards:
-
-```
-plan → snapshot → apply → restart-per-kind → verify → report
-```
-
-- **Plan** (`hermes_cli/update_inventory.py`, `hermes update --plan`):
- read-only inventory — install kind, all profiles, every live gateway
- with supervisor + running code version. Deployment kinds are
- first-class: `git` updates in place; `docker`/`nix`/`apt` are NOT
- in-place-updatable and the updater reports the correct external
- command instead of fighting the deployment model.
-- **Snapshot** (`hermes_cli/backup.py`): pre-update quick snapshot for
- EVERY profile (the code swap + fleet restart touch all of them), each
- into its own `state-snapshots/`, identical file set + 1 GiB per-file
- cap + keep=1. **Never add a partial/tiered snapshot set** — mixed
- coverage creates torn-restore states across schema generations. Quick
- snapshots are FILE-LOSS RECOVERY (the per-profile cron-jobs safety
- net restores from them), NOT code-rollback insurance; `--backup` full
- mode owns rollback.
-- **Apply**: git pull, or the Windows ZIP fallback — which fires ONLY
- when git itself failed (`_should_zip_fallback_on_update_error`,
- argv-classified; a dependency-install failure must never trigger a
- tree-clobbering re-download), REFUSES a dirty working tree
- (`-uall`, plus a pre-swap TOCTOU re-check), and grafts the live
- `apps/desktop/release/` into the staged swap (the GitHub source ZIP
- has no built desktop app; without the graft the swap deletes it).
-- **Restart-per-kind**: systemd and launchd restarts are FLEET-WIDE
- (every `hermes-gateway*` unit / `ai.hermes.gateway*` LaunchAgent),
- drain-first (SIGUSR1) with per-unit/per-label failure isolation.
- Restarting only the invoking profile's service leaves siblings on
- stale `sys.modules` until they crash — the largest dupe-PR cluster in
- the repo's history came from that bug.
-- **Verify**: gateways stamp their running `code_sha`/`code_version`
- into `gateway_state.json` on every runtime-status write
- (`gateway/status.py`); after the restart phase the updater compares
- each live gateway against the fresh checkout and prints a fleet
- version matrix. A provably-stale gateway fails the update (exit 1) —
- automation must never treat a mixed-version fleet as healthy.
-- **Report**: every run writes a machine-readable receipt to
- `~/.hermes/logs/update_receipts/` (`latest.json` pointer; steps,
- skips WITH reasons, restart outcome, plan, fleet snapshot).
- Finalization is owned by the `cmd_update` command boundary — early
- `sys.exit` paths (preflight refusals, fetch failures) still persist
- a receipt with the real exit code. A begun-but-unwritten receipt is
- a bug: the refused/failed runs are the ones receipts exist for.
-
-Architecture direction: process-scan-based coordination between the
-updater, serve/dashboard, and the gateway is being replaced by a
-gateway-owned control socket (#92091). Do not add new scan heuristics
-without checking that design; scans are the fallback layer.
-
-### Gateway lifecycle vs. the Desktop app
-
-`hermes serve` (control plane, desktop-spawned child) dies with the app
-— by design. The messaging gateway (`gateway run`) SURVIVES the app: the
-serve backend's `/api/gateway/*` endpoints spawn it detached
-(`_spawn_hermes_action` — `start_new_session` / `DETACHED_PROCESS`), so
-`before-quit`'s backend SIGTERM never reaches it. Bots keep running
-when the user closes the app. The known breach of this contract is the
-Windows shim-unlock teardown (`taskkill /T /F` on venv-shim holders,
-#85265) — it exists to let updates proceed, and its replacement is
-#92091's `pause-for-update`. Do not "fix" gateway-dies-with-app reports
-by re-parenting the gateway under the backend, and do not "fix" update
-locks by widening the tree-kill.
-
----
-
-## Important Policies
-
-### Prompt Caching Must Not Break
-
-Hermes-Agent ensures caching remains valid throughout a conversation. **Do NOT implement changes that would:**
-- Alter past context mid-conversation
-- Change toolsets mid-conversation
-- Reload memories or rebuild system prompts mid-conversation
-
-Cache-breaking forces dramatically higher costs. The ONLY time we alter context is during context compression.
-
-Slash commands that mutate system-prompt state (skills, tools, memory, etc.)
-must be **cache-aware**: default to deferred invalidation (change takes
-effect next session), with an opt-in `--now` flag for immediate
-invalidation. See `/skills install --now` for the canonical pattern.
-
-### Background Process Notifications (Gateway)
-
-When `terminal(background=true, notify_on_complete=true)` is used, the gateway runs a watcher that
-detects process completion and triggers a new agent turn. Control verbosity of background process
-messages with `display.background_process_notifications`
-in config.yaml (or `HERMES_BACKGROUND_NOTIFICATIONS` env var):
-
-- `concise` — one-line status message on completion; failures append a short output tail (default)
-- `all` — running-output updates + final raw-output message
-- `result` — only the final raw-output completion message
-- `error` — only the final raw-output message when exit code != 0
-- `off` — no watcher messages at all
-
----
-
-## Profiles: Multi-Instance Support
-
-Hermes supports **profiles** — multiple fully isolated instances, each with its own
-`HERMES_HOME` directory (config, API keys, memory, sessions, skills, gateway, etc.).
-
-The core mechanism: `_apply_profile_override()` in `hermes_cli/main.py` sets
-`HERMES_HOME` before any module imports. All `get_hermes_home()` references
-automatically scope to the active profile.
-
-### Rules for profile-safe code
-
-1. **Use `get_hermes_home()` for all HERMES_HOME paths.** Import from `hermes_constants`.
- NEVER hardcode `~/.hermes` or `Path.home() / ".hermes"` in code that reads/writes state.
- ```python
- # GOOD
- from hermes_constants import get_hermes_home
- config_path = get_hermes_home() / "config.yaml"
-
- # BAD — breaks profiles
- config_path = Path.home() / ".hermes" / "config.yaml"
- ```
-
-2. **Use `display_hermes_home()` for user-facing messages.** Import from `hermes_constants`.
- This returns `~/.hermes` for default or `~/.hermes/profiles/<name>` for profiles.
- ```python
- # GOOD
- from hermes_constants import display_hermes_home
- print(f"Config saved to {display_hermes_home()}/config.yaml")
-
- # BAD — shows wrong path for profiles
- print("Config saved to ~/.hermes/config.yaml")
- ```
-
-3. **Module-level constants are fine** — they cache `get_hermes_home()` at import time,
- which is AFTER `_apply_profile_override()` sets the env var. Just use `get_hermes_home()`,
- not `Path.home() / ".hermes"`.
-
-4. **Tests that mock `Path.home()` must also set `HERMES_HOME`** — since code now uses
- `get_hermes_home()` (reads env var), not `Path.home() / ".hermes"`:
- ```python
- with patch.object(Path, "home", return_value=tmp_path), \
- patch.dict(os.environ, {"HERMES_HOME": str(tmp_path / ".hermes")}):
- ...
- ```
-
-5. **Gateway platform adapters should use token locks** — if the adapter connects with
- a unique credential (bot token, API key), call `acquire_scoped_lock()` from
- `gateway.status` in the `connect()`/`start()` method and `release_scoped_lock()` in
- `disconnect()`/`stop()`. This prevents two profiles from using the same credential.
- See `plugins/platforms/irc/adapter.py` for the canonical pattern.
-
-6. **Profile operations are HOME-anchored, not HERMES_HOME-anchored** — `_get_profiles_root()`
- returns `Path.home() / ".hermes" / "profiles"`, NOT `get_hermes_home() / "profiles"`.
- This is intentional — it lets `hermes -p coder profile list` see all profiles regardless
- of which one is active.
-
-7. **Multiplex profile-scoped env reads MUST fail closed — never borrow from `os.environ`**
- (`agent/secret_scope.py` contract; #72348, #86905). Under `gateway.multiplex_profiles`,
- `os.environ` holds the **default profile's** values; a secondary profile's `.env` lives
- only in its secret scope (installed per-turn by `_profile_runtime_scope`). Any
- profile-level env config — credentials (`app_secret`, tokens) AND authorization
- (`FEISHU_ALLOWED_USERS`, `{PLATFORM}_ALLOW_ALL_USERS`, `GATEWAY_ALLOW_ALL_USERS`,
- `group_policy`, `allow_bots`, ...) — must be read scope-aware:
- - Adapters: `_get_scoped_secret()` (canonical fail-closed copy in
- `plugins/platforms/feishu/adapter.py`, #86905).
- - Gateway authz: `_auth_env()` / `_platform_gate_env()` (`gateway/authz_mixin.py`).
- Rules:
- - Scope installed + multiplex active → a scoped miss returns the **default**.
- NEVER fall through to `os.environ` — that leaks another profile's value and
- silently breaks routing/admission (a leaked default allowlist skips the
- allow-all check and rejects every secondary-profile sender, #86905).
- - Unscoped default-profile path (`UnscopedSecretError`) and single-profile
- deployments keep the `os.environ` read — there it IS the profile's own value.
- - Authorization config is the sharpest edge: allowlist/allow-all leaks cause
- silent rejections (or worse, fail-open) that only show up as missing replies.
- - The `_get_scoped_secret` wrapper is copy-pasted across ~15 platform adapters —
- when touching any of them, make sure the fail-closed semantics are present;
- do not reintroduce the `except _UnscopedSecretError: val = os.getenv(...)`
- fallback-after-miss shape.
-
-## Known Pitfalls
-
-### DO NOT infer process identity from argv substrings
-The bug class behind ~10 fleet-update issues (#90778, #87594, #78089,
-#76129, #91964, ...): classifying a process by `"serve" in cmdline` or
-similar. `kanban --preserve-cache` contains "serve"; a flag VALUE can
-equal a subcommand (`-m dashboard serve`); truncated cmdlines hide the
-real subcommand. Rules:
-- Use the canonical matchers: `gateway.status.looks_like_gateway_command_line`
- (gateway run), `hermes_cli.update_cmd._hermes_holder_subcommand`
- (top-level subcommand of any Hermes argv). Never hand-roll token scans.
-- Flag sets must be DERIVED from the parser
- (`_holder_value_flags()` introspects `build_top_level_parser()`), never
- hand-written lists — they drift.
-- Never blanket-exclude ancestors from process scans: when `/update` runs
- as the gateway's child, a gateway ancestor must stay visible to the
- pause machinery (#87594). Exclude interactive ancestry, carve out
- gateway-shaped ancestors.
-- Match on FULL cmdlines; truncate only at display time (#78089).
-- Before adding any new scan heuristic, read #92091 — the gateway control
- socket replaces scans as the primary coordination mechanism; scans are
- the fallback layer for old/crashed processes.
-
-### DO NOT hardcode `~/.hermes` paths
-Use `get_hermes_home()` from `hermes_constants` for code paths. Use `display_hermes_home()`
-for user-facing print/log messages. Hardcoding `~/.hermes` breaks profiles — each profile
-has its own `HERMES_HOME` directory. This was the source of 5 bugs fixed in PR #3575.
-
-### All CLI menu-pickers MUST use curses.
-Interactive menus must use `hermes_cli/curses_ui.py`. See `hermes_cli/tools_config.py` for an example.
-
-### DO NOT use `\033[K` (ANSI erase-to-EOL) in spinner/display code
-Leaks as literal `?[K` text under `prompt_toolkit`'s `patch_stdout`. Use space-padding: `f"\r{line}{' ' * pad}"`.
-
-### `_last_resolved_tool_names` is a process-global in `model_tools.py`
-`_run_single_child()` in `delegate_tool.py` saves and restores this global around subagent execution. If you add new code that reads this global, be aware it may be temporarily stale during child agent runs.
-
-### DO NOT hardcode cross-tool references in schema descriptions
-Tool schema descriptions must not mention tools from other toolsets by name (e.g., `browser_navigate` saying "prefer web_search"). Those tools may be unavailable (missing API keys, disabled toolset), causing the model to hallucinate calls to non-existent tools. If a cross-reference is needed, add it dynamically in `get_tool_definitions()` in `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks for the pattern.
-
-### The gateway has TWO message guards — both must bypass approval/control commands
-When an agent is running, messages pass through two sequential guards:
-(1) **base adapter** (`gateway/platforms/base.py`) queues messages in
-`_pending_messages` when `session_key in self._active_sessions`, and
-(2) **gateway runner** (`gateway/run.py`) intercepts `/stop`, `/new`,
-`/queue`, `/status`, `/approve`, `/deny` before they reach
-`running_agent.interrupt()`. Any new command that must reach the runner
-while the agent is blocked (e.g. approval prompts) MUST bypass BOTH
-guards and be dispatched inline, not via `_process_message_background()`
-(which races session lifecycle).
-
-### Streaming delivery contract (stream-is-the-message adapters) — duplicate-final class
-Adapters with `draft_stream_is_message = True` (relay Slack native streaming)
-keep ONE cumulative native stream per turn; the stream IS the final message.
-Four invariants, each learned from a live duplicate-final incident (NS-658
-canary ledger, hermes#85796 / gateway-gateway#210). Violating any of them
-re-creates a duplicate or a frozen stream:
-
-1. **Draft frames must be prefix-stable.** The connector computes append-only
- deltas: frame N must be a string prefix of frame N+1. NEVER mutate draft
- frames per-tick — no fence-closing (`ensure_closed_code_fences`), no cursor
- suffix, no segment-state resets at tool boundaries, no mrkdwn conversion.
- Any non-prefix frame triggers a whole-snapshot re-append on the platform
- ("stacked copies"). The finalize path may still transform the real final.
-2. **The consumer declares the final; the adapter never guesses.**
- `finish(final_text)` carries the completed `final_response` (verifier
- footer, completion explainer included) as the authoritative finalize
- payload. New post-stream response augmentation MUST ride this payload —
- if it mutates `final_response` after the stream sealed, it re-opens the
- #11 bug (`delivered_final_matches` mismatch → corrective duplicate send).
-3. **Interim sends must carry `_interim_send` metadata.** Any consumer-side
- `adapter.send()` that is NOT the turn-final (commentary, segment-tail
- flushes) must set `metadata["_interim_send"] = True`, or the relay
- adapter's seal-interception will seal the live stream with interim text.
- Seal-interception exists at BOTH egress doors (`send()` AND
- `send_for_platform()`); a new egress door needs the same two checks.
-4. **Reconcile by edit, never by plain send.** Any lane that delivers a final
- beside an already-sealed stream (queued follow-ups, media-accompanied
- finals, future lanes) must first try `edit_message` on the consumer's
- `message_id`; plain `send()` is the fallback only when no editable message
- exists. A sealed native stream is a regular message — `chat.update` on it
- works (live-verified).
-
-Contract tests: `tests/gateway/test_stream_final_contract.py` (all four
-invariants, mutation-checked). Slack streaming API ground truth (live-probed,
-also encoded in connector comments/tests): `chat.*Stream` speaks STANDARD
-markdown, not mrkdwn; `stopStream.markdown_text` APPENDS (never replaces);
-`startStream`/`stopStream` are rate-limit Tier 2 (~20/min).
-
-Guard style note: check `draft_stream_is_message` with `is True` — MagicMock
-adapters in older tests auto-create truthy attributes.
-
-### Squash merges from stale branches silently revert recent fixes
-Before squash-merging a PR, ensure the branch is up to date with `main`
-(`git fetch origin main && git reset --hard origin/main` in the worktree,
-then re-apply the PR's commits). A stale branch's version of an unrelated
-file will silently overwrite recent fixes on main when squashed. Verify
-with `git diff HEAD~1..HEAD` after merging — unexpected deletions are a
-red flag.
-
-### Don't wire in dead code without E2E validation
-Unused code that was never shipped was dead for a reason. Before wiring an
-unused module into a live code path, E2E test the real resolution chain
-with actual imports (not mocks) against a temp `HERMES_HOME`.
-
-### Tests must not write to `~/.hermes/`
-The `_isolate_hermes_home` autouse fixture in `tests/conftest.py` redirects `HERMES_HOME` to a temp dir. Never hardcode `~/.hermes/` paths in tests.
-
-**Profile tests**: When testing profile features, also mock `Path.home()` so that
-`_get_profiles_root()` and `_get_default_hermes_home()` resolve within the temp dir.
-Use the pattern from `tests/hermes_cli/test_profiles.py`:
-```python
-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
-```
-
----
-
-## Testing
-
-### Python
-**ALWAYS use `scripts/run_tests.sh`** — do not call `pytest` directly. The script enforces
-hermetic environment parity with CI (unset credential vars, TZ=UTC, LANG=C.UTF-8,
-per-file subprocess isolation via `scripts/run_tests_parallel.py` — no xdist,
-worker count auto-scaled from CPU count). Direct `pytest`
-on a 16+ core developer machine with API keys set diverges from CI in ways
-that have caused multiple "works locally, fails in CI" incidents (and the reverse).
+**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).
```bash
-scripts/run_tests.sh # full suite, CI-parity
-scripts/run_tests.sh tests/gateway/ # one directory
-scripts/run_tests.sh tests/agent/test_foo.py -k test_x # one test (file + -k; the runner is file-granular)
-scripts/run_tests.sh -v --tb=long # pass-through pytest flags
+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:** the runner auto-retries a failing test FILE once in a fresh
-subprocess (`--file-retries`, default 1; `HERMES_TEST_FILE_RETRIES=0` to
-disable). Pass-on-retry counts as green but is printed in a `⚠ FLAKY` summary
-section with both attempts' output. A FLAKY report is a bug to fix, not noise
-to ignore — timing-sensitive tests must not assume a quiet runner (loose
-wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)`
-negative-timing races).
-
-#### Subprocess-per-test-file isolation
-
-Every test file runs in a freshly-spawned Python subprocess via `run_tests_parallel.py`. This means module-level dicts/sets and
-ContextVars from one test file cannot leak into the next.
-
-#### Why the wrapper
-
-| | Without wrapper | With wrapper |
-| ------------------- | ------------------------------------------- | ----------------------------------------- |
-| Provider API keys | Whatever is in your env (auto-detects pool) | All env vars except a specific few unset. |
-| HOME / `~/.hermes/` | Your real config+auth.json | Temp dir per test |
-| Timezone | Local TZ (PDT etc.) | UTC |
-| Locale | Whatever is set | C.UTF-8 |
-
-### Where to place what tests
-
-The CI change classifier (`scripts/ci/classify_changes.py`) runs specific jobs based on what files changed. A Python test that asserts
-about the contents of `package.json`, `package-lock.json`, `.ts`/`.tsx`
-source, or any other JS-side artifact will not run on a PR that only touches
-those files. This means a regression can go green on a PR and red on `main` (where the
-classifier fails open and runs everything).
-
-Any test that reads or asserts about `package.json`,
-`package-lock.json`, `tsconfig.json`, `.ts`/`.tsx`/`.js`/`.mjs`/`.cjs`
-source files configuration belongs in the JS (vitest) test suite, not in `tests/*.py`.
+- **Flake policy:** a failing FILE is retried once in a fresh subprocess (`--file-retries`;
+ `HERMES_TEST_FILE_RETRIES=0` disables). 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:** `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
-Hermes supports Linux, macOS and native Windows, and plenty of its behaviour
-genuinely differs per host. Those differences are tested by running on the
-host, not by patching `sys.platform`.
-
-```python
-```
-
-Things that are host-independent can stay unmarked:
-
-- **Pure functions that take a platform as data** —
- `hidden_windows_child_options(opts, is_windows=True)` is input→output, not a
- fake host. (Contrast: setting a module-level `IS_WINDOWS` flag and then
- calling `windows_detach_flags()` *is* a fake.)
-- **Declaration/packaging invariants** — "pyproject declares `tzdata` with a
- `sys_platform == 'win32'` marker" asserts about a file, not about runtime.
-
-The line: **if the test needs the interpreter to believe it is on another OS
-in order to pass, it belongs on that OS.**
-When one test body walks several platforms in sequence, split it.
-Keep the host-native arm on the Linux lane and move the other arm into its own marked test.
-
-**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 the macOS/Windows lanes import by grepping for the marker
-*name*, and the lane then filters with `-m <marker>`. A test gated with
-`@pytest.mark.skipif(sys.platform != "win32")` therefore skips on Linux AND is
-never imported on the Windows lane — it runs on no host at all, silently. The
-same trap catches a file-local alias (`windows_only = pytest.mark.skipif(...)`):
-the grep matches the name, so the file *is* listed, but `-m windows_only`
-deselects every test in it and the lane reports green over zero coverage.
-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.
+Behaviour that genuinely differs per host is tested ON that host with `@pytest.mark.linux_only`
+/ `macos_only` / `windows_only`, 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.
+
+**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py` finds files for
+the macOS/Windows lanes by grepping the marker *name*, then filters with `-m <marker>`. A
+`skipif(sys.platform != "win32")` test skips on Linux AND is never imported on Windows — it runs
+nowhere, silently. A file-local alias (`windows_only = pytest.mark.skipif(...)`) is listed but
+`-m windows_only` deselects everything: green over zero coverage. Don't `pytest.skip()` non-host
+rows of a platform `@parametrize` — split into one marked test per OS.
+
+**Live Windows process-topology E2E (`wine2e` lane):** `windows-venv-e2e.yml` runs
+`tests/hermes_cli/test_venv_holder_windows_live.py` on a real `windows-latest` runner (real
+processes, no mocked psutil) ONLY on pushes to `wine2e/**` branches. Workflow: write probes
+pinning CORRECT behavior, push to `wine2e/` to reproduce live on unfixed code, fix, iterate to
+green, then open the PR with the live receipt. Extend it 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).
### Don't write change-detector tests
-A test is a **change-detector** if it fails whenever data that is **expected
-to change** gets updated — model catalogs, config version numbers,
-enumeration counts, hardcoded lists of provider models. These tests add no
-behavioral coverage; they just guarantee that routine source updates break
-CI and cost engineering time to "fix."
-
-**Do not write:**
-
-```python
-# catalog snapshot — breaks every model release
-assert "gemini-2.5-pro" in _PROVIDER_MODELS["gemini"]
-assert "MiniMax-M2.7" in models
-
-# config version literal — breaks every schema bump
-assert DEFAULT_CONFIG["_config_version"] == 21
-
-# enumeration count — breaks every time a skill/provider is added
-assert len(_PROVIDER_MODELS["huggingface"]) == 8
-```
-
-**Do write:**
-
-```python
-# behavior: does the catalog plumbing work at all?
-assert "gemini" in _PROVIDER_MODELS
-assert len(_PROVIDER_MODELS["gemini"]) >= 1
-
-# behavior: does migration bump the user's version to current latest?
-assert raw["_config_version"] == DEFAULT_CONFIG["_config_version"]
-
-# invariant: no plan-only model leaks into the legacy list
-assert not (set(moonshot_models) & coding_plan_only_models)
-
-# invariant: every model in the catalog has a context-length entry
-for m in _PROVIDER_MODELS["huggingface"]:
- assert m.lower() in DEFAULT_CONTEXT_LENGTHS_LOWER
-```
-
-The rule: if the test reads like a snapshot of current data, delete it. If
-it reads like a contract about how two pieces of data must relate, keep it.
-When a PR adds a new provider/model and you want a test, make the test
-assert the relationship (e.g. "catalog entries all have context lengths"),
-not the specific names.
-
-Reviewers should reject new change-detector tests; authors should convert
-them into invariants before re-requesting review.
+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 source file's text is testing *the shape of the
-source code*, not its behavior. This is a hard antipattern, banned outright.
-Any test that reads a .py, .ts, .tsx, etc., file is suspect.
-
-**Why it's actively harmful, not just weak:**
-
-- It passes when the implementation is subtly broken (the regex matches a
- call site that exists but is wired wrong) and fails when a correct
- refactor changes formatting, variable names, or control flow with
- identical runtime behavior. Both directions of failure are wrong.
-- It can't be run against a built/bundled/minified artifact, so it silently
- stops testing anything the moment code moves, gets renamed, or a
- dependency reformats it.
-- It actively blocks refactors: reviewers see "keeps a pattern intact" tests
- fail during pure structural cleanup with no behavior change, and either
- hand-wave the failure (dangerous) or waste time updating regexes that add
- nothing (waste).
-- It gives false confidence. a green suite full of source-regex tests
- looks like coverage but has never once executed the code path it claims
- to guard.
-
-**Do not write:**
-
+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
-const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')
-
-test('backend spawn hides the Windows console', () => {
- assert.match(source, /spawn\(\s*backend\.command,\s*backend\.args[\s\S]{0,300}hiddenWindowsChildOptions/)
-})
-```
-
-**Do write — extract the logic into a small pure/DI-testable function and
-call it for real:**
-
-```ts
-// backend-spawn.ts
-export function hiddenWindowsChildOptions(options: SpawnOptionsLike = {}, isWindows = process.platform === 'win32') {
+export function hiddenWindowsChildOptions(options = {}, isWindows = process.platform === 'win32') {
if (!isWindows || 'windowsHide' in options) return options
return { ...options, windowsHide: true }
}
-
-// backend-spawn.test.ts
-test('windowsHide defaults to true on Windows, is left alone elsewhere', () => {
- assert.equal(hiddenWindowsChildOptions({}, true).windowsHide, true)
- assert.equal(hiddenWindowsChildOptions({}, false).windowsHide, undefined)
- assert.equal(hiddenWindowsChildOptions({ windowsHide: false }, true).windowsHide, false)
-})
```
+If the logic lives inline in a god-file and extraction feels disruptive, that is the signal to
+extract, not to regex around it.
-If the logic lives inline in a god-file (`main.ts`, `cli.py`,
-`gateway/run.py`) and extracting it feels disruptive: that's the actual
-signal to do the extraction, not to regex around it.
+## 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, Sep-2026 compat window |
+| `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 |
+
+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.
diff --git a/agent/AGENTS.md b/agent/AGENTS.md
new file mode 100644
index 00000000000..7fb81c5a66a
--- /dev/null
+++ b/agent/AGENTS.md
@@ -0,0 +1,109 @@
+# agent/ — AIAgent, turn loop, prompt, compression
+
+Applies on top of the root `AGENTS.md` (prompt-caching invariant, facade + siblings rules).
+
+## Shape
+
+`run_agent.py` is the public facade: `AIAgent` is assembled from mixins (`agent/turn_facade.py`,
+`client_lifecycle.py`, `stream_delivery.py`, `session_persistence.py`, `compression_facade.py`, ...).
+Construction runs `agent/agent_init.py::init_agent`; a turn is
+`agent/conversation_loop.py::run_conversation`, which `AIAgent.run_conversation` forwards to after
+taking the session turn lease (`turn_facade_lease.py`). `AIAgent.__init__` takes ~60 parameters
+(credentials, routing, callbacks, session context, budget, credential pool, ...) — read
+`run_agent.py` for the list; the subset you usually touch: `base_url`, `api_key`, `provider`,
+`api_mode` (`"chat_completions" | "codex_responses" | ...`), `model` (empty → resolved from
+config/provider later), `max_iterations` (default 500, shared with subagents),
+`enabled_toolsets`/`disabled_toolsets`, `quiet_mode`, `save_trajectories`, `platform`
+(`"cli"`, `"telegram"`, ...), `session_id`, `skip_context_files`, `skip_memory`, `credential_pool`.
+`chat(message) -> str` is the simple interface; `run_conversation(user_message, system_message=None,
+conversation_history=None, task_id=None) -> dict` returns `final_response` + `messages`.
+
+## Agent loop (`agent/conversation_loop.py` + `agent/turn_*.py`)
+
+Entirely synchronous, with interrupt checks, budget tracking, and a one-turn grace call:
+
+```python
+while (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \
+ or self._budget_grace_call:
+ if self._interrupt_requested: break
+ response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)
+ if response.tool_calls:
+ for tc in response.tool_calls:
+ messages.append(tool_result_message(handle_function_call(tc.name, tc.args, task_id)))
+ api_call_count += 1
+ else:
+ return response.content
+```
+
+Each phase of an iteration is its own sibling, so a change to (say) overflow handling touches one
+~600-line file: `turn_preflight*`, `turn_iteration_prep`, `turn_request_assembly`/`turn_api_request`,
+`turn_api_call`, `turn_api_error`, `turn_response_intake`/`turn_response_check`,
+`turn_empty_response`, `turn_tool_round`/`turn_tool_validation`, `turn_overflow`,
+`turn_truncation`, `turn_context_compaction`, `turn_recovery`, `turn_retry_state`,
+`turn_stop_gates`, `turn_liveness`, `turn_usage`, `turn_final_response`, `turn_finalizer`,
+`turn_summary`. Find the phase with `grep -rn "def X" agent/turn_*.py`.
+
+Messages use OpenAI format `{"role": "system|user|assistant|tool", ...}`; reasoning content is stored
+in `assistant_msg["reasoning"]`.
+
+**Agent-level tools** (`todo`, `memory`, ...) are intercepted by `agent/tool_executor.py` through the
+`INLINE_TOOL_EXECUTORS` table in `agent/inline_tool_executors.py` before `handle_function_call()`.
+Adding one: register in that table (no `if name == ...` chain); `tools/todo_tool.py` is the pattern.
+
+## Message-flow invariants (every change is reviewed against these)
+
+- **Prompt caching must not break.** Never alter past context, change toolsets, reload memories,
+ or rebuild the system prompt mid-conversation. The system prompt is byte-stable for the life of
+ a conversation; the ONLY context mutation is compression. Anything that must inject content
+ mid-conversation rides a **user message or tool result**, never the system prompt: skill slash
+ commands (`agent/skill_commands.py`) inject as a user message; subdirectory `AGENTS.md` hints
+ (`agent/subdirectory_hints.py`) append to the tool result (head+tail truncated past `_MAX_HINT_CHARS = 32_000`, with a warning).
+- **Strict role alternation.** Never two same-role messages in a row; never a synthetic user
+ message injected mid-loop. Cron deliveries live in their own session for this reason.
+- **Context files** (`agent/prompt_builder.py`) load from the CWD only at startup and are capped
+ (`CONTEXT_FILE_MAX_CHARS` / dynamic cap from the context window / `context_file_max_chars`).
+ Never load an install-tree `AGENTS.md` as project context (PR #64611); subdirectory hints reject
+ paths outside the working dir so `~/.codex/AGENTS.md` / `~/.claude/CLAUDE.md` never mix in.
+- **`_last_resolved_tool_names` is a process-global in `model_tools.py`.** `_run_single_child()`
+ in `tools/delegate_tool.py` saves/restores it around subagent execution; code reading it may see
+ a temporarily stale value during child runs.
+
+## Compression (`agent/compression_facade.py`, `conversation_compression.py`, `turn_context_compaction.py`)
+
+Two layers: gateway session hygiene (85% threshold) and the agent `ContextCompressor` (50%,
+configurable; per-model overrides; failure cooldown after provider-proven overflow). The algorithm
+prunes old tool results first (no LLM call), then picks boundaries, then generates a structured
+summary with the `auxiliary` compression model. In-place compaction keeps a single stable session
+id; native Responses/Codex compaction paths are provider-specific. Compression is the sanctioned
+cache break — keep it the only one. Full detail:
+`website/docs/developer-guide/context-compression-and-caching.md`.
+
+## Model and provider resolution
+
+- Runtime provider/model resolution and its precedence: `website/docs/developer-guide/provider-runtime.md`.
+ Provider profiles are plugins (`plugins/model-providers/<name>/`, see `plugins/AGENTS.md`);
+ `agent/model_metadata.py` holds context lengths and capabilities.
+- **Auxiliary (side-LLM) work** — curator, vision, embedding, title generation, session_search,
+ compression — resolves through `agent/auxiliary_client.py::_resolve_auto_route`; each task can pin
+ its own `provider/model/base_url/max_tokens/reasoning_effort` under `auxiliary:` in config.yaml.
+- Fallback models and credential pools are resolution-chain code: E2E them with real imports
+ against a temp `HERMES_HOME`, not mocks (root rubric).
+
+## Memory, context engines, curator
+
+`agent/memory_provider.py` (ABC) + `agent/memory_manager.py` (orchestrator) drive memory-provider
+plugins; `agent/context_engine.py` drives context-engine plugins; `agent/image_gen_provider.py`
+image-gen plugins (all in `plugins/AGENTS.md`). `agent/curator.py` + `curator_backup.py` implement
+the skill curator (`skills/AGENTS.md`). Cron sessions pass `skip_memory=True` by default — memory
+providers intentionally do not run during cron.
+
+## Tests
+
+Loop/phase tests go in `tests/agent/`; patch the binding the phase actually reads (siblings often
+`from run_agent import X` inside the function — root "patch where production reads"). Assert
+message-shape invariants (alternation, byte-stable system prompt) rather than snapshotting prompt
+text.
+
+Long-form: `website/docs/developer-guide/agent-loop.md`, `prompt-assembly.md`,
+`context-compression-and-caching.md`, `provider-runtime.md`, `session-storage.md`,
+`subagent-lifecycle-api.md`.
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index c59d13e8b1c..fb1fc39b5bc 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -3,7 +3,8 @@
How to build Hermes Desktop well. This is a judgment guide, not an inventory —
it teaches the invariants and the reasoning behind them so a change fits the app
even as files move. Read it with the repository `AGENTS.md` (root rules still
-apply) and [`DESIGN.md`](./DESIGN.md) for the visual and interaction contract.
+apply), [`DESIGN.md`](./DESIGN.md) for the visual and interaction contract, and
+`src/AGENTS.md` for the backend contract, slash-palette curation, and Bot Mode.
When a rule here and the code disagree, trust the code and fix whichever is
wrong — but never break an invariant to make a change easier.
diff --git a/apps/desktop/src/AGENTS.md b/apps/desktop/src/AGENTS.md
new file mode 100644
index 00000000000..523c13c0b76
--- /dev/null
+++ b/apps/desktop/src/AGENTS.md
@@ -0,0 +1,83 @@
+# apps/desktop/src/ — backend contract, slash palette, Bot Mode
+
+Applies on top of `apps/desktop/AGENTS.md` (the judgment guide) and the root `AGENTS.md`.
+Root TypeScript style rules apply.
+
+## The desktop is its own chat surface on a `hermes serve` backend
+
+Electron + React + nanostores (`@assistant-ui/react`) talking to a `tui_gateway` backend over
+JSON-RPC (`requestGateway(method, params)`); transport lives in the framework-agnostic `apps/shared`
+(`@hermes/shared`: `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard also consumes.
+The desktop has **no build/runtime dependency on the dashboard frontend**: it spawns a headless
+`hermes serve` (`headless_backend=True` → `cmd_dashboard` skips `_build_web_ui` and exports
+`HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists).
+`dashboard` and `serve` share `cmd_dashboard`/`start_server` but neither launches the other. It does
+NOT embed `hermes --tui` — own composer, transcript, slash pipeline.
+
+**One backward-compat fallback:** `serve` is newer, so the spawn (`electron/backend-command.ts` +
+`backendSupportsServe()` in `electron/main.ts`) checks whether the resolved runtime registers `serve`
+and ONLY when it does not (older managed install / PATH `hermes` not yet updated) rewrites argv to
+legacy `dashboard --no-open`. Without it a new app against an un-upgraded runtime crashes on an
+unknown subcommand and bricks every mid-upgrade user. Keep it narrow and tested.
+
+Lifecycle: `serve` dies with the app by design; the messaging gateway survives it (spawned detached
+via `/api/gateway/*`). Never re-parent the gateway under the backend — `gateway/AGENTS.md`.
+
+## Slash commands: curated client-side, dispatched to the backend
+
+- The backend already provides everything: `commands.catalog` and `complete.slash` include built-ins,
+ user `quick_commands`, AND skill-derived commands. No new RPC is needed to see skills.
+- `src/lib/desktop-slash-commands.ts` is the load-bearing file: `DESKTOP_COMMAND_SPECS` (built-ins
+ and their desktop surfaces) + `NO_DESKTOP_SURFACE` block-lists (terminal-only / messaging-only /
+ picker-owned / settings-owned / advanced). `isDesktopSlashCommand(name)` gates **execution** (true
+ for built-ins AND any non-built-in so typed skill/quick commands run);
+ `isDesktopSlashSuggestion(name)` gates **discovery** — used by BOTH completion paths in
+ `app/chat/composer/hooks/use-slash-completions.ts` and by `filterDesktopCommandsCatalog`;
+ `isDesktopSlashExtensionCommand(name)` is true for anything not a known built-in, and both
+ suggestion and catalog paths let extensions through (the allow-list once silently dropped every
+ skill/quick command from completions even though they executed when typed).
+- Dispatch: `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`) — desktop-owned built-ins
+ (`/skin`, `/help`, `/new`, ...) locally or via `commands.catalog`; everything else `slash.exec` →
+ `command.dispatch` fallback; a skill command resolves to `{type: "skill", message}` and is
+ submitted as a normal prompt.
+
+**Rule:** palette curation hides noise (terminal-only / messaging-only built-ins), NEVER
+user-activated extensions. If you tighten `desktop-slash-commands.ts`, keep
+`isDesktopSlashExtensionCommand` flowing into both paths. Test: from `apps/desktop`,
+`npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace deps install at the repo root).
+
+## Bot Mode (`src/plugins/hermes-bots/`) — one bot = ONE canonical forever-chat, identified by NAME
+
+Each bot is a Hermes **profile** with a persistent identity. This invariant regressed repeatedly,
+cost users conversation history each time, and is not open for re-litigation in a routine PR.
+
+The chat's only identity is **(profile, session titled exactly "Bot Chat")**; the state DB's
+UNIQUE(title) index makes that pair a registry of at most one row. Clicking a bot row:
+1. **Resolve the registry, every time:** `session.list {title, include_hidden: true}` (indexed,
+ window-free; hidden rows resolve because canonical chats are always hidden; compression lineages
+ resolve to the live tip). Row exists → open it. That is the whole happy path.
+2. **No row → create it**, titled `Bot Chat`, born hidden, kicked off with the bot's intro. Creation
+ adopts-before-minting: it re-runs the lookup first so a concurrent/pre-existing row is opened,
+ never forked (`set_session_title` silently drops conflicting titles — returns 0 rows — which is how
+ the 2026-08 infinite fork loop started).
+
+**There is NO session-id pin.** The old design stored a pointer in `ui_meta['hermes-bots'].chat`;
+five hardening waves (#88690, #90732, #90751, the #91791 revert, #92042) each guarded a new way it
+dangled or was stolen (rows[0] steals, `last_session` adoptions, transient clears, a pin re-anchored
+onto a cron session). A name cannot dangle; legacy `chat` keys in ui_meta are ignored and dropped.
+**Recency must never win** (#91791 → #92042): canonical Bot Chats are unconditionally hidden from the
+Sessions sidebar, so the bot row is the ONLY door — "newest visible session wins" walls the whole
+relationship off behind a row that previews one session and opens another. Side-chats ("New chat
+with this agent") are not plumbing-titled, stay visible in the sidebar, and are never the row's target.
+
+Reviewer corollaries: no per-bot session browser (removed in #90732; don't add it back). Reject any
+stored session-id pointer as canonical identity — including "as a fallback tier" or "for
+verification". Reject anything consulting recency/visibility/"where the user left off" for the row's
+target; such reports are about side-chats and the fix belongs in the Sessions sidebar hide-sweep.
+The gateway reports the registry row as `canonical_session` on `profiles.list` (resolved server-side
+by title); roster preview, activity signals, and the `/new`→`/compact` guard all read it, so preview
+identity and click identity are the same row by construction. Contract tests:
+in `src/plugins/hermes-bots/`: `canonical-chat-registry.test.ts` (tripwire: the open path never
+reads/writes a stored pointer), `canonical-chat-creation.test.ts`, `canonical-chat-adopt-on-conflict.test.ts`,
+`bot-row-opens-canonical-chat.test.ts`, `hide-bot-chats.test.ts`; plus repo-root
+`tests/tui_gateway/test_profiles_list_canonical_session.py`.
diff --git a/cron/AGENTS.md b/cron/AGENTS.md
new file mode 100644
index 00000000000..756f1eed0ee
--- /dev/null
+++ b/cron/AGENTS.md
@@ -0,0 +1,61 @@
+# cron/ (+ kanban) — scheduled jobs and the multi-agent work queue
+
+Applies on top of the root `AGENTS.md`. Long-form: `website/docs/developer-guide/cron-internals.md`;
+user docs `website/docs/user-guide/features/cron.md`, `kanban.md`.
+
+## Cron
+
+`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop; `scheduler_*.py` siblings). Agents
+schedule via the `cronjob` tool; users via `hermes cron list|add|edit|pause|resume|run|remove` or
+`/cron`. Schedules: duration (`"30m"`, `"2h"`, `"1d"`), "every" phrase (`"every 2h"`, `"every monday
+9am"`), 5-field cron (`"0 9 * * *"`), ISO one-shot (`"2026-06-01T09:00:00Z"`). Per-job fields:
+`skills`, `model`/`provider` overrides, `script` (pre-run data-collection script whose stdout is
+injected into the prompt; `no_agent=True` makes the script the whole job), `context_from` (chain job
+A's last output into job B's prompt), `workdir` (run with that directory's `AGENTS.md`/`CLAUDE.md`
+loaded), multi-platform delivery.
+
+Hardening invariants — each guards a real failure; don't weaken without answering for it:
+- **3-minute hard interrupt** on cron sessions: runaway loops cannot monopolise the scheduler.
+- Catch-up window = half the period, clamped to 120s–2h; 120s grace for missed one-shots.
+- File lock `~/.hermes/cron/.tick.lock` prevents duplicate ticks across processes.
+- Cron sessions pass `skip_memory=True`; memory providers intentionally do not run during cron.
+- Deliveries are **not mirrored** into the target gateway session — they land in their own cron
+ session with a header/footer frame so the main conversation's role alternation stays intact.
+- The cron ticker runs in the desktop-spawned backend when `HERMES_DESKTOP=1` — that env var means
+ "spawned by the app", not "a GUI is watching" (root: capability is a property of the session).
+- Background `delegate_task` is process-local; work that must survive restarts is a cron job or a
+ `terminal(background=True, notify_on_complete=True)` process.
+
+## Kanban (multi-agent work queue)
+
+Durable SQLite-backed board letting multiple profiles/workers collaborate. Users: `hermes kanban
+<verb>`; dispatcher-spawned workers use a dedicated `kanban_*` toolset so their schema footprint is
+zero outside a kanban task (footprint ladder rung 3).
+
+- **CLI:** `hermes_cli/kanban.py` facade + 14 `kanban_*.py` siblings (`boards`, `db`, `db_connect`,
+ `db_dispatch`, `db_notify`, `workspace`, ...). Verbs: `init, create, list (ls), show, assign, link,
+ unlink, comment, attach, attachments, attach-rm, complete, request-review, request-changes,
+ reopen-review, block, unblock, archive, tail`, plus `watch, stats, runs, log, assignees, heartbeat,
+ notify-*, dispatch, daemon, gc`. Argparse alias dispatch must accept both `list` and `ls` (root).
+- **Toolset:** `tools/kanban_tools.py` — `kanban_show, kanban_complete, kanban_request_review,
+ kanban_request_changes, kanban_block, kanban_heartbeat, kanban_comment, kanban_create, kanban_link,
+ kanban_attach, kanban_attach_url, kanban_attachments`; profiles enabling `kanban` outside a
+ dispatched task also get `kanban_list` and `kanban_unblock` for board routing.
+- **Dispatcher:** long-lived loop (default 60s) that reclaims stale claims, promotes ready tasks,
+ atomically claims, and spawns assigned profiles. Runs **inside the gateway** by default
+ (`kanban.dispatch_in_gateway: true`). Standalone: `plugins/kanban/systemd/hermes-kanban-dispatcher.service`.
+- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) + systemd unit. `kanban_db.connect` is its
+ own connection helper — do not alias it to `projects_db.connect` (a path-proximity generator did).
+
+Isolation: **board** is the hard boundary — workers get `HERMES_KANBAN_BOARD` pinned in their env and
+cannot see other boards; **tenant** is a soft namespace within a board (workspace-path + memory-key
+isolation, one fleet serving several businesses). After `kanban.failure_limit` consecutive
+non-success attempts on a task (default 2) the dispatcher auto-blocks it to stop spin loops.
+Process-identity note: `kanban --preserve-cache` contains "serve" — never classify processes by argv
+substring (root).
+
+## Tests
+
+`tests/cron/`, `tests/hermes_cli/test_kanban*.py`, `tests/tools/test_kanban*.py`. Schedule parsing
+and catch-up windows are pure functions — test them as data. Never assert on the verb list or
+toolset size (root: no change-detectors). Time-based tests use loose bounds (≥ 2s) and event sync.
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
new file mode 100644
index 00000000000..21ee4f3c250
--- /dev/null
+++ b/gateway/AGENTS.md
@@ -0,0 +1,108 @@
+# gateway/ — messaging gateway, adapters, delivery
+
+Applies on top of the root `AGENTS.md`. Long-form: `website/docs/developer-guide/gateway-internals.md`.
+New platform adapter: follow `gateway/platforms/ADDING_A_PLATFORM.md` step by step.
+
+## Shape
+
+`gateway/run.py` is the facade; phases live in `run_*.py` (startup, adapters, inbound, turn, busy,
+goals, notifications, shutdown, ...), sessions in `session*.py`, slash handlers in
+`slash_commands_*.py` mixins, authorization in `authz_mixin.py`, adapters in `platforms/<name>.py`
+over `platforms/base.py`. `builtin_hooks/` is the extension point for always-registered gateway
+hooks (none shipped). The gateway reads user YAML **raw** (`run.py` + `config.py`), not through
+`DEFAULT_CONFIG` — a key the CLI sees but the gateway doesn't means you're on the wrong loader
+(`hermes_cli/AGENTS.md`). Each adapter picks a base toolset (Telegram → `"messaging"`).
+
+Slash commands: handlers are looked up by name through `_command_handler_table`; a command is
+listed in `_IDLE_COMMANDS` or `_PLAIN_COMMANDS` (works mid-run) in `run_busy.py`. No
+`if canonical == ...` chains. Registry + adding a command: `hermes_cli/AGENTS.md`.
+
+## The gateway has TWO message guards — both must bypass approval/control commands
+
+While an agent is running, an inbound message passes two sequential guards: (1) the **base
+adapter** (`platforms/base.py`) queues it in `_pending_messages` when `session_key in
+self._active_sessions`; (2) the **runner** (`run.py`/`run_busy.py`) intercepts `/stop`, `/new`,
+`/queue`, `/status`, `/approve`, `/deny` before they reach `running_agent.interrupt()`. Any new
+command that must reach the runner while the agent is blocked (approval prompts) MUST bypass BOTH
+guards and be dispatched inline — never via `_process_message_background()`, which races session
+lifecycle.
+
+## Streaming delivery contract (stream-is-the-message adapters)
+
+Adapters with `draft_stream_is_message = True` (relay Slack native streaming) keep ONE cumulative
+native stream per turn; the stream IS the final message. Four invariants, each from a live
+duplicate-final incident (NS-658 canary ledger, hermes#85796 / gateway-gateway#210); violating any
+re-creates a duplicate or frozen stream:
+
+1. **Draft frames are prefix-stable.** Frame N must be a string prefix of frame N+1. Never mutate
+ drafts per tick — no fence-closing (`ensure_closed_code_fences`), cursor suffix, segment-state
+ resets at tool boundaries, or mrkdwn conversion. A non-prefix frame forces a whole-snapshot
+ re-append ("stacked copies"). The finalize path may still transform the real final.
+2. **The consumer declares the final; the adapter never guesses.** `finish(final_text)` carries the
+ completed `final_response` (verifier footer, completion explainer included). New post-stream
+ augmentation MUST ride this payload — mutating `final_response` after the seal re-opens the
+ `delivered_final_matches` mismatch → corrective duplicate send.
+3. **Interim sends carry `metadata["_interim_send"] = True`.** Any consumer-side `adapter.send()`
+ that is not the turn-final (commentary, segment-tail flushes) must set it or seal-interception
+ seals the live stream with interim text. Seal-interception exists at BOTH egress doors (`send()`
+ and `send_for_platform()`); a new egress door needs the same two checks.
+4. **Reconcile by edit, never by plain send.** A lane delivering a final beside a sealed stream
+ (queued follow-ups, media-accompanied finals) first tries `edit_message` on the consumer's
+ `message_id`; plain `send()` only when no editable message exists. A sealed native stream is a
+ regular message — `chat.update` works (live-verified).
+
+Contract tests: `tests/gateway/test_stream_final_contract.py` (mutation-checked). Slack ground
+truth: `chat.*Stream` speaks STANDARD markdown, not mrkdwn; `stopStream.markdown_text` APPENDS;
+`startStream`/`stopStream` are Tier 2 (~20/min). Check `draft_stream_is_message is True` —
+MagicMock adapters in older tests auto-create truthy attributes.
+
+## Background process notifications
+
+`terminal(background=true, notify_on_complete=true)` starts a gateway watcher that detects
+completion and triggers a new agent turn. Verbosity: `display.background_process_notifications`
+(or `HERMES_BACKGROUND_NOTIFICATIONS`): `concise` (default; one line, failures append an output
+tail), `all` (running updates + final raw output), `result` (final raw output only), `error`
+(final raw output only on non-zero exit), `off`.
+
+Cron deliveries are NOT mirrored into the target gateway session — they land in their own cron
+session with a header/footer frame so the main conversation's role alternation stays intact
+(`cron/AGENTS.md`).
+
+## Gateway lifecycle vs. the Desktop app
+
+`hermes serve` (control plane, desktop-spawned child) dies with the app — by design. The messaging
+gateway (`gateway run`) SURVIVES the app: the serve backend's `/api/gateway/*` endpoints spawn it
+detached (`_spawn_hermes_action` — `start_new_session` / `DETACHED_PROCESS`), so `before-quit`'s
+SIGTERM never reaches it and bots keep running. The known breach is the Windows shim-unlock
+teardown (`taskkill /T /F` on venv-shim holders, #85265), which exists to let updates proceed and is
+replaced by #92091's `pause-for-update`. Do NOT "fix" gateway-dies-with-app by re-parenting the
+gateway under the backend, and do NOT "fix" update locks by widening the tree-kill. Gateways stamp
+`code_sha`/`code_version` into `gateway_state.json` (`status.py`) so the updater can verify a fleet.
+
+## Profiles and secrets in adapters
+
+- **Token locks.** An adapter that connects with a unique credential (bot token, API key) calls
+ `acquire_scoped_lock()` from `gateway.status` in `connect()`/`start()` and `release_scoped_lock()`
+ in `disconnect()`/`stop()`, so two profiles cannot share one credential. Canonical:
+ `plugins/platforms/irc/adapter.py`.
+- **Multiplex profile-scoped env reads MUST fail closed — never borrow from `os.environ`**
+ (`agent/secret_scope.py`; #72348, #86905). Under `gateway.multiplex_profiles`, `os.environ` holds
+ the DEFAULT profile's values; a secondary profile's `.env` exists only in its secret scope,
+ installed per turn by `_profile_runtime_scope`. All profile-level env config — credentials
+ (`app_secret`, tokens) AND authorization (`FEISHU_ALLOWED_USERS`, `{PLATFORM}_ALLOW_ALL_USERS`,
+ `GATEWAY_ALLOW_ALL_USERS`, `group_policy`, `allow_bots`) — is read scope-aware: adapters via
+ `_get_scoped_secret()` (canonical fail-closed copy: `plugins/platforms/feishu/adapter.py`),
+ gateway authz via `_auth_env()` / `_platform_gate_env()` (`authz_mixin.py`). Scope installed +
+ multiplex active → a scoped miss returns the **default**, NEVER `os.environ` (a leaked allowlist
+ skips the allow-all check and silently rejects every secondary-profile sender, #86905). The
+ unscoped default-profile path (`UnscopedSecretError`) and single-profile deployments keep the
+ `os.environ` read — there it IS the profile's own value. `_get_scoped_secret` is copy-pasted
+ across ~15 adapters: when touching one, verify fail-closed semantics and never reintroduce the
+ `except _UnscopedSecretError: val = os.getenv(...)` fallback-after-miss shape.
+
+## Tests
+
+`tests/gateway/`. Adapter tests exercise the real delivery path with a fake transport; never
+assert on hardcoded platform lists or command counts (root: no change-detectors). Session-key and
+guard behaviour are invariants worth a test; platform API quirks belong in connector comments +
+tests, not in prose.
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md
new file mode 100644
index 00000000000..bdee473f038
--- /dev/null
+++ b/hermes_cli/AGENTS.md
@@ -0,0 +1,123 @@
+# hermes_cli/ + cli.py — CLI, slash commands, config, skins, updater, profiles
+
+Applies on top of the root `AGENTS.md`. Long-form: `website/docs/developer-guide/cli-internals.md`.
+
+## CLI architecture
+
+`cli.py` holds `HermesCLI` (REPL loop, config, slash dispatch); behaviour lives in mixins
+`hermes_cli/cli_commands_mixin.py`, `cli_stream_mixin.py`, `cli_status_bar_mixin.py`,
+`cli_billing_mixin.py`, `cli_tui_mixin.py`, ... **Rich** renders banner/panels; **prompt_toolkit**
+handles input + autocomplete; `KawaiiSpinner` (`agent/display.py`) animates API calls and prints
+the `┊` activity feed. `load_cli_config()` in `cli.py` merges CLI defaults + user YAML.
+`process_command()` resolves the canonical name via `resolve_command()` then dispatches through
+`HermesCLI._SLASH_DISPATCH` (`canonical -> (method name, pass_arg)`), falling back to a
+`_handle_<name>_command` method by naming convention. **There is no `elif` ladder — do not add one.**
+Skill slash commands (`agent/skill_commands.py`) scan `~/.hermes/skills/` and inject as a **user
+message**, never into the system prompt (prompt caching).
+
+Rules: all interactive menu-pickers use curses (`hermes_cli/curses_ui.py`; example
+`hermes_cli/tools_config.py`). Never emit `\033[K` (ANSI erase-to-EOL) in spinner/display code —
+it leaks as literal `?[K` under prompt_toolkit's `patch_stdout`; space-pad instead:
+`f"\r{line}{' ' * pad}"`. Wrapper CLIs extend via the protected hooks in `cli_tui_mixin.py`
+(`website/docs/developer-guide/extending-the-cli.md`), not by overriding `run()`.
+
+## Slash command registry (`hermes_cli/commands.py`)
+
+`COMMAND_REGISTRY` (list of `CommandDef`) is the single source; everything derives from it: CLI
+dispatch (`resolve_command()`), gateway `GATEWAY_KNOWN_COMMANDS` + dispatch, `gateway_help_lines()`,
+`telegram_bot_commands()` (BotCommand menu), `slack_subcommand_map()`, `COMMANDS` (autocomplete),
+`COMMANDS_BY_CATEGORY` (`show_help()`). Fields: `name` (no slash), `description`, `category`
+(`Session | Configuration | Tools & Skills | Info | Exit`), `aliases` tuple, `args_hint`,
+`cli_only`, `gateway_only`, `gateway_config_gate` (config dotpath; a `cli_only` command becomes
+gateway-available when truthy — `GATEWAY_KNOWN_COMMANDS` always includes gated commands so the
+gateway can dispatch them; help/menus show them only when the gate is open).
+
+**Adding a command:** (1) `CommandDef("mycommand", "What it does", "Session", aliases=("mc",),
+args_hint="[arg]")` in `COMMAND_REGISTRY`; (2) `_handle_mycommand_command(self, cmd_original)` on the
+relevant `cli_*_mixin.py` (picked up by convention) or an explicit `_SLASH_DISPATCH` entry
+`"mycommand": ("_handle_mycommand", True)` when the method name/arg-passing differs; (3) for the
+gateway, `_handle_mycommand_command(self, event)` on the matching `gateway/slash_commands_*.py`
+mixin and list it in `_IDLE_COMMANDS` (or `_PLAIN_COMMANDS` if it must work mid-run) in
+`gateway/run_busy.py` — handlers resolve by name via `_command_handler_table`; (4) persistent
+settings via `save_config_value()` in `cli.py`. **Adding an alias** = add to `aliases`; every
+surface updates automatically. Commands that mutate system-prompt state default to deferred
+invalidation with `--now` opt-in (root invariant).
+
+## Config system (`hermes_cli/config.py`)
+
+- **config.yaml option:** add to `DEFAULT_CONFIG`. Bump `_config_version` ONLY to actively
+ migrate/transform existing config (rename keys, restructure); new keys deep-merge automatically.
+ Top-level sections (non-exhaustive): `model, agent, terminal, compression, display, stt, tts,
+ memory, security, delegation, smart_model_routing, checkpoints, auxiliary, curator, skills,
+ gateway, logging, cron, profiles, plugins, honcho`. `auxiliary` = per-task side-LLM overrides
+ (`agent/AGENTS.md`); `curator` = `enabled, interval_hours, min_idle_hours, stale_after_days,
+ archive_after_days, backup.*`.
+- **.env = SECRETS ONLY** (keys, tokens, passwords): add to `OPTIONAL_ENV_VARS` with
+ `{"description", "prompt", "url", "password": True, "category": provider|tool|messaging|setting}`.
+ Non-secret settings go in config.yaml; if internal code needs an env mirror, bridge it in code
+ (`gateway_timeout`; `terminal.cwd` → `TERMINAL_CWD`). `MESSAGING_CWD` is removed and `TERMINAL_CWD`
+ in `.env` is deprecated — the loader warns; canonical is `terminal.cwd`.
+- **Three loaders — know which you're in:** `load_cli_config()` (CLI, `cli.py`); `load_config()`
+ (`hermes tools/setup`, most subcommands, `hermes_cli/config.py`, merges `DEFAULT_CONFIG`); raw
+ YAML (gateway runtime, `gateway/run.py` + `gateway/config.py`). If the CLI sees a key and the
+ gateway doesn't (or vice versa), you're on the wrong loader — check `DEFAULT_CONFIG` coverage.
+- **Working directory:** CLI uses `os.getcwd()`; messaging uses `terminal.cwd`, bridged to
+ `TERMINAL_CWD` for child tools.
+
+## Skin engine (`hermes_cli/skin_engine.py`)
+
+Skins are **pure data** (`SkinConfig`); no code change to add one. `init_skin_from_config()` reads
+`display.skin` at startup; `get_active_skin()` (cached), `set_active_skin(name)` (`/skin`),
+`load_skin(name)` (user `~/.hermes/skins/*.yaml` → built-ins → default; missing values inherit
+from `default`). Built-ins in `_BUILTIN_SKINS`: `default`, `ares`, `mono`, `slate`. Keys: `colors.*`
+(banner border/title/accent/dim/text, response_border), `spinner.*` (waiting/thinking faces,
+thinking_verbs, wings), `tool_prefix`, `tool_emojis`, `branding.*` (agent_name, welcome,
+response_label, prompt_symbol). Consumers: `banner.py`, `display.py`, `cli.py`. Key-by-key table
+and YAML template: `website/docs/user-guide/features/skins.md`.
+
+## Update pipeline (`hermes update`) — transactional; every stage guards a real field failure
+
+Fleet-update campaign #91277 (Aug 2026). A PR that weakens a stage must answer for the failure class
+it guards. `plan → snapshot → apply → restart-per-kind → verify → report`
+
+- **Plan** (`update_inventory.py`, `hermes update --plan`): read-only inventory — install kind, all
+ profiles, every live gateway with supervisor + running code version. Deployment kinds are
+ first-class: `git` updates in place; `docker`/`nix`/`apt` are NOT in-place-updatable and the
+ updater reports the correct external command instead of fighting the deployment model.
+- **Snapshot** (`backup.py`): pre-update quick snapshot for EVERY profile (the code swap + fleet
+ restart touch all of them), each into its own `state-snapshots/`, identical file set, 1 GiB
+ per-file cap, keep=1. **Never add a partial/tiered snapshot set** — mixed coverage creates
+ torn-restore states across schema generations. Quick snapshots are FILE-LOSS RECOVERY (the
+ per-profile cron-jobs safety net restores from them), NOT code-rollback insurance; `--backup`
+ full mode owns rollback.
+- **Apply**: git pull, or the Windows ZIP fallback — which fires ONLY when git itself failed
+ (`_should_zip_fallback_on_update_error`, argv-classified; a dependency-install failure must never
+ trigger a tree-clobbering re-download), REFUSES a dirty working tree (`-uall` + a pre-swap TOCTOU
+ re-check), and grafts the live `apps/desktop/release/` into the staged swap (the GitHub source
+ ZIP has no built desktop app; without the graft the swap deletes it).
+- **Restart-per-kind**: systemd and launchd restarts are FLEET-WIDE (every `hermes-gateway*` unit /
+ `ai.hermes.gateway*` LaunchAgent), drain-first (SIGUSR1), with per-unit/per-label failure
+ isolation. Restarting only the invoking profile's service leaves siblings on stale `sys.modules`
+ until they crash — the largest dupe-PR cluster in the repo's history came from that bug.
+- **Verify**: gateways stamp `code_sha`/`code_version` into `gateway_state.json` on every
+ runtime-status write (`gateway/status.py`); the updater compares each live gateway against the
+ fresh checkout and prints a fleet version matrix. A provably-stale gateway fails the update
+ (exit 1) — automation must never treat a mixed-version fleet as healthy.
+- **Report**: every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/`
+ (`latest.json` pointer; steps, skips WITH reasons, restart outcome, plan, fleet snapshot).
+ Finalization is owned by the `cmd_update` command boundary — early `sys.exit` paths (preflight
+ refusals, fetch failures) still persist a receipt with the real exit code. A begun-but-unwritten
+ receipt is a bug: refused/failed runs are the ones receipts exist for.
+
+Process-scan coordination between updater, serve/dashboard, and gateway is being replaced by a
+gateway-owned control socket (#92091); scans are the fallback layer for old/crashed processes — read
+#92091 before adding any heuristic. Process identity rules (never argv substrings; canonical
+matchers; parser-derived flag sets; never blanket-exclude gateway ancestors, #87594): root
+`AGENTS.md` and `website/docs/developer-guide/cli-internals.md`.
+
+## Profiles (multi-instance)
+
+`_apply_profile_override()` in `hermes_cli/main.py` sets `HERMES_HOME` before any module import, so
+every `get_hermes_home()` scopes to the active profile (rules in root). Profiles are independent
+islands by design — no live config inheritance; `--clone` copies at creation. Multiplex
+(`gateway.multiplex_profiles`) secret-scope rules: `gateway/AGENTS.md`.
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md
new file mode 100644
index 00000000000..5c85946d3b7
--- /dev/null
+++ b/plugins/AGENTS.md
@@ -0,0 +1,86 @@
+# plugins/ — plugin kinds, compat contract, in-tree policy
+
+Applies on top of the root `AGENTS.md`. Authoring guide + canonical compat contract:
+`website/docs/developer-guide/plugins/index.md`. Per-kind guides: `memory-provider-plugin.md`,
+`model-provider-plugin.md`, `context-engine-plugin.md`, `image-gen-provider-plugin.md`, ...
+
+## Plugins never touch core (Teknium, May 2026)
+
+Plugins live in their own directory and work within the ABCs / hooks / `ctx` surface we provide.
+A plugin MUST NOT modify `run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.
+If it needs a capability the framework lacks, widen the **generic** plugin surface (new hook, new
+ctx method) and have the plugin use it — never hardcode plugin-specific logic into core (PR #5295
+removed 95 lines of hardcoded honcho argparse from `main.py`). Plugin setup goes through
+`hermes memory setup` → `provider.post_setup(hermes_home, config)`, never a parallel top-level
+command. A hook with no concrete consumer is speculative infrastructure and is rejected (root).
+
+## What may live in this tree (policy)
+
+- **No new in-tree memory providers (May 2026).** `plugins/memory/` is closed (honcho, mem0,
+ supermemory, byterover, hindsight, holographic, openviking, retaindb stay; bug fixes welcome). New
+ backends ship as standalone repos implementing the same `MemoryProvider` ABC, discovered through
+ the same path, integrated via `hermes memory setup` / `post_setup()`.
+- **No new third-party-product plugins (June 2026).** Observability/metrics backends, vendor SaaS
+ connectors, analytics dashboards, paid-service tie-ins ship as standalone plugin repos
+ (`~/.hermes/plugins/` or pip entry point) promoted in Discord `#plugins-skills-and-skins`. Reason:
+ every absorbed product is our maintenance burden against a fast-moving core for a backend we don't
+ own. `observability/`, `kanban/`, `disk-cleanup/` are precedent, not an invitation. Closing such a
+ PR is a coupling decision, not a quality judgment.
+- Reference/docs-companion plugins (`example-dashboard`, `strike-freedom-cockpit`,
+ `plugin-llm-example`, `plugin-llm-async-example`) live in
+ [`hermes-example-plugins`](https://github.com/NousResearch/hermes-example-plugins), not here.
+
+## Plugin kinds and their discovery systems
+
+| Kind | Where | Discovery | Notes |
+|---|---|---|---|
+| General | `plugins/<name>/`, `~/.hermes/plugins/`, `./.hermes/plugins/`, pip entry points | `PluginManager` (`hermes_cli/plugins.py`), later-wins | `register(ctx)` registers hooks (`pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`, `on_session_start`, `on_session_end`), tools (`ctx.register_tool`), CLI subcommands (`ctx.register_cli_command` — argparse tree wired into `hermes` at startup, no `main.py` change) |
+| Memory provider | `plugins/memory/<name>/` | `plugins/memory/__init__.py`: bundled → `$HERMES_HOME/plugins/` → `./.hermes/plugins/` (opt-in `HERMES_ENABLE_PROJECT_PLUGINS`) → `hermes_agent.memory_providers` entry points; **bundled-first** | Activated by name via `memory.provider`, so a dropped-in dir must not shadow a shipped one (reverse of general later-wins). Enumerates without importing. Implements `MemoryProvider` ABC (`agent/memory_provider.py`), orchestrated by `agent/memory_manager.py`: `sync_turn`, `prefetch`, `shutdown`, optional `post_setup`. `cli.py` with `register_cli(subparser)` is wired by `discover_plugin_cli_commands()` — only for the ACTIVE provider, so `hermes --help` stays clean |
+| Model provider | `plugins/model-providers/<name>/` | `providers/__init__.py._discover_providers()`, **lazy**, on first `get_provider_profile()`/`list_providers()`; bundled → `$HERMES_HOME/plugins/model-providers/` → legacy `providers/<name>.py` | `__init__.py` calls `providers.register_provider(ProviderProfile(...))` at load; **last-writer-wins** so a user plugin overrides a bundled profile. `PluginManager` records `kind: model-provider` manifests but does NOT import them (would double-instantiate); manifests without `kind:` are auto-coerced by source heuristic (`register_provider` + `ProviderProfile`) |
+| Context engine / image-gen / others | `plugins/context_engine/`, `plugins/image_gen/`, ... | ABC + orchestrator + per-plugin directory | Plug into `agent/context_engine.py`, `agent/image_gen_provider.py` |
+| Platform adapters | `plugins/platforms/<name>/adapter.py` | gateway | Token-lock and scoped-secret rules in `gateway/AGENTS.md` (`irc`, `feishu` are canonical) |
+
+**Discovery timing pitfall:** `discover_plugins()` runs only as a side effect of importing
+`model_tools.py`. Code that reads plugin state without importing `model_tools.py` first must call
+`discover_plugins()` explicitly (idempotent). Hooks are invoked from `model_tools.py` (pre/post
+tool) and `run_agent.py` (lifecycle). When a plugin changes a default, add a migration guard keyed
+on an "existing config" signal (`_explicitly_configured`) so existing users keep the old default.
+
+## Native plugin compatibility contract (summary — canonical text in the docs page)
+
+Compatibility is a **behavior contract**, not a monolithic `PLUGIN_API_VERSION`, a manifest-wide
+native `api:` match, or version literals on unrelated payloads. Documented surfaces stay additive:
+
+- Hook payload data is added as **keyword fields**; callbacks are signature-inspected so old narrow
+ signatures receive only the fields they declare and `**kwargs` callbacks get the full payload.
+- Never remove or rename `PluginContext` methods; new parameters are optional with defaults and
+ keyword-only where possible.
+- Unknown native manifest fields are ignored.
+- New provider methods get default implementations; optional callback kwargs are
+ signature-inspected, not forwarded unconditionally.
+- A local schema version exists only for a capability with a wire or persisted contract, and old
+ state/config/session replay is preserved or migrated.
+- Deprecations: once-per-process warning, documented replacement + migration note, ≥ 2 subsequent
+ minor releases before removal.
+- Compat tests load **frozen plugins through the real discovery path** and assert outcomes — never
+ exact registry/catalog counts, source-reading tests, or "a global version literal changed".
+
+## Sep 2026 decomposition compat window (ends 2026-09-14)
+
+PR #102117 moved internals into `<stem>_<topic>` siblings. Old import paths resolve through
+`PLUGIN-COMPAT` `__getattr__` blocks (listed in `COMPAT_MANIFEST.md` / `compat_manifest.json`)
+until `hermes_cli.plugin_compat.COMPAT_REMOVAL_DATE`, when the commit that added them is reverted.
+`hermes_cli/plugin_compat.py` is the single source: `scan_plugin` (AST scan), `compat_report`
+(hits across enabled external plugins, cached to `HERMES_HOME/.plugin-compat-report.json`,
+refreshed by discovery), `removal_in_effect`, `warn_once`. Surfaces: CLI banner notice,
+`hermes plugins compat` (shows affected user plugins), `hermes doctor`, post-update notices, the
+TUI/Desktop `plugins.compat_report` RPC. After the date `PluginManager` skips a hitting plugin
+unless `plugins.allow_deprecated_imports: true`. **In-tree code and tests never use compat paths**
+(`scripts/check_compat_pointers.py` in CI; `-W error::hermes_cli.plugin_compat.HermesPluginCompatWarning`).
+External-plugin compat is handled ONCE here — never add per-PR re-export shims.
+
+## Tests
+
+`tests/plugins/`. Load through real discovery with a temp `HERMES_HOME`; assert behaviour (tool
+registered, hook fired with expected kwargs), not counts. Opt-in telemetry rule applies to plugins
+too: no attribution tag ships by default (`tests/plugins/memory/test_hindsight_provider.py`).
diff --git a/skills/AGENTS.md b/skills/AGENTS.md
new file mode 100644
index 00000000000..27e47db7b60
--- /dev/null
+++ b/skills/AGENTS.md
@@ -0,0 +1,75 @@
+# skills/ + optional-skills/ — bundled skills, authoring standards, curator
+
+Applies on top of the root `AGENTS.md`. Long-form: `website/docs/developer-guide/creating-skills.md`;
+user docs: `website/docs/user-guide/features/skills.md`, `curator.md`.
+
+## Two surfaces
+
+- **`skills/`** — built-in, loadable by default, organised by category (`skills/github/`, `skills/mlops/`).
+- **`optional-skills/`** — heavier/niche skills shipped but NOT active; installed via
+ `hermes skills install official/<category>/<skill>` (adapter `tools/skills_hub_official.py`
+ `OptionalSkillSource`). Categories: `autonomous-ai-agents, blockchain, communication, creative,
+ devops, email, health, mcp, migration, mlops, productivity, research, security, web-development`.
+
+Reviewing a skill PR: check the target directory — heavy-dep or niche skills go to `optional-skills/`.
+
+## SKILL.md frontmatter
+
+`name`, `description`, `version`, `author`, `license`, `platforms` (OS gate: `[macos]`,
+`[linux, macos]`, ...), `metadata.hermes.tags`, `metadata.hermes.category`,
+`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml settings the skill needs —
+stored under `skills.config.<key>`, prompted during setup, injected at load). Top-level `tags:` /
+`category:` are accepted and mirrored from `metadata.hermes.*` by the loader.
+
+## Authoring standards (HARDLINE — enforced by `tests/skills/test_authoring_standards.py`)
+
+Every new or modernised skill — bundled, optional, or contributed — meets all of these before merge:
+
+1. **`description` ≤ 60 chars, one sentence, ends with a period.** Long descriptions bloat listings
+ and dilute attention when many skills load. State the capability, not the implementation; no
+ marketing words ("powerful", "comprehensive", "seamless", "advanced"); don't repeat the name.
+ Check: `len(re.search(r'^description: (.*)$', text, re.M).group(1)) <= 60`.
+2. **Prose references native Hermes tools or the MCP servers the skill expects, in backticks**
+ (`terminal`, `web_extract`, `read_file`, `patch`, `search_files`, `vision_analyze`,
+ `browser_navigate`, `delegate_task`). Never name shell utilities the agent has wrapped: `grep` →
+ `search_files`, `cat`/`head`/`tail` → `read_file`, `sed`/`awk` → `patch`, `find`/`ls` →
+ `search_files target='files'`. MCP dependencies are named with setup in `## Prerequisites`.
+ Third-party CLIs and pipelines are fine inside script files, not as the headline surface.
+3. **`platforms:` gating is audited against actual script imports.** POSIX-only primitives
+ (`fcntl`, `termios`, `os.setsid`, `os.kill(pid, 0)`, `/proc`, hardcoded `/tmp`, `signal.SIGKILL`,
+ bash heredocs, `osascript`, `apt`, `systemctl`) require a platform declaration. Fix cross-platform
+ first (`tempfile.gettempdir`, `pathlib.Path`, `psutil.pid_exists`, Python filtering instead of
+ `grep`); gate narrower only when the dependency is genuinely platform-bound.
+4. **`author` credits the human first.** External contributor's real name + GitHub handle first,
+ "Hermes Agent" second. A commit authored as "Hermes Agent" (they drafted with Hermes) is replaced
+ with the human's name — credit the human, not the tool.
+5. **Modern section order:** `# <Skill> Skill`, 2–3 sentence intro (what it does and doesn't),
+ `## When to Use`, `## Prerequisites`, `## How to Run`, `## Quick Reference`, `## Procedure`,
+ `## Pitfalls`, `## Verification`. ~200 lines for a complex skill, ~100 simple. Cut intro fluff,
+ marketing prose, and env-var re-explanations already in Prerequisites.
+6. **`scripts/`, `references/`, `templates/`.** Don't make the model inline-write parsers or
+ non-trivial logic every call — ship a helper script and reference it by skill-relative path.
+7. **Tests at `tests/skills/test_<skill>_skill.py`**, stdlib + pytest + `unittest.mock` only, no
+ live network. Run `scripts/run_tests.sh tests/skills/test_<skill>_skill.py -q`.
+8. **`.env.example` additions sit in a clearly delimited block.** Contributor copies of the file are
+ usually stale; edits outside the skill's own block are dropped during salvage.
+
+No `offset`/`limit` pagination on skill-loading tools — the agent must read a skill fully (root).
+The salvage/modernisation checklist for external skill PRs is `references/new-skill-pr-salvage.md`
+in the `hermes-agent-dev` skill.
+
+## Curator (skill lifecycle)
+
+Background maintenance that tracks usage on agent-created skills and auto-archives stale ones;
+archives go to `~/.hermes/skills/.archive/` and are restorable. Core `agent/curator.py` (review
+loop, auto-transitions, LLM review prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots);
+CLI `hermes_cli/curator.py` → `hermes curator status|run|pause|resume|pin|unpin|archive|restore|
+prune|backup|rollback`; telemetry `tools/skill_usage.py` owns `~/.hermes/skills/.usage.json`
+(`use_count`, `view_count`, `patch_count`, `last_activity_at`, `state` active/stale/archived,
+`pinned`). Config `curator:` — `enabled, interval_hours, min_idle_hours, stale_after_days,
+archive_after_days, backup.*`; its LLM calls route through `auxiliary` (`agent/AGENTS.md`).
+
+Invariants: touches only `created_by: "agent"` skills (bundled + hub-installed are off-limits);
+never deletes — archive is the maximum; pinned skills are exempt from every auto-transition and
+the LLM review; `skill_manage(action="delete")` refuses pinned skills while patch/edit/write_file/
+remove_file still work so the agent can keep improving them.
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
new file mode 100644
index 00000000000..7e6526a72a8
--- /dev/null
+++ b/tools/AGENTS.md
@@ -0,0 +1,96 @@
+# tools/ + toolsets.py + model_tools.py — model tools
+
+Applies on top of the root `AGENTS.md`: settle the **Footprint Ladder** before adding anything here.
+Most capabilities should NOT be core tools. Long-form: `website/docs/developer-guide/adding-tools.md`,
+`tools-runtime.md`.
+
+## Registry and discovery
+
+`tools/registry.py` has no deps and is imported by every tool file; each `tools/*.py` calls
+`registry.register()` at import time; `model_tools.py` imports the registry and triggers discovery
+(`discover_builtin_tools()`), then `run_agent.py`, `cli.py`, `batch_runner.py`, `environments/`
+consume it. Any `tools/*.py` with a top-level `registry.register()` is imported automatically — no
+manual import list. The registry handles schema collection, dispatch (`handle_function_call()`),
+availability (`check_fn`, TTL-cached process-wide), and error wrapping. **All handlers return a JSON
+string.**
+
+## Adding a core tool (2 files) — only when the user is explicitly contributing a core tool
+
+For custom/local-only tools do NOT edit core: create `~/.hermes/plugins/<name>/plugin.yaml` +
+`__init__.py` and call `ctx.register_tool(...)`; plugin toolsets are discovered automatically and
+toggled without touching `tools/` or `toolsets.py` (`plugins/AGENTS.md`).
+
+1. `tools/your_tool.py`:
+ ```python
+ from tools.registry import registry
+ def check_requirements() -> bool: return bool(os.getenv("EXAMPLE_API_KEY"))
+ def example_tool(param: str, task_id: str = None) -> str: return json.dumps({"success": True, ...})
+ registry.register(name="example_tool", toolset="example",
+ schema={"name": "example_tool", "description": "...", "parameters": {...}},
+ handler=lambda args, **kw: example_tool(param=args.get("param", ""), task_id=kw.get("task_id")),
+ check_fn=check_requirements, requires_env=["EXAMPLE_API_KEY"])
+ ```
+2. `toolsets.py`: add the name to `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **Required**
+ — discovery registers the schema, but a tool is only exposed if a toolset names it.
+ `_HERMES_CORE_TOOLS` is the default bundle every platform's base toolset inherits, not dead code.
+
+Rules for tool code:
+- **Schema descriptions must not name tools from other toolsets** (`browser_navigate` saying "prefer
+ web_search"). Those tools may be unavailable (missing key, disabled toolset) and the model
+ hallucinates calls to them. Cross-references are added dynamically in `get_tool_definitions()` in
+ `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks.
+- **Paths in schema descriptions use `display_hermes_home()`** (schema is built at import, after
+ `_apply_profile_override()` set `HERMES_HOME`). **State files use `get_hermes_home()`**, never
+ `Path.home()/.hermes`, so each profile gets its own state.
+- **No `offset`/`limit` on instructional tools** (skills, prompts, playbooks) — models read page 1
+ and skip the rest (root rubric).
+- **`check_fn` answers reachability/opt-in, never surface.** It is TTL-cached process-wide, and one
+ process serves many sessions; GUI-only tools go in a named toolset (`desktop_ui`, `project`)
+ folded in by `_load_enabled_toolsets(platform)` (root: capability is a property of the SESSION).
+- **Agent-level tools** (`todo`, `memory`) are intercepted before `handle_function_call()` via the
+ `INLINE_TOOL_EXECUTORS` table (`agent/inline_tool_executors.py`; `agent/AGENTS.md`).
+- **`_last_resolved_tool_names`** is a process-global in `model_tools.py`; `_run_single_child()` in
+ `delegate_tool.py` saves/restores it around child runs — readers may see it stale mid-delegation.
+- New tools integrate with existing setup UX (`hermes tools`, `hermes setup`, auto-install) rather
+ than a raw env var; secrets go in `OPTIONAL_ENV_VARS` (`hermes_cli/AGENTS.md`).
+
+## Toolsets (`toolsets.py`)
+
+Single `TOOLSETS` dict. Keys today: `browser, clarify, code_execution, cronjob, debugging,
+delegation, discord, discord_admin, feishu_doc, feishu_drive, file, homeassistant, image_gen,
+kanban, memory, messaging, moa, rl, safe, search, session_search, skills, spotify, terminal, todo,
+tts, video, vision, web, yuanbao` (don't assert the list in tests). Per-platform enable/disable via
+`hermes tools` (curses) or `tools.<platform>.enabled/disabled` in config.yaml. `browser_exec`
+replaces the other browser tools when `browser.backend` is `browser-use`.
+
+## Backends and providers inside tools/
+
+Several tools front pluggable backends: terminal environments in `tools/environments/` (local,
+docker, ssh, modal, daytona, singularity; `terminal_tool_backends.py`, `tool_backend_helpers.py`),
+browser (`browser_tool_*.py`: cdp, cloud, install, lifecycle, session, real_profile, vision), MCP
+client (`mcp_tool_*.py`: config, discovery, transport, registration, content, errors), TTS
+(`tts_tool_providers.py`, `tts_command_provider.py`), skills hub sources (`skills_hub_official.py`
+`OptionalSkillSource`). Adding a backend = a new sibling or provider entry in the existing table,
+never an `elif` on a backend name (root shape rules). Remote-backend file visibility problems are
+fixed at the mount, not by adding a tool.
+
+## Delegation (`tools/delegate_tool.py`)
+
+Spawns a subagent with isolated context + terminal session; the parent waits for the summary unless
+`background=true`, which returns a delegation id and re-enters the result via the async-delegation
+completion queue. Shapes: single (`goal` + optional `context`, `toolsets`) or batch (`tasks: [...]`,
+concurrency capped by `delegation.max_concurrent_children`, default 3). Roles: `leaf` (default;
+no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execute_code`) and
+`orchestrator` (keeps `delegate_task`; gated by `delegation.orchestrator_enabled`, bounded by
+`delegation.max_spawn_depth`, default 2). Config knobs under `delegation:`:
+`max_concurrent_children, max_spawn_depth, child_timeout_seconds, orchestrator_enabled,
+subagent_auto_approve, inherit_mcp_toolsets, max_iterations`. **Durability:** background
+delegation is process-local; work that must survive restart uses `cronjob` or
+`terminal(background=True, notify_on_complete=True)`. API: `website/docs/developer-guide/subagent-lifecycle-api.md`.
+
+## Tests
+
+`tests/tools/`. Test the handler through the registry (real dispatch), not the bare function only;
+assert contracts ("every registered tool has a toolset", "no schema description names a tool from
+another toolset") rather than tool counts. Approval/security-boundary tools are E2E'd with real
+imports against a temp `HERMES_HOME` (see `tests/tools/test_approval_config_readonly.py`).
diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md
new file mode 100644
index 00000000000..fe62d4df5e5
--- /dev/null
+++ b/tui_gateway/AGENTS.md
@@ -0,0 +1,74 @@
+# tui_gateway/ + ui-tui/ — the TUI and its JSON-RPC backend
+
+Applies on top of the root `AGENTS.md`. The TUI fully replaces the classic prompt_toolkit CLI;
+activate with `hermes --tui` or `HERMES_TUI=1`. `tui_gateway` is ALSO the backend the Desktop app
+and the dashboard `/chat` talk to — changes here have three consumers.
+
+## Process model
+
+```
+hermes --tui
+ └─ Node (Ink) ──stdio JSON-RPC── Python (tui_gateway)
+ │ └─ AIAgent + tools + sessions
+ └─ renders transcript, composer, prompts, activity
+```
+
+TypeScript owns the screen. Python owns sessions, tools, model calls, and slash-command logic.
+Never move agent behaviour into the renderer.
+
+## Transport
+
+Newline-delimited JSON-RPC over stdio: requests from Ink, events from Python. `tui_gateway/server.py`
+is the facade with the method/event catalog; methods live in `methods_*.py` siblings (`methods_config`,
+`methods_complete`, `methods_browser`, `methods_bot_relay`, ...), event publishing in
+`event_publisher.py` / `event_replay.py`. Desktop reaches the same server over WebSocket via
+`apps/shared` (`JsonRpcGatewayClient`). New RPC = a new `methods_<topic>.py` or an entry in an
+existing topical sibling, registered in the table — no `if method == ...` chain (root shape rules).
+
+## Key surfaces
+
+| Surface | Ink component | Gateway method / event |
+|---|---|---|
+| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta` / `message.complete` |
+| Tool activity | `thinking.tsx` | `tool.start` / `tool.progress` / `tool.complete` |
+| Approvals | `prompts.tsx` | `approval.request` → `approval.respond` |
+| Clarify / sudo / secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify.respond`, `sudo.respond`, `secret.respond` |
+| Session picker | `sessionPicker.tsx` | `session.list` / `session.resume` |
+| Slash commands | local handler + fallthrough | `slash.exec` → `_SlashWorker`; `command.dispatch` |
+| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |
+| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` carries skin data |
+| Plugin compat notice | — | `plugins.compat_report` (see `plugins/AGENTS.md`) |
+
+## Slash command flow
+
+1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, ...) are
+ handled locally in `app.tsx`.
+2. Everything else → `slash.exec`, which runs in the persistent `_SlashWorker` subprocess →
+ `command.dispatch` fallback, which the gateway resolves into a skill / alias / exec directive
+ (a skill command resolves to `{type: "skill", message}` and is submitted as a normal prompt).
+
+`commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) already include
+built-ins, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` /
+`get_skill_commands()`) — clients do not need a new RPC to see skills. The command definitions
+themselves come from `hermes_cli/commands.py` (`hermes_cli/AGENTS.md`).
+
+## Dev commands
+
+```bash
+cd ui-tui
+npm install # first time
+npm run dev # watch mode (rebuilds hermes-ink + tsx --watch)
+npm start # production
+npm run build # full build (hermes-ink + tsc)
+npm run typecheck # tsc --noEmit
+npm run lint # eslint
+npm run fmt # prettier
+npm test # vitest
+```
+
+Python tests: `tests/tui_gateway/` via `scripts/run_tests.sh`. TS tests: vitest in `ui-tui`. A
+Python test that asserts about `package.json` / `.ts` sources will not run on a JS-only PR — keep
+JS-side assertions in vitest (root testing rules). Root TypeScript style rules apply.
+
+Related: `web/AGENTS.md` (dashboard embeds this TUI over a PTY), `apps/desktop/AGENTS.md` (own
+renderer on the same backend).
diff --git a/web/AGENTS.md b/web/AGENTS.md
new file mode 100644
index 00000000000..265fb75cd9a
--- /dev/null
+++ b/web/AGENTS.md
@@ -0,0 +1,45 @@
+# web/ + hermes_cli/web_routers/ — the dashboard (`hermes dashboard` → `/chat`)
+
+Applies on top of the root `AGENTS.md`. Backend routers: `hermes_cli/web_routers/*.py`, one file per
+dashboard surface, mounted by `hermes_cli/web_server.py` (+ `web_server_*.py` siblings). Frontend:
+`web/src/`. Shared JSON-RPC/WS client: `apps/shared` (`@hermes/shared`), also used by the desktop.
+
+## The dashboard embeds the REAL `hermes --tui` — not a rewrite
+
+`hermes_cli/pty_bridge.py` + the `@app.websocket("/api/pty")` endpoint in `web_server.py`:
+
+- `web/src/pages/ChatPage.tsx` mounts xterm.js `Terminal` with the WebGL renderer, `@xterm/addon-fit`
+ (container-driven resize) and `@xterm/addon-unicode11` (wide-character widths).
+- `/api/pty?token=…` upgrades to a WebSocket; auth uses the same ephemeral `_SESSION_TOKEN` as REST,
+ passed as a query param because browsers cannot set `Authorization` on a WS upgrade.
+- The server spawns exactly what `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL
+ works, native Windows does not).
+- Frames are raw PTY bytes each way; resize travels as `\x1b[RESIZE:<cols>;<rows>]`, intercepted
+ on the server and applied with `TIOCSWINSZ`.
+
+**Do not re-implement the primary chat experience in React.** Transcript, composer/input flow
+(including slash-command behaviour), and the PTY-backed terminal belong to the embedded TUI; anything
+added to Ink shows up here automatically. If you are rebuilding the transcript or composer for the
+dashboard, stop and extend Ink (`tui_gateway/AGENTS.md`).
+
+**Structured React UI around the TUI is fine when it is not a second chat surface.** Sidebar
+widgets, inspectors, summaries, status panels (`ChatSidebar`, `ModelPickerDialog`, `ToolCall`)
+complement the embedded TUI. Keep their state independent of the PTY child's session and surface
+their failures non-destructively so the terminal pane keeps working.
+
+## `dashboard` vs `serve`
+
+`dashboard` and `serve` share `cmd_dashboard` / `start_server` but are independent surfaces — neither
+launches the other. `serve` is the headless backend the desktop app spawns (`headless_backend=True`:
+`cmd_dashboard` skips `_build_web_ui` and exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()`
+disables the SPA even if a stray `web_dist/` exists — only JSON-RPC/WS/API is reachable). The
+desktop has no build/runtime dependency on this frontend. Details: `apps/desktop/src/AGENTS.md`.
+
+## Rules
+
+- Auth: every new REST route and WS endpoint uses the same session token; never a second scheme.
+- Routers are one-file-per-surface; a new surface is a new `web_routers/<surface>.py`, not a growing
+ `web_server.py`.
+- Tests: Python in `tests/hermes_cli/` (routers, pty bridge); JS in the `web/` vitest suite. Python
+ tests must not assert about `package.json` / `.tsx` sources (root testing rules). Root TypeScript
+ style rules apply.
diff --git a/website/docs/developer-guide/cli-internals.md b/website/docs/developer-guide/cli-internals.md
new file mode 100644
index 00000000000..8742ad36230
--- /dev/null
+++ b/website/docs/developer-guide/cli-internals.md
@@ -0,0 +1,63 @@
+---
+sidebar_position: 15
+title: "CLI Internals"
+description: "How hermes_cli is shaped: slash dispatch, config loaders, the skin engine, the transactional update pipeline, and process-identity rules"
+---
+
+# CLI Internals
+
+Companion to `hermes_cli/AGENTS.md` (the rules) — this page holds the longer explanations.
+
+## Update pipeline
+
+The stage-by-stage contract (`plan → snapshot → apply → restart-per-kind → verify → report`) and the
+field failure each stage guards are documented in `hermes_cli/AGENTS.md`; user-facing behaviour
+(receipts, `--plan`, snapshot modes) is in [Updating](../getting-started/updating.md).
+
+## Process identity: never infer it from argv substrings
+
+The bug class behind ~10 fleet-update issues (#90778, #87594, #78089, #76129, #91964, ...):
+classifying a process by `"serve" in cmdline` or similar. `kanban --preserve-cache` contains
+"serve"; a flag VALUE can equal a subcommand (`-m dashboard serve`); truncated cmdlines hide the real
+subcommand. Rules:
+
+- Use the canonical matchers: `gateway.status.looks_like_gateway_command_line` (gateway run),
+ `hermes_cli.update_cmd._hermes_holder_subcommand` (top-level subcommand of any Hermes argv). Never
+ hand-roll token scans.
+- Flag sets must be DERIVED from the parser (`_holder_value_flags()` introspects
+ `build_top_level_parser()`), never hand-written lists — they drift.
+- Never blanket-exclude ancestors from process scans: when `/update` runs as the gateway's child, a
+ gateway ancestor must stay visible to the pause machinery (#87594). Exclude interactive ancestry,
+ carve out gateway-shaped ancestors.
+- Match on FULL cmdlines; truncate only at display time (#78089).
+- Before adding any new scan heuristic, read #92091 — the gateway control socket replaces scans as
+ the primary coordination mechanism; scans are the fallback layer for old/crashed processes.
+
+## Skin engine — what skins customize
+
+| Element | Skin key | Used by |
+|---|---|---|
+| Banner panel border / title / section headers / dim / body | `colors.banner_border`, `banner_title`, `banner_accent`, `banner_dim`, `banner_text` | `banner.py` |
+| Response box border | `colors.response_border` | `cli.py` |
+| Spinner faces (waiting / thinking) | `spinner.waiting_faces`, `spinner.thinking_faces` | `display.py` |
+| Spinner verbs / wings (optional) | `spinner.thinking_verbs`, `spinner.wings` | `display.py` |
+| Tool output prefix / per-tool emojis | `tool_prefix`, `tool_emojis` | `display.py` → `get_tool_emoji()` |
+| Agent name / welcome / response label / prompt symbol | `branding.agent_name`, `welcome`, `response_label`, `prompt_symbol` | `banner.py`, `cli.py` |
+
+Built-in skins (`_BUILTIN_SKINS` in `hermes_cli/skin_engine.py`): `default` (classic gold/kawaii),
+`ares` (crimson/bronze with custom spinner wings), `mono` (grayscale), `slate` (cool blue). Add a
+built-in as a dict entry `{"name", "description", "colors", "spinner", "branding", "tool_prefix"}`.
+User skins are `~/.hermes/skins/<name>.yaml` with the same keys, activated with `/skin <name>` or
+`display.skin: <name>`; the full YAML template is in the
+[Skins & Themes](../user-guide/features/skins.md) user guide.
+
+## Profiles: multi-instance support
+
+Hermes supports profiles — fully isolated instances, each with its own `HERMES_HOME` (config, API
+keys, memory, sessions, skills, gateway). `_apply_profile_override()` in `hermes_cli/main.py` sets
+`HERMES_HOME` before any module imports, so every `get_hermes_home()` reference scopes to the active
+profile. Profile operations are HOME-anchored (`_get_profiles_root()` returns
+`Path.home() / ".hermes" / "profiles"`, not `get_hermes_home() / "profiles"`) so
+`hermes -p coder profile list` sees all profiles regardless of which one is active — intentional.
+Profile-safe coding rules are in the root `AGENTS.md`; multiplex secret-scope rules in
+`gateway/AGENTS.md`.