loop

package
v0.3.0-beta.15 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package loop owns loop-domain validation and compile surfaces.

Index

Constants

View Source
const (
	CatalogKindReadOnly  CatalogKind = "read_only"
	CatalogKindWorkspace CatalogKind = "workspace"

	CatalogSortName     = "name"
	DefaultCatalogLimit = 50
	MaxCatalogLimit     = 200
)
View Source
const (
	// GenerationOutputStatusControlPending identifies a completed worker whose Loop control is unsettled.
	GenerationOutputStatusControlPending = "control_pending"
	// GenerationOutputStatusAwaitingGoal identifies a settled pause or approval gate awaiting re-entry.
	GenerationOutputStatusAwaitingGoal = "awaiting_goal"
)
View Source
const (
	// ReasonMetaActualState names the durable state that rejected a lifecycle verb.
	ReasonMetaActualState = "actual_state"
	// ReasonMetaAllowedTransitions lists the valid next lifecycle verbs as a comma-separated value.
	ReasonMetaAllowedTransitions = "allowed_transitions"
	// ReasonMetaWinnerActorKind attributes a winning concurrent lifecycle mutation.
	ReasonMetaWinnerActorKind = "winner_actor_kind"
	// ReasonMetaWinnerActorID identifies the winning concurrent lifecycle actor.
	ReasonMetaWinnerActorID = "winner_actor_id"
	// ReasonMetaWinnerReason carries the bounded reason recorded by the winning mutation.
	ReasonMetaWinnerReason = "winner_reason"
	// ReasonMetaWinnerRequestedAt carries the winning mutation timestamp in RFC3339Nano form.
	ReasonMetaWinnerRequestedAt = "winner_requested_at"
)
View Source
const (
	LifecycleSourceNode       = "node"
	LifecycleSourceLoopConfig = "loop_config"
	LifecycleSourceDefault    = "default"
	BreakerGlobalSource       = "breaker (global)"
)
View Source
const (
	DefaultNodeInventoryLimit = 50
	MaxNodeInventoryLimit     = 200
)
View Source
const (
	// NodeWaitKindTimer parks a cell until its durable timestamp is due.
	NodeWaitKindTimer = "timer"
	// NodeWaitKindEvent parks a cell until a matching watch event is admitted.
	NodeWaitKindEvent = "event"
	// NodeWaitKindApprovalEscalation parks a gate while its escalation ladder remains active.
	NodeWaitKindApprovalEscalation = "approval_escalation"
)
View Source
const (
	// ResourceKind is the desired-state resource kind for projected loop definitions.
	ResourceKind = resources.ResourceKind("loop")
	// ResourceMaxBytes is intentionally small because loop resources project metadata only.
	ResourceMaxBytes = 64 * 1024
	// NamePattern is the canonical loop definition name pattern.
	NamePattern = `^[a-z][a-z0-9_-]*$`
)
View Source
const (
	// LoopMaxFanoutWidth is the absolute structural fan-out width ceiling.
	LoopMaxFanoutWidth = 64
	// LoopMaxGateRevisions is the absolute structural gate revision ceiling.
	LoopMaxGateRevisions = dsl.GateMaxRevisionsCeiling
	// LoopMaxNoProgressWindow is the compile-time generation no-progress ceiling.
	LoopMaxNoProgressWindow = 30
	// LoopFailureBreakerLimit is the compile-time consecutive-failure breaker ceiling.
	LoopFailureBreakerLimit = 2
	// LoopMaxAncestryDepth is the maximum run-loop parent chain depth.
	LoopMaxAncestryDepth = 8
)
View Source
const (
	// CodeCycle reports a graph cycle.
	CodeCycle = "cycle"
	// CodeUnreachableNode reports a node unreachable from source roots.
	CodeUnreachableNode = "unreachable_node"
	// CodeNonTerminatingStructure reports a body with no terminal path.
	CodeNonTerminatingStructure = "non_terminating_structure"
	// CodeFanOutUnbounded reports a fan-out without finite materialization bounds.
	CodeFanOutUnbounded = "fan_out_unbounded"
	// CodeFanOutCeilingExceeded reports fan-out width beyond LoopMaxFanoutWidth.
	CodeFanOutCeilingExceeded = "fan_out_ceiling_exceeded"
	// CodeGateMaxRevisionsCeilingExceeded reports gate max_revisions beyond its ceiling.
	CodeGateMaxRevisionsCeilingExceeded = "gate_max_revisions_ceiling_exceeded"
	// CodeNodeIDInvalid reports a non-snake_case node id.
	CodeNodeIDInvalid = "node_id_invalid"
	// CodeVerdictPolicyRequiresJudge reports revise_until_clean without a judge/human source.
	CodeVerdictPolicyRequiresJudge = "verdict_policy_requires_judge"
	// CodeMetricSingle reports multiple metric criteria in one definition.
	CodeMetricSingle = "metric_single"
	// CodeMetricMachineCriterionRequired reports a metric on a non-machine criterion.
	CodeMetricMachineCriterionRequired = "metric_machine_criterion_required"
	// CodeMetricDirectionRequired reports a metric without a direction.
	CodeMetricDirectionRequired = "metric_direction_required"
	// CodeMetricDirectionInvalid reports a direction outside the closed metric enum.
	CodeMetricDirectionInvalid = "metric_direction_invalid"
	// CodeMetricMinDeltaInvalid reports a negative or non-finite metric delta.
	CodeMetricMinDeltaInvalid = "metric_min_delta_invalid"
	// CodeInvalidHarvest reports an unsupported or malformed harvest policy.
	CodeInvalidHarvest = "invalid_harvest"
	// CodeUnknownActionKind reports action kinds that are neither reserved nor resolvable ToolIDs.
	CodeUnknownActionKind = "unknown_action_kind"
	// CodeUnknownControlKind reports a control kind outside the closed enum.
	CodeUnknownControlKind = "unknown_control_kind"
	// CodeUnknownSourceKind reports a source kind outside the closed enum.
	CodeUnknownSourceKind = "unknown_source_kind"
	// CodeWatchKindRequired reports a watch-source missing its extension source kind.
	CodeWatchKindRequired = "watch_kind_required"
	// CodeWatchEventsSubscriptionRequired reports a watch-events node with no subscriptions.
	CodeWatchEventsSubscriptionRequired = "watch_events_subscription_required"
	// CodeWatchEventsKindUnknown reports a watch-events subscription kind outside the hook catalog.
	CodeWatchEventsKindUnknown = "watch_events_kind_unknown"
	// CodeWatchEventsKindUnsupported reports a hook catalog kind outside the watch-events registry.
	CodeWatchEventsKindUnsupported = "watch_events_kind_unsupported"
	// CodeWatchEventsFilterInvalid reports a CEL filter that cannot compile in the event env.
	CodeWatchEventsFilterInvalid = "watch_events_filter_invalid"
	// CodeWatchEventsFilterTooBroad is reserved for registry RequiredVars gates.
	CodeWatchEventsFilterTooBroad = "watch_events_filter_too_broad"
	// CodeWatchEventsShapeInvalid reports events/watch/produces shape contradictions.
	CodeWatchEventsShapeInvalid = "watch_events_shape_invalid"
	// CodeFileImportParseRequired reports a missing or unsupported file-import parse mode.
	CodeFileImportParseRequired = "file_import_parse_required"
	// CodeDuplicateNodeID reports repeated node IDs.
	CodeDuplicateNodeID = "duplicate_node_id"
	// CodeUnknownTerminalState reports contract terminal states outside the closed enum.
	CodeUnknownTerminalState = "unknown_terminal_state"
	// CodeGoalJudgeRequired reports a Goal without at least one valid supported judge.
	CodeGoalJudgeRequired = "goal_judge_required"
	// CodeGoalObjectiveRequired reports a Goal without a non-empty objective.
	CodeGoalObjectiveRequired = "goal_objective_required"
	// CodeGoalMaxTurnsRequired reports a Goal without a positive authored turn limit.
	CodeGoalMaxTurnsRequired = "goal_max_turns_required"
	// CodeGoalOutputStatusMissingBlocked reports a Goal output schema that cannot represent blocked.
	CodeGoalOutputStatusMissingBlocked = "goal_output_status_missing_blocked"
	// CodeGoalOnExhaustedInvalid reports an unsupported Goal exhaustion policy.
	CodeGoalOnExhaustedInvalid = "goal_on_exhausted_invalid"
	// CodeGoalHumanJudgeUnsupported reports a human Goal judge, which v1 cannot lease safely.
	CodeGoalHumanJudgeUnsupported = "goal_human_judge_unsupported"
	// CodeContinuousForbidsParallel reports a continuous Goal inside parallel fan-out.
	CodeContinuousForbidsParallel = "continuous_forbids_parallel"
	// CodeRetryFreshSessionRequiresContinuous reports an invalid fresh-session retry policy.
	CodeRetryFreshSessionRequiresContinuous = "retry_fresh_session_requires_continuous"
	// CodeSessionSpecAmbiguous reports a session envelope that is not exactly isolated or continuous.
	CodeSessionSpecAmbiguous = "session_spec_ambiguous"
	// CodeContinuousHandleReused reports duplicate continuous Goal display identities.
	CodeContinuousHandleReused = "continuous_handle_reused"
	// CodeRetryMaxUnsupported reports the retired retry.max key.
	CodeRetryMaxUnsupported = "retry_max_unsupported"
	// CodeNetworkParticipationInvalid reports malformed authored participation intent.
	CodeNetworkParticipationInvalid = "network_participation_invalid"
	// CodeLoopRequiresLive reports a Network-using graph without authored Live participation.
	CodeLoopRequiresLive = "loop_requires_live"
	// CodeErrorRouteBackward reports an error route that is not a direct forward edge.
	CodeErrorRouteBackward = "error_route_backward"
	// CodeErrorRouteConflict reports route and allow_fail on the same error policy.
	CodeErrorRouteConflict = "error_route_conflict"
	// CodeErrorRouteDead warns about an error route on an infallible node.
	CodeErrorRouteDead = "error_route_dead"
	// CodeRetryOnGoalNode reports generic lifecycle retry fields on a Goal node.
	CodeRetryOnGoalNode = "retry_on_goal_node"
	// CodeTimeoutExceedsDeadline reports a per-attempt timeout beyond the node deadline.
	CodeTimeoutExceedsDeadline = "timeout_exceeds_deadline"
	// CodeDurationInvalid reports an invalid or non-positive lifecycle duration.
	CodeDurationInvalid = "duration_invalid"
	// CodeResultContractInvalid reports a result contract that cannot resolve against output.
	CodeResultContractInvalid = "result_contract_invalid"
	// CodeEffectShapeInvalid reports an effect that is not exactly one emit or tool call.
	CodeEffectShapeInvalid = "effect_shape_invalid"
	// CodeEffectToolUnknown warns that an effect tool is absent from the schema snapshot.
	CodeEffectToolUnknown = "effect_tool_unknown"
	// CodeWaitShapeInvalid reports an invalid wait discriminator or expiry shape.
	CodeWaitShapeInvalid = "wait_shape_invalid"
	// CodeWaitExpiryWithoutPath warns that expiry can only surface needs-attention.
	CodeWaitExpiryWithoutPath = "wait_expiry_without_path"
	// CodeWatchIdentityRequired reports a watch source without stable event identity support.
	CodeWatchIdentityRequired = "watch_identity_required"
	// CodeParentCloseInvalid reports parent-close policy outside run-loop or its closed enum.
	CodeParentCloseInvalid = "parent_close_invalid"
	// CodeAutopauseRuleInvalid identifies a config-side autopause compilation failure.
	CodeAutopauseRuleInvalid = "autopause_rule_invalid"
)
View Source
const (
	// WatchEventsTaskStream is the task_events replay stream name.
	WatchEventsTaskStream = watchEventsTaskStream
	// WatchEventsLoopStream is the loop_run_events replay stream name.
	WatchEventsLoopStream = watchEventsLoopStream
	// WatchEventsAutomationStream is the automation_runs replay stream name.
	WatchEventsAutomationStream = watchEventsAutomationStream
	// WatchEventsNetworkStream is the network_timeline_log replay stream name.
	WatchEventsNetworkStream = watchEventsNetworkStream
	// WatchEventsObserveStream is the event_summaries replay stream name.
	WatchEventsObserveStream = watchEventsObserveStream
	// WatchEventsSessionStream is the per-session event replay stream base name.
	WatchEventsSessionStream = watchEventsSessionStream
)
View Source
const (
	// AttentionSilence reports ambiguous loss of liveness evidence without declaring death.
	AttentionSilence = "silence"
)
View Source
const CoordinatorControlKindLoopAction = "loop_action"

CoordinatorControlKindLoopAction identifies a Loop-owned action-control completion envelope.

View Source
const DefaultWatchSilenceWindow = 30 * time.Minute

DefaultWatchSilenceWindow is the fallback inactivity clock for watch-source loops.

View Source
const (
	// DefinitionFileName is the canonical filename inside one loop-definition directory.
	DefinitionFileName = "loop.yaml"
)
View Source
const InlineGoalLoopName = "__session_goal__"

InlineGoalLoopName is the reserved non-catalog display identity for session Goals.

View Source
const (
	// LoopOutputInlineLimitBytes is the largest loop node result kept inline in task_runs.
	LoopOutputInlineLimitBytes = 16 * 1024
)

Variables

View Source
var (
	// ErrActionUnknownKind reports a non-reserved action kind missing from RuntimeRegistry.
	ErrActionUnknownKind = errors.New("loop: unknown action kind")
	// ErrActionDependencyMissing reports an unwired action runtime collaborator.
	ErrActionDependencyMissing = errors.New("loop: action dependency missing")
	// ErrActionStalled reports a harvest that must wait for an external result.
	ErrActionStalled = errors.New("loop: action stalled")
	// ErrActionSchemaInvalid reports run-agent structured output that failed output_schema validation.
	ErrActionSchemaInvalid = errors.New("loop: action schema validation failed")
	// ErrActionTimeout reports an action turn canceled by the node timeout.
	ErrActionTimeout = errors.New("loop: action timeout")
)
View Source
var (
	ErrCatalogQueryInvalid  = errors.New("loop: catalog query is invalid")
	ErrCatalogCursorInvalid = errors.New("loop: catalog cursor is invalid")
	ErrCatalogUnavailable   = errors.New("loop: catalog is unavailable")
)
View Source
var (
	// ErrValidation reports invalid loop-domain input.
	ErrValidation = errors.New("loop: validation failed")
	// ErrDefinitionReadOnly reports an attempted mutation of a non-workspace definition.
	ErrDefinitionReadOnly = errors.New("loop: definition is read-only")
	// ErrRunNotFound reports a missing loop_run aggregate.
	ErrRunNotFound = errors.New("loop: run not found")
	// ErrConfigNotFound reports the absence of a per-loop loop_config row.
	ErrConfigNotFound = errors.New("loop: config not found")
	// ErrOutputRefNotFound reports a missing content-addressed loop output payload.
	ErrOutputRefNotFound = errors.New("loop: output ref not found")
	// ErrInvalidTransition reports an illegal status transition.
	ErrInvalidTransition = errors.New("loop: invalid status transition")
	// ErrTransitionConflict reports that the durable compare-and-swap lost a race.
	ErrTransitionConflict = errors.New("loop: transition conflict")
	// ErrConcurrencyConflict reports a same-loop start rejected by policy.
	ErrConcurrencyConflict = errors.New("loop: concurrency conflict")
	// ErrAncestryRejected reports an invalid run-loop ancestry chain.
	ErrAncestryRejected = errors.New("loop: ancestry rejected")
	// ErrStaleGenerationOutput reports an output write fenced by a newer cell epoch.
	ErrStaleGenerationOutput = errors.New("loop: stale generation output")
)
View Source
var (
	// ErrDefinitionExists reports a write/fork that would overwrite an existing loop definition.
	ErrDefinitionExists = errors.New("loop definition already exists")
	// ErrDefinitionNotFound reports a missing loop definition.
	ErrDefinitionNotFound = errors.New("loop definition not found")
)

Functions

func ActionFailureOutputRef

func ActionFailureOutputRef(failure ActionFailure) (string, bool)

ActionFailureOutputRef encodes a validated failure for a generation output cell.

func ActionFailureOutputRefFromMetadata

func ActionFailureOutputRefFromMetadata(raw json.RawMessage) (string, bool)

ActionFailureOutputRefFromMetadata extracts a valid failure payload from task-run metadata.

func ActionStructuredCandidate

func ActionStructuredCandidate(result ActionPromptResult) (json.RawMessage, error)

ActionStructuredCandidate returns the structured object supplied by one action prompt result.

func AppendQuarantineRequeue

func AppendQuarantineRequeue(
	raw json.RawMessage,
	actor task.ActorContext,
	reason string,
	at time.Time,
	generation int,
) (json.RawMessage, error)

AppendQuarantineRequeue retains episode history and appends sanitized requeue provenance.

func BuildEffectContext

func BuildEffectContext(req EffectContextRequest) (map[string]any, error)

BuildEffectContext pre-binds stable identity, failure, attempt, and decision links.

func BuildExecutedDefinitionSnapshot

func BuildExecutedDefinitionSnapshot(
	resolved *ResolvedDefinition,
	effective EffectiveConfig,
) (json.RawMessage, string, error)

BuildExecutedDefinitionSnapshot creates the only content-addressed artifact executable after Start.

func ContextWithActionUsageReporter

func ContextWithActionUsageReporter(ctx context.Context, reporter ActionUsageReporter) context.Context

ContextWithActionUsageReporter attaches a cumulative action usage reporter to ctx.

func DecodeWaitAheadRejectCursors

func DecodeWaitAheadRejectCursors(raw json.RawMessage) (map[string]int64, bool, error)

DecodeWaitAheadRejectCursors returns the stream fence captured when a reject-policy wait entered.

func DeleteWritableDefinition

func DeleteWritableDefinition(root string, name string) error

DeleteWritableDefinition deletes a user/workspace loop definition directory.

func DeriveStartActor

func DeriveStartActor(
	kind dsl.StartKind,
	workspaceID string,
	actorRef string,
	originRef string,
) (task.ActorContext, error)

DeriveStartActor maps every start surface to its canonical task ActorContext derivation.

func EffectDeliveryID

func EffectDeliveryID(runID RunID, sourceEventID string, trigger EffectTrigger, entryIndex int) string

EffectDeliveryID derives the stable at-least-once identity for one entry.

func EncodeNodeInventoryCursor

func EncodeNodeInventoryCursor(query NodeInventoryQuery, item NodeInventoryItem) (string, error)

EncodeNodeInventoryCursor creates an opaque continuation cursor from the last returned row.

func ForkDefinitionFile

func ForkDefinitionFile(sourceFilePath string, targetRoot string) (_ string, err error)

ForkDefinitionFile copies a file-backed loop definition directory into a writable root.

func GenerationOutputStatusParked

func GenerationOutputStatusParked(status string) bool

GenerationOutputStatusParked reports whether a cell is deliberately excluded from scheduling, rerun, and no-progress arithmetic.

func GoalNodeTaskID

func GoalNodeTaskID(loopRunID RunID, generation int, nodeID dsl.NodeID, itemIndex int) string

GoalNodeTaskID returns the stable task identity shared by every segment of one Goal node instance.

func GoalSegmentIdempotencyKey

func GoalSegmentIdempotencyKey(
	loopRunID RunID,
	generation int,
	nodeID dsl.NodeID,
	itemIndex int,
	controlEpoch int64,
) string

GoalSegmentIdempotencyKey returns the epoch-scoped deduplication key for one Goal segment.

func GoalSegmentRunID

func GoalSegmentRunID(
	loopRunID RunID,
	generation int,
	nodeID dsl.NodeID,
	itemIndex int,
	controlEpoch int64,
) string

GoalSegmentRunID returns the epoch-scoped worker run identity for one Goal segment.

func IsDefinitionFileName

func IsDefinitionFileName(name string) bool

IsDefinitionFileName reports whether name can hold a loop definition document.

func IsKnownFailureClass

func IsKnownFailureClass(value FailureClass) bool

IsKnownFailureClass reports whether value belongs to the closed failure vocabulary.

func MaterializeContract

func MaterializeContract(contract dsl.Contract, inputs map[string]any) (dsl.Contract, error)

MaterializeContract resolves the user-facing contract narrative from Run inputs.

func MaterializeGoalParams

func MaterializeGoalParams(node dsl.Node, namespace map[string]any) (dsl.GoalParams, error)

MaterializeGoalParams resolves one Goal node against its runtime namespace.

func NewResourceCodec

func NewResourceCodec() (resources.KindCodec[ResourceSpec], error)

NewResourceCodec returns the JSON codec for loop resource projections.

func NewRuntimeValidationError

func NewRuntimeValidationError(items ...RuntimeValidationItem) error

NewRuntimeValidationError constructs a normalized validation error.

func NodeCellTaskID

func NodeCellTaskID(loopRunID RunID, generation int, nodeID string, itemIndex int) string

NodeCellTaskID is the canonical workspace-task id for one loop node cell.

func OutputPayloadRequiresRef

func OutputPayloadRequiresRef(payload json.RawMessage) bool

OutputPayloadRequiresRef reports whether a loop node result must be externalized.

func OutputRefForPayload

func OutputRefForPayload(payload json.RawMessage) string

OutputRefForPayload returns the content-addressed ref for a persisted loop output payload.

func OutputRefLooksContentAddressed

func OutputRefLooksContentAddressed(ref string) bool

OutputRefLooksContentAddressed reports whether a ref uses Compozy's loop output hash form.

func RenderContractBlock

func RenderContractBlock(contract dsl.Contract) string

RenderContractBlock renders the ADR-018 loop contract for worker prompt context.

func ReportActionSessionBound

func ReportActionSessionBound(ctx context.Context, sessionID string)

ReportActionSessionBound records the exact ACP session used by an action executor.

func ResolveEffectiveResources

func ResolveEffectiveResources(
	records []resources.Record[ResourceSpec],
	workspaceID string,
) []resources.Record[ResourceSpec]

ResolveEffectiveResources overlays records for one read scope using loop precedence.

func ResolveInputs

func ResolveInputs(def dsl.Definition, inputs Inputs) (map[string]any, error)

ResolveInputs applies run and definition values for callers without configured layers.

func ResolveStartBinding

func ResolveStartBinding(
	ctx context.Context,
	resolver DefinitionResolver,
	ws WorkspaceID,
	name string,
	kind dsl.StartKind,
) (*dsl.StartBinding, error)

ResolveStartBinding loads the definition and returns the matching start binding.

func ResolveStartTargetInputs

func ResolveStartTargetInputs(
	ctx context.Context,
	resolver DefinitionResolver,
	req StartTargetResolution,
) (map[string]any, error)

ResolveStartTargetInputs resolves static inputs plus input_mapping into typed loop inputs.

func RetiredRuntimeKeyPath

func RetiredRuntimeKeyPath(raw []byte) (string, bool)

RetiredRuntimeKeyPath returns the first deterministic path to a retired runtime key.

func RetryWakeIdempotencyKey

func RetryWakeIdempotencyKey(cell RetryDueCell) string

RetryWakeIdempotencyKey is shared by the durable scan and opportunistic timer paths.

func SupportedWatchEvents

func SupportedWatchEvents() map[hooks.HookEvent]WatchEventsContract

SupportedWatchEvents returns the closed watch-events registry for shipped phases.

func SyntheticGoalGateID

func SyntheticGoalGateID(nodeID dsl.NodeID, generation int, itemIndex int, cause ReasonCode) dsl.NodeID

SyntheticGoalGateID returns the exact Goal approval gate correlation identity.

func ValidateActionStructured

func ValidateActionStructured(schema dsl.Schema, result ActionPromptResult) (json.RawMessage, error)

ValidateActionStructured applies the Loop-owned generation-output schema validator. Child action executors use this seam instead of owning a second schema implementation. Free-text turns are scanned newest-first and the first candidate object that satisfies the schema wins, so JSON quoted mid-turn cannot shadow the answer.

func ValidateDefinitionInputDefaults

func ValidateDefinitionInputDefaults(def dsl.Definition) error

ValidateDefinitionInputDefaults validates only author-contained defaults.

func ValidateDefinitionRuntime

func ValidateDefinitionRuntime(
	ctx context.Context,
	catalog RuntimeCatalog,
	def dsl.Definition,
) error

ValidateDefinitionRuntime validates only runtime values authored in one definition.

func ValidateEffectiveRuntime

func ValidateEffectiveRuntime(ctx context.Context, catalog RuntimeCatalog, cfg EffectiveConfig) error

ValidateEffectiveRuntime validates every explicit runtime value before a run is created.

func ValidateLoopConfigRuntime

func ValidateLoopConfigRuntime(ctx context.Context, catalog RuntimeCatalog, cfg LoopConfig) error

ValidateLoopConfigRuntime validates runtime values in one raw configuration layer.

func ValidateName

func ValidateName(name string) (string, error)

ValidateName returns a trimmed loop name when it matches the canonical name pattern.

func ValidateNodeRequeueMutation

func ValidateNodeRequeueMutation(m NodeRequeueMutation) error

ValidateNodeRequeueMutation rejects incomplete or stale node requeue requests.

func ValidateRuntimeRules

func ValidateRuntimeRules(rules []RuntimeRule) error

ValidateRuntimeRules enforces exclusive selectors and non-empty runtime values.

func ValidateStartTarget

func ValidateStartTarget(
	ctx context.Context,
	resolver DefinitionResolver,
	req StartTargetValidation,
) error

ValidateStartTarget checks the allowlist and the target input keys/templates without firing a loop.

func ValidateWaitPayload

func ValidateWaitPayload(expect json.RawMessage, payload json.RawMessage) error

ValidateWaitPayload validates one admitted wait payload against its persisted schema.

func WaitExpiryOrigin

func WaitExpiryOrigin(route string) task.Origin

WaitExpiryOrigin identifies a coordinator wake caused by authored wait expiry.

func WaitExpiryRouteOutputRef

func WaitExpiryRouteOutputRef(route string) string

WaitExpiryRouteOutputRef records the authored timeout branch selected by the due scanner.

func WatchEventsBaseStream

func WatchEventsBaseStream(stream string) string

WatchEventsBaseStream returns the stable registry stream for a cursor stream key.

func WatchEventsSessionIDFromStream

func WatchEventsSessionIDFromStream(stream string) (string, bool)

WatchEventsSessionIDFromStream extracts the session id from a dynamic session event stream key.

func WatchEventsSessionStreamForSession

func WatchEventsSessionStreamForSession(sessionID string) string

WatchEventsSessionStreamForSession returns the cursor stream key for one session.

Types

type ActionAppliedRuntimeRecorder

type ActionAppliedRuntimeRecorder interface {
	RecordAppliedRuntime(
		ctx context.Context,
		workspaceID WorkspaceID,
		loopRunID RunID,
		generation int,
		nodeID dsl.NodeID,
		itemIndex int,
		resolved ResolvedRuntime,
	) error
}

ActionAppliedRuntimeRecorder persists the runtime actually applied by a successful bind.

type ActionControl

type ActionControl struct {
	Disposition  ActionDisposition `json:"disposition"`
	GoalStatus   string            `json:"goal_status"`
	Cause        ReasonCode        `json:"cause,omitempty"`
	GateID       dsl.NodeID        `json:"gate_id,omitempty"`
	CheckpointID string            `json:"checkpoint_id,omitempty"`
}

ActionControl carries a neutral loop-owned control result through task completion.

func DecodeActionControlResult

func DecodeActionControlResult(raw json.RawMessage) (ActionControl, error)

DecodeActionControlResult validates one persisted neutral task completion for Loop ownership.

func (ActionControl) Validate

func (c ActionControl) Validate() error

Validate enforces the Goal status/disposition contract before coordinator settlement.

type ActionDisposition

type ActionDisposition string

ActionDisposition is the typed action-to-coordinator control vocabulary.

const (
	// ActionDispositionSucceeded follows normal action harvest.
	ActionDispositionSucceeded ActionDisposition = "succeeded"
	// ActionDispositionBlocked terminates the run as blocked.
	ActionDispositionBlocked ActionDisposition = "blocked"
	// ActionDispositionExhausted terminates the run as exhausted.
	ActionDispositionExhausted ActionDisposition = "exhausted"
	// ActionDispositionPaused parks the run until Resume.
	ActionDispositionPaused ActionDisposition = "paused"
	// ActionDispositionNeedsApproval parks the run behind a typed approval.
	ActionDispositionNeedsApproval ActionDisposition = "needs-approval"
)

func (ActionDisposition) Valid

func (d ActionDisposition) Valid() bool

Valid reports whether the disposition is part of the closed coordinator-control vocabulary.

type ActionEvent

type ActionEvent struct {
	Sequence int64           `json:"sequence"`
	Type     string          `json:"type,omitempty"`
	Text     string          `json:"text,omitempty"`
	Content  json.RawMessage `json:"content,omitempty"`
}

ActionEvent is a stable projection of one ACP/network event harvested by sequence.

type ActionEventRangeReader

type ActionEventRangeReader interface {
	ReadActionEventRange(ctx context.Context, req ActionEventRangeRequest) (ActionEventRangeResult, error)
}

ActionEventRangeReader reads ACP/network events by stable sequence.

type ActionEventRangeRequest

type ActionEventRangeRequest struct {
	SessionID     string
	EventStartSeq int64
	EventEndSeq   int64
	Raw           ActionRawResult
	Node          dsl.Node
}

ActionEventRangeRequest asks an injected event reader to harvest one append-only window.

type ActionEventRangeResult

type ActionEventRangeResult struct {
	Events     []ActionEvent
	Structured json.RawMessage
}

ActionEventRangeResult is the structured result of an async event-range harvest.

type ActionExecutionInput

type ActionExecutionInput struct {
	WorkspaceID              WorkspaceID
	LoopRunID                RunID
	Generation               int
	NodeID                   dsl.NodeID
	ItemIndex                int
	Attempt                  int
	CellEpoch                int64
	DeathResume              *DeathResumeContext
	RetryFailure             *ClassifiedFailure
	RepairFailures           []ActionRepairFailure
	Namespace                map[string]any
	Contract                 *dsl.Contract
	ToolScope                tools.Scope
	Actor                    task.ActorContext
	CorrelationID            string
	RuntimeSelection         *ActionRuntimeSelection
	CWD                      string
	AllowedTools             []string
	OriginSessionID          string
	OriginCreationProfileRef string
	OriginPolicySpecDigest   string
	OriginCreationDigest     string
	GoalContextNudgeRatio    *float64
	UsageReporter            ActionUsageReporter
	PersistedTaskTokensUsed  int64
	GoalSegmentEpoch         int64
	NetworkParticipation     *participation.Spec
}

ActionExecutionInput is the loop-owned execution context for one node instance.

func (ActionExecutionInput) RuntimeSelectionOrZero

func (in ActionExecutionInput) RuntimeSelectionOrZero() ActionRuntimeSelection

RuntimeSelectionOrZero returns the configured runtime inputs or their zero-value semantics.

type ActionExecutor

type ActionExecutor interface {
	Execute(ctx context.Context, node dsl.Node, in ActionExecutionInput) (ActionRawResult, error)
	Harvest(ctx context.Context, raw ActionRawResult, node dsl.Node) (ActionOutput, error)
}

ActionExecutor runs one loop action node and converts its raw result into node output.

type ActionFailure

type ActionFailure struct {
	Kind     string `json:"kind"`
	Code     string `json:"code"`
	Cause    string `json:"cause"`
	Recovery string `json:"recovery"`
	Target   string `json:"target,omitempty"`
}

ActionFailure is the durable operator-safe failure payload stored for a Loop action.

func ActionFailureFromMetadata

func ActionFailureFromMetadata(raw json.RawMessage) (ActionFailure, bool)

ActionFailureFromMetadata extracts a validated operator-safe failure from task-run metadata.

func NewActionFailure

func NewActionFailure(code string, cause string, recovery string) ActionFailure

NewActionFailure constructs a normalized action failure payload.

type ActionLoopStarter

type ActionLoopStarter interface {
	Start(ctx context.Context, ws WorkspaceID, name string, inputs Inputs, actor task.ActorContext) (*Run, error)
}

ActionLoopStarter is the run-loop seam implemented by loop.Service.

type ActionOutput

type ActionOutput struct {
	Structured      json.RawMessage
	Value           any
	Text            string
	SessionID       string
	EventStartSeq   int64
	EventEndSeq     int64
	TokensUsed      int64
	ChildLoopRunID  RunID
	Status          string
	ResolvedRuntime *ResolvedRuntime
}

ActionOutput is the typed loop-node output written into generation snapshots.

type ActionPromptOutcome

type ActionPromptOutcome string

ActionPromptOutcome is the durable managed-input terminal classification.

const (
	// ActionPromptOutcomeCompleted carries exactly one valid ACP stop reason.
	ActionPromptOutcomeCompleted ActionPromptOutcome = "completed"
	// ActionPromptOutcomeInvalidResult carries malformed terminal provider evidence.
	ActionPromptOutcomeInvalidResult ActionPromptOutcome = "invalid-result"
	// ActionPromptOutcomeFailed carries a normalized post-dispatch failure.
	ActionPromptOutcomeFailed ActionPromptOutcome = "failed"
	// ActionPromptOutcomeAmbiguous records an effect whose terminal truth cannot be proven.
	ActionPromptOutcomeAmbiguous ActionPromptOutcome = "ambiguous"
	// ActionPromptOutcomeBudgetFenced records a pre-submit budget fence.
	ActionPromptOutcomeBudgetFenced ActionPromptOutcome = "budget-fenced"
	// ActionPromptOutcomeControlFenced records a pre-submit control fence.
	ActionPromptOutcomeControlFenced ActionPromptOutcome = "control-fenced"
	// ActionPromptOutcomeRejectedBeforeSubmit records a proven effect-known-false rejection.
	ActionPromptOutcomeRejectedBeforeSubmit ActionPromptOutcome = "rejected-before-submit"
)

type ActionPromptOwner

type ActionPromptOwner struct {
	LoopRunID     RunID
	TaskRunID     string
	Generation    int
	NodeID        NodeID
	ItemIndex     int
	Turn          int
	PromptAttempt int
	ControlEpoch  int64
	BindingEpoch  int64
}

ActionPromptOwner is the complete CAS identity for one managed Goal prompt.

type ActionPromptRequest

type ActionPromptRequest struct {
	PromptID             string
	Message              string
	Kind                 string
	Owner                ActionPromptOwner
	UsageBaseTokens      int64
	UsageBaseReported    bool
	ContextUsageSequence *int64
	ContextUsageUsed     *int64
	UsageReporter        ActionUsageReporter
}

ActionPromptRequest is one work-order turn inside a bound run-agent session.

type ActionPromptResult

type ActionPromptResult struct {
	PromptID         string
	Outcome          ActionPromptOutcome
	Text             string
	Structured       json.RawMessage
	EventStartSeq    int64
	EventEndSeq      int64
	TokensUsed       int64
	TokensReported   bool
	StopReason       ActionStopReason
	FenceDisposition ActionDisposition
	ReasonCode       ReasonCode
}

ActionPromptResult captures one ACP prompt turn.

type ActionPromptTerminal

type ActionPromptTerminal struct {
	PromptID         string
	Outcome          ActionPromptOutcome
	Text             string
	Structured       json.RawMessage
	EventStartSeq    int64
	EventEndSeq      int64
	TokensUsed       int64
	TokensReported   bool
	StopReason       ActionStopReason
	FenceDisposition ActionDisposition
	Disposition      ActionDisposition
	ReasonCode       ReasonCode
}

ActionPromptTerminal is the durable evidence reconstructed for a managed prompt.

type ActionPromptTicket

type ActionPromptTicket struct {
	QueueEntryID string
	PromptID     string
}

ActionPromptTicket identifies one prepared, non-dispatchable managed prompt.

type ActionRawResult

type ActionRawResult struct {
	ToolResult      tools.ToolResult
	Structured      json.RawMessage
	Value           any
	Text            string
	WorkspaceID     string
	SessionID       string
	EventStartSeq   int64
	EventEndSeq     int64
	TokensUsed      int64
	ChildLoopRunID  RunID
	Status          string
	RenderedParams  json.RawMessage
	RenderedHarvest *dsl.HarvestSpec
	Control         *ActionControl
	ResolvedRuntime *ResolvedRuntime
}

ActionRawResult captures backend-specific action output before harvest policy.

type ActionRegistry

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

ActionRegistry resolves open action kinds through reserved executors or RuntimeRegistry.

func NewActionRegistry

func NewActionRegistry(runtime tools.Registry, opts ...ActionRegistryOption) (*ActionRegistry, error)

NewActionRegistry creates the runtime action adapter over the existing tools registry.

func (*ActionRegistry) Resolve

func (r *ActionRegistry) Resolve(ctx context.Context, scope tools.Scope, kind string) (ActionExecutor, error)

Resolve returns the executor for a scoped action kind. Reserved kinds win before falling through to the existing RuntimeRegistry.

func (*ActionRegistry) ResolvePinned

func (r *ActionRegistry) ResolvePinned(
	ctx context.Context,
	scope tools.Scope,
	kind string,
	expected *ToolSchemaSnapshot,
) (ActionExecutor, error)

ResolvePinned returns an executor only when an open tool still matches the Run-owned schema contract.

type ActionRegistryOption

type ActionRegistryOption func(*actionRegistryConfig)

ActionRegistryOption configures the loop action registry.

func WithActionChannelResultHarvester

func WithActionChannelResultHarvester(harvester ChannelResultHarvester) ActionRegistryOption

WithActionChannelResultHarvester wires channel_result harvest.

func WithActionChannelResultStore

func WithActionChannelResultStore(conversations ChannelResultConversationStore) ActionRegistryOption

WithActionChannelResultStore wires durable conversation storage for channel_result harvest.

func WithActionEventRangeReader

func WithActionEventRangeReader(reader ActionEventRangeReader) ActionRegistryOption

WithActionEventRangeReader wires async event-range harvest.

func WithActionGoalExecutor

func WithActionGoalExecutor(executor ActionExecutor) ActionRegistryOption

WithActionGoalExecutor wires the Goal convergence executor without importing the child package.

func WithActionLoopStarter

func WithActionLoopStarter(starter ActionLoopStarter) ActionRegistryOption

WithActionLoopStarter wires child loop starts for run-loop.

func WithActionRunAgentExecutor

func WithActionRunAgentExecutor(executor ActionExecutor) ActionRegistryOption

WithActionRunAgentExecutor overrides the reserved run-agent executor.

func WithActionRunLoopExecutor

func WithActionRunLoopExecutor(executor ActionExecutor) ActionRegistryOption

WithActionRunLoopExecutor overrides the reserved run-loop executor.

func WithActionSessionBinder

func WithActionSessionBinder(binder ActionSessionBinder) ActionRegistryOption

WithActionSessionBinder wires ACP session binding for run-agent.

func WithActionTransformExecutor

func WithActionTransformExecutor(executor ActionExecutor) ActionRegistryOption

WithActionTransformExecutor overrides the reserved transform executor.

type ActionRepairFailure

type ActionRepairFailure struct {
	NodeID      string             `json:"node_id"`
	ItemIndex   int                `json:"item_index"`
	Disposition AttemptDisposition `json:"disposition"`
	Failure     ClassifiedFailure  `json:"failure"`
}

ActionRepairFailure is one classified failure supplied to a repair generation.

type ActionRuntimeSelection

type ActionRuntimeSelection struct {
	Defaults    RuntimeDefaults
	ConfigRules []RuntimeRule
	RunRules    []RuntimeRule
	Catalog     RuntimeCatalog
	Recorder    ActionAppliedRuntimeRecorder
}

ActionRuntimeSelection carries the runtime inputs shared by runtime-aware action executors.

type ActionSessionBindRequest

type ActionSessionBindRequest struct {
	WorkspaceID                    WorkspaceID
	LoopRunID                      RunID
	Generation                     int
	NodeID                         dsl.NodeID
	ItemIndex                      int
	Agent                          string
	CWD                            string
	Handle                         string
	SharedKey                      string
	Mode                           string
	OriginSessionID                string
	TargetBindingEpoch             int64
	CellFence                      *ActionSessionCellFence
	ExpectedControlEpoch           int64
	ExpectedCheckpointPhase        string
	ExpectedTaskRunID              string
	ExpectedQueueEntryID           string
	ExpectedPromptID               string
	ExpectedCheckpointBindingEpoch int64
	ExpectedCheckpointSessionID    string
	ExpectedCheckpointHandle       string
	ReseedGrantID                  int64
	BindingAttemptID               string
	DesiredSessionID               string
	PinnedCreationProfileRef       string
	PinnedCreationDigest           string
	StaticPolicySpecDigest         string
	Isolated                       bool
	Runtime                        RuntimeSpec
	AllowedTools                   []string
	MaxTurns                       int
	ContractBlock                  string
	NetworkParticipation           *participation.Spec
}

ActionSessionBindRequest describes shared-default or isolated run-agent binding.

type ActionSessionBinder

type ActionSessionBinder interface {
	BindActionSession(ctx context.Context, req ActionSessionBindRequest) (ActionSessionBinding, error)
	PromptActionSession(
		ctx context.Context,
		binding ActionSessionBinding,
		req ActionPromptRequest,
	) (ActionPromptResult, error)
	CancelActionSession(ctx context.Context, binding ActionSessionBinding) error
}

ActionSessionBinder binds and prompts ACP sessions for run-agent.

type ActionSessionBinding

type ActionSessionBinding struct {
	WorkspaceID        WorkspaceID
	LoopRunID          RunID
	SessionID          string
	Handle             string
	SharedKey          string
	ControlEpoch       int64
	BindingEpoch       int64
	BindingAttemptID   string
	CreationProfileRef string
	PolicySpecDigest   string
	CreationDigest     string
	State              string
	Ownership          string
	Isolated           bool
	AppliedRuntime     RuntimeSpec
}

ActionSessionBinding is the durable session binding returned by the runtime.

type ActionSessionCellFence

type ActionSessionCellFence struct {
	Epoch     int64
	TaskRunID string
}

ActionSessionCellFence identifies the live ordinary-action cell allowed to activate a session binding.

type ActionSessionCreationError

type ActionSessionCreationError struct {
	EffectKnownFalse bool
	Code             string
	Err              error
}

ActionSessionCreationError carries provider-effect certainty without importing session internals.

func (*ActionSessionCreationError) Error

Error implements error.

func (*ActionSessionCreationError) Unwrap

func (e *ActionSessionCreationError) Unwrap() error

Unwrap preserves the provider/session creation cause.

type ActionSessionRetryRequest

type ActionSessionRetryRequest struct {
	BindRequest           ActionSessionBindRequest
	FailedBinding         ActionSessionBinding
	FailureCode           string
	ExpectedPromptAttempt int
	RetryWithFreshSession bool
}

ActionSessionRetryRequest asks the binder to persist one Goal-owned retry decision.

type ActionStopReason

type ActionStopReason string

ActionStopReason is the closed ACP terminal reason vocabulary persisted for managed prompts.

const (
	// ActionStopEndTurn reports a normal provider turn boundary.
	ActionStopEndTurn ActionStopReason = "end_turn"
	// ActionStopMaxTokens reports provider context exhaustion.
	ActionStopMaxTokens ActionStopReason = "max_tokens"
	// ActionStopMaxTurnRequests reports exhaustion of one provider request allowance.
	ActionStopMaxTurnRequests ActionStopReason = "max_turn_requests"
	// ActionStopRefusal reports an explicit provider refusal.
	ActionStopRefusal ActionStopReason = "refusal"
	// ActionStopCancelled reports a correlated cancellation.
	ActionStopCancelled ActionStopReason = "cancelled" //nolint:misspell // ACP persists the British spelling.
)

func (ActionStopReason) Valid

func (r ActionStopReason) Valid() bool

Valid reports whether the stop reason is part of the closed persisted vocabulary.

type ActionUsageReporter

type ActionUsageReporter interface {
	ReportActionTokensUsed(tokensUsed int64)
}

ActionUsageReporter receives cumulative token usage for one running action task.

type ActionUsageReporterFunc

type ActionUsageReporterFunc func(tokensUsed int64)

ActionUsageReporterFunc adapts a function into an ActionUsageReporter.

func (ActionUsageReporterFunc) ReportActionTokensUsed

func (f ActionUsageReporterFunc) ReportActionTokensUsed(tokensUsed int64)

ReportActionTokensUsed calls f with a cumulative token count.

type AdmissionClaim

type AdmissionClaim struct {
	WorkspaceID      WorkspaceID
	LoopName         string
	SourceKey        string
	EventKey         string
	LoopRunID        RunID
	ClaimedAt        time.Time
	ExpiresAt        time.Time
	SuppressedCount  int
	LastSuppressedAt *time.Time
}

AdmissionClaim is one workspace-scoped watch redelivery tombstone.

type AdmissionIdentity

type AdmissionIdentity struct {
	SourceKey string
	EventKey  string
	Horizon   time.Duration
}

AdmissionIdentity is the stable source-delivery key claimed with run creation.

func NormalizeAdmissionIdentity

func NormalizeAdmissionIdentity(identity AdmissionIdentity) (AdmissionIdentity, error)

NormalizeAdmissionIdentity canonicalizes the workspace-local suppression identity.

type AnnotationStore

type AnnotationStore interface {
	ListLoopUIAnnotations(ctx context.Context, ws WorkspaceID, loopName string) ([]UIAnnotation, error)
	ReplaceLoopUIAnnotations(ctx context.Context, ws WorkspaceID, loopName string, annotations []UIAnnotation) error
}

AnnotationStore persists workspace-scoped loop editor sidecars.

type AttemptDisposition

type AttemptDisposition string

AttemptDisposition is the closed durable outcome vocabulary for one node attempt.

const (
	AttemptSucceeded   AttemptDisposition = "succeeded"
	AttemptRetried     AttemptDisposition = "retried"
	AttemptRouted      AttemptDisposition = "routed"
	AttemptAbsorbed    AttemptDisposition = "absorbed"
	AttemptEscalated   AttemptDisposition = "escalated"
	AttemptQuarantined AttemptDisposition = "quarantined"
	AttemptCanceled    AttemptDisposition = "canceled"
	AttemptResumed     AttemptDisposition = "resumed"
)

func (AttemptDisposition) Valid

func (d AttemptDisposition) Valid() bool

Valid reports whether value belongs to the closed attempt-disposition vocabulary.

type BestGeneration

type BestGeneration struct {
	Generation int64
	Score      float64
	Nodes      map[string]map[int]BestNodeProjection
}

BestGeneration projects the run's ratchet baseline.

type BestNodeProjection

type BestNodeProjection struct {
	Output any
}

BestNodeProjection exposes only the best generation node output.

type CancelState

type CancelState string

CancelState is the durable graceful-cancellation state machine.

const (
	CancelStateNone       CancelState = ""
	CancelStateRequested  CancelState = "requested"
	CancelStateDelivering CancelState = "delivering"
	CancelStateDraining   CancelState = "draining"
	CancelStateCanceled   CancelState = "canceled"
)

func (CancelState) Valid

func (s CancelState) Valid() bool

Valid reports whether value belongs to the closed cancel-state vocabulary.

type CancellationMutation

type CancellationMutation struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	NodeID      NodeID
	Kind        RunCancelKind
	Reason      string
	Actor       task.ActorContext
	RequestedAt time.Time
	Effects     []RenderedEffectIntent
}

CancellationMutation is the durable first-writer command for a Run or node.

func (CancellationMutation) Validate

func (m CancellationMutation) Validate(nodeRequired bool) error

Validate rejects cancellation commands that cannot preserve ownership and provenance.

type CancellationReconciler

type CancellationReconciler interface {
	ReconcilePendingCancellations(context.Context, int, task.ActorContext) (int, error)
}

CancellationReconciler retries committed cooperative cancellation delivery.

type CancellationReconciliationStore

type CancellationReconciliationStore interface {
	CancellationStore
	ListPendingCancellations(context.Context, int) ([]PendingCancellation, error)
}

CancellationReconciliationStore lists durable cancellation deliveries that still need progress.

type CancellationResult

type CancellationResult struct {
	Run                 Run
	Coordinator         *task.Run
	SessionIDs          []string
	RevokedPromptLeases []GoalPromptLease
	Terminal            bool
	Applied             bool
}

CancellationResult returns committed truth plus exact post-commit process identities.

type CancellationSessionController

type CancellationSessionController interface {
	CancelLoopSession(context.Context, string, string) error
	KillLoopSession(context.Context, string, string) error
}

CancellationSessionController performs post-commit prompt cancellation or immediate process stop.

type CancellationSessionControllerFuncs

type CancellationSessionControllerFuncs struct {
	Cancel func(context.Context, string, string) error
	Kill   func(context.Context, string, string) error
}

CancellationSessionControllerFuncs adapts cancellation callbacks.

func (CancellationSessionControllerFuncs) CancelLoopSession

func (f CancellationSessionControllerFuncs) CancelLoopSession(ctx context.Context, id, reason string) error

CancelLoopSession implements CancellationSessionController.

func (CancellationSessionControllerFuncs) KillLoopSession

func (f CancellationSessionControllerFuncs) KillLoopSession(ctx context.Context, id, reason string) error

KillLoopSession implements CancellationSessionController.

type CancellationStore

type CancellationStore interface {
	RequestRunCancellation(context.Context, CancellationMutation) (CancellationResult, error)
	AdvanceRunCancellation(context.Context, CancellationMutation, CancelState) (CancellationResult, error)
	RequestNodeCancellation(context.Context, CancellationMutation) (CancellationResult, error)
	AdvanceNodeCancellation(context.Context, CancellationMutation, CancelState) (CancellationResult, error)
}

CancellationStore owns atomic cancellation state, fencing, Goal cleanup, and terminal truth.

type CatalogFacets

type CatalogFacets struct {
	Kinds      map[CatalogKind]int
	Categories map[string]int
	Statuses   map[Status]int
}

type CatalogItem

type CatalogItem struct {
	Record  resources.Record[ResourceSpec]
	Summary CatalogRunSummary
}

type CatalogKind

type CatalogKind string

type CatalogPage

type CatalogPage struct {
	Items      []CatalogItem
	Facets     CatalogFacets
	NextCursor string
	HasMore    bool
	Total      int
	Limit      int
}

func BuildCatalogPage

func BuildCatalogPage(
	records []resources.Record[ResourceSpec],
	summaries map[string]CatalogRunSummary,
	query CatalogQuery,
) (CatalogPage, error)

type CatalogQuery

type CatalogQuery struct {
	WorkspaceID string
	Search      string
	Kind        CatalogKind
	Category    string
	Status      Status
	Sort        string
	Cursor      string
	Limit       int
}

func NormalizeCatalogQuery

func NormalizeCatalogQuery(query CatalogQuery) (CatalogQuery, error)

type CatalogResourceSpec

type CatalogResourceSpec struct {
	UseWhen  string   `json:"use_when,omitempty"`
	Keywords []string `json:"keywords,omitempty"`
	Category string   `json:"category,omitempty"`
}

CatalogResourceSpec is the matchable catalog metadata projected from a loop definition.

type CatalogRunAggregate

type CatalogRunAggregate struct {
	Runs      int
	Succeeded int
	Failed    int
}

type CatalogRunHead

type CatalogRunHead struct {
	ID             RunID
	LoopName       string
	Status         Status
	BestGeneration *int64
	BestScore      *float64
	CreatedAt      time.Time
}

type CatalogRunQuery

type CatalogRunQuery struct {
	WorkspaceID    WorkspaceID
	LoopNames      []string
	AggregateAfter time.Time
}

type CatalogRunReader

type CatalogRunReader interface {
	ListLoopCatalogRunSummaries(
		ctx context.Context,
		query CatalogRunQuery,
	) (map[string]CatalogRunSummary, error)
}

type CatalogRunSummary

type CatalogRunSummary struct {
	LoopName     string
	LastRun      *CatalogRunHead
	Aggregate30d CatalogRunAggregate
}

type ChannelResultConversationStore

type ChannelResultConversationStore interface {
	ListConversationMessages(
		ctx context.Context,
		ref storepkg.NetworkConversationRef,
		query storepkg.NetworkConversationMessageQuery,
	) ([]storepkg.NetworkConversationMessage, error)
}

ChannelResultConversationStore is the durable network conversation read seam used by channel_result harvest.

type ChannelResultHarvestRequest

type ChannelResultHarvestRequest struct {
	Window      string
	Responder   string
	ContentRule string
	Raw         ActionRawResult
	Node        dsl.Node
}

ChannelResultHarvestRequest asks for the designated result message after a network send.

type ChannelResultHarvestResult

type ChannelResultHarvestResult struct {
	Found      bool
	MessageID  string
	Structured json.RawMessage
	Text       string
}

ChannelResultHarvestResult is the designated result coordination message.

type ChannelResultHarvester

type ChannelResultHarvester interface {
	HarvestChannelResult(ctx context.Context, req *ChannelResultHarvestRequest) (ChannelResultHarvestResult, error)
}

ChannelResultHarvester harvests the ADR-021 channel_result semantics.

type ClassifiedFailure

type ClassifiedFailure struct {
	Class         FailureClass   `json:"class"`
	Code          string         `json:"code"`
	Cause         string         `json:"cause"`
	Hint          string         `json:"hint,omitempty"`
	Target        string         `json:"target,omitempty"`
	RetryAfter    *time.Duration `json:"retry_after,omitempty"`
	RetryEligible bool           `json:"retry_eligible"`
}

ClassifiedFailure is the canonical operator-safe failure projection.

func ClassifyNodeFailure

func ClassifyNodeFailure(ev FailureEvidence) ClassifiedFailure

ClassifyNodeFailure classifies immutable evidence without IO or shared state.

type Compiler

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

Compiler compiles authoring definitions into runtime-ready resolved form.

func NewCompiler

func NewCompiler(opts ...CompilerOption) *Compiler

NewCompiler creates a resolved-form compiler.

func (*Compiler) Compile

func (c *Compiler) Compile(def dsl.Definition) (*ResolvedDefinition, error)

Compile lints, parses templates/CEL, snapshots tool schemas, and folds defaults.

type CompilerOption

type CompilerOption func(*Compiler)

CompilerOption configures a compiler.

func WithCompilerToolSchemaSource

func WithCompilerToolSchemaSource(source ToolSchemaSource) CompilerOption

WithCompilerToolSchemaSource injects the pure schema source used during compile.

type ConfigSnapshot

type ConfigSnapshot struct {
	Stored    *LoopConfig
	Effective EffectiveConfig
}

ConfigSnapshot keeps the stored override and daemon-resolved runtime config from one read.

type ControlProvenance

type ControlProvenance struct {
	ActorKind   string
	ActorID     string
	Reason      string
	RuleID      string
	RequestedAt time.Time
}

ControlProvenance attributes one durable node-control mutation.

type CoordinatorControlStore

type CoordinatorControlStore interface {
	ReactivateLoopCoordinator(
		context.Context,
		*CoordinatorReactivationRequest,
	) (CoordinatorReactivationResult, error)
}

CoordinatorControlStore owns atomic non-Goal control reactivation.

type CoordinatorReactivationRequest

type CoordinatorReactivationRequest struct {
	Run           Run
	Cause         TransitionCause
	Actor         task.ActorContext
	Decisions     []GateDecisionRecord
	ReactivatedAt time.Time
}

CoordinatorReactivationRequest atomically returns a parked non-Goal Run to execution.

type CoordinatorReactivationResult

type CoordinatorReactivationResult struct {
	Run task.Run
}

CoordinatorReactivationResult identifies the durable coordinator wake reserved by reactivation.

type CoordinatorRunActivator

type CoordinatorRunActivator interface {
	ActivateCoordinatorRun(context.Context, task.Run)
}

CoordinatorRunActivator starts a committed coordinator wake.

type CoordinatorRunActivatorFunc

type CoordinatorRunActivatorFunc func(context.Context, task.Run)

CoordinatorRunActivatorFunc adapts a function to CoordinatorRunActivator.

func (CoordinatorRunActivatorFunc) ActivateCoordinatorRun

func (f CoordinatorRunActivatorFunc) ActivateCoordinatorRun(ctx context.Context, run task.Run)

ActivateCoordinatorRun implements CoordinatorRunActivator.

type CoordinatorRunner

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

CoordinatorRunner computes loop generation plans without mutating task storage.

func NewCoordinatorRunner

func NewCoordinatorRunner(
	taskRuns CoordinatorTaskRunReader,
	loopStore Store,
	outputs GenerationOutputReader,
	logger *slog.Logger,
	opts ...CoordinatorRunnerOption,
) (*CoordinatorRunner, error)

NewCoordinatorRunner constructs the in-daemon loop generation coordinator.

func (*CoordinatorRunner) ActionRunDeathStreakLimit

func (r *CoordinatorRunner) ActionRunDeathStreakLimit(ctx context.Context, taskRun task.Run) (int, error)

ActionRunDeathStreakLimit returns the pinned confirmed-death continuation cap for one action cell.

func (*CoordinatorRunner) ActionRunSilenceWindow

func (r *CoordinatorRunner) ActionRunSilenceWindow(ctx context.Context, taskRun task.Run) (time.Duration, error)

ActionRunSilenceWindow returns the pinned silence-attention policy for one action cell.

func (*CoordinatorRunner) ActionRunTimeout

func (r *CoordinatorRunner) ActionRunTimeout(
	ctx context.Context,
	taskRun task.Run,
) (time.Duration, bool, error)

ActionRunTimeout returns the parsed node timeout for one queued loop action run.

func (*CoordinatorRunner) ActionRunTimeoutReason

func (r *CoordinatorRunner) ActionRunTimeoutReason(
	ctx context.Context,
	taskRun task.Run,
) (string, error)

ActionRunTimeoutReason returns the failure code selected by the same deterministic timeout/deadline calculation as ActionRunTimeout.

func (*CoordinatorRunner) ExecuteActionRun

func (r *CoordinatorRunner) ExecuteActionRun(
	ctx context.Context,
	taskRun task.Run,
	actor task.ActorContext,
) (task.RunResult, error)

ExecuteActionRun executes one queued loop action node run through the configured action registry.

func (*CoordinatorRunner) Run

Run returns the coordinator plan for a claimed coordinator task_run.

type CoordinatorRunnerOption

type CoordinatorRunnerOption func(*CoordinatorRunner)

CoordinatorRunnerOption configures the loop coordinator runner.

func WithCoordinatorActionRegistry

func WithCoordinatorActionRegistry(registry *ActionRegistry) CoordinatorRunnerOption

WithCoordinatorActionRegistry injects runtime action execution for worker node runs.

func WithCoordinatorGateEvaluator

func WithCoordinatorGateEvaluator(evaluator gate.GateEvaluator) CoordinatorRunnerOption

WithCoordinatorGateEvaluator injects runtime evaluation for gate control nodes.

func WithCoordinatorHookDispatcher

func WithCoordinatorHookDispatcher(hooks HookDispatcher) CoordinatorRunnerOption

WithCoordinatorHookDispatcher injects loop hook dispatch for coordinator call sites.

func WithCoordinatorNodeAttemptReader

func WithCoordinatorNodeAttemptReader(reader NodeAttemptReader) CoordinatorRunnerOption

WithCoordinatorNodeAttemptReader injects the durable attempt-ledger reader.

func WithCoordinatorNodeControlReader

func WithCoordinatorNodeControlReader(reader NodeControlReader) CoordinatorRunnerOption

WithCoordinatorNodeControlReader injects cross-generation node control reads.

func WithCoordinatorRetryRand

func WithCoordinatorRetryRand(randFloat64 func() float64) CoordinatorRunnerOption

WithCoordinatorRetryRand injects the retry jitter source.

func WithCoordinatorRuntimeCatalog

func WithCoordinatorRuntimeCatalog(catalog WorkspaceRuntimeCatalog) CoordinatorRunnerOption

WithCoordinatorRuntimeCatalog injects pre-bind provider/model validation.

func WithCoordinatorTargetHealth

func WithCoordinatorTargetHealth(health TargetHealth) CoordinatorRunnerOption

WithCoordinatorTargetHealth injects daemon-global loop-target admission and accounting.

func WithCoordinatorVerdictReader

func WithCoordinatorVerdictReader(reader gate.VerdictReader) CoordinatorRunnerOption

WithCoordinatorVerdictReader injects persisted machine-verdict history.

func WithCoordinatorWatchEventsLedger

func WithCoordinatorWatchEventsLedger(ledger WatchEventsLedger) CoordinatorRunnerOption

WithCoordinatorWatchEventsLedger injects the watch-events replay reader.

func WithCoordinatorWatchPoller

func WithCoordinatorWatchPoller(poller WatchPoller) CoordinatorRunnerOption

WithCoordinatorWatchPoller injects the watch-source poll bridge used by source/watch-source nodes.

func WithCoordinatorWatchSilenceWindow

func WithCoordinatorWatchSilenceWindow(window time.Duration) CoordinatorRunnerOption

WithCoordinatorWatchSilenceWindow overrides the watch-source inactivity window.

type CoordinatorTaskRunReader

type CoordinatorTaskRunReader interface {
	GetTaskRun(ctx context.Context, id string) (task.Run, error)
}

CoordinatorTaskRunReader is the task-run read seam required by the loop coordinator.

type DeadNodeResumeRequest

type DeadNodeResumeRequest struct {
	WorkspaceID      WorkspaceID
	RunID            RunID
	Generation       int
	NodeID           NodeID
	ItemIndex        int
	TaskRunID        string
	SourceSessionID  string
	Checkpoint       *DeathResumeCheckpoint
	ExpectedEpoch    int64
	DeathStreakLimit int
	Cause            string
	Actor            task.ActorContext
	ConfirmedAt      time.Time
}

DeadNodeResumeRequest is the complete CAS identity for one confirmed-dead worker.

func DeadNodeResumeRequestForTaskRun

func DeadNodeResumeRequestForTaskRun(
	run task.Run,
	workspaceID WorkspaceID,
	sourceSessionID string,
	checkpoint *DeathResumeCheckpoint,
	deathStreakLimit int,
	cause string,
	actor task.ActorContext,
	confirmedAt time.Time,
) (DeadNodeResumeRequest, error)

DeadNodeResumeRequestForTaskRun derives the exact cell identity pinned into one worker run.

func (DeadNodeResumeRequest) Validate

func (r DeadNodeResumeRequest) Validate() error

Validate rejects ambiguous or unscoped death observations.

type DeadNodeResumeResult

type DeadNodeResumeResult struct {
	Run               task.Run
	Continued         bool
	Replay            bool
	AttentionRequired bool
	IssuedEpoch       int64
}

DeadNodeResumeResult reports whether one deterministic continuation was committed.

type DeadNodeResumer

type DeadNodeResumer interface {
	ResumeDeadNode(context.Context, DeadNodeResumeRequest) (DeadNodeResumeResult, error)
}

DeadNodeResumer is the single atomic authority for confirmed-death continuation.

type DeathResumeCheckpoint

type DeathResumeCheckpoint struct {
	SessionID     string               `json:"session_id"`
	EventStartSeq int64                `json:"event_start_seq"`
	EventEndSeq   int64                `json:"event_end_seq"`
	Partials      []DeathResumePartial `json:"partials,omitempty"`
}

DeathResumeCheckpoint pins the last persisted session-event window carried into a continuation.

func (*DeathResumeCheckpoint) Clone

Clone returns an ownership-safe checkpoint copy.

func (DeathResumeCheckpoint) Validate

func (c DeathResumeCheckpoint) Validate(sourceSessionID string) error

Validate rejects a checkpoint that does not describe the confirmed-dead source session.

type DeathResumeContext

type DeathResumeContext struct {
	SourceTaskRunID string
	SourceSessionID string
	Checkpoint      *DeathResumeCheckpoint
}

DeathResumeContext identifies the continuation provenance exposed to an action executor.

type DeathResumePartial

type DeathResumePartial struct {
	Sequence int64  `json:"sequence"`
	Type     string `json:"type"`
	Text     string `json:"text"`
}

DeathResumePartial is one bounded, operator-safe progress fragment from the dead session.

type DefaultsResolver

type DefaultsResolver func(context.Context, WorkspaceID) (LoopDefaults, error)

DefaultsResolver resolves the `[loops.defaults.*]` layer for one workspace.

type DefinitionLinter

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

DefinitionLinter is the shared structural and reference linter.

func NewLinter

func NewLinter(opts ...LinterOption) *DefinitionLinter

NewLinter creates the shared loop linter.

func (*DefinitionLinter) Lint

func (l *DefinitionLinter) Lint(def dsl.Definition) []LintError

Lint validates one loop definition.

type DefinitionResolver

type DefinitionResolver interface {
	ResolveLoop(ctx context.Context, ws WorkspaceID, name string) (*ResolvedDefinition, error)
}

DefinitionResolver resolves a loop name to a compiled definition.

type DefinitionResolverFunc

type DefinitionResolverFunc func(context.Context, WorkspaceID, string) (*ResolvedDefinition, error)

DefinitionResolverFunc adapts a function to DefinitionResolver.

func (DefinitionResolverFunc) ResolveLoop

func (f DefinitionResolverFunc) ResolveLoop(
	ctx context.Context,
	ws WorkspaceID,
	name string,
) (*ResolvedDefinition, error)

ResolveLoop implements DefinitionResolver.

type DefinitionSnapshot

type DefinitionSnapshot struct {
	WorkspaceID WorkspaceID
	Digest      string
	Version     int
	Definition  json.RawMessage
	ByteSize    int
	CreatedAt   time.Time
	LastUsedAt  time.Time
}

DefinitionSnapshot is the content-addressed executed definition pinned by one or more runs.

type DefinitionState

type DefinitionState struct {
	Config      *LoopConfig
	Annotations []UIAnnotation
}

DefinitionState contains mutable sidecars owned by one file-backed Loop definition.

type DefinitionStateStore

type DefinitionStateStore interface {
	DeleteLoopDefinitionState(ctx context.Context, ws WorkspaceID, loopName string) (DefinitionState, error)
	RestoreLoopDefinitionState(
		ctx context.Context,
		ws WorkspaceID,
		loopName string,
		state DefinitionState,
	) error
}

DefinitionStateStore owns atomic removal and restoration of definition sidecars.

type DisplayCost

type DisplayCost struct {
	Tokens           int64   `json:"tokens"`
	PricePerTokenUSD float64 `json:"price_per_token_usd"`
	USD              float64 `json:"usd"`
}

DisplayCost is derived UI-only cost information.

func DeriveDisplayCost

func DeriveDisplayCost(tokens int64, pricePerTokenUSD float64) DisplayCost

DeriveDisplayCost derives a display-only cost value from token count and price.

type EffectAcknowledgement

type EffectAcknowledgement struct {
	Entry       EffectOutboxEntry
	Outcome     EffectResultOutcome
	Code        string
	Cause       string
	Duration    time.Duration
	CustomEvent json.RawMessage
	At          time.Time
}

EffectAcknowledgement atomically records result events and closes one pending row.

func (EffectAcknowledgement) Validate

func (a EffectAcknowledgement) Validate() error

Validate rejects acknowledgements that cannot preserve delivery identity.

type EffectContextRequest

type EffectContextRequest struct {
	Run           *Run
	Trigger       EffectTrigger
	Generation    int
	NodeID        NodeID
	ItemIndex     int
	Attempt       int
	NextAttemptAt *time.Time
	Disposition   AttemptDisposition
	Failure       *ClassifiedFailure
	Quarantine    json.RawMessage
}

EffectContextRequest contains immutable facts bound before an effect template is resolved.

type EffectDispatcher

type EffectDispatcher interface {
	DrainPendingLoopEffects(context.Context, EffectDrainPage) (EffectDrainReport, error)
}

EffectDispatcher drains committed effect deliveries without observing event-table tails.

type EffectDrainPage

type EffectDrainPage struct {
	Limit int
}

EffectDrainPage controls one relay sweep.

type EffectDrainReport

type EffectDrainReport struct {
	Read      int
	Delivered int
	Failed    int
}

EffectDrainReport summarizes one relay sweep.

type EffectOutboxEntry

type EffectOutboxEntry struct {
	LoopRunID     RunID
	WorkspaceID   WorkspaceID
	DeliveryID    string
	SourceEventID string
	Trigger       string
	Generation    int
	NodeID        NodeID
	ItemIndex     int
	EntryIndex    int
	Entry         json.RawMessage
	State         EffectOutboxState
	Attempts      int
	CreatedAt     time.Time
	DeliveredAt   *time.Time
}

EffectOutboxEntry is one immutable rendered effect delivery.

type EffectOutboxState

type EffectOutboxState string

EffectOutboxState is the closed delivery state vocabulary.

const (
	EffectPending   EffectOutboxState = "pending"
	EffectDelivered EffectOutboxState = "delivered"
	EffectFailed    EffectOutboxState = "failed"
)

func (EffectOutboxState) Valid

func (s EffectOutboxState) Valid() bool

Valid reports whether value belongs to the closed outbox-state vocabulary.

type EffectResultOutcome

type EffectResultOutcome string

EffectResultOutcome is the stable per-entry result vocabulary.

const (
	EffectResultOK               EffectResultOutcome = "ok"
	EffectResultFailed           EffectResultOutcome = "failed"
	EffectResultApprovalRequired EffectResultOutcome = "approval_required"
	EffectResultToolMissing      EffectResultOutcome = "tool_missing"
)

func (EffectResultOutcome) Valid

func (o EffectResultOutcome) Valid() bool

Valid reports whether the outcome belongs to the stable result vocabulary.

type EffectTrigger

type EffectTrigger string

EffectTrigger is the closed authored reaction vocabulary.

const (
	EffectTriggerOnError        EffectTrigger = "on_error"
	EffectTriggerOnRetry        EffectTrigger = "on_retry"
	EffectTriggerOnSuccess      EffectTrigger = "on_success"
	EffectTriggerOnPause        EffectTrigger = "on_pause"
	EffectTriggerOnTimeout      EffectTrigger = "on_timeout"
	EffectTriggerOnCancel       EffectTrigger = "on_cancel"
	EffectTriggerOnQuarantine   EffectTrigger = "on_quarantine"
	EffectTriggerWaitEscalation EffectTrigger = "wait_escalation"
	EffectTriggerOnDone         EffectTrigger = "on_done"
	EffectTriggerOnNoOp         EffectTrigger = "on_noop"
	EffectTriggerOnBlocked      EffectTrigger = "on_blocked"
	EffectTriggerOnFailed       EffectTrigger = "on_failed"
	EffectTriggerOnExhausted    EffectTrigger = "on_exhausted"
	EffectTriggerOnStalled      EffectTrigger = "on_stalled"
	EffectTriggerOnCanceled     EffectTrigger = "on_canceled"
)

func (EffectTrigger) NodeScoped

func (t EffectTrigger) NodeScoped() bool

NodeScoped reports whether the trigger belongs to one node lifecycle.

func (EffectTrigger) Valid

func (t EffectTrigger) Valid() bool

Valid reports whether the trigger belongs to the authored reaction vocabulary.

type EffectiveConfig

type EffectiveConfig struct {
	HumanGateEnabled  bool               `json:"human_gate_enabled"`
	ReattemptStrategy ReattemptStrategy  `json:"reattempt_strategy"`
	EnabledChecks     json.RawMessage    `json:"enabled_checks_json"`
	IterationCap      int                `json:"iteration_cap"`
	BudgetTokens      int                `json:"budget_tokens"`
	BudgetWallSec     int                `json:"budget_wall_sec"`
	BudgetOnExceeded  dsl.BudgetExceeded `json:"budget_on_exceeded"`
	NoProgressWindow  int                `json:"no_progress_window"`
	FanOutWidth       int                `json:"fan_out_width"`
	GateMaxRevisions  int                `json:"gate_max_revisions"`
	RuntimeDefaults   RuntimeDefaults    `json:"runtime_defaults"`
	RuntimeRules      []RuntimeRule      `json:"runtime_rules"`
	RunRuntimeRules   []RuntimeRule      `json:"run_runtime_rules"`
	Lifecycle         LifecycleConfig    `json:"lifecycle"`
}

EffectiveConfig is the fully resolved non-null runtime config.

func ResolveEffectiveConfig

func ResolveEffectiveConfig(
	resolved *ResolvedDefinition,
	defaults LoopDefaults,
	stored *LoopConfig,
	perRun LoopConfig,
) (EffectiveConfig, error)

ResolveEffectiveConfig merges definition, defaults, loop_config, and per-run layers.

type FailureClass

type FailureClass string

FailureClass is the closed node-failure vocabulary.

const (
	FailureTransport         FailureClass = "transport"
	FailurePayloadDeclared   FailureClass = "payload_declared"
	FailureQualityRejection  FailureClass = "quality_rejection"
	FailureAuthoring         FailureClass = "authoring"
	FailureCancellation      FailureClass = "cancellation"
	FailureAttemptTimeout    FailureClass = "attempt_timeout"
	FailureBudgetExhausted   FailureClass = "budget_exhausted"
	FailureTargetUnavailable FailureClass = "target_unavailable"
)

func (FailureClass) RetryEligible

func (c FailureClass) RetryEligible() bool

RetryEligible reports whether the class may use automatic node retry.

type FailureEvidence

type FailureEvidence struct {
	CancelRequested   bool
	PayloadFailure    *ActionFailure
	QualityRejected   bool
	Authoring         bool
	AttemptTimedOut   bool
	BudgetExhausted   bool
	TargetUnavailable bool
	Transport         bool
	LeaseExpired      bool
	ToolError         *tools.ToolError
	Code              string
	Cause             string
	Hint              string
	Target            string
	RetryAfter        *time.Duration
	BackoffMax        time.Duration
}

FailureEvidence contains immutable facts observed at the coordinator boundary. Text fields must already have crossed NewActionFailure's sanitization boundary.

type GateDecision

type GateDecision string

GateDecision is the closed approval decision vocabulary consumed by Approve.

const (
	// GateDecisionApprove resumes the run.
	GateDecisionApprove GateDecision = "approve"
	// GateDecisionRequestChanges resumes the run after a requested revision.
	GateDecisionRequestChanges GateDecision = "request_changes"
	// GateDecisionReject terminates the run as blocked.
	GateDecisionReject GateDecision = "reject"
)

type GateDecisionReader

type GateDecisionReader interface {
	ListLoopGateDecisions(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		generation int,
		gateID NodeID,
	) (map[string]gate.HumanDecision, error)
}

GateDecisionReader reads persisted human decisions for coordinator gate re-evaluation.

type GateDecisionRecord

type GateDecisionRecord struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	Generation  int
	GateID      NodeID
	CriterionID string
	Decision    GateDecision
	Actor       task.ActorContext
	Note        string
	DecidedAt   time.Time
}

GateDecisionRecord persists one human approval decision for a gate criterion.

type GateInstanceProjection

type GateInstanceProjection struct {
	GateID    string
	ItemIndex int
}

GateInstanceProjection identifies one materialized gate in a fan-out-aware history.

type GenerationHistory

type GenerationHistory struct {
	Previous *PreviousGeneration
	Best     *BestGeneration
}

GenerationHistory is the read-only generation-boundary context for a namespace.

func ProjectGenerationHistory

func ProjectGenerationHistory(
	generation int,
	run Run,
	previousOutputs []GenerationOutput,
	previousVerdicts []gate.VerdictRecord,
	routeCauses []gate.VerdictRecord,
	bestOutputs []GenerationOutput,
) (GenerationHistory, error)

ProjectGenerationHistory creates a generation history from reader records without IO.

func ReadGenerationHistory

func ReadGenerationHistory(
	ctx context.Context,
	reader GenerationHistoryReader,
	run Run,
	generation int,
) (GenerationHistory, error)

ReadGenerationHistory loads the previous and best generation projections for one namespace.

type GenerationHistoryReader

type GenerationHistoryReader interface {
	GenerationOutputReader
	gate.VerdictReader
}

GenerationHistoryReader provides all durable records needed for history projection.

type GenerationIntent

type GenerationIntent struct {
	Generation       int64            `json:"generation"`
	ParentGeneration int64            `json:"parent_generation"`
	Origin           GenerationOrigin `json:"origin"`
}

GenerationIntent records immutable provenance for a newly created generation.

func (GenerationIntent) Validate

func (i GenerationIntent) Validate() error

Validate rejects generation provenance that cannot satisfy the persistent invariant.

type GenerationLifecycleEventIntent

type GenerationLifecycleEventIntent struct {
	Kind            GenerationLifecycleEventKind `json:"kind"`
	GateID          string                       `json:"gate_id,omitempty"`
	ItemIndex       int                          `json:"item_index,omitempty"`
	Route           gate.RouteAction             `json:"route,omitempty"`
	Reason          string                       `json:"reason,omitempty"`
	BestGeneration  *int64                       `json:"best_generation,omitempty"`
	NodeID          string                       `json:"node_id,omitempty"`
	Attempt         int                          `json:"attempt,omitempty"`
	IssuedEpoch     int64                        `json:"issued_epoch,omitempty"`
	NextAttemptAt   *time.Time                   `json:"next_attempt_at,omitempty"`
	FailureClass    FailureClass                 `json:"failure_class,omitempty"`
	Failure         *ClassifiedFailure           `json:"failure,omitempty"`
	Disposition     AttemptDisposition           `json:"disposition,omitempty"`
	QuarantineEntry json.RawMessage              `json:"quarantine_entry,omitempty"`
	AttentionFlag   string                       `json:"attention_flag,omitempty"`
	// AttentionProducerNodeID names the parked producer behind a dependency attention flag.
	AttentionProducerNodeID string                 `json:"attention_producer_node_id,omitempty"`
	TargetFamily            string                 `json:"target_family,omitempty"`
	Target                  string                 `json:"target,omitempty"`
	BreakerState            string                 `json:"breaker_state,omitempty"`
	ActorKind               string                 `json:"actor_kind,omitempty"`
	ActorID                 string                 `json:"actor_id,omitempty"`
	RuleID                  string                 `json:"rule_id,omitempty"`
	WaitKind                string                 `json:"wait_kind,omitempty"`
	AheadArrival            string                 `json:"ahead_arrival,omitempty"`
	AheadCursors            map[string]int64       `json:"ahead_cursors,omitempty"`
	Effects                 []RenderedEffectIntent `json:"effects,omitempty"`
}

GenerationLifecycleEventIntent requests one durable generation lifecycle event.

type GenerationLifecycleEventKind

type GenerationLifecycleEventKind string

GenerationLifecycleEventKind identifies a durable event emitted while a generation snapshot is finalized.

const (
	// GenerationLifecycleEventGenerationStarted records the start of a generation.
	GenerationLifecycleEventGenerationStarted GenerationLifecycleEventKind = "generation_started"
	// GenerationLifecycleEventGateVerdict records a sanitized gate verdict.
	GenerationLifecycleEventGateVerdict GenerationLifecycleEventKind = "gate_verdict"
	// GenerationLifecycleEventNodeRetryScheduled records one durable retry schedule.
	GenerationLifecycleEventNodeRetryScheduled GenerationLifecycleEventKind = "node_retry_scheduled"
	// GenerationLifecycleEventNodeSucceeded records an effect-bearing successful node outcome.
	GenerationLifecycleEventNodeSucceeded GenerationLifecycleEventKind = "node_succeeded"
	// GenerationLifecycleEventNodeFailed records an effect-bearing handled or terminal node failure.
	GenerationLifecycleEventNodeFailed GenerationLifecycleEventKind = "node_failed"
	// GenerationLifecycleEventNodeCanceled records one cooperatively drained node attempt.
	GenerationLifecycleEventNodeCanceled GenerationLifecycleEventKind = "node_canceled"
	// GenerationLifecycleEventNodeQuarantined records one durable quarantine episode.
	GenerationLifecycleEventNodeQuarantined GenerationLifecycleEventKind = "node_quarantined"
	// GenerationLifecycleEventNodeAttentionFlagged records one dependency-parked attention flag.
	GenerationLifecycleEventNodeAttentionFlagged GenerationLifecycleEventKind = "node_attention_flagged"
	// GenerationLifecycleEventNodePaused records one automatic pause episode.
	GenerationLifecycleEventNodePaused GenerationLifecycleEventKind = "node_paused"
	// GenerationLifecycleEventNodeWaitStarted records one durable wait entry.
	GenerationLifecycleEventNodeWaitStarted GenerationLifecycleEventKind = "node_wait_started"
	// GenerationLifecycleEventNodeWaitResumed records an ahead-arrival wait resolution.
	GenerationLifecycleEventNodeWaitResumed GenerationLifecycleEventKind = "node_wait_resumed"
	// GenerationLifecycleEventTargetBreakerTransition records a loop-target breaker state change.
	GenerationLifecycleEventTargetBreakerTransition GenerationLifecycleEventKind = "target_breaker_transition"
)

type GenerationLineageReader

type GenerationLineageReader interface {
	ListGenerations(ctx context.Context, workspaceID string, runID string) ([]LoopGeneration, error)
}

GenerationLineageReader provides workspace-scoped immutable generation history.

type GenerationOrigin

type GenerationOrigin string

GenerationOrigin identifies why a loop generation was created.

const (
	OriginInitial            GenerationOrigin = "initial"
	OriginStopWhen           GenerationOrigin = "stop_when"
	OriginReattempt          GenerationOrigin = "reattempt"
	OriginGateRevise         GenerationOrigin = "gate_revise"
	OriginGateNextGeneration GenerationOrigin = "gate_next_generation"
	OriginDoDRetry           GenerationOrigin = "dod_retry"
	OriginRatchetRestore     GenerationOrigin = "ratchet_restore"
	OriginRequeue            GenerationOrigin = "requeue"
)

type GenerationOutput

type GenerationOutput struct {
	Generation       int              `json:"generation,omitempty"`
	NodeID           string           `json:"node_id"`
	ItemIndex        int              `json:"item_index,omitempty"`
	Status           string           `json:"status"`
	OutputRef        string           `json:"output_ref,omitempty"`
	TaskRunID        string           `json:"task_run_id,omitempty"`
	ChildLoopRunID   string           `json:"child_loop_run_id,omitempty"`
	ResolvedRuntime  *ResolvedRuntime `json:"resolved_runtime,omitempty"`
	Attempt          int              `json:"attempt,omitempty"`
	NextAttemptAt    *time.Time       `json:"next_attempt_at,omitempty"`
	FirstScheduledAt *time.Time       `json:"first_scheduled_at,omitempty"`
	Epoch            int64            `json:"epoch,omitempty"`
	// SessionID is the ACP session bound to the cell's task run; it is a
	// read-model join and never part of snapshot state.
	SessionID string `json:"-"`
	// ExpectedEpoch is the cell epoch observed by the planner. It is used only
	// for compare-and-swap and is never stored as domain state.
	ExpectedEpoch *int64 `json:"expected_epoch,omitempty"`
	// contains filtered or unexported fields
}

GenerationOutput is one loop_generation_outputs row mutation.

type GenerationOutputBlob

type GenerationOutputBlob struct {
	OutputRef string          `json:"output_ref"`
	Payload   json.RawMessage `json:"payload_json"`
	At        time.Time       `json:"at"`
}

GenerationOutputBlob is one content-addressed loop output payload required by a generation snapshot.

type GenerationOutputLister

type GenerationOutputLister interface {
	ListGenerationOutputs(
		ctx context.Context,
		workspaceID WorkspaceID,
		runID RunID,
		generation int,
	) ([]GenerationOutput, error)
}

GenerationOutputLister reads loop-owned generation output snapshots.

type GenerationOutputPayloadKey

type GenerationOutputPayloadKey struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	Generation  int
	NodeID      NodeID
	ItemIndex   int
	OutputRef   string
}

GenerationOutputPayloadKey identifies the exact cell that owns an externalized payload.

type GenerationOutputPayloadReader

type GenerationOutputPayloadReader interface {
	GetGenerationOutputPayload(
		ctx context.Context,
		key GenerationOutputPayloadKey,
	) (json.RawMessage, error)
}

GenerationOutputPayloadReader resolves externalized payloads through their owning cell.

type GenerationOutputReader

type GenerationOutputReader interface {
	GenerationOutputLister
	GenerationOutputPayloadReader
}

GenerationOutputReader lists snapshots and hydrates externalized output payloads for the coordinator.

type GenerationSnapshotPayload

type GenerationSnapshotPayload struct {
	Outputs              []GenerationOutput                `json:"outputs,omitempty"`
	Attempts             []NodeAttempt                     `json:"attempts,omitempty"`
	Controls             []NodeControlMutation             `json:"controls,omitempty"`
	Waits                []NodeWaitIntent                  `json:"waits,omitempty"`
	OutputBlobs          []GenerationOutputBlob            `json:"output_blobs,omitempty"`
	Verdicts             []gate.VerdictIntent              `json:"verdicts,omitempty"`
	BestUpdate           *gate.BestUpdateIntent            `json:"best_update,omitempty"`
	GenerationProvenance *GenerationIntent                 `json:"generation_provenance,omitempty"`
	Events               []GenerationLifecycleEventIntent  `json:"events,omitempty"`
	BoundaryEffects      map[Status][]RenderedEffectIntent `json:"boundary_effects,omitempty"`
}

GenerationSnapshotPayload is the loop-owned payload carried by task.GenerationSnapshot.

func GenerationSnapshotPayloadFrom

func GenerationSnapshotPayloadFrom(value any) (GenerationSnapshotPayload, error)

GenerationSnapshotPayloadFrom normalizes the loop-owned payload of a generation snapshot.

type GlobalBreakerPolicy

type GlobalBreakerPolicy struct {
	Threshold     int
	ProbeInterval time.Duration
	Source        string
}

GlobalBreakerPolicy is reload-scoped and deliberately excluded from run snapshots.

func ResolveGlobalBreakerPolicy

func ResolveGlobalBreakerPolicy(threshold int, probeInterval time.Duration) (GlobalBreakerPolicy, error)

ResolveGlobalBreakerPolicy returns reload-scoped policy with its fixed source label.

type GoalControlState

type GoalControlState struct {
	WorkspaceID  WorkspaceID
	LoopRunID    RunID
	Generation   int
	NodeID       dsl.NodeID
	ItemIndex    int
	ControlEpoch int64
	GoalStatus   string
	TurnsUsed    int
	TurnLimit    int
	TaskRunID    string
	QueueEntryID string
	PromptID     string
	PromptKind   string
	OpenTurn     bool
	GateID       NodeID
	Cause        ReasonCode
	RunStatus    Status
}

GoalControlState is the neutral parent-owned view of one awaiting Goal checkpoint.

type GoalControlStore

type GoalControlStore interface {
	LoadAwaitingGoalControl(context.Context, WorkspaceID, RunID) (GoalControlState, bool, error)
	ReactivateGoalRun(context.Context, GoalReactivationRequest) (GoalReactivationResult, error)
}

GoalControlStore is the optional atomic re-entry extension implemented by Loop stores.

type GoalGrantKind

type GoalGrantKind string

GoalGrantKind classifies one checkpoint-local reactivation permit.

const (
	GoalGrantTurnExtension GoalGrantKind = "turn-extension"
	GoalGrantBudget        GoalGrantKind = "budget"
	GoalGrantReseed        GoalGrantKind = "reseed"
	GoalGrantPlainResume   GoalGrantKind = "plain-resume"
)

type GoalGrantScope

type GoalGrantScope string

GoalGrantScope constrains the exact operation authorized by a Goal grant.

const (
	GoalGrantScopeTurnLimit     GoalGrantScope = "turn-limit"
	GoalGrantScopeSettleCurrent GoalGrantScope = "settle-current"
	GoalGrantScopeWorkAndSettle GoalGrantScope = "work-and-settle"
	GoalGrantScopeRotateBinding GoalGrantScope = "rotate-binding"
	GoalGrantScopeReactivate    GoalGrantScope = "reactivate"
)

type GoalPromptLease

type GoalPromptLease struct {
	QueueEntryID   string
	SessionID      string
	OwnerKind      string
	LoopRunID      string
	TaskRunID      string
	RunGeneration  int64
	PromptAttempt  int
	ControlEpoch   int64
	BindingEpoch   int64
	PromptID       string
	PromptKind     string
	JudgeAttemptID string
}

GoalPromptLease is the neutral identity required to revoke one managed Goal prompt lease.

type GoalPromptLeaseRevoker

type GoalPromptLeaseRevoker interface {
	RevokeGoalPromptLease(context.Context, GoalPromptLease, string) error
}

GoalPromptLeaseRevoker cancels one exact in-memory prompt lease after durable revocation commits.

type GoalPromptLeaseRevokerFunc

type GoalPromptLeaseRevokerFunc func(context.Context, GoalPromptLease, string) error

GoalPromptLeaseRevokerFunc adapts a function to GoalPromptLeaseRevoker.

func (GoalPromptLeaseRevokerFunc) RevokeGoalPromptLease

func (f GoalPromptLeaseRevokerFunc) RevokeGoalPromptLease(
	ctx context.Context,
	lease GoalPromptLease,
	reason string,
) error

RevokeGoalPromptLease implements GoalPromptLeaseRevoker.

type GoalReactivationRequest

type GoalReactivationRequest struct {
	State         GoalControlState
	Kind          GoalGrantKind
	Scope         GoalGrantScope
	TurnIncrement int
	Actor         task.ActorContext
	Decisions     []GateDecisionRecord
}

GoalReactivationRequest atomically grants and enqueues one successor Goal segment.

type GoalReactivationResult

type GoalReactivationResult struct {
	Run          task.Run
	ControlEpoch int64
	GrantID      int64
	Existing     bool
}

GoalReactivationResult records the monotonic grant and exactly-one successor identity.

type GoalRunActivator

type GoalRunActivator interface {
	ActivateGoalRun(context.Context, task.Run)
}

GoalRunActivator hands a committed Goal successor to the existing task-run activation path.

type GoalRunActivatorFunc

type GoalRunActivatorFunc func(context.Context, task.Run)

GoalRunActivatorFunc adapts a function to GoalRunActivator.

func (GoalRunActivatorFunc) ActivateGoalRun

func (f GoalRunActivatorFunc) ActivateGoalRun(ctx context.Context, run task.Run)

ActivateGoalRun implements GoalRunActivator.

type GoalRunPolicy

type GoalRunPolicy struct {
	ContextNudgeRatio float64
}

GoalRunPolicy is the workspace-resolved policy pinned into a new Run.

func (GoalRunPolicy) Validate

func (p GoalRunPolicy) Validate() error

Validate rejects values that cannot be persisted or used as a context threshold.

type GoalRunPolicyResolver

type GoalRunPolicyResolver interface {
	ResolveGoalRunPolicy(context.Context, WorkspaceID) (*GoalRunPolicy, error)
}

GoalRunPolicyResolver resolves workspace policy before any Run start write.

type GoalRunPolicyResolverFunc

type GoalRunPolicyResolverFunc func(context.Context, WorkspaceID) (*GoalRunPolicy, error)

GoalRunPolicyResolverFunc adapts a function to GoalRunPolicyResolver.

func (GoalRunPolicyResolverFunc) ResolveGoalRunPolicy

func (f GoalRunPolicyResolverFunc) ResolveGoalRunPolicy(
	ctx context.Context,
	workspaceID WorkspaceID,
) (*GoalRunPolicy, error)

ResolveGoalRunPolicy implements GoalRunPolicyResolver.

type HookDispatcher

HookDispatcher is the loop hook surface consumed at loop-owned call sites.

type InlineGoalClearStore

type InlineGoalClearStore interface {
	ClearInlineGoal(context.Context, InlineGoalClearStoreRequest) (InlineGoalClearStoreResult, error)
}

InlineGoalClearStore owns newest-session selection, live revocation, and the clear tombstone.

type InlineGoalClearStoreRequest

type InlineGoalClearStoreRequest struct {
	WorkspaceID     WorkspaceID
	OriginSessionID string
	Actor           task.ActorContext
	ClearedAt       time.Time
}

InlineGoalClearStoreRequest identifies the newest visible session Goal to clear atomically.

type InlineGoalClearStoreResult

type InlineGoalClearStoreResult struct {
	Run                 Run
	Terminalized        bool
	RevokedPromptLeases []GoalPromptLease
}

InlineGoalClearStoreResult carries the cleared Run and leases canceled after commit.

type InlineReplaceResult

type InlineReplaceResult struct {
	ReplacedRunID RunID
	Run           *Run
}

InlineReplaceResult is the public result of one successful expected-Run replacement.

type InlineReplaceStoreRequest

type InlineReplaceStoreRequest struct {
	ExpectedRunID RunID
	Run           *Run
	Actor         task.ActorContext
	ReplacedAt    time.Time
}

InlineReplaceStoreRequest carries one fully prepared replacement into the atomic store boundary.

type InlineReplaceStoreResult

type InlineReplaceStoreResult struct {
	ReplacedRunID       RunID
	ReplacedRun         Run
	Run                 Run
	RevokedPromptLeases []GoalPromptLease
}

InlineReplaceStoreResult carries committed replacement state and leases canceled after commit.

type InlineRunStore

type InlineRunStore interface {
	CreateInlineLoopRunForStart(context.Context, Run) (Run, error)
	ReplaceInlineLoopRun(context.Context, InlineReplaceStoreRequest) (InlineReplaceStoreResult, error)
}

InlineRunStore owns atomic session-origin start and replacement writes.

type InputDefaultError

type InputDefaultError struct {
	Loop   string             `json:"loop"`
	Key    string             `json:"key"`
	Reason InputDefaultReason `json:"reason"`
	Err    error              `json:"-"`
}

InputDefaultError is the typed validation error shared by static defaults and effective starts.

func AsInputDefaultError

func AsInputDefaultError(err error) (*InputDefaultError, bool)

AsInputDefaultError extracts the structured input-default diagnostic.

func (*InputDefaultError) Error

func (e *InputDefaultError) Error() string

func (*InputDefaultError) Unwrap

func (e *InputDefaultError) Unwrap() error

Unwrap keeps input-default failures in the Loop validation family.

type InputDefaultLayers

type InputDefaultLayers struct {
	Global    map[string]any
	Workspace map[string]any
}

InputDefaultLayers carries source-preserving configured values for one named Loop.

type InputDefaultReason

type InputDefaultReason string

InputDefaultReason is the closed machine-readable input resolution failure vocabulary.

const (
	InputDefaultReasonUnknownInput InputDefaultReason = "unknown_input"
	InputDefaultReasonTypeMismatch InputDefaultReason = "type_mismatch"
	InputDefaultReasonRequired     InputDefaultReason = "required"
)

type InputDefaultsResolver

type InputDefaultsResolver func(context.Context, WorkspaceID, string) (InputDefaultLayers, error)

InputDefaultsResolver resolves source-preserving configured inputs for one named Loop.

type InputOrigin

type InputOrigin string

InputOrigin identifies the layer that supplied one effective Loop input.

const (
	InputOriginRun        InputOrigin = "run"
	InputOriginWorkspace  InputOrigin = "workspace"
	InputOriginGlobal     InputOrigin = "global"
	InputOriginDefinition InputOrigin = "definition"
)

type Inputs

type Inputs struct {
	Values                     map[string]any         `json:"values,omitempty"`
	ParentLoopRunID            RunID                  `json:"parent_loop_run_id,omitempty"`
	ConfigOverrides            LoopConfig             `json:"config_overrides"`
	StartMetadata              map[string]any         `json:"start_metadata,omitempty"`
	NetworkParticipation       *participation.Request `json:"network_participation,omitempty"`
	NetworkParticipationSource participation.Source   `json:"-"`
	Admission                  *AdmissionIdentity     `json:"-"`
}

Inputs carries user inputs plus runtime-only start metadata.

type ItemRuntime

type ItemRuntime struct {
	TaskID      string
	TaskType    string
	Complexity  string
	Frontmatter RuntimeSpec
	Node        RuntimeSpec
}

ItemRuntime carries task identity and authored runtime layers for one item.

func ItemRuntimeFromNamespace

func ItemRuntimeFromNamespace(namespace map[string]any, node RuntimeSpec) (ItemRuntime, error)

ItemRuntimeFromNamespace extracts runtime-selection metadata from an imported task item.

type LifecycleAutopauseRule

type LifecycleAutopauseRule struct {
	Match  string `json:"match"`
	Action string `json:"action"`
}

LifecycleAutopauseRule is one validated ordered runtime rule.

type LifecycleConfig

type LifecycleConfig struct {
	RetryMaxAttempts       *int
	RetryBackoffBase       *time.Duration
	RetryBackoffMax        *time.Duration
	LivenessSilenceWindow  *time.Duration
	ResumeDeathStreakLimit *int
	PredicateCostLimit     *uint64
	WaitAdmissionAttempts  *int
	WaitAdmissionInterval  *time.Duration
	AdmissionHorizon       *time.Duration
	Autopause              []LifecycleAutopauseRule
}

LifecycleConfig is one pointer-backed node-lifecycle configuration layer.

func DefaultLifecycleConfig

func DefaultLifecycleConfig() LifecycleConfig

DefaultLifecycleConfig returns the shipped per-family lifecycle defaults.

func (LifecycleConfig) Clone

func (c LifecycleConfig) Clone() LifecycleConfig

Clone returns an owned copy of a lifecycle configuration layer.

type LintError

type LintError struct {
	NodeID   dsl.NodeID   `json:"node_id,omitempty"`
	Code     string       `json:"code"`
	Message  string       `json:"message"`
	Severity LintSeverity `json:"severity"`
}

LintError is the per-node shape surfaced to authoring clients.

type LintFailedError

type LintFailedError struct {
	Errors []LintError
}

LintFailedError carries blocking lint diagnostics from compile.

func (*LintFailedError) Error

func (e *LintFailedError) Error() string

type LintSeverity

type LintSeverity string

LintSeverity classifies a lint result.

const (
	// SeverityError blocks publish/compile.
	SeverityError LintSeverity = "error"
	// SeverityWarning is diagnostic-only.
	SeverityWarning LintSeverity = "warning"
)

type Linter

type Linter interface {
	Lint(def dsl.Definition) []LintError
}

Linter validates loop definitions without performing IO.

type LinterOption

type LinterOption func(*DefinitionLinter)

LinterOption configures the default linter.

func WithToolSchemaSource

func WithToolSchemaSource(source ToolSchemaSource) LinterOption

WithToolSchemaSource injects the pure schema snapshot source for open ToolID actions.

type LoopConfig

type LoopConfig struct {
	HumanGateEnabled  *bool               `json:"human_gate_enabled,omitempty"  yaml:"human_gate_enabled,omitempty"`
	ReattemptStrategy *ReattemptStrategy  `json:"reattempt_strategy,omitempty"  yaml:"reattempt_strategy,omitempty"`
	EnabledChecks     json.RawMessage     `json:"enabled_checks_json,omitempty" yaml:"enabled_checks_json,omitempty"`
	IterationCap      *int                `json:"iteration_cap,omitempty"       yaml:"iteration_cap,omitempty"`
	BudgetTokens      *int                `json:"budget_tokens,omitempty"       yaml:"budget_tokens,omitempty"`
	BudgetWallSec     *int                `json:"budget_wall_sec,omitempty"     yaml:"budget_wall_sec,omitempty"`
	BudgetOnExceeded  *dsl.BudgetExceeded `json:"budget_on_exceeded,omitempty"  yaml:"budget_on_exceeded,omitempty"`
	NoProgressWindow  *int                `json:"no_progress_window,omitempty"  yaml:"no_progress_window,omitempty"`
	FanOutWidth       *int                `json:"fan_out_width,omitempty"       yaml:"fan_out_width,omitempty"`
	GateMaxRevisions  *int                `json:"gate_max_revisions,omitempty"  yaml:"gate_max_revisions,omitempty"`
	RuntimeDefaults   *RuntimeDefaults    `json:"runtime_defaults,omitempty"    yaml:"runtime_defaults,omitempty"`
	RuntimeRules      []RuntimeRule       `json:"runtime_rules,omitempty"       yaml:"runtime_rules,omitempty"`
	Lifecycle         *LifecycleConfig    `json:"lifecycle,omitempty"           yaml:"lifecycle,omitempty"`
}

LoopConfig is the raw per-loop or per-run override layer.

func ClampLoopConfig

func ClampLoopConfig(cfg LoopConfig) LoopConfig

ClampLoopConfig clamps one override layer before merge or persistence.

func (LoopConfig) Clone

func (cfg LoopConfig) Clone() LoopConfig

Clone returns a deep copy of a raw config layer.

type LoopDefaults

type LoopDefaults struct {
	Delivery LoopConfig
	Watch    LoopConfig
}

LoopDefaults carries the `[loops.defaults.*]` layer consumed by the resolver.

func DefaultLoopDefaults

func DefaultLoopDefaults() LoopDefaults

DefaultLoopDefaults returns the built-in fallback `[loops.defaults.*]` layer.

type LoopGeneration

type LoopGeneration struct {
	RunID            string
	Generation       int64
	ParentGeneration int64
	Origin           GenerationOrigin
	CreatedAt        time.Time
}

LoopGeneration is the durable provenance record for one loop generation.

type ManagedActionSessionBinder

type ManagedActionSessionBinder interface {
	BindActionSession(context.Context, ActionSessionBindRequest) (ActionSessionBinding, error)
	AdvanceActionSessionRetry(context.Context, *ActionSessionRetryRequest) error
	PrepareActionPrompt(
		context.Context,
		ActionSessionBinding,
		ActionPromptRequest,
	) (ActionPromptTicket, error)
	AwaitActionPrompt(context.Context, ActionPromptTicket) (ActionPromptResult, error)
	CancelActionPrompts(context.Context, ActionPromptOwner) error
}

ManagedActionSessionBinder exposes durable prepare/await/cancel semantics for Goal.

type NodeAttempt

type NodeAttempt struct {
	LoopRunID     RunID              `json:"loop_run_id"`
	Generation    int                `json:"generation"`
	NodeID        NodeID             `json:"node_id"`
	ItemIndex     int                `json:"item_index"`
	Attempt       int                `json:"attempt"`
	FailureClass  *FailureClass      `json:"failure_class,omitempty"`
	FailureCode   string             `json:"failure_code,omitempty"`
	Cause         string             `json:"cause,omitempty"`
	Hint          string             `json:"hint,omitempty"`
	Target        string             `json:"target,omitempty"`
	Disposition   AttemptDisposition `json:"disposition"`
	StartedAt     time.Time          `json:"started_at"`
	EndedAt       *time.Time         `json:"ended_at,omitempty"`
	NextAttemptAt *time.Time         `json:"next_attempt_at,omitempty"`
}

NodeAttempt is one immutable attempt-ledger row.

type NodeAttemptReader

type NodeAttemptReader interface {
	ListNodeAttempts(
		ctx context.Context,
		workspaceID WorkspaceID,
		runID RunID,
	) ([]NodeAttempt, error)
}

NodeAttemptReader reads the immutable attempt ledger for lifecycle planning and repair context.

type NodeControl

type NodeControl struct {
	LoopRunID               RunID
	NodeID                  NodeID
	Paused                  bool
	PauseProvenance         *ControlProvenance
	Quarantined             bool
	QuarantineEntry         json.RawMessage
	QuarantinedAt           *time.Time
	AttentionFlag           string
	AttentionReason         string
	AttentionProducerNodeID string
	CancelState             CancelState
	CancelProvenance        *ControlProvenance
	LastEvidenceAt          *time.Time
	DeathResumeStreak       int
	Revision                int64
	UpdatedAt               time.Time
}

NodeControl is the cross-generation control state for one authored node.

type NodeControlMutation

type NodeControlMutation struct {
	Kind             NodeControlMutationKind `json:"kind"`
	NodeID           NodeID                  `json:"node_id"`
	ExpectedRevision int64                   `json:"expected_revision"`
	ExpectExisting   bool                    `json:"expect_existing,omitempty"`
	QuarantineEntry  json.RawMessage         `json:"quarantine_entry,omitempty"`
	AttentionFlag    string                  `json:"attention_flag,omitempty"`
	AttentionReason  string                  `json:"attention_reason,omitempty"`
	// AttentionProducerNodeID names the parked producer that owns the repair
	// record a dependency-quarantined consumer routes to.
	AttentionProducerNodeID string      `json:"attention_producer_node_id,omitempty"`
	CancelState             CancelState `json:"cancel_state,omitempty"`
	PauseActorKind          string      `json:"pause_actor_kind,omitempty"`
	PauseActorID            string      `json:"pause_actor_id,omitempty"`
	PauseReason             string      `json:"pause_reason,omitempty"`
	PauseRuleID             string      `json:"pause_rule_id,omitempty"`
	At                      time.Time   `json:"at"`
}

NodeControlMutation is persisted with the generation snapshot that caused it.

type NodeControlMutationKind

type NodeControlMutationKind string

NodeControlMutationKind identifies one coordinator-owned control transition.

const (
	NodeControlMutationPause      NodeControlMutationKind = "pause"
	NodeControlMutationQuarantine NodeControlMutationKind = "quarantine"
	NodeControlMutationAttention  NodeControlMutationKind = "attention"
	NodeControlMutationCancel     NodeControlMutationKind = "cancel"
)

type NodeControlReader

type NodeControlReader interface {
	ListNodeControls(context.Context, WorkspaceID, RunID) ([]NodeControl, error)
}

NodeControlReader reads cross-generation parked state for succession planning.

type NodeID

type NodeID = dsl.NodeID

NodeID aliases the DSL graph node identity.

const (
	// BudgetGateID is the synthetic approval gate used by budget escalation.
	BudgetGateID NodeID = "budget"
)

type NodeInventoryCursor

type NodeInventoryCursor struct {
	WorkspaceID WorkspaceID        `json:"workspace_id"`
	State       NodeInventoryState `json:"state"`
	LoopName    string             `json:"loop,omitempty"`
	RunID       RunID              `json:"run_id,omitempty"`
	StateAt     time.Time          `json:"state_at"`
	LoopRunID   RunID              `json:"loop_run_id"`
	Generation  int                `json:"generation"`
	NodeID      NodeID             `json:"node_id"`
	ItemIndex   int                `json:"item_index"`
}

NodeInventoryCursor is the decoded keyset cursor bound to the original filters.

func DecodeNodeInventoryCursor

func DecodeNodeInventoryCursor(query NodeInventoryQuery) (*NodeInventoryCursor, error)

DecodeNodeInventoryCursor validates an opaque cursor against its workspace and filters.

type NodeInventoryItem

type NodeInventoryItem struct {
	State      NodeInventoryState
	LoopRunID  RunID
	LoopName   string
	Generation int
	NodeID     NodeID
	ItemIndex  int
	StateAt    time.Time
	Wait       *NodeWait
	Control    *NodeControl
	Output     *GenerationOutput
	Attempt    *NodeAttempt
}

NodeInventoryItem is one stable-ordered inventory row with exactly one state detail.

type NodeInventoryPage

type NodeInventoryPage struct {
	Items      []NodeInventoryItem
	NextCursor string
}

NodeInventoryPage is one page and its opaque continuation cursor.

type NodeInventoryQuery

type NodeInventoryQuery struct {
	WorkspaceID WorkspaceID
	State       NodeInventoryState
	LoopName    string
	RunID       RunID
	Cursor      string
	Limit       int
}

NodeInventoryQuery filters one workspace-scoped inventory page.

func NormalizeNodeInventoryQuery

func NormalizeNodeInventoryQuery(query NodeInventoryQuery) (NodeInventoryQuery, error)

NormalizeNodeInventoryQuery validates public filters and applies the default page size.

type NodeInventoryReader

type NodeInventoryReader interface {
	ListNodeInventory(context.Context, NodeInventoryQuery) (NodeInventoryPage, error)
}

NodeInventoryReader owns workspace-scoped state inventory reads.

type NodeInventoryState

type NodeInventoryState string

NodeInventoryState is the closed workspace node-inventory vocabulary.

const (
	NodeInventoryWaiting     NodeInventoryState = "waiting"
	NodeInventoryQuarantined NodeInventoryState = "quarantined"
	NodeInventoryAttention   NodeInventoryState = "attention"
	NodeInventoryRetrying    NodeInventoryState = "retrying"
)

func (NodeInventoryState) Valid

func (s NodeInventoryState) Valid() bool

Valid reports whether the state belongs to the public inventory vocabulary.

type NodeLifecycleService

NodeLifecycleService exposes node-scoped control verbs implemented by the aggregate.

type NodeLivenessObservation

type NodeLivenessObservation struct {
	WorkspaceID  WorkspaceID
	LoopRunID    RunID
	TaskRunID    string
	ObservedAt   time.Time
	Evidence     bool
	SilenceAfter time.Duration
}

NodeLivenessObservation records one evidence probe for a live node attempt.

func (NodeLivenessObservation) Validate

func (o NodeLivenessObservation) Validate() error

Validate rejects observations that cannot be scoped to one live cell.

type NodeLivenessRecorder

type NodeLivenessRecorder interface {
	RecordNodeLiveness(context.Context, NodeLivenessObservation) error
}

NodeLivenessRecorder persists evidence and silence attention through one CAS authority.

type NodePauseMode

type NodePauseMode string

NodePauseMode controls what happens to an in-flight node attempt.

const (
	// NodePauseDrain lets an already-running attempt settle while parking future work.
	NodePauseDrain NodePauseMode = "drain"
	// NodePauseCancel requests cancellation of an already-running attempt after commit.
	NodePauseCancel NodePauseMode = "cancel"
)

type NodePauseMutation

type NodePauseMutation struct {
	WorkspaceID      WorkspaceID
	RunID            RunID
	NodeID           NodeID
	Mode             NodePauseMode
	Reason           string
	RuleID           string
	ExpectedRevision *int64
	Actor            task.ActorContext
	RequestedAt      time.Time
}

NodePauseMutation is the first-writer command for one authored node.

func (NodePauseMutation) Validate

func (m NodePauseMutation) Validate() error

Validate rejects pause requests that cannot preserve scope and provenance.

type NodePauseResult

type NodePauseResult struct {
	Control    NodeControl
	SessionIDs []string
	Applied    bool
}

NodePauseResult reports committed truth and exact post-commit cancellation targets.

type NodePauseStore

type NodePauseStore interface {
	PauseNode(context.Context, NodePauseMutation) (NodePauseResult, error)
	ResumeNode(context.Context, NodeResumeMutation) (NodeResumeResult, error)
}

NodePauseStore owns pause/resume CAS, cell fencing, events, and coordinator reservation.

type NodeProjection

type NodeProjection struct {
	Status      string
	Output      any
	Failure     *ClassifiedFailure
	Disposition AttemptDisposition
}

NodeProjection is one previous-generation node's observable state.

type NodeRequeueMutation

type NodeRequeueMutation struct {
	WorkspaceID      WorkspaceID
	RunID            RunID
	NodeID           NodeID
	Reason           string
	ExpectedRevision *int64
	Actor            task.ActorContext
	RequestedAt      time.Time
}

NodeRequeueMutation requests one quarantined node to re-enter normal succession.

func (NodeRequeueMutation) Normalize

Normalize trims requeue identities before validation and persistence lookup.

type NodeRequeueResult

type NodeRequeueResult struct {
	Control     NodeControl
	Coordinator task.Run
}

NodeRequeueResult returns the cleared control and committed coordinator wake.

type NodeRequeueStore

type NodeRequeueStore interface {
	RequeueNode(context.Context, NodeRequeueMutation) (NodeRequeueResult, error)
}

NodeRequeueStore owns the atomic quarantine-clear and coordinator reservation.

type NodeResumeMode

type NodeResumeMode string

NodeResumeMode controls how parked retry state is restored.

const (
	// NodeResumePlain restores the schedule and attempt counter that existed at pause time.
	NodeResumePlain NodeResumeMode = "plain"
	// NodeResumeResetAttempts clears retry delay and restarts the attempt counter.
	NodeResumeResetAttempts NodeResumeMode = "reset_attempts"
	// NodeResumeImmediate preserves the attempt counter but clears any retry delay.
	NodeResumeImmediate NodeResumeMode = "immediate"
)

type NodeResumeMutation

type NodeResumeMutation struct {
	WorkspaceID      WorkspaceID
	RunID            RunID
	NodeID           NodeID
	Mode             NodeResumeMode
	ExpectedRevision *int64
	Actor            task.ActorContext
	RequestedAt      time.Time
}

NodeResumeMutation releases one paused node episode.

func (NodeResumeMutation) Validate

func (m NodeResumeMutation) Validate() error

Validate rejects resume requests that cannot preserve scope and provenance.

type NodeResumeResult

type NodeResumeResult struct {
	Control     NodeControl
	Coordinator *task.Run
	Applied     bool
}

NodeResumeResult reports committed truth and the coordinator wake, when one was needed.

type NodeWait

type NodeWait struct {
	LoopRunID         RunID
	Generation        int
	NodeID            NodeID
	ItemIndex         int
	Kind              string
	ResumeAt          *time.Time
	NextEscalationAt  *time.Time
	EscalationCursor  int
	ClaimState        WaitClaimState
	ClaimedByKind     string
	ClaimedByID       string
	ClaimedAt         *time.Time
	AdmissionFailures int
	Expect            json.RawMessage
	AheadPayload      json.RawMessage
	IssuedEpoch       int64
	CreatedAt         time.Time
}

NodeWait is one durable pause point for a node cell.

type NodeWaitIntent

type NodeWaitIntent struct {
	NodeID           NodeID          `json:"node_id"`
	ItemIndex        int             `json:"item_index,omitempty"`
	Kind             string          `json:"kind"`
	ResumeAt         *time.Time      `json:"resume_at,omitempty"`
	NextEscalationAt *time.Time      `json:"next_escalation_at,omitempty"`
	Expect           json.RawMessage `json:"expect,omitempty"`
	ClaimState       WaitClaimState  `json:"claim_state,omitempty"`
	ClaimedByKind    string          `json:"claimed_by_kind,omitempty"`
	ClaimedByID      string          `json:"claimed_by_id,omitempty"`
	ClaimedAt        *time.Time      `json:"claimed_at,omitempty"`
	AheadPayload     json.RawMessage `json:"ahead_payload,omitempty"`
	IssuedEpoch      int64           `json:"issued_epoch"`
	CreatedAt        time.Time       `json:"created_at"`
}

NodeWaitIntent persists one wait in the same transaction as its waiting cell.

type NodeWaitReader

type NodeWaitReader interface {
	ListNodeWaits(context.Context, WorkspaceID, RunID) ([]NodeWait, error)
}

NodeWaitReader reads active durable waits for one workspace-owned run.

type Option

type Option func(*service)

Option configures a loop service.

func WithCancellationSessionController

func WithCancellationSessionController(controller CancellationSessionController) Option

WithCancellationSessionController injects post-commit prompt and process cancellation.

func WithClock

func WithClock(now func() time.Time) Option

WithClock injects a deterministic clock.

func WithCoordinatorRunActivator

func WithCoordinatorRunActivator(activator CoordinatorRunActivator) Option

WithCoordinatorRunActivator injects the post-commit activation path for non-Goal coordinator wakes.

func WithDefaults

func WithDefaults(defaults LoopDefaults) Option

WithDefaults injects the `[loops.defaults.*]` layer consumed by the resolver.

func WithDefaultsResolver

func WithDefaultsResolver(resolver DefaultsResolver) Option

WithDefaultsResolver injects workspace-aware `[loops.defaults.*]` resolution.

func WithGoalPromptLeaseRevoker

func WithGoalPromptLeaseRevoker(revoker GoalPromptLeaseRevoker) Option

WithGoalPromptLeaseRevoker injects post-commit cancellation for exact managed Goal prompt leases.

func WithGoalRunActivator

func WithGoalRunActivator(activator GoalRunActivator) Option

WithGoalRunActivator injects the post-commit activation path for Goal successor workers.

func WithHookDispatcher

func WithHookDispatcher(hooks HookDispatcher) Option

WithHookDispatcher injects loop hook dispatch at aggregate call sites.

func WithInputDefaultsResolver

func WithInputDefaultsResolver(resolver InputDefaultsResolver) Option

WithInputDefaultsResolver injects workspace-aware `[loops.inputs.<name>]` resolution.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger injects structured observability for post-commit service failures.

func WithParticipationResolver

func WithParticipationResolver(resolver participation.Resolver) Option

WithParticipationResolver injects the canonical execution participation resolver.

func WithRunIDFactory

func WithRunIDFactory(factory func() (RunID, error)) Option

WithRunIDFactory injects a deterministic run ID factory.

func WithRuntimeCatalog

func WithRuntimeCatalog(catalog WorkspaceRuntimeCatalog) Option

WithRuntimeCatalog injects workspace-specific effective runtime validation.

type ParkedNodeWaitEvent

type ParkedNodeWaitEvent struct {
	ItemIndex         int
	IssuedEpoch       int64
	AdmissionAttempts int
}

ParkedNodeWaitEvent addresses one event-backed wait through the shared watch-events index.

type ParkedWatchEventScanCursor

type ParkedWatchEventScanCursor struct {
	WorkspaceID string
	LoopRunID   string
	NodeID      string
}

ParkedWatchEventScanCursor resumes a deterministic parked-subscription scan.

type ParkedWatchEventSubscription

type ParkedWatchEventSubscription struct {
	WorkspaceID   string
	LoopRunID     string
	LoopName      string
	NodeID        string
	Generation    int
	Inputs        map[string]any
	Subscriptions []watchpkg.EventSubscriptionRef
	Cursors       map[string]int64
	Contracts     map[hooks.HookEvent]WatchEventsContract
	Wait          *ParkedNodeWaitEvent
}

ParkedWatchEventSubscription is one dormant watch-events node recovered from persisted loop generation output state.

type PayloadDiagnostic

type PayloadDiagnostic struct {
	Code  string `json:"code"`
	Cause string `json:"cause"`
}

PayloadDiagnostic is a recordable result of a skipped payload inspection.

type PayloadInspection

type PayloadInspection struct {
	Failure    *ActionFailure     `json:"failure,omitempty"`
	Diagnostic *PayloadDiagnostic `json:"diagnostic,omitempty"`
}

PayloadInspection is the pure result of inspecting a successful transport body.

func InspectPayloadFailure

func InspectPayloadFailure(raw json.RawMessage, contract *dsl.ResultContract) PayloadInspection

InspectPayloadFailure applies a custom result contract or the built-in v0 truth table.

type PendingCancellation

type PendingCancellation struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	NodeID      NodeID
	State       CancelState
	Reason      string
	RequestedAt time.Time
	RequestedBy task.ActorIdentity
	SessionIDs  []string
}

PendingCancellation carries one durable delivery command and its current session bindings.

type PlanNodePreview

type PlanNodePreview struct {
	ID        dsl.NodeID    `json:"id"`
	Class     dsl.NodeClass `json:"class"`
	Kind      string        `json:"kind"`
	DependsOn []dsl.NodeID  `json:"depends_on,omitempty"`
}

PlanNodePreview is one gen-1 node materialized by DryRun.

type PlanPreview

type PlanPreview struct {
	LoopName                     string                 `json:"loop_name"`
	ResolvedInputs               map[string]any         `json:"resolved_inputs"`
	InputOrigins                 map[string]InputOrigin `json:"input_origins"`
	Generation                   int                    `json:"generation"`
	Nodes                        []PlanNodePreview      `json:"nodes"`
	Contract                     dsl.Contract           `json:"contract"`
	MaterializedContract         dsl.Contract           `json:"materialized_contract"`
	EffectiveConfig              EffectiveConfig        `json:"effective_config"`
	ResolvedNetworkParticipation participation.Spec     `json:"resolved_network_participation"`
}

PlanPreview is the no-state preview returned by DryRun.

type PredicateDiagnostic

type PredicateDiagnostic struct {
	Predicate string
	Cause     string
	Outcome   PredicateErrorPolicy
}

PredicateDiagnostic is the durable diagnostic payload later consumers append.

type PredicateErrorPolicy

type PredicateErrorPolicy string

PredicateErrorPolicy is the explicit response to an evaluation failure.

const (
	// PredicateErrorExit exits the current loop by policy.
	PredicateErrorExit PredicateErrorPolicy = "exit"
	// PredicateErrorRoute produces a routable failure.
	PredicateErrorRoute PredicateErrorPolicy = "route"
)

type PredicateFailureDisposition

type PredicateFailureDisposition struct {
	Policy     PredicateErrorPolicy
	ExitReason string
	Failure    *ClassifiedFailure
	Diagnostic PredicateDiagnostic
}

PredicateFailureDisposition is the pure result of applying predicate policy.

func ApplyPredicateFailurePolicy

func ApplyPredicateFailurePolicy(
	predicate string,
	kind PredicateKind,
	override *PredicateErrorPolicy,
	cause error,
) (PredicateFailureDisposition, error)

ApplyPredicateFailurePolicy maps a broken predicate to its deterministic policy result.

type PredicateKind

type PredicateKind string

PredicateKind distinguishes loop-exit predicates from routing predicates.

const (
	// PredicateContinuation fails open so a broken continuation cannot hang a run.
	PredicateContinuation PredicateKind = "continuation"
	// PredicateRouting fails closed as a routable authoring failure.
	PredicateRouting PredicateKind = "routing"
)

type PreviousGeneration

type PreviousGeneration struct {
	Generation  int64
	Nodes       map[string]map[int]NodeProjection
	Verdicts    map[string]map[int]VerdictProjection
	RouteCauses []GateInstanceProjection
}

PreviousGeneration projects the immediately preceding generation.

type QuarantineEntry

type QuarantineEntry struct {
	NodeID    NodeID                 `json:"node_id"`
	InputRef  string                 `json:"input_ref"`
	Target    string                 `json:"target,omitempty"`
	Episodes  []QuarantineEpisode    `json:"episodes"`
	Requeues  []QuarantineProvenance `json:"requeues,omitempty"`
	Truncated bool                   `json:"truncated,omitempty"`
}

QuarantineEntry is the self-contained, sanitized repair record retained across requeues.

type QuarantineEpisode

type QuarantineEpisode struct {
	Generation    int           `json:"generation"`
	QuarantinedAt time.Time     `json:"quarantined_at"`
	Attempts      []NodeAttempt `json:"attempts"`
}

QuarantineEpisode captures the classified attempt chain that caused one quarantine.

type QuarantineProvenance

type QuarantineProvenance struct {
	ActorKind   string    `json:"actor_kind"`
	ActorID     string    `json:"actor_id"`
	Reason      string    `json:"reason,omitempty"`
	RequestedAt time.Time `json:"requested_at"`
	Generation  int       `json:"generation"`
}

QuarantineProvenance attributes one operator or agent requeue request.

type ReasonCode

type ReasonCode string

ReasonCode is the deterministic machine-readable failure code surfaced to agents.

const (
	// ReasonCodeUnknownActionKind reports an action kind missing from reserved kinds and RuntimeRegistry.
	ReasonCodeUnknownActionKind ReasonCode = "unknown_action_kind"
	// ReasonCodeActionDependencyMissing reports an unwired runtime collaborator for a reserved action.
	ReasonCodeActionDependencyMissing ReasonCode = "action_dependency_missing"
	// ReasonCodeActionStalled reports a harvest window that produced no designated result.
	ReasonCodeActionStalled ReasonCode = "action_stalled"
	// ReasonCodeActionSchemaInvalid reports run-agent output_schema validation failure.
	ReasonCodeActionSchemaInvalid ReasonCode = "action_schema_invalid"
	// ReasonCodeActionTimeout reports timeout cancellation of an action turn.
	ReasonCodeActionTimeout ReasonCode = "action_timeout"
	// ReasonCodeActionContractStale reports runtime tool schemas that differ from the Run snapshot.
	ReasonCodeActionContractStale ReasonCode = "action_contract_stale"
)
const (
	// ReasonCodeActiveRunExists reports a forbid-concurrency start conflict.
	ReasonCodeActiveRunExists ReasonCode = "active_loop_run_exists"
	// ReasonCodeAncestryCycle reports a run-loop target already in its parent chain.
	ReasonCodeAncestryCycle ReasonCode = "run_loop_ancestry_cycle"
	// ReasonCodeAncestryDepthExceeded reports a parent chain deeper than the hard ceiling.
	ReasonCodeAncestryDepthExceeded ReasonCode = "run_loop_ancestry_depth_exceeded"
	// ReasonCodeInvalidStatusTransition reports a rejected status edge.
	ReasonCodeInvalidStatusTransition ReasonCode = "invalid_status_transition"
	// ReasonCodeTerminalRun reports an operation rejected because the run is already terminal.
	ReasonCodeTerminalRun ReasonCode = "terminal_loop_run"
	// ReasonCodeRunTerminal reports a node lifecycle verb rejected by terminal run truth.
	ReasonCodeRunTerminal ReasonCode = "run_terminal"
	// ReasonCodeNodeNotPaused reports a resume request against a node that is not paused.
	ReasonCodeNodeNotPaused ReasonCode = "node_not_paused"
	// ReasonCodeNodeNotQuarantined reports a requeue request against a node outside quarantine.
	ReasonCodeNodeNotQuarantined ReasonCode = "node_not_quarantined"
	// ReasonCodeAlreadyDecided reports a lifecycle compare-and-swap lost to a durable winner.
	ReasonCodeAlreadyDecided ReasonCode = "already_decided"
	// ReasonCodeStartKindNotAllowed reports a start surface missing from the loop definition allowlist.
	ReasonCodeStartKindNotAllowed ReasonCode = "start_kind_not_allowed"
	// ReasonCodeStartInputInvalid reports invalid static or mapped start inputs.
	ReasonCodeStartInputInvalid ReasonCode = "start_input_invalid"
	// ReasonCodeStartInputMappingInvalid reports invalid or unresolvable input_mapping entries.
	ReasonCodeStartInputMappingInvalid ReasonCode = "start_input_mapping_invalid"
)
const (
	ReasonCodeGoalNotActive            ReasonCode = "goal_not_active"
	ReasonCodeGoalReplaceRequired      ReasonCode = "goal_replace_required"
	ReasonCodeGoalReplaceStale         ReasonCode = "goal_replace_stale"
	ReasonCodeGoalEvidenceTooLarge     ReasonCode = "goal_evidence_too_large"
	ReasonCodeGoalReportConflict       ReasonCode = "goal_report_conflict"
	ReasonCodeGoalReportedBlocked      ReasonCode = "goal_reported_blocked"
	ReasonCodeGoalActionControlInvalid ReasonCode = "goal_action_control_invalid"
	ReasonCodeGoalStopReasonInvalid    ReasonCode = "goal_stop_reason_invalid"
	ReasonCodeGoalPromptRequestFailed  ReasonCode = "goal_prompt_request_failed"
	ReasonCodeGoalJudgeUnavailable     ReasonCode = "goal_judge_unavailable"
	ReasonCodeGoalJudgeBroken          ReasonCode = "goal_judge_broken"
	ReasonCodeGoalJudgeOutcomeInvalid  ReasonCode = "goal_judge_outcome_invalid"
	ReasonCodeGoalAgentRefused         ReasonCode = "goal_agent_refused"
	//nolint:misspell // The persisted reason code uses the ACP contract's British spelling.
	ReasonCodeGoalCompactionCancelled         ReasonCode = "goal_compaction_cancelled"
	ReasonCodeGoalPresubmitRetriesExhausted   ReasonCode = "goal_presubmit_retries_exhausted"
	ReasonCodeGoalRecoveryAmbiguous           ReasonCode = "goal_recovery_ambiguous"
	ReasonCodeGoalControlRevokedInFlight      ReasonCode = "goal_control_revoked_in_flight"
	ReasonCodeGoalBudgetFenced                ReasonCode = "goal_budget_fenced"
	ReasonCodeGoalTurnsExhausted              ReasonCode = "goal_turns_exhausted"
	ReasonCodeGoalReseedConfirmationRequired  ReasonCode = "goal_reseed_confirmation_required"
	ReasonCodeGoalControlStale                ReasonCode = "goal_control_stale"
	ReasonCodeGoalPromptFenced                ReasonCode = "goal_prompt_fenced"
	ReasonCodeGoalOriginInvalid               ReasonCode = "goal_origin_invalid"
	ReasonCodeGoalOriginWorkspaceMismatch     ReasonCode = "goal_origin_workspace_mismatch"
	ReasonCodeGoalOriginProfileUnavailable    ReasonCode = "goal_origin_profile_unavailable"
	ReasonCodeSessionCreationIdentityMismatch ReasonCode = "session_creation_identity_mismatch"
	ReasonCodeContinuousBindingMismatch       ReasonCode = "continuous_binding_mismatch"
)

type ReasonError

type ReasonError struct {
	Code ReasonCode
	Err  error
	Meta map[string]string
}

ReasonError carries a deterministic reason code while preserving errors.Is.

func (*ReasonError) Error

func (e *ReasonError) Error() string

func (*ReasonError) Unwrap

func (e *ReasonError) Unwrap() error

Unwrap returns the wrapped sentinel error.

type ReattemptStrategy

type ReattemptStrategy string

ReattemptStrategy configures generation re-attempt breadth.

const (
	// ReattemptFailedOnly retries failed work only.
	ReattemptFailedOnly ReattemptStrategy = "failed_only"
	// ReattemptFullBody retries the whole generation body.
	ReattemptFullBody ReattemptStrategy = "full_body"
)

type RenderedEffectIntent

type RenderedEffectIntent struct {
	Trigger    EffectTrigger   `json:"trigger"`
	Generation int             `json:"generation"`
	NodeID     NodeID          `json:"node_id,omitempty"`
	ItemIndex  int             `json:"item_index,omitempty"`
	EntryIndex int             `json:"entry_index"`
	Entry      json.RawMessage `json:"entry"`
}

RenderedEffectIntent is one immutable entry ready for same-transaction outbox insertion.

func RenderEffectIntents

func RenderEffectIntents(
	effects []dsl.EffectSpec,
	req EffectContextRequest,
) ([]RenderedEffectIntent, error)

RenderEffectIntents resolves each entry independently and persists failures as data.

func (RenderedEffectIntent) Validate

func (i RenderedEffectIntent) Validate() error

Validate rejects incomplete rendered delivery intents before persistence.

type RepairContextEntry

type RepairContextEntry struct {
	NodeID   string `json:"node_id"`
	Cause    string `json:"cause"`
	Guidance string `json:"guidance"`
}

RepairContextEntry keeps cause and guidance scoped to one failed node.

func BuildRepairContext

func BuildRepairContext(failures []RepairFailure) []RepairContextEntry

BuildRepairContext projects unabsorbed failures into deterministic per-node guidance.

type RepairFailure

type RepairFailure struct {
	NodeID   string
	Failure  ClassifiedFailure
	Absorbed bool
}

RepairFailure is one classified node failure considered at a generation boundary.

type ResolvedDefaults

type ResolvedDefaults struct {
	FanOutBatchSize int                   `json:"fan_out_batch_size"`
	RunLoopMode     dsl.RunLoopMode       `json:"run_loop_mode"`
	Concurrency     dsl.ConcurrencyPolicy `json:"concurrency"`
}

ResolvedDefaults records defaults folded at compile time.

type ResolvedDefinition

type ResolvedDefinition struct {
	Definition           dsl.Definition
	DefinitionVersion    int
	Templates            map[string]*refs.Template
	Conditions           map[string]*refs.Condition
	ToolSchemas          map[string]ToolSchemaSnapshot
	WatchEventsContracts map[hooks.HookEvent]WatchEventsContract
	Defaults             ResolvedDefaults
	EffectiveConfig      EffectiveConfig
	// contains filtered or unexported fields
}

ResolvedDefinition is the publish-time artifact hydrated by runtime execution.

func LoadExecutedDefinitionSnapshot

func LoadExecutedDefinitionSnapshot(
	raw json.RawMessage,
	expectedDigest string,
) (*ResolvedDefinition, error)

LoadExecutedDefinitionSnapshot verifies and purely hydrates one Run-owned execution artifact.

type ResolvedInputs

type ResolvedInputs struct {
	Values  map[string]any
	Origins map[string]InputOrigin
}

ResolvedInputs contains effective values and the exact winning source for every present key.

func ResolveInputDefaults

func ResolveInputDefaults(
	def dsl.Definition,
	loopName string,
	run map[string]any,
	layers InputDefaultLayers,
) (ResolvedInputs, error)

ResolveInputDefaults applies run > workspace > global > definition precedence per key.

type ResolvedLifecycleConfig

type ResolvedLifecycleConfig struct {
	RetryMaxAttempts       int                      `json:"retry_max_attempts"`
	RetryBackoffBase       time.Duration            `json:"retry_backoff_base"`
	RetryBackoffMax        time.Duration            `json:"retry_backoff_max"`
	RetryNonRetryable      []string                 `json:"retry_non_retryable"`
	Deadline               *time.Duration           `json:"deadline,omitempty"`
	LivenessSilenceWindow  time.Duration            `json:"liveness_silence_window"`
	ResumeDeathStreakLimit int                      `json:"resume_death_streak_limit"`
	PredicateCostLimit     uint64                   `json:"predicate_cost_limit"`
	WaitAdmissionAttempts  int                      `json:"wait_admission_attempts"`
	WaitAdmissionInterval  time.Duration            `json:"wait_admission_interval"`
	AdmissionHorizon       time.Duration            `json:"admission_horizon"`
	Autopause              []LifecycleAutopauseRule `json:"autopause"`
	Sources                map[string]string        `json:"sources"`
}

ResolvedLifecycleConfig is the admission-pinned lifecycle policy for one node.

func ResolveNodeLifecycleConfig

func ResolveNodeLifecycleConfig(
	node dsl.Node,
	loopConfig *LifecycleConfig,
	defaults LifecycleConfig,
) (ResolvedLifecycleConfig, error)

ResolveNodeLifecycleConfig applies node > loop_config > default without mutating any layer.

type ResolvedRuntime

type ResolvedRuntime struct {
	Runtime RuntimeSpec       `json:"runtime"`
	Source  RuntimeProvenance `json:"source"`
}

ResolvedRuntime is field-merged runtime intent plus per-field provenance.

func ResolveItemRuntime

func ResolveItemRuntime(layers RuntimeLayers, item ItemRuntime) (ResolvedRuntime, error)

ResolveItemRuntime resolves one worker item using the ADR-001 field precedence.

func ResolveJudgeRuntime

func ResolveJudgeRuntime(defaults RuntimeSpec, criterion RuntimeSpec) ResolvedRuntime

ResolveJudgeRuntime merges judge defaults with one criterion runtime.

func ValidateResolvedRuntime

func ValidateResolvedRuntime(
	ctx context.Context,
	catalog RuntimeCatalog,
	taskID string,
	resolved ResolvedRuntime,
) (ResolvedRuntime, error)

ValidateResolvedRuntime validates canonical runtime intent before a session bind.

type ResourceParseOptions

type ResourceParseOptions struct {
	Source                 Source
	Dir                    string
	FilePath               string
	InstalledFromExtension string
	Linter                 Linter
}

ResourceParseOptions carries source context for a YAML-to-resource projection.

type ResourceSpec

type ResourceSpec struct {
	Name                   string              `json:"name"`
	Version                int                 `json:"version,omitempty"`
	Description            string              `json:"description,omitempty"`
	Catalog                CatalogResourceSpec `json:"catalog,omitzero"`
	ContractGoal           string              `json:"contract_goal,omitempty"`
	Start                  []StartResourceSpec `json:"start,omitempty"`
	Source                 Source              `json:"source"`
	Dir                    string              `json:"dir,omitempty"`
	FilePath               string              `json:"file_path,omitempty"`
	DefinitionChecksum     string              `json:"definition_checksum,omitempty"`
	InstalledFromExtension string              `json:"installed_from_extension,omitempty"`
}

ResourceSpec is the resource-kernel projection for a loop definition.

The canonical YAML body remains on the source filesystem. This spec stores only matchable catalog/start metadata plus source references needed by catalog, fork, and immutability flows.

func CloneResourceSpec

func CloneResourceSpec(spec ResourceSpec) ResourceSpec

CloneResourceSpec returns a deep copy of a projected loop resource.

func ParseResource

func ParseResource(data []byte, opts ResourceParseOptions) (ResourceSpec, dsl.Definition, error)

ParseResource projects one YAML loop definition into a metadata resource spec.

func ParseResourceFile

func ParseResourceFile(path string, opts ResourceParseOptions) (ResourceSpec, dsl.Definition, error)

ParseResourceFile reads and projects one YAML loop definition from disk.

func ResourceSpecFromDefinition

func ResourceSpecFromDefinition(def dsl.Definition, opts ResourceParseOptions) ResourceSpec

ResourceSpecFromDefinition extracts metadata from a parsed loop definition.

func WriteDefinition

func WriteDefinition(root string, data []byte, opts WriteDefinitionOptions) (ResourceSpec, string, error)

WriteDefinition validates and writes one loop definition under root/<meta.name>/loop.yaml.

type RetryDueCell

type RetryDueCell struct {
	WorkspaceID   WorkspaceID
	LoopRunID     RunID
	Generation    int
	NodeID        NodeID
	ItemIndex     int
	Attempt       int
	Epoch         int64
	NextAttemptAt time.Time
}

RetryDueCell is one durable retry schedule selected by the scheduler backstop.

type RetryDueCursor

type RetryDueCursor struct {
	NextAttemptAt time.Time
	LoopRunID     RunID
	Generation    int
	NodeID        NodeID
	ItemIndex     int
}

RetryDueCursor is the stable composite cursor for retry due-time paging.

func (RetryDueCursor) Empty

func (c RetryDueCursor) Empty() bool

Empty reports whether the cursor is the initial page position.

type Run

type Run struct {
	ID                    RunID
	WorkspaceID           WorkspaceID
	LoopName              string
	Status                Status
	Generation            int
	BestGeneration        *int64
	BestScore             *float64
	ReattemptStrategy     ReattemptStrategy
	CreatedAt             time.Time
	StartedAt             time.Time
	LastProgressAt        time.Time
	StartedBy             task.ActorIdentity
	StartedOrigin         task.Origin
	DefinitionVersion     int
	DefinitionDigest      string
	DefinitionSnapshot    json.RawMessage
	ActiveGateID          NodeID
	ActiveHumanCriteria   json.RawMessage
	BudgetApprovalSeq     int
	StartMetadata         map[string]any
	IterationCap          int
	BudgetTokens          int
	BudgetWallSec         int
	BudgetOnExceeded      dsl.BudgetExceeded
	TokensUsed            int64
	ParentLoopRunID       RunID
	PauseRequested        bool
	CancelRequested       bool
	CancelKind            RunCancelKind
	ControlActor          task.ActorIdentity
	ControlRequestedAt    time.Time
	GoalContextNudgeRatio float64
	*RunStartState
	Origin *RunOrigin
	Inputs map[string]any
}

Run is the durable loop_run aggregate returned by the service.

func StartFromActor

func StartFromActor(
	ctx context.Context,
	service Service,
	resolver DefinitionResolver,
	req StartBindingRequest,
	actor task.ActorContext,
) (*Run, error)

StartFromActor enforces the definition allowlist before delegating to Service.Start.

func StartFromBinding

func StartFromBinding(
	ctx context.Context,
	service Service,
	resolver DefinitionResolver,
	req StartBindingRequest,
) (*Run, error)

StartFromBinding derives the actor for the surface, enforces the definition allowlist, and then delegates execution to the single loop Service.Start point.

func (Run) NetworkSpecSnapshot

func (r Run) NetworkSpecSnapshot() participation.Spec

NetworkSpecSnapshot returns the immutable snapshot, defaulting uninitialized in-memory runs to Local.

func (*Run) SetAdmission

func (r *Run) SetAdmission(identity AdmissionIdentity)

SetAdmission attaches one transient watch-admission identity to a start command.

func (*Run) SetNetworkSpec

func (r *Run) SetNetworkSpec(spec participation.Spec)

SetNetworkSpec replaces the immutable participation snapshot.

type RunAdmission

type RunAdmission struct {
	Identity   AdmissionIdentity
	Suppressed bool
	Claim      *AdmissionClaim
}

RunAdmission groups the transient watch-admission command and its optional suppression answer.

type RunAgentActionExecutor

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

RunAgentActionExecutor binds an ACP session and prompts a profile-backed agent.

func (*RunAgentActionExecutor) Execute

Execute renders the work-order prompt, binds a session, and validates structured output.

func (*RunAgentActionExecutor) Harvest

Harvest returns the run-agent prompt result.

type RunCancelKind

type RunCancelKind uint8

RunCancelKind records the operator's run-level cancellation intent.

const (
	RunCancelNone RunCancelKind = iota
	RunCancelCancel
	RunCancelKill
)

func ParseRunCancelKind

func ParseRunCancelKind(value string) RunCancelKind

ParseRunCancelKind converts the durable string representation into the compact runtime enum.

func (RunCancelKind) String

func (k RunCancelKind) String() string

String returns the durable run-cancel representation.

func (RunCancelKind) Valid

func (k RunCancelKind) Valid() bool

Valid reports whether value belongs to the closed run-cancel vocabulary.

type RunEvent

type RunEvent struct {
	ID          string
	LoopRunID   RunID
	WorkspaceID WorkspaceID
	Seq         int64
	Kind        string
	Payload     json.RawMessage
	At          time.Time
	DeliveryKey string
}

RunEvent is one retained loop_run_events row.

type RunEventQuery

type RunEventQuery struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	AfterSeq    int64
	Limit       int
}

RunEventQuery filters retained loop run events.

type RunID

type RunID string

RunID is the durable loop_runs primary key.

type RunListQuery

type RunListQuery struct {
	WorkspaceID     WorkspaceID
	LoopName        string
	Status          Status
	OriginKind      string
	OriginSessionID string
	Live            *bool
	Limit           int
	CreatedAfter    time.Time
}

RunListQuery filters workspace-scoped loop run listings.

type RunLoopActionExecutor

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

RunLoopActionExecutor starts a child loop for await or detach semantics.

func (*RunLoopActionExecutor) Execute

Execute starts the child through loop.Service.Start.

func (*RunLoopActionExecutor) Harvest

Harvest returns the run-loop child id and await status.

type RunOrigin

type RunOrigin struct {
	Kind               RunOriginKind
	SessionID          string
	CreationProfileRef string
	PolicySpecDigest   string
	CreationDigest     string
}

RunOrigin pins session creation truth for inline execution and reseed.

func (RunOrigin) Normalize

func (o RunOrigin) Normalize() RunOrigin

Normalize trims one Run origin without changing its meaning.

func (RunOrigin) Validate

func (o RunOrigin) Validate() error

Validate enforces catalog/session origin field presence.

type RunOriginKind

type RunOriginKind string

RunOriginKind classifies the durable source of one Loop Run.

const (
	// RunOriginCatalog identifies a catalog-backed Run.
	RunOriginCatalog RunOriginKind = "catalog"
	// RunOriginSession identifies a snapshot-only Run created from a session.
	RunOriginSession RunOriginKind = "session"
)

type RunReader

type RunReader interface {
	ListLoopRuns(ctx context.Context, query RunListQuery) ([]Run, error)
	ListLoopRunEvents(ctx context.Context, query RunEventQuery) ([]RunEvent, error)
	ListGenerationOutputs(
		ctx context.Context,
		workspaceID WorkspaceID,
		runID RunID,
		generation int,
	) ([]GenerationOutput, error)
}

RunReader exposes read-model operations outside the aggregate mutation service.

type RunStartState

type RunStartState struct {
	NetworkSpec participation.Spec `json:"network_spec"`
	Admission   *RunAdmission      `json:"-"`
}

RunStartState keeps immutable participation and transient admission state off the hot Run value.

type RuntimeCatalog

type RuntimeCatalog interface {
	CanonicalProvider(string) string
	ValidateRuntime(context.Context, RuntimeSpec) error
}

RuntimeCatalog validates provider identity and preserves exact model IDs for the provider boundary.

type RuntimeDefaults

type RuntimeDefaults = dsl.RuntimeDefaults

RuntimeDefaults contains worker and judge default runtime intent.

type RuntimeLayers

type RuntimeLayers struct {
	Defaults    RuntimeSpec
	ConfigRules []RuntimeRule
	RunRules    []RuntimeRule
}

RuntimeLayers are the ordered runtime-selection layers owned by the engine.

type RuntimeMatch

type RuntimeMatch = dsl.RuntimeMatch

RuntimeMatch selects one task identity dimension.

type RuntimeProvenance

type RuntimeProvenance struct {
	Provider  RuntimeSource `json:"provider,omitempty"`
	Model     RuntimeSource `json:"model,omitempty"`
	Reasoning RuntimeSource `json:"reasoning,omitempty"`
}

RuntimeProvenance records the source of every resolved runtime field.

type RuntimeRule

type RuntimeRule = dsl.RuntimeRule

RuntimeRule is one task runtime selection rule.

type RuntimeSource

type RuntimeSource string

RuntimeSource identifies the layer that supplied one resolved runtime field.

const (

	// RuntimeSourceRun identifies a per-run runtime rule.
	RuntimeSourceRun RuntimeSource = "run"
	// RuntimeSourceFrontmatter identifies task frontmatter.
	RuntimeSourceFrontmatter RuntimeSource = "frontmatter"
	// RuntimeSourceConfig identifies a configured runtime rule.
	RuntimeSourceConfig RuntimeSource = "config"
	// RuntimeSourceNode identifies rendered node params.runtime.
	RuntimeSourceNode RuntimeSource = "node"
	// RuntimeSourceDefault identifies effective runtime_defaults.
	RuntimeSourceDefault RuntimeSource = "default"
	// RuntimeSourceCriterion identifies an agent-judge criterion runtime.
	RuntimeSourceCriterion RuntimeSource = "criterion"
	// RuntimeSourceAgent identifies a value completed by the agent definition.
	RuntimeSourceAgent RuntimeSource = "agent"
)

type RuntimeSpec

type RuntimeSpec = dsl.RuntimeSpec

RuntimeSpec is the provider/model/reasoning intent resolved by the Loop engine.

type RuntimeValidationError

type RuntimeValidationError struct {
	Items []RuntimeValidationItem `json:"runtime_validation"`
}

RuntimeValidationError reports one or more invalid runtime fields.

func AsRuntimeValidationError

func AsRuntimeValidationError(err error) (*RuntimeValidationError, bool)

AsRuntimeValidationError extracts structured runtime diagnostics.

func (*RuntimeValidationError) Error

func (e *RuntimeValidationError) Error() string

Error implements error.

func (*RuntimeValidationError) Unwrap

func (e *RuntimeValidationError) Unwrap() error

Unwrap keeps runtime validation in the loop validation error family.

type RuntimeValidationItem

type RuntimeValidationItem struct {
	TaskID string `json:"task_id,omitempty"`
	Field  string `json:"field"`
	Value  string `json:"value"`
	Reason string `json:"reason"`
}

RuntimeValidationItem is one deterministic runtime validation diagnostic.

type SafeActionFailureProvider

type SafeActionFailureProvider interface {
	error
	SafeActionFailure() ActionFailure
}

SafeActionFailureProvider lets a domain error publish durable operator-safe cause and recovery detail without exposing its internal error text.

type Service

type Service interface {
	Start(ctx context.Context, ws WorkspaceID, name string, inputs Inputs, actor task.ActorContext) (*Run, error)
	StartInline(
		ctx context.Context,
		ws WorkspaceID,
		definition dsl.Definition,
		inputs Inputs,
		origin RunOrigin,
		actor task.ActorContext,
	) (*Run, error)
	ReplaceInline(
		ctx context.Context,
		expectedRunID RunID,
		ws WorkspaceID,
		definition dsl.Definition,
		inputs Inputs,
		origin RunOrigin,
		actor task.ActorContext,
	) (InlineReplaceResult, error)
	ClearInlineGoal(
		ctx context.Context,
		ws WorkspaceID,
		originSessionID string,
		actor task.ActorContext,
	) error
	DryRun(ctx context.Context, ws WorkspaceID, name string, inputs Inputs) (*PlanPreview, error)
	CancelRun(ctx context.Context, ws WorkspaceID, runID RunID, reason string, actor task.ActorContext) error
	KillRun(ctx context.Context, ws WorkspaceID, runID RunID, reason string, actor task.ActorContext) error
	CancelNode(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		nodeID NodeID,
		reason string,
		actor task.ActorContext,
	) error
	KillNode(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		nodeID NodeID,
		reason string,
		actor task.ActorContext,
	) error
	Pause(ctx context.Context, ws WorkspaceID, runID RunID, actor task.ActorContext) error
	// Resume clears pause_requested on running runs or transitions paused runs back to running.
	Resume(ctx context.Context, ws WorkspaceID, runID RunID, actor task.ActorContext) error
	Approve(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		gateID NodeID,
		decision GateDecision,
		actor task.ActorContext,
	) error
	Configure(ctx context.Context, ws WorkspaceID, name string, cfg LoopConfig) error
	GetConfig(ctx context.Context, ws WorkspaceID, name string) (*LoopConfig, error)
	GetConfigSnapshot(ctx context.Context, ws WorkspaceID, name string) (ConfigSnapshot, error)
	Get(ctx context.Context, ws WorkspaceID, runID RunID) (*Run, error)
	Transition(ctx context.Context, runID RunID, to Status, cause TransitionCause) error
}

Service is the task_04 loop aggregate API surface.

func NewService

func NewService(
	loopStore Store,
	resolver DefinitionResolver,
	goalPolicy GoalRunPolicyResolver,
	opts ...Option,
) (Service, error)

NewService creates the loop aggregate service.

type Source

type Source string

Source names the source-precedence class for one loop definition.

const (
	// SourceMarketplace identifies marketplace extension-contributed loop definitions.
	SourceMarketplace Source = "marketplace"
	// SourceUser identifies user-owned global loop definitions under $COMPOZY_HOME.
	SourceUser Source = "user"
	// SourceAdditional identifies loop definitions discovered through additional workspace roots.
	SourceAdditional Source = "additional"
	// SourceWorkspace identifies workspace-local loop definitions under <workspace>/.compozy.
	SourceWorkspace Source = "workspace"
)

func (Source) Normalize

func (s Source) Normalize() Source

Normalize returns the canonical source value.

func (Source) PrecedenceRank

func (s Source) PrecedenceRank() int

PrecedenceRank returns the explicit task_03 source-precedence rank.

func (Source) Valid

func (s Source) Valid() bool

Valid reports whether s is a supported loop source class.

type StagedWritableDefinitionDeletion

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

StagedWritableDefinitionDeletion owns a reversible definition-directory removal.

func StageWritableDefinitionDeletion

func StageWritableDefinitionDeletion(root string, name string) (*StagedWritableDefinitionDeletion, error)

StageWritableDefinitionDeletion atomically moves a writable definition outside its scanned root.

func (*StagedWritableDefinitionDeletion) Commit

Commit permanently removes a staged definition directory.

func (*StagedWritableDefinitionDeletion) Restore

Restore moves a staged definition back into the scanned writable root.

type StartBindingRequest

type StartBindingRequest struct {
	WorkspaceID WorkspaceID
	LoopName    string
	Kind        dsl.StartKind
	ActorRef    string
	OriginRef   string
	Inputs      Inputs
}

StartBindingRequest describes one concrete start from a declared loop surface.

type StartResourceSpec

type StartResourceSpec struct {
	Kind             string   `json:"kind"`
	InputKeys        []string `json:"input_keys,omitempty"`
	InputMappingKeys []string `json:"input_mapping_keys,omitempty"`
}

StartResourceSpec is the matchable start-surface metadata projected from a loop definition.

type StartTargetResolution

type StartTargetResolution struct {
	StartTargetValidation
	TriggerPayload map[string]any
}

StartTargetResolution resolves static inputs plus input_mapping against a trigger payload.

type StartTargetValidation

type StartTargetValidation struct {
	WorkspaceID  WorkspaceID
	LoopName     string
	Kind         dsl.StartKind
	Inputs       map[string]any
	InputMapping map[string]string
}

StartTargetValidation validates static and mapped inputs for one automation-carried start.

type Status

type Status string

Status is the closed loop_runs.status vocabulary.

const (
	// StatusQueued is a live deferred same-loop start.
	StatusQueued Status = "queued"
	// StatusRunning is a live coordinator-owned run.
	StatusRunning Status = "running"
	// StatusWatching is a dormant watch-source run.
	StatusWatching Status = "watching"
	// StatusNeedsApproval is a dormant human-gate run.
	StatusNeedsApproval Status = "needs-approval"
	// StatusPaused is a dormant operator-paused run.
	StatusPaused Status = "paused"
	// StatusDone is a verified terminal outcome.
	StatusDone Status = "done"
	// StatusNoOp is a truthful terminal no-work outcome.
	StatusNoOp Status = "no-op"
	// StatusBlocked is a terminal external-dependency outcome.
	StatusBlocked Status = "blocked"
	// StatusFailed is a terminal unrecoverable failure outcome.
	StatusFailed Status = "failed"
	// StatusExhausted is a terminal hard-limit outcome.
	StatusExhausted Status = "exhausted"
	// StatusStalled is a terminal no-progress outcome.
	StatusStalled Status = "stalled"
	// StatusCanceled is a terminal operator-canceled outcome.
	StatusCanceled Status = "canceled"
)

func (Status) Live

func (s Status) Live() bool

Live reports whether the status is non-terminal.

func (Status) Terminal

func (s Status) Terminal() bool

Terminal reports whether the status is terminal.

func (Status) Valid

func (s Status) Valid() bool

Valid reports whether the status belongs to the closed vocabulary.

type Store

type Store interface {
	CreateLoopRunForStart(ctx context.Context, run Run, policy dsl.ConcurrencyPolicy) (Run, error)
	GetLoopRun(ctx context.Context, ws WorkspaceID, runID RunID) (Run, error)
	GetLoopRunByID(ctx context.Context, runID RunID) (Run, error)
	GetLoopDefinitionSnapshot(ctx context.Context, ws WorkspaceID, digest string) (DefinitionSnapshot, error)
	FindActiveLoopRun(ctx context.Context, ws WorkspaceID, loopName string) (*Run, error)
	CompareAndSwapLoopRunStatus(
		ctx context.Context,
		runID RunID,
		from Status,
		to Status,
		cause TransitionCause,
		at time.Time,
	) error
	RecordLoopGateDecisions(ctx context.Context, records []GateDecisionRecord) error
	ListLoopGateDecisions(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		generation int,
		gateID NodeID,
	) (map[string]gate.HumanDecision, error)
	SetLoopRunPauseRequested(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		requested bool,
		actor task.ActorContext,
	) error
	UpsertLoopConfig(ctx context.Context, ws WorkspaceID, loopName string, cfg LoopConfig) error
	GetLoopConfig(ctx context.Context, ws WorkspaceID, loopName string) (*LoopConfig, error)
}

Store is the loop aggregate persistence contract.

type StoreChannelResultHarvester

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

StoreChannelResultHarvester reads the durable Compozy Network conversation store for result messages.

func NewStoreChannelResultHarvester

func NewStoreChannelResultHarvester(
	conversations ChannelResultConversationStore,
) (*StoreChannelResultHarvester, error)

NewStoreChannelResultHarvester creates the default durable-store channel_result harvester.

func (*StoreChannelResultHarvester) HarvestChannelResult

HarvestChannelResult waits within the declared window for the designated result message.

type StoreFinalizer

type StoreFinalizer struct{}

StoreFinalizer writes loop-owned generation snapshots inside task transactions.

func NewStoreFinalizer

func NewStoreFinalizer() *StoreFinalizer

NewStoreFinalizer constructs a loop generation snapshot writer.

func (*StoreFinalizer) WriteGenerationSnapshot

func (f *StoreFinalizer) WriteGenerationSnapshot(
	ctx context.Context,
	tx task.Tx,
	snap task.GenerationSnapshot,
) error

WriteGenerationSnapshot upserts loop_generation_outputs rows in the caller-owned transaction.

type TargetHealth

TargetHealth is the loop-owned admission and accounting seam over the daemon-global loop-target dead-entity service.

type ToolCallActionExecutor

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

ToolCallActionExecutor adapts a ToolID action to RuntimeRegistry.Call.

func (*ToolCallActionExecutor) Execute

Execute calls RuntimeRegistry.Call with rendered action params.

func (*ToolCallActionExecutor) Harvest

Harvest applies the node harvest policy to a tool call result.

type ToolSchemaSnapshot

type ToolSchemaSnapshot struct {
	ToolID             string          `json:"tool_id"`
	InputSchema        json.RawMessage `json:"input_schema,omitempty"`
	OutputSchema       json.RawMessage `json:"output_schema,omitempty"`
	InputSchemaDigest  string          `json:"input_schema_digest,omitempty"`
	OutputSchemaDigest string          `json:"output_schema_digest,omitempty"`
}

ToolSchemaSnapshot is the pure tool-schema view consumed by lint and compile.

type ToolSchemaSource

type ToolSchemaSource interface {
	Snapshot(toolID string) (ToolSchemaSnapshot, bool)
}

ToolSchemaSource resolves open action ToolIDs without tying lint to runtime IO.

type TransformActionExecutor

type TransformActionExecutor struct{}

TransformActionExecutor evaluates pure in-daemon transform maps.

func (TransformActionExecutor) Execute

Execute evaluates params.map without side effects.

func (TransformActionExecutor) Harvest

Harvest returns the transform output as-is.

type TransitionCause

type TransitionCause string

TransitionCause records why a status transition happened.

const (
	// TransitionCauseStart records initial run creation.
	TransitionCauseStart TransitionCause = "start"
	// TransitionCausePromote records queued-run promotion.
	TransitionCausePromote TransitionCause = "promote"
	// TransitionCauseOperatorCancel records a graceful operator cancellation.
	TransitionCauseOperatorCancel TransitionCause = "operator_cancel"
	// TransitionCauseOperatorKill records an immediate operator kill.
	TransitionCauseOperatorKill TransitionCause = "operator_kill"
	// TransitionCauseGoalReplace records an expected-run inline Goal replacement.
	TransitionCauseGoalReplace TransitionCause = "goal_replace"
	// TransitionCauseGoalClear records an inline Goal clear that also stops a live Run.
	TransitionCauseGoalClear TransitionCause = "goal_clear"
	// TransitionCausePauseBoundary records a generation boundary honoring pause_requested.
	TransitionCausePauseBoundary TransitionCause = "pause_boundary"
	// TransitionCauseOperatorResume records operator resume.
	TransitionCauseOperatorResume TransitionCause = "operator_resume"
	// TransitionCauseApproval records a human approval.
	TransitionCauseApproval TransitionCause = "approval"
	// TransitionCauseWaitExpired records an authored wait or approval timeout route.
	TransitionCauseWaitExpired TransitionCause = "wait_expired"
	// TransitionCauseGateRejected records a human gate rejection.
	TransitionCauseGateRejected TransitionCause = "gate_rejected"
	// TransitionCauseContract records a coordinator contract verdict.
	TransitionCauseContract TransitionCause = "contract"
	// TransitionCauseBudget records a hard budget outcome.
	TransitionCauseBudget TransitionCause = "budget"
	// TransitionCauseIterationCap records a generation iteration-cap outcome.
	TransitionCauseIterationCap TransitionCause = "iteration_cap"
	// TransitionCauseNoProgress records a coordinator no-progress outcome.
	TransitionCauseNoProgress TransitionCause = "no_progress"
	// TransitionCauseWatchPoll records a watch-source poll yielding dormancy.
	TransitionCauseWatchPoll TransitionCause = "watch_poll"
	// TransitionCauseWatchEvents records a watch-events source yielding dormancy.
	TransitionCauseWatchEvents TransitionCause = "watch_events"
	// TransitionCauseCoordinatorFailure records an execution failure before a boundary settled.
	TransitionCauseCoordinatorFailure TransitionCause = "coordinator_failure"
)

type UIAnnotation

type UIAnnotation struct {
	NodeID NodeID
	X      float64
	Y      float64
}

UIAnnotation is one editor sidecar position for a loop node.

type VerdictProjection

type VerdictProjection struct {
	Outcome        gate.VerdictOutcome
	Score          *float64
	BlockingIssues any
	Criteria       any
}

VerdictProjection is one persisted machine gate verdict.

type WaitAdmission

type WaitAdmission interface {
	ResumeWait(context.Context, WaitResumeMutation) (WaitResumeResult, error)
}

WaitAdmission owns the atomic wait claim and coordinator reservation.

type WaitClaimState

type WaitClaimState string

WaitClaimState is the closed durable wait-claim vocabulary.

const (
	WaitClaimWaiting              WaitClaimState = "waiting"
	WaitClaimClaimed              WaitClaimState = "claimed"
	WaitClaimResumed              WaitClaimState = "resumed"
	WaitClaimInterventionRequired WaitClaimState = "intervention_required"
)

func (WaitClaimState) Valid

func (s WaitClaimState) Valid() bool

Valid reports whether value belongs to the closed wait-claim vocabulary.

type WaitDueCursor

type WaitDueCursor struct {
	ResumeAt   time.Time
	LoopRunID  RunID
	Generation int
	NodeID     NodeID
	ItemIndex  int
}

WaitDueCursor is the stable composite cursor for timer-wait paging.

func (WaitDueCursor) Empty

func (c WaitDueCursor) Empty() bool

Empty reports whether this is the initial page position.

type WaitEscalationCursor

type WaitEscalationCursor struct {
	NextEscalationAt time.Time
	LoopRunID        RunID
	Generation       int
	NodeID           NodeID
	ItemIndex        int
}

WaitEscalationCursor is the stable composite cursor for wait-ladder paging.

func (WaitEscalationCursor) Empty

func (c WaitEscalationCursor) Empty() bool

Empty reports whether this is the initial page position.

type WaitEscalationStore

type WaitEscalationStore interface {
	EscalateDueLoopWaitsPage(
		context.Context,
		time.Time,
		WaitEscalationCursor,
		int,
	) (WaitEscalationCursor, error)
}

WaitEscalationStore owns due ladder steps and terminal expiry transitions.

type WaitResumeMutation

type WaitResumeMutation struct {
	WorkspaceID       WorkspaceID
	RunID             RunID
	Generation        int
	NodeID            NodeID
	ItemIndex         int
	Payload           json.RawMessage
	ClaimedByKind     string
	ClaimedByID       string
	AdmissionAttempts int
	RequestedAt       time.Time
}

WaitResumeMutation admits one payload into a durable wait.

func (WaitResumeMutation) Validate

func (m WaitResumeMutation) Validate() error

Validate rejects wait admissions that cannot preserve identity and provenance.

type WaitResumeResult

type WaitResumeResult struct {
	Wait        NodeWait
	Coordinator *task.Run
	Won         bool
}

WaitResumeResult reports the winning provenance and committed coordinator wake.

type WatchEvent

type WatchEvent struct {
	Kind        string         `json:"kind"`
	Seq         int64          `json:"seq"`
	Stream      string         `json:"stream"`
	At          string         `json:"at"`
	WorkspaceID string         `json:"workspace_id"`
	TaskID      string         `json:"task_id,omitempty"`
	RunID       string         `json:"run_id,omitempty"`
	LoopRunID   string         `json:"loop_run_id,omitempty"`
	LoopName    string         `json:"loop_name,omitempty"`
	SessionID   string         `json:"session_id,omitempty"`
	Channel     string         `json:"channel,omitempty"`
	WorkID      string         `json:"work_id,omitempty"`
	Payload     map[string]any `json:"payload,omitempty"`
	LedgerKind  string         `json:"-"`
}

WatchEvent is the normalized loop-facing event envelope produced from a durable replay row.

func (WatchEvent) EventMap

func (e WatchEvent) EventMap() map[string]any

EventMap returns the CEL-facing event namespace used by watch-events filters.

type WatchEventsContract

type WatchEventsContract struct {
	Kind          hooks.HookEvent `json:"kind"`
	Stream        string          `json:"stream"`
	LedgerTypes   []string        `json:"ledger_types"`
	PayloadFields []string        `json:"payload_fields"`
	RequiredVars  []string        `json:"required_vars"`
}

WatchEventsContract describes one supported watch-events family row.

type WatchEventsCursorReader

type WatchEventsCursorReader interface {
	ReadCursors(ctx context.Context, q WatchEventsQuery) (map[string]int64, error)
}

WatchEventsCursorReader reads per-stream cursor maxima for initial parking.

type WatchEventsLedger

type WatchEventsLedger interface {
	ReadMatches(ctx context.Context, q WatchEventsQuery) ([]WatchEvent, error)
}

WatchEventsLedger reads durable replay streams for watch-events evaluation.

type WatchEventsQuery

type WatchEventsQuery struct {
	WorkspaceID string
	Streams     map[string]int64
	Kinds       []string
	Limit       int
}

WatchEventsQuery selects replay rows strictly after each stream cursor.

type WatchIdentitySource

type WatchIdentitySource interface {
	SupportsStableWatchIdentity(kind string) bool
}

WatchIdentitySource reports whether a watch source kind provides stable event identity.

type WatchPoller

type WatchPoller = watchpkg.Poller

WatchPoller is the coordinator seam for daemon -> extension watch/poll calls.

type WorkspaceID

type WorkspaceID string

WorkspaceID is the workspace owner for loop aggregate state.

type WorkspaceRuntimeCatalog

type WorkspaceRuntimeCatalog interface {
	ForWorkspace(context.Context, WorkspaceID) (RuntimeCatalog, error)
}

WorkspaceRuntimeCatalog resolves workspace-specific provider validation authority.

type WriteDefinitionOptions

type WriteDefinitionOptions struct {
	Source    Source
	Overwrite bool
	Linter    Linter
}

WriteDefinitionOptions configures a writable loop definition write.

Source Files

Directories

Path Synopsis
dsl
Package dsl defines the compozy.loop/v1 authoring document.
Package dsl defines the compozy.loop/v1 authoring document.
refs
Package refs validates loop template and CEL references against one namespace.
Package refs validates loop template and CEL references against one namespace.
Package gate evaluates loop verification gates.
Package gate evaluates loop verification gates.
Package goal defines the durable convergence contracts implemented by the Loop store.
Package goal defines the durable convergence contracts implemented by the Loop store.

Jump to

Keyboard shortcuts

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