Documentation
¶
Overview ¶
Package state provides structured graph state, paths, contracts, patches, and snapshots.
Index ¶
- Constants
- func Append[T any](writer Writer, ref Ref[[]T], value T) error
- func CloneValue(value any) (any, error)
- func CountKeys(current *State) int
- func CountScopes(current *State) int
- func Delete[T any](writer Writer, ref Ref[T]) error
- func DeletePath(current *State, path string) error
- func Get[T any](reader Reader, ref Ref[T]) (T, error)
- func IsNilReducer(reducer Reducer) bool
- func Merge(writer Writer, ref Ref[map[string]any], value map[string]any) error
- func MergePath(current *State, path string, value map[string]any) error
- func Read[T any](reader Reader, ref Ref[T]) (T, bool)
- func ReadPath(current *State, path string) (any, bool)
- func ReadRequired[T any](reader Reader, ref Ref[T]) (T, error)
- func Reduce[T any](writer Writer, ref Ref[T], value T) error
- func Replace[T any](writer Writer, ref Ref[T], value T) error
- func ResolveStateValue(root any, segments []string) (any, bool)
- func SetPath(current *State, path string, value any) error
- func SplitStatePath(path string) []string
- func SummaryFields(current *State) []zap.Field
- func ValidateJSONSchemaDefinition(schema JSONSchema) error
- type Access
- func (a *Access) AppendAny(path Path, value any) error
- func (a *Access) Delete(path Path) error
- func (a *Access) MergeAny(path Path, value map[string]any) error
- func (a *Access) Patch() Patch
- func (a *Access) ReadAny(path Path) (any, bool)
- func (a *Access) ReduceAny(path Path, reducer string, value any) error
- func (a *Access) SetAny(path Path, value any) error
- func (a *Access) State() *State
- type AccessMode
- type ArtifactRef
- type BranchPatch
- type BreakpointHit
- type Change
- type Codec
- type Contract
- type Editor
- func (e *Editor) AppendAny(path Path, value any) error
- func (e *Editor) Delete(path Path) error
- func (e *Editor) MergeAny(path Path, value map[string]any) error
- func (e *Editor) Patch() Patch
- func (e *Editor) ReadAny(path Path) (any, bool)
- func (e *Editor) ReduceAny(path Path, reducer string, value any) error
- func (e *Editor) SetAny(path Path, value any) error
- func (e *Editor) State() *State
- type FieldAccess
- type JSONSchema
- type JSONStateCodec
- type MaxReducer
- type MergeStrategy
- type MessagesReducer
- type ParallelMergeOptions
- type Patch
- type PatchOp
- type PatchOpKind
- type Path
- func Internal(namespace string, segments ...string) Path
- func MustPath(section string, segments ...string) Path
- func NewPath(section string, segments ...string) (Path, error)
- func ParsePath(text string) (Path, error)
- func Runtime(segments ...string) Path
- func Scope(scope string, segments ...string) Path
- func Shared(segments ...string) Path
- func (p Path) Child(segments ...string) (Path, error)
- func (p Path) Empty() bool
- func (p Path) MarshalJSON() ([]byte, error)
- func (p Path) MustChild(segments ...string) Path
- func (p Path) Section() string
- func (p Path) Segments() []string
- func (p Path) String() string
- func (p *Path) UnmarshalJSON(data []byte) error
- type Reader
- type Reducer
- type Ref
- func (r Ref[T]) Path() Path
- func (r Ref[T]) ReadField() FieldAccess
- func (r Ref[T]) ReadWriteField() FieldAccess
- func (r Ref[T]) Required() Ref[T]
- func (r Ref[T]) WithDescription(description string) Ref[T]
- func (r Ref[T]) WithMerge(strategy MergeStrategy) Ref[T]
- func (r Ref[T]) WithReducer(identifier string) Ref[T]
- func (r Ref[T]) WriteField() FieldAccess
- type RestoredStateSnapshot
- type RuntimeState
- type Snapshot
- type State
- func FromMap(input map[string]any) *State
- func FromShared(shared map[string]any) *State
- func FromSnapshot(snapshot Snapshot) (*State, error)
- func MergeParallelPatches(base *State, branches []BranchPatch, options ParallelMergeOptions) (*State, error)
- func MergeResumeInput(base *State, input *State) (*State, error)
- func NewState() *State
- func PrepareContinuationState(base *State, input *State) (*State, error)
- func ProjectStateByContract(full *State, contract Contract) *State
- type SumReducer
- type ValidationError
- type ValidationIssue
- func ValidateAppliedInputPatchByContract(inputState *State, patch Patch, contract Contract) []ValidationIssue
- func ValidateAppliedPatchResultByContract(resultState *State, patch Patch, contract Contract) []ValidationIssue
- func ValidateContract(contract Contract) []ValidationIssue
- func ValidateInputPatch(patch Patch) []ValidationIssue
- func ValidateInputPatchByContract(patch Patch, contract Contract) []ValidationIssue
- func ValidateInputPatchByContractWithReducers(base *State, patch Patch, contract Contract, reducers map[string]Reducer) []ValidationIssue
- func ValidateJSONSchemaValue(value any, schema JSONSchema, basePath string) []ValidationIssue
- func ValidateNodePatch(patch Patch) []ValidationIssue
- func ValidatePatch(patch Patch) []ValidationIssue
- func ValidatePatchByContract(patch Patch, contract Contract) []ValidationIssue
- func ValidatePatchResultByContract(base *State, patch Patch, contract Contract) []ValidationIssue
- func ValidatePatchResultByContractWithReducers(base *State, patch Patch, contract Contract, reducers map[string]Reducer) []ValidationIssue
- func ValidateRequiredReads(current *State, contract Contract) []ValidationIssue
- func ValidateStateBySchemas(currentState *State, schemas map[string]JSONSchema) []ValidationIssue
- type Writer
Constants ¶
const ( SectionShared = "shared" // SectionScopes stores state namespaced by node or agent scope. SectionScopes = "scopes" // SectionInternal is reserved for framework internals. SectionInternal = "internal" // SectionRuntime stores checkpoint/runtime metadata. SectionRuntime = "runtime" )
const DefaultSnapshotVersion = "state-v2"
Variables ¶
This section is empty.
Functions ¶
func Append ¶
Append records an append operation for a slice ref while preserving the concrete []T type when the path is initially missing.
func CloneValue ¶
CloneValue returns a cycle-safe best-effort copy of value. Pointer and map identity, plus repeated references to the same slice view, are preserved within the copied object graph, including cycles. Distinct overlapping slice views are copied independently and need not share backing storage. The returned error means full isolation could not be proven because the graph contains an opaque reference value. In that case the returned copy may retain aliases and must not be exposed as an isolated view.
func CountScopes ¶
func DeletePath ¶
func Get ¶
Get returns the value at ref or a descriptive error that distinguishes missing paths from type mismatches.
func IsNilReducer ¶
func Read ¶
Read returns the value at ref and false when the path is missing or the value has a different Go type. JSON checkpoint restore preserves JSON-compatible shapes, but does not reconstruct arbitrary Go slice, map, or struct types; capability views that expose typed values should convert restored JSON shapes explicitly.
func ReadRequired ¶
ReadRequired is the error-returning form of Read kept for call-site clarity.
func SplitStatePath ¶
func SummaryFields ¶
func ValidateJSONSchemaDefinition ¶
func ValidateJSONSchemaDefinition(schema JSONSchema) error
Types ¶
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access is the node-facing state API. Read-only access wraps a State directly; editing access records structured patch ops and applies them to a working copy so later reads observe earlier writes.
func NewAccess ¶
NewAccess returns a read-only copy of state for inspection or condition evaluation. Mutating methods on the returned access fail.
func NewEditingAccess ¶
NewEditingAccess returns a copy-on-write view over state. Mutations update the working copy and are captured as a Patch for replay or parallel merging.
func (*Access) AppendAny ¶
AppendAny records an append operation at path. Prefer the typed Append helper when appending to a Ref[[]T].
func (*Access) ReadAny ¶
ReadAny reads a cloned value at path. The returned value can be mutated by the caller without changing state-owned data.
type AccessMode ¶
type AccessMode string
AccessMode describes how a node uses a state field.
const ( // AccessRead declares that a node reads the field. AccessRead AccessMode = "read" // AccessWrite declares that a node writes the field. AccessWrite AccessMode = "write" // AccessReadWrite declares that a node both reads and writes the field. AccessReadWrite AccessMode = "read_write" )
type ArtifactRef ¶
type ArtifactRef struct {
ID string `json:"id"`
RunID string `json:"run_id,omitempty"`
StepID string `json:"step_id,omitempty"`
NodeID string `json:"node_id,omitempty"`
OperationKey string `json:"operation_key,omitempty"`
ParentRunID string `json:"parent_run_id,omitempty"`
ParentStepID string `json:"parent_step_id,omitempty"`
ParentTaskID string `json:"parent_task_id,omitempty"`
RootRunID string `json:"root_run_id,omitempty"`
RunPath []string `json:"run_path,omitempty"`
Namespace string `json:"namespace,omitempty"`
Type string `json:"type,omitempty"`
MIMEType string `json:"mime_type,omitempty"`
Location string `json:"location,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
func CloneArtifactRefs ¶
func CloneArtifactRefs(artifacts []ArtifactRef) []ArtifactRef
type BranchPatch ¶
BranchPatch is one fan-in branch's state mutation.
Order must be stable for the graph wave. The merger uses Order, NodeID, then input order to make append and merge application deterministic.
type BreakpointHit ¶
type Change ¶
type Change struct {
Path string `json:"path"`
Before any `json:"before,omitempty"`
After any `json:"after,omitempty"`
}
func DiffSnapshots ¶
type Contract ¶
type Contract struct {
Fields []FieldAccess
WildcardRead bool
WildcardWrite bool
}
Contract declares the state paths a node may read or write. It is used for input projection, write validation, and parallel merge conflict handling.
func NewContract ¶
func NewContract(fields ...FieldAccess) Contract
NewContract constructs a contract from cloned field declarations.
func (Contract) WritePaths ¶
WritePaths returns unique paths declared writable by the contract.
type Editor ¶
type Editor struct {
// contains filtered or unexported fields
}
Editor applies patch operations to a working state while recording them for later replay. Most node code should use Access instead.
func NewEditorWithReducers ¶
type FieldAccess ¶
type FieldAccess struct {
Path Path
Mode AccessMode
Required bool
Merge MergeStrategy
Reducer string
Type string
Schema JSONSchema
Description string
}
FieldAccess declares one path in a node contract.
type JSONSchema ¶
func (JSONSchema) Clone ¶
func (schema JSONSchema) Clone() JSONSchema
func (JSONSchema) Type ¶
func (schema JSONSchema) Type() string
type JSONStateCodec ¶
type JSONStateCodec struct {
// contains filtered or unexported fields
}
func NewJSONStateCodec ¶
func NewJSONStateCodec(version string) *JSONStateCodec
func (*JSONStateCodec) Diff ¶
func (c *JSONStateCodec) Diff(before, after Snapshot) ([]Change, error)
func (*JSONStateCodec) Name ¶
func (c *JSONStateCodec) Name() string
func (*JSONStateCodec) Version ¶
func (c *JSONStateCodec) Version() string
type MaxReducer ¶
type MaxReducer struct{}
type MergeStrategy ¶
type MergeStrategy string
MergeStrategy describes how concurrent branch writes should be reconciled.
const ( // MergeDefault lets the merge engine infer behavior from patch operations. MergeDefault MergeStrategy = "" // MergeReplace allows only identical concurrent replacements. MergeReplace MergeStrategy = "replace" // MergeMerge allows object merge operations with disjoint keys. MergeMerge MergeStrategy = "merge" // MergeAppend allows append operations to be ordered deterministically. MergeAppend MergeStrategy = "append" )
type MessagesReducer ¶
type MessagesReducer struct{}
type ParallelMergeOptions ¶
type Patch ¶
type Patch struct {
// contains filtered or unexported fields
}
Patch is an ordered list of state mutations. It is immutable from callers' perspective: constructors and readers clone operation values.
func (Patch) Apply ¶
Apply replays the patch against a clone of base and returns the resulting state.
func (Patch) ApplyWithReducers ¶
func (Patch) MarshalJSON ¶
func (*Patch) UnmarshalJSON ¶
type PatchOp ¶
type PatchOp struct {
Kind PatchOpKind `json:"kind"`
Path Path `json:"path"`
Value any `json:"value,omitempty"`
Reducer string `json:"reducer,omitempty"`
}
PatchOp is one state mutation recorded by an Editor.
type PatchOpKind ¶
type PatchOpKind string
PatchOpKind identifies how a patch operation updates its path.
const ( // OpSet replaces the value at Path. OpSet PatchOpKind = "set" // OpDelete removes the value at Path. OpDelete PatchOpKind = "delete" // OpMerge deep-merges an object value into Path. OpMerge PatchOpKind = "merge" // OpAppend appends a value or slice of values to Path. OpAppend PatchOpKind = "append" OpReduce PatchOpKind = "reduce" )
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is the canonical address format used by state. Business code should construct paths through typed refs or capability views instead of parsing strings at call sites.
func NewPath ¶
NewPath constructs a validated state path from a known section and clean segments. Segments may not contain dots.
func ParsePath ¶
ParsePath parses the dotted form used in DSL and event payloads, for example "shared.request.input".
func (Path) MarshalJSON ¶
MarshalJSON encodes a path as its canonical dotted string.
func (Path) MustChild ¶
MustChild is Child for package-level ref declarations; it panics on invalid input.
func (*Path) UnmarshalJSON ¶
type Ref ¶
type Ref[T any] struct { // contains filtered or unexported fields }
Ref is a typed handle to one state path. It is intended to be declared once by a path-bound capability view and reused by business code.
func (Ref[T]) ReadField ¶
func (r Ref[T]) ReadField() FieldAccess
ReadField converts the ref into a read-only contract field.
func (Ref[T]) ReadWriteField ¶
func (r Ref[T]) ReadWriteField() FieldAccess
ReadWriteField converts the ref into a read-write contract field.
func (Ref[T]) Required ¶
Required marks the field as required when the ref is converted into a contract field.
func (Ref[T]) WithDescription ¶
WithDescription sets human-readable contract documentation.
func (Ref[T]) WithMerge ¶
func (r Ref[T]) WithMerge(strategy MergeStrategy) Ref[T]
WithMerge sets the parallel merge strategy emitted in contract fields.
func (Ref[T]) WithReducer ¶
func (Ref[T]) WriteField ¶
func (r Ref[T]) WriteField() FieldAccess
WriteField converts the ref into a write-only contract field.
type RestoredStateSnapshot ¶
type RestoredStateSnapshot struct {
Snapshot Snapshot `json:"snapshot"`
Business *State `json:"business"`
Runtime RuntimeState `json:"runtime"`
Artifacts []ArtifactRef `json:"artifacts,omitempty"`
}
func RestoreStateSnapshot ¶
func RestoreStateSnapshot(snapshot Snapshot) (RestoredStateSnapshot, error)
type RuntimeState ¶
type RuntimeState struct {
RunID string `json:"run_id,omitempty"`
CurrentStepID string `json:"current_step_id,omitempty"`
CurrentTaskID string `json:"current_task_id,omitempty"`
CurrentNodeID string `json:"current_node_id,omitempty"`
CurrentNodeIDs []string `json:"current_node_ids,omitempty"`
CurrentStepIDs []string `json:"current_step_ids,omitempty"`
NextNodeIDs []string `json:"next_node_ids,omitempty"`
ParallelWaveID string `json:"parallel_wave_id,omitempty"`
WaveID string `json:"wave_id,omitempty"`
Status string `json:"status,omitempty"`
RetryCount int `json:"retry_count,omitempty"`
PauseRequested bool `json:"pause_requested,omitempty"`
CancelRequested bool `json:"cancel_requested,omitempty"`
BreakpointHit *BreakpointHit `json:"breakpoint_hit,omitempty"`
}
type Snapshot ¶
type Snapshot struct {
Version string `json:"version"`
Scopes map[string]any `json:"scopes,omitempty"`
Internal map[string]any `json:"internal,omitempty"`
Runtime map[string]any `json:"runtime,omitempty"`
}
func SnapshotFromState ¶
func SnapshotFromStateWithRuntime ¶
func SnapshotFromStateWithRuntime(current *State, runtime RuntimeState, artifacts []ArtifactRef) (Snapshot, error)
type State ¶
type State struct {
// contains filtered or unexported fields
}
State is the private storage envelope for state. External packages should use Access, typed Ref values, or registered capability views instead of mutating this structure directly.
func FromMap ¶
FromMap creates state from an exported envelope. Missing root sections are initialized.
func FromShared ¶
FromShared creates state with best-effort copies placed under the shared section. Opaque values that cannot be safely cloned may retain aliases.
func FromSnapshot ¶
func MergeParallelPatches ¶
func MergeParallelPatches(base *State, branches []BranchPatch, options ParallelMergeOptions) (*State, error)
MergeParallelPatches applies fan-in branch patches to a shared base state in a deterministic order and rejects ambiguous overlapping writes.
func NewState ¶
func NewState() *State
NewState creates an empty state envelope with all root sections present.
func ProjectStateByContract ¶
func (*State) Clone ¶
Clone returns a cycle-safe best-effort copy of state. Callers that require proven isolation should use CloneStrict.
func (*State) CloneStrict ¶
CloneStrict returns an isolated copy or an error when state contains an opaque mutable value that cannot be safely cloned.
func (*State) MarshalJSON ¶
MarshalJSON encodes the exported state envelope.
func (*State) SetSection ¶
SetSection replaces one root section. The value must be an object.
func (*State) UnmarshalJSON ¶
UnmarshalJSON decodes an exported state envelope and initializes missing root sections.
type SumReducer ¶
type SumReducer struct{}
type ValidationError ¶
type ValidationError struct {
Boundary string `json:"boundary"`
Issues []ValidationIssue `json:"issues"`
}
func NewValidationError ¶
func NewValidationError(boundary string, issues []ValidationIssue) *ValidationError
func (*ValidationError) Error ¶
func (validationErr *ValidationError) Error() string
type ValidationIssue ¶
type ValidationIssue struct {
Path string `json:"path,omitempty"`
Kind string `json:"kind"`
Message string `json:"message"`
}
func ValidateAppliedInputPatchByContract ¶
func ValidateAppliedInputPatchByContract(inputState *State, patch Patch, contract Contract) []ValidationIssue
func ValidateAppliedPatchResultByContract ¶
func ValidateAppliedPatchResultByContract(resultState *State, patch Patch, contract Contract) []ValidationIssue
func ValidateContract ¶
func ValidateContract(contract Contract) []ValidationIssue
func ValidateInputPatch ¶
func ValidateInputPatch(patch Patch) []ValidationIssue
func ValidateInputPatchByContract ¶
func ValidateInputPatchByContract(patch Patch, contract Contract) []ValidationIssue
func ValidateJSONSchemaValue ¶
func ValidateJSONSchemaValue(value any, schema JSONSchema, basePath string) []ValidationIssue
func ValidateNodePatch ¶
func ValidateNodePatch(patch Patch) []ValidationIssue
func ValidatePatch ¶
func ValidatePatch(patch Patch) []ValidationIssue
func ValidatePatchByContract ¶
func ValidatePatchByContract(patch Patch, contract Contract) []ValidationIssue
func ValidatePatchResultByContract ¶
func ValidatePatchResultByContract(base *State, patch Patch, contract Contract) []ValidationIssue
func ValidateRequiredReads ¶
func ValidateRequiredReads(current *State, contract Contract) []ValidationIssue
func ValidateStateBySchemas ¶
func ValidateStateBySchemas(currentState *State, schemas map[string]JSONSchema) []ValidationIssue
type Writer ¶
type Writer interface {
SetAny(path Path, value any) error
Delete(path Path) error
MergeAny(path Path, value map[string]any) error
AppendAny(path Path, value any) error
ReduceAny(path Path, reducer string, value any) error
}
Writer is the minimal mutation surface used by typed refs and capability views. Implementations are expected to record explicit patch operations.