[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75895QQ3G3BCF9R2BZ5FBNS":3,"skill-same:01M75895QQ3G3BCF9R2BZ5FBNS":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M75895QQ3G3BCF9R2BZ5FBNS","hermes-gateway-operations",null,"Diagnose, configure, and maintain Hermes messaging gateway platforms (Telegram, Discord, WhatsApp, etc.). Covers connectivity troubleshooting, secret\u002Ftoken setup, gateway state inspection, and common failure patterns.","lukemcqueen\u002Fsteadfaste-fleet","lukemcqueen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F405240?v=4","01M757MHPAGRXTJAT46SKZP98R","Luke McQueen","01M757MHPZ573KP8DT9GB8SBQ7",4,"MIT","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fhermes-gateway-operations\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: hermes-gateway-operations\nversion: 1.0.0\ndescription: >-\n  Diagnose, configure, and maintain Hermes messaging gateway platforms\n  (Telegram, Discord, WhatsApp, etc.). Covers connectivity troubleshooting,\n  secret\u002Ftoken setup, gateway state inspection, and common failure patterns.\n---\n\n# Hermes Gateway Operations\n\nDiagnostic and maintenance procedures for the Hermes messaging gateway.\n\n## When to load\n\n- User reports \"messages not sending\" on any platform\n- Gateway is disconnected or repeatedly reconnecting\n- Need to set up a new platform (Telegram bot token, Discord token, etc.)\n- Debugging `.env` configuration for gateway platforms\n\n## Diagnostic Path (Telegram example)\n\nAlways follow this sequence — each step feeds the next:\n\n```\n1. gateway_state.json    → platform state (\"disconnected\" \u002F \"connected\")\n2. gateway.log           → error message (\"No bot token configured\")\n3. .env                  → check TELEGRAM_BOT_TOKEN exists\n4. config.yaml           → check platform_plugins and telegram\n```\n\n### Step 1 — Inspect gateway state\n\n```bash\ncat ~\u002F.hermes\u002Fstate\u002Fgateway_state.json 2>\u002Fdev\u002Fnull\n# {\"platforms\": {\"telegram\": {\"status\": \"connected\", \"last_seen\": \"...\"}}}\n```\n\n`\"disconnected\"` + a `last_seen` far in the past = the platform dropped and\nisn't reconnecting. `\"connected\"` but messages not arriving = delivery-side\nproblem (see Step 5).\n\n### Step 2 — Read the gateway log\n\n```bash\ntail -50 ~\u002F.hermes\u002Flogs\u002Fgateway.log\n```\n\nTypical failure lines:\n- `No bot token configured for platform telegram` → token missing\n- `401 Unauthorized from Telegram API` → token wrong\u002Frevoked\n- `Connection reset by peer` → transient network; check reconnect behavior\n\n### Step 3 — Verify the token\n\n```bash\n# Does the var exist?\ngrep -c \"TELEGRAM_BOT_TOKEN\" ~\u002F.hermes\u002F.env\n\n# Is it set in the environment?\nprintenv TELEGRAM_BOT_TOKEN >\u002Fdev\u002Fnull && echo \"set\" || echo \"UNSET\"\n\n# Is the token VALID? (never print it)\ncurl -s \"https:\u002F\u002Fapi.telegram.org\u002Fbot$(cat ~\u002F.hermes\u002F.env | grep TELEGRAM_BOT_TOKEN | cut -d= -f2)\u002FgetMe\" | head -c 200\n```\n\n> **Never print secrets.** Read tokens via `$(cat \u003Cfile>)` or `grep | cut`\n> inside the command — never pass them as literal strings.\n\n### Step 4 — Check config.yaml\n\n```bash\ngrep -A5 \"telegram:\" ~\u002F.hermes\u002Fconfig.yaml\n```\n\nConfirm the platform is enabled in `platform_plugins` and no stale config\n(e.g. old bot name, wrong chat ID).\n\n### Step 5 — Delivery-side check (connected but nothing arrives)\n\nIf the gateway is connected but messages don't reach the user:\n- Confirm the destination chat ID is correct\n- Check `deliver` targets on the failing cron\u002Fjob\n- Verify the platform session didn't expire (re-auth if needed)\n\n## Restarting to load new code — and verifying it actually happened\n\nThe gateway **holds the MCP servers it spawned**, so new governance\u002Fenforcer code\nis not loaded until the gateway restarts. Two independent failure modes:\n\n> **What this coupling IS — and what it is NOT.** The half that forces a gateway\n> restart for a code change is the in-process ENFORCEMENT\u002FPLUGIN layer\n> (governance-enforcer plugin, the loop-gov\u002F`review` MCP, mycortex-*). It is NOT the\n> messaging transport: the poll→dispatch→reply loop is already decoupled to the\n> standalone `fleet-gateway.service`, so a `hermes gateway restart` is never about\n> messaging. When asked \"why must we still restart the hermes gateway?\", point at the\n> plugin\u002FMCP layer and the deploy≠load mechanism, never at the already-standalone\n> messaging.\n\n1. **Restarting from inside the gateway is blocked by design — and the block matches the COMMAND,\n   so deferring it is not an escape.** A restart issued from inside a Hermes session (a tool call) is\n   refused because the gateway would SIGTERM the command before it completed. Wrapping it to run\n   later (`systemd-run --on-active`, `nohup … &`, `at`) is refused as well: the guard inspects the\n   command and the script it references, not merely the timing, and attempting the workaround IS the\n   violation. Restart from a **separate shell**, or hand the operator the gateway's own `\u002Frestart`\n   command — which exits with the code its supervisor relaunches on, so the service comes back by\n   design and announces itself. Name which one you are asking for, and hand it over once; do not\n   loop-retry.\n2. **A restart can report success and still not land.** Verify; do not assume:\n\n```bash\nsystemctl --user show hermes-gateway.service -p MainPID -p ExecMainStartTimestamp -p NRestarts\n```\n\n`MainPID` and `ExecMainStartTimestamp` **must change**. Observed failure: an\nattempt that left both unchanged at the previous start time — the unit never\nre-activated, so the MCP child still held pre-change code while everything\n*looked* restarted.\n\nThen confirm WHAT THE CHILD LOADED — by content, not by a timestamp:\n\n```bash\npython3 - \u003C\u003C'EOF'\nimport hashlib, json, pathlib\nstamp = pathlib.Path.home() \u002F \".steadfaste-fleet\" \u002F \"state\" \u002F \"loop-gov-daemon.json\"\nmod = pathlib.Path.home() \u002F \".steadfaste-fleet\" \u002F \"tools\" \u002F \"loop-governance\" \u002F \"loop-gov-mcp.py\"\nrec = json.loads(stamp.read_text())            # written by the daemon itself at startup\nnow = hashlib.sha256(mod.read_bytes()).hexdigest()\nprint(\"daemon loaded:\", rec[\"sha256\"][:12], \"pid\", rec[\"pid\"])\nprint(\"on disk now :\", now[:12])\nprint(\"CURRENT\" if rec[\"sha256\"] == now else \"STALE — the loaded code differs from the file\")\nEOF\n```\n\n> **Portability — do NOT check this with `date -r \u003Cpath>`.** That is GNU syntax; on macOS (BSD)\n> `date -r` takes SECONDS since the epoch, so the same command silently means something else\n> instead of failing loudly. macOS also has no `sha256sum` (it ships `shasum -a 256`), which is\n> why the snippet hashes in Python rather than shelling out. `ps -o lstart=` is portable when you\n> only want the start time.\n\nAn older child start is a HINT that the old code is live — but mtime alone cannot settle it: the\nrestart command's own machinery (a dogfood\u002Fdoctor pass) RE-DEPLOYS, and a deploy rewrites files\nwhose bytes did not change, so the mtime moves while a current process reads as stale. Settle it by\nCONTENT — a startup hash stamp the process writes, or a witness only the new revision can produce —\nand never chase the resulting warning with another restart. Rule and mechanism:\n`deploy-load-verification`.\n\nNote: a config value in `~\u002Fsteadfaste-fleet\u002F.env` does **not** need a restart once\nthe gate's own resolver is deployed (it re-reads per call); only the code does.\n\n### A restart that preserves sessions is INVISIBLE — announce it, and tell the agent\n\nThe only message about a restart is sent by the process that then exits; nothing\nfollows it. So a human in the chat cannot tell the restart happened, and the agent\ncannot tell them either: sessions survive a gateway restart (starting fresh is\n`\u002Fnew`), so an agent asked \"did you restart?\" answers from its own memory —\n\"no, I still have our context\" — which is true of the SESSION, false about the\ngateway, and the only answer available. Three things fix that, and the third is\nthe one usually missed:\n\n1. **The restart command's reply states what happens to the CONVERSATION.**\n   \"restart\" reads like \"fresh start\"; a session that carries over otherwise looks\n   like nothing happened.\n2. **The NEW process announces itself at startup, before it serves anything**, in the\n   operator's wording, verbatim: `♻ Gateway restarted successfully. Your session\n   continues.` Keep that phrasing — it answers both questions a restart raises (did it\n   work, did I lose the conversation) in one line, and a longer invented variant is not\n   what the operator wants here. Persist a per-chat marker BEFORE sending the restart\n   reply — the process that writes the marker is the one that exits, so in-memory state\n   cannot carry it. Consume the marker on the first turn, so the human is told once and\n   not on every later reply. If the startup send fails, LEAVE the marker and let the\n   first reply carry the confirmation: a transient send failure must not lose the news.\n3. **Hand the AGENT the same fact on its first prompt after the restart** (a\n   `[system]` note prepended to the turn). Announcing to the human alone leaves the\n   agent still answering \"no\" — the contradiction the human will notice.\n\nProve a restart with the unit, not with the chat:\n\n```bash\nsystemctl --user show \u003Cunit>.service -p NRestarts -p MainPID -p ExecMainStartTimestamp\n```\n\nA NEW `MainPID` plus start timestamp is the proof. `NRestarts` increments only for a\n**policy** restart (`Restart=` firing) — an operator-issued `systemctl restart` does\nnot increment it, so a changing `NRestarts` is evidence the unit restarted ITSELF.\n\n- **`Restart=always` is required for restart-on-clean-exit**, the pattern where a\n  service asks systemd to bring it back by exiting on purpose: `Restart=on-failure`\n  does NOT start the unit again after `exit(0)`, so the exit is a plain stop and the\n  bot stays down. Check the policy before trusting the mechanism.\n- **The exit code is the SUPERVISOR's, never a constant — derive it, and refuse when\n  nothing would bring the process back.** systemd (`Restart=always`) relaunches on any\n  exit, so `os._exit(0)` is right; a launchd job whose plist says `SuccessfulExit=false`\n  is relaunched only after a NON-zero exit, so the same handler must exit `75`\n  (EX_TEMPFAIL) on macOS or it PARKS the service silently. Prove who owns the process\n  first — `launchctl list`'s PID column showing OUR pid is the test, because\n  `XPC_SERVICE_NAME` is inherited by children exactly as systemd's `INVOCATION_ID` is —\n  then read the job's own plist for the relaunch condition and exit with the code it\n  wants. When no recognised condition covers a deliberate exit, refuse and name the\n  plist fix instead of exiting into silence. Conditions and the full exit-code table:\n  `macos-service-management`.\n- **Probing this with a throwaway unit: end the probe with\n  `systemctl --user stop \u003Cunit>` and exit 0.** Under `Restart=always`, a probe that\n  exits non-zero restarts itself in a loop — it floods the journal and, if it also\n  touches live state, does so repeatedly. Confirm the unit is gone afterwards\n  (`systemctl --user list-units --all | grep \u003Cname>`).\n\n## A non-Hermes backend is a SEPARATE runtime, not a Hermes session\n\nA backend of `kind: command` (a CLI coding agent) is a distinct process with its\nown tooling: it inherits **none** of a Hermes session's memory, skills, or\ngovernance. \"Agent X has no memory\" is therefore a property of that backend's\nOWN integration layer, never of the host — establish where its memory comes from\nbefore touching anything shared:\n\n| Backend | Memory comes from |\n|---|---|\n| Hermes session | the `mycortex-mem` memory-provider plugin, in-process |\n| command\u002FCLI agent | its own MCP server or extension, spawned by the agent CLI |\n\n`hermes mcp list` does not list plugin-provided stores, so its absence proves\nnothing about a Hermes session; a CLI agent's tools appear in ITS agent config\n(its own `mcp.json`\u002Fsettings), not in `config.yaml`.\n\n### One service-hosted agent reports a store unreachable, a sibling works\n\nCompare the two SERVING UNITS' sandbox flags before blaming the store —\nhardening is invisible in the agent's own output, and the store's availability\ncheck often swallows the real exception:\n\n```bash\nsystemctl --user show \u003Cfailing>.service -p NoNewPrivileges -p PrivateTmp\nsystemctl --user show \u003Cworking>.service -p NoNewPrivileges -p PrivateTmp\n```\n\n`NoNewPrivileges=true` refuses `sg`\u002F`newgrp` setgid **even when the process\nalready holds the target group**, which breaks any store whose only access path\nis `sg docker -c \"docker exec …\"`. Reproduce faithfully with\n`setpriv --no-new-privs -- \u003Ccmd>` — it keeps the real supplementary groups,\nwhereas `systemd-run` drops them and fails for the wrong reason. Fix by giving\nthe store a direct `docker exec` path when the group is already held; never by\ndropping the hardening flag. Mechanism and store-specific fix: `psql-automation`.\n\n### Slash commands are the GATEWAY's, never the agent's\n\nWhen a `kind: command` backend (a CLI coding agent) serves a chat, the built-in slash\ncommands belong to the GATEWAY: such a backend handles `\u002Fnew`, `\u002Fmodel`, `\u002Fcompact`,\n`\u002Frestart` only in its interactive\u002FRPC surface, so forwarded as prompt prose they become\nordinary conversation — a `\u002Fnew` is answered politely while every bit of context stays.\nIntercept them in the gateway's command dispatcher and never pass them through\n(backend mechanics: `pi-coding-agent`).\n\n- **Each command needs a defined contract, not just a route.** `\u002Fnew` starts a fresh\n  session; `\u002Fmodel` persists the override per chat — a stateless prompt wrapper has\n  nowhere to keep it, so the GATEWAY owns a small chat→model store, mode 0600 (a chat id\n  is personal data); `\u002Fcompact` reports what it reclaimed, and \"nothing to compact\" for a\n  session too small; `\u002Frestart` exits WITH THE CODE ITS SUPERVISOR RELAUNCHES ON (`0`\n  under `Restart=always`, `75` under launchd's `SuccessfulExit=false`) so the service\n  comes back by design, and the new process announces itself (above). A refusal must name\n  the half that is missing — \"not running under systemd\" is a dead end on a host that IS\n  supervised, by launchd.\n- **Design for the EMPTY chat.** Commands run on chats with no conversation yet, where a\n  backend's session operations hang or refuse (compact on a transcript that does not exist\n  never answers). Probe state first and answer with the specific condition — \"this chat has\n  no conversation yet\" — never a generic failure.\n- **A control timeout must cover a real turn plus the operation.** Compacting a large\n  session measured ~1m46s; a 30s deadline reports a healthy backend as broken.\n- **Test parity with a STUB transport and an echoing backend** (`\u002Fbin\u002Fecho` so the reply\n  body IS the argv). A probe that polls with the real bot token starts a second poller and\n  steals the live channel's messages (409); echoing is what lets the assertion check the\n  ARGV the gateway produced — model declared exactly once, no duplicate `--model`.\n\n### Inline menus (buttons) for gateway commands\n\nA slash command that picks a VALUE (a model, a voice, a page) is better served by a menu than a\nfree-text argument — but build it on the gateway's plumbing, not beside it:\n\n- **Read the transport before building the UI.** The button markup, edit-in-place and callback\n  routing may already exist. Feature-detect each and degrade to the text form when a platform\n  lacks it, rather than erroring — the command stays usable without buttons.\n- **Carry an INDEX in the callback, never the value.** `callback_data` is capped (64 bytes on\n  Telegram) while a real id runs 40+; re-render the menu from CURRENT state on every press, so a\n  stale button can only ever be out of range. Answer it — never apply a value the menu did not\n  show.\n- **Tick the value IN FORCE, not just an override** — the backend default is what most chats are\n  running, so ticking only overrides leaves every menu unticked; offer the reset entry only when\n  an override exists.\n- **Edit in place** — one message per menu, not one per press — and ANSWER every callback so the\n  client's spinner clears. Consume your own callbacks so a press never reaches the backend as\n  prompt prose.\n- **The list is gateway-owned config.** A backend's raw catalogue is hundreds of entries and a\n  menu of hundreds is worse than a command: curate it in the gateway config so the operator can\n  edit it. Warn on stderr for unusable entries (\"N blank entries ignored (M usable)\") instead of\n  silently serving a shorter menu.\n- **Enabling the menu is PER-HOST work — ship a deployable enabler, not a procedure.** The\n  list lives in each host's own gateway config, so every host needs a config step and a\n  restart before its menu appears. Make that a script (portable: stdlib only, no YAML\n  dependency, since the gateway reads its config with `json.loads`) that derives the list from\n  that host's own backend catalogue, MERGES only the list key — every other key preserved,\n  idempotent — and offers a `--check` sweep. Then REGISTER it in the deploy map: a helper meant\n  for every host that is not registered exists only in the repo, and tests that load it by repo\n  path stay green while hosts never receive it. Give \"cannot derive the list here\" its own exit\n  code rather than reporting an empty catalogue, and read the written config back to confirm\n  the other keys survived (a shape mismatch between the producer and the writer silently\n  writes an empty list and reports success).\n- **Warn when the backend cannot TAKE the value at all.** A shim-style backend declares no\n  value flag, so a selection is stored and never applied: the menu looks live and does nothing.\n  At startup, check whether any backend declares the placeholder that consumes the selection\n  and say so on stderr instead of serving a dead menu — the host's operator cannot otherwise\n  tell a working menu from a decorative one.\n- **Test the menu through the stub transport**: a callback arrives as its own KIND with the data\n  in the body. Assert the first page, the tick, a page step, a stale out-of-range press, and that\n  a chat with no configured list still gets the text form.\n\nConcrete shapes — paths, the callback envelope, callback-data encoding, and the test cases:\n`references\u002Finline-menus.md`.\n\n## Adding a New Platform\n\n1. Obtain the token\u002Fsecret for the platform (Telegram bot token from\n   @BotFather, Discord bot token, etc.)\n2. Add to `~\u002F.hermes\u002F.env` (never commit the file)\n3. Enable in `config.yaml` → `platform_plugins`\n4. Restart the gateway\n5. Verify `gateway_state.json` shows `\"connected\"` and send a test message\n\n## Enabling the decoupled fleet-gateway (a CLI-agent backend)\n\nThe repo ships a standalone `fleet-gateway` unit (`docs\u002Ftemplates\u002Ffleet-gateway.service`)\nthat answers a messaging bot with a pluggable backend, including a `kind: command` CLI\ncoding agent (pi, Codex, Claude Code). It is deliberately INDEPENDENT of\n`hermes-gateway.service` — own unit, own config, no `After=`\u002F`Wants=` on the incumbent.\nEnablement is a concrete sequence; books\u002Fdetail: `pi-coding-agent`, `steadfaste-fleet`.\n\n1. **Config**: copy `ops\u002Fscripts\u002Fgateway.yaml.example` (or `gateway-pi.example.yaml` for a\n   CLI backend) to `~\u002F.steadfaste-fleet\u002Fgateway.yaml` — OUTSIDE the repo. A CLI backend entry\n   is `kind: command` with an ABSOLUTE launcher path: `command` is an argv list, so `~`\u002F`$HOME`\n   are NOT expanded and the launcher is often a symlink into a dir not on a service PATH — a\n   relative or guessed path is a silent per-message no-op.\n2. **Env** in the fleet env (`~\u002Fsteadfaste-fleet\u002F.env`): the bot's `token_ref` var,\n   `TELEGRAM_ALLOWED_USERS` (sender allowlist — REQUIRED; without it any Telegram user reaches\n   a bot that RUNS CODE), `TELEGRAM_HOME_CHANNEL`, `GATEWAY_SECRET` (HMAC; the daemon refuses to\n   start without it), `TELEGRAM_API_BASE` (the transport fails CLOSED without it — the standard\n   value is `https:\u002F\u002Fapi.telegram.org`; a missing base would otherwise build `\u002Fbot\u003Ctoken>\u002Fmethod`),\n   plus the bus URL\u002Fauth.\n3. **Unit**: copy the template into `~\u002F.config\u002Fsystemd\u002Fuser\u002F`, `daemon-reload`, `enable --now`.\n4. **Provider key** for the CLI backend via the `!command` pattern pointing at\n   `env-value.sh \u003CVAR>` — it supplies exactly the one var, so the agent never inherits the whole\n   env file.\n\nPitfalls that cost a cycle here:\n\n- **One poller per bot token — Telegram 409.** The unit's `ExecStartPre` guard\n  (`guard_distinct_token.py`) REFUSES a config whose `token_ref` IS (or resolves to) the live\n  `TELEGRAM_BOT_TOKEN`. Give the second gateway its OWN bot and its OWN token var\n  (e.g. `MOSESPI_BOT_TOKEN`); two pollers on one token drop the live channel. This is the guard\n  working, not a bug to bypass.\n- **The unit's `ExecStart` interpreter must actually have the deps.** The template defaults to\n  `\u002Fusr\u002Fbin\u002Fpython3`; the fleet deps live in the fleet venv `~\u002F.steadfaste-fleet\u002Fvenv\u002Fbin\u002Fpython3`.\n  Point BOTH `ExecStartPre` and `ExecStart` at the venv python, and when a dep is missing install\n  it INTO that venv (age-gated) rather than routing around it — a bot-lock\n  `ImportError: psycopg package required` is the daemon's Postgres bus dependency surfacing, not a\n  bad config; and a unit that crash-loops with that traceback is otherwise indistinguishable from\n  a broken install.\n- **`~\u002F.hermes\u002Fconfig.yaml` is Hermes-owned and the patch\u002Fwrite tools REFUSE it** (\"Agent cannot\n  modify security-sensitive configuration\"). Edit it only through the CLI: `hermes mcp add \u003Cname>\n  --command … --args …` \u002F `hermes mcp remove \u003Cname>`, or `hermes config`. The `add` flow prompts\n  `Enable all N tools?` and CANCELS with no TTY — pipe `printf 'y\\n' |` to accept. Read back with\n  `hermes mcp list`. A doctor FAIL naming an MCP server that is present under a different key is a\n  NAME drift (the fleet-canonical name is what the doctor expects, e.g. `agent-bus` and not a\n  legacy alias) — add the canonical key and remove the legacy one, one server for the script.\n\n## Diagnosing a CLI-agent gateway that answers NOTHING (\"bot stopped working\")\n\nWhen a `kind: command` gateway (pi\u002FCodex\u002Fetc.) goes silent, the probe sequence is\nconfig → env → backend-direct → backend-through-gateway-code → inbound peek. Each\nstep either finds the break or rules it out; stop at the first red.\n\n1. **Config** — the live `~\u002F.steadfaste-fleet\u002Fgateway.yaml` (OUTSIDE the repo): backend\n   argv (ABSOLUTE paths), `stream`, `model`, `reply_mode`. Compare against the repo\n   examples; verify the model pi can resolve.\n2. **Daemon env** — the unit's `EnvironmentFile` is `~\u002Fsteadfaste-fleet\u002F.env`; confirm the\n   daemon PROCESS actually has the provider key it passes to the child\n   (`tr '\\0' '\\n' \u003C \u002Fproc\u002F\u003Cpid>\u002Fenviron | grep -E 'OPENROUTER|TELEGRAM'`).\n3. **Backend direct** — run the exact argv the gateway builds (`\u003Cpi> --session-id\n   \u003Cid> --model \u003Cmodel> \"\u003Cprompt>\"`) with stdout\u002Fstderr separated; a green here proves\n   the agent + model + key.\n4. **Backend through the gateway's code** — `build_gateway(cfg)` then\n   `backend.dispatch(envelope, sink=...)` with a VALID envelope. This is where the probe\n   pitfalls below bite.\n5. **Inbound peek** — raw `getUpdates?offset=\u003Cpersisted>` returns only NEWER updates\n   WITHOUT consuming them (the offset advances only when you pass a higher one):\n   0 pending = nothing stuck in Telegram's queue for the bot.\n6. **Journal + unit** — `journalctl --user -u fleet-gateway.service`, `systemctl\n   --user show \u003Cunit> -p Restart -p NRestarts`, and kernel\u002Fdmesg OOM for the death cause.\n7. **Backend session transcripts — the record of whether a turn RAN.** The CLI\n   agent's own session files (pi: `~\u002F.pi\u002Fagent\u002Fsessions\u002F--home-moses--\u002F*hc-pi-\u003Cchat>.jsonl` —\n   timestamp-prefixed) are appended only when dispatch actually invoked the agent;\n   their mtimes distinguish \"message consumed, agent answered\" from \"message never\n   arrived\". Pair with the offset peek: 0 pending updates + no session-file advance\n   since the restart = no real inbound reached the bot — the pipeline is healthy,\n   nothing was lost. Your own dispatch probes create\u002Fadvance these files, so\n   discount sessions named for your probe's `--session-id` when dating real turns.\n\nReading the evidence you get: **a healthy poller's journal is nearly SILENT**\n(errors and restart announces only — no per-turn logging), so silence proves\nnothing is broken, and the negative evidence carries the diagnosis. What each\nprobe positively proves: the restart announce reaching the chat = outbound path;\ndispatch-through-gateway-code returning a reply envelope = backend + model + key;\nupdate-offset peek = inbound queue state.\n\nProbe pitfalls (each reads as a REAL defect and is a false lead):\n\n- **The probe's getUpdates 409 is YOUR OWN probe, and the daemon logs it as \"poll\n  conflict\".** Calling `get_updates` against the live bot's token collides with the\n  daemon's long-poll; the COLLISION appears in the daemon's journal as `poll conflict\n  1\u002F3: another consumer owns this bot` — which reads exactly like a rival poller. A\n  single conflict whose timestamp matches your probe time is self-inflicted; the daemon\n  backs off 4s and recovers. Count the conflicts and check WHEN they landed before\n  hunting a second poller.\n- **A synthetic envelope needs a VALID UUID `msg_id`.** `env.validate` rejects a\n  non-UUID silently and dispatch returns `None` — which reads as \"the agent produced\n  nothing\" (0 sink calls, clean None). The test files warn about exactly this\n  (\"a synthetic `m` is rejected silently\"). Use a real `uuid4()`.\n- **The probe process env ≠ the daemon's env.** `_child_env` = the CALLER's `os.environ`\n  + spec overrides; if the probe lacks `OPENROUTER_API_KEY` (it lives in the unit's\n  `~\u002Fsteadfaste-fleet\u002F.env`, not the shell's), pi runs without the key, prints nothing to\n  stdout, exits 0, and dispatch returns a clean \"nothing to say\". Load the unit's env\n  file into the probe (`os.environ.setdefault` per line) OR source it, and confirm the\n  key is present before believing a negative.\n- **The pairing banner \"0 approved chat(s)\" is cosmetic when the user is in\n  `TELEGRAM_ALLOWED_USERS`.** `_sender_allowed` = env allowlist ∪ pairing store; pairing\n  only gates UNKNOWN senders. An empty `paired_chats.json` next to a configured\n  allowlist is not the bug — the owner passes on the env half.\n\nSilent death forensics — a unit that auto-restarted without a `Stopping` line:\n\n- `Restart=always` + no Stopping + no restart in `journalctl -u` = the process was\n  KILLED from outside (SIGKILL\u002FSIGTERM), not stopped by systemd. Correlate the death\n  time with nearby SSH\u002F`logind` sessions — an operator's own kill is the common case.\n- `systemctl --user show \u003Cunit> -p MemoryMax` reading `infinity` rules out cgroup OOM;\n  the memory PEAK includes the child agent (pi) in the same cgroup, so a big peak is\n  not a daemon leak on its own.\n\n## A gateway that serves the default profile ONLY — duplicate credential across profiles\n\n`gateway.multiplex_profiles` unset means ON, but not unconditionally: at every boot\nthe default gateway runs the same preflight as `hermes gateway migrate --multiplex`\nand multiplexes only when the fold would be safe. A **duplicate bot credential\nbetween two profiles is a hard blocker** — so the gateway comes up serving the\ndefault profile only, parks the other profile's adapter, and says so loudly (a\nboxed warning at start; the same text in the `hermes update` summary, in\n`hermes gateway status`, and in the dashboard's `\u002Fapi\u002Fstatus` as\n`multiplex_standalone_reason`). Log form:\n\n```\nhermes_cli.gateway_multiplex_mode: gateway.multiplex_profiles is unset (default: on)\nbut this gateway stays standalone: Profiles 'default' and 'personal' both configure\n\u003Cplatform> with the same credential ... It serves the default profile only\n```\n\nOne token is one poller, so nothing is written on a refusal and neither a restart\nnor `--force` clears it. Diagnose with counts only — never print a token:\n\n```bash\nls ~\u002F.hermes\u002Fprofiles\u002F                                     # default profile IS ~\u002F.hermes\nls -la ~\u002F.hermes\u002F.env ~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F.env       # size\u002Fmtime, no content\ngrep -c TELEGRAM_BOT_TOKEN ~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F.env  # count, never the value\n```\n\nBefore acting, decide whether the OTHER profile is real or vestigial — a profile\nthat never served a turn still blocks the fold (structural survey:\n`hermes-home-cleanup`). Then pick one fix:\n\n- **delete it** — `hermes profile delete -y \u003Cname>`. Ask the owner first: it prints the\n  skill count it destroys and leaves a `.deleted\u002F` tombstone. Prove nothing is lost\n  BEFORE deleting — a name-only diff of both `.env` files plus a hash of the shared var\n  (exact commands: `hermes-home-cleanup`) — because a strict subset with an identical\n  hash means no backup copy of the credential is needed, and making one only spreads it.\n- **keep the profile, strip just that platform's var** from its `.env` — smallest change.\n- **give it its own bot** and route its chats from the default profile's\n  `config.yaml` (`gateway.profile_routes`).\n\nThen `hermes gateway migrate --multiplex`. **Expect it to be a NO-OP once the duplicate is\ngone, and never read its rc=0 as \"the state is fixed\":** with one profile left it prints\n\"Only one profile exists: nothing to multiplex\" and does NOT restart, so the boot-time\n`multiplex_standalone_reason` in `gateway_state.json` keeps naming the deleted profile and\nthe dashboard keeps showing it. A restart is what re-runs the preflight:\n`systemctl --user restart hermes-gateway.service`, then verify it LANDED (`MainPID` AND\n`ExecMainStartTimestamp` both change) and read the post-state — the reason becomes\n`only one profile exists (nothing to multiplex)`, `hermes profile list` stops printing the\nwarning, and the boot log reads `Cron scheduler will tick N profile(s)` with the stale\nprofile absent. Before restarting from inside a session, check your own ancestry: a CLI\nsession (`sshd → shell → hermes`) survives it, a session hosted BY the gateway does not\n(`ps -o pid=,cmd= --ppid \u003Cgateway-pid>`).\n\n- **Never identify the active profile by listing `profiles\u002F*\u002F`.** Resolve\n  `HERMES_PROFILE` → `AGENT_NAME` (never hostname). A directory under `profiles\u002F`\n  is a second Hermes HOME, not a routing entry, and the alphabetically-first entry\n  is not the active one — every fleet script carries that warning because it bites.\n- **A profile is not \"unused\" because it is small.** Its `.env` alone is enough to\n  block the whole host's multiplexing; the blocker outlives any single session.\n\n## Common Failure Patterns\n\n| Symptom | Root cause | Fix |\n|---------|-----------|-----|\n| `No bot token configured` | Token missing from .env | Add token, restart gateway |\n| `401 Unauthorized` | Token revoked or wrong | Generate new token, update .env |\n| Repeated reconnecting | Network \u002F API instability | Check outbound connectivity; verify with `curl` |\n| Connected but no delivery | Wrong chat ID \u002F deliver target | Verify destination chat ID and `deliver` config |\n| Gateway up, platform down | Platform-side outage | Wait + monitor; check platform status page |\n| Serves default only; boxed \"stays standalone\" warning naming two profiles | Two profiles configure the same platform credential | Strip the credential from the redundant profile (or delete it), then `hermes gateway migrate --multiplex` |\n\n## Verification\n\n```bash\n# End-to-end test after any fix: send a test message to the home channel\n# via a cron or direct invocation, then confirm it arrived.\n```\n\n## Related\n- `hermes-agent` — general Hermes configuration\n- `telegram-delivery-diagnostics` — Telegram-specific delivery debugging\n- `fleet-bus` — inter-agent messaging (separate from the user gateway)\n- `psql-automation` — the `sg`\u002F`NoNewPrivileges` store-access mechanism behind a\n  \"store unreachable\" report from a hardened service\n","# Hermes Gateway Operations\n\nDiagnostic and maintenance procedures for the Hermes messaging gateway.\n\n## When to load\n\n- User reports \"messages not sending\" on any platform\n- Gateway is disconnected or repeatedly reconnecting\n- Need to set up a new platform (Telegram bot token, Discord token, etc.)\n- Debugging `.env` configuration for gateway platforms\n\n## Diagnostic Path (Telegram example)\n\nAlways follow this sequence — each step feeds the next:\n\n```\n1. gateway_state.json    → platform state (\"disconnected\" \u002F \"connected\")\n2. gateway.log           → error message (\"No bot token configured\")\n3. .env                  → check TELEGRAM_BOT_TOKEN exists\n4. config.yaml           → check platform_plugins and telegram\n```\n\n### Step 1 — Inspect gateway state\n\n```bash\ncat ~\u002F.hermes\u002Fstate\u002Fgateway_state.json 2>\u002Fdev\u002Fnull\n# {\"platforms\": {\"telegram\": {\"status\": \"connected\", \"last_seen\": \"...\"}}}\n```\n\n`\"disconnected\"` + a `last_seen` far in the past = the platform dropped and\nisn't reconnecting. `\"connected\"` but messages not arriving = delivery-side\nproblem (see Step 5).\n\n### Step 2 — Read the gateway log\n\n```bash\ntail -50 ~\u002F.hermes\u002Flogs\u002Fgateway.log\n```\n\nTypical failure lines:\n- `No bot token configured for platform telegram` → token missing\n- `401 Unauthorized from Telegram API` → token wrong\u002Frevoked\n- `Connection reset by peer` → transient network; check reconnect behavior\n\n### Step 3 — Verify the token\n\n```bash\n# Does the var exist?\ngrep -c \"TELEGRAM_BOT_TOKEN\" ~\u002F.hermes\u002F.env\n\n# Is it set in the environment?\nprintenv TELEGRAM_BOT_TOKEN >\u002Fdev\u002Fnull && echo \"set\" || echo \"UNSET\"\n\n# Is the token VALID? (never print it)\ncurl -s \"https:\u002F\u002Fapi.telegram.org\u002Fbot$(cat ~\u002F.hermes\u002F.env | grep TELEGRAM_BOT_TOKEN | cut -d= -f2)\u002FgetMe\" | head -c 200\n```\n\n> **Never print secrets.** Read tokens via `$(cat \u003Cfile>)` or `grep | cut`\n> inside the command — never pass them as literal strings.\n\n### Step 4 — Check config.yaml\n\n```bash\ngrep -A5 \"telegram:\" ~\u002F.hermes\u002Fconfig.yaml\n```\n\nConfirm the platform is enabled in `platform_plugins` and no stale config\n(e.g. old bot name, wrong chat ID).\n\n### Step 5 — Delivery-side check (connected but nothing arrives)\n\nIf the gateway is connected but messages don't reach the user:\n- Confirm the destination chat ID is correct\n- Check `deliver` targets on the failing cron\u002Fjob\n- Verify the platform session didn't expire (re-auth if needed)\n\n## Restarting to load new code — and verifying it actually happened\n\nThe gateway **holds the MCP servers it spawned**, so new governance\u002Fenforcer code\nis not loaded until the gateway restarts. Two independent failure modes:\n\n> **What this coupling IS — and what it is NOT.** The half that forces a gateway\n> restart for a code change is the in-process ENFORCEMENT\u002FPLUGIN layer\n> (governance-enforcer plugin, the loop-gov\u002F`review` MCP, mycortex-*). It is NOT the\n> messaging transport: the poll→dispatch→reply loop is already decoupled to the\n> standalone `fleet-gateway.service`, so a `hermes gateway restart` is never about\n> messaging. When asked \"why must we still restart the hermes gateway?\", point at the\n> plugin\u002FMCP layer and the deploy≠load mechanism, never at the already-standalone\n> messaging.\n\n1. **Restarting from inside the gateway is blocked by design — and the block matches the COMMAND,\n   so deferring it is not an escape.** A restart issued from inside a Hermes session (a tool call) is\n   refused because the gateway would SIGTERM the command before it completed. Wrapping it to run\n   later (`systemd-run --on-active`, `nohup … &`, `at`) is refused as well: the guard inspects the\n   command and the script it references, not merely the timing, and attempting the workaround IS the\n   violation. Restart from a **separate shell**, or hand the operator the gateway's own `\u002Frestart`\n   command — which exits with the code its supervisor relaunches on, so the service comes back by\n   design and announces itself. Name which one you are asking for, and hand it over once; do not\n   loop-retry.\n2. **A restart can report success and still not land.** Verify; do not assume:\n\n```bash\nsystemctl --user show hermes-gateway.service -p MainPID -p ExecMainStartTimestamp -p NRestarts\n```\n\n`MainPID` and `ExecMainStartTimestamp` **must change**. Observed failure: an\nattempt that left both unchanged at the previous start time — the unit never\nre-activated, so the MCP child still held pre-change code while everything\n*looked* restarted.\n\nThen confirm WHAT THE CHILD LOADED — by content, not by a timestamp:\n\n```bash\npython3 - \u003C\u003C'EOF'\nimport hashlib, json, pathlib\nstamp = pathlib.Path.home() \u002F \".steadfaste-fleet\" \u002F \"state\" \u002F \"loop-gov-daemon.json\"\nmod = pathlib.Path.home() \u002F \".steadfaste-fleet\" \u002F \"tools\" \u002F \"loop-governance\" \u002F \"loop-gov-mcp.py\"\nrec = json.loads(stamp.read_text())            # written by the daemon itself at startup\nnow = hashlib.sha256(mod.read_bytes()).hexdigest()\nprint(\"daemon loaded:\", rec[\"sha256\"][:12], \"pid\", rec[\"pid\"])\nprint(\"on disk now :\", now[:12])\nprint(\"CURRENT\" if rec[\"sha256\"] == now else \"STALE — the loaded code differs from the file\")\nEOF\n```\n\n> **Portability — do NOT check this with `date -r \u003Cpath>`.** That is GNU syntax; on macOS (BSD)\n> `date -r` takes SECONDS since the epoch, so the same command silently means something else\n> instead of failing loudly. macOS also has no `sha256sum` (it ships `shasum -a 256`), which is\n> why the snippet hashes in Python rather than shelling out. `ps -o lstart=` is portable when you\n> only want the start time.\n\nAn older child start is a HINT that the old code is live — but mtime alone cannot settle it: the\nrestart command's own machinery (a dogfood\u002Fdoctor pass) RE-DEPLOYS, and a deploy rewrites files\nwhose bytes did not change, so the mtime moves while a current process reads as stale. Settle it by\nCONTENT — a startup hash stamp the process writes, or a witness only the new revision can produce —\nand never chase the resulting warning with another restart. Rule and mechanism:\n`deploy-load-verification`.\n\nNote: a config value in `~\u002Fsteadfaste-fleet\u002F.env` does **not** need a restart once\nthe gate's own resolver is deployed (it re-reads per call); only the code does.\n\n### A restart that preserves sessions is INVISIBLE — announce it, and tell the agent\n\nThe only message about a restart is sent by the process that then exits; nothing\nfollows it. So a human in the chat cannot tell the restart happened, and the agent\ncannot tell them either: sessions survive a gateway restart (starting fresh is\n`\u002Fnew`), so an agent asked \"did you restart?\" answers from its own memory —\n\"no, I still have our context\" — which is true of the SESSION, false about the\ngateway, and the only answer available. Three things fix that, and the third is\nthe one usually missed:\n\n1. **The restart command's reply states what happens to the CONVERSATION.**\n   \"restart\" reads like \"fresh start\"; a session that carries over otherwise looks\n   like nothing happened.\n2. **The NEW process announces itself at startup, before it serves anything**, in the\n   operator's wording, verbatim: `♻ Gateway restarted successfully. Your session\n   continues.` Keep that phrasing — it answers both questions a restart raises (did it\n   work, did I lose the conversation) in one line, and a longer invented variant is not\n   what the operator wants here. Persist a per-chat marker BEFORE sending the restart\n   reply — the process that writes the marker is the one that exits, so in-memory state\n   cannot carry it. Consume the marker on the first turn, so the human is told once and\n   not on every later reply. If the startup send fails, LEAVE the marker and let the\n   first reply carry the confirmation: a transient send failure must not lose the news.\n3. **Hand the AGENT the same fact on its first prompt after the restart** (a\n   `[system]` note prepended to the turn). Announcing to the human alone leaves the\n   agent still answering \"no\" — the contradiction the human will notice.\n\nProve a restart with the unit, not with the chat:\n\n```bash\nsystemctl --user show \u003Cunit>.service -p NRestarts -p MainPID -p ExecMainStartTimestamp\n```\n\nA NEW `MainPID` plus start timestamp is the proof. `NRestarts` increments only for a\n**policy** restart (`Restart=` firing) — an operator-issued `systemctl restart` does\nnot increment it, so a changing `NRestarts` is evidence the unit restarted ITSELF.\n\n- **`Restart=always` is required for restart-on-clean-exit**, the pattern where a\n  service asks systemd to bring it back by exiting on purpose: `Restart=on-failure`\n  does NOT start the unit again after `exit(0)`, so the exit is a plain stop and the\n  bot stays down. Check the policy before trusting the mechanism.\n- **The exit code is the SUPERVISOR's, never a constant — derive it, and refuse when\n  nothing would bring the process back.** systemd (`Restart=always`) relaunches on any\n  exit, so `os._exit(0)` is right; a launchd job whose plist says `SuccessfulExit=false`\n  is relaunched only after a NON-zero exit, so the same handler must exit `75`\n  (EX_TEMPFAIL) on macOS or it PARKS the service silently. Prove who owns the process\n  first — `launchctl list`'s PID column showing OUR pid is the test, because\n  `XPC_SERVICE_NAME` is inherited by children exactly as systemd's `INVOCATION_ID` is —\n  then read the job's own plist for the relaunch condition and exit with the code it\n  wants. When no recognised condition covers a deliberate exit, refuse and name the\n  plist fix instead of exiting into silence. Conditions and the full exit-code table:\n  `macos-service-management`.\n- **Probing this with a throwaway unit: end the probe with\n  `systemctl --user stop \u003Cunit>` and exit 0.** Under `Restart=always`, a probe that\n  exits non-zero restarts itself in a loop — it floods the journal and, if it also\n  touches live state, does so repeatedly. Confirm the unit is gone afterwards\n  (`systemctl --user list-units --all | grep \u003Cname>`).\n\n## A non-Hermes backend is a SEPARATE runtime, not a Hermes session\n\nA backend of `kind: command` (a CLI coding agent) is a distinct process with its\nown tooling: it inherits **none** of a Hermes session's memory, skills, or\ngovernance. \"Agent X has no memory\" is therefore a property of that backend's\nOWN integration layer, never of the host — establish where its memory comes from\nbefore touching anything shared:\n\n| Backend | Memory comes from |\n|---|---|\n| Hermes session | the `mycortex-mem` memory-provider plugin, in-process |\n| command\u002FCLI agent | its own MCP server or extension, spawned by the agent CLI |\n\n`hermes mcp list` does not list plugin-provided stores, so its absence proves\nnothing about a Hermes session; a CLI agent's tools appear in ITS agent config\n(its own `mcp.json`\u002Fsettings), not in `config.yaml`.\n\n### One service-hosted agent reports a store unreachable, a sibling works\n\nCompare the two SERVING UNITS' sandbox flags before blaming the store —\nhardening is invisible in the agent's own output, and the store's availability\ncheck often swallows the real exception:\n\n```bash\nsystemctl --user show \u003Cfailing>.service -p NoNewPrivileges -p PrivateTmp\nsystemctl --user show \u003Cworking>.service -p NoNewPrivileges -p PrivateTmp\n```\n\n`NoNewPrivileges=true` refuses `sg`\u002F`newgrp` setgid **even when the process\nalready holds the target group**, which breaks any store whose only access path\nis `sg docker -c \"docker exec …\"`. Reproduce faithfully with\n`setpriv --no-new-privs -- \u003Ccmd>` — it keeps the real supplementary groups,\nwhereas `systemd-run` drops them and fails for the wrong reason. Fix by giving\nthe store a direct `docker exec` path when the group is already held; never by\ndropping the hardening flag. Mechanism and store-specific fix: `psql-automation`.\n\n### Slash commands are the GATEWAY's, never the agent's\n\nWhen a `kind: command` backend (a CLI coding agent) serves a chat, the built-in slash\ncommands belong to the GATEWAY: such a backend handles `\u002Fnew`, `\u002Fmodel`, `\u002Fcompact`,\n`\u002Frestart` only in its interactive\u002FRPC surface, so forwarded as prompt prose they become\nordinary conversation — a `\u002Fnew` is answered politely while every bit of context stays.\nIntercept them in the gateway's command dispatcher and never pass them through\n(backend mechanics: `pi-coding-agent`).\n\n- **Each command needs a defined contract, not just a route.** `\u002Fnew` starts a fresh\n  session; `\u002Fmodel` persists the override per chat — a stateless prompt wrapper has\n  nowhere to keep it, so the GATEWAY owns a small chat→model store, mode 0600 (a chat id\n  is personal data); `\u002Fcompact` reports what it reclaimed, and \"nothing to compact\" for a\n  session too small; `\u002Frestart` exits WITH THE CODE ITS SUPERVISOR RELAUNCHES ON (`0`\n  under `Restart=always`, `75` under launchd's `SuccessfulExit=false`) so the service\n  comes back by design, and the new process announces itself (above). A refusal must name\n  the half that is missing — \"not running under systemd\" is a dead end on a host that IS\n  supervised, by launchd.\n- **Design for the EMPTY chat.** Commands run on chats with no conversation yet, where a\n  backend's session operations hang or refuse (compact on a transcript that does not exist\n  never answers). Probe state first and answer with the specific condition — \"this chat has\n  no conversation yet\" — never a generic failure.\n- **A control timeout must cover a real turn plus the operation.** Compacting a large\n  session measured ~1m46s; a 30s deadline reports a healthy backend as broken.\n- **Test parity with a STUB transport and an echoing backend** (`\u002Fbin\u002Fecho` so the reply\n  body IS the argv). A probe that polls with the real bot token starts a second poller and\n  steals the live channel's messages (409); echoing is what lets the assertion check the\n  ARGV the gateway produced — model declared exactly once, no duplicate `--model`.\n\n### Inline menus (buttons) for gateway commands\n\nA slash command that picks a VALUE (a model, a voice, a page) is better served by a menu than a\nfree-text argument — but build it on the gateway's plumbing, not beside it:\n\n- **Read the transport before building the UI.** The button markup, edit-in-place and callback\n  routing may already exist. Feature-detect each and degrade to the text form when a platform\n  lacks it, rather than erroring — the command stays usable without buttons.\n- **Carry an INDEX in the callback, never the value.** `callback_data` is capped (64 bytes on\n  Telegram) while a real id runs 40+; re-render the menu from CURRENT state on every press, so a\n  stale button can only ever be out of range. Answer it — never apply a value the menu did not\n  show.\n- **Tick the value IN FORCE, not just an override** — the backend default is what most chats are\n  running, so ticking only overrides leaves every menu unticked; offer the reset entry only when\n  an override exists.\n- **Edit in place** — one message per menu, not one per press — and ANSWER every callback so the\n  client's spinner clears. Consume your own callbacks so a press never reaches the backend as\n  prompt prose.\n- **The list is gateway-owned config.** A backend's raw catalogue is hundreds of entries and a\n  menu of hundreds is worse than a command: curate it in the gateway config so the operator can\n  edit it. Warn on stderr for unusable entries (\"N blank entries ignored (M usable)\") instead of\n  silently serving a shorter menu.\n- **Enabling the menu is PER-HOST work — ship a deployable enabler, not a procedure.** The\n  list lives in each host's own gateway config, so every host needs a config step and a\n  restart before its menu appears. Make that a script (portable: stdlib only, no YAML\n  dependency, since the gateway reads its config with `json.loads`) that derives the list from\n  that host's own backend catalogue, MERGES only the list key — every other key preserved,\n  idempotent — and offers a `--check` sweep. Then REGISTER it in the deploy map: a helper meant\n  for every host that is not registered exists only in the repo, and tests that load it by repo\n  path stay green while hosts never receive it. Give \"cannot derive the list here\" its own exit\n  code rather than reporting an empty catalogue, and read the written config back to confirm\n  the other keys survived (a shape mismatch between the producer and the writer silently\n  writes an empty list and reports success).\n- **Warn when the backend cannot TAKE the value at all.** A shim-style backend declares no\n  value flag, so a selection is stored and never applied: the menu looks live and does nothing.\n  At startup, check whether any backend declares the placeholder that consumes the selection\n  and say so on stderr instead of serving a dead menu — the host's operator cannot otherwise\n  tell a working menu from a decorative one.\n- **Test the menu through the stub transport**: a callback arrives as its own KIND with the data\n  in the body. Assert the first page, the tick, a page step, a stale out-of-range press, and that\n  a chat with no configured list still gets the text form.\n\nConcrete shapes — paths, the callback envelope, callback-data encoding, and the test cases:\n`references\u002Finline-menus.md`.\n\n## Adding a New Platform\n\n1. Obtain the token\u002Fsecret for the platform (Telegram bot token from\n   @BotFather, Discord bot token, etc.)\n2. Add to `~\u002F.hermes\u002F.env` (never commit the file)\n3. Enable in `config.yaml` → `platform_plugins`\n4. Restart the gateway\n5. Verify `gateway_state.json` shows `\"connected\"` and send a test message\n\n## Enabling the decoupled fleet-gateway (a CLI-agent backend)\n\nThe repo ships a standalone `fleet-gateway` unit (`docs\u002Ftemplates\u002Ffleet-gateway.service`)\nthat answers a messaging bot with a pluggable backend, including a `kind: command` CLI\ncoding agent (pi, Codex, Claude Code). It is deliberately INDEPENDENT of\n`hermes-gateway.service` — own unit, own config, no `After=`\u002F`Wants=` on the incumbent.\nEnablement is a concrete sequence; books\u002Fdetail: `pi-coding-agent`, `steadfaste-fleet`.\n\n1. **Config**: copy `ops\u002Fscripts\u002Fgateway.yaml.example` (or `gateway-pi.example.yaml` for a\n   CLI backend) to `~\u002F.steadfaste-fleet\u002Fgateway.yaml` — OUTSIDE the repo. A CLI backend entry\n   is `kind: command` with an ABSOLUTE launcher path: `command` is an argv list, so `~`\u002F`$HOME`\n   are NOT expanded and the launcher is often a symlink into a dir not on a service PATH — a\n   relative or guessed path is a silent per-message no-op.\n2. **Env** in the fleet env (`~\u002Fsteadfaste-fleet\u002F.env`): the bot's `token_ref` var,\n   `TELEGRAM_ALLOWED_USERS` (sender allowlist — REQUIRED; without it any Telegram user reaches\n   a bot that RUNS CODE), `TELEGRAM_HOME_CHANNEL`, `GATEWAY_SECRET` (HMAC; the daemon refuses to\n   start without it), `TELEGRAM_API_BASE` (the transport fails CLOSED without it — the standard\n   value is `https:\u002F\u002Fapi.telegram.org`; a missing base would otherwise build `\u002Fbot\u003Ctoken>\u002Fmethod`),\n   plus the bus URL\u002Fauth.\n3. **Unit**: copy the template into `~\u002F.config\u002Fsystemd\u002Fuser\u002F`, `daemon-reload`, `enable --now`.\n4. **Provider key** for the CLI backend via the `!command` pattern pointing at\n   `env-value.sh \u003CVAR>` — it supplies exactly the one var, so the agent never inherits the whole\n   env file.\n\nPitfalls that cost a cycle here:\n\n- **One poller per bot token — Telegram 409.** The unit's `ExecStartPre` guard\n  (`guard_distinct_token.py`) REFUSES a config whose `token_ref` IS (or resolves to) the live\n  `TELEGRAM_BOT_TOKEN`. Give the second gateway its OWN bot and its OWN token var\n  (e.g. `MOSESPI_BOT_TOKEN`); two pollers on one token drop the live channel. This is the guard\n  working, not a bug to bypass.\n- **The unit's `ExecStart` interpreter must actually have the deps.** The template defaults to\n  `\u002Fusr\u002Fbin\u002Fpython3`; the fleet deps live in the fleet venv `~\u002F.steadfaste-fleet\u002Fvenv\u002Fbin\u002Fpython3`.\n  Point BOTH `ExecStartPre` and `ExecStart` at the venv python, and when a dep is missing install\n  it INTO that venv (age-gated) rather than routing around it — a bot-lock\n  `ImportError: psycopg package required` is the daemon's Postgres bus dependency surfacing, not a\n  bad config; and a unit that crash-loops with that traceback is otherwise indistinguishable from\n  a broken install.\n- **`~\u002F.hermes\u002Fconfig.yaml` is Hermes-owned and the patch\u002Fwrite tools REFUSE it** (\"Agent cannot\n  modify security-sensitive configuration\"). Edit it only through the CLI: `hermes mcp add \u003Cname>\n  --command … --args …` \u002F `hermes mcp remove \u003Cname>`, or `hermes config`. The `add` flow prompts\n  `Enable all N tools?` and CANCELS with no TTY — pipe `printf 'y\\n' |` to accept. Read back with\n  `hermes mcp list`. A doctor FAIL naming an MCP server that is present under a different key is a\n  NAME drift (the fleet-canonical name is what the doctor expects, e.g. `agent-bus` and not a\n  legacy alias) — add the canonical key and remove the legacy one, one server for the script.\n\n## Diagnosing a CLI-agent gateway that answers NOTHING (\"bot stopped working\")\n\nWhen a `kind: command` gateway (pi\u002FCodex\u002Fetc.) goes silent, the probe sequence is\nconfig → env → backend-direct → backend-through-gateway-code → inbound peek. Each\nstep either finds the break or rules it out; stop at the first red.\n\n1. **Config** — the live `~\u002F.steadfaste-fleet\u002Fgateway.yaml` (OUTSIDE the repo): backend\n   argv (ABSOLUTE paths), `stream`, `model`, `reply_mode`. Compare against the repo\n   examples; verify the model pi can resolve.\n2. **Daemon env** — the unit's `EnvironmentFile` is `~\u002Fsteadfaste-fleet\u002F.env`; confirm the\n   daemon PROCESS actually has the provider key it passes to the child\n   (`tr '\\0' '\\n' \u003C \u002Fproc\u002F\u003Cpid>\u002Fenviron | grep -E 'OPENROUTER|TELEGRAM'`).\n3. **Backend direct** — run the exact argv the gateway builds (`\u003Cpi> --session-id\n   \u003Cid> --model \u003Cmodel> \"\u003Cprompt>\"`) with stdout\u002Fstderr separated; a green here proves\n   the agent + model + key.\n4. **Backend through the gateway's code** — `build_gateway(cfg)` then\n   `backend.dispatch(envelope, sink=...)` with a VALID envelope. This is where the probe\n   pitfalls below bite.\n5. **Inbound peek** — raw `getUpdates?offset=\u003Cpersisted>` returns only NEWER updates\n   WITHOUT consuming them (the offset advances only when you pass a higher one):\n   0 pending = nothing stuck in Telegram's queue for the bot.\n6. **Journal + unit** — `journalctl --user -u fleet-gateway.service`, `systemctl\n   --user show \u003Cunit> -p Restart -p NRestarts`, and kernel\u002Fdmesg OOM for the death cause.\n7. **Backend session transcripts — the record of whether a turn RAN.** The CLI\n   agent's own session files (pi: `~\u002F.pi\u002Fagent\u002Fsessions\u002F--home-moses--\u002F*hc-pi-\u003Cchat>.jsonl` —\n   timestamp-prefixed) are appended only when dispatch actually invoked the agent;\n   their mtimes distinguish \"message consumed, agent answered\" from \"message never\n   arrived\". Pair with the offset peek: 0 pending updates + no session-file advance\n   since the restart = no real inbound reached the bot — the pipeline is healthy,\n   nothing was lost. Your own dispatch probes create\u002Fadvance these files, so\n   discount sessions named for your probe's `--session-id` when dating real turns.\n\nReading the evidence you get: **a healthy poller's journal is nearly SILENT**\n(errors and restart announces only — no per-turn logging), so silence proves\nnothing is broken, and the negative evidence carries the diagnosis. What each\nprobe positively proves: the restart announce reaching the chat = outbound path;\ndispatch-through-gateway-code returning a reply envelope = backend + model + key;\nupdate-offset peek = inbound queue state.\n\nProbe pitfalls (each reads as a REAL defect and is a false lead):\n\n- **The probe's getUpdates 409 is YOUR OWN probe, and the daemon logs it as \"poll\n  conflict\".** Calling `get_updates` against the live bot's token collides with the\n  daemon's long-poll; the COLLISION appears in the daemon's journal as `poll conflict\n  1\u002F3: another consumer owns this bot` — which reads exactly like a rival poller. A\n  single conflict whose timestamp matches your probe time is self-inflicted; the daemon\n  backs off 4s and recovers. Count the conflicts and check WHEN they landed before\n  hunting a second poller.\n- **A synthetic envelope needs a VALID UUID `msg_id`.** `env.validate` rejects a\n  non-UUID silently and dispatch returns `None` — which reads as \"the agent produced\n  nothing\" (0 sink calls, clean None). The test files warn about exactly this\n  (\"a synthetic `m` is rejected silently\"). Use a real `uuid4()`.\n- **The probe process env ≠ the daemon's env.** `_child_env` = the CALLER's `os.environ`\n  + spec overrides; if the probe lacks `OPENROUTER_API_KEY` (it lives in the unit's\n  `~\u002Fsteadfaste-fleet\u002F.env`, not the shell's), pi runs without the key, prints nothing to\n  stdout, exits 0, and dispatch returns a clean \"nothing to say\". Load the unit's env\n  file into the probe (`os.environ.setdefault` per line) OR source it, and confirm the\n  key is present before believing a negative.\n- **The pairing banner \"0 approved chat(s)\" is cosmetic when the user is in\n  `TELEGRAM_ALLOWED_USERS`.** `_sender_allowed` = env allowlist ∪ pairing store; pairing\n  only gates UNKNOWN senders. An empty `paired_chats.json` next to a configured\n  allowlist is not the bug — the owner passes on the env half.\n\nSilent death forensics — a unit that auto-restarted without a `Stopping` line:\n\n- `Restart=always` + no Stopping + no restart in `journalctl -u` = the process was\n  KILLED from outside (SIGKILL\u002FSIGTERM), not stopped by systemd. Correlate the death\n  time with nearby SSH\u002F`logind` sessions — an operator's own kill is the common case.\n- `systemctl --user show \u003Cunit> -p MemoryMax` reading `infinity` rules out cgroup OOM;\n  the memory PEAK includes the child agent (pi) in the same cgroup, so a big peak is\n  not a daemon leak on its own.\n\n## A gateway that serves the default profile ONLY — duplicate credential across profiles\n\n`gateway.multiplex_profiles` unset means ON, but not unconditionally: at every boot\nthe default gateway runs the same preflight as `hermes gateway migrate --multiplex`\nand multiplexes only when the fold would be safe. A **duplicate bot credential\nbetween two profiles is a hard blocker** — so the gateway comes up serving the\ndefault profile only, parks the other profile's adapter, and says so loudly (a\nboxed warning at start; the same text in the `hermes update` summary, in\n`hermes gateway status`, and in the dashboard's `\u002Fapi\u002Fstatus` as\n`multiplex_standalone_reason`). Log form:\n\n```\nhermes_cli.gateway_multiplex_mode: gateway.multiplex_profiles is unset (default: on)\nbut this gateway stays standalone: Profiles 'default' and 'personal' both configure\n\u003Cplatform> with the same credential ... It serves the default profile only\n```\n\nOne token is one poller, so nothing is written on a refusal and neither a restart\nnor `--force` clears it. Diagnose with counts only — never print a token:\n\n```bash\nls ~\u002F.hermes\u002Fprofiles\u002F                                     # default profile IS ~\u002F.hermes\nls -la ~\u002F.hermes\u002F.env ~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F.env       # size\u002Fmtime, no content\ngrep -c TELEGRAM_BOT_TOKEN ~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F.env  # count, never the value\n```\n\nBefore acting, decide whether the OTHER profile is real or vestigial — a profile\nthat never served a turn still blocks the fold (structural survey:\n`hermes-home-cleanup`). Then pick one fix:\n\n- **delete it** — `hermes profile delete -y \u003Cname>`. Ask the owner first: it prints the\n  skill count it destroys and leaves a `.deleted\u002F` tombstone. Prove nothing is lost\n  BEFORE deleting — a name-only diff of both `.env` files plus a hash of the shared var\n  (exact commands: `hermes-home-cleanup`) — because a strict subset with an identical\n  hash means no backup copy of the credential is needed, and making one only spreads it.\n- **keep the profile, strip just that platform's var** from its `.env` — smallest change.\n- **give it its own bot** and route its chats from the default profile's\n  `config.yaml` (`gateway.profile_routes`).\n\nThen `hermes gateway migrate --multiplex`. **Expect it to be a NO-OP once the duplicate is\ngone, and never read its rc=0 as \"the state is fixed\":** with one profile left it prints\n\"Only one profile exists: nothing to multiplex\" and does NOT restart, so the boot-time\n`multiplex_standalone_reason` in `gateway_state.json` keeps naming the deleted profile and\nthe dashboard keeps showing it. A restart is what re-runs the preflight:\n`systemctl --user restart hermes-gateway.service`, then verify it LANDED (`MainPID` AND\n`ExecMainStartTimestamp` both change) and read the post-state — the reason becomes\n`only one profile exists (nothing to multiplex)`, `hermes profile list` stops printing the\nwarning, and the boot log reads `Cron scheduler will tick N profile(s)` with the stale\nprofile absent. Before restarting from inside a session, check your own ancestry: a CLI\nsession (`sshd → shell → hermes`) survives it, a session hosted BY the gateway does not\n(`ps -o pid=,cmd= --ppid \u003Cgateway-pid>`).\n\n- **Never identify the active profile by listing `profiles\u002F*\u002F`.** Resolve\n  `HERMES_PROFILE` → `AGENT_NAME` (never hostname). A directory under `profiles\u002F`\n  is a second Hermes HOME, not a routing entry, and the alphabetically-first entry\n  is not the active one — every fleet script carries that warning because it bites.\n- **A profile is not \"unused\" because it is small.** Its `.env` alone is enough to\n  block the whole host's multiplexing; the blocker outlives any single session.\n\n## Common Failure Patterns\n\n| Symptom | Root cause | Fix |\n|---------|-----------|-----|\n| `No bot token configured` | Token missing from .env | Add token, restart gateway |\n| `401 Unauthorized` | Token revoked or wrong | Generate new token, update .env |\n| Repeated reconnecting | Network \u002F API instability | Check outbound connectivity; verify with `curl` |\n| Connected but no delivery | Wrong chat ID \u002F deliver target | Verify destination chat ID and `deliver` config |\n| Gateway up, platform down | Platform-side outage | Wait + monitor; check platform status page |\n| Serves default only; boxed \"stays standalone\" warning naming two profiles | Two profiles configure the same platform credential | Strip the credential from the redundant profile (or delete it), then `hermes gateway migrate --multiplex` |\n\n## Verification\n\n```bash\n# End-to-end test after any fix: send a test message to the home channel\n# via a cron or direct invocation, then confirm it arrived.\n```\n\n## Related\n- `hermes-agent` — general Hermes configuration\n- `telegram-delivery-diagnostics` — Telegram-specific delivery debugging\n- `fleet-bus` — inter-agent messaging (separate from the user gateway)\n- `psql-automation` — the `sg`\u002F`NoNewPrivileges` store-access mechanism behind a\n  \"store unreachable\" report from a hardened service\n",{"name":5,"version":24,"description":7},"1.0.0","main","162463c5db5a1e06f4c54abddce6ee13c3d7612b","skills\u002Fdevops\u002Fhermes-gateway-operations",1,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet","steadfaste.com","https:\u002F\u002Fgithub.com\u002Flukemcqueen","AI Architect | Building Hermes Cortex: governed multi-agent AI for autonomous software engineering | Enterprise Tech Consultant","2026-11-14 22:33:34",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermes-gateway-operations",{"tool":40,"command":41},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermes-gateway-operations",{"tool":43,"command":44},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermes-gateway-operations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fhermes-gateway-operations\u002FSKILL.md",true,[48],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"references\u002Finline-menus.md","REFERENCE","参考文档",3249,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fhermes-gateway-operations\u002Freferences\u002Finline-menus.md",[55,63,70,77,84,91],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":62},"01M7DXY4G8NSVB59K8B6S2AQNP","macbook-linux-maintenance","Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fmacbook-linux-maintenance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":62},"01M7DXXYJCXFJ3TGB84ZQ8KFE6","governance-regression-triage","Triage a host's governance issues: what changed.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fgovernance-regression-triage\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":62},"01M7DXXSAP1G8FDRJAMXQGBBMK","enforcement-immutability","Use when enforcement files lose their immutable flag.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fenforcement-immutability\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":62},"01M78SSDQVRYX64Y16X32TC0NS","steadfaste-fleet-repo-deploy","Use when committing to the steadfaste-fleet repo.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-repo-deploy\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":62},"01M78SS928F3R2RJAYVW4E30CE","steadfaste-fleet-maintenance","Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-maintenance\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":62},"01M78SP1CHW0T0BWE5ZT6JBPX8","fleet-preflight","DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its \"Repo-Specific Pre-Flight\" section covers git search, Hermes boundary, and deployment verification.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-preflight\u002FSKILL.md",[],[]]