planning

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: 17 Imported by: 0

Documentation

Overview

Package planning validates immutable task graphs before a host schedules work. Graph validity does not establish authorization, verified task completion or reserved capacity. Those checks belong to the host and durable scheduler.

Index

Constants

View Source
const (
	PrefixPlan id.Prefix = "plan"
	PrefixTask id.Prefix = "ptask"
)

Entity prefixes distinguish plans from their task definitions.

View Source
const (
	MaxReplanAttempts   = 16
	MaxProgressAttempts = 256
)

Hard bounds keep policy work and proposal counts finite.

Variables

View Source
var ErrConflict = errors.New("cortex: plan revision conflict")

ErrConflict means the caller proposed a change against another revision.

View Source
var ErrInvalid = errors.New("cortex: invalid plan")

ErrInvalid identifies an unsafe, unsupported or changed graph.

View Source
var ErrNotFound = errors.New("cortex: plan not found")

ErrNotFound means the plan or revision does not exist in the exact scope.

Functions

func ArtifactProducer

func ArtifactProducer(p Plan, taskID id.ID) string

ArtifactProducer identifies output captured for a task in this exact sealed plan. Use it when the host captures an artifact before trusted verification. A new plan revision requires new verification even when bytes are unchanged.

func Ready

func Ready(p Plan, states []TaskState, at time.Time) ([]id.ID, error)

Ready returns pending tasks in definition order whose entire prerequisite chain has current verified artifacts. It performs no I/O or authorization. The scheduler must recheck grants and atomically claim work before dispatch. Any revision requires explicitly refreshed states; evidence is never reused solely because a task ID survived the revision.

func TaskContract

func TaskContract(p Plan, taskID, contractID id.ID) (verification.Contract, error)

TaskContract derives a task's checks using a new host-selected contract ID. Persist the returned contract before executing or verifying that task. It preserves plan constraints and verifier parameters, and requires every assigned criterion even when that criterion is optional for the plan as a whole.

func Validate

func Validate(p Plan, limits Limits) error

Validate rejects modified definitions without resealing them.

func ValidateTaskAcceptance

func ValidateTaskAcceptance(p Plan, taskID id.ID, states []TaskState, at time.Time) error

ValidateTaskAcceptance checks verified output and its complete prerequisite chain. The host must supply trusted reports and current authorized bindings.

func ValidateTaskBinding

func ValidateTaskBinding(p Plan, taskID id.ID, binding verification.Binding) error

ValidateTaskBinding checks candidate shape and frozen task sources/tools. It does not establish provenance authenticity, current access or a verifier pass.

func ValidateTaskBindingForContract

func ValidateTaskBindingForContract(p Plan, taskID id.ID, contract verification.Contract, binding verification.Binding) error

ValidateTaskBindingForContract checks a retained plan or task contract and the exact task artifact/context. It does not establish authority or a verifier pass.

func ValidateTaskContract

func ValidateTaskContract(p Plan, taskID id.ID, contract verification.Contract) error

ValidateTaskContract accepts the exact plan contract or its task projection. It rejects omitted, weakened, foreign or superseded task requirements. Contract integrity does not establish current host authority or verifier authenticity.

Types

type Access

type Access string

Access is a host-defined resource permission. Write includes read access.

const (
	AccessRead  Access = "read"
	AccessWrite Access = "write"
)

type ArtifactRequirement

type ArtifactRequirement struct {
	Name      string `json:"name"`
	MediaType string `json:"media_type"`
	MaxBytes  int64  `json:"max_bytes"`
}

ArtifactRequirement declares the single output owned by a task. A later verifier must check its content, media type and byte bound before acceptance. The captured evidence Producer must come from ArtifactProducer.

type Authority

type Authority struct {
	Resources []ResourceGrant               `json:"resources,omitempty"`
	Effects   []execution.EffectRequirement `json:"effects,omitempty"`
	Budget    execution.Budget              `json:"budget"`
}

Authority is a bounded capability ceiling, not a credential or a reservation. A host must resolve current permissions before trusting one from storage.

func TaskAuthority

func TaskAuthority(p Plan, taskID id.ID) (Authority, error)

TaskAuthority returns capabilities declared for one task in a sealed plan.

func (Authority) Validate

func (a Authority) Validate() error

Validate checks declarations without authenticating their issuer.

func (Authority) Within

func (a Authority) Within(parent Authority) bool

Within checks attenuation, preserving pinned resource and handler revisions.

type Limits

type Limits struct {
	MaxTasks int
	MaxDepth int
	MaxEdges int
}

Limits can narrow the hard bounds of 256 tasks, 64 levels and 4096 edges. Zero values use those bounds; negative or larger values are invalid.

type ListRequest

type ListRequest struct {
	After id.ID
	Limit int
}

ListRequest pages plan identities in lexical ID order. Limit is 1..256.

type Origin

type Origin struct {
	Kind   string `json:"kind"`
	ID     id.ID  `json:"id"`
	Digest string `json:"digest"`
}

Origin pins the execution configuration used to derive a graph. It is provenance, not authorization to load or execute the referenced configuration.

type Plan

type Plan struct {
	SchemaVersion  int                           `json:"schema_version"`
	ID             id.ID                         `json:"id"`
	Scope          cortex.Scope                  `json:"scope"`
	Revision       int64                         `json:"revision"`
	Digest         string                        `json:"digest"`
	PreviousDigest string                        `json:"previous_digest,omitempty"`
	Objective      string                        `json:"objective"`
	Contract       verification.Contract         `json:"contract"`
	Budget         execution.Budget              `json:"budget"`
	Owners         []string                      `json:"owners"`
	Resources      []ResourceGrant               `json:"resources,omitempty"`
	Tasks          []Task                        `json:"tasks"`
	Actor          string                        `json:"actor"`
	Reason         string                        `json:"reason"`
	AffectedTasks  []id.ID                       `json:"affected_tasks,omitempty"`
	Effects        []execution.EffectRequirement `json:"effects,omitempty"`
	Sources        []verification.Source         `json:"sources,omitempty"`
	Origin         Origin                        `json:"origin,omitzero"`
}

Plan binds a graph to an exact scope, contract and authority ceiling. Digests establish integrity only; Actor is a host-authenticated audit reference.

func ApplyRevision

func ApplyRevision(current Plan, proposal Revision, expected int64, limits Limits) (Plan, error)

ApplyRevision validates a detached replacement against the current grant and contract. The durable store must still compare expected under its write lock. It does not transfer claims or reuse accepted evidence across revisions.

func Seal

func Seal(p Plan, limits Limits) (Plan, error)

Seal validates and detaches a definition before hashing its canonical JSON.

type ProgressAttempt

type ProgressAttempt struct {
	PlanDigest    string        `json:"plan_digest"`
	RunID         id.AgentRunID `json:"run_id"`
	TaskID        id.ID         `json:"task_id"`
	FinishedAt    time.Time     `json:"finished_at"`
	FailureDigest string        `json:"failure_digest,omitempty"`
	Advanced      bool          `json:"advanced"`
}

ProgressAttempt is a host-observed attempt, not a model's self-assessment. Advanced means new accepted artifacts or retained checks were produced. FailureDigest groups equivalent failures without retaining private error text.

type ProgressConflict

type ProgressConflict struct {
	PlanDigest  string `json:"plan_digest"`
	TaskID      id.ID  `json:"task_id"`
	LeftDigest  string `json:"left_digest"`
	RightDigest string `json:"right_digest"`
}

ProgressConflict references contradictory observations about one task. The host must establish the contradiction from retained, authorized evidence.

type ProgressSnapshot

type ProgressSnapshot struct {
	SchemaVersion     int                      `json:"schema_version"`
	Plan              Plan                     `json:"plan"`
	At                time.Time                `json:"at"`
	StartedAt         time.Time                `json:"started_at"`
	LastProgressAt    time.Time                `json:"last_progress_at"`
	WaitingSince      time.Time                `json:"waiting_since,omitzero"`
	Account           execution.BudgetSnapshot `json:"account"`
	Attempts          []ProgressAttempt        `json:"attempts,omitempty"`
	Conflicts         []ProgressConflict       `json:"conflicts,omitempty"`
	UnresolvedEffects bool                     `json:"unresolved_effects"`
}

ProgressSnapshot binds a policy decision to the current sealed graph. The host reconstructs progress from retained observations and reads Account from execution.BudgetStore. Conservative replan charges include outstanding holds; they must not be replaced by a model's count or reset after a plan revision. The pure policy establishes no authority, capacity reservation or acceptance.

func (ProgressSnapshot) Validate

func (s ProgressSnapshot) Validate() error

Validate rejects inconsistent, unbounded or stale graph observations. It does not authenticate the observer or certify the meaning of a progress signal.

type ReplanAction

type ReplanAction string

ReplanAction is a proposed next step, never permission to execute it.

const (
	ReplanContinue  ReplanAction = "continue"
	ReplanWait      ReplanAction = "wait"
	ReplanReconcile ReplanAction = "reconcile"
	ReplanPropose   ReplanAction = "propose"
	ReplanStop      ReplanAction = "stop"
)

type ReplanDecision

type ReplanDecision struct {
	SchemaVersion  int          `json:"schema_version"`
	Action         ReplanAction `json:"action"`
	Reason         ReplanReason `json:"reason"`
	PlanID         id.ID        `json:"plan_id"`
	PlanRevision   int64        `json:"plan_revision"`
	PlanDigest     string       `json:"plan_digest"`
	SnapshotDigest string       `json:"snapshot_digest"`
	PolicyDigest   string       `json:"policy_digest"`
}

ReplanDecision binds a proposal to exact observations and normalized policy. Reserve a proposal attempt under current host authorization before requesting model output. Persist its consumption even if the model or validation fails.

func ProposeReplan

func ProposeReplan(snapshot ProgressSnapshot, policy ReplanPolicy) ReplanDecision

ProposeReplan selects a deterministic response to trusted progress. It performs no I/O, does not mutate the snapshot and never claims that a task succeeded. Unknown effects take priority even after deadlines: stopping dispatch must not discard the obligation to reconcile an external operation.

type ReplanPolicy

type ReplanPolicy struct {
	SchemaVersion       int           `json:"schema_version"`
	Disabled            bool          `json:"disabled"`
	MaxReplans          int           `json:"max_replans"`
	FailureThreshold    int           `json:"failure_threshold"`
	NoProgressThreshold int           `json:"no_progress_threshold"`
	MaxIdle             time.Duration `json:"max_idle"`
	DeadlineReserve     time.Duration `json:"deadline_reserve"`
}

ReplanPolicy bounds proposal selection. Zero fields use two proposal attempts, two equivalent failures, three attempts without progress, five minutes idle and thirty seconds of deadline reserve. Disabled stops proposal selection. The account replan allowance must not exceed MaxReplans, so an atomic reservation can enforce this ceiling across competing workers. These settings do not authorize retries, cancel work or change acceptance.

func (ReplanPolicy) Normalize

func (p ReplanPolicy) Normalize() (ReplanPolicy, error)

Normalize resolves defaults and rejects settings beyond finite host bounds.

type ReplanReason

type ReplanReason string

ReplanReason is a bounded explanation without private failure content.

const (
	ReplanHealthy           ReplanReason = "healthy"
	ReplanWaiting           ReplanReason = "waiting"
	ReplanStalledWait       ReplanReason = "stalled_wait"
	ReplanIdle              ReplanReason = "idle"
	ReplanRepeatedFailure   ReplanReason = "repeated_failure"
	ReplanNoProgress        ReplanReason = "no_progress"
	ReplanContradiction     ReplanReason = "contradictory_evidence"
	ReplanUnresolvedEffects ReplanReason = "unresolved_effects"
	ReplanDeadlinePressure  ReplanReason = "deadline_pressure"
	ReplanDeadline          ReplanReason = "deadline"
	ReplanBudget            ReplanReason = "budget"
	ReplanLimit             ReplanReason = "replan_limit"
	ReplanDisabled          ReplanReason = "disabled"
	ReplanInvalidSnapshot   ReplanReason = "invalid_snapshot"
	ReplanInvalidPolicy     ReplanReason = "invalid_policy"
)

type ResourceGrant

type ResourceGrant struct {
	Resource string `json:"resource"`
	Revision string `json:"revision"`
	Access   Access `json:"access"`
}

ResourceGrant pins an allowed resource and its host revision.

type ReviewRequirement

type ReviewRequirement struct {
	ReviewerAgent     string `json:"reviewer_agent"`
	ReviewerPrincipal string `json:"reviewer_principal"`
	PolicyRevision    string `json:"policy_revision"`
}

ReviewRequirement pins the independent reviewer and host review policy. A matching review is required before task acceptance; it cannot replace verifier evidence. Hosts authenticate these identities and prepare independent context.

type Revision

type Revision struct {
	Plan   Plan
	Actor  string
	Reason string
}

Revision is a proposed replacement graph plus host-authenticated audit data. ApplyRevision assigns chain metadata; model-provided revision metadata is ignored.

type Status

type Status string

Status describes scheduler state. Succeeded alone never proves acceptance.

const (
	StatusPending   Status = "pending"
	StatusReady     Status = "ready"
	StatusClaimed   Status = "claimed"
	StatusRunning   Status = "running"
	StatusWaiting   Status = "waiting"
	StatusVerifying Status = "verifying"
	StatusSucceeded Status = "succeeded"
	StatusFailed    Status = "failed"
	StatusBlocked   Status = "blocked"
	StatusCancelled Status = "cancelled"
)

type Store

type Store interface {
	CreatePlan(context.Context, Plan) error
	GetPlan(context.Context, id.ID) (Plan, error)
	GetPlanRevision(context.Context, id.ID, int64) (Plan, error)
	ListPlans(context.Context, ListRequest) ([]Plan, error)
	CommitRevision(context.Context, Revision, int64) (Plan, error)
	ReadTasks(context.Context, id.ID) ([]Task, error)
}

Store is optional immutable plan persistence. Every operation requires exact context scope. Commits serialize by plan identity and expected revision; identical retries return the accepted revision, even if later revisions exist. These methods persist definitions, not task claims or verification decisions.

type Task

type Task struct {
	ID          id.ID               `json:"id"`
	Instruction string              `json:"instruction"`
	Owner       string              `json:"owner"`
	DependsOn   []id.ID             `json:"depends_on,omitempty"`
	Criteria    []string            `json:"criteria"`
	Resources   []ResourceGrant     `json:"resources,omitempty"`
	Budget      execution.Budget    `json:"budget"`
	Output      ArtifactRequirement `json:"output"`
	Effects     []string            `json:"effects,omitempty"`
	Sources     []string            `json:"sources,omitempty"`
	Review      *ReviewRequirement  `json:"review,omitempty"`
}

Task is an immutable definition, separate from claims and execution state. Criteria reference the plan's host-authored acceptance contract.

type TaskState

type TaskState struct {
	TaskID     id.ID                  `json:"task_id"`
	PlanDigest string                 `json:"plan_digest"`
	Status     Status                 `json:"status"`
	Current    verification.Binding   `json:"current"`
	Reports    []verification.Report  `json:"reports,omitempty"`
	Contract   *verification.Contract `json:"contract,omitempty"`
}

TaskState is a host-supplied readiness snapshot. Current must be rebuilt from currently authorized artifact and environment revisions, not copied from a persisted report. Reports must come from trusted verifier storage. This type carries no credentials and cannot authenticate remote success claims. Contract is the retained task contract; nil selects the original plan contract.

Jump to

Keyboard shortcuts

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