* feat(workflow): post line-anchored review comments with suggested fixes Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached the operator only as a flat list in the PR body, so the author had to map every finding back to its line by hand and apply mechanical fixes by hand. Now the line-anchored findings are also posted as inline review comments, carrying a one-click suggestion when the reviewer could state the fix. Domain (internal/domain/workflow): - ReviewFinding gains Suggestion; Validate rejects one on anything but a confirmed finding, so the agent's record_finding call is refused with something it can act on. Validate splits into validateAnchor / validateClassification / validateDisposition, which also brings it back under the cyclop limit the gate enforces. - StagePostReviewComments runs after StageOpenPR in the implement workflow. It posts only line-anchored findings (Line > 0); a whole-file finding has no line to attach to and stays in the body list, which remains the complete record. It is best-effort: the PR is open and the body already lists every finding, so a failed comment is logged, never a park -- the same reasoning as OpenPR's existing best-effort LinkBranch call. - The suggestion fence is gated on Verdict == confirmed where the fence is written, because it is a one-click apply: a wrong suggestion breaks the code and the author has to notice. Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations, type-asserted like PullRequestReader so a forge that cannot is skipped rather than faked (NoopForge is pinned as not satisfying it). GitHub loops one CreateComment per comment and joins the failures, so one refused anchor cannot drop the rest; Gitea carries them on a single COMMENT-state review. Two deliberate departures from the PRD's sketch, both recorded in it: - The interface is batch (CreateReviewComments), not one call per comment: Gitea's only inline shape is one submitted review, and the set then crosses NATS once instead of once per finding. - The head SHA is resolved inside each forge implementation rather than by the caller. The stage runs in archie-agent, which holds no forge credentials and has no PullRequestReader; the daemon-side forgerpc handler is the only place that does. Transport (internal/forgerpc): workflow.Forger gains the method, so the agent reaches the daemon over the new create_review_comments subject; the server type-asserts the writer and answers an incapable forge with an error the stage logs. This is the one proxied method whose absence on an image skew does not park a task. The reviewer prompt and record_finding schema ask for a suggestion on a confirmed, mechanically fixable defect only. Regenerating the wfextract symbol table -- the documented way a new exported workflow symbol reaches interpreted stage plugins -- also picked up symbols that were missing from the committed table (the Status* and Source* constants, ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to every wrapper afterwards, as that file's header requires. Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new stage logic each fail a test that names the behaviour -- dropping the confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure escape -- so the tests discriminate rather than passing vacuously. * fix(build): drop the Dockerfile pin assertion The guard fetched golangci-lint's go.mod at image build time to fail the build when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped on self-inflicted pin drift, but it added a network fetch and a new failure mode to the release build, which is not where that belongs. The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0 equals GOFUMPT_VERSION) and the comment above them still states the invariant, so the reasoning survives without the build-time machinery. The pin change itself reaches the agent image through the normal release path: CI rebuilds and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only release deliberately does not. * feat(workflow): add the remediate workflow for PR review remediation Implements step 5 of docs/prds/pr-review-remediation.md: a remediate workflow that resumes the task's existing worktree onto its PR branch (worktree.Manager.Resume, not Prepare's refresh), runs a builder agent against the review's actionable comments, commits and pushes to the same branch, and replies via the forge's ReplyToReview. Task.RetryCount doubles as the remediation round counter, capped by the repo's max_retries; the round-cap stage parks the task and posts one comment when it's hit. Task gains a ReviewPayload field (JSON-encoded review unit) with full store/proto/staterpc plumbing. workflow.Forger gains Comment and ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume and its Dir lookup are added as an unexported optional Trees capability rather than widening the exported interface, which is already at golangci-lint's interfacebloat cap and is projected into wfextract's Yaegi symbol table for repository-authored stage plugins. The daemon-side reaction consumer that dispatches into this workflow (subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing per-task serialization) is tracked separately in archie-core-8li9.4. * feat(messaging): extract standalone messaging service binary and process composition * feat(messaging): adapt channel frontends to consume Gateway ChatContract * feat(messaging): remove in-process channels and Router from daemon bootstrap Telegram, email and webhook now run only in the Messaging Service, which reaches this process through the Gateway's ChatContract. The daemon builds no channel and no gateway.Router, so the wiring that existed only to serve them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway, setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the release-announcement path helper. The seams those paths owned move to where they can still be honoured: - Channel ValidateConfig runs in archiemessaging.compose, which now returns an error, so a configured-but-invalid front-end fails the service rather than being dropped silently. - The inbound rate limiter moves to the Gateway process, which owns the only Router and therefore the only place a per-sender budget applies to every channel's turns. - The daemon's gateway readiness probe becomes a ContractProbe against the Gateway. It cannot observe a channel lifecycle it no longer runs, and a channel-count probe would have reported every daemon degraded. - telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a chat turn runner actually reads. Telegram operator features that were wired only in the daemon (/update, release announcements, version reporting, SIGHUP reload) are not yet wired in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting: archie-core-8cda.6.8. The Gateway process builds no worktree manager, so review_pr is unadvertised on every channel: archie-core-8cda.6.7. * feat(messaging): re-wire the Telegram operator surface in the Messaging Service setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's own process. Each is resolved by where the fact it needs is owned, not by where it used to be built; the decision table is in docs/architecture/migration-decisions.md. Wired here: /update (built from this service's own [chat.telegram] check and install commands), the update-report relay (same sha256(bot_user)[:8] path the daemon wrote, so a pending report is found rather than written afresh), show_tool_calls, and /restart's config reload, which re-resolves the token and allowlist from this service's own file and refuses a reload that resolves to an empty token. /version is sourced from the Gateway: ChatSnapshot gains a Version field carrying the Gateway's rendered build block, read per call and bounded by the dependency timeout. cmd/archie-messaging deliberately takes no version ldflags, so it cannot report a partial upgrade as a matched one. RunningVersions and ReleaseAnnouncements stay nil. Both need a component's real running version, and the only versions this process can obtain are a different binary's stamps -- reporting them would manufacture exactly the false success the update check exists to catch, and the announcer without parseable versions is a no-op that reads as configured. archie-core-8cda.6.9 carries the contract that unblocks them. Dangerous stays nil: no composition has ever supplied a command authority. Enrich is dropped from the update service: componentInstallTypeEnricher read [nats], which this service must not decode, so the check command's own reported install type stands. * fix(workflow): guard inline review comments against head drift Two findings from the review of q9au. A comment's line numbers describe exactly one revision of the branch, but the forge resolved the pull request's head at posting time -- after the review had already read the worktree. A push in that window (a collaborator, a retry) meant the findings were anchored to whatever now occupied those lines, mislabelling instead of failing. The revision the review measured now travels with the comment set: OpenPR records it from the same worktree read it already performs (TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through Forger to forgerpc, and the forge refuses the whole set once the head it reads has moved off it -- which the best-effort stage logs, the PR body remaining the record. An unmeasured revision posts unverified rather than dropping every finding, so a worktree that cannot report one degrades instead of regressing. Suggestion was documented single-line only, because GitHub applies a suggestion fence up to its first line and a multi-line replacement would silently corrupt the file. Only the verdict was validated, so a multi-line suggestion reached the renderer and posted as that truncated fence. Validate now rejects an embedded newline, which makes record_finding refuse it with feedback the model can act on instead of the reviewer discovering the corruption later.
641 lines
22 KiB
Go
641 lines
22 KiB
Go
package telegram
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-telegram/bot"
|
|
"github.com/go-telegram/bot/models"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
|
)
|
|
|
|
// These aliases keep Telegram's public configuration surface source
|
|
// compatible while making the authority contract reusable by other
|
|
// interactive adapters such as the Web UI.
|
|
type (
|
|
DangerousCommandAuthority = messaging.DangerousCommandAuthority
|
|
CheckpointInfo = messaging.CheckpointInfo
|
|
)
|
|
|
|
// ── dangerous command approval system ─────────────────────────────
|
|
|
|
// dangerousCmdPrefix separates dangerous-command callbacks from other
|
|
// callback types handled in defaultHandler.
|
|
const dangerousCmdPrefix = "dangerous:"
|
|
|
|
// dangerousAction records a pending command a human must approve or deny.
|
|
// It mirrors the updateAction pattern: random token, recipient-bound,
|
|
// expiring, single-use, and carrying a hash so a changed command cannot
|
|
// reuse the callback.
|
|
type dangerousAction struct {
|
|
id string // random token
|
|
command string // the full command text
|
|
commandHash string // sha256(command) — prevents changed-command replay
|
|
description string // human-readable label shown to the approver
|
|
recipient int64 // Telegram user who may approve
|
|
createdAt time.Time
|
|
expiresAt time.Time
|
|
// onApprove is the function to call when approved. The Gateway
|
|
// supplies this when registering the pending command so the
|
|
// authority stays out of the Telegram callback path.
|
|
onApprove func(ctx context.Context) (string, error)
|
|
}
|
|
|
|
// permanentApproval records a decision to approve a category of dangerous
|
|
// commands permanently. Scope and lifetime are explicit.
|
|
type permanentApproval struct {
|
|
// CommandPattern is a prefix match against the command text, e.g.
|
|
// "/rollback", "/stop", or a tool name.
|
|
CommandPattern string
|
|
Recipient int64
|
|
GrantedAt time.Time
|
|
ExpiresAt time.Time
|
|
// Scope describes the approval boundary for audit purposes.
|
|
Scope string
|
|
}
|
|
|
|
// ── Gateway methods ──────────────────────────────────────────────
|
|
|
|
// registerDangerousAction stores a pending command and returns a callback
|
|
// token. The caller must present the action to the user (via an inline
|
|
// keyboard) immediately after registering.
|
|
func (g *Gateway) registerDangerousAction(
|
|
command, description string,
|
|
recipient int64,
|
|
onApprove func(ctx context.Context) (string, error),
|
|
) string {
|
|
token := makeDangerousToken()
|
|
sum := sha256.Sum256([]byte(command))
|
|
hash := hex.EncodeToString(sum[:])
|
|
|
|
g.dangerousMu.Lock()
|
|
defer g.dangerousMu.Unlock()
|
|
|
|
now := time.Now()
|
|
// Expire tokens older than maxPendingAge.
|
|
maxPendingAge := 10 * time.Minute
|
|
for key, action := range g.dangerousActions {
|
|
if !action.expiresAt.After(now) {
|
|
delete(g.dangerousActions, key)
|
|
}
|
|
}
|
|
g.dangerousActions[token] = dangerousAction{
|
|
id: token,
|
|
command: command,
|
|
commandHash: hash,
|
|
description: description,
|
|
recipient: recipient,
|
|
createdAt: now,
|
|
expiresAt: now.Add(maxPendingAge),
|
|
onApprove: onApprove,
|
|
}
|
|
return token
|
|
}
|
|
|
|
// dangerousKeyboard builds the three-button inline keyboard for a
|
|
// dangerous command: "Approve this time", "Approve Permanently", "Deny".
|
|
func (g *Gateway) dangerousKeyboard(token string) *models.InlineKeyboardMarkup {
|
|
return &models.InlineKeyboardMarkup{
|
|
InlineKeyboard: [][]models.InlineKeyboardButton{
|
|
{
|
|
{
|
|
Text: "Approve this time",
|
|
CallbackData: dangerousCmdPrefix + "approve:" + token,
|
|
},
|
|
},
|
|
{
|
|
{
|
|
Text: "Approve Permanently",
|
|
CallbackData: dangerousCmdPrefix + "permanent:" + token,
|
|
},
|
|
},
|
|
{
|
|
{
|
|
Text: "Deny",
|
|
CallbackData: dangerousCmdPrefix + "deny:" + token,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
// answerDangerousCallback is the common acknowledge/shake response.
|
|
func (g *Gateway) answerDangerousCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) {
|
|
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
|
CallbackQueryID: queryID,
|
|
Text: text,
|
|
ShowAlert: alert,
|
|
}); err != nil {
|
|
g.log.Warn("answer dangerous callback failed", "error", err)
|
|
}
|
|
}
|
|
|
|
// handleDangerousCallback is the entrypoint for all dangerous-command
|
|
// inline-button taps. It validates the token (recipient, expiry, replay,
|
|
// hash), records an audit event, and executes or rejects the command.
|
|
func (g *Gateway) handleDangerousCallback(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("dangerous callback from unauthorized sender", "user_id", query.From.ID)
|
|
g.answerDangerousCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
|
return
|
|
}
|
|
|
|
action, ok := g.consumeDangerousAction(query)
|
|
if !ok {
|
|
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
|
return
|
|
}
|
|
|
|
decision, _ := parseDangerousCallback(query.Data)
|
|
g.log.Info(
|
|
"dangerous command decision",
|
|
"command", action.command, "decision", decision,
|
|
"recipient", query.From.ID, "username", query.From.Username,
|
|
)
|
|
|
|
switch decision {
|
|
case "deny":
|
|
g.executeDangerousDeny(ctx, b, query, action)
|
|
case "approve":
|
|
g.executeDangerousApprove(ctx, b, query, action)
|
|
case "permanent":
|
|
g.executeDangerousPermanent(ctx, b, query, action)
|
|
default:
|
|
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
|
}
|
|
}
|
|
|
|
// consumeDangerousAction validates and atomically consumes the pending
|
|
// action associated with the callback query. Returns the action and true
|
|
// if valid; false if expired, wrong recipient, or already consumed.
|
|
func (g *Gateway) consumeDangerousAction(query *models.CallbackQuery) (dangerousAction, bool) {
|
|
_, token := parseDangerousCallback(query.Data)
|
|
g.dangerousMu.Lock()
|
|
action, found := g.dangerousActions[token]
|
|
if found && action.recipient == query.From.ID && action.expiresAt.After(time.Now()) {
|
|
delete(g.dangerousActions, token)
|
|
}
|
|
g.dangerousMu.Unlock()
|
|
return action, found && action.recipient == query.From.ID && action.expiresAt.After(time.Now())
|
|
}
|
|
|
|
func (g *Gateway) executeDangerousDeny(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
|
g.answerDangerousCallback(ctx, b, query.ID, "Command denied.", false)
|
|
g.editDangerousMessage(ctx, b, query, "❌ Denied: "+action.description)
|
|
}
|
|
|
|
func (g *Gateway) executeDangerousApprove(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
|
result, err := action.onApprove(ctx)
|
|
if err != nil {
|
|
g.log.Error("dangerous command execution failed", "command", action.command, "error", err)
|
|
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
|
|
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
|
|
return
|
|
}
|
|
g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false)
|
|
msg := "✅ Approved: " + action.description
|
|
if result != "" {
|
|
msg += "\n\n" + result
|
|
}
|
|
g.editDangerousMessage(ctx, b, query, msg)
|
|
}
|
|
|
|
func (g *Gateway) executeDangerousPermanent(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
|
g.recordPermanentApproval(query.From.ID, action.command)
|
|
|
|
result, err := action.onApprove(ctx)
|
|
if err != nil {
|
|
g.log.Error("dangerous command execution failed (permanent approval)", "command", action.command, "error", err)
|
|
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
|
|
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
|
|
return
|
|
}
|
|
g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved and executed (valid 24h).", false)
|
|
msg := "✅ Approved (permanent, 24h): " + action.description
|
|
if result != "" {
|
|
msg += "\n\n" + result
|
|
}
|
|
g.editDangerousMessage(ctx, b, query, msg)
|
|
}
|
|
|
|
func (g *Gateway) recordPermanentApproval(recipient int64, command string) {
|
|
scope := permanentApproval{
|
|
CommandPattern: command,
|
|
Recipient: recipient,
|
|
GrantedAt: time.Now(),
|
|
ExpiresAt: time.Now().Add(24 * time.Hour),
|
|
Scope: fmt.Sprintf("Permanent approval for %q by user %d, expires in 24h", command, recipient),
|
|
}
|
|
g.dangerousMu.Lock()
|
|
g.permanentApprovals = append(g.permanentApprovals, scope)
|
|
now := time.Now()
|
|
kept := g.permanentApprovals[:0]
|
|
for _, pa := range g.permanentApprovals {
|
|
if pa.ExpiresAt.After(now) {
|
|
kept = append(kept, pa)
|
|
}
|
|
}
|
|
g.permanentApprovals = kept
|
|
g.dangerousMu.Unlock()
|
|
|
|
g.log.Info("dangerous command permanently approved", "scope", scope.Scope)
|
|
}
|
|
|
|
// hasPermanentApproval checks whether recipient has a current permanent
|
|
// approval covering the given command text.
|
|
func (g *Gateway) hasPermanentApproval(recipient int64, command string) bool {
|
|
g.dangerousMu.Lock()
|
|
defer g.dangerousMu.Unlock()
|
|
|
|
now := time.Now()
|
|
kept := g.permanentApprovals[:0]
|
|
found := false
|
|
for _, pa := range g.permanentApprovals {
|
|
if !pa.ExpiresAt.After(now) {
|
|
continue
|
|
}
|
|
kept = append(kept, pa)
|
|
if pa.Recipient == recipient && strings.HasPrefix(command, pa.CommandPattern) {
|
|
found = true
|
|
}
|
|
}
|
|
g.permanentApprovals = kept
|
|
return found
|
|
}
|
|
|
|
// hasPermanentApprovalExact is the exact-match variant used by the tool
|
|
// approval path. Prefix matching is appropriate for slash commands
|
|
// (/rollback covers /rollback 3); it is not for tool-approval keys
|
|
// composed of action + resource, where "delete session abc" must not
|
|
// grant on "delete session abc2".
|
|
func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool {
|
|
g.dangerousMu.Lock()
|
|
defer g.dangerousMu.Unlock()
|
|
|
|
now := time.Now()
|
|
kept := g.permanentApprovals[:0]
|
|
found := false
|
|
for _, pa := range g.permanentApprovals {
|
|
if !pa.ExpiresAt.After(now) {
|
|
continue
|
|
}
|
|
kept = append(kept, pa)
|
|
if pa.Recipient == recipient && pa.CommandPattern == pattern {
|
|
found = true
|
|
}
|
|
}
|
|
g.permanentApprovals = kept
|
|
return found
|
|
}
|
|
|
|
func (g *Gateway) editDangerousMessage(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("edit dangerous message failed", "error", err)
|
|
}
|
|
}
|
|
|
|
// ── /rollback handler ───────────────────────────────────────────
|
|
|
|
// rollbackHandler serves /rollback: show available checkpoints, or with
|
|
// a number, request approval to restore that checkpoint.
|
|
func (g *Gateway) rollbackHandler() 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.Dangerous == nil {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Rollback is not configured for this installation.")
|
|
return
|
|
}
|
|
|
|
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/rollback", ""))
|
|
if rest == "" {
|
|
g.showCheckpoints(ctx, b, msg.Chat.ID, msg.MessageThreadID)
|
|
return
|
|
}
|
|
|
|
num, err := strconv.Atoi(rest)
|
|
if err != nil || num < 1 {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Usage: /rollback <checkpoint number>")
|
|
return
|
|
}
|
|
g.requestRollbackApproval(ctx, b, msg, num)
|
|
}
|
|
}
|
|
|
|
func (g *Gateway) showCheckpoints(ctx context.Context, b *bot.Bot, chatID int64, threadID int) {
|
|
checkpoints, err := g.Dangerous.ListCheckpoints(ctx)
|
|
if err != nil {
|
|
g.log.Error("list checkpoints failed", "error", err)
|
|
g.sendMessage(ctx, b, chatID, threadID, "Could not list checkpoints.")
|
|
return
|
|
}
|
|
if len(checkpoints) == 0 {
|
|
g.sendMessage(ctx, b, chatID, threadID, "No checkpoints available.")
|
|
return
|
|
}
|
|
var text strings.Builder
|
|
text.WriteString("Available checkpoints:\n\n")
|
|
for _, c := range checkpoints {
|
|
fmt.Fprintf(&text, "%d — %s (%s)", c.Number, c.Timestamp.Format("2006-01-02 15:04"), c.Label)
|
|
if c.Size != "" {
|
|
fmt.Fprintf(&text, " — %s", c.Size)
|
|
}
|
|
text.WriteByte('\n')
|
|
}
|
|
text.WriteString("\nUse /rollback <number> to restore a checkpoint.")
|
|
g.sendMessage(ctx, b, chatID, threadID, text.String())
|
|
}
|
|
|
|
func (g *Gateway) requestRollbackApproval(ctx context.Context, b *bot.Bot, msg *models.Message, num int) {
|
|
rest := fmt.Sprintf("%d", num)
|
|
if g.hasPermanentApproval(msg.From.ID, "/rollback") {
|
|
result, err := g.Dangerous.Rollback(ctx, num)
|
|
if err != nil {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Rollback failed: %v", err))
|
|
return
|
|
}
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Rollback to checkpoint "+rest+":\n\n"+result)
|
|
return
|
|
}
|
|
|
|
cmdText := fmt.Sprintf("/rollback %d", num)
|
|
desc := fmt.Sprintf("Rollback to checkpoint %d", num)
|
|
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
|
|
return g.Dangerous.Rollback(ctx, num)
|
|
})
|
|
|
|
params := &bot.SendMessageParams{
|
|
ChatID: msg.Chat.ID,
|
|
Text: rollbackApprovalText(num),
|
|
ReplyMarkup: g.dangerousKeyboard(token),
|
|
}
|
|
if msg.MessageThreadID != 0 {
|
|
params.MessageThreadID = msg.MessageThreadID
|
|
}
|
|
if _, err := b.SendMessage(ctx, params); err != nil {
|
|
g.log.Error("send dangerous prompt (rollback) failed", "error", err)
|
|
}
|
|
}
|
|
|
|
func rollbackApprovalText(num int) string {
|
|
return fmt.Sprintf(
|
|
"⚠️ **Dangerous command**\n\n"+
|
|
"Command: `/rollback %d`\n"+
|
|
"Effect: Restore the worktree filesystem to checkpoint %d.\n"+
|
|
"This will discard any changes made after that checkpoint.\n\n"+
|
|
"_This request expires in 10 minutes._",
|
|
num, num,
|
|
)
|
|
}
|
|
|
|
// ── /stop handler ──────────────────────────────────────────────
|
|
|
|
// stopCurrentTurn cancels whatever this conversation is currently doing.
|
|
//
|
|
// Cancellation propagates through the turn's context, so it reaches the
|
|
// model stream and any tool running underneath it -- a shell command built
|
|
// with exec.CommandContext is killed with the turn, which is the case that
|
|
// matters. Whatever the reply had already streamed stays on screen: it is
|
|
// the record of what Archie did before being stopped.
|
|
func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
|
|
var cancelled bool
|
|
var dropped int
|
|
|
|
session := conversationID(msg).String()
|
|
if g.turns != nil {
|
|
cancelled, dropped = g.turns.Stop(session)
|
|
g.log.Info("stop requested", "session", session, "cancelled", cancelled, "dropped", dropped)
|
|
}
|
|
if client != nil {
|
|
if res, err := client.Cancel(ctx, session); err == nil {
|
|
if res.Cancelled {
|
|
cancelled = true
|
|
}
|
|
dropped += res.Dropped
|
|
}
|
|
}
|
|
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
|
stopReport(cancelled, dropped, nil))
|
|
}
|
|
|
|
// stopReport describes what a /stop actually stopped.
|
|
//
|
|
// It names the parts rather than saying "stopped" unconditionally.
|
|
// Claiming success when nothing was running teaches the operator to
|
|
// distrust the command at exactly the moment they need to believe it.
|
|
func stopReport(cancelled bool, dropped int, tasks []int64) string {
|
|
var parts []string
|
|
if cancelled {
|
|
parts = append(parts, "the running reply")
|
|
}
|
|
if dropped > 0 {
|
|
parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped))
|
|
}
|
|
if len(tasks) > 0 {
|
|
ids := make([]string, len(tasks))
|
|
for i, id := range tasks {
|
|
ids[i] = fmt.Sprintf("#%d", id)
|
|
}
|
|
parts = append(parts, "task(s) "+strings.Join(ids, ", "))
|
|
}
|
|
|
|
if len(parts) == 0 {
|
|
return "Nothing is running.\n\nUse /stop <process-name> to terminate a background process."
|
|
}
|
|
return "🛑 Stopped " + joinWithAnd(parts) + "."
|
|
}
|
|
|
|
// joinWithAnd renders a list the way it would be read aloud.
|
|
func joinWithAnd(parts []string) string {
|
|
switch len(parts) {
|
|
case 1:
|
|
return parts[0]
|
|
case 2:
|
|
return parts[0] + " and " + parts[1]
|
|
default:
|
|
return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1]
|
|
}
|
|
}
|
|
|
|
// stopHandler serves /stop.
|
|
//
|
|
// Bare /stop is the emergency brake: it cancels the conversation's running
|
|
// turn immediately, with no approval step. Approval exists to protect
|
|
// against destructive commands, and stopping is the opposite -- gating it
|
|
// behind a confirmation round-trip would defeat the entire point.
|
|
//
|
|
// /stop <process-name> keeps the original behaviour of terminating a named
|
|
// background process, which is destructive and still requires approval.
|
|
func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc {
|
|
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
msg, ok := g.authorizedMessage(ctx, b, update)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/stop", ""))
|
|
if rest == "" {
|
|
g.stopCurrentTurn(ctx, b, msg, client)
|
|
return
|
|
}
|
|
|
|
if g.Dangerous == nil {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Process control is not configured for this installation.")
|
|
return
|
|
}
|
|
|
|
// Check permanent approval.
|
|
if g.hasPermanentApproval(msg.From.ID, "/stop") {
|
|
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Stop failed: %v", err))
|
|
return
|
|
}
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Process stopped: "+rest)
|
|
return
|
|
}
|
|
|
|
cmdText := fmt.Sprintf("/stop %s", rest)
|
|
desc := fmt.Sprintf("Stop process %q", rest)
|
|
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
|
|
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
|
|
return "", err
|
|
}
|
|
return "", nil
|
|
})
|
|
|
|
params := &bot.SendMessageParams{
|
|
ChatID: msg.Chat.ID,
|
|
Text: fmt.Sprintf(
|
|
"⚠️ **Dangerous command**\n\n"+
|
|
"Command: `/stop %s`\n"+
|
|
"Effect: Terminate the running background process %q.\n"+
|
|
"This will discard any in-progress work on that process.\n\n"+
|
|
"_This request expires in 10 minutes._",
|
|
rest, rest,
|
|
),
|
|
ReplyMarkup: g.dangerousKeyboard(token),
|
|
}
|
|
if msg.MessageThreadID != 0 {
|
|
params.MessageThreadID = msg.MessageThreadID
|
|
}
|
|
if _, err := b.SendMessage(ctx, params); err != nil {
|
|
g.log.Error("send dangerous prompt (stop) failed", "error", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── helpers ────────────────────────────────────────────────────
|
|
|
|
// restAfterTelegram strips a slash-command token from a Telegram message
|
|
// text, including an optional @bot suffix.
|
|
func restAfterTelegram(text, cmd, gatewayName string) string {
|
|
s := text
|
|
if gatewayName != "" {
|
|
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
|
|
}
|
|
s = strings.TrimPrefix(s, cmd)
|
|
return s
|
|
}
|
|
|
|
func makeDangerousToken() string {
|
|
bytes := make([]byte, 16)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
panic("crypto/rand: " + err.Error())
|
|
}
|
|
return hex.EncodeToString(bytes)
|
|
}
|
|
|
|
// parseDangerousCallback splits a dangerous-command callback data into
|
|
// decision ("approve", "permanent", "deny") and token.
|
|
func parseDangerousCallback(data string) (decision, token string) {
|
|
data = strings.TrimPrefix(data, dangerousCmdPrefix)
|
|
decision, token, _ = strings.Cut(data, ":")
|
|
if decision != "approve" && decision != "permanent" && decision != "deny" {
|
|
return "", ""
|
|
}
|
|
return decision, token
|
|
}
|
|
|
|
// ── /approve and /deny handlers ─────────────────────────────────
|
|
|
|
// approveHandler serves /approve: list any pending dangerous commands,
|
|
// or approve a specific one by token. When a pending command exists, the
|
|
// user interacts via inline buttons rather than typing /approve directly;
|
|
// this handler is for the edge case where a user types /approve without
|
|
// a pending command context.
|
|
func (g *Gateway) approveHandler() 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.Dangerous == nil {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
|
"Dangerous-command approval is not configured.\n\n"+
|
|
"Use /rollback or /stop to trigger approval inline.")
|
|
return
|
|
}
|
|
|
|
g.dangerousMu.Lock()
|
|
now := time.Now()
|
|
var pending []dangerousAction
|
|
for key, action := range g.dangerousActions {
|
|
if !action.expiresAt.After(now) {
|
|
delete(g.dangerousActions, key)
|
|
continue
|
|
}
|
|
if action.recipient == msg.From.ID {
|
|
pending = append(pending, action)
|
|
}
|
|
}
|
|
g.dangerousMu.Unlock()
|
|
|
|
if len(pending) == 0 {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
|
"No pending commands to approve.\n\n"+
|
|
"Use /rollback or /stop to trigger a dangerous command approval inline.")
|
|
return
|
|
}
|
|
|
|
var text strings.Builder
|
|
text.WriteString("Pending dangerous commands:\n\n")
|
|
for i, action := range pending {
|
|
fmt.Fprintf(&text, "%d. %s", i+1, action.description)
|
|
remaining := time.Until(action.expiresAt).Truncate(time.Second)
|
|
fmt.Fprintf(&text, " (expires in %s)", remaining)
|
|
text.WriteByte('\n')
|
|
}
|
|
text.WriteString("\nUse the inline buttons on each pending command to approve or deny.")
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, text.String())
|
|
}
|
|
}
|
|
|
|
// denyHandler serves /deny: the counterpart to /approve for rejecting
|
|
// pending dangerous commands. Like /approve, the primary interaction is
|
|
// through inline buttons on each pending command.
|
|
func (g *Gateway) denyHandler() bot.HandlerFunc {
|
|
return g.approveHandler() // Same behaviour: show pending commands.
|
|
}
|