ports

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: EUPL-1.2 Imports: 10 Imported by: 0

Documentation

Overview

Package ports defines the boundary interfaces for the hexagonal architecture.

Port interfaces establish contracts between the domain layer and external concerns, enabling dependency inversion and testability. All adapters in the infrastructure layer implement these ports, ensuring the domain layer remains pure and agnostic of external implementation details.

Architecture Role

In the hexagonal architecture pattern:

  • Domain layer defines port interfaces (this package)
  • Infrastructure layer implements ports as adapters (repositories, executors, stores)
  • Application layer orchestrates domain operations through ports
  • Domain layer depends on nothing; all dependencies point inward

This inverted dependency structure allows:

  • Testing domain logic with mock implementations
  • Swapping infrastructure implementations without domain changes
  • Clear boundaries between business logic and technical concerns

Port Interfaces by Concern

## Repository Ports

Workflow and template persistence:

  • WorkflowRepository: Load, list, and check existence of workflow definitions
  • TemplateRepository: Load, list, and check existence of workflow templates

## State Persistence Ports

Runtime state and history management:

  • StateStore: Save, load, delete, and list workflow execution states
  • HistoryStore: Record, query, and cleanup workflow execution history
  • PluginStore: Persist plugin state across sessions
  • PluginConfig: Manage plugin enabled state and configuration
  • PluginStateStore: Combined persistence and configuration interface

## Execution Ports

Command and step execution contracts:

  • CommandExecutor: Execute shell commands via detected shell ($SHELL, fallback /bin/sh) with streaming support
  • CLIExecutor: Execute external binaries directly without shell interpretation
  • StepExecutor: Execute a single workflow step (used by parallel execution)
  • ParallelExecutor: Execute multiple branches concurrently with strategy support

## Agent Integration Ports

AI agent CLI invocation and conversation management:

  • AgentProvider: Execute AI agent prompts (single-shot and conversation modes)
  • AgentRegistry: Register, retrieve, and list available agent providers
  • Tokenizer: Count tokens for context window management (exact or approximate)

## Plugin System Ports

Plugin lifecycle and operation management:

  • Plugin: Base interface all plugins must implement (init, shutdown)
  • PluginManager: Discover, load, initialize, and shutdown plugins
  • OperationProvider: Execute plugin-provided operations
  • PluginRegistry: Register and unregister plugin operations
  • PluginLoader: Discover and load plugins from filesystem

## Interactive Mode Ports

User interaction during workflow execution:

  • InteractivePrompt: Step-by-step execution control (run, skip, retry, abort, edit)
  • InputCollector: Pre-execution collection of missing workflow inputs

## Expression Evaluation Ports

Runtime expression handling:

  • ExpressionEvaluator: Evaluate boolean and integer expressions with runtime context
  • ExpressionValidator: Validate expression syntax at compile-time

## Logging Ports

Structured logging abstraction:

  • Logger: Domain logging interface (debug, info, warn, error) with context support

Usage Patterns

Ports are consumed by:

  1. Application services (dependency injection)
  2. Domain entities (passed as parameters when needed)
  3. Test code (mock implementations)

Example: Injecting ports into application service

type WorkflowService struct {
    repo   ports.WorkflowRepository
    store  ports.StateStore
    logger ports.Logger
}

func NewWorkflowService(
    repo ports.WorkflowRepository,
    store ports.StateStore,
    executor ports.Executor,
    logger ports.Logger,
    validator ports.ExpressionValidator,
) *WorkflowService {
    return &WorkflowService{
        repo:      repo,
        store:     store,
        executor:  executor,
        logger:    logger,
        validator: validator,
    }
}

Example: Testing with mock implementations

func TestWorkflowExecution(t *testing.T) {
    mockRepo := testutil.NewMockWorkflowRepository()
    mockStore := testutil.NewMockStateStore()
    mockLogger := testutil.NewMockLogger()

    service := NewWorkflowService(mockRepo, mockStore, mockExecutor, mockLogger, mockValidator)
    // Test service behavior
}

Port Design Principles

When implementing port interfaces:

  • Accept context.Context for cancellation and timeout support
  • Return domain errors (not infrastructure errors) when possible
  • Use domain types in signatures (workflow.Workflow, not YAML structs)
  • Keep interfaces small and focused (Interface Segregation Principle)
  • Document contract expectations and error conditions
  • internal/domain/workflow: Core domain entities (Workflow, Step, State, Context)
  • internal/application: Services that consume ports
  • internal/infrastructure: Concrete implementations of ports
  • internal/testutil: Mock implementations for testing

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidRequest    = errors.New("invalid request")
	ErrSessionClosed     = errors.New("session closed")
	ErrDuplicateResponse = errors.New("duplicate response")
	ErrSessionExists     = errors.New("session already exists")
	ErrRunNotFound       = errors.New("run not found")
)

Sentinel errors for the facade port layer.

These sentinels are the canonical "what went wrong" signals callers use with errors.Is to branch on known failure modes without importing application or infrastructure packages. Their relationship to domain/errors.ErrorCode is as follows:

  • ErrInvalidRequest → ErrorCodeUserInputValidationFailed (empty/malformed identifier)
  • ErrSessionClosed → ErrorCodeExecutionCommandTimeout / general lifecycle error
  • ErrDuplicateResponse → no direct ErrorCode; indicates protocol misuse
  • ErrSessionExists → ErrorCodeExecutionCommandTimeout / lifecycle error
  • ErrRunNotFound → ErrorCodeUserInputMissingFile (run ID not in registry/history)

The application adapter (application.Adapter) is responsible for wrapping domain/errors.StructuredError values with these sentinels using fmt.Errorf("%w", sentinelErr) so that callers in the interface layers can rely on errors.Is without depending on the application or domain/errors packages directly. The domain port layer declares only the sentinel values; the wrapping convention belongs to the adapter implementation.

View Source
var ErrInvalidEvent = errors.New("invalid event: Type must not be empty")

ErrInvalidEvent is returned when a Record call is made with a zero-Type event.

Functions

This section is empty.

Types

type ACPClient added in v0.11.2

type ACPClient interface {
	RequestPermission(ctx context.Context, req PermissionRequest) (PermissionResponse, error)
}

ACPClient is the domain port for agent→editor approval callbacks. Scope: one method only (F102 v1); fs/terminal methods are deferred per spec Decision #2(b).

type AgentOutputNormalizer added in v0.11.2

type AgentOutputNormalizer interface {
	// Normalize maps the provider's raw output into ordered ContentBlocks. The provider
	// argument is the resolved provider name (matching the agent registry key).
	Normalize(provider string, rawOutput []byte) []transcript.ContentBlock
}

AgentOutputNormalizer converts a provider's raw CLI output (NDJSON) into the canonical transcript ContentBlock vocabulary for F106 message.assistant events. It is the seam that absorbs per-provider output divergence (Claude, Codex, Gemini, Copilot, OpenAI compatible) in a single place (SC-002), implemented in the infrastructure agents layer.

Implementations must be total and panic-free: an unknown provider, empty output, or unparseable lines yield no blocks rather than an error.

type AgentProvider

type AgentProvider interface {
	// Execute invokes the agent with the given prompt and options.
	// When stdout/stderr writers are non-nil, agent output is streamed to them in real-time.
	// Returns AgentResult containing output, parsed response, token usage, and any errors.
	Execute(ctx context.Context, prompt string, options map[string]any, stdout, stderr io.Writer) (*workflow.AgentResult, error)

	// ExecuteConversation invokes the agent with conversation history for multi-turn interactions.
	// When stdout/stderr writers are non-nil, agent output is streamed to them in real-time.
	// The state parameter contains the conversation history (turns) to send to the agent.
	// Returns ConversationResult containing the updated conversation state, final output, and token usage.
	ExecuteConversation(ctx context.Context, state *workflow.ConversationState, prompt string, options map[string]any, stdout, stderr io.Writer) (*workflow.ConversationResult, error)

	// Name returns the provider identifier (e.g., "claude", "codex", "gemini").
	Name() string

	// Validate checks if the provider is properly configured and available.
	// Returns error if the agent CLI binary is not found or misconfigured.
	Validate() error
}

AgentProvider defines the contract for executing AI agent CLI commands. Implementations adapt specific agent CLIs (Claude, Codex, Gemini, etc.) to this unified interface.

type AgentRegistry

type AgentRegistry interface {
	// Register adds a provider to the registry.
	// Returns error if a provider with the same name already exists.
	Register(provider AgentProvider) error

	// Get retrieves a provider by name.
	// Returns error if provider is not found.
	Get(name string) (AgentProvider, error)

	// List returns all registered provider names.
	List() []string

	// Has checks if a provider with the given name is registered.
	Has(name string) bool
}

AgentRegistry manages available agent providers and resolves them by name.

type AgentRoleRepository added in v0.11.2

type AgentRoleRepository interface {
	Load(ctx context.Context, name string) (*workflow.AgentRole, error)
	LoadFromPath(ctx context.Context, absolutePath string) (*workflow.AgentRole, error)
}

type AuditTrailWriter

type AuditTrailWriter interface {
	Write(ctx context.Context, event *workflow.AuditEvent) error
	Close() error
}

AuditTrailWriter defines the contract for appending audit trail entries.

type BatchValidator added in v0.11.2

type BatchValidator interface {
	// ValidateDir validates all .yaml workflow files found directly in dir (non-recursive).
	// Returns ErrInvalidRequest when dir is empty. Returns an OS error when dir cannot be read.
	ValidateDir(ctx context.Context, dir string, opts ValidateOptions) ([]FileValidationResult, error)
	// ValidatePack validates all .yaml workflow files inside the "workflows/" sub-directory
	// of the installed pack identified by packName. Returns ErrInvalidRequest when packName
	// is empty. Returns an error when the pack cannot be located.
	ValidatePack(ctx context.Context, packName string, opts ValidateOptions) ([]FileValidationResult, error)
}

BatchValidator is a focused port for directory- and pack-scoped validation. It is implemented by application.Adapter and consumed by the CLI `awf validate --dir` and `awf validate --pack` paths (runValidateDir, runValidatePack).

Rationale for keeping this port separate from WorkflowFacade (mirrors the SingleStepRunner / WorkflowReader segregation, M1):

  • WorkflowFacade.Validate validates a SINGLE named workflow through the canonical resolver; it is consumed by every interface layer (CLI, API, ACP).
  • BatchValidator operates on a raw filesystem directory or an installed pack name, bypassing the resolver — it is a CLI-only convenience for mass validation. Burdening every WorkflowFacade implementer (test fakes, ACP session facades, HTTP API handler fakes) with two extra methods they never invoke would violate ISP.

Both methods accept ValidateOptions so callers can forward --skip-plugins and --validator-timeout across all validation paths uniformly.

Both methods return one FileValidationResult per discovered .yaml file. A method-level error (e.g. unreadable directory, unknown pack) is returned as the function error; per-file validation failures are captured inside FileValidationResult.Valid/Errors instead so that the caller can display a full summary even when some files fail.

type CLIExecutor

type CLIExecutor interface {
	// Run executes a binary with given arguments.
	// Returns stdout and stderr as byte slices, plus any execution error.
	//
	// When stdoutW or stderrW are non-nil, output is tee'd to these writers
	// in real-time (streaming mode) while also being captured in the returned
	// byte slices. When nil, output is only captured (buffer mode).
	//
	// The context allows cancellation and timeout control.
	// If the context is cancelled, the execution should be terminated.
	//
	// Error cases:
	// - Binary not found: error != nil
	// - Non-zero exit code: error != nil (error should contain exit code info)
	// - Context cancelled/timeout: error will be context.Canceled or context.DeadlineExceeded
	Run(ctx context.Context, name string, stdoutW, stderrW io.Writer, args ...string) (stdout, stderr []byte, err error)

	// Start launches a binary without blocking and returns a CLIProcess handle
	// for signal, wait, and done-notification lifecycle control.
	Start(ctx context.Context, name string, args ...string) (CLIProcess, error)
}

CLIExecutor defines the contract for executing external CLI binaries. Unlike CommandExecutor (shell execution via detected shell), this executes binaries directly without shell interpretation.

This interface is designed for testing agent providers that invoke external CLI tools (claude, gemini, codex, etc.) by allowing test code to inject mock implementations that return predefined responses.

type CLIProcess added in v0.11.2

type CLIProcess interface {
	Signal(sig os.Signal) error
	Wait() error
	Done() <-chan struct{}
}

CLIProcess is an asynchronous subprocess handle returned by CLIExecutor.Start. Signal and Wait are safe to call concurrently; Wait is idempotent.

On Windows, Signal(os.Interrupt) is best-effort; callers must treat the 5-second deadline as mandatory and fall back to Signal(os.Kill) unconditionally.

type Command

type Command struct {
	Program      string
	Dir          string
	Env          map[string]string
	IsScriptFile bool
	Stdout       io.Writer
	Stderr       io.Writer
}

Command represents a command to execute.

When IsScriptFile is false (default), Program is passed to the user's detected shell (via $SHELL, fallback /bin/sh) as a shell command string, allowing shell features like pipes and redirects.

When IsScriptFile is true and Program starts with a shebang (#!), the content is written to a temporary file, made executable, and executed directly — letting the kernel dispatch the correct interpreter. If no shebang is present, execution falls back to $SHELL -c for backward compatibility.

Use ShellEscape() from pkg/interpolation for user-provided values.

type CommandExecutor

type CommandExecutor interface {
	Execute(ctx context.Context, cmd *Command) (*CommandResult, error)
}

type CommandResult

type CommandResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
}

type EnrichedInputRequest added in v0.11.2

type EnrichedInputRequest struct {
	Prompt string
}

EnrichedInputRequest carries the prompt for the bridge-synthesized EventInputRequired.

type EnrichedMessagePayload added in v0.11.2

type EnrichedMessagePayload struct {
	Content string
}

EnrichedMessagePayload carries message content for both EventMessageUser and EventMessageAssistant. The Kind field on the enclosing Event distinguishes which participant produced the message.

type EnrichedStepPayload added in v0.11.2

type EnrichedStepPayload struct {
	// Status preserves the terminal outcome. Empty supports older transcripts.
	Status     string
	StepName   string
	Error      string
	DurationMs int64
	// HadOutput reports whether the step produced any human-visible stdout/stderr.
	// It is meaningful only on EventStepCompleted (false on EventStepStarted). The CLI
	// renderer uses it to reproduce the legacy F037 success-feedback behavior: a step
	// that completed with no output gets an explicit "<step>: completed successfully"
	// line, whereas a step that already printed output does not (its output is the
	// feedback). It is derived from the step state at emit time, not from the event
	// stream, because shell-step stdout is streamed out-of-band via the output writers
	// and never appears as a facade event.
	HadOutput bool
	// Output and Stderr carry the step's captured stdout/stderr at completion time.
	// Like HadOutput they are derived from the step state at emit time (shell-step
	// stdout is streamed out-of-band via the output writers and is not otherwise
	// recoverable from the event stream). They are meaningful only on
	// EventStepCompleted and let event-only consumers (TUI monitoring, SSE) display
	// per-step output without polling an ExecutionContext. The CLI renderer ignores
	// them (it streams stdout directly through the output writers).
	Output string
	Stderr string
}

EnrichedStepPayload carries step metadata for EventStepStarted, EventStepCompleted, EventStepCallWorkflowStarted, and EventStepCallWorkflowCompleted.

type EnrichedTerminal added in v0.11.2

type EnrichedTerminal struct {
	Error string
}

EnrichedTerminal carries the terminal error for EventWorkflowFailed. It is nil/unused for EventWorkflowCompleted (success requires no error payload).

type ErrorFormatter

type ErrorFormatter interface {
	// FormatError converts a StructuredError into a formatted string representation.
	// The format depends on the implementation (JSON, human-readable, etc.).
	//
	// Parameters:
	//   - err: The structured error to format
	//
	// Returns:
	//   - Formatted error string according to the implementation's output mode
	//
	// Example:
	//
	//	// JSON formatter:
	//	// {"error_code":"USER.INPUT.MISSING_FILE","message":"workflow file not found",...}
	//
	//	// Human formatter:
	//	// [USER.INPUT.MISSING_FILE] workflow file not found
	FormatError(err *errors.StructuredError) string
}

ErrorFormatter defines the contract for formatting structured errors into different output representations (JSON, human-readable, etc.). Implementations live in infrastructure layer.

ErrorFormatter enables:

  • Machine-readable JSON output for CI/CD pipelines
  • Human-readable CLI output with color and formatting
  • Consistent error presentation across output modes

Example usage:

formatter := infrastructure.NewJSONErrorFormatter()
output := formatter.FormatError(structuredErr)

type Event added in v0.11.2

type Event struct {
	Seq         uint64
	Kind        EventKind
	RunID       string
	ParentRunID string
	Payload     any
	Timestamp   time.Time
}

Event is a projection wrapper emitted on RunSession.Events(). Seq, RunID, ParentRunID are reused verbatim from the source event — no independent sequence numbering is introduced (A2, FR-006, D3).

Payload type by Kind:

Kind                          Payload type           Notes
──────────────────────────── ────────────────────── ───────────────────────────────
EventStepStarted              *EnrichedStepPayload
EventStepCompleted            *EnrichedStepPayload   HadOutput/Output/Stderr valid
EventStepCallWorkflowStarted  *EnrichedStepPayload
EventStepCallWorkflowCompleted *EnrichedStepPayload
EventRunStarted               nil
EventRunCompleted             nil
EventMessageUser              *EnrichedMessagePayload
EventMessageAssistant         *EnrichedMessagePayload
EventToolCall                 nil  (raw transcript payload; may be non-nil in future)
EventToolResult               nil  (raw transcript payload; may be non-nil in future)
EventInputRequired            *EnrichedInputRequest
EventWorkflowCompleted        nil  (success: no error payload needed)
EventWorkflowFailed           *EnrichedTerminal      Error field carries the reason
EventKindUnknown              nil  (drop: unrecognized or zero-init)

Zero-value safety: a zero-value Event has Kind == EventKindUnknown (iota = 0), which is the fail-closed sentinel. Accidental zero-init therefore produces an "unknown" event rather than a valid observable event. Consumers must always handle the EventKindUnknown case.

type EventKind added in v0.11.2

type EventKind uint8

EventKind classifies a facade Event.

The taxonomy covers three groups:

  1. Run lifecycle (EventRunStarted, EventRunCompleted) — emitted once per top-level run at start and end of the execution loop.

  2. Step lifecycle (EventStepStarted, EventStepCompleted, EventStepCallWorkflowStarted, EventStepCallWorkflowCompleted) — emitted around each step, including nested sub-workflow dispatch.

  3. Exchange content (EventMessageUser, EventMessageAssistant, EventToolCall, EventToolResult) — emitted for each message or tool invocation produced by an agent during a step's exchange.

Two additional kinds are synthesized by the facade bridge rather than sourced from the underlying transcript:

  • EventInputRequired — the workflow is paused awaiting user input via Respond.
  • EventWorkflowCompleted / EventWorkflowFailed — terminal sentinels that signal the end of the Events() stream; the channel is closed immediately after.

EventKindUnknown is the zero value and the fail-closed fallback for any unrecognized or uninitialized event type (NFR-007).

const (
	// EventKindUnknown is the zero value and the fail-closed fallback for any
	// unrecognized or uninitialized event type (NFR-007). Because it is iota (= 0),
	// an accidental zero-init of an Event struct will always produce this kind rather
	// than a valid observable event — callers must treat it as "unknown/drop" rather
	// than as a real event. Consumers that switch on EventKind should always include
	// a default case that handles EventKindUnknown.
	EventKindUnknown               EventKind = iota
	EventRunStarted                          // run lifecycle: execution loop started
	EventRunCompleted                        // run lifecycle: execution loop finished
	EventStepStarted                         // step lifecycle: step entered
	EventStepCompleted                       // step lifecycle: step exited
	EventStepCallWorkflowStarted             // step lifecycle: sub-workflow dispatch started
	EventStepCallWorkflowCompleted           // step lifecycle: sub-workflow dispatch finished
	EventMessageUser                         // exchange content: user message produced
	EventMessageAssistant                    // exchange content: assistant message produced
	EventToolCall                            // exchange content: tool invocation issued
	EventToolResult                          // exchange content: tool invocation result received
	EventInputRequired                       // bridge-synthesized: workflow awaits user input
	EventWorkflowCompleted                   // terminal: workflow finished successfully
	EventWorkflowFailed                      // terminal: workflow finished with error
)

func (EventKind) String added in v0.11.2

func (k EventKind) String() string

type EventPublisher added in v0.11.2

type EventPublisher interface {
	Publish(ctx context.Context, event *pluginmodel.DomainEvent) error
	Close() error
}

type ExpressionEvaluator

type ExpressionEvaluator interface {
	// EvaluateBool evaluates a boolean expression against the provided context.
	// Returns the boolean result of the expression, or an error if evaluation fails.
	// Example: "inputs.count > 5" → true/false
	EvaluateBool(expr string, ctx *interpolation.Context) (bool, error)

	// EvaluateInt evaluates an arithmetic expression against the provided context.
	// Returns the integer result of the expression, or an error if evaluation fails.
	// The result is coerced to int type regardless of the underlying numeric type.
	// Example: "20 / 4" → 5
	EvaluateInt(expr string, ctx *interpolation.Context) (int, error)
}

ExpressionEvaluator defines the contract for evaluating runtime expressions. This port abstracts expression evaluation to maintain domain layer purity by avoiding direct dependencies on external expression libraries.

Unlike ExpressionValidator (which validates syntax at compile-time), ExpressionEvaluator handles runtime evaluation with actual data context.

type ExpressionValidator

type ExpressionValidator interface {
	// Compile validates the syntax of an expression string.
	// Returns nil if the expression is syntactically valid, error otherwise.
	// This method does NOT evaluate the expression, only checks if it can be compiled.
	Compile(expression string) error
}

ExpressionValidator defines the contract for validating expression syntax. This port abstracts expression compilation to maintain domain layer purity by avoiding direct dependencies on external expression libraries.

type FileValidationResult added in v0.11.2

type FileValidationResult struct {
	// Name is the bare workflow name (filename without the .yaml extension) as it
	// would appear in `awf validate <name>` or `awf run <name>`.
	Name string
	// Valid is true when the workflow passed all validation checks.
	Valid bool
	// Errors contains structured validation failures; empty when Valid is true.
	Errors []ValidationError
}

FileValidationResult carries the outcome of validating a single workflow file. It is the element type of the slice returned by BatchValidator methods so that callers can display per-file valid/invalid status without re-parsing results.

type HistoryFilter added in v0.11.2

type HistoryFilter struct {
	WorkflowName string
	Status       string
	Since        time.Time
	Until        time.Time
	Limit        int
}

HistoryFilter scopes a WorkflowFacade.History query.

type HistoryStore

type HistoryStore interface {
	Record(ctx context.Context, record *workflow.ExecutionRecord) error
	List(ctx context.Context, filter *workflow.HistoryFilter) ([]*workflow.ExecutionRecord, error)
	GetStats(ctx context.Context, filter *workflow.HistoryFilter) (*workflow.HistoryStats, error)
	Cleanup(ctx context.Context, olderThan time.Duration) (int, error)
	Close() error
}

HistoryStore defines the contract for persisting workflow execution history.

type InputCollector

type InputCollector interface {
	// PromptForInput prompts the user to provide a value for a single workflow input.
	//
	// Behavior by input type:
	//   - Required inputs: Empty value triggers error and re-prompt
	//   - Optional inputs: Empty value returns input.Default or nil
	//   - Enum inputs: Display numbered list (1-9) for selection
	//   - Validated inputs: Apply workflow.InputValidation constraints, re-prompt on error
	//
	// Type coercion is applied based on input.Type:
	//   - "string": Return value as-is
	//   - "integer": Parse string to int
	//   - "boolean": Parse "true"/"false" to bool
	//
	// Returns:
	//   - Validated input value (typed as any for flexibility)
	//   - Error if user cancels (Ctrl+C, EOF) or validation fails repeatedly
	//
	// Implementation notes:
	//   - Check stdin is terminal before calling (fail if non-interactive)
	//   - Handle io.EOF as cancellation, not panic
	//   - Display validation errors with constraint details
	PromptForInput(ctx context.Context, input *workflow.Input) (any, error)
}

InputCollector defines the contract for collecting missing workflow inputs interactively. This port is used for pre-execution input collection when required inputs are missing from command-line arguments.

Key differences from InteractivePrompt:

  • InputCollector: Pre-execution input collection (before workflow starts)
  • InteractivePrompt: During-execution step control (while workflow runs)

Implementation requirements:

  • Display enum options as numbered list when Validation.Enum is present
  • Validate input values against workflow.InputValidation constraints
  • Re-prompt on validation errors with specific error messages
  • Handle optional inputs by accepting empty values and using defaults
  • Support graceful cancellation (Ctrl+C, Ctrl+D/EOF)

Example usage:

collector := cli.NewCLIInputCollector(os.Stdin, os.Stdout, colorizer)
value, err := collector.PromptForInput(&workflow.Input{
    Name:        "environment",
    Type:        "string",
    Description: "Deployment environment",
    Required:    true,
    Validation: &workflow.InputValidation{
        Enum: []string{"dev", "staging", "prod"},
    },
})
if err != nil {
    return fmt.Errorf("input collection failed: %w", err)
}

type InputRequest added in v0.11.2

type InputRequest struct {
	PromptID string
	Prompt   string
	Default  string
}

InputRequest describes a prompt that the workflow needs answered.

type InputResponse added in v0.11.2

type InputResponse struct {
	PromptID string
	Value    string
}

InputResponse carries the user's answer to an InputRequest.

type InteractivePrompt

type InteractivePrompt interface {
	StepPresenter
	StatusPresenter
	UserInteraction
}

InteractivePrompt defines the composite contract for interactive mode user interaction. Implementations handle UI rendering and user input during step-by-step execution. This interface embeds StepPresenter, StatusPresenter, and UserInteraction for backward compatibility.

type Logger

type Logger interface {
	Debug(msg string, fields ...any)
	Info(msg string, fields ...any)
	Warn(msg string, fields ...any)
	Error(msg string, fields ...any)
	WithContext(ctx map[string]any) Logger
}

type NopLogger added in v0.11.2

type NopLogger struct{}

NopLogger is a no-op Logger. It lives in the domain ports package (zero dependencies) so any layer can use it as a defensive fallback without pulling in internal/infrastructure/logger.

func (NopLogger) Debug added in v0.11.2

func (NopLogger) Debug(string, ...any)

func (NopLogger) Error added in v0.11.2

func (NopLogger) Error(string, ...any)

func (NopLogger) Info added in v0.11.2

func (NopLogger) Info(string, ...any)

func (NopLogger) Warn added in v0.11.2

func (NopLogger) Warn(string, ...any)

func (NopLogger) WithContext added in v0.11.2

func (NopLogger) WithContext(map[string]any) Logger

type NopSpan added in v0.11.2

type NopSpan struct{}

func (NopSpan) AddEvent added in v0.11.2

func (NopSpan) AddEvent(_ string)

func (NopSpan) End added in v0.11.2

func (NopSpan) End()

func (NopSpan) RecordError added in v0.11.2

func (NopSpan) RecordError(_ error)

func (NopSpan) SetAttribute added in v0.11.2

func (NopSpan) SetAttribute(_ string, _ any)

type NopTracer added in v0.11.2

type NopTracer struct{}

func (NopTracer) Start added in v0.11.2

func (NopTracer) Start(ctx context.Context, _ string) (context.Context, Span)

type OperationProvider

type OperationProvider interface {
	// GetOperation returns an operation by name.
	GetOperation(name string) (*pluginmodel.OperationSchema, bool)
	// ListOperations returns all available operations.
	ListOperations() []*pluginmodel.OperationSchema
	// Execute runs a plugin operation.
	Execute(ctx context.Context, name string, inputs map[string]any) (*pluginmodel.OperationResult, error)
}

OperationProvider supplies plugin-provided operations.

type PackDiscoverer added in v0.11.2

type PackDiscoverer interface {
	DiscoverWorkflows(ctx context.Context) ([]workflow.WorkflowEntry, error)
	LoadWorkflow(ctx context.Context, packName, workflowName string) (*workflow.Workflow, error)
}

PackDiscoverer discovers installed workflow packs and loads individual pack workflows.

type ParallelExecutor

type ParallelExecutor interface {
	// Execute runs multiple branches concurrently according to the given strategy.
	// It respects the MaxConcurrent limit via semaphore and applies the strategy
	// to determine overall success/failure.
	Execute(
		ctx context.Context,
		wf *workflow.Workflow,
		branches []string,
		config workflow.ParallelConfig,
		execCtx *workflow.ExecutionContext,
		stepExecutor StepExecutor,
	) (*workflow.ParallelResult, error)
}

ParallelExecutor defines the contract for executing parallel branches.

type PermissionOption added in v0.11.2

type PermissionOption struct {
	ID    string
	Label string
	Kind  string
}

PermissionOption represents a selectable choice in a permission prompt. Kind is "allow" or "deny".

type PermissionRequest added in v0.11.2

type PermissionRequest struct {
	SessionID  string
	ToolCallID string
	Prompt     string
	Options    []PermissionOption
}

PermissionRequest carries the data the editor needs to present a permission prompt.

type PermissionResponse added in v0.11.2

type PermissionResponse struct {
	OptionID string
}

PermissionResponse carries the user's selection. OptionID == "" means the prompt was cancelled without a selection.

type Plugin

type Plugin interface {
	// Name returns the unique plugin identifier.
	Name() string
	// Version returns the plugin version.
	Version() string
	// Init initializes the plugin with configuration.
	Init(ctx context.Context, config map[string]any) error
	// Shutdown gracefully stops the plugin.
	Shutdown(ctx context.Context) error
}

Plugin defines the contract that all plugins must implement.

type PluginConfig

type PluginConfig interface {
	// SetEnabled enables or disables a plugin by name.
	SetEnabled(ctx context.Context, name string, enabled bool) error
	// IsEnabled returns whether a plugin is enabled.
	// Default is true: plugins not explicitly disabled are considered enabled.
	// Only plugins whose name appears in the disabled set return false.
	// Unknown plugin names return true (default-enabled contract).
	IsEnabled(name string) bool
	// GetConfig returns the stored configuration for a plugin.
	GetConfig(name string) map[string]any
	// SetConfig stores configuration for a plugin.
	SetConfig(ctx context.Context, name string, config map[string]any) error
}

PluginConfig manages plugin configuration and enabled state.

type PluginLoader

type PluginLoader interface {
	// DiscoverPlugins scans a directory for plugins and returns their info.
	// Each subdirectory with a plugin.yaml is considered a plugin.
	DiscoverPlugins(ctx context.Context, pluginsDir string) ([]*pluginmodel.PluginInfo, error)
	// LoadPlugin loads a single plugin from a directory path.
	LoadPlugin(ctx context.Context, pluginDir string) (*pluginmodel.PluginInfo, error)
	// ValidatePlugin checks if a discovered plugin is valid and compatible.
	ValidatePlugin(info *pluginmodel.PluginInfo) error
}

PluginLoader discovers and loads plugins from the filesystem.

type PluginManager

type PluginManager interface {
	// Discover finds plugins in the plugins directory.
	Discover(ctx context.Context) ([]*pluginmodel.PluginInfo, error)
	// Load loads a plugin by name.
	Load(ctx context.Context, name string) error
	// Init initializes a loaded plugin.
	Init(ctx context.Context, name string, config map[string]any) error
	// Shutdown stops a running plugin.
	Shutdown(ctx context.Context, name string) error
	// ShutdownAll stops all running plugins.
	ShutdownAll(ctx context.Context) error
	// Get returns plugin info by name.
	Get(name string) (*pluginmodel.PluginInfo, bool)
	// List returns all known plugins.
	List() []*pluginmodel.PluginInfo
}

PluginManager handles plugin lifecycle operations.

type PluginRegistry

type PluginRegistry interface {
	// RegisterOperation adds a plugin operation.
	RegisterOperation(op *pluginmodel.OperationSchema) error
	// UnregisterOperation removes a plugin operation.
	UnregisterOperation(name string) error
	// Operations returns all registered operations.
	Operations() []*pluginmodel.OperationSchema
}

PluginRegistry manages registration of plugin-provided extensions.

type PluginStateStore

type PluginStateStore interface {
	PluginStore
	PluginConfig
}

PluginStateStore combines persistence and configuration interfaces. Maintains backward compatibility while enabling consumers to use narrower interfaces.

type PluginStore

type PluginStore interface {
	// Save persists all plugin states to storage.
	Save(ctx context.Context) error
	// Load reads plugin states from storage.
	Load(ctx context.Context) error
	// GetState returns the full state for a plugin, or nil if not found.
	GetState(name string) *pluginmodel.PluginState
	// ListDisabled returns names of all explicitly disabled plugins.
	ListDisabled() []string
}

PluginStore handles plugin state persistence.

type Progress added in v0.11.2

type Progress struct {
	// Total is the number of distinct steps for which at least one lifecycle event was observed.
	Total int
	// Completed is the number of steps for which EventStepCompleted was observed.
	Completed int
	// Failed is the number of steps for which a failure was observed.
	Failed int
}

Progress summarizes step-level execution counts derived from the event stream. It is a read-only snapshot: counts only reflect events that reached the replay buffer.

type Recorder added in v0.11.2

type Recorder interface {
	// Record appends the event to the transcript. Returns ErrInvalidEvent when
	// event.Type is empty. Honors ctx cancellation.
	Record(ctx context.Context, event transcript.ExchangeEvent) error

	// Subscribe returns a channel that receives every subsequent recorded event
	// and a cancel closure that unregisters the subscriber and closes the channel.
	// Calling cancel more than once is a no-op.
	Subscribe() (ch <-chan transcript.ExchangeEvent, cancel func())

	// Close flushes and releases resources. Idempotent: second call returns nil.
	Close() error
}

Recorder is the port for writing and broadcasting transcript exchange events.

type RecorderFactory added in v0.11.2

type RecorderFactory func(path string) (Recorder, error)

RecorderFactory creates a new Recorder that writes to path. The parent directory of path must already exist.

type ResumeRequest added in v0.11.2

type ResumeRequest struct {
	// RunID is the identifier of the run to resume (required).
	RunID string
	// InputOverrides replaces specific workflow input values for the resumed execution.
	// A nil map means "no overrides; use the values stored with the original run".
	InputOverrides map[string]any
	// FromStep names the step at which execution should restart.
	// An empty string means "restart from the current/last persisted step".
	FromStep string
}

ResumeRequest is the input for resuming a previously paused or interrupted workflow run. It mirrors RunRequest so callers that construct both use a consistent pattern. Zero-value ResumeRequest (RunID == "") produces ErrInvalidRequest.

type RunOptions added in v0.11.2

type RunOptions struct {
	DryRun  bool
	Verbose bool
	Timeout time.Duration
}

RunOptions carries optional execution modifiers for a RunRequest.

type RunRecord added in v0.11.2

type RunRecord struct {
	RunID        string
	WorkflowID   string
	WorkflowName string
	Status       RunState
	StartedAt    time.Time
	CompletedAt  time.Time
	DurationMs   int64
	ErrorMessage string
}

RunRecord is a single entry in the workflow execution history.

type RunRequest added in v0.11.2

type RunRequest struct {
	Identifier   string         // canonical "pack/workflow" identifier
	Inputs       map[string]any // workflow input values
	Options      RunOptions
	ValidateOpts ValidateOptions // honored only by Validate; ignored by Run/Resume
}

RunRequest is the input for starting or validating a workflow execution. Zero-value RunRequest (Identifier == "") produces ErrInvalidRequest. ValidateOpts is honored only by Validate; ignored by Run/Resume.

type RunSession added in v0.11.2

type RunSession interface {
	ID() string
	Events() <-chan Event
	Respond(InputResponse) error
	Err() error
	Close() error
}

RunSession represents an active workflow execution. Close is idempotent: multiple calls return the same nil/error without panicking.

type RunState added in v0.11.2

type RunState string

RunState is the canonical lifecycle state of a workflow run or step. Using a named string type rather than a bare string prevents accidental assignment of arbitrary strings and makes switch exhaustiveness visible to the linter and the reader.

const (
	// RunStatePending means the run has been accepted but execution has not started.
	RunStatePending RunState = "pending"
	// RunStateRunning means the run is actively executing.
	RunStateRunning RunState = "running"
	// RunStateCompleted means the run finished successfully.
	RunStateCompleted RunState = "completed"
	// RunStateFailed means the run stopped due to an error.
	RunStateFailed RunState = "failed"
	// RunStateCancelled means the run was cancelled before completion.
	RunStateCancelled RunState = "cancelled"
)

type RunStatus added in v0.11.2

type RunStatus struct {
	// RunID is the unique identifier of the run.
	RunID string
	// Status is the lifecycle state: pending, running, completed, failed, cancelled.
	Status RunState
	// CurrentStep is the name of the step currently executing; empty when no step is
	// in progress (i.e. between steps, or once the run reached a terminal state).
	CurrentStep string
	// StartedAt is the wall-clock time at which execution started (EventRunStarted timestamp).
	// Zero when the event was not observed (NopRecorder path or history fallback).
	StartedAt time.Time
	// CompletedAt is the wall-clock time at which the run reached a terminal state.
	// Zero for still-running sessions.
	CompletedAt time.Time
	// Steps lists all steps for which at least one lifecycle event was observed, in
	// observation order (first EventStepStarted wins for ordering). Empty when the run
	// has not yet produced any step events (pending / history fallback without step data).
	Steps []StepStatus
	// Progress summarizes step counts derived from Steps. Zero-value when Steps is empty.
	Progress Progress
	// Inputs carries the workflow input values that were passed at run start.
	// Populated only when the run was started through the facade (live session path).
	// Nil for history-fallback records where inputs are not stored.
	Inputs map[string]any
}

RunStatus reflects the current state of a workflow run. Fields added since the initial DTO are backward-compatible: existing callers that only read RunID/Status/StartedAt/CompletedAt are unaffected; the new fields are populated when derivable from the session's event stream (live runs) and left at their zero value when not available (history-fallback path where only persisted metadata exists).

type RunStepRequest added in v0.11.2

type RunStepRequest struct {
	Identifier string            // canonical "pack/workflow" identifier
	StepName   string            // the step to execute
	Inputs     map[string]any    // workflow input values
	Mocks      map[string]string // mocked upstream state outputs
}

RunStepRequest is the input for executing a single workflow step in isolation (the `awf run --step` path). It bypasses the state machine and runs one step.

type Severity added in v0.5.0

type Severity int

Severity indicates the importance of a validation result. SeverityError is the zero value — unset severity defaults to error level.

const (
	SeverityError   Severity = 0
	SeverityWarning Severity = 1
	SeverityInfo    Severity = 2
)

type SingleStepRunner added in v0.11.2

type SingleStepRunner interface {
	RunStep(ctx context.Context, req RunStepRequest) (StepResult, error)
}

SingleStepRunner is a focused port for isolated single-step execution. It is implemented by application.Adapter and consumed only by the CLI `awf run --step` path (runSingleStep). Keeping it separate from WorkflowFacade ensures no other interface (API, TUI, ACP, test fakes) is required to implement this CLI-only operation (M1).

type SkillRepository added in v0.11.2

type SkillRepository interface {
	Load(ctx context.Context, name string) (*workflow.Skill, error)
	LoadFromPath(ctx context.Context, absolutePath string) (*workflow.Skill, error)
}

type Span added in v0.11.2

type Span interface {
	End()
	SetAttribute(key string, value any)
	RecordError(err error)
	AddEvent(name string)
}

type StateStore

type StateStore interface {
	Save(ctx context.Context, state *workflow.ExecutionContext) error
	Load(ctx context.Context, workflowID string) (*workflow.ExecutionContext, error)
	Delete(ctx context.Context, workflowID string) error
	List(ctx context.Context) ([]string, error)
}

StateStore defines the contract for persisting workflow execution state.

type StatusPresenter

type StatusPresenter interface {
	// ShowAborted displays a message indicating workflow was aborted.
	ShowAborted()

	// ShowSkipped displays a message indicating step was skipped.
	ShowSkipped(stepName string, nextStep string)

	// ShowCompleted displays a message indicating workflow completed.
	ShowCompleted(status workflow.ExecutionStatus)

	// ShowError displays an error message.
	ShowError(err error)
}

StatusPresenter defines the contract for displaying terminal and outcome states. Implementations handle rendering of workflow completion, abortion, and errors.

type StepExecuteRequest added in v0.5.0

type StepExecuteRequest struct {
	StepName string
	StepType string
	Config   map[string]any
	Inputs   map[string]any
}

StepExecuteRequest carries the inputs for a custom step type execution.

type StepExecuteResult added in v0.5.0

type StepExecuteResult struct {
	Output   string
	Data     map[string]any
	ExitCode int
}

StepExecuteResult holds the output produced by a custom step type.

type StepExecutor

type StepExecutor interface {
	// ExecuteStep runs a single step and returns the result.
	// The step is looked up by name from the workflow.
	ExecuteStep(
		ctx context.Context,
		wf *workflow.Workflow,
		stepName string,
		execCtx *workflow.ExecutionContext,
	) (*workflow.BranchResult, error)
}

StepExecutor defines the contract for executing a single workflow step. This is used by parallel execution to delegate individual branch execution.

type StepPresenter

type StepPresenter interface {
	// ShowHeader displays the interactive mode header with workflow name.
	ShowHeader(workflowName string)

	// ShowStepDetails displays step information before execution.
	ShowStepDetails(info *workflow.InteractiveStepInfo)

	// ShowExecuting displays a message indicating step execution is in progress.
	ShowExecuting(stepName string)

	// ShowStepResult displays the outcome of step execution.
	ShowStepResult(state *workflow.StepState, nextStep string)
}

StepPresenter defines the contract for displaying step lifecycle information. Implementations handle rendering of step execution progress and outcomes.

type StepResult added in v0.11.2

type StepResult struct {
	StepName    string
	Output      string
	Stderr      string
	ExitCode    int
	Status      RunState // pending, running, completed, failed, cancelled
	Error       string
	StartedAt   time.Time
	CompletedAt time.Time
}

StepResult carries the outcome of a single isolated step execution.

type StepStatus added in v0.11.2

type StepStatus struct {
	// Name is the step identifier as declared in the workflow YAML.
	Name string
	// Status is the last known state of the step: running, completed, failed, etc.
	Status RunState
	// Error holds the step-level error message when Status == RunStateFailed; empty otherwise.
	Error string
	// StartedAt is stamped when EventStepStarted is observed for this step; zero if not yet started.
	StartedAt time.Time
	// CompletedAt is stamped when EventStepCompleted (or a failure event) is observed; zero if not finished.
	CompletedAt time.Time
}

StepStatus carries the observed lifecycle state of a single workflow step, derived from the event stream projected into the RunSession replay buffer. It is a snapshot: zero-value times mean the event was not yet observed.

type StepTypeProvider added in v0.5.0

type StepTypeProvider interface {
	HasStepType(typeName string) bool
	ExecuteStep(ctx context.Context, req StepExecuteRequest) (StepExecuteResult, error)
}

StepTypeProvider dispatches execution of custom step types to the owning plugin. HasStepType must be O(1); implementations cache the type list at Init() time.

type TemplateRepository

type TemplateRepository interface {
	GetTemplate(ctx context.Context, name string) (*workflow.Template, error)
	ListTemplates(ctx context.Context) ([]string, error)
	Exists(ctx context.Context, name string) bool
}

type Tokenizer

type Tokenizer interface {
	// CountTokens returns the number of tokens in the given text.
	// The count may be exact (tiktoken) or approximate (character-based)
	// depending on the implementation.
	CountTokens(text string) (int, error)

	// CountTurnsTokens returns the total token count across multiple conversation turns.
	// This allows optimizations for batch counting in some implementations.
	CountTurnsTokens(turns []string) (int, error)

	// IsEstimate returns true if this tokenizer produces approximate counts.
	// Used to set TokensEstimated flag in conversation results.
	IsEstimate() bool

	// ModelName returns the tokenizer model identifier (e.g., "cl100k_base", "approximation").
	// Used for debugging and logging.
	ModelName() string
}

Tokenizer defines the contract for counting tokens in text. Implementations provide model-specific or approximation-based token counting for context window management.

type ToolContent added in v0.11.2

type ToolContent struct {
	Type string
	Text string
}

type ToolDefinition added in v0.11.2

type ToolDefinition struct {
	Name        string
	Description string
	InputSchema map[string]any
	Source      string
}

type ToolProvider added in v0.11.2

type ToolProvider interface {
	ListTools(ctx context.Context) ([]ToolDefinition, error)
	CallTool(ctx context.Context, name string, args map[string]any) (*ToolResult, error)
	Close(ctx context.Context) error
}

ToolProvider exposes a set of tools and executes them on behalf of a transport adapter (e.g. the MCP server).

CallTool contract:

  • args may be nil or an empty map; implementations MUST treat both identically (no arguments supplied). Adapters pass nil when the request carries no arguments.
  • On success, return a non-nil *ToolResult. Returning (nil, nil) is discouraged; adapters defensively map it to an IsError result rather than dereferencing nil.
  • Execution failures should be reported either as a returned error or as a *ToolResult with IsError=true; adapters surface both forms back to the client as tool errors.

type ToolResult added in v0.11.2

type ToolResult struct {
	Content []ToolContent
	IsError bool
}

type ToolRouter added in v0.11.2

type ToolRouter interface {
	ListTools(ctx context.Context) ([]ToolDefinition, error)
	CallTool(ctx context.Context, name string, args map[string]any) (*ToolResult, error)
}

ToolRouter is the narrow contract handed to agent providers that need to discover and invoke tools without owning their lifecycle. It is structurally a ToolProvider minus Close — the lifecycle stays with the component that constructed the router (e.g. the application's MCP proxy service), so leaking Close to the agent would invite double-close bugs. Both application/tools.Router and any future routing implementation satisfy this interface.

type Tracer added in v0.11.2

type Tracer interface {
	Start(ctx context.Context, spanName string) (context.Context, Span)
}

type UserInputReader added in v0.11.2

type UserInputReader interface {
	// ReadInput reads the next user message.
	// Returns empty string when the user submits no input (signals conversation end).
	// Returns error if the context is cancelled or an I/O error occurs.
	ReadInput(ctx context.Context) (string, error)
}

UserInputReader defines the contract for reading user input between conversation turns. Driven port — called by ConversationManager to get the next user message.

type UserInteraction

type UserInteraction interface {
	// PromptAction prompts the user for an action and returns their choice.
	// hasRetry indicates whether the [r]etry option should be available.
	PromptAction(ctx context.Context, hasRetry bool) (workflow.InteractiveAction, error)

	// EditInput prompts the user to edit an input value.
	// Returns the new value and any error from parsing.
	EditInput(ctx context.Context, name string, current any) (any, error)

	// ShowContext displays the current runtime context (inputs, states).
	ShowContext(ctx *workflow.RuntimeContext)
}

UserInteraction defines the contract for interactive user input and context display. Implementations handle user prompts, input editing, and runtime context visualization.

type ValidateOptions added in v0.11.2

type ValidateOptions struct {
	SkipPlugins      bool          // true ⇒ plugin validators are not invoked
	ValidatorTimeout time.Duration // >0 ⇒ bounds the plugin-validator phase via context deadline; 0 ⇒ no extra deadline
}

ValidateOptions carries validation-only knobs honored by WorkflowFacade.Validate and BatchValidator. Zero value = full validation (run all plugin validators, no extra per-validation deadline).

type ValidationError added in v0.11.2

type ValidationError struct {
	Code    domerrors.ErrorCode
	Field   string
	Message string
}

ValidationError is a single structured error entry in a ValidationReport. Code provides a machine-readable ErrorCode for programmatic branching. Field names the workflow element that failed validation (may be empty for top-level errors). Message is the human-readable explanation.

type ValidationReport added in v0.11.2

type ValidationReport struct {
	Valid  bool
	Errors []ValidationError
}

ValidationReport is returned by WorkflowFacade.Validate.

type ValidationResult added in v0.5.0

type ValidationResult struct {
	Severity Severity
	Message  string
	Step     string // empty for workflow-level findings
	Field    string // empty when not specific to a field
}

ValidationResult is a single finding from a workflow or step validator.

type WorkflowFacade added in v0.11.2

type WorkflowFacade interface {
	List(ctx context.Context) ([]WorkflowSummary, error)
	Validate(ctx context.Context, req RunRequest) (ValidationReport, error)
	Status(ctx context.Context, runID string) (RunStatus, error)
	History(ctx context.Context, filter HistoryFilter) ([]RunRecord, error)
	Run(ctx context.Context, req RunRequest) (RunSession, error)
	// Resume re-drives a previously persisted, non-completed run.
	// Returns ErrRunNotFound when runID is unknown to both the live session registry
	// and the history store. Returns ErrInvalidRequest when req.RunID is empty.
	Resume(ctx context.Context, req ResumeRequest) (RunSession, error)
}

WorkflowFacade is the primary port for workflow orchestration. Driving port — called by interface layer (CLI, API, MQ). RunStep is intentionally absent: single-step isolation is a CLI-only concern (awf run --step) and is exposed through the focused SingleStepRunner port so that every other implementer of WorkflowFacade is not burdened with it (M1).

type WorkflowInfo added in v0.11.2

type WorkflowInfo struct {
	Name   string
	Source WorkflowSource
	Path   string
}

WorkflowInfo carries the minimal metadata returned by ListWithSource. It lives in the ports package so that the application layer and the domain port interface share the same type without importing infrastructure packages.

type WorkflowReader added in v0.11.2

type WorkflowReader interface {
	GetWorkflow(ctx context.Context, identifier string) (*workflow.Workflow, error)
	HistoryStats(ctx context.Context, filter HistoryFilter) (*workflow.HistoryStats, error)
}

WorkflowReader is a focused read-only port for workflow-definition introspection (loading a single workflow) and history statistics. It is implemented by application.Adapter and consumed by the HTTP API for the two read endpoints whose payloads have no lightweight DTO equivalent on WorkflowFacade: GET /api/workflows/{scope}/{name} and GET /api/history/stats.

It is intentionally kept separate from WorkflowFacade — mirroring the SingleStepRunner segregation (M1) — so that the many WorkflowFacade implementers and test fakes that only drive execution/listing are not forced to implement definition-introspection methods they never use. GetWorkflow returns the domain aggregate (*workflow.Workflow) and HistoryStats returns *workflow.HistoryStats directly: these are domain types (no infrastructure leak), and returning them verbatim keeps the HTTP response shape byte-identical to the pre-facade path, so routing these endpoints through the facade introduces no JSON regression.

type WorkflowRepository

type WorkflowRepository interface {
	Load(ctx context.Context, name string) (*workflow.Workflow, error)
	List(ctx context.Context) ([]string, error)
	// ListWithSource returns workflow names together with their discovery source.
	// The ordering follows the same priority as List: earlier paths win for
	// duplicates and are listed first.
	ListWithSource(ctx context.Context) ([]WorkflowInfo, error)
	Exists(ctx context.Context, name string) (bool, error)
}

type WorkflowSource added in v0.11.2

type WorkflowSource string

WorkflowSource identifies the origin of a discovered workflow. It maps directly to the three discovery paths wired by the CLI:

  • SourceEnv — AWF_WORKFLOWS_PATH environment variable
  • SourceLocal — ./.awf/workflows/ (project-local)
  • SourceGlobal — $XDG_CONFIG_HOME/awf/workflows/ (user-wide)
const (
	SourceEnv    WorkflowSource = "env"
	SourceLocal  WorkflowSource = "local"
	SourceGlobal WorkflowSource = "global"
)

type WorkflowSummary added in v0.11.2

type WorkflowSummary struct {
	Name        string
	Scope       string
	Workflow    string
	Description string
	Version     string
	Tags        []string
}

WorkflowSummary is a lightweight descriptor returned by WorkflowFacade.List.

Scope and Workflow are the two components of the canonical identifier grammar "scope/workflow" (Scope is "local"/"global"/"env" or a vendor pack name; Workflow is the local part). They are populated from the underlying WorkflowEntry so that interface layers (notably the HTTP API's /api/workflows/{scope}/{name} grammar) can reconstruct addressable identifiers from a listing without re-parsing Name.

type WorkflowValidatorProvider added in v0.5.0

type WorkflowValidatorProvider interface {
	ValidateWorkflow(ctx context.Context, workflowJSON []byte) ([]ValidationResult, error)
	ValidateStep(ctx context.Context, workflowJSON []byte, stepName string) ([]ValidationResult, error)
}

WorkflowValidatorProvider runs plugin-provided validation rules against a workflow. workflowJSON is the JSON-encoded domain workflow struct.

Jump to

Keyboard shortcuts

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