task

package
v0.3.0-beta.19 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package task defines the canonical task-domain models, interfaces, limits, and validation helpers shared by persistence, runtime, and transport layers.

Index

Constants

View Source
const (
	// CatalogScopeAll includes global tasks and the workspace selected by the query.
	CatalogScopeAll CatalogScope = "all"
	// CatalogScopeGlobal includes only global tasks.
	CatalogScopeGlobal CatalogScope = "global"
	// CatalogScopeWorkspace includes only tasks from the selected workspace.
	CatalogScopeWorkspace CatalogScope = "workspace"

	// CatalogSortRecent orders tasks by their latest durable activity.
	CatalogSortRecent CatalogSort = "recent"
	// CatalogSortPriority orders tasks by priority and then latest durable activity.
	CatalogSortPriority CatalogSort = "priority"

	// DefaultCatalogLimit bounds public task catalog reads when no limit is supplied.
	DefaultCatalogLimit = 50
	// MaxCatalogLimit bounds one public task catalog page.
	MaxCatalogLimit = 200
)
View Source
const (
	// DefaultRunLeaseDuration is the conservative lease duration used when a caller omits one.
	DefaultRunLeaseDuration = 5 * time.Minute
	// MaxRunLeaseDuration is the MVP guardrail for a single task-run lease extension.
	MaxRunLeaseDuration = 24 * time.Hour

	// LeaseRecoveryExhaustedReason identifies a run whose shared attempt budget cannot grant another claim.
	LeaseRecoveryExhaustedReason = "lease_recovery_exhausted"
)
View Source
const (
	// MaxReferenceBytes caps persisted identifiers and external references at 256 bytes.
	MaxReferenceBytes = 256
	// MaxReasonBytes caps operator-authored audit reasons at 4 KiB.
	MaxReasonBytes = 4 * 1024
	// MaxDiagnosticBytes caps persisted diagnostic text at 16 KiB.
	MaxDiagnosticBytes = 16 * 1024
	// MaxAuditCollectionItems caps identifier collections copied into audit events.
	MaxAuditCollectionItems = 50
	// MaxMetadataBytes caps task metadata payloads at 16 KiB.
	MaxMetadataBytes = 16 * 1024
	// MaxPayloadBytes caps persisted event-style JSON payloads at 64 KiB.
	MaxPayloadBytes = 64 * 1024
	// MaxResultBytes caps persisted run results at 64 KiB.
	MaxResultBytes = 64 * 1024
	// DefaultTaskMaxAttempts is the canonical retry budget used when callers omit an explicit value.
	DefaultTaskMaxAttempts = 3
	// MaxTaskMaxAttempts caps task-level attempt policy at ten tries.
	MaxTaskMaxAttempts = 10
	// MaxHierarchyDepth caps parent/child nesting at eight levels.
	MaxHierarchyDepth = 8
	// MaxDependencyCount caps dependency edges per task at thirty-two.
	MaxDependencyCount = 32
	// MaxDirectChildren caps direct child tasks per parent at sixty-four.
	MaxDirectChildren = 64
)
View Source
const (
	// TaskFieldCreatedBy identifies the immutable creator identity field.
	TaskFieldCreatedBy = "created_by"
	// TaskFieldOrigin identifies the immutable technical ingress field.
	TaskFieldOrigin = "origin"
	// TaskFieldScope identifies the immutable task scope field.
	TaskFieldScope = "scope"
	// TaskFieldWorkspaceID identifies the immutable workspace binding field.
	TaskFieldWorkspaceID = "workspace_id"
	// TaskFieldParentTaskID identifies the immutable parent-task linkage field.
	TaskFieldParentTaskID = "parent_task_id"
	// TaskFieldTitle identifies the mutable task title field.
	TaskFieldTitle = "title"
	// TaskFieldDescription identifies the mutable task description field.
	TaskFieldDescription = "description"
	// TaskFieldPriority identifies the mutable task priority field.
	TaskFieldPriority = "priority"
	// TaskFieldMaxAttempts identifies the mutable task attempt-policy field.
	TaskFieldMaxAttempts = "max_attempts"
	// TaskFieldAutoEnqueueOnReady identifies the mutable auto-enqueue policy field.
	TaskFieldAutoEnqueueOnReady = "auto_enqueue_on_ready"
	// TaskFieldApprovalPolicy identifies the mutable approval-policy field.
	TaskFieldApprovalPolicy = "approval_policy"
	// TaskFieldMetadata identifies the mutable task metadata field.
	TaskFieldMetadata = "metadata"
	// TaskFieldOwner identifies the mutable ownership field.
	TaskFieldOwner = "owner"
)
View Source
const (
	// CoordinatorModeInherit uses daemon/workspace coordinator defaults.
	CoordinatorModeInherit CoordinatorMode = "inherit"
	// CoordinatorModeGuided injects task-specific guidance into the existing coordinator.
	CoordinatorModeGuided CoordinatorMode = "guided"

	// WorkerModeInherit uses normal task/run and workspace worker defaults.
	WorkerModeInherit WorkerMode = "inherit"
	// WorkerModeSelect narrows worker selection using the task profile.
	WorkerModeSelect WorkerMode = "select"

	// SandboxModeInherit uses workspace/global sandbox defaults.
	SandboxModeInherit SandboxMode = "inherit"
	// SandboxModeNone disables task-level sandbox selection when config permits it.
	SandboxModeNone SandboxMode = "none"
	// SandboxModeRef selects one named sandbox reference at session start.
	SandboxModeRef SandboxMode = "ref"

	// RuntimeModeDefault uses the normal task-session runtime contract.
	RuntimeModeDefault RuntimeMode = "default"
	// RuntimeModeEvidence explicitly allows runtime/browser/mobile evidence work.
	RuntimeModeEvidence RuntimeMode = "evidence"
)
View Source
const (
	// FailureKindOperatorForced identifies an operator-authored forced terminal failure.
	FailureKindOperatorForced = "operator_forced"
	// MaxForceRunBulkIDs bounds per-request bulk recovery work.
	MaxForceRunBulkIDs = 50
	// MaxRetryRunChainDepth bounds linear retry lineage to prevent accidental retry loops.
	MaxRetryRunChainDepth = 10
	// DefaultForceRunRateLimitPerMinute bounds force operations by actor and task.
	DefaultForceRunRateLimitPerMinute = 10
)
View Source
const (
	// CoordinatorFailureKind identifies the typed safe coordinator diagnostic envelope.
	CoordinatorFailureKind = "coordinator_failure"
)
View Source
const DefaultTaskStarvationAge = 2 * time.Minute

DefaultTaskStarvationAge is the queued age past which a claimable run is treated as starved by the scheduler convergence backstop and the scheduler status surface.

Variables

View Source
var (
	// ErrTaskNotFound reports that no persisted task matched the lookup.
	ErrTaskNotFound = errors.New("task: task not found")
	// ErrTaskRunNotFound reports that no persisted task run matched the lookup.
	ErrTaskRunNotFound = errors.New("task: task run not found")
	// ErrTaskRunIdempotencyNotFound reports that no persisted task-run idempotency record matched the lookup.
	ErrTaskRunIdempotencyNotFound = errors.New("task: task run idempotency not found")
	// ErrTaskDependencyNotFound reports that no persisted dependency edge matched the lookup.
	ErrTaskDependencyNotFound = errors.New("task: task dependency not found")
	// ErrTaskBlockNotFound reports that no persisted task block matched the lookup.
	ErrTaskBlockNotFound = errors.New("task: task block not found")
	// ErrTaskEventNotFound reports that no persisted task event matched the lookup.
	ErrTaskEventNotFound = errors.New("task: task event not found")
	// ErrTaskTriageStateNotFound reports that no persisted triage state matched the lookup.
	ErrTaskTriageStateNotFound = errors.New("task: task triage state not found")
	// ErrExecutionProfileNotFound reports that no persisted task execution profile matched the lookup.
	ErrExecutionProfileNotFound = errors.New("task: task execution profile not found")
	// ErrRunReviewNotFound reports that no persisted task-run review matched the lookup.
	ErrRunReviewNotFound = errors.New("task: task run review not found")
	// ErrValidation reports that a task-domain payload or state failed validation.
	ErrValidation = errors.New("task: validation failed")
	// ErrImmutableField reports that a caller attempted to change an immutable task field.
	ErrImmutableField = errors.New("task: immutable field")
	// ErrInvalidScopeBinding reports that a scope and workspace binding combination is invalid.
	ErrInvalidScopeBinding = errors.New("task: invalid scope binding")
	// ErrPayloadTooLarge reports that a JSON payload exceeded the task-domain size guardrails.
	ErrPayloadTooLarge = errors.New("task: payload too large")
	// ErrGraphLimitExceeded reports that a task hierarchy or dependency operation exceeded a bounded limit.
	ErrGraphLimitExceeded = errors.New("task: graph limit exceeded")
	// ErrCycleDetected reports that a dependency insert would introduce a cycle.
	ErrCycleDetected = errors.New("task: dependency cycle detected")
	// ErrInvalidStatusTransition reports that a task or run lifecycle transition is not allowed.
	ErrInvalidStatusTransition = errors.New("task: invalid status transition")
	// ErrTerminalRunCommandInProgress reports that one durable terminal intent already owns the run.
	ErrTerminalRunCommandInProgress = errors.New("task: terminal run command in progress")
	// ErrConflict reports that an idempotent write conflicts with previously persisted state.
	ErrConflict = errors.New("task: conflict")
	// ErrSessionAlreadyBound reports that a run already owns a session binding.
	ErrSessionAlreadyBound = errors.New("task: session already bound")
	// ErrSessionAttachNotAllowed reports that a run cannot attach an existing session in its current state.
	ErrSessionAttachNotAllowed = errors.New("task: session attach not allowed")
	// ErrPermissionDenied reports that the resolved actor context lacks authority for the requested task action.
	ErrPermissionDenied = errors.New("task: permission denied")
	// ErrNoClaimableRun reports that no task run matched claim criteria.
	ErrNoClaimableRun = errors.New("task: no claimable run")
	// ErrInvalidClaimToken reports that a lease mutation did not prove ownership with the current token.
	ErrInvalidClaimToken = errors.New("task: invalid claim token")
	// ErrHallucinatedTaskRefs reports completion claims for task IDs not created by the completing session.
	ErrHallucinatedTaskRefs = errors.New("task: completion claims task ids not created by this session")
	// ErrLeaseExpired reports that a lease mutation targeted an expired ownership lease.
	ErrLeaseExpired = errors.New("task: lease expired")
	// ErrSessionNotLive reports that a creator session cannot accept a wake delivery.
	ErrSessionNotLive = errors.New("task: creator session is not live")
	// ErrActiveRunLease reports that a session already owns an active task-run lease.
	ErrActiveRunLease = errors.New("task: active run lease exists")
	// ErrWorkspaceActiveRunCapReached reports that workspace execution capacity is currently full.
	ErrWorkspaceActiveRunCapReached = errors.New("task: workspace active run cap reached")
	// ErrNetworkWakeSettlementConflict reports a terminal wake outcome that conflicts with durable truth.
	ErrNetworkWakeSettlementConflict = errors.New("task: network wake settlement conflict")
	// ErrForbiddenOperatorAction reports that config or policy forbids a force operation for the actor.
	ErrForbiddenOperatorAction = errors.New("task: forbidden operator action")
	// ErrForceOpRequiresReason reports that a force operation requires a non-empty reason.
	ErrForceOpRequiresReason = errors.New("task: force operation requires reason")
	// ErrForceOpRateLimited reports that an actor exceeded the force-operation rate limit.
	ErrForceOpRateLimited = errors.New("task: force operation rate limited")
	// ErrRetryChainTooDeep reports that retry would exceed the configured retry lineage depth.
	ErrRetryChainTooDeep = errors.New("task: retry chain too deep")
	// ErrBulkTooLarge reports that a bulk operation exceeded its bounded item limit.
	ErrBulkTooLarge = errors.New("task: bulk operation too large")
)
View Source
var (
	// ErrCatalogCursorInvalid reports a malformed cursor or one reused with a different query.
	ErrCatalogCursorInvalid = errors.New("task: catalog cursor is invalid")
)
View Source
var (
	// ErrInboxCursorInvalid reports a malformed cursor or one reused with another actor or query.
	ErrInboxCursorInvalid = errors.New("task: inbox cursor is invalid")
)

Functions

func ApplyRunDesignationSummary

func ApplyRunDesignationSummary(summary *RunSummary, run Run)

ApplyRunDesignationSummary projects designation metadata from a run into a summary.

func ClaimTokenHash

func ClaimTokenHash(rawToken string) (string, error)

ClaimTokenHash returns the canonical hash persisted for one raw claim token.

func ClampSummaryCount

func ClampSummaryCount(count int) int32

ClampSummaryCount converts an internal count to the compact Summary count representation.

func CoordinatorCompletedRunResult

func CoordinatorCompletedRunResult() json.RawMessage

CoordinatorCompletedRunResult returns the canonical durable result for a completed coordinator run.

func DefaultSchedulerDrainTimeout

func DefaultSchedulerDrainTimeout() time.Duration

DefaultSchedulerDrainTimeout keeps API transports from duplicating scheduler policy.

func EncodeCatalogCursor

func EncodeCatalogCursor(query CatalogQuery, summary *Summary) (string, error)

EncodeCatalogCursor captures the last returned row without relying on later anchor lookup.

func EncodeInboxCursor

func EncodeInboxCursor(query InboxQuery, actor ActorIdentity, item InboxItem) (string, error)

EncodeInboxCursor captures the last returned item without later anchor lookup.

func ImmutableTaskFields

func ImmutableTaskFields() []string

ImmutableTaskFields returns the canonical immutable task field names.

func IsImmutableTaskField

func IsImmutableTaskField(field string) bool

IsImmutableTaskField reports whether the supplied field name is immutable after task creation.

func IsMutableTaskField

func IsMutableTaskField(field string) bool

IsMutableTaskField reports whether the supplied field name is directly mutable on a task.

func IsTerminalRunStatus

func IsTerminalRunStatus(status RunStatus) bool

func MutableTaskFields

func MutableTaskFields() []string

MutableTaskFields returns the canonical mutable task field names.

func NewClaimToken

func NewClaimToken() (string, error)

NewClaimToken generates one raw bearer token for a successful claim response.

func NormalizeInboxQuery

func NormalizeInboxQuery(query InboxQuery, actor ActorIdentity) (InboxQuery, ActorIdentity, error)

NormalizeInboxQuery validates and canonicalizes an actor-bound inbox query.

func PriorityRank

func PriorityRank(priority Priority) int

PriorityRank returns the canonical highest-first task priority rank.

func RedactClaimTokenJSON

func RedactClaimTokenJSON(raw json.RawMessage) json.RawMessage

RedactClaimTokenJSON removes raw claim-token fields and values from a JSON payload.

func RedactClaimTokens

func RedactClaimTokens(value string) string

RedactClaimTokens replaces raw claim bearer tokens in free-form strings.

func StatusProjectionEventType

func StatusProjectionEventType(eventType string) string

StatusProjectionEventType returns the canonical transition type included in durable Network task-status projections. Empty means the event is not a status transition.

func ValidateApprovalSemantics

func ValidateApprovalSemantics(policy ApprovalPolicy, state ApprovalState, path string) error

ValidateApprovalSemantics reports whether one approval policy and state pair is internally consistent.

func ValidateCapabilityIDs

func ValidateCapabilityIDs(values []string, path string) error

ValidateCapabilityIDs reports whether every capability identifier is safe for exact matching.

func ValidateDependencyCount

func ValidateDependencyCount(count int) error

ValidateDependencyCount reports whether the supplied dependency count stays within the bounded edge limit.

func ValidateDiagnosticSize

func ValidateDiagnosticSize(value string, path string) error

ValidateDiagnosticSize reports whether persisted diagnostic text fits the diagnostic limit.

func ValidateDirectChildCount

func ValidateDirectChildCount(count int) error

ValidateDirectChildCount reports whether the supplied direct-child count stays within the bounded fan-out limit.

func ValidateHierarchyDepth

func ValidateHierarchyDepth(depth int) error

ValidateHierarchyDepth reports whether the supplied task depth stays within the bounded hierarchy limit.

func ValidateImmutableRunFields

func ValidateImmutableRunFields(current Run, next Run) error

ValidateImmutableRunFields rejects lifecycle updates that rewrite durable execution identity.

func ValidateImmutableTaskFields

func ValidateImmutableTaskFields(current Task, next Task) error

ValidateImmutableTaskFields reports whether an update attempted to change immutable task fields.

func ValidateMetadataSize

func ValidateMetadataSize(payload json.RawMessage, path string) error

ValidateMetadataSize reports whether metadata JSON respects the shared 16 KiB guardrail.

func ValidatePayloadSize

func ValidatePayloadSize(payload json.RawMessage, path string) error

ValidatePayloadSize reports whether a persisted JSON payload respects the shared 64 KiB guardrail.

func ValidateReasonSize

func ValidateReasonSize(value string, path string) error

ValidateReasonSize reports whether operator-authored audit text fits the reason limit.

func ValidateReferenceSize

func ValidateReferenceSize(value string, path string) error

ValidateReferenceSize reports whether an identifier or external reference fits the domain limit.

func ValidateResultSize

func ValidateResultSize(payload json.RawMessage, path string) error

ValidateResultSize reports whether a persisted run result respects the shared 64 KiB guardrail.

func ValidateRunLeaseMutation

func ValidateRunLeaseMutation(run Run, claimToken string, commandAt time.Time) error

ValidateRunLeaseMutation verifies the current lease at the instant of a lifecycle write. Tokenless direct runs remain valid without a lease.

func ValidateScopeBinding

func ValidateScopeBinding(
	scope Scope,
	workspaceBinding string,
	path string,
	workspaceField string,
) error

ValidateScopeBinding enforces the canonical scope/workspace invariant shared by task-domain records.

func VerifyClaimToken

func VerifyClaimToken(rawToken string, persistedHash string) bool

VerifyClaimToken reports whether rawToken hashes to the persisted canonical hash.

Types

type ActorContext

type ActorContext struct {
	Actor     ActorIdentity `json:"actor"`
	Origin    Origin        `json:"origin"`
	Authority Authority     `json:"authority"`
	Scope     CallerScope   `json:"scope"`
}

ActorContext carries the authenticated principal, ingress origin, resolved task authority, and caller scope.

func DeriveAgentSessionActorContext

func DeriveAgentSessionActorContext(sessionRef string, workspaceID string) (ActorContext, error)

DeriveAgentSessionActorContext derives one trusted agent-session actor context. The session ref becomes both the immutable actor ref and origin ref.

func DeriveAgentSessionActorContextForOrigin

func DeriveAgentSessionActorContextForOrigin(
	sessionRef string,
	workspaceID string,
	originKind OriginKind,
	originRef string,
) (ActorContext, error)

DeriveAgentSessionActorContextForOrigin derives one trusted agent-session actor context for an authenticated agent ingress operation.

func DeriveAutomationActorContext

func DeriveAutomationActorContext(actorRef string, originRef string) (ActorContext, error)

DeriveAutomationActorContext derives one trusted automation actor context. If originRef is empty, the actor ref is reused as the durable origin ref.

func DeriveAutomationActorContextForWorkspace

func DeriveAutomationActorContextForWorkspace(
	actorRef string,
	workspaceID string,
	originRef string,
) (ActorContext, error)

DeriveAutomationActorContextForWorkspace derives one trusted automation actor constrained to a registered workspace.

func DeriveAutomationLinkedAgentSessionActorContext

func DeriveAutomationLinkedAgentSessionActorContext(
	sessionRef string,
	workspaceID string,
	originRef string,
) (ActorContext, error)

DeriveAutomationLinkedAgentSessionActorContext derives one trusted agent-session actor context for work created explicitly by an automation- launched session. The session remains the immutable actor while the origin is anchored to the automation activation that launched it.

func DeriveDaemonActorContext

func DeriveDaemonActorContext(actorRef string, originRef string) (ActorContext, error)

DeriveDaemonActorContext derives one trusted daemon-owned actor context. If originRef is empty, the actor ref is reused as the durable origin ref.

func DeriveExtensionActorContext

func DeriveExtensionActorContext(actorRef string, originRef string) (ActorContext, error)

DeriveExtensionActorContext derives one trusted extension actor context. If originRef is empty, the actor ref is reused as the durable origin ref.

func DeriveExtensionActorContextForWorkspace

func DeriveExtensionActorContextForWorkspace(
	actorRef string,
	workspaceID string,
	originRef string,
) (ActorContext, error)

DeriveExtensionActorContextForWorkspace derives one trusted extension actor constrained to a registered workspace.

func DeriveHumanActorContext

func DeriveHumanActorContext(actorRef string, originKind OriginKind, originRef string) (ActorContext, error)

DeriveHumanActorContext derives one trusted local-human actor context for CLI, web, HTTP, or UDS task ingress.

func DeriveHumanActorContextForWorkspace

func DeriveHumanActorContextForWorkspace(
	actorRef string,
	workspaceID string,
	originKind OriginKind,
	originRef string,
) (ActorContext, error)

DeriveHumanActorContextForWorkspace derives a trusted local-human actor bound to an optional route workspace.

func DeriveNetworkPeerActorContext

func DeriveNetworkPeerActorContext(actorRef string, originRef string) (ActorContext, error)

DeriveNetworkPeerActorContext derives one trusted network-peer actor context. If originRef is empty, the actor ref is reused as the durable origin ref so ingress layers may include peer or peer/channel details as needed.

func (ActorContext) Validate

func (a ActorContext) Validate() error

Validate reports whether the actor context contains a valid principal, origin, and authority envelope.

type ActorIdentity

type ActorIdentity struct {
	Kind ActorKind `json:"kind"`
	Ref  string    `json:"ref"`
}

ActorIdentity is the immutable server-derived actor identity attached to task and run writes.

func (ActorIdentity) IsZero

func (a ActorIdentity) IsZero() bool

IsZero reports whether the actor identity is empty.

func (ActorIdentity) Validate

func (a ActorIdentity) Validate(path string) error

Validate reports whether the actor identity contains a supported kind and non-empty reference.

type ActorKind

type ActorKind string

ActorKind identifies the authenticated principal class behind task writes.

const (
	// ActorKindHuman identifies a human principal writing through CLI, web, HTTP, or UDS surfaces.
	ActorKindHuman ActorKind = "human"
	// ActorKindAgentSession identifies an Compozy agent session principal.
	ActorKindAgentSession ActorKind = "agent_session"
	// ActorKindAutomation identifies daemon-owned automation flows.
	ActorKindAutomation ActorKind = "automation"
	// ActorKindExtension identifies an authenticated extension runtime principal.
	ActorKindExtension ActorKind = "extension"
	// ActorKindNetworkPeer identifies an authenticated network peer principal.
	ActorKindNetworkPeer ActorKind = "network_peer"
	// ActorKindDaemon identifies daemon-owned system work.
	ActorKindDaemon ActorKind = "daemon"
)

func (ActorKind) Normalize

func (k ActorKind) Normalize() ActorKind

Normalize returns the normalized representation of the actor kind.

func (ActorKind) Validate

func (k ActorKind) Validate(path string) error

Validate reports whether the actor kind is supported.

type AddDependency

type AddDependency struct {
	TaskID          string         `json:"task_id"`
	DependsOnTaskID string         `json:"depends_on_task_id"`
	Kind            DependencyKind `json:"kind"`
}

AddDependency captures one dependency-edge creation request.

func (AddDependency) Validate

func (r AddDependency) Validate(path string) error

Validate reports whether the dependency-create request is internally consistent.

type ApprovalPolicy

type ApprovalPolicy string

ApprovalPolicy identifies whether a task requires an explicit approval step.

const (
	// ApprovalPolicyNone identifies tasks that do not require approval.
	ApprovalPolicyNone ApprovalPolicy = "none"
	// ApprovalPolicyManual identifies tasks that require an explicit approve or reject action.
	ApprovalPolicyManual ApprovalPolicy = "manual"
	// DefaultApprovalPolicy is the canonical policy used when callers omit approval requirements.
	DefaultApprovalPolicy ApprovalPolicy = ApprovalPolicyNone
)

func (ApprovalPolicy) Normalize

func (p ApprovalPolicy) Normalize() ApprovalPolicy

Normalize returns the normalized representation of the approval policy.

func (ApprovalPolicy) Validate

func (p ApprovalPolicy) Validate(path string) error

Validate reports whether the approval policy is one of the supported values.

type ApprovalState

type ApprovalState string

ApprovalState identifies the current approval outcome for one task.

const (
	// ApprovalStateNotRequired identifies tasks whose policy does not require approval.
	ApprovalStateNotRequired ApprovalState = "not_required"
	// ApprovalStatePending identifies tasks waiting for approval.
	ApprovalStatePending ApprovalState = "pending"
	// ApprovalStateApproved identifies tasks that were approved.
	ApprovalStateApproved ApprovalState = "approved"
	// ApprovalStateRejected identifies tasks that were rejected.
	ApprovalStateRejected ApprovalState = "rejected"
)

func (ApprovalState) Normalize

func (s ApprovalState) Normalize() ApprovalState

Normalize returns the normalized representation of the approval state.

func (ApprovalState) Validate

func (s ApprovalState) Validate(path string) error

Validate reports whether the approval state is one of the supported values.

type Authority

type Authority struct {
	Read            bool `json:"read"`
	Write           bool `json:"write"`
	CreateGlobal    bool `json:"create_global"`
	CreateWorkspace bool `json:"create_workspace"`
}

Authority captures the task-domain permissions resolved for one authenticated principal.

func FullAccessAuthority

func FullAccessAuthority() Authority

FullAccessAuthority returns the v1 broad task-domain authority granted to authenticated first-class task surfaces after ingress-level authentication and capability checks succeed.

func (Authority) Validate

func (a Authority) Validate(path string) error

Validate reports whether the authority flags are internally consistent.

type AutonomyError

type AutonomyError struct {
	Reason AutonomyReasonCode
	Err    error
}

AutonomyError carries the deterministic reason for a session-bound autonomy rejection.

func (*AutonomyError) Error

func (e *AutonomyError) Error() string

Error returns the redacted public error string.

func (*AutonomyError) Unwrap

func (e *AutonomyError) Unwrap() error

Unwrap returns the wrapped task-domain sentinel.

type AutonomyLeaseAuthority

type AutonomyLeaseAuthority interface {
	LookupActiveRunForSession(
		ctx context.Context,
		sessionID string,
		runID string,
	) (AutonomyLeaseHandle, error)
}

AutonomyLeaseAuthority resolves the internal lease credential for the calling session without exposing the raw claim token at public boundaries.

type AutonomyLeaseHandle

type AutonomyLeaseHandle struct {
	RunID           string
	TaskID          string
	RunKind         RunKind
	WorkspaceID     string
	TargetSessionID string
	OwnerKey        string
	SessionID       string
	Status          RunStatus
	ClaimedBy       *ActorIdentity
	ClaimToken      string
	ClaimTokenHash  string
	LeaseUntil      time.Time
	HeartbeatAt     time.Time
}

AutonomyLeaseHandle is the internal-only active lease handle used to call the existing token-fenced lease writers.

type AutonomyLeaseStore

type AutonomyLeaseStore interface {
	ListAutonomyLeaseHandles(ctx context.Context, sessionID string) ([]AutonomyLeaseHandle, error)
}

AutonomyLeaseStore is the narrowed internal store surface required by the session-bound autonomy lookup.

type AutonomyReasonCode

type AutonomyReasonCode string

AutonomyReasonCode is the stable machine-readable reason for session-bound autonomy lease lookup failures.

const (
	AutonomySessionRequired  AutonomyReasonCode = "AUTONOMY_SESSION_REQUIRED"
	AutonomyNoActiveLease    AutonomyReasonCode = "AUTONOMY_NO_ACTIVE_LEASE"
	AutonomyForeignRun       AutonomyReasonCode = "AUTONOMY_FOREIGN_RUN"
	AutonomyLeaseExpired     AutonomyReasonCode = "AUTONOMY_LEASE_EXPIRED"
	AutonomyLeaseAlreadyHeld AutonomyReasonCode = "AUTONOMY_LEASE_ALREADY_HELD"
)

func AutonomyReasonOf

func AutonomyReasonOf(err error) (AutonomyReasonCode, bool)

AutonomyReasonOf extracts a deterministic autonomy reason code from an error.

type BindRunReviewSessionRequest

type BindRunReviewSessionRequest struct {
	ReviewID          string `json:"review_id"`
	SessionID         string `json:"session_id"`
	ReviewerAgentName string `json:"reviewer_agent_name,omitempty"`
	ReviewerPeerID    string `json:"reviewer_peer_id,omitempty"`
	ReviewerChannelID string `json:"reviewer_channel_id,omitempty"`
}

BindRunReviewSessionRequest captures a reviewer-session binding.

func (BindRunReviewSessionRequest) Normalize

Normalize returns a canonical reviewer-session binding request.

func (BindRunReviewSessionRequest) Validate

func (r BindRunReviewSessionRequest) Validate(path string) error

Validate reports whether the binding request can bind a reviewer session.

type BlockExpiryTarget

type BlockExpiryTarget struct {
	TaskID  string `json:"task_id"`
	BlockID string `json:"block_id"`
}

BlockExpiryTarget identifies one task block selected by a read-only expiry snapshot.

type BlockKind

type BlockKind string

BlockKind identifies a runtime-declared reason a task cannot proceed.

const (
	// BlockKindNeedsInput reports that the task needs human or creator input.
	BlockKindNeedsInput BlockKind = "needs_input"
	// BlockKindCapability reports that the task needs a capability that is not currently available.
	BlockKindCapability BlockKind = "capability"
	// BlockKindTransient reports a temporary external or environmental blocker.
	BlockKindTransient BlockKind = "transient"
)

func (BlockKind) Normalize

func (k BlockKind) Normalize() BlockKind

Normalize returns the normalized representation of the task-block kind.

func (BlockKind) Validate

func (k BlockKind) Validate(path string) error

Validate reports whether the task-block kind is supported.

type BlockMutationResult

type BlockMutationResult struct {
	Block         TaskBlock       `json:"block"`
	Recurrence    BlockRecurrence `json:"recurrence"`
	EscalatedTask *Task           `json:"escalated_task,omitempty"`
}

BlockMutationResult is the durable result of a task-block creation mutation.

type BlockReader

type BlockReader interface {
	ListTaskBlocks(ctx context.Context, taskID string, includeCleared bool) ([]TaskBlock, error)
	HasOpenTaskBlocks(ctx context.Context, taskID string) (bool, error)
}

BlockReader is the persistence surface for read-only task-block projections.

type BlockRecurrence

type BlockRecurrence struct {
	TaskID    string    `json:"task_id"`
	Kind      BlockKind `json:"kind"`
	Count     int       `json:"count"`
	UpdatedAt time.Time `json:"updated_at,omitzero"`
}

BlockRecurrence stores breaker accounting for one task and block kind.

type BlockRequest

type BlockRequest struct {
	TaskID     string          `json:"task_id"`
	Kind       BlockKind       `json:"kind"`
	Reason     string          `json:"reason"`
	Details    json.RawMessage `json:"details,omitempty"`
	ExpiresAt  time.Time       `json:"expires_at,omitzero"`
	RunID      string          `json:"run_id,omitempty"`
	ClaimToken string          `json:"claim_token,omitempty"`
}

BlockRequest captures the service-level request to create a task block.

type BlockStore

type BlockStore interface {
	BlockReader
	ListExpiredTaskBlockTargets(ctx context.Context, now time.Time) ([]BlockExpiryTarget, error)
	CreateTaskBlock(ctx context.Context, mutation CreateTaskBlockMutation) (BlockMutationResult, error)
	ClearTaskBlock(ctx context.Context, mutation ClearTaskBlockMutation) (TaskBlock, error)
	ClearTaskNeedsAttention(
		ctx context.Context,
		mutation NeedsAttentionClearMutation,
	) (NeedsAttentionClearResult, error)
	ExpireTaskBlocks(ctx context.Context, mutation ExpireTaskBlocksMutation) (ExpireTaskBlocksResult, error)
	BlockTaskAndReleaseRun(
		ctx context.Context,
		mutation BlockTaskAndReleaseRunMutation,
	) (BlockTaskAndReleaseRunResult, error)
}

BlockStore is the persistence surface for task-block lifecycle mutations.

type BlockTaskAndReleaseRunMutation

type BlockTaskAndReleaseRunMutation struct {
	Block           TaskBlock `json:"block"`
	RunID           string    `json:"run_id"`
	ClaimToken      string    `json:"claim_token"`
	Now             time.Time `json:"now"`
	RecurrenceLimit int       `json:"recurrence_limit"`
	Actor           ActorContext
}

BlockTaskAndReleaseRunMutation inserts a block and atomically parks the active run.

type BlockTaskAndReleaseRunResult

type BlockTaskAndReleaseRunResult struct {
	Block          TaskBlock       `json:"block"`
	Run            Run             `json:"run"`
	Recurrence     BlockRecurrence `json:"recurrence"`
	EscalatedTask  *Task           `json:"escalated_task,omitempty"`
	ReleaseReason  string          `json:"release_reason"`
	PreviousRun    Run             `json:"previous_run"`
	ClaimTokenHash string          `json:"claim_token_hash,omitempty"`
}

BlockTaskAndReleaseRunResult is the durable result of the atomic block-and-release mutation.

type BlockedReason

type BlockedReason struct {
	Source           BlockedSource `json:"source"`
	Kind             BlockKind     `json:"kind,omitempty"`
	Reason           string        `json:"reason,omitempty"`
	BlockID          string        `json:"block_id,omitempty"`
	DependsOnTaskIDs []string      `json:"depends_on_task_ids,omitempty"`
}

BlockedReason is a derived read projection; it is never persisted.

type BlockedSource

type BlockedSource string

BlockedSource identifies one source in the derived blocked-reasons projection.

const (
	// BlockedSourceDependency reports unresolved task dependency edges.
	BlockedSourceDependency BlockedSource = "dependency"
	// BlockedSourceApproval reports a pending approval gate.
	BlockedSourceApproval BlockedSource = "approval"
	// BlockedSourcePaused reports an operator pause gate.
	BlockedSourcePaused BlockedSource = "paused"
	// BlockedSourceBlock reports an open runtime-declared task block.
	BlockedSourceBlock BlockedSource = "block"
)

func (BlockedSource) Normalize

func (s BlockedSource) Normalize() BlockedSource

Normalize returns the normalized representation of the blocked-reason source.

func (BlockedSource) Validate

func (s BlockedSource) Validate(path string) error

Validate reports whether the blocked-reason source is supported.

type BoundRunSessionSettlement

type BoundRunSessionSettlement struct {
	Run  Run
	Task Task
}

BoundRunSessionSettlement is the durable task projection produced with a lease session binding.

type BulkForceRunItem

type BulkForceRunItem struct {
	RunID string `json:"run_id"`
	OK    bool   `json:"ok"`
	Run   *Run   `json:"run,omitempty"`
	Err   error  `json:"-"`
}

BulkForceRunItem records one per-run bulk recovery outcome.

type BulkForceRunRequest

type BulkForceRunRequest struct {
	RunIDs   []string        `json:"run_ids"`
	Reason   string          `json:"reason,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

BulkForceRunRequest captures a bounded release/fail batch.

type BulkForceRunResult

type BulkForceRunResult struct {
	Items []BulkForceRunItem `json:"items"`
}

BulkForceRunResult records bounded per-row outcomes.

type CallerScope

type CallerScope struct {
	SessionID   string `json:"session_id,omitempty"`
	WorkspaceID string `json:"workspace_id,omitempty"`
	Operator    bool   `json:"operator,omitempty"`
}

CallerScope carries daemon-derived caller ownership for scoped operations.

func (CallerScope) Validate

func (s CallerScope) Validate(actor ActorIdentity) error

Validate reports whether caller ownership is canonical for the actor kind.

type CancelRun

type CancelRun struct {
	Reason   string          `json:"reason,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

CancelRun captures one run-cancellation request.

func (CancelRun) Validate

func (r CancelRun) Validate(path string) error

Validate reports whether the cancel-run request is internally consistent.

type CancelTask

type CancelTask struct {
	Reason   string          `json:"reason,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

CancelTask captures the task-level cancellation request payload.

func (CancelTask) Validate

func (r CancelTask) Validate(path string) error

Validate reports whether the task-cancellation request is internally consistent.

type CatalogCursor

type CatalogCursor struct {
	PriorityRank int       `json:"priority_rank"`
	ActivityAt   time.Time `json:"activity_at"`
	TaskID       string    `json:"task_id"`
}

CatalogCursor is the captured ordering tuple of the last returned row.

func DecodeCatalogCursor

func DecodeCatalogCursor(query CatalogQuery) (CatalogCursor, error)

DecodeCatalogCursor verifies and decodes a query-bound task catalog cursor.

type CatalogManager

type CatalogManager interface {
	ListTaskCatalog(ctx context.Context, query CatalogQuery, actor ActorContext) (CatalogPage, error)
}

CatalogManager is the public task catalog capability exposed by Service.

type CatalogOwnerFacet

type CatalogOwnerFacet struct {
	Owner Ownership `json:"owner"`
	Count int       `json:"count"`
}

CatalogOwnerFacet is one exact assigned-owner count before the page cut.

type CatalogPage

type CatalogPage struct {
	Tasks        []Summary
	StatusFacets []CatalogStatusFacet
	OwnerFacets  []CatalogOwnerFacet
	NextCursor   string
	HasMore      bool
	Total        int
	Limit        int
}

CatalogPage is one stable, counted task catalog page.

type CatalogQuery

type CatalogQuery struct {
	Scope                CatalogScope
	WorkspaceID          string
	Status               Status
	Priority             Priority
	IncludeDrafts        bool
	ApprovalState        ApprovalState
	OwnerKind            OwnerKind
	OwnerRef             string
	ParentTaskID         string
	WorktreeID           string
	ParticipationChannel string
	Search               string
	Sort                 CatalogSort
	Cursor               string
	Limit                int
}

CatalogQuery captures one bounded task catalog request.

func CatalogQueryWithoutCursor

func CatalogQueryWithoutCursor(query CatalogQuery) CatalogQuery

CatalogQueryWithoutCursor returns the query identity used to encode a next cursor.

func NormalizeCatalogQuery

func NormalizeCatalogQuery(query CatalogQuery) (CatalogQuery, error)

NormalizeCatalogQuery validates and canonicalizes one public task catalog request.

type CatalogReader

type CatalogReader interface {
	ListTaskCatalog(ctx context.Context, query CatalogQuery) (CatalogPage, error)
}

CatalogReader is the batched persistence capability used by public task catalogs.

type CatalogScope

type CatalogScope string

CatalogScope identifies the visibility boundary applied to a catalog query.

func (CatalogScope) Normalize

func (s CatalogScope) Normalize() CatalogScope

Normalize returns the canonical catalog scope.

type CatalogSort

type CatalogSort string

CatalogSort identifies a supported task catalog ordering.

func (CatalogSort) Normalize

func (s CatalogSort) Normalize() CatalogSort

Normalize returns the canonical catalog sort.

type CatalogStatusFacet

type CatalogStatusFacet struct {
	Status Status `json:"status"`
	Count  int    `json:"count"`
}

CatalogStatusFacet is one exact status count before the page cut.

type ClaimCriteria

type ClaimCriteria struct {
	RunID                string         `json:"run_id,omitempty"`
	Scope                Scope          `json:"scope,omitempty"`
	WorkspaceID          string         `json:"workspace_id,omitempty"`
	RunKind              RunKind        `json:"run_kind,omitempty"`
	TargetSessionID      string         `json:"target_session_id,omitempty"`
	ClaimerSessionID     string         `json:"claimer_session_id"`
	ClaimedBy            *ActorIdentity `json:"claimed_by,omitempty"`
	AgentName            string         `json:"agent_name,omitempty"`
	RequiredCapabilities []string       `json:"required_capabilities,omitempty"`
	PriorityMin          int            `json:"priority_min,omitempty"`
	ParticipationChannel string         `json:"participation_channel,omitempty"`
	// WorkspaceActiveRunCap is trusted Service policy and never caller-controlled wire input.
	WorkspaceActiveRunCap int `json:"-"`
	// CallerNetworkParticipation is trusted hook context, never run-selection input.
	CallerNetworkParticipation *participation.Spec  `json:"-"`
	Soul                       *SoulClaimProvenance `json:"soul,omitempty"`
	LeaseDuration              time.Duration        `json:"lease_duration"`
	Now                        time.Time            `json:"now"`
}

ClaimCriteria captures the atomic next-work filters for one claiming session.

func (ClaimCriteria) Normalize

func (c ClaimCriteria) Normalize(defaultNow time.Time) (ClaimCriteria, error)

func (ClaimCriteria) Validate

func (c ClaimCriteria) Validate(path string) error

Validate reports whether the claim criteria is safe to execute transactionally.

type ClaimResult

type ClaimResult struct {
	Task                *Task                        `json:"task,omitempty"`
	Run                 Run                          `json:"run"`
	ClaimToken          string                       `json:"claim_token"`
	LeaseUntil          time.Time                    `json:"lease_until"`
	CoordinationChannel *CoordinationChannelMetadata `json:"coordination_channel,omitempty"`
}

ClaimResult is the successful synchronous claim result. ClaimToken is raw and must not cross public surfaces.

type ClaimedRunSettlement

type ClaimedRunSettlement struct {
	Run               Run
	Task              Task
	StatusTransitions []StatusTransition
}

ClaimedRunSettlement is the durable claim projection without the raw bearer token.

type ClearTaskBlockMutation

type ClearTaskBlockMutation struct {
	TaskID    string        `json:"task_id"`
	BlockID   string        `json:"block_id"`
	ClearedBy ActorIdentity `json:"cleared_by"`
	ClearedAt time.Time     `json:"cleared_at"`
	ClearNote string        `json:"clear_note,omitempty"`
	Actor     ActorContext
}

ClearTaskBlockMutation captures an audited task-block clear.

type CompletedRunHistoryImport

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

CompletedRunHistoryImport is the explicit bootstrap-only boundary for one already-completed historical run. Runtime execution must create queued work through the execution transaction instead.

func NewCompletedRunHistoryImport

func NewCompletedRunHistoryImport(run Run, actor ActorContext) (CompletedRunHistoryImport, error)

NewCompletedRunHistoryImport validates and isolates one completed history snapshot before it reaches persistence.

func (*CompletedRunHistoryImport) Actor

Actor reports the authority responsible for the import.

func (*CompletedRunHistoryImport) Run

func (c *CompletedRunHistoryImport) Run() Run

Run reports an isolated copy of the completed historical snapshot.

type CompletedRunSettlement

type CompletedRunSettlement struct {
	Run               Run
	Task              Task
	StatusTransitions []StatusTransition
	RolledUpRuns      []Run
}

CompletedRunSettlement is the durable result of completing one run and reconciling successful parent-task aggregation in the same transaction.

type ContextBundle

type ContextBundle struct {
	Task               Reference           `json:"task"`
	LatestEventSeq     int64               `json:"latest_event_seq"`
	CurrentRun         *RunSummary         `json:"current_run,omitempty"`
	PriorAttempts      []RunSummary        `json:"prior_attempts"`
	RecentEvents       []TimelineItem      `json:"recent_events"`
	HandoffSummary     string              `json:"handoff_summary,omitempty"`
	Limits             RuntimeLimits       `json:"limits"`
	ExecutionProfile   *ExecutionProfile   `json:"execution_profile,omitempty"`
	ReviewContinuation *ReviewContinuation `json:"review_continuation,omitempty"`
	ReviewHistory      []RunReviewSummary  `json:"review_history"`
}

ContextBundle is the bounded task/run context injected into task sessions.

func NormalizeContextBundle

func NormalizeContextBundle(bundle ContextBundle) ContextBundle

NormalizeContextBundle returns a bundle with stable empty array fields.

type ContextRequest

type ContextRequest struct {
	SessionID string    `json:"session_id"`
	RunID     string    `json:"run_id,omitempty"`
	Now       time.Time `json:"now"`
}

ContextRequest identifies the active lease context one agent session may read.

type CoordinationChannelMetadata

type CoordinationChannelMetadata struct {
	ID                  string    `json:"id"`
	DisplayName         string    `json:"display_name"`
	Purpose             string    `json:"purpose,omitempty"`
	WorkspaceID         string    `json:"workspace_id,omitempty"`
	TaskID              string    `json:"task_id,omitempty"`
	RunID               string    `json:"run_id,omitempty"`
	WorkflowID          string    `json:"workflow_id,omitempty"`
	AllowedMessageKinds []string  `json:"allowed_message_kinds,omitempty"`
	LastActivityAt      time.Time `json:"last_activity_at"`
}

CoordinationChannelMetadata is the safe channel display metadata returned with a claim.

type CoordinatorCompletion

type CoordinatorCompletion struct {
	RunID      string                    `json:"run_id"`
	ClaimToken string                    `json:"claim_token"`
	Plan       CoordinatorCompletionPlan `json:"plan"`
	Actor      ActorContext              `json:"actor"`
	Now        time.Time                 `json:"now"`
}

CoordinatorCompletion captures the token-fenced apply request for one coordinator plan.

func (CoordinatorCompletion) Normalize

func (c CoordinatorCompletion) Normalize(defaultNow time.Time) (CoordinatorCompletion, error)

Normalize returns a validated coordinator completion request with default time applied.

func (CoordinatorCompletion) Validate

func (c CoordinatorCompletion) Validate(path string) error

Validate reports whether the coordinator completion request is internally consistent.

type CoordinatorCompletionPlan

type CoordinatorCompletionPlan struct {
	NodeTasks           []CoordinatorTaskSpec
	Dependencies        []CoordinatorDependencySpec
	NodeRuns            []EnqueueSpec
	RunStops            []CoordinatorStopSpec
	ParentCloses        []CoordinatorParentCloseSpec
	Snapshot            GenerationSnapshot
	PostReserveSnapshot *GenerationSnapshot
	// GenerationInFlight means at least one current-generation node is still live.
	GenerationInFlight bool
	CancellationDrain  bool
	// NextCoordinator is emitted by the gate/carry-forward planner; the task_05 reconciler does not yet populate it.
	NextCoordinator  *EnqueueSpec
	Terminal         *CoordinatorTerminal
	Yield            bool
	PostCommitWakes  []CoordinatorWakeSpec
	PostCommitTimers []CoordinatorTimerSpec
}

CoordinatorCompletionPlan contains all coordinator mutations that task applies atomically.

func (CoordinatorCompletionPlan) Normalize

Normalize returns a coordinator plan with normalized enqueue specs and terminal data.

func (CoordinatorCompletionPlan) Validate

func (p CoordinatorCompletionPlan) Validate(path string) error

Validate reports whether a coordinator completion plan is internally consistent.

type CoordinatorCompletionResult

type CoordinatorCompletionResult struct {
	Run             Run                     `json:"run"`
	EnqueuedRuns    []Run                   `json:"enqueued_runs,omitempty"`
	LoopRunID       string                  `json:"loop_run_id,omitempty"`
	Context         json.RawMessage         `json:"context,omitempty"`
	Paused          bool                    `json:"paused,omitempty"`
	Terminal        bool                    `json:"terminal,omitempty"`
	PlanSuperseded  bool                    `json:"plan_superseded,omitempty"`
	TokensUsed      int64                   `json:"tokens_used,omitempty"`
	Settlement      *CompletedRunSettlement `json:"-"`
	CompletionEvent Event                   `json:"-"`
}

CoordinatorCompletionResult records the durable state written by coordinator finalization.

type CoordinatorControlResult

type CoordinatorControlResult struct {
	Kind    string          `json:"kind"`
	Payload json.RawMessage `json:"payload"`
}

CoordinatorControlResult is a neutral coordinator-owned completion envelope. The owning coordinator validates Payload without introducing a task-domain dependency.

func (CoordinatorControlResult) Validate

func (r CoordinatorControlResult) Validate(path string) error

Validate reports whether a neutral coordinator-control envelope is bounded and well formed.

type CoordinatorDependencySpec

type CoordinatorDependencySpec struct {
	TaskID          string         `json:"task_id"`
	DependsOnTaskID string         `json:"depends_on_task_id"`
	Kind            DependencyKind `json:"kind,omitempty"`
}

CoordinatorDependencySpec describes a node task dependency that must exist before enqueueing runs.

func (CoordinatorDependencySpec) Normalize

Normalize returns a normalized coordinator dependency spec.

func (CoordinatorDependencySpec) Validate

func (s CoordinatorDependencySpec) Validate(path string) error

Validate reports whether a coordinator dependency spec has a valid dependency edge.

type CoordinatorFailure

type CoordinatorFailure struct {
	Kind     string `json:"kind"`
	Code     string `json:"code"`
	Cause    string `json:"cause"`
	Recovery string `json:"recovery"`
}

CoordinatorFailure is the bounded operator-safe diagnostic for coordinator execution failures.

func CoordinatorFailureFromRunFailure

func CoordinatorFailureFromRunFailure(failure RunFailure) (CoordinatorFailure, bool)

CoordinatorFailureFromRunFailure parses a valid typed coordinator failure.

type CoordinatorMode

type CoordinatorMode string

CoordinatorMode identifies task-specific coordinator bootstrap behavior.

func (CoordinatorMode) Normalize

func (m CoordinatorMode) Normalize() CoordinatorMode

Normalize returns the normalized coordinator mode.

type CoordinatorParentCloseSpec

type CoordinatorParentCloseSpec struct {
	ParentLoopRunID string `json:"parent_loop_run_id"`
	ChildLoopRunID  string `json:"child_loop_run_id"`
	Policy          string `json:"policy"`
	ParentStatus    string `json:"parent_status"`
}

CoordinatorParentCloseSpec applies one authored parent-close policy to an owned child Loop.

func (CoordinatorParentCloseSpec) Normalize

Normalize trims a parent-close mutation without changing its authored policy.

func (CoordinatorParentCloseSpec) Validate

func (s CoordinatorParentCloseSpec) Validate(path string) error

Validate rejects parent-close mutations that cannot prove ownership or policy.

type CoordinatorPostCommitHandler

type CoordinatorPostCommitHandler interface {
	ApplyCoordinatorPostCommit(
		context.Context,
		[]CoordinatorParentCloseSpec,
		ActorContext,
	) error
}

CoordinatorPostCommitHandler applies process-side effects after a coordinator plan commits.

type CoordinatorProfile

type CoordinatorProfile struct {
	Mode      CoordinatorMode `json:"mode"`
	AgentName string          `json:"agent_name,omitempty"`
	Provider  string          `json:"provider,omitempty"`
	Model     string          `json:"model,omitempty"`
	Guidance  string          `json:"guidance,omitempty"`
}

CoordinatorProfile supplies optional guidance to the existing coordinator runtime.

type CoordinatorRunner

type CoordinatorRunner interface {
	Run(ctx context.Context, taskRunID RunID) (CoordinatorCompletionPlan, error)
}

CoordinatorRunner builds a pure coordinator completion plan for one claimed coordinator run.

type CoordinatorStopSpec

type CoordinatorStopSpec struct {
	LoopRunID  string `json:"loop_run_id"`
	ReasonCode string `json:"reason_code,omitempty"`
}

CoordinatorStopSpec describes a child loop_run stop requested by a pure coordinator plan.

func (CoordinatorStopSpec) Normalize

Normalize returns a normalized loop stop request.

func (CoordinatorStopSpec) Validate

func (s CoordinatorStopSpec) Validate(path string) error

Validate reports whether a loop stop request names a child loop run.

type CoordinatorTaskSpec

type CoordinatorTaskSpec struct {
	TaskID      string          `json:"task_id"`
	Title       string          `json:"title"`
	Description string          `json:"description,omitempty"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
}

CoordinatorTaskSpec describes a node task that must exist before node runs are queued.

func (CoordinatorTaskSpec) Normalize

Normalize returns a normalized coordinator task spec.

func (CoordinatorTaskSpec) Validate

func (s CoordinatorTaskSpec) Validate(path string) error

Validate reports whether a coordinator task spec has enough data to create a node task.

type CoordinatorTerminal

type CoordinatorTerminal struct {
	Status     string          `json:"status"`
	Cause      string          `json:"cause,omitempty"`
	ReasonCode string          `json:"reason_code,omitempty"`
	GateID     string          `json:"gate_id,omitempty"`
	Details    json.RawMessage `json:"details,omitempty"`
}

CoordinatorTerminal describes the correlated run status selected at a generation boundary.

func (CoordinatorTerminal) Normalize

Normalize returns normalized coordinator terminal data.

func (CoordinatorTerminal) Validate

func (t CoordinatorTerminal) Validate(path string) error

Validate reports whether coordinator terminal data has the minimum persisted shape.

type CoordinatorTimerArmer

type CoordinatorTimerArmer interface {
	ArmCoordinatorTimer(context.Context, CoordinatorTimerSpec, ActorContext) error
}

CoordinatorTimerArmer arms best-effort timers only after coordinator state commits.

type CoordinatorTimerSpec

type CoordinatorTimerSpec struct {
	LoopRunID      string
	Generation     int
	NodeID         string
	ItemIndex      int
	Attempt        int
	IssuedEpoch    int64
	FireAt         time.Time
	IdempotencyKey string
}

CoordinatorTimerSpec describes one best-effort post-commit timer. Durable state remains authoritative and the scheduler backstop recovers missed fires.

func (CoordinatorTimerSpec) Normalize

Normalize returns a stable timer identity and UTC deadline.

func (CoordinatorTimerSpec) Validate

func (s CoordinatorTimerSpec) Validate(path string) error

Validate reports whether the timer can be fenced against one output cell.

type CoordinatorWakeSpec

type CoordinatorWakeSpec struct {
	LoopRunID      string `json:"loop_run_id"`
	IdempotencyKey string `json:"idempotency_key"`
}

CoordinatorWakeSpec describes a coordinator wake to enqueue after the boundary transaction commits.

func (CoordinatorWakeSpec) Normalize

Normalize returns a normalized post-commit wake request.

func (CoordinatorWakeSpec) Validate

func (s CoordinatorWakeSpec) Validate(path string) error

Validate reports whether a post-commit wake has a stable target.

type CreateTask

type CreateTask struct {
	ID                   string                 `json:"id,omitempty"`
	Identifier           string                 `json:"identifier,omitempty"`
	Scope                Scope                  `json:"scope"`
	WorkspaceID          string                 `json:"workspace_id,omitempty"`
	ParentTaskID         string                 `json:"parent_task_id,omitempty"`
	Title                string                 `json:"title"`
	Description          string                 `json:"description,omitempty"`
	Priority             Priority               `json:"priority,omitempty"`
	MaxAttempts          *int                   `json:"max_attempts,omitempty"`
	Draft                bool                   `json:"draft,omitempty"`
	AutoEnqueueOnReady   bool                   `json:"auto_enqueue_on_ready,omitempty"`
	ApprovalPolicy       ApprovalPolicy         `json:"approval_policy,omitempty"`
	Owner                *Ownership             `json:"owner,omitempty"`
	WakeCreator          *bool                  `json:"wake_creator,omitempty"`
	NetworkParticipation *participation.Request `json:"network_participation,omitempty"`
	Metadata             json.RawMessage        `json:"metadata,omitempty"`
}

CreateTask captures the mutable inputs accepted when creating a new task.

func (CreateTask) Validate

func (r CreateTask) Validate(path string) error

Validate reports whether the create-task request is internally consistent.

type CreateTaskBlockMutation

type CreateTaskBlockMutation struct {
	Block           TaskBlock `json:"block"`
	RecurrenceLimit int       `json:"recurrence_limit"`
	Actor           ActorContext
}

CreateTaskBlockMutation inserts one task block and evaluates breaker accounting atomically.

type CreateTaskDefinitionMutation

type CreateTaskDefinitionMutation struct {
	Task    Task
	Profile *ExecutionProfile
	Events  []Event
}

CreateTaskDefinitionMutation commits a task definition, optional execution profile intent, and every causal event as one persistence command.

type DefinitionStore

type DefinitionStore interface {
	CreateTaskDefinition(ctx context.Context, mutation CreateTaskDefinitionMutation) error
	UpdateTaskDefinition(ctx context.Context, mutation *UpdateTaskDefinitionMutation) (ExecutionProfile, error)
	SetTaskExecutionProfile(ctx context.Context, mutation *ExecutionProfileMutation) (ExecutionProfile, error)
	SetTaskWorktreePolicy(ctx context.Context, mutation *WorktreePolicyMutation) (ExecutionProfile, error)
	DeleteTaskExecutionProfile(ctx context.Context, mutation ExecutionProfileDeleteMutation) error
}

DefinitionStore owns atomic task-definition and profile commands.

type DeleteTaskMutationStore

type DeleteTaskMutationStore interface {
	BlockReader
	GetTask(ctx context.Context, id string) (Task, error)
	UpdateTask(ctx context.Context, task Task, actor ActorContext) error
	DeleteTask(ctx context.Context, id string) error
	CountDirectChildren(ctx context.Context, parentTaskID string) (int, error)
	ListDependencies(ctx context.Context, taskID string) ([]Dependency, error)
	ListDependents(ctx context.Context, dependsOnTaskID string) ([]Dependency, error)
	ListTaskRuns(ctx context.Context, query RunQuery) ([]Run, error)
}

DeleteTaskMutationStore is the narrowed persistence surface required to execute task deletion and dependent reconciliation as one unit.

type DeleteTaskTransactionStore

type DeleteTaskTransactionStore interface {
	WithDeleteTaskTransaction(ctx context.Context, fn func(DeleteTaskMutationStore) error) error
}

DeleteTaskTransactionStore optionally exposes transactional delete-task execution so the manager can roll back the primary delete when dependent reconciliation fails.

type Dependency

type Dependency struct {
	TaskID          string         `json:"task_id"`
	DependsOnTaskID string         `json:"depends_on_task_id"`
	Kind            DependencyKind `json:"kind"`
	CreatedAt       time.Time      `json:"created_at"`
}

Dependency is the durable edge record connecting one task to a blocking dependency.

func (Dependency) Validate

func (d Dependency) Validate() error

Validate reports whether the dependency edge contains the canonical persisted shape.

type DependencyKind

type DependencyKind string

DependencyKind identifies the semantic meaning of one dependency edge.

const (
	// DependencyKindBlocks identifies a dependency that must resolve before the task may proceed.
	DependencyKindBlocks DependencyKind = "blocks"
)

func (DependencyKind) Normalize

func (k DependencyKind) Normalize() DependencyKind

Normalize returns the normalized representation of the dependency kind.

func (DependencyKind) Validate

func (k DependencyKind) Validate(path string) error

Validate reports whether the dependency kind is supported.

type DependencyReference

type DependencyReference struct {
	TaskID          string         `json:"task_id"`
	DependsOnTaskID string         `json:"depends_on_task_id"`
	Kind            DependencyKind `json:"kind"`
	CreatedAt       time.Time      `json:"created_at"`
	DependsOn       Reference      `json:"depends_on"`
}

DependencyReference enriches one dependency edge with the referenced blocker identity.

type DependencyStore

type DependencyStore interface {
	CreateDependency(ctx context.Context, dependency Dependency) error
	DeleteDependency(ctx context.Context, taskID string, dependsOnID string) error
	ListDependencies(ctx context.Context, taskID string) ([]Dependency, error)
	ListDependents(ctx context.Context, dependsOnTaskID string) ([]Dependency, error)
	CountDependencies(ctx context.Context, taskID string) (int, error)
	HasDependencyPath(ctx context.Context, fromTaskID string, toTaskID string) (bool, error)
}

DependencyStore is the persistence surface for durable dependency edges.

type EnqueueRun

type EnqueueRun struct {
	TaskID                     string                 `json:"task_id"`
	RunKind                    RunKind                `json:"run_kind,omitempty"`
	LoopRunID                  string                 `json:"loop_run_id,omitempty"`
	IdempotencyKey             string                 `json:"idempotency_key,omitempty"`
	NetworkParticipation       *participation.Request `json:"network_participation,omitempty"`
	NetworkParticipationSource participation.Source   `json:"-"`
	DesignationGroupID         string                 `json:"designation_group_id,omitempty"`
	WorktreePerRun             bool                   `json:"worktree_per_run,omitempty"`
	Metadata                   json.RawMessage        `json:"metadata,omitempty"`
}

EnqueueRun captures the mutable inputs accepted when queuing a task run.

func (EnqueueRun) Validate

func (r EnqueueRun) Validate(path string) error

Validate reports whether the enqueue-run request is internally consistent.

type EnqueueSpec

type EnqueueSpec struct {
	TaskID                       string              `json:"task_id"`
	RunID                        string              `json:"run_id,omitempty"`
	RunKind                      RunKind             `json:"run_kind,omitempty"`
	LoopRunID                    string              `json:"loop_run_id,omitempty"`
	IdempotencyKey               string              `json:"idempotency_key,omitempty"`
	DesignationGroupID           string              `json:"designation_group_id,omitempty"`
	ResolvedNetworkParticipation *participation.Spec `json:"resolved_network_participation,omitempty"`
	Metadata                     json.RawMessage     `json:"metadata,omitempty"`
}

EnqueueSpec describes one task_run reservation requested by the coordinator plan.

func (EnqueueSpec) Normalize

func (s EnqueueSpec) Normalize() EnqueueSpec

Normalize returns a normalized enqueue spec.

func (EnqueueSpec) Validate

func (s EnqueueSpec) Validate(path string) error

Validate reports whether an enqueue spec can become a queue reservation.

type Event

type Event struct {
	ID        string          `json:"id"`
	TaskID    string          `json:"task_id"`
	RunID     string          `json:"run_id,omitempty"`
	EventType string          `json:"event_type"`
	Actor     ActorIdentity   `json:"actor"`
	Origin    Origin          `json:"origin"`
	Payload   json.RawMessage `json:"payload,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
}

Event is the immutable audit record emitted for task-domain actions.

func NewCoordinatorRunCompletedEvent

func NewCoordinatorRunCompletedEvent(
	eventID string,
	run Run,
	taskRecord Task,
	actor ActorContext,
	timestamp time.Time,
) (Event, error)

NewCoordinatorRunCompletedEvent builds the canonical event committed by the coordinator state transaction. The store supplies the durable event ID while the task domain owns the public payload shape.

func (Event) Validate

func (e Event) Validate() error

Validate reports whether the audit event contains the canonical persisted shape.

type EventCommitObserverStore

type EventCommitObserverStore interface {
	SetTaskEventCommitObserver(observer EventObserver)
}

EventCommitObserverStore publishes immutable task events only after the transaction that owns them has committed.

type EventObserver

type EventObserver interface {
	OnTaskEvent(ctx context.Context, record EventRecord)
}

EventObserver receives immutable task events after durable persistence.

type EventQuery

type EventQuery struct {
	TaskID    string `json:"task_id,omitempty"`
	RunID     string `json:"run_id,omitempty"`
	EventType string `json:"event_type,omitempty"`
	Limit     int    `json:"limit,omitempty"`
}

EventQuery captures the supported list filters for task-event reads.

func (EventQuery) Validate

func (q EventQuery) Validate(path string) error

Validate reports whether the task-event query filters are internally consistent.

type EventRecord

type EventRecord struct {
	Sequence int64 `json:"sequence"`
	Event    Event `json:"event"`
}

EventRecord is one immutable task event plus its stable stream sequence.

type EventRecordQuery

type EventRecordQuery struct {
	TaskID        string `json:"task_id,omitempty"`
	AfterSequence int64  `json:"after_sequence,omitempty"`
	Limit         int    `json:"limit,omitempty"`
	Descending    bool   `json:"descending,omitempty"`
	AllTasks      bool   `json:"-"`
}

EventRecordQuery captures low-level task event record reads that include a stable sequence.

func (EventRecordQuery) Validate

func (q EventRecordQuery) Validate(path string) error

Validate reports whether the sequenced event record query is internally consistent.

type EventSequenceStore

type EventSequenceStore interface {
	GetTaskEventRecord(ctx context.Context, eventID string) (EventRecord, error)
	ListTaskEventRecords(ctx context.Context, query EventRecordQuery) ([]EventRecord, error)
}

EventSequenceStore is the persistence surface for stable task event sequencing used by live reads.

type EventStore

type EventStore interface {
	CreateTaskEvent(ctx context.Context, event Event) error
	ListTaskEvents(ctx context.Context, query EventQuery) ([]Event, error)
	TaskWakeEventExists(ctx context.Context, taskID string, wakeEventID string) (bool, error)
}

EventStore is the persistence surface for immutable task audit events.

type Execution

type Execution struct {
	Task        Task            `json:"task"`
	Run         Run             `json:"run"`
	Action      ExecutionAction `json:"action"`
	ExistingRun bool            `json:"existing_run,omitempty"`
}

Execution captures the task and run created or resolved at the explicit execution boundary.

type ExecutionAction

type ExecutionAction string

ExecutionAction identifies the operator action that crossed the create-versus-execute lifecycle boundary.

const (
	// ExecutionActionStart records an explicit operator start request.
	ExecutionActionStart ExecutionAction = "start"
	// ExecutionActionPublish records a draft publish request that also starts execution.
	ExecutionActionPublish ExecutionAction = "publish"
	// ExecutionActionApproval records an approval request that also starts execution.
	ExecutionActionApproval ExecutionAction = "approval"
)

type ExecutionMutationStore

type ExecutionMutationStore interface {
	DeleteTaskMutationStore
	ExecutionProfileStore
	IdempotencyStore
	CreateTaskEvent(ctx context.Context, event Event) error
	ReserveQueuedRun(
		ctx context.Context,
		reservation QueueRunReservation,
	) (Task, Run, bool, error)
}

ExecutionMutationStore exposes the persistence operations that one publish/start/approve/enqueue command may use while holding a single writer transaction.

type ExecutionProfile

type ExecutionProfile struct {
	TaskID               string                 `json:"task_id"`
	Coordinator          CoordinatorProfile     `json:"coordinator"`
	Worker               WorkerProfile          `json:"worker"`
	Review               ReviewProfile          `json:"review"`
	Participants         ParticipantPolicy      `json:"participants"`
	Sandbox              SandboxPolicy          `json:"sandbox"`
	Worktree             WorktreePolicy         `json:"worktree"`
	Runtime              RuntimePolicy          `json:"runtime"`
	NetworkParticipation *participation.Request `json:"network_participation,omitempty"`
	CreatedAt            time.Time              `json:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at"`
}

ExecutionProfile is the typed task-owned orchestration selection state.

func DefaultExecutionProfile

func DefaultExecutionProfile(taskID string) ExecutionProfile

DefaultExecutionProfile returns the inherit-mode profile for one task.

func (*ExecutionProfile) Normalize

Normalize returns a canonical copy with trimmed fields, default modes, and stable selector sets.

func (*ExecutionProfile) Validate

Validate reports whether the profile can be persisted as typed orchestration state.

type ExecutionProfileDeleteMutation

type ExecutionProfileDeleteMutation struct {
	TaskID string
	Event  Event
}

ExecutionProfileDeleteMutation commits one profile deletion and its event.

type ExecutionProfileMutation

type ExecutionProfileMutation struct {
	Profile ExecutionProfile
	Event   Event
}

ExecutionProfileMutation commits one profile replacement and its event.

type ExecutionProfileStore

type ExecutionProfileStore interface {
	GetExecutionProfile(ctx context.Context, taskID string) (ExecutionProfile, error)
	UpsertExecutionProfile(ctx context.Context, profile *ExecutionProfile) (ExecutionProfile, error)
	DeleteExecutionProfile(ctx context.Context, taskID string) error
}

ExecutionProfileStore is the persistence surface for task-owned execution profiles.

type ExecutionProfileValidationOptions

type ExecutionProfileValidationOptions struct {
	AllowProviderOverride       bool
	AllowSandboxNone            bool
	AllowSandboxRef             bool
	DefaultWorktreeMode         WorktreeMode
	MaxCoordinatorGuidanceBytes int
}

ExecutionProfileValidationOptions carries config-backed gates without coupling task to config.

func DefaultExecutionProfileValidationOptions

func DefaultExecutionProfileValidationOptions() ExecutionProfileValidationOptions

DefaultExecutionProfileValidationOptions returns the permissive built-in gates.

type ExecutionRequest

type ExecutionRequest struct {
	IdempotencyKey       string                 `json:"idempotency_key,omitempty"`
	NetworkParticipation *participation.Request `json:"network_participation,omitempty"`
	Metadata             json.RawMessage        `json:"metadata,omitempty"`
}

ExecutionRequest captures the mutable inputs accepted when an operator publish, start, or approval action enqueues executable work.

func (ExecutionRequest) Validate

func (r ExecutionRequest) Validate(path string) error

Validate reports whether the task execution request is internally consistent.

type ExecutionTransactionStore

type ExecutionTransactionStore interface {
	WithTaskExecutionTransaction(
		ctx context.Context,
		fn func(ExecutionMutationStore) error,
	) error
}

ExecutionTransactionStore owns the atomic execution-command boundary.

type ExpireTaskBlocksMutation

type ExpireTaskBlocksMutation struct {
	Now       time.Time           `json:"now"`
	ClearedBy ActorIdentity       `json:"cleared_by"`
	Targets   []BlockExpiryTarget `json:"targets"`
}

ExpireTaskBlocksMutation finalizes a fixed snapshot of expired transient blocks.

type ExpireTaskBlocksResult

type ExpireTaskBlocksResult struct {
	Blocks []TaskBlock `json:"blocks"`
}

ExpireTaskBlocksResult describes expired transient blocks finalized by a sweep.

type ExpiredLeaseEventPayload

type ExpiredLeaseEventPayload struct {
	PreviousStatus               RunStatus           `json:"previous_status"`
	Status                       RunStatus           `json:"status"`
	TaskStatus                   Status              `json:"task_status"`
	Reason                       string              `json:"reason,omitempty"`
	SessionID                    string              `json:"session_id,omitempty"`
	LeaseUntil                   time.Time           `json:"lease_until"`
	PreviousTokenHash            string              `json:"previous_claim_token_hash,omitempty"`
	ResolvedNetworkParticipation *participation.Spec `json:"resolved_network_participation"`
}

ExpiredLeaseEventPayload is the canonical audit payload for an expired task-run lease.

type ExpiredLeaseRecovery

type ExpiredLeaseRecovery struct {
	Now    time.Time    `json:"now"`
	Reason string       `json:"reason,omitempty"`
	Limit  int          `json:"limit,omitempty"`
	Actor  ActorContext `json:"-"`
}

ExpiredLeaseRecovery captures deterministic recovery of stale task-run leases.

func (ExpiredLeaseRecovery) Normalize

func (r ExpiredLeaseRecovery) Normalize(defaultNow time.Time) (ExpiredLeaseRecovery, error)

Normalize returns a validated expired-lease recovery request.

func (ExpiredLeaseRecovery) Validate

func (r ExpiredLeaseRecovery) Validate(path string) error

Validate reports whether the expired-lease recovery request is internally consistent.

type ExpiredLeaseRecoveryResult

type ExpiredLeaseRecoveryResult struct {
	Run                    Run       `json:"run"`
	PreviousRunStatus      RunStatus `json:"previous_run_status"`
	PreviousSessionID      string    `json:"previous_session_id,omitempty"`
	PreviousLeaseUntil     time.Time `json:"previous_lease_until"`
	PreviousClaimTokenHash string    `json:"previous_claim_token_hash,omitempty"`
	Reason                 string    `json:"reason,omitempty"`
	Exhausted              bool      `json:"exhausted,omitempty"`
}

ExpiredLeaseRecoveryResult records one recovered lease and its previous owner state.

type FailedRunLeaseMutation

type FailedRunLeaseMutation struct {
	Run     Run
	Failure RunFailure
}

FailedRunLeaseMutation is the fenced run mutation with its canonical failure.

type FailedRunLeaseSettlement

type FailedRunLeaseSettlement struct {
	Run               Run
	Task              Task
	StatusTransitions []StatusTransition
}

FailedRunLeaseSettlement is the durable task projection produced with a lease failure.

type ForceFailRun

type ForceFailRun struct {
	Reason   string          `json:"reason"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

ForceFailRun captures one operator/agent forced failure request.

type ForceFailRunMutation

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

ForceFailRunMutation declares one forced failure authorized against an exact observed ownership snapshot.

func NewForceFailRunMutation

func NewForceFailRunMutation(previous Run, reason string, now time.Time) ForceFailRunMutation

NewForceFailRunMutation captures the exact queued or claimed run to fail.

func (ForceFailRunMutation) Fence

Fence reports the exact source snapshot required by the command.

func (ForceFailRunMutation) Now

func (m ForceFailRunMutation) Now() time.Time

Now reports the command timestamp.

func (ForceFailRunMutation) Reason

func (m ForceFailRunMutation) Reason() string

Reason reports the requested failure diagnostic.

type ForceRecoveryOptions

type ForceRecoveryOptions struct {
	AllowAgentForce    bool `json:"allow_agent_force"`
	RateLimitPerMinute int  `json:"rate_limit_per_minute,omitempty"`
}

ForceRecoveryOptions controls operator/agent force-operation policy.

type ForceReleaseRun

type ForceReleaseRun struct {
	Reason   string          `json:"reason,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

ForceReleaseRun captures one operator/agent force release request.

type ForceReleaseRunMutation

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

ForceReleaseRunMutation declares one force release authorized against an exact observed ownership snapshot. Callers cannot construct its fence field independently from the run they authorized.

func NewForceReleaseRunMutation

func NewForceReleaseRunMutation(previous Run, now time.Time) ForceReleaseRunMutation

NewForceReleaseRunMutation captures the exact claimed run to release.

func (ForceReleaseRunMutation) Fence

Fence reports the exact source snapshot required by the command.

func (ForceReleaseRunMutation) Now

Now reports the command timestamp.

type ForceRunInputInvalidation

type ForceRunInputInvalidation struct {
	QueueGeneration int64 `json:"queue_generation,omitempty"`
	CanceledInputs  int   `json:"canceled_inputs,omitempty"`
}

ForceRunInputInvalidation reports the session-input fence committed with a force mutation.

type ForceRunMutationResult

type ForceRunMutationResult struct {
	Previous Run `json:"previous"`
	Run      Run `json:"run"`
}

ForceRunMutationResult records the before/after state for one force mutation.

type GenerationSnapshot

type GenerationSnapshot struct {
	LoopRunID  string `json:"loop_run_id,omitempty"`
	Generation int    `json:"generation,omitempty"`
	Payload    any    `json:"-"`
}

GenerationSnapshot is opaque to internal/task; internal/loop owns its payload schema.

type GenerationStateFinalizer

type GenerationStateFinalizer interface {
	WriteGenerationSnapshot(ctx context.Context, tx Tx, snap GenerationSnapshot) error
}

GenerationStateFinalizer writes generation state inside task's coordinator transaction.

type HallucinatedTaskRefsError

type HallucinatedTaskRefsError struct {
	RunID          string
	TaskID         string
	RunStatus      RunStatus
	SessionID      string
	ClaimTokenHash string
	ClaimedTaskIDs []string
	InvalidTaskIDs []string
}

HallucinatedTaskRefsError carries the rejected completion claim without exposing the raw claim token.

func NewHallucinatedTaskRefsError

func NewHallucinatedTaskRefsError(
	run Run,
	claimedTaskIDs []string,
	invalidTaskIDs []string,
) *HallucinatedTaskRefsError

NewHallucinatedTaskRefsError builds the typed completion-claim rejection.

func (*HallucinatedTaskRefsError) Error

func (e *HallucinatedTaskRefsError) Error() string

func (*HallucinatedTaskRefsError) Unwrap

func (e *HallucinatedTaskRefsError) Unwrap() error

Unwrap exposes the stable sentinel used by API and agent-tool callers.

type HeartbeatRunLeaseSettlement

type HeartbeatRunLeaseSettlement struct {
	Run  Run
	Task Task
}

HeartbeatRunLeaseSettlement is the durable task projection produced with a heartbeat.

type IdempotencyStore

type IdempotencyStore interface {
	GetTaskRunByIdempotencyKey(ctx context.Context, key string, origin Origin) (Run, error)
	SaveTaskRunIdempotency(ctx context.Context, record RunIdempotency) error
}

IdempotencyStore is the persistence surface for non-human run idempotency tracking.

type InboxCursor

type InboxCursor struct {
	Unread       bool      `json:"unread"`
	ActivityAt   time.Time `json:"activity_at"`
	PriorityRank int       `json:"priority_rank"`
	TaskID       string    `json:"task_id"`
}

InboxCursor captures the last returned row's complete ordering tuple.

func DecodeInboxCursor

func DecodeInboxCursor(query InboxQuery, actor ActorIdentity) (InboxCursor, error)

DecodeInboxCursor verifies and decodes one actor- and query-bound inbox cursor.

type InboxItem

type InboxItem struct {
	Task             Reference      `json:"task"`
	Lane             InboxLane      `json:"lane"`
	ApprovalPolicy   ApprovalPolicy `json:"approval_policy,omitempty"`
	ApprovalState    ApprovalState  `json:"approval_state,omitempty"`
	BlockingReason   string         `json:"blocking_reason,omitempty"`
	LatestActivityAt time.Time      `json:"latest_activity_at"`
	Run              *RunSummary    `json:"run,omitempty"`
	Triage           TriageState    `json:"triage"`
}

InboxItem is one action-ready task inbox item.

type InboxLane

type InboxLane string

InboxLane identifies one actor-scoped inbox grouping.

const (
	// InboxLaneMyWork identifies directly assigned or actively owned work.
	InboxLaneMyWork InboxLane = "my_work"
	// InboxLaneApprovals identifies approval-gated work awaiting a decision.
	InboxLaneApprovals InboxLane = "approvals"
	// InboxLaneFailedRuns identifies tasks whose latest execution failed.
	InboxLaneFailedRuns InboxLane = "failed_runs"
	// InboxLaneBlocked identifies blocked tasks that are not awaiting approval.
	InboxLaneBlocked InboxLane = "blocked"
	// InboxLaneArchived identifies tasks archived by the current actor.
	InboxLaneArchived InboxLane = "archived"
)

func InboxLanes

func InboxLanes(filter InboxLane) []InboxLane

InboxLanes returns the canonical lane order for a filtered or complete view.

func (InboxLane) Normalize

func (l InboxLane) Normalize() InboxLane

Normalize returns the canonical inbox lane.

func (InboxLane) Validate

func (l InboxLane) Validate(path string) error

Validate ensures the inbox lane is supported.

type InboxLaneGroup

type InboxLaneGroup struct {
	Lane        InboxLane   `json:"lane"`
	Count       int         `json:"count"`
	UnreadCount int         `json:"unread_count"`
	Items       []InboxItem `json:"items,omitempty"`
}

InboxLaneGroup groups page items by lane while preserving exact filtered counts.

type InboxPage

type InboxPage struct {
	Groups         []InboxLaneGroup
	StatusFacets   []InboxStatusFacet
	PriorityFacets []InboxPriorityFacet
	NextCursor     string
	HasMore        bool
	Total          int
	UnreadTotal    int
	ArchivedTotal  int
	Limit          int
}

InboxPage is one global stable page with exact pre-cursor counts.

type InboxPriorityFacet

type InboxPriorityFacet struct {
	Priority Priority `json:"priority"`
	Count    int      `json:"count"`
}

InboxPriorityFacet is one exact filtered priority count.

type InboxQuery

type InboxQuery struct {
	Scope       CatalogScope
	WorkspaceID string
	WorktreeID  string
	OwnerKind   OwnerKind
	OwnerRef    string
	Lane        InboxLane
	Status      Status
	Priority    Priority
	Unread      *bool
	Search      string
	Cursor      string
	Limit       int
}

InboxQuery captures one bounded actor-scoped task inbox request.

func (InboxQuery) Validate

func (q InboxQuery) Validate() error

Validate reports whether the query fields are supported without decoding an actor-bound cursor.

type InboxReader

type InboxReader interface {
	ListTaskInbox(ctx context.Context, query InboxQuery, actor ActorIdentity) (InboxPage, error)
}

InboxReader is the batched persistence capability consumed by Observer.

type InboxStatusFacet

type InboxStatusFacet struct {
	Status Status `json:"status"`
	Count  int    `json:"count"`
}

InboxStatusFacet is one exact filtered status count.

type InspectEventSummary

type InspectEventSummary struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"`
	SessionID string    `json:"session_id,omitempty"`
	TaskID    string    `json:"task_id,omitempty"`
	RunID     string    `json:"run_id,omitempty"`
	Outcome   string    `json:"outcome,omitempty"`
	Summary   string    `json:"summary,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

InspectEventSummary is the recent event summary projection used by task inspect.

type InspectNextAction

type InspectNextAction string

InspectNextAction is the deterministic next-step hint emitted by task inspect.

const (
	InspectNextActionClaimAvailable    InspectNextAction = "claim_available"
	InspectNextActionWaitingForSession InspectNextAction = "waiting_for_session"
	InspectNextActionStranded          InspectNextAction = "stranded"
	InspectNextActionRunning           InspectNextAction = "running"
	InspectNextActionRecoveryRequired  InspectNextAction = "recovery_required"
	InspectNextActionTerminal          InspectNextAction = "terminal"
)

type InspectRunSummary

type InspectRunSummary struct {
	RunID                   string    `json:"run_id"`
	TaskID                  string    `json:"task_id"`
	Status                  RunStatus `json:"status"`
	ClaimTokenHashTruncated string    `json:"claim_token_hash_truncated,omitempty"`
	LeaseUntil              time.Time `json:"lease_until"`
	HeartbeatAt             time.Time `json:"heartbeat_at"`
	HeartbeatAgeSeconds     *int64    `json:"heartbeat_age_seconds,omitempty"`
	Retries                 int       `json:"retries,omitempty"`
	LastErrorSummary        string    `json:"last_error_summary,omitempty"`
	FailureKind             string    `json:"failure_kind,omitempty"`
	BoundSessionID          string    `json:"bound_session_id,omitempty"`
	StartedAt               time.Time `json:"started_at"`
	EndedAt                 time.Time `json:"ended_at"`
	PreviousRunID           string    `json:"previous_run_id,omitempty"`
	QueuedAt                time.Time `json:"queued_at"`
	Attempt                 int       `json:"attempt"`
	RecoveryCount           int       `json:"recovery_count"`
}

InspectRunSummary is the redacted run projection used by task inspect.

type InspectSchedulerState

type InspectSchedulerState struct {
	Paused    bool      `json:"paused"`
	PausedBy  string    `json:"paused_by,omitempty"`
	PausedAt  time.Time `json:"paused_at"`
	Reason    string    `json:"reason,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
}

InspectSchedulerState captures the read-only scheduler pause state used by diagnostics.

type InspectSessionSummary

type InspectSessionSummary struct {
	SessionID      string    `json:"session_id"`
	State          string    `json:"state,omitempty"`
	AgentName      string    `json:"agent_name,omitempty"`
	ProviderName   string    `json:"provider_name,omitempty"`
	WorkspaceID    string    `json:"workspace_id,omitempty"`
	StartedAt      time.Time `json:"started_at"`
	LastActivityAt time.Time `json:"last_activity_at"`
	StopReason     string    `json:"stop_reason,omitempty"`
	FailureKind    string    `json:"failure_kind,omitempty"`
}

InspectSessionSummary is the session projection used by task inspect.

type InspectStateReader

type InspectStateReader interface {
	ListSessions(ctx context.Context, query store.SessionListQuery) ([]store.SessionInfo, error)
	ListEventSummaries(ctx context.Context, query store.EventSummaryQuery) ([]store.EventSummary, error)
	GetSchedulerPauseState(ctx context.Context) (InspectSchedulerState, error)
}

InspectStateReader supplies read-only runtime state for task inspect diagnostics.

type InspectTarget

type InspectTarget string

InspectTarget identifies whether an inspect response was requested by task or run id.

const (
	// InspectTargetTask reports an inspect request rooted at a task id.
	InspectTargetTask InspectTarget = "task"
	// InspectTargetRun reports an inspect request rooted at a run id.
	InspectTargetRun InspectTarget = "run"
)

type InspectView

type InspectView struct {
	Target                InspectTarget                       `json:"target"`
	Task                  Summary                             `json:"task"`
	CurrentRun            *InspectRunSummary                  `json:"current_run,omitempty"`
	BoundSession          *InspectSessionSummary              `json:"bound_session,omitempty"`
	RecentRuns            []InspectRunSummary                 `json:"recent_runs,omitempty"`
	RecentEvents          []InspectEventSummary               `json:"recent_events,omitempty"`
	Scheduler             InspectSchedulerState               `json:"scheduler"`
	Diagnostics           []diagnosticcontract.DiagnosticItem `json:"diagnostics,omitempty"`
	NextAction            InspectNextAction                   `json:"next_action"`
	AsOf                  time.Time                           `json:"as_of"`
	EligibleSessionCount  int                                 `json:"-"`
	SessionCatalogPresent bool                                `json:"-"`
}

InspectView is the task-domain read-only snapshot behind CLI/API inspect.

type LeaseCompletion

type LeaseCompletion struct {
	RunID          string    `json:"run_id"`
	ClaimToken     string    `json:"claim_token"`
	Result         RunResult `json:"result"`
	CreatedTaskIDs []string  `json:"created_task_ids,omitempty"`
	TokensUsed     int64     `json:"tokens_used,omitempty"`
	Now            time.Time `json:"now"`
	Actor          ActorContext
}

LeaseCompletion captures a token-fenced successful terminal transition.

func (LeaseCompletion) Normalize

func (c LeaseCompletion) Normalize(defaultNow time.Time) (LeaseCompletion, error)

Normalize returns a validated completion request with default time applied.

func (LeaseCompletion) Validate

func (c LeaseCompletion) Validate(path string) error

Validate reports whether the completion request is internally consistent.

type LeaseFailure

type LeaseFailure struct {
	RunID      string     `json:"run_id"`
	ClaimToken string     `json:"claim_token"`
	Failure    RunFailure `json:"failure"`
	TokensUsed int64      `json:"tokens_used,omitempty"`
	Now        time.Time  `json:"now"`
	Actor      ActorContext
}

LeaseFailure captures a token-fenced failed terminal transition.

func (LeaseFailure) Normalize

func (f LeaseFailure) Normalize(defaultNow time.Time) (LeaseFailure, error)

Normalize returns a validated failure request with default time applied.

func (LeaseFailure) Validate

func (f LeaseFailure) Validate(path string) error

Validate reports whether the failure request is internally consistent.

type LeaseHeartbeat

type LeaseHeartbeat struct {
	RunID         string        `json:"run_id"`
	ClaimToken    string        `json:"claim_token"`
	LeaseDuration time.Duration `json:"lease_duration"`
	Now           time.Time     `json:"now"`
	TokensUsed    int64         `json:"tokens_used,omitempty"`
	Actor         ActorContext  `json:"-"`
}

LeaseHeartbeat captures a token-fenced lease extension request.

func (LeaseHeartbeat) Normalize

func (h LeaseHeartbeat) Normalize(defaultNow time.Time) (LeaseHeartbeat, error)

Normalize returns a validated heartbeat request with default time and lease duration applied.

func (LeaseHeartbeat) Validate

func (h LeaseHeartbeat) Validate(path string) error

Validate reports whether the heartbeat request is internally consistent.

type LeaseRelease

type LeaseRelease struct {
	RunID      string       `json:"run_id"`
	ClaimToken string       `json:"claim_token"`
	Reason     string       `json:"reason,omitempty"`
	Now        time.Time    `json:"now"`
	Actor      ActorContext `json:"-"`
}

LeaseRelease captures a token-fenced release request.

func (LeaseRelease) Normalize

func (r LeaseRelease) Normalize(defaultNow time.Time) (LeaseRelease, error)

Normalize returns a validated release request with default time applied.

func (LeaseRelease) Validate

func (r LeaseRelease) Validate(path string) error

Validate reports whether the release request is internally consistent.

type LeaseSessionBinding

type LeaseSessionBinding struct {
	RunID      string       `json:"run_id"`
	ClaimToken string       `json:"claim_token"`
	SessionID  string       `json:"session_id"`
	Now        time.Time    `json:"now"`
	Actor      ActorContext `json:"-"`
}

LeaseSessionBinding captures a token-fenced session attachment for one leased run.

func (LeaseSessionBinding) Normalize

func (b LeaseSessionBinding) Normalize(defaultNow time.Time) (LeaseSessionBinding, error)

Normalize returns a validated session-binding request with default time applied.

func (LeaseSessionBinding) Validate

func (b LeaseSessionBinding) Validate(path string) error

Validate reports whether the session-binding request is internally consistent.

type LeaseSettlementMutationStore

type LeaseSettlementMutationStore interface {
	DeleteTaskMutationStore
	CreateTaskEvent(ctx context.Context, event Event) error
	ClaimNextRun(ctx context.Context, criteria ClaimCriteria) (ClaimResult, error)
	HeartbeatRunLease(ctx context.Context, heartbeat LeaseHeartbeat) (Run, error)
	BindLeasedRunSession(ctx context.Context, binding LeaseSessionBinding) (Run, error)
	ReleaseRunLease(ctx context.Context, release LeaseRelease) (Run, error)
	ListActiveSessionRunLeases(ctx context.Context, sessionID string) ([]Run, error)
	ReleaseSessionRunLease(
		ctx context.Context,
		previous Run,
		release SessionLeaseRelease,
		actor ActorContext,
	) (Run, error)
	FailRunLeaseMutation(ctx context.Context, failure LeaseFailure) (FailedRunLeaseMutation, error)
	GetTaskRun(ctx context.Context, id string) (Run, error)
}

LeaseSettlementMutationStore exposes the persistence operations that one claim, heartbeat, release, or failure settlement may use inside one transaction.

type LeaseSettlementTransactionStore

type LeaseSettlementTransactionStore interface {
	WithLeaseSettlementTransaction(
		ctx context.Context,
		action string,
		fn func(LeaseSettlementMutationStore) error,
	) error
}

LeaseSettlementTransactionStore owns the atomic lease-settlement boundary.

type LiveService

type LiveService interface {
	Timeline(ctx context.Context, taskID string, query TimelineQuery, actor ActorContext) ([]TimelineItem, error)
	Stream(ctx context.Context, taskID string, query StreamQuery, actor ActorContext) (<-chan StreamEvent, error)
	Tree(ctx context.Context, taskID string, actor ActorContext) (*TreeView, error)
	RunDetail(ctx context.Context, runID string, actor ActorContext) (*RunDetailView, error)
}

LiveService exposes task-native live and run-detail reads for downstream API handlers.

type Manager

type Manager interface {
	CreateTask(ctx context.Context, spec CreateTask, actor ActorContext) (*Task, error)
	CreateChildTask(ctx context.Context, parentTaskID string, spec CreateTask, actor ActorContext) (*Task, error)
	DeleteTask(ctx context.Context, id string, actor ActorContext) error
	UpdateTask(ctx context.Context, id string, patch Patch, actor ActorContext) (*Task, error)
	PublishTask(ctx context.Context, id string, req ExecutionRequest, actor ActorContext) (*Execution, error)
	StartTask(ctx context.Context, id string, req ExecutionRequest, actor ActorContext) (*Execution, error)
	ApproveTask(ctx context.Context, id string, req ExecutionRequest, actor ActorContext) (*Execution, error)
	RejectTask(ctx context.Context, id string, actor ActorContext) (*Task, error)
	CancelTask(ctx context.Context, id string, req CancelTask, actor ActorContext) (*Task, error)
	PauseTask(ctx context.Context, id string, req PauseTaskRequest, actor ActorContext) (*Task, error)
	ResumeTask(ctx context.Context, id string, req ResumeTaskRequest, actor ActorContext) (*Task, error)
	BlockTask(ctx context.Context, req BlockRequest, actor ActorContext) (TaskBlock, error)
	RecoverTask(ctx context.Context, id string, note string, actor ActorContext) (*Task, error)
	ClearTaskBlock(
		ctx context.Context,
		taskID string,
		blockID string,
		note string,
		actor ActorContext,
	) (TaskBlock, error)
	ExpireTaskBlocks(ctx context.Context, now time.Time, actor ActorContext) (ExpireTaskBlocksResult, error)
	ListTaskBlocks(ctx context.Context, taskID string, includeCleared bool, actor ActorContext) ([]TaskBlock, error)
	MarkTaskRead(ctx context.Context, id string, actor ActorContext) (TriageState, error)
	ArchiveTask(ctx context.Context, id string, actor ActorContext) (TriageState, error)
	DismissTask(ctx context.Context, id string, actor ActorContext) (TriageState, error)

	GetExecutionProfile(ctx context.Context, taskID string, actor ActorContext) (ExecutionProfile, error)
	SetExecutionProfile(
		ctx context.Context,
		taskID string,
		profile *ExecutionProfile,
		actor ActorContext,
	) (ExecutionProfile, error)
	SetWorktreePolicy(
		ctx context.Context,
		taskID string,
		policy WorktreePolicy,
		actor ActorContext,
	) (ExecutionProfile, error)
	DeleteExecutionProfile(ctx context.Context, taskID string, actor ActorContext) error

	RequestRunReview(ctx context.Context, req RunReviewRequest, actor ActorContext) (RunReview, bool, error)
	GetRunReview(ctx context.Context, reviewID string, actor ActorContext) (RunReview, error)
	RecordRunReview(ctx context.Context, req RecordRunReviewRequest, actor ActorContext) (RunReviewResult, error)
	BindRunReviewSession(
		ctx context.Context,
		req BindRunReviewSessionRequest,
		actor ActorContext,
	) (RunReviewBinding, error)
	LookupRunReviewForSession(ctx context.Context, sessionID string, actor ActorContext) (RunReviewBinding, error)
	ListRunReviews(ctx context.Context, query RunReviewQuery, actor ActorContext) ([]RunReview, error)

	AddDependency(ctx context.Context, spec AddDependency, actor ActorContext) error
	RemoveDependency(ctx context.Context, taskID string, dependsOnID string, actor ActorContext) error

	EnqueueRun(ctx context.Context, spec EnqueueRun, actor ActorContext) (*Run, error)
	ClaimNextRun(ctx context.Context, criteria ClaimCriteria, actor ActorContext) (*ClaimResult, error)
	StartRun(ctx context.Context, runID string, req StartRun, actor ActorContext) (*Run, error)
	AttachRunSession(ctx context.Context, runID string, sessionID string, actor ActorContext) (*Run, error)
	HeartbeatRunLease(ctx context.Context, heartbeat LeaseHeartbeat, actor ActorContext) (*Run, error)
	ReleaseRunLease(ctx context.Context, release LeaseRelease, actor ActorContext) (*Run, error)
	ForceReleaseRun(ctx context.Context, runID string, release ForceReleaseRun, actor ActorContext) (*Run, error)
	ForceFailRun(ctx context.Context, runID string, failure ForceFailRun, actor ActorContext) (*Run, error)
	RetryRun(ctx context.Context, runID string, retry RetryRunRequest, actor ActorContext) (*RetryRunResult, error)
	RecoverRun(
		ctx context.Context,
		runID string,
		req RecoverRunRequest,
		actor ActorContext,
	) (*RetryRunResult, error)
	BulkForceReleaseRuns(ctx context.Context, req BulkForceRunRequest, actor ActorContext) (BulkForceRunResult, error)
	BulkForceFailRuns(ctx context.Context, req BulkForceRunRequest, actor ActorContext) (BulkForceRunResult, error)
	CompleteRunLease(ctx context.Context, completion LeaseCompletion, actor ActorContext) (*Run, error)
	FailRunLease(ctx context.Context, failure LeaseFailure, actor ActorContext) (*Run, error)
	SettleNetworkWake(
		ctx context.Context,
		settlement NetworkWakeSettlement,
		actor ActorContext,
	) (*NetworkWakeSettlementResult, error)
	CompleteRun(ctx context.Context, runID string, result RunResult, actor ActorContext) (*Run, error)
	FailRun(ctx context.Context, runID string, failure RunFailure, actor ActorContext) (*Run, error)
	CancelRun(ctx context.Context, runID string, req CancelRun, actor ActorContext) (*Run, error)
	RecoverExpiredRunLeases(
		ctx context.Context,
		recovery ExpiredLeaseRecovery,
		actor ActorContext,
	) ([]ExpiredLeaseRecoveryResult, error)
	SchedulerStatus(ctx context.Context, actor ActorContext) (SchedulerStatus, error)
	PauseScheduler(ctx context.Context, req SchedulerPauseRequest, actor ActorContext) (SchedulerStatus, error)
	ResumeScheduler(ctx context.Context, req SchedulerResumeRequest, actor ActorContext) (SchedulerStatus, error)
	DrainScheduler(ctx context.Context, req SchedulerDrainRequest, actor ActorContext) (SchedulerDrainResult, error)
	SchedulerBacklog(ctx context.Context, query SchedulerBacklogQuery, actor ActorContext) (SchedulerBacklog, error)

	GetTask(ctx context.Context, id string, actor ActorContext) (*View, error)
	InspectTask(ctx context.Context, taskID string, actor ActorContext) (*InspectView, error)
	InspectRun(ctx context.Context, runID string, actor ActorContext) (*InspectView, error)
	ListTaskRuns(ctx context.Context, taskID string, query RunQuery, actor ActorContext) ([]Run, error)
	ListTasks(ctx context.Context, query Query, actor ActorContext) ([]Summary, error)
	ListTaskCatalog(ctx context.Context, query CatalogQuery, actor ActorContext) (CatalogPage, error)

	LiveService
}

Manager is the task-domain authority for task and run lifecycle operations.

type NeedsAttention

type NeedsAttention struct {
	Reason string        `json:"reason"`
	At     time.Time     `json:"at"`
	By     ActorIdentity `json:"by"`
}

NeedsAttention stores task-level escalation metadata.

type NeedsAttentionClearMutation

type NeedsAttentionClearMutation struct {
	TaskID    string       `json:"task_id"`
	Note      string       `json:"note,omitempty"`
	Actor     ActorContext `json:"actor"`
	ClearedAt time.Time    `json:"cleared_at"`
}

NeedsAttentionClearMutation clears task-level escalation metadata.

type NeedsAttentionClearResult

type NeedsAttentionClearResult struct {
	Task  Task        `json:"task"`
	Event EventRecord `json:"event"`
}

NeedsAttentionClearResult is the task projection and exact audit record committed by one clear.

type NeedsAttentionMutation

type NeedsAttentionMutation struct {
	TaskID   string        `json:"task_id"`
	Reason   string        `json:"reason"`
	Actor    ActorIdentity `json:"actor"`
	MarkedAt time.Time     `json:"marked_at"`
	Origin   Origin        `json:"origin"`
}

NeedsAttentionMutation captures task-level escalation metadata.

type NetworkWakeBootRecoveryMutation

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

NetworkWakeBootRecoveryMutation authorizes one daemon-owned recovery of an exact taskless network-wake run and carries the actor needed by its durable network lifecycle ledger entry.

func NewNetworkWakeBootRecoveryMutation

func NewNetworkWakeBootRecoveryMutation(
	previous Run,
	recovery RunBootRecovery,
	actor ActorContext,
	now time.Time,
) NetworkWakeBootRecoveryMutation

NewNetworkWakeBootRecoveryMutation captures an exact taskless wake recovery.

func (NetworkWakeBootRecoveryMutation) Actor

Actor reports the trusted daemon actor that owns the recovery.

func (NetworkWakeBootRecoveryMutation) FailureText

func (m NetworkWakeBootRecoveryMutation) FailureText() string

FailureText reports the sanitized terminal diagnostic for fail recovery.

func (NetworkWakeBootRecoveryMutation) Fence

Fence reports the exact source snapshot required by the command.

func (NetworkWakeBootRecoveryMutation) Now

Now reports the recovery timestamp.

func (NetworkWakeBootRecoveryMutation) Recovery

Recovery reports the normalized recovery decision.

type NetworkWakeSettlement

type NetworkWakeSettlement struct {
	WorkspaceID     string
	WakeID          string
	TaskRunID       string
	ClaimToken      string
	TargetSessionID string
	OwnerKey        string
	Outcome         store.NetworkWakeOutcome
	Now             time.Time
	Actor           ActorContext
}

NetworkWakeSettlement is the complete token-fenced terminal command for one taskless wake.

func (NetworkWakeSettlement) Normalize

func (s NetworkWakeSettlement) Normalize(defaultNow time.Time) (NetworkWakeSettlement, error)

Normalize canonicalizes a settlement command before the transaction boundary.

func (NetworkWakeSettlement) Validate

func (s NetworkWakeSettlement) Validate() error

Validate rejects incomplete identity, authority, and outcome combinations.

type NetworkWakeSettlementResult

type NetworkWakeSettlementResult struct {
	Run       Run
	Outcome   store.NetworkWakeOutcome
	Duplicate bool
}

NetworkWakeSettlementResult reports the single committed terminal truth.

type NominalRunMutationResult

type NominalRunMutationResult struct {
	Previous Run
	Run      Run
}

NominalRunMutationResult records the exact source and committed run snapshots for one non-terminal lifecycle mutation.

type OperatorTaskContextRequest

type OperatorTaskContextRequest struct {
	TaskID string    `json:"task_id"`
	Now    time.Time `json:"now"`
}

OperatorTaskContextRequest identifies the task context an operator read path may request.

type Option

type Option func(*managerOptions)

Option customizes Service construction.

func WithBlockRecurrenceLimit

func WithBlockRecurrenceLimit(limit int) Option

WithBlockRecurrenceLimit overrides the same-kind re-block count before task escalation.

func WithCancelGracePeriod

func WithCancelGracePeriod(timeout time.Duration) Option

WithCancelGracePeriod overrides the cooperative-stop grace period used before requesting forced session termination during task-driven cancellation.

func WithCoordinatorPostCommitHandler

func WithCoordinatorPostCommitHandler(handler CoordinatorPostCommitHandler) Option

WithCoordinatorPostCommitHandler injects process-side effects that must run only after commit.

func WithCoordinatorRunner

func WithCoordinatorRunner(runner CoordinatorRunner) Option

WithCoordinatorRunner injects the in-daemon generation coordinator runner.

func WithCoordinatorTerminalHookStatusValidator

func WithCoordinatorTerminalHookStatusValidator(validator func(string) bool) Option

WithCoordinatorTerminalHookStatusValidator injects the subset that should emit loop terminal hooks.

func WithCoordinatorTerminalStatusValidator

func WithCoordinatorTerminalStatusValidator(validator func(string) bool) Option

WithCoordinatorTerminalStatusValidator injects the owner-defined loop-run status vocabulary.

func WithCoordinatorTimerArmer

func WithCoordinatorTimerArmer(armer CoordinatorTimerArmer) Option

WithCoordinatorTimerArmer injects the daemon-owned retry timer fast path.

func WithEventObserver

func WithEventObserver(observer EventObserver) Option

WithEventObserver injects a best-effort observer for immutable task events.

func WithExecutionProfileValidationOptions

func WithExecutionProfileValidationOptions(options ExecutionProfileValidationOptions) Option

WithExecutionProfileValidationOptions injects config-backed profile gates.

func WithForceRecoveryOptions

func WithForceRecoveryOptions(options ForceRecoveryOptions) Option

WithForceRecoveryOptions injects config-backed force-operation policy.

func WithGenerationStateFinalizer

func WithGenerationStateFinalizer(finalizer GenerationStateFinalizer) Option

WithGenerationStateFinalizer injects the generation-state writer used inside coordinator finalization.

func WithIDGenerator

func WithIDGenerator(newID func(prefix string) (string, error)) Option

WithIDGenerator overrides identifier generation for deterministic tests.

func WithInspectStateReader

func WithInspectStateReader(reader InspectStateReader) Option

WithInspectStateReader injects read-only runtime state used by task inspect.

func WithManagerNow

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

WithManagerNow overrides the manager clock for deterministic tests.

func WithParticipationResolver

func WithParticipationResolver(resolver participation.Resolver) Option

WithParticipationResolver injects the single network participation resolver used before task-run reservation.

func WithRunReviewRequestedObserver

func WithRunReviewRequestedObserver(observer RunReviewRequestedObserver) Option

WithRunReviewRequestedObserver injects a best-effort observer for newly persisted run review requests.

func WithRuntimeViewReader

func WithRuntimeViewReader(reader RuntimeViewReader) Option

WithRuntimeViewReader injects optional session telemetry enrichment for task live reads.

func WithSessionExecutor

func WithSessionExecutor(sessions SessionExecutor) Option

WithSessionExecutor injects the runtime session bridge used by later task-run lifecycle operations.

func WithStarvationAge

func WithStarvationAge(age time.Duration) Option

WithStarvationAge overrides the queued-age threshold used by scheduler-status starvation counts so the status surface agrees with the scheduler's own threshold.

func WithStore

func WithStore(store Store) Option

WithStore injects the durable task-domain store consumed by the manager.

func WithTaskRunHooks

func WithTaskRunHooks(hooks RunHookDispatcher) Option

WithTaskRunHooks injects the task-run hook bridge used at authoritative run transitions.

func WithWakeNotifier

func WithWakeNotifier(notifier WakeNotifier) Option

WithWakeNotifier injects the creator-session wake bridge used at task transitions.

func WithWorkAdmissionChecker

func WithWorkAdmissionChecker(checker admission.Checker) Option

WithWorkAdmissionChecker injects the daemon-owned new-work gate.

func WithWorkspaceAccessPolicy

func WithWorkspaceAccessPolicy(policy workspaceaccess.Policy) Option

WithWorkspaceAccessPolicy injects the cross-workspace decision policy.

func WithWorkspaceActiveRunCap

func WithWorkspaceActiveRunCap(limit int) Option

WithWorkspaceActiveRunCap injects the trusted concurrent-run limit applied to workspace-scoped task execution. Zero disables the limit.

func WithWorktreeRefValidator

func WithWorktreeRefValidator(validator WorktreeRefValidator) Option

WithWorktreeRefValidator injects attached same-workspace worktree validation.

type Origin

type Origin struct {
	Kind OriginKind `json:"kind"`
	Ref  string     `json:"ref"`
}

Origin is the immutable technical ingress context attached to task and run writes.

func (Origin) Validate

func (o Origin) Validate(path string) error

Validate reports whether the origin contains a supported kind and non-empty reference.

type OriginKind

type OriginKind string

OriginKind identifies the technical ingress surface that produced a task-domain write.

const (
	// OriginKindCLI identifies CLI ingress.
	OriginKindCLI OriginKind = "cli"
	// OriginKindWeb identifies web UI ingress.
	OriginKindWeb OriginKind = "web"
	// OriginKindUDS identifies local UDS ingress.
	OriginKindUDS OriginKind = "uds"
	// OriginKindHTTP identifies HTTP ingress.
	OriginKindHTTP OriginKind = "http"
	// OriginKindAutomation identifies automation ingress.
	OriginKindAutomation OriginKind = "automation"
	// OriginKindExtension identifies extension ingress.
	OriginKindExtension OriginKind = "extension"
	// OriginKindNetwork identifies network ingress.
	OriginKindNetwork OriginKind = "network"
	// OriginKindAgentSession identifies session tool-call ingress.
	OriginKindAgentSession OriginKind = "agent_session"
	// OriginKindDaemon identifies daemon-owned internal ingress.
	OriginKindDaemon OriginKind = "daemon"
)

func (OriginKind) Normalize

func (k OriginKind) Normalize() OriginKind

Normalize returns the normalized representation of the origin kind.

func (OriginKind) Validate

func (k OriginKind) Validate(path string) error

Validate reports whether the origin kind is supported.

type OwnerKind

type OwnerKind string

OwnerKind identifies who currently owns a task operationally.

const (
	// OwnerKindHuman identifies a human owner.
	OwnerKindHuman OwnerKind = "human"
	// OwnerKindAgentSession identifies an agent-session owner.
	OwnerKindAgentSession OwnerKind = "agent_session"
	// OwnerKindAutomation identifies an automation owner.
	OwnerKindAutomation OwnerKind = "automation"
	// OwnerKindExtension identifies an extension owner.
	OwnerKindExtension OwnerKind = "extension"
	// OwnerKindNetworkPeer identifies a network-peer owner.
	OwnerKindNetworkPeer OwnerKind = "network_peer"
	// OwnerKindPool identifies pooled ownership without a dedicated assignee.
	OwnerKindPool OwnerKind = "pool"
)

func OwnerKindForActor

func OwnerKindForActor(kind ActorKind) OwnerKind

OwnerKindForActor maps an actor identity kind to its operational owner kind so actor-scoped reads can filter tasks by the same ownership the inbox applies.

func (OwnerKind) Normalize

func (k OwnerKind) Normalize() OwnerKind

Normalize returns the normalized representation of the owner kind.

func (OwnerKind) Validate

func (k OwnerKind) Validate(path string) error

Validate reports whether the owner kind is supported.

type Ownership

type Ownership struct {
	Kind OwnerKind `json:"kind"`
	Ref  string    `json:"ref"`
}

Ownership is the optional mutable operational assignee attached to a task.

func (Ownership) IsZero

func (o Ownership) IsZero() bool

IsZero reports whether the ownership value is empty.

func (Ownership) Validate

func (o Ownership) Validate(path string) error

Validate reports whether the ownership value contains a supported kind and non-empty reference.

type ParticipantPolicy

type ParticipantPolicy struct {
	AllowedChannelIDs     []string `json:"allowed_channel_ids,omitempty"`
	PreferredChannelIDs   []string `json:"preferred_channel_ids,omitempty"`
	AllowedPeerIDs        []string `json:"allowed_peer_ids,omitempty"`
	PreferredPeerIDs      []string `json:"preferred_peer_ids,omitempty"`
	AllowedAgentNames     []string `json:"allowed_agent_names,omitempty"`
	PreferredAgentNames   []string `json:"preferred_agent_names,omitempty"`
	RequiredCapabilities  []string `json:"required_capabilities,omitempty"`
	PreferredCapabilities []string `json:"preferred_capabilities,omitempty"`
}

ParticipantPolicy is an upper-bound routing policy, not a permission grant.

type Patch

type Patch struct {
	Title                *string                `json:"title,omitempty"`
	Description          *string                `json:"description,omitempty"`
	Priority             *Priority              `json:"priority,omitempty"`
	MaxAttempts          *int                   `json:"max_attempts,omitempty"`
	AutoEnqueueOnReady   *bool                  `json:"auto_enqueue_on_ready,omitempty"`
	ApprovalPolicy       *ApprovalPolicy        `json:"approval_policy,omitempty"`
	Metadata             *json.RawMessage       `json:"metadata,omitempty"`
	Owner                *Ownership             `json:"owner,omitempty"`
	ClearOwner           bool                   `json:"clear_owner,omitempty"`
	NetworkParticipation *participation.Request `json:"network_participation,omitempty"`
}

Patch captures the mutable task fields accepted by update operations.

func (Patch) Validate

func (p Patch) Validate(path string) error

Validate reports whether the task patch contains at least one mutable field and valid values.

type PauseMutation

type PauseMutation struct {
	TaskID   string    `json:"task_id"`
	Actor    string    `json:"actor"`
	Reason   string    `json:"reason"`
	PausedAt time.Time `json:"paused_at"`
}

PauseMutation captures one persisted per-task pause write.

type PauseState

type PauseState struct {
	TaskID          string    `json:"task_id"`
	Paused          bool      `json:"paused"`
	PausedBy        string    `json:"paused_by,omitempty"`
	PausedAt        time.Time `json:"paused_at,omitzero"`
	PausedReason    string    `json:"paused_reason,omitempty"`
	EffectivePaused bool      `json:"effective_paused"`
	PausedByTaskID  string    `json:"paused_by_task_id,omitempty"`
}

PauseState reports direct and inherited pause state for one task.

type PauseTaskRequest

type PauseTaskRequest struct {
	Reason   string          `json:"reason"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

PauseTaskRequest captures one per-task pause request.

type PendingTerminalRunCommand

type PendingTerminalRunCommand struct {
	RunID        string
	SessionID    string
	Phase        TerminalRunCommandPhase
	StopRequired bool
}

PendingTerminalRunCommand is the safe daemon-facing projection of one internal recovery obligation. It deliberately omits receipt, actor, payload, workspace, claim hash, and lease data.

type Priority

type Priority string

Priority identifies the operator-facing urgency assigned to one task.

const (
	// PriorityLow identifies the lowest urgency.
	PriorityLow Priority = "low"
	// PriorityMedium identifies the default urgency.
	PriorityMedium Priority = "medium"
	// PriorityHigh identifies elevated urgency.
	PriorityHigh Priority = "high"
	// PriorityUrgent identifies the highest urgency.
	PriorityUrgent Priority = "urgent"
	// DefaultPriority is the canonical priority used when callers omit the field.
	DefaultPriority Priority = PriorityMedium
)

func (Priority) Normalize

func (p Priority) Normalize() Priority

Normalize returns the normalized representation of the task priority.

func (Priority) Validate

func (p Priority) Validate(path string) error

Validate reports whether the task priority is one of the supported values.

type Query

type Query struct {
	Scope         Scope         `json:"scope,omitempty"`
	WorkspaceID   string        `json:"workspace_id,omitempty"`
	Status        Status        `json:"status,omitempty"`
	Priority      Priority      `json:"priority,omitempty"`
	ApprovalState ApprovalState `json:"approval_state,omitempty"`
	OwnerKind     OwnerKind     `json:"owner_kind,omitempty"`
	OwnerRef      string        `json:"owner_ref,omitempty"`
	ParentTaskID  string        `json:"parent_task_id,omitempty"`
	Search        string        `json:"search,omitempty"`
	CreatedByKind ActorKind     `json:"created_by_kind,omitempty"`
	CreatedByRef  string        `json:"created_by_ref,omitempty"`
	Limit         int           `json:"limit,omitempty"`
}

Query captures the supported list filters for task reads.

func (Query) Validate

func (q Query) Validate(path string) error

Validate reports whether the task-query filters are internally consistent.

type QueueRunReservation

type QueueRunReservation struct {
	TaskID               string             `json:"task_id"`
	RunID                string             `json:"run_id"`
	RunKind              RunKind            `json:"run_kind,omitempty"`
	LoopRunID            string             `json:"loop_run_id,omitempty"`
	IdempotencyKey       string             `json:"idempotency_key,omitempty"`
	Origin               Origin             `json:"origin"`
	NetworkSpec          participation.Spec `json:"network_spec"`
	DesignationGroupID   string             `json:"designation_group_id,omitempty"`
	ResolvedWorktreeMode WorktreeMode       `json:"resolved_worktree_mode"`
	ResolvedWorktreeRef  string             `json:"resolved_worktree_ref,omitempty"`
	Metadata             json.RawMessage    `json:"metadata,omitempty"`
	QueuedAt             time.Time          `json:"queued_at"`
}

QueueRunReservation captures the canonical store-level queue reservation input.

func (QueueRunReservation) Validate

func (r QueueRunReservation) Validate(path string) error

Validate reports whether the store-level queue reservation input is internally consistent.

type RecordRunReviewRequest

type RecordRunReviewRequest struct {
	ReviewID string           `json:"review_id"`
	RunID    string           `json:"run_id"`
	Verdict  RunReviewVerdict `json:"verdict"`
}

RecordRunReviewRequest captures an authoritative persisted review verdict write.

func (RecordRunReviewRequest) Normalize

Normalize returns a canonical verdict-recording request.

func (RecordRunReviewRequest) Validate

func (r RecordRunReviewRequest) Validate(path string) error

Validate reports whether the verdict-recording request can identify a review and run.

type RecordStore

type RecordStore interface {
	CreateTask(ctx context.Context, task Task) error
	DeleteTask(ctx context.Context, id string) error
	UpdateTask(ctx context.Context, task Task, actor ActorContext) error
	GetTask(ctx context.Context, id string) (Task, error)
	ListTasks(ctx context.Context, query Query) ([]Summary, error)
	CountDirectChildren(ctx context.Context, parentTaskID string) (int, error)
}

RecordStore is the persistence surface for durable task records.

type RecoverRunMutation

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

RecoverRunMutation declares one needs-attention recovery authorized against an exact observed ownership snapshot.

func NewRecoverRunMutation

func NewRecoverRunMutation(
	previous Run,
	newRunID string,
	origin Origin,
	reason string,
	metadata json.RawMessage,
	queuedAt time.Time,
) RecoverRunMutation

NewRecoverRunMutation captures the exact needs-attention source and the immutable inputs for its replacement run.

func (RecoverRunMutation) Fence

Fence reports the exact source snapshot required by the command.

func (RecoverRunMutation) Metadata

func (m RecoverRunMutation) Metadata() json.RawMessage

Metadata reports an isolated copy of the replacement run metadata.

func (RecoverRunMutation) NewRunID

func (m RecoverRunMutation) NewRunID() string

NewRunID reports the replacement run identity.

func (RecoverRunMutation) Origin

func (m RecoverRunMutation) Origin() Origin

Origin reports the replacement run origin.

func (RecoverRunMutation) QueuedAt

func (m RecoverRunMutation) QueuedAt() time.Time

QueuedAt reports the replacement run enqueue time.

func (RecoverRunMutation) Reason

func (m RecoverRunMutation) Reason() string

Reason reports the recovery diagnostic.

type RecoverRunRequest

type RecoverRunRequest struct {
	Reason   string          `json:"reason,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

RecoverRunRequest captures one operator/agent recovery request for a needs_attention run.

type Reference

type Reference struct {
	ID              string     `json:"id"`
	Identifier      string     `json:"identifier,omitempty"`
	Title           string     `json:"title"`
	Status          Status     `json:"status"`
	Priority        Priority   `json:"priority,omitempty"`
	Owner           *Ownership `json:"owner,omitempty"`
	Scope           Scope      `json:"scope"`
	WorkspaceID     string     `json:"workspace_id,omitempty"`
	LatestEventSeq  int64      `json:"latest_event_seq"`
	Paused          bool       `json:"paused,omitempty"`
	EffectivePaused bool       `json:"effective_paused,omitempty"`
	PausedByTaskID  string     `json:"paused_by_task_id,omitempty"`
}

Reference is the human-meaningful task identity used in enriched read models.

type ReleasedRunLeaseSettlement

type ReleasedRunLeaseSettlement struct {
	Run               Run
	PreviousRun       Run
	Task              Task
	StatusTransitions []StatusTransition
}

ReleasedRunLeaseSettlement is the durable task projection produced with a release.

type ResourceAuthorizer

type ResourceAuthorizer interface {
	AuthorizeTask(ctx context.Context, actor ActorContext, task Task) error
	AuthorizeTaskScope(ctx context.Context, actor ActorContext, scope Scope, workspaceID string) error
}

ResourceAuthorizer owns task-resource visibility and mutation policy.

type ResumeMutation

type ResumeMutation struct {
	TaskID    string    `json:"task_id"`
	ResumedAt time.Time `json:"resumed_at"`
}

ResumeMutation captures one persisted per-task resume write.

type ResumeTaskRequest

type ResumeTaskRequest struct {
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

ResumeTaskRequest captures one per-task resume request.

type RetryRunMutation

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

RetryRunMutation declares one retry authorized against an exact observed failed-run snapshot.

func NewRetryRunMutation

func NewRetryRunMutation(
	previous Run,
	newRunID string,
	origin Origin,
	metadata json.RawMessage,
	queuedAt time.Time,
) RetryRunMutation

NewRetryRunMutation captures the exact failed source and immutable inputs for its replacement run.

func (RetryRunMutation) Fence

Fence reports the exact failed source snapshot required by the command.

func (RetryRunMutation) Metadata

func (m RetryRunMutation) Metadata() json.RawMessage

Metadata reports an isolated copy of the replacement run metadata.

func (RetryRunMutation) NewRunID

func (m RetryRunMutation) NewRunID() string

NewRunID reports the replacement run identity.

func (RetryRunMutation) Origin

func (m RetryRunMutation) Origin() Origin

Origin reports the replacement run origin.

func (RetryRunMutation) QueuedAt

func (m RetryRunMutation) QueuedAt() time.Time

QueuedAt reports the replacement run enqueue time.

type RetryRunRequest

type RetryRunRequest struct {
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

RetryRunRequest captures one operator/agent retry request.

type RetryRunResult

type RetryRunResult struct {
	PreviousRun Run `json:"previous_run"`
	Run         Run `json:"run"`
}

RetryRunResult records the source terminal run and the newly queued retry.

type ReviewContinuation

type ReviewContinuation struct {
	ReviewID          string   `json:"review_id"`
	ReviewedRunID     string   `json:"reviewed_run_id"`
	ReviewRound       int      `json:"review_round"`
	Outcome           string   `json:"outcome"`
	Reason            string   `json:"reason"`
	MissingWork       []string `json:"missing_work"`
	NextRoundGuidance string   `json:"next_round_guidance"`
}

ReviewContinuation is the rejected-review guidance that produced a continuation run.

type ReviewPolicy

type ReviewPolicy string

ReviewPolicy identifies when a terminal task run needs a review gate.

const (
	// ReviewPolicyNone disables review gating.
	ReviewPolicyNone ReviewPolicy = "none"
	// ReviewPolicyOnSuccess requests review only after a successful run.
	ReviewPolicyOnSuccess ReviewPolicy = "on_success"
	// ReviewPolicyOnFailure requests review only after a failed or canceled run.
	ReviewPolicyOnFailure ReviewPolicy = "on_failure"
	// ReviewPolicyAlways requests review after every terminal run.
	ReviewPolicyAlways ReviewPolicy = "always"
)

func (ReviewPolicy) MatchesRunStatus

func (p ReviewPolicy) MatchesRunStatus(status RunStatus) bool

MatchesRunStatus reports whether this policy applies to a terminal run status.

func (ReviewPolicy) Normalize

func (p ReviewPolicy) Normalize() ReviewPolicy

Normalize returns the normalized review policy value.

func (ReviewPolicy) Validate

func (p ReviewPolicy) Validate(path string) error

Validate reports whether the review policy is one of the supported values.

type ReviewProfile

type ReviewProfile struct {
	AgentName             string   `json:"agent_name,omitempty"`
	Provider              string   `json:"provider,omitempty"`
	Model                 string   `json:"model,omitempty"`
	AllowedAgentNames     []string `json:"allowed_agent_names,omitempty"`
	PreferredAgentNames   []string `json:"preferred_agent_names,omitempty"`
	AllowedChannelIDs     []string `json:"allowed_channel_ids,omitempty"`
	PreferredChannelIDs   []string `json:"preferred_channel_ids,omitempty"`
	AllowedPeerIDs        []string `json:"allowed_peer_ids,omitempty"`
	PreferredPeerIDs      []string `json:"preferred_peer_ids,omitempty"`
	RequiredCapabilities  []string `json:"required_capabilities,omitempty"`
	PreferredCapabilities []string `json:"preferred_capabilities,omitempty"`
}

ReviewProfile narrows reviewer execution shape; verdict authority stays in task review APIs.

type Run

type Run struct {
	ID             string         `json:"id"`
	TaskID         string         `json:"task_id"`
	WorkspaceID    string         `json:"workspace_id,omitempty"`
	Attempt        int32          `json:"attempt"`
	RecoveryCount  int32          `json:"recovery_count"`
	RunKind        RunKind        `json:"run_kind,omitempty"`
	Status         RunStatus      `json:"status"`
	LoopRunID      string         `json:"loop_run_id,omitempty"`
	PreviousRunID  string         `json:"previous_run_id,omitempty"`
	FailureKind    string         `json:"failure_kind,omitempty"`
	ClaimedBy      *ActorIdentity `json:"claimed_by,omitempty"`
	SessionID      string         `json:"session_id,omitempty"`
	Origin         Origin         `json:"origin"`
	IdempotencyKey string         `json:"idempotency_key,omitempty"`
	*RunNetworkState
	*RunWorktreeState
	DesignationGroupID    string            `json:"designation_group_id,omitempty"`
	ClaimTokenHash        string            `json:"claim_token_hash,omitempty"`
	LeaseUntil            time.Time         `json:"lease_until"`
	HeartbeatAt           time.Time         `json:"heartbeat_at"`
	RequiredCapabilities  []string          `json:"required_capabilities,omitempty"`
	PreferredCapabilities []string          `json:"preferred_capabilities,omitempty"`
	Review                *RunReviewLineage `json:"review,omitempty"`
	Metadata              json.RawMessage   `json:"metadata,omitempty"`
	QueuedAt              time.Time         `json:"queued_at"`
	ClaimedAt             time.Time         `json:"claimed_at"`
	StartedAt             time.Time         `json:"started_at"`
	EndedAt               time.Time         `json:"ended_at"`
	TokensUsed            int64             `json:"tokens_used,omitempty"`
	Error                 string            `json:"error,omitempty"`
	Result                json.RawMessage   `json:"result,omitempty"`
}

Run is the durable execution record for one task attempt.

func (Run) IsLoopWorker

func (r Run) IsLoopWorker() bool

IsLoopWorker reports whether this run is a loop-correlated worker node.

func (Run) IsNetworkWake

func (r Run) IsNetworkWake() bool

IsNetworkWake reports whether this run is taskless durable Network work.

func (Run) IsTaskAnchored

func (r Run) IsTaskAnchored() bool

IsTaskAnchored reports whether task state and projections own this run.

func (Run) NetworkSpecSnapshot

func (r Run) NetworkSpecSnapshot() participation.Spec

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

func (Run) NetworkWakeCorrelation

func (r Run) NetworkWakeCorrelation() (wakeID, targetSessionID, ownerKey string)

NetworkWakeCorrelation returns the optional durable wake correlation tuple.

func (Run) ResolvedWorktreeModeValue

func (r Run) ResolvedWorktreeModeValue() WorktreeMode

ResolvedWorktreeModeValue returns the immutable worktree mode snapshot.

func (Run) ResolvedWorktreeRefValue

func (r Run) ResolvedWorktreeRefValue() string

ResolvedWorktreeRefValue returns the optional immutable worktree reference.

func (*Run) SetNetworkState

func (r *Run) SetNetworkState(
	spec participation.Spec,
	wakeID string,
	targetSessionID string,
	ownerKey string,
)

SetNetworkState replaces the immutable participation and wake correlation state.

func (*Run) SetResolvedWorktreeMode

func (r *Run) SetResolvedWorktreeMode(mode WorktreeMode)

SetResolvedWorktreeMode updates the immutable mode snapshot.

func (*Run) SetResolvedWorktreeRef

func (r *Run) SetResolvedWorktreeRef(ref string)

SetResolvedWorktreeRef updates the immutable reference snapshot.

func (*Run) SetWorktreeID

func (r *Run) SetWorktreeID(worktreeID string)

SetWorktreeID updates the bound worktree identity without changing the snapshot policy.

func (*Run) SetWorktreeState

func (r *Run) SetWorktreeState(worktreeID string, mode WorktreeMode, ref string)

SetWorktreeState replaces the run's worktree binding snapshot.

func (Run) Validate

func (r Run) Validate() error

Validate reports whether the task-run record contains the canonical persisted shape.

func (Run) WorktreeIDValue

func (r Run) WorktreeIDValue() string

WorktreeIDValue returns the optional bound worktree identity.

type RunBootRecovery

type RunBootRecovery struct {
	Action         RunBootRecoveryAction `json:"action"`
	Reason         string                `json:"reason,omitempty"`
	SessionState   string                `json:"session_state,omitempty"`
	Classification string                `json:"classification,omitempty"`
	Detail         string                `json:"detail,omitempty"`
	StopRequired   bool                  `json:"stop_required,omitempty"`
}

RunBootRecovery captures one daemon-owned recovery decision for an in-flight run discovered during boot reconciliation.

func (RunBootRecovery) Validate

func (r RunBootRecovery) Validate(path string) error

Validate reports whether the boot-recovery request contains one supported recovery action.

type RunBootRecoveryAction

type RunBootRecoveryAction string

RunBootRecoveryAction identifies the manager-owned recovery action applied to a non-terminal run during daemon startup reconciliation.

const (
	// RunBootRecoveryRequeue resets one claimed run back to the durable queue.
	RunBootRecoveryRequeue RunBootRecoveryAction = "requeue"
	// RunBootRecoveryMarkRunning promotes one live attached run into running.
	RunBootRecoveryMarkRunning RunBootRecoveryAction = "mark_running"
	// RunBootRecoveryFail marks one orphaned attached run as failed.
	RunBootRecoveryFail RunBootRecoveryAction = "fail"
)

func (RunBootRecoveryAction) Normalize

Normalize returns the normalized representation of the boot-recovery action.

func (RunBootRecoveryAction) Validate

func (a RunBootRecoveryAction) Validate(path string) error

Validate reports whether the boot-recovery action is supported.

type RunBootRecoveryMutation

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

RunBootRecoveryMutation authorizes one daemon recovery of an exact task-anchored run. Only the non-terminal requeue and mark-running actions are represented here; failure continues through the terminal mutation boundary.

func NewRunBootRecoveryMutation

func NewRunBootRecoveryMutation(
	previous Run,
	action RunBootRecoveryAction,
	startedAt time.Time,
) RunBootRecoveryMutation

NewRunBootRecoveryMutation captures the source run and recovery action.

func (RunBootRecoveryMutation) Action

Action reports the requested daemon recovery action.

func (RunBootRecoveryMutation) Fence

Fence reports the exact source snapshot required by the command.

func (RunBootRecoveryMutation) StartedAt

func (m RunBootRecoveryMutation) StartedAt() time.Time

StartedAt reports the execution timestamp used by mark-running recovery.

type RunDesignation

type RunDesignation struct {
	GroupID string
	Index   int
	Brief   string
}

RunDesignation is the compact assignment slice carried by designated fan-out runs.

func DesignationFromRun

func DesignationFromRun(run Run) (RunDesignation, bool)

DesignationFromRun extracts the fan-out assignment metadata from a task run.

func (RunDesignation) Summary

Summary returns the prompt/API-safe projection of a run designation.

type RunDesignationSummary

type RunDesignationSummary struct {
	Index int    `json:"index"`
	Brief string `json:"brief,omitempty"`
}

RunDesignationSummary is the prompt/API-safe designation projection for run summaries.

type RunDetailView

type RunDetailView struct {
	Run     Run                   `json:"run"`
	Task    *Reference            `json:"task,omitempty"`
	Session *RunSessionRef        `json:"session,omitempty"`
	Summary RunOperationalSummary `json:"summary"`
}

RunDetailView is one run detail payload with an optional task anchor.

type RunDirectExecutionAdmissionMutation

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

RunDirectExecutionAdmissionMutation authorizes one exact queued worker run to enter tokenless direct execution under a trusted actor.

func NewRunDirectExecutionAdmissionMutation

func NewRunDirectExecutionAdmissionMutation(
	previous Run,
	actor ActorContext,
	claimedAt time.Time,
) RunDirectExecutionAdmissionMutation

NewRunDirectExecutionAdmissionMutation captures the queued run and actor that may own its direct execution lifecycle.

func (RunDirectExecutionAdmissionMutation) Actor

Actor reports the trusted direct executor captured by the command.

func (RunDirectExecutionAdmissionMutation) ClaimedAt

ClaimedAt reports when direct ownership was admitted.

func (RunDirectExecutionAdmissionMutation) Fence

Fence reports the exact queued snapshot required by the command.

type RunFailure

type RunFailure struct {
	Error    string          `json:"error"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

RunFailure captures the durable failure payload returned by a failed run.

func CanonicalCoordinatorRunFailure

func CanonicalCoordinatorRunFailure(failure RunFailure) RunFailure

CanonicalCoordinatorRunFailure returns a bounded operator-safe coordinator failure. Invalid, untyped, or non-canonical metadata is replaced instead of persisted.

func NewCoordinatorRunFailure

func NewCoordinatorRunFailure(code string, cause string, recovery string) (RunFailure, error)

NewCoordinatorRunFailure builds a validated safe failure for persistence and projection.

func (RunFailure) Validate

func (r RunFailure) Validate(path string) error

Validate reports whether the run failure contains a message and bounded metadata.

type RunHookDispatcher

type RunHookDispatcher interface {
	DispatchTaskBlocked(
		context.Context,
		hookspkg.TaskBlockedPayload,
	) (hookspkg.TaskBlockedPayload, error)
	DispatchTaskUnblocked(
		context.Context,
		hookspkg.TaskUnblockedPayload,
	) (hookspkg.TaskUnblockedPayload, error)
	DispatchTaskNeedsAttention(
		context.Context,
		hookspkg.TaskNeedsAttentionPayload,
	) (hookspkg.TaskNeedsAttentionPayload, error)
	DispatchTaskRecovered(
		context.Context,
		hookspkg.TaskRecoveredPayload,
	) (hookspkg.TaskRecoveredPayload, error)
	DispatchTaskStatusChanged(
		context.Context,
		hookspkg.TaskStatusChangedPayload,
	) (hookspkg.TaskStatusChangedPayload, error)
	DispatchTaskRunEnqueued(
		context.Context,
		hookspkg.TaskRunEnqueuedPayload,
	) (hookspkg.TaskRunEnqueuedPayload, error)
	DispatchTaskRunPreClaim(
		context.Context,
		hookspkg.TaskRunPreClaimPayload,
	) (hookspkg.TaskRunPreClaimPayload, error)
	DispatchTaskRunPostClaim(
		context.Context,
		hookspkg.TaskRunPostClaimPayload,
	) (hookspkg.TaskRunPostClaimPayload, error)
	DispatchTaskRunLeaseExtended(
		context.Context,
		hookspkg.TaskRunLeaseExtendedPayload,
	) (hookspkg.TaskRunLeaseExtendedPayload, error)
	DispatchTaskRunLeaseExpired(
		context.Context,
		hookspkg.TaskRunLeaseExpiredPayload,
	) (hookspkg.TaskRunLeaseExpiredPayload, error)
	DispatchTaskRunLeaseRecovered(
		context.Context,
		hookspkg.TaskRunLeaseRecoveredPayload,
	) (hookspkg.TaskRunLeaseRecoveredPayload, error)
	DispatchTaskRunReleased(
		context.Context,
		hookspkg.TaskRunReleasedPayload,
	) (hookspkg.TaskRunReleasedPayload, error)
	DispatchTaskRunCompleted(
		context.Context,
		hookspkg.TaskRunCompletedPayload,
	) (hookspkg.TaskRunCompletedPayload, error)
	DispatchTaskRunFailed(
		context.Context,
		hookspkg.TaskRunFailedPayload,
	) (hookspkg.TaskRunFailedPayload, error)
}

RunHookDispatcher is the narrow hook bridge consumed by task-run transitions.

type RunID

type RunID string

RunID identifies a durable task_run row without exposing raw lease credentials.

type RunIdempotency

type RunIdempotency struct {
	IdempotencyKey string    `json:"idempotency_key"`
	RunID          string    `json:"run_id"`
	Origin         Origin    `json:"origin"`
	CreatedAt      time.Time `json:"created_at"`
}

RunIdempotency is the durable deduplication record for non-human run ingress.

func (RunIdempotency) Validate

func (r RunIdempotency) Validate() error

Validate reports whether the persisted idempotency record contains the canonical shape.

type RunKind

type RunKind uint8

RunKind identifies which executor owns a task-run body.

const (
	// RunKindUnknown is the zero value used before normalization.
	RunKindUnknown RunKind = iota
	// RunKindWorker identifies normal ACP-backed worker runs.
	RunKindWorker
	// RunKindCoordinator identifies in-daemon generation coordinator runs.
	RunKindCoordinator
	// RunKindNetworkWake identifies durable Network admission work without a task anchor.
	RunKindNetworkWake
)

func ParseRunKind

func ParseRunKind(value string) RunKind

ParseRunKind returns the canonical task-run kind for a durable string value.

func (RunKind) MarshalJSON

func (k RunKind) MarshalJSON() ([]byte, error)

MarshalJSON encodes run kind as the public/durable string value.

func (RunKind) Normalize

func (k RunKind) Normalize() RunKind

Normalize returns the normalized representation of the task-run kind.

func (RunKind) String

func (k RunKind) String() string

String returns the durable string representation of the task-run kind.

func (*RunKind) UnmarshalJSON

func (k *RunKind) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the public/durable run kind string.

func (RunKind) Validate

func (k RunKind) Validate(path string) error

Validate reports whether the task-run kind is one of the supported executor kinds.

type RunLeaseFailedEventPayload

type RunLeaseFailedEventPayload struct {
	Status         RunStatus       `json:"status"`
	Error          string          `json:"error"`
	Metadata       json.RawMessage `json:"metadata,omitempty"`
	ClaimTokenHash string          `json:"claim_token_hash,omitempty"`
}

RunLeaseFailedEventPayload is the canonical audit payload for a token-fenced lease failure.

func NewRunLeaseFailedEventPayload

func NewRunLeaseFailedEventPayload(mutation *FailedRunLeaseMutation) RunLeaseFailedEventPayload

NewRunLeaseFailedEventPayload builds the public-safe payload from a canonical mutation.

type RunMetadataMutation

type RunMetadataMutation struct {
	RunID            string
	ExpectedMetadata json.RawMessage
	Metadata         json.RawMessage
}

RunMetadataMutation is a metadata-only CAS. It cannot alter lifecycle, session, lease, identity, or payload fields.

type RunMutation

type RunMutation func(runMutationStore) error

RunMutation is an opaque task-domain capability executed by the owning store transaction. Its private store parameter prevents other packages from constructing arbitrary lifecycle transactions.

type RunMutationFence

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

RunMutationFence captures the complete mutable ownership identity of one run snapshot. Its fields are intentionally private so mutation commands can only obtain a fence by capturing an observed Run.

func NewRunMutationFence

func NewRunMutationFence(run Run) RunMutationFence

NewRunMutationFence captures the fields that authorize one lifecycle write.

func (RunMutationFence) ClaimTokenHash

func (f RunMutationFence) ClaimTokenHash() string

ClaimTokenHash reports the fenced lease credential identity.

func (RunMutationFence) LeaseUntil

func (f RunMutationFence) LeaseUntil() time.Time

LeaseUntil reports the fenced lease generation.

func (RunMutationFence) Matches

func (f RunMutationFence) Matches(run Run) bool

Matches reports whether run still represents the captured ownership state.

func (RunMutationFence) RunID

func (f RunMutationFence) RunID() string

RunID reports the fenced run identity.

func (RunMutationFence) SessionID

func (f RunMutationFence) SessionID() string

SessionID reports the fenced session binding.

func (RunMutationFence) Status

func (f RunMutationFence) Status() RunStatus

Status reports the fenced lifecycle state.

func (RunMutationFence) TaskID

func (f RunMutationFence) TaskID() string

TaskID reports the fenced task ownership identity.

func (RunMutationFence) WorkspaceID

func (f RunMutationFence) WorkspaceID() string

WorkspaceID reports the fenced workspace ownership identity.

type RunMutationTransactionStore

type RunMutationTransactionStore interface {
	WithTaskMutationTransaction(
		ctx context.Context,
		action string,
		mutation RunMutation,
	) error
}

RunMutationTransactionStore owns the atomic boundary between an authoritative task mutation and its durable audit record.

type RunNeedsAttentionCommand

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

RunNeedsAttentionCommand declares one fully fenced needs-attention request.

func NewRunNeedsAttentionCommand

func NewRunNeedsAttentionCommand(previous Run, diagnostic string) RunNeedsAttentionCommand

NewRunNeedsAttentionCommand captures the exact run snapshot to escalate.

func (RunNeedsAttentionCommand) Diagnostic

func (c RunNeedsAttentionCommand) Diagnostic() string

Diagnostic reports the sanitized operator-facing diagnostic.

func (RunNeedsAttentionCommand) Fence

Fence reports the exact source snapshot required by the command.

type RunNeedsAttentionEventPayload

type RunNeedsAttentionEventPayload struct {
	PreviousStatus               RunStatus           `json:"previous_status"`
	Status                       RunStatus           `json:"status"`
	SessionID                    string              `json:"session_id,omitempty"`
	Diagnostic                   string              `json:"diagnostic,omitempty"`
	QueuedAt                     time.Time           `json:"queued_at,omitzero"`
	ResolvedNetworkParticipation *participation.Spec `json:"resolved_network_participation"`
}

RunNeedsAttentionEventPayload is the canonical audit payload for a run that requires intervention.

type RunNeedsAttentionMutation

type RunNeedsAttentionMutation struct {
	Previous Run
	Run      Run
	Applied  bool
}

RunNeedsAttentionMutation records the run state observed and applied by one needs-attention transaction. Applied is false for the idempotent path.

type RunNetworkSessionBinder

type RunNetworkSessionBinder interface {
	BindTaskRunNetwork(ctx context.Context, sessionID string, run Run) error
	RestoreTaskRunNetwork(ctx context.Context, sessionID string) error
}

RunNetworkSessionBinder is the optional task-session bridge that moves a claimant into the run-owned coordination channel for the lease lifetime.

type RunNetworkState

type RunNetworkState struct {
	NetworkSpec            participation.Spec `json:"network_spec"`
	NetworkWakeID          string             `json:"network_wake_id,omitempty"`
	NetworkTargetSessionID string             `json:"network_target_session_id,omitempty"`
	NetworkOwnerKey        string             `json:"network_owner_key,omitempty"`
}

RunNetworkState keeps immutable participation and wake-only correlation off the hot Run value.

type RunOperationalSummary

type RunOperationalSummary struct {
	LastActivityAt time.Time `json:"last_activity_at"`
	LastEventType  string    `json:"last_event_type,omitempty"`
	ToolCallCount  *int64    `json:"tool_call_count,omitempty"`
	TurnCount      *int64    `json:"turn_count,omitempty"`
	InputTokens    *int64    `json:"input_tokens,omitempty"`
	OutputTokens   *int64    `json:"output_tokens,omitempty"`
	TotalTokens    *int64    `json:"total_tokens,omitempty"`
	TotalCost      *float64  `json:"total_cost,omitempty"`
	CostCurrency   *string   `json:"cost_currency,omitempty"`
	CostStatus     string    `json:"cost_status,omitempty"`
	CostSource     string    `json:"cost_source,omitempty"`
}

RunOperationalSummary captures run-detail metrics aggregated from runtime data when available.

type RunQuery

type RunQuery struct {
	TaskID               string    `json:"task_id,omitempty"`
	Status               RunStatus `json:"status,omitempty"`
	SessionID            string    `json:"session_id,omitempty"`
	DesignationGroupID   string    `json:"designation_group_id,omitempty"`
	ParticipationChannel string    `json:"participation_channel,omitempty"`
	Limit                int       `json:"limit,omitempty"`
}

RunQuery captures the supported list filters for task-run reads.

func (RunQuery) Validate

func (q RunQuery) Validate(path string) error

Validate reports whether the task-run query filters are internally consistent.

type RunReadAuthorizer

type RunReadAuthorizer interface {
	AuthorizeRunRead(ctx context.Context, actor ActorContext, run Run, task *Task) error
}

RunReadAuthorizer owns task-backed and taskless run-read policy.

type RunResult

type RunResult struct {
	Value              json.RawMessage           `json:"value,omitempty"`
	TokensUsed         int64                     `json:"tokens_used,omitempty"`
	CoordinatorControl *CoordinatorControlResult `json:"coordinator_control,omitempty"`
}

RunResult captures the durable JSON result returned by a completed run.

func (RunResult) StoredValue

func (r RunResult) StoredValue() (json.RawMessage, error)

StoredValue returns the task_runs.result_json representation while preserving the historical raw Value shape for ordinary completions.

func (RunResult) Validate

func (r RunResult) Validate(path string) error

Validate reports whether the run result respects the shared result-size guardrail.

type RunReview

type RunReview struct {
	ReviewID          string           `json:"review_id"`
	TaskID            string           `json:"task_id"`
	RunID             string           `json:"run_id"`
	ParentReviewID    string           `json:"parent_review_id,omitempty"`
	Policy            ReviewPolicy     `json:"policy"`
	ReviewRound       int              `json:"review_round"`
	Attempt           int              `json:"attempt"`
	Status            RunReviewStatus  `json:"status"`
	Outcome           RunReviewOutcome `json:"outcome,omitempty"`
	Confidence        *float64         `json:"confidence,omitempty"`
	Reason            string           `json:"reason,omitempty"`
	DeliveryID        string           `json:"delivery_id,omitempty"`
	MissingWork       json.RawMessage  `json:"missing_work,omitempty"`
	NextRoundGuidance string           `json:"next_round_guidance,omitempty"`
	ReviewText        string           `json:"review_text,omitempty"`
	ReviewerSessionID string           `json:"reviewer_session_id,omitempty"`
	ReviewerAgentName string           `json:"reviewer_agent_name,omitempty"`
	ReviewerPeerID    string           `json:"reviewer_peer_id,omitempty"`
	ReviewerChannelID string           `json:"reviewer_channel_id,omitempty"`
	ReviewedBy        *ActorIdentity   `json:"reviewed_by,omitempty"`
	RequestedAt       time.Time        `json:"requested_at"`
	RoutedAt          time.Time        `json:"routed_at"`
	StartedAt         time.Time        `json:"started_at"`
	ReviewedAt        time.Time        `json:"reviewed_at"`
	DeadlineAt        time.Time        `json:"deadline_at"`
	CreatedAt         time.Time        `json:"created_at"`
	UpdatedAt         time.Time        `json:"updated_at"`
}

RunReview is the task-domain record for one post-terminal review gate.

func (*RunReview) Normalize

func (r *RunReview) Normalize(now time.Time) (RunReview, error)

Normalize returns a canonical review record.

func (*RunReview) Validate

func (r *RunReview) Validate() error

Validate reports whether the run-review record can be persisted.

type RunReviewBinding

type RunReviewBinding struct {
	Review            RunReview `json:"review"`
	SessionID         string    `json:"session_id"`
	ReviewerAgentName string    `json:"reviewer_agent_name,omitempty"`
	ReviewerPeerID    string    `json:"reviewer_peer_id,omitempty"`
	ReviewerChannelID string    `json:"reviewer_channel_id,omitempty"`
}

RunReviewBinding is the lookup shape consumed by reviewer-session tooling.

type RunReviewLineage

type RunReviewLineage struct {
	Required           bool            `json:"required,omitempty"`
	RequestRound       int             `json:"request_round,omitempty"`
	PolicySnapshot     ReviewPolicy    `json:"policy_snapshot,omitempty"`
	RequestID          string          `json:"request_id,omitempty"`
	ParentRunID        string          `json:"parent_run_id,omitempty"`
	ReviewID           string          `json:"review_id,omitempty"`
	ReviewRound        int             `json:"review_round,omitempty"`
	ContinuationReason string          `json:"continuation_reason,omitempty"`
	MissingWork        json.RawMessage `json:"missing_work,omitempty"`
	NextRoundGuidance  string          `json:"next_round_guidance,omitempty"`
}

RunReviewLineage captures review-gate fields attached to a task run.

type RunReviewOutcome

type RunReviewOutcome string

RunReviewOutcome identifies the authoritative reviewer verdict.

const (
	// RunReviewOutcomeApproved accepts the run result.
	RunReviewOutcomeApproved RunReviewOutcome = "approved"
	// RunReviewOutcomeRejected rejects the run and may request continuation work.
	RunReviewOutcomeRejected RunReviewOutcome = "rejected"
	// RunReviewOutcomeBlocked reports the review could not continue due to external blockers.
	RunReviewOutcomeBlocked RunReviewOutcome = "blocked"
	// RunReviewOutcomeError reports reviewer/tool execution failed.
	RunReviewOutcomeError RunReviewOutcome = "error"
	// RunReviewOutcomeTimeout reports the review exceeded its deadline.
	RunReviewOutcomeTimeout RunReviewOutcome = "timeout"
	// RunReviewOutcomeInvalidOutput reports the reviewer returned a malformed verdict.
	RunReviewOutcomeInvalidOutput RunReviewOutcome = "invalid_output"
)

func (RunReviewOutcome) Normalize

func (o RunReviewOutcome) Normalize() RunReviewOutcome

Normalize returns the normalized run-review outcome.

func (RunReviewOutcome) Validate

func (o RunReviewOutcome) Validate(path string) error

Validate reports whether the run-review outcome is supported.

type RunReviewQuery

type RunReviewQuery struct {
	TaskID            string          `json:"task_id,omitempty"`
	RunID             string          `json:"run_id,omitempty"`
	Status            RunReviewStatus `json:"status,omitempty"`
	ReviewerSessionID string          `json:"reviewer_session_id,omitempty"`
	Limit             int             `json:"limit,omitempty"`
}

RunReviewQuery captures supported review read filters.

func (RunReviewQuery) Validate

func (q RunReviewQuery) Validate(path string) error

Validate reports whether review query filters are internally consistent.

type RunReviewRequest

type RunReviewRequest struct {
	TaskID         string       `json:"task_id"`
	RunID          string       `json:"run_id"`
	ReviewRound    int          `json:"review_round,omitempty"`
	Attempt        int          `json:"attempt,omitempty"`
	Policy         ReviewPolicy `json:"policy,omitempty"`
	ParentReviewID string       `json:"parent_review_id,omitempty"`
	Reason         string       `json:"reason,omitempty"`
	DeadlineAt     time.Time    `json:"deadline_at"`
}

RunReviewRequest captures one authoritative request to review a terminal run.

func (RunReviewRequest) Normalize

func (r RunReviewRequest) Normalize() RunReviewRequest

Normalize returns a canonical review request.

func (RunReviewRequest) Validate

func (r RunReviewRequest) Validate(path string) error

Validate reports whether the review request has enough data for a persisted request row.

type RunReviewRequestedNotification

type RunReviewRequestedNotification struct {
	Review RunReview
	Task   Task
	Run    Run
	Actor  ActorContext
}

RunReviewRequestedNotification is emitted after one review request is durably created and its audit event has been recorded.

type RunReviewRequestedObserver

type RunReviewRequestedObserver interface {
	OnRunReviewRequested(ctx context.Context, notification *RunReviewRequestedNotification)
}

RunReviewRequestedObserver receives typed review-request wakeups without tailing task events or storage tables.

type RunReviewResult

type RunReviewResult struct {
	Review          RunReview `json:"review"`
	ContinuationRun *Run      `json:"continuation_run,omitempty"`
	CircuitOpened   bool      `json:"circuit_opened,omitempty"`
}

RunReviewResult reports the stored verdict and optional rejected-review continuation run.

type RunReviewStatus

type RunReviewStatus string

RunReviewStatus identifies the lifecycle state of one run review request.

const (
	// RunReviewStatusRequested reports a persisted review request awaiting routing.
	RunReviewStatusRequested RunReviewStatus = "requested"
	// RunReviewStatusRouted reports a review that has been routed but not yet bound.
	RunReviewStatusRouted RunReviewStatus = "routed"
	// RunReviewStatusInReview reports a review bound to a reviewer session.
	RunReviewStatusInReview RunReviewStatus = "in_review"
	// RunReviewStatusRecorded reports a persisted terminal reviewer verdict.
	RunReviewStatusRecorded RunReviewStatus = "recorded"
	// RunReviewStatusCircuitOpened reports review routing stopped by circuit policy.
	RunReviewStatusCircuitOpened RunReviewStatus = "circuit_opened"
	// RunReviewStatusCanceled reports an explicitly canceled review request.
	RunReviewStatusCanceled RunReviewStatus = "canceled"
)

func (RunReviewStatus) Normalize

func (s RunReviewStatus) Normalize() RunReviewStatus

Normalize returns the normalized run-review status.

func (RunReviewStatus) Validate

func (s RunReviewStatus) Validate(path string) error

Validate reports whether the run-review status is supported.

type RunReviewStore

type RunReviewStore interface {
	RequestRunReview(ctx context.Context, review *RunReview) (RunReview, bool, error)
	GetRunReview(ctx context.Context, reviewID string) (RunReview, error)
	RecordRunReview(
		ctx context.Context,
		req RecordRunReviewRequest,
		actor ActorContext,
		recordedAt time.Time,
		continuationRunID string,
	) (RunReviewResult, error)
	BindRunReviewSession(ctx context.Context, req BindRunReviewSessionRequest, boundAt time.Time) (RunReview, error)
	LookupRunReviewBySession(ctx context.Context, sessionID string) (RunReview, error)
	ListRunReviews(ctx context.Context, query RunReviewQuery) ([]RunReview, error)
}

RunReviewStore is the persistence surface for task-run review gate records.

type RunReviewSummary

type RunReviewSummary struct {
	ReviewID      string `json:"review_id"`
	RunID         string `json:"run_id"`
	ReviewRound   int    `json:"review_round"`
	Attempt       int    `json:"attempt"`
	Status        string `json:"status"`
	Outcome       string `json:"outcome,omitempty"`
	Reason        string `json:"reason,omitempty"`
	ReviewedAt    string `json:"reviewed_at,omitempty"`
	ReviewerLabel string `json:"reviewer_label,omitempty"`
}

RunReviewSummary is the redacted review history shape included in task context.

type RunReviewVerdict

type RunReviewVerdict struct {
	Outcome           RunReviewOutcome `json:"outcome"`
	Confidence        *float64         `json:"confidence"`
	Reason            string           `json:"reason"`
	DeliveryID        string           `json:"delivery_id"`
	MissingWork       json.RawMessage  `json:"missing_work,omitempty"`
	NextRoundGuidance string           `json:"next_round_guidance,omitempty"`
	ReviewText        string           `json:"review_text,omitempty"`
}

RunReviewVerdict captures the terminal reviewer payload persisted by the task domain.

func (RunReviewVerdict) Normalize

func (v RunReviewVerdict) Normalize() RunReviewVerdict

Normalize returns a canonical verdict payload.

func (RunReviewVerdict) Validate

func (v RunReviewVerdict) Validate(path string) error

Validate reports whether the verdict can be persisted as an authoritative reviewer decision.

type RunRunningMutation

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

RunRunningMutation authorizes starting -> running against one exact run ownership snapshot.

func NewRunRunningMutation

func NewRunRunningMutation(previous Run, claimToken string, startedAt time.Time) RunRunningMutation

NewRunRunningMutation captures the starting run and its execution timestamp.

func (RunRunningMutation) ClaimToken

func (m RunRunningMutation) ClaimToken() string

ClaimToken reports the lease credential authorizing the transition.

func (RunRunningMutation) CommandAt

func (m RunRunningMutation) CommandAt() time.Time

CommandAt reports when the transition was authorized.

func (RunRunningMutation) Fence

Fence reports the exact source snapshot required by the command.

func (RunRunningMutation) MatchesSource

func (m RunRunningMutation) MatchesSource(run Run) bool

MatchesSource reports whether the current run still has the captured lease owner.

func (RunRunningMutation) StartedAt

func (m RunRunningMutation) StartedAt() time.Time

StartedAt reports the requested execution timestamp.

type RunSessionAttachmentExecutor

type RunSessionAttachmentExecutor interface {
	AttachTaskRunSession(ctx context.Context, run Run, sessionID string) (*SessionRef, error)
}

RunSessionAttachmentExecutor validates an existing session against one claimed run's immutable execution-environment snapshot before binding it.

type RunSessionBindingMutation

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

RunSessionBindingMutation authorizes one exact claimed or starting run to bind the session returned by the runtime bridge.

func NewRunSessionBindingMutation

func NewRunSessionBindingMutation(
	previous Run,
	claimToken string,
	sessionID string,
	worktreeID string,
	commandAt time.Time,
) RunSessionBindingMutation

NewRunSessionBindingMutation captures the source run and requested session.

func (RunSessionBindingMutation) ClaimToken

func (m RunSessionBindingMutation) ClaimToken() string

ClaimToken reports the lease credential authorizing the binding.

func (RunSessionBindingMutation) CommandAt

func (m RunSessionBindingMutation) CommandAt() time.Time

CommandAt reports when the binding was authorized.

func (RunSessionBindingMutation) Fence

Fence reports the exact source snapshot required by the command.

func (RunSessionBindingMutation) MatchesSource

func (m RunSessionBindingMutation) MatchesSource(run Run) bool

MatchesSource reports whether the current run still has the captured lease owner.

func (RunSessionBindingMutation) SessionID

func (m RunSessionBindingMutation) SessionID() string

SessionID reports the normalized session binding requested by the command.

func (RunSessionBindingMutation) WorktreeID

func (m RunSessionBindingMutation) WorktreeID() string

WorktreeID reports the normalized worktree binding returned by the runtime bridge.

type RunSessionRef

type RunSessionRef struct {
	SessionID   string    `json:"session_id"`
	WorkspaceID string    `json:"workspace_id,omitempty"`
	AgentName   string    `json:"agent_name,omitempty"`
	Name        string    `json:"name,omitempty"`
	State       string    `json:"state,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

RunSessionRef links one run to its backing session when available.

type RunStartingMutation

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

RunStartingMutation authorizes claimed -> starting against one exact run ownership snapshot.

func NewRunStartingMutation

func NewRunStartingMutation(previous Run, claimToken string, commandAt time.Time) RunStartingMutation

NewRunStartingMutation captures the claimed run that may enter starting.

func (RunStartingMutation) ClaimToken

func (m RunStartingMutation) ClaimToken() string

ClaimToken reports the lease credential authorizing the transition.

func (RunStartingMutation) CommandAt

func (m RunStartingMutation) CommandAt() time.Time

CommandAt reports when the transition was authorized.

func (RunStartingMutation) Fence

Fence reports the exact source snapshot required by the command.

func (RunStartingMutation) MatchesSource

func (m RunStartingMutation) MatchesSource(run Run) bool

MatchesSource reports whether the current run still has the captured lease owner.

type RunStarvation

type RunStarvation struct {
	RunID            string     `json:"run_id"`
	WakeCount        int        `json:"wake_count"`
	FirstStarvedAt   time.Time  `json:"first_starved_at"`
	LastWakeAt       time.Time  `json:"last_wake_at,omitzero"`
	EscalationTier   int        `json:"escalation_tier"`
	SpawnRequestedAt *time.Time `json:"spawn_requested_at,omitempty"`
	StarvedEventAt   *time.Time `json:"starved_event_at,omitempty"`
	UpdatedAt        time.Time  `json:"updated_at"`
}

RunStarvation is the durable per-run escalation budget the scheduler advances each cycle a claimable run stays queued past the starvation threshold. It survives daemon restart so the tier ladder resumes from the persisted count rather than restarting on every Rebuild.

type RunStarvationMutation

type RunStarvationMutation struct {
	RunID            string     `json:"run_id"`
	WakeCount        int        `json:"wake_count"`
	FirstStarvedAt   time.Time  `json:"first_starved_at"`
	LastWakeAt       time.Time  `json:"last_wake_at,omitzero"`
	EscalationTier   int        `json:"escalation_tier"`
	SpawnRequestedAt *time.Time `json:"spawn_requested_at,omitempty"`
	StarvedEventAt   *time.Time `json:"starved_event_at,omitempty"`
	UpdatedAt        time.Time  `json:"updated_at"`
}

RunStarvationMutation captures one upsert of a run's escalation budget.

type RunStatus

type RunStatus uint8

RunStatus identifies the canonical lifecycle state of a task run.

const (
	// TaskRunStatusUnknown is the zero value used before normalization.
	TaskRunStatusUnknown RunStatus = iota
	// TaskRunStatusQueued reports a run that has been accepted but not yet claimed.
	TaskRunStatusQueued
	// TaskRunStatusClaimed reports a run that has been claimed for execution.
	TaskRunStatusClaimed
	// TaskRunStatusStarting reports a run that is starting its execution session.
	TaskRunStatusStarting
	// TaskRunStatusRunning reports a run that is actively executing.
	TaskRunStatusRunning
	// TaskRunStatusCompleted reports a run that finished successfully.
	TaskRunStatusCompleted
	// TaskRunStatusFailed reports a run that finished with an error.
	TaskRunStatusFailed
	// TaskRunStatusCanceled reports a run that was canceled.
	TaskRunStatusCanceled
	// TaskRunStatusNeedsAttention reports a nonterminal run that requires operator or agent recovery.
	TaskRunStatusNeedsAttention
)

func ParseRunStatus

func ParseRunStatus(value string) RunStatus

ParseRunStatus returns the canonical task-run status for a durable string value.

func (RunStatus) MarshalJSON

func (s RunStatus) MarshalJSON() ([]byte, error)

MarshalJSON encodes run status as the public/durable string value.

func (RunStatus) Normalize

func (s RunStatus) Normalize() RunStatus

Normalize returns the normalized representation of the task-run status.

func (RunStatus) String

func (s RunStatus) String() string

String returns the durable string representation of the task-run status.

func (*RunStatus) UnmarshalJSON

func (s *RunStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the public/durable run status string.

func (RunStatus) Validate

func (s RunStatus) Validate(path string) error

Validate reports whether the task-run status is one of the supported lifecycle states.

type RunStore

type RunStore interface {
	UpdateTaskRunMetadata(ctx context.Context, mutation RunMetadataMutation) (Run, error)
	GetTaskRun(ctx context.Context, id string) (Run, error)
	ListTaskRuns(ctx context.Context, query RunQuery) ([]Run, error)
	ListTaskRunsByStatus(ctx context.Context, statuses []RunStatus) ([]Run, error)
	CountActiveSessionBindings(ctx context.Context, sessionID string) (int, error)
	CompleteRunLeaseSettlement(ctx context.Context, completion LeaseCompletion) (CompletedRunSettlement, error)
	SettleNetworkWake(ctx context.Context, settlement NetworkWakeSettlement) (NetworkWakeSettlementResult, error)
	CompleteCoordinatorAndEnqueueNext(
		ctx context.Context,
		completion CoordinatorCompletion,
		finalizer GenerationStateFinalizer,
	) (CoordinatorCompletionResult, error)
	// RecoverExpiredRunLeases commits each run mutation with its canonical recovery events.
	RecoverExpiredRunLeases(ctx context.Context, recovery ExpiredLeaseRecovery) ([]ExpiredLeaseRecoveryResult, error)
}

RunStore is the persistence surface for durable task-run records.

type RunSummary

type RunSummary struct {
	ID                           string                 `json:"id"`
	TaskID                       string                 `json:"task_id"`
	RunKind                      RunKind                `json:"run_kind,omitempty"`
	LoopRunID                    string                 `json:"loop_run_id,omitempty"`
	Status                       RunStatus              `json:"status"`
	Attempt                      int                    `json:"attempt"`
	RecoveryCount                int                    `json:"recovery_count"`
	PreviousRunID                string                 `json:"previous_run_id,omitempty"`
	FailureKind                  string                 `json:"failure_kind,omitempty"`
	MaxAttempts                  int                    `json:"max_attempts"`
	SessionID                    string                 `json:"session_id,omitempty"`
	WorktreeID                   string                 `json:"worktree_id,omitempty"`
	ResolvedWorktreeMode         WorktreeMode           `json:"resolved_worktree_mode,omitempty"`
	ResolvedWorktreeRef          string                 `json:"resolved_worktree_ref,omitempty"`
	ClaimedBy                    *ActorIdentity         `json:"claimed_by,omitempty"`
	ClaimTokenHash               string                 `json:"claim_token_hash,omitempty"`
	LeaseUntil                   time.Time              `json:"lease_until"`
	HeartbeatAt                  time.Time              `json:"heartbeat_at"`
	ResolvedNetworkParticipation *participation.Spec    `json:"resolved_network_participation"`
	DesignationGroupID           string                 `json:"designation_group_id,omitempty"`
	Designation                  *RunDesignationSummary `json:"designation,omitempty"`
	QueuedAt                     time.Time              `json:"queued_at"`
	ClaimedAt                    time.Time              `json:"claimed_at"`
	StartedAt                    time.Time              `json:"started_at"`
	EndedAt                      time.Time              `json:"ended_at"`
	TokensUsed                   int64                  `json:"tokens_used,omitempty"`
	Error                        string                 `json:"error,omitempty"`
}

RunSummary captures the operator-facing run chip data used by enriched task cards.

type RunWorktreeState

type RunWorktreeState struct {
	WorktreeID           string       `json:"worktree_id,omitempty"`
	ResolvedWorktreeMode WorktreeMode `json:"resolved_worktree_mode"`
	ResolvedWorktreeRef  string       `json:"resolved_worktree_ref,omitempty"`
}

RunWorktreeState keeps optional worktree binding data off the hot Run value.

type RuntimeLimits

type RuntimeLimits struct {
	MaxRuntimeSeconds int64 `json:"max_runtime_seconds"`
	SummaryMaxBytes   int   `json:"summary_max_bytes"`
	ContextMaxBytes   int   `json:"context_body_max_bytes"`
}

RuntimeLimits reports the runtime limits relevant to one task context bundle.

type RuntimeMode

type RuntimeMode string

RuntimeMode identifies task-level runtime evidence behavior.

func (RuntimeMode) Normalize

func (m RuntimeMode) Normalize() RuntimeMode

Normalize returns the normalized runtime mode.

type RuntimePolicy

type RuntimePolicy struct {
	Mode RuntimeMode `json:"mode"`
}

RuntimePolicy opts a task into broader runtime-evidence operations.

type RuntimeViewReader

type RuntimeViewReader interface {
	GetSession(ctx context.Context, sessionID string) (*RunSessionRef, error)
	ListSessionEvents(ctx context.Context, sessionID string, query store.EventQuery) ([]store.SessionEvent, error)
	ListSessionTokenStats(ctx context.Context, sessionID string) ([]store.TokenStats, error)
}

RuntimeViewReader enriches run-detail reads with session and usage telemetry when available.

type SandboxMode

type SandboxMode string

SandboxMode identifies task-level sandbox selection behavior.

func (SandboxMode) Normalize

func (m SandboxMode) Normalize() SandboxMode

Normalize returns the normalized sandbox mode.

type SandboxPolicy

type SandboxPolicy struct {
	Mode       SandboxMode `json:"mode"`
	SandboxRef string      `json:"sandbox_ref,omitempty"`
}

SandboxPolicy selects task-level sandbox behavior at session start.

type SchedulerBacklog

type SchedulerBacklog struct {
	Runs  []SchedulerBacklogRun `json:"runs"`
	Total int                   `json:"total"`
}

SchedulerBacklog reports queued scheduler backlog rows and the unbounded total.

type SchedulerBacklogQuery

type SchedulerBacklogQuery struct {
	Limit         int    `json:"limit,omitempty"`
	Scope         Scope  `json:"scope,omitempty"`
	WorkspaceID   string `json:"workspace_id,omitempty"`
	IncludePaused bool   `json:"include_paused,omitempty"`
}

SchedulerBacklogQuery captures read filters for queued scheduler backlog.

func (SchedulerBacklogQuery) Validate

func (q SchedulerBacklogQuery) Validate(path string) error

Validate reports whether the scheduler backlog filters are internally consistent.

type SchedulerBacklogRun

type SchedulerBacklogRun struct {
	Task            Task   `json:"task"`
	Run             Run    `json:"run"`
	EffectivePaused bool   `json:"effective_paused"`
	PausedByTaskID  string `json:"paused_by_task_id,omitempty"`
}

SchedulerBacklogRun joins one queued run with the task that owns it.

type SchedulerDrainRequest

type SchedulerDrainRequest struct {
	Reason  string        `json:"reason,omitempty"`
	Timeout time.Duration `json:"timeout,omitempty"`
}

SchedulerDrainRequest captures one drain invocation.

type SchedulerDrainResult

type SchedulerDrainResult struct {
	Status          SchedulerStatus `json:"status"`
	Completed       bool            `json:"completed"`
	TimedOut        bool            `json:"timed_out,omitempty"`
	RemainingClaims int             `json:"remaining_claims"`
	StartedAt       time.Time       `json:"started_at"`
	CompletedAt     time.Time       `json:"completed_at"`
}

SchedulerDrainResult reports the final state observed by one drain invocation.

type SchedulerPauseMutation

type SchedulerPauseMutation struct {
	Paused    bool      `json:"paused"`
	Actor     string    `json:"actor,omitempty"`
	Reason    string    `json:"reason,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
}

SchedulerPauseMutation captures one scheduler-wide pause-state write.

type SchedulerPauseRequest

type SchedulerPauseRequest struct {
	Reason string `json:"reason,omitempty"`
}

SchedulerPauseRequest captures one scheduler-wide pause request.

type SchedulerPauseState

type SchedulerPauseState struct {
	Paused    bool      `json:"paused"`
	PausedBy  string    `json:"paused_by,omitempty"`
	PausedAt  time.Time `json:"paused_at,omitzero"`
	Reason    string    `json:"reason,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitzero"`
}

SchedulerPauseState records the singleton scheduler-wide pause state.

type SchedulerResumeRequest

type SchedulerResumeRequest struct {
	Reason string `json:"reason,omitempty"`
}

SchedulerResumeRequest captures one scheduler-wide resume request.

type SchedulerStatus

type SchedulerStatus struct {
	Paused                 bool      `json:"paused"`
	PausedBy               string    `json:"paused_by,omitempty"`
	PausedAt               time.Time `json:"paused_at,omitzero"`
	PausedReason           string    `json:"paused_reason,omitempty"`
	ActiveClaimCount       int       `json:"active_claim_count"`
	QueuedRunCount         int       `json:"queued_run_count"`
	PausedTaskCount        int       `json:"paused_task_count"`
	StarvedRunCount        int       `json:"starved_run_count"`
	NeedsAttentionRunCount int       `json:"needs_attention_run_count"`
	AsOf                   time.Time `json:"as_of"`
}

SchedulerStatus reports scheduler-wide pause state and live backlog counts.

type Scope

type Scope string

Scope identifies whether a task is daemon-global or workspace-scoped.

const (
	// ScopeGlobal identifies a daemon-wide task with no workspace binding.
	ScopeGlobal Scope = "global"
	// ScopeWorkspace identifies a task bound to one workspace.
	ScopeWorkspace Scope = "workspace"
)

func (Scope) Normalize

func (s Scope) Normalize() Scope

Normalize returns the normalized representation of the scope.

func (Scope) Validate

func (s Scope) Validate(path string) error

Validate reports whether the scope is one of the supported task scope values.

type Service

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

Service centralizes canonical task-domain creation, mutation, read, and graph-management rules above the persistence layer.

func NewManager

func NewManager(opts ...Option) (*Service, error)

NewManager constructs one task-domain manager with the supplied dependencies.

func (*Service) AddDependency

func (m *Service) AddDependency(ctx context.Context, spec AddDependency, actor ActorContext) error

AddDependency adds one dependency edge through the manager, reconciles the task status, and records the canonical audit event.

func (*Service) ApproveTask

func (m *Service) ApproveTask(
	ctx context.Context,
	id string,
	req ExecutionRequest,
	actor ActorContext,
) (*Execution, error)

ApproveTask records one approval decision for a manual-approval task that is currently awaiting a decision, then enqueues the approved run.

func (*Service) ArchiveTask

func (m *Service) ArchiveTask(
	ctx context.Context,
	id string,
	actor ActorContext,
) (TriageState, error)

ArchiveTask persists the current actor-scoped triage state as archived for the task's latest known activity snapshot.

func (*Service) AttachRunSession

func (m *Service) AttachRunSession(
	ctx context.Context,
	runID string,
	sessionID string,
	actor ActorContext,
) (*Run, error)

AttachRunSession binds one existing session to a claimed or starting run.

func (*Service) BindLeasedRunSession

func (m *Service) BindLeasedRunSession(
	ctx context.Context,
	binding LeaseSessionBinding,
	actor ActorContext,
) (*Run, error)

BindLeasedRunSession records the executing session for one active leased run after token verification.

func (*Service) BindRunReviewSession

func (m *Service) BindRunReviewSession(
	ctx context.Context,
	req BindRunReviewSessionRequest,
	actor ActorContext,
) (RunReviewBinding, error)

BindRunReviewSession binds one persisted review request to a reviewer session.

func (*Service) BlockTask

func (m *Service) BlockTask(ctx context.Context, req BlockRequest, actor ActorContext) (TaskBlock, error)

BlockTask creates a runtime-declared task block and parks the active run when supplied.

func (*Service) BulkForceFailRuns

func (m *Service) BulkForceFailRuns(
	ctx context.Context,
	req BulkForceRunRequest,
	actor ActorContext,
) (BulkForceRunResult, error)

BulkForceFailRuns applies forced failure one row at a time to preserve per-row preconditions.

func (*Service) BulkForceReleaseRuns

func (m *Service) BulkForceReleaseRuns(
	ctx context.Context,
	req BulkForceRunRequest,
	actor ActorContext,
) (BulkForceRunResult, error)

BulkForceReleaseRuns applies force release one row at a time to preserve per-row preconditions.

func (*Service) CancelRun

func (m *Service) CancelRun(
	ctx context.Context,
	runID string,
	req CancelRun,
	actor ActorContext,
) (*Run, error)

CancelRun cancels one non-terminal task run under manager authority.

func (*Service) CancelTask

func (m *Service) CancelTask(
	ctx context.Context,
	id string,
	req CancelTask,
	actor ActorContext,
) (*Task, error)

CancelTask propagates manager-owned cancellation through the target task, affected runs, and all non-terminal descendants.

func (*Service) ClaimNextRun

func (m *Service) ClaimNextRun(
	ctx context.Context,
	criteria ClaimCriteria,
	actor ActorContext,
) (*ClaimResult, error)

ClaimNextRun atomically claims the next eligible run for one session and returns the raw claim token once.

func (*Service) ClearTaskBlock

func (m *Service) ClearTaskBlock(
	ctx context.Context,
	taskID string,
	blockID string,
	note string,
	actor ActorContext,
) (TaskBlock, error)

ClearTaskBlock clears one open task block through the service-owned transition.

func (*Service) CompleteRun

func (m *Service) CompleteRun(
	ctx context.Context,
	runID string,
	result RunResult,
	actor ActorContext,
) (*Run, error)

CompleteRun marks one running task run as completed and reconciles task state.

func (*Service) CompleteRunLease

func (m *Service) CompleteRunLease(
	ctx context.Context,
	completion LeaseCompletion,
	actor ActorContext,
) (*Run, error)

CompleteRunLease marks one active task-run lease complete after token verification.

func (*Service) CreateChildTask

func (m *Service) CreateChildTask(
	ctx context.Context,
	parentTaskID string,
	spec CreateTask,
	actor ActorContext,
) (*Task, error)

CreateChildTask creates one child task beneath the supplied parent and emits an additional parent-scoped audit event.

func (*Service) CreateTask

func (m *Service) CreateTask(
	ctx context.Context,
	spec CreateTask,
	actor ActorContext,
) (*Task, error)

CreateTask derives one canonical task record from trusted actor context and persists the corresponding immutable audit event.

func (*Service) DeleteExecutionProfile

func (m *Service) DeleteExecutionProfile(
	ctx context.Context,
	taskID string,
	actor ActorContext,
) error

DeleteExecutionProfile removes the persisted profile after active-run drift checks.

func (*Service) DeleteTask

func (m *Service) DeleteTask(ctx context.Context, id string, actor ActorContext) error

DeleteTask removes one task after verifying it is not still in use by child tasks or non-terminal runs, then reconciles any dependents unblocked by the cascade-deleted dependency edges.

func (*Service) DismissTask

func (m *Service) DismissTask(
	ctx context.Context,
	id string,
	actor ActorContext,
) (TriageState, error)

DismissTask persists the current actor-scoped triage state as dismissed for the task's latest known activity snapshot.

func (*Service) DrainScheduler

func (m *Service) DrainScheduler(
	ctx context.Context,
	req SchedulerDrainRequest,
	actor ActorContext,
) (SchedulerDrainResult, error)

DrainScheduler pauses the scheduler and waits until active claims reach zero or the timeout expires.

func (*Service) EnqueueRun

func (m *Service) EnqueueRun(
	ctx context.Context,
	spec EnqueueRun,
	actor ActorContext,
) (*Run, error)

EnqueueRun persists one new queue-first task run under manager authority.

func (*Service) ExpireTaskBlocks

func (m *Service) ExpireTaskBlocks(
	ctx context.Context,
	now time.Time,
	actor ActorContext,
) (ExpireTaskBlocksResult, error)

ExpireTaskBlocks finalizes expired transient blocks through service-owned transitions.

func (*Service) FailRun

func (m *Service) FailRun(
	ctx context.Context,
	runID string,
	failure RunFailure,
	actor ActorContext,
) (*Run, error)

FailRun marks one starting or running task run as failed and reconciles task state.

func (*Service) FailRunLease

func (m *Service) FailRunLease(
	ctx context.Context,
	failure LeaseFailure,
	actor ActorContext,
) (*Run, error)

FailRunLease marks one active task-run lease failed after token verification.

func (*Service) ForceFailRun

func (m *Service) ForceFailRun(
	ctx context.Context,
	runID string,
	failure ForceFailRun,
	actor ActorContext,
) (*Run, error)

ForceFailRun marks one queued or claimed run failed without requiring the raw claim token.

func (*Service) ForceReleaseRun

func (m *Service) ForceReleaseRun(
	ctx context.Context,
	runID string,
	release ForceReleaseRun,
	actor ActorContext,
) (*Run, error)

ForceReleaseRun releases one claimed run without requiring the raw claim token.

func (*Service) GetExecutionProfile

func (m *Service) GetExecutionProfile(
	ctx context.Context,
	taskID string,
	actor ActorContext,
) (ExecutionProfile, error)

GetExecutionProfile returns the persisted profile or the default inherit profile.

func (*Service) GetRunReview

func (m *Service) GetRunReview(ctx context.Context, reviewID string, actor ActorContext) (RunReview, error)

GetRunReview returns one persisted task-run review.

func (*Service) GetTask

func (m *Service) GetTask(ctx context.Context, id string, actor ActorContext) (*View, error)

GetTask returns one expanded task view after enforcing read authority.

func (*Service) HeartbeatRunLease

func (m *Service) HeartbeatRunLease(
	ctx context.Context,
	heartbeat LeaseHeartbeat,
	actor ActorContext,
) (*Run, error)

HeartbeatRunLease extends one active task-run lease after token verification.

func (*Service) InspectRun

func (m *Service) InspectRun(ctx context.Context, runID string, actor ActorContext) (*InspectView, error)

InspectRun returns a deterministic read-only snapshot rooted at one run id.

func (*Service) InspectTask

func (m *Service) InspectTask(ctx context.Context, taskID string, actor ActorContext) (*InspectView, error)

InspectTask returns a deterministic read-only snapshot for one task id.

func (*Service) ListPendingTerminalRunCommands

func (m *Service) ListPendingTerminalRunCommands(
	ctx context.Context,
	actor ActorContext,
) ([]PendingTerminalRunCommand, error)

ListPendingTerminalRunCommands returns only the non-sensitive session facts needed by daemon boot recovery.

func (*Service) ListRunReviews

func (m *Service) ListRunReviews(
	ctx context.Context,
	query RunReviewQuery,
	actor ActorContext,
) ([]RunReview, error)

ListRunReviews returns persisted review requests that match the supplied filters.

func (*Service) ListTaskBlocks

func (m *Service) ListTaskBlocks(
	ctx context.Context,
	taskID string,
	includeCleared bool,
	actor ActorContext,
) ([]TaskBlock, error)

ListTaskBlocks returns task block rows after enforcing read authority and task existence.

func (*Service) ListTaskCatalog

func (m *Service) ListTaskCatalog(
	ctx context.Context,
	query CatalogQuery,
	actor ActorContext,
) (CatalogPage, error)

ListTaskCatalog returns one batched public catalog page after enforcing read authority.

func (*Service) ListTaskRuns

func (m *Service) ListTaskRuns(
	ctx context.Context,
	taskID string,
	query RunQuery,
	actor ActorContext,
) ([]Run, error)

ListTaskRuns returns task runs for one task after enforcing read authority and task existence.

func (*Service) ListTasks

func (m *Service) ListTasks(
	ctx context.Context,
	query Query,
	actor ActorContext,
) ([]Summary, error)

ListTasks returns task summaries that satisfy the supplied query filters after enforcing read authority.

func (*Service) LookupActiveRunForSession

func (m *Service) LookupActiveRunForSession(
	ctx context.Context,
	sessionID string,
	runID string,
) (AutonomyLeaseHandle, error)

LookupActiveRunForSession resolves the internal claim token for a session-owned run while preserving the existing token-fenced lease writers as the sole mutation authority.

func (*Service) LookupRunReviewForSession

func (m *Service) LookupRunReviewForSession(
	ctx context.Context,
	sessionID string,
	actor ActorContext,
) (RunReviewBinding, error)

LookupRunReviewForSession returns the active review bound to one reviewer session.

func (*Service) MarkRunNeedsAttention

func (m *Service) MarkRunNeedsAttention(
	ctx context.Context,
	runID string,
	diagnostic string,
	actor ActorContext,
) (Run, error)

MarkRunNeedsAttention transitions a nonterminal run to needs_attention via a CAS store mutation and records the canonical event. It is idempotent: a run already in needs_attention is returned unchanged. The diagnostic must never embed a raw claim token.

func (*Service) MarkTaskRead

func (m *Service) MarkTaskRead(
	ctx context.Context,
	id string,
	actor ActorContext,
) (TriageState, error)

MarkTaskRead persists the current actor-scoped triage state as read for the task's latest known activity snapshot.

func (*Service) OnTaskEvent

func (m *Service) OnTaskEvent(ctx context.Context, record EventRecord)

OnTaskEvent receives records from stores that own post-commit publication.

func (*Service) PauseScheduler

func (m *Service) PauseScheduler(
	ctx context.Context,
	req SchedulerPauseRequest,
	actor ActorContext,
) (SchedulerStatus, error)

PauseScheduler marks the daemon scheduler as paused for new dispatch and claims.

func (*Service) PauseTask

func (m *Service) PauseTask(
	ctx context.Context,
	id string,
	req PauseTaskRequest,
	actor ActorContext,
) (*Task, error)

PauseTask marks one task as paused for future scheduler and claim eligibility.

func (*Service) PublishTask

func (m *Service) PublishTask(
	ctx context.Context,
	id string,
	req ExecutionRequest,
	actor ActorContext,
) (*Execution, error)

PublishTask transitions one durable draft into manager-owned runnable reconciliation, then enqueues the executable run for the explicit execution boundary.

func (*Service) RecordRunReview

func (m *Service) RecordRunReview(
	ctx context.Context,
	req RecordRunReviewRequest,
	actor ActorContext,
) (RunReviewResult, error)

RecordRunReview persists an authoritative reviewer verdict and optional continuation run.

func (*Service) RecordRunStarved

func (m *Service) RecordRunStarved(
	ctx context.Context,
	runID string,
	queuedAt time.Time,
	age time.Duration,
	actor ActorContext,
) error

RecordRunStarved emits the canonical task.run_starved event for one starved queued run. The scheduler stays observational; run-event authority remains in the task service.

func (*Service) RecoverExpiredRunLeases

func (m *Service) RecoverExpiredRunLeases(
	ctx context.Context,
	recovery ExpiredLeaseRecovery,
	actor ActorContext,
) ([]ExpiredLeaseRecoveryResult, error)

RecoverExpiredRunLeases requeues stale task-run leases and emits lease-expiration hooks once.

func (*Service) RecoverRun

func (m *Service) RecoverRun(
	ctx context.Context,
	runID string,
	req RecoverRunRequest,
	actor ActorContext,
) (*RetryRunResult, error)

RecoverRun terminalizes a needs_attention run and queues one fresh child to resume work.

func (*Service) RecoverRunOnBoot

func (m *Service) RecoverRunOnBoot(
	ctx context.Context,
	runID string,
	recovery RunBootRecovery,
	actor ActorContext,
) (*Run, error)

RecoverRunOnBoot applies one daemon-owned recovery decision to a non-terminal run discovered during startup reconciliation.

func (*Service) RecoverTask

func (m *Service) RecoverTask(ctx context.Context, id string, note string, actor ActorContext) (*Task, error)

RecoverTask clears task-level needs_attention escalation through the service-owned transition.

func (*Service) RecoverTerminalRunCommandOnBoot

func (m *Service) RecoverTerminalRunCommandOnBoot(
	ctx context.Context,
	evidence TerminalRunRecoveryEvidence,
	actor ActorContext,
) (*Run, error)

RecoverTerminalRunCommandOnBoot resumes one exact durable intent before the daemon performs generic active-run recovery.

func (*Service) RejectTask

func (m *Service) RejectTask(ctx context.Context, id string, actor ActorContext) (*Task, error)

RejectTask records one rejection decision for a manual-approval task that is currently awaiting a decision and reconciles the resulting task status.

func (*Service) ReleaseRunLease

func (m *Service) ReleaseRunLease(
	ctx context.Context,
	release LeaseRelease,
	actor ActorContext,
) (*Run, error)

ReleaseRunLease releases one active task-run lease after token verification and requeues the run.

func (*Service) ReleaseSessionRunLeases

func (m *Service) ReleaseSessionRunLeases(
	ctx context.Context,
	release SessionLeaseRelease,
	actor ActorContext,
) ([]SessionLeaseReleaseResult, error)

ReleaseSessionRunLeases structurally releases every active task-run lease bound to one session without requiring the raw claim token. This is reserved for daemon-owned runtime cleanup paths such as safe-spawn reaping.

func (*Service) RemoveDependency

func (m *Service) RemoveDependency(
	ctx context.Context,
	taskID string,
	dependsOnID string,
	actor ActorContext,
) error

RemoveDependency deletes one dependency edge through the manager, reconciles the task status, and records the canonical audit event.

func (*Service) RequestRunReview

func (m *Service) RequestRunReview(
	ctx context.Context,
	req RunReviewRequest,
	actor ActorContext,
) (RunReview, bool, error)

RequestRunReview persists or returns the idempotent review request for a terminal task run.

func (*Service) ResumeScheduler

func (m *Service) ResumeScheduler(
	ctx context.Context,
	_ SchedulerResumeRequest,
	actor ActorContext,
) (SchedulerStatus, error)

ResumeScheduler clears the daemon scheduler pause flag.

func (*Service) ResumeTask

func (m *Service) ResumeTask(
	ctx context.Context,
	id string,
	req ResumeTaskRequest,
	actor ActorContext,
) (*Task, error)

ResumeTask clears one task pause for future scheduler and claim eligibility.

func (*Service) RetryRun

func (m *Service) RetryRun(
	ctx context.Context,
	runID string,
	retry RetryRunRequest,
	actor ActorContext,
) (*RetryRunResult, error)

RetryRun creates one new queued run linked to a failed source run.

func (*Service) RunDetail

func (m *Service) RunDetail(
	ctx context.Context,
	runID string,
	actor ActorContext,
) (*RunDetailView, error)

RunDetail returns one persisted run and its task reference when the run is task-backed.

func (*Service) SchedulerBacklog

func (m *Service) SchedulerBacklog(
	ctx context.Context,
	query SchedulerBacklogQuery,
	actor ActorContext,
) (SchedulerBacklog, error)

SchedulerBacklog returns queued scheduler backlog rows.

func (*Service) SchedulerStatus

func (m *Service) SchedulerStatus(ctx context.Context, actor ActorContext) (SchedulerStatus, error)

SchedulerStatus returns scheduler-wide pause state and live queue pressure.

func (*Service) SetExecutionProfile

func (m *Service) SetExecutionProfile(
	ctx context.Context,
	taskID string,
	profile *ExecutionProfile,
	actor ActorContext,
) (ExecutionProfile, error)

SetExecutionProfile validates and persists one task-owned execution profile.

func (*Service) SetWorktreePolicy

func (m *Service) SetWorktreePolicy(
	ctx context.Context,
	taskID string,
	policy WorktreePolicy,
	actor ActorContext,
) (ExecutionProfile, error)

SetWorktreePolicy patches only the worktree block of one task execution profile.

func (*Service) SettleNetworkWake

func (m *Service) SettleNetworkWake(
	ctx context.Context,
	settlement NetworkWakeSettlement,
	actor ActorContext,
) (*NetworkWakeSettlementResult, error)

SettleNetworkWake atomically terminalizes one claimed taskless wake and publishes committed hooks.

func (*Service) StartRun

func (m *Service) StartRun(
	ctx context.Context,
	runID string,
	req StartRun,
	actor ActorContext,
) (*Run, error)

StartRun transitions one claimed or starting run into active execution.

func (*Service) StartTask

func (m *Service) StartTask(
	ctx context.Context,
	id string,
	req ExecutionRequest,
	actor ActorContext,
) (*Execution, error)

StartTask enqueues one executable run for an already-created task.

func (*Service) Stream

func (m *Service) Stream(
	ctx context.Context,
	taskID string,
	query StreamQuery,
	actor ActorContext,
) (<-chan StreamEvent, error)

func (*Service) Timeline

func (m *Service) Timeline(
	ctx context.Context,
	taskID string,
	query TimelineQuery,
	actor ActorContext,
) ([]TimelineItem, error)

func (*Service) Tree

func (m *Service) Tree(ctx context.Context, taskID string, actor ActorContext) (*TreeView, error)

func (*Service) UpdateTask

func (m *Service) UpdateTask(
	ctx context.Context,
	id string,
	patch Patch,
	actor ActorContext,
) (*Task, error)

UpdateTask applies one mutable patch while preserving immutable identity and structural fields under manager control.

type SessionExecutor

type SessionExecutor interface {
	StartTaskSession(ctx context.Context, spec *StartTaskSession) (*SessionRef, error)
	AttachTaskSession(ctx context.Context, runID string, sessionID string) (*SessionRef, error)
	RequestTaskStop(ctx context.Context, sessionID string, reason StopReason) error
	ForceTaskStop(ctx context.Context, sessionID string, reason StopReason) error
}

SessionExecutor is the injected runtime bridge used to start, attach, and stop task sessions.

type SessionLeaseRelease

type SessionLeaseRelease struct {
	SessionID string    `json:"session_id"`
	Reason    string    `json:"reason,omitempty"`
	Now       time.Time `json:"now"`
}

SessionLeaseRelease captures a daemon-owned structural release for all active leases bound to one runtime session.

func (SessionLeaseRelease) Normalize

func (r SessionLeaseRelease) Normalize(defaultNow time.Time) (SessionLeaseRelease, error)

Normalize returns a validated structural session lease release request.

func (SessionLeaseRelease) Validate

func (r SessionLeaseRelease) Validate(path string) error

Validate reports whether the structural session lease release is internally consistent.

type SessionLeaseReleaseResult

type SessionLeaseReleaseResult struct {
	Run                    Run       `json:"run"`
	PreviousRunStatus      RunStatus `json:"previous_run_status"`
	PreviousSessionID      string    `json:"previous_session_id,omitempty"`
	PreviousLeaseUntil     time.Time `json:"previous_lease_until"`
	PreviousClaimTokenHash string    `json:"previous_claim_token_hash,omitempty"`
	Reason                 string    `json:"reason,omitempty"`
}

SessionLeaseReleaseResult records one structurally released session lease.

type SessionRef

type SessionRef struct {
	SessionID   string    `json:"session_id"`
	WorkspaceID string    `json:"workspace_id,omitempty"`
	WorktreeID  string    `json:"worktree_id,omitempty"`
	StartedAt   time.Time `json:"started_at"`
}

SessionRef is the task-domain view of a runtime session binding.

func (SessionRef) Validate

func (r SessionRef) Validate() error

Validate reports whether the session reference returned by the bridge is usable.

type SoulClaimProvenance

type SoulClaimProvenance struct {
	SnapshotID string    `json:"snapshot_id,omitempty"`
	Digest     string    `json:"digest,omitempty"`
	AgentName  string    `json:"agent_name,omitempty"`
	CapturedAt time.Time `json:"captured_at"`
}

SoulClaimProvenance captures pre-resolved session Soul data at claim time.

func (SoulClaimProvenance) Validate

func (p SoulClaimProvenance) Validate(path string) error

Normalize returns a validated claim criteria with default scope, time, and lease duration applied.

type StartRun

type StartRun struct {
	IdempotencyKey string `json:"idempotency_key,omitempty"`
	ClaimToken     string `json:"claim_token,omitempty"`
}

StartRun captures one run-start request.

func (StartRun) Validate

func (r StartRun) Validate(path string) error

Validate reports whether the start-run request is internally consistent.

type StartTaskSession

type StartTaskSession struct {
	Task             Task              `json:"task"`
	Run              Run               `json:"run"`
	ExecutionProfile *ExecutionProfile `json:"execution_profile,omitempty"`
	Actor            ActorContext      `json:"actor"`
}

StartTaskSession captures the task and run context needed to allocate a dedicated session.

func (*StartTaskSession) Validate

func (r *StartTaskSession) Validate() error

Validate reports whether the session-start request contains the task and run context required by the bridge.

type Status

type Status string

Status identifies the canonical lifecycle state of a task.

const (
	// TaskStatusDraft reports a saved draft that is not yet runnable.
	TaskStatusDraft Status = "draft"
	// TaskStatusPending reports a task that exists but has not yet been reconciled into ready work.
	TaskStatusPending Status = "pending"
	// TaskStatusBlocked reports a task with unresolved dependencies.
	TaskStatusBlocked Status = "blocked"
	// TaskStatusNeedsAttention reports a task escalated out of normal claim flow for recovery.
	TaskStatusNeedsAttention Status = "needs_attention"
	// TaskStatusReady reports a task that may execute because dependencies are satisfied.
	TaskStatusReady Status = "ready"
	// TaskStatusInProgress reports a task with an active starting or running run.
	TaskStatusInProgress Status = "in_progress"
	// TaskStatusCompleted reports a task that finished successfully.
	TaskStatusCompleted Status = "completed"
	// TaskStatusFailed reports a task that ended unsuccessfully.
	TaskStatusFailed Status = "failed"
	// TaskStatusCanceled reports a task that was canceled before successful completion.
	TaskStatusCanceled Status = "canceled"
)

func (Status) Normalize

func (s Status) Normalize() Status

Normalize returns the normalized representation of the task status.

func (Status) Validate

func (s Status) Validate(path string) error

Validate reports whether the task status is one of the supported lifecycle states.

type StatusTransition

type StatusTransition struct {
	Task           Task
	PreviousStatus Status
}

StatusTransition records one durable task status change committed as part of successful run settlement.

type StopReason

type StopReason string

StopReason identifies why the task domain asked the session bridge to stop a session.

const (
	// StopReasonCompleted identifies successful task-run completion.
	StopReasonCompleted StopReason = "completed"
	// StopReasonFailed identifies failed task-run termination.
	StopReasonFailed StopReason = "failed"
	// StopReasonCancellation identifies explicit task or run cancellation.
	StopReasonCancellation StopReason = "cancellation"
	// StopReasonShutdown identifies daemon shutdown or boot recovery stop requests.
	StopReasonShutdown StopReason = "shutdown"
	// StopReasonOrphanedRun identifies orphaned-run recovery handling.
	StopReasonOrphanedRun StopReason = "orphaned_run"
)

func (StopReason) Normalize

func (r StopReason) Normalize() StopReason

Normalize returns the normalized representation of the session stop reason.

func (StopReason) Validate

func (r StopReason) Validate(path string) error

Validate reports whether the stop reason is supported.

type StreamEvent

type StreamEvent struct {
	Sequence int64        `json:"sequence"`
	Type     string       `json:"type"`
	Timeline TimelineItem `json:"timeline"`
}

StreamEvent is one task-scoped replayable live event suitable for SSE transport.

type StreamQuery

type StreamQuery struct {
	AfterSequence int64 `json:"after_sequence,omitempty"`
}

StreamQuery captures reconnect-friendly task stream replay semantics.

func (StreamQuery) Validate

func (q StreamQuery) Validate(path string) error

Validate reports whether the task stream query filters are internally consistent.

type Summary

type Summary struct {
	ID              string                `json:"id"`
	Identifier      string                `json:"identifier,omitempty"`
	Scope           Scope                 `json:"scope"`
	WorkspaceID     string                `json:"workspace_id,omitempty"`
	ParentTaskID    string                `json:"parent_task_id,omitempty"`
	Title           string                `json:"title"`
	Priority        Priority              `json:"priority,omitempty"`
	Status          Status                `json:"status"`
	BlockedReasons  *[]BlockedReason      `json:"blocked_reasons,omitempty"`
	NeedsAttention  *NeedsAttention       `json:"needs_attention,omitempty"`
	ApprovalPolicy  ApprovalPolicy        `json:"approval_policy,omitempty"`
	ApprovalState   ApprovalState         `json:"approval_state,omitempty"`
	CurrentRunID    string                `json:"current_run_id,omitempty"`
	PausedBy        string                `json:"paused_by,omitempty"`
	PausedReason    string                `json:"paused_reason,omitempty"`
	PausedByTaskID  string                `json:"paused_by_task_id,omitempty"`
	CreatedBy       ActorIdentity         `json:"created_by"`
	Origin          Origin                `json:"origin"`
	Owner           *Ownership            `json:"owner,omitempty"`
	Dependencies    []DependencyReference `json:"dependencies,omitempty"`
	ActiveRun       *RunSummary           `json:"active_run,omitempty"`
	MaxAttempts     int                   `json:"max_attempts,omitempty"`
	LatestEventSeq  int64                 `json:"latest_event_seq"`
	ChildCount      int32                 `json:"child_count,omitempty"`
	DependencyCount int32                 `json:"dependency_count,omitempty"`
	// Bool fields are clustered to keep Summary within the 512-byte gocritic copy threshold.
	AutoEnqueueOnReady bool      `json:"auto_enqueue_on_ready,omitempty"`
	Draft              bool      `json:"draft"`
	Paused             bool      `json:"paused,omitempty"`
	EffectivePaused    bool      `json:"effective_paused,omitempty"`
	WakeCreator        bool      `json:"wake_creator"`
	PausedAt           time.Time `json:"paused_at,omitzero"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
	ClosedAt           time.Time `json:"closed_at"`
	LastActivityAt     time.Time `json:"last_activity_at"`
}

Summary is the lightweight read model returned from list-oriented task queries.

type Task

type Task struct {
	ID             string         `json:"id"`
	Identifier     string         `json:"identifier,omitempty"`
	Scope          Scope          `json:"scope"`
	WorkspaceID    string         `json:"workspace_id,omitempty"`
	ParentTaskID   string         `json:"parent_task_id,omitempty"`
	Title          string         `json:"title"`
	Description    string         `json:"description,omitempty"`
	Priority       Priority       `json:"priority,omitempty"`
	MaxAttempts    int            `json:"max_attempts,omitempty"`
	Status         Status         `json:"status"`
	ApprovalPolicy ApprovalPolicy `json:"approval_policy,omitempty"`
	ApprovalState  ApprovalState  `json:"approval_state,omitempty"`
	Owner          *Ownership     `json:"owner,omitempty"`
	CurrentRunID   string         `json:"current_run_id,omitempty"`
	LatestEventSeq int64          `json:"latest_event_seq"`
	// AutoEnqueueOnReady, when true, makes the runtime enqueue this task's run
	// automatically once its blocking dependencies complete (opt-in; default
	// false preserves the explicit-execution-boundary contract). Clustered with
	// Paused to keep Task within the 512-byte gocritic copy threshold.
	AutoEnqueueOnReady bool            `json:"auto_enqueue_on_ready,omitempty"`
	Paused             bool            `json:"paused,omitempty"`
	WakeCreator        bool            `json:"wake_creator"`
	PausedBy           string          `json:"paused_by,omitempty"`
	PausedAt           time.Time       `json:"paused_at,omitzero"`
	PausedReason       string          `json:"paused_reason,omitempty"`
	NeedsAttention     *NeedsAttention `json:"needs_attention,omitempty"`
	CreatedBy          ActorIdentity   `json:"created_by"`
	Origin             Origin          `json:"origin"`
	CreatedAt          time.Time       `json:"created_at"`
	UpdatedAt          time.Time       `json:"updated_at"`
	ClosedAt           time.Time       `json:"closed_at"`
	Metadata           json.RawMessage `json:"metadata,omitempty"`
}

Task is the durable coordination record owned by the task domain.

func (Task) Validate

func (t Task) Validate() error

Validate reports whether the task record contains the canonical persisted shape.

type TaskBlock

type TaskBlock struct {
	ID          string          `json:"id"`
	WorkspaceID string          `json:"workspace_id"`
	TaskID      string          `json:"task_id"`
	Kind        BlockKind       `json:"kind"`
	Reason      string          `json:"reason"`
	Details     json.RawMessage `json:"details,omitempty"`
	CreatedBy   ActorIdentity   `json:"created_by"`
	CreatedAt   time.Time       `json:"created_at"`
	ExpiresAt   time.Time       `json:"expires_at,omitzero"`
	ClearedAt   time.Time       `json:"cleared_at,omitzero"`
	ClearedBy   ActorIdentity   `json:"cleared_by,omitzero"`
	ClearNote   string          `json:"clear_note,omitempty"`
}

TaskBlock is a durable runtime-declared block row for one task.

type TerminalRunCommand

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

TerminalRunCommand is an opaque durable receipt plus immutable terminal intent.

func RestoreTerminalRunCommand

func RestoreTerminalRunCommand(record TerminalRunCommandRecord) (TerminalRunCommand, error)

RestoreTerminalRunCommand validates and restores one durable store record.

func (TerminalRunCommand) Actor

func (c TerminalRunCommand) Actor() ActorContext

Actor reports the actor authorized when the command was admitted.

func (TerminalRunCommand) Advance

func (c TerminalRunCommand) Advance(
	phase TerminalRunCommandPhase,
	updatedAt time.Time,
) (TerminalRunCommand, error)

Advance returns the next valid durable external-effect phase.

func (TerminalRunCommand) CommandAt

func (c TerminalRunCommand) CommandAt() time.Time

CommandAt reports the immutable command timestamp.

func (TerminalRunCommand) CommandID

func (c TerminalRunCommand) CommandID() string

CommandID reports the private durable receipt identity.

func (TerminalRunCommand) Fence

Fence reports the exact source run ownership snapshot.

func (TerminalRunCommand) Kind

Kind reports the immutable terminal intent kind.

func (TerminalRunCommand) Phase

Phase reports the durable external-effect phase.

func (TerminalRunCommand) Record

Record returns an isolated persistence representation of the command.

func (TerminalRunCommand) RunID

func (c TerminalRunCommand) RunID() string

RunID reports the command's run identity.

func (TerminalRunCommand) StopReason

func (c TerminalRunCommand) StopReason() StopReason

StopReason reports the requested physical stop classification.

func (TerminalRunCommand) StopRequired

func (c TerminalRunCommand) StopRequired() bool

StopRequired reports whether settlement depends on a physical session stop.

func (TerminalRunCommand) TaskID

func (c TerminalRunCommand) TaskID() string

TaskID reports the command's task identity.

func (TerminalRunCommand) WorkspaceID

func (c TerminalRunCommand) WorkspaceID() string

WorkspaceID reports the command's workspace boundary; empty means global scope.

type TerminalRunCommandKind

type TerminalRunCommandKind string

TerminalRunCommandKind identifies one durable non-lease terminal intent.

const (
	TerminalRunCommandCompleted      TerminalRunCommandKind = "completed"
	TerminalRunCommandFailed         TerminalRunCommandKind = "failed"
	TerminalRunCommandCanceled       TerminalRunCommandKind = "canceled"
	TerminalRunCommandNeedsAttention TerminalRunCommandKind = "needs_attention"
)

type TerminalRunCommandPhase

type TerminalRunCommandPhase string

TerminalRunCommandPhase records how far the external stop effect progressed.

const (
	TerminalRunCommandPhaseAdmitted      TerminalRunCommandPhase = "admitted"
	TerminalRunCommandPhaseStopRequested TerminalRunCommandPhase = "stop_requested"
	TerminalRunCommandPhaseStopConfirmed TerminalRunCommandPhase = "stop_confirmed"
)

type TerminalRunCommandRecord

type TerminalRunCommandRecord struct {
	CommandID        string
	RunID            string
	TaskID           string
	WorkspaceID      string
	Kind             TerminalRunCommandKind
	Phase            TerminalRunCommandPhase
	SourceStatus     RunStatus
	SourceSession    string
	SourceClaimHash  string
	SourceLeaseUntil time.Time
	IntentJSON       json.RawMessage
	ActorJSON        json.RawMessage
	CommandAt        time.Time
	AdmittedAt       time.Time
	UpdatedAt        time.Time
}

TerminalRunCommandRecord is the store-facing serialized representation.

type TerminalRunCommandStore

type TerminalRunCommandStore interface {
	ReserveTerminalRunCommand(
		ctx context.Context,
		command TerminalRunCommand,
	) (authoritative TerminalRunCommand, inserted bool, err error)
	AdvanceTerminalRunCommandPhase(
		ctx context.Context,
		command TerminalRunCommand,
		next TerminalRunCommandPhase,
		updatedAt time.Time,
	) (TerminalRunCommand, error)
	ReleaseTerminalRunCommand(ctx context.Context, command TerminalRunCommand) error
	ListTerminalRunCommands(ctx context.Context) ([]TerminalRunCommand, error)
}

TerminalRunCommandStore owns the short durable transactions around one external session-stop effect. The command receipt never crosses public APIs.

type TerminalRunMutation

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

TerminalRunMutation declares the exact run snapshot that may win one terminal transition. Construction always captures lifecycle, session, claim, and lease identity together.

func NewTerminalRunMutation

func NewTerminalRunMutation(previous Run, next Run) TerminalRunMutation

NewTerminalRunMutation creates one fully fenced terminal command.

func (TerminalRunMutation) Fence

Fence reports the exact source snapshot required by the command.

func (TerminalRunMutation) NextRun

func (m TerminalRunMutation) NextRun() Run

NextRun reports the requested terminal record.

type TerminalRunRecoveryDisposition

type TerminalRunRecoveryDisposition string

TerminalRunRecoveryDisposition classifies whether boot must resume the external stop, may settle it, or lacks conclusive evidence for either.

const (
	TerminalRunRecoveryResumeStop   TerminalRunRecoveryDisposition = "resume_stop"
	TerminalRunRecoveryStopObserved TerminalRunRecoveryDisposition = "stop_observed"
	TerminalRunRecoveryAmbiguous    TerminalRunRecoveryDisposition = "ambiguous"
)

type TerminalRunRecoveryEvidence

type TerminalRunRecoveryEvidence struct {
	RunID       string
	SessionID   string
	State       string
	Disposition TerminalRunRecoveryDisposition
}

TerminalRunRecoveryEvidence describes daemon-observed session state for one pending terminal command.

type TimelineItem

type TimelineItem struct {
	Sequence  int64           `json:"sequence"`
	EventID   string          `json:"event_id"`
	Task      Reference       `json:"task"`
	Run       *RunSummary     `json:"run,omitempty"`
	EventType string          `json:"event_type"`
	Actor     ActorIdentity   `json:"actor"`
	Origin    Origin          `json:"origin"`
	Payload   json.RawMessage `json:"payload,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
}

TimelineItem is the normalized task event row consumed by live task surfaces.

type TimelineQuery

type TimelineQuery struct {
	AfterSequence int64 `json:"after_sequence,omitempty"`
	Limit         int   `json:"limit,omitempty"`
}

TimelineQuery captures reconnect-friendly task timeline windowing semantics.

func (TimelineQuery) Validate

func (q TimelineQuery) Validate(path string) error

Validate reports whether the task timeline query filters are internally consistent.

type TreeNode

type TreeNode struct {
	Task           Reference   `json:"task"`
	ParentTaskID   string      `json:"parent_task_id,omitempty"`
	Depth          int         `json:"depth"`
	ChildCount     int         `json:"child_count,omitempty"`
	ActiveRun      *RunSummary `json:"active_run,omitempty"`
	LastActivityAt time.Time   `json:"last_activity_at"`
}

TreeNode is one node inside a task-tree live snapshot.

type TreeView

type TreeView struct {
	Root        TreeNode   `json:"root"`
	Descendants []TreeNode `json:"descendants,omitempty"`
}

TreeView is the manager-owned live snapshot for one task tree.

type TriageState

type TriageState struct {
	TaskID             string        `json:"task_id"`
	Actor              ActorIdentity `json:"actor"`
	Read               bool          `json:"read"`
	Archived           bool          `json:"archived"`
	Dismissed          bool          `json:"dismissed"`
	LastSeenActivityAt time.Time     `json:"last_seen_activity_at"`
	UpdatedAt          time.Time     `json:"updated_at"`
}

TriageState is the durable actor-scoped inbox and triage state for one task.

func (TriageState) Validate

func (t TriageState) Validate() error

Validate reports whether the durable task triage state contains the canonical shape.

type TriageStore

type TriageStore interface {
	GetTaskTriageState(ctx context.Context, taskID string, actor ActorIdentity) (TriageState, error)
	UpsertTaskTriageState(ctx context.Context, state TriageState) error
}

TriageStore is the persistence surface for durable actor-scoped task triage state.

type Tx

type Tx interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Tx is the narrow SQL transaction surface exposed to generation-state finalizers.

type UnboundTaskSessionCleaner

type UnboundTaskSessionCleaner interface {
	CleanupUnboundTaskSession(ctx context.Context, run Run, ref SessionRef) error
}

UnboundTaskSessionCleaner compensates resources created before a fenced run binding loses its lease race.

type UpdateTaskDefinitionMutation

type UpdateTaskDefinitionMutation struct {
	Task                      Task
	UpdateTaskRow             bool
	PatchNetworkParticipation bool
	NetworkParticipation      *participation.Request
	Actor                     ActorContext
	Events                    []Event
}

UpdateTaskDefinitionMutation commits a task-row update, optional execution profile intent, and every causal event as one persistence command.

type View

type View struct {
	Summary              Summary               `json:"summary"`
	Task                 Task                  `json:"task"`
	Children             []Summary             `json:"children,omitempty"`
	Dependencies         []Dependency          `json:"dependencies,omitempty"`
	DependencyReferences []DependencyReference `json:"dependency_references,omitempty"`
	Runs                 []Run                 `json:"runs,omitempty"`
	Events               []Event               `json:"events,omitempty"`
}

View is the expanded read model returned from single-task lookups.

type WakeCreatorMutation

type WakeCreatorMutation struct {
	TaskID      string    `json:"task_id"`
	WakeCreator bool      `json:"wake_creator"`
	UpdatedAt   time.Time `json:"updated_at"`
}

WakeCreatorMutation captures the per-task creator-wake opt-in flag.

type WakeEvent

type WakeEvent struct {
	WakeEventID string     `json:"wake_event_id"`
	WorkspaceID string     `json:"workspace_id,omitempty"`
	TaskID      string     `json:"task_id"`
	RunID       string     `json:"run_id,omitempty"`
	Reason      WakeReason `json:"reason"`
	Summary     string     `json:"summary"`
}

WakeEvent is the task-domain wake payload handed to the daemon bridge.

func (WakeEvent) Normalize

func (e WakeEvent) Normalize() WakeEvent

Normalize returns a trimmed wake event with bounded redacted summary text.

func (WakeEvent) Validate

func (e WakeEvent) Validate() error

Validate reports whether the wake event has the minimum delivery identity.

type WakeNotifier

type WakeNotifier interface {
	WakeCreator(ctx context.Context, creatorSessionID string, ev WakeEvent) error
}

WakeNotifier delivers one wake event to a creator session.

type WakeReason

type WakeReason string

WakeReason identifies the transition class that woke a task creator.

const (
	// WakeReasonTerminal wakes the creator after a run reaches a terminal state.
	WakeReasonTerminal WakeReason = "terminal"
	// WakeReasonBlocked wakes the creator after a task block is created.
	WakeReasonBlocked WakeReason = "blocked"
	// WakeReasonNeedsAttention wakes the creator after the task escalates to needs_attention.
	WakeReasonNeedsAttention WakeReason = "needs_attention"
)

func (WakeReason) Normalize

func (r WakeReason) Normalize() WakeReason

Normalize returns the canonical wake reason value.

func (WakeReason) Validate

func (r WakeReason) Validate(path string) error

Validate reports whether the wake reason is supported.

type WorkerMode

type WorkerMode string

WorkerMode identifies how a task narrows worker selection.

func (WorkerMode) Normalize

func (m WorkerMode) Normalize() WorkerMode

Normalize returns the normalized worker mode.

type WorkerProfile

type WorkerProfile struct {
	Mode                  WorkerMode `json:"mode"`
	AgentName             string     `json:"agent_name,omitempty"`
	Provider              string     `json:"provider,omitempty"`
	Model                 string     `json:"model,omitempty"`
	AllowedAgentNames     []string   `json:"allowed_agent_names,omitempty"`
	PreferredAgentNames   []string   `json:"preferred_agent_names,omitempty"`
	RequiredCapabilities  []string   `json:"required_capabilities,omitempty"`
	PreferredCapabilities []string   `json:"preferred_capabilities,omitempty"`
}

WorkerProfile narrows eligible task workers without granting runtime authority.

type WorktreeMode

type WorktreeMode string

WorktreeMode identifies task-level worktree selection behavior.

const (
	// WorktreeModeInherit resolves through the configured task default at enqueue time.
	WorktreeModeInherit WorktreeMode = "inherit"
	// WorktreeModeNone runs from the parent workspace root.
	WorktreeModeNone WorktreeMode = "none"
	// WorktreeModeRef binds the run to one attached worktree.
	WorktreeModeRef WorktreeMode = "ref"
	// WorktreeModePerRun materializes one fresh worktree for each run.
	WorktreeModePerRun WorktreeMode = "per_run"
)

func (WorktreeMode) Normalize

func (m WorktreeMode) Normalize() WorktreeMode

Normalize returns the normalized worktree mode.

type WorktreePolicy

type WorktreePolicy struct {
	Mode        WorktreeMode `json:"mode"`
	WorktreeRef string       `json:"worktree_ref,omitempty"`
}

WorktreePolicy selects task-level worktree behavior at enqueue time.

type WorktreePolicyMutation

type WorktreePolicyMutation struct {
	TaskID string
	Policy WorktreePolicy
	Event  Event
}

WorktreePolicyMutation commits one worktree block patch and its event.

type WorktreeRefValidator

type WorktreeRefValidator interface {
	ValidateTaskWorktreeRef(ctx context.Context, workspaceID string, ref string) error
}

WorktreeRefValidator checks that a profile reference resolves to an attached worktree owned by the task's workspace.

Source Files

Jump to

Keyboard shortcuts

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