workflow

package
v0.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package workflow provides deterministic orchestration of Framework-managed child Processes. A Workflow is an ordered sequence of sealed Stages; it is not a general in-process task graph, scheduler, journal, or node registry.

Use this package when each delegated operation needs its own Process identity, snapshot, budget, capabilities, cancellation, and tree recovery. Ordinary in-process control flow belongs outside the Agent Framework.

Stage constructors validate and freeze static bindings. Restore validates execution progress against those bindings without reconstructing them. Fork and Map share window admission, settlement, and ordered output handling.

Child admission and execution Failures propagate unchanged, preserving their kind, code, and complete diagnostic text. Fan-out waits for the active window to drain and propagates its first failure in declaration order. The Process tree retains the child identity and Stage binding; Workflow-owned decisions use workflow-prefixed failure codes. Single-child Stages also wait for the child subtree to drain. Restoring any handshake boundary resumes the same invocation and its Engine-assigned wait.

Transform, Switch, Fork, and Loop callbacks run inside a discardable Step. They must be bounded, deterministic, side-effect-free, and cooperate with context cancellation during CPU work. Context carries cancellation, never hidden domain input. A canceled candidate cannot advance committed state.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidStage = errors.New("workflow: invalid stage")

	ErrInvalidDefinitionConfig = errors.New("workflow: invalid definition configuration")

	ErrInvalidExecutionState = errors.New("workflow: invalid execution state")

	ErrInvalidProtocol = errors.New("workflow: invalid protocol payload")
)

Functions

This section is empty.

Types

type BindingRole

type BindingRole string

BindingRole describes how an exact child binding participates in a Stage.

const (
	// BindingRoleInvalid is the invalid zero value.
	BindingRoleInvalid BindingRole = ""
	// BindingRoleCall is the single child of a Call Stage.
	BindingRoleCall BindingRole = "call"
	// BindingRoleCase is one named child of a Switch Stage.
	BindingRoleCase BindingRole = "case"
	// BindingRoleBranch is one named child of a Fork Stage.
	BindingRoleBranch BindingRole = "branch"
	// BindingRoleItem is the repeated child of a Map Stage.
	BindingRoleItem BindingRole = "item"
	// BindingRoleBody is the repeated child of a Loop Stage.
	BindingRoleBody BindingRole = "body"
)

type BindingTopology

type BindingTopology struct {
	// Role is the binding's structural role in its Stage.
	Role BindingRole `json:"role"`
	// ID is the stable case or branch identity when the role is named.
	ID string `json:"id,omitempty"`
	// DeploymentRef is the exact child behavior binding identity.
	DeploymentRef agent.DeploymentRef `json:"deployment_ref"`
	// InputSchema is the exact input contract of the child binding.
	InputSchema agent.Schema `json:"input_schema"`
	// OutputSchema is the exact output contract of the child binding.
	OutputSchema agent.Schema `json:"output_schema"`
	// Budget is the non-renewable allocation for each child start.
	Budget agent.Budget `json:"budget"`
	// Capabilities is the attenuated authority granted to each child.
	Capabilities agent.CapabilitySet `json:"capabilities"`
}

BindingTopology is a function-free projection of one exact child binding. ID is present only for named Switch cases and Fork branches.

type CallConfig

type CallConfig struct {
	// ID is unique within the Workflow and remains stable across restoration.
	ID string

	// Deployment is the exact child behavior binding. The Stage retains only
	// its immutable DeploymentRef and Descriptor schemas.
	Deployment agent.Deployment

	// Budget is permanently allocated from the parent when the child starts.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to the child.
	Capabilities agent.CapabilitySet
}

CallConfig declares one exact child Deployment and its non-renewable Framework resource allocation.

type Definition

type Definition struct {
	// contains filtered or unexported fields
}

Definition is an immutable managed Workflow Strategy.

func NewDefinition

func NewDefinition(config DefinitionConfig) (*Definition, error)

NewDefinition connects adjacent stage schemas at construction, so a mismatched pipeline fails where it is declared rather than midway through a run that has already started child Processes and spent budget.

func (*Definition) Descriptor

func (d *Definition) Descriptor() agent.Descriptor

Descriptor returns the immutable erased Workflow contract.

func (*Definition) Restore

func (d *Definition) Restore(state agent.ExecutionState) (agent.Execution, error)

Restore recreates a Workflow solely from its opaque state and this exact Definition. Phase-specific progress, window bounds, and unique child identities are validated before admitting the restored Execution.

func (*Definition) Start

func (d *Definition) Start(input agent.Input) (agent.Execution, error)

Start creates a fresh Workflow from validated caller input.

func (*Definition) Topology

func (d *Definition) Topology() Topology

Topology returns a fresh, function-free projection of this Definition. An invalid or nil Definition returns the zero Topology.

type DefinitionConfig

type DefinitionConfig struct {
	// Name is the stable qualified Definition name.
	Name string

	// Description states the managed orchestration behavior for discovery.
	Description string

	// Stages is a non-empty ordered sequence of sealed operations.
	Stages []Stage
}

DefinitionConfig contains one immutable managed Workflow behavior. Stages execute in declaration order and must have exactly matching adjacent schemas.

type ForkBranch

type ForkBranch struct {
	// ID is unique within this Fork Stage and stable across restoration.
	ID string

	// Deployment is the exact child behavior binding for this branch.
	Deployment agent.Deployment

	// Budget is permanently allocated from the parent when the branch starts.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to the child.
	Capabilities agent.CapabilitySet
}

ForkBranch declares one exact managed child Deployment.

type ForkConfig

type ForkConfig[I, B, O any] struct {
	// ID is unique within the Workflow and remains stable across restoration.
	ID string

	// Branches is a non-empty list in stable declaration order. Every branch
	// accepts I and produces B.
	Branches []ForkBranch

	// WindowSize is the positive number of branches started and settled as one
	// execution window before the next window begins.
	WindowSize uint32

	// Reduce combines all B values after every branch succeeds.
	Reduce ForkReducer[B, O]
}

ForkConfig declares a homogeneous fan-out and deterministic reduction.

type ForkReducer

type ForkReducer[B, O any] func(ctx context.Context, branchOutputs []B) (O, error)

ForkReducer combines branch outputs in declaration order. It must be bounded, deterministic, side-effect-free, honor ctx cancellation, and never retain the slice. Context is not a source of domain input.

type LoopConfig

type LoopConfig[T any] struct {
	// ID is unique within the Workflow and remains stable across restoration.
	ID string

	// Body is the exact T-to-T child Deployment used for every iteration.
	Body agent.Deployment

	// Budget is permanently allocated from the parent for each iteration.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to each child.
	Capabilities agent.CapabilitySet

	// MaxIterations is the positive hard upper bound on body child Processes.
	MaxIterations uint32

	// Predicate decides whether the latest body output satisfies the Loop.
	Predicate LoopPredicate[T]
}

LoopConfig declares one at-least-once managed body iteration.

type LoopPredicate

type LoopPredicate[T any] func(ctx context.Context, value T) (bool, error)

LoopPredicate is a bounded, deterministic, side-effect-free completion test evaluated after each successful body child Process. It must honor ctx cancellation; context is not a source of domain input.

type LoopResult

type LoopResult[T any] struct {
	// Value is the latest body output, or the initial input before any iteration.
	Value T `json:"value"`
	// Iterations is the number of completed body child Processes.
	Iterations uint32 `json:"iterations"`
	// Satisfied reports whether Predicate accepted Value.
	Satisfied bool `json:"satisfied"`
}

LoopResult is the exact semantic output of a Loop Stage. Satisfied is false when MaxIterations was exhausted; that outcome is still a valid completion.

func (LoopResult[T]) Valid

func (l LoopResult[T]) Valid() bool

type MapConfig

type MapConfig[I, O any] struct {
	// ID is unique within the Workflow and remains stable across restoration.
	ID string

	// Deployment is the exact child behavior binding used for every item.
	Deployment agent.Deployment

	// Budget is permanently allocated from the parent for each started item.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to each child.
	Capabilities agent.CapabilitySet

	// WindowSize is the positive number of items started and settled as one
	// execution window before the next window begins. Only that window is
	// decoded into I values; snapshot recovery still validates the full input.
	WindowSize uint32

	// MaxItems is the positive maximum accepted input length.
	MaxItems uint32
}

MapConfig declares a bounded homogeneous item fan-out. The Stage input is []I, each exact child Deployment consumes one I and produces one O, and the Stage output is []O in original item order.

type Stage

type Stage struct {
	// contains filtered or unexported fields
}

Stage is an immutable operation in one Workflow Definition. Values can only be constructed by this package, keeping the execution algebra closed.

func Call

func Call(config CallConfig) (Stage, error)

Call constructs one managed child-Process Stage. No child Process is created until the Workflow Execution returns a Framework StartChild Effect.

func Fork

func Fork[I, B, O any](config ForkConfig[I, B, O]) (Stage, error)

Fork constructs one windowed managed fan-out Stage. Branch inputs and outputs are homogeneous; heterogeneous work can be wrapped by child Workflows that expose a shared contract.

func Loop

func Loop[T any](config LoopConfig[T]) (Stage, error)

Loop constructs one at-least-once managed iteration Stage. Body must accept and produce exactly T; the Stage itself produces LoopResult[T].

func Map

func Map[I, O any](config MapConfig[I, O]) (Stage, error)

Map constructs one bounded managed item fan-out Stage. Empty input is valid and produces a non-nil empty []O without creating child Processes.

func Switch

func Switch[I any](config SwitchConfig[I]) (Stage, error)

Switch constructs one selected managed child-Process Stage. Every case must accept the same I schema and produce one exactly matching output schema.

func Transform

func Transform[I, O any](id string, transform TransformFunc[I, O]) (Stage, error)

Transform constructs one typed pure Stage. JSON schemas derived from I and O remain the authoritative erased boundary used by the Workflow Definition.

Example
package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/Tangerg/scope/agent/strategy/workflow"
)

func main() {
	stage, err := workflow.Transform("normalize", func(_ context.Context, input string) (string, error) {
		return strings.ToUpper(input), nil
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(stage.Valid())
}
Output:
true

func (Stage) Valid

func (s Stage) Valid() bool

Valid reports whether a constructor admitted this immutable Stage.

type StageKind

type StageKind string

StageKind is the operation kind owned by a sealed Workflow Stage.

const (
	// StageKindInvalid is the invalid zero value.
	StageKindInvalid StageKind = ""
	// StageKindTransform identifies a pure value transformation.
	StageKindTransform StageKind = "transform"
	// StageKindCall identifies one exact child Process call.
	StageKindCall StageKind = "call"
	// StageKindSwitch identifies pure selection among exact child cases.
	StageKindSwitch StageKind = "switch"
	// StageKindFork identifies bounded homogeneous branch fan-out.
	StageKindFork StageKind = "fork"
	// StageKindMap identifies bounded homogeneous item fan-out.
	StageKindMap StageKind = "map"
	// StageKindLoop identifies bounded at-least-once child iteration.
	StageKindLoop StageKind = "loop"
)

type StageTopology

type StageTopology struct {
	// ID is the stable Stage identity within the Definition.
	ID string `json:"id"`
	// Kind is the sealed operation kind.
	Kind StageKind `json:"kind"`
	// InputSchema is the exact Stage input contract.
	InputSchema agent.Schema `json:"input_schema"`
	// OutputSchema is the exact Stage output contract.
	OutputSchema agent.Schema `json:"output_schema"`
	// Bindings are exact child bindings in stable declaration order.
	Bindings []BindingTopology `json:"bindings,omitempty"`
	// WindowSize is the fixed Fork or Map execution-window size.
	WindowSize uint32 `json:"window_size,omitempty"`
	// MaxItems is the maximum accepted Map input length.
	MaxItems uint32 `json:"max_items,omitempty"`
	// MaxIterations is the hard Loop body-start limit.
	MaxIterations uint32 `json:"max_iterations,omitempty"`
}

StageTopology is a function-free projection of one sealed Stage. Limits are non-zero only for the Stage kinds that own them.

type SwitchCase

type SwitchCase struct {
	// ID is unique within this Switch Stage and stable across restoration.
	ID string

	// Deployment is the exact child behavior binding for this case.
	Deployment agent.Deployment

	// Budget is permanently allocated from the parent when selected.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to the child.
	Capabilities agent.CapabilitySet
}

SwitchCase declares one exact child Deployment for a selected case.

type SwitchConfig

type SwitchConfig[I any] struct {
	// ID is unique within the Workflow and remains stable across restoration.
	ID string

	// Select chooses one case without performing external work.
	Select SwitchSelector[I]

	// Cases is a non-empty list in stable declaration order.
	Cases []SwitchCase
}

SwitchConfig declares one pure selection function and a closed case set.

type SwitchSelector

type SwitchSelector[I any] func(ctx context.Context, input I) (caseID string, err error)

SwitchSelector is a bounded, deterministic, side-effect-free case selector. It must honor ctx cancellation and returns the exact SwitchCase ID to invoke for the current value. Context is not a source of domain input.

type Topology

type Topology struct {
	// Descriptor is the Workflow's authoritative static contract.
	Descriptor agent.Descriptor `json:"descriptor"`
	// Stages are projected in execution order.
	Stages []StageTopology `json:"stages"`
}

Topology is a detached Definition-derived, function-free projection for diagnostics, documentation, UI rendering, and deployment audit. Mutating a projection never changes the Definition or a later projection.

type TransformFunc

type TransformFunc[I, O any] func(ctx context.Context, input I) (O, error)

TransformFunc is a bounded, deterministic, side-effect-free reduction. It must honor ctx cancellation during CPU work. External work belongs in a Call stage that starts a child Process; ctx is not a source of domain input.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL