loop

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 54 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 (
	EffectiveConfigSourceBuiltin              = "builtin"
	EffectiveConfigSourceDefinition           = "definition"
	EffectiveConfigSourceDeliveryDefaults     = "loops.defaults.delivery"
	EffectiveConfigSourceWatchDefaults        = "loops.defaults.watch"
	EffectiveConfigSourceInheritedEnvironment = "inherited_environment"
	EffectiveConfigSourceLoopConfig           = "loop_config"
	EffectiveConfigSourcePerRun               = "per_run"
)
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 (
	CodeInputTypeRequired        = "input_type_required"
	CodeInputTypeInvalid         = "input_type_invalid"
	CodeInputFieldUnknown        = "input_field_unknown"
	CodeInputRefRequired         = "input_ref_required"
	CodeInputRefKindInvalid      = "input_ref_kind_invalid"
	CodeInputEnumInvalid         = "input_enum_invalid"
	CodeInputDefaultInvalid      = "input_default_invalid"
	CodeRequestEntityKindInvalid = "request_entity_kind_invalid"
)
View Source
const (
	CodeResultViewNotLiteral        = "result_view_not_literal"
	CodeResultViewFieldRequiresFull = "result_view_field_requires_full"
)
View Source
const (
	DefaultNodeInventoryLimit = 50
	MaxNodeInventoryLimit     = 200
)
View Source
const (
	// AttentionSilence reports ambiguous loss of liveness evidence without declaring death.
	AttentionSilence = "silence"
	// AttentionWaitIntervention reports a node parked for explicit operator recovery.
	AttentionWaitIntervention = "wait_intervention"
)
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"
	// NodeWaitKindRequest parks a human request until answer, expiry, or cancellation.
	NodeWaitKindRequest = "request"
)
View Source
const (
	RequestKindAsk         = "ask"
	RequestKindReview      = "review"
	RequestStatePending    = "pending"
	RequestStateAnswered   = "answered"
	RequestStateExpired    = "expired"
	RequestStateCanceled   = "canceled"
	RequestDecisionRespond = "respond"
	RequestDecisionApprove = "approve"
	RequestDecisionEdit    = "edit"
	RequestDecisionReject  = "reject"
)
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 (
	// 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"
	// CodeStrategyCoverageUndeclared reports partial coverage without explicit author consent.
	CodeStrategyCoverageUndeclared = "strategy_coverage_undeclared"
	// CodeStrategyThresholdInvalid reports a malformed or misplaced strategy threshold.
	CodeStrategyThresholdInvalid = "strategy_threshold_invalid"
	// CodeStrategyWaitAllEquivalent hints that a 100-percent quorum is wait_all.
	CodeStrategyWaitAllEquivalent = "strategy_wait_all_equivalent"
	// CodeIterationNameConflict reports colliding or reserved fan-out iteration names.
	CodeIterationNameConflict = "iteration_name_conflict"
	// 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"
	// CodeRunLoopOutputShapeInvalid reports a produces shape unsupported by run-loop completion.
	CodeRunLoopOutputShapeInvalid = "run_loop_output_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"
	// CodeUnknownParameter reports a removed or unsupported authoring field.
	CodeUnknownParameter = "unknown_parameter"
	// CodeEvalErrorPolicyInvalid reports an on_eval_error value or placement outside its closed grammar.
	CodeEvalErrorPolicyInvalid = "eval_error_policy_invalid"
	// CodeRouteDefaultMissing reports a route node without its required default destination.
	CodeRouteDefaultMissing = "route_default_missing"
	// CodeRouteTargetInvalid reports an unknown, backward, duplicate, or undeclared route destination.
	CodeRouteTargetInvalid = "route_target_invalid"
	// CodeRouteMappingInvalid reports a gate outcome mapping outside the closed route grammar.
	CodeRouteMappingInvalid = "route_mapping_invalid"
	// CodeRouteActionRemoved reports the deleted branch action and points authors to object-form routing.
	CodeRouteActionRemoved = "route_action_removed"
	// 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"
	// CodeGoalOutputStatusMissingComplete reports a Goal output schema that cannot represent completion.
	CodeGoalOutputStatusMissingComplete = "goal_output_status_missing_complete"
	// 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"
	// CodeEnvironmentCWDRemoved reports the retired action cwd field.
	CodeEnvironmentCWDRemoved = "environment_cwd_removed"
	// CodeEnvironmentInvalid reports a malformed EnvironmentSpec.
	CodeEnvironmentInvalid = "environment_invalid"
	// CodeEnvironmentUnsupported reports Environment on a node that cannot start agents.
	CodeEnvironmentUnsupported = "environment_unsupported"
	// 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"
	// CodeAskExpectRequired reports an ask without an answer schema.
	CodeAskExpectRequired = "ask_expect_required"
	// CodeResponderPolicyInvalid reports an unsupported responders.agents value.
	CodeResponderPolicyInvalid = "responder_policy_invalid"
	// CodeReviewShapeInvalid reports an invalid action review grammar.
	CodeReviewShapeInvalid = "review_shape_invalid"
	// CodeReviewRespondSchemaRequired reports respond without a declared action output.
	CodeReviewRespondSchemaRequired = "review_respond_schema_required"
	// 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
	// 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 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
)
View Source
const LoopWatchEventPageLimit = 64

LoopWatchEventPageLimit bounds one durable event-ledger read.

View Source
const ReasonMetaRecordedDecision = "recorded_decision"

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")
	// ErrActionInvalidOutput reports run-agent structured output that failed output_schema validation.
	ErrActionInvalidOutput = errors.New("loop: action output schema validation failed")
	// ErrActionMaterialization reports authored templates that cannot resolve against the runtime namespace.
	ErrActionMaterialization = errors.New("loop: action materialization failed")
	// ErrActionTimeout reports an action turn canceled by the node timeout.
	ErrActionTimeout = errors.New("loop: action timeout")
	// ErrActionResultTooLarge reports a tool result that cannot be consumed without truncation.
	ErrActionResultTooLarge = errors.New("loop: action result too large")
)
View Source
var (
	ErrAmendNotParked     = errors.New("loop: amendment target is not parked")
	ErrAmendNoOutput      = errors.New("loop: amendment target has no output")
	ErrAmendSchemaMissing = errors.New("loop: amendment target has no declared output schema")
)
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")
	// ErrExecutedDefinitionSnapshot reports a Run-owned snapshot that cannot be loaded safely.
	ErrExecutedDefinitionSnapshot = errors.New("loop: executed definition snapshot unavailable")
	// 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 (
	ErrRequestNotFound         = errors.New("loop: request not found")
	ErrRequestAlreadyAnswered  = errors.New("loop: request already answered")
	ErrRequestExpired          = errors.New("loop: request expired")
	ErrRequestCanceled         = errors.New("loop: request canceled")
	ErrRespondNotPermitted     = errors.New("loop: respond not permitted")
	ErrRespondSelfDenied       = errors.New("loop: respond self denied")
	ErrRequestValidationFailed = errors.New("loop: request validation failed")
)
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")
)
View Source
var (
	ErrTimelineBranchChanged      = errors.New("timeline_branch_changed")
	ErrInvalidTimelineCursor      = errors.New("invalid_cursor")
	ErrTimelinePositionBeyondHead = errors.New("timeline_position_beyond_head")
)
View Source
var (
	ErrRerunBusy             = errors.New("loop: rerun generation is busy")
	ErrRerunNodeUnsettled    = errors.New("loop: rerun node is unsettled")
	ErrTimeTravelKeyReuse    = errors.New("loop: time travel request id reused")
	ErrForkGenerationUnknown = errors.New("loop: fork generation is unknown")
	ErrDiffCrossLoop         = errors.New("loop: diff requires the same loop")
	ErrTimeTravelSelfDenied  = errors.New("loop: time travel self-operation denied")
)
View Source
var ErrInvalidRosterCursor = errors.New("invalid_cursor")
View Source
var ErrInvalidRunListCursor = errors.New("invalid_cursor")

ErrInvalidRunListCursor reports a malformed or filter-incompatible run-list cursor.

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 ActionPromptWithOutputContract

func ActionPromptWithOutputContract(prompt string, schema dsl.Schema) (string, error)

ActionPromptWithOutputContract appends the authored output schema so an action agent knows the exact terminal JSON shape before its first attempt.

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 IsLoopID

func IsLoopID(value string) bool

IsLoopID reports whether value is a Loop identity: a generated run id or an authored definition name.

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,
	admitted ...dsl.NodeParams,
) (dsl.GoalParams, error)

MaterializeGoalParams resolves one Goal node against its runtime namespace.

func NewRequestReasonError

func NewRequestReasonError(code ReasonCode, err error, details map[string]string) error

NewRequestReasonError preserves a request sentinel while adding a stable public code.

func NewRequestValidationError

func NewRequestValidationError(err error) error

NewRequestValidationError projects JSON Schema failures as field-addressed public details.

func NewResourceCodec

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

NewResourceCodec returns the JSON codec for loop resource projections.

func NewRuntimeValidationCauseError

func NewRuntimeValidationCauseError(cause error, item RuntimeValidationItem) error

NewRuntimeValidationCauseError reports one invalid runtime field with a typed cause.

func NewRuntimeValidationError

func NewRuntimeValidationError(items ...RuntimeValidationItem) error

NewRuntimeValidationError constructs a normalized validation error.

func NewSafeActionFailureError

func NewSafeActionFailureError(err error, failure ActionFailure) error

NewSafeActionFailureError wraps an error with a SafeActionFailure payload.

func NodeCellAttemptIdempotencyKey

func NodeCellAttemptIdempotencyKey(
	loopRunID RunID,
	generation int,
	nodeID string,
	itemIndex int,
	attempt int,
) string

NodeCellAttemptIdempotencyKey is the canonical reservation key for one loop node cell attempt.

func NodeCellAttemptRunID

func NodeCellAttemptRunID(
	loopRunID RunID,
	generation int,
	nodeID string,
	itemIndex int,
	attempt int,
) string

NodeCellAttemptRunID is the canonical task-run id for one loop node cell attempt.

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 NodeStateFilterValues

func NodeStateFilterValues() []string

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 ReportActionLivenessSession

func ReportActionLivenessSession(ctx context.Context, sessionID string)

ReportActionLivenessSession names the session whose activity proves an action is alive. Unlike ReportActionSessionBound it transfers no run-session ownership or crash recovery, so executors that own their binding and recovery, such as Goals, keep that authority.

func ReportActionSessionBound

func ReportActionSessionBound(ctx context.Context, sessionID string)

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

func ResolveActionEnvironment

func ResolveActionEnvironment(
	node dsl.EnvironmentSpec,
	loopDefault dsl.EnvironmentSpec,
) (dsl.EnvironmentSpec, error)

ResolveActionEnvironment applies node-over-loop precedence and validates the closed environment shape.

func ResolveEffectiveResources

func ResolveEffectiveResources(
	records []resources.Record[ResourceSpec],
	lens ResourceLens,
) []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,
	profileID string,
	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 RunEventKindValues

func RunEventKindValues() []string

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 ValidateActionRunResult

func ValidateActionRunResult(run task.Run, result task.RunResult) error

ValidateActionRunResult revalidates the exact durable result against the output schema pinned into the task-run metadata before lease settlement.

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 ValidateDefinitionInputs

func ValidateDefinitionInputs(def dsl.Definition) error

ValidateDefinitionInputs validates author-contained defaults without resolving configured layers.

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 ValidateInputEntities

func ValidateInputEntities(
	ctx context.Context,
	workspaceID WorkspaceID,
	profileID string,
	loopName string,
	definition dsl.Definition,
	resolved ResolvedInputs,
	entities InputEntityCatalog,
	runtimes WorkspaceRuntimeCatalog,
) error

ValidateInputEntities checks resolved entity and runtime values against injected authorities.

func ValidateInputLayer

func ValidateInputLayer(
	def dsl.Definition,
	loopName string,
	values map[string]any,
	origin InputOrigin,
) error

ValidateInputLayer validates the values present in one precedence layer without requiring omissions.

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 the supported selector shapes 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 ACPOptionSelection

type ACPOptionSelection = dsl.ACPOptionSelection

ACPOptionSelection is one typed provider-advertised ACP option value.

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 ActionCompactionOutcome

type ActionCompactionOutcome struct {
	CompactionID string
	Status       string
}

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 event harvested by sequence.

type ActionEventRangeReader

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

ActionEventRangeReader reads ACP 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 {
	GrantCeiling     string
	WorkspaceID      WorkspaceID
	LoopRunID        RunID
	Generation       int
	NodeID           dsl.NodeID
	ItemIndex        int
	Attempt          int
	CellEpoch        int64
	SessionSharedKey string
	DeathResume      *DeathResumeContext
	RetryFailure     *ClassifiedFailure
	RepairFailures   []ActionRepairFailure
	Namespace        map[string]any
	Contract         *dsl.Contract
	ToolScope        tools.Scope
	Actor            *task.ActorContext
	CorrelationID    string
	RuntimeSelection *ActionRuntimeSelection
	Environment      *dsl.EnvironmentSpec
	OriginSessionID  string
	*ActionExecutionProvenance
	ProvenanceParentSessionID string
	GoalContextNudgeRatio     *float64
	UsageReporter             ActionUsageReporter
	PersistedTaskTokensUsed   int64
	GoalSegmentEpoch          int64
	AdmittedParams            dsl.NodeParams
}

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

func (ActionExecutionInput) ActorOrZero

func (in ActionExecutionInput) ActorOrZero() task.ActorContext

ActorOrZero returns the authenticated actor without copying it through each action helper.

func (ActionExecutionInput) EnvironmentValue

func (in ActionExecutionInput) EnvironmentValue() dsl.EnvironmentSpec

EnvironmentValue returns the action environment without exposing optional storage details.

func (ActionExecutionInput) RuntimeSelectionOrZero

func (in ActionExecutionInput) RuntimeSelectionOrZero() ActionRuntimeSelection

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

func (*ActionExecutionInput) SetOriginProvenance

func (in *ActionExecutionInput) SetOriginProvenance(profileRef string, policyDigest string, creationDigest string)

SetOriginProvenance replaces the optional immutable origin snapshot.

type ActionExecutionProvenance

type ActionExecutionProvenance struct {
	OriginCreationProfileRef string
	OriginPolicySpecDigest   string
	OriginCreationDigest     string
}

ActionExecutionProvenance keeps optional immutable origin digests compact.

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 ActionPromptDelivery

type ActionPromptDelivery string
const (
	ActionPromptDeliveryNormal      ActionPromptDelivery = ""
	ActionPromptDeliveryMaintenance ActionPromptDelivery = "maintenance"
)

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 {
	Delivery             ActionPromptDelivery
	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 {
	Compaction       *ActionCompactionOutcome
	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
	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) Harvest

func (r *ActionRegistry) Harvest(
	ctx context.Context,
	executor ActionExecutor,
	node dsl.Node,
	raw ActionRawResult,
) (ActionOutput, error)

Harvest applies the registry result policy without replacing the resolved executor.

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,
	resultView tools.ResultView,
) (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 WithActionDefaultMaxResultBytes

func WithActionDefaultMaxResultBytes(maxBytes int64) ActionRegistryOption

WithActionDefaultMaxResultBytes sets the configured outer result bound for Loop actions.

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 WithActionToolWorkspaceRootResolver

func WithActionToolWorkspaceRootResolver(resolver ActionToolWorkspaceRootResolver) ActionRegistryOption

WithActionToolWorkspaceRootResolver wires trusted workspace roots for registry-backed tool actions.

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 {
	GrantCeiling                   string
	ProfileID                      string
	WorkspaceID                    WorkspaceID
	LoopRunID                      RunID
	Generation                     int
	NodeID                         dsl.NodeID
	ItemIndex                      int
	Agent                          string
	Environment                    *dsl.EnvironmentSpec
	Handle                         string
	SharedKey                      string
	Mode                           string
	OriginSessionID                string
	ProvenanceParentSessionID      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
}

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

func (ActionSessionBindRequest) EnvironmentValue

func (r ActionSessionBindRequest) EnvironmentValue() dsl.EnvironmentSpec

EnvironmentValue returns the binding environment without exposing optional storage details.

func (ActionSessionBindRequest) RuntimeValue

func (r ActionSessionBindRequest) RuntimeValue() RuntimeSpec

RuntimeValue returns the requested runtime or the zero-value intent when none was supplied.

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
	RequestedRuntime   RuntimeSpec
	AppliedRuntime     RuntimeSpec
	SpeedResolution    *speedpkg.Resolution
}

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 ActionToolWorkspaceRootRequest

type ActionToolWorkspaceRootRequest struct {
	WorkspaceID WorkspaceID
	Environment dsl.EnvironmentSpec
}

ActionToolWorkspaceRootRequest identifies the effective workspace root for one tool action.

type ActionToolWorkspaceRootResolver

type ActionToolWorkspaceRootResolver interface {
	AcquireActionToolWorkspaceRoot(context.Context, ActionToolWorkspaceRootRequest) (string, func(), error)
}

ActionToolWorkspaceRootResolver resolves trusted roots outside the Loop package.

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 AmendInput

type AmendInput struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	Generation  int
	NodeID      NodeID
	ItemIndex   int
	Payload     json.RawMessage
	Schema      json.RawMessage
	Reason      string
	Actor       task.ActorContext
	RequestedAt time.Time
}

func (AmendInput) Validate

func (in AmendInput) Validate() error

type AmendmentStore

type AmendmentStore interface {
	AmendNodeOutput(context.Context, AmendInput) (NodeAmendment, error)
	ListNodeAmendments(context.Context, WorkspaceID, RunID) ([]NodeAmendment, error)
}

type AnnotationStore

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

AnnotationStore persists workspace-scoped loop editor sidecars.

type ArtifactAvailability

type ArtifactAvailability string

ArtifactAvailability states whether produced content can still be read.

const (
	ArtifactAvailable ArtifactAvailability = "available"
	ArtifactPartial   ArtifactAvailability = "partial"
	ArtifactPruned    ArtifactAvailability = "pruned"
)

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 Blocker

type Blocker struct {
	Kind         string     `json:"kind"`
	NodeID       NodeID     `json:"node_id,omitempty"`
	GateID       NodeID     `json:"gate_id,omitempty"`
	ItemIndex    int        `json:"item_index,omitzero"`
	WaitingSince time.Time  `json:"waiting_since"`
	ExpiresAt    *time.Time `json:"expires_at,omitempty"`
	Expired      bool       `json:"expired,omitzero"`
	Unblocker    string     `json:"unblocker"`
}

Blocker describes one ordered condition preventing progress and its exact unblocker.

type Briefing

type Briefing struct {
	RunID     RunID         `json:"run_id"`
	Status    Status        `json:"status"`
	Tone      BriefingTone  `json:"tone"`
	Headline  string        `json:"headline"`
	Detail    string        `json:"detail,omitempty"`
	Blockers  []Blocker     `json:"blockers"`
	Outcome   *RunOutcome   `json:"outcome,omitzero"`
	Artifacts []RunArtifact `json:"artifacts"`
	Progress  StepProgress  `json:"progress"`
	Usage     RunUsage      `json:"usage"`
}

Briefing is the server-owned verdict shared by UI, CLI, HTTP, UDS, and tools.

func ProjectBriefing

func ProjectBriefing(source *BriefingSource) Briefing

ProjectBriefing is the deterministic server-owned verdict projection.

type BriefingSource

type BriefingSource struct {
	Graph                dsl.Graph
	Outputs              []GenerationOutput
	Run                  Run
	Roster               RosterPage
	Requests             []Request
	Artifacts            []RunArtifact
	Outcome              *RunOutcome
	ApprovalWaitingSince time.Time
	Now                  time.Time
}

BriefingSource contains the durable facts required to project one briefing.

type BriefingTone

type BriefingTone string

BriefingTone classifies the run verdict for public read surfaces.

const (
	BriefingToneOK       BriefingTone = "ok"
	BriefingToneNeedsYou BriefingTone = "needs_you"
	BriefingToneDegraded BriefingTone = "degraded"
	BriefingToneFailed   BriefingTone = "failed"
)

type CancelState

type CancelState string

CancelState records terminal node cancellation provenance.

const (
	CancelStateNone     CancelState = ""
	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
	ItemIndex   *int
	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 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 {
	StopLoopSession(context.Context, string, string) error
}

CancellationSessionController performs the post-commit process stop.

type CancellationSessionControllerFuncs

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

CancellationSessionControllerFuncs adapts cancellation callbacks.

func (CancellationSessionControllerFuncs) StopLoopSession

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

StopLoopSession implements CancellationSessionController.

type CancellationStore

type CancellationStore interface {
	RequestRunCancellation(context.Context, CancellationMutation) (CancellationResult, error)
	RequestNodeCancellation(context.Context, CancellationMutation) (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 {
	AllWorkspaces bool
	WorkspaceIDs  []string
	WorkspaceID   string
	ProfileID     string
	ProfileName   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
	ProfileID      string
	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 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,omitzero"`
	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 CollectOutput

type CollectOutput struct {
	Total        int     `json:"total"`
	Succeeded    int     `json:"succeeded"`
	Failed       int     `json:"failed"`
	Canceled     int     `json:"canceled"`
	CoverageRate float64 `json:"coverage_rate"`
	Partial      bool    `json:"partial"`
}

CollectOutput is the stable coverage value produced by a strategy-aware collect cell.

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 CompletionState

type CompletionState string

CompletionState records whether a terminal run satisfied full or partial coverage.

const (
	CompletionComplete CompletionState = "complete"
	CompletionPartial  CompletionState = "partial"
)

func (CompletionState) Valid

func (s CompletionState) Valid() bool

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.

func WithCoordinatorWorktreeCandidateVerifier

func WithCoordinatorWorktreeCandidateVerifier(verifier WorktreeCandidateVerifier) CoordinatorRunnerOption

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, string) (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, profileID string, name string) (*ResolvedDefinition, error)
}

DefinitionResolver resolves a loop name to a compiled definition.

type DefinitionResolverFunc

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

DefinitionResolverFunc adapts a function to DefinitionResolver.

func (DefinitionResolverFunc) ResolveLoop

func (f DefinitionResolverFunc) ResolveLoop(
	ctx context.Context,
	ws WorkspaceID,
	profileID string,
	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,
		profileID string,
		loopName string,
	) (DefinitionState, error)
	RestoreLoopDefinitionState(
		ctx context.Context,
		ws WorkspaceID, profileID string,
		loopName string,
		state DefinitionState,
	) error
}

DefinitionStateStore owns atomic removal and restoration of definition sidecars.

type DiffEndpoint

type DiffEndpoint struct {
	RunID      RunID  `json:"run_id"`
	Generation int64  `json:"generation"`
	Status     Status `json:"status"`
	AsOf       bool   `json:"as_of,omitzero"`
}

type DiffInputRow

type DiffInputRow struct {
	Key     string    `json:"key"`
	Base    DiffValue `json:"base"`
	Against DiffValue `json:"against"`
}

type DiffNodeRow

type DiffNodeRow struct {
	NodeID    string    `json:"node_id"`
	ItemIndex int       `json:"item_index,omitzero"`
	Change    string    `json:"change"`
	Base      DiffValue `json:"base,omitzero"`
	Against   DiffValue `json:"against,omitzero"`
	Cause     string    `json:"cause,omitempty"`
}

type DiffQuery

type DiffQuery struct {
	RunID             RunID
	Generation        int64
	AgainstGeneration int64
	AgainstRunID      RunID
}

type DiffResult

type DiffResult struct {
	Kind                 string           `json:"kind"`
	Base                 DiffEndpoint     `json:"base"`
	Against              DiffEndpoint     `json:"against"`
	Inputs               []DiffInputRow   `json:"inputs"`
	Nodes                []DiffNodeRow    `json:"nodes"`
	Terminal             *DiffTerminalRow `json:"terminal,omitzero"`
	DefinitionDivergence bool             `json:"definition_divergence,omitzero"`
}

type DiffTerminalRow

type DiffTerminalRow struct {
	Base    Status `json:"base"`
	Against Status `json:"against"`
}

type DiffValue

type DiffValue struct {
	Inline json.RawMessage `json:"inline,omitempty"`
	Size   int             `json:"size,omitzero"`
	Hash   string          `json:"hash,omitempty"`
}

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 EffectiveChecksJSON

type EffectiveChecksJSON string

EffectiveChecksJSON stores immutable resolved check configuration compactly.

func (EffectiveChecksJSON) Bytes

Bytes returns the raw JSON representation expected by JSON consumers.

func (EffectiveChecksJSON) MarshalJSON

func (v EffectiveChecksJSON) MarshalJSON() ([]byte, error)

MarshalJSON preserves the raw-object wire contract.

func (*EffectiveChecksJSON) UnmarshalJSON

func (v *EffectiveChecksJSON) UnmarshalJSON(data []byte) error

UnmarshalJSON validates and stores one immutable raw JSON value.

type EffectiveConfig

type EffectiveConfig struct {
	HumanGateEnabled   bool                 `json:"human_gate_enabled"`
	ReattemptStrategy  ReattemptStrategy    `json:"reattempt_strategy"`
	EnabledChecks      *EffectiveChecksJSON `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"`
	Environment        dsl.EnvironmentSpec  `json:"environment"`
	Lifecycle          LifecycleConfig      `json:"lifecycle"`
	RequestExpireAfter string               `json:"request_expire_after"`
	Sources            map[string]string    `json:"sources,omitempty"`
}

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 FanoutRollup

type FanoutRollup struct {
	Generation int    `json:"generation"`
	NodeID     NodeID `json:"node_id"`
	Done       int    `json:"done"`
	Total      int    `json:"total"`
	Failed     int    `json:"failed"`
}

type ForkInput

type ForkInput struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	Generation  int64
	Inputs      map[string]any
	Reason      string
	RequestID   string
	Actor       task.ActorContext
}

type ForkRef

type ForkRef struct {
	RunID      RunID `json:"run_id"`
	Generation int64 `json:"generation"`
}

type ForkStoreRequest

type ForkStoreRequest struct {
	Source         *Run
	Child          *Run
	SeedOutputs    []GenerationOutput
	Concurrency    dsl.ConcurrencyPolicy
	Operation      TimeTravelOp
	RequestDigest  string
	IdempotencyKey string
	At             time.Time
}

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,omitzero"`
	Route           gate.RouteAction             `json:"route,omitempty"`
	Reason          string                       `json:"reason,omitempty"`
	BestGeneration  *int64                       `json:"best_generation,omitzero"`
	NodeID          string                       `json:"node_id,omitempty"`
	Attempt         int                          `json:"attempt,omitzero"`
	IssuedEpoch     int64                        `json:"issued_epoch,omitzero"`
	NextAttemptAt   *time.Time                   `json:"next_attempt_at,omitempty"`
	FailureClass    FailureClass                 `json:"failure_class,omitempty"`
	Failure         *ClassifiedFailure           `json:"failure,omitzero"`
	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"`
	Predicate               string                 `json:"predicate,omitempty"`
	DiagnosticCode          string                 `json:"diagnostic_code,omitempty"`
	Cost                    uint64                 `json:"cost,omitzero"`
	CostLimit               uint64                 `json:"cost_limit,omitzero"`
	Warning                 bool                   `json:"warning,omitzero"`
	SelectedRoute           string                 `json:"selected_route,omitempty"`
	MatchedWhen             string                 `json:"matched_when,omitempty"`
	DefaultRoute            bool                   `json:"default_route,omitzero"`
	ItemIndexes             []int                  `json:"item_indexes,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"
	// GenerationLifecycleEventPredicateDiagnostic records predicate cost or evaluation diagnostics.
	GenerationLifecycleEventPredicateDiagnostic GenerationLifecycleEventKind = "predicate_diagnostic"
	// GenerationLifecycleEventRouteTaken records one exclusive routing decision.
	GenerationLifecycleEventRouteTaken GenerationLifecycleEventKind = "route_taken"
	// GenerationLifecycleEventBranchPruned records one bounded strategy-cancel aggregate.
	GenerationLifecycleEventBranchPruned GenerationLifecycleEventKind = "branch_pruned"
)

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"
	OriginOperatorRerun      GenerationOrigin = "operator_rerun"
	OriginForkSeed           GenerationOrigin = "fork_seed"
)

type GenerationOutput

type GenerationOutput struct {
	Generation       int              `json:"generation,omitzero"`
	NodeID           string           `json:"node_id"`
	ItemIndex        int              `json:"item_index,omitzero"`
	OutputID         string           `json:"output_id,omitempty"`
	ArtifactName     string           `json:"artifact_name,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,omitzero"`
	Attempt          int              `json:"attempt,omitzero"`
	NextAttemptAt    *time.Time       `json:"next_attempt_at,omitempty"`
	FirstScheduledAt *time.Time       `json:"first_scheduled_at,omitempty"`
	Epoch            int64            `json:"epoch,omitzero"`
	// 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:"-"`
	// TaskRunStatus is the current task-run lifecycle state joined by the
	// roster read model; it is never part of snapshot state.
	TaskRunStatus task.RunStatus `json:"-"`
	// TaskRunTokensUsed is the task run's retained cumulative usage joined by
	// the roster read model; it is never part of snapshot state.
	TaskRunTokensUsed int64 `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,omitzero"`
	// 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 GenerationOutputOverlayReader

type GenerationOutputOverlayReader interface {
	ApplyGenerationOutputOverlays(
		context.Context,
		WorkspaceID,
		RunID,
		int,
		[]GenerationOutput,
	) ([]GenerationOutput, error)
}

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"`
	Requests              []RequestIntent                   `json:"requests,omitempty"`
	StrategyCancellations []StrategyCancellationIntent      `json:"strategy_cancellations,omitempty"`
	OutputBlobs           []GenerationOutputBlob            `json:"output_blobs,omitempty"`
	Verdicts              []gate.VerdictIntent              `json:"verdicts,omitempty"`
	BestUpdate            *gate.BestUpdateIntent            `json:"best_update,omitzero"`
	GenerationProvenance  *GenerationIntent                 `json:"generation_provenance,omitzero"`
	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 GoalPauseStore

type GoalPauseStore interface {
	RequestGoalPause(context.Context, WorkspaceID, RunID, task.ActorContext) ([]GoalPromptLease, error)
}

GoalPauseStore persists pause intent before identifying the exact work to interrupt.

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 InputDefaultLayers

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

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

type InputDefaultsResolver

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

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

type InputEntityCatalog

type InputEntityCatalog interface {
	HasInputEntity(context.Context, WorkspaceID, string, dsl.EntityKind, string) (bool, error)
}

InputEntityCatalog is the daemon-owned authority for exact entity lookups.

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"
	InputOriginAutomation InputOrigin = "automation"
	InputOriginResponse   InputOrigin = "response"
)

type InputValidationError

type InputValidationError struct {
	Loop   string                `json:"loop"`
	Field  string                `json:"field"`
	Kind   string                `json:"kind,omitempty"`
	Value  string                `json:"value,omitempty"`
	Origin InputOrigin           `json:"origin"`
	Reason InputValidationReason `json:"reason"`
	Err    error                 `json:"-"`
}

InputValidationError carries one field-addressed Loop input failure.

func AsInputValidationError

func AsInputValidationError(err error) (*InputValidationError, bool)

AsInputValidationError extracts the structured input diagnostic.

func (*InputValidationError) Error

func (e *InputValidationError) Error() string

func (*InputValidationError) Unwrap

func (e *InputValidationError) Unwrap() error

Unwrap keeps input failures in the Loop validation family.

type InputValidationReason

type InputValidationReason string

InputValidationReason is the closed machine-readable input failure vocabulary.

const (
	InputValidationReasonUnknownInput       InputValidationReason = "unknown_input"
	InputValidationReasonRequired           InputValidationReason = "required"
	InputValidationReasonTypeMismatch       InputValidationReason = "type_mismatch"
	InputValidationReasonEnumMismatch       InputValidationReason = "enum_mismatch"
	InputValidationReasonInvalidKindPayload InputValidationReason = "invalid_kind_payload"
	InputValidationReasonUnknownReference   InputValidationReason = "unknown_reference"
	InputValidationReasonInvalidRuntime     InputValidationReason = "invalid_runtime"
)

type Inputs

type Inputs struct {
	ProfileID            string               `json:"-"`
	Values               map[string]any       `json:"values,omitempty"`
	ParentLoopRunID      RunID                `json:"parent_loop_run_id,omitempty"`
	ConfigOverrides      LoopConfig           `json:"config_overrides"`
	InheritedEnvironment *dsl.EnvironmentSpec `json:"-"`
	StartMetadata        map[string]any       `json:"start_metadata,omitempty"`
	Admission            *AdmissionIdentity   `json:"-"`
}

Inputs carries user inputs plus runtime-only start metadata.

type InvalidNodeStateError

type InvalidNodeStateError struct {
	State   NodeStateFilter
	Allowed []string
}

func (*InvalidNodeStateError) Error

func (e *InvalidNodeStateError) Error() string

func (*InvalidNodeStateError) Unwrap

func (e *InvalidNodeStateError) Unwrap() error

type ItemRuntime

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

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

func ItemRuntimeFromNamespace

func ItemRuntimeFromNamespace(
	namespace map[string]any,
	params dsl.NodeParams,
	materialized RuntimeSpec,
) (ItemRuntime, error)

ItemRuntimeFromNamespace extracts runtime-selection metadata and the authored node/input layer.

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"`
	Path     string       `json:"path,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,omitzero"   yaml:"human_gate_enabled,omitempty"`
	ReattemptStrategy  *ReattemptStrategy   `json:"reattempt_strategy,omitzero"   yaml:"reattempt_strategy,omitempty"`
	EnabledChecks      json.RawMessage      `json:"enabled_checks_json,omitempty" yaml:"enabled_checks_json,omitempty"`
	IterationCap       *int                 `json:"iteration_cap,omitzero"        yaml:"iteration_cap,omitempty"`
	BudgetTokens       *int                 `json:"budget_tokens,omitzero"        yaml:"budget_tokens,omitempty"`
	BudgetWallSec      *int                 `json:"budget_wall_sec,omitzero"      yaml:"budget_wall_sec,omitempty"`
	BudgetOnExceeded   *dsl.BudgetExceeded  `json:"budget_on_exceeded,omitzero"   yaml:"budget_on_exceeded,omitempty"`
	NoProgressWindow   *int                 `json:"no_progress_window,omitzero"   yaml:"no_progress_window,omitempty"`
	FanOutWidth        *int                 `json:"fan_out_width,omitzero"        yaml:"fan_out_width,omitempty"`
	GateMaxRevisions   *int                 `json:"gate_max_revisions,omitzero"   yaml:"gate_max_revisions,omitempty"`
	RuntimeDefaults    *RuntimeDefaults     `json:"runtime_defaults,omitzero"     yaml:"runtime_defaults,omitempty"`
	RuntimeRules       []RuntimeRule        `json:"runtime_rules,omitempty"       yaml:"runtime_rules,omitempty"`
	Environment        *dsl.EnvironmentSpec `json:"environment,omitzero"          yaml:"environment,omitempty"`
	Lifecycle          *LifecycleConfig     `json:"lifecycle,omitzero"            yaml:"lifecycle,omitempty"`
	RequestExpireAfter *string              `json:"request_expire_after,omitzero" yaml:"request_expire_after,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 NodeAmendment

type NodeAmendment struct {
	WorkspaceID WorkspaceID
	LoopRunID   RunID
	Generation  int
	NodeID      NodeID
	ItemIndex   int
	Sequence    int
	OriginalRef string
	AmendedRef  string
	Original    json.RawMessage
	Amended     json.RawMessage
	ActorKind   string
	ActorID     string
	Reason      string
	CreatedAt   time.Time
}

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,omitzero"`
	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 NodeAttemptView

type NodeAttemptView struct {
	Attempt      int        `json:"attempt"`
	State        NodeState  `json:"state"`
	FailureClass string     `json:"failure_class,omitempty"`
	Disposition  string     `json:"disposition"`
	StartedAt    time.Time  `json:"started_at"`
	EndedAt      *time.Time `json:"ended_at,omitempty"`
}

type NodeCancellation

type NodeCancellation struct {
	Disposition string `json:"disposition"`
	ActorKind   string `json:"actor_kind,omitempty"`
	ActorRef    string `json:"actor_ref,omitempty"`
	Cause       string `json:"cause,omitempty"`
}

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
	GateRevisions           map[int]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,omitzero"`
	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"`
	GateRevisions           map[int]int `json:"gate_revisions,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"
	NodeControlMutationGateRevision NodeControlMutationKind = "gate_revision"
)

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 {
	AllWorkspaces bool               `json:"all_workspaces"`
	ReadScope     store.ReadScope    `json:"read_scope"`
	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 {
	WorkspaceID string
	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 {
	AllWorkspaces bool
	ReadScope     store.ReadScope
	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
	ItemIndex        *int
	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
	Workers     []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
	ItemIndex        *int
	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 NodeState

type NodeState string

NodeState is the closed public roster state vocabulary.

const (
	NodeStatePending        NodeState = "pending"
	NodeStateQueued         NodeState = "queued"
	NodeStateRunning        NodeState = "running"
	NodeStateRetrying       NodeState = "retrying"
	NodeStateWaiting        NodeState = "waiting"
	NodeStatePaused         NodeState = "paused"
	NodeStateAwaitingChild  NodeState = "awaiting_child"
	NodeStateControlPending NodeState = "control_pending"
	NodeStateAwaitingGoal   NodeState = "awaiting_goal"
	NodeStateSucceeded      NodeState = "succeeded"
	NodeStatePartial        NodeState = "partial"
	NodeStateFailed         NodeState = "failed"
	NodeStateCanceled       NodeState = "canceled"
	NodeStateQuarantined    NodeState = "quarantined"
	NodeStateNotTaken       NodeState = "not_taken"
)

type NodeStateFilter

type NodeStateFilter string

NodeStateFilter is the deliberately narrower CLI/HTTP filter vocabulary.

const NodeStateFilterAll NodeStateFilter = "all"

type NodeUsage

type NodeUsage struct {
	Tokens int64 `json:"tokens"`
}

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,omitzero"`
	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 WithCancellationConcurrency

func WithCancellationConcurrency(limit int) Option

WithCancellationConcurrency bounds concurrent post-commit session stops.

func WithCancellationSessionController

func WithCancellationSessionController(controller CancellationSessionController) Option

WithCancellationSessionController injects post-commit 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 WithInputEntityCatalog

func WithInputEntityCatalog(catalog InputEntityCatalog) Option

WithInputEntityCatalog injects workspace-aware exact entity lookup authority.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger injects structured observability for post-commit service failures.

func WithResponderPolicy

func WithResponderPolicy(policy ResponderPolicy) Option

WithResponderPolicy injects the daemon-owned initiator-lineage policy.

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.

func WithWorkerRunActivator

func WithWorkerRunActivator(activator WorkerRunActivator) Option

WithWorkerRunActivator injects the post-commit activation path for Loop workers.

type OutputBlobAvailabilityReader

type OutputBlobAvailabilityReader interface {
	ListAvailableLoopOutputRefs(
		context.Context,
		WorkspaceID,
		RunID,
	) (map[string]bool, error)
}

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
	ProfileID     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,omitzero"`
	Diagnostic *PayloadDiagnostic `json:"diagnostic,omitzero"`
}

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 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"`
}

PlanPreview is the no-state preview returned by DryRun.

type PredicateDiagnostic

type PredicateDiagnostic struct {
	Code      string               `json:"code"`
	Predicate string               `json:"predicate"`
	Cause     string               `json:"cause,omitempty"`
	Outcome   PredicateErrorPolicy `json:"outcome,omitempty"`
	Cost      uint64               `json:"cost,omitzero"`
	CostLimit uint64               `json:"cost_limit,omitzero"`
	Warning   bool                 `json:"warning,omitzero"`
}

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,omitzero"`
}

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"
	// ReasonCodeInvalidOutput reports run-agent output_schema validation failure.
	ReasonCodeInvalidOutput ReasonCode = "invalid_output"
	// ReasonCodeActionMaterializationFailed reports an authored value that could not be materialized.
	ReasonCodeActionMaterializationFailed ReasonCode = "action_materialization_failed"
	// 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"
	// ReasonCodeActionResultTooLarge reports an action tool result above its effective byte limit.
	ReasonCodeActionResultTooLarge ReasonCode = "action_result_too_large"
)
const (
	ReasonCodeAmendNotParked     ReasonCode = "amend_not_parked"
	ReasonCodeAmendNoOutput      ReasonCode = "amend_no_output"
	ReasonCodeAmendSchemaMissing ReasonCode = "amend_schema_missing"
)
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 (
	ReasonCodeGoalWaitDeferred         ReasonCode = "goal_wait_deferred"
	ReasonCodeGoalWaitTimeout          ReasonCode = "goal_wait_timeout"
	ReasonCodeGoalWaitUnavailable      ReasonCode = "goal_wait_unavailable"
	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"
)
const (
	ReasonCodeRequestNotFound         ReasonCode = "request_not_found"
	ReasonCodeRequestValidationFailed ReasonCode = "request_validation_failed"
	ReasonCodeRequestAlreadyAnswered  ReasonCode = "request_already_answered"
	ReasonCodeRequestExpired          ReasonCode = "request_expired"
	ReasonCodeRequestCanceled         ReasonCode = "request_canceled"
	ReasonCodeRespondNotPermitted     ReasonCode = "respond_not_permitted"
	ReasonCodeRespondSelfDenied       ReasonCode = "respond_self_denied"
)
const (
	ReasonCodeRerunBusy             ReasonCode = "rerun_busy"
	ReasonCodeRerunNodeUnsettled    ReasonCode = "rerun_node_unsettled"
	ReasonCodeTimeTravelKeyReuse    ReasonCode = "timetravel_key_reuse"
	ReasonCodeForkGenerationUnknown ReasonCode = "fork_generation_unknown"
	ReasonCodeDiffCrossLoop         ReasonCode = "diff_cross_loop"
	ReasonCodeTimeTravelSelfDenied  ReasonCode = "timetravel_self_denied"
)

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"
	// ReattemptHalt leaves the failed generation terminal until an explicit rerun.
	ReattemptHalt ReattemptStrategy = "halt"
)

type ReconciliationStore

type ReconciliationStore interface {
	NeutralizeLoopRunOrphans(context.Context) (SweepReport, error)
	SweepLoopRunOrphans(context.Context) (SweepReport, error)
	BackfillLoopProvenance(context.Context) (int, error)
}

ReconciliationStore owns durable reconciliation writes.

type RenderedEffectIntent

type RenderedEffectIntent struct {
	Trigger    EffectTrigger   `json:"trigger"`
	Generation int             `json:"generation"`
	NodeID     NodeID          `json:"node_id,omitempty"`
	ItemIndex  int             `json:"item_index,omitzero"`
	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 Request

type Request struct {
	WorkspaceID      string                   `json:"workspace_id"`
	ProfileID        string                   `json:"profile_id"`
	LoopRunID        RunID                    `json:"loop_run_id"`
	LoopName         string                   `json:"loop_name,omitempty"`
	Generation       int                      `json:"generation"`
	NodeID           NodeID                   `json:"node_id"`
	ItemIndex        int                      `json:"item_index"`
	Kind             string                   `json:"kind"`
	State            string                   `json:"state"`
	Prompt           string                   `json:"prompt"`
	Context          json.RawMessage          `json:"context"`
	Expect           json.RawMessage          `json:"expect"`
	EditSchema       json.RawMessage          `json:"edit_schema,omitempty"`
	RespondSchema    json.RawMessage          `json:"respond_schema,omitempty"`
	ProposedPreview  json.RawMessage          `json:"proposed_preview,omitempty"`
	Decisions        []string                 `json:"decisions"`
	Agents           dsl.ResponderAgentPolicy `json:"agents"`
	AnsweredDecision string                   `json:"answered_decision,omitempty"`
	ActorKind        string                   `json:"actor_kind,omitempty"`
	ActorID          string                   `json:"actor_id,omitempty"`
	OpenedAt         time.Time                `json:"opened_at"`
	ResolvedAt       *time.Time               `json:"resolved_at,omitempty"`
	ExpiresAt        *time.Time               `json:"expires_at,omitempty"`
}

Request is the public redaction-safe request projection.

type RequestDetail

type RequestDetail = Request

type RequestIntent

type RequestIntent struct {
	WorkspaceID     WorkspaceID              `json:"workspace_id"`
	NodeID          NodeID                   `json:"node_id"`
	ItemIndex       int                      `json:"item_index,omitzero"`
	Kind            string                   `json:"kind"`
	Prompt          string                   `json:"prompt"`
	Context         json.RawMessage          `json:"context"`
	ContextPreview  json.RawMessage          `json:"context_preview"`
	AnswerSchema    json.RawMessage          `json:"answer_schema"`
	EditSchema      json.RawMessage          `json:"edit_schema,omitempty"`
	RespondSchema   json.RawMessage          `json:"respond_schema,omitempty"`
	Decisions       json.RawMessage          `json:"decisions"`
	Proposed        json.RawMessage          `json:"proposed,omitempty"`
	ProposedPreview json.RawMessage          `json:"proposed_preview,omitempty"`
	Agents          dsl.ResponderAgentPolicy `json:"agents"`
	ExpiresAt       *time.Time               `json:"expires_at,omitempty"`
	IssuedEpoch     int64                    `json:"issued_epoch"`
	OpenedAt        time.Time                `json:"opened_at"`
}

RequestIntent persists one request-shaped read model beside its authoritative wait.

type RequestPage

type RequestPage struct {
	Items      []Request `json:"items"`
	Pending    int       `json:"-"`
	NextCursor string    `json:"next_cursor"`
}

type RequestQuery

type RequestQuery struct {
	AllWorkspaces bool
	WorkspaceIDs  []string
	ReadScope     store.ReadScope
	RunID         RunID
	State         string
	Cursor        string
	Limit         int
}

type RequestRef

type RequestRef struct {
	RunID      RunID
	Generation int
	NodeID     NodeID
	ItemIndex  int
}

RequestRef identifies one request cell.

type RequestStore

type RequestStore interface {
	ListRequests(context.Context, WorkspaceID, RequestQuery) (RequestPage, error)
	GetRequest(context.Context, WorkspaceID, RequestRef, bool) (Request, error)
	RespondRequest(context.Context, RespondInput) (RespondResult, error)
}

type RerunInput

type RerunInput struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	FromNode    NodeID
	ItemIndex   *int
	Reason      string
	RequestID   string
	Actor       task.ActorContext
}

type RerunResult

type RerunResult struct {
	RunID            RunID    `json:"run_id"`
	Generation       int64    `json:"generation"`
	ParentGeneration int64    `json:"parent_generation"`
	RerunNodes       []string `json:"rerun_nodes"`
	Carried          int      `json:"carried"`
	Replayed         bool     `json:"replayed,omitzero"`
}

type RerunStoreRequest

type RerunStoreRequest struct {
	WorkspaceID    WorkspaceID
	Source         *Run
	NextOutputs    []GenerationOutput
	Intent         GenerationIntent
	Operation      TimeTravelOp
	RequestDigest  string
	IdempotencyKey string
	At             time.Time
}

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
	// InstalledFromExtension is daemon-owned resource provenance, never authored Loop YAML.
	InstalledFromExtension string
	// ExtensionOwner is the daemon-owned canonical manifest identity used for policy grants.
	ExtensionOwner       string
	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,omitzero"`
	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"`
	// SpeedResolution is the confirmed ACP outcome for Runtime.Speed.
	SpeedResolution *speedpkg.Resolution `json:"speed_resolution,omitzero"`
}

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 ResourceLens

type ResourceLens struct {
	WorkspaceID string
	ProfileID   string
	ProfileName string
}

ResourceLens selects the four resource layers visible to one active profile inside one workspace.

func (ResourceLens) Normalize

func (l ResourceLens) Normalize() ResourceLens

Normalize returns the canonical resource selection lens.

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,omitzero"`
	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"`
	// ExtensionOwner is daemon-owned canonical manifest identity, never authored Loop YAML.
	ExtensionOwner string `json:"extension_owner,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 RespondInput

type RespondInput struct {
	WorkspaceID WorkspaceID
	RunID       RunID
	Generation  int
	NodeID      NodeID
	ItemIndex   int
	Decision    string
	Payload     json.RawMessage
	Note        string
	Actor       task.ActorContext
	RequestKind string
	RejectRoute NodeID
}

type RespondResult

type RespondResult struct {
	Request     Request   `json:"request"`
	Coordinator *task.Run `json:"-"`
	Won         bool      `json:"won"`
}

type ResponderPolicy

type ResponderPolicy interface {
	DeniesSelfOperation(
		ctx context.Context,
		workspaceID string,
		runID string,
		actor task.ActorContext,
	) (bool, error)
}

ResponderPolicy is the daemon-owned trust boundary for self-operation rules.

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 RosterBulkReader

type RosterBulkReader interface {
	ListLoopRosterOutputs(context.Context, WorkspaceID, RunID) ([]GenerationOutput, error)
	ListLoopRosterRouteCauses(context.Context, WorkspaceID, RunID) ([]RouteCause, error)
}

type RosterNode

type RosterNode struct {
	Generation     int               `json:"generation"`
	NodeID         NodeID            `json:"node_id"`
	ItemIndex      int               `json:"item_index"`
	State          NodeState         `json:"state"`
	Attempt        int               `json:"attempt"`
	Attempts       []NodeAttemptView `json:"attempts"`
	NextRetryAt    *time.Time        `json:"next_retry_at,omitempty"`
	ChildLoopRunID string            `json:"child_loop_run_id,omitempty"`
	Cancellation   *NodeCancellation `json:"cancellation,omitzero"`
	StartedAt      *time.Time        `json:"started_at,omitempty"`
	EndedAt        *time.Time        `json:"ended_at,omitempty"`
	SessionID      string            `json:"session_id,omitempty"`
	CellTaskID     string            `json:"cell_task_id,omitempty"`
	Usage          *NodeUsage        `json:"usage,omitzero"`
	Action         bool              `json:"-"`
}

type RosterPage

type RosterPage struct {
	RunID         RunID          `json:"run_id"`
	LoopName      string         `json:"loop_name"`
	RunStatus     Status         `json:"run_status"`
	Nodes         []RosterNode   `json:"nodes"`
	FanoutRollups []FanoutRollup `json:"fanout_rollups"`
	NextCursor    string         `json:"next_cursor,omitempty"`
}

func ProjectRoster

func ProjectRoster(source *RosterSource, query RosterQuery) (RosterPage, error)

ProjectRoster computes the complete node-generation roster without writes.

type RosterQuery

type RosterQuery struct {
	State      NodeStateFilter
	Generation int
	Cursor     string
	Limit      int
}

type RosterSource

type RosterSource struct {
	Run         Run
	Graph       dsl.Graph
	Generations []LoopGeneration
	Outputs     []GenerationOutput
	Attempts    []NodeAttempt
	Controls    []NodeControl
	Waits       []NodeWait
	RouteCauses []RouteCause
	PrunedNodes map[string]bool
	Outcome     *RunOutcome
}

func (*RosterSource) MarkPrunedNodeItem

func (s *RosterSource) MarkPrunedNodeItem(generation int, nodeID NodeID, itemIndex int) error

MarkPrunedNodeItem adds exact durable branch-pruning evidence to a roster source.

type RouteCause

type RouteCause struct {
	Generation  int64
	NodeID      NodeID
	ItemIndex   int
	Route       NodeID
	Cause       string
	MatchedWhen string
	Default     bool
	At          time.Time
}

RouteCause is one workspace-scoped route_taken projection.

type RouteCauseReader

type RouteCauseReader interface {
	ListRouteCauses(
		ctx context.Context,
		workspaceID WorkspaceID,
		runID RunID,
		generation int64,
	) ([]RouteCause, error)
}

RouteCauseReader loads durable route decisions for one generation.

type Run

type Run struct {
	ID                    RunID
	ProfileID             string
	WorkspaceID           WorkspaceID
	LoopName              string
	Status                Status
	Generation            int
	BestGeneration        *int64
	BestScore             *float64
	ReattemptStrategy     ReattemptStrategy
	CreatedAt             time.Time
	StartedAt             time.Time
	LastProgressAt        time.Time
	CompletedAt           *time.Time
	StartedBy             task.ActorIdentity
	StartedOrigin         task.Origin
	DefinitionVersion     int
	DefinitionDigest      string
	DefinitionSnapshot    json.RawMessage
	ActiveGateID          NodeID
	BudgetApprovalSeq     int
	StartMetadata         map[string]any
	IterationCap          int
	BudgetTokens          int
	BudgetWallSec         int
	BudgetOnExceeded      dsl.BudgetExceeded
	TokensUsed            int64
	ParentLoopRunID       RunID
	Historical            bool
	PauseRequested        bool
	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) ActiveHumanCriteriaValue

func (r Run) ActiveHumanCriteriaValue() json.RawMessage

ActiveHumanCriteriaValue returns a cloned view of the active human criteria.

func (Run) CompletionStateSnapshot

func (r Run) CompletionStateSnapshot() CompletionState

CompletionStateSnapshot returns the persisted coverage state.

func (Run) ForkedFromSnapshot

func (r Run) ForkedFromSnapshot() *ForkRef

ForkedFromSnapshot returns a defensive copy of the source lineage.

func (Run) ForksSnapshot

func (r Run) ForksSnapshot() []ForkRef

ForksSnapshot returns a defensive copy of child lineage.

func (Run) GrantCeilingSnapshot

func (r Run) GrantCeilingSnapshot() string

GrantCeilingSnapshot returns the workspace-access ceiling the run was authored under.

func (*Run) SetActiveHumanCriteria

func (r *Run) SetActiveHumanCriteria(criteria json.RawMessage)

SetActiveHumanCriteria replaces the active human criteria with an isolated copy.

func (*Run) SetAdmission

func (r *Run) SetAdmission(identity AdmissionIdentity)

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

func (*Run) SetCompletionState

func (r *Run) SetCompletionState(state CompletionState)

SetCompletionState replaces the persisted coverage state.

func (*Run) SetForkedFrom

func (r *Run) SetForkedFrom(source *ForkRef)

SetForkedFrom replaces the source lineage.

func (*Run) SetForks

func (r *Run) SetForks(forks []ForkRef)

SetForks replaces the child-lineage projection.

func (*Run) SetGrantCeiling

func (r *Run) SetGrantCeiling(ceiling string)

SetGrantCeiling replaces the workspace-access ceiling the run was authored under.

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 RunArtifact

type RunArtifact struct {
	Name         string               `json:"name"`
	Output       string               `json:"output,omitempty"`
	Ref          string               `json:"ref,omitempty"`
	Availability ArtifactAvailability `json:"availability"`
}

RunArtifact identifies one logical output and its content reference.

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 RunEventBackwardQuery

type RunEventBackwardQuery struct {
	WorkspaceID  WorkspaceID
	RunID        RunID
	FixedHeadSeq int64
	BeforeSeq    int64
	Limit        int
}

RunEventBackwardQuery identifies one snapshot-fenced reverse event page.

type RunEventKind

type RunEventKind string
const (
	RunEventNodeRunning          RunEventKind = "node_running"
	RunEventNodeSucceeded        RunEventKind = "node_succeeded"
	RunEventNodeFailed           RunEventKind = "node_failed"
	RunEventGateVerdict          RunEventKind = "gate_verdict"
	RunEventGenerationStarted    RunEventKind = "generation_started"
	RunEventTokenTick            RunEventKind = "token_tick"
	RunEventNeedsApproval        RunEventKind = "needs_approval"
	RunEventStatusChanged        RunEventKind = "status_changed"
	RunEventGoalTurnStarted      RunEventKind = "goal_turn_started"
	RunEventGoalTurnCompleted    RunEventKind = "goal_turn_completed"
	RunEventGoalStatusChanged    RunEventKind = "goal_status_changed"
	RunEventRuntimeApplied       RunEventKind = "runtime_applied"
	RunEventPredicateDiagnostic  RunEventKind = "predicate_diagnostic"
	RunEventRouteTaken           RunEventKind = "route_taken"
	RunEventNodeRetryScheduled   RunEventKind = "node_retry_scheduled"
	RunEventNodePaused           RunEventKind = "node_paused"
	RunEventNodeResumed          RunEventKind = "node_resumed"
	RunEventNodeCanceled         RunEventKind = "node_canceled"
	RunEventNodeQuarantined      RunEventKind = "node_quarantined"
	RunEventNodeRequeued         RunEventKind = "node_requeued"
	RunEventNodeWaitStarted      RunEventKind = "node_wait_started"
	RunEventNodeWaitResumed      RunEventKind = "node_wait_resumed"
	RunEventNodeAttentionFlagged RunEventKind = "node_attention_flagged"
	RunEventNodeAttentionCleared RunEventKind = "node_attention_cleared"
	RunEventEffectResults        RunEventKind = "effect_results"
	RunEventCustomEvent          RunEventKind = "custom_event"
	RunEventDuplicateSuppressed  RunEventKind = "duplicate_suppressed"
	RunEventTargetBreaker        RunEventKind = "target_breaker_transition"
	RunEventStaleScheduleDropped RunEventKind = "stale_schedule_dropped"
	RunEventLateArrival          RunEventKind = "late_arrival"
	RunEventRequestOpened        RunEventKind = "request_opened"
	RunEventRequestAnswered      RunEventKind = "request_answered"
	RunEventRequestExpired       RunEventKind = "request_expired"
	RunEventRequestCanceled      RunEventKind = "request_canceled"
	RunEventNodeAmended          RunEventKind = "node_amended"
	RunEventBranchPruned         RunEventKind = "branch_pruned"
	RunEventRunForked            RunEventKind = "run_forked"
)

type RunEventQuery

type RunEventQuery struct {
	ReadScope   store.ReadScope
	WorkspaceID WorkspaceID
	RunID       RunID
	AfterSeq    int64
	Limit       int
}

RunEventQuery filters retained loop run events.

type RunHistoryBest

type RunHistoryBest struct {
	Generation int64
	Score      float64
}

RunHistoryBest carries the ratchet state a finished run settled on.

type RunHistoryEvent

type RunHistoryEvent struct {
	Kind    RunEventKind
	Payload any
	At      time.Time
}

RunHistoryEvent is one already-emitted run event replayed by a history import.

type RunHistoryGeneration

type RunHistoryGeneration struct {
	Intent      GenerationIntent
	CreatedAt   time.Time
	Outputs     []GenerationOutput
	OutputBlobs []GenerationOutputBlob
	Attempts    []NodeAttempt
	Controls    []NodeControlMutation
	Waits       []NodeWaitIntent
	Requests    []RequestIntent
	Verdicts    []RunHistoryVerdict
}

RunHistoryGeneration is the already-settled state of one generation.

type RunHistoryGoalTurn

type RunHistoryGoalTurn struct {
	Seq             int64
	Generation      int
	NodeID          NodeID
	ItemIndex       int
	Turn            int
	SessionID       string
	BindingHandle   string
	BindingEpoch    int64
	PromptID        string
	PromptAttempt   int
	UsageBaseTokens int64
	StopReason      ActionStopReason
	VerdictOutcome  gate.VerdictOutcome
	BlockingIssues  json.RawMessage
	Criteria        json.RawMessage
	Warnings        json.RawMessage
	EvidenceRef     string
	PromptRef       string
	TokensUsed      int64
	ActorKind       string
	ActorID         string
	StartedAt       time.Time
	EndedAt         time.Time
}

RunHistoryGoalTurn is one completed Goal turn replayed as immutable audit history.

type RunHistoryImport

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

RunHistoryImport is the explicit bootstrap-only boundary for one already-executed historical Loop run. Runtime execution must go through the coordinator instead.

func NewRunHistoryImport

func NewRunHistoryImport(snapshot *RunHistorySnapshot) (RunHistoryImport, error)

NewRunHistoryImport validates and isolates one executed run ledger before persistence.

func (*RunHistoryImport) Actor

func (i *RunHistoryImport) Actor() task.ActorContext

Actor reports the authority responsible for the import.

func (*RunHistoryImport) Snapshot

func (i *RunHistoryImport) Snapshot() RunHistorySnapshot

Snapshot reports an isolated copy of the validated ledger.

type RunHistorySnapshot

type RunHistorySnapshot struct {
	Run         Run
	Generations []RunHistoryGeneration
	Decisions   []GateDecisionRecord
	Events      []RunHistoryEvent
	GoalTurns   []RunHistoryGoalTurn
	Best        *RunHistoryBest
	Actor       task.ActorContext
}

RunHistorySnapshot is the caller-authored ledger of one already-executed run.

type RunHistoryVerdict

type RunHistoryVerdict struct {
	Generation int
	Intent     gate.VerdictIntent
	DecidedAt  time.Time
}

RunHistoryVerdict pairs one machine gate verdict with the moment it was decided.

type RunID

type RunID string

RunID is the durable loop_runs primary key.

type RunListAttention

type RunListAttention struct {
	Kind  string
	Count int
	Since time.Time
}

type RunListPosition

type RunListPosition struct {
	Rank      int
	CreatedAt time.Time
	ID        RunID
}

RunListPosition identifies one run by operational rank, creation time, and ID.

type RunListQuery

type RunListQuery struct {
	AllWorkspaces    bool
	WorkspaceIDs     []string
	ReadScope        store.ReadScope
	WorkspaceID      WorkspaceID
	LoopName         string
	Status           Status
	OriginKind       string
	OriginSessionID  string
	Live             *bool
	Limit            int
	CreatedAfter     time.Time
	OperationalOrder bool
	// After resumes operational ordering and must come from the same active filters.
	After *RunListPosition
}

RunListQuery filters loop run listings within one explicit profile read lens and workspace. AllProfiles is reserved for intentional aggregates.

type RunListSummary

type RunListSummary struct {
	RunID     RunID
	Attention *RunListAttention
	Progress  StepProgress
	Forks     []ForkRef
}

type RunListSummaryReader

type RunListSummaryReader interface {
	ListLoopRunSummaries(context.Context, WorkspaceID, []RunID) (map[RunID]RunListSummary, error)
}

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 RunOutcome

type RunOutcome struct {
	Status    Status    `json:"status"`
	Cause     string    `json:"cause"`
	ActorKind string    `json:"actor_kind,omitempty"`
	ActorRef  string    `json:"actor_ref,omitempty"`
	At        time.Time `json:"at"`
}

RunOutcome carries the cause-aware terminal settlement and its durable timestamp.

type RunReadService

type RunReadService interface {
	NodeRoster(context.Context, string, RunID, RosterQuery) (RosterPage, error)
	Briefing(context.Context, string, RunID) (Briefing, error)
	Timeline(context.Context, string, RunID, TimelineQuery) (TimelinePage, error)
}

RunReadService exposes computed, workspace-scoped run projections.

func NewRunReadService

func NewRunReadService(store RunReadStore, now func() time.Time) RunReadService

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 RunReconciler

type RunReconciler interface {
	NeutralizeOrphans(context.Context) (SweepReport, error)
	SweepOnce(context.Context) (SweepReport, error)
	BackfillProvenance(context.Context) (int, error)
}

RunReconciler converges Loop execution records without claiming work.

func NewRunReconciler

func NewRunReconciler(store ReconciliationStore) RunReconciler

NewRunReconciler constructs the reconciliation boundary over its durable store.

type RunStartState

type RunStartState struct {
	Admission *RunAdmission `json:"-"`
	// contains filtered or unexported fields
}

RunStartState keeps infrequently used projections off the hot Run value.

type RunTraces

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

RunTraces owns one root loop.run span per live Loop run, from loop.started to loop.terminal, so the turns its nodes prompt become descendants of the run.

func (*RunTraces) ContextWithRun

func (t *RunTraces) ContextWithRun(ctx context.Context, runID RunID) context.Context

ContextWithRun returns ctx parented under the run's loop.run span, or ctx unchanged when the run has none. Only the span context is attached, so cancellation and values of ctx are untouched.

func (*RunTraces) OnLoopStarted

func (t *RunTraces) OnLoopStarted(ctx context.Context, payload hookspkg.LoopStartedPayload) error

OnLoopStarted starts the run's loop.run root span.

func (*RunTraces) OnLoopTerminal

func (t *RunTraces) OnLoopTerminal(_ context.Context, payload hookspkg.LoopTerminalPayload) error

OnLoopTerminal ends the run's loop.run span; a failed run carries an error status.

type RunUsage

type RunUsage struct {
	Tokens        int64   `json:"tokens"`
	CostUSD       float64 `json:"cost_usd,omitzero"`
	BudgetUsedPct float64 `json:"budget_used_pct,omitzero"`
	Duration      string  `json:"duration,omitempty"`
}

RunUsage summarizes token, cost, budget, and elapsed-time usage.

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 supported task matcher shape.

type RuntimeProvenance

type RuntimeProvenance struct {
	Provider   RuntimeSource            `json:"provider,omitempty"`
	Model      RuntimeSource            `json:"model,omitempty"`
	Reasoning  RuntimeSource            `json:"reasoning,omitempty"`
	Speed      RuntimeSource            `json:"speed,omitempty"`
	ACPOptions map[string]RuntimeSource `json:"acp_options,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"
	// RuntimeSourceInput identifies a typed runtime input referenced by a node.
	RuntimeSourceInput RuntimeSource = "input"
	// 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 provider, model, reasoning, speed, and typed ACP option intent resolved by the Loop engine.

type RuntimeValidationError

type RuntimeValidationError struct {
	Items []RuntimeValidationItem `json:"runtime_validation"`
	// Cause is an optional typed failure (for example a disabled provider) that callers match
	// with errors.Is; it is not serialized.
	Cause error `json:"-"`
}

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 and exposes its cause.

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
	CancelNode(
		ctx context.Context,
		ws WorkspaceID,
		runID RunID,
		nodeID NodeID,
		itemIndex *int,
		reason string,
		actor task.ActorContext,
	) error
	Pause(ctx context.Context, ws WorkspaceID, runID RunID, actor task.ActorContext) error
	// Resume reactivates paused runs; session Goals must settle pending pauses before reentry.
	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
	ListRequests(ctx context.Context, ws WorkspaceID, query RequestQuery) (RequestPage, error)
	GetRequest(ctx context.Context, ws WorkspaceID, ref RequestRef) (RequestDetail, error)
	Respond(ctx context.Context, input RespondInput) (RespondResult, error)
	AmendNodeOutput(ctx context.Context, input AmendInput) (NodeAmendment, error)
	Configure(ctx context.Context, ws WorkspaceID, profileID string, name string, cfg LoopConfig) error
	GetConfig(ctx context.Context, ws WorkspaceID, name string) (*LoopConfig, error)
	GetConfigSnapshot(ctx context.Context, ws WorkspaceID, profileID string, 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 SessionCleanupCause

type SessionCleanupCause string

SessionCleanupCause identifies the transaction that retired a run-owned session.

const (
	SessionCleanupCauseTerminal       SessionCleanupCause = "terminal"
	SessionCleanupCauseReseed         SessionCleanupCause = "reseed"
	SessionCleanupCauseControlRevoked SessionCleanupCause = "control-revoked"
	SessionCleanupCauseStop           SessionCleanupCause = "stop"
	SessionCleanupCauseOperatorCancel SessionCleanupCause = "operator-cancel"
)

func (SessionCleanupCause) Valid

func (c SessionCleanupCause) Valid() bool

Valid reports whether cause belongs to the closed persistence vocabulary.

type SessionCleanupObligation

type SessionCleanupObligation struct {
	ID          int64
	CleanupID   string
	WorkspaceID WorkspaceID
	LoopRunID   RunID
	SourceKind  SessionCleanupSourceKind
	SourceID    string
	SourceEpoch int64
	SessionID   string
	Cause       SessionCleanupCause
	CreatedAt   time.Time
	CompletedAt *time.Time
}

SessionCleanupObligation is one durable, idempotently acknowledged session Stop effect.

func (SessionCleanupObligation) Validate

func (o SessionCleanupObligation) Validate() error

Validate enforces the complete run-owned cleanup identity.

type SessionCleanupSourceKind

type SessionCleanupSourceKind string

SessionCleanupSourceKind identifies the durable owner of a Loop session.

const (
	SessionCleanupSourceGoalBinding SessionCleanupSourceKind = "goal-binding"
	SessionCleanupSourceTaskRun     SessionCleanupSourceKind = "task-run"
)

func (SessionCleanupSourceKind) Valid

func (k SessionCleanupSourceKind) Valid() bool

Valid reports whether source belongs to the closed persistence vocabulary.

type SessionCleanupStore

type SessionCleanupStore interface {
	ClaimLoopSessionCleanup(context.Context, int) ([]SessionCleanupObligation, error)
	AcknowledgeLoopSessionCleanup(context.Context, string, time.Time) error
}

SessionCleanupStore owns pending cleanup delivery and acknowledgement.

type SessionWork

type SessionWork struct {
	RunID          RunID
	Since          time.Time
	ReconciledAt   time.Time
	LeaseUntil     time.Time
	Status         Status
	NeedsAttention bool
	OwnsGoal       bool
	Waits          []NodeWait
}

SessionWork is durable loop evidence for a session's ephemeral supervision view.

type SettleResult

type SettleResult struct {
	CellsSettled      int
	RunsCanceled      int
	CoordinatorStatus taskpkg.Status
}

SettleResult summarizes one atomic Loop execution-record settlement.

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 StartResult

type StartResult struct {
	Run      Run  `json:"run"`
	Replayed bool `json:"replayed,omitzero"`
}

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
	ProfileID    string
	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 StepProgress

type StepProgress struct {
	Round      int `json:"round"`
	StepsDone  int `json:"steps_done"`
	StepsTotal int `json:"steps_total"`
}

StepProgress summarizes current-round action completion.

func ProgressFromRoster

func ProgressFromRoster(roster RosterPage, generation int) StepProgress

func ProgressFromRosterSource

func ProgressFromRosterSource(source *RosterSource) (StepProgress, error)

ProgressFromRosterSource projects progress from the complete current-round roster.

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,
		profileID string,
		digest string,
	) (DefinitionSnapshot, error)
	FindActiveLoopRun(ctx context.Context, ws WorkspaceID, profileID string, 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, profileID string, loopName string, cfg LoopConfig) error
	GetLoopConfig(ctx context.Context, ws WorkspaceID, profileID string, loopName string) (*LoopConfig, error)
}

Store is the loop aggregate persistence contract.

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 StrategyCancellationIntent

type StrategyCancellationIntent struct {
	NodeID     string    `json:"node_id"`
	ItemIndex  int       `json:"item_index"`
	ActorKind  string    `json:"actor_kind"`
	ActorID    string    `json:"actor_id"`
	ReasonCode string    `json:"reason_code"`
	At         time.Time `json:"at"`
}

StrategyCancellationIntent atomically closes pending waits and requests for one canceled lane cell.

type SweepReport

type SweepReport struct {
	RunsExamined    int
	RecordsSettled  int
	OrphansRepaired int
}

SweepReport summarizes one reconciliation pass.

type TargetHealth

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

type TerminalCause

type TerminalCause string

TerminalCause is the terminal outcome that determines task settlement.

const (
	TerminalCauseDone       TerminalCause = "done"
	TerminalCauseNoOp       TerminalCause = "no-op"
	TerminalCauseFailed     TerminalCause = "failed"
	TerminalCauseExhausted  TerminalCause = "exhausted"
	TerminalCauseStalled    TerminalCause = "stalled"
	TerminalCauseCanceled   TerminalCause = "canceled"
	TerminalCauseRunMissing TerminalCause = "run_missing"
)

type TimeTravelOp

type TimeTravelOp struct {
	ID               string
	Kind             string
	IdempotencyKey   string
	RequestDigest    string
	SourceRunID      RunID
	SourceGeneration *int64
	FromNode         NodeID
	ItemIndex        *int
	Actor            task.ActorContext
	Reason           string
	ResultRunID      RunID
	ResultGeneration *int64
	CreatedAt        time.Time
}

type TimeTravelService

type TimeTravelService interface {
	DiffRun(ctx context.Context, workspaceID WorkspaceID, query DiffQuery) (DiffResult, error)
	RerunFromNode(ctx context.Context, input RerunInput) (RerunResult, error)
	ForkRun(ctx context.Context, input ForkInput) (StartResult, error)
}

TimeTravelService exposes the optional historical read and mutation surface.

type TimelineEntry

type TimelineEntry struct {
	Seq        int64        `json:"seq"`
	FirstSeq   int64        `json:"first_seq,omitzero"`
	Kind       RunEventKind `json:"kind"`
	Generation int64        `json:"generation,omitzero"`
	NodeID     NodeID       `json:"node_id,omitempty"`
	Attempt    int          `json:"attempt,omitzero"`
	Title      string       `json:"title"`
	At         time.Time    `json:"at"`
}

func ProjectTimelineEvent

func ProjectTimelineEvent(event RunEvent, view TimelineView) (*TimelineEntry, error)

ProjectTimelineEvent applies the server-owned tier and meaning projection to one live event.

type TimelineEventReader

type TimelineEventReader interface {
	GetLoopRunEventHead(context.Context, WorkspaceID, RunID) (int64, error)
	ListLoopRunEventsBackward(context.Context, RunEventBackwardQuery) ([]RunEvent, error)
}

type TimelinePage

type TimelinePage struct {
	RunID      RunID           `json:"run_id"`
	HeadSeq    int64           `json:"head_seq"`
	Entries    []TimelineEntry `json:"entries"`
	NextCursor string          `json:"next_cursor,omitempty"`
}

func ProjectTimeline

func ProjectTimeline(runID RunID, events []RunEvent, query TimelineQuery) (TimelinePage, error)

ProjectTimeline creates a snapshot-fenced newest-first page from durable events.

type TimelinePositionError

type TimelinePositionError struct {
	Position int64
	Head     int64
}

func (*TimelinePositionError) Error

func (e *TimelinePositionError) Error() string

func (*TimelinePositionError) Unwrap

func (e *TimelinePositionError) Unwrap() error

type TimelineQuery

type TimelineQuery struct {
	View     TimelineView
	Cursor   string
	Limit    int
	AfterSeq int64
}

type TimelineTier

type TimelineTier string
const (
	TimelineNotable  TimelineTier = "notable"
	TimelineActivity TimelineTier = "activity"
	TimelineChatter  TimelineTier = "chatter"
)

func TimelineTierFor

func TimelineTierFor(kind RunEventKind) (TimelineTier, bool)

type TimelineView

type TimelineView string
const (
	TimelineViewNotable TimelineView = "notable"
	TimelineViewAll     TimelineView = "all"
)

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"`
	FullOutputSchema       json.RawMessage `json:"full_output_schema,omitempty"`
	FullOutputSchemaDigest string          `json:"full_output_schema_digest,omitempty"`
}

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

func (ToolSchemaSnapshot) OutputSchemaFor

func (s ToolSchemaSnapshot) OutputSchemaFor(view tools.ResultView) (json.RawMessage, string)

OutputSchemaFor selects the node's output contract.

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 an operator cancellation.
	TransitionCauseOperatorCancel TransitionCause = "operator_cancel"
	// 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"
	// TransitionCauseOperatorRerun records reactivation from a settled generation.
	TransitionCauseOperatorRerun TransitionCause = "operator_rerun"
)

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"`
	ProfileID   string         `json:"profile_id,omitempty"`
	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"`
	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
	ReadScope   store.ReadScope
	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 WorkerRunActivator

type WorkerRunActivator interface {
	ActivateWorkerRun(context.Context, task.Run)
}

WorkerRunActivator hands a committed Loop worker run to the daemon runtime.

type WorkerRunActivatorFunc

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

WorkerRunActivatorFunc adapts a function to WorkerRunActivator.

func (WorkerRunActivatorFunc) ActivateWorkerRun

func (f WorkerRunActivatorFunc) ActivateWorkerRun(ctx context.Context, run task.Run)

ActivateWorkerRun implements WorkerRunActivator.

type WorkspaceID

type WorkspaceID string

WorkspaceID is the workspace owner for loop aggregate state.

type WorkspaceRuntimeCatalog

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

WorkspaceRuntimeCatalog resolves workspace-specific provider validation authority.

type WorktreeCandidateVerifier

type WorktreeCandidateVerifier interface {
	VerifyReviewCandidate(context.Context, string, string, []string, string) (bool, error)
}

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