Files
archie/modules/runs/investigate_test.go
T
sam 90637aa457 fix(runs): settle held actions a skipped or failed approval would leave
The end-of-run decision read the document's last approval step alone, so a conditional approval that was skipped, or one that continued past a failure, let a run finish without ever putting its held actions to people. Those approvals no longer count as settling. Resume still replays the agent and the request exactly once.

Triggers and dry runs now refuse a document that names an identity or profile, dry runs check required inputs, and step ids cannot contain dots that references read as separators.

The shipped investigate document gains a test that holds an action, suspends, resumes through the journal and reports one approved action.

Refs #2039
2026-11-21 01:20:21 +11:00

222 lines
8.1 KiB
Go

package runs
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/runs/internal/store"
)
// TestContinuedFailureDoesNotSwallowSuspension guards the run's stop signals:
// on_failure continue covers a step's own failure, never a suspension, a lost
// lease or a cancellation. A continued suspension would run the rest of the
// workflow while the step is still waiting.
func TestContinuedFailureDoesNotSwallowSuspension(t *testing.T) {
doc, err := ParseDocument(`steps:
- {type: workflow.sleep, on_failure: continue, settings: {for: 1h}}
- {type: run.notify, settings: {title: too soon}}
`)
if err != nil {
t.Fatalf("ParseDocument: %v", err)
}
told := &notices{}
wf := Deps{Settings: onePersonPath{}, Judge: &actionJudge{}, Notifier: told}.Compile(doc)
rc := newContext(t.Context(), &fakeWork{}, store.Run{ID: uuid.New()}, uuid.New(), nil)
if _, err := wf(rc, jsontext.Value(`null`)); !errors.Is(err, errSuspended) {
t.Fatalf("run error = %v, want a suspension", err)
}
if len(told.sent) != 0 {
t.Fatalf("a suspended run sent %d notifications", len(told.sent))
}
}
// investigateModel calls the action tool once, reports findings once the tool
// has answered, and answers any later turn (such as recording the cause)
// without a tool call.
type investigateModel struct {
tool string
calls int
}
func (m *investigateModel) Name() string { return "investigate-fake" }
func (m *investigateModel) Chat(_ context.Context, req chat.Request) (chat.Response, error) {
m.calls++
for _, tool := range req.Tools {
if tool.Name != m.tool {
continue
}
last := req.Messages[len(req.Messages)-1]
if last.Role == chat.RoleTool {
return chat.Response{
Role: chat.RoleAssistant, FinishReason: "stop",
Content: "web-1 is out of disk; restart it.",
}, nil
}
return chat.Response{
Role: chat.RoleAssistant, FinishReason: "tool_calls",
ToolCalls: []chat.ToolCall{{ID: "call-1", Name: m.tool, Arguments: `{"target":"web-1"}`}},
}, nil
}
return chat.Response{Role: chat.RoleAssistant, FinishReason: "stop", Content: "no incident recorded"}, nil
}
func (m *investigateModel) ChatStream(context.Context, chat.Request) (chat.Stream, error) {
return nil, errors.New("not streamed")
}
// investigateSettings resolves the default agent model and offers the fake
// model to every agent step.
type investigateSettings struct {
onePersonPath
model chat.Provider
}
func (s investigateSettings) AgentModelForAlias(context.Context, string) (governance.Model, error) {
return governance.Model{Model: "test"}, nil
}
func (s investigateSettings) AgentProvider(context.Context, governance.Model) (chat.Provider, chat.ModelInfo, error) {
return s.model, chat.ModelInfo{}, nil
}
func (investigateSettings) AttemptsPerRun(context.Context) (int, error) { return 8, nil }
// EscalationPath waits long enough that the first attempt suspends, as a
// person who has not answered yet does.
func (investigateSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) {
return []governance.PathStep{{Person: "p", DeadlineMS: time.Hour.Milliseconds()}}, nil
}
// investigateBox declares one action so the model has something to call. The
// judge decides it, so the connector itself is never invoked.
type investigateBox struct{}
func (investigateBox) Declarations() []connectors.Declaration {
return []connectors.Declaration{{
Connector: "host", Kind: connectors.KindAction, Name: "restart",
Description: "Restart a host",
Schema: jsontext.Value(`{"type":"object","properties":{"target":{"type":"string"}},"required":["target"]}`),
}}
}
func (investigateBox) Tool(string) (connectors.Tool, bool) { return nil, true }
// heldJudge is actionJudge with the real Execute contract for held actions: a
// held action is not run by the agent's tool call, only by an approval.
type heldJudge struct{ actionJudge }
func (j *heldJudge) Execute(ctx context.Context, d judgement.Decision, input jsontext.Value, key string) (string, error) {
if !d.Level.Runs() {
return "", judgement.ErrHeld
}
return j.actionJudge.Execute(ctx, d, input, key)
}
// investigateMemory records nothing; the workflow only needs the finish step.
type investigateMemory struct{}
func (investigateMemory) Past(context.Context, uuid.UUID, memory.Target) ([]memory.Incident, error) {
return nil, nil
}
func (investigateMemory) Record(context.Context, uuid.UUID, jsontext.Value, memory.Target, string, string) error {
return nil
}
func (investigateMemory) Finish(context.Context, uuid.UUID, []memory.Action, int) (memory.Review, error) {
return memory.Review{}, nil
}
// TestInvestigateDocumentSuspendsAndResumes guards the document the binary
// ships: it investigates the event, holds its action for approval, suspends
// while the person decides, and on resume replays the agent and the request
// instead of asking or running anything twice.
func TestInvestigateDocumentSuspendsAndResumes(t *testing.T) {
doc, err := ParseDocument(InvestigateDocument())
if err != nil {
t.Fatalf("the shipped investigate document doesn't parse: %v", err)
}
model := &investigateModel{tool: toolName("host", "restart")}
judge := &heldJudge{actionJudge{levels: map[string]judgement.Level{"restart": judgement.ProposeAndWait}}}
asked := &askCounter{}
told := &notices{}
deps := Deps{
Settings: investigateSettings{model: model}, Toolbox: investigateBox{},
Judge: judge, Approver: asked, Notifier: told, Memory: investigateMemory{},
}
run := store.Run{
ID: uuid.New(), OrgID: "org", Workflow: "investigate", Version: 1,
Input: jsontext.Value(`{"event":{"fields":{"host":"web-1"}}}`),
}
// The first attempt proposes the action, asks once and suspends on the
// person's answer.
first := &fakeWork{}
engine := newEngine(nil, first, slog.New(slog.DiscardHandler), Options{})
useWorkflow(engine, deps.Compile(doc))
engine.execute(t.Context(), run, uuid.New())
if len(first.finished) != 0 {
t.Fatalf("the first attempt finished %v instead of suspending", first.finished)
}
if asked.asked != 1 || judge.executed != 0 {
t.Fatalf("first attempt asked %d and executed %d, want 1 and 0", asked.asked, judge.executed)
}
// The resumed attempt replays the agent and the request, takes the answer,
// runs the action once and reports one notification.
calls := model.calls
resumed := &signalAfter{steps: first.steps, arrives: 1}
engine = newEngine(nil, resumed, slog.New(slog.DiscardHandler), Options{})
useWorkflow(engine, deps.Compile(doc))
engine.execute(t.Context(), run, uuid.New())
if len(resumed.finished) != 1 || resumed.finished[0] != store.StateSucceeded {
t.Fatalf("resumed run finished %v, want one success", resumed.finished)
}
if asked.asked != 1 {
t.Fatalf("the resumed run asked %d times in total, want the first attempt's one", asked.asked)
}
if judge.executed != 1 {
t.Fatalf("the resumed run executed the action %d times, want once", judge.executed)
}
if model.calls != calls {
t.Fatalf("the resumed run called the model %d times, want none", model.calls-calls)
}
if len(told.sent) != 1 {
t.Fatalf("the run sent %d notifications, want one", len(told.sent))
}
if body := told.sent[0].Body; !strings.Contains(body, "restart") || !strings.Contains(body, approvals.StateApproved) {
t.Fatalf("the notification doesn't report the approved action: %q", body)
}
asks := 0
for _, s := range resumed.steps {
if strings.HasPrefix(s.Name, "ask:") {
asks++
}
}
if asks != 1 {
t.Fatalf("the run recorded %d approval requests, want one", asks)
}
var result AgentResult
if err := json.Unmarshal(resumed.results[0], &result); err != nil {
t.Fatalf("run result: %v", err)
}
if result.Answer == "" {
t.Fatalf("run result has no findings: %s", resumed.results[0])
}
}