From 9fd4696492dffe874f00ce308a8879473e6e743e Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 27 Jul 2026 05:18:26 +1000 Subject: [PATCH] fix(telegram): publish command menu to all scopes, not just default The menu still showed ~60 stale hermes commands (/steer, /reload_mcp, /background) even though SetMyCommands succeeded and logged 8 commands. Telegram resolves a chat's menu by scope specificity rather than by recency: a list registered against all_private_chats wins over the default scope in every DM. We wrote only the default scope, so hermes's older per-scope registrations kept shadowing ours. getMyCommands confirms it -- default held our 8, all_private_chats and all_group_chats each held hermes's ~60. That state lives on Telegram's side, keyed to the bot token, so it survived the migration off hermes and would survive any redeploy. Publish to default, all_private_chats and all_group_chats so the leftovers are overwritten rather than shadowing us. One failing scope no longer aborts the rest. --- .beads/interactions.jsonl | 2 ++ .beads/issues.jsonl | 2 ++ internal/channels/telegram/commands.go | 39 ++++++++++++++++++++------ 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 448f1b5cd..2ffd85f2f 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -143,3 +143,5 @@ {"id":"int-73d136618f699f155055eb438881117a","kind":"field_change","created_at":"2026-07-26T17:44:50.351097372Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.23","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Adversarial review completed across two rounds; all findings fixed and re-verified clean."}} {"id":"int-545cf6991d178c87be720cda75a8cecb","kind":"field_change","created_at":"2026-07-26T17:44:50.845655116Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.41","extra":{"field":"status","new_value":"closed","old_value":"blocked","reason":"Blocking dependency abg.17.16 closed; tool-provider engine work was already implementation-complete and previously reviewed clean."}} {"id":"int-1b6bdffe51700db83938f5128b005a97","kind":"field_change","created_at":"2026-07-26T18:57:43.797683721Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.32","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented via go-telegram/bot v1.22.0 rich messages. gateway.LLMStreamResponder + Router.RouteStream provide the streaming seam (degrades to Route when unset); telegram draft.go streams deltas through sendRichMessageDraft throttled to 700ms; main.go derives blocking and streaming responders from one shared turn impl using runtime.ChatStream. Also removed the markdownToHTML converter from the prior commit -- v1.22 takes Markdown natively and supports tables, so the conversion was unnecessary. 4 RouteStream tests; full suite + golangci-lint clean."}} +{"id":"int-932a44040e5dc8c24f4212f377b16115","kind":"field_change","created_at":"2026-07-26T19:15:22.216249366Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.33","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Shipped in cec0f3e. 16.33: chat.telegram.allowed_user_ids plumbed through config; empty list now DENIES (was: allowed everyone); matches sender from.id not chat id so groups cannot inherit access; rejections logged with sender id; startup warns on empty list. Old TestIsChatAllowed asserted the vulnerable fail-open behaviour and was replaced with fail-closed tests. Sam's id 1312197967 added to carina's config.toml before push. 16.34: SetMyCommands publishes the command list Router actually handles; non-fatal on failure."}} +{"id":"int-51ec484ce6786e942b4127275b3fac4e","kind":"field_change","created_at":"2026-07-26T19:15:22.402251424Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.34","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Shipped in cec0f3e. 16.33: chat.telegram.allowed_user_ids plumbed through config; empty list now DENIES (was: allowed everyone); matches sender from.id not chat id so groups cannot inherit access; rejections logged with sender id; startup warns on empty list. Old TestIsChatAllowed asserted the vulnerable fail-open behaviour and was replaced with fail-closed tests. Sam's id 1312197967 added to carina's config.toml before push. 16.34: SetMyCommands publishes the command list Router actually handles; non-fatal on failure."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index f83780429..5416e22bd 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -53,6 +53,8 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.16.35","title":"Telegram: /restart command to reload gateway config","description":"Operator escape hatch: restart the chat gateway from chat to pick up config changes (notably the allowlist) or recover from a wedged adapter, without shell access to the host.","acceptance_criteria":"/restart is admin-only (allowlisted sender). Re-reads config and restarts the gateway. Replies with the outcome. In-flight agent tasks are not killed.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:42Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:11:42Z","dependencies":[{"issue_id":"archie-core-abg.16.35","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:42Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.16.34","title":"Telegram: register command menu via SetMyCommands","description":"The bot never calls SetMyCommands, so Telegram shows no command menu and the commands the Router implements (/status, /help, /models, /model, /spawn, /approve, /cancel) are undiscoverable. Asking the bot for /commands makes the LLM answer that it has none, which is wrong.","acceptance_criteria":"SetMyCommands is called at startup with the commands the Router actually handles. Failure is logged, not fatal.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:41Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:11:41Z","dependencies":[{"issue_id":"archie-core-abg.16.34","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:41Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16.32","title":"Telegram: stream LLM replies via sendMessageDraft","description":"Chat replies currently block for the whole LLM turn, then arrive as one message. The typing indicator masks the wait but shows no progress. go-telegram/bot exposes SendMessageDraft (see examples/streaming_draft) and ai-sdk's runtime.ChatStream already returns core.StreamResult with a TextStream \u003c-chan string, so both halves exist -- only the gateway seam is missing, since gateway.LLMResponder is func(ctx, Message) (string, error) and cannot emit partial output.","acceptance_criteria":"Gateway exposes an optional streaming responder; Router falls back to the blocking path when unset. Telegram adapter streams deltas into a draft, then finalises with a formatted SendMessage. Draft updates are throttled to respect Telegram rate limits. Streaming failure falls back to a normal send rather than losing the reply.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T18:52:20Z","created_by":"Sam Catlow","updated_at":"2026-07-26T18:57:44Z","started_at":"2026-07-26T18:52:30Z","closed_at":"2026-07-26T18:57:44Z","close_reason":"Implemented via go-telegram/bot v1.22.0 rich messages. gateway.LLMStreamResponder + Router.RouteStream provide the streaming seam (degrades to Route when unset); telegram draft.go streams deltas through sendRichMessageDraft throttled to 700ms; main.go derives blocking and streaming responders from one shared turn impl using runtime.ChatStream. Also removed the markdownToHTML converter from the prior commit -- v1.22 takes Markdown natively and supports tables, so the conversion was unnecessary. 4 RouteStream tests; full suite + golangci-lint clean.","dependencies":[{"issue_id":"archie-core-abg.16.32","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T04:52:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-50z","title":"Enforce typed plugin engine architecture rule","description":"Cement the repository invariant that a plugin engine is a typed capability family with an owning registry/manager and lifecycle semantics, never a generic daemon hook. Add one canonical architecture rule referenced by both AGENTS.md and CLAUDE.md, record it in Beads memory, and add an executable architecture test that prevents drift without touching the concurrently edited secret/config packages.","acceptance_criteria":"A canonical rule defines typed domain contract, owning registry/manager, lifecycle and health expectations, narrow host access, and trust boundaries; AGENTS.md and CLAUDE.md both surface the rule through their shared source; an architecture test fails for generic plugin-hook expansion or an engine interface without a family manager; focused tests and task check pass; fresh adversarial review has no surviving findings.","notes":"Complete. Red proof: architecture test failed on missing canonical rule. Green: internal/plugin tests pass; golangci-lint ./internal/plugin reports zero issues; gofumpt diff is empty. Fresh adversarial review initially found bypassable owner checks and ambiguous trust wording; remediated with signature-linked single-owner validation, negative fixtures (metadata-only, embedded-only, unrelated/split owners, pointer and collection wrappers), and precise trusted-in-process/out-of-process/container language. Final fresh review: zero surviving findings. Full task check was attempted but is currently blocked by concurrent unrelated migrations: gateway fakeTaskCreator still implements CreateTask(context.Context,string) while interface now wants SpawnRequest, and daemon EnqueueIssue callers omit the new eighth argument. No secret/config source was edited by this issue.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:00:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:14:06Z","started_at":"2026-07-26T05:00:43Z","closed_at":"2026-07-26T05:14:06Z","close_reason":"Strict plugin-engine invariant documented in canonical architecture and shared AGENTS/CLAUDE instructions, persisted in Beads memory, mechanically enforced with adversarial negative controls, and independently reviewed with zero findings.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.39","title":"MVP: migrate Hermes profiles, memory, skills, and session state","description":"The copied live Hermes instance contains root plus agile-lead, dev, and local-agent profiles with distinct models, gateways, memories, SOUL prompts, skills, sessions, and cron state. archie-core currently has forge identities but no profile-scoped gateway/tool/memory/workspace composition and no importer. Define the mapping into archie-core identities/profiles and build a one-time idempotent migration plus cutover rehearsal.","acceptance_criteria":"Document and implement the mapping for all copied profiles -- MAPPING DOCUMENTED (docs/prds/hermes-migration-dry-run.md), NOT YET IMPLEMENTED (blocked on abg.36). Import SOUL/USER/MEMORY/skills/session/cron without secrets -- NOT STARTED (design-blocked on abg.36, see report). Produce a dry-run report -- DONE. Rehearse dual-run/shadow validation and rollback-safe cutover checklist -- NOT STARTED.","notes":"Dry-run inventory + mapping report delivered: docs/prds/hermes-migration-dry-run.md. Surveyed .hermes-carina/ (live copy of the Hermes deployment) structurally only -- directory listings and non-secret YAML top-level keys, zero secret file contents read (.env/auth.json/mcp-tokens/ explicitly excluded and never opened). Found and catalogued 4 environments (main/agile-lead/dev/local-agent), their skill counts (34/20/25/17), main's 419 session keys (sessions/sessions.json), cron jobs.json presence. Proposed a mapping table: environment-\u003eIdentityConfig, SOUL.md-\u003enew persona system-prompt field (no existing archie-core field for this), memories/-\u003einternal/memory.Manager (needs format translator), skills/-\u003einternal/skill.Catalog (closest 1:1, needs tool-compat pass), sessions-\u003egateway.SessionStore (needs translator), cron/jobs.json-\u003eblocked, no archie-core cron subsystem exists yet (abg.24 territory). Documented explicit exclusion list for the eventual importer (secrets never copied). Documented why actual import tooling is blocked until abg.36 lands (no point importing SOUL/memory/skills into a runtime that doesn't consume them per-turn yet) -- this report is prep, not the importer itself.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:16:40Z","started_at":"2026-07-26T05:14:49Z","dependencies":[{"issue_id":"archie-core-abg.39","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index acdd5fa57..d4b18c503 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -2,6 +2,7 @@ package telegram import ( "context" + "fmt" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" @@ -22,15 +23,35 @@ var gatewayCommands = []models.BotCommand{ {Command: "help", Description: "Show available commands"}, } -// registerCommands publishes the command menu. A failure here costs -// discoverability, not function -- every command still works when typed -- -// so it is logged rather than treated as fatal. +// commandScopes are the scopes the menu is published to. +// +// Telegram resolves a chat's menu by scope specificity, not recency: a +// list set on all_private_chats wins over the default scope in every DM. +// Publishing only to the default scope therefore leaves the bot showing +// whatever a previous owner of the token registered against the narrower +// scopes -- state that lives on Telegram's side and survives redeploys, +// rewrites and migrations. Writing every scope we care about overwrites +// those leftovers instead of being shadowed by them. +var commandScopes = []models.BotCommandScope{ + &models.BotCommandScopeDefault{}, + &models.BotCommandScopeAllPrivateChats{}, + &models.BotCommandScopeAllGroupChats{}, +} + +// registerCommands publishes the command menu to every scope. A failure +// here costs discoverability, not function -- every command still works +// when typed -- so it is logged rather than treated as fatal, and one +// failing scope does not stop the others. func (g *Gateway) registerCommands(ctx context.Context, b *bot.Bot) { - if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{ - Commands: gatewayCommands, - }); err != nil { - g.log.Warn("set command menu failed", "error", err) - return + for _, scope := range commandScopes { + if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{ + Commands: gatewayCommands, + Scope: scope, + }); err != nil { + g.log.Warn("set command menu failed", "scope", fmt.Sprintf("%T", scope), "error", err) + continue + } } - g.log.Info("command menu registered", "commands", len(gatewayCommands)) + g.log.Info("command menu registered", + "commands", len(gatewayCommands), "scopes", len(commandScopes)) }