From 208a1a9c38fd7bb6b06053e3cd675b1cf53fcda7 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 26 Sep 2026 13:17:02 +1000 Subject: [PATCH] feat(workflow): workflow.call step with save-time input and cycle checks (archie-core-t2db.41) --- internal/domain/workflow/definition.go | 14 +- internal/domain/workflow/task/caller.go | 21 ++ internal/domain/workflow/task/task.go | 8 + internal/domain/workflow/workflow.go | 6 + internal/domain/workflow/workflow_call.go | 319 +++++++++++++++++ .../domain/workflow/workflow_call_test.go | 329 ++++++++++++++++++ internal/events/events.go | 10 + .../workflowsteps/workflowsteps.go | 2 +- 8 files changed, 704 insertions(+), 5 deletions(-) create mode 100644 internal/domain/workflow/task/caller.go create mode 100644 internal/domain/workflow/workflow_call.go create mode 100644 internal/domain/workflow/workflow_call_test.go diff --git a/internal/domain/workflow/definition.go b/internal/domain/workflow/definition.go index f5239bee4..9b5e81177 100644 --- a/internal/domain/workflow/definition.go +++ b/internal/domain/workflow/definition.go @@ -25,8 +25,9 @@ type YAMLDefinition struct { // repoFreeStepTypes are the step types that run without a repository. A // workflow whose repository is not required may use only these, since it may -// run with no worktree at all. -var repoFreeStepTypes = map[string]bool{AgentRunStepName: true} +// run with no worktree at all. workflow.call needs none of the caller's own: +// the callee's own repository mode decides whether its run clones. +var repoFreeStepTypes = map[string]bool{AgentRunStepName: true, WorkflowCallStepName: true} // StepRecord selects one registered step type and supplies its typed settings. type StepRecord struct { @@ -112,9 +113,13 @@ type ( WorkflowDefinitionCollection = task.WorkflowDefinitionCollection ) -// ValidateDefinitionCollection rejects malformed, duplicate, or mismatched definitions. +// ValidateDefinitionCollection rejects malformed, duplicate, or mismatched +// definitions, and every workflow.call step a definition carries: the callee +// must exist, its inputs must be satisfiable, and the call graph must be +// acyclic (docs/prds/workflow-calls.md). func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, registry StepRegistry) error { seen := make(map[string]struct{}, len(collection.Definitions)) + parsed := make(map[string]YAMLDefinition, len(collection.Definitions)) for _, entry := range collection.Definitions { if _, ok := seen[entry.ID]; ok { return fmt.Errorf("duplicate workflow id %q", entry.ID) @@ -127,8 +132,9 @@ func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, regis if definition.ID != entry.ID { return fmt.Errorf("workflow entry id %q does not match YAML id %q", entry.ID, definition.ID) } + parsed[entry.ID] = definition } - return nil + return validateWorkflowCalls(parsed) } // DecodeDefinitionCollection strictly decodes the control-plane projection. diff --git a/internal/domain/workflow/task/caller.go b/internal/domain/workflow/task/caller.go new file mode 100644 index 000000000..a849505c1 --- /dev/null +++ b/internal/domain/workflow/task/caller.go @@ -0,0 +1,21 @@ +package task + +import "context" + +// Caller is what a workflow.call step uses to start a callee run and read it +// back while waiting. It is the consumer-owned contract the workflow engine +// holds (the same shape as Store), satisfied by *staterpc.Client for an +// agent-container run: the callee is a first-class task the State Store +// derives from the caller's row (docs/prds/workflow-calls.md). +type Caller interface { + // StartCall enqueues the callee task for callerTaskID's workflow.call + // step: org, workspace, identity, owner, repo and issue number are + // derived from the caller's row, the callee carries the call's inputs, + // and the callee's depth is the caller's + 1. The store refuses a + // caller that is not running and a call past the depth limit. + StartCall(ctx context.Context, callerTaskID int64, workflow string, inputs map[string]any) (*Task, error) + // CallStatus reads one call's callee: its status and latest transition + // detail. A store only answers for a task whose call_parent_task_id is + // callerTaskID, so a caller reads only its own callees. + CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (status, detail string, err error) +} diff --git a/internal/domain/workflow/task/task.go b/internal/domain/workflow/task/task.go index d0df7a328..2cdbd0070 100644 --- a/internal/domain/workflow/task/task.go +++ b/internal/domain/workflow/task/task.go @@ -122,6 +122,14 @@ type Task struct { // budget: one shared counter made N operator retries eat the // review-remediation budget and vice versa. RemediationRounds int `json:"remediation_rounds"` + // CallParentTaskID is the task whose workflow.call step started this + // one; 0 on a root run. A caller reads only the tasks it started, + // through WorkflowCallStatus. + CallParentTaskID int64 `json:"call_parent_task_id,omitempty"` + // CallDepth counts workflow.call hops from the root run. The engine + // refuses a call past workflow.MaxCallDepth, and the store re-checks on + // insert, so no enqueue path can pass the limit. + CallDepth int `json:"call_depth,omitempty"` // CreatedAt and UpdatedAt are the SQLite row timestamps, exposed so // callers can show a task's age and last activity. They are written by // column defaults and the UPDATE statements, never by the caller. diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 156202753..5e893cdd4 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/tools" @@ -82,6 +83,11 @@ type TaskContext struct { Store Store Trees Trees Agent agentexec.Runner + // Calls starts workflow.call callees and reads them back while a + // wait:true caller waits. Nil is only safe for a workflow with no + // workflow.call step: such a step in a runner with no capability + // fails the run with a named error (docs/prds/workflow-calls.md). + Calls task.Caller // Reviewer runs the adversarial self-review stage (StageReview). Nil // is only safe when Repo.ReviewEnabled is false; StageReview parks // rather than silently skipping if it is enabled with no Reviewer diff --git a/internal/domain/workflow/workflow_call.go b/internal/domain/workflow/workflow_call.go new file mode 100644 index 000000000..ac33236ce --- /dev/null +++ b/internal/domain/workflow/workflow_call.go @@ -0,0 +1,319 @@ +package workflow + +import ( + "context" + "fmt" + "regexp" + "strings" + "time" + + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// WorkflowCallStepName is the step type that starts another workflow as its +// own run. The callee is a first-class task the State Store derives from the +// caller's row: its own pinned definition, its own agent profile, its own +// container and its own outcome (docs/prds/workflow-calls.md). +const WorkflowCallStepName = "workflow.call" + +// MaxCallDepth bounds how deep one run may call callees. A cycle is refused +// at save, so the limit is not a loop guard -- it bounds a legitimate fan-out +// chain, and every wait:true caller on the path holds its container while it +// waits, so an unbounded depth would pin unbounded containers. +const MaxCallDepth = 5 + +// callPollInterval is how often a wait:true caller re-reads its callee's +// status. A var so tests do not sleep. +var callPollInterval = 2 * time.Second + +// workflowCallSettings are the workflow.call step's settings. An inputs value +// is either a literal or a reference to the calling workflow's declared +// input, written "inputs." -- the PRD's `inputs: { src_ip: +// inputs.src_ip }` shape. +type workflowCallSettings struct { + Workflow string `yaml:"workflow"` + Inputs map[string]any `yaml:"inputs,omitempty"` + Wait bool `yaml:"wait,omitempty"` +} + +// callReference is the prefix an inputs value must carry to be read as a +// reference to the calling workflow's declared input. +const callReference = "inputs." + +// refName is the identifier grammar a reference suffix must match, shared +// with the workflow interface's input names. +var refName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// WorkflowCallStepType contributes the workflow.call step type. +func WorkflowCallStepType() StepType { + return StepType{Name: WorkflowCallStepName, Factory: newWorkflowCallStage} +} + +func newWorkflowCallStage(settings yaml.Node) (Stage, error) { + var s workflowCallSettings + if settings.Kind == 0 { + return Stage{}, fmt.Errorf("%s: settings.workflow is required", WorkflowCallStepName) + } + if err := settings.Decode(&s); err != nil { + return Stage{}, fmt.Errorf("%s: %w", WorkflowCallStepName, err) + } + if strings.TrimSpace(s.Workflow) == "" { + return Stage{}, fmt.Errorf("%s: settings.workflow is required", WorkflowCallStepName) + } + for name, value := range s.Inputs { + if _, ok := value.(map[string]any); ok { + return Stage{}, fmt.Errorf("%s: input %q must be a literal or an inputs. reference, not a nested document", WorkflowCallStepName, name) + } + if ref, ok := value.(string); ok && strings.HasPrefix(ref, callReference) && !refName.MatchString(strings.TrimPrefix(ref, callReference)) { + return Stage{}, fmt.Errorf("%s: input %q reference %q must name an input as inputs.", WorkflowCallStepName, name, ref) + } + } + return Stage{Name: WorkflowCallStepName, Run: func(ctx context.Context, tc *TaskContext) error { + return runWorkflowCall(ctx, s, tc) + }}, nil +} + +// runWorkflowCall starts the callee and, with wait true, waits for its +// terminal state. The callee reports on its own run; the call is recorded on +// the caller's timeline. +func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContext) error { + if tc.Calls == nil { + return fmt.Errorf("%s: this runner carries no callee capability", WorkflowCallStepName) + } + if tc.Task.CallDepth+1 > MaxCallDepth { + return fmt.Errorf("%s: call depth %d would pass the limit of %d", WorkflowCallStepName, tc.Task.CallDepth+1, MaxCallDepth) + } + inputs, err := resolveCallInputs(s.Inputs, tc.Task.Inputs) + if err != nil { + return fmt.Errorf("%s: %w", WorkflowCallStepName, err) + } + callee, err := tc.Calls.StartCall(ctx, tc.Task.ID, s.Workflow, inputs) + if err != nil { + return fmt.Errorf("%s: start %q: %w", WorkflowCallStepName, s.Workflow, err) + } + started := map[string]any{"callee_task_id": callee.ID, "workflow": s.Workflow, "wait": s.Wait} + if err := tc.EmitDurable(ctx, events.KindWorkflowCallStarted, WorkflowCallStepName, + fmt.Sprintf("started %q as task %d", s.Workflow, callee.ID), started); err != nil { + tc.Log.Warn("workflow call start not persisted", "err", err) + } + if !s.Wait { + return nil + } + return awaitCallee(ctx, s, tc, callee.ID) +} + +// resolveCallInputs turns the call's saved values into the callee's inputs: a +// reference reads the caller's actual input, a literal passes through. +func resolveCallInputs(call, callerInputs map[string]any) (map[string]any, error) { + if len(call) == 0 { + return nil, nil + } + resolved := make(map[string]any, len(call)) + for name, value := range call { + if ref, ok := value.(string); ok && isCallReference(ref) { + got, present := callerInputs[strings.TrimPrefix(ref, callReference)] + if !present { + return nil, fmt.Errorf("input %q references %q, which the calling workflow's run does not carry", name, ref) + } + resolved[name] = got + continue + } + resolved[name] = value + } + return resolved, nil +} + +// isCallReference reports whether a saved string value is a reference to the +// calling workflow's declared input. A literal that merely begins with +// "inputs." but does not name an input reads as the literal it is. +func isCallReference(value string) bool { + return strings.HasPrefix(value, callReference) && refName.MatchString(strings.TrimPrefix(value, callReference)) +} + +// callEnded reports whether a callee status ends the caller's wait. A parked +// callee ends it too: the callee will not move without an operator, so the +// caller must not wait for one. +func callEnded(status string) bool { + switch status { + case StatusCompleted, StatusPROpen, StatusMerged, StatusParked, StatusDead, StatusRejected, StatusClosedWontDo: + return true + default: + return false + } +} + +// awaitCallee polls the callee until it is terminal, failing the stage with +// the callee's detail when the callee did not succeed. The caller's own wall +// clock bounds the wait. +func awaitCallee(ctx context.Context, s workflowCallSettings, tc *TaskContext, callTaskID int64) error { + for { + status, detail, err := tc.Calls.CallStatus(ctx, tc.Task.ID, callTaskID) + if err != nil { + return fmt.Errorf("%s: read task %d: %w", WorkflowCallStepName, callTaskID, err) + } + if callEnded(status) { + if callSucceeded(status) { + if err := tc.EmitDurable(ctx, events.KindWorkflowCallFinished, WorkflowCallStepName, + fmt.Sprintf("%q (task %d) finished: %s", s.Workflow, callTaskID, detail), + map[string]any{"callee_task_id": callTaskID, "workflow": s.Workflow, "status": status, "detail": detail}); err != nil { + tc.Log.Warn("workflow call finish not persisted", "err", err) + } + return nil + } + return fmt.Errorf("%s: callee %q (task %d) ended %s: %s", WorkflowCallStepName, s.Workflow, callTaskID, status, detail) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(callPollInterval): + } + } +} + +// callSucceeded reports whether a callee's terminal state satisfies its +// caller. pr_open and merged are successes: a repository callee opens its PR +// and reports on it as its own outcome. +func callSucceeded(status string) bool { + switch status { + case StatusCompleted, StatusPROpen, StatusMerged: + return true + default: + return false + } +} + +// validateWorkflowCalls checks every workflow.call step against the rest of +// the collection: the callee must exist, the call's inputs must satisfy the +// callee's declared inputs, and no workflow may reach itself through calls +// (docs/prds/workflow-calls.md). +func validateWorkflowCalls(parsed map[string]YAMLDefinition) error { + calls := make(map[string][]string, len(parsed)) + for id, d := range parsed { + for i, step := range d.Steps { + if step.Type != WorkflowCallStepName { + continue + } + s, err := decodeCallSettings(step) + if err != nil { + return fmt.Errorf("workflow %q step %d: %w", id, i+1, err) + } + callee, ok := parsed[s.Workflow] + if !ok { + return fmt.Errorf("workflow %q step %d calls %q, which is not defined", id, i+1, s.Workflow) + } + if err := checkCallInputs(id, i, d.WorkflowInterface, callee, s.Inputs); err != nil { + return err + } + calls[id] = append(calls[id], s.Workflow) + } + } + return refuseCallCycles(calls) +} + +func decodeCallSettings(step StepRecord) (workflowCallSettings, error) { + var s workflowCallSettings + if err := step.Settings.Decode(&s); err != nil { + return workflowCallSettings{}, err + } + return s, nil +} + +// checkCallInputs validates one call's saved inputs against the callee's +// declared inputs, resolving references against the calling workflow's own +// declared input types. Values are not known at save time -- types are. +func checkCallInputs(callerID string, index int, caller task.WorkflowInterface, callee YAMLDefinition, inputs map[string]any) error { + for name, value := range inputs { + spec, ok := callee.Inputs[name] + if !ok { + return fmt.Errorf("workflow %q step %d: input %q is not declared by %q", callerID, index+1, name, callee.ID) + } + resolved, err := callInputType(caller, name, value) + if err != nil { + return fmt.Errorf("workflow %q step %d: %w", callerID, index+1, err) + } + if resolved == "" { + // A null literal satisfies the type check vacuously; the + // callee's own run enforces it against the real value. + continue + } + if !task.TypeAccepts(spec.Type, resolved) { + return fmt.Errorf("workflow %q step %d: input %q is %s, want %s", callerID, index+1, name, resolved, spec.Type) + } + } + for name, spec := range callee.Inputs { + if _, assigned := inputs[name]; !assigned && spec.Required { + return fmt.Errorf("workflow %q step %d: input %q is required by %q", callerID, index+1, name, callee.ID) + } + } + return nil +} + +// callInputType names the type a saved call value carries at run time: a +// reference carries the calling workflow's declared input type, a literal its +// own JSON type. An error means the reference names an input the caller does +// not declare. +func callInputType(caller task.WorkflowInterface, name string, value any) (string, error) { + if ref, ok := value.(string); ok && isCallReference(ref) { + spec, ok := caller.Inputs[strings.TrimPrefix(ref, callReference)] + if !ok { + return "", fmt.Errorf("input %q references %q, which the calling workflow does not declare", name, ref) + } + return spec.Type, nil + } + if value == nil { + return "", nil + } + return task.ValueType(value), nil +} + +// refuseCallCycles walks the call graph from every workflow and refuses one +// that reaches itself, directly or through other workflows, naming the path. +func refuseCallCycles(calls map[string][]string) error { + const ( + unseen = 0 + open = 1 + done = 2 + ) + state := make(map[string]int, len(calls)) + var path []string + var walk func(id string) error + walk = func(id string) error { + state[id] = open + path = append(path, id) + defer func() { state[id] = done; path = path[:len(path)-1] }() + for _, callee := range calls[id] { + switch state[callee] { + case open: + cycle := append(append([]string{}, path[cycleStart(path, callee):]...), callee) + return fmt.Errorf("workflow %q calls itself through %s", callee, strings.Join(cycle, " -> ")) + case unseen: + if err := walk(callee); err != nil { + return err + } + } + } + return nil + } + for id := range calls { + if state[id] == unseen { + if err := walk(id); err != nil { + return err + } + } + } + return nil +} + +// cycleStart finds where the open path enters the cycle, so the reported path +// runs from the cycle's first workflow rather than from the DFS root. +func cycleStart(path []string, cycleRoot string) int { + for i, id := range path { + if id == cycleRoot { + return i + } + } + return 0 +} diff --git a/internal/domain/workflow/workflow_call_test.go b/internal/domain/workflow/workflow_call_test.go new file mode 100644 index 000000000..01ea6b731 --- /dev/null +++ b/internal/domain/workflow/workflow_call_test.go @@ -0,0 +1,329 @@ +package workflow + +import ( + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +func callRegistry() StepRegistry { + registry := BuiltinStepRegistry() + registry[AgentRunStepName] = newAgentRunStage + registry[WorkflowCallStepName] = newWorkflowCallStage + return registry +} + +// fakeCaller records StartCall/CallStatus and answers the poll with a +// scripted sequence of statuses. +type fakeCaller struct { + starts []startCall + statuses map[int64][]statusAt + statusErr error + startErr error +} + +type startCall struct { + callerID int64 + workflow string + inputs map[string]any +} + +type statusAt struct { + status string + detail string +} + +func (f *fakeCaller) StartCall(_ context.Context, callerID int64, workflow string, inputs map[string]any) (*task.Task, error) { + if f.startErr != nil { + return nil, f.startErr + } + f.starts = append(f.starts, startCall{callerID: callerID, workflow: workflow, inputs: inputs}) + callee := &task.Task{ID: int64(len(f.starts) + 100), Workflow: workflow, CallParentTaskID: callerID, CallDepth: 1, Status: StatusQueued} + return callee, nil +} + +func (f *fakeCaller) CallStatus(_ context.Context, callerID, callID int64) (string, string, error) { + if f.statusErr != nil { + return "", "", f.statusErr + } + seq := f.statuses[callID] + if len(seq) == 0 { + return "", "", nil + } + at := seq[0] + if len(seq) > 1 { + f.statuses[callID] = seq[1:] + } + return at.status, at.detail, nil +} + +func callerYAML(callee string, extra ...string) string { + body := "id: caller\nsteps:\n - type: workflow.call\n settings:\n workflow: " + callee + "\n" + for _, line := range extra { + body += line + "\n" + } + return body +} + +// ---- Save-time: collection validation ---- + +func TestValidateCollectionWorkflowCalls(t *testing.T) { + for _, test := range []struct { + name string + collection WorkflowDefinitionCollection + want string + }{ + { + name: "callee is not defined", + collection: collectionOf( + callerYAML("missing"), + ), + want: `calls "missing", which is not defined`, + }, + { + name: "direct self-call", + collection: collectionOf( + "id: w\nsteps:\n - type: workflow.call\n settings:\n workflow: w\n", + ), + want: `calls itself through w -> w`, + }, + { + name: "indirect cycle", + collection: collectionOf( + "id: a\nsteps:\n - type: workflow.call\n settings:\n workflow: b\n", + "id: b\nsteps:\n - type: workflow.call\n settings:\n workflow: a\n", + ), + want: "calls itself through a -> b -> a", + }, + { + name: "reference to an undeclared caller input", + collection: collectionOf( + callerYAML("callee", " inputs: {src_ip: \"inputs.missing\"}"), + "id: callee\ninputs:\n src_ip: {type: string}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" references "inputs.missing", which the calling workflow does not declare`, + }, + { + name: "callee input type mismatch", + collection: collectionOf( + "id: caller\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\"}\n", + "id: callee\ninputs:\n src_ip: {type: number}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" is string, want number`, + }, + { + name: "required callee input is not assigned", + collection: collectionOf( + "id: caller\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {severity: \"inputs.src_ip\"}\n", + "id: callee\ninputs:\n src_ip: {type: string, required: true}\n severity: {type: string}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" is required by "callee"`, + }, + { + name: "undeclared callee input", + collection: collectionOf( + "id: caller\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {extra: 7}\n", + "id: callee\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "extra" is not declared by "callee"`, + }, + } { + t.Run(test.name, func(t *testing.T) { + err := ValidateDefinitionCollection(test.collection, callRegistry()) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("ValidateDefinitionCollection() error = %v, want containing %q", err, test.want) + } + }) + } + + valid := collectionOf( + "id: caller\nrepository: none\ninputs:\n src_ip: {type: string, required: true}\n n: {type: number}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\", n: 3}\n", + "id: callee\ninputs:\n src_ip: {type: string, required: true}\n n: {type: number}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ) + if err := ValidateDefinitionCollection(valid, callRegistry()); err != nil { + t.Fatalf("ValidateDefinitionCollection(valid) = %v, want nil", err) + } + + // A chain of distinct workflows is not a cycle. + chain := collectionOf( + "id: a\nsteps:\n - type: workflow.call\n settings:\n workflow: b\n", + "id: b\nsteps:\n - type: workflow.call\n settings:\n workflow: c\n", + "id: c\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ) + if err := ValidateDefinitionCollection(chain, callRegistry()); err != nil { + t.Fatalf("ValidateDefinitionCollection(chain) = %v, want nil", err) + } +} + +func collectionOf(yamls ...string) WorkflowDefinitionCollection { + c := WorkflowDefinitionCollection{} + for _, y := range yamls { + c.Definitions = append(c.Definitions, WorkflowDefinitionEntry{ID: yamlID(y), YAML: y}) + } + return c +} + +func yamlID(y string) string { + for _, line := range strings.Split(y, "\n") { + if strings.HasPrefix(line, "id: ") { + return strings.TrimPrefix(line, "id: ") + } + } + return "" +} + +// ---- Runtime: the stage ---- + +func compileCaller(t *testing.T, yaml string) Workflow { + t.Helper() + wf, err := ParseAndCompile(yaml, callRegistry()) + if err != nil { + t.Fatalf("ParseAndCompile: %v", err) + } + return wf +} + +func TestWorkflowCallStageRefusesWithoutCapability(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n") + store := &recordingStore{} + tc := &TaskContext{Task: &Task{ID: 3, Attempt: 1}, Store: store, Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler)} + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "callee capability") { + t.Fatalf("park reason %q; want a park naming the missing capability", tc.Task.ParkReason) + } + if len(store.ofKind(events.KindWorkflowCallStarted)) != 0 { + t.Error("a refused call must not record a started event") + } +} + +func TestWorkflowCallStageDepthLimit(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n") + caller := &fakeCaller{} + store := &recordingStore{} + deep := &Task{ID: 3, Attempt: 1, CallDepth: MaxCallDepth} + tc := &TaskContext{Task: deep, Calls: caller, Store: store, Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler)} + Run(context.Background(), wf, tc) + if len(caller.starts) != 0 { + t.Fatalf("StartCall ran %d times at the depth limit, want none", len(caller.starts)) + } + if !strings.Contains(deep.ParkReason, "depth") { + t.Fatalf("park reason %q; want a park naming the depth limit", deep.ParkReason) + } +} + +func TestWorkflowCallWaitFalseStartsAndContinues(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\"}\n wait: false\n - type: agent.run\n settings:\n mission: report\n") + caller := &fakeCaller{} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1, Inputs: map[string]any{"src_ip": "10.0.0.9"}}, + Calls: caller, Store: store, Trees: &fakeTrees{dir: "/scratch/3"}, Log: slog.New(slog.DiscardHandler), + Agent: &fakeAgentRunner{result: agentexec.Result{Status: agentexec.StatusPassed, Summary: "reported"}}, + Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}, + } + Run(context.Background(), wf, tc) + if len(caller.starts) != 1 { + t.Fatalf("StartCall ran %d times, want exactly one", len(caller.starts)) + } + start := caller.starts[0] + if start.callerID != 3 || start.workflow != "callee" { + t.Errorf("start = %+v, want caller 3 calling callee", start) + } + if got := start.inputs["src_ip"]; got != "10.0.0.9" { + t.Errorf("input src_ip = %v, want the caller's resolved input", got) + } + if tc.Outcome.Status != StatusCompleted { + t.Errorf("outcome = %+v, want the caller to continue and complete", tc.Outcome) + } + started := store.ofKind(events.KindWorkflowCallStarted) + if len(started) != 1 || started[0].Data["callee_task_id"] != int64(101) { + t.Errorf("started events = %+v, want one carrying callee task 101", started) + } +} + +func TestWorkflowCallWaitTrueWaitsForTerminalCallee(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n - type: agent.run\n settings:\n mission: report\n") + caller := &fakeCaller{statuses: map[int64][]statusAt{ + 101: {{StatusQueued, ""}, {StatusRunning, ""}, {StatusCompleted, "contained 10.0.0.9"}}, + }} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{dir: "/scratch/3"}, Log: slog.New(slog.DiscardHandler), + Agent: &fakeAgentRunner{result: agentexec.Result{Status: agentexec.StatusPassed, Summary: "reported"}}, + Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}, + } + callPollInterval = time.Millisecond + defer func() { callPollInterval = 2 * time.Second }() + Run(context.Background(), wf, tc) + if tc.Outcome.Status != StatusCompleted { + t.Errorf("outcome = %+v, want completed after the callee succeeded", tc.Outcome) + } + finished := store.ofKind(events.KindWorkflowCallFinished) + if len(finished) != 1 || finished[0].Data["status"] != StatusCompleted || finished[0].Data["detail"] != "contained 10.0.0.9" { + t.Errorf("finished events = %+v, want the callee's terminal status and detail", finished) + } +} + +func TestWorkflowCallWaitTrueFailsWhenCalleeFails(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n") + caller := &fakeCaller{statuses: map[int64][]statusAt{ + 101: {{StatusParked, "needs an operator"}}, + }} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler), + } + callPollInterval = time.Millisecond + defer func() { callPollInterval = 2 * time.Second }() + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "needs an operator") { + t.Fatalf("reason %q; want a park carrying the callee's detail", tc.Task.ParkReason) + } + if len(store.ofKind(events.KindWorkflowCallFinished)) != 0 { + t.Error("a failed call must not record a finished event") + } +} + +func TestWorkflowCallWaitTrueStartFailure(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n") + caller := &fakeCaller{startErr: errors.New("callee is not enabled for this org")} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler), + } + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "callee is not enabled") { + t.Fatalf("reason %q; want the start failure parked", tc.Task.ParkReason) + } +} + +func TestWorkflowCallSettingsValidation(t *testing.T) { + for _, test := range []struct{ name, yaml, want string }{ + {"no workflow named", "id: w\nrepository: none\nsteps:\n - type: workflow.call\n", "settings.workflow is required"}, + {"works in a repository-free workflow", "id: w\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: other\n", ""}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := ParseDefinition(test.yaml, callRegistry()) + if test.want == "" { + if err != nil { + t.Fatalf("ParseDefinition() = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("ParseDefinition() error = %v, want containing %q", err, test.want) + } + }) + } +} diff --git a/internal/events/events.go b/internal/events/events.go index cb4b7325a..2cf470309 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -119,6 +119,16 @@ const ( // the sender. data: source, capture_id, binding_id. KindUnsignedEvent = "unsigned_event" + // KindWorkflowCallStarted marks the moment a workflow.call step + // started its callee run (docs/prds/workflow-calls.md). data: + // callee_task_id, workflow, wait. + KindWorkflowCallStarted = "workflow_call_started" + // KindWorkflowCallFinished carries the terminal state of a waited-on + // callee back onto the caller's timeline. data: callee_task_id, + // workflow, status, detail. Only a call the caller waited on records + // one; a wait:false callee reports on its own run. + KindWorkflowCallFinished = "workflow_call_finished" + // KindUpdateReport carries the phase-2 outcome of a dashboard-initiated // update -- whether the restarted daemon came back up healthy and on // the version it claimed, relayed once on the boot that finds the diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index e44c01fef..ba672b39a 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -64,7 +64,7 @@ type eventSteps struct{} func (eventSteps) Name() string { return "event" } func (eventSteps) StepTypes() []workflow.StepType { - return []workflow.StepType{workflow.AgentRunStepType()} + return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType()} } // Providers returns the provider set the roots that resolve a workflow step