Files
archie/internal/app/archied/gateway_runtime.go
T
sam 36981c2024 feat(statestore): CancelExecution, and one cancel path for daemon stop and operator actions
Plan item 5 of docs/prds/execution-tree-state-machine.md (archie-core-1217).
Until now a stop was a context cancel plus a caller-side transition, and the
step rows a worker still held running could never be told: the execution moved
while the work carried on, and the old interrupt-first ordering existed only
because the record could not defend itself. The step table can: the PRD's
ordering -- the store is the record, the context cancel is the delivery --
became safe the moment a worker's next step write fails ErrStaleTransition
against a cancelled step.

- storecontract.ExecutionCanceller and the CancelExecution RPC: one
  transaction moves every non-terminal StepExecution of the execution's
  current attempt to cancelled (one event row each, in the same
  transaction), and the execution itself to the status the operator action
  names, under the shared transition table with its audit row. Staleness is
  decided before legality, the way guardTransition decides it. Earlier
  attempts are never rewritten. Deliberately administrative: the
  deny-by-default grant rule covers it, pinned by a test.
- taskactions.Service routes stop, cancel, abandon and reject through it and
  the old Transition/CancelTask combinations are deleted; the daemon's
  in-memory cancel is demoted to the delivery hook the PRD names, called
  after the store record.
- The gateway's chat controller records first and delivers second, the same
  order, and records even when no runtime is wired here (a standalone
  gateway cannot reach the daemon's goroutines): the record is what unsticks
  a lost-cancel task, and the delivery is best effort. StopRunning and
  TaskRuntime.CancelRunningTasks are deleted outright -- no production
  caller remained once the task_action tool owned stopping, and the daemon's
  CancelRunningTasks/runningTasks.stopAll go with them.
- The gateway's chat adapter writes through CancelExecution instead of a
  bare Transition, so chat /cancel and the dashboard's action service land
  on the same path.

PRD decisions recorded here:
- Each cancelled step's event row is stage_finish with {cancelled: true} and
  the reason as its detail -- the exact-one-event-per-step-transition rule
  covers the pending -> cancelled transition too, even for a step that never
  ran.
- A parked cancel carries the needs_human class, matching the Transition
  path this replaces; the transient class stays with parkRunningTask's
  unwind parks, which now meet ErrStaleTransition for cancelled runs and are
  ignored there.
- Cancelling a wait:true callee is deferred to #1216's agent-call children:
  the callee's own tree and the wait flag are what make
  "cancelling a caller cancels each callee it waits on" decidable, and the
  callee writes it cannot fake are this issue's half of the contract.
- RecoverStale's interrupted sweep is plan item 6, untouched here.
2026-09-27 06:34:01 +10:00

148 lines
6.3 KiB
Go

package archied
import (
"context"
"fmt"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/tools"
)
// setupChatRuntime wires the model runtime, tool registry, persona registry,
// chat task creator/controller, default chat identity and the release-update
// service. The daemon and the standalone Gateway build through this one
// constructor so the two processes cannot diverge.
func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error {
// ── LLM runtime ──────────────────────────────────────────────────
// Created before the router so the LLMResponder can be wired in for
// non-command message processing.
providers := executionProviders(cfg)
b.setLLM(agentexec.NewRuntime(providers))
b.toolReg = tools.NewRegistry()
chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels)
chatModels.ApplyModelCatalog(b.catalog)
b.chatModels = chatModels
// ── Persona registry ─────────────────────────────────────────────
if b.personas == nil {
personas, version, err := b.controlPlane.Personas(ctx)
if err != nil {
return fmt.Errorf("load personas: %w", err)
}
b.personas = gateway.NewPersonaRegistry(nil)
b.applyPersonas(personas, version)
if err := b.watchPersonas(ctx, version); err != nil {
return fmt.Errorf("watch personas: %w", err)
}
}
// ── Operator health surface ──────────────────────────────────────
// Built before the gateways because every turn runner and router built
// later carries both: the recorder is written by sendChatTurn, the source
// is read by /status.
b.providerOutcomes = newProviderOutcomeRecorder()
b.statusHealth = newStatusHealth(b)
profiles, defaultChatIdentity := chatTaskProfiles(cfg)
var chatTasks gateway.TaskCreator
if len(profiles) > 0 {
chatTasks = gateway.NewStoreTaskCreatorForProfiles(
chatTaskWriterAdapter{enqueue: b.stateStore.EnqueueChatTask},
profiles,
)
}
b.chatTasks = chatTasks
b.defaultChatIdentity = defaultChatIdentity
var canceller storecontract.ExecutionCanceller
if ec, ok := b.stateStore.(storecontract.ExecutionCanceller); ok {
canceller = ec
}
b.chatController = gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: b.stateStore.TaskByID,
requeue: b.stateStore.Requeue,
cancelExecution: canceller.CancelExecution,
})
b.updateService = makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
return nil
}
// watchPersonas keeps the persona stream established for the life of the
// process. The first stream is opened synchronously, so a control plane that
// cannot be watched at all fails the boot that asked for it rather than
// leaving the process running personas it can no longer update; after that the
// watch reconnects instead of ending (see keepWatch).
//
// Persona updates are not reported through apply status -- the personas kind
// has no apply-status wiring, which is archie-core-aj35, not this watch.
func (b *boot) watchPersonas(ctx context.Context, version int64) error {
updates, err := b.controlPlane.WatchPersonas(ctx, version)
if err != nil {
return err
}
go keepWatch(ctx, b.log, controlplane.PersonasKind, version, updates,
b.controlPlane.WatchPersonas,
waitFor,
func(update controlplane.AppliedPersonas) int64 { return update.Version },
func(update controlplane.AppliedPersonas) {
if update.Err != nil {
b.log.Error("persona watch failed", "err", update.Err)
return
}
b.applyPersonas(update.Collection, update.Version)
})
return nil
}
func (b *boot) applyPersonas(collection agent.PersonaCollection, version int64) {
personas := make([]gateway.Persona, 0, len(collection.Personas))
for _, persona := range collection.Personas {
personas = append(personas, gateway.Persona{Name: persona.Name, Prompt: persona.Prompt})
}
b.personas.Replace(personas, collection.Default)
b.log.Info("personas applied", "version", version)
}
// setupGatewayChat is the sole production constructor of the local contract.
// Frontends use its gRPC representation; only this service owns the router.
func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
if err := b.setupChatRuntime(ctx, b.cfg); err != nil {
return nil, err
}
cfg := b.cfg
router := gateway.NewRouter(b.stateStore, nil, "web")
router.Limiter = b.rateLimiter
router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
router.Models = b.chatModels
router.Personas = b.personas
router.Updates = b.updateService
router.InitSessions(b.chatSessionStore)
configureTaskCommands(router, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity)
router.Health = b.statusHealth
setup := chatSetup{
Cfg: config.NewHolder(cfg), LLM: b.chatLLM, ChatModels: b.chatModels, ToolReg: b.toolReg,
Personas: b.personas, ChatTasks: b.chatTasks,
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.stateStore.TaskByID, taskLogs: b.taskLogs},
ChatTaskActor: actor, ChatPRReviewer: b.prReviewer(),
DefaultChatIdentity: b.defaultChatIdentity,
Bus: b.bus, Log: b.log,
MemoryEngine: b.memoryStore(),
MemoryWriter: b.memoryWriter(),
// The Gateway executes the web chat's turns, so it is the process
// that must record their outcomes for /status.
ProviderOutcomes: b.providerOutcomes,
}
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router)
router.Titles = newChatTitleGenerator(setup)
router.Log = b.log
return &gateway.LocalChatAdapter{
Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log),
Models: b.chatModels, Personas: b.personas, TaskActor: actor,
}, nil
}