coordination

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package coordination defines accountable assignments around Cortex execution. Message integrity does not grant authority or establish task acceptance.

Index

Constants

View Source
const (
	PrefixTaskAcceptance    id.Prefix = "taccept"
	PrefixTaskAcceptedEvent id.Prefix = "taccepted"
	MaxTaskAcceptanceBytes            = 2 << 20
)
View Source
const (
	// PrefixBoardTransition identifies an immutable publication or resolution.
	PrefixBoardTransition id.Prefix = "btrans"
	// MaxBoardTransitions bounds all candidates and resolutions for one resource.
	MaxBoardTransitions = 128
	// MaxPlanBoardTransitions bounds retained transitions within one plan.
	MaxPlanBoardTransitions = 4096
	// MaxBoardRequestBytes bounds retained binding and dependency metadata.
	MaxBoardRequestBytes = 64 << 10
)
View Source
const (
	PrefixClaim      id.Prefix = "tclaim"
	MaxClaimBytes              = 16 << 10
	MaxClaimDuration           = 30 * time.Minute
)
View Source
const (
	PrefixAssignment id.Prefix = "assign"
	PrefixHandoff    id.Prefix = "hoff"
	MaxHandoffBytes            = 256 << 10
)
View Source
const (
	PrefixReview   id.Prefix = "areview"
	MaxReviewBytes           = MaxHandoffBytes + 128<<10
)
View Source
const (
	// PrefixTaskAdjudication identifies an immutable review policy decision.
	PrefixTaskAdjudication id.Prefix = "tadj"
	// MaxTaskAdjudicationBytes bounds stored decisions without copying artifacts.
	MaxTaskAdjudicationBytes = 32 << 10
)
View Source
const (
	MaxTaskUsageJobs  = 256
	MaxTaskUsageBytes = 16 << 20
)
View Source
const MaxPlanningArtifactResources = MaxPlanBoardTransitions / MaxBoardTransitions

MaxPlanningArtifactResources bounds a complete operator board projection.

View Source
const PrefixPlanReplan id.Prefix = "rplan"

PrefixPlanReplan identifies one permanently charged proposal attempt.

View Source
const PrefixTaskClaimedEvent id.Prefix = "tclaimed"
View Source
const PrefixTaskDispatchEvent id.Prefix = "tdispatch"
View Source
const PrefixTaskRenewalEvent id.Prefix = "trenew"
View Source
const PrefixTaskRunEvent id.Prefix = "trunstart"

Variables

View Source
var (
	ErrInvalidTaskAcceptance  = cortex.ErrInvalidTaskAcceptance
	ErrTaskAcceptanceConflict = cortex.ErrTaskAcceptanceConflict
	ErrTaskAcceptanceNotFound = cortex.ErrTaskAcceptanceNotFound
)
View Source
var (
	ErrInvalidAssignment     = cortex.ErrInvalidAssignment
	ErrAssignmentConflict    = cortex.ErrAssignmentConflict
	ErrAssignmentNotFound    = cortex.ErrAssignmentNotFound
	ErrAssignmentUnavailable = cortex.ErrAssignmentUnavailable
)
View Source
var (
	ErrInvalidClaim  = cortex.ErrInvalidClaim
	ErrClaimConflict = cortex.ErrClaimConflict
	ErrClaimNotFound = cortex.ErrClaimNotFound
)
View Source
var (
	ErrInvalidHandoff     = cortex.ErrInvalidHandoff
	ErrHandoffUnavailable = cortex.ErrHandoffUnavailable
)
View Source
var (
	ErrInvalidReview  = cortex.ErrInvalidReview
	ErrReviewConflict = cortex.ErrReviewConflict
	ErrReviewNotFound = cortex.ErrReviewNotFound
)
View Source
var (
	ErrInvalidScheduler                = cortex.ErrInvalidScheduler
	ErrSchedulerFull                   = cortex.ErrSchedulerFull
	ErrSchedulerStopped                = cortex.ErrSchedulerStopped
	ErrSchedulerReconciliationRequired = cortex.ErrSchedulerReconciliationRequired
)
View Source
var (
	ErrTaskUsageConflict = cortex.ErrTaskUsageConflict
	ErrTaskUsageClosed   = cortex.ErrTaskUsageClosed
)
View Source
var (
	ErrInvalidTaskSettlement  = cortex.ErrInvalidTaskSettlement
	ErrTaskSettlementConflict = cortex.ErrTaskSettlementConflict
)
View Source
var ErrInvalidTaskUsage = cortex.ErrInvalidTaskUsage
View Source
var ErrPlanningDenied = errors.New("cortex: planning operator access denied")

ErrPlanningDenied distinguishes current operator permission from availability.

View Source
var ErrPlanningUnavailable = errors.New("cortex: planning operator unavailable")

ErrPlanningUnavailable means the host has not installed a guarded capability.

Functions

func EventSources

func EventSources() []string

EventSources returns the finite importer categories. Claim and effect history categories include superseded ownership incarnations.

func HandoffSendParams

func HandoffSendParams(h Handoff, localNode string) (a2a.SendParams, error)

HandoffSendParams preserves the sealed body through A2A text/metadata fields. localNode is this host's canonical identity, mapped to empty local routing.

func PrepareTaskUsageSettlement

func PrepareTaskUsageSettlement(r TaskUsageSettlementRequest, snapshot TaskUsageSnapshot, closed TaskUsageClosure, reservation execution.Reservation, at time.Time) (execution.Settlement, error)

PrepareTaskUsageSettlement derives charges from complete retained evidence. Callers must authenticate Billing and hold current authority and storage guards. This function does not establish those guarantees or write accounting.

func ValidateClaimSuccessor

func ValidateClaimSuccessor(previous, next Claim) error

ValidateClaimSuccessor checks the ownership chain without authorizing it.

func ValidateHandoff

func ValidateHandoff(h Handoff, p planning.Plan, current HandoffAuthority, at time.Time) error

ValidateHandoff checks a peer proposal against current local plan and grants. Inputs still require authorized content reads and trusted verification before they can satisfy task dependencies. This method performs no I/O.

func ValidateHandoffPlan

func ValidateHandoffPlan(h Handoff, p planning.Plan, at time.Time) error

ValidateHandoffPlan checks the proposal against sealed plan definitions and time. It does not authenticate a principal, grant or scheduler generation.

func ValidateReview

func ValidateReview(r Review, subject Assignment, binding verification.Binding, p planning.Plan, at time.Time) error

ValidateReview checks current submission, plan, independent identity/context and all subject inputs. The caller must authenticate these records and load retained bytes. Findings never enter verification.Aggregate as verdicts.

func ValidateTaskCompletion

func ValidateTaskCompletion(request TaskCompletionRequest, subject Assignment, binding verification.Binding, p planning.Plan, at time.Time) error

ValidateTaskCompletion checks the exact producer and independent review input set before any reviewer dispatch. The store also validates retained execution.

func ValidateTaskRecoverySnapshot

func ValidateTaskRecoverySnapshot(proof TaskRecoveryProof, snapshot execution.RunRecoverySnapshot, c Claim, h Handoff, current verification.Binding, at time.Time) error

ValidateTaskRecoverySnapshot checks terminality and original invocation bindings. The caller must hold current host authority, authenticate the proof, and keep the journal locked through the adoption transaction.

Types

type A2AHandoffHandler

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

A2AHandoffHandler validates transport identity and delegates local admission. Remote aliases must agree with the authenticated resolver's canonical nodes. A nil receiver permits outgoing transport only, never local admission.

func NewA2AHandoffHandler

func NewA2AHandoffHandler(localNode string, receiver *HandoffReceiver, now func() time.Time) (*A2AHandoffHandler, error)

NewA2AHandoffHandler keeps typed assignment logic outside the messaging bus.

func (*A2AHandoffHandler) ReceiveHandoff

func (a *A2AHandoffHandler) ReceiveHandoff(ctx context.Context, e *a2a.Envelope) error

ReceiveHandoff applies fresh host authority and durable admission to local work.

func (*A2AHandoffHandler) ValidateHandoff

func (a *A2AHandoffHandler) ValidateHandoff(ctx context.Context, e *a2a.Envelope) error

ValidateHandoff checks immutable payload and transport binding before storage.

type AcceptedClaimStore

type AcceptedClaimStore interface {
	ListAcceptedTaskClaims(context.Context, TaskAcceptanceListRequest) ([]Claim, error)
}

AcceptedClaimStore pages immutable accepted ownership by acceptance ID, including claims superseded by later plan revisions. Every returned claim must retain its matching acceptance and ownership history. Reads grant no authority.

type AcceptedDependency

type AcceptedDependency struct {
	AcceptanceID id.ID                `json:"acceptance_id"`
	Digest       string               `json:"digest"`
	Current      verification.Binding `json:"current"`
}

AcceptedDependency names a retained acceptance and freshly resolved context. Hosts must fence current grants and external revisions during acceptance.

type AdjudicationDecision

type AdjudicationDecision string

AdjudicationDecision is review policy only, not verification or acceptance.

const (
	AdjudicationSupported AdjudicationDecision = "supported"
	AdjudicationBlocked   AdjudicationDecision = "blocked"
)

type AgentReplyListRequest

type AgentReplyListRequest struct {
	After string
	Limit int
}

AgentReplyListRequest bounds host discovery with an opaque cursor.

type AgentReplyPage

type AgentReplyPage struct {
	Runs []ScheduledAgentReply
	Next string
}

AgentReplyPage contains at most the requested limit of distinct scoped runs. Empty Next ends a pass; a later pass revisits skipped and interrupted work.

type AgentReplyRecoverer

type AgentReplyRecoverer interface {
	Recover(context.Context, id.AgentRunID) error
}

AgentReplyRecoverer validates the current suspension and authority before resume.

type AgentReplyRecoveryConfig

type AgentReplyRecoveryConfig struct {
	Discovery                                  AgentReplySource
	Recoverer                                  AgentReplyRecoverer
	Interval, DiscoveryTimeout, AttemptTimeout time.Duration
	MaxInFlight, MaxPerScope                   int
	ReportError                                func(error)
}

AgentReplyRecoveryConfig bounds discovery and synchronous recovery attempts. Callbacks must honor cancellation. ReportError must return promptly.

type AgentReplyRecoveryService

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

AgentReplyRecoveryService owns discovery, per-scope fairness and joined shutdown.

func NewAgentReplyRecoveryService

func NewAgentReplyRecoveryService(config AgentReplyRecoveryConfig) (*AgentReplyRecoveryService, error)

NewAgentReplyRecoveryService defaults to four concurrent runs, one per scope, one-second polling, five-second discovery and one-minute attempts. Attempts cannot exceed thirty minutes. Construction starts no background work.

func (*AgentReplyRecoveryService) RequestStop

func (s *AgentReplyRecoveryService) RequestStop()

RequestStop cancels discovery and every owned attempt before drainage.

func (*AgentReplyRecoveryService) Start

Start preserves host identity while owning an independent service lifetime.

func (*AgentReplyRecoveryService) Status

Status returns local counters without run content or scope values.

func (*AgentReplyRecoveryService) Stop

Stop succeeds only after discovery and all recovery callbacks drain.

type AgentReplySource

type AgentReplySource interface {
	ListAgentReplyRuns(context.Context, AgentReplyListRequest) (AgentReplyPage, error)
}

AgentReplySource discovers paused or admitted runs under current host authority. Include runs with retained answers even if admission has not been recorded. Complete each pass, honor cancellation and never execute agents in this port.

type ArtifactBoard

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

ArtifactBoard exposes guarded durable publication and private history reads. It does not publish content or treat historical heads as fresh task evidence.

func NewArtifactBoard

func NewArtifactBoard(storage ArtifactBoardStore, authority ArtifactBoardAuthority) (*ArtifactBoard, error)

NewArtifactBoard requires explicit current authority for every operation.

func (*ArtifactBoard) Read

Read returns detached private metadata after a second current authorization check. Referenced content still requires its normal verified export path.

func (*ArtifactBoard) Write

Write retains a publication, conflict or explicitly authorized resolution. Recover uncertain acknowledgments using the same immutable request ID.

type ArtifactBoardAuthority

type ArtifactBoardAuthority interface {
	WithArtifactBoardFence(context.Context, ArtifactBoardRequest, func(ArtifactBoardRequest) error) error
	AuthorizeArtifactBoard(context.Context, ArtifactBoardRequest) error
	WithArtifactBoardReadFence(context.Context, ArtifactBoardRead, func(ArtifactBoardRead) error) error
	AuthorizeArtifactBoardRead(context.Context, ArtifactBoardRead) error
}

ArtifactBoardAuthority authenticates the current caller and holds current resource, source and evidence revisions across each callback. Resolve requests require an explicit ownership-transfer grant in addition to publication rights. Implementations must call next exactly once synchronously and honor cancellation.

type ArtifactBoardEntry

type ArtifactBoardEntry struct {
	SchemaVersion  int                  `json:"schema_version"`
	Request        ArtifactBoardRequest `json:"request"`
	RequestDigest  string               `json:"request_digest"`
	PlanRevision   int64                `json:"plan_revision"`
	Sequence       int64                `json:"sequence"`
	HeadRevision   int64                `json:"head_revision"`
	PreviousDigest string               `json:"previous_digest,omitempty"`
	Conflict       bool                 `json:"conflict"`
	Owner          Identity             `json:"owner"`
	TaskID         id.ID                `json:"task_id"`
	Artifact       evidence.Ref         `json:"artifact"`
	At             time.Time            `json:"at"`
	Digest         string               `json:"digest"`
}

ArtifactBoardEntry retains a candidate even when its expected head lost a race. A conflict never advances HeadRevision. PreviousDigest names the head observed at admission. Only explicit resolution can transfer its owner.

func SealArtifactBoardEntry

func SealArtifactBoardEntry(e ArtifactBoardEntry) (ArtifactBoardEntry, error)

SealArtifactBoardEntry checks retained structure and detaches references.

func (ArtifactBoardEntry) Validate

func (e ArtifactBoardEntry) Validate() error

Validate verifies integrity, not current evidence freshness or authority.

type ArtifactBoardRead

type ArtifactBoardRead struct {
	Scope    cortex.Scope           `json:"scope"`
	PlanID   id.ID                  `json:"plan_id"`
	Resource planning.ResourceGrant `json:"resource"`
	After    int64                  `json:"after"`
	Limit    int                    `json:"limit"`
}

ArtifactBoardRead pins an exact resource and finite history page. Metadata remains private; historical references do not grant content access or certify that a formerly accepted output is still valid under current source revisions.

func (ArtifactBoardRead) Freeze

Freeze checks metadata read bounds before any storage access.

type ArtifactBoardRequest

type ArtifactBoardRequest struct {
	SchemaVersion    int                    `json:"schema_version"`
	ID               id.ID                  `json:"id"`
	Scope            cortex.Scope           `json:"scope"`
	PlanID           id.ID                  `json:"plan_id"`
	PlanDigest       string                 `json:"plan_digest"`
	Resource         planning.ResourceGrant `json:"resource"`
	AcceptanceID     id.ID                  `json:"acceptance_id"`
	AcceptanceDigest string                 `json:"acceptance_digest"`
	Current          verification.Binding   `json:"current"`
	Dependencies     []AcceptedDependency   `json:"dependencies,omitempty"`
	ExpectedRevision int64                  `json:"expected_revision"`
	ExpectedDigest   string                 `json:"expected_digest,omitempty"`
	Resolve          id.ID                  `json:"resolve,omitempty"`
	Actor            string                 `json:"actor"`
	Reason           string                 `json:"reason"`
}

ArtifactBoardRequest publishes an accepted output or explicitly resolves a retained conflict. Resource is an exact declared write grant. Resolve names the conflicting transition whose candidate is selected, never a content patch. Current and Dependencies are freshly resolved under the host authority fence.

func (ArtifactBoardRequest) Freeze

Freeze validates and detaches bounded input without establishing authority.

type ArtifactBoardStore

type ArtifactBoardStore interface {
	WriteArtifactBoard(context.Context, ArtifactBoardRequest) (ArtifactBoardEntry, error)
	ReadArtifactBoard(context.Context, ArtifactBoardRead) ([]ArtifactBoardEntry, error)
}

ArtifactBoardStore is trusted atomic storage. Public callers use ArtifactBoard so historical retries and reads still authenticate the current caller.

type ArtifactPublicationConfig

type ArtifactPublicationConfig struct {
	Store            ArtifactPublicationStore
	Discovery        TaskPlanSource
	Authority        ArtifactBoardAuthority
	Resolver         ArtifactPublicationResolver
	AuthorizeScan    func(context.Context, id.ID) error
	PageSize         int
	PageTimeout      time.Duration
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

ArtifactPublicationConfig connects accepted output discovery to the guarded board. Only one offer per acceptance is processed per pass. Current source and evidence bindings must be resolved under the board authority fence.

type ArtifactPublicationResolver

type ArtifactPublicationResolver interface {
	ResolveArtifactPublication(context.Context, TaskAcceptance) (*ArtifactBoardRequest, error)
}

ArtifactPublicationResolver supplies one currently authorized publication for the exact acceptance. Return nil while unresolved. It must not invoke tools or models. Conflict resolution is an explicit separate ArtifactBoard.Write action.

type ArtifactPublicationService

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

ArtifactPublicationService publishes qualified accepted outputs and retains conflicts for explicit resolution. It never edits accepted runs or their output.

func NewArtifactPublicationService

func NewArtifactPublicationService(config ArtifactPublicationConfig) (*ArtifactPublicationService, error)

NewArtifactPublicationService validates ports and bounds without starting work.

func (*ArtifactPublicationService) RequestStop

func (s *ArtifactPublicationService) RequestStop()

RequestStop signals cancellation while retaining in-flight ownership.

func (*ArtifactPublicationService) Start

Start begins accepted-output discovery.

func (*ArtifactPublicationService) Status

Status exposes counters without private artifact metadata.

func (*ArtifactPublicationService) Stop

Stop waits for all publication callbacks to drain.

type ArtifactPublicationStore

type ArtifactPublicationStore interface {
	ArtifactBoardStore
	TaskAcceptanceStore
}

ArtifactPublicationStore discovers accepted output and retains board decisions.

type Assignment

type Assignment struct {
	SchemaVersion  int             `json:"schema_version"`
	Handoff        Handoff         `json:"handoff"`
	Revision       int64           `json:"revision"`
	State          AssignmentState `json:"state"`
	Actor          string          `json:"actor"`
	Reason         string          `json:"reason"`
	At             time.Time       `json:"at"`
	PreviousDigest string          `json:"previous_digest,omitempty"`
	RequestDigest  string          `json:"request_digest"`
	Submission     *Submission     `json:"submission,omitempty"`
	Digest         string          `json:"digest"`
}

Assignment is one immutable journal revision, including its original proposal. Submissions require retained evidence admission. Cancellation does not prove external effects stopped, and a submission never establishes task success.

func Advance

func Advance(previous Assignment, change AssignmentChange, at time.Time) (Assignment, error)

Advance records one legal observation without changing authority or ownership.

func Propose

func Propose(h Handoff, at time.Time) (Assignment, error)

Propose creates a detached initial snapshot. The store must validate the proposal against the current plan under the same lock used by plan revisions.

func (Assignment) Validate

func (a Assignment) Validate() error

Validate checks a snapshot's integrity; the store checks its predecessor.

type AssignmentChange

type AssignmentChange struct {
	AssignmentID     id.ID           `json:"assignment_id"`
	ExpectedRevision int64           `json:"expected_revision"`
	HandoffDigest    string          `json:"handoff_digest"`
	Fence            uint64          `json:"fence"`
	State            AssignmentState `json:"state"`
	Actor            string          `json:"actor"`
	Reason           string          `json:"reason"`
	Submission       *Submission     `json:"submission,omitempty"`
}

AssignmentChange binds an observation to the original assignment generation. Actor must come from authenticated host context, never an unchecked peer field.

func (AssignmentChange) BindingDigest

func (c AssignmentChange) BindingDigest() (string, error)

BindingDigest validates and hashes every caller-controlled transition field.

func (AssignmentChange) Freeze

Freeze detaches every transition field before host storage callbacks.

type AssignmentHistoryRequest

type AssignmentHistoryRequest struct {
	AssignmentID  id.ID
	AfterRevision int64
	Limit         int
}

AssignmentHistoryRequest pages immutable revisions in ascending order.

type AssignmentListRequest

type AssignmentListRequest struct {
	PlanID id.ID
	After  id.ID
	Limit  int
}

AssignmentListRequest pages stable identities for one plan, in lexical order.

type AssignmentState

type AssignmentState string

AssignmentState records host-observed progress. None of these states grants dispatch permission or establishes verified task success.

const (
	AssignmentProposed  AssignmentState = "proposed"
	AssignmentAccepted  AssignmentState = "accepted"
	AssignmentWorking   AssignmentState = "working"
	AssignmentBlocked   AssignmentState = "blocked"
	AssignmentSubmitted AssignmentState = "submitted"
	AssignmentRejected  AssignmentState = "rejected"
	AssignmentCancelled AssignmentState = "cancelled"
	MaxAssignmentBytes                  = MaxHandoffBytes + 16<<10
)

func (AssignmentState) Terminal

func (s AssignmentState) Terminal() bool

Terminal reports whether the progress journal can accept another observation.

type AssignmentStore

type AssignmentStore interface {
	ProposeAssignment(context.Context, Handoff) (Assignment, error)
	AdvanceAssignment(context.Context, AssignmentChange) (Assignment, error)
	GetAssignment(context.Context, id.ID) (Assignment, error)
	ListAssignments(context.Context, AssignmentListRequest) ([]Assignment, error)
	AssignmentHistory(context.Context, AssignmentHistoryRequest) ([]Assignment, error)
}

AssignmentStore is an optional exact-scope progress journal, not an authority boundary. Hosts must authorize every call and fence grants and worker ownership separately. It is not sufficient on its own for HandoffReceiverConfig.Accept. Identical retries return the original observation even after expiry or replan; that historical acknowledgement must never be interpreted as permission to run. New progress serializes with plan revisions; terminal observations remain legal after expiry or replan. No method dispatches work or marks a task successful.

type BudgetedClaim

type BudgetedClaim struct {
	Claim       Claim                 `json:"claim"`
	Reservation execution.Reservation `json:"reservation"`
	Fresh       bool                  `json:"-"`
}

BudgetedClaim retains the original acquisition, including its allocation. Fresh is false on every retry, even if the original response was lost. These historical snapshots do not reflect later renewals or settlements.

func (BudgetedClaim) Validate

func (a BudgetedClaim) Validate(request BudgetedClaimRequest) error

Validate checks that the retained acquisition matches its original request. This proves neither current ownership nor permission to spend the allocation.

type BudgetedClaimRequest

type BudgetedClaimRequest struct {
	Claim       ClaimRequest                 `json:"claim"`
	Reservation execution.ReservationRequest `json:"reservation"`
}

BudgetedClaimRequest reserves ownership and capacity in one transaction. The reservation's OwnerRef must be the claim ID. Neither record grants authority or proves task readiness; the host must establish those before dispatch.

func (BudgetedClaimRequest) Freeze

Freeze detaches the request and checks that both reservations name one attempt.

type BudgetedClaimStore

type BudgetedClaimStore interface {
	AcquireBudgetedTaskClaim(context.Context, BudgetedClaimRequest) (BudgetedClaim, error)
	GetBudgetedTaskClaim(context.Context, id.ID) (BudgetedClaim, error)
}

BudgetedClaimStore atomically reserves one task owner and its capacity. It is an accounting primitive, not ClaimReadyTask or a runtime dispatch API.

type Claim

type Claim struct {
	SchemaVersion    int           `json:"schema_version"`
	ID               id.ID         `json:"id"`
	Scope            cortex.Scope  `json:"scope"`
	PlanID           id.ID         `json:"plan_id"`
	PlanRevision     int64         `json:"plan_revision"`
	PlanDigest       string        `json:"plan_digest"`
	TaskID           id.ID         `json:"task_id"`
	Worker           Identity      `json:"worker"`
	GrantRef         string        `json:"grant_ref"`
	Fence            uint64        `json:"fence"`
	Revision         int64         `json:"revision"`
	State            ClaimState    `json:"state"`
	RunID            id.AgentRunID `json:"run_id,omitempty"`
	AcquiredAt       time.Time     `json:"acquired_at"`
	At               time.Time     `json:"at"`
	ExpiresAt        time.Time     `json:"expires_at"`
	Deadline         time.Time     `json:"deadline"`
	PreviousDigest   string        `json:"previous_digest,omitempty"`
	Digest           string        `json:"digest"`
	AcceptanceID     *id.ID        `json:"acceptance_id,omitempty"`
	RecoveryDigest   string        `json:"recovery_digest,omitempty"`
	RetirementDigest string        `json:"retirement_digest,omitempty"`
}

Claim is an immutable ownership revision. Dispatching is recorded before an external call. Its expiry enters recovery, never permission to repeat work.

func AcquireClaim

func AcquireClaim(previous *Claim, request ClaimRequest, p planning.Plan, at time.Time) (Claim, error)

AcquireClaim starts an attempt after release, or after a completed task moves to a newer plan revision. Success cannot be overwritten within the same plan. An expired dispatch remains unavailable until a separate recovery protocol proves its effects and run are settled. This function cannot waive recovery.

func AdoptRecoveredClaim

func AdoptRecoveredClaim(c Claim, token ClaimToken, acceptanceID id.ID, proof TaskRecoveryProof, at time.Time) (Claim, error)

AdoptRecoveredClaim records a proof-bound recovery transition without renewing the expired lease. Storage must first validate current task and journal evidence.

func BeginDispatch

func BeginDispatch(c Claim, token ClaimToken, runID id.AgentRunID, at time.Time) (Claim, error)

BeginDispatch binds a reserved child run before any external execution. A lost acknowledgment must be reconciled by the host and is never permission to retry.

func CompleteClaim

func CompleteClaim(c Claim, token ClaimToken, acceptanceID id.ID, at time.Time) (Claim, error)

CompleteClaim closes a live dispatched claim after storage validates evidence. The pure transition alone does not establish verifier trust or task acceptance.

func ExpireClaim

func ExpireClaim(c Claim, expectedRevision int64, at time.Time) (Claim, error)

ExpireClaim releases only reservations that never began dispatch. A dispatched run becomes recovering and retains its fence and identity for reconciliation.

func RenewClaim

func RenewClaim(c Claim, token ClaimToken, duration time.Duration, at time.Time) (Claim, error)

RenewClaim extends a live reservation or dispatch without changing its fence.

func RetireRecoveredClaim

func RetireRecoveredClaim(c Claim, request TaskRetirementRequest, at time.Time) (Claim, error)

RetireRecoveredClaim constructs the ownership successor. Storage must first compare the complete sealed journal, unsuccessful closure and guarded settlement. Retirement preserves the expired lease and original run; it grants no retry.

func (Claim) Token

func (c Claim) Token() ClaimToken

Token identifies this exact immutable observation of ownership.

func (Claim) Validate

func (c Claim) Validate() error

Validate checks integrity; callers still need current host authorization.

type ClaimExpiryStore

type ClaimExpiryStore interface {
	ListTaskClaims(context.Context, ClaimListRequest) ([]Claim, error)
	ExpireTaskClaim(context.Context, id.ID, id.ID, int64) (Claim, error)
}

ClaimExpiryStore is the scoped storage capability needed for expiry. It cannot dispatch work, accept results, settle usage or grant a replacement worker. Implementations must honor cancellation and atomically compare revisions.

type ClaimHistoryRequest

type ClaimHistoryRequest struct {
	PlanID        id.ID
	TaskID        id.ID
	AfterRevision int64
	Limit         int
}

ClaimHistoryRequest pages immutable task ownership revisions.

type ClaimListRequest

type ClaimListRequest struct {
	PlanID      id.ID
	AfterTaskID id.ID
	Limit       int
}

ClaimListRequest pages every task ever claimed in the plan, including tasks removed by replanning. A complete sweep starts again after reaching the end.

func (ClaimListRequest) Validate

func (r ClaimListRequest) Validate() error

Validate checks the shared pagination bounds without granting scope access.

type ClaimRecoveryConfig

type ClaimRecoveryConfig struct {
	Store            ClaimExpiryStore
	Clock            verification.Clock
	Discovery        TaskPlanSource
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

ClaimRecoveryConfig connects authorized discovery to scoped claim expiry. Discovery must include plans with outstanding claims even after cancellation or completion. PageTimeout bounds one storage page, not an entire plan pass. MaxInFlight bounds concurrent plan passes; MaxPerScope bounds each exact scope. ReportError must return promptly. Store callbacks must honor cancellation.

type ClaimRecoveryService

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

ClaimRecoveryService owns bounded discovery and paged expiry until Stop drains it. It does not execute agents, reconcile providers, accept results or refund reservations. Restart rereads from the beginning, preserving durable outcomes.

func NewClaimRecoveryService

func NewClaimRecoveryService(config ClaimRecoveryConfig) (*ClaimRecoveryService, error)

NewClaimRecoveryService validates explicit ports without starting work. Defaults are four concurrent plans, one per scope, 256 claims per page, a five-second page timeout and a one-second interval between pages. A pass keeps its slot until it reaches the end or fails. The host source must eventually finish each pass.

func (*ClaimRecoveryService) RequestStop

func (s *ClaimRecoveryService) RequestStop()

RequestStop signals cancellation. Stop must still join the owned work.

func (*ClaimRecoveryService) Start

func (s *ClaimRecoveryService) Start(ctx context.Context) error

Start preserves service identity values and owns an independent lifetime.

func (*ClaimRecoveryService) Status

Status reports local process counters without scope or run content.

func (*ClaimRecoveryService) Stop

Stop waits for discovery and all page callbacks before returning success.

type ClaimRequest

type ClaimRequest struct {
	SchemaVersion    int           `json:"schema_version"`
	ID               id.ID         `json:"id"`
	PlanID           id.ID         `json:"plan_id"`
	PlanRevision     int64         `json:"plan_revision"`
	PlanDigest       string        `json:"plan_digest"`
	TaskID           id.ID         `json:"task_id"`
	ExpectedRevision int64         `json:"expected_revision"`
	Worker           Identity      `json:"worker"`
	GrantRef         string        `json:"grant_ref"`
	Duration         time.Duration `json:"duration"`
}

ClaimRequest reserves exclusive ownership. It does not prove readiness, grant authority or reserve execution budget. The scheduler must establish those separately before atomically recording dispatch and calling the agent runtime.

func (ClaimRequest) Freeze

func (r ClaimRequest) Freeze() (ClaimRequest, string, error)

Freeze detaches and fingerprints a bounded ownership request.

type ClaimState

type ClaimState string

ClaimState distinguishes a reservation from a dispatch with uncertain effects.

const (
	ClaimHeld        ClaimState = "held"
	ClaimDispatching ClaimState = "dispatching"
	ClaimRecovering  ClaimState = "recovering"
	ClaimReleased    ClaimState = "released"
	ClaimRetired     ClaimState = "retired"
	ClaimCompleted   ClaimState = "completed"
)

type ClaimStore

type ClaimStore interface {
	AcquireTaskClaim(context.Context, ClaimRequest) (Claim, error)
	RenewTaskClaim(context.Context, ClaimToken, time.Duration) (Claim, error)
	BeginTaskDispatch(context.Context, ClaimToken, id.AgentRunID) (DispatchAdmission, error)
	ExpireTaskClaim(context.Context, id.ID, id.ID, int64) (Claim, error)
	GetTaskClaim(context.Context, id.ID, id.ID) (Claim, error)
	ListTaskClaims(context.Context, ClaimListRequest) ([]Claim, error)
	TaskClaimHistory(context.Context, ClaimHistoryRequest) ([]Claim, error)
}

ClaimStore serializes task ownership separately from readiness and execution. A host must resolve current identity/grants. Tokens are not credentials and historical acknowledgments do not renew permission. All reads use exact scope.

type ClaimSweepPage

type ClaimSweepPage struct {
	NextTaskID                               id.ID
	Scanned, Released, Recovering, Conflicts int
}

ClaimSweepPage contains acknowledged observations, not execution permission. NextTaskID is nonzero only for a full page. Continue with that cursor, then restart from the beginning after an empty cursor to revisit live or conflicting claims. Counts are per call and do not imply newly committed transitions.

type ClaimSweeper

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

ClaimSweeper expires at most one bounded page in an explicitly supplied scope. It releases unused claims and fences dispatched work into recovery. The caller owns discovery, periodic scheduling and cancellation. Recovering work requires provider and effect reconciliation before any retry or acceptance.

func NewClaimSweeper

func NewClaimSweeper(store ClaimExpiryStore, clock verification.Clock) (*ClaimSweeper, error)

NewClaimSweeper requires explicit storage and a trusted observation clock. Storage checks expiry against its own clock inside the revision transaction.

func (*ClaimSweeper) Sweep

Sweep validates the entire page before its first write. A concurrent renewal or expiry is a conflict to revisit on the next pass. Other errors return no cursor: some writes may have committed, so repeat the same page using fresh storage observations. An error or a historical acknowledgment never permits execution.

type ClaimToken

type ClaimToken struct {
	ClaimID  id.ID    `json:"claim_id"`
	PlanID   id.ID    `json:"plan_id"`
	TaskID   id.ID    `json:"task_id"`
	Worker   Identity `json:"worker"`
	Fence    uint64   `json:"fence"`
	Revision int64    `json:"revision"`
}

ClaimToken is an optimistic fence, not a bearer credential. Every mutation checks its full identity, generation and revision against retained ownership.

func (ClaimToken) Validate

func (t ClaimToken) Validate() error

Validate checks a token's bounded shape without granting its holder authority.

type ClaimedTaskWorker

type ClaimedTaskWorker interface {
	RunClaimedTask(context.Context, ReadyTaskClaimRequest, ReadyTaskClaim) error
}

ClaimedTaskWorker runs one fresh ownership admission. Implementations must use guarded dispatch, accepted assignments and RunPreparedTask (or an equivalent fenced runtime). The receipt alone never authorizes a provider or tool call. Return when work suspends or enters asynchronous verification, preserving its durable state. A return releases local capacity, never shared reservations. Honor cancellation and perform no detached work after returning.

type CurrentTaskAcceptance

type CurrentTaskAcceptance struct {
	State      planning.TaskState `json:"state"`
	ObservedAt time.Time          `json:"observed_at"`
	ValidUntil time.Time          `json:"valid_until"`
}

CurrentTaskAcceptance is an observation of current acceptance, never a lease. ValidUntil includes reviewer and prerequisite evidence retention bounds.

type CurrentTaskAcceptanceRequest

type CurrentTaskAcceptanceRequest struct {
	Accepted     AcceptedDependency   `json:"accepted"`
	Dependencies []AcceptedDependency `json:"dependencies,omitempty"`
}

CurrentTaskAcceptanceRequest pins a retained acceptance and freshly authorized bindings for its full prerequisite chain. References never grant access.

func (CurrentTaskAcceptanceRequest) Validate

func (r CurrentTaskAcceptanceRequest) Validate() error

Validate bounds the evidence closure before storage or external resolution.

type CurrentTaskAcceptanceStore

type CurrentTaskAcceptanceStore interface {
	ReadCurrentTaskAcceptance(context.Context, CurrentTaskAcceptanceRequest) (CurrentTaskAcceptance, error)
}

CurrentTaskAcceptanceStore reuses transactional admission validation for an operator read, including late contradictions and changed assignment state. The host must fence current grants and external source revisions for all inputs.

type Delivery

type Delivery struct {
	Event     Event  `json:"event"`
	SinkID    string `json:"sink_id"`
	Reference string `json:"reference"`
}

Delivery binds an authenticated sink acknowledgment to one exact immutable event. Reference is a private receipt identifier, never event content.

func (Delivery) Validate

func (r Delivery) Validate() error

Validate checks receipt bindings. The trusted sink must authenticate transport and durable receipt identity; a string or hash alone is not external proof.

type DeliveryRequest

type DeliveryRequest struct {
	Event  Event  `json:"event"`
	SinkID string `json:"sink_id"`
}

DeliveryRequest pins one immutable private event and sink.

func (DeliveryRequest) Freeze

Freeze detaches metadata before passing it to host ports.

type DispatchAdmission

type DispatchAdmission struct {
	Claim Claim
	Fresh bool
}

DispatchAdmission identifies whether this call first recorded dispatch intent. Fresh is false for historical retries, including after a lost acknowledgment. Even a fresh admission requires current authority, readiness and budget checks in the host scheduler. The store itself never invokes the runtime.

type EffectContinuationOffer

type EffectContinuationOffer struct {
	Request   execution.EffectContinuationRequest
	Arguments []byte
}

EffectContinuationOffer contains exact adapter arguments, never model authority. Return nil while an authenticated provider disposition or grant is unavailable.

type EffectContinuationResolver

type EffectContinuationResolver interface {
	ResolveEffectContinuation(context.Context, Claim, execution.RunRecoverySnapshot, execution.EffectRecord, []execution.EffectContinuation) (*EffectContinuationOffer, error)
}

EffectContinuationResolver resolves proof and arguments without invoking tools. Inputs are detached and scope-authorized; the executor authenticates each offer again under current authority before reserving or dispatching an action.

type EffectContinuationService

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

EffectContinuationService owns discovery, provider reconciliation and admitted retries or compensation. It never dispatches replacement tasks or accepts old candidates. Its retained result evidence is input to a new verified preparation.

func NewEffectContinuationService

func NewEffectContinuationService(config EffectContinuationServiceConfig) (*EffectContinuationService, error)

NewEffectContinuationService validates ports without starting work. It shares the existing bounded recovery traversal and resumes only from durable intent.

func (*EffectContinuationService) RequestStop

func (s *EffectContinuationService) RequestStop()

RequestStop cancels callbacks without claiming they have drained.

func (*EffectContinuationService) Start

Start owns an independent service lifetime with the caller's identity values.

func (*EffectContinuationService) Status

Status exposes local service counts without private provider content.

func (*EffectContinuationService) Stop

Stop joins discovery and every adapter callback before returning success.

type EffectContinuationServiceConfig

type EffectContinuationServiceConfig struct {
	Effects          execution.EffectExecutorConfig
	Authority        execution.EffectContinuationAuthority
	Resolver         EffectContinuationResolver
	Discovery        TaskPlanSource
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

EffectContinuationServiceConfig enables explicit bounded follow-up actions. Effects.Store must implement continuation, discovery, recovery snapshots and recovering ownership. AuthorizeScan must permit private journal reads. Discovery covers plan/claim reads. All callbacks must honor cancellation until drain.

type EffectRecoveryService

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

EffectRecoveryService owns discovery and read-only effect reconciliation. It never seals runs, dispatches tools, adopts results or refunds reservations. Restart scans from the beginning and reuses durable terminal receipts.

func NewEffectRecoveryService

func NewEffectRecoveryService(config EffectRecoveryServiceConfig) (*EffectRecoveryService, error)

NewEffectRecoveryService validates ports without starting work. Defaults are four concurrent plans, one per scope, 64 entries per page, five seconds per claim/seal read and one second between pages. Each effect page is bounded by execution.MaxEffectDuration. Recovery.MaxConcurrent limits scans and probes.

func (*EffectRecoveryService) RequestStop

func (s *EffectRecoveryService) RequestStop()

RequestStop signals cancellation without claiming drainage.

func (*EffectRecoveryService) Start

Start preserves service identity values and owns an independent lifetime.

func (*EffectRecoveryService) Status

Status returns local counters without scope, run or provider content.

func (*EffectRecoveryService) Stop

Stop joins discovery, storage reads and adapter callbacks before returning.

type EffectRecoveryServiceConfig

type EffectRecoveryServiceConfig struct {
	Recovery         execution.EffectExecutorConfig
	Discovery        TaskPlanSource
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

EffectRecoveryServiceConfig connects authorized plan discovery to sealed recovering runs. Recovery.Store must also implement BoundEffectStore, EffectDiscoveryStore, RunCallSealStore and ListTaskClaims. Discovery must authorize claim reads and include outstanding claims in cancelled plans. Scan and per-operation authority are required. Callbacks must honor cancellation.

type Event

type Event struct {
	SchemaVersion     int           `json:"schema_version"`
	Scope             cortex.Scope  `json:"scope"`
	PlanID            id.ID         `json:"plan_id"`
	Sequence          int64         `json:"sequence"`
	EventID           string        `json:"event_id"`
	Type              string        `json:"type"`
	SourceKind        string        `json:"source_kind"`
	SourceID          string        `json:"source_id"`
	SourceDigest      string        `json:"source_digest"`
	PlanRevision      int64         `json:"plan_revision,omitempty"`
	ClaimRevision     int64         `json:"claim_revision,omitempty"`
	PredecessorDigest string        `json:"predecessor_digest,omitempty"`
	TaskID            id.ID         `json:"task_id,omitempty"`
	RunID             id.AgentRunID `json:"run_id,omitempty"`
	Artifact          *evidence.Ref `json:"artifact,omitempty"`
	ObservedAt        time.Time     `json:"observed_at,omitempty"`
	Digest            string        `json:"digest"`
}

Event is private immutable transition metadata. Sequence orders index materialization only, not historical occurrence across source journals. Source revisions and predecessor digests retain their original causal order. EventID reuses an existing outbox ID or a stable source identity hash.

func SealEvent

func SealEvent(e Event) (Event, error)

SealEvent detaches bounded metadata. Sequence zero is a source projection awaiting atomic index insertion, never a deliverable event.

func (Event) Validate

func (e Event) Validate() error

Validate checks indexed metadata integrity without authorizing delivery.

type EventAuthority

type EventAuthority interface {
	AuthorizeCoordinationScan(context.Context, id.ID, string) error
	WithCoordinationDeliveryFence(context.Context, DeliveryRequest, func(DeliveryRequest) error) error
	AuthorizeCoordinationDelivery(context.Context, DeliveryRequest) error
}

EventAuthority fences current source-read and sink-delivery grants. Scan categories ending in history authorize exact-plan claim traversal and its retained child metadata. Delivery must additionally check the exact SourceKind, SourceID and SourceDigest. Historical events never imply current work authority.

type EventImport

type EventImport struct {
	Scope         cortex.Scope
	PlanID        id.ID
	Source, After string
	Limit         int
}

EventImport bounds one source-journal page. After is an opaque storage cursor. An empty Next in the response completes that source pass.

func (EventImport) Validate

func (r EventImport) Validate() error

Validate rejects unbounded or unsupported source scans.

type EventImportPage

type EventImportPage struct {
	Next     string
	Imported int
}

EventImportPage reports bounded materialization progress. Imports are idempotent across restarts; callers may safely restart a pass from zero.

type EventPage

type EventPage struct {
	Scope  cortex.Scope
	PlanID id.ID
	After  int64
	Limit  int
}

EventPage selects an exact plan and finite metadata sequence page.

func (EventPage) Validate

func (r EventPage) Validate() error

Validate checks scope, identity and page bounds before access.

type EventService

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

EventService imports immutable outboxes and delivers metadata with stable identities. It never dispatches work or exports artifact contents.

func NewEventService

func NewEventService(config EventServiceConfig) (*EventService, error)

NewEventService validates finite bounds without starting polling.

func (*EventService) RequestStop

func (s *EventService) RequestStop()

RequestStop signals cancellation without detaching owned sink calls.

func (*EventService) Start

func (s *EventService) Start(ctx context.Context) error

Start begins authorized discovery and idempotent metadata delivery.

func (*EventService) Status

func (s *EventService) Status() TaskServiceStatus

Status reports process counters without private resource metadata.

func (*EventService) Stop

func (s *EventService) Stop(ctx context.Context) error

Stop waits until all in-flight callbacks drain.

type EventServiceConfig

type EventServiceConfig struct {
	Store            EventStore
	Discovery        TaskPlanSource
	Authority        EventAuthority
	Sink             EventSink
	SinkID           string
	PageSize         int
	PageTimeout      time.Duration
	MaxTrackedPlans  int
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

EventServiceConfig connects retained source intents to one bounded private metadata sink. Callbacks must honor cancellation; shutdown owns them until they return. PageSize defaults32, PageTimeout30s, tracked plans1024.

type EventSink

type EventSink interface {
	DeliverCoordinationEvent(context.Context, DeliveryRequest) (Delivery, error)
}

EventSink durably deduplicates scope, PlanID, EventID and Digest within SinkID. It must authenticate its transport and returned receipt. Repeated calls with the same identity must return the same reference, including after lost acks. An uncertain outcome returns an error; never report a speculative acknowledgment.

type EventStore

type EventStore interface {
	ImportCoordinationEvents(context.Context, EventImport) (EventImportPage, error)
	ListCoordinationEvents(context.Context, EventPage) ([]Event, error)
	GetCoordinationDelivery(context.Context, Event, string) (*Delivery, error)
	AcknowledgeCoordinationEvent(context.Context, Delivery) error
}

EventStore indexes retained source intents and acknowledges exact sink receipts. It never calls a provider or publishes run content.

type Handoff

type Handoff struct {
	SchemaVersion  int                `json:"schema_version"`
	ID             id.ID              `json:"id"`
	AssignmentID   id.ID              `json:"assignment_id"`
	Fence          uint64             `json:"fence"`
	Scope          cortex.Scope       `json:"scope"`
	PlanID         id.ID              `json:"plan_id"`
	PlanRevision   int64              `json:"plan_revision"`
	PlanDigest     string             `json:"plan_digest"`
	TaskID         id.ID              `json:"task_id"`
	ParentRunID    id.AgentRunID      `json:"parent_run_id"`
	Sender         Identity           `json:"sender"`
	Receiver       Identity           `json:"receiver"`
	Purpose        HandoffPurpose     `json:"purpose"`
	GrantRef       string             `json:"grant_ref"`
	Authority      planning.Authority `json:"authority"`
	ContractDigest string             `json:"contract_digest"`
	Criteria       []string           `json:"criteria"`
	Inputs         []evidence.Ref     `json:"inputs,omitempty"`
	Deadline       time.Time          `json:"deadline"`
	Digest         string             `json:"digest"`
}

Handoff is an immutable proposed assignment. Fence is an asserted scheduler generation, not proof of ownership. The receiving host must verify it against its durable assignment before accepting work. No message means task success.

func DecodeHandoff

func DecodeHandoff(data []byte) (Handoff, error)

DecodeHandoff refuses unknown fields and trailing payloads before validating the sealed proposal. Decoding does not authenticate identities or grants.

func SealHandoff

func SealHandoff(h Handoff) (Handoff, error)

SealHandoff checks structure and detaches the canonical proposed assignment.

func (Handoff) Validate

func (h Handoff) Validate() error

Validate checks integrity only. Use ValidateHandoff against current host data before accepting work; peer-provided grants and plan digests cannot authorize it.

type HandoffAuthority

type HandoffAuthority struct {
	Sender, Receiver Identity
	AssignmentID     id.ID
	ParentRunID      id.AgentRunID
	Fence            uint64
	GrantRef         string
	Ceiling          planning.Authority
	// ProducerPrincipal is required for review and comes from host provenance.
	ProducerPrincipal string
}

HandoffAuthority comes from the receiving host's current identity and grant resolver. Assignment and fence must come from durable scheduler ownership.

type HandoffContext

type HandoffContext struct {
	Plan      planning.Plan
	Authority HandoffAuthority
}

HandoffContext is freshly resolved by the receiving host, never from the peer.

type HandoffPurpose

type HandoffPurpose string

HandoffPurpose selects production or a review without effect tools.

const (
	HandoffWork   HandoffPurpose = "work"
	HandoffReview HandoffPurpose = "review"
)

type HandoffReceiver

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

HandoffReceiver admits bounded host work without using an ordinary agent run.

func NewHandoffReceiver

func NewHandoffReceiver(config HandoffReceiverConfig) (*HandoffReceiver, error)

NewHandoffReceiver requires explicit current-authority and persistence ports.

func (*HandoffReceiver) Receive

func (r *HandoffReceiver) Receive(ctx context.Context, h Handoff) error

Receive validates the complete proposal before passing it to host acceptance.

type HandoffReceiverConfig

type HandoffReceiverConfig struct {
	Resolve       func(context.Context, Handoff) (HandoffContext, error)
	Accept        func(context.Context, Handoff) error
	Now           func() time.Time
	MaxConcurrent int
}

HandoffReceiverConfig separates host resolution from durable acceptance. Accept must atomically check current assignment ownership, grants and plan revision, and deduplicate by assignment/fence/digest. Success acknowledges only retained work. It must not dispatch an unreserved agent or mark a task passed. Both callbacks must honor cancellation and protect direct artifact access.

type Identity

type Identity struct {
	Agent     string `json:"agent"`
	Node      string `json:"node,omitempty"`
	Principal string `json:"principal"`
}

Identity is a claimed endpoint and principal. A host resolver must bind it to authenticated local or remote identity before accepting the assignment.

type OrchestrationExpirer

type OrchestrationExpirer interface {
	Expire(context.Context, id.OrchestrationID) error
}

OrchestrationExpirer closes expired admission and retains uncertain outcomes. Its implementation must check the stored deadline and cannot replay execution.

type OrchestrationExpiryConfig

type OrchestrationExpiryConfig struct {
	Discovery                                  OrchestrationSource
	Expirer                                    OrchestrationExpirer
	Interval, DiscoveryTimeout, AttemptTimeout time.Duration
	MaxInFlight, MaxPerScope                   int
	ReportError                                func(error)
}

OrchestrationExpiryConfig installs bounded discovery and per-team maintenance. ReportError must return promptly. All callbacks must honor cancellation.

type OrchestrationExpiryService

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

OrchestrationExpiryService reuses the scheduler's bounded discovery, exact-scope fairness and joined shutdown. It cannot start children or settle reservations.

func NewOrchestrationExpiryService

func NewOrchestrationExpiryService(config OrchestrationExpiryConfig) (*OrchestrationExpiryService, error)

NewOrchestrationExpiryService validates ports without starting work. Defaults are four concurrent teams, one per scope, one-second polling, five-second discovery and five-second expiry attempts. Interrupted work is rediscovered.

func (*OrchestrationExpiryService) RequestStop

func (s *OrchestrationExpiryService) RequestStop()

RequestStop signals all callbacks before drainage.

func (*OrchestrationExpiryService) Start

Start retains service identity values and owns an independent lifetime.

func (*OrchestrationExpiryService) Status

Status returns process counters without team content or scope values.

func (*OrchestrationExpiryService) Stop

Stop joins discovery and expiry callbacks before returning success.

type OrchestrationListRequest

type OrchestrationListRequest struct {
	After string
	Limit int
}

OrchestrationListRequest bounds host discovery using an opaque cursor.

type OrchestrationPage

type OrchestrationPage struct {
	Teams []ScheduledOrchestration
	Next  string
}

OrchestrationPage contains at most the requested limit. An empty Next ends a pass. Sources must include closed accounts whose parent cleanup may be pending.

type OrchestrationRecoverer

type OrchestrationRecoverer interface {
	Recover(context.Context, id.OrchestrationID) error
}

OrchestrationRecoverer revalidates current host authority and durable ownership before continuing a team. Discovery alone never grants execution permission.

type OrchestrationRecoveryConfig

type OrchestrationRecoveryConfig struct {
	Discovery                                  OrchestrationSource
	Recoverer                                  OrchestrationRecoverer
	Interval, DiscoveryTimeout, AttemptTimeout time.Duration
	MaxInFlight, MaxPerScope                   int
	ReportError                                func(error)
}

OrchestrationRecoveryConfig bounds discovery and synchronous recovery passes. A timed-out attempt cancels its execution; the runner must retain uncertainty. All callbacks must honor cancellation, and ReportError must return promptly.

type OrchestrationRecoveryService

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

OrchestrationRecoveryService owns bounded recovery passes and joined shutdown.

func NewOrchestrationRecoveryService

func NewOrchestrationRecoveryService(config OrchestrationRecoveryConfig) (*OrchestrationRecoveryService, error)

NewOrchestrationRecoveryService defaults to four concurrent teams, one per scope, one-second polling, five-second discovery and a one-minute attempt. Attempts are capped at thirty minutes. It starts no work until Start is called.

func (*OrchestrationRecoveryService) RequestStop

func (s *OrchestrationRecoveryService) RequestStop()

RequestStop cancels discovery and every owned attempt before drainage.

func (*OrchestrationRecoveryService) Start

Start retains startup identity while owning an independent service lifetime.

func (*OrchestrationRecoveryService) Status

Status returns local counters without team content or scope values.

func (*OrchestrationRecoveryService) Stop

Stop succeeds only after discovery and all recovery callbacks drain.

type OrchestrationSource

type OrchestrationSource interface {
	ListOrchestrations(context.Context, OrchestrationListRequest) (OrchestrationPage, error)
}

OrchestrationSource discovers team identities under the host service identity. The host authorizes discovery; maintenance restores each exact scope. A source must finish each pass and honor cancellation. It must never dispatch agents.

type PlanReplanAbandonment

type PlanReplanAbandonment = PreparedRunAbandonment

PlanReplanAbandonment preserves the replan proof name for prepared-run closure.

type PlanReplanAdmission

type PlanReplanAdmission struct {
	SchemaVersion int                   `json:"schema_version"`
	Request       PlanReplanRequest     `json:"request"`
	RequestDigest string                `json:"request_digest"`
	Reservation   execution.Reservation `json:"reservation"`
	At            time.Time             `json:"at"`
	Fresh         bool                  `json:"-"`
}

PlanReplanAdmission is the retained attempt and charged allocation. Fresh is returned only by the transaction that first admitted it, never by a read.

func (PlanReplanAdmission) Validate

func (a PlanReplanAdmission) Validate() error

Validate checks integrity without authenticating the caller or authorizing dispatch.

type PlanReplanAuthorizer

type PlanReplanAuthorizer interface {
	AuthorizePlanReplan(context.Context, PlanReplanControl) error
}

PlanReplanAuthorizer authenticates actor, trusted progress, current resources, pricing bounds and every quiescence attestation. Commit additionally requires permission to supersede the exact graph. Historical retries reauthorize access.

type PlanReplanControl

type PlanReplanControl struct {
	Request     PlanReplanRequest      `json:"request"`
	Operation   string                 `json:"operation"`
	Abandonment *PlanReplanAbandonment `json:"abandonment,omitempty"`
	Claims      []TaskRecoveryProof    `json:"claims,omitempty"`
}

PlanReplanControl binds current authority to one admitted operation. Dispatch spans admission and the entire runtime callback. Commit proofs must cover all current dispatched ownership, including tasks removed from the proposed graph.

func (PlanReplanControl) Freeze

Freeze bounds and detaches current authority inputs.

type PlanReplanFence

type PlanReplanFence interface {
	WithPlanReplanFence(context.Context, PlanReplanControl, func(PlanReplanControl) error) error
}

PlanReplanFence holds current plan grants and worker incarnation exclusion through the entire synchronous operation, including model dispatch. Every host actor that can revoke authority or deliver delayed work must share this fence.

type PlanReplanOutcome

type PlanReplanOutcome struct {
	SchemaVersion   int                         `json:"schema_version"`
	AttemptID       id.ID                       `json:"attempt_id"`
	AdmissionDigest string                      `json:"admission_digest"`
	RunRevision     int64                       `json:"run_revision"`
	RunDigest       string                      `json:"run_digest"`
	Proposed        *planning.Plan              `json:"proposed,omitempty"`
	Abandonment     *PlanReplanAbandonment      `json:"abandonment,omitempty"`
	Settlement      execution.SettlementReceipt `json:"settlement"`
	At              time.Time                   `json:"at"`
	Digest          string                      `json:"digest"`
}

PlanReplanOutcome retains terminal model observations, including malformed or failed proposals. Accounting remains charged even when Proposed is nil.

func SealPlanReplanOutcome

func SealPlanReplanOutcome(o PlanReplanOutcome) (PlanReplanOutcome, error)

SealPlanReplanOutcome detaches and fingerprints retained model disposition.

func (PlanReplanOutcome) Validate

func (o PlanReplanOutcome) Validate() error

Validate checks outcome integrity; hashes do not authenticate provider work.

type PlanReplanRequest

type PlanReplanRequest struct {
	SchemaVersion  int                          `json:"schema_version"`
	ID             id.ID                        `json:"id"`
	Progress       planning.ProgressSnapshot    `json:"progress"`
	Policy         planning.ReplanPolicy        `json:"policy"`
	Reservation    execution.ReservationRequest `json:"reservation"`
	RunID          id.AgentRunID                `json:"run_id"`
	SessionID      id.SessionID                 `json:"session_id"`
	AgentID        id.AgentID                   `json:"agent_id"`
	PreparedDigest string                       `json:"prepared_digest"`
	InputDigest    string                       `json:"input_digest"`
	Actor          string                       `json:"actor"`
	Reason         string                       `json:"reason"`
}

PlanReplanRequest binds trusted progress and a frozen, tool-free model run to one shared account allocation. Admission never grants execution authority.

func (PlanReplanRequest) Freeze

Freeze validates deterministic proposal eligibility and immutable bindings.

type PlanReplanResolver

type PlanReplanResolver interface {
	ResolvePlanReplan(context.Context, id.ID) (*PlanReplanRequest, error)
	ResolvePlanReplanControl(context.Context, PlanReplanAdmission, *PlanReplanOutcome) (*PlanReplanControl, error)
}

PlanReplanResolver supplies trusted progress for new attempts and authenticated recovery/commit proof for retained attempts. Nil means pending. It must honor cancellation and never invoke models, effects or task dispatch itself.

type PlanReplanRuntime

type PlanReplanRuntime interface {
	ExecutePlanReplan(context.Context, PlanReplanAdmission) error
}

PlanReplanRuntime executes a fresh admission through the existing prepared runtime with its reserved RunID, frozen input and explicit empty tool allowlist. It must never restart existing or ambiguous creation and must honor cancellation.

type PlanReplanService

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

PlanReplanService owns proposal recovery and dispatch until callbacks drain. It does not dispatch tasks or reuse artifacts after committing a revision.

func NewPlanReplanService

func NewPlanReplanService(config PlanReplanServiceConfig) (*PlanReplanService, error)

NewPlanReplanService validates ports without starting background work.

func (*PlanReplanService) RequestStop

func (s *PlanReplanService) RequestStop()

RequestStop cancels work without claiming callback drainage.

func (*PlanReplanService) Start

func (s *PlanReplanService) Start(ctx context.Context) error

Start creates the service's independently owned lifetime.

func (*PlanReplanService) Status

Status reports local counters without model or evidence content.

func (*PlanReplanService) Stop

func (s *PlanReplanService) Stop(ctx context.Context) error

Stop waits for discovery, authority, model and recovery callbacks to return.

type PlanReplanServiceConfig

type PlanReplanServiceConfig struct {
	Store            PlanReplanStore
	Discovery        TaskPlanSource
	AuthorizeScan    func(context.Context, id.ID) error
	Resolver         PlanReplanResolver
	Fence            PlanReplanFence
	Authorizer       PlanReplanAuthorizer
	Runtime          PlanReplanRuntime
	AttemptTimeout   time.Duration
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

PlanReplanServiceConfig connects shared discovery to bounded proposal work. AuthorizeScan runs before reading retained attempts and outcomes. Discovery must retain plans with pending attempts even after their deadlines expire.

type PlanReplanStore

type PlanReplanStore interface {
	GetPlan(context.Context, id.ID) (planning.Plan, error)
	AdmitPlanReplan(context.Context, PlanReplanRequest) (PlanReplanAdmission, error)
	GetPlanReplan(context.Context, id.ID) (*PlanReplanAdmission, error)
	ListPlanReplans(context.Context, id.ID) ([]PlanReplanAdmission, error)
	ObservePlanReplan(context.Context, PlanReplanControl) (*PlanReplanOutcome, error)
	GetPlanReplanOutcome(context.Context, id.ID) (*PlanReplanOutcome, error)
	GetPlanReplanCommit(context.Context, id.ID) (*planning.Plan, error)
	CommitPlanReplan(context.Context, PlanReplanControl) (planning.Plan, error)
}

PlanReplanStore persists bounded proposals independently of plan definitions. Implementations serialize admission and commit with all plan ownership writes. These trusted storage primitives must be called through current host guards.

type PlanReplanner

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

PlanReplanner coordinates guarded admission, observation and graph commit.

func NewPlanReplanner

func NewPlanReplanner(store PlanReplanStore, fence PlanReplanFence, authorizer PlanReplanAuthorizer, runtime PlanReplanRuntime, configs ...PlanReplannerConfig) (*PlanReplanner, error)

NewPlanReplanner requires explicit authority and the bounded prepared runtime.

func (*PlanReplanner) Commit

func (r *PlanReplanner) Commit(ctx context.Context, control PlanReplanControl) (planning.Plan, error)

Commit preserves historical evidence while atomically superseding a graph.

func (*PlanReplanner) Execute

Execute admits and dispatches once. Any error or historical acknowledgment is observation-only; callers must never infer permission from a retained receipt.

func (*PlanReplanner) Observe

Observe retains terminal output or an authenticated permanent abandonment. Nil means pending and never authorizes another invocation.

type PlanReplannerConfig

type PlanReplannerConfig struct {
	// ExecutionTimeout defaults to 30 seconds and cannot exceed 30 minutes.
	// The reservation and caller deadlines can only shorten this limit.
	ExecutionTimeout time.Duration
}

PlanReplannerConfig bounds a fresh model dispatch.

type PlanningAccess

type PlanningAccess struct {
	PlanID    id.ID  `json:"plan_id,omitempty"`
	Operation string `json:"operation"`
}

PlanningAccess identifies metadata access without carrying credentials.

type PlanningArtifactCandidate

type PlanningArtifactCandidate struct {
	ID       id.ID        `json:"id"`
	TaskID   id.ID        `json:"task_id"`
	Owner    Identity     `json:"owner"`
	Artifact evidence.Ref `json:"artifact"`
	At       time.Time    `json:"at"`
}

PlanningArtifactCandidate references historical accepted output. It neither certifies current verification nor grants access to the referenced content.

type PlanningArtifactReadResolver

type PlanningArtifactReadResolver interface {
	ResolvePlanningArtifactReads(context.Context, planning.Plan) ([]ArtifactBoardRead, error)
}

PlanningArtifactReadResolver selects exact declared writable resources whose metadata the caller may inspect. ArtifactBoard independently authorizes reads. Return complete histories (After zero, Limit MaxBoardTransitions), at most MaxPlanningArtifactResources resources. Omitted resources remain private.

type PlanningArtifactResolver

type PlanningArtifactResolver interface {
	ResolvePlanningArtifact(context.Context, PlanningCommand) (ArtifactBoardRequest, error)
}

PlanningArtifactResolver resolves current grants and verified artifact bindings.

type PlanningArtifactView

type PlanningArtifactView struct {
	Resource     planning.ResourceGrant      `json:"resource"`
	HeadRevision int64                       `json:"head_revision"`
	HeadDigest   string                      `json:"head_digest,omitempty"`
	Head         *PlanningArtifactCandidate  `json:"head,omitempty"`
	Conflicts    []PlanningArtifactCandidate `json:"conflicts"`
}

PlanningArtifactView reports a durable head and unresolved ownership conflicts. Head pins are required when explicitly resolving a selected conflict.

type PlanningCancellation

type PlanningCancellation interface {
	CancelPlanningAssignment(context.Context, PlanningCommand) (Assignment, error)
}

PlanningCancellation stops a selected assignment through a current authority fence. Cancellation never releases a reservation or proves effects quiescent.

func NewPlanningCancellation

NewPlanningCancellation constructs guarded assignment cancellation. It keeps task ownership and shared charges until normal proof-based recovery finishes.

type PlanningCancellationAuthority

type PlanningCancellationAuthority interface {
	WithPlanningCancellationFence(context.Context, PlanningCommand, func() error) error
	AuthorizePlanningCancellation(context.Context, PlanningCommand, Assignment) (string, error)
}

PlanningCancellationAuthority authenticates the actor and excludes delayed dispatch, task acceptance and grant changes throughout cancellation. The fence must be shared by those writers across host processes. Actor is host-resolved.

type PlanningCancellationStore

type PlanningCancellationStore interface {
	PlanningOperatorStore
	GetRun(context.Context, id.AgentRunID) (*run.Run, error)
}

PlanningCancellationStore retains the selected assignment and producer run.

type PlanningCapabilities

type PlanningCapabilities struct {
	Claim           bool `json:"claim"`
	Retry           bool `json:"retry"`
	Reassign        bool `json:"reassign"`
	Replan          bool `json:"replan"`
	Reconcile       bool `json:"reconcile"`
	ResolveConflict bool `json:"resolve_conflict"`
	Cancel          bool `json:"cancel"`
}

PlanningCapabilities reports installed services, not live qualification.

type PlanningClaimResolver

type PlanningClaimResolver interface {
	ResolvePlanningClaim(context.Context, PlanningCommand) (ReadyTaskClaimRequest, error)
}

PlanningClaimResolver authenticates worker selection and persists stable request identities. It must not infer new grants from an operator command.

type PlanningCommand

type PlanningCommand struct {
	Operation                  string `json:"operation"`
	OperationID                id.ID  `json:"operation_id"`
	PlanID                     id.ID  `json:"plan_id"`
	ExpectedRevision           int64  `json:"expected_revision"`
	ExpectedDigest             string `json:"expected_digest"`
	TaskID                     id.ID  `json:"task_id,omitempty"`
	ExpectedClaimRevision      int64  `json:"expected_claim_revision,omitempty"`
	ExpectedAssignmentRevision int64  `json:"expected_assignment_revision,omitempty"`
	Worker                     string `json:"worker,omitempty"`
	ExpectedResourceRevision   int64  `json:"expected_resource_revision,omitempty"`
	ExpectedResourceDigest     string `json:"expected_resource_digest,omitempty"`
	ConflictID                 id.ID  `json:"conflict_id,omitempty"`
	Reason                     string `json:"reason"`
}

PlanningCommand carries selection and optimistic pins, never authority inputs. OperationID is a retained request identity and must be reused after lost replies.

func (PlanningCommand) Validate

func (c PlanningCommand) Validate() error

Validate bounds transport input before any trusted resolver is called.

type PlanningCommandResult

type PlanningCommandResult struct {
	OperationID  id.ID  `json:"operation_id"`
	Operation    string `json:"operation"`
	Fresh        bool   `json:"fresh"`
	PlanRevision int64  `json:"plan_revision,omitempty"`
	PlanDigest   string `json:"plan_digest,omitempty"`
	ClaimID      id.ID  `json:"claim_id,omitempty"`
	AssignmentID id.ID  `json:"assignment_id,omitempty"`
	Pending      bool   `json:"pending"`
}

PlanningCommandResult is an acknowledgment, not evidence of task success.

type PlanningDetail

type PlanningDetail struct {
	Artifacts    []PlanningArtifactView   `json:"artifacts"`
	Replans      []PlanningReplanView     `json:"replans"`
	Plan         PlanningPlanView         `json:"plan"`
	Tasks        []PlanningTaskView       `json:"tasks"`
	Budget       execution.BudgetSnapshot `json:"budget"`
	Complete     bool                     `json:"complete"`
	ObservedAt   time.Time                `json:"observed_at"`
	Capabilities PlanningCapabilities     `json:"capabilities"`
}

PlanningDetail is a fenced point-in-time projection, not a dispatch credential.

type PlanningOperator

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

PlanningOperator exposes bounded metadata, never candidate or context bytes.

func NewPlanningOperator

func NewPlanningOperator(c PlanningOperatorConfig) (*PlanningOperator, error)

NewPlanningOperator rejects incomplete optional service groups.

func (*PlanningOperator) Capabilities

func (o *PlanningOperator) Capabilities() PlanningCapabilities

Capabilities is safe before authorization because it contains no scoped data.

func (*PlanningOperator) Command

Command routes only to installed guarded services. A failed acknowledgment must be reconciled with the same operation identity, never a fresh dispatch.

func (*PlanningOperator) Detail

func (o *PlanningOperator) Detail(ctx context.Context, planID id.ID) (PlanningDetail, error)

Detail revalidates retained acceptance against current bindings and reports.

func (*PlanningOperator) List

List returns at most 64 exact-scope graph headers after current authorization.

type PlanningOperatorAuthority

type PlanningOperatorAuthority interface {
	AuthorizePlanning(context.Context, PlanningAccess) error
	WithPlanningReadFence(context.Context, PlanningAccess, func() error) error
}

PlanningOperatorAuthority authenticates the current caller before and after reads. The read fence must hold external grants and source revisions until the synchronous callback returns. List permission covers the exact scoped roster.

type PlanningOperatorConfig

type PlanningOperatorConfig struct {
	Store     PlanningOperatorStore
	Source    SchedulingSource
	Authority PlanningOperatorAuthority
	Clock     verification.Clock
	// Retry and Reassign require explicit host support in the claim resolver.
	Retry, Reassign  bool
	Claims           PlanningClaimResolver
	Admitter         TaskClaimAdmitter
	Worker           ClaimedTaskWorker
	Replans          PlanningReplanResolver
	Replanner        *PlanReplanner
	Completion       *TaskCompletionServiceConfig
	Artifacts        *ArtifactBoard
	ArtifactResolver PlanningArtifactResolver
	ArtifactReads    PlanningArtifactReadResolver
	Cancellation     PlanningCancellation
}

PlanningOperatorConfig joins projections with existing guarded command ports. Source reconstructs current bindings. Reports supplied by Source never replace authoritative snapshots. Every optional command needs its resolver and runtime.

type PlanningOperatorStore

PlanningOperatorStore supplies retained facts; it is not an authorization port.

type PlanningPlanView

type PlanningPlanView struct {
	ID        id.ID     `json:"id"`
	Revision  int64     `json:"revision"`
	Digest    string    `json:"digest"`
	Objective string    `json:"objective"`
	Tasks     int       `json:"tasks"`
	Deadline  time.Time `json:"deadline"`
}

PlanningPlanView describes one immutable graph revision.

type PlanningReplanResolver

type PlanningReplanResolver interface {
	ResolvePlanningReplan(context.Context, PlanningCommand) (PlanReplanControl, error)
}

PlanningReplanResolver reconstructs trusted progress, runtime pins and proofs.

type PlanningReplanView

type PlanningReplanView struct {
	ID               id.ID              `json:"id"`
	RunID            id.AgentRunID      `json:"run_id"`
	BaseRevision     int64              `json:"base_revision"`
	BaseDigest       string             `json:"base_digest"`
	Status           string             `json:"status"`
	ProposedDigest   string             `json:"proposed_digest,omitempty"`
	ProposedTasks    []PlanningTaskView `json:"proposed_tasks,omitempty"`
	AcceptedRevision int64              `json:"accepted_revision,omitempty"`
}

PlanningReplanView exposes a retained proposal for explicit operator review. Proposal text is model output and never grants new resource authority.

type PlanningRunCanceller

type PlanningRunCanceller interface {
	CancelRun(context.Context, id.AgentRunID) error
}

PlanningRunCanceller supplies the existing managed run cancellation operation. Its return does not attest external effects have stopped or justify refunds.

type PlanningTaskView

type PlanningTaskView struct {
	ID                 id.ID            `json:"id"`
	Instruction        string           `json:"instruction"`
	Owner              string           `json:"owner"`
	DependsOn          []id.ID          `json:"depends_on,omitempty"`
	Status             planning.Status  `json:"status"`
	ClaimID            id.ID            `json:"claim_id,omitempty"`
	ClaimRevision      int64            `json:"claim_revision,omitempty"`
	ClaimState         ClaimState       `json:"claim_state,omitempty"`
	RunID              id.AgentRunID    `json:"run_id,omitempty"`
	AssignmentID       id.ID            `json:"assignment_id,omitempty"`
	AssignmentRevision int64            `json:"assignment_revision,omitempty"`
	AssignmentState    AssignmentState  `json:"assignment_state,omitempty"`
	AcceptanceID       id.ID            `json:"acceptance_id,omitempty"`
	AcceptedArtifact   *evidence.Ref    `json:"accepted_artifact,omitempty"`
	CurrentlyAccepted  bool             `json:"currently_accepted"`
	Ready              bool             `json:"ready"`
	ReviewRequired     bool             `json:"review_required"`
	Budget             execution.Budget `json:"budget"`
	NextAction         string           `json:"next_action"`
}

PlanningTaskView separates durable acceptance from current verified success.

type PreparedRunAbandonment

type PreparedRunAbandonment struct {
	AdmissionDigest string    `json:"admission_digest"`
	Issuer          string    `json:"issuer"`
	ProofRef        string    `json:"proof_ref"`
	ProofDigest     string    `json:"proof_digest"`
	ObservedAt      time.Time `json:"observed_at"`
	ExpiresAt       time.Time `json:"expires_at"`
}

PreparedRunAbandonment is authenticated permanent quiescence of an admission whose run may never have been created. Missing rows alone are never proof.

type ProviderRecoveryService

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

ProviderRecoveryService owns plan discovery, claim pages and provider recovery pages until Stop drains them. Restart begins discovery again and reuses durable provider receipts. Scope fairness and lifecycle behavior match TaskService.

func NewProviderRecoveryService

func NewProviderRecoveryService(config ProviderRecoveryServiceConfig) (*ProviderRecoveryService, error)

NewProviderRecoveryService validates ports without starting work. Defaults are four concurrent plan passes, one per scope, 64 entries per page, five seconds per claim/seal read and one second between pages. Provider pages use Recovery's own timeout. A pass retains its slot through all claim and call pages.

func (*ProviderRecoveryService) RequestStop

func (s *ProviderRecoveryService) RequestStop()

RequestStop signals cancellation without claiming drainage.

func (*ProviderRecoveryService) Start

Start preserves service identity values and owns an independent lifetime.

func (*ProviderRecoveryService) Status

Status reports local counters without scope, run or provider content.

func (*ProviderRecoveryService) Stop

Stop joins discovery, storage reads and provider callbacks before returning.

type ProviderRecoveryServiceConfig

type ProviderRecoveryServiceConfig struct {
	Recovery         execution.ProviderRecoveryConfig
	Discovery        TaskPlanSource
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

ProviderRecoveryServiceConfig connects authorized plan discovery to retained recovering claims. Recovery.Store must also provide ListTaskClaims and RunCallSealStore. Discovery authorizes plan/claim reads under the service identity and must include outstanding claims in cancelled or completed plans. Recovery.AuthorizeScan and every per-call authority port remain mandatory. Unsealed runs are left untouched for a later pass. The service cannot seal a journal, execute calls, adopt a result, or settle usage.

type ReadyTaskClaim

type ReadyTaskClaim struct {
	RequestDigest string          `json:"request_digest"`
	Acquisition   BudgetedClaim   `json:"acquisition"`
	Outbox        TaskClaimOutbox `json:"outbox"`
	Fresh         bool            `json:"-"`
}

ReadyTaskClaim records the original readiness admission. Fresh is true only when this call confirms the first commit. Acquisition is always historical; the host rechecks current claims, grants, budgets and evidence at dispatch.

func (ReadyTaskClaim) Validate

func (r ReadyTaskClaim) Validate(request ReadyTaskClaimRequest) error

Validate checks the original request, allocation and outbox association. The Fresh flag comes from trusted storage; this method cannot prove a first write.

type ReadyTaskClaimRequest

type ReadyTaskClaimRequest struct {
	SchemaVersion int                  `json:"schema_version"`
	Acquisition   BudgetedClaimRequest `json:"acquisition"`
	Dependencies  []AcceptedDependency `json:"dependencies,omitempty"`
}

ReadyTaskClaimRequest reserves an attempt after reloading every accepted prerequisite. The host must fence current grants and external revisions for Dependencies and authenticate the worker before calling storage.

func (ReadyTaskClaimRequest) Freeze

Freeze checks and detaches a bounded request. Caller reports cannot replace the verification material retained by the store.

type ReadyTaskClaimStore

type ReadyTaskClaimStore interface {
	ClaimReadyTask(context.Context, ReadyTaskClaimRequest) (ReadyTaskClaim, error)
	GetReadyTaskClaim(context.Context, id.ID) (ReadyTaskClaim, error)
}

ReadyTaskClaimStore checks prerequisites, acquires ownership, reserves shared capacity and retains an event intent atomically. It never invokes an agent.

type RenewingClaimedTaskWorker

type RenewingClaimedTaskWorker interface {
	ClaimedTaskWorker
	RunClaimedTaskWithRenewal(context.Context, ReadyTaskClaimRequest, ReadyTaskClaim, TaskRenewalStart) error
}

RenewingClaimedTaskWorker supports the child-creation activation boundary. The context's deadline is the overall execution ceiling. A watchdog cancels it at the last confirmed claim expiry. Individual calls retain their own authorization leases, which task renewal does not extend.

type Review

type Review struct {
	SchemaVersion       int             `json:"schema_version"`
	ID                  id.ID           `json:"id"`
	Handoff             Handoff         `json:"handoff"`
	SubjectAssignmentID id.ID           `json:"subject_assignment_id"`
	SubjectRevision     int64           `json:"subject_revision"`
	SubjectDigest       string          `json:"subject_digest"`
	BindingDigest       string          `json:"binding_digest"`
	RunID               id.AgentRunID   `json:"run_id"`
	RunRevision         int64           `json:"run_revision"`
	PreparedDigest      string          `json:"prepared_digest"`
	ReviewedAt          time.Time       `json:"reviewed_at"`
	Findings            []ReviewFinding `json:"findings"`
	Digest              string          `json:"digest"`
}

Review binds advisory findings to a submitted assignment and a separate run. The host authenticates identities, resolves current grants and prepares the reviewer independently. Sealing provides integrity, not that authentication.

func SealReview

func SealReview(r Review) (Review, error)

SealReview detaches findings and seals the complete observation.

func (Review) Output

func (r Review) Output() ([]byte, error)

Output returns the canonical reviewer document for these findings.

func (Review) Validate

func (r Review) Validate() error

Validate checks integrity without granting authority or task acceptance.

func (Review) ValidateOutput

func (r Review) ValidateOutput(data []byte) error

ValidateOutput accepts equivalent JSON formatting while refusing unknown fields, trailing documents and any changed subject, evidence or finding.

type ReviewAssessment

type ReviewAssessment string

ReviewAssessment is an advisory finding, never a verifier verdict.

const (
	ReviewSupported    ReviewAssessment = "supported"
	ReviewContradicted ReviewAssessment = "contradicted"
	ReviewMissing      ReviewAssessment = "missing_evidence"
)

type ReviewFinding

type ReviewFinding struct {
	CriterionID string           `json:"criterion_id"`
	Assessment  ReviewAssessment `json:"assessment"`
	Reason      string           `json:"reason"`
	EvidenceIDs []id.ID          `json:"evidence_ids,omitempty"`
}

ReviewFinding retains a criterion's rationale and exact input references. Supporting and contradictory findings require evidence. Missing evidence may name available references but cannot invent a reference for absent bytes.

type ReviewListRequest

type ReviewListRequest struct {
	AssignmentID id.ID
	After        id.ID
	Limit        int
}

ReviewListRequest bounds exact-scope discovery for one producer assignment.

type ReviewOutput

type ReviewOutput struct {
	SchemaVersion int             `json:"schema_version"`
	HandoffDigest string          `json:"handoff_digest"`
	SubjectDigest string          `json:"subject_digest"`
	BindingDigest string          `json:"binding_digest"`
	Findings      []ReviewFinding `json:"findings"`
}

ReviewOutput is the bounded structured document produced by the reviewer. Subject and handoff digests prevent reusing prose for another assignment.

type ReviewStore

type ReviewStore interface {
	RecordAssignmentReview(context.Context, Review) (Review, error)
	GetAssignmentReview(context.Context, id.ID) (Review, error)
	ListAssignmentReviews(context.Context, ReviewListRequest) ([]Review, error)
}

ReviewStore retains independent observations without changing assignment or verifier status. Hosts authorize every call; historical reads confer no access to artifact bytes. Identical retries acknowledge the retained observation.

type ScheduledAgentReply

type ScheduledAgentReply struct {
	Scope cortex.Scope  `json:"scope"`
	ID    id.AgentRunID `json:"id"`
}

ScheduledAgentReply identifies a run to inspect, without granting execution.

type ScheduledOrchestration

type ScheduledOrchestration struct {
	Scope cortex.Scope       `json:"scope"`
	ID    id.OrchestrationID `json:"id"`
}

ScheduledOrchestration identifies a candidate team. It grants no execution authority.

type ScheduledPlan

type ScheduledPlan struct {
	Scope  cortex.Scope `json:"scope"`
	PlanID id.ID        `json:"plan_id"`
}

ScheduledPlan is a host-discovered identity, never an execution grant.

type ScheduledTaskCompletion

type ScheduledTaskCompletion struct {
	Scope        cortex.Scope
	AssignmentID id.ID
}

ScheduledTaskCompletion identifies a producer assignment without granting access.

type ScheduledVerificationJob

type ScheduledVerificationJob struct {
	Scope cortex.Scope `json:"scope"`
	ID    id.ID        `json:"id"`
}

ScheduledVerificationJob identifies captured work without granting execution.

type Scheduler

type Scheduler interface {
	Tick(context.Context, id.ID) error
}

Scheduler advances at most one currently ready task per tick. A nil return means the tick finished; only TaskAcceptanceStore can establish task success.

type SchedulerConfig

type SchedulerConfig struct {
	Renewal       *TaskRenewalConfig
	Source        SchedulingSource
	Resolver      TaskClaimResolver
	Admitter      TaskClaimAdmitter
	Worker        ClaimedTaskWorker
	Clock         verification.Clock
	MaxConcurrent int
	MaxPerScope   int
	MaxQueued     int
	TickTimeout   time.Duration
}

SchedulerConfig requires explicit host services. Limits apply to this process; shared capacity and ownership remain enforced by durable guarded admission. TickTimeout bounds queueing, state resolution and execution together. A tick ends at its original claim expiry unless guarded Renewal is configured.

type SchedulerStatus

type SchedulerStatus struct {
	Active, Queued int
	Stopped        bool
}

SchedulerStatus exposes local capacity without scope or task content.

type SchedulingSource

type SchedulingSource interface {
	LoadSchedulingState(context.Context, id.ID) (planning.Plan, []planning.TaskState, error)
}

SchedulingSource loads a retained plan and current authorized task states. Reports must come from trusted storage. Reconstruct Current from live grants and source revisions. Missing states mean pending, as in planning.Ready. This read does not replace the atomic checks in TaskClaimAdmitter.

type ScopedAgentReplySource

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

ScopedAgentReplySource discovers only run identities in an explicit inventory of exact scopes. It checks current host discovery authority around each page.

func NewScopedAgentReplySource

func NewScopedAgentReplySource(store suspension.ReplyDiscoveryStore, scopes []cortex.Scope, authorize func(context.Context, cortex.Scope) error) (*ScopedAgentReplySource, error)

NewScopedAgentReplySource detaches at most 256 distinct scopes. Native stores return bounded identity projections, including admitted and expired pauses.

func (*ScopedAgentReplySource) ListAgentReplyRuns

ListAgentReplyRuns reads one bounded exact-scope page. Empty scopes advance normally. The service starts another pass after an empty Next cursor.

type ScopedOrchestrationSource

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

ScopedOrchestrationSource walks an explicit host-owned inventory of exact scopes. Authorization is repeated before and after every bounded storage page. It includes closed budgets so interrupted parent cleanup is retried.

func NewScopedOrchestrationSource

func NewScopedOrchestrationSource(store orchestration.BudgetDiscoveryStore, scopes []cortex.Scope, authorize func(context.Context, cortex.Scope) error) (*ScopedOrchestrationSource, error)

NewScopedOrchestrationSource detaches at most 256 distinct exact scopes. Authorize checks the current host service identity, not an agent's authority.

func (*ScopedOrchestrationSource) ListOrchestrations

ListOrchestrations reads one scope page and returns a cursor for the next page or scope. Empty scopes advance normally. A completed pass restarts on polling.

type ScopedVerificationSource

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

ScopedVerificationSource projects captured jobs from explicit authorized scopes.

func NewScopedVerificationSource

func NewScopedVerificationSource(store VerificationJobDiscoveryStore, scopes []cortex.Scope, authorize func(context.Context, cortex.Scope) error) (*ScopedVerificationSource, error)

NewScopedVerificationSource freezes at most 256 distinct exact scopes. Current discovery grants are checked before and after every bounded storage read.

func (*ScopedVerificationSource) ListCapturedVerificationJobs

func (s *ScopedVerificationSource) ListCapturedVerificationJobs(ctx context.Context, req VerificationJobListRequest) (VerificationJobPage, error)

ListCapturedVerificationJobs returns validated identities, never candidate bytes. Terminal and busy jobs advance the cursor so later work cannot be starved.

type Submission

type Submission struct {
	SchemaVersion    int           `json:"schema_version"`
	JobID            id.ID         `json:"job_id"`
	JobRequestDigest string        `json:"job_request_digest"`
	RunID            id.AgentRunID `json:"run_id"`
	RunRevision      int64         `json:"run_revision"`
	BindingDigest    string        `json:"binding_digest"`
}

Submission pins a retained verification job and its exact execution binding. It contains no peer verdict. Storage must load the job, fenced run and bytes; structurally valid references alone cannot admit a submission.

func (Submission) Validate

func (s Submission) Validate() error

Validate checks the pins without authenticating the producer or reading bytes.

type TaskAcceptance

type TaskAcceptance struct {
	SchemaVersion int                   `json:"schema_version"`
	Request       TaskAcceptanceRequest `json:"request"`
	RequestDigest string                `json:"request_digest"`
	Claim         Claim                 `json:"claim"`
	ObservedAt    time.Time             `json:"observed_at"`
	Outbox        TaskAcceptanceOutbox  `json:"outbox"`
	Digest        string                `json:"digest"`
	Fresh         bool                  `json:"-"`
}

TaskAcceptance is a historical verified task transition and its outbox intent. Fresh is true only for a confirmed first write. Revalidate current evidence and authority before using the result as a dependency or publishing any content.

func SealTaskAcceptance

func SealTaskAcceptance(a TaskAcceptance) (TaskAcceptance, error)

SealTaskAcceptance validates and detaches a storage-produced transition.

func (TaskAcceptance) Validate

func (a TaskAcceptance) Validate() error

Validate checks integrity without claiming continuing freshness or access.

type TaskAcceptanceAuthorizer

type TaskAcceptanceAuthorizer interface {
	AuthorizeTaskAcceptance(context.Context, TaskAcceptanceRequest) error
}

TaskAcceptanceAuthorizer authenticates Actor and authorizes the complete task, claim, assignment and dependency request against current host policy. A stored principal, claim token or artifact digest is not a credential.

type TaskAcceptanceFence

type TaskAcceptanceFence interface {
	WithTaskAcceptanceFence(context.Context, TaskAcceptanceRequest, func(TaskAcceptanceRequest) error) error
}

TaskAcceptanceFence holds the host's grant and external revision guards for the task and its complete prerequisite chain until acceptance returns. Resolve current bindings from authoritative sources and invoke the callback exactly once, synchronously. All relevant mutations, including other processes, must participate in those guards. An unlocked read does not implement this port. External services need conditional operations or an explicitly bounded observation window; this interface cannot create cross-service atomicity.

type TaskAcceptanceListRequest

type TaskAcceptanceListRequest struct {
	PlanID id.ID
	After  id.ID
	Limit  int
}

TaskAcceptanceListRequest bounds exact-scope recovery and outbox discovery.

func (TaskAcceptanceListRequest) Validate

func (r TaskAcceptanceListRequest) Validate() error

Validate checks bounded acceptance pagination without granting read access.

type TaskAcceptanceOutbox

type TaskAcceptanceOutbox struct {
	EventID      id.ID         `json:"event_id"`
	Type         string        `json:"type"`
	AcceptanceID id.ID         `json:"acceptance_id"`
	PlanID       id.ID         `json:"plan_id"`
	TaskID       id.ID         `json:"task_id"`
	RunID        id.AgentRunID `json:"run_id"`
}

TaskAcceptanceOutbox is a retained metadata-only event. Delivery requires host authorization; the event is not a public stream sequence or content grant.

type TaskAcceptanceRequest

type TaskAcceptanceRequest struct {
	SchemaVersion      int                            `json:"schema_version"`
	ID                 id.ID                          `json:"id"`
	Claim              ClaimToken                     `json:"claim"`
	AssignmentID       id.ID                          `json:"assignment_id"`
	AssignmentRevision int64                          `json:"assignment_revision"`
	AssignmentDigest   string                         `json:"assignment_digest"`
	Result             verification.ResultReadRequest `json:"result"`
	Current            verification.Binding           `json:"current"`
	Dependencies       []AcceptedDependency           `json:"dependencies,omitempty"`
	Actor              string                         `json:"actor"`
	Reason             string                         `json:"reason"`
	Recovery           *TaskRecoveryProof             `json:"recovery,omitempty"`
	Adjudication       *TaskAdjudicationRef           `json:"adjudication,omitempty"`
}

TaskAcceptanceRequest pins ownership, assignment and a committed result. Dependencies must cover the complete prerequisite chain. No peer verdict or caller-supplied report list can replace retained verifier evidence.

func (TaskAcceptanceRequest) Freeze

Freeze detaches bounded trusted host input. Digests are not credentials.

type TaskAcceptanceStore

type TaskAcceptanceStore interface {
	AcceptTaskResult(context.Context, TaskAcceptanceRequest) (TaskAcceptance, error)
	GetTaskAcceptance(context.Context, id.ID) (TaskAcceptance, error)
	ListTaskAcceptances(context.Context, TaskAcceptanceListRequest) ([]TaskAcceptance, error)
}

TaskAcceptanceStore persists verified success and completes its claim atomically. Callers authenticate Actor and fence external grants/revisions. The store never invokes an agent, settles unknown usage or grants publication permission.

type TaskAcceptor

type TaskAcceptor interface {
	Accept(context.Context, TaskAcceptanceRequest) (TaskAcceptance, error)
}

TaskAcceptor checks current host authority before atomic task storage. Even historical retries require authorization. An error may follow a durable commit; recover with the same request ID rather than creating another acceptance.

func NewTaskAcceptor

func NewTaskAcceptor(storage TaskAcceptanceStore, fence TaskAcceptanceFence, authorizer TaskAcceptanceAuthorizer) (TaskAcceptor, error)

NewTaskAcceptor requires explicit storage, fencing and authorization ports.

type TaskAdjudication

type TaskAdjudication struct {
	SchemaVersion int                     `json:"schema_version"`
	Request       TaskAdjudicationRequest `json:"request"`
	RequestDigest string                  `json:"request_digest"`
	Decision      AdjudicationDecision    `json:"decision"`
	ObservedAt    time.Time               `json:"observed_at"`
	Digest        string                  `json:"digest"`
}

TaskAdjudication retains a derived policy decision. Contradictions and missing evidence stay blocked. Independent review never overrides failed verification.

func PrepareTaskAdjudication

func PrepareTaskAdjudication(request TaskAdjudicationRequest, r Review, p planning.Plan, at time.Time) (TaskAdjudication, error)

PrepareTaskAdjudication derives a decision from retained review and plan pins. The store must independently validate both runs, submission and evidence bytes.

func SealTaskAdjudication

func SealTaskAdjudication(a TaskAdjudication) (TaskAdjudication, error)

SealTaskAdjudication validates the stored decision's integrity only.

func (TaskAdjudication) Validate

func (a TaskAdjudication) Validate() error

Validate checks integrity without treating the record as current evidence.

type TaskAdjudicationRef

type TaskAdjudicationRef struct {
	ID     id.ID  `json:"id"`
	Digest string `json:"digest"`
}

TaskAdjudicationRef pins a stored decision, never a caller-supplied verdict.

func (TaskAdjudicationRef) Validate

func (r TaskAdjudicationRef) Validate() error

Validate checks identity and content binding without granting authority.

type TaskAdjudicationRequest

type TaskAdjudicationRequest struct {
	SchemaVersion      int    `json:"schema_version"`
	ID                 id.ID  `json:"id"`
	PlanID             id.ID  `json:"plan_id"`
	PlanDigest         string `json:"plan_digest"`
	TaskID             id.ID  `json:"task_id"`
	AssignmentID       id.ID  `json:"assignment_id"`
	AssignmentRevision int64  `json:"assignment_revision"`
	AssignmentDigest   string `json:"assignment_digest"`
	BindingDigest      string `json:"binding_digest"`
	ReviewID           id.ID  `json:"review_id"`
	ReviewDigest       string `json:"review_digest"`
	PolicyRevision     string `json:"policy_revision"`
	Actor              string `json:"actor"`
	Reason             string `json:"reason"`
}

TaskAdjudicationRequest binds host policy to one immutable submitted result and retained independent review. Actor must be authenticated by the host. A human actor cannot provide an override verdict through this request.

func (TaskAdjudicationRequest) Freeze

Freeze detaches request metadata; the store resolves its evidence itself.

type TaskAdjudicationStore

type TaskAdjudicationStore interface {
	RecordTaskAdjudication(context.Context, TaskAdjudicationRequest) (TaskAdjudication, error)
	GetTaskAdjudication(context.Context, id.ID) (TaskAdjudication, error)
}

TaskAdjudicationStore retains decisions atomically with the plan fence. Hosts authorize every read and write, including retries, against current policy.

type TaskAdoptionService

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

TaskAdoptionService owns scoped discovery and guarded adoption through shutdown. It never seals journals, invokes tasks or settles reservations. Failed or pending recovery is revisited on later discovery passes; committed receipts remain durable.

func NewTaskAdoptionService

func NewTaskAdoptionService(config TaskAdoptionServiceConfig) (*TaskAdoptionService, error)

NewTaskAdoptionService validates configuration without starting work. Defaults match provider recovery: four plan passes, one per scope, 64 claims per page, five seconds per claim/seal read and one second between pages. Each full adoption attempt defaults to thirty seconds and cannot exceed that duration.

func (*TaskAdoptionService) RequestStop

func (s *TaskAdoptionService) RequestStop()

RequestStop signals cancellation without claiming drainage.

func (*TaskAdoptionService) Start

func (s *TaskAdoptionService) Start(ctx context.Context) error

Start preserves service identity values and owns an independent lifetime.

func (*TaskAdoptionService) Status

Status reports local counters without task, proof or result content.

func (*TaskAdoptionService) Stop

Stop joins discovery, snapshot reads, resolution and adoption callbacks.

type TaskAdoptionServiceConfig

type TaskAdoptionServiceConfig struct {
	Store            TaskAdoptionStore
	Discovery        TaskPlanSource
	AuthorizeScan    func(context.Context, Claim, execution.RunCallSeal) error
	Resolver         TaskRecoveryResolver
	Fence            TaskRecoveryFence
	Authorizer       TaskRecoveryAuthorizer
	AttemptTimeout   time.Duration
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

TaskAdoptionServiceConfig installs optional adoption of sealed recovering runs. Discovery authorizes plan/claim reads; AuthorizeScan authorizes each snapshot before storage or resolution. Fence and Authorizer implement the complete recovery proof contract. AttemptTimeout includes scan, resolution and adoption. Concrete callbacks must honor cancellation and retain original dispatch identity.

type TaskAdoptionStore

type TaskAdoptionStore interface {
	TaskRecoveryStore
	execution.RunRecoverySnapshotStore
	// contains filtered or unexported methods
}

TaskAdoptionStore supports scoped discovery, sealed snapshots and atomic adoption. All journal writers must honor the same admission guard.

type TaskBillingProof

type TaskBillingProof struct {
	Issuer          string    `json:"issuer"`
	Revision        string    `json:"revision"`
	ProofRef        string    `json:"proof_ref"`
	ProofDigest     string    `json:"proof_digest"`
	PricingRevision string    `json:"pricing_revision,omitempty"`
	ObservedAt      time.Time `json:"observed_at"`
	ExpiresAt       time.Time `json:"expires_at"`
}

TaskBillingProof identifies host-authenticated billing evidence. Its content must bind the scope, claim, seal, usage and closure digests, allocation, original provider accounts and routing, verifier attempts and pricing. Known charges must be final. Unknown charges, including delayed delivery, must be bounded by the retained settlement charge. Other work must add no unaccounted charges to refunded dimensions. Hashes and references alone establish none of these facts.

type TaskCallSealAuthorizer

type TaskCallSealAuthorizer interface {
	AuthorizeTaskCallSeal(context.Context, TaskCallSealRequest) error
}

TaskCallSealAuthorizer authenticates the actor and exact task/run permission, including retries. A completed claim alone does not grant closure authority.

type TaskCallSealFence

type TaskCallSealFence interface {
	WithTaskCallSealFence(context.Context, TaskCallSealRequest, func(TaskCallSealRequest) error) error
}

TaskCallSealFence holds current host authority through one synchronous write.

type TaskCallSealRequest

type TaskCallSealRequest struct {
	SchemaVersion int                          `json:"schema_version"`
	Claim         ClaimToken                   `json:"claim"`
	ClaimDigest   string                       `json:"claim_digest"`
	Seal          execution.RunCallSealRequest `json:"seal"`
}

TaskCallSealRequest closes call admission for the exact accepted ownership revision. Closure neither proves external quiescence nor settles accounting.

func (TaskCallSealRequest) Freeze

Freeze validates and detaches task and journal bindings.

type TaskCallSealStore

type TaskCallSealStore interface {
	SealTaskCalls(context.Context, TaskCallSealRequest) (execution.RunCallSeal, error)
}

TaskCallSealStore checks accepted ownership and the retained run while holding plan, run and journal guards through commit. Retries recheck accepted history; a replacement claim does not authorize calls on the old run.

type TaskCallSealer

type TaskCallSealer interface {
	Seal(context.Context, TaskCallSealRequest) (execution.RunCallSeal, error)
}

TaskCallSealer closes accepted task admission under explicit host authority.

func NewTaskCallSealer

func NewTaskCallSealer(store TaskCallSealStore, fence TaskCallSealFence, authorizer TaskCallSealAuthorizer) (TaskCallSealer, error)

NewTaskCallSealer requires storage, current authorization and synchronous fencing. A failed acknowledgment can follow commit. Retry the identical request while accepted history remains valid; never infer that an error means calls remain open.

type TaskClaimAdmitter

type TaskClaimAdmitter interface {
	Admit(context.Context, ReadyTaskClaimRequest) (ReadyTaskClaim, error)
}

TaskClaimAdmitter guards atomic admission with current host authority. Every retry repeats authorization. An error can follow a durable commit; retry the same request identity and never infer dispatch permission from an acknowledgment.

func NewTaskClaimAdmitter

func NewTaskClaimAdmitter(storage ReadyTaskClaimStore, fence TaskClaimFence, authorizer TaskClaimAuthorizer) (TaskClaimAdmitter, error)

NewTaskClaimAdmitter requires explicit storage, fencing and authorization ports.

type TaskClaimAuthorizer

type TaskClaimAuthorizer interface {
	AuthorizeTaskClaim(context.Context, ReadyTaskClaimRequest) error
}

TaskClaimAuthorizer authenticates the caller and requested worker, checks its current attenuated grant and allocation, and authorizes every prerequisite. Identity references, grant names and receipt digests are not credentials.

type TaskClaimFence

type TaskClaimFence interface {
	WithTaskClaimFence(context.Context, ReadyTaskClaimRequest, func(ReadyTaskClaimRequest) error) error
}

TaskClaimFence holds current grant and external revision guards through ready task admission. Resolve the complete prerequisite chain and invoke the callback once, synchronously. All relevant writers, including other processes, must participate. External services need conditional operations or an explicit bounded observation window; an unlocked read does not implement this port.

type TaskClaimOutbox

type TaskClaimOutbox struct {
	EventID id.ID  `json:"event_id"`
	Type    string `json:"type"`
	ClaimID id.ID  `json:"claim_id"`
	PlanID  id.ID  `json:"plan_id"`
	TaskID  id.ID  `json:"task_id"`
}

TaskClaimOutbox retains metadata for authorized event delivery. It contains no public stream sequence, artifact content or permission to dispatch.

type TaskClaimRenewer

type TaskClaimRenewer interface {
	Renew(context.Context, TaskRenewalRequest) (TaskRenewal, error)
}

TaskClaimRenewer guards durable execution renewal with current host authority. Errors can follow a committed renewal. Reconcile rather than inferring a new expiry; historical acknowledgements never authorize continued execution.

func NewTaskClaimRenewer

func NewTaskClaimRenewer(storage TaskRenewalStore, fence TaskRenewalFence, authorizer TaskRenewalAuthorizer) (TaskClaimRenewer, error)

NewTaskClaimRenewer requires explicit storage, fencing and authorization ports.

type TaskClaimResolver

type TaskClaimResolver interface {
	ResolveTaskClaim(context.Context, planning.Plan, id.ID) (ReadyTaskClaimRequest, error)
}

TaskClaimResolver resolves current worker identity and an attenuated allocation for one ready task. Persist stable request identities before returning if they must survive process failure. Returned references are never credentials.

type TaskCompletion

type TaskCompletion struct {
	SchemaVersion int                   `json:"schema_version"`
	Request       TaskCompletionRequest `json:"request"`
	RequestDigest string                `json:"request_digest"`
	Reservation   execution.Reservation `json:"reservation"`
	ObservedAt    time.Time             `json:"observed_at"`
	Digest        string                `json:"digest"`
	Fresh         bool                  `json:"-"`
}

TaskCompletion is a durable review dispatch intent and conservative allocation. Only a confirmed Fresh response permits the initial dispatch. Every subsequent observation is reconciliation-only, including a lost initial acknowledgment. Unknown usage remains charged until separately authenticated settlement.

func SealTaskCompletion

func SealTaskCompletion(c TaskCompletion) (TaskCompletion, error)

SealTaskCompletion detaches a storage-produced dispatch receipt.

func (TaskCompletion) Validate

func (c TaskCompletion) Validate() error

Validate checks immutable identity and allocation, not current authority.

type TaskCompletionAbandoner

type TaskCompletionAbandoner interface {
	Abandon(context.Context, TaskCompletionAbandonmentRequest) (TaskCompletionSettlement, error)
}

TaskCompletionAbandoner closes proven quiescent reviewers without redispatch.

type TaskCompletionAbandonmentAuthority

type TaskCompletionAbandonmentAuthority interface {
	WithTaskCompletionAbandonmentFence(context.Context, TaskCompletionAbandonmentRequest, func(TaskCompletionAbandonmentRequest) error) error
	AuthorizeTaskCompletionAbandonment(context.Context, TaskCompletionAbandonmentRequest) error
}

TaskCompletionAbandonmentAuthority authenticates the proof issuer and permanent dispatch/provider exclusion. Its fence must be shared by every delayed worker and held synchronously through commit. Historical retries reauthorize access.

type TaskCompletionAbandonmentRequest

type TaskCompletionAbandonmentRequest struct {
	Completion TaskCompletion         `json:"completion"`
	Proof      PreparedRunAbandonment `json:"proof"`
	Actor      string                 `json:"actor"`
	Reason     string                 `json:"reason"`
}

TaskCompletionAbandonmentRequest permanently closes one admitted reviewer. The host must prove that no delayed dispatch or provider return can arrive. Absence, lease expiry and cancellation alone do not establish this condition.

func (TaskCompletionAbandonmentRequest) Freeze

Freeze detaches the exact admission and host attestation for authorization.

type TaskCompletionAbandonmentResolver

type TaskCompletionAbandonmentResolver interface {
	ResolveTaskCompletionAbandonment(context.Context, TaskCompletion) (*TaskCompletionAbandonmentRequest, error)
}

TaskCompletionAbandonmentResolver supplies authenticated proof material only when a host has permanently excluded all execution for the reserved reviewer.

type TaskCompletionAbandonmentStore

type TaskCompletionAbandonmentStore interface {
	AbandonTaskCompletion(context.Context, TaskCompletionAbandonmentRequest) (TaskCompletionSettlement, error)
}

TaskCompletionAbandonmentStore atomically marks permanent abandonment and settles unknown usage conservatively. Call through an authenticated host guard.

type TaskCompletionAcceptance

type TaskCompletionAcceptance interface {
	Accept(context.Context, TaskAcceptanceRequest) (TaskAcceptance, error)
}

TaskCompletionAcceptance routes ordinary completion to a guarded TaskAcceptor and expired ownership to a guarded TaskAdopter with authenticated recovery proof. It must not synthesize proof or renew an expired producer merely to accept it.

type TaskCompletionAuthority

type TaskCompletionAuthority interface {
	WithTaskCompletionFence(context.Context, Assignment, func(Assignment) error) error
	AuthorizeTaskCompletion(context.Context, Assignment) error
}

TaskCompletionAuthority authenticates the coordinator and guards producer and required reviewer policy, grants and external revisions for one bounded pass. Authorize covers submission, reservation, advisory review recording and derived adjudication. The fence must invoke its callback once synchronously and keep these guards through return. Reviewer execution and task acceptance also enforce their own current authority. Store metadata alone is never sufficient.

type TaskCompletionCloser

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

TaskCompletionCloser applies current host authority to permanent closure.

func NewTaskCompletionCloser

NewTaskCompletionCloser requires an explicit proof authorizer and shared fence.

func (*TaskCompletionCloser) Abandon

Abandon permanently closes the exact reviewer while retaining unknown costs.

type TaskCompletionListRequest

type TaskCompletionListRequest struct {
	After string
	Limit int
}

TaskCompletionListRequest bounds host discovery using an opaque cursor.

type TaskCompletionPage

type TaskCompletionPage struct {
	Assignments []ScheduledTaskCompletion
	Next        string
}

TaskCompletionPage ends a discovery pass when Next is empty.

type TaskCompletionRequest

type TaskCompletionRequest struct {
	SchemaVersion      int                          `json:"schema_version"`
	AssignmentID       id.ID                        `json:"assignment_id"`
	AssignmentRevision int64                        `json:"assignment_revision"`
	AssignmentDigest   string                       `json:"assignment_digest"`
	BindingDigest      string                       `json:"binding_digest"`
	Handoff            Handoff                      `json:"handoff"`
	SessionID          id.SessionID                 `json:"session_id"`
	RunID              id.AgentRunID                `json:"run_id"`
	ReviewID           id.ID                        `json:"review_id"`
	AdjudicationID     id.ID                        `json:"adjudication_id"`
	AcceptanceID       id.ID                        `json:"acceptance_id"`
	PreparedDigest     string                       `json:"prepared_digest"`
	InputDigest        string                       `json:"input_digest"`
	Reservation        execution.ReservationRequest `json:"reservation"`
	Actor              string                       `json:"actor"`
	Reason             string                       `json:"reason"`
}

TaskCompletionRequest reserves one independent review for a submitted result. PreparedDigest and InputDigest bind the private runtime material supplied by the host. No private input bytes or provider credentials enter the journal.

func (TaskCompletionRequest) Freeze

Freeze bounds and detaches the full immutable review dispatch request.

type TaskCompletionResolver

type TaskCompletionResolver interface {
	ResolveTaskSubmission(context.Context, Assignment) (*Submission, error)
	ResolveTaskCompletion(context.Context, Assignment) (*TaskCompletionRequest, error)
	ResolveTaskAcceptance(context.Context, TaskCompletion, TaskAdjudication) (*TaskAcceptanceRequest, error)
}

TaskCompletionResolver resolves already committed producer evidence, independent prepared review work, and current acceptance bindings. Nil means pending. Never execute agents or mutate storage here. Requests must retain stable identities across process restarts. Acceptance may carry authenticated recovery proof.

type TaskCompletionReviewer

type TaskCompletionReviewer interface {
	Execute(context.Context, TaskCompletion) error
	Observe(context.Context, TaskCompletion) (*Review, error)
}

TaskCompletionReviewer executes only a fresh reserved independent reviewer. Execute must authenticate current grants, fence execution, create the reserved RunID once and reject existing or uncertain creation. It must enforce prepared and input digests, no effect tools and the reserved budget. Observe resolves only retained output for that run with current read authority; nil means pending. Neither method may redispatch an uncertain run. Both honor cancellation.

type TaskCompletionService

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

TaskCompletionService owns bounded completion attempts and joined shutdown. A retained intent is reconciliation-only after any uncertain dispatch.

func NewTaskCompletionService

func NewTaskCompletionService(config TaskCompletionServiceConfig) (*TaskCompletionService, error)

NewTaskCompletionService validates required host ports without starting work. Attempts default to one minute and cannot exceed thirty minutes. Discovery and fairness use the shared lifecycle with four concurrent attempts, one per scope.

func (*TaskCompletionService) RequestStop

func (s *TaskCompletionService) RequestStop()

RequestStop cancels discovery and every outstanding completion attempt.

func (*TaskCompletionService) Start

Start owns discovery and preserves the host's service identity.

func (*TaskCompletionService) Status

Status reports process counters without assignment content.

func (*TaskCompletionService) Stop

Stop waits for every owned callback before storage can be disposed.

type TaskCompletionServiceConfig

type TaskCompletionServiceConfig struct {
	Store                                      TaskCompletionServiceStore
	Discovery                                  TaskCompletionSource
	Resolver                                   TaskCompletionResolver
	Authority                                  TaskCompletionAuthority
	Reviewer                                   TaskCompletionReviewer
	Acceptor                                   TaskCompletionAcceptance
	Abandoner                                  TaskCompletionAbandoner
	Interval, DiscoveryTimeout, AttemptTimeout time.Duration
	MaxInFlight, MaxPerScope                   int
	ReportError                                func(error)
}

TaskCompletionServiceConfig bounds an independently scheduled completion loop. Discovery authorizes assignment metadata reads. Pending review returns immediately, leaving worker execution slots free. An optional Abandoner requires a resolver implementing TaskCompletionAbandonmentResolver and an explicit proof-authorized closer. Callbacks must honor cancellation.

type TaskCompletionServiceStore

TaskCompletionServiceStore supplies durable producer and reviewer records.

type TaskCompletionSettlement

type TaskCompletionSettlement struct {
	Abandonment      *TaskCompletionAbandonmentRequest `json:"abandonment,omitempty"`
	SchemaVersion    int                               `json:"schema_version"`
	AssignmentID     id.ID                             `json:"assignment_id"`
	CompletionDigest string                            `json:"completion_digest"`
	RunID            id.AgentRunID                     `json:"run_id"`
	RunRevision      int64                             `json:"run_revision"`
	RunDigest        string                            `json:"run_digest"`
	Settlement       execution.SettlementReceipt       `json:"settlement"`
	ObservedAt       time.Time                         `json:"observed_at"`
	Digest           string                            `json:"digest"`
}

TaskCompletionSettlement retains terminal reviewer accounting or an authenticated permanent abandonment. Unknown provider usage stays charged. This receipt cannot accept a task, prove an absent run never executed, or authorize another reviewer attempt.

func SealTaskCompletionSettlement

func SealTaskCompletionSettlement(s TaskCompletionSettlement) (TaskCompletionSettlement, error)

SealTaskCompletionSettlement validates the terminal accounting receipt.

func (TaskCompletionSettlement) Validate

func (s TaskCompletionSettlement) Validate() error

Validate checks integrity, not current authority or review success.

type TaskCompletionSettlementStore

type TaskCompletionSettlementStore interface {
	SettleTaskCompletion(context.Context, id.ID, string) (*TaskCompletionSettlement, error)
	GetTaskCompletionSettlement(context.Context, id.ID) (*TaskCompletionSettlement, error)
}

TaskCompletionSettlementStore closes exact terminal reviewer runs under the plan/run/account transaction. An existing abandonment is returned unchanged. Nil means the reserved run is absent or pending; no inference of nonexecution is made. Hosts authorize and fence every call.

type TaskCompletionSource

type TaskCompletionSource interface {
	ListTaskCompletionAssignments(context.Context, TaskCompletionListRequest) (TaskCompletionPage, error)
}

TaskCompletionSource authorizes discovery of producer assignments, including working assignments whose committed result has not been submitted yet. Honor cancellation, finish each pass and never invoke providers here.

type TaskCompletionStore

type TaskCompletionStore interface {
	ReserveTaskCompletion(context.Context, TaskCompletionRequest) (TaskCompletion, error)
	GetTaskCompletion(context.Context, id.ID) (*TaskCompletion, error)
}

TaskCompletionStore atomically reserves review identity and shared capacity. It does not execute or retry reviewers. Get returns nil when no intent exists. Hosts must authorize both methods; stored metadata does not grant access.

type TaskDispatch

type TaskDispatch struct {
	RequestDigest string             `json:"request_digest"`
	Claim         Claim              `json:"claim"`
	Assignment    Assignment         `json:"assignment"`
	Outbox        TaskDispatchOutbox `json:"outbox"`
	Fresh         bool               `json:"-"`
}

TaskDispatch records the original atomic transition. Historical receipts never authorize execution. Even Fresh requires current host authority and a runtime that creates the reserved child exactly once without adopting an existing run.

func (TaskDispatch) Validate

func (r TaskDispatch) Validate(request TaskDispatchRequest) error

Validate checks the original request and receipt associations, not current authorization. Fresh is supplied by trusted storage and is not serialized.

type TaskDispatchAdmitter

type TaskDispatchAdmitter interface {
	Admit(context.Context, TaskDispatchRequest) (TaskDispatch, error)
}

TaskDispatchAdmitter guards durable dispatch intent with current authority. It does not invoke a worker. Every retry repeats authorization; an error may follow a durable commit, so preserve the original request when recovering.

func NewTaskDispatchAdmitter

func NewTaskDispatchAdmitter(storage TaskDispatchStore, fence TaskDispatchFence, authorizer TaskDispatchAuthorizer) (TaskDispatchAdmitter, error)

NewTaskDispatchAdmitter requires explicit storage, fencing and authorization.

type TaskDispatchAuthorizer

type TaskDispatchAuthorizer interface {
	AuthorizeTaskDispatch(context.Context, TaskDispatchRequest) error
}

TaskDispatchAuthorizer authenticates Actor and Worker, resolves the retained admission, assignment and parent, and checks their current attenuated grant, allocation and complete prerequisite chain. Stored identities and digests are references, never credentials or proof of current permission.

type TaskDispatchFence

type TaskDispatchFence interface {
	WithTaskDispatchFence(context.Context, TaskDispatchRequest, func(TaskDispatchRequest) error) error
}

TaskDispatchFence resolves current host authority and prerequisite bindings, then holds their grant and external revision guards through the callback. Invoke it once, synchronously. Every relevant writer, including other processes, must participate. External services require conditional operations or a declared bounded observation window; an unlocked read is insufficient.

type TaskDispatchOutbox

type TaskDispatchOutbox struct {
	EventID      id.ID         `json:"event_id"`
	Type         string        `json:"type"`
	ClaimID      id.ID         `json:"claim_id"`
	PlanID       id.ID         `json:"plan_id"`
	TaskID       id.ID         `json:"task_id"`
	AssignmentID id.ID         `json:"assignment_id"`
	RunID        id.AgentRunID `json:"run_id"`
}

TaskDispatchOutbox retains metadata for authorized delivery. The reserved run ID identifies an intent; it does not establish that execution started.

type TaskDispatchRequest

type TaskDispatchRequest struct {
	SchemaVersion      int                  `json:"schema_version"`
	Scope              cortex.Scope         `json:"scope"`
	Claim              ClaimToken           `json:"claim"`
	ClaimDigest        string               `json:"claim_digest"`
	AdmissionDigest    string               `json:"admission_digest"`
	AssignmentID       id.ID                `json:"assignment_id"`
	AssignmentRevision int64                `json:"assignment_revision"`
	AssignmentDigest   string               `json:"assignment_digest"`
	ParentRunRevision  int64                `json:"parent_run_revision"`
	RunID              id.AgentRunID        `json:"run_id"`
	Dependencies       []AcceptedDependency `json:"dependencies,omitempty"`
	Actor              string               `json:"actor"`
	Reason             string               `json:"reason"`
}

TaskDispatchRequest pins a ready admission, current ownership, an accepted assignment and its active parent. Dependencies contain the complete current prerequisite chain. Hosts must fence grants and external revisions through this operation and authenticate Actor and Worker; these fields are not credentials.

func (TaskDispatchRequest) Freeze

Freeze detaches the bounded dispatch request before storage or host callbacks.

type TaskDispatchStore

type TaskDispatchStore interface {
	DispatchReadyTask(context.Context, TaskDispatchRequest) (TaskDispatch, error)
	GetTaskDispatch(context.Context, id.ID) (TaskDispatch, error)
}

TaskDispatchStore rechecks readiness and ownership, fences the active parent, and retains dispatch intent and assignment progress atomically. It invokes no agent, creates no run and delivers no public event.

type TaskPlanListRequest

type TaskPlanListRequest struct {
	After string
	Limit int
}

TaskPlanListRequest bounds discovery. After is an opaque host cursor. A source must eventually finish a pass so new work before an earlier cursor is revisited.

type TaskPlanPage

type TaskPlanPage struct {
	Plans []ScheduledPlan `json:"plans"`
	Next  string          `json:"next,omitempty"`
}

TaskPlanPage returns at most the requested limit. Empty Next ends the pass. A new pass starts on a later poll, including after a process restart.

type TaskPlanSource

type TaskPlanSource interface {
	ListScheduledPlans(context.Context, TaskPlanListRequest) (TaskPlanPage, error)
}

TaskPlanSource discovers plans under the host service identity. The source authorizes discovery across scopes; ordinary store calls still require scope. Execution ticks repeat current admission checks; recovery ticks expire claims or reconcile retained provider proof. Recovery discovery must include plans with outstanding claims, including cancelled or completed plans. Honor context cancellation and avoid provider/tool execution in this port.

type TaskRecoveryAdopter

type TaskRecoveryAdopter interface {
	Adopt(context.Context, TaskAcceptanceRequest) (TaskAcceptance, error)
}

TaskRecoveryAdopter adopts verified output after an expired dispatch. Errors may follow a commit: retry the identical request ID to recover its receipt.

func NewTaskRecoveryAdopter

func NewTaskRecoveryAdopter(storage TaskRecoveryStore, fence TaskRecoveryFence, authorizer TaskRecoveryAuthorizer) (TaskRecoveryAdopter, error)

NewTaskRecoveryAdopter requires explicit recovery authentication and fencing. Ordinary TaskAcceptor ports cannot authorize this separate transition.

type TaskRecoveryAuthorizer

type TaskRecoveryAuthorizer interface {
	AuthorizeTaskRecovery(context.Context, TaskAcceptanceRequest) error
}

TaskRecoveryAuthorizer authenticates Actor and the Recovery issuer, revision and proof content. The attestation must bind the exact claim/seal/snapshot and authenticate all original provider and effect receipts, prove permanent worker and tool quiescence, and cover delayed delivery. It also authorizes the current result and complete prerequisite chain. Hashes and fixture refs are not proof. Historical retries still require current access and authentic original proof.

type TaskRecoveryFence

type TaskRecoveryFence interface {
	WithTaskRecoveryFence(context.Context, TaskAcceptanceRequest, func(TaskAcceptanceRequest) error) error
}

TaskRecoveryFence holds current host grants, source revisions and permanent worker/tool quiescence through one synchronous adoption callback. Its guards must cover every relevant writer, including remote processes. Authenticate original dispatch identities; current agent configuration cannot replace them. Never hold a database transaction across external proof retrieval.

type TaskRecoveryProof

type TaskRecoveryProof struct {
	SchemaVersion  int                   `json:"schema_version"`
	ClaimDigest    string                `json:"claim_digest"`
	Seal           execution.RunCallSeal `json:"seal"`
	SnapshotDigest string                `json:"snapshot_digest"`
	Issuer         string                `json:"issuer"`
	Revision       string                `json:"revision"`
	ProofRef       string                `json:"proof_ref"`
	ProofDigest    string                `json:"proof_digest"`
	ObservedAt     time.Time             `json:"observed_at"`
	ExpiresAt      time.Time             `json:"expires_at"`
}

TaskRecoveryProof identifies host-authenticated, permanent quiescence of the original worker incarnation and all its tools. Its signed/attested content must bind the full claim, seal and snapshot, authenticate the original provider and effect receipts, and prove delayed delivery cannot produce further effects. Shape and hashes alone prove none of this. ExpiresAt bounds the adoption window; permanent quiescence cannot be withdrawn after adoption. It grants no retry.

func (TaskRecoveryProof) Freeze

Freeze validates and detaches proof metadata without authenticating its issuer.

type TaskRecoveryResolver

type TaskRecoveryResolver interface {
	ResolveTaskRecovery(context.Context, Claim, execution.RunRecoverySnapshot) (*TaskAcceptanceRequest, error)
}

TaskRecoveryResolver obtains current task/result/prerequisite bindings and retained quiescence proof for the original claim and snapshot. Return nil when proof or verified output is not ready. It must honor cancellation, never invoke the task, and reuse the exact request ID and contents after uncertain commits. Resolution grants no authority: the recovery fence and authorizer run afterward.

type TaskRecoveryStore

type TaskRecoveryStore interface {
	AdoptTaskResult(context.Context, TaskAcceptanceRequest) (TaskAcceptance, error)
}

TaskRecoveryStore atomically adopts a verified result from a recovering claim. Only trusted host code may call it after authenticating Recovery and fencing current grants/revisions. It preserves reservations and never invokes work.

type TaskRenewal

type TaskRenewal struct {
	RequestDigest string            `json:"request_digest"`
	Claim         Claim             `json:"claim"`
	Outbox        TaskRenewalOutbox `json:"outbox"`
	Fresh         bool              `json:"-"`
}

TaskRenewal retains the original renewal. Fresh is true only for a confirmed first write. Historical receipts may describe expired ownership; a renewal loop must check Fresh, current authority and expiry before extending local work.

func (TaskRenewal) Validate

func (r TaskRenewal) Validate(request TaskRenewalRequest) error

Validate checks immutable successor and outbox bindings, not live authority.

type TaskRenewalAuthorizer

type TaskRenewalAuthorizer interface {
	AuthorizeTaskRenewal(context.Context, TaskRenewalRequest) error
}

TaskRenewalAuthorizer authenticates the worker and checks its current attenuated grant, parent, child, assignment, budget and prerequisite access. Waiting work may retain ownership, but renewal never grants resume permission.

type TaskRenewalConfig

type TaskRenewalConfig struct {
	Source   TaskRenewalSource
	Renewer  TaskClaimRenewer
	Duration time.Duration
	Interval time.Duration
}

TaskRenewalConfig enables renewal after confirmed child creation. Interval must be at least a millisecond and at most half Duration. Configure guarded renewal against the same store used for admission and dispatch.

type TaskRenewalFence

type TaskRenewalFence interface {
	WithTaskRenewalFence(context.Context, TaskRenewalRequest, func(TaskRenewalRequest) error) error
}

TaskRenewalFence holds current grants and external prerequisite revisions through the callback. Every relevant writer must participate. Invoke next exactly once and synchronously; an unlocked read does not implement this port.

type TaskRenewalOutbox

type TaskRenewalOutbox struct {
	EventID id.ID         `json:"event_id"`
	Type    string        `json:"type"`
	ClaimID id.ID         `json:"claim_id"`
	PlanID  id.ID         `json:"plan_id"`
	TaskID  id.ID         `json:"task_id"`
	RunID   id.AgentRunID `json:"run_id"`
}

TaskRenewalOutbox retains metadata for authorized delivery. It grants no execution permission and does not allocate a public event sequence.

type TaskRenewalRequest

type TaskRenewalRequest struct {
	Actor              string               `json:"actor"`
	Reason             string               `json:"reason"`
	SchemaVersion      int                  `json:"schema_version"`
	Claim              Claim                `json:"claim"`
	ParentRunID        id.AgentRunID        `json:"parent_run_id"`
	ParentRunRevision  int64                `json:"parent_run_revision"`
	RunRevision        int64                `json:"run_revision"`
	AssignmentID       id.ID                `json:"assignment_id"`
	AssignmentRevision int64                `json:"assignment_revision"`
	AssignmentDigest   string               `json:"assignment_digest"`
	Dependencies       []AcceptedDependency `json:"dependencies,omitempty"`
	Duration           time.Duration        `json:"duration"`
}

TaskRenewalRequest extends dispatched ownership while fencing the current parent, child, assignment and prerequisites. Claims and run revisions are observations, not credentials. The host must authenticate the worker and hold current grant and external revision guards through the storage transaction.

func (TaskRenewalRequest) Freeze

Freeze validates and detaches a bounded renewal request.

type TaskRenewalSource

type TaskRenewalSource interface {
	ResolveTaskRenewal(context.Context, Claim, time.Duration) (TaskRenewalRequest, error)
}

TaskRenewalSource reads current parent, child, assignment and prerequisite revisions for the exact claim. It invokes no external work. Duration is the scheduler ceiling; the source may attenuate it to a tighter child deadline. Both this port and the renewer must honor cancellation.

type TaskRenewalStart

type TaskRenewalStart func(Claim) error

TaskRenewalStart activates renewal for the immediate dispatched successor of an admitted claim. Call exactly once, synchronously after confirmed fresh child creation and before external execution. It never authorizes a call.

type TaskRenewalStore

type TaskRenewalStore interface {
	RenewTaskExecution(context.Context, TaskRenewalRequest) (TaskRenewal, error)
}

TaskRenewalStore atomically renews dispatched ownership and retains its metadata outbox after current execution checks. It invokes no external work.

type TaskRetirement

type TaskRetirement struct {
	SchemaVersion int                   `json:"schema_version"`
	Request       TaskRetirementRequest `json:"request"`
	RequestDigest string                `json:"request_digest"`
	Claim         Claim                 `json:"claim"`
	Digest        string                `json:"digest"`
	Fresh         bool                  `json:"-"`
}

TaskRetirement retains the request and immutable retired ownership. Fresh is true only for a confirmed initial commit. Historical receipts grant no work.

func SealTaskRetirement

func SealTaskRetirement(r TaskRetirement) (TaskRetirement, error)

SealTaskRetirement validates the receipt and detaches host-owned slices.

func (TaskRetirement) Validate

func (r TaskRetirement) Validate() error

Validate checks integrity without authenticating proof or granting authority.

type TaskRetirementAuthorizer

type TaskRetirementAuthorizer interface {
	AuthorizeTaskRetirement(context.Context, TaskRetirementRequest) error
}

TaskRetirementAuthorizer authenticates Actor and the Recovery attestation for the exact claim, seal and snapshot. Authenticate all provider/effect receipts and prove that delayed delivery cannot change outcomes or create more effects. Authorize the bound unsuccessful closure and settlement. Historical retries still require current access and authentic original proof.

type TaskRetirementFence

type TaskRetirementFence interface {
	WithTaskRetirementFence(context.Context, TaskRetirementRequest, func(TaskRetirementRequest) error) error
}

TaskRetirementFence holds current grants and permanent worker/tool quiescence through one synchronous callback. Every relevant writer must participate. Resolve external proof before entering the storage transaction.

type TaskRetirementRequest

type TaskRetirementRequest struct {
	SchemaVersion    int               `json:"schema_version"`
	Claim            ClaimToken        `json:"claim"`
	Recovery         TaskRecoveryProof `json:"recovery"`
	ClosureDigest    string            `json:"closure_digest"`
	SettlementDigest string            `json:"settlement_digest"`
	Actor            string            `json:"actor"`
	Reason           string            `json:"reason"`
}

TaskRetirementRequest releases unsuccessful ownership after its calls and accounting are closed. Recovery must authenticate permanent worker/tool quiescence and all external outcomes, including delayed deliveries.

func (TaskRetirementRequest) Freeze

Freeze detaches the full request. Proof references do not authenticate it.

type TaskRetirementResolver

type TaskRetirementResolver interface {
	ResolveTaskRetirement(context.Context, Claim, execution.RunRecoverySnapshot, TaskUsageClosure, TaskUsageSettlement) (*TaskRetirementRequest, error)
}

TaskRetirementResolver obtains authenticated quiescence proof for the exact original claim, journal and accounting. Return nil while proof is pending. Honor cancellation and reuse request contents after an uncertain commit. Resolution must not invoke or retry work; the guarded retirer checks authority.

type TaskRetirementService

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

TaskRetirementService owns discovery and retirement until shutdown drains. It never seals journals, settles budgets, dispatches replacements or accepts results.

func NewTaskRetirementService

func NewTaskRetirementService(config TaskRetirementServiceConfig) (*TaskRetirementService, error)

NewTaskRetirementService validates explicit ports without starting work. Attempts default to thirty seconds, with the shared recovery traversal bounds. Discovery must retain plans with unsuccessful ownership, including expired plans.

func (*TaskRetirementService) RequestStop

func (s *TaskRetirementService) RequestStop()

RequestStop signals cancellation without claiming drainage.

func (*TaskRetirementService) Start

Start preserves service identity values and owns an independent lifetime.

func (*TaskRetirementService) Status

Status reports local counters without proof or task content.

func (*TaskRetirementService) Stop

Stop joins discovery, proof resolution and guarded retirement callbacks.

type TaskRetirementServiceConfig

type TaskRetirementServiceConfig struct {
	Store            TaskRetirementServiceStore
	Discovery        TaskPlanSource
	AuthorizeScan    func(context.Context, Claim, execution.RunCallSeal) error
	Resolver         TaskRetirementResolver
	Fence            TaskRetirementFence
	Authorizer       TaskRetirementAuthorizer
	AttemptTimeout   time.Duration
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	PageTimeout      time.Duration
	PageSize         int
	MaxInFlight      int
	MaxPerScope      int
	ReportError      func(error)
}

TaskRetirementServiceConfig connects authorized discovery to guarded retirement. Discovery covers plan/claim/seal reads. AuthorizeScan covers journal, closure, settlement and retirement reads before proof resolution. Callbacks must honor cancellation; the service retains ownership until every callback returns.

type TaskRetirementServiceStore

type TaskRetirementServiceStore interface {
	TaskRetirementStore
	TaskUsageClosureStore
	TaskUsageSettlementStore
	execution.RunRecoverySnapshotStore
	// contains filtered or unexported methods
}

TaskRetirementServiceStore discovers recovering ownership and retains its closed accounting, sealed journal and retirement receipt.

type TaskRetirementStore

type TaskRetirementStore interface {
	RetireTaskClaim(context.Context, TaskRetirementRequest) (TaskRetirement, error)
	GetTaskRetirement(context.Context, id.ID) (*TaskRetirement, error)
}

TaskRetirementStore retires one exact recovering claim atomically. Get returns nil when no receipt exists. Callers must authenticate proof and hold host fences.

type TaskRetirer

type TaskRetirer interface {
	Retire(context.Context, TaskRetirementRequest) (TaskRetirement, error)
}

TaskRetirer releases reconciled ownership under current host authority. Retry the identical request after an uncertain commit acknowledgment.

func NewTaskRetirer

func NewTaskRetirer(store TaskRetirementStore, fence TaskRetirementFence, authorizer TaskRetirementAuthorizer) (TaskRetirer, error)

NewTaskRetirer requires explicit storage, proof authentication and fencing.

type TaskRunAdmitter

type TaskRunAdmitter interface {
	Admit(context.Context, TaskRunRequest) (TaskRunStart, error)
}

TaskRunAdmitter guards atomic child creation with current host authority. It does not execute the child. Every retry repeats authorization, including historical acknowledgments. Preserve the request after an ambiguous failure.

func NewTaskRunAdmitter

func NewTaskRunAdmitter(storage TaskRunStore, fence TaskRunFence, authorizer TaskRunAuthorizer) (TaskRunAdmitter, error)

NewTaskRunAdmitter requires explicit storage, fencing and authorization.

type TaskRunAuthorizer

type TaskRunAuthorizer interface {
	AuthorizeTaskRun(context.Context, TaskRunRequest) error
}

TaskRunAuthorizer authenticates Actor and Worker and resolves their retained dispatch, assignment and parent. It checks the current attenuated grant, allocation, complete prerequisite chain, prepared configuration and capture policy. Stored identities and digests are references, never credentials.

type TaskRunFence

type TaskRunFence interface {
	WithTaskRunFence(context.Context, TaskRunRequest, func(TaskRunRequest) error) error
}

TaskRunFence resolves current host authority and prerequisite bindings, then holds their grant and external revision guards through the callback. Invoke it once, synchronously. Every relevant writer, including other processes, must participate. External services need conditional operations or a declared bounded observation window; an unlocked read is insufficient.

type TaskRunOutbox

type TaskRunOutbox struct {
	EventID  id.ID         `json:"event_id"`
	Type     string        `json:"type"`
	ClaimID  id.ID         `json:"claim_id"`
	PlanID   id.ID         `json:"plan_id"`
	TaskID   id.ID         `json:"task_id"`
	RunID    id.AgentRunID `json:"run_id"`
	IntentID id.ID         `json:"intent_id"`
}

TaskRunOutbox records child creation metadata for authorized event delivery. It carries no input, output or proof that an external call has started.

type TaskRunRequest

type TaskRunRequest struct {
	SchemaVersion      int                        `json:"schema_version"`
	Claim              ClaimToken                 `json:"claim"`
	DispatchDigest     string                     `json:"dispatch_digest"`
	AssignmentRevision int64                      `json:"assignment_revision"`
	AssignmentDigest   string                     `json:"assignment_digest"`
	ParentRunRevision  int64                      `json:"parent_run_revision"`
	Dependencies       []AcceptedDependency       `json:"dependencies,omitempty"`
	Run                run.Run                    `json:"run"`
	Intent             verification.CaptureIntent `json:"intent"`
	Actor              string                     `json:"actor"`
	Reason             string                     `json:"reason"`
}

TaskRunRequest binds a pristine prepared child to current dispatched ownership. Run has no timestamps or persisted revision; storage supplies those at commit. The host must authorize the prepared configuration and fence current grants and external prerequisite revisions. Creating this row does not invoke a provider.

func (TaskRunRequest) Freeze

func (r TaskRunRequest) Freeze() (TaskRunRequest, string, error)

Freeze validates and detaches a bounded request, including its private input.

func (TaskRunRequest) InitialRun

func (r TaskRunRequest) InitialRun(at time.Time) (run.Run, error)

InitialRun builds the pristine persisted snapshot at trusted storage time. Creation timestamps use milliseconds so all built-in stores round-trip them. Storage must still check live ownership, policy and prerequisites atomically.

type TaskRunStart

type TaskRunStart struct {
	RequestDigest string        `json:"request_digest"`
	RunID         id.AgentRunID `json:"run_id"`
	RunDigest     string        `json:"run_digest"`
	CreatedAt     time.Time     `json:"created_at"`
	IntentID      id.ID         `json:"intent_id"`
	IntentDigest  string        `json:"intent_digest"`
	Outbox        TaskRunOutbox `json:"outbox"`
	Fresh         bool          `json:"-"`
}

TaskRunStart retains creation metadata without copying private run input. Fresh only identifies confirmed first creation. Historical receipts never permit reexecution; reconcile the current run after an ambiguous acknowledgment.

func (TaskRunStart) Validate

func (r TaskRunStart) Validate(request TaskRunRequest) error

Validate checks the original request and initial run digest without granting authority.

type TaskRunStore

type TaskRunStore interface {
	CreateTaskRun(context.Context, TaskRunRequest) (TaskRunStart, error)
	GetTaskRunStart(context.Context, id.ID) (TaskRunStart, error)
}

TaskRunStore atomically creates the reserved child, its capture intent and an immutable start receipt. An existing run is never adopted, even if identical. Hosts must authorize each request and guard external revisions through commit.

type TaskScheduler

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

TaskScheduler uses FIFO order within an exact scope and round-robin admission across queued scopes. It starts no polling loop; renewed ticks supervise their own ownership. Call Tick from the host lifecycle and Shutdown before disposing its stores or worker services.

func NewScheduler

func NewScheduler(config SchedulerConfig) (*TaskScheduler, error)

NewScheduler validates finite local bounds and all required host ports. Zero limits use 4 concurrent tasks, 1 per scope, 64 queued ticks and one minute.

func (*TaskScheduler) Shutdown

func (s *TaskScheduler) Shutdown(ctx context.Context) error

Shutdown rejects new ticks, cancels queued and owned work, then waits until callbacks return or ctx expires. A timeout leaves the scheduler stopped; call again to wait for drainage. No budget is refunded and no durable claim is released on an uncertain worker outcome. Processes recover those records.

func (*TaskScheduler) Status

func (s *TaskScheduler) Status() SchedulerStatus

Status returns current local queue and worker counts.

func (*TaskScheduler) Tick

func (s *TaskScheduler) Tick(ctx context.Context, planID id.ID) error

Tick waits for local capacity, reloads readiness and resolves fresh authority, then attempts the first ready task in plan definition order. Every failure returns to the host; this method never retries an ambiguous admission or call.

type TaskService

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

TaskService polls one bounded page per interval and owns all resulting ticks. It never retries an uncertain invocation, accepts outputs or refunds capacity. Stop it before disposing stores. You may restart after complete drainage.

func NewTaskService

func NewTaskService(config TaskServiceConfig) (*TaskService, error)

NewTaskService validates ports and finite bounds without starting work. Defaults are one-second polling, a five-second discovery timeout and 64 in-flight ticks.

func (*TaskService) RequestStop

func (s *TaskService) RequestStop()

RequestStop signals cancellation without claiming drainage. Use Stop to wait before disposing stores or notifying shutdown subscribers.

func (*TaskService) Start

func (s *TaskService) Start(ctx context.Context) error

Start preserves startup context values for the host service identity while giving the service its own lifetime. It is idempotent while running. An earlier timed-out Stop must finish before a new scheduler can start.

func (*TaskService) Status

func (s *TaskService) Status() TaskServiceStatus

Status reports the current lifecycle incarnation's counters.

func (*TaskService) Stop

func (s *TaskService) Stop(ctx context.Context) error

Stop cancels discovery and all owned ticks, then waits for complete drainage. A timeout leaves the service stopping, with stores and reservations retained. Call Stop again to wait; the caller deadline is not permission to detach work.

type TaskServiceConfig

type TaskServiceConfig struct {
	Scheduler        SchedulerConfig
	Discovery        TaskPlanSource
	Interval         time.Duration
	DiscoveryTimeout time.Duration
	MaxInFlight      int
	ReportError      func(error)
}

TaskServiceConfig connects bounded discovery to the guarded scheduler. Limits cover this process only. ReportError is optional and must return promptly; the engine reports error types without logging their potentially private text.

type TaskServiceStatus

type TaskServiceStatus struct {
	Running, Stopping bool
	Active            int
	Failures          uint64
}

TaskServiceStatus contains process counters, without plan or scope content. Active includes queued and executing ticks. Stopping remains true after a timed-out Stop until every callback returns.

type TaskSettlementRunReader

type TaskSettlementRunReader interface {
	GetRun(context.Context, id.AgentRunID) (*run.Run, error)
}

TaskSettlementRunReader reads current run state under the supplied exact scope. Discovery authorization must cover this read. It grants no execution authority.

type TaskSettlementService

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

TaskSettlementService owns discovery, admission closure and settlement until Stop drains every callback. Journal sealing needs its separate optional ports. The service never invokes task work.

func NewTaskSettlementService

func NewTaskSettlementService(config TaskSettlementServiceConfig) (*TaskSettlementService, error)

NewTaskSettlementService validates explicit ports without starting work. Defaults are four plan passes, one per scope, 64 entries per page, five seconds per page/seal read and one second between rounds. Each full attempt defaults to thirty seconds and cannot exceed it. Unbudgeted claims and pending proof wait without refunds. Discovery must include completed or cancelled plans with debt.

func (*TaskSettlementService) RequestStop

func (s *TaskSettlementService) RequestStop()

RequestStop signals cancellation without claiming drainage.

func (*TaskSettlementService) Start

Start preserves service identity values and owns an independent lifetime.

func (*TaskSettlementService) Status

Status reports local counters without task content or billing references.

func (*TaskSettlementService) Stop

Stop joins discovery, storage, proof resolution and accounting callbacks.

type TaskSettlementServiceConfig

type TaskSettlementServiceConfig struct {
	Store TaskSettlementStore
	// UnsuccessfulRuns enables discovery of sealed recovering claims and closure
	// of their failed, cancelled or incomplete child runs. It also settles explicitly
	// rejected completed runs whose closure already exists; it never infers rejection.
	// Nil preserves accepted-only discovery.
	UnsuccessfulRuns  TaskSettlementRunReader
	Discovery         TaskPlanSource
	AuthorizeScan     func(context.Context, Claim, execution.RunCallSeal) error
	ClosureActor      string
	ClosureFence      TaskUsageClosureFence
	ClosureAuthorizer TaskUsageClosureAuthorizer
	// Configure both ports to seal ordinary accepted task journals automatically.
	// ClosureActor also identifies the caller for this separate authorization.
	CallSealFence      TaskCallSealFence
	CallSealAuthorizer TaskCallSealAuthorizer
	Resolver           TaskUsageSettlementResolver
	Fence              TaskUsageSettlementFence
	Authorizer         TaskUsageSettlementAuthorizer
	AttemptTimeout     time.Duration
	Interval           time.Duration
	DiscoveryTimeout   time.Duration
	PageTimeout        time.Duration
	PageSize           int
	MaxInFlight        int
	MaxPerScope        int
	ReportError        func(error)
}

TaskSettlementServiceConfig connects accepted and optional unsuccessful work to guarded settlement. Discovery authorizes plan/claim reads; AuthorizeScan covers budget, usage, current run and receipt reads before proof resolution. ClosureActor names the host identity authorized to close verifier admission. Concrete ports must honor cancellation.

type TaskSettlementStore

type TaskSettlementStore interface {
	AcceptedClaimStore
	TaskUsageSettlementStore
	TaskUsageClosureStore
	TaskUsageSnapshotStore
	execution.RunRecoverySnapshotStore

	GetBudgetedTaskClaim(context.Context, id.ID) (BudgetedClaim, error)
	// contains filtered or unexported methods
}

TaskSettlementStore supports scoped discovery and atomic guarded accounting. Journal, verifier and budget writers must share the documented storage guards.

type TaskUsageCloser

type TaskUsageCloser interface {
	Close(context.Context, TaskUsageClosureRequest) (TaskUsageClosure, error)
}

TaskUsageCloser closes admission after current host checks. Errors may follow a commit; retry the identical request to recover its historical receipt.

func NewTaskUsageCloser

func NewTaskUsageCloser(store TaskUsageClosureStore, fence TaskUsageClosureFence, authorizer TaskUsageClosureAuthorizer) (TaskUsageCloser, error)

NewTaskUsageCloser requires explicit authority and fencing ports.

type TaskUsageClosure

type TaskUsageClosure struct {
	SchemaVersion int                     `json:"schema_version"`
	Request       TaskUsageClosureRequest `json:"request"`
	RequestDigest string                  `json:"request_digest"`
	At            time.Time               `json:"at"`
	Digest        string                  `json:"digest"`
	Fresh         bool                    `json:"-"`
}

TaskUsageClosure retains permanent local admission closure. Fresh is true only for the first confirmed write. A retry is a historical acknowledgment.

func SealTaskUsageClosure

func SealTaskUsageClosure(c TaskUsageClosure) (TaskUsageClosure, error)

SealTaskUsageClosure validates and detaches a closure receipt.

func (TaskUsageClosure) Validate

func (c TaskUsageClosure) Validate() error

Validate checks receipt integrity, not authority or external quiescence.

type TaskUsageClosureAuthorizer

type TaskUsageClosureAuthorizer interface {
	AuthorizeTaskUsageClosure(context.Context, TaskUsageClosureRequest) error
}

TaskUsageClosureAuthorizer authenticates Actor and authorizes permanent local closure for the exact run, claim and evidence, including historical retries. When Rejection is present it must also authorize permanent task-result rejection.

type TaskUsageClosureFence

type TaskUsageClosureFence interface {
	WithTaskUsageClosureFence(context.Context, TaskUsageClosureRequest, func(TaskUsageClosureRequest) error) error
}

TaskUsageClosureFence holds current host authority through one synchronous storage callback. External proof retrieval must happen before that callback.

type TaskUsageClosureRequest

type TaskUsageClosureRequest struct {
	SchemaVersion int                   `json:"schema_version"`
	Usage         TaskUsageRequest      `json:"usage"`
	UsageDigest   string                `json:"usage_digest"`
	Actor         string                `json:"actor"`
	Reason        string                `json:"reason"`
	Termination   *TaskUsageTermination `json:"termination,omitempty"`
	Rejection     *TaskUsageRejection   `json:"rejection,omitempty"`
}

TaskUsageClosureRequest permanently closes new verification admission against an exact usage observation. It does not authorize refunds or assert final bills.

func (TaskUsageClosureRequest) Freeze

Freeze validates and detaches closure input without authenticating its actor.

func (TaskUsageClosureRequest) MatchesClaim

func (r TaskUsageClosureRequest) MatchesClaim(c Claim) bool

MatchesClaim checks ownership identity and closure mode. It does not establish current storage state, host authorization or the stated terminal run revision.

type TaskUsageClosureStore

type TaskUsageClosureStore interface {
	CloseTaskUsage(context.Context, TaskUsageClosureRequest) (TaskUsageClosure, error)
	GetTaskUsageClosure(context.Context, id.AgentRunID) (*TaskUsageClosure, error)
}

TaskUsageClosureStore closes admission atomically with full evidence checks. Its trusted caller must hold current host authority through the transaction. Get returns nil when no closure exists. Reads and retries grant no authority.

type TaskUsageRejection

type TaskUsageRejection struct {
	RunRevision        int64               `json:"run_revision"`
	CompletedAt        time.Time           `json:"completed_at"`
	ResultRef          string              `json:"result_ref"`
	VerificationStatus verification.Status `json:"verification_status"`
}

TaskUsageRejection permanently declines task acceptance of a completed run. The closure's Actor and Reason identify the authorized decision. Rejection preserves the run and its artifacts; it does not release ownership or permit retries, compensation or deletion. Verification may have passed independently.

type TaskUsageRequest

type TaskUsageRequest struct {
	Claim          ClaimToken            `json:"claim"`
	Seal           execution.RunCallSeal `json:"seal"`
	SnapshotDigest string                `json:"snapshot_digest"`
}

TaskUsageRequest pins ownership and the journal observation to account for. The store reads all verifier jobs for that run, including earlier attempts.

func (TaskUsageRequest) Freeze

func (r TaskUsageRequest) Freeze() (TaskUsageRequest, error)

Freeze detaches the request without authenticating evidence or granting access.

type TaskUsageSettlement

type TaskUsageSettlement struct {
	SchemaVersion int                         `json:"schema_version"`
	Request       TaskUsageSettlementRequest  `json:"request"`
	RequestDigest string                      `json:"request_digest"`
	Settlement    execution.SettlementReceipt `json:"settlement"`
	Digest        string                      `json:"digest"`
	Fresh         bool                        `json:"-"`
}

TaskUsageSettlement records both the guarded request and accounting receipt. Fresh is true only for a confirmed first write and is never persisted.

func SealTaskUsageSettlement

func SealTaskUsageSettlement(s TaskUsageSettlement) (TaskUsageSettlement, error)

SealTaskUsageSettlement validates and detaches a receipt without granting funds.

func (TaskUsageSettlement) Validate

func (s TaskUsageSettlement) Validate() error

Validate checks integrity and operation binding, not billing authenticity.

type TaskUsageSettlementAuthorizer

type TaskUsageSettlementAuthorizer interface {
	AuthorizeTaskUsageSettlement(context.Context, TaskUsageSettlementRequest) error
}

TaskUsageSettlementAuthorizer authenticates Actor and Billing for the full request, including historical retries. It must refuse unknown charges without an enforced upper bound and any unaccounted fees in refunded dimensions.

type TaskUsageSettlementFence

type TaskUsageSettlementFence interface {
	WithTaskUsageSettlementFence(context.Context, TaskUsageSettlementRequest, func(TaskUsageSettlementRequest) error) error
}

TaskUsageSettlementFence holds current host authority through one synchronous transaction callback. Resolve external billing proof before entering it.

type TaskUsageSettlementRequest

type TaskUsageSettlementRequest struct {
	SchemaVersion     int              `json:"schema_version"`
	Usage             TaskUsageRequest `json:"usage"`
	UsageDigest       string           `json:"usage_digest"`
	ClosureDigest     string           `json:"closure_digest"`
	ReservationID     id.ID            `json:"reservation_id"`
	ReservationDigest string           `json:"reservation_digest"`
	Billing           TaskBillingProof `json:"billing"`
	Actor             string           `json:"actor"`
	Reason            string           `json:"reason"`
}

TaskUsageSettlementRequest binds final accounting to accepted, terminated or rejected work, closed admission, one complete usage observation and the original allocation.

func (TaskUsageSettlementRequest) Freeze

Freeze detaches settlement input without authenticating its proof or actor.

type TaskUsageSettlementResolver

type TaskUsageSettlementResolver interface {
	ResolveTaskUsageSettlement(context.Context, TaskUsageSnapshot, TaskUsageClosure, execution.Reservation) (*TaskUsageSettlementRequest, error)
}

TaskUsageSettlementResolver resolves retained billing proof for the exact observation and original allocation. Return nil while proof is pending. It must honor cancellation and must never execute or retry the task. Resolution grants no authority; the settlement fence and authorizer run afterward.

type TaskUsageSettlementStore

type TaskUsageSettlementStore interface {
	SettleTaskUsage(context.Context, TaskUsageSettlementRequest) (TaskUsageSettlement, error)
	GetTaskUsageSettlement(context.Context, id.AgentRunID) (*TaskUsageSettlement, error)
}

TaskUsageSettlementStore atomically compares current evidence and settles the original budgeted claim. Trusted callers must authenticate billing and hold current authority through the write. Get returns nil when no receipt exists.

type TaskUsageSettler

type TaskUsageSettler interface {
	Settle(context.Context, TaskUsageSettlementRequest) (TaskUsageSettlement, error)
}

TaskUsageSettler commits accounting under explicit host authority. Retry the identical request after uncertain acknowledgments; reads grant no authority.

func NewTaskUsageSettler

NewTaskUsageSettler requires explicit billing authority and fencing ports.

type TaskUsageSnapshot

type TaskUsageSnapshot struct {
	SchemaVersion int                           `json:"schema_version"`
	Claim         Claim                         `json:"claim"`
	Journal       execution.RunRecoverySnapshot `json:"journal"`
	Jobs          []verification.Job            `json:"jobs,omitempty"`
	Digest        string                        `json:"digest"`
}

TaskUsageSnapshot retains a single transactional view of ownership, provider observations and every verifier job. It does not close verifier admission, authenticate usage, authorize settlement or guarantee future billing finality.

func SealTaskUsageSnapshot

func SealTaskUsageSnapshot(s TaskUsageSnapshot) (TaskUsageSnapshot, error)

SealTaskUsageSnapshot validates membership, ordering and bounds, then detaches the observation. Only trusted complete storage reads establish completeness.

func (TaskUsageSnapshot) Validate

func (s TaskUsageSnapshot) Validate() error

Validate checks the complete retained digest, not provider authenticity.

type TaskUsageSnapshotStore

type TaskUsageSnapshotStore interface {
	SnapshotTaskUsage(context.Context, TaskUsageRequest) (TaskUsageSnapshot, error)
}

TaskUsageSnapshotStore reads complete evidence under the plan, run and journal guards. Hosts must authorize this read; the result grants no spending authority.

type TaskUsageSummary

type TaskUsageSummary struct {
	Observed      execution.Resources      `json:"observed"`
	Known         execution.KnownResources `json:"known"`
	Overflow      execution.KnownResources `json:"overflow"`
	ProviderCalls int                      `json:"provider_calls"`
	VerifierCalls int                      `json:"verifier_calls"`
	OpenJobs      int                      `json:"open_jobs"`
}

TaskUsageSummary distinguishes observed lower bounds from exact retained usage. Known covers only the currently retained calls. OpenJobs and future job admission still prevent using this observation as final accounting authority.

func SummarizeTaskUsage

func SummarizeTaskUsage(s TaskUsageSnapshot) (TaskUsageSummary, error)

SummarizeTaskUsage includes failed work and all verifier attempts. Missing receipts never become known zero; partial observations survive as lower bounds. Tool/effect costs and local token estimates cannot establish billable usage.

type TaskUsageTermination

type TaskUsageTermination struct {
	RunRevision int64     `json:"run_revision"`
	State       run.State `json:"state"`
	CompletedAt time.Time `json:"completed_at"`
}

TaskUsageTermination binds accounting closure to a failed, cancelled or incomplete run. It does not release ownership or grant permission to retry.

type VerificationJobDiscoveryStore

type VerificationJobDiscoveryStore interface {
	ListVerificationJobs(context.Context, verification.JobListRequest) ([]verification.Job, error)
}

VerificationJobDiscoveryStore is the existing scoped job listing capability.

type VerificationJobListRequest

type VerificationJobListRequest struct {
	After string
	Limit int
}

VerificationJobListRequest bounds discovery with an opaque host cursor.

type VerificationJobPage

type VerificationJobPage struct {
	Jobs []ScheduledVerificationJob
	Next string
}

VerificationJobPage contains scoped identities. Empty Next ends a pass.

type VerificationJobRecoverer

type VerificationJobRecoverer interface {
	Recover(context.Context, id.ID) error
}

VerificationJobRecoverer rechecks saved state and current authority per job.

type VerificationJobSource

type VerificationJobSource interface {
	ListCapturedVerificationJobs(context.Context, VerificationJobListRequest) (VerificationJobPage, error)
}

VerificationJobSource discovers captured jobs under current host authority. It must finish each pass and must not evaluate or generate candidate content.

type VerificationRecoveryConfig

type VerificationRecoveryConfig struct {
	Discovery                                  VerificationJobSource
	Recoverer                                  VerificationJobRecoverer
	Interval, DiscoveryTimeout, AttemptTimeout time.Duration
	MaxInFlight, MaxPerScope                   int
	ReportError                                func(error)
}

VerificationRecoveryConfig bounds discovery and synchronous recovery attempts.

type VerificationRecoveryService

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

VerificationRecoveryService owns bounded discovery, fairness and joined shutdown.

func NewVerificationRecoveryService

func NewVerificationRecoveryService(config VerificationRecoveryConfig) (*VerificationRecoveryService, error)

NewVerificationRecoveryService defaults to four concurrent jobs, one per scope, one-second polling and one-minute attempts. Construction starts no background work.

func (*VerificationRecoveryService) RequestStop

func (s *VerificationRecoveryService) RequestStop()

RequestStop cancels discovery and all owned recovery attempts.

func (*VerificationRecoveryService) Start

Start preserves trusted host context while owning its own service lifetime.

func (*VerificationRecoveryService) Status

Status returns local counters without scope or candidate content.

func (*VerificationRecoveryService) Stop

Stop joins discovery and attempts before storage can be disposed.

Jump to

Keyboard shortcuts

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