Documentation
¶
Overview ¶
Package routedrun defines the durable domain model for the AgentPaaS Durable Routed Run: deployments, aliases, invocations, runs, attempts, workflows, time envelopes, artifacts, progress, and store interfaces.
Core concerns:
- Stable typed IDs (DeploymentID, InvocationID, RunID, AttemptID, …)
- Enumerations and CAS-friendly record types with generation fields
- State-transition validation for run/attempt/workflow lifecycles
- Store interfaces (DeploymentStore, RunStore, WorkflowStore) plus filesystem and in-memory implementations (LocalStore, MemoryStore)
- Write-ahead logging, control journal hooks, artifact workspaces, resume/progress helpers, and time-envelope wiring
Daemon gRPC handlers and the supervisor consume these types; this package does not open network listeners or drive containers directly.
Index ¶
- Constants
- Variables
- func AttemptIDValidate(id AttemptID) bool
- func MarshalCanonical(v interface{}) ([]byte, error)
- func NowMonotonicMs(clock Clock) int64
- func UnmarshalStrict(data []byte, v interface{}) error
- func ValidateAttemptTransition(from, to AttemptStatus) error
- func ValidateChildBatchTransition(from, to ChildBatchStatus) error
- func ValidateIDPrefix(id, prefix string) bool
- func ValidateNodeTransition(from, to NodeStatus) error
- func ValidateResumeCheckpoint(cp *ResumeCheckpointData, expectedRunID RunID, policyDigest string, ...) error
- func ValidateRunTransition(from, to RunStatus) error
- func ValidateServiceTransition(from, to ServiceStatus) error
- func ValidateWorkflowTransition(from, to WorkflowStatus) error
- type ActiveTimeLedger
- type AdmissionOutcome
- type AggregateUsageSummary
- type AliasRecord
- type ArtifactID
- type ArtifactMetadata
- type ArtifactRef
- type ArtifactWorkspace
- func (aw *ArtifactWorkspace) ListMetadata() []*ArtifactMetadata
- func (aw *ArtifactWorkspace) RemoveUnreferenced() error
- func (aw *ArtifactWorkspace) Root() string
- func (aw *ArtifactWorkspace) TotalSize() int64
- func (aw *ArtifactWorkspace) ValidateAndAccept(ctx context.Context, relPath string, attemptID AttemptID) (*ArtifactMetadata, error)
- type AttemptID
- type AttemptLease
- type AttemptProgress
- type AttemptRecord
- type AttemptReport
- type AttemptStatus
- type AuthorityScope
- type Candidate
- type CheckpointID
- type CheckpointStore
- type CheckpointSummary
- type ChildBatch
- type ChildBatchID
- type ChildBatchStatus
- type ChildResult
- type ChildResultID
- type ChildSpawnRequest
- type Clock
- type ControlCommand
- type ControlJournal
- type ControlRequest
- type ControlRequestID
- type Cost
- type DataClassification
- type DeploymentID
- type DeploymentRecord
- type DeploymentStatus
- type DeploymentStore
- type DesiredState
- type DurableIdempotencyRecord
- type FailureReason
- type FailureScope
- type FakeClock
- func (c *FakeClock) AdvanceMonotonic(d time.Duration)
- func (c *FakeClock) After(d time.Duration) <-chan time.Time
- func (c *FakeClock) NewTimer(d time.Duration) TimerHandle
- func (c *FakeClock) Now() time.Time
- func (c *FakeClock) NowMonotonic() time.Time
- func (c *FakeClock) NowMonotonicUnixMs() int64
- func (c *FakeClock) SetWall(t time.Time)
- type HandoffEnvelope
- type HandoffID
- type InvocationID
- type InvocationReceipt
- type InvocationRequest
- type InvokeJob
- type InvokeJobEvent
- type InvokeJobEventKind
- type InvokeJobResult
- type InvokeJobResultStatus
- type JoinPolicy
- type LLMBudgetSummary
- type LeaseID
- type LimitAmendment
- type LimitAmendmentID
- type LocalStore
- func (s *LocalStore) AdmitInvocation(ctx context.Context, request *InvocationRequest, ...) (*InvocationReceipt, error)
- func (s *LocalStore) AppendControlResult(ctx context.Context, req *ControlRequest, result interface{}) error
- func (s *LocalStore) AppendLedger(ctx context.Context, runID RunID, entry string) error
- func (s *LocalStore) AppendLimitAmendment(ctx context.Context, workflowID WorkflowID, expectedAuthorityGeneration int64, ...) error
- func (s *LocalStore) ApplyTransition(ctx context.Context, workflowID WorkflowID, expectedGeneration int64, ...) error
- func (s *LocalStore) CommitChildResult(ctx context.Context, result *ChildResult) error
- func (s *LocalStore) CommitHandoff(ctx context.Context, handoff *HandoffEnvelope) error
- func (s *LocalStore) CompareAndSwapAlias(ctx context.Context, alias *AliasRecord) error
- func (s *LocalStore) CreateAttempt(ctx context.Context, attempt *AttemptRecord) error
- func (s *LocalStore) CreateChildBatch(ctx context.Context, batch *ChildBatch) error
- func (s *LocalStore) CreateDeployment(ctx context.Context, dep *DeploymentRecord) error
- func (s *LocalStore) CreateNode(ctx context.Context, node *PipelineNode) error
- func (s *LocalStore) CreateRun(ctx context.Context, run *RunRecord) error
- func (s *LocalStore) CreateWorkflow(ctx context.Context, wf *WorkflowRecord) error
- func (s *LocalStore) GetActiveTimeLedger(ctx context.Context, workflowID WorkflowID) (*ActiveTimeLedger, error)
- func (s *LocalStore) GetActiveTimeLedgerGeneration(ctx context.Context, workflowID WorkflowID) (int64, error)
- func (s *LocalStore) GetAttempt(ctx context.Context, attemptID AttemptID) (*AttemptRecord, error)
- func (s *LocalStore) GetAttemptGeneration(ctx context.Context, attemptID AttemptID) (int64, error)
- func (s *LocalStore) GetAttemptProgress(ctx context.Context, attemptID AttemptID) (*AttemptProgress, error)
- func (s *LocalStore) GetCheckpoint(ctx context.Context, checkpointID CheckpointID) (*SemanticCheckpoint, error)
- func (s *LocalStore) GetDeployment(ctx context.Context, deploymentID DeploymentID) (*DeploymentRecord, error)
- func (s *LocalStore) GetDesiredState(ctx context.Context, workflowID WorkflowID) (*DesiredState, error)
- func (s *LocalStore) GetHandoff(ctx context.Context, handoffID HandoffID) (*HandoffEnvelope, error)
- func (s *LocalStore) GetInvocationByIdempotency(ctx context.Context, callerIdentity, idempotencyKey string) (*InvocationReceipt, error)
- func (s *LocalStore) GetLatestCheckpoint(ctx context.Context, attemptID AttemptID) (*SemanticCheckpoint, error)
- func (s *LocalStore) GetNode(ctx context.Context, nodeID NodeID) (*PipelineNode, error)
- func (s *LocalStore) GetRun(ctx context.Context, runID RunID) (*RunRecord, error)
- func (s *LocalStore) GetRunGeneration(ctx context.Context, runID RunID) (int64, error)
- func (s *LocalStore) GetWorkflow(ctx context.Context, workflowID WorkflowID) (*WorkflowRecord, error)
- func (s *LocalStore) ListAliases(ctx context.Context) ([]*AliasRecord, error)
- func (s *LocalStore) ListAttempts(ctx context.Context, runID RunID) ([]*AttemptRecord, error)
- func (s *LocalStore) ListChildBatches(ctx context.Context, workflowID WorkflowID) ([]*ChildBatch, error)
- func (s *LocalStore) ListChildResults(ctx context.Context, childBatchID ChildBatchID) ([]*ChildResult, error)
- func (s *LocalStore) ListDeployments(ctx context.Context) ([]*DeploymentRecord, error)
- func (s *LocalStore) ListHandoffs(ctx context.Context, workflowID WorkflowID) ([]*HandoffEnvelope, error)
- func (s *LocalStore) ListInvocations(ctx context.Context) ([]*InvocationReceipt, error)
- func (s *LocalStore) ListNodes(ctx context.Context, workflowID WorkflowID) ([]*PipelineNode, error)
- func (s *LocalStore) ListRuns(ctx context.Context, workflowID WorkflowID) ([]*RunRecord, error)
- func (s *LocalStore) ListServices(ctx context.Context, workflowID WorkflowID) ([]*MCPServiceBinding, error)
- func (s *LocalStore) ListWorkflows(ctx context.Context) ([]*WorkflowRecord, error)
- func (s *LocalStore) PutActiveTimeLedger(ctx context.Context, workflowID WorkflowID, ledger *ActiveTimeLedger, ...) error
- func (s *LocalStore) ReconcileInterrupted(ctx context.Context, runID RunID) error
- func (s *LocalStore) RecoverWAL(wfID WorkflowID) error
- func (s *LocalStore) RegisterService(ctx context.Context, svc *MCPServiceBinding) error
- func (s *LocalStore) RequestControl(ctx context.Context, req *ControlRequest) error
- func (s *LocalStore) ResolveAlias(ctx context.Context, alias string) (*AliasRecord, error)
- func (s *LocalStore) SaveAttemptProgress(ctx context.Context, attemptID AttemptID, progress *AttemptProgress) error
- func (s *LocalStore) SaveCheckpoint(ctx context.Context, cp *SemanticCheckpoint) error
- func (s *LocalStore) SetDeploymentStatus(ctx context.Context, deploymentID DeploymentID, status DeploymentStatus, ...) error
- func (s *LocalStore) UpdateAttempt(ctx context.Context, attempt *AttemptRecord, expectedGeneration int64) error
- func (s *LocalStore) UpdateChildBatch(ctx context.Context, batch *ChildBatch, expectedGeneration int64) error
- func (s *LocalStore) UpdateNode(ctx context.Context, node *PipelineNode, expectedGeneration int64) error
- func (s *LocalStore) UpdateRun(ctx context.Context, run *RunRecord, expectedGeneration int64) error
- func (s *LocalStore) UpdateService(ctx context.Context, svc *MCPServiceBinding, expectedGeneration int64) error
- func (s *LocalStore) UpdateWorkflow(ctx context.Context, wf *WorkflowRecord, expectedGeneration int64) error
- type LocalStoreOption
- type MCPServiceBinding
- type MemoryStore
- func (s *MemoryStore) AdmitInvocation(ctx context.Context, request *InvocationRequest, ...) (*InvocationReceipt, error)
- func (s *MemoryStore) AppendControlResult(ctx context.Context, req *ControlRequest, result interface{}) error
- func (s *MemoryStore) AppendLedger(ctx context.Context, runID RunID, entry string) error
- func (s *MemoryStore) AppendLimitAmendment(ctx context.Context, workflowID WorkflowID, expectedAuthorityGeneration int64, ...) error
- func (s *MemoryStore) ApplyTransition(ctx context.Context, workflowID WorkflowID, expectedGeneration int64, ...) error
- func (s *MemoryStore) CommitChildResult(ctx context.Context, result *ChildResult) error
- func (s *MemoryStore) CommitHandoff(ctx context.Context, handoff *HandoffEnvelope) error
- func (s *MemoryStore) CompareAndSwapAlias(ctx context.Context, alias *AliasRecord) error
- func (s *MemoryStore) CreateAttempt(ctx context.Context, attempt *AttemptRecord) error
- func (s *MemoryStore) CreateChildBatch(ctx context.Context, batch *ChildBatch) error
- func (s *MemoryStore) CreateDeployment(ctx context.Context, dep *DeploymentRecord) error
- func (s *MemoryStore) CreateNode(ctx context.Context, node *PipelineNode) error
- func (s *MemoryStore) CreateRun(ctx context.Context, run *RunRecord) error
- func (s *MemoryStore) CreateWorkflow(ctx context.Context, wf *WorkflowRecord) error
- func (s *MemoryStore) GetActiveTimeLedger(ctx context.Context, workflowID WorkflowID) (*ActiveTimeLedger, error)
- func (s *MemoryStore) GetActiveTimeLedgerGeneration(ctx context.Context, workflowID WorkflowID) (int64, error)
- func (s *MemoryStore) GetAttempt(ctx context.Context, attemptID AttemptID) (*AttemptRecord, error)
- func (s *MemoryStore) GetDeployment(ctx context.Context, deploymentID DeploymentID) (*DeploymentRecord, error)
- func (s *MemoryStore) GetDesiredState(ctx context.Context, workflowID WorkflowID) (*DesiredState, error)
- func (s *MemoryStore) GetHandoff(ctx context.Context, handoffID HandoffID) (*HandoffEnvelope, error)
- func (s *MemoryStore) GetInvocationByIdempotency(ctx context.Context, callerIdentity, idempotencyKey string) (*InvocationReceipt, error)
- func (s *MemoryStore) GetNode(ctx context.Context, nodeID NodeID) (*PipelineNode, error)
- func (s *MemoryStore) GetRun(ctx context.Context, runID RunID) (*RunRecord, error)
- func (s *MemoryStore) GetWorkflow(ctx context.Context, workflowID WorkflowID) (*WorkflowRecord, error)
- func (s *MemoryStore) ListAliases(ctx context.Context) ([]*AliasRecord, error)
- func (s *MemoryStore) ListAttempts(ctx context.Context, runID RunID) ([]*AttemptRecord, error)
- func (s *MemoryStore) ListChildBatches(ctx context.Context, workflowID WorkflowID) ([]*ChildBatch, error)
- func (s *MemoryStore) ListChildResults(ctx context.Context, childBatchID ChildBatchID) ([]*ChildResult, error)
- func (s *MemoryStore) ListDeployments(ctx context.Context) ([]*DeploymentRecord, error)
- func (s *MemoryStore) ListHandoffs(ctx context.Context, workflowID WorkflowID) ([]*HandoffEnvelope, error)
- func (s *MemoryStore) ListInvocations(ctx context.Context) ([]*InvocationReceipt, error)
- func (s *MemoryStore) ListNodes(ctx context.Context, workflowID WorkflowID) ([]*PipelineNode, error)
- func (s *MemoryStore) ListRuns(ctx context.Context, workflowID WorkflowID) ([]*RunRecord, error)
- func (s *MemoryStore) ListServices(ctx context.Context, workflowID WorkflowID) ([]*MCPServiceBinding, error)
- func (s *MemoryStore) ListWorkflows(ctx context.Context) ([]*WorkflowRecord, error)
- func (s *MemoryStore) PutActiveTimeLedger(ctx context.Context, workflowID WorkflowID, ledger *ActiveTimeLedger, ...) error
- func (s *MemoryStore) ReconcileInterrupted(ctx context.Context, runID RunID) error
- func (s *MemoryStore) RegisterService(ctx context.Context, svc *MCPServiceBinding) error
- func (s *MemoryStore) RequestControl(ctx context.Context, req *ControlRequest) error
- func (s *MemoryStore) ResolveAlias(ctx context.Context, alias string) (*AliasRecord, error)
- func (s *MemoryStore) SetDeploymentStatus(ctx context.Context, deploymentID DeploymentID, status DeploymentStatus, ...) error
- func (s *MemoryStore) UpdateAttempt(ctx context.Context, attempt *AttemptRecord, expectedGeneration int64) error
- func (s *MemoryStore) UpdateChildBatch(ctx context.Context, batch *ChildBatch, expectedGeneration int64) error
- func (s *MemoryStore) UpdateNode(ctx context.Context, node *PipelineNode, expectedGeneration int64) error
- func (s *MemoryStore) UpdateRun(ctx context.Context, run *RunRecord, expectedGeneration int64) error
- func (s *MemoryStore) UpdateService(ctx context.Context, svc *MCPServiceBinding, expectedGeneration int64) error
- func (s *MemoryStore) UpdateWorkflow(ctx context.Context, wf *WorkflowRecord, expectedGeneration int64) error
- type MemoryStoreOption
- type Migration
- type MigrationRegistry
- func (r *MigrationRegistry) Current() string
- func (r *MigrationRegistry) IsSupported(version string) bool
- func (r *MigrationRegistry) Migrate(fromVersion string, state []byte) (toVersion string, out []byte, err error)
- func (r *MigrationRegistry) MigrateFile(path string) error
- func (r *MigrationRegistry) MigrateTree(root string) error
- func (r *MigrationRegistry) NeedsMigration(version string) bool
- type ModelCallID
- type ModelRequirements
- type NodeID
- type NodeStateTransition
- type NodeStatus
- type NormalizedUsage
- type PipelineNode
- type ProgressSummary
- type ProgressTailer
- type RecoveryDisposition
- type RestartProvenance
- type ResumeCapability
- type ResumeCheckpointData
- type ResumeCheckpointLoader
- type ResumeReason
- type RouteDecision
- type RunID
- type RunRecord
- type RunStatus
- type RunStore
- type SemanticCheckpoint
- type ServiceHealthSummary
- type ServiceID
- type ServiceLease
- type ServiceStatus
- type SystemClock
- type SystemTimer
- type TerminationEvent
- type TerminationReason
- type TimeBudgetSummary
- type TimeEnvelope
- func CloseActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
- func FreezeActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
- func NewTimeEnvelope(maxActiveMs, attemptLeaseMs, stallTimeoutMs, modelCallTimeoutMs int64) TimeEnvelope
- func StartActiveSegment(env TimeEnvelope, nowMs int64) (TimeEnvelope, error)
- func TimeEnvelopeFromCeilings(maxActiveMs, attemptLeaseMs, stallTimeoutMs, modelCallTimeoutMs int64) (TimeEnvelope, bool)
- func TimeEnvelopeFromReceipt(receipt *InvocationReceipt) (TimeEnvelope, bool)
- func UnfreezeActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
- func UnmarshalTimeEnvelopeFromPayload(payload map[string]any) (TimeEnvelope, bool)
- func WithAmendedCeiling(env TimeEnvelope, newMaxActiveMs, newAuthorityGeneration int64) TimeEnvelope
- type Timer
- type TimerHandle
- type TransitionError
- type WALEntry
- type WALOp
- type WorkflowCredentialRecord
- type WorkflowID
- type WorkflowPolicySnapshot
- type WorkflowRecord
- type WorkflowReport
- type WorkflowStatus
- type WorkflowStore
Constants ¶
const ( ArtifactMaxPerFile = int64(25 * 1024 * 1024) // 25 MiB ArtifactMaxTotal = int64(100 * 1024 * 1024) // 100 MiB ArtifactMaxPathLen = 512 ArtifactMaxSegments = 8 ArtifactDirEnvVar = "AGENTPAAS_ARTIFACT_DIR" ArtifactMountPath = "/workspace/artifacts" )
const ( PrefixDeployment = "dep-" PrefixInvocation = "inv-" PrefixControl = "ctrl-" PrefixAmendment = "amend-" PrefixWorkflow = "wf-" PrefixNode = "node-" PrefixService = "svc-" PrefixHandoff = "ho-" PrefixChildBatch = "cb-" PrefixChildResult = "cr-" PrefixRun = "run-" PrefixAttempt = "at-" PrefixLease = "ls-" PrefixIdempotency = "idem-" )
ID prefixes match the stable ID types and existing contract tests.
const CurrentSchemaVersion = "0.3.0"
CurrentSchemaVersion is the current schema version for routed run state.
const DefaultModelCallTimeoutMs = int64(120_000) // 120 seconds
DefaultModelCallTimeoutMs is the default per-operation model-call timeout when a receipt does not carry one. It matches the v0.2.3 ceiling-5 HTTP client timeout.
const DefaultStallTimeoutMs = int64(120_000) // 2 minutes
DefaultStallTimeoutMs is the default per-operation stall timeout when a receipt does not carry one. It is the ceiling-1 / ceiling-3 default the durable path applies for stall detection absent an explicit policy value.
Variables ¶
var ( ErrNotFound = errors.New("routedrun: not found") ErrAlreadyExists = errors.New("routedrun: already exists") ErrCASConflict = errors.New("routedrun: generation conflict") ErrIdempotencyConflict = errors.New("routedrun: idempotency conflict") ErrAlreadyRunning = errors.New("routedrun: already running") ErrDeploymentInactive = errors.New("routedrun: deployment inactive") ErrSymlinkRejected = errors.New("routedrun: symlink rejected") ErrUnsafePermissions = errors.New("routedrun: unsafe permissions") ErrSizeCapExceeded = errors.New("routedrun: size cap exceeded") ErrInvalidPath = errors.New("routedrun: invalid path component") ErrUnknownSchemaVersion = errors.New("routedrun: unknown or unsupported schema version") ErrInvalidArgument = errors.New("routedrun: invalid argument") ErrLeaseCallerSelected = errors.New("routedrun: caller-selected lease id rejected") ErrJournalSequenceConflict = errors.New("routedrun: journal sequence conflict") )
Store errors (sentinel).
var AttemptTransitions = map[AttemptStatus]map[AttemptStatus]bool{ AttemptStatusPending: { AttemptStatusRunning: true, AttemptStatusCancelled: true, AttemptStatusFailed: true, }, AttemptStatusRunning: { AttemptStatusNeedsReplan: true, AttemptStatusSucceeded: true, AttemptStatusFailed: true, AttemptStatusFenced: true, AttemptStatusCancelled: true, }, AttemptStatusNeedsReplan: { AttemptStatusRunning: true, AttemptStatusCancelled: true, AttemptStatusFailed: true, }, AttemptStatusSucceeded: {}, AttemptStatusFailed: {}, AttemptStatusFenced: {}, AttemptStatusCancelled: {}, }
AttemptTransitions defines legal AttemptStatus transitions.
var ChildBatchTransitions = map[ChildBatchStatus]map[ChildBatchStatus]bool{ ChildBatchIntent: { ChildBatchAllocated: true, ChildBatchCancelled: true, }, ChildBatchAllocated: { ChildBatchRunning: true, ChildBatchCancelled: true, }, ChildBatchRunning: { ChildBatchPauseRequested: true, ChildBatchJoining: true, ChildBatchFailed: true, ChildBatchCancelled: true, }, ChildBatchPauseRequested: { ChildBatchPaused: true, ChildBatchRunning: true, ChildBatchStopping: true, ChildBatchCancelled: true, }, ChildBatchPaused: { ChildBatchRunning: true, ChildBatchStopping: true, ChildBatchCancelled: true, }, ChildBatchJoining: { ChildBatchSucceeded: true, ChildBatchFailed: true, ChildBatchCancelled: true, }, ChildBatchStopping: { ChildBatchStopped: true, ChildBatchFailed: true, ChildBatchCancelled: true, }, ChildBatchSucceeded: {}, ChildBatchFailed: {}, ChildBatchCancelled: {}, }
ChildBatchTransitions defines legal ChildBatchStatus transitions.
var ErrSegmentAlreadyOpen = errors.New("time envelope: active segment already open")
ErrSegmentAlreadyOpen is returned by StartActiveSegment when a segment is already open. Per b30-summary.md:357-358 at most one segment may be open per workflow; a second start is rejected rather than silently closing the first, so callers must explicitly close before restarting.
var NodeTransitions = map[NodeStatus]map[NodeStatus]bool{ NodeStatusPending: { NodeStatusReady: true, NodeStatusCancelled: true, NodeStatusSkipped: true, }, NodeStatusReady: { NodeStatusLaunching: true, NodeStatusCancelled: true, NodeStatusSkipped: true, }, NodeStatusLaunching: { NodeStatusRunning: true, NodeStatusFailed: true, NodeStatusCancelled: true, }, NodeStatusRunning: { NodeStatusPauseRequested: true, NodeStatusSucceeded: true, NodeStatusFailed: true, NodeStatusCancelled: true, }, NodeStatusPauseRequested: { NodeStatusPaused: true, NodeStatusRunning: true, NodeStatusCancelled: true, NodeStatusFailed: true, }, NodeStatusPaused: { NodeStatusRunning: true, NodeStatusNeedsReplan: true, NodeStatusCancelled: true, }, NodeStatusNeedsReplan: { NodeStatusRunning: true, NodeStatusCancelled: true, }, NodeStatusSucceeded: {}, NodeStatusFailed: {}, NodeStatusCancelled: {}, NodeStatusSkipped: {}, }
NodeTransitions defines legal NodeStatus transitions.
var RunTransitions = map[RunStatus]map[RunStatus]bool{ RunStatusPending: { RunStatusRunning: true, RunStatusCancelled: true, RunStatusFailed: true, }, RunStatusRunning: { RunStatusPauseRequested: true, RunStatusSucceeded: true, RunStatusFailed: true, RunStatusCancelled: true, RunStatusBudgetExceeded: true, RunStatusExpired: true, }, RunStatusPauseRequested: { RunStatusPaused: true, RunStatusRunning: true, RunStatusCancelled: true, RunStatusFailed: true, RunStatusBudgetExceeded: true, RunStatusExpired: true, }, RunStatusPaused: { RunStatusRunning: true, RunStatusNeedsReplan: true, RunStatusCancelled: true, RunStatusFailed: true, RunStatusExpired: true, }, RunStatusNeedsReplan: { RunStatusRunning: true, RunStatusCancelled: true, RunStatusFailed: true, RunStatusExpired: true, }, RunStatusSucceeded: {}, RunStatusFailed: {}, RunStatusCancelled: {}, RunStatusBudgetExceeded: {}, RunStatusExpired: {}, }
var ServiceTransitions = map[ServiceStatus]map[ServiceStatus]bool{ ServiceStatusDeclared: { ServiceStatusStarting: true, ServiceStatusFailed: true, }, ServiceStatusStarting: { ServiceStatusReady: true, ServiceStatusFailed: true, ServiceStatusStopped: true, }, ServiceStatusReady: { ServiceStatusUnhealthy: true, ServiceStatusStopping: true, ServiceStatusFailed: true, }, ServiceStatusUnhealthy: { ServiceStatusReady: true, ServiceStatusFenced: true, ServiceStatusStopping: true, ServiceStatusFailed: true, }, ServiceStatusFenced: { ServiceStatusStopping: true, ServiceStatusFailed: true, }, ServiceStatusStopping: { ServiceStatusStopped: true, ServiceStatusFailed: true, }, ServiceStatusStopped: {}, ServiceStatusFailed: {}, }
ServiceTransitions defines legal ServiceStatus transitions.
var WorkflowTransitions = map[WorkflowStatus]map[WorkflowStatus]bool{ WorkflowStatusPending: { WorkflowStatusRunning: true, WorkflowStatusCancelled: true, WorkflowStatusFailed: true, }, WorkflowStatusRunning: { WorkflowStatusPauseRequested: true, WorkflowStatusSucceeded: true, WorkflowStatusFailed: true, WorkflowStatusCancelled: true, WorkflowStatusBudgetExceeded: true, WorkflowStatusExpired: true, }, WorkflowStatusPauseRequested: { WorkflowStatusPaused: true, WorkflowStatusRunning: true, WorkflowStatusCancelled: true, WorkflowStatusFailed: true, WorkflowStatusBudgetExceeded: true, WorkflowStatusExpired: true, }, WorkflowStatusPaused: { WorkflowStatusRunning: true, WorkflowStatusNeedsReplan: true, WorkflowStatusCancelled: true, WorkflowStatusFailed: true, WorkflowStatusExpired: true, }, WorkflowStatusNeedsReplan: { WorkflowStatusRunning: true, WorkflowStatusCancelled: true, WorkflowStatusFailed: true, WorkflowStatusExpired: true, }, WorkflowStatusSucceeded: {}, WorkflowStatusFailed: {}, WorkflowStatusCancelled: {}, WorkflowStatusExpired: {}, WorkflowStatusBudgetExceeded: {}, }
WorkflowTransitions defines legal WorkflowStatus transitions.
Functions ¶
func AttemptIDValidate ¶
AttemptIDValidate returns true if the attempt ID looks valid (non-empty, at- prefix).
func MarshalCanonical ¶
MarshalCanonical marshals v to canonical JSON (sorted keys, no indentation).
func NowMonotonicMs ¶
NowMonotonicMs returns the monotonic millisecond timestamp for the given clock, or time.Now().UnixMilli() when clock is nil. This is the convenience helper call sites use to feed EffectiveOperationDeadlineMs / ActiveTime- RemainingMs.
func UnmarshalStrict ¶
UnmarshalStrict unmarshals JSON into v, rejecting unknown fields.
func ValidateAttemptTransition ¶
func ValidateAttemptTransition(from, to AttemptStatus) error
ValidateAttemptTransition validates that an AttemptStatus transition is legal.
func ValidateChildBatchTransition ¶
func ValidateChildBatchTransition(from, to ChildBatchStatus) error
ValidateChildBatchTransition validates that a ChildBatchStatus transition is legal.
func ValidateIDPrefix ¶
ValidateIDPrefix returns true if id is non-empty and starts with the given prefix.
func ValidateNodeTransition ¶
func ValidateNodeTransition(from, to NodeStatus) error
ValidateNodeTransition validates that a NodeStatus transition is legal.
func ValidateResumeCheckpoint ¶
func ValidateResumeCheckpoint( cp *ResumeCheckpointData, expectedRunID RunID, policyDigest string, imageDigest string, ) error
ValidateResumeCheckpoint verifies a checkpoint is compatible with the current attempt's policy/image/catalog. Returns nil if compatible.
func ValidateRunTransition ¶
ValidateRunTransition validates that a RunStatus transition is legal. Returns nil if valid, or a *TransitionError if invalid.
func ValidateServiceTransition ¶
func ValidateServiceTransition(from, to ServiceStatus) error
ValidateServiceTransition validates that a ServiceStatus transition is legal.
func ValidateWorkflowTransition ¶
func ValidateWorkflowTransition(from, to WorkflowStatus) error
ValidateWorkflowTransition validates that a WorkflowStatus transition is legal.
Types ¶
type ActiveTimeLedger ¶
type ActiveTimeLedger struct {
SchemaVersion string `json:"schema_version"`
// Total consumed active time (RUNNING + PAUSE_REQUESTED).
ConsumedMs int64 `json:"consumed_ms"`
// Currently running segment start (nil if frozen/paused).
// Monotonic millisecond timestamp.
RunningSegmentStartMs *int64 `json:"running_segment_start_ms,omitempty"`
// SegmentStartWallMs is the wall-clock time (Unix millis) recorded
// alongside RunningSegmentStartMs. On daemon restart, if the monotonic
// clock has reset (nowMs < segStart), the wall-clock delta is used
// instead to avoid charging an arbitrary duration (F20).
SegmentStartWallMs *int64 `json:"segment_start_wall_ms,omitempty"`
// Frozen state: when PAUSED or NEEDS_REPLAN, the consumed time at freeze.
FrozenConsumedMs int64 `json:"frozen_consumed_ms,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
ActiveTimeLedger tracks active execution time for a workflow.
type AdmissionOutcome ¶
type AdmissionOutcome int
AdmissionOutcome represents the result of attempting to admit an invocation.
const ( AdmissionAccepted AdmissionOutcome = iota // 0 AdmissionIdempotentReplay // 1 AdmissionAlreadyRunning // 2 AdmissionIdempotencyConflict // 3 AdmissionDeploymentInactive // 4 )
func (AdmissionOutcome) MarshalJSON ¶
func (o AdmissionOutcome) MarshalJSON() ([]byte, error)
AdmissionOutcome.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AdmissionOutcome) String ¶
func (o AdmissionOutcome) String() string
AdmissionOutcome.String returns the string representation.
func (*AdmissionOutcome) UnmarshalJSON ¶
func (o *AdmissionOutcome) UnmarshalJSON(data []byte) error
AdmissionOutcome.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AdmissionOutcome) Valid ¶
func (o AdmissionOutcome) Valid() bool
AdmissionOutcome.Valid reports whether the admission outcome value is valid.
type AggregateUsageSummary ¶
type AggregateUsageSummary struct {
SchemaVersion string `json:"schema_version"`
TotalModelCalls int `json:"total_model_calls"`
TotalInputTokens int64 `json:"total_input_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
TotalCostDecimal string `json:"total_cost_decimal"`
TotalActiveTimeMs int64 `json:"total_active_time_ms"`
}
AggregateUsageSummary aggregates usage across an entire workflow.
type AliasRecord ¶
type AliasRecord struct {
SchemaVersion string `json:"schema_version"`
Alias string `json:"alias"`
TargetDeploymentID DeploymentID `json:"target_deployment_id"`
TargetVersion string `json:"target_version"`
Generation int64 `json:"generation"`
UpdatedAt time.Time `json:"updated_at"`
UpdatedBy string `json:"updated_by"`
}
AliasRecord is a mutable, generation-checked pointer to a deployment version.
type ArtifactID ¶
type ArtifactID string
ArtifactID identifies an artifact.
func (ArtifactID) MarshalText ¶
func (id ArtifactID) MarshalText() ([]byte, error)
ArtifactID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ArtifactID) Scan ¶
func (id *ArtifactID) Scan(src interface{}) error
ArtifactID.Scan scans a database value into artifact id.
It returns an error if the operation fails or inputs are invalid.
func (ArtifactID) String ¶
func (id ArtifactID) String() string
ArtifactID.String returns the string representation.
func (*ArtifactID) UnmarshalText ¶
func (id *ArtifactID) UnmarshalText(b []byte) error
ArtifactID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type ArtifactMetadata ¶
type ArtifactMetadata struct {
SchemaVersion string `json:"schema_version"`
ArtifactID ArtifactID `json:"artifact_id"`
RunID RunID `json:"run_id"`
AttemptID AttemptID `json:"attempt_id"`
// Relative path beneath the artifact root (POSIX).
RelativePath string `json:"relative_path"`
// Byte size.
ByteSize int64 `json:"byte_size"`
// SHA-256 hex digest.
Digest string `json:"digest"`
// Media type (best-effort, from file extension).
MediaType string `json:"media_type,omitempty"`
// Creating attempt.
CreatingAttempt AttemptID `json:"creating_attempt"`
// Last update timestamp.
UpdatedAt time.Time `json:"updated_at"`
}
ArtifactMetadata records the durable metadata for an accepted artifact.
type ArtifactRef ¶
type ArtifactRef struct {
SchemaVersion string `json:"schema_version"`
ArtifactID ArtifactID `json:"artifact_id"`
WorkflowID WorkflowID `json:"workflow_id"`
NodeID *NodeID `json:"node_id,omitempty"`
RunID RunID `json:"run_id"`
AttemptID AttemptID `json:"attempt_id"`
// Immutable logical reference (e.g., "output.json", "checkpoint.bin").
LogicalRef string `json:"logical_ref"`
// Digest (SHA-256 hex).
Digest string `json:"digest"`
// Byte size.
ByteSize int64 `json:"byte_size"`
// Media type (e.g., "application/json").
MediaType string `json:"media_type"`
// Schema reference (when declared).
Schema string `json:"schema,omitempty"`
// Classification.
Classification DataClassification `json:"classification"`
CreatedAt time.Time `json:"created_at"`
}
ArtifactRef is an immutable logical reference to an artifact. It NEVER exposes a host/container path.
type ArtifactWorkspace ¶
type ArtifactWorkspace struct {
// contains filtered or unexported fields
}
ArtifactWorkspace manages the bounded artifact directory for a run.
func NewArtifactWorkspace ¶
func NewArtifactWorkspace(root string, runID RunID) (*ArtifactWorkspace, error)
NewArtifactWorkspace creates an artifact workspace manager for a run. The root is typically ~/.agentpaas/state/runs/<run_id>/artifacts/.
func (*ArtifactWorkspace) ListMetadata ¶
func (aw *ArtifactWorkspace) ListMetadata() []*ArtifactMetadata
ListMetadata returns all accepted artifact metadata.
func (*ArtifactWorkspace) RemoveUnreferenced ¶
func (aw *ArtifactWorkspace) RemoveUnreferenced() error
RemoveUnreferenced removes files in the artifact dir that were never accepted into durable metadata. Called during fencing/finalization.
func (*ArtifactWorkspace) Root ¶
func (aw *ArtifactWorkspace) Root() string
Root returns the host filesystem root for the artifact directory.
func (*ArtifactWorkspace) TotalSize ¶
func (aw *ArtifactWorkspace) TotalSize() int64
TotalSize returns the total bytes of accepted artifacts.
func (*ArtifactWorkspace) ValidateAndAccept ¶
func (aw *ArtifactWorkspace) ValidateAndAccept( ctx context.Context, relPath string, attemptID AttemptID, ) (*ArtifactMetadata, error)
ValidateAndAccept validates, hashes, and accepts an artifact reference. The file must exist beneath the artifact root (no symlinks, no traversal). Returns the artifact metadata on success.
type AttemptID ¶
type AttemptID string
AttemptID identifies an attempt within a run.
func NewAttemptID ¶
NewAttemptID generates a cryptographically random attempt ID.
func (AttemptID) MarshalText ¶
AttemptID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*AttemptID) Scan ¶
AttemptID.Scan scans a database value into attempt id.
It returns an error if the operation fails or inputs are invalid.
func (*AttemptID) UnmarshalText ¶
AttemptID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type AttemptLease ¶
type AttemptLease struct {
SchemaVersion string `json:"schema_version"`
LeaseID LeaseID `json:"lease_id"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
// Lease duration in milliseconds.
DurationMs int64 `json:"duration_ms"`
AcquiredAt time.Time `json:"acquired_at"`
ExpiresAt time.Time `json:"expires_at"`
LeaseToken string `json:"lease_token"`
}
AttemptLease represents a lease on an attempt.
type AttemptProgress ¶
type AttemptProgress struct {
SchemaVersion string `json:"schema_version"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
// Latest heartbeat.
LastPhase string `json:"last_phase"`
LastHeartbeat time.Time `json:"last_heartbeat"`
LastSequence int64 `json:"last_sequence"`
// Latest checkpoint reference.
LatestCheckpointID CheckpointID `json:"latest_checkpoint_id,omitempty"`
ResumeCapability *ResumeCapability `json:"resume_capability,omitempty"`
}
AttemptProgress is the live progress metadata for an attempt.
type AttemptRecord ¶
type AttemptRecord struct {
SchemaVersion string `json:"schema_version"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
WorkflowID WorkflowID `json:"workflow_id"`
Status AttemptStatus `json:"status"`
// Attempt number (1-based).
AttemptNumber int `json:"attempt_number"`
// Failure information.
FailureReason *FailureReason `json:"failure_reason,omitempty"`
FailureScope *FailureScope `json:"failure_scope,omitempty"`
RecoveryDisposition *RecoveryDisposition `json:"recovery_disposition,omitempty"`
ResumeCapability *ResumeCapability `json:"resume_capability,omitempty"`
// Lease.
Lease *AttemptLease `json:"lease,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TerminatedAt *time.Time `json:"terminated_at,omitempty"`
}
AttemptRecord represents a single attempt within a run.
type AttemptReport ¶
type AttemptReport struct {
SchemaVersion string `json:"schema_version"`
RunID RunID `json:"run_id"`
AttemptID AttemptID `json:"attempt_id"`
Status AttemptStatus `json:"status"`
Reason *FailureReason `json:"reason,omitempty"`
FailureScope *FailureScope `json:"failure_scope,omitempty"`
RecoveryDisposition *RecoveryDisposition `json:"recovery_disposition,omitempty"`
ResumeCapability *ResumeCapability `json:"resume_capability,omitempty"`
Progress *ProgressSummary `json:"progress,omitempty"`
Checkpoint *CheckpointSummary `json:"checkpoint,omitempty"`
Artifacts []ArtifactRef `json:"artifacts,omitempty"`
Time *TimeBudgetSummary `json:"time,omitempty"`
LLMBudget *LLMBudgetSummary `json:"llm_budget,omitempty"`
RouteDecisions []RouteDecision `json:"route_decisions,omitempty"`
RecommendedActions []string `json:"recommended_actions,omitempty"`
EvidenceRefs []string `json:"evidence_refs,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
AttemptReport is the portable report for a single attempt.
type AttemptStatus ¶
type AttemptStatus int
AttemptStatus represents the lifecycle status of an attempt.
const ( AttemptStatusPending AttemptStatus = iota // 0 AttemptStatusRunning // 1 AttemptStatusNeedsReplan // 2 AttemptStatusSucceeded // 3 AttemptStatusFailed // 4 AttemptStatusFenced // 5 AttemptStatusCancelled // 6 )
func AllAttemptStatuses ¶
func AllAttemptStatuses() []AttemptStatus
AllAttemptStatuses returns all valid AttemptStatus values.
func (AttemptStatus) IsTerminal ¶
func (s AttemptStatus) IsTerminal() bool
IsTerminal returns true for terminal attempt statuses.
func (AttemptStatus) MarshalJSON ¶
func (s AttemptStatus) MarshalJSON() ([]byte, error)
AttemptStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AttemptStatus) String ¶
func (s AttemptStatus) String() string
AttemptStatus.String returns the string representation.
func (*AttemptStatus) UnmarshalJSON ¶
func (s *AttemptStatus) UnmarshalJSON(data []byte) error
AttemptStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AttemptStatus) Valid ¶
func (s AttemptStatus) Valid() bool
AttemptStatus.Valid reports whether the attempt status value is valid.
type AuthorityScope ¶
type AuthorityScope string
AuthorityScope represents an administrative authority scope.
const ( AuthScopeDefault AuthorityScope = "default" AuthScopeControl AuthorityScope = "runs:control" AuthScopeAmendLimits AuthorityScope = "runs:amend_limits" )
func (AuthorityScope) MarshalJSON ¶
func (s AuthorityScope) MarshalJSON() ([]byte, error)
AuthorityScope.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AuthorityScope) String ¶
func (s AuthorityScope) String() string
AuthorityScope.String returns the string representation.
func (*AuthorityScope) UnmarshalJSON ¶
func (s *AuthorityScope) UnmarshalJSON(data []byte) error
AuthorityScope.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (AuthorityScope) Valid ¶
func (s AuthorityScope) Valid() bool
AuthorityScope.Valid reports whether the authority scope value is valid.
type Candidate ¶
type Candidate struct {
SchemaVersion string `json:"schema_version"`
ID string `json:"id"`
Role string `json:"role"` // primary, recovery
Provider string `json:"provider"`
Model string `json:"model"`
Location string `json:"location"` // local, cloud
Credential string `json:"credential,omitempty"`
UpstreamProviders []string `json:"upstream_providers,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
AuthNone bool `json:"auth_none,omitempty"`
}
Candidate describes a model candidate for routing.
type CheckpointID ¶
type CheckpointID string
CheckpointID identifies a checkpoint.
func (CheckpointID) MarshalText ¶
func (id CheckpointID) MarshalText() ([]byte, error)
CheckpointID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*CheckpointID) Scan ¶
func (id *CheckpointID) Scan(src interface{}) error
CheckpointID.Scan scans a database value into checkpoint id.
It returns an error if the operation fails or inputs are invalid.
func (CheckpointID) String ¶
func (id CheckpointID) String() string
CheckpointID.String returns the string representation.
func (*CheckpointID) UnmarshalText ¶
func (id *CheckpointID) UnmarshalText(b []byte) error
CheckpointID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type CheckpointStore ¶
type CheckpointStore interface {
// SaveCheckpoint atomically persists a semantic checkpoint.
// It must never mutate an existing checkpoint.
SaveCheckpoint(ctx context.Context, cp *SemanticCheckpoint) error
// GetCheckpoint retrieves a checkpoint by ID.
GetCheckpoint(ctx context.Context, checkpointID CheckpointID) (*SemanticCheckpoint, error)
// GetLatestCheckpoint returns the latest safe checkpoint for a given attempt.
GetLatestCheckpoint(ctx context.Context, attemptID AttemptID) (*SemanticCheckpoint, error)
}
CheckpointStore defines persistence operations for semantic checkpoints.
type CheckpointSummary ¶
type CheckpointSummary struct {
SchemaVersion string `json:"schema_version"`
CheckpointID CheckpointID `json:"checkpoint_id"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
ActionCount int `json:"action_count"`
TotalModelCalls int `json:"total_model_calls"`
CreatedAt time.Time `json:"created_at"`
}
CheckpointSummary describes a checkpoint.
type ChildBatch ¶
type ChildBatch struct {
SchemaVersion string `json:"schema_version"`
ChildBatchID ChildBatchID `json:"child_batch_id"`
WorkflowID WorkflowID `json:"workflow_id"`
ParentNodeID NodeID `json:"parent_node_id"`
Status ChildBatchStatus `json:"status"`
// Spawn request details.
SpawnRequest ChildSpawnRequest `json:"spawn_request"`
// Join policy.
JoinPolicy JoinPolicy `json:"join_policy"`
// Children allocated to this batch.
ChildRunIDs []RunID `json:"child_run_ids,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
ChildBatch represents a batch of child runs spawned by a parent.
type ChildBatchID ¶
type ChildBatchID string
ChildBatchID identifies a child batch.
func NewChildBatchID ¶
func NewChildBatchID() (ChildBatchID, error)
NewChildBatchID generates a cryptographically random child batch ID.
func (ChildBatchID) MarshalText ¶
func (id ChildBatchID) MarshalText() ([]byte, error)
ChildBatchID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ChildBatchID) Scan ¶
func (id *ChildBatchID) Scan(src interface{}) error
ChildBatchID.Scan scans a database value into child batch id.
It returns an error if the operation fails or inputs are invalid.
func (ChildBatchID) String ¶
func (id ChildBatchID) String() string
ChildBatchID.String returns the string representation.
func (*ChildBatchID) UnmarshalText ¶
func (id *ChildBatchID) UnmarshalText(b []byte) error
ChildBatchID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type ChildBatchStatus ¶
type ChildBatchStatus int
ChildBatchStatus represents the lifecycle status of a child batch.
const ( ChildBatchIntent ChildBatchStatus = iota // 0 ChildBatchAllocated // 1 ChildBatchRunning // 2 ChildBatchPauseRequested // 3 ChildBatchPaused // 4 ChildBatchJoining // 5 ChildBatchStopping // 6 ChildBatchStopped // 7 ChildBatchSucceeded // 8 ChildBatchFailed // 9 ChildBatchCancelled // 10 )
func AllChildBatchStatuses ¶
func AllChildBatchStatuses() []ChildBatchStatus
AllChildBatchStatuses returns all valid ChildBatchStatus values.
func (ChildBatchStatus) MarshalJSON ¶
func (s ChildBatchStatus) MarshalJSON() ([]byte, error)
ChildBatchStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ChildBatchStatus) String ¶
func (s ChildBatchStatus) String() string
ChildBatchStatus.String returns the string representation.
func (*ChildBatchStatus) UnmarshalJSON ¶
func (s *ChildBatchStatus) UnmarshalJSON(data []byte) error
ChildBatchStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ChildBatchStatus) Valid ¶
func (s ChildBatchStatus) Valid() bool
ChildBatchStatus.Valid reports whether the child batch status value is valid.
type ChildResult ¶
type ChildResult struct {
SchemaVersion string `json:"schema_version"`
ChildResultID ChildResultID `json:"child_result_id"`
ChildBatchID ChildBatchID `json:"child_batch_id"`
ChildRunID RunID `json:"child_run_id"`
Status RunStatus `json:"status"`
OutputJSON string `json:"output_json,omitempty"`
FailureReason *FailureReason `json:"failure_reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
ChildResult represents the result of a single child run.
type ChildResultID ¶
type ChildResultID string
ChildResultID identifies a child run result.
func NewChildResultID ¶
func NewChildResultID() (ChildResultID, error)
NewChildResultID generates a cryptographically random child result ID.
func (ChildResultID) MarshalText ¶
func (id ChildResultID) MarshalText() ([]byte, error)
ChildResultID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ChildResultID) Scan ¶
func (id *ChildResultID) Scan(src interface{}) error
ChildResultID.Scan scans a database value into child result id.
It returns an error if the operation fails or inputs are invalid.
func (ChildResultID) String ¶
func (id ChildResultID) String() string
ChildResultID.String returns the string representation.
func (*ChildResultID) UnmarshalText ¶
func (id *ChildResultID) UnmarshalText(b []byte) error
ChildResultID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type ChildSpawnRequest ¶
type ChildSpawnRequest struct {
SchemaVersion string `json:"schema_version"`
ChildPackageName string `json:"child_package_name"`
ChildPackageVersion string `json:"child_package_version"`
MaxFanOut int `json:"max_fan_out"`
MaxConcurrency int `json:"max_concurrency"`
InputJSONTemplate string `json:"input_json_template"`
}
ChildSpawnRequest describes a request to spawn child runs.
type Clock ¶
type Clock interface {
// Now returns the current wall-clock time in UTC.
Now() time.Time
// NowMonotonic returns a monotonic clock reading used for duration
// decisions. On most platforms this is time.Now(); the interface
// allows a fake clock in tests to keep the monotonic axis independent
// of the wall axis.
NowMonotonic() time.Time
}
Clock is the injectable clock abstraction. Now() returns a UTC wall-clock time for evidence timestamps; NowMonotonic() returns a monotonic clock reading for duration decisions (immune to wall-clock jumps). The split lets tests inject a FakeClock with independent wall and monotonic axes (b30-summary.md:382: "Timezone/wall-clock jump does not change monotonic duration behavior").
type ControlCommand ¶
type ControlCommand int
ControlCommand represents an operator command for a run/workflow.
const ( ControlCancel ControlCommand = iota // 0 ControlPause // 1 ControlResume // 2 ControlRestart // 3 ControlContinue // 4 ControlAmendLimits // 5 )
func (ControlCommand) MarshalJSON ¶
func (c ControlCommand) MarshalJSON() ([]byte, error)
ControlCommand.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ControlCommand) String ¶
func (c ControlCommand) String() string
ControlCommand.String returns the string representation.
func (*ControlCommand) UnmarshalJSON ¶
func (c *ControlCommand) UnmarshalJSON(data []byte) error
ControlCommand.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ControlCommand) Valid ¶
func (c ControlCommand) Valid() bool
ControlCommand.Valid reports whether the control command value is valid.
type ControlJournal ¶
type ControlJournal struct {
// contains filtered or unexported fields
}
ControlJournal is the per-attempt append-only control journal for a durable invoke job. It records InvokeJobEvent records (accepted, started, progress_ref, succeeded, failed, cancelled) with monotonic sequence numbers and per-event HMAC authentication.
B29-8 NOTE — Dual WAL formats (recovery precedence): The B27 progress journal (harness/progress.go JSONL) and the B29 event/inbox/approval WALs (trigger/durable_eventstore.go, runtime/inbox.go) are independent WAL formats with different recovery paths. On restart, the supervisor replays the B27 control journal first (for attempt lifecycle events), then replays B29 WALs for event store and inbox state. The B27 journal is the authoritative source for attempt state (pre- and post-B30). B29 WALs augment with event/inbox payloads but never override B27 journal assertions about attempt state/leases. Recovery precedence: B27 control journal > B29 event WAL > B29 inbox WAL.
SECURITY MODEL:
- The journal directory is 0700, created under the run state dir.
- Every event file is 0600, written atomically (temp + fsync + rename).
- Symlink traversal is rejected at write AND read time.
- The per-attempt HMAC key is 32 random bytes from crypto/rand, stored OUTSIDE the control directory at <stateRoot>/runs/<runID>/control-key with mode 0600. Python (the non-root worker) must not read it; full UID isolation is T04, but the file mode is enforced here and tested.
- Event payloads are bounded to 64KB.
- Sequence numbers are monotonic with no gaps.
The journal is safe to read after a daemon restart for reconciliation.
func NewControlJournal ¶
func NewControlJournal(stateRoot, runID, attemptID string) (*ControlJournal, error)
NewControlJournal opens (or creates) a per-attempt control journal rooted at <stateRoot>/runs/<runID>/control/<attemptID>. The HMAC key is loaded from (or generated into) <stateRoot>/runs/<runID>/control-key (0600).
stateRoot is the daemon state root (e.g. ~/.agentpaas/state). runID and attemptID are the per-run / per-attempt identifiers. Both are sanitised to single path components via safeID to prevent path traversal.
func (*ControlJournal) Append ¶
func (cj *ControlJournal) Append(event InvokeJobEvent) error
Append writes a single event atomically to the journal. The event's sequence must be exactly lastSeq+1 (no gaps, no duplicates). The HMAC is recomputed and stored alongside the event; on read-back the HMAC is verified. Oversized payloads (>64KB) are rejected.
func (*ControlJournal) Close ¶
func (cj *ControlJournal) Close() error
Close releases any held resources. Safe to call multiple times.
func (*ControlJournal) Read ¶
func (cj *ControlJournal) Read(fromSeq int64) ([]InvokeJobEvent, error)
Read returns all events with sequence >= fromSeq, in ascending sequence order. Every event's HMAC is verified on read-back; a tampered event causes an error and no events are returned.
type ControlRequest ¶
type ControlRequest struct {
SchemaVersion string `json:"schema_version"`
ControlRequestID ControlRequestID `json:"control_request_id"`
WorkflowID WorkflowID `json:"workflow_id"`
Command ControlCommand `json:"command"`
// Generation for compare-and-swap.
ExpectedGeneration int64 `json:"expected_generation"`
// For restart: the source exact deployment ref (default) or current alias.
TargetDeploymentRef string `json:"target_deployment_ref,omitempty"`
// For continue: recovery action.
RecoveryAction string `json:"recovery_action,omitempty"`
// Actor identity.
ActorIdentity string `json:"actor_identity"`
// Authority scope that permits this command.
AuthorityScope AuthorityScope `json:"authority_scope"`
IdempotencyKey string `json:"idempotency_key"`
CreatedAt time.Time `json:"created_at"`
}
ControlRequest represents an operator lifecycle command.
type ControlRequestID ¶
type ControlRequestID string
ControlRequestID identifies a control request.
func NewControlRequestID ¶
func NewControlRequestID() (ControlRequestID, error)
NewControlRequestID generates a cryptographically random control request ID.
func (ControlRequestID) MarshalText ¶
func (id ControlRequestID) MarshalText() ([]byte, error)
ControlRequestID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ControlRequestID) Scan ¶
func (id *ControlRequestID) Scan(src interface{}) error
ControlRequestID.Scan scans a database value into control request id.
It returns an error if the operation fails or inputs are invalid.
func (ControlRequestID) String ¶
func (id ControlRequestID) String() string
ControlRequestID.String returns the string representation.
func (*ControlRequestID) UnmarshalText ¶
func (id *ControlRequestID) UnmarshalText(b []byte) error
ControlRequestID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type Cost ¶
type Cost struct {
SchemaVersion string `json:"schema_version"`
AmountDecimal string `json:"amount_decimal"`
Currency string `json:"currency"`
}
Cost represents a monetary cost.
type DataClassification ¶
type DataClassification string
DataClassification represents the sensitivity level of data.
const ( ClassificationPublic DataClassification = "public" ClassificationInternal DataClassification = "internal" ClassificationConfidential DataClassification = "confidential" ClassificationRestricted DataClassification = "restricted" )
func AllDataClassifications ¶
func AllDataClassifications() []DataClassification
AllDataClassifications returns all valid DataClassification values in order.
func MaxClassification ¶
func MaxClassification(a, b DataClassification) DataClassification
MaxClassification returns the more restrictive of a and b.
func (DataClassification) Level ¶
func (c DataClassification) Level() int
Level returns a numeric level for ordering: public=0, internal=1, confidential=2, restricted=3.
func (DataClassification) MarshalJSON ¶
func (c DataClassification) MarshalJSON() ([]byte, error)
DataClassification.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (DataClassification) String ¶
func (c DataClassification) String() string
DataClassification.String returns the string representation.
func (*DataClassification) UnmarshalJSON ¶
func (c *DataClassification) UnmarshalJSON(data []byte) error
DataClassification.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (DataClassification) Valid ¶
func (c DataClassification) Valid() bool
Valid returns true if c is a known DataClassification.
type DeploymentID ¶
type DeploymentID string
DeploymentID identifies an immutable deployment version.
func NewDeploymentID ¶
func NewDeploymentID() (DeploymentID, error)
NewDeploymentID generates a cryptographically random deployment ID.
func (DeploymentID) MarshalText ¶
func (id DeploymentID) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
func (*DeploymentID) Scan ¶
func (id *DeploymentID) Scan(src interface{}) error
Scan implements database/sql.Scanner.
func (DeploymentID) String ¶
func (id DeploymentID) String() string
DeploymentID.String returns the string representation.
func (*DeploymentID) UnmarshalText ¶
func (id *DeploymentID) UnmarshalText(b []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type DeploymentRecord ¶
type DeploymentRecord struct {
SchemaVersion string `json:"schema_version"`
DeploymentID DeploymentID `json:"deployment_id"`
PackageName string `json:"package_name"`
PackageVersion string `json:"package_version"`
Generation int64 `json:"generation"`
Status DeploymentStatus `json:"status"`
MaxConcurrentRuns int `json:"max_concurrent_runs"`
// Immutable digests
BundleDigest string `json:"bundle_digest"`
PolicyDigest string `json:"policy_digest"`
ImageLockDigest string `json:"image_lock_digest"`
ProvenanceDigest string `json:"provenance_digest"`
// For workflow deployments: exact version/digest of every statically
// declared stage, MCP service, and child-allowlist package.
NestedPackageDigests map[string]string `json:"nested_package_digests,omitempty"`
// Audit references
CreatedAt time.Time `json:"created_at"`
ActivatedAt *time.Time `json:"activated_at,omitempty"`
DeactivatedAt *time.Time `json:"deactivated_at,omitempty"`
CreatedBy string `json:"created_by"`
}
DeploymentRecord is the immutable record of a deployment version.
type DeploymentStatus ¶
type DeploymentStatus int
DeploymentStatus represents the lifecycle status of a deployment.
const ( DeploymentActive DeploymentStatus = iota // 0 DeploymentInactive // 1 )
func (DeploymentStatus) MarshalJSON ¶
func (s DeploymentStatus) MarshalJSON() ([]byte, error)
DeploymentStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (DeploymentStatus) String ¶
func (s DeploymentStatus) String() string
DeploymentStatus.String returns the string representation.
func (*DeploymentStatus) UnmarshalJSON ¶
func (s *DeploymentStatus) UnmarshalJSON(data []byte) error
DeploymentStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (DeploymentStatus) Valid ¶
func (s DeploymentStatus) Valid() bool
DeploymentStatus.Valid reports whether the deployment status value is valid.
type DeploymentStore ¶
type DeploymentStore interface {
// CreateDeployment persists a new deployment record.
CreateDeployment(ctx context.Context, dep *DeploymentRecord) error
// GetDeployment retrieves a deployment by ID.
GetDeployment(ctx context.Context, deploymentID DeploymentID) (*DeploymentRecord, error)
// ListDeployments returns all deployments.
ListDeployments(ctx context.Context) ([]*DeploymentRecord, error)
// SetDeploymentStatus atomically updates the deployment status.
// The generation parameter enables compare-and-swap.
SetDeploymentStatus(ctx context.Context, deploymentID DeploymentID, status DeploymentStatus, expectedGeneration int64) error
// CompareAndSwapAlias atomically updates an alias record.
// Returns an error if the generation does not match.
CompareAndSwapAlias(ctx context.Context, alias *AliasRecord) error
// ResolveAlias returns the deployment ID that the alias currently points to.
ResolveAlias(ctx context.Context, alias string) (*AliasRecord, error)
// ListAliases returns all alias records.
ListAliases(ctx context.Context) ([]*AliasRecord, error)
// AdmitInvocation performs the one atomic admission operation:
// idempotency lookup, canonical-intent comparison, alias/exact and
// nested-snapshot resolution, active-status check, top-level concurrency
// check, invocation record creation, topology-specific workflow/node/run
// identity creation, and first durable READY launch-intent transaction.
AdmitInvocation(ctx context.Context, request *InvocationRequest, expectedDeploymentGeneration int64) (*InvocationReceipt, error)
// GetInvocationByIdempotency retrieves a previous invocation result for
// idempotency replay.
GetInvocationByIdempotency(ctx context.Context, callerIdentity, idempotencyKey string) (*InvocationReceipt, error)
// ListInvocations lists all invocations.
ListInvocations(ctx context.Context) ([]*InvocationReceipt, error)
}
DeploymentStore defines the durable storage interface for deployments, aliases, and invocation admission.
type DesiredState ¶
type DesiredState struct {
SchemaVersion string `json:"schema_version"`
WorkflowID WorkflowID `json:"workflow_id"`
DesiredCommand ControlCommand `json:"desired_command"`
ControlRequestID ControlRequestID `json:"control_request_id"`
Generation int64 `json:"generation"`
// Cancellation precedence: true when cancel wins over pause/resume.
CancelPrecedence bool `json:"cancel_precedence"`
CreatedAt time.Time `json:"created_at"`
}
DesiredState represents the operator-desired lifecycle state.
type DurableIdempotencyRecord ¶
type DurableIdempotencyRecord struct {
SchemaVersion string `json:"schema_version"`
InvocationID InvocationID `json:"invocation_id"`
CallerIdentity string `json:"caller_identity"`
IdempotencyKey string `json:"idempotency_key"`
// Canonical intent digest for comparison.
InvocationIntentDigest string `json:"invocation_intent_digest"`
// Outcome of the original admission.
Outcome AdmissionOutcome `json:"outcome"`
CreatedAt time.Time `json:"created_at"`
}
DurableIdempotencyRecord stores the data needed to detect idempotent replays.
type FailureReason ¶
type FailureReason int
FailureReason categorises why an attempt or run failed.
const ( FailureModelTimeout FailureReason = iota // 0 FailureModelConnectionFailed // 1 FailureModelRateLimited // 2 FailureModelServiceError // 3 FailureModelContextLimit // 4 FailureModelOutputLimit // 5 FailureModelMalformedJSON // 6 FailureModelIdentityMismatch // 7 FailureModelQuotaExhausted // 9 FailureNoEligibleTarget // 10 FailureAttemptTimeExhausted // 11 FailureStallTimeout // 12 FailureNoProgressGuardrail // 13 FailureRepeatedActionGuardrail // 14 FailureLLMBudgetExhausted // 15 FailureActiveTimeExhausted // 16 FailurePolicyDenied // 17 FailureExternalDependencyFailed // 18 FailureAgentException // 19 FailureDaemonRestarted // 21 FailureUserCancelled // 22 FailureMCPProtocolError // 24 FailureHandoffMissing // 25 FailureHandoffInvalid // 26 FailureChildSpawnDenied // 27 FailureChildBatchFailed // 28 FailureWorkflowResourceExhausted // 29 )
func AllFailureReasons ¶
func AllFailureReasons() []FailureReason
AllFailureReasons returns all valid FailureReason values.
func (FailureReason) MarshalJSON ¶
func (r FailureReason) MarshalJSON() ([]byte, error)
FailureReason.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (FailureReason) String ¶
func (r FailureReason) String() string
FailureReason.String returns the string representation.
func (*FailureReason) UnmarshalJSON ¶
func (r *FailureReason) UnmarshalJSON(data []byte) error
FailureReason.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (FailureReason) Valid ¶
func (r FailureReason) Valid() bool
FailureReason.Valid reports whether the failure reason value is valid.
type FailureScope ¶
type FailureScope int
FailureScope categorises where a failure originated.
const ( FailureScopeModelCall FailureScope = iota // 0 FailureScopeWorker // 1 FailureScopeBudget // 2 FailureScopePolicy // 3 FailureScopeCredential // 4 FailureScopeExternal // 5 FailureScopePlatform // 6 FailureScopeWorkflow // 7 FailureScopeMCPService // 8 FailureScopeHandoff // 9 FailureScopeChildBatch // 10 )
func AllFailureScopes ¶
func AllFailureScopes() []FailureScope
AllFailureScopes returns all valid FailureScope values.
func (FailureScope) MarshalJSON ¶
func (s FailureScope) MarshalJSON() ([]byte, error)
FailureScope.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (FailureScope) String ¶
func (s FailureScope) String() string
FailureScope.String returns the string representation.
func (*FailureScope) UnmarshalJSON ¶
func (s *FailureScope) UnmarshalJSON(data []byte) error
FailureScope.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (FailureScope) Valid ¶
func (s FailureScope) Valid() bool
FailureScope.Valid reports whether the failure scope value is valid.
type FakeClock ¶
type FakeClock struct {
// contains filtered or unexported fields
}
FakeClock is a test clock with independent wall and monotonic axes and manual timer advancement. Now() returns the wall axis (settable via SetWall); NowMonotonic() returns the monotonic axis (advanceable via AdvanceMonotonic). Timers scheduled via After/NewTimer fire in declaration-independent order as the monotonic axis advances.
The wall and monotonic axes are deliberately decoupled so that tests can simulate wall-clock jumps (forward or backward) without affecting duration arithmetic (b30-summary.md:382). This is what the T08 fake-clock 24h / 100-turn test relies on.
func NewFakeClock ¶
NewFakeClock constructs a FakeClock whose wall and monotonic axes both start at initial. The two axes are independent thereafter: SetWall moves only the wall axis, AdvanceMonotonic moves only the monotonic axis.
func (*FakeClock) AdvanceMonotonic ¶
AdvanceMonotonic advances the monotonic axis by d and fires any timers whose deadline has been reached, in deadline order. Timers fire exactly once. Negative d is a no-op (monotonic time does not move backward).
func (*FakeClock) After ¶
After schedules a one-shot timer that fires after d on the monotonic axis.
func (*FakeClock) NewTimer ¶
func (c *FakeClock) NewTimer(d time.Duration) TimerHandle
NewTimer schedules a one-shot timer handle on the monotonic axis.
func (*FakeClock) NowMonotonic ¶
NowMonotonic returns the monotonic axis.
func (*FakeClock) NowMonotonicUnixMs ¶
NowMonotonicUnixMs returns the monotonic axis as a Unix millisecond timestamp, which is what TimeEnvelope segment accounting expects.
type HandoffEnvelope ¶
type HandoffEnvelope struct {
SchemaVersion string `json:"schema_version"`
HandoffID HandoffID `json:"handoff_id"`
WorkflowID WorkflowID `json:"workflow_id"`
SourceNodeID NodeID `json:"source_node_id"`
TargetNodeID NodeID `json:"target_node_id"`
// Structured context (JSON).
ContextJSON string `json:"context_json"`
// Artifact references.
ArtifactRefs []ArtifactRef `json:"artifact_refs,omitempty"`
// Classification is at least the most restrictive of producer declaration,
// context, and referenced artifacts.
Classification DataClassification `json:"classification"`
CreatedAt time.Time `json:"created_at"`
}
HandoffEnvelope represents a handoff between stages with structured context and artifact references.
type HandoffID ¶
type HandoffID string
HandoffID identifies a handoff between stages.
func NewHandoffID ¶
NewHandoffID generates a cryptographically random handoff ID.
func (HandoffID) MarshalText ¶
HandoffID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*HandoffID) Scan ¶
HandoffID.Scan scans a database value into handoff id.
It returns an error if the operation fails or inputs are invalid.
func (*HandoffID) UnmarshalText ¶
HandoffID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type InvocationID ¶
type InvocationID string
InvocationID identifies a durable invocation.
func NewInvocationID ¶
func NewInvocationID() (InvocationID, error)
NewInvocationID generates a cryptographically random invocation ID.
func (InvocationID) MarshalText ¶
func (id InvocationID) MarshalText() ([]byte, error)
InvocationID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*InvocationID) Scan ¶
func (id *InvocationID) Scan(src interface{}) error
InvocationID.Scan scans a database value into invocation id.
It returns an error if the operation fails or inputs are invalid.
func (InvocationID) String ¶
func (id InvocationID) String() string
InvocationID.String returns the string representation.
func (*InvocationID) UnmarshalText ¶
func (id *InvocationID) UnmarshalText(b []byte) error
InvocationID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type InvocationReceipt ¶
type InvocationReceipt struct {
SchemaVersion string `json:"schema_version"`
InvocationID InvocationID `json:"invocation_id"`
WorkflowID WorkflowID `json:"workflow_id"`
RunID RunID `json:"run_id"`
// Resolved exact deployment identity at admission time.
ResolvedDeploymentID DeploymentID `json:"resolved_deployment_id"`
ResolvedDeploymentVersion string `json:"resolved_deployment_version"`
ResolvedDeploymentDigest string `json:"resolved_deployment_digest"`
// Nested package identities captured at admission.
NestedPackageDigests map[string]string `json:"nested_package_digests,omitempty"`
// Requested reference as supplied by the caller.
RequestedDeploymentRef string `json:"requested_deployment_ref"`
// Canonical invocation-intent digest over the deployment reference,
// input, initial ceilings, and creation options.
InvocationIntentDigest string `json:"invocation_intent_digest"`
// Caller identity.
CallerIdentity string `json:"caller_identity"`
// Initial ceilings.
InitialMaxActiveDurationMs int64 `json:"initial_max_active_duration_ms"`
InitialAttemptLeaseMs int64 `json:"initial_attempt_lease_ms"`
InitialMaxCostUsdDecimal string `json:"initial_max_cost_usd_decimal"`
// Timestamp.
AdmittedAt time.Time `json:"admitted_at"`
}
InvocationReceipt is the durable record returned on admission.
type InvocationRequest ¶
type InvocationRequest struct {
SchemaVersion string `json:"schema_version"`
// Requested deployment reference (alias or exact version).
RequestedDeploymentRef string `json:"requested_deployment_ref"`
// Bounded input JSON.
InputJSON string `json:"input_json"`
InputDigest string `json:"input_digest"`
// Initial ceilings.
InitialMaxActiveDurationMs int64 `json:"initial_max_active_duration_ms"`
InitialAttemptLeaseMs int64 `json:"initial_attempt_lease_ms"`
InitialMaxCostUsdDecimal string `json:"initial_max_cost_usd_decimal"`
// Creation options digest captures all options that can change
// execution or authority.
CreationOptionsDigest string `json:"creation_options_digest"`
// Idempotency key (required by API).
IdempotencyKey string `json:"idempotency_key"`
// Caller identity for scoping idempotency lookup.
CallerIdentity string `json:"caller_identity"`
}
InvocationRequest represents a durable invocation request.
type InvokeJob ¶
type InvokeJob struct {
SchemaVersion string `json:"schema_version"`
// Identity chain. AttemptID is empty until the T05 supervisor claim
// creates the attempt; the daemon writes the job envelope with an empty
// attempt at the READY launch-intent transaction and fills it on claim.
InvocationID InvocationID `json:"invocation_id"`
WorkflowID WorkflowID `json:"workflow_id"`
RunID RunID `json:"run_id"`
AttemptID AttemptID `json:"attempt_id,omitempty"`
// Resolved exact deployment identity at admission time.
ResolvedDeploymentID DeploymentID `json:"resolved_deployment_id"`
ResolvedDeploymentVersion string `json:"resolved_deployment_version"`
ResolvedDeploymentDigest string `json:"resolved_deployment_digest"`
// Nested package identities captured at admission (workflow deployments).
NestedPackageDigests map[string]string `json:"nested_package_digests,omitempty"`
// Bounded input. InputPayload is the bounded input JSON (subject to the
// same size cap as InvocationRequest.InputJSON); InputDigest is its
// canonical digest for tamper detection.
InputDigest string `json:"input_digest"`
InputPayload string `json:"input_payload,omitempty"`
// Initial ceilings narrowed from the workflow-level authority.
InitialMaxActiveDurationMs int64 `json:"initial_max_active_duration_ms"`
InitialAttemptLeaseMs int64 `json:"initial_attempt_lease_ms"`
InitialMaxCostUsdDecimal string `json:"initial_max_cost_usd_decimal"`
// B30-T04 policy-derived resource ceilings. CPUQuotaSeconds is the
// per-attempt CPU-time budget (RLIMIT_CPU); 0 means unlimited CPU
// (bounded by the container CFS quota). MaxPIDs is the per-attempt
// process-count limit (RLIMIT_NPROC); 0 means an explicit policy
// decision to forbid ALL subprocesses. These are applied by the
// harness Python runner (see apply_resource_limits) and the runtime
// driver container spec (MemoryLimitBytes / NanoCPUs / PidsLimit).
CPUQuotaSeconds int64 `json:"cpu_quota_seconds,omitempty"`
MaxPIDs int `json:"max_pids,omitempty"`
// Progress journal configuration: root of the per-attempt control
// journal directory (0700) under the run state dir.
ProgressJournalRoot string `json:"progress_journal_root,omitempty"`
// Artifact root for this run's durable artifact store.
ArtifactRoot string `json:"artifact_root,omitempty"`
// Compatibility-safe SDK configuration (JSON). Contains only
// compatibility/version hints — never credentials.
SDKConfig string `json:"sdk_config,omitempty"`
// CredentialValue is intentionally empty and exists ONLY as a compile-
// time guard: any code that attempts to set a credential on the job will
// be caught by the TestInvokeJob_TypeFields assertion. Do not remove.
CredentialValue string `json:"-"`
// CreationOptionsDigest mirrors the invocation request's
// creation-options digest for authority comparison on replay.
CreationOptionsDigest string `json:"creation_options_digest,omitempty"`
// CallerIdentity scopes idempotency lookup at the job level.
CallerIdentity string `json:"caller_identity,omitempty"`
// IdempotencyKey is the caller-supplied exactly-once key.
IdempotencyKey string `json:"idempotency_key,omitempty"`
// CreatedAt is when the daemon materialised the job envelope.
CreatedAt time.Time `json:"created_at"`
}
InvokeJob is the durable per-attempt invocation envelope passed from the daemon into a standalone durable worker. It is materialised from an admitted InvocationReceipt at the supervisor claim transition (T05) and persisted under the per-run state directory.
SECURITY: InvokeJob deliberately carries NO raw credential value. Identity keys and gateway secrets are never embedded in the job envelope, the returned material, or the control journal (spec b30-summary.md line 114). Credentials are injected out-of-band via the protected secret-grant path.
type InvokeJobEvent ¶
type InvokeJobEvent struct {
SchemaVersion string `json:"schema_version"`
// Sequence is the 1-based monotonic event sequence; gaps are rejected.
Sequence int64 `json:"sequence"`
// Timestamp of the event.
Timestamp time.Time `json:"timestamp"`
// EventKind classifies the event.
EventKind InvokeJobEventKind `json:"event_kind"`
// HMAC over (sequence || timestamp || event_kind || payload) using the
// per-attempt control key. Verified on read-back.
HMAC string `json:"hmac"`
// Payload is the bounded event payload JSON. Must be <= 64KB.
Payload string `json:"payload,omitempty"`
}
InvokeJobEvent is a single append-only control-journal event for one attempt. The journal is symlink-safe, HMAC'd per attempt, and bounded (no event > 64KB). Sequence numbers are monotonic with no gaps.
type InvokeJobEventKind ¶
type InvokeJobEventKind int
InvokeJobEventKind enumerates control-journal event kinds. These are stable string values; callers must not infer them from error strings.
const ( InvokeJobEventUnspecified InvokeJobEventKind = iota InvokeJobEventAccepted // durable admission committed, before container start InvokeJobEventStarted // container started, before Python handler entry InvokeJobEventProgressRef // progress checkpoint reference written InvokeJobEventSucceeded // terminal: result committed to protected store InvokeJobEventFailed // terminal: failure recorded InvokeJobEventCancelled // terminal: cancel precedence won )
func (InvokeJobEventKind) String ¶
func (k InvokeJobEventKind) String() string
String returns the stable name for an event kind.
type InvokeJobResult ¶
type InvokeJobResult struct {
SchemaVersion string `json:"schema_version"`
InvocationID InvocationID `json:"invocation_id"`
WorkflowID WorkflowID `json:"workflow_id"`
RunID RunID `json:"run_id"`
AttemptID AttemptID `json:"attempt_id,omitempty"`
// ResultDigest is the canonical digest of StructuredResult.
ResultDigest string `json:"result_digest"`
// ArtifactReferences are relative paths under the run artifact root.
ArtifactReferences []string `json:"artifact_references,omitempty"`
// StructuredResult is the bounded structured result JSON.
StructuredResult string `json:"structured_result,omitempty"`
// TerminalStatus is the terminal outcome.
TerminalStatus InvokeJobResultStatus `json:"terminal_status"`
// Timing.
StartedAt time.Time `json:"started_at,omitempty"`
FinishedAt time.Time `json:"finished_at,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
// FailureReason is set when TerminalStatus is Failed.
FailureReason string `json:"failure_reason,omitempty"`
}
InvokeJobResult is the terminal result of a durable invoke job. Written to the protected result store by the supervisor (T05/T08) on terminal transition. For T02 Part A, GetRunResult returns empty/not-found until T05 writes results.
type InvokeJobResultStatus ¶
type InvokeJobResultStatus int
InvokeJobResultStatus is the terminal status of an invoke job.
const ( InvokeJobResultUnspecified InvokeJobResultStatus = iota InvokeJobResultSucceeded InvokeJobResultFailed InvokeJobResultCancelled )
func (InvokeJobResultStatus) String ¶
func (s InvokeJobResultStatus) String() string
String returns the stable name for a result status.
type JoinPolicy ¶
type JoinPolicy struct {
SchemaVersion string `json:"schema_version"`
// join_all: wait for all, all_first: first result triggers join.
Mode string `json:"mode"` // join_all, all_first
}
JoinPolicy describes how child results are joined.
type LLMBudgetSummary ¶
type LLMBudgetSummary struct {
SchemaVersion string `json:"schema_version"`
TotalTokens int64 `json:"total_tokens"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
TotalCostDecimal string `json:"total_cost_decimal"`
RemainingCostDecimal string `json:"remaining_cost_decimal"`
ModelCalls int `json:"model_calls"`
}
LLMBudgetSummary describes LLM budget usage.
type LeaseID ¶
type LeaseID string
LeaseID identifies an opaque fencing token.
func NewLeaseID ¶
NewLeaseID generates a cryptographically random opaque fencing token. Callers must never supply their own lease IDs; stores overwrite any caller-selected lease identity with NewLeaseID.
func (LeaseID) MarshalText ¶
LeaseID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*LeaseID) Scan ¶
LeaseID.Scan scans a database value into lease id.
It returns an error if the operation fails or inputs are invalid.
func (*LeaseID) UnmarshalText ¶
LeaseID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type LimitAmendment ¶
type LimitAmendment struct {
SchemaVersion string `json:"schema_version"`
AmendmentID LimitAmendmentID `json:"amendment_id"`
WorkflowID WorkflowID `json:"workflow_id"`
ExpectedAuthorityGeneration int64 `json:"expected_authority_generation"`
// Absolute, increase-only values (optional, zero=unchanged).
NewMaxActiveDurationMs int64 `json:"new_max_active_duration_ms,omitempty"`
NewCurrentAttemptLeaseMs int64 `json:"new_current_attempt_lease_ms,omitempty"`
NewMaxLLMSpendDecimal string `json:"new_max_llm_spend_decimal,omitempty"`
// Before/after ceiling snapshot.
BeforeMaxActiveDurationMs int64 `json:"before_max_active_duration_ms"`
BeforeMaxAttemptLeaseMs int64 `json:"before_max_attempt_lease_ms"`
BeforeMaxLLMSpendDecimal string `json:"before_max_llm_spend_decimal"`
AfterMaxActiveDurationMs int64 `json:"after_max_active_duration_ms"`
AfterMaxAttemptLeaseMs int64 `json:"after_max_attempt_lease_ms"`
AfterMaxLLMSpendDecimal string `json:"after_max_llm_spend_decimal"`
// Spend reservation snapshot at amendment time.
ConsumedActiveTimeMs int64 `json:"consumed_active_time_ms"`
ReservedSpendDecimal string `json:"reserved_spend_decimal"`
Reason string `json:"reason"`
ActorIdentity string `json:"actor_identity"`
IdempotencyKey string `json:"idempotency_key"`
NewAuthorityGeneration int64 `json:"new_authority_generation"`
CreatedAt time.Time `json:"created_at"`
}
LimitAmendment represents an administrative limit ceiling amendment.
type LimitAmendmentID ¶
type LimitAmendmentID string
LimitAmendmentID identifies a limit amendment.
func NewLimitAmendmentID ¶
func NewLimitAmendmentID() (LimitAmendmentID, error)
NewLimitAmendmentID generates a cryptographically random limit amendment ID.
func (LimitAmendmentID) MarshalText ¶
func (id LimitAmendmentID) MarshalText() ([]byte, error)
LimitAmendmentID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*LimitAmendmentID) Scan ¶
func (id *LimitAmendmentID) Scan(src interface{}) error
LimitAmendmentID.Scan scans a database value into limit amendment id.
It returns an error if the operation fails or inputs are invalid.
func (LimitAmendmentID) String ¶
func (id LimitAmendmentID) String() string
LimitAmendmentID.String returns the string representation.
func (*LimitAmendmentID) UnmarshalText ¶
func (id *LimitAmendmentID) UnmarshalText(b []byte) error
LimitAmendmentID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type LocalStore ¶
type LocalStore struct {
// contains filtered or unexported fields
}
LocalStore is a protected file-backed implementation of DeploymentStore, RunStore, and WorkflowStore under a locked directory layout.
func OpenLocalStore ¶
func OpenLocalStore(root string, opts ...LocalStoreOption) (*LocalStore, error)
OpenLocalStore opens or initializes a local store rooted at root (typically ~/.agentpaas/state). Creates protected directory layout.
func (*LocalStore) AdmitInvocation ¶
func (s *LocalStore) AdmitInvocation(ctx context.Context, request *InvocationRequest, expectedDeploymentGeneration int64) (*InvocationReceipt, error)
LocalStore.AdmitInvocation admits invocation.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) AppendControlResult ¶
func (s *LocalStore) AppendControlResult(ctx context.Context, req *ControlRequest, result interface{}) error
LocalStore.AppendControlResult appends control result.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) AppendLedger ¶
LocalStore.AppendLedger appends ledger.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) AppendLimitAmendment ¶
func (s *LocalStore) AppendLimitAmendment(ctx context.Context, workflowID WorkflowID, expectedAuthorityGeneration int64, amendment *LimitAmendment) error
LocalStore.AppendLimitAmendment appends limit amendment.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ApplyTransition ¶
func (s *LocalStore) ApplyTransition(ctx context.Context, workflowID WorkflowID, expectedGeneration int64, command string) error
LocalStore.ApplyTransition applies transition.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CommitChildResult ¶
func (s *LocalStore) CommitChildResult(ctx context.Context, result *ChildResult) error
LocalStore.CommitChildResult commits child result.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CommitHandoff ¶
func (s *LocalStore) CommitHandoff(ctx context.Context, handoff *HandoffEnvelope) error
LocalStore.CommitHandoff commits handoff.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CompareAndSwapAlias ¶
func (s *LocalStore) CompareAndSwapAlias(ctx context.Context, alias *AliasRecord) error
LocalStore.CompareAndSwapAlias compares and swap alias.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CreateAttempt ¶
func (s *LocalStore) CreateAttempt(ctx context.Context, attempt *AttemptRecord) error
LocalStore.CreateAttempt creates the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CreateChildBatch ¶
func (s *LocalStore) CreateChildBatch(ctx context.Context, batch *ChildBatch) error
LocalStore.CreateChildBatch creates the child batch.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CreateDeployment ¶
func (s *LocalStore) CreateDeployment(ctx context.Context, dep *DeploymentRecord) error
func (*LocalStore) CreateNode ¶
func (s *LocalStore) CreateNode(ctx context.Context, node *PipelineNode) error
LocalStore.CreateNode creates the node.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) CreateRun ¶
func (s *LocalStore) CreateRun(ctx context.Context, run *RunRecord) error
func (*LocalStore) CreateWorkflow ¶
func (s *LocalStore) CreateWorkflow(ctx context.Context, wf *WorkflowRecord) error
func (*LocalStore) GetActiveTimeLedger ¶
func (s *LocalStore) GetActiveTimeLedger(ctx context.Context, workflowID WorkflowID) (*ActiveTimeLedger, error)
GetActiveTimeLedger loads the workflow active-time ledger.
func (*LocalStore) GetActiveTimeLedgerGeneration ¶
func (s *LocalStore) GetActiveTimeLedgerGeneration(ctx context.Context, workflowID WorkflowID) (int64, error)
GetActiveTimeLedgerGeneration returns the file generation of the active-time ledger, for use with CAS writes via PutActiveTimeLedger.
func (*LocalStore) GetAttempt ¶
func (s *LocalStore) GetAttempt(ctx context.Context, attemptID AttemptID) (*AttemptRecord, error)
LocalStore.GetAttempt returns the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetAttemptGeneration ¶
GetAttemptGeneration returns the persisted envelope generation of the attempt record. The supervisor (B30-T05) uses this to drive compare-and-swap transitions on attempts whose AttemptRecord struct does not itself carry a Generation field.
func (*LocalStore) GetAttemptProgress ¶
func (s *LocalStore) GetAttemptProgress(ctx context.Context, attemptID AttemptID) (*AttemptProgress, error)
GetAttemptProgress retrieves the latest progress metadata for an attempt.
func (*LocalStore) GetCheckpoint ¶
func (s *LocalStore) GetCheckpoint(ctx context.Context, checkpointID CheckpointID) (*SemanticCheckpoint, error)
GetCheckpoint retrieves a checkpoint by ID.
func (*LocalStore) GetDeployment ¶
func (s *LocalStore) GetDeployment(ctx context.Context, deploymentID DeploymentID) (*DeploymentRecord, error)
LocalStore.GetDeployment returns the deployment.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetDesiredState ¶
func (s *LocalStore) GetDesiredState(ctx context.Context, workflowID WorkflowID) (*DesiredState, error)
LocalStore.GetDesiredState returns the desired state.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetHandoff ¶
func (s *LocalStore) GetHandoff(ctx context.Context, handoffID HandoffID) (*HandoffEnvelope, error)
LocalStore.GetHandoff returns the handoff.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetInvocationByIdempotency ¶
func (s *LocalStore) GetInvocationByIdempotency(ctx context.Context, callerIdentity, idempotencyKey string) (*InvocationReceipt, error)
LocalStore.GetInvocationByIdempotency returns the invocation by idempotency.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetLatestCheckpoint ¶
func (s *LocalStore) GetLatestCheckpoint(ctx context.Context, attemptID AttemptID) (*SemanticCheckpoint, error)
GetLatestCheckpoint returns the latest safe checkpoint for a given attempt. It scans the checkpoints directory for checkpoints with matching attempt_id and returns the one with the highest sequence number.
func (*LocalStore) GetNode ¶
func (s *LocalStore) GetNode(ctx context.Context, nodeID NodeID) (*PipelineNode, error)
LocalStore.GetNode returns the node.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetRun ¶
LocalStore.GetRun returns the run.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) GetRunGeneration ¶
GetRunGeneration returns the persisted envelope generation of the run record. The supervisor (B30-T05) uses this to drive compare-and-swap transitions on runs whose RunRecord struct does not itself carry a Generation field.
func (*LocalStore) GetWorkflow ¶
func (s *LocalStore) GetWorkflow(ctx context.Context, workflowID WorkflowID) (*WorkflowRecord, error)
LocalStore.GetWorkflow returns the workflow.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListAliases ¶
func (s *LocalStore) ListAliases(ctx context.Context) ([]*AliasRecord, error)
LocalStore.ListAliases lists the aliases.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListAttempts ¶
func (s *LocalStore) ListAttempts(ctx context.Context, runID RunID) ([]*AttemptRecord, error)
LocalStore.ListAttempts lists the attempts.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListChildBatches ¶
func (s *LocalStore) ListChildBatches(ctx context.Context, workflowID WorkflowID) ([]*ChildBatch, error)
LocalStore.ListChildBatches lists the child batches.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListChildResults ¶
func (s *LocalStore) ListChildResults(ctx context.Context, childBatchID ChildBatchID) ([]*ChildResult, error)
LocalStore.ListChildResults lists the child results.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListDeployments ¶
func (s *LocalStore) ListDeployments(ctx context.Context) ([]*DeploymentRecord, error)
LocalStore.ListDeployments lists the deployments.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListHandoffs ¶
func (s *LocalStore) ListHandoffs(ctx context.Context, workflowID WorkflowID) ([]*HandoffEnvelope, error)
LocalStore.ListHandoffs lists the handoffs.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListInvocations ¶
func (s *LocalStore) ListInvocations(ctx context.Context) ([]*InvocationReceipt, error)
LocalStore.ListInvocations lists the invocations.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListNodes ¶
func (s *LocalStore) ListNodes(ctx context.Context, workflowID WorkflowID) ([]*PipelineNode, error)
LocalStore.ListNodes lists the nodes.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListRuns ¶
func (s *LocalStore) ListRuns(ctx context.Context, workflowID WorkflowID) ([]*RunRecord, error)
LocalStore.ListRuns lists the runs.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListServices ¶
func (s *LocalStore) ListServices(ctx context.Context, workflowID WorkflowID) ([]*MCPServiceBinding, error)
LocalStore.ListServices lists the services.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ListWorkflows ¶
func (s *LocalStore) ListWorkflows(ctx context.Context) ([]*WorkflowRecord, error)
LocalStore.ListWorkflows lists the workflows.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) PutActiveTimeLedger ¶
func (s *LocalStore) PutActiveTimeLedger(ctx context.Context, workflowID WorkflowID, ledger *ActiveTimeLedger, expectedGeneration int64) error
PutActiveTimeLedger persists the workflow active-time ledger. expectedGeneration is the file generation expected. Pass 0 to bypass CAS.
func (*LocalStore) ReconcileInterrupted ¶
func (s *LocalStore) ReconcileInterrupted(ctx context.Context, runID RunID) error
LocalStore.ReconcileInterrupted reconciles interrupted.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) RecoverWAL ¶
func (s *LocalStore) RecoverWAL(wfID WorkflowID) error
RecoverWAL replays committed entries and discards uncommitted ones for a workflow. Safe to call on store open or after a crash.
func (*LocalStore) RegisterService ¶
func (s *LocalStore) RegisterService(ctx context.Context, svc *MCPServiceBinding) error
LocalStore.RegisterService registers service.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) RequestControl ¶
func (s *LocalStore) RequestControl(ctx context.Context, req *ControlRequest) error
LocalStore.RequestControl requests control.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) ResolveAlias ¶
func (s *LocalStore) ResolveAlias(ctx context.Context, alias string) (*AliasRecord, error)
LocalStore.ResolveAlias resolves the alias.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) SaveAttemptProgress ¶
func (s *LocalStore) SaveAttemptProgress(ctx context.Context, attemptID AttemptID, progress *AttemptProgress) error
SaveAttemptProgress updates the attempt record with progress metadata. This is called by the progress tailer after ingesting a heartbeat.
func (*LocalStore) SaveCheckpoint ¶
func (s *LocalStore) SaveCheckpoint(ctx context.Context, cp *SemanticCheckpoint) error
SaveCheckpoint atomically persists a semantic checkpoint. If a checkpoint with the same ID already exists, it returns ErrAlreadyExists (idempotent: never mutates).
func (*LocalStore) SetDeploymentStatus ¶
func (s *LocalStore) SetDeploymentStatus(ctx context.Context, deploymentID DeploymentID, status DeploymentStatus, expectedGeneration int64) error
LocalStore.SetDeploymentStatus sets the deployment status.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateAttempt ¶
func (s *LocalStore) UpdateAttempt(ctx context.Context, attempt *AttemptRecord, expectedGeneration int64) error
LocalStore.UpdateAttempt updates the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateChildBatch ¶
func (s *LocalStore) UpdateChildBatch(ctx context.Context, batch *ChildBatch, expectedGeneration int64) error
LocalStore.UpdateChildBatch updates the child batch.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateNode ¶
func (s *LocalStore) UpdateNode(ctx context.Context, node *PipelineNode, expectedGeneration int64) error
LocalStore.UpdateNode updates the node.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateRun ¶
LocalStore.UpdateRun updates the run.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateService ¶
func (s *LocalStore) UpdateService(ctx context.Context, svc *MCPServiceBinding, expectedGeneration int64) error
LocalStore.UpdateService updates the service.
It returns an error if the operation fails or inputs are invalid.
func (*LocalStore) UpdateWorkflow ¶
func (s *LocalStore) UpdateWorkflow(ctx context.Context, wf *WorkflowRecord, expectedGeneration int64) error
LocalStore.UpdateWorkflow updates the workflow.
It returns an error if the operation fails or inputs are invalid.
type LocalStoreOption ¶
type LocalStoreOption func(*LocalStore)
LocalStoreOption configures a LocalStore.
func WithClock ¶
func WithClock(now func() time.Time) LocalStoreOption
WithClock injects a clock for deterministic tests.
type MCPServiceBinding ¶
type MCPServiceBinding struct {
SchemaVersion string `json:"schema_version"`
ServiceID ServiceID `json:"service_id"`
WorkflowID WorkflowID `json:"workflow_id"`
Status ServiceStatus `json:"status"`
// Package identity.
PackageName string `json:"package_name"`
PackageVersion string `json:"package_version"`
// Logical service name within the package.
ServiceName string `json:"service_name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
MCPServiceBinding represents a binding to an MCP service.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-memory implementation of DeploymentStore, RunStore, and WorkflowStore for deterministic tests.
func NewMemoryStore ¶
func NewMemoryStore(opts ...MemoryStoreOption) *MemoryStore
NewMemoryStore constructs an empty in-memory store.
func (*MemoryStore) AdmitInvocation ¶
func (s *MemoryStore) AdmitInvocation(ctx context.Context, request *InvocationRequest, expectedDeploymentGeneration int64) (*InvocationReceipt, error)
MemoryStore.AdmitInvocation admits invocation.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) AppendControlResult ¶
func (s *MemoryStore) AppendControlResult(ctx context.Context, req *ControlRequest, result interface{}) error
MemoryStore.AppendControlResult appends control result.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) AppendLedger ¶
MemoryStore.AppendLedger appends ledger.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) AppendLimitAmendment ¶
func (s *MemoryStore) AppendLimitAmendment(ctx context.Context, workflowID WorkflowID, expectedAuthorityGeneration int64, amendment *LimitAmendment) error
MemoryStore.AppendLimitAmendment appends limit amendment.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ApplyTransition ¶
func (s *MemoryStore) ApplyTransition(ctx context.Context, workflowID WorkflowID, expectedGeneration int64, command string) error
MemoryStore.ApplyTransition applies transition.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CommitChildResult ¶
func (s *MemoryStore) CommitChildResult(ctx context.Context, result *ChildResult) error
MemoryStore.CommitChildResult commits child result.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CommitHandoff ¶
func (s *MemoryStore) CommitHandoff(ctx context.Context, handoff *HandoffEnvelope) error
MemoryStore.CommitHandoff commits handoff.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CompareAndSwapAlias ¶
func (s *MemoryStore) CompareAndSwapAlias(ctx context.Context, alias *AliasRecord) error
MemoryStore.CompareAndSwapAlias compares and swap alias.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateAttempt ¶
func (s *MemoryStore) CreateAttempt(ctx context.Context, attempt *AttemptRecord) error
MemoryStore.CreateAttempt creates the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateChildBatch ¶
func (s *MemoryStore) CreateChildBatch(ctx context.Context, batch *ChildBatch) error
MemoryStore.CreateChildBatch creates the child batch.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateDeployment ¶
func (s *MemoryStore) CreateDeployment(ctx context.Context, dep *DeploymentRecord) error
MemoryStore.CreateDeployment creates the deployment.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateNode ¶
func (s *MemoryStore) CreateNode(ctx context.Context, node *PipelineNode) error
MemoryStore.CreateNode creates the node.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateRun ¶
func (s *MemoryStore) CreateRun(ctx context.Context, run *RunRecord) error
MemoryStore.CreateRun creates the run.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) CreateWorkflow ¶
func (s *MemoryStore) CreateWorkflow(ctx context.Context, wf *WorkflowRecord) error
MemoryStore.CreateWorkflow creates the workflow.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetActiveTimeLedger ¶
func (s *MemoryStore) GetActiveTimeLedger(ctx context.Context, workflowID WorkflowID) (*ActiveTimeLedger, error)
GetActiveTimeLedger loads the in-memory active-time ledger.
func (*MemoryStore) GetActiveTimeLedgerGeneration ¶
func (s *MemoryStore) GetActiveTimeLedgerGeneration(ctx context.Context, workflowID WorkflowID) (int64, error)
GetActiveTimeLedgerGeneration returns the CAS generation for the active-time ledger. MemoryStore does not enforce CAS so this returns 0.
func (*MemoryStore) GetAttempt ¶
func (s *MemoryStore) GetAttempt(ctx context.Context, attemptID AttemptID) (*AttemptRecord, error)
MemoryStore.GetAttempt returns the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetDeployment ¶
func (s *MemoryStore) GetDeployment(ctx context.Context, deploymentID DeploymentID) (*DeploymentRecord, error)
MemoryStore.GetDeployment returns the deployment.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetDesiredState ¶
func (s *MemoryStore) GetDesiredState(ctx context.Context, workflowID WorkflowID) (*DesiredState, error)
MemoryStore.GetDesiredState returns the desired state.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetHandoff ¶
func (s *MemoryStore) GetHandoff(ctx context.Context, handoffID HandoffID) (*HandoffEnvelope, error)
MemoryStore.GetHandoff returns the handoff.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetInvocationByIdempotency ¶
func (s *MemoryStore) GetInvocationByIdempotency(ctx context.Context, callerIdentity, idempotencyKey string) (*InvocationReceipt, error)
MemoryStore.GetInvocationByIdempotency returns the invocation by idempotency.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetNode ¶
func (s *MemoryStore) GetNode(ctx context.Context, nodeID NodeID) (*PipelineNode, error)
MemoryStore.GetNode returns the node.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetRun ¶
MemoryStore.GetRun returns the run.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) GetWorkflow ¶
func (s *MemoryStore) GetWorkflow(ctx context.Context, workflowID WorkflowID) (*WorkflowRecord, error)
MemoryStore.GetWorkflow returns the workflow.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListAliases ¶
func (s *MemoryStore) ListAliases(ctx context.Context) ([]*AliasRecord, error)
MemoryStore.ListAliases lists the aliases.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListAttempts ¶
func (s *MemoryStore) ListAttempts(ctx context.Context, runID RunID) ([]*AttemptRecord, error)
MemoryStore.ListAttempts lists the attempts.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListChildBatches ¶
func (s *MemoryStore) ListChildBatches(ctx context.Context, workflowID WorkflowID) ([]*ChildBatch, error)
MemoryStore.ListChildBatches lists the child batches.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListChildResults ¶
func (s *MemoryStore) ListChildResults(ctx context.Context, childBatchID ChildBatchID) ([]*ChildResult, error)
MemoryStore.ListChildResults lists the child results.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListDeployments ¶
func (s *MemoryStore) ListDeployments(ctx context.Context) ([]*DeploymentRecord, error)
MemoryStore.ListDeployments lists the deployments.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListHandoffs ¶
func (s *MemoryStore) ListHandoffs(ctx context.Context, workflowID WorkflowID) ([]*HandoffEnvelope, error)
MemoryStore.ListHandoffs lists the handoffs.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListInvocations ¶
func (s *MemoryStore) ListInvocations(ctx context.Context) ([]*InvocationReceipt, error)
MemoryStore.ListInvocations lists the invocations.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListNodes ¶
func (s *MemoryStore) ListNodes(ctx context.Context, workflowID WorkflowID) ([]*PipelineNode, error)
MemoryStore.ListNodes lists the nodes.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListRuns ¶
func (s *MemoryStore) ListRuns(ctx context.Context, workflowID WorkflowID) ([]*RunRecord, error)
MemoryStore.ListRuns lists the runs.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListServices ¶
func (s *MemoryStore) ListServices(ctx context.Context, workflowID WorkflowID) ([]*MCPServiceBinding, error)
MemoryStore.ListServices lists the services.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ListWorkflows ¶
func (s *MemoryStore) ListWorkflows(ctx context.Context) ([]*WorkflowRecord, error)
MemoryStore.ListWorkflows lists the workflows.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) PutActiveTimeLedger ¶
func (s *MemoryStore) PutActiveTimeLedger(ctx context.Context, workflowID WorkflowID, ledger *ActiveTimeLedger, expectedGeneration int64) error
PutActiveTimeLedger stores the active-time ledger. expectedGeneration is the CAS generation. Pass 0 to bypass CAS.
func (*MemoryStore) ReconcileInterrupted ¶
func (s *MemoryStore) ReconcileInterrupted(ctx context.Context, runID RunID) error
MemoryStore.ReconcileInterrupted reconciles interrupted.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) RegisterService ¶
func (s *MemoryStore) RegisterService(ctx context.Context, svc *MCPServiceBinding) error
MemoryStore.RegisterService registers service.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) RequestControl ¶
func (s *MemoryStore) RequestControl(ctx context.Context, req *ControlRequest) error
MemoryStore.RequestControl requests control.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) ResolveAlias ¶
func (s *MemoryStore) ResolveAlias(ctx context.Context, alias string) (*AliasRecord, error)
MemoryStore.ResolveAlias resolves the alias.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) SetDeploymentStatus ¶
func (s *MemoryStore) SetDeploymentStatus(ctx context.Context, deploymentID DeploymentID, status DeploymentStatus, expectedGeneration int64) error
MemoryStore.SetDeploymentStatus sets the deployment status.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateAttempt ¶
func (s *MemoryStore) UpdateAttempt(ctx context.Context, attempt *AttemptRecord, expectedGeneration int64) error
MemoryStore.UpdateAttempt updates the attempt.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateChildBatch ¶
func (s *MemoryStore) UpdateChildBatch(ctx context.Context, batch *ChildBatch, expectedGeneration int64) error
MemoryStore.UpdateChildBatch updates the child batch.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateNode ¶
func (s *MemoryStore) UpdateNode(ctx context.Context, node *PipelineNode, expectedGeneration int64) error
MemoryStore.UpdateNode updates the node.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateRun ¶
func (s *MemoryStore) UpdateRun(ctx context.Context, run *RunRecord, expectedGeneration int64) error
MemoryStore.UpdateRun updates the run.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateService ¶
func (s *MemoryStore) UpdateService(ctx context.Context, svc *MCPServiceBinding, expectedGeneration int64) error
MemoryStore.UpdateService updates the service.
It returns an error if the operation fails or inputs are invalid.
func (*MemoryStore) UpdateWorkflow ¶
func (s *MemoryStore) UpdateWorkflow(ctx context.Context, wf *WorkflowRecord, expectedGeneration int64) error
MemoryStore.UpdateWorkflow updates the workflow.
It returns an error if the operation fails or inputs are invalid.
type MemoryStoreOption ¶
type MemoryStoreOption func(*MemoryStore)
MemoryStoreOption configures a MemoryStore.
func WithMemoryClock ¶
func WithMemoryClock(now func() time.Time) MemoryStoreOption
WithMemoryClock injects a fake clock.
type Migration ¶
type Migration struct {
FromVersion string
ToVersion string
Apply func(state []byte) ([]byte, error)
}
Migration transforms persisted state from FromVersion to ToVersion. Apply must be idempotent: applying twice to already-migrated bytes is a no-op or returns the same ToVersion bytes.
type MigrationRegistry ¶
type MigrationRegistry struct {
// contains filtered or unexported fields
}
MigrationRegistry is an ordered registry of supported schema migrations. Unknown or newer versions fail closed before any mutation.
func DefaultMigrationRegistry ¶
func DefaultMigrationRegistry() *MigrationRegistry
DefaultMigrationRegistry returns a registry for CurrentSchemaVersion with no older migrations registered yet (v0.3.0 is the starting schema).
func NewMigrationRegistry ¶
func NewMigrationRegistry(current string, migrations []Migration) (*MigrationRegistry, error)
NewMigrationRegistry builds a registry for the given current schema version. Migrations must form a single forward chain without gaps or cycles.
func (*MigrationRegistry) Current ¶
func (r *MigrationRegistry) Current() string
Current returns the registry's current schema version.
func (*MigrationRegistry) IsSupported ¶
func (r *MigrationRegistry) IsSupported(version string) bool
IsSupported reports whether version is current or an explicitly registered older version.
func (*MigrationRegistry) Migrate ¶
func (r *MigrationRegistry) Migrate(fromVersion string, state []byte) (toVersion string, out []byte, err error)
Migrate applies the ordered chain from version to current (or to target if set). Unknown/newer versions fail closed without calling Apply.
func (*MigrationRegistry) MigrateFile ¶
func (r *MigrationRegistry) MigrateFile(path string) error
MigrateFile migrates a single JSON file on disk with atomic replacement and recoverable backup. Interruption leaves either the original or the fully migrated file (plus backup until commit marker is written).
Layout beside path:
path.bak.<from> path.migrate.tmp path.migrate.commit (written after rename; then backups may be removed)
func (*MigrationRegistry) MigrateTree ¶
func (r *MigrationRegistry) MigrateTree(root string) error
MigrateTree walks a store root and migrates every JSON state file under it. Fails closed on the first unknown/newer version without mutating further files once an error is observed; already-migrated files remain migrated.
func (*MigrationRegistry) NeedsMigration ¶
func (r *MigrationRegistry) NeedsMigration(version string) bool
NeedsMigration reports whether version is older than current and can be migrated.
type ModelCallID ¶
type ModelCallID string
ModelCallID identifies a model call.
func (ModelCallID) MarshalText ¶
func (id ModelCallID) MarshalText() ([]byte, error)
ModelCallID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ModelCallID) Scan ¶
func (id *ModelCallID) Scan(src interface{}) error
ModelCallID.Scan scans a database value into model call id.
It returns an error if the operation fails or inputs are invalid.
func (ModelCallID) String ¶
func (id ModelCallID) String() string
ModelCallID.String returns the string representation.
func (*ModelCallID) UnmarshalText ¶
func (id *ModelCallID) UnmarshalText(b []byte) error
ModelCallID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type ModelRequirements ¶
type ModelRequirements struct {
SchemaVersion string `json:"schema_version"`
CapabilityTier string `json:"capability_tier"` // basic, standard, advanced
ContextTokens int `json:"context_tokens"`
Features []string `json:"features,omitempty"` // chat, structured_json, reasoning_effort
}
ModelRequirements describes the minimum requirements for a model candidate.
type NodeID ¶
type NodeID string
NodeID identifies a workflow node/stage.
func (NodeID) MarshalText ¶
NodeID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*NodeID) Scan ¶
NodeID.Scan scans a database value into node id.
It returns an error if the operation fails or inputs are invalid.
func (*NodeID) UnmarshalText ¶
NodeID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type NodeStateTransition ¶
type NodeStateTransition struct {
SchemaVersion string `json:"schema_version"`
NodeID NodeID `json:"node_id"`
FromState NodeStatus `json:"from_state"`
ToState NodeStatus `json:"to_state"`
Reason string `json:"reason,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
NodeStateTransition records a node state transition event.
type NodeStatus ¶
type NodeStatus int
NodeStatus represents the lifecycle status of a pipeline node/stage.
const ( NodeStatusPending NodeStatus = iota // 0 NodeStatusReady // 1 NodeStatusLaunching // 2 NodeStatusRunning // 3 NodeStatusPauseRequested // 4 NodeStatusPaused // 5 NodeStatusNeedsReplan // 6 NodeStatusSucceeded // 7 NodeStatusFailed // 8 NodeStatusCancelled // 9 NodeStatusSkipped // 10 )
func AllNodeStatuses ¶
func AllNodeStatuses() []NodeStatus
AllNodeStatuses returns all valid NodeStatus values.
func (NodeStatus) MarshalJSON ¶
func (s NodeStatus) MarshalJSON() ([]byte, error)
NodeStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (NodeStatus) String ¶
func (s NodeStatus) String() string
NodeStatus.String returns the string representation.
func (*NodeStatus) UnmarshalJSON ¶
func (s *NodeStatus) UnmarshalJSON(data []byte) error
NodeStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (NodeStatus) Valid ¶
func (s NodeStatus) Valid() bool
NodeStatus.Valid reports whether the node status value is valid.
type NormalizedUsage ¶
type NormalizedUsage struct {
SchemaVersion string `json:"schema_version"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
TotalTokens int64 `json:"total_tokens"`
}
NormalizedUsage represents normalized model usage for a call.
type PipelineNode ¶
type PipelineNode struct {
SchemaVersion string `json:"schema_version"`
NodeID NodeID `json:"node_id"`
WorkflowID WorkflowID `json:"workflow_id"`
Status NodeStatus `json:"status"`
RunID RunID `json:"run_id,omitempty"`
// Stage order (0-based).
StageOrder int `json:"stage_order"`
// Package reference for this stage.
PackageName string `json:"package_name"`
PackageVersion string `json:"package_version"`
// Handoff from previous stage (nil for first stage).
IncomingHandoffID *HandoffID `json:"incoming_handoff_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
PipelineNode represents a stage in a pipeline workflow.
type ProgressSummary ¶
type ProgressSummary struct {
SchemaVersion string `json:"schema_version"`
ModelCallsCompleted int `json:"model_calls_completed"`
ToolCallsCompleted int `json:"tool_calls_completed"`
ActionsSinceCheckpoint int `json:"actions_since_checkpoint"`
ActionsWithoutProgress int `json:"actions_without_progress"`
}
ProgressSummary describes progress within an attempt.
type ProgressTailer ¶
type ProgressTailer struct {
// contains filtered or unexported fields
}
ProgressTailer reads authenticated journal records and persists checkpoints. It verifies HMAC and sequence before updating any state.
func NewProgressTailer ¶
func NewProgressTailer( journalPath string, key []byte, store CheckpointStore, attemptID AttemptID, runID RunID, ) *ProgressTailer
NewProgressTailer creates a tailer for the given journal.
func (*ProgressTailer) IngestRecord ¶
IngestRecord verifies and ingests a single journal record. Returns the checkpoint ID if a checkpoint was created, or "" for a heartbeat. Returns an error if the record fails verification.
func (*ProgressTailer) SetAuditAppender ¶
func (t *ProgressTailer) SetAuditAppender(appender audit.AuditAppender)
SetAuditAppender attaches an audit appender for recording journal validation failures (e.g. tampered/malformed journal records). When set, the tailer emits a progress_journal_invalid audit event and marks ResumeCapability as ResumeCapNone on the first journal error.
func (*ProgressTailer) Start ¶
func (t *ProgressTailer) Start(ctx context.Context)
start begins tailing the journal file in a goroutine.
func (*ProgressTailer) Stop ¶
func (t *ProgressTailer) Stop()
Stop signals the tailer to stop and waits.
type RecoveryDisposition ¶
type RecoveryDisposition int
RecoveryDisposition describes whether and how an attempt may be recovered.
const ( RecoveryNotNeeded RecoveryDisposition = iota // 0 RecoveryAutoRecovered // 1 RecoveryNeedsReplan // 2 RecoveryTerminal // 3 )
func (RecoveryDisposition) MarshalJSON ¶
func (d RecoveryDisposition) MarshalJSON() ([]byte, error)
RecoveryDisposition.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (RecoveryDisposition) String ¶
func (d RecoveryDisposition) String() string
RecoveryDisposition.String returns the string representation.
func (*RecoveryDisposition) UnmarshalJSON ¶
func (d *RecoveryDisposition) UnmarshalJSON(data []byte) error
RecoveryDisposition.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (RecoveryDisposition) Valid ¶
func (d RecoveryDisposition) Valid() bool
RecoveryDisposition.Valid reports whether the recovery disposition value is valid.
type RestartProvenance ¶
type RestartProvenance struct {
SchemaVersion string `json:"schema_version"`
SourceRunID RunID `json:"source_run_id"`
SourceWorkflowID WorkflowID `json:"source_workflow_id"`
SourceInvocationID InvocationID `json:"source_invocation_id"`
SourceDeploymentID DeploymentID `json:"source_deployment_id"`
SourceDeploymentVersion string `json:"source_deployment_version"`
OriginalInputDigest string `json:"original_input_digest"`
RestartedAt time.Time `json:"restarted_at"`
}
RestartProvenance records the source of a restarted run.
type ResumeCapability ¶
type ResumeCapability int
ResumeCapability describes what resume strategies are available.
const ( ResumeCapSafeCheckpoint ResumeCapability = iota // 0 ResumeCapRestartOnly // 1 ResumeCapNone // 2 )
func (ResumeCapability) MarshalJSON ¶
func (rc ResumeCapability) MarshalJSON() ([]byte, error)
ResumeCapability.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ResumeCapability) String ¶
func (rc ResumeCapability) String() string
ResumeCapability.String returns the string representation.
func (*ResumeCapability) UnmarshalJSON ¶
func (rc *ResumeCapability) UnmarshalJSON(data []byte) error
ResumeCapability.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ResumeCapability) Valid ¶
func (rc ResumeCapability) Valid() bool
ResumeCapability.Valid reports whether the resume capability value is valid.
type ResumeCheckpointData ¶
type ResumeCheckpointData struct {
CheckpointID CheckpointID `json:"checkpoint_id"`
SourceAttemptID AttemptID `json:"source_attempt_id"`
RunID RunID `json:"run_id"`
WorkflowID WorkflowID `json:"workflow_id"`
NodeID NodeID `json:"node_id,omitempty"`
// Semantic fields.
Phase string `json:"phase"`
CompletedWork []string `json:"completed_work"`
RemainingWork []string `json:"remaining_work"`
ArtifactRefs []string `json:"artifact_references"`
LastCommittedAction string `json:"last_committed_action"`
// Integrity digests.
CheckpointDigest string `json:"checkpoint_digest"`
ArtifactMetaDigest string `json:"artifact_meta_digest"`
// Artifact metadata (path, digest, size — NOT content).
Artifacts []ArtifactMetadata `json:"artifacts,omitempty"`
// Resume reason (trusted, set by daemon — never by trigger payload).
ResumeReason ResumeReason `json:"resume_reason"`
// Checkpoint creation timestamp.
CreatedAt time.Time `json:"created_at"`
}
ResumeCheckpointData is the trusted data delivered to a resumed attempt's harness, never injected into the user trigger payload.
type ResumeCheckpointLoader ¶
type ResumeCheckpointLoader struct {
// contains filtered or unexported fields
}
ResumeCheckpointLoader loads and validates a checkpoint for resume.
func NewResumeCheckpointLoader ¶
func NewResumeCheckpointLoader(store CheckpointStore) *ResumeCheckpointLoader
NewResumeCheckpointLoader creates a loader.
func (*ResumeCheckpointLoader) LoadResumeCheckpoint ¶
func (l *ResumeCheckpointLoader) LoadResumeCheckpoint( ctx context.Context, attemptID AttemptID, runID RunID, resumeReason ResumeReason, ) (*ResumeCheckpointData, error)
LoadResumeCheckpoint loads the latest safe checkpoint for an attempt and converts it to trusted resume data. Returns ErrNotFound if no checkpoint exists (initial attempt).
type ResumeReason ¶
type ResumeReason string
ResumeReason is a trusted enum set by the daemon.
const ( ResumeReasonFailureContinuation ResumeReason = "failure_continuation" ResumeReasonOperatorPauseResume ResumeReason = "operator_pause_resume" )
func (ResumeReason) Valid ¶
func (r ResumeReason) Valid() bool
Valid checks if a ResumeReason is a known value.
type RouteDecision ¶
type RouteDecision struct {
SchemaVersion string `json:"schema_version"`
ModelCallID ModelCallID `json:"model_call_id"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
CandidateID string `json:"candidate_id"`
Provider string `json:"provider"`
Model string `json:"model"`
AttemptedRecovery bool `json:"attempted_recovery"`
Succeeded bool `json:"succeeded"`
FailureReason *FailureReason `json:"failure_reason,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
RouteDecision records the routing decision for a model call.
type RunID ¶
type RunID string
RunID identifies a run.
func (RunID) MarshalText ¶
RunID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*RunID) Scan ¶
RunID.Scan scans a database value into run id.
It returns an error if the operation fails or inputs are invalid.
func (*RunID) UnmarshalText ¶
RunID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type RunRecord ¶
type RunRecord struct {
SchemaVersion string `json:"schema_version"`
RunID RunID `json:"run_id"`
WorkflowID WorkflowID `json:"workflow_id"`
Status RunStatus `json:"status"`
// Polymorphic run kind.
RunKind string `json:"run_kind"` // standalone, pipeline_stage, parent, child, mcp_service
// Immutable policy and catalog snapshot refs.
PolicyDigest string `json:"policy_digest"`
CatalogSnapshotRef string `json:"catalog_snapshot_ref,omitempty"`
// Node that owns this run (for pipeline stages).
NodeID *NodeID `json:"node_id,omitempty"`
// Aggregate ceilings (narrowed from workflow-level).
MaxActiveDurationMs int64 `json:"max_active_duration_ms"`
MaxAttemptLeaseMs int64 `json:"max_attempt_lease_ms"`
MaxLLMSpendDecimal string `json:"max_llm_spend_decimal"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TerminatedAt *time.Time `json:"terminated_at,omitempty"`
}
RunRecord is the durable record of a run.
type RunStatus ¶
type RunStatus int
RunStatus represents the lifecycle status of a run.
func AllRunStatuses ¶
func AllRunStatuses() []RunStatus
AllRunStatuses returns all valid RunStatus values.
func ApplyRunTransition ¶
ApplyRunTransition validates and applies a RunStatus transition. Returns the new status on success, or the original status and a *TransitionError.
func (RunStatus) IsTerminal ¶
IsTerminal returns true for terminal run statuses.
func (RunStatus) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*RunStatus) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type RunStore ¶
type RunStore interface {
// CreateRun persists a new run record.
// Top-level runs are created inside AdmitInvocation; callers must not
// follow admission with another CreateRun. CreateRun is available only
// for atomic workflow transitions that create dynamic service/child work.
CreateRun(ctx context.Context, run *RunRecord) error
// GetRun retrieves a run by ID.
GetRun(ctx context.Context, runID RunID) (*RunRecord, error)
// UpdateRun atomically updates a run record.
UpdateRun(ctx context.Context, run *RunRecord, expectedGeneration int64) error
// CreateAttempt persists a new attempt record.
CreateAttempt(ctx context.Context, attempt *AttemptRecord) error
// GetAttempt retrieves an attempt by ID.
GetAttempt(ctx context.Context, attemptID AttemptID) (*AttemptRecord, error)
// UpdateAttempt atomically updates an attempt record.
UpdateAttempt(ctx context.Context, attempt *AttemptRecord, expectedGeneration int64) error
// ListRuns lists runs, optionally filtered by workflow ID.
ListRuns(ctx context.Context, workflowID WorkflowID) ([]*RunRecord, error)
// ListAttempts lists attempts for a run.
ListAttempts(ctx context.Context, runID RunID) ([]*AttemptRecord, error)
// AppendLedger appends a ledger entry for active-time/cost accounting.
AppendLedger(ctx context.Context, runID RunID, entry string) error
// ReconcileInterrupted handles interrupted runs: revokes the lease,
// records DAEMON_RESTARTED, and fails the attempt.
ReconcileInterrupted(ctx context.Context, runID RunID) error
}
RunStore defines the durable storage interface for runs and attempts.
type SemanticCheckpoint ¶
type SemanticCheckpoint struct {
SchemaVersion string `json:"schema_version"`
CheckpointID CheckpointID `json:"checkpoint_id"`
AttemptID AttemptID `json:"attempt_id"`
RunID RunID `json:"run_id"`
WorkflowID WorkflowID `json:"workflow_id"`
NodeID NodeID `json:"node_id,omitempty"`
LeaseID LeaseID `json:"lease_id"`
// Semantic fields from the worker.
Phase string `json:"phase"`
CompletedWork []string `json:"completed_work"`
RemainingWork []string `json:"remaining_work"`
ArtifactRefs []string `json:"artifact_references"`
LastCommittedAction string `json:"last_committed_action"`
SafeToResume bool `json:"safe_to_resume"`
// Integrity digests.
CheckpointDigest string `json:"checkpoint_digest"`
ArtifactMetaDigest string `json:"artifact_meta_digest"`
// Sequence from the journal.
Sequence int64 `json:"sequence"`
// Timestamps.
CreatedAt time.Time `json:"created_at"`
}
SemanticCheckpoint is a durable safe-resume point. It is stored atomically and never mutated after creation.
func (*SemanticCheckpoint) ComputeDigest ¶
func (cp *SemanticCheckpoint) ComputeDigest() string
ComputeDigest returns SHA-256 hex of the canonical checkpoint content (Phase, CompletedWork, RemainingWork, LastCommittedAction, SafeToResume, ArtifactRefs). This is used to verify checkpoint integrity on read-back. An empty digest for a safe-to-resume checkpoint is invalid per pitfall #149.
func (*SemanticCheckpoint) VerifyDigest ¶
func (cp *SemanticCheckpoint) VerifyDigest() error
VerifyDigest checks that the checkpoint's digest is non-empty and matches the SHA-256 of the canonical checkpoint content. Returns nil if valid, or an error describing the mismatch.
type ServiceHealthSummary ¶
type ServiceHealthSummary struct {
SchemaVersion string `json:"schema_version"`
ServiceID ServiceID `json:"service_id"`
Status ServiceStatus `json:"status"`
LastChecked time.Time `json:"last_checked"`
LastHealthy *time.Time `json:"last_healthy,omitempty"`
ErrorCount int `json:"error_count"`
LastError string `json:"last_error,omitempty"`
}
ServiceHealthSummary is a compact health status for a service.
type ServiceID ¶
type ServiceID string
ServiceID identifies an MCP service binding.
func NewServiceID ¶
NewServiceID generates a cryptographically random service ID.
func (ServiceID) MarshalText ¶
ServiceID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*ServiceID) Scan ¶
ServiceID.Scan scans a database value into service id.
It returns an error if the operation fails or inputs are invalid.
func (*ServiceID) UnmarshalText ¶
ServiceID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type ServiceLease ¶
type ServiceLease struct {
SchemaVersion string `json:"schema_version"`
LeaseID LeaseID `json:"lease_id"`
ServiceID ServiceID `json:"service_id"`
WorkflowID WorkflowID `json:"workflow_id"`
AcquiredAt time.Time `json:"acquired_at"`
ExpiresAt time.Time `json:"expires_at"`
LeaseToken string `json:"lease_token"`
}
ServiceLease represents a lease on an MCP service instance.
type ServiceStatus ¶
type ServiceStatus int
ServiceStatus represents the lifecycle status of an MCP service binding.
const ( ServiceStatusDeclared ServiceStatus = iota // 0 ServiceStatusStarting // 1 ServiceStatusReady // 2 ServiceStatusUnhealthy // 3 ServiceStatusFenced // 4 ServiceStatusStopping // 5 ServiceStatusStopped // 6 ServiceStatusFailed // 7 )
func AllServiceStatuses ¶
func AllServiceStatuses() []ServiceStatus
AllServiceStatuses returns all valid ServiceStatus values.
func (ServiceStatus) MarshalJSON ¶
func (s ServiceStatus) MarshalJSON() ([]byte, error)
ServiceStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ServiceStatus) String ¶
func (s ServiceStatus) String() string
ServiceStatus.String returns the string representation.
func (*ServiceStatus) UnmarshalJSON ¶
func (s *ServiceStatus) UnmarshalJSON(data []byte) error
ServiceStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (ServiceStatus) Valid ¶
func (s ServiceStatus) Valid() bool
ServiceStatus.Valid reports whether the service status value is valid.
type SystemClock ¶
type SystemClock struct{}
SystemClock is the production Clock implementation using time.Now.
func (SystemClock) Now ¶
func (SystemClock) Now() time.Time
Now returns the current wall-clock time in UTC.
func (SystemClock) NowMonotonic ¶
func (SystemClock) NowMonotonic() time.Time
NowMonotonic returns the current monotonic reading. time.Now() carries a monotonic component on most platforms, so the same call suffices for duration arithmetic via Sub.
type SystemTimer ¶
type SystemTimer struct{}
SystemTimer is the production Timer implementation using time.After / time.NewTimer.
func (SystemTimer) After ¶
func (SystemTimer) After(d time.Duration) <-chan time.Time
After fires once after d.
func (SystemTimer) NewTimer ¶
func (SystemTimer) NewTimer(d time.Duration) TimerHandle
NewTimer returns a handle backed by time.NewTimer.
type TerminationEvent ¶
type TerminationEvent struct {
Kind TerminationReason
ObservedAt time.Time
}
TerminationEvent is a simultaneously-observed termination signal.
type TerminationReason ¶
type TerminationReason int
TerminationReason is the deterministic reason a workflow terminated. The numeric values define the precedence order: lower numbers win when events coincide (b30-summary.md:360-366):
- user cancellation
- active-time exhaustion
- lease expiry
- stall
- process/provider failure
const ( // TerminationUnknown is the zero value and must not be emitted. TerminationUnknown TerminationReason = iota TerminationUserCancel TerminationActiveTimeExhausted TerminationLeaseExpired TerminationStall TerminationProcessFailure )
func ResolveTermination ¶
func ResolveTermination(env TimeEnvelope, events []TerminationEvent) TerminationReason
ResolveTermination applies the deterministic precedence rules from b30-summary.md:360-366 to a set of simultaneously-observed events and returns the winner. It is a pure function — no side effects. If events is empty it returns TerminationUnknown. Ties between equal-precedence events (impossible by construction since each Kind is distinct) resolve to the earliest ObservedAt for stability.
func (TerminationReason) String ¶
func (r TerminationReason) String() string
String returns the stable name for a termination reason.
type TimeBudgetSummary ¶
type TimeBudgetSummary struct {
SchemaVersion string `json:"schema_version"`
AttemptDurationMs int64 `json:"attempt_duration_ms"`
RunActiveTimeMs int64 `json:"run_active_time_ms"`
WorkflowActiveTimeMs int64 `json:"workflow_active_time_ms"`
RemainingMs int64 `json:"remaining_ms"`
// CPUSeconds (B30-T04) is the consumed CPU time for this attempt,
// reported SEPARATELY from accumulated workflow active time
// (AttemptDurationMs / RunActiveTimeMs / WorkflowActiveTimeMs).
// Active time accrues only while the workflow is RUNNING; CPU time
// accrues while the worker is using a CPU core regardless of
// pause/resume state. When a CPU quota is signed by policy
// (InvokeJob.CPUQuotaSeconds), CPUSeconds is bounded by that quota.
CPUSeconds int64 `json:"cpu_seconds,omitempty"`
}
TimeBudgetSummary describes time usage within an attempt.
type TimeEnvelope ¶
type TimeEnvelope struct {
SchemaVersion string `json:"schema_version"`
// CurrentMaxActiveDurationMs is the current maximum active duration
// (may be amended by B39; T03 stores the initial value).
CurrentMaxActiveDurationMs int64 `json:"current_max_active_duration_ms"`
// ConsumedActiveDurationMs is the accumulated active time.
ConsumedActiveDurationMs int64 `json:"consumed_active_duration_ms"`
// RunningSegmentStartMs is the optional running-segment start (nil
// when frozen/paused). Monotonic millisecond timestamp.
RunningSegmentStartMs *int64 `json:"running_segment_start_ms,omitempty"`
// AttemptLeaseRemainingMs is the attempt lease remaining (nil if no
// active lease).
AttemptLeaseRemainingMs *int64 `json:"attempt_lease_remaining_ms,omitempty"`
// StallTimeoutMs is the stall timeout (per-operation ceiling for
// stall detection).
StallTimeoutMs int64 `json:"stall_timeout_ms,omitempty"`
// ModelCallTimeoutMs is the model-call timeout (per-operation ceiling
// for model calls).
ModelCallTimeoutMs int64 `json:"model_call_timeout_ms,omitempty"`
// LifecycleAuthorityGeneration is the lifecycle/authority generation,
// incremented on amendments. T03 starts at 1.
LifecycleAuthorityGeneration int64 `json:"lifecycle_authority_generation"`
// CancellationGeneration is the cancellation generation, incremented
// on each cancellation request. T03 starts at 0.
CancellationGeneration int64 `json:"cancellation_generation"`
// FrozenConsumedMs mirrors ActiveTimeLedger.FrozenConsumedMs: when
// PAUSED or NEEDS_REPLAN, the consumed time at freeze. Does not
// accrue while frozen.
FrozenConsumedMs int64 `json:"frozen_consumed_ms,omitempty"`
}
TimeEnvelope is the authoritative active-time / operation-deadline / cancellation envelope for a workflow. It wraps and extends the B26 ActiveTimeLedger: the ledger tracks consumed active time, the envelope adds per-operation timeouts, the attempt lease, the stall / model-call timeouts, and the lifecycle / cancellation generations used by B39 amendments and user cancellation respectively.
Per b30-summary.md:337-340, the envelope is the single authoritative source for:
- current maximum active duration (may be amended by B39; T03 stores the initial value and reserves the amendment seam but does not activate amendment behavior).
- accumulated active time (mirrors ActiveTimeLedger.ConsumedMs).
- optional running-segment start (nil when frozen/paused).
- attempt lease remaining (nil if no active lease).
- stall timeout and model-call timeout (per-operation ceilings).
- lifecycle/authority generation (incremented on amendments; starts at 1).
- cancellation generation (incremented on each cancellation request; starts at 0).
All segment-accounting operations (StartActiveSegment, CloseActiveSegment, FreezeActiveSegment, UnfreezeActiveSegment, WithAmendedCeiling) return a NEW TimeEnvelope and never mutate the caller's struct (pitfall #134 CAS lesson). Callers must treat the envelope as immutable between updates.
func CloseActiveSegment ¶
func CloseActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
CloseActiveSegment closes an open segment and accrues the elapsed active time to ConsumedActiveDurationMs. It is idempotent: if no segment is open it returns the envelope unchanged (a daemon restart conservatively closes an interrupted active segment exactly once — b30-summary.md:355-356).
nowMs MUST be a monotonic millisecond timestamp. If nowMs precedes the segment start (e.g. a backward monotonic jump, which should not happen but is defended against), the elapsed is clamped to 0 so consumed time never goes negative.
func FreezeActiveSegment ¶
func FreezeActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
FreezeActiveSegment closes the open segment (accruing elapsed) AND records FrozenConsumedMs for PAUSED / NEEDS_REPLAN. While frozen the envelope does not accrue active time. Returns a NEW TimeEnvelope.
func NewTimeEnvelope ¶
func NewTimeEnvelope(maxActiveMs, attemptLeaseMs, stallTimeoutMs, modelCallTimeoutMs int64) TimeEnvelope
NewTimeEnvelope constructs a fresh TimeEnvelope with the given ceilings and lifecycle/authority generation = 1 and cancellation generation = 0. StallTimeoutMs and ModelCallTimeoutMs are the per-operation ceilings.
func StartActiveSegment ¶
func StartActiveSegment(env TimeEnvelope, nowMs int64) (TimeEnvelope, error)
StartActiveSegment begins a new active segment at nowMs. It returns a NEW TimeEnvelope with RunningSegmentStartMs = nowMs. If a segment is already open it returns ErrSegmentAlreadyOpen without modifying the envelope.
nowMs MUST be a monotonic millisecond timestamp (see Clock.NowMonotonic). Atomic with observed workflow state: RUNNING or PAUSE_REQUESTED accrue; PAUSED and NEEDS_REPLAN do not (b30-summary.md:353-359). The caller is responsible for only starting a segment in an accruing state.
func TimeEnvelopeFromCeilings ¶
func TimeEnvelopeFromCeilings(maxActiveMs, attemptLeaseMs, stallTimeoutMs, modelCallTimeoutMs int64) (TimeEnvelope, bool)
TimeEnvelopeFromCeilings builds a TimeEnvelope directly from explicit ceilings. Returns (TimeEnvelope{}, false) when maxActiveMs is non-positive (the legacy fallback signal).
func TimeEnvelopeFromReceipt ¶
func TimeEnvelopeFromReceipt(receipt *InvocationReceipt) (TimeEnvelope, bool)
TimeEnvelopeFromReceipt builds a fresh TimeEnvelope from the initial ceilings carried on an InvocationReceipt. The envelope starts with zero consumed active time, no open segment, lifecycle/authority generation = 1, and cancellation generation = 0 (b30-summary.md:337-340).
maxActiveMs comes from receipt.InitialMaxActiveDurationMs; attemptLeaseMs from receipt.InitialAttemptLeaseMs. stallTimeoutMs and modelCallTimeoutMs default to DefaultStallTimeoutMs / DefaultModelCallTimeoutMs when the receipt carries no explicit value (the receipt schema is the initial aggregate ceilings; per-operation timeouts are policy-derived defaults until B39 amendments land).
When the receipt carries zero max-active (the legacy v0.2.3 trigger path never admitted), this returns (TimeEnvelope{}, false) so callers can fall back to the legacy constant.
func UnfreezeActiveSegment ¶
func UnfreezeActiveSegment(env TimeEnvelope, nowMs int64) TimeEnvelope
UnfreezeActiveSegment clears the frozen state and allows a new segment to start. ConsumedActiveDurationMs is preserved (the frozen interval was not charged). Returns a NEW TimeEnvelope.
func UnmarshalTimeEnvelopeFromPayload ¶
func UnmarshalTimeEnvelopeFromPayload(payload map[string]any) (TimeEnvelope, bool)
UnmarshalTimeEnvelopeFromPayload extracts a TimeEnvelope embedded under the "time_envelope" key of an invoke payload. Returns (TimeEnvelope{}, false) when absent or invalid, signaling the caller to use the legacy fallback.
func WithAmendedCeiling ¶
func WithAmendedCeiling(env TimeEnvelope, newMaxActiveMs, newAuthorityGeneration int64) TimeEnvelope
WithAmendedCeiling returns a NEW TimeEnvelope with the updated maximum active duration and lifecycle/authority generation, preserving ConsumedActiveDurationMs (no time lost on amendment). T03 reserves this seam but does NOT expose amendment behavior to callers — B39 owns it (b30-summary.md:371-373). The seam is atomic: the ceiling and generation advance together in a single immutable update.
func (TimeEnvelope) ActiveTimeRemainingMs ¶
func (e TimeEnvelope) ActiveTimeRemainingMs(nowMs int64) int64
ActiveTimeRemainingMs returns the remaining active time in milliseconds. When a segment is running (RunningSegmentStartMs != nil), the elapsed time since start is added to ConsumedActiveDurationMs before subtraction. nowMs is a monotonic millisecond timestamp (see Clock.NowMonotonic).
The arithmetic is overflow-safe: if the running-segment elapsed would push consumed past CurrentMaxActiveDurationMs, the result clamps to 0 rather than wrapping negative (b30-summary.md:380-381).
func (TimeEnvelope) EffectiveOperationDeadlineMs ¶
func (e TimeEnvelope) EffectiveOperationDeadlineMs(nowMs, operationTimeoutMs int64) int64
EffectiveOperationDeadlineMs returns the effective per-operation deadline in milliseconds: the minimum of operationTimeoutMs, the attempt lease remaining, and the active time remaining (b30-summary.md:342-345).
effective_operation_deadline = min(operation_timeout,
attempt_lease_remaining,
active_time_remaining)
operationTimeoutMs is the per-operation timeout from policy: StallTimeoutMs for stall detection, ModelCallTimeoutMs for model calls. The caller selects which one to pass.
If any of the three is zero or negative, the deadline is now (expired) and the method returns 0.
func (TimeEnvelope) IsExpired ¶
func (e TimeEnvelope) IsExpired(nowMs int64) bool
IsExpired returns true if active time is exhausted (remaining <= 0) or the attempt lease has expired (remaining <= 0). nowMs is a monotonic millisecond timestamp.
func (TimeEnvelope) MarshalForPayload ¶
func (e TimeEnvelope) MarshalForPayload() map[string]any
MarshalForPayload returns a map[string]any representation of the envelope suitable for embedding in an invoke payload under a reserved key. The schema mirrors the JSON tags on TimeEnvelope so the harness can unmarshal it back with UnmarshalFromPayload.
type Timer ¶
type Timer interface {
// After fires once after d, sending the current time on the returned
// channel.
After(d time.Duration) <-chan time.Time
// NewTimer returns a handle that can be stopped and reset.
NewTimer(d time.Duration) TimerHandle
}
Timer is the injectable timer abstraction.
type TimerHandle ¶
type TimerHandle interface {
// Stop stops the timer. It returns false if the timer has already
// expired or been stopped.
Stop() bool
// Reset resets the timer to d. It returns false if the timer had
// already expired or been stopped.
Reset(d time.Duration) bool
// C returns the channel the timer fires on.
C() <-chan time.Time
}
TimerHandle is a stoppable, resettable timer.
type TransitionError ¶
type TransitionError struct {
Resource string `json:"resource"`
FromState interface{} `json:"from_state"`
ToState interface{} `json:"to_state"`
Message string `json:"message"`
}
TransitionError is returned when an invalid state transition is attempted.
func NewTransitionError ¶
func NewTransitionError(resource string, from, to interface{}) *TransitionError
NewTransitionError creates a new TransitionError.
func (*TransitionError) Error ¶
func (e *TransitionError) Error() string
TransitionError.Error returns the error message.
type WALEntry ¶
type WALEntry struct {
SchemaVersion string `json:"schema_version"`
EntryID string `json:"entry_id"`
WorkflowID string `json:"workflow_id"`
Generation int64 `json:"generation"` // expected generation before apply
NewGeneration int64 `json:"new_generation"`
Command string `json:"command"`
Operations []WALOp `json:"operations,omitempty"`
Committed bool `json:"committed"`
CreatedAt time.Time `json:"created_at"`
CommittedAt *time.Time `json:"committed_at,omitempty"`
}
WALEntry is one durable journal entry for ApplyTransition.
type WALOp ¶
type WALOp struct {
// Kind is one of: workflow, node, run, handoff, child_batch, child_result, service, desired_state, amendment, control.
Kind string `json:"kind"`
// ID is the resource identity (node_id, run_id, etc.).
ID string `json:"id,omitempty"`
// Payload is the full JSON body to materialize (optional for delete).
Payload json.RawMessage `json:"payload,omitempty"`
// Action is put (default) or delete.
Action string `json:"action,omitempty"`
}
WALOp is a single materialization operation inside a workflow transition.
type WorkflowCredentialRecord ¶
type WorkflowCredentialRecord struct {
SchemaVersion string `json:"schema_version"`
WorkflowID WorkflowID `json:"workflow_id"`
TargetID string `json:"target_id"`
Provider string `json:"provider"`
// Typed availability state.
Available bool `json:"available"`
Generation int64 `json:"generation"`
Scope string `json:"scope"` // workflow, run, attempt
// Source of the availability record.
SourceNodeID NodeID `json:"source_node_id,omitempty"`
SourceAttempt AttemptID `json:"source_attempt_id,omitempty"`
// Typed cause of unavailability.
Cause string `json:"cause,omitempty"`
CheckedAt time.Time `json:"checked_at"`
}
WorkflowCredentialRecord tracks credential/provider availability for a workflow.
type WorkflowID ¶
type WorkflowID string
WorkflowID identifies a workflow.
func NewWorkflowID ¶
func NewWorkflowID() (WorkflowID, error)
NewWorkflowID generates a cryptographically random workflow ID.
func (WorkflowID) MarshalText ¶
func (id WorkflowID) MarshalText() ([]byte, error)
WorkflowID.MarshalText marshals the value as text.
It returns an error if the operation fails or inputs are invalid.
func (*WorkflowID) Scan ¶
func (id *WorkflowID) Scan(src interface{}) error
WorkflowID.Scan scans a database value into workflow id.
It returns an error if the operation fails or inputs are invalid.
func (WorkflowID) String ¶
func (id WorkflowID) String() string
WorkflowID.String returns the string representation.
func (*WorkflowID) UnmarshalText ¶
func (id *WorkflowID) UnmarshalText(b []byte) error
WorkflowID.UnmarshalText unmarshals the value as text.
It returns an error if the operation fails or inputs are invalid.
type WorkflowPolicySnapshot ¶
type WorkflowPolicySnapshot struct {
SchemaVersion string `json:"schema_version"`
PolicyDigest string `json:"policy_digest"`
CatalogSnapshotRef string `json:"catalog_snapshot_ref,omitempty"`
MaxActiveDurationMs int64 `json:"max_active_duration_ms"`
MaxAttemptLeaseMs int64 `json:"max_attempt_lease_ms"`
MaxLLMSpendDecimal string `json:"max_llm_spend_decimal"`
}
WorkflowPolicySnapshot contains immutable workflow-policy references.
type WorkflowRecord ¶
type WorkflowRecord struct {
SchemaVersion string `json:"schema_version"`
WorkflowID WorkflowID `json:"workflow_id"`
WorkflowKind string `json:"workflow_kind"` // standalone, pipeline, parent_child
InvocationID InvocationID `json:"invocation_id"`
DeploymentID DeploymentID `json:"deployment_id"`
Status WorkflowStatus `json:"status"`
Generation int64 `json:"generation"`
// Immutable policy and catalog snapshot refs.
PolicyDigest string `json:"policy_digest"`
CatalogSnapshotRef string `json:"catalog_snapshot_ref,omitempty"`
// Aggregate ceilings.
MaxActiveDurationMs int64 `json:"max_active_duration_ms"`
MaxAttemptLeaseMs int64 `json:"max_attempt_lease_ms"`
MaxLLMSpendDecimal string `json:"max_llm_spend_decimal"`
// Authority generation for limit amendments.
AuthorityGeneration int64 `json:"authority_generation"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TerminatedAt *time.Time `json:"terminated_at,omitempty"`
TerminalReason *FailureReason `json:"terminal_reason,omitempty"`
}
WorkflowRecord is the durable record of a workflow.
type WorkflowReport ¶
type WorkflowReport struct {
SchemaVersion string `json:"schema_version"`
WorkflowID WorkflowID `json:"workflow_id"`
WorkflowKind string `json:"workflow_kind"`
RequestedDeploymentRef string `json:"requested_deployment_ref"`
ResolvedDeploymentID DeploymentID `json:"resolved_deployment_id"`
ResolvedDeploymentVersion string `json:"resolved_deployment_version"`
ResolvedDeploymentDigest string `json:"resolved_deployment_digest"`
InvocationID InvocationID `json:"invocation_id"`
Nodes []PipelineNode `json:"nodes,omitempty"`
ActiveNodeIDs []NodeID `json:"active_node_ids,omitempty"`
ServiceBindings []MCPServiceBinding `json:"service_bindings,omitempty"`
Handoffs []HandoffEnvelope `json:"handoffs,omitempty"`
ChildBatches []ChildBatch `json:"child_batches,omitempty"`
AggregateLimits *WorkflowPolicySnapshot `json:"aggregate_limits,omitempty"`
AggregateUsage *AggregateUsageSummary `json:"aggregate_usage,omitempty"`
ActiveTime *ActiveTimeLedger `json:"active_time,omitempty"`
LimitAmendments []LimitAmendment `json:"limit_amendments,omitempty"`
ControlHistory []ControlRequest `json:"control_history,omitempty"`
TerminalReason *FailureReason `json:"terminal_reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
WorkflowReport is the portable report for a completed workflow.
type WorkflowStatus ¶
type WorkflowStatus int
WorkflowStatus represents the lifecycle status of a workflow.
const ( WorkflowStatusPending WorkflowStatus = iota // 0 WorkflowStatusRunning // 1 WorkflowStatusPauseRequested // 2 WorkflowStatusPaused // 3 WorkflowStatusNeedsReplan // 4 WorkflowStatusSucceeded // 5 WorkflowStatusFailed // 6 WorkflowStatusCancelled // 7 WorkflowStatusExpired // 8 WorkflowStatusBudgetExceeded // 9 )
func AllWorkflowStatuses ¶
func AllWorkflowStatuses() []WorkflowStatus
AllWorkflowStatuses returns all valid WorkflowStatus values.
func (WorkflowStatus) IsTerminal ¶
func (s WorkflowStatus) IsTerminal() bool
IsTerminal returns true for terminal workflow statuses.
func (WorkflowStatus) MarshalJSON ¶
func (s WorkflowStatus) MarshalJSON() ([]byte, error)
WorkflowStatus.MarshalJSON marshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (WorkflowStatus) String ¶
func (s WorkflowStatus) String() string
WorkflowStatus.String returns the string representation.
func (*WorkflowStatus) UnmarshalJSON ¶
func (s *WorkflowStatus) UnmarshalJSON(data []byte) error
WorkflowStatus.UnmarshalJSON unmarshals the value as JSON.
It returns an error if the operation fails or inputs are invalid.
func (WorkflowStatus) Valid ¶
func (s WorkflowStatus) Valid() bool
WorkflowStatus.Valid reports whether the workflow status value is valid.
type WorkflowStore ¶
type WorkflowStore interface {
// CreateWorkflow persists a new workflow record.
CreateWorkflow(ctx context.Context, wf *WorkflowRecord) error
// GetWorkflow retrieves a workflow by ID.
GetWorkflow(ctx context.Context, workflowID WorkflowID) (*WorkflowRecord, error)
// UpdateWorkflow atomically updates a workflow record.
UpdateWorkflow(ctx context.Context, wf *WorkflowRecord, expectedGeneration int64) error
// ListWorkflows lists all workflows.
ListWorkflows(ctx context.Context) ([]*WorkflowRecord, error)
// CreateNode persists a new pipeline node.
CreateNode(ctx context.Context, node *PipelineNode) error
// GetNode retrieves a node by ID.
GetNode(ctx context.Context, nodeID NodeID) (*PipelineNode, error)
// UpdateNode atomically updates a node record.
UpdateNode(ctx context.Context, node *PipelineNode, expectedGeneration int64) error
// ListNodes lists nodes for a workflow.
ListNodes(ctx context.Context, workflowID WorkflowID) ([]*PipelineNode, error)
// RegisterService registers an MCP service binding.
RegisterService(ctx context.Context, svc *MCPServiceBinding) error
// UpdateService updates a service binding status.
UpdateService(ctx context.Context, svc *MCPServiceBinding, expectedGeneration int64) error
// ListServices lists service bindings for a workflow.
ListServices(ctx context.Context, workflowID WorkflowID) ([]*MCPServiceBinding, error)
// CommitHandoff commits a handoff envelope atomically (single-commit).
CommitHandoff(ctx context.Context, handoff *HandoffEnvelope) error
// GetHandoff retrieves a handoff by ID.
GetHandoff(ctx context.Context, handoffID HandoffID) (*HandoffEnvelope, error)
// ListHandoffs lists handoffs for a workflow.
ListHandoffs(ctx context.Context, workflowID WorkflowID) ([]*HandoffEnvelope, error)
// CreateChildBatch persists a new child batch.
CreateChildBatch(ctx context.Context, batch *ChildBatch) error
// UpdateChildBatch atomically updates a child batch.
UpdateChildBatch(ctx context.Context, batch *ChildBatch, expectedGeneration int64) error
// ListChildBatches lists child batches for a workflow.
ListChildBatches(ctx context.Context, workflowID WorkflowID) ([]*ChildBatch, error)
// CommitChildResult commits a child result atomically.
CommitChildResult(ctx context.Context, result *ChildResult) error
// ListChildResults lists child results for a child batch.
ListChildResults(ctx context.Context, childBatchID ChildBatchID) ([]*ChildResult, error)
// RequestControl submits a control request.
RequestControl(ctx context.Context, req *ControlRequest) error
// GetDesiredState returns the current desired state for a workflow.
GetDesiredState(ctx context.Context, workflowID WorkflowID) (*DesiredState, error)
// AppendControlResult appends a control result record.
AppendControlResult(ctx context.Context, req *ControlRequest, result interface{}) error
// AppendLimitAmendment atomically appends a limit amendment to a workflow.
// Uses expectedAuthorityGeneration for compare-and-swap.
AppendLimitAmendment(ctx context.Context, workflowID WorkflowID, expectedAuthorityGeneration int64, amendment *LimitAmendment) error
// ApplyTransition applies one atomic logical update spanning node/run
// result, handoff or child result, aggregate counters, and the next
// workflow state. Uses compare-and-swap generation and idempotency.
ApplyTransition(ctx context.Context, workflowID WorkflowID, expectedGeneration int64, command string) error
}
WorkflowStore defines the durable storage interface for workflows, nodes, services, handoffs, and child batches.