state

package
v0.1.98 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package state stores deployment state and runtime metadata (design doc §5.2, §14).

DeploymentStore, TransactionalDeployment, and RuntimeStore are the boundaries plan, apply, and runtime code should use so callers do not depend on a specific SQL backend. MVP implements them in internal/state/sqlite.

Thread-safety: interfaces assume a single-process CLI unless a concrete backend documents stronger concurrency guarantees.

Index

Constants

View Source
const (
	DefaultTenantID = "tenant-1"
	DefaultThreadID = "thread-1"
	DefaultActorID  = "user-1"
	DefaultSource   = "cli"
)

Local development defaults for run attribution (issue #111). Do not rely on these in CI or production; pass explicit tenant, thread, and actor identifiers.

View Source
const (
	DefaultRunListLimit = 50
	MaxRunListLimit     = 500
)

Run list limits shared by SQLite queries and HTTP/CLI surfaces.

View Source
const (
	ArtifactKindResolvedGraph      = "resolved_graph"
	ArtifactKindExecutionIR        = "execution_ir"
	ArtifactKindCapabilityManifest = "capability_manifest"
	ArtifactKindSchemaBundle       = "schema_bundle"
)

Artifact kind values for deployment_artifacts (issue #207).

View Source
const (
	RunStatusRunning     = "running"
	RunStatusInterrupted = "interrupted"
	RunStatusSucceeded   = "succeeded"
	RunStatusFailed      = "failed"
)

Run status values stored on runs (design doc §14.2, issue #105).

View Source
const (
	TraceActorTypeUser   = "user"
	TraceActorTypeAgent  = "agent"
	TraceActorTypeSystem = "system"
)

Trace actor_type column values (issue #115). Canonical typed enums live in internal/trace.

View Source
const (
	CheckpointStatusRunning     = "running"
	CheckpointStatusInterrupted = "interrupted"
	CheckpointStatusCompleted   = "completed"
	CheckpointStatusFailed      = "failed"
)

Checkpoint status values stored in run_checkpoints (issue #105).

View Source
const DefaultEnvironment = "local"

DefaultEnvironment is the deployment/runtime env when none is selected (matches CLI planEnvironment).

Variables

View Source
var ErrAttributionRequired = errors.New("attribution required: set tenant_id, thread_id, and actor_id")

ErrAttributionRequired is returned when explicit tenant, thread, and actor ids are required but one or more are omitted (issue #111 production guardrail).

Functions

func ApplyAttribution

func ApplyAttribution(r *Run, a RunAttribution)

ApplyAttribution copies normalized attribution onto a Run.

func ClampRunListLimit

func ClampRunListLimit(limit int) int

ClampRunListLimit returns limit clamped to [DefaultRunListLimit, MaxRunListLimit] when limit <= 0 or above max.

func NormalizeAttribution

func NormalizeAttribution(a *RunAttribution)

NormalizeAttribution fills empty attribution fields with DefaultTenantID, DefaultThreadID, DefaultActorID, and DefaultSource. Optional fields (parent run, idempotency key) stay empty when unset.

func RequireExplicitAttribution

func RequireExplicitAttribution(a RunAttribution) error

RequireExplicitAttribution returns ErrAttributionRequired when tenant_id, thread_id, or actor_id is empty. Call before NormalizeAttribution when production guardrails are enabled.

func UsesAttributionDefaults

func UsesAttributionDefaults(a RunAttribution) bool

UsesAttributionDefaults reports whether any core attribution field is unset and would receive a local default from NormalizeAttribution.

Types

type AppliedProject

type AppliedProject struct {
	ProjectName string
	Env         string
	Version     string
	AppliedAt   time.Time
}

AppliedProject is one row in applied_projects (design doc §14.1).

type AppliedResource

type AppliedResource struct {
	Kind               string
	Name               string
	Env                string
	SpecHash           string
	NormalizedSpecJSON string
	AppliedAt          time.Time
}

AppliedResource is one row in applied_resources (design doc §14.1).

type ArtifactStore added in v0.1.94

type ArtifactStore interface {
	// PutArtifact stores a immutable payload, deduped by Digest. Re-putting an identical digest is
	// a no-op and never overwrites the stored payload.
	PutArtifact(ctx context.Context, a DeploymentArtifact) error
	// GetArtifact returns the artifact for digest, or sql.ErrNoRows.
	GetArtifact(ctx context.Context, digest string) (*DeploymentArtifact, error)
	// PutSnapshot stores a snapshot row, deduped by Digest. Re-putting is a no-op.
	PutSnapshot(ctx context.Context, s DeploymentSnapshot) error
	// GetSnapshot returns the snapshot for digest, or sql.ErrNoRows.
	GetSnapshot(ctx context.Context, digest string) (*DeploymentSnapshot, error)
	// SetCurrentSnapshot points env at digest — the snapshot deployed now. Called on every apply,
	// including a re-apply of an earlier digest (rollback), so the pointer always reflects the last
	// apply, not first-insert order.
	SetCurrentSnapshot(ctx context.Context, env, digest string) error
	// CurrentSnapshotDigestForEnv returns the snapshot digest currently deployed for env (the apply
	// pointer), or sql.ErrNoRows. Used to flag a run as executing a superseded artifact
	// (inspect/logs): superseded == run's pinned digest differs from this.
	CurrentSnapshotDigestForEnv(ctx context.Context, env string) (string, error)
	// PruneUnreferencedArtifacts deletes snapshots not referenced by any run and artifacts not
	// referenced by any surviving snapshot. Trace pruning must not orphan an artifact a run still
	// references, so this is reference-guarded. Returns rows removed.
	PruneUnreferencedArtifacts(ctx context.Context) (removed int64, err error)
}

ArtifactStore persists immutable, content-addressed deployment artifacts and snapshots (design doc §14, issue #207). Writes are insert-if-absent (dedupe by content); artifacts and snapshots are never mutated once written.

type DeploymentArtifact added in v0.1.94

type DeploymentArtifact struct {
	Digest        string
	Kind          string
	FormatVersion string
	Payload       []byte
	CreatedAt     time.Time
}

DeploymentArtifact is one immutable, content-addressed payload in deployment_artifacts (design doc §14, issue #207). Digest is the SHA-256 of Payload; identical payloads dedupe. FormatVersion says how to decode Payload and must be checked before use — never reinterpret an unknown format.

type DeploymentSnapshot added in v0.1.94

type DeploymentSnapshot struct {
	Digest                   string
	FormatVersion            string
	CompilerVersion          string
	Environment              string
	GraphDigest              string
	ExecutionIRDigest        string
	CapabilityManifestDigest string
	SchemaBundleDigest       string
	CreatedAt                time.Time
}

DeploymentSnapshot is one row in deployment_snapshots (design doc §14, issue #207): the content-addressed root of the immutable configuration a run executed under. Digest is over the canonical snapshot identity (format_version, compiler_version, environment, and the three artifact digests) — not over timestamps or paths, so it is stable across a change of --state path or project directory. CompilerVersion is provenance for the compilation as a whole; each referenced artifact carries its own FormatVersion.

type DeploymentStore

type DeploymentStore interface {
	UpsertAppliedResource(ctx context.Context, r AppliedResource) error
	GetAppliedResource(ctx context.Context, env string, id spec.ResourceID) (*AppliedResource, error)
	ListAppliedResourcesByEnv(ctx context.Context, env string) ([]AppliedResource, error)
	DeleteAppliedResource(ctx context.Context, env string, id spec.ResourceID) error
	UpsertAppliedProject(ctx context.Context, p AppliedProject) error
	GetAppliedProject(ctx context.Context, env, projectName string) (*AppliedProject, error)
}

DeploymentStore persists deployment rows from design doc §14.1 (applied_resources, applied_projects).

Thread-safety: MVP targets a single-process CLI. Implementations are not required to support arbitrary concurrent callers; treat the store as non-thread-safe unless a backend documents otherwise.

type Run

type Run struct {
	RunID            string
	WorkflowName     string
	Env              string
	Status           string
	StartedAt        time.Time
	FinishedAt       *time.Time
	InputJSON        string
	OutputJSON       string
	ErrorText        string
	TotalCostUSD     float64
	WorkflowSpecHash string
	EnvironmentName  string
	// DeploymentSnapshotDigest pins the immutable deployment snapshot this run executes under
	// (issue #207). Resume hydrates configuration and authority from this snapshot rather than
	// re-resolving current config, so a policy/tool/manifest edit landing mid-run cannot change an
	// in-flight run's authority. Empty for runs created before #207 (resume falls back to current
	// config for those).
	DeploymentSnapshotDigest string
	TenantID                 string
	ThreadID                 string
	ActorID                  string
	ParentRunID              string
	RequestID                string
	IdempotencyKey           string
	Source                   string
}

Run is one workflow execution row in runs (design doc §14.2).

type RunAttribution

type RunAttribution struct {
	TenantID       string
	ThreadID       string
	ActorID        string
	ParentRunID    string
	RequestID      string
	IdempotencyKey string
	Source         string
}

RunAttribution scopes a run to a tenant and thread and records who triggered it.

func AttributionFromRun

func AttributionFromRun(r *Run) RunAttribution

AttributionFromRun copies persisted attribution from a run row.

type RunCheckpoint

type RunCheckpoint struct {
	RunID       string
	Seq         int64
	StepIndex   int
	StepID      string
	ContextJSON string
	Status      string
	CreatedAt   time.Time
}

RunCheckpoint is one row in run_checkpoints (issue #105). ContextJSON holds the opaque engine-owned execution snapshot (interpolation context, accumulated step outputs, total cost) serialized as canonical JSON.

type RunListFilter

type RunListFilter struct {
	TenantID     string
	ThreadID     string
	ActorID      string
	WorkflowName string
	Limit        int
}

RunListFilter selects runs for logs and inspector queries (issue #111). Empty filter fields are ignored. Limit is clamped via ClampRunListLimit.

type RunStep

type RunStep struct {
	RunID      string
	StepID     string
	Status     string
	StartedAt  *time.Time
	FinishedAt *time.Time
	InputJSON  string
	OutputJSON string
	ErrorText  string
	CostUSD    float64
}

RunStep is one row in run_steps (design doc §14.2).

type RuntimeStore

type RuntimeStore interface {
	StartRun(ctx context.Context, r Run) error
	FinishRun(ctx context.Context, runID, status string, finishedAt time.Time, outputJSON, errorText string, totalCostUSD float64) error
	UpsertRunStep(ctx context.Context, st RunStep) error
	AppendTraceEvent(ctx context.Context, runID string, ts time.Time, eventType, actorType, stepID, dataJSON string) (seq int64, err error)
	GetRun(ctx context.Context, runID string) (*Run, error)
	// ListRecentRuns returns runs ordered by started_at descending (newest first), limited to limit rows.
	ListRecentRuns(ctx context.Context, limit int) ([]Run, error)
	// ListRunsByWorkflow returns runs for the given workflow_name ordered by started_at descending.
	ListRunsByWorkflow(ctx context.Context, workflowName string, limit int) ([]Run, error)
	// ListRunsFiltered returns runs matching optional tenant/thread/actor/workflow filters.
	ListRunsFiltered(ctx context.Context, filter RunListFilter) ([]Run, error)
	ListTraceEventsByRunID(ctx context.Context, runID string) ([]TraceEvent, error)
	// DeleteRunsStartedBefore removes every run with started_at strictly before cutoff (UTC), and
	// associated run_steps / trace_events (SQLite: ON DELETE CASCADE). Used for trace retention (issue #75).
	DeleteRunsStartedBefore(ctx context.Context, cutoff time.Time) (deleted int64, err error)
	// SaveCheckpoint appends a checkpoint row for run_id (monotonic seq per run).
	SaveCheckpoint(ctx context.Context, cp RunCheckpoint) error
	// GetLatestCheckpoint returns the newest checkpoint for run_id or sql.ErrNoRows.
	GetLatestCheckpoint(ctx context.Context, runID string) (*RunCheckpoint, error)
	// UpdateRunStatus sets runs.status without finishing the run (issue #105 interrupted).
	UpdateRunStatus(ctx context.Context, runID, status string) error
}

RuntimeStore persists execution rows from design doc §14.2 (runs, run_steps, trace_events).

Thread-safety: same expectations as DeploymentStore.

type TraceEvent

type TraceEvent struct {
	RunID     string
	Seq       int64
	Timestamp time.Time
	Type      string
	ActorType string
	StepID    string
	DataJSON  string
	TenantID  string
	ThreadID  string
	ActorID   string
	// PrevHash and Hash link events into a per-run tamper-evident chain (issue #116).
	// Empty values mean the row predates the chain migration or was not chained on insert.
	PrevHash string
	Hash     string
}

TraceEvent is one append-only row in trace_events (design doc §14.2).

type TransactionalDeployment

type TransactionalDeployment interface {
	RunDeploymentTx(ctx context.Context, fn func(ctx context.Context, dep DeploymentStore) error) error
}

TransactionalDeployment runs deployment mutations in a single atomic transaction when supported (design doc §12.2 D apply, issue #15).

Directories

Path Synopsis
Package sqlite implements deployment and runtime/trace state in SQLite (design doc §§14.1–14.2).
Package sqlite implements deployment and runtime/trace state in SQLite (design doc §§14.1–14.2).

Jump to

Keyboard shortcuts

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