diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index d58beed9e..7e29cad54 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -152,3 +152,4 @@ {"id":"int-98886b5c0eed086effa6684ec75bbb48","kind":"field_change","created_at":"2026-07-26T20:33:10.385698708Z","actor":"Sam Catlow","issue_id":"archie-core-3ro","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped locally: Telegram calls the assistant Archie rather than Gateway; restart copy is Archie-facing; new sessions receive and preserve an Archie baseline identity; model selector shows provider in the header and provider-free model names; successful selections acknowledge the chosen model; model/provider callbacks use stable tokens so stale keyboards cannot select a different option. task check and lint pass; fresh review clean."}} {"id":"int-09fd2039fe043eb9110fa9bdb678b3e9","kind":"field_change","created_at":"2026-07-27T01:44:06.19963429Z","actor":"Sam Catlow","issue_id":"archie-core-n55","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped locally: /models removed from Telegram menu, help, and Router; /model is the sole model selector/direct-switch command; /help menu text is now 'See what Archie can do'; command docs updated. task check passes and fresh review reports no findings."}} {"id":"int-30b8e857c7ac14ce8bfbac49283d7853","kind":"field_change","created_at":"2026-07-27T02:53:55.882577468Z","actor":"Sam Catlow","issue_id":"archie-core-rqp.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped: authorized /version reports installed gateway and runtime build versions from the composition root; menu/help parity covered; task check and scoped lint clean; fresh review found no blocking issues."}} +{"id":"int-21fc57e924a09c3e2cc06dad0b9fc341","kind":"field_change","created_at":"2026-07-27T03:02:11.029169675Z","actor":"Sam Catlow","issue_id":"archie-core-rqp","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped: deployment-neutral /update with configured argv check/install adapters, gateway/runtime release sections, per-user exact-version persisted deferrals, recipient-bound expiring single-use callback actions, global install serialization, callback authorization, and truthful progress/failure. Webhook callback queries enabled. task check and scoped lint clean; adversarial review findings remediated."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 31e57765c..c58fac34a 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -129,7 +129,7 @@ {"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0} {"_type":"issue","id":"archie-core-rqp.1","title":"Telegram: report installed gateway and runtime versions","description":"Add an authorized /version command as the installed-version prerequisite for component-aware /update. Telegram remains presentation-only; the composition root supplies installed component versions.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-27T02:50:47Z","created_by":"Sam Catlow","updated_at":"2026-07-27T02:53:56Z","started_at":"2026-07-27T02:50:48Z","closed_at":"2026-07-27T02:53:56Z","close_reason":"Shipped: authorized /version reports installed gateway and runtime build versions from the composition root; menu/help parity covered; task check and scoped lint clean; fresh review found no blocking issues.","dependencies":[{"issue_id":"archie-core-rqp.1","depends_on_id":"archie-core-rqp","type":"parent-child","created_at":"2026-07-27T12:50:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-n55","title":"Simplify Telegram model command surface","description":"Remove the redundant /models command from Telegram's published and executable command surface; retain /model selector. Make /help menu copy useful rather than self-referential.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-27T01:41:43Z","created_by":"Sam Catlow","updated_at":"2026-07-27T01:44:06Z","started_at":"2026-07-27T01:41:50Z","closed_at":"2026-07-27T01:44:06Z","close_reason":"Shipped locally: /models removed from Telegram menu, help, and Router; /model is the sole model selector/direct-switch command; /help menu text is now 'See what Archie can do'; command docs updated. task check passes and fresh review reports no findings.","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-rqp","title":"Telegram: component-aware /update with approve or defer","description":"Add an /update control flow that checks for available releases, presents separate archied gateway and archie-agent runtime versions/changelog sections, and lets an authorized user approve or defer. Keep discovery and execution behind typed interfaces so Docker/Watchtower, package-manager, and other installations can supply their own updater without the Telegram gateway assuming a deployment mechanism.","acceptance_criteria":"/update reports whether gateway and runtime updates are available, with separate version and changelog sections and explicit no-change wording. Telegram provides Approve and Defer actions restricted to authorized users. Deferral is persisted and suppresses repeated prompts according to an explicit policy. Approval calls a typed installation updater and reports progress/failure without claiming success early. No Watchtower-only or Docker-only behavior exists in the gateway package. Commands, menu, help, callback authorization, concurrency, persistence, and failure paths are tested.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:47:21Z","created_by":"Sam Catlow","updated_at":"2026-07-27T02:49:27Z","started_at":"2026-07-27T02:49:27Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-rqp","title":"Telegram: component-aware /update with approve or defer","description":"Add an /update control flow that checks for available releases, presents separate archied gateway and archie-agent runtime versions/changelog sections, and lets an authorized user approve or defer. Keep discovery and execution behind typed interfaces so Docker/Watchtower, package-manager, and other installations can supply their own updater without the Telegram gateway assuming a deployment mechanism.","acceptance_criteria":"/update reports whether gateway and runtime updates are available, with separate version and changelog sections and explicit no-change wording. Telegram provides Approve and Defer actions restricted to authorized users. Deferral is persisted and suppresses repeated prompts according to an explicit policy. Approval calls a typed installation updater and reports progress/failure without claiming success early. No Watchtower-only or Docker-only behavior exists in the gateway package. Commands, menu, help, callback authorization, concurrency, persistence, and failure paths are tested.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:47:21Z","created_by":"Sam Catlow","updated_at":"2026-07-27T03:02:11Z","started_at":"2026-07-27T02:49:27Z","closed_at":"2026-07-27T03:02:11Z","close_reason":"Shipped: deployment-neutral /update with configured argv check/install adapters, gateway/runtime release sections, per-user exact-version persisted deferrals, recipient-bound expiring single-use callback actions, global install serialization, callback authorization, and truthful progress/failure. Webhook callback queries enabled. task check and scoped lint clean; adversarial review findings remediated.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-b8t","title":"Telegram: announce newly installed Archie releases","description":"When archied starts after an installed release upgrade, notify authorized Telegram users once with an exact component-aware rundown from CHANGELOG.md. Present archied as THE GATEWAY and archie-agent as THE RUNTIME, explicitly saying when either component has no changes. Persist announced versions per recipient so ordinary restarts do not repeat notifications.","acceptance_criteria":"Repository has a maintained component-aware CHANGELOG.md. On an installed version advance, each configured authorized Telegram user receives one concise message with separate THE GATEWAY and THE RUNTIME sections and explicit no-change wording where applicable. Announced component versions are persisted and duplicate restarts do not repeat. First-run and development builds have explicit non-spam behavior. Parsing, version transition, persistence failure, and delivery failure paths are tested.","notes":"Component history decision: CHANGELOG.archied.md for gateway/control plane and CHANGELOG.archie.md for agent runtime, with root CHANGELOG.md as index. Installed/update messages render both sources and explicitly state when a component has no changes.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:39:18Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:48:38Z","started_at":"2026-07-26T19:46:23Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16.36","title":"Telegram: /restore to revert the last change","description":"Operator escape hatch requested alongside /restart: revert the last change from chat when an agent-authored change breaks something, without needing shell access to the host. Gateway-scoped.","acceptance_criteria":"Admin-only (allowlisted sender). Reverts the last change and reports what was reverted. Safe to run when there is nothing to revert.","notes":"Design finding: /restore must restore the latest agent-authored filesystem checkpoint, not revert an arbitrary daemon checkout commit. The change boundary will be owned by the sandboxed MCP execution layer: capture a pre-change checkpoint once per mutating agent turn, retain enough metadata to report files, and make restore safe/idempotent when empty. Hermes reference behavior uses this same filesystem-checkpoint boundary for /rollback; /undo is conversation-only. Blocked on 17.43.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:15:34Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:27:32Z","started_at":"2026-07-26T19:25:16Z","dependencies":[{"issue_id":"archie-core-abg.16.36","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:15:33Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.36","depends_on_id":"archie-core-abg.17.43","type":"blocks","created_at":"2026-07-27T05:27:32Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-a5w","title":"Evaluate internal/workflow architecture and APIs","description":"Perform a read-only, repository-grounded evaluation of internal/workflow. Identify correctness, definition clarity, reuse, interface ownership, coupling, testability, and maintainability improvements, with concrete evidence and prioritized recommendations.","acceptance_criteria":"Assessment covers package definitions, consumers, subpackages, tests, and architecture invariants; findings are prioritized with file references and actionable recommendations; no code or git changes are made.","notes":"Evaluation completed. Highest-priority findings: repository Yaegi stages expose full TaskContext and may be evaluated in the daemon; workflow Run ignores persistence failures and returns no result; baseline runs after repo stages; push precedes custom gate and diff cap; TDD repro is not environmentally restricted to tests; routing and status models are stringly and ambiguous; extension loaders duplicate incompatible plugin contracts and silently skip failures; AgentStage review is unused by production definitions; chat tasks still hit issue-only operations; lifecycle and routing tests are materially incomplete. Scoped workflow tests passed with GPG fixture access and scoped golangci-lint reported zero issues.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T06:39:19Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:47:45Z","started_at":"2026-07-26T06:39:27Z","closed_at":"2026-07-26T06:47:45Z","close_reason":"Read-only package evaluation completed and reported with prioritized, actionable findings.","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 8fc30111b..7fe8c0d26 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -49,6 +49,7 @@ import ( "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" "github.com/samcharles93/archie-core/internal/releaseannounce" + "github.com/samcharles93/archie-core/internal/releaseupdate" "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/storage" @@ -295,6 +296,16 @@ func run() int { tg.Version = func() string { return fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion) } + if len(cfg.Chat.Telegram.UpdateCheckCommand) != 0 { + updates := &releaseupdate.Service{ + Catalog: releaseupdate.CommandCatalog{Command: cfg.Chat.Telegram.UpdateCheckCommand}, + StatePath: filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"), + } + if len(cfg.Chat.Telegram.UpdateInstallCommand) != 0 { + updates.Installer = releaseupdate.CommandInstaller{Command: cfg.Chat.Telegram.UpdateInstallCommand} + } + tg.Updates = updates + } releaseAnnouncements := &releaseannounce.Announcer{ StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser), Components: []releaseannounce.Component{ diff --git a/config.example.toml b/config.example.toml index 10962a6e6..cda3cba17 100644 --- a/config.example.toml +++ b/config.example.toml @@ -51,6 +51,13 @@ class = "ollama" # "openrouter/openai/gpt-5.6-sol", # ] +# Optional self-hosted update adapter. Both values are argv arrays (never +# shell snippets). The check command must write a releaseupdate.Snapshot JSON +# document to stdout; configure the installer as well to show Approve/Defer. +# [chat.telegram] +# update_check_command = ["/usr/local/bin/archie-update-check"] +# update_install_command = ["/usr/local/bin/archie-update-install"] + # External MCP tools are launched and managed by Archie's MCP client. # [[tools.mcp_servers]] # name = "desktop-commander" diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index 8f5e8dfe1..6c8fe0389 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -21,6 +21,7 @@ type commandSpec struct { var gatewayCommandSpecs = []commandSpec{ {Command: "status", Description: "Show task counts by state", Usage: "/status"}, {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, + {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, {Command: "provider", Description: "Choose the provider used for chat", Usage: "/provider"}, {Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [provider/model]"}, {Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] "}, @@ -30,7 +31,7 @@ var gatewayCommandSpecs = []commandSpec{ {Command: "help", Description: "See what Archie can do", Usage: "/help"}, } -var telegramOnlyCommands = []string{"provider", "restart", "help", "version"} +var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update"} var gatewayCommands = func() []models.BotCommand { commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs)) diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index da3a416d1..aa738f0af 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -20,6 +20,7 @@ import ( "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/releaseupdate" ) // Gateway is a Telegram gateway.Gateway backed by go-telegram/bot. @@ -44,6 +45,9 @@ type Gateway struct { // Version reports installed component versions. The composition root owns // build metadata; Telegram only renders it for authorized users. Version func() string + // Updates is injected by the composition root. It owns release discovery, + // deferral persistence, and installation; Telegram only presents it. + Updates UpdateService // restartCh carries /restart requests from a bot handler to the // supervisor loop in Start. Buffered so a handler never blocks. @@ -53,6 +57,9 @@ type Gateway struct { modelCallbacks map[string]string providerMu sync.RWMutex providerCallbacks map[string]string + updateMu sync.Mutex + updateInProgress bool + updateActions map[string]updateAction log *slog.Logger bot *bot.Bot @@ -60,6 +67,13 @@ type Gateway struct { running bool } +type UpdateService interface { + Check(context.Context, int64) (releaseupdate.Snapshot, error) + Defer(context.Context, int64, releaseupdate.Snapshot) error + Install(context.Context, func(string)) error + CanInstall() bool +} + type ReleaseAnnouncer interface { Announce( ctx context.Context, @@ -79,6 +93,7 @@ func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *s restartCh: make(chan restartRequest, 1), modelCallbacks: make(map[string]string), providerCallbacks: make(map[string]string), + updateActions: make(map[string]updateAction), log: log.With("component", "gateway-telegram"), } } @@ -158,6 +173,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, // Gateway-local commands: handled directly, no LLM. b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(router)) b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler()) + b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler()) @@ -174,7 +190,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, URL: g.WebhookURL, SecretToken: g.WebhookSecret, MaxConnections: 40, - AllowedUpdates: []string{"message"}, + AllowedUpdates: []string{"message", "callback_query"}, DropPendingUpdates: true, } if _, err := b.SetWebhook(ctx, params); err != nil { @@ -318,6 +334,8 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { g.handleProviderCallback(ctx, b, update, router) case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): g.handleModelCallback(ctx, b, update, router) + case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): + g.handleUpdateCallback(ctx, b, update) } return } diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go new file mode 100644 index 000000000..4a0215e37 --- /dev/null +++ b/internal/channels/telegram/update.go @@ -0,0 +1,225 @@ +package telegram + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "strings" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/releaseupdate" +) + +const ( + updateCallbackPrefix = "update:" + updateApproveCallback = updateCallbackPrefix + "approve:" + updateDeferCallback = updateCallbackPrefix + "defer:" +) + +type updateAction struct { + recipient int64 + snapshot releaseupdate.Snapshot + expiresAt time.Time +} + +func (g *Gateway) updateHandler() bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + msg, ok := g.authorizedMessage(ctx, b, update) + if !ok { + return + } + if g.Updates == nil { + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Updates are not configured for this installation.") + return + } + snapshot, err := g.Updates.Check(ctx, msg.From.ID) + if err != nil { + g.log.Warn("check updates failed", "error", err) + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "I couldn't check for updates right now.") + return + } + g.sendUpdateMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, msg.From.ID, snapshot) + } +} + +func (g *Gateway) sendUpdateMessage(ctx context.Context, b *bot.Bot, chatID int64, threadID int, recipient int64, snapshot releaseupdate.Snapshot) { + params := &bot.SendMessageParams{ChatID: chatID, Text: updateText(snapshot)} + if len(snapshot.Available()) > 0 { + if g.Updates.CanInstall() { + params.ReplyMarkup = g.updateKeyboard(recipient, snapshot) + } + } + if threadID != 0 { + params.MessageThreadID = threadID + } + if _, err := b.SendMessage(ctx, params); err != nil { + g.log.Error("send update status failed", "error", err) + } +} + +func updateText(snapshot releaseupdate.Snapshot) string { + if len(snapshot.Available()) == 0 && !snapshot.Deferred { + return "Archie is up to date." + } + if len(snapshot.Available()) == 0 && snapshot.Deferred { + return "The available update is deferred. Archie will ask again when a newer release is available." + } + var text strings.Builder + text.WriteString("Archie has an update available:") + for _, component := range snapshot.Components { + fmt.Fprintf(&text, "\n\n--- %s ---\n", component.Label) + if component.Available == "" || component.Available == component.Installed { + fmt.Fprintf(&text, "No %s changes as part of this release.", strings.ToLower(strings.TrimPrefix(component.Label, "THE "))) + continue + } + fmt.Fprintf(&text, "%s available", component.Available) + if component.Changelog != "" { + fmt.Fprintf(&text, "\n\n%s", component.Changelog) + } + } + return text.String() +} + +func (g *Gateway) updateKeyboard(recipient int64, snapshot releaseupdate.Snapshot) *models.InlineKeyboardMarkup { + token := makeUpdateToken() + g.updateMu.Lock() + now := time.Now() + for key, action := range g.updateActions { + if !action.expiresAt.After(now) { + delete(g.updateActions, key) + } + } + g.updateActions[token] = updateAction{recipient: recipient, snapshot: snapshot, expiresAt: now.Add(10 * time.Minute)} + g.updateMu.Unlock() + return &models.InlineKeyboardMarkup{InlineKeyboard: [][]models.InlineKeyboardButton{{ + {Text: "Approve update", CallbackData: updateApproveCallback + token}, + {Text: "Defer", CallbackData: updateDeferCallback + token}, + }}} +} + +func makeUpdateToken() string { + bytes := make([]byte, 16) + if _, err := rand.Read(bytes); err != nil { + panic("crypto/rand: " + err.Error()) + } + return hex.EncodeToString(bytes) +} + +func (g *Gateway) handleUpdateCallback(ctx context.Context, b *bot.Bot, update *models.Update) { + query := update.CallbackQuery + if query == nil { + return + } + if !g.isSenderAllowed(query.From.ID) { + g.log.Warn("update callback from unauthorized sender", "user_id", query.From.ID) + g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) + return + } + if g.Updates == nil { + g.answerModelCallback(ctx, b, query.ID, "Updates are not configured for this installation.", true) + return + } + approved := strings.TrimPrefix(query.Data, updateApproveCallback) + deferred := strings.TrimPrefix(query.Data, updateDeferCallback) + token := approved + if token == query.Data { + token = deferred + } + g.updateMu.Lock() + action, found := g.updateActions[token] + if found && action.recipient == query.From.ID { + delete(g.updateActions, token) + } + g.updateMu.Unlock() + if !found || action.recipient != query.From.ID || !action.expiresAt.After(time.Now()) { + g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true) + return + } + switch { + case strings.HasPrefix(query.Data, updateDeferCallback): + if err := g.Updates.Defer(ctx, query.From.ID, action.snapshot); err != nil { + g.log.Warn("defer update failed", "error", err) + g.answerModelCallback(ctx, b, query.ID, "Couldn't defer the update.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "Update deferred.", false) + g.editUpdateMessage(ctx, b, query, "Update deferred. Archie will ask again when a newer release is available.") + case strings.HasPrefix(query.Data, updateApproveCallback): + fresh, err := g.Updates.Check(ctx, query.From.ID) + if err != nil || !sameUpdateSnapshot(fresh, action.snapshot) { + g.answerModelCallback(ctx, b, query.ID, "The available releases changed. Run /update again.", true) + return + } + if !g.beginUpdate() { + g.answerModelCallback(ctx, b, query.ID, "An update is already in progress.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "Starting update…", false) + g.editUpdateMessage(ctx, b, query, "Update approved. Starting now…") + go g.installUpdate(ctx, b, query) + default: + g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true) + } +} + +func (g *Gateway) beginUpdate() bool { + g.updateMu.Lock() + defer g.updateMu.Unlock() + if g.updateInProgress { + return false + } + g.updateInProgress = true + return true +} + +func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.CallbackQuery) { + defer func() { + g.updateMu.Lock() + g.updateInProgress = false + g.updateMu.Unlock() + }() + message := query.Message.Message + if message == nil { + return + } + progress := func(text string) { + g.sendMessage(ctx, b, message.Chat.ID, message.MessageThreadID, text) + } + if err := g.Updates.Install(ctx, progress); err != nil { + g.log.Error("approved update failed", "error", err) + progress("Update failed. Archie is still running; check the installation logs and try again.") + return + } + progress("Update completed. Archie will use the new version after it restarts.") +} + +func sameUpdateSnapshot(left, right releaseupdate.Snapshot) bool { + leftAvailable, rightAvailable := left.Available(), right.Available() + if len(leftAvailable) != len(rightAvailable) { + return false + } + versions := make(map[string]string, len(leftAvailable)) + for _, component := range leftAvailable { + versions[component.ID] = component.Available + } + for _, component := range rightAvailable { + if versions[component.ID] != component.Available { + return false + } + } + return true +} + +func (g *Gateway) editUpdateMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) { + if query.Message.Message == nil { + return + } + message := query.Message.Message + if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{ChatID: message.Chat.ID, MessageID: message.ID, Text: text}); err != nil { + g.log.Warn("update update message failed", "error", err) + } +} diff --git a/internal/channels/telegram/update_test.go b/internal/channels/telegram/update_test.go new file mode 100644 index 000000000..f07dc87a3 --- /dev/null +++ b/internal/channels/telegram/update_test.go @@ -0,0 +1,71 @@ +package telegram + +import ( + "context" + "log/slog" + "strings" + "testing" + + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/releaseupdate" +) + +func TestUpdateShowsComponentSectionsAndActions(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + g.Updates = &updateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{ + {ID: "gateway", Label: "THE GATEWAY", Installed: "v0.1.0", Available: "v0.1.1", Changelog: "- Clearer help"}, + {ID: "runtime", Label: "THE RUNTIME", Installed: "v0.1.0"}, + }}} + b, requests := newTelegramTestBot(t) + + g.updateHandler()(context.Background(), b, &models.Update{Message: &models.Message{ + From: &models.User{ID: 42}, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}, Text: "/update", + }}) + + if len(*requests) != 1 || (*requests)[0].method != "sendMessage" { + t.Fatalf("requests = %#v, want update message", *requests) + } + text := (*requests)[0].form["text"] + for _, want := range []string{"Archie has an update available:", "--- THE GATEWAY ---", "v0.1.1 available", "- Clearer help", "--- THE RUNTIME ---", "No runtime changes"} { + if !strings.Contains(text, want) { + t.Errorf("update text missing %q: %q", want, text) + } + } + if !strings.Contains((*requests)[0].form["reply_markup"], updateApproveCallback) || !strings.Contains((*requests)[0].form["reply_markup"], updateDeferCallback) { + t.Errorf("update keyboard = %q", (*requests)[0].form["reply_markup"]) + } +} + +func TestUpdateCallbackRejectsUnauthorizedSender(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + g.Updates = &updateStub{} + b, requests := newTelegramTestBot(t) + + g.handleUpdateCallback(context.Background(), b, &models.Update{CallbackQuery: &models.CallbackQuery{ + ID: "callback", From: models.User{ID: 99}, Data: updateApproveCallback, + }}) + + if g.Updates.(*updateStub).installCalls != 0 { + t.Error("unauthorized callback started an installation") + } + if len(*requests) != 1 || (*requests)[0].method != "answerCallbackQuery" { + t.Fatalf("requests = %#v, want authorization response", *requests) + } +} + +type updateStub struct { + snapshot releaseupdate.Snapshot + installCalls int +} + +func (s *updateStub) Check(context.Context, int64) (releaseupdate.Snapshot, error) { + return s.snapshot, nil +} +func (s *updateStub) Defer(context.Context, int64, releaseupdate.Snapshot) error { return nil } +func (s *updateStub) Install(_ context.Context, progress func(string)) error { + s.installCalls++ + progress("Update started.") + return nil +} +func (*updateStub) CanInstall() bool { return true } diff --git a/internal/config/config.go b/internal/config/config.go index 487ad1cb7..8c100d877 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -498,6 +498,11 @@ type TelegramConfig struct { // TokenEnv names the env var holding the bot token from @BotFather. // Empty disables the Telegram channel. TokenEnv string `toml:"token_env" yaml:"token_env"` + // UpdateCheckCommand writes a releaseupdate.Snapshot JSON document to + // stdout. UpdateInstallCommand applies an already-approved update. Both + // are argv arrays, never shell snippets. + UpdateCheckCommand []string `toml:"update_check_command" yaml:"update_check_command"` + UpdateInstallCommand []string `toml:"update_install_command" yaml:"update_install_command"` } // EmailConfig configures the inbound email channel via SMTP. diff --git a/internal/nats/client.go b/internal/nats/client.go index 1ef1a327e..dbcc662fd 100644 --- a/internal/nats/client.go +++ b/internal/nats/client.go @@ -159,11 +159,11 @@ func (c *Client) Fetch(ctx context.Context) (jetstream.Msg, error) { if msg == nil { continue } - if err := batch.Error(); err != nil { - return nil, fmt.Errorf("nats fetch batch: %w", err) - } return msg, nil } + if err := batch.Error(); err != nil { + return nil, fmt.Errorf("nats fetch batch: %w", err) + } return nil, nil } diff --git a/internal/nats/client_test.go b/internal/nats/client_test.go index fbb8207e1..4e87db305 100644 --- a/internal/nats/client_test.go +++ b/internal/nats/client_test.go @@ -2,11 +2,13 @@ package nats import ( "context" + "errors" "log/slog" "testing" "github.com/nats-io/nats-server/v2/server" natssrv "github.com/nats-io/nats-server/v2/test" + "github.com/nats-io/nats.go/jetstream" ) // startEmbedded starts an embedded NATS server with JetStream file storage. @@ -162,3 +164,105 @@ func TestSubjectRouting(t *testing.T) { } } } + +// --- mock types for Fetch error propagation tests --- + +// errSentinel is a distinguishable error used in mock MessageBatch.Error(). +var errSentinel = errors.New("nats: consumer deleted") + +// mockMessageBatch implements jetstream.MessageBatch. +type mockMessageBatch struct { + msgs <-chan jetstream.Msg + err error +} + +func (m *mockMessageBatch) Messages() <-chan jetstream.Msg { return m.msgs } +func (m *mockMessageBatch) Error() error { return m.err } + +// mockConsumer implements jetstream.Consumer. +// Only Fetch is exercised by Client.Fetch; the remaining methods panic to +// flag accidental usage. +type mockConsumer struct { + batch jetstream.MessageBatch +} + +func (m *mockConsumer) Fetch(int, ...jetstream.FetchOpt) (jetstream.MessageBatch, error) { + return m.batch, nil +} +func (m *mockConsumer) FetchBytes(int, ...jetstream.FetchOpt) (jetstream.MessageBatch, error) { + panic("FetchBytes not implemented") +} +func (m *mockConsumer) FetchNoWait(int) (jetstream.MessageBatch, error) { + panic("FetchNoWait not implemented") +} +func (m *mockConsumer) Consume(jetstream.MessageHandler, ...jetstream.PullConsumeOpt) (jetstream.ConsumeContext, error) { + panic("Consume not implemented") +} +func (m *mockConsumer) Messages(...jetstream.PullMessagesOpt) (jetstream.MessagesContext, error) { + panic("Messages not implemented") +} +func (m *mockConsumer) Next(...jetstream.FetchOpt) (jetstream.Msg, error) { + panic("Next not implemented") +} +func (m *mockConsumer) Info(context.Context) (*jetstream.ConsumerInfo, error) { + panic("Info not implemented") +} +func (m *mockConsumer) CachedInfo() *jetstream.ConsumerInfo { + panic("CachedInfo not implemented") +} + +func TestFetchPropagatesBatchErrorWhenNoMessages(t *testing.T) { + // Reproduces issue #35: when JetStream reports an error by closing the + // Messages() channel with zero messages and setting a non-nil batch error, + // Client.Fetch must propagate that error instead of returning (nil, nil). + ch := make(chan jetstream.Msg) + close(ch) // zero messages + + batch := &mockMessageBatch{msgs: ch, err: errSentinel} + cons := &mockConsumer{batch: batch} + + client := &Client{ + consumer: cons, + log: slog.New(slog.DiscardHandler), + } + + msg, err := client.Fetch(context.Background()) + if err == nil { + t.Fatal("expected an error from Fetch when batch has an error and no messages, got nil") + } + if msg != nil { + t.Fatalf("expected nil message when batch has an error, got %v", msg) + } + if !errors.Is(err, errSentinel) { + t.Fatalf("expected errSentinel, got %v", err) + } +} + +func TestFetchPropagatesBatchErrorEvenWhenLastMessageSeen(t *testing.T) { + // Companion: when the batch delivers a message but also has a non-nil + // error (the existing inside-loop check), we confirm the existing path + // still works. This is not the reported bug but guards against + // regressions. + ch := make(chan jetstream.Msg, 1) + ch <- nil // nil message triggers the msg==nil continue + close(ch) + + batch := &mockMessageBatch{msgs: ch, err: errSentinel} + cons := &mockConsumer{batch: batch} + + client := &Client{ + consumer: cons, + log: slog.New(slog.DiscardHandler), + } + + msg, err := client.Fetch(context.Background()) + if err == nil { + t.Fatal("expected an error from Fetch when batch has an error, got nil") + } + if msg != nil { + t.Fatalf("expected nil message when batch has an error, got %v", msg) + } + if !errors.Is(err, errSentinel) { + t.Fatalf("expected errSentinel, got %v", err) + } +} diff --git a/internal/releaseupdate/command.go b/internal/releaseupdate/command.go new file mode 100644 index 000000000..49dcfb5f3 --- /dev/null +++ b/internal/releaseupdate/command.go @@ -0,0 +1,41 @@ +package releaseupdate + +import ( + "context" + "encoding/json" + "fmt" + "os/exec" +) + +// CommandCatalog reads a Snapshot JSON document from an explicitly configured +// argv command. It never invokes a shell; deployment tooling remains an +// administrator-owned adapter. +type CommandCatalog struct{ Command []string } + +func (c CommandCatalog) Check(ctx context.Context) (Snapshot, error) { + if len(c.Command) == 0 { + return Snapshot{}, fmt.Errorf("update check command is empty") + } + output, err := exec.CommandContext(ctx, c.Command[0], c.Command[1:]...).Output() + if err != nil { + return Snapshot{}, fmt.Errorf("run update check: %w", err) + } + var snapshot Snapshot + if err := json.Unmarshal(output, &snapshot); err != nil { + return Snapshot{}, fmt.Errorf("decode update check output: %w", err) + } + return snapshot, nil +} + +type CommandInstaller struct{ Command []string } + +func (i CommandInstaller) Install(ctx context.Context, progress func(string)) error { + if len(i.Command) == 0 { + return fmt.Errorf("update install command is empty") + } + progress("Installing approved update…") + if output, err := exec.CommandContext(ctx, i.Command[0], i.Command[1:]...).CombinedOutput(); err != nil { + return fmt.Errorf("run update installer: %w: %s", err, string(output)) + } + return nil +} diff --git a/internal/releaseupdate/service.go b/internal/releaseupdate/service.go new file mode 100644 index 000000000..8e907c532 --- /dev/null +++ b/internal/releaseupdate/service.go @@ -0,0 +1,193 @@ +// Package releaseupdate provides deployment-neutral release discovery, +// per-user deferrals, and installation orchestration. +package releaseupdate + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "sync" +) + +// Catalog discovers the currently installed and newest available releases. +// Deployment-specific adapters (a package manager, image registry, or custom +// release feed) implement it outside the chat gateway. +type Catalog interface { + Check(context.Context) (Snapshot, error) +} + +// Installer applies an approved update. It reports only work it has actually +// started; callers remain responsible for telling users the final result. +type Installer interface { + Install(context.Context, func(string)) error +} + +type Component struct { + ID string + Label string + Installed string + Available string + Changelog string +} + +type Snapshot struct { + Components []Component + Deferred bool +} + +func (s Snapshot) Available() []Component { + available := make([]Component, 0, len(s.Components)) + for _, component := range s.Components { + if component.Available != "" && component.Available != component.Installed { + available = append(available, component) + } + } + return available +} + +// Service persists a user's decision to defer an exact available version. A +// later version is deliberately shown again rather than being silently hidden. +type Service struct { + Catalog Catalog + Installer Installer + StatePath string + mu sync.Mutex +} + +func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error) { + if s.Catalog == nil { + return Snapshot{}, errors.New("update discovery is not configured") + } + snapshot, err := s.Catalog.Check(ctx) + if err != nil { + return Snapshot{}, fmt.Errorf("check for updates: %w", err) + } + if s.StatePath == "" { + return snapshot, nil + } + s.mu.Lock() + defer s.mu.Unlock() + state, err := loadDeferrals(s.StatePath) + if err != nil { + return Snapshot{}, err + } + deferred := state[strconv.FormatInt(recipient, 10)] + for index := range snapshot.Components { + component := &snapshot.Components[index] + if deferred[component.ID] == component.Available { + component.Available = "" + snapshot.Deferred = true + } + } + return snapshot, nil +} + +// Defer records only the exact versions the caller displayed. It refuses a +// changed catalog rather than silently suppressing a release the user never saw. +func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot) error { + if s.Catalog == nil { + return errors.New("update discovery is not configured") + } + if s.StatePath == "" { + return errors.New("update deferral storage is not configured") + } + s.mu.Lock() + defer s.mu.Unlock() + snapshot, err := s.Catalog.Check(ctx) + if err != nil { + return fmt.Errorf("check updates before deferring: %w", err) + } + state, err := loadDeferrals(s.StatePath) + if err != nil { + return err + } + key := strconv.FormatInt(recipient, 10) + if state[key] == nil { + state[key] = make(map[string]string) + } + if !sameAvailable(snapshot, expected) { + return errors.New("available releases changed; check again") + } + for _, component := range expected.Available() { + state[key][component.ID] = component.Available + } + return saveDeferrals(s.StatePath, state) +} + +func sameAvailable(left, right Snapshot) bool { + leftAvailable, rightAvailable := left.Available(), right.Available() + if len(leftAvailable) != len(rightAvailable) { + return false + } + versions := make(map[string]string, len(leftAvailable)) + for _, component := range leftAvailable { + versions[component.ID] = component.Available + } + for _, component := range rightAvailable { + if versions[component.ID] != component.Available { + return false + } + } + return true +} + +func (s *Service) Install(ctx context.Context, progress func(string)) error { + if s.Installer == nil { + return errors.New("update installation is not configured") + } + return s.Installer.Install(ctx, progress) +} + +func (s *Service) CanInstall() bool { return s.Installer != nil } + +type deferrals map[string]map[string]string + +func loadDeferrals(path string) (deferrals, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return make(deferrals), nil + } + if err != nil { + return nil, fmt.Errorf("read update deferrals: %w", err) + } + var state deferrals + if err := json.Unmarshal(data, &state); err != nil { + return nil, fmt.Errorf("decode update deferrals: %w", err) + } + return state, nil +} + +func saveDeferrals(path string, state deferrals) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return fmt.Errorf("create update state directory: %w", err) + } + file, err := os.CreateTemp(filepath.Dir(path), ".update-deferrals-*") + if err != nil { + return fmt.Errorf("create update state: %w", err) + } + tempPath := file.Name() + defer func() { _ = os.Remove(tempPath) }() + if err := file.Chmod(0o600); err != nil { + _ = file.Close() + return fmt.Errorf("protect update state: %w", err) + } + if err := json.NewEncoder(file).Encode(state); err != nil { + _ = file.Close() + return fmt.Errorf("encode update deferrals: %w", err) + } + if err := file.Sync(); err != nil { + _ = file.Close() + return fmt.Errorf("sync update deferrals: %w", err) + } + if err := file.Close(); err != nil { + return fmt.Errorf("close update state: %w", err) + } + if err := os.Rename(tempPath, path); err != nil { + return fmt.Errorf("replace update state: %w", err) + } + return nil +} diff --git a/internal/releaseupdate/service_test.go b/internal/releaseupdate/service_test.go new file mode 100644 index 000000000..f2377613b --- /dev/null +++ b/internal/releaseupdate/service_test.go @@ -0,0 +1,73 @@ +package releaseupdate + +import ( + "context" + "path/filepath" + "testing" +) + +func TestServiceDefersOnlyTheVersionsShownToThatRecipient(t *testing.T) { + catalog := &catalogStub{snapshot: Snapshot{Components: []Component{ + {ID: "gateway", Label: "THE GATEWAY", Installed: "v0.1.0", Available: "v0.1.1", Changelog: "- Clearer help"}, + {ID: "runtime", Label: "THE RUNTIME", Installed: "v0.1.0"}, + }}} + service := Service{Catalog: catalog, StatePath: filepath.Join(t.TempDir(), "deferrals.json")} + + first, err := service.Check(context.Background(), 42) + if err != nil { + t.Fatal(err) + } + if got := len(first.Available()); got != 1 { + t.Fatalf("available before defer = %d, want 1", got) + } + if err := service.Defer(context.Background(), 42, first); err != nil { + t.Fatal(err) + } + + deferred, err := service.Check(context.Background(), 42) + if err != nil { + t.Fatal(err) + } + if got := len(deferred.Available()); got != 0 { + t.Fatalf("available after defer = %d, want 0", got) + } + if !deferred.Deferred { + t.Error("Deferred = false, want true") + } + + catalog.snapshot.Components[0].Available = "v0.1.2" + newer, err := service.Check(context.Background(), 42) + if err != nil { + t.Fatal(err) + } + if got := len(newer.Available()); got != 1 { + t.Fatalf("available for newer version = %d, want 1", got) + } +} + +func TestServiceInstallForwardsProgressAndFailure(t *testing.T) { + installer := &installerStub{} + service := Service{Installer: installer} + var progress []string + if err := service.Install(context.Background(), func(message string) { progress = append(progress, message) }); err != nil { + t.Fatal(err) + } + if !installer.called { + t.Error("installer was not called") + } + if len(progress) != 1 || progress[0] != "Pulling release..." { + t.Errorf("progress = %#v", progress) + } +} + +type catalogStub struct{ snapshot Snapshot } + +func (s *catalogStub) Check(context.Context) (Snapshot, error) { return s.snapshot, nil } + +type installerStub struct{ called bool } + +func (s *installerStub) Install(_ context.Context, progress func(string)) error { + s.called = true + progress("Pulling release...") + return nil +}