Files
archie/internal/channels/telegram/commands.go
T
sam f6397af7f4 fix: address the Greptile findings on the merged PRs (#902)
* fix: address the Greptile findings on the merged PRs

Four valid review findings from PRs #892, #893, #898 and #899, which were
merged without the comments being read.

- Config.Clone left the new diff-cap pointers aliased (#899, mine). Clone
  deep-copies every reference field, including the *bool beside it, so a
  clone could write the cap through to the published snapshot. Both the
  top-level field and the identity overrides are copied, with the clone test
  extended to cover them.
- providerOutcomeRecorder.record could report an older call as the latest
  (#892). The completion time is taken before the lock, so two concurrent
  calls can reach the lock in the opposite order to their completion and the
  unconditional store overwrote the newer outcome. It now keeps the newer,
  via a recordAt seam that makes the reordering testable.
- Curator model calls bypassed the recorder (#892). curatorLLMRunner calls
  the runtime directly, so a daemon whose only recent model traffic was
  curator work reported "no calls attempted yet" while the provider was
  demonstrably reachable. It records at its own adapter, and sendChatTurn's
  "single choke point" comment is corrected to say there are two.
- A provider error reached /status raw (#892), unlike channel details, so a
  multiline or oversized error broke the one-line-per-fact layout. Both now
  share one bounded formatter.

Found while fixing the curator path: agentexec.NewRuntime returns nil when no
provider is configured, and a nil *runtime.Runtime panics on its first method
call, so a curator asking for a completion took the daemon down. It now
returns an error, and records nothing -- a local misconfiguration is not a
provider call.

Not fixed, filed instead: the shared lastPollAt masking a stuck identity, the
container max-uptime callback resurrecting teardown bookkeeping, the
dashboard dropping a served-only status filter on cold load, and the route
registry test's line-by-line parser.

* fix(build): drop goimports from the gate's formatter set

`task check` spent 136 of its 167 seconds in `task fmt`, and 134 of those
136 in one formatter: goimports alone over the tree.

golangci-lint's goimports formatter calls imports.Process once per file,
which builds a fresh x/tools ProcessEnv each time, so
internal/imports.getFixesWithSource re-reads modindex.Read($GOMODCACHE) per
file. On this machine that index is 62.7 MiB / 2,081,070 lines (an 11 GiB
module cache), and modindex's in-process memo does not take effect: 3 files
read 187.9 MiB back, 15 files open the payload 15 times. That is ~53 GiB of
I/O and CSV parsing per run, and it is linear at ~155 ms per file (122 files
-> 18.8s, 864 -> 133.8s). Pointing the index cache elsewhere drops the same
command to 3.9s.

The same analyzer runs under `golangci-lint run`, so a cold cache pays it
again: 169s cold with goimports, 31s without -- which is what CI and archied's
own PR gate see, since only `fmt` never caches locally.

Removing it costs no enforcement. gofumpt and gci remain, `task lint` still
reports formatter drift as an issue, and the whole-tree fmt is now 2.2s with
the tree byte-identical. What is given up is goimports' convenience of
adding and removing import lines, which compile errors already cover.

The examples/secret-engines exclusion stays: gofumpt and gci leave those
Yaegi programs alone today, but the exclusion is the stated invariant that a
formatter must not rewrite the imports of files it cannot type-check, and
TestFormattersExcludeInterpretedSecretEngines holds it. Its comment no longer
pins the reason to the formatter that was dropped.

* fix(gateway): stop /status promising and mis-reporting health it cannot see

Two findings from the cloud review of #892.

Title generation no longer records chat-model health. It runs detached after
a first turn under its own 30s bound and its error is swallowed by the
caller, but it shared the process-wide outcome recorder, so a title that
merely timed out overwrote the health line with "failed" -- reporting a
broken provider on the strength of a call no user was waiting for.

The /status command description no longer claims "workers" and "channels".
Neither can render: newStatusHealth reads the container pool and the poll
loop from boot, but the only production router.Health assignment is in
setupGatewayChat, which runs solely in the archie-gateway process, where
neither exists; channels is nil since the Messaging Service took the
front-ends. Only the broker and chat-model lines actually appear, so that is
what the help text now says.

The underlying split -- daemon owns the facts, Gateway owns the Router -- is
filed rather than patched here: it needs either a cross-process health
contract or a ratified two-section /status, not a quick wire-up.
2026-09-20 02:42:36 +10:00

107 lines
5.5 KiB
Go

package telegram
import (
"context"
"fmt"
"strings"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
type commandSpec struct {
Command string
Description string
Usage string
}
// gatewayCommandSpecs is the single source of truth for both Telegram's
// published command menu and /help. Keeping the discoverability surfaces
// together prevents a newly registered command from being omitted from help.
var gatewayCommandSpecs = []commandSpec{
{Command: "status", Description: "Show health: queue depth, broker, and the last chat-model call", Usage: "/status"},
{Command: "tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"},
{Command: "version", Description: "Show installed Archie versions", Usage: "/version"},
{Command: "update", Description: "Check for Archie updates", Usage: "/update"},
{Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"},
{Command: "personality", Description: "Choose a communication style", Usage: "/personality [name]"},
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
{Command: "start", Description: "Confirm that Archie is running", Usage: "/start"},
{Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"},
{Command: "reset", Description: "Alias for /new", Usage: "/reset [title]"},
{Command: "topic", Description: "List or switch sessions for this channel", Usage: "/topic [off|help|<session-id>]"},
{Command: "retry", Description: "Replay the last message with a fresh reply", Usage: "/retry"},
{Command: "undo", Description: "Remove the last N messages from the session", Usage: "/undo [N]"},
{Command: "title", Description: "Show or set the current session's title", Usage: "/title [name]"},
{Command: "branch", Description: "Create a child session that inherits the current history", Usage: "/branch [name]"},
{Command: "fork", Description: "Alias for /branch", Usage: "/fork [name]"},
{Command: "compress", Description: "Compress the current session's context", Usage: "/compress [here [N]|focus <topic>|--preview|--dry-run]"},
{Command: "compact", Description: "Alias for /compress", Usage: "/compact [here [N]|focus <topic>|--preview|--dry-run]"},
{Command: "whoami", Description: "Show the active identity and model", Usage: "/whoami"},
{Command: "profile", Description: "Show the active identity's profile", Usage: "/profile"},
{Command: "sessions", Description: "List this channel's sessions", Usage: "/sessions"},
{Command: "resume", Description: "Switch to a session by id or unique prefix", Usage: "/resume <session-id>"},
{Command: "delete", Description: "Permanently delete a session and its history", Usage: "/delete <session-id>"},
{Command: "agents", Description: "List tasks currently being worked", Usage: "/agents"},
{Command: "rollback", Description: "Restore a filesystem checkpoint", Usage: "/rollback [number]"},
{Command: "stop", Description: "Terminate a background process", Usage: "/stop <process-name>"},
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
{Command: "help", Description: "See what Archie can do", Usage: "/help"},
}
var gatewayCommands = func() []models.BotCommand {
commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs))
for _, spec := range gatewayCommandSpecs {
commands = append(commands, models.BotCommand{
Command: spec.Command,
Description: spec.Description,
})
}
return commands
}()
func gatewayHelpText() string {
var help strings.Builder
help.WriteString("🤖 **Archie**\n\n")
help.WriteString("Send a message to chat with Archie. Replies stream into Telegram as they are generated.\n\n")
help.WriteString("**Commands**\n")
for _, spec := range gatewayCommandSpecs {
fmt.Fprintf(&help, "`%s`\n%s\n\n", spec.Usage, spec.Description)
}
return strings.TrimSpace(help.String())
}
// 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) {
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), "scopes", len(commandScopes))
}