[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78SN2PH6KQ7X20P7FMY1PM5":3,"skill-same:01M78SN2PH6KQ7X20P7FMY1PM5":75},{"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":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M78SN2PH6KQ7X20P7FMY1PM5","fleet-bus",null,"Agent Bus (PGMQ) operations — queue inspection, DLQ management, message recovery, auth, and health diagnostics. Covers the Postgres-backed message queue that replaces the legacy file inbox.","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\u002Ffleet-bus\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: fleet-bus\nversion: 1.3.0\ncategory: devops\ndescription: \"Agent Bus (PGMQ) operations — queue inspection, DLQ management, message recovery, auth, and health diagnostics. Covers the Postgres-backed message queue that replaces the legacy file inbox.\"\nplatforms: [linux]\nauthor: Steadfaste Fleet\nmetadata:\n  hermes:\n    tags: [bus, pgmq, dlq, messaging, queue, postgres, recovery]\n    related_skills: [system-remediation, steadfaste-fleet-deployment]\n---\n\u003C!-- renamed from skills\u002Fdevops\u002Fcortex-bus\u002FSKILL.md in the cortex-to-fleet sweep; content predates the range (commit 353c3d54) -->\n\n\n# Agent Bus — PGMQ Operations\n\n## Overview\n\nThe Agent Bus is a Postgres-native message queue (`lib\u002Fpgmq` implementation with `SKIP LOCKED`) running on port `:8903`, proxied through nginx. All inter-agent communication flows through it. It replaces the old file-based agent inbox.\n\n> **📐 Architecture reference:** `docs\u002Freference\u002Ffleet-bus-config.md`, `docs\u002Fbus-architecture.md`, `docs\u002Forch-bus-setup.md`, `docs\u002Festher-bus-setup.md` — these live on the **orchestrator hosts' private repo** (moses\u002Festher) and may NOT exist on this host or in the public repo. Check before opening: `ls ~\u002Fsteadfaste-fleet\u002Fdocs\u002Freference\u002Ffleet-bus-config.md 2>\u002Fdev\u002Fnull || echo \"not on this host — request from orchestrator via inbox_orchestrator\"`. This skill covers operational diagnostics only.\n\n> **⚠️ Postgres access (post-2026-08-05 migration):** the `legacy Postgres`\n> container was replaced by **`mycortex-postgres`** (role\u002Fdb **`mycortex`**,\n> port still `:15432`). All psql examples below use the new container\u002Frole:\n> `sg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex ...\"`.\n> The old `mycortex` role does NOT exist in the new container — using it fails\n> with `FATAL: role \"mycortex\" does not exist`.\n\nKey architectural facts:\n- **Bus server** processes at `~\u002Fsteadfaste-fleet\u002Fcore\u002Ffleet_bus\u002Fserver.py` (module `fleet_bus.server:app`, service `fleet-bus.service`)\n- **Queue module** at `~\u002Fsteadfaste-fleet\u002Fcore\u002Ffleet_bus\u002Fqueue.py`\n- **Postgres schema** `bus.*` in the shared mycortex database (`:15432`)\n- **MCP tools** `mcp__fleet_bus__*` route through the bus via HTTP\n- **Health check**: `curl http:\u002F\u002F127.0.0.1:8903\u002Fhealth` returns 200\n- **Bearer token auth**: token from `FLEET_BUS_TOKEN` in `.env`\n\n## When to Use\n\n- Diagnosing message delivery failures between agents\n- Inspecting queue depth or DLQ buildup\n- Recovering stuck `processing` messages\n- Fixing bus auth or permission issues\n- Investigating why an agent isn't receiving messages\n\n## Message Contract (strict input formatting)\n\nEvery `\u002Fapi\u002Fpgmq\u002Fsend` is validated at ingestion (2026-09-02, anti-poisoning\u002Fanti-spam at fleet scale). Violations → **400 + reason**; over quota → **429**.\n\n| Field | Rule |\n|-------|------|\n| `from` | Required, lowercase agent name, **must equal the authenticated sender** (spoofing rejected with 400 `\"from '\u003CX>' does not match authenticated agent '\u003CY>'\"`) |\n| `subject` | Required, `^[A-Z][A-Z0-9_]{0,63}$` (`EXEC`, `PING`, `DOCTOR_TEST`, …) |\n| `body` | Required, object or string |\n| `to` \u002F `correlation_id` \u002F `timestamp` \u002F `type` \u002F `priority` \u002F `forwarded_from` | Optional; `priority` **int** 0-100 — string values (`\"normal\"`, `\"urgent\"`) are rejected with 400. Map via dict before sending. `forwarded_from` set by the bus forwarder when relaying a message between bus instances (preserves the original sender). |\n| Unknown keys | **Rejected** — no field smuggling |\n| Size | 64 KiB max\u002Fmessage |\n| Rate | 600 sends\u002Fhr\u002Fagent (`FLEET_BUS_RATE_LIMIT_PER_HOUR`), sliding window |\n\n`workflow_step_result` queue uses its own schema (`workflow_id` `step_id` `status` `result` `error`) — agents post step results without an envelope.\n\nImplementation: `core\u002Ffleet_bus\u002Fvalidate.py` + `core\u002Ffleet_bus\u002Fratelimit.py`, tests in `tests\u002Ftest_bus_validate.py`. Sending messages: use `bus_send()` \u002F the MCP inbox tools — they build conforming envelopes.\n\n## Inbox Message Decision Framework\n\nClassify each inbox message on two axes, then act per the matrix. **Priority** (error=None priority): `critical` | `urgent` | `normal` | `notification`. **Scope**: `Simple (\u003C3 items)` | `Moderate (3–10)` | `Complex (>10)` | `Multi-agent`.\n\n| Prio → | Simple | Moderate | Complex | Multi-agent |\n|--------|--------|----------|---------|-------------|\n| critical | AUTO-ACT | AUTO-ACT | AUTO-ACT + notify | Delegate + notify |\n| urgent | AUTO-ACT | AUTO-ACT | AUTO-ACT + report | Delegate + report |\n| normal | AUTO-ACT | AUTO-ACT | Escalate | Escalate |\n| notification | Acknowledge | Acknowledge | Acknowledge | Forward |\n\n**After-action:** deliver what was done, how it was verified, the evidence, and the cycle ID.\n\n## Diagnosing Bus State\n\n### 1. Queue Overview\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count\nFROM bus.messages\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\"\n```\n\nShows every queue with its message counts broken down by state:\n\n| State | Meaning |\n|-------|---------|\n| `pending` | Ready for dequeue — normal state |\n| `processing` | Currently dequeued, within visibility timeout |\n| `archived` | Successfully processed (or auto-archived) |\n\n### 2. DLQ Inspection (Dead Letter Queue)\n\nMessages that exceeded `max_retries` (default 3) move to `{queue}_dlq`. DLQ messages older than 6 hours are auto-archived by `bus.recover_timeouts()`.\n\n```bash\n# DLQ depth by queue\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest\nFROM bus.messages\nWHERE queue_name LIKE '%dlq%'\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\"\n\n# DLQ message content — who sent it, what about, how many retries\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT \n    queue_name,\n    COALESCE(body->>'from', '(empty)') as sender,\n    body->>'subject' as subject,\n    body->>'topic' as topic,\n    retry_count,\n    error,\n    enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending' AND queue_name LIKE '%dlq%'\nORDER BY queue_name, enqueued_at DESC\nLIMIT 50;\n\\\"\"\n```\n\n### 3. Check Queue Schema Integrity\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT name, is_dlq, parent_queue, max_retries FROM bus.queues ORDER BY name;\n\\\"\"\n```\n\nEvery queue ending in `_dlq` MUST have `is_dlq = true`. If false, the auto-archive and chain-deletion break silently.\n\n### 4. Run Recovery\n\n```bash\n# Returns count of messages recovered\u002Farchived\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT bus.recover_timeouts();\n\\\"\"\n```\n\nThe `recover_timeouts()` function does three things:\n1. **Recovers** processing→pending for messages below `max_retries`\n2. **Moves** over-retry processing messages to DLQ (or deletes if already in a DLQ)\n3. **Auto-archives** DLQ messages older than 6 hours\n\n### 5. Interpreting Recovery Counts\n\nThe `orch-bus-recover-timeouts` cron (every 5m) calls `bus.recover_timeouts()` and reports results. The **silent threshold is 50** — below that, no notification is sent (routine timeouts are normal).\n\n| Recovery count | Meaning |\n|----------------|---------|\n| 0–5 | Normal — routine visibility timeouts |\n| 5–50 | Mild backlog — catching up, no action needed |\n| 50+ | Moderate+ backlog — worth investigating |\n\n### 6. Normal DLQ Baselines\n\nDLQ messages \u003C 6 hours old are normal — they auto-archive on each `recover_timeouts()` tick.\n\n| DLQ depth | State |\n|-----------|-------|\n| \u003C 50 | Normal — transient backlog |\n| 50–200 | Moderate — check sender breakdown |\n| 200+ | Elevated — investigate with DLQ content query (section 2) |\n\nIf messages older than 6 hours are present, `is_dlq` may be broken (see Common Issues below).\n\nThe threshold (50) is set in `ops\u002Fscripts\u002Forch-bus\u002Forch-bus-recover-timeouts.sh` as `RECOVER_THRESHOLD=50`.\n\n### 7. Health Report Monitoring (`orch-bus-confirmation-poller.py report`)\n\nThe `orch-bus-confirmation-alert` cron (every 60m) runs `orch-bus-confirmation-poller.py report` producing a combined bus health report covering message tracker status + queue depths + DLQ health.\n\n**Report behaviour:**\n- **Silent when healthy** — no output if no DLQ backlog, no overdue confirmations, no pending messages. Zero stdout = zero notification.\n- **Alerts on DLQ backlog** — checks both `depth` (pending) AND `processing` state in DLQ queues. Messages stuck in processing count as a backlog.\n- **Reports on overdue confirmations** — tracked messages past their confirmation deadline.\n\n**Common gotcha — processing messages in DLQ hidden from alerts:**\nThe DLQ alert code in `cmd_report()` at `ops\u002Fscripts\u002Forch-bus\u002Forch-bus-confirmation-poller.py` initially only checked `depth > 0` for DLQ queues. Messages in `processing` state were invisible. The fix adds `or processing > 0` to both the marker and `dlq_issues` detection.\n\n```python\n# Before (missed processing messages):\nmarker = \" ⚠️ DLQ\" if is_dlq and depth > 0 else \"\"\nif depth > 0: dlq_issues.append(name)\n\n# After (checks both):\nmarker = \" ⚠️ DLQ\" if is_dlq and (depth > 0 or processing > 0) else \"\"\nif depth > 0 or processing > 0: dlq_issues.append(name)\n```\n\n**Silent-when-clean pattern** — the report collects all data first, then only prints if there's something to report:\n\n```python\n# At the end of data collection:\nif not overdue and not dlq_issues and not pending:\n    return  # completely silent\n```\n\n### 8. Cron Alert Design: Silent-When-Clean\n\nA general principle for no_agent cron scripts that produce health\u002Fstatus reports:\n\n- **No output = no notification.** The user should only hear from a cron when there's something to act on.\n- **Collect data first, print only if there's a signal.** Build the entire report into variables (`queue_lines`, `dlq_issues`), then check whether anything needs attention before printing.\n- **Silence is the default, not a special mode.** The healthy state should produce zero stdout. Don't print \"✅ All clean\" — that's noise.\n- **Thresholds belong in the script, not hardcoded in docs.** The `RECOVER_THRESHOLD` variable in the script defines what's actionable. Docs reference the variable name, not the value.\n\nThis pattern applies to: health reports, watchdog crons, depth monitors, alert crons, and any periodically-running agent script that checks system state.\n\n### 9. Stuck Pending Messages at Max Retries\n\nThe `recover_timeouts()` function only moves messages from `processing` → pending\u002FDLQ. Messages that were never dequeued while it ran remain in `pending` with their retry count unchanged. This means **messages can sit in `pending` with `retry_count = max_retries` without ever being promoted to the DLQ**.\n\nThese are truly stuck: the message was dequeued up to max_retries times, timed out each time, but no agent subsequently dequeued it again, so it never re-entered `processing` state for `recover_timeouts()` to catch.\n\n**Detection query:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, retry_count, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest,\n    COALESCE(body->>'from', '(null)') as sender,\n    body->>'subject' as subject,\n    body->>'topic' as topic\nFROM bus.messages\nWHERE state = 'pending'\n  AND retry_count >= (SELECT COALESCE(max_retries, 3) FROM bus.queues WHERE name = bus.messages.queue_name)\nGROUP BY queue_name, retry_count, body->>'from', body->>'subject', body->>'topic'\nHAVING COUNT(*) > 0\nORDER BY COUNT(*) DESC\nLIMIT 20;\n\\\"\" 2>&1\n```\n\n**Remediation:**\n\n⚠️ **`bus.dlq_move(msg_id)` does NOT exist in the schema.** Attempting to call it produces `ERROR: function bus.dlq_move(uuid) does not exist`. Use `bus.archive()` instead.\n\nThe correct approach requires getting the message ID first, then archiving it individually — `bus.archive()` takes a single `msg_id`.\n\n**Step 1 — Get the stuck message IDs:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT msg_id::text, queue_name, body->>'subject' as subject,\n    retry_count, enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending'\n  AND retry_count >= (SELECT max_retries FROM bus.queues WHERE name = bus.messages.queue_name)\n  AND queue_name = 'inbox_target'\nORDER BY enqueued_at;\n\\\"\\\" 2>&1\n```\n\n**Step 2 — Archive each via `bus.archive()` with explicit `::uuid` cast:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nSELECT bus.archive('inbox_target', '\u003Cmsg_id>'::uuid, 'esther-remediation');\n\\\"\\\" 2>&1\n```\n\nRepeat for each stuck message ID. Verify the queue is clean afterward with the detection query from Step 1.\n\n**Bulk fallback (bypasses proper archive function — use only when you're sure all are orphaned):**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nUPDATE bus.messages SET state = 'archived', archived_at = NOW()\nWHERE state = 'pending'\n  AND retry_count >= (SELECT max_retries FROM bus.queues WHERE name = bus.messages.queue_name)\n  AND queue_name = 'inbox_target';\n\\\"\\\" 2>&1\n```\n\n> **Why individual archiving:** `bus.archive()` logs the action via `bus.audit()` and handles DLQ chain metadata correctly. The direct UPDATE is faster for bulk cleanup but skips audit logging — acceptable for known-orphaned messages where you want to clear a backlog fast.\n\n**Root cause:** Target agent stopped dequeuing. The message was picked up by visibility timeout (default 30s), retried, exhausted max_retries, and the agent never dequeued it again. Fix by clearing backlog or restarting the agent's consumer.\n\n### 10. Raw-Field Wrapper Messages\n\nSome bus senders wrap the payload inside a `raw` field, producing messages like:\n```json\n{\"raw\": \"{\\\"from\\\": \\\"moses\\\", \\\"to\\\": \\\"moses\\\", \\\"topic\\\": \\\"health\\\"}\"}\n```\n\nThis means `body->>'from'` evaluates to `NULL` at the top level. The sender data is nested inside `body->'raw'->>'from'` after a JSON decode of the inner string.\n\n**Detection query:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT COUNT(*) as count, queue_name\nFROM bus.messages\nWHERE state = 'pending'\n  AND body->>'from' IS NULL\n  AND body ? 'raw'\nGROUP BY queue_name\nORDER BY COUNT(*) DESC;\n\\\"\" 2>&1\n```\n\n**Reading actual content:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT msg_id, queue_name,\n    body->'raw'->>'from' as actual_sender,\n    body->'raw'->>'subject' as actual_subject,\n    body->'raw'->>'topic' as actual_topic,\n    enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending'\n  AND body->>'from' IS NULL\n  AND body ? 'raw'\nORDER BY enqueued_at DESC\nLIMIT 20;\n\\\"\" 2>&1\n```\n\n### 11. Fleet-Wide Queue Scan During Inbox Processing\n\nWhen an inbox-processing cron runs, scan all queues for a fleet-wide health picture — even though you can only act on your own queue. This surfaces backlogs in other agents.\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest\nFROM bus.messages\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\" 2>&1\n```\n\nCompare depths:\n- **0:** Clean\n- **1–50:** Normal backlog\n- **50–200:** Moderate — flag in report\n- **200+:** Elevated — escalate\n\n**Note:** PSQL access is via local `sg docker` gateway. For remote agents, use the bus API at `\u002Fapi\u002Fpgmq\u002Fqueues` (lists all queues but not per-message detail).\n\n## Inspecting the bus from a cron\u002Funattended tick (governance-gated shell)\n\nThe governance enforcer classifies `curl …`, `sg docker -c \"docker exec … psql …\"`\nand `execute_code` as WRITE-CLASS, so a cron tick with no active governance lock\ncannot run them — and opening a cycle for a read-only inspection is noise.\nWorking ungated alternatives:\n- `mcp__agent_bus__bus_inbox_peek` — **the non-destructive inspection tool**\n  (`queue`, `limit`, `archived`). It issues only `GET \u002Fapi\u002Fpgmq\u002Fpeek\u002F{queue}` \u002F\n  `\u002Fapi\u002Fpgmq\u002Farchives\u002F{queue}` and never dequeues, so it is safe on a queue another\n  consumer owns; each entry carries `subject` and `correlation_id`, which is what a\n  dispatch RESULT is matched on (the 6-checkpoint rule). Use `archived: true` for a\n  result the handler has already processed — archived messages are invisible to a\n  pending-only peek, which is the usual reason \"the result was never sent\".\n- `mcp__agent_bus__inbox_read` \u002F `inbox_watch` \u002F `inbox_list_agents` — inbox + agent\n  liveness, served over the bus, never gated (they are deferred MCP tools, not shell).\n  **`inbox_read` DEQUEUES** (`POST \u002Fapi\u002Fpgmq\u002Fread`, 60 s visibility timeout) from\n  your own queue only — it is a consuming read, not an inspection primitive, and it\n  can never see another agent's queue or the orchestrator queue.\n- `browser_exec`: `http:\u002F\u002F127.0.0.1:8903\u002Fhealth` is unauthenticated and reports\n  `{\"status\":\"ok\",…,\"queues\":N}`; the dashboard at `\u002F` renders `\u002Fapi\u002Fbus\u002Fdashboard`,\n  `\u002Fapi\u002Fpgmq\u002Fqueues`, `\u002Fapi\u002Fworkflows`, ALL of which need a Bearer token — opened\n  without creds the dashboard shows `ERROR Cannot read properties of undefined\n  (reading 'total')`, which is an auth artifact, NOT a bus fault. `\u002Fmetrics` is 404.\n- Read-only primitives (`ls`, `cat`, `grep`, `find`, `git status\u002Flog\u002Fdiff`) stay\n  lock-free for state files, e.g. `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json`\n  — check `last_run` and `total_local_to_peer`\u002F`total_peer_to_local` to prove the\n  LOCAL write path is alive.\n- **Do not `read_file` `bus-forwarder-state.json`** in full: it is ~770 KB of dedup\n  keys and will flood context — grep it for the three scalar fields instead.\n\n## Common Issues\n\n### DLQ Messages Accumulating Without Auto-Archive\n\n**Symptom:** DLQ depth grows without bound, old messages (6h+) stay in `pending` state.\n\n**Root cause:** The `is_dlq` flag was not set on DLQ queues — `bus.recover_timeouts()` Step 3 (auto-archive) checks `WHERE q.is_dlq = true` and silently skips queues where it's false. Also Step 2 cannot chain-delete exhausted DLQ messages, causing `_dlq_dlq` accumulation.\n\n**Fix:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nUPDATE bus.queues SET is_dlq = true WHERE name LIKE '%_dlq%' AND is_dlq = false;\n\\\"\" 2>&1\n\n# Run recovery to immediately clear old messages\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT bus.recover_timeouts();\n\\\"\"\n```\n\nAfter fix, the cron `orch-bus-recover-timeouts` (every 5m) auto-maintains the DLQ. Verify with queue overview query.\n\n**Prevention:** The queue creation code at `core\u002Ffleet_bus\u002Fqueue.py:create_queues_for_agent()` already sets `is_dlq = true` — the bug only affects queues created before the column was added to the schema.\n\n### recover_timeouts Fails with messages_queue_name_fkey (missing DLQ row)\n\n**Symptom:** `orch-bus-recover-timeouts` cron (every 5m) fails with `Script exited\nwith code 1`; running the function directly shows:\n`ERROR: insert or update on table \"messages\" violates foreign key constraint\n\"messages_queue_name_fkey\" — Key (queue_name)=(inbox_orchestrator_dlq) is not\npresent in table \"queues\".`\n\n**Root cause:** a queue exists in `bus.queues` but its `\u003Cqueue>_dlq` row was\nnever seeded. The seed creates `inbox_orchestrator` without its DLQ\n(`core\u002Ffleet_bus\u002Fschema\u002Fauth.sql`, 2026-08-12), while agent inboxes get DLQs\nvia `create_queues_for_agent()`. `recover_timeouts()` Step 2b moves exhausted\nprocessing messages to `queue_name || '_dlq'` — the FK fails and **kills the\nwhole run**, so the cron never recovers anything.\n\n**Fix (2026-08-12):** two layers, both in the repo:\n1. **Seed** — `auth.sql` now inserts `inbox_orchestrator_dlq` (`is_dlq=true`,\n   `parent_queue='inbox_orchestrator'`) next to the shared inbox.\n2. **Defensive** — `recover_timeouts()` Step 2b now auto-creates any missing\n   `_dlq` queue row before the move:\n   ```sql\n   INSERT INTO bus.queues (name, is_dlq, parent_queue)\n   SELECT DISTINCT m.queue_name || '_dlq', true, m.queue_name\n   FROM bus.messages m\n   LEFT JOIN bus.queues q ON q.name = m.queue_name || '_dlq'\n   WHERE q.name IS NULL AND m.state = 'processing'\n     AND m.timeout_at \u003C now() AND m.retry_count >= m.max_retries\n   ON CONFLICT (name) DO NOTHING;\n   ```\n\n**Apply to a live DB** (schema changes deploy via file copy, not auto-applied):\n```bash\nsg docker -c \"docker exec -i mycortex-postgres psql -U mycortex -d mycortex -v ON_ERROR_STOP=1 -f -\" \u003C core\u002Ffleet_bus\u002Fschema\u002Fqueue.sql\nsg docker -c \"docker exec -i mycortex-postgres psql -U mycortex -d mycortex -v ON_ERROR_STOP=1 -f -\" \u003C core\u002Ffleet_bus\u002Fschema\u002Fauth.sql\n```\n\n**Verify:** `SELECT bus.recover_timeouts();` returns a number (not an error), and\n`SELECT name FROM bus.queues WHERE name = '\u003Cqueue>_dlq';` exists for every\nnon-DLQ queue. Check for other missing DLQ rows: `SELECT name FROM bus.queues\nWHERE is_dlq = false AND name || '_dlq' NOT IN (SELECT name FROM bus.queues)`.\n\n**Pitfall — string `priority` rejected with 400.** The bus API expects `\"priority\"` as an **integer** (0-100). Passing `\"normal\"`, `\"urgent\"`, or `\"critical\"` as strings produces a 400. Always map string priorities to int before sending:\n```python\npriority = {\"normal\": 0, \"urgent\": 10, \"critical\": 20}.get(priority_str, 0)\n```\nThe same 400 is returned when the `from` field doesn't match the authenticated user — `\"from 'moses' does not match authenticated agent 'esther'\"`. Each agent must send as themselves, not as another agent.\n\n### All Bus Tools Return 401 (Not 200)\n\nThe MCP bus tools (`mcp__fleet_bus__*`) return HTTP 401 when:\n1. `FLEET_BUS_TOKEN` in `.env` doesn't match the hash in `bus.tokens` table\n2. The token is missing entirely from the PG table\n\n**Diagnostic:**\n```bash\n# Check which tokens exist\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nSELECT agent_name, substring(token_hash::text, 1, 20) as token_prefix, rotated_at\nFROM bus.tokens ORDER BY agent_name;\n\\\"\"\n\n# Verify your .env token matches\ngrep FLEET_BUS_TOKEN ~\u002Fsteadfaste-fleet\u002F.env\n```\n\n### Bus Unreachable (Connection Refused)\n\n**Symptom:** `curl http:\u002F\u002F127.0.0.1:8903\u002Fhealth` fails.\n\n**Check:**\n```bash\n# Is the bus process running?\nss -tlnp | grep 8903\n\n# Is the systemd service active?\nsystemctl --user status fleet-bus.service\n\n# Restart if needed\nsystemctl --user restart fleet-bus.service\n```\n\nNote: The bus at `:8903` is a direct local connection. It's also proxied through nginx at the orchestrator's bus port (e.g. `:13004` for Moses, `:14004` for Esther) with Bearer auth. The MCP tools route through nginx, not directly.\n\n## Client fail-fast on 4xx — BusPermanentError, never outboxed (2026-09-09)\n\n`ops\u002Fscripts\u002Flib\u002Ffleet_bus.py` classifies 4xx responses as PERMANENT, not retryable:\n\n- `lib._bus_post` raises `BusPermanentError` on any 4xx — except 401\u002F403 while the\n  Basic-auth fallback still has a try left.\n- On a permanent rejection `bus_send` returns `{queued: false, permanent: true}`\n  and **never writes the outbox file**. Do not layer retry-on-4xx logic on top:\n  permanent means permanent (bad subject\u002Fformat\u002FACL — e.g. a lowercase subject\n  that `validate.py` rejects with HTTP 400).\n- The inner Basic-auth fallback propagates any non-401\u002F403 server response as\n  permanent too. A 400 behind nginx now fails fast instead of looping.\n- The outbox sweep **quarantines permanently-rejected files on the first\n  attempt** instead of burning retry budget — a poison message no longer\n  retries 12× over 17h (the incident that motivated this contract).\n\nVerification pattern: send a live poison message (lowercase subject), assert\nexactly one rejection and zero outbox writes (US-001, 8\u002F8 tests, commit\n`4dd90223`).\n\n## Forwarder: role-aware PEER resolution (2026-08-03)\n\n**Symptom:** Esther's `orch-bus-forwarder.py` silently self-synced (Esther↔Esther) — the \"mirror of Moses' bus\" never existed, and the forwarder skipped sync since Jul 31 (`peer_downed_at` stuck).\n\n**Root cause:** `PEER_URL` defaulted to `FLEET_BUS_FALLBACK_URL` — which on Esther's host is HER OWN external URL (`:14004`). The fallback URL is \"my bus when primary is down\", NOT \"the other orchestrator\".\n\n**Fix (commit `fc9aafdb`):** role-aware peer resolution in both module-level and `main()` config resolution:\n- On **Esther**: peer = Moses = `FLEET_BUS_URL` (`:13004`)\n- On **Moses**: peer = Esther = `FLEET_BUS_FALLBACK_URL` (`:14004`)\n- `PEER_AUTH` falls back to `FLEET_BASIC_AUTH` (nginx Basic creds — external peer = nginx, Bearer gets 401)\n\n**Verify:** run the forwarder; state file `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` should show `peer_downed_at` cleared and \"Peer recovered — drained N→local, N→peer\".\n\n**Config resolution (commit `c8c54b4b`, 2026-08-05):** the forwarder reads its\nconfig (LOCAL_URL\u002FTOKEN, PEER_URL\u002FAUTH\u002FTOKEN) in **env → `.env` →\n`~\u002Fsteadfaste-fleet\u002F.env`** order. Before this fix it read `os.environ` ONLY\ndespite the docstring claiming conf\u002F.env fallback — so cron runs (no env)\nresolved empty `PEER_URL`\u002F`PEER_AUTH`\u002F`LOCAL_TOKEN` and the LOCAL→PEER drain\nfailed silently (failover messages sat on the backup bus even after the primary\nreturned). Symptom: `orch-bus-forwarder-sync` cron reports `LOCAL→PEER: N\nfailed` every tick, or `total_local_to_peer` stops advancing. Fix keeps every\nconfig key resolvable from the conf in a bare env; `_load_config_file` \u002F\n`_resolve_var` are defined above the config block (were after use — NameError\nat import). Verify: run the forwarder in a bare env and confirm `PEER_URL`\nresolves from `.env`; a manual drain run pushes stranded messages\n(`total_local_to_peer` increments) and worker inboxes empty locally.\n\n**ACL prerequisite (2026-08-03):** the backup orchestrator's `orch-bus-forwarder`\nmirrors ALL `inbox_*` queues to the peer, so its `bus.permissions` row on the\nPRIMARY's bus needs every inbox queue in `can_read` + `can_write`. Without it,\nLOCAL→PEER drain fails with `403 — Agent 'esther' does not have write access to\nqueue 'inbox_gisu'` (per-queue ACL at `core\u002Ffleet_bus\u002Fserver.py`\n`_check_permission`). Grant SQL: `docs\u002Festher-bus-setup.md` Step 7. Symptom:\n`orch-bus-forwarder-sync` cron alerts `LOCAL→PEER: N failed` every tick while\nthe messages sit in the local queues indefinitely.\n\n## Dedup: consumed copies are never re-forwarded (2026-08-12)\n\n**Symptom:** a single `fleet send gisu EXEC \"…fleet-doctor.py…\"` produced **3\nidentical EXECs** in `inbox_gisu` with the same `correlation_id`\n(`send-ba7f68e22d6a`) at 00:04\u002F00:06\u002F00:11 KST. Gisu's handler archived all\nthree (corr-idempotent), but the duplicate-delivery race left a task row\npending ~10h. The same window showed duplicated UPDATE_REQUESTs \u002F EXECs on\n**every** agent's inbox (joseph 3×, kustos\u002Ftitus\u002Fmoses 2–3×).\n\n**Root cause:** `_sync_direction` in `orch-bus-forwarder.py` skipped a message\nwhose dedup key already existed on the destination **without recording it in\n`seen`** — the old comment said \"the mirror should warm it again next tick\".\nBut when the real consumer (the worker's `agent-message-handler`) archives the\ndestination copy, the next tick re-forwarded the lingering backup copy back to\nthe primary: fresh `msg_id`, same `corr`. Repeat every consumer tick.\n\n**Fix:** the dest-hit skip now does `seen.add(dkey)` — each logical message\nforwards at most once per direction per host. A consumed copy is a DELIVERED\nmessage, not a gap to re-warm. Regression test:\n`tests\u002Ftest-bus-forwarder-dedup.py` (RED on old code, GREEN on fix).\n\n**`fleet bus` on hosts without the local bus schema (2026-08-12):** `fleet bus`\nreads the LOCAL Postgres via `docker exec` — on hosts whose `mycortex-postgres`\nlacks `bus.messages`\u002F`bus.queues` (or container down), `cmd_bus` used to\ntraceback with `UnboundLocalError` because the queue-summary block was skipped.\nFixed in `6876e47c`: `total_pending`\u002F`total_proc` initialized up front,\n`local_db_ok` flag set on error, and the final branch prints\n`⚠️ Local bus DB unavailable` instead of crashing or a false \"No activity\".\n`fleet bus --all` never crashed (different branch) — that's why it slipped\nthrough. The remote bus itself is healthy; use `fleet status`\u002F`fleet depth` for the\nfleet view.\n\n**Inspect for duplicates** (per-agent, recent window):\n```bash\ncd ~\u002Fsteadfaste-fleet\u002Fops\u002Fscripts && python3 -c \"\nimport sys, json; sys.path.insert(0, '.')\nfrom lib.fleet_bus import bus_archives\nfor a in ('gisu','joseph','kustos','titus','moses'):\n    arch = bus_archives(f'inbox_{a}', limit=400, since_minutes=720)\n    corrs = {}\n    for m in arch:\n        b = m.get('body') or {}; c = b.get('correlation_id') or '?'\n        corrs.setdefault((c, b.get('subject')), 0)\n        corrs[(c, b.get('subject'))] += 1\n    dups = {k: v for k, v in corrs.items() if v > 1}\n    print(a, 'duplicates:', len(dups))\n\"\n```\n\n## Token rotation (Bearer, `hbus_*`)\n\n- **Hash scheme:** `bus.tokens.token_hash` = `hashlib.pbkdf2_hmac(\"sha256\", token, b\"hermes-bus-salt\", 100000).hex()` (`core\u002Ffleet_bus\u002Fauth.py hash_token`).\n- **Rotate:** generate `\"hbus_\" + secrets.token_hex(32)` → update `~\u002Fsteadfaste-fleet\u002F.env` AND `~\u002Fsteadfaste-fleet\u002F.env` (both carry `FLEET_BUS_TOKEN`; the forwarder's `LOCAL_TOKEN` reads the conf) → `UPDATE bus.tokens SET token_hash='\u003Cpbkdf2(new)>', rotated_at=NOW() WHERE agent_name='\u003Cagent>'` → verify Bearer against the LOCAL bus (`127.0.0.1:8903`): new → 200, old → 401.\n- **Verify Bearer on the LOCAL bus only.** Testing Bearer against the external nginx port (`:13004`\u002F`:14004`) is meaningless — nginx validates Basic auth and sets `X-Forwarded-User`; a Bearer header sent through nginx is ignored (401 for missing Basic). A token that \"401s\" through nginx can still be LIVE on the local bus.\n- **Never delete `FLEET_BUS_TOKEN` from `.env` because Bearer \"401s through nginx\".** The local raw bus (`127.0.0.1:8903`) REQUIRES that Bearer token; a 401 through nginx only proves the request lacked Basic auth. Removing it silently breaks every local-bus consumer — `orch-bus-forwarder` exits 1 with `LOCAL_URL and LOCAL_TOKEN required`, `orch-bus-inbox-relay` prints `cannot relay`, the confirmation-poller goes deaf. The systemd bridge runner (`fleet-bus-bridge-run.py`) returns 0 regardless of the script's exit code, so the timer shows `success` while the job crashes — the tells are a FROZEN `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` `last_run` and a growing BACKUP-bus `inbox_orchestrator` depth (stale-mirror sweep stopped). Restore the token (verify against `127.0.0.1:8903` → 200), then re-run the forwarder.\n- **Identity mapping pitfall:** a token found in another agent's docs\u002Fconfig may be a DIFFERENT agent's row — the esther setup guide carried MOSES' token (esther's `.env` seeded with it), so it authenticated as moses with full queue privileges. Before rotating, look up the identity by hash: `SELECT agent_name FROM bus.tokens WHERE token_hash='\u003Cpbkdf2(leaked)>' AND is_active=true`. Rotate the MAPPED row (or sync it to the owner's real token hash).\n- **Peer-bus consistency:** each orchestrator's Postgres is independent; if the peer's token row on your bus doesn't match his real token, sync it from his bus (`SELECT token_hash FROM bus.tokens WHERE agent_name='moses'` on his host, then UPDATE your row) so a leaked token dies on your bus too.\n- **Rotation order (configs first):** update consumer configs (`.env`, `.env`) BEFORE the token table so the forwarder\u002FMCP never hit a dead token mid-rotation.\n\n## Stale-mirror sweep — backup bus no longer grows forever (2026-08-14)\n\n**Symptom:** `inbox_orchestrator` (or any `inbox_*`) on the BACKUP orchestrator's\nbus accumulates pending messages monotonically — 74→94→196 over days, 3rd\nfleet sighting (joseph escalation). The primary bus stays clean; the backup's\nown queue-depth watchdogs never cover it (depth-watchdog checks only own\ninbox; confirmation-poller checks only the primary URL).\n\n**Root cause:** the backup bus is a warm-standby MIRROR: the forwarder copies\npending messages from the primary (PEER→LOCAL) and nothing consumes them while\nthe primary is up (the backup's handler polls the primary by design). The\n2026-08-12 dedup fix (record dest-hit in `seen`) stopped duplicate\nre-forwarding but stranded every mirrored-back copy forever: a copy whose\ndedup key was in `seen` was skipped every tick and NEVER archived.\n\n**Fix (commit `ea833284`):** stale-mirror sweep in `_sync_direction` — on a\nBACKUP source (`can_archive_source=True`), a copy whose key is already in\n`seen` (forwarded once or dest-hit-confirmed) is archived once the peer\nCONFIRMS it no longer holds the original (consumed). Failover-safe:\n`_dest_has_key` is tri-state (True\u002FFalse\u002FNone); a copy is kept when the\noriginal is still pending on the primary, or when the peer is unreachable\n(None — never archive blind during an outage; the local copy may be the only\nsnapshot of an unconsumed message). Tests 4-6 in\n`tests\u002Ftest-bus-forwarder-dedup.py` (RED on old code, GREEN on fix).\n\n**Diagnostic:** `SELECT queue_name, state, COUNT(*) FROM bus.messages GROUP BY 1,2`\non the backup's Postgres — a growing `pending` count of `topic='reports'`\nmirrors (skill\u002Flearning reports, each ×2: original + mirror) is the signature.\n\n### Forwarder must rewrite `from` to match the forwarding agent's auth identity\n\n**Symptom:** forwarder-sync cron reports `PEER->LOCAL: N failed` with\n`400 Invalid message: from 'moses' does not match authenticated agent 'esther'`.\n\n**Root cause:** the forwarder copies messages from the peer bus and sends them\nto the local bus preserving the original sender's `from` field. The destination\nbus validates `from` against the authenticated agent — when Esther's forwarder\nforwards Moses' messages, it authenticates as `esther` but sends `from: moses`.\n\n**Fix:** two changes in `orch-bus-forwarder.py`:\n\n1. **Resolve `LOCAL_AGENT` from `agent.env`** at module load — reads\n   `~\u002F.steadfaste-fleet\u002Fagent.env` for `AGENT_NAME=`. Falls back to `\"unknown\"`\n   if the file is missing.\n\n2. **Before `_send_bus()`**, rewrite `body[\"from\"]` to `LOCAL_AGENT` and\n   preserve the original sender as `body[\"forwarded_from\"]`:\n\n```python\noriginal_from = body.get(\"from\", \"\")\nif original_from and original_from != LOCAL_AGENT:\n    body[\"forwarded_from\"] = original_from\n    body[\"from\"] = LOCAL_AGENT\n```\n\n**Why `forwarded_from`:** consumers that need to know who actually sent the\nmessage (e.g. the orchestrator processing a worker's escalation) can read\n`forwarded_from`. The old approach (just `body[\"from\"] = _HOST`) lost the\noriginal sender identity entirely.\n\n**Envelope allowlist:** the bus server's `ENVELOPE_KEYS` in\n`core\u002Ffleet_bus\u002Fvalidate.py` includes `forwarded_from` — the field passes\nvalidation and does not trigger \"unknown envelope field\" rejection. Without\nthis, a forwarded message with `forwarded_from` gets **400**.\n\n**Detection:** check the forwarder cron output for \"Invalid message: from 'X'\ndoes not match authenticated agent 'Y'\" errors. The fix applies to both\nPEER->LOCAL and LOCAL->PEER directions since both authenticate as the\nforwarding agent.\n\n## Shared orchestrator inbox (`inbox_orchestrator`, 2026-08-03)\n\nWorkers' fix requests to `inbox_moses` are **invisible to Esther** — each agent\nonly polls its own inbox. The backup orchestrator literally cannot see worker\nescalations when the primary is down. Fix: a shared `inbox_orchestrator` queue\nboth orchestrators read\u002Fwrite — now the **default target** for all agent →\norchestrator traffic:\n\n- **Schema:** `core\u002Ffleet_bus\u002Fschema\u002Fauth.sql` seeds the queue idempotently (also auto-creates on first send)\n- **Handler:** `agent-message-handler.py` on orchestrators polls `inbox_orchestrator` as a secondary queue — **archive from the SOURCE queue** (`source_queue`, not the hardcoded own-inbox name)\n- **Workers:** `contact-orchestrator.sh` defaults to `inbox_orchestrator` (override with `FLEET_INBOX_TARGET` only for point-to-point replies)\n- **Docs:** ACL table in `docs\u002Fbus-architecture.md` + `docs\u002Freference\u002Ffleet-bus-config.md` (orchestrators read `inbox_orchestrator`; workers `can_send` it)\n\n**ACL model:** BOTH buses use the canonical **per-queue array** ACLs\n(`can_read`\u002F`can_write` `TEXT[]` + `is_admin`) in `bus.permissions` — unified\n2026-08-04. The old boolean model (`can_send`\u002F`can_archive`\u002F`can_requeue`,\n`ops\u002Fservices\u002Ffleet-bus\u002Fserver.py`) is **deleted**. If a 403 appears, check\nthe agent's `can_write` array, not boolean flags.\n\n### Reading a pending message's FULL body (evaluating an inbox message)\n\nThe peek responses carry METADATA only (`msg_id`, `from`, `subject`,\n`correlation_id`) — but the raw `\u002Fapi\u002Fpgmq\u002Fpeek\u002F\u003Cqueue>` response DOES include\neach message's `body` (the MCP tool trims it). To evaluate a pending request\n(an escalation, a handoff, a SKILL_DRIFT_RECOVERY_REQUEST), three rules decide\nwhere the body is and how to read it:\n\n- **Read it with `curl -u \"$FLEET_BASIC_AUTH\" \"$FLEET_BUS_URL\u002Fapi\u002Fpgmq\u002Fpeek\u002F\u003Cqueue>?limit=100\"`\n  and parse `messages[].body`.** Basic auth, not Bearer: nginx on the external\n  URL ignores Bearer and requires Basic; the Bearer token only works on the\n  local raw bus.\n- **Peer-enqueued messages are NOT in the local store.** For the BACKUP\n  orchestrator, `FLEET_BUS_URL` points at the PEER's bus (esther → moses\n  `:13004`), so a psql query against the local `mycortex-postgres` or a curl to\n  the local `:8903` returns NOTHING for a message the MCP peek just showed —\n  that reads as \"not found\" but means \"on the peer\". Curl the URL the MCP\n  actually talks to (`FLEET_BUS_URL`), never the local bus, to find a\n  peer-enqueued message.\n- **A message that vanished from peek moved to ARCHIVES — check who consumed it\n  before acting.** `\u002Fapi\u002Fpgmq\u002Farchives\u002F\u003Cqueue>` carries `archived_at`; a\n  freshly-archived request means the orchestrator handler (or the peer) already\n  took it. Verify the work is not in flight on their side (git log, working\n  tree, an unmerged diff) before duplicating it — acting on a copy whose\n  original was consumed is how two sessions race to land the same change.\n\n### `fleet send`: the self-test gate, and which subjects reach an agent\n\n- **Every send to a fleet agent is REFUSED until the identical flow ran on\n  yourself.** `fleet send \u003Cagent> \u003Csubject> \u003Cbody>` demands: send to your\n  own agent, run `agent-message-handler.py --once`, verify the handler\n  processed it, then re-send with `--self-tested`. That gate proves the\n  TRANSPORT — it says nothing about whether the subject has correct\n  semantics, so a passing self-test does not mean the message will reach\n  the agent's session.\n- **Unknown subjects bounce: the handler archives the message and answers\n  with an error result — it never reaches the agent's session.** Sending\n  an ad-hoc subject (a grant notice, a custom request label) produces\n  exactly that bounce. The subjects that reach an agent are the protocol\n  set (`EXEC`, `UPDATE_REQUEST`, `TASK_REQUEST`, ...) plus `FLEET_NOTICE`,\n  which the handler explicitly notifies + archives + answers\n  `FLEET_NOTICE_RESULT` on. For an informational message to a worker, use\n  `FLEET_NOTICE`, and afterwards verify the msg_id is PENDING in the\n  target queue (peek), never trusting the send confirmation alone.\n\n## Bus tokens silently expire at T+90d — rotation does NOT refresh `expires_at` (2026-10-14)\n\n**Symptom:** every authenticated endpoint on the LOCAL bus returns\n`401 {\"detail\":\"Invalid or expired token\"}` for a token that is correct, while\n`GET \u002Fhealth` still returns 200 (it is unauthenticated). Downstream: the\norch-bus-forwarder's LOCAL leg silently returns 0 messages (`_peek_bus` maps a\nnon-200 to `[]`), so LOCAL→PEER never drains and the mirror looks idle;\n`bus-inbox-inspect.py` reports `inspection_error: queue fetch failed: 401` for\nthe local bus; the bridge runner still exits 0 (it ignores the script's exit\ncode), so systemd shows `success`.\n\n**Diagnosis:** query the token table, not the HTTP layer — `expires_at` is the\nusual culprit and `is_active` stays true:\n```bash\n# psycopg from the bus venv is the reliable route when `docker exec` is\n# blocked in cron mode and the host port refuses a raw psql connection.\n~\u002F.hermes\u002Fhermes-agent\u002Fvenv\u002Fbin\u002Fpython3 - \u003C\u003C'PY'\nimport psycopg\nc=psycopg.connect(host='127.0.0.1',port=15432,dbname='mycortex',user='mycortex',password='\u003CFLEET_BUS_PG_PASS>')\nwith c.cursor() as cur:\n    cur.execute(\"SELECT agent_name,is_active,rotated_at,expires_at,(expires_at\u003C=now()) FROM bus.tokens ORDER BY expires_at\")\n    [print(r) for r in cur.fetchall()]\nPY\n```\nCompare `hash_token(\u003CFLEET_BUS_TOKEN>)` (`core\u002Ffleet_bus\u002Fauth.py`) with the\nrow's `token_hash` to confirm the secret is right and only the expiry is stale.\n\n**Root cause (two layers):**\n1. `issue_token_for_agent()`'s `ON CONFLICT (agent_name) DO UPDATE` refreshes\n   `token_hash`\u002F`rotated_at` but **not** `expires_at` — a row inserted\n   2026-07-16 (default `now() + INTERVAL '90 days'`) keeps that original expiry\n   forever, so every rotation silently inherits the first row's deadline. All\n   rows seeded on the same day expire at the same instant.\n2. `ops\u002Fscripts\u002Ftoken-expiry-alert.py` exists but was never wired to a cron or\n   timer, so the pre-expiry warning never fired — the first signal is the T+90d\n   hard failure.\n\n**Fix (restore, per agent):**\n```sql\nUPDATE bus.tokens SET expires_at = GREATEST(rotated_at, created_at) + INTERVAL '90 days'\nWHERE agent_name = '\u003Cagent>' RETURNING agent_name, expires_at;\n```\nVerify: Bearer `GET \u002Fapi\u002Fpgmq\u002Fqueues` → 200, then run the deployed forwarder via\n`fleet-bus-bridge-run.py --name orch-bus-forwarder-sync --script\norch-bus-forwarder.py --deliver local` and confirm `total_local_to_peer`\nadvances in `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` (proves the LOCAL\nwrite path, not just the DB row). Real fix for the class: add\n`expires_at = now() + INTERVAL '90 days'` to the `ON CONFLICT` clause, and\nschedule `token-expiry-alert.py` daily.\n\n**Do not \"fix\" this by deleting `FLEET_BUS_TOKEN`** — the local bus legitimately\nrequires it; extend\u002Frotate instead.\n\n## References\n\n- `references\u002Fforwarder-peer-resolution.md` — role-aware PEER fix detail (2026-08-03)\n- `references\u002Fcredential-rotation.md`, `references\u002Fdlq-monitor-fix.md`, `references\u002Fcross-server-architecture.md` — may exist on orchestrator hosts only (check `ls ~\u002F.hermes\u002Fskills\u002Fdevops\u002Ffleet-bus\u002Freferences\u002F` first)\n- `core\u002Ffleet_bus\u002Fqueue.py` — Queue creation, DLQ logic, send\u002Fread\u002Farchive\n- `core\u002Ffleet_bus\u002Fserver.py` — HTTP API, auth, dashboard\n","\u003C!-- renamed from skills\u002Fdevops\u002Fcortex-bus\u002FSKILL.md in the cortex-to-fleet sweep; content predates the range (commit 353c3d54) -->\n\n\n# Agent Bus — PGMQ Operations\n\n## Overview\n\nThe Agent Bus is a Postgres-native message queue (`lib\u002Fpgmq` implementation with `SKIP LOCKED`) running on port `:8903`, proxied through nginx. All inter-agent communication flows through it. It replaces the old file-based agent inbox.\n\n> **📐 Architecture reference:** `docs\u002Freference\u002Ffleet-bus-config.md`, `docs\u002Fbus-architecture.md`, `docs\u002Forch-bus-setup.md`, `docs\u002Festher-bus-setup.md` — these live on the **orchestrator hosts' private repo** (moses\u002Festher) and may NOT exist on this host or in the public repo. Check before opening: `ls ~\u002Fsteadfaste-fleet\u002Fdocs\u002Freference\u002Ffleet-bus-config.md 2>\u002Fdev\u002Fnull || echo \"not on this host — request from orchestrator via inbox_orchestrator\"`. This skill covers operational diagnostics only.\n\n> **⚠️ Postgres access (post-2026-08-05 migration):** the `legacy Postgres`\n> container was replaced by **`mycortex-postgres`** (role\u002Fdb **`mycortex`**,\n> port still `:15432`). All psql examples below use the new container\u002Frole:\n> `sg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex ...\"`.\n> The old `mycortex` role does NOT exist in the new container — using it fails\n> with `FATAL: role \"mycortex\" does not exist`.\n\nKey architectural facts:\n- **Bus server** processes at `~\u002Fsteadfaste-fleet\u002Fcore\u002Ffleet_bus\u002Fserver.py` (module `fleet_bus.server:app`, service `fleet-bus.service`)\n- **Queue module** at `~\u002Fsteadfaste-fleet\u002Fcore\u002Ffleet_bus\u002Fqueue.py`\n- **Postgres schema** `bus.*` in the shared mycortex database (`:15432`)\n- **MCP tools** `mcp__fleet_bus__*` route through the bus via HTTP\n- **Health check**: `curl http:\u002F\u002F127.0.0.1:8903\u002Fhealth` returns 200\n- **Bearer token auth**: token from `FLEET_BUS_TOKEN` in `.env`\n\n## When to Use\n\n- Diagnosing message delivery failures between agents\n- Inspecting queue depth or DLQ buildup\n- Recovering stuck `processing` messages\n- Fixing bus auth or permission issues\n- Investigating why an agent isn't receiving messages\n\n## Message Contract (strict input formatting)\n\nEvery `\u002Fapi\u002Fpgmq\u002Fsend` is validated at ingestion (2026-09-02, anti-poisoning\u002Fanti-spam at fleet scale). Violations → **400 + reason**; over quota → **429**.\n\n| Field | Rule |\n|-------|------|\n| `from` | Required, lowercase agent name, **must equal the authenticated sender** (spoofing rejected with 400 `\"from '\u003CX>' does not match authenticated agent '\u003CY>'\"`) |\n| `subject` | Required, `^[A-Z][A-Z0-9_]{0,63}$` (`EXEC`, `PING`, `DOCTOR_TEST`, …) |\n| `body` | Required, object or string |\n| `to` \u002F `correlation_id` \u002F `timestamp` \u002F `type` \u002F `priority` \u002F `forwarded_from` | Optional; `priority` **int** 0-100 — string values (`\"normal\"`, `\"urgent\"`) are rejected with 400. Map via dict before sending. `forwarded_from` set by the bus forwarder when relaying a message between bus instances (preserves the original sender). |\n| Unknown keys | **Rejected** — no field smuggling |\n| Size | 64 KiB max\u002Fmessage |\n| Rate | 600 sends\u002Fhr\u002Fagent (`FLEET_BUS_RATE_LIMIT_PER_HOUR`), sliding window |\n\n`workflow_step_result` queue uses its own schema (`workflow_id` `step_id` `status` `result` `error`) — agents post step results without an envelope.\n\nImplementation: `core\u002Ffleet_bus\u002Fvalidate.py` + `core\u002Ffleet_bus\u002Fratelimit.py`, tests in `tests\u002Ftest_bus_validate.py`. Sending messages: use `bus_send()` \u002F the MCP inbox tools — they build conforming envelopes.\n\n## Inbox Message Decision Framework\n\nClassify each inbox message on two axes, then act per the matrix. **Priority** (error=None priority): `critical` | `urgent` | `normal` | `notification`. **Scope**: `Simple (\u003C3 items)` | `Moderate (3–10)` | `Complex (>10)` | `Multi-agent`.\n\n| Prio → | Simple | Moderate | Complex | Multi-agent |\n|--------|--------|----------|---------|-------------|\n| critical | AUTO-ACT | AUTO-ACT | AUTO-ACT + notify | Delegate + notify |\n| urgent | AUTO-ACT | AUTO-ACT | AUTO-ACT + report | Delegate + report |\n| normal | AUTO-ACT | AUTO-ACT | Escalate | Escalate |\n| notification | Acknowledge | Acknowledge | Acknowledge | Forward |\n\n**After-action:** deliver what was done, how it was verified, the evidence, and the cycle ID.\n\n## Diagnosing Bus State\n\n### 1. Queue Overview\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count\nFROM bus.messages\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\"\n```\n\nShows every queue with its message counts broken down by state:\n\n| State | Meaning |\n|-------|---------|\n| `pending` | Ready for dequeue — normal state |\n| `processing` | Currently dequeued, within visibility timeout |\n| `archived` | Successfully processed (or auto-archived) |\n\n### 2. DLQ Inspection (Dead Letter Queue)\n\nMessages that exceeded `max_retries` (default 3) move to `{queue}_dlq`. DLQ messages older than 6 hours are auto-archived by `bus.recover_timeouts()`.\n\n```bash\n# DLQ depth by queue\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest\nFROM bus.messages\nWHERE queue_name LIKE '%dlq%'\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\"\n\n# DLQ message content — who sent it, what about, how many retries\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT \n    queue_name,\n    COALESCE(body->>'from', '(empty)') as sender,\n    body->>'subject' as subject,\n    body->>'topic' as topic,\n    retry_count,\n    error,\n    enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending' AND queue_name LIKE '%dlq%'\nORDER BY queue_name, enqueued_at DESC\nLIMIT 50;\n\\\"\"\n```\n\n### 3. Check Queue Schema Integrity\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT name, is_dlq, parent_queue, max_retries FROM bus.queues ORDER BY name;\n\\\"\"\n```\n\nEvery queue ending in `_dlq` MUST have `is_dlq = true`. If false, the auto-archive and chain-deletion break silently.\n\n### 4. Run Recovery\n\n```bash\n# Returns count of messages recovered\u002Farchived\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT bus.recover_timeouts();\n\\\"\"\n```\n\nThe `recover_timeouts()` function does three things:\n1. **Recovers** processing→pending for messages below `max_retries`\n2. **Moves** over-retry processing messages to DLQ (or deletes if already in a DLQ)\n3. **Auto-archives** DLQ messages older than 6 hours\n\n### 5. Interpreting Recovery Counts\n\nThe `orch-bus-recover-timeouts` cron (every 5m) calls `bus.recover_timeouts()` and reports results. The **silent threshold is 50** — below that, no notification is sent (routine timeouts are normal).\n\n| Recovery count | Meaning |\n|----------------|---------|\n| 0–5 | Normal — routine visibility timeouts |\n| 5–50 | Mild backlog — catching up, no action needed |\n| 50+ | Moderate+ backlog — worth investigating |\n\n### 6. Normal DLQ Baselines\n\nDLQ messages \u003C 6 hours old are normal — they auto-archive on each `recover_timeouts()` tick.\n\n| DLQ depth | State |\n|-----------|-------|\n| \u003C 50 | Normal — transient backlog |\n| 50–200 | Moderate — check sender breakdown |\n| 200+ | Elevated — investigate with DLQ content query (section 2) |\n\nIf messages older than 6 hours are present, `is_dlq` may be broken (see Common Issues below).\n\nThe threshold (50) is set in `ops\u002Fscripts\u002Forch-bus\u002Forch-bus-recover-timeouts.sh` as `RECOVER_THRESHOLD=50`.\n\n### 7. Health Report Monitoring (`orch-bus-confirmation-poller.py report`)\n\nThe `orch-bus-confirmation-alert` cron (every 60m) runs `orch-bus-confirmation-poller.py report` producing a combined bus health report covering message tracker status + queue depths + DLQ health.\n\n**Report behaviour:**\n- **Silent when healthy** — no output if no DLQ backlog, no overdue confirmations, no pending messages. Zero stdout = zero notification.\n- **Alerts on DLQ backlog** — checks both `depth` (pending) AND `processing` state in DLQ queues. Messages stuck in processing count as a backlog.\n- **Reports on overdue confirmations** — tracked messages past their confirmation deadline.\n\n**Common gotcha — processing messages in DLQ hidden from alerts:**\nThe DLQ alert code in `cmd_report()` at `ops\u002Fscripts\u002Forch-bus\u002Forch-bus-confirmation-poller.py` initially only checked `depth > 0` for DLQ queues. Messages in `processing` state were invisible. The fix adds `or processing > 0` to both the marker and `dlq_issues` detection.\n\n```python\n# Before (missed processing messages):\nmarker = \" ⚠️ DLQ\" if is_dlq and depth > 0 else \"\"\nif depth > 0: dlq_issues.append(name)\n\n# After (checks both):\nmarker = \" ⚠️ DLQ\" if is_dlq and (depth > 0 or processing > 0) else \"\"\nif depth > 0 or processing > 0: dlq_issues.append(name)\n```\n\n**Silent-when-clean pattern** — the report collects all data first, then only prints if there's something to report:\n\n```python\n# At the end of data collection:\nif not overdue and not dlq_issues and not pending:\n    return  # completely silent\n```\n\n### 8. Cron Alert Design: Silent-When-Clean\n\nA general principle for no_agent cron scripts that produce health\u002Fstatus reports:\n\n- **No output = no notification.** The user should only hear from a cron when there's something to act on.\n- **Collect data first, print only if there's a signal.** Build the entire report into variables (`queue_lines`, `dlq_issues`), then check whether anything needs attention before printing.\n- **Silence is the default, not a special mode.** The healthy state should produce zero stdout. Don't print \"✅ All clean\" — that's noise.\n- **Thresholds belong in the script, not hardcoded in docs.** The `RECOVER_THRESHOLD` variable in the script defines what's actionable. Docs reference the variable name, not the value.\n\nThis pattern applies to: health reports, watchdog crons, depth monitors, alert crons, and any periodically-running agent script that checks system state.\n\n### 9. Stuck Pending Messages at Max Retries\n\nThe `recover_timeouts()` function only moves messages from `processing` → pending\u002FDLQ. Messages that were never dequeued while it ran remain in `pending` with their retry count unchanged. This means **messages can sit in `pending` with `retry_count = max_retries` without ever being promoted to the DLQ**.\n\nThese are truly stuck: the message was dequeued up to max_retries times, timed out each time, but no agent subsequently dequeued it again, so it never re-entered `processing` state for `recover_timeouts()` to catch.\n\n**Detection query:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, retry_count, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest,\n    COALESCE(body->>'from', '(null)') as sender,\n    body->>'subject' as subject,\n    body->>'topic' as topic\nFROM bus.messages\nWHERE state = 'pending'\n  AND retry_count >= (SELECT COALESCE(max_retries, 3) FROM bus.queues WHERE name = bus.messages.queue_name)\nGROUP BY queue_name, retry_count, body->>'from', body->>'subject', body->>'topic'\nHAVING COUNT(*) > 0\nORDER BY COUNT(*) DESC\nLIMIT 20;\n\\\"\" 2>&1\n```\n\n**Remediation:**\n\n⚠️ **`bus.dlq_move(msg_id)` does NOT exist in the schema.** Attempting to call it produces `ERROR: function bus.dlq_move(uuid) does not exist`. Use `bus.archive()` instead.\n\nThe correct approach requires getting the message ID first, then archiving it individually — `bus.archive()` takes a single `msg_id`.\n\n**Step 1 — Get the stuck message IDs:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT msg_id::text, queue_name, body->>'subject' as subject,\n    retry_count, enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending'\n  AND retry_count >= (SELECT max_retries FROM bus.queues WHERE name = bus.messages.queue_name)\n  AND queue_name = 'inbox_target'\nORDER BY enqueued_at;\n\\\"\\\" 2>&1\n```\n\n**Step 2 — Archive each via `bus.archive()` with explicit `::uuid` cast:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nSELECT bus.archive('inbox_target', '\u003Cmsg_id>'::uuid, 'esther-remediation');\n\\\"\\\" 2>&1\n```\n\nRepeat for each stuck message ID. Verify the queue is clean afterward with the detection query from Step 1.\n\n**Bulk fallback (bypasses proper archive function — use only when you're sure all are orphaned):**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nUPDATE bus.messages SET state = 'archived', archived_at = NOW()\nWHERE state = 'pending'\n  AND retry_count >= (SELECT max_retries FROM bus.queues WHERE name = bus.messages.queue_name)\n  AND queue_name = 'inbox_target';\n\\\"\\\" 2>&1\n```\n\n> **Why individual archiving:** `bus.archive()` logs the action via `bus.audit()` and handles DLQ chain metadata correctly. The direct UPDATE is faster for bulk cleanup but skips audit logging — acceptable for known-orphaned messages where you want to clear a backlog fast.\n\n**Root cause:** Target agent stopped dequeuing. The message was picked up by visibility timeout (default 30s), retried, exhausted max_retries, and the agent never dequeued it again. Fix by clearing backlog or restarting the agent's consumer.\n\n### 10. Raw-Field Wrapper Messages\n\nSome bus senders wrap the payload inside a `raw` field, producing messages like:\n```json\n{\"raw\": \"{\\\"from\\\": \\\"moses\\\", \\\"to\\\": \\\"moses\\\", \\\"topic\\\": \\\"health\\\"}\"}\n```\n\nThis means `body->>'from'` evaluates to `NULL` at the top level. The sender data is nested inside `body->'raw'->>'from'` after a JSON decode of the inner string.\n\n**Detection query:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT COUNT(*) as count, queue_name\nFROM bus.messages\nWHERE state = 'pending'\n  AND body->>'from' IS NULL\n  AND body ? 'raw'\nGROUP BY queue_name\nORDER BY COUNT(*) DESC;\n\\\"\" 2>&1\n```\n\n**Reading actual content:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT msg_id, queue_name,\n    body->'raw'->>'from' as actual_sender,\n    body->'raw'->>'subject' as actual_subject,\n    body->'raw'->>'topic' as actual_topic,\n    enqueued_at::timestamptz(0)\nFROM bus.messages\nWHERE state = 'pending'\n  AND body->>'from' IS NULL\n  AND body ? 'raw'\nORDER BY enqueued_at DESC\nLIMIT 20;\n\\\"\" 2>&1\n```\n\n### 11. Fleet-Wide Queue Scan During Inbox Processing\n\nWhen an inbox-processing cron runs, scan all queues for a fleet-wide health picture — even though you can only act on your own queue. This surfaces backlogs in other agents.\n\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT queue_name, state, COUNT(*) as count,\n    MIN(enqueued_at)::timestamptz(0) as oldest,\n    MAX(enqueued_at)::timestamptz(0) as newest\nFROM bus.messages\nGROUP BY queue_name, state\nORDER BY queue_name, state;\n\\\"\" 2>&1\n```\n\nCompare depths:\n- **0:** Clean\n- **1–50:** Normal backlog\n- **50–200:** Moderate — flag in report\n- **200+:** Elevated — escalate\n\n**Note:** PSQL access is via local `sg docker` gateway. For remote agents, use the bus API at `\u002Fapi\u002Fpgmq\u002Fqueues` (lists all queues but not per-message detail).\n\n## Inspecting the bus from a cron\u002Funattended tick (governance-gated shell)\n\nThe governance enforcer classifies `curl …`, `sg docker -c \"docker exec … psql …\"`\nand `execute_code` as WRITE-CLASS, so a cron tick with no active governance lock\ncannot run them — and opening a cycle for a read-only inspection is noise.\nWorking ungated alternatives:\n- `mcp__agent_bus__bus_inbox_peek` — **the non-destructive inspection tool**\n  (`queue`, `limit`, `archived`). It issues only `GET \u002Fapi\u002Fpgmq\u002Fpeek\u002F{queue}` \u002F\n  `\u002Fapi\u002Fpgmq\u002Farchives\u002F{queue}` and never dequeues, so it is safe on a queue another\n  consumer owns; each entry carries `subject` and `correlation_id`, which is what a\n  dispatch RESULT is matched on (the 6-checkpoint rule). Use `archived: true` for a\n  result the handler has already processed — archived messages are invisible to a\n  pending-only peek, which is the usual reason \"the result was never sent\".\n- `mcp__agent_bus__inbox_read` \u002F `inbox_watch` \u002F `inbox_list_agents` — inbox + agent\n  liveness, served over the bus, never gated (they are deferred MCP tools, not shell).\n  **`inbox_read` DEQUEUES** (`POST \u002Fapi\u002Fpgmq\u002Fread`, 60 s visibility timeout) from\n  your own queue only — it is a consuming read, not an inspection primitive, and it\n  can never see another agent's queue or the orchestrator queue.\n- `browser_exec`: `http:\u002F\u002F127.0.0.1:8903\u002Fhealth` is unauthenticated and reports\n  `{\"status\":\"ok\",…,\"queues\":N}`; the dashboard at `\u002F` renders `\u002Fapi\u002Fbus\u002Fdashboard`,\n  `\u002Fapi\u002Fpgmq\u002Fqueues`, `\u002Fapi\u002Fworkflows`, ALL of which need a Bearer token — opened\n  without creds the dashboard shows `ERROR Cannot read properties of undefined\n  (reading 'total')`, which is an auth artifact, NOT a bus fault. `\u002Fmetrics` is 404.\n- Read-only primitives (`ls`, `cat`, `grep`, `find`, `git status\u002Flog\u002Fdiff`) stay\n  lock-free for state files, e.g. `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json`\n  — check `last_run` and `total_local_to_peer`\u002F`total_peer_to_local` to prove the\n  LOCAL write path is alive.\n- **Do not `read_file` `bus-forwarder-state.json`** in full: it is ~770 KB of dedup\n  keys and will flood context — grep it for the three scalar fields instead.\n\n## Common Issues\n\n### DLQ Messages Accumulating Without Auto-Archive\n\n**Symptom:** DLQ depth grows without bound, old messages (6h+) stay in `pending` state.\n\n**Root cause:** The `is_dlq` flag was not set on DLQ queues — `bus.recover_timeouts()` Step 3 (auto-archive) checks `WHERE q.is_dlq = true` and silently skips queues where it's false. Also Step 2 cannot chain-delete exhausted DLQ messages, causing `_dlq_dlq` accumulation.\n\n**Fix:**\n```bash\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nUPDATE bus.queues SET is_dlq = true WHERE name LIKE '%_dlq%' AND is_dlq = false;\n\\\"\" 2>&1\n\n# Run recovery to immediately clear old messages\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -t -c \\\"\nSELECT bus.recover_timeouts();\n\\\"\"\n```\n\nAfter fix, the cron `orch-bus-recover-timeouts` (every 5m) auto-maintains the DLQ. Verify with queue overview query.\n\n**Prevention:** The queue creation code at `core\u002Ffleet_bus\u002Fqueue.py:create_queues_for_agent()` already sets `is_dlq = true` — the bug only affects queues created before the column was added to the schema.\n\n### recover_timeouts Fails with messages_queue_name_fkey (missing DLQ row)\n\n**Symptom:** `orch-bus-recover-timeouts` cron (every 5m) fails with `Script exited\nwith code 1`; running the function directly shows:\n`ERROR: insert or update on table \"messages\" violates foreign key constraint\n\"messages_queue_name_fkey\" — Key (queue_name)=(inbox_orchestrator_dlq) is not\npresent in table \"queues\".`\n\n**Root cause:** a queue exists in `bus.queues` but its `\u003Cqueue>_dlq` row was\nnever seeded. The seed creates `inbox_orchestrator` without its DLQ\n(`core\u002Ffleet_bus\u002Fschema\u002Fauth.sql`, 2026-08-12), while agent inboxes get DLQs\nvia `create_queues_for_agent()`. `recover_timeouts()` Step 2b moves exhausted\nprocessing messages to `queue_name || '_dlq'` — the FK fails and **kills the\nwhole run**, so the cron never recovers anything.\n\n**Fix (2026-08-12):** two layers, both in the repo:\n1. **Seed** — `auth.sql` now inserts `inbox_orchestrator_dlq` (`is_dlq=true`,\n   `parent_queue='inbox_orchestrator'`) next to the shared inbox.\n2. **Defensive** — `recover_timeouts()` Step 2b now auto-creates any missing\n   `_dlq` queue row before the move:\n   ```sql\n   INSERT INTO bus.queues (name, is_dlq, parent_queue)\n   SELECT DISTINCT m.queue_name || '_dlq', true, m.queue_name\n   FROM bus.messages m\n   LEFT JOIN bus.queues q ON q.name = m.queue_name || '_dlq'\n   WHERE q.name IS NULL AND m.state = 'processing'\n     AND m.timeout_at \u003C now() AND m.retry_count >= m.max_retries\n   ON CONFLICT (name) DO NOTHING;\n   ```\n\n**Apply to a live DB** (schema changes deploy via file copy, not auto-applied):\n```bash\nsg docker -c \"docker exec -i mycortex-postgres psql -U mycortex -d mycortex -v ON_ERROR_STOP=1 -f -\" \u003C core\u002Ffleet_bus\u002Fschema\u002Fqueue.sql\nsg docker -c \"docker exec -i mycortex-postgres psql -U mycortex -d mycortex -v ON_ERROR_STOP=1 -f -\" \u003C core\u002Ffleet_bus\u002Fschema\u002Fauth.sql\n```\n\n**Verify:** `SELECT bus.recover_timeouts();` returns a number (not an error), and\n`SELECT name FROM bus.queues WHERE name = '\u003Cqueue>_dlq';` exists for every\nnon-DLQ queue. Check for other missing DLQ rows: `SELECT name FROM bus.queues\nWHERE is_dlq = false AND name || '_dlq' NOT IN (SELECT name FROM bus.queues)`.\n\n**Pitfall — string `priority` rejected with 400.** The bus API expects `\"priority\"` as an **integer** (0-100). Passing `\"normal\"`, `\"urgent\"`, or `\"critical\"` as strings produces a 400. Always map string priorities to int before sending:\n```python\npriority = {\"normal\": 0, \"urgent\": 10, \"critical\": 20}.get(priority_str, 0)\n```\nThe same 400 is returned when the `from` field doesn't match the authenticated user — `\"from 'moses' does not match authenticated agent 'esther'\"`. Each agent must send as themselves, not as another agent.\n\n### All Bus Tools Return 401 (Not 200)\n\nThe MCP bus tools (`mcp__fleet_bus__*`) return HTTP 401 when:\n1. `FLEET_BUS_TOKEN` in `.env` doesn't match the hash in `bus.tokens` table\n2. The token is missing entirely from the PG table\n\n**Diagnostic:**\n```bash\n# Check which tokens exist\nsg docker -c \"docker exec mycortex-postgres psql -U mycortex -d mycortex -c \\\"\nSELECT agent_name, substring(token_hash::text, 1, 20) as token_prefix, rotated_at\nFROM bus.tokens ORDER BY agent_name;\n\\\"\"\n\n# Verify your .env token matches\ngrep FLEET_BUS_TOKEN ~\u002Fsteadfaste-fleet\u002F.env\n```\n\n### Bus Unreachable (Connection Refused)\n\n**Symptom:** `curl http:\u002F\u002F127.0.0.1:8903\u002Fhealth` fails.\n\n**Check:**\n```bash\n# Is the bus process running?\nss -tlnp | grep 8903\n\n# Is the systemd service active?\nsystemctl --user status fleet-bus.service\n\n# Restart if needed\nsystemctl --user restart fleet-bus.service\n```\n\nNote: The bus at `:8903` is a direct local connection. It's also proxied through nginx at the orchestrator's bus port (e.g. `:13004` for Moses, `:14004` for Esther) with Bearer auth. The MCP tools route through nginx, not directly.\n\n## Client fail-fast on 4xx — BusPermanentError, never outboxed (2026-09-09)\n\n`ops\u002Fscripts\u002Flib\u002Ffleet_bus.py` classifies 4xx responses as PERMANENT, not retryable:\n\n- `lib._bus_post` raises `BusPermanentError` on any 4xx — except 401\u002F403 while the\n  Basic-auth fallback still has a try left.\n- On a permanent rejection `bus_send` returns `{queued: false, permanent: true}`\n  and **never writes the outbox file**. Do not layer retry-on-4xx logic on top:\n  permanent means permanent (bad subject\u002Fformat\u002FACL — e.g. a lowercase subject\n  that `validate.py` rejects with HTTP 400).\n- The inner Basic-auth fallback propagates any non-401\u002F403 server response as\n  permanent too. A 400 behind nginx now fails fast instead of looping.\n- The outbox sweep **quarantines permanently-rejected files on the first\n  attempt** instead of burning retry budget — a poison message no longer\n  retries 12× over 17h (the incident that motivated this contract).\n\nVerification pattern: send a live poison message (lowercase subject), assert\nexactly one rejection and zero outbox writes (US-001, 8\u002F8 tests, commit\n`4dd90223`).\n\n## Forwarder: role-aware PEER resolution (2026-08-03)\n\n**Symptom:** Esther's `orch-bus-forwarder.py` silently self-synced (Esther↔Esther) — the \"mirror of Moses' bus\" never existed, and the forwarder skipped sync since Jul 31 (`peer_downed_at` stuck).\n\n**Root cause:** `PEER_URL` defaulted to `FLEET_BUS_FALLBACK_URL` — which on Esther's host is HER OWN external URL (`:14004`). The fallback URL is \"my bus when primary is down\", NOT \"the other orchestrator\".\n\n**Fix (commit `fc9aafdb`):** role-aware peer resolution in both module-level and `main()` config resolution:\n- On **Esther**: peer = Moses = `FLEET_BUS_URL` (`:13004`)\n- On **Moses**: peer = Esther = `FLEET_BUS_FALLBACK_URL` (`:14004`)\n- `PEER_AUTH` falls back to `FLEET_BASIC_AUTH` (nginx Basic creds — external peer = nginx, Bearer gets 401)\n\n**Verify:** run the forwarder; state file `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` should show `peer_downed_at` cleared and \"Peer recovered — drained N→local, N→peer\".\n\n**Config resolution (commit `c8c54b4b`, 2026-08-05):** the forwarder reads its\nconfig (LOCAL_URL\u002FTOKEN, PEER_URL\u002FAUTH\u002FTOKEN) in **env → `.env` →\n`~\u002Fsteadfaste-fleet\u002F.env`** order. Before this fix it read `os.environ` ONLY\ndespite the docstring claiming conf\u002F.env fallback — so cron runs (no env)\nresolved empty `PEER_URL`\u002F`PEER_AUTH`\u002F`LOCAL_TOKEN` and the LOCAL→PEER drain\nfailed silently (failover messages sat on the backup bus even after the primary\nreturned). Symptom: `orch-bus-forwarder-sync` cron reports `LOCAL→PEER: N\nfailed` every tick, or `total_local_to_peer` stops advancing. Fix keeps every\nconfig key resolvable from the conf in a bare env; `_load_config_file` \u002F\n`_resolve_var` are defined above the config block (were after use — NameError\nat import). Verify: run the forwarder in a bare env and confirm `PEER_URL`\nresolves from `.env`; a manual drain run pushes stranded messages\n(`total_local_to_peer` increments) and worker inboxes empty locally.\n\n**ACL prerequisite (2026-08-03):** the backup orchestrator's `orch-bus-forwarder`\nmirrors ALL `inbox_*` queues to the peer, so its `bus.permissions` row on the\nPRIMARY's bus needs every inbox queue in `can_read` + `can_write`. Without it,\nLOCAL→PEER drain fails with `403 — Agent 'esther' does not have write access to\nqueue 'inbox_gisu'` (per-queue ACL at `core\u002Ffleet_bus\u002Fserver.py`\n`_check_permission`). Grant SQL: `docs\u002Festher-bus-setup.md` Step 7. Symptom:\n`orch-bus-forwarder-sync` cron alerts `LOCAL→PEER: N failed` every tick while\nthe messages sit in the local queues indefinitely.\n\n## Dedup: consumed copies are never re-forwarded (2026-08-12)\n\n**Symptom:** a single `fleet send gisu EXEC \"…fleet-doctor.py…\"` produced **3\nidentical EXECs** in `inbox_gisu` with the same `correlation_id`\n(`send-ba7f68e22d6a`) at 00:04\u002F00:06\u002F00:11 KST. Gisu's handler archived all\nthree (corr-idempotent), but the duplicate-delivery race left a task row\npending ~10h. The same window showed duplicated UPDATE_REQUESTs \u002F EXECs on\n**every** agent's inbox (joseph 3×, kustos\u002Ftitus\u002Fmoses 2–3×).\n\n**Root cause:** `_sync_direction` in `orch-bus-forwarder.py` skipped a message\nwhose dedup key already existed on the destination **without recording it in\n`seen`** — the old comment said \"the mirror should warm it again next tick\".\nBut when the real consumer (the worker's `agent-message-handler`) archives the\ndestination copy, the next tick re-forwarded the lingering backup copy back to\nthe primary: fresh `msg_id`, same `corr`. Repeat every consumer tick.\n\n**Fix:** the dest-hit skip now does `seen.add(dkey)` — each logical message\nforwards at most once per direction per host. A consumed copy is a DELIVERED\nmessage, not a gap to re-warm. Regression test:\n`tests\u002Ftest-bus-forwarder-dedup.py` (RED on old code, GREEN on fix).\n\n**`fleet bus` on hosts without the local bus schema (2026-08-12):** `fleet bus`\nreads the LOCAL Postgres via `docker exec` — on hosts whose `mycortex-postgres`\nlacks `bus.messages`\u002F`bus.queues` (or container down), `cmd_bus` used to\ntraceback with `UnboundLocalError` because the queue-summary block was skipped.\nFixed in `6876e47c`: `total_pending`\u002F`total_proc` initialized up front,\n`local_db_ok` flag set on error, and the final branch prints\n`⚠️ Local bus DB unavailable` instead of crashing or a false \"No activity\".\n`fleet bus --all` never crashed (different branch) — that's why it slipped\nthrough. The remote bus itself is healthy; use `fleet status`\u002F`fleet depth` for the\nfleet view.\n\n**Inspect for duplicates** (per-agent, recent window):\n```bash\ncd ~\u002Fsteadfaste-fleet\u002Fops\u002Fscripts && python3 -c \"\nimport sys, json; sys.path.insert(0, '.')\nfrom lib.fleet_bus import bus_archives\nfor a in ('gisu','joseph','kustos','titus','moses'):\n    arch = bus_archives(f'inbox_{a}', limit=400, since_minutes=720)\n    corrs = {}\n    for m in arch:\n        b = m.get('body') or {}; c = b.get('correlation_id') or '?'\n        corrs.setdefault((c, b.get('subject')), 0)\n        corrs[(c, b.get('subject'))] += 1\n    dups = {k: v for k, v in corrs.items() if v > 1}\n    print(a, 'duplicates:', len(dups))\n\"\n```\n\n## Token rotation (Bearer, `hbus_*`)\n\n- **Hash scheme:** `bus.tokens.token_hash` = `hashlib.pbkdf2_hmac(\"sha256\", token, b\"hermes-bus-salt\", 100000).hex()` (`core\u002Ffleet_bus\u002Fauth.py hash_token`).\n- **Rotate:** generate `\"hbus_\" + secrets.token_hex(32)` → update `~\u002Fsteadfaste-fleet\u002F.env` AND `~\u002Fsteadfaste-fleet\u002F.env` (both carry `FLEET_BUS_TOKEN`; the forwarder's `LOCAL_TOKEN` reads the conf) → `UPDATE bus.tokens SET token_hash='\u003Cpbkdf2(new)>', rotated_at=NOW() WHERE agent_name='\u003Cagent>'` → verify Bearer against the LOCAL bus (`127.0.0.1:8903`): new → 200, old → 401.\n- **Verify Bearer on the LOCAL bus only.** Testing Bearer against the external nginx port (`:13004`\u002F`:14004`) is meaningless — nginx validates Basic auth and sets `X-Forwarded-User`; a Bearer header sent through nginx is ignored (401 for missing Basic). A token that \"401s\" through nginx can still be LIVE on the local bus.\n- **Never delete `FLEET_BUS_TOKEN` from `.env` because Bearer \"401s through nginx\".** The local raw bus (`127.0.0.1:8903`) REQUIRES that Bearer token; a 401 through nginx only proves the request lacked Basic auth. Removing it silently breaks every local-bus consumer — `orch-bus-forwarder` exits 1 with `LOCAL_URL and LOCAL_TOKEN required`, `orch-bus-inbox-relay` prints `cannot relay`, the confirmation-poller goes deaf. The systemd bridge runner (`fleet-bus-bridge-run.py`) returns 0 regardless of the script's exit code, so the timer shows `success` while the job crashes — the tells are a FROZEN `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` `last_run` and a growing BACKUP-bus `inbox_orchestrator` depth (stale-mirror sweep stopped). Restore the token (verify against `127.0.0.1:8903` → 200), then re-run the forwarder.\n- **Identity mapping pitfall:** a token found in another agent's docs\u002Fconfig may be a DIFFERENT agent's row — the esther setup guide carried MOSES' token (esther's `.env` seeded with it), so it authenticated as moses with full queue privileges. Before rotating, look up the identity by hash: `SELECT agent_name FROM bus.tokens WHERE token_hash='\u003Cpbkdf2(leaked)>' AND is_active=true`. Rotate the MAPPED row (or sync it to the owner's real token hash).\n- **Peer-bus consistency:** each orchestrator's Postgres is independent; if the peer's token row on your bus doesn't match his real token, sync it from his bus (`SELECT token_hash FROM bus.tokens WHERE agent_name='moses'` on his host, then UPDATE your row) so a leaked token dies on your bus too.\n- **Rotation order (configs first):** update consumer configs (`.env`, `.env`) BEFORE the token table so the forwarder\u002FMCP never hit a dead token mid-rotation.\n\n## Stale-mirror sweep — backup bus no longer grows forever (2026-08-14)\n\n**Symptom:** `inbox_orchestrator` (or any `inbox_*`) on the BACKUP orchestrator's\nbus accumulates pending messages monotonically — 74→94→196 over days, 3rd\nfleet sighting (joseph escalation). The primary bus stays clean; the backup's\nown queue-depth watchdogs never cover it (depth-watchdog checks only own\ninbox; confirmation-poller checks only the primary URL).\n\n**Root cause:** the backup bus is a warm-standby MIRROR: the forwarder copies\npending messages from the primary (PEER→LOCAL) and nothing consumes them while\nthe primary is up (the backup's handler polls the primary by design). The\n2026-08-12 dedup fix (record dest-hit in `seen`) stopped duplicate\nre-forwarding but stranded every mirrored-back copy forever: a copy whose\ndedup key was in `seen` was skipped every tick and NEVER archived.\n\n**Fix (commit `ea833284`):** stale-mirror sweep in `_sync_direction` — on a\nBACKUP source (`can_archive_source=True`), a copy whose key is already in\n`seen` (forwarded once or dest-hit-confirmed) is archived once the peer\nCONFIRMS it no longer holds the original (consumed). Failover-safe:\n`_dest_has_key` is tri-state (True\u002FFalse\u002FNone); a copy is kept when the\noriginal is still pending on the primary, or when the peer is unreachable\n(None — never archive blind during an outage; the local copy may be the only\nsnapshot of an unconsumed message). Tests 4-6 in\n`tests\u002Ftest-bus-forwarder-dedup.py` (RED on old code, GREEN on fix).\n\n**Diagnostic:** `SELECT queue_name, state, COUNT(*) FROM bus.messages GROUP BY 1,2`\non the backup's Postgres — a growing `pending` count of `topic='reports'`\nmirrors (skill\u002Flearning reports, each ×2: original + mirror) is the signature.\n\n### Forwarder must rewrite `from` to match the forwarding agent's auth identity\n\n**Symptom:** forwarder-sync cron reports `PEER->LOCAL: N failed` with\n`400 Invalid message: from 'moses' does not match authenticated agent 'esther'`.\n\n**Root cause:** the forwarder copies messages from the peer bus and sends them\nto the local bus preserving the original sender's `from` field. The destination\nbus validates `from` against the authenticated agent — when Esther's forwarder\nforwards Moses' messages, it authenticates as `esther` but sends `from: moses`.\n\n**Fix:** two changes in `orch-bus-forwarder.py`:\n\n1. **Resolve `LOCAL_AGENT` from `agent.env`** at module load — reads\n   `~\u002F.steadfaste-fleet\u002Fagent.env` for `AGENT_NAME=`. Falls back to `\"unknown\"`\n   if the file is missing.\n\n2. **Before `_send_bus()`**, rewrite `body[\"from\"]` to `LOCAL_AGENT` and\n   preserve the original sender as `body[\"forwarded_from\"]`:\n\n```python\noriginal_from = body.get(\"from\", \"\")\nif original_from and original_from != LOCAL_AGENT:\n    body[\"forwarded_from\"] = original_from\n    body[\"from\"] = LOCAL_AGENT\n```\n\n**Why `forwarded_from`:** consumers that need to know who actually sent the\nmessage (e.g. the orchestrator processing a worker's escalation) can read\n`forwarded_from`. The old approach (just `body[\"from\"] = _HOST`) lost the\noriginal sender identity entirely.\n\n**Envelope allowlist:** the bus server's `ENVELOPE_KEYS` in\n`core\u002Ffleet_bus\u002Fvalidate.py` includes `forwarded_from` — the field passes\nvalidation and does not trigger \"unknown envelope field\" rejection. Without\nthis, a forwarded message with `forwarded_from` gets **400**.\n\n**Detection:** check the forwarder cron output for \"Invalid message: from 'X'\ndoes not match authenticated agent 'Y'\" errors. The fix applies to both\nPEER->LOCAL and LOCAL->PEER directions since both authenticate as the\nforwarding agent.\n\n## Shared orchestrator inbox (`inbox_orchestrator`, 2026-08-03)\n\nWorkers' fix requests to `inbox_moses` are **invisible to Esther** — each agent\nonly polls its own inbox. The backup orchestrator literally cannot see worker\nescalations when the primary is down. Fix: a shared `inbox_orchestrator` queue\nboth orchestrators read\u002Fwrite — now the **default target** for all agent →\norchestrator traffic:\n\n- **Schema:** `core\u002Ffleet_bus\u002Fschema\u002Fauth.sql` seeds the queue idempotently (also auto-creates on first send)\n- **Handler:** `agent-message-handler.py` on orchestrators polls `inbox_orchestrator` as a secondary queue — **archive from the SOURCE queue** (`source_queue`, not the hardcoded own-inbox name)\n- **Workers:** `contact-orchestrator.sh` defaults to `inbox_orchestrator` (override with `FLEET_INBOX_TARGET` only for point-to-point replies)\n- **Docs:** ACL table in `docs\u002Fbus-architecture.md` + `docs\u002Freference\u002Ffleet-bus-config.md` (orchestrators read `inbox_orchestrator`; workers `can_send` it)\n\n**ACL model:** BOTH buses use the canonical **per-queue array** ACLs\n(`can_read`\u002F`can_write` `TEXT[]` + `is_admin`) in `bus.permissions` — unified\n2026-08-04. The old boolean model (`can_send`\u002F`can_archive`\u002F`can_requeue`,\n`ops\u002Fservices\u002Ffleet-bus\u002Fserver.py`) is **deleted**. If a 403 appears, check\nthe agent's `can_write` array, not boolean flags.\n\n### Reading a pending message's FULL body (evaluating an inbox message)\n\nThe peek responses carry METADATA only (`msg_id`, `from`, `subject`,\n`correlation_id`) — but the raw `\u002Fapi\u002Fpgmq\u002Fpeek\u002F\u003Cqueue>` response DOES include\neach message's `body` (the MCP tool trims it). To evaluate a pending request\n(an escalation, a handoff, a SKILL_DRIFT_RECOVERY_REQUEST), three rules decide\nwhere the body is and how to read it:\n\n- **Read it with `curl -u \"$FLEET_BASIC_AUTH\" \"$FLEET_BUS_URL\u002Fapi\u002Fpgmq\u002Fpeek\u002F\u003Cqueue>?limit=100\"`\n  and parse `messages[].body`.** Basic auth, not Bearer: nginx on the external\n  URL ignores Bearer and requires Basic; the Bearer token only works on the\n  local raw bus.\n- **Peer-enqueued messages are NOT in the local store.** For the BACKUP\n  orchestrator, `FLEET_BUS_URL` points at the PEER's bus (esther → moses\n  `:13004`), so a psql query against the local `mycortex-postgres` or a curl to\n  the local `:8903` returns NOTHING for a message the MCP peek just showed —\n  that reads as \"not found\" but means \"on the peer\". Curl the URL the MCP\n  actually talks to (`FLEET_BUS_URL`), never the local bus, to find a\n  peer-enqueued message.\n- **A message that vanished from peek moved to ARCHIVES — check who consumed it\n  before acting.** `\u002Fapi\u002Fpgmq\u002Farchives\u002F\u003Cqueue>` carries `archived_at`; a\n  freshly-archived request means the orchestrator handler (or the peer) already\n  took it. Verify the work is not in flight on their side (git log, working\n  tree, an unmerged diff) before duplicating it — acting on a copy whose\n  original was consumed is how two sessions race to land the same change.\n\n### `fleet send`: the self-test gate, and which subjects reach an agent\n\n- **Every send to a fleet agent is REFUSED until the identical flow ran on\n  yourself.** `fleet send \u003Cagent> \u003Csubject> \u003Cbody>` demands: send to your\n  own agent, run `agent-message-handler.py --once`, verify the handler\n  processed it, then re-send with `--self-tested`. That gate proves the\n  TRANSPORT — it says nothing about whether the subject has correct\n  semantics, so a passing self-test does not mean the message will reach\n  the agent's session.\n- **Unknown subjects bounce: the handler archives the message and answers\n  with an error result — it never reaches the agent's session.** Sending\n  an ad-hoc subject (a grant notice, a custom request label) produces\n  exactly that bounce. The subjects that reach an agent are the protocol\n  set (`EXEC`, `UPDATE_REQUEST`, `TASK_REQUEST`, ...) plus `FLEET_NOTICE`,\n  which the handler explicitly notifies + archives + answers\n  `FLEET_NOTICE_RESULT` on. For an informational message to a worker, use\n  `FLEET_NOTICE`, and afterwards verify the msg_id is PENDING in the\n  target queue (peek), never trusting the send confirmation alone.\n\n## Bus tokens silently expire at T+90d — rotation does NOT refresh `expires_at` (2026-10-14)\n\n**Symptom:** every authenticated endpoint on the LOCAL bus returns\n`401 {\"detail\":\"Invalid or expired token\"}` for a token that is correct, while\n`GET \u002Fhealth` still returns 200 (it is unauthenticated). Downstream: the\norch-bus-forwarder's LOCAL leg silently returns 0 messages (`_peek_bus` maps a\nnon-200 to `[]`), so LOCAL→PEER never drains and the mirror looks idle;\n`bus-inbox-inspect.py` reports `inspection_error: queue fetch failed: 401` for\nthe local bus; the bridge runner still exits 0 (it ignores the script's exit\ncode), so systemd shows `success`.\n\n**Diagnosis:** query the token table, not the HTTP layer — `expires_at` is the\nusual culprit and `is_active` stays true:\n```bash\n# psycopg from the bus venv is the reliable route when `docker exec` is\n# blocked in cron mode and the host port refuses a raw psql connection.\n~\u002F.hermes\u002Fhermes-agent\u002Fvenv\u002Fbin\u002Fpython3 - \u003C\u003C'PY'\nimport psycopg\nc=psycopg.connect(host='127.0.0.1',port=15432,dbname='mycortex',user='mycortex',password='\u003CFLEET_BUS_PG_PASS>')\nwith c.cursor() as cur:\n    cur.execute(\"SELECT agent_name,is_active,rotated_at,expires_at,(expires_at\u003C=now()) FROM bus.tokens ORDER BY expires_at\")\n    [print(r) for r in cur.fetchall()]\nPY\n```\nCompare `hash_token(\u003CFLEET_BUS_TOKEN>)` (`core\u002Ffleet_bus\u002Fauth.py`) with the\nrow's `token_hash` to confirm the secret is right and only the expiry is stale.\n\n**Root cause (two layers):**\n1. `issue_token_for_agent()`'s `ON CONFLICT (agent_name) DO UPDATE` refreshes\n   `token_hash`\u002F`rotated_at` but **not** `expires_at` — a row inserted\n   2026-07-16 (default `now() + INTERVAL '90 days'`) keeps that original expiry\n   forever, so every rotation silently inherits the first row's deadline. All\n   rows seeded on the same day expire at the same instant.\n2. `ops\u002Fscripts\u002Ftoken-expiry-alert.py` exists but was never wired to a cron or\n   timer, so the pre-expiry warning never fired — the first signal is the T+90d\n   hard failure.\n\n**Fix (restore, per agent):**\n```sql\nUPDATE bus.tokens SET expires_at = GREATEST(rotated_at, created_at) + INTERVAL '90 days'\nWHERE agent_name = '\u003Cagent>' RETURNING agent_name, expires_at;\n```\nVerify: Bearer `GET \u002Fapi\u002Fpgmq\u002Fqueues` → 200, then run the deployed forwarder via\n`fleet-bus-bridge-run.py --name orch-bus-forwarder-sync --script\norch-bus-forwarder.py --deliver local` and confirm `total_local_to_peer`\nadvances in `~\u002F.steadfaste-fleet\u002Fstate\u002Fbus-forwarder-state.json` (proves the LOCAL\nwrite path, not just the DB row). Real fix for the class: add\n`expires_at = now() + INTERVAL '90 days'` to the `ON CONFLICT` clause, and\nschedule `token-expiry-alert.py` daily.\n\n**Do not \"fix\" this by deleting `FLEET_BUS_TOKEN`** — the local bus legitimately\nrequires it; extend\u002Frotate instead.\n\n## References\n\n- `references\u002Fforwarder-peer-resolution.md` — role-aware PEER fix detail (2026-08-03)\n- `references\u002Fcredential-rotation.md`, `references\u002Fdlq-monitor-fix.md`, `references\u002Fcross-server-architecture.md` — may exist on orchestrator hosts only (check `ls ~\u002F.hermes\u002Fskills\u002Fdevops\u002Ffleet-bus\u002Freferences\u002F` first)\n- `core\u002Ffleet_bus\u002Fqueue.py` — Queue creation, DLQ logic, send\u002Fread\u002Farchive\n- `core\u002Ffleet_bus\u002Fserver.py` — HTTP API, auth, dashboard\n",{"name":5,"author":24,"version":25,"category":26,"metadata":27,"platforms":40,"description":7},"Steadfaste Fleet","1.3.0","devops",{"hermes":28},{"tags":29,"related_skills":37},[30,31,32,33,34,35,36],"bus","pgmq","dlq","messaging","queue","postgres","recovery",[38,39],"system-remediation","steadfaste-fleet-deployment",[41],"linux","main","9dc0e92c5fa81d4db5292b205716e8ea0c00d10e","skills\u002Fdevops\u002Ffleet-bus",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":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill fleet-bus",{"tool":57,"command":58},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill fleet-bus",{"tool":60,"command":61},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill fleet-bus","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-bus\u002FSKILL.md",true,[65,71],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fagent-registry.md","REFERENCE","参考文档",8782,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-bus\u002Freferences\u002Fagent-registry.md",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fforwarder-peer-resolution.md",3233,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-bus\u002Freferences\u002Fforwarder-peer-resolution.md",[76,83,90,97,104,111],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"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",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"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":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"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":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"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":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"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":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"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",[],[]]