Skip to content

rules package reference

Package path: github.com/cpcf/gess/rules

const (
FieldConstraintOpUnknown FieldConstraintOperator = ""
FieldConstraintOpExists FieldConstraintOperator = "exists"
FieldConstraintOpEqual FieldConstraintOperator = "eq"
FieldConstraintOpNotEqual FieldConstraintOperator = "neq"
FieldConstraintOpLessThan FieldConstraintOperator = "lt"
FieldConstraintOpLessOrEqual FieldConstraintOperator = "lte"
FieldConstraintOpGreaterThan FieldConstraintOperator = "gt"
FieldConstraintOpGreaterOrEqual FieldConstraintOperator = "gte"
FieldConstraintExists = FieldConstraintOpExists
FieldConstraintEqual = FieldConstraintOpEqual
FieldConstraintNotEqual = FieldConstraintOpNotEqual
FieldConstraintLessThan = FieldConstraintOpLessThan
FieldConstraintLessOrEqual = FieldConstraintOpLessOrEqual
FieldConstraintGreaterThan = FieldConstraintOpGreaterThan
FieldConstraintGreaterOrEqual = FieldConstraintOpGreaterOrEqual
)

var (
ErrInvalidRuleset = errors.New("gess: invalid ruleset")
ErrIncompatibleRuleset = errors.New("gess: incompatible ruleset")
ErrClosedSession = errors.New("gess: closed session")
ErrConcurrencyMisuse = errors.New("gess: concurrency misuse")
ErrActionFailed = errors.New("gess: action failed")
ErrValidation = errors.New("gess: validation failed")
ErrFactNotFound = errors.New("gess: fact not found")
ErrStaleFactID = errors.New("gess: stale fact id")
ErrDuplicateFact = errors.New("gess: duplicate fact")
ErrMatcher = errors.New("gess: matcher error")
ErrUnsupportedRuntime = errors.New("gess: unsupported runtime")
ErrInvalidPath = errors.New("gess: invalid path")
ErrInvalidListPattern = errors.New("gess: invalid list pattern")
ErrInvalidHigherOrderCondition = errors.New("gess: invalid higher-order condition")
ErrAggregateValidation = errors.New("gess: aggregate validation failed")
ErrAggregateEvaluation = errors.New("gess: aggregate evaluation failed")
ErrFunctionValidation = errors.New("gess: function validation failed")
ErrFunctionEvaluation = errors.New("gess: function evaluation failed")
ErrQueryNotFound = errors.New("gess: query not found")
ErrQueryArgument = errors.New("gess: query argument failed")
ErrQueryValidation = errors.New("gess: query validation failed")
ErrQueryExecution = errors.New("gess: query execution failed")
ErrLogicalSupportUnavailable = errors.New("gess: logical support unavailable")
ErrLogicalOnlyRetract = errors.New("gess: cannot retract logical-only fact")
ErrLogicalFactModify = errors.New("gess: cannot modify fact with logical support")
ErrDivideByZero = errors.New("gess: divide by zero")
ErrBuiltinArgument = errors.New("gess: built-in function argument error")
ErrExplainLogUnavailable = errors.New("gess: explain log unavailable")
ErrRuleNotFound = errors.New("gess: rule not found")
ErrDemandCascadeLimit = errors.New("gess: backchain demand cascade limit exceeded")
ErrFactLimit = errors.New("gess: session fact limit exceeded")
ErrUnsupportedValue = errors.New("gess: unsupported value")
ErrInvalidCheckpoint = errors.New("gess: invalid checkpoint")
ErrUnsupportedCheckpointVersion = errors.New("gess: unsupported checkpoint version")
ErrInvalidMutationLog = errors.New("gess: invalid mutation log")
ErrUnsupportedMutationLogVersion = errors.New("gess: unsupported mutation log version")
)

AccumulateCondition maintains aggregate results over matching input facts.

type AccumulateCondition struct {
Input ConditionSpec
Specs []AggregateSpec
Source SourceSpan
}

Accumulate builds an AccumulateCondition.

func Accumulate(input ConditionSpec, specs ...AggregateSpec) AccumulateCondition

CloneAccumulateCondition returns a defensive copy of s.

func CloneAccumulateCondition(s AccumulateCondition) AccumulateCondition

Action is a compiled, inspectable action reference on a rule or query.

type Action struct {
NameValue string
Order int
GessSourceText string
AssertTemplateValuesAction *AssertTemplateValuesActionSpec
}

CloneAction returns a defensive copy of a.

func CloneAction(a Action) Action
func (a Action) AssertTemplateValues() (*AssertTemplateValuesActionSpec, bool)
func (a Action) DeclarationOrder() int
func (a Action) GessSource() string
func (a Action) Name() string

ActionBindingReadSetSpec declares which bindings an action reads.

type ActionBindingReadSetSpec struct {
Reads []ActionBindingReadSpec
}

CloneActionBindingReadSetSpec returns a defensive copy of s.

func CloneActionBindingReadSetSpec(s *ActionBindingReadSetSpec) *ActionBindingReadSetSpec

ActionBindingReadSpec declares one binding an action reads.

type ActionBindingReadSpec struct {
Binding string
Field string
Path PathSpec
}

CloneActionBindingReadSpec returns a defensive copy of s.

func CloneActionBindingReadSpec(s ActionBindingReadSpec) ActionBindingReadSpec

ActionCallSpec is a host-function call action.

type ActionCallSpec struct {
Name string
Fn DSLCallFunc
Args []ExpressionSpec
}

CloneActionCallSpec returns a defensive copy of s.

func CloneActionCallSpec(s *ActionCallSpec) *ActionCallSpec

ActionContext is passed to an ActionFunc. It exposes the activation’s identity and generation, read access to bound facts and values, and the mutation API.

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

NewActionContext returns an ActionContext backed by handle.

func NewActionContext(handle ActionContextHandle) ActionContext
func (c ActionContext) ActivationID() ActivationID
func (c ActionContext) Assert(templateKey TemplateKey, fields Fields) (AssertResult, error)
func (c ActionContext) AssertLogical(templateKey TemplateKey, fields Fields) (AssertResult, error)
func (c ActionContext) AssertTemplateValues(templateKey TemplateKey, values ...Value) error
func (c ActionContext) Binding(name string) (FactSnapshot, bool)
func (c ActionContext) BindingID(name string) (FactID, bool)
func (c ActionContext) BindingScalarValue(name, field string) (Value, bool)
func (c ActionContext) BindingValue(name string) (Value, bool)
func (c ActionContext) BoundFacts() []FactSnapshot
func (c ActionContext) ClearFocusStack() error
func (c ActionContext) Context() context.Context
func (c ActionContext) Emit(values ...Value) error
func (c ActionContext) Generation() Generation
func (c ActionContext) Global(name string) (Value, bool)
func (c ActionContext) Halt() error
func (c ActionContext) Modify(id FactID, patch FactPatch) (ModifyResult, error)
func (c ActionContext) PopFocus() (ModuleName, error)
func (c ActionContext) PushFocus(module ModuleName) error
func (c ActionContext) RHSBind(name string) (Value, bool)
func (c ActionContext) Retract(id FactID) (RetractResult, error)
func (c ActionContext) RuleID() RuleID
func (c ActionContext) RuleRevisionID() RuleRevisionID
func (c ActionContext) RulesetID() RulesetID
func (c ActionContext) SessionID() SessionID
func (c ActionContext) SetFocus(module ModuleName) error
func (c ActionContext) SetRHSBind(name string, value Value)

ActionContextHandle is the runtime implementation behind ActionContext.

type ActionContextHandle interface {
SetRHSBind(name string, value Value)
RHSBind(name string) (Value, bool)
Context() context.Context
SessionID() SessionID
RulesetID() RulesetID
ActivationID() ActivationID
RuleID() RuleID
RuleRevisionID() RuleRevisionID
Generation() Generation
BoundFacts() []FactSnapshot
Binding(name string) (FactSnapshot, bool)
BindingID(name string) (FactID, bool)
BindingValue(name string) (Value, bool)
BindingScalarValue(name, field string) (Value, bool)
Global(name string) (Value, bool)
Assert(templateKey TemplateKey, fields Fields) (AssertResult, error)
AssertLogical(templateKey TemplateKey, fields Fields) (AssertResult, error)
AssertTemplateValues(templateKey TemplateKey, values ...Value) error
Modify(id FactID, patch FactPatch) (ModifyResult, error)
Retract(id FactID) (RetractResult, error)
Halt() error
Emit(values ...Value) error
PushFocus(module ModuleName) error
SetFocus(module ModuleName) error
PopFocus() (ModuleName, error)
ClearFocusStack() error
}

ActionContextHandleOf returns the engine-owned implementation behind c.

func ActionContextHandleOf(c ActionContext) ActionContextHandle

ActionEffectKind identifies the mutation an ActionEffectSpec performs.

type ActionEffectKind uint8

ActionEffectAssert, ActionEffectAssertLogical, ActionEffectModify, ActionEffectRetract, ActionEffectEmit, ActionEffectBind, ActionEffectPushFocus, ActionEffectPopFocus, ActionEffectClearFocus, ActionEffectHalt

Section titled “ActionEffectAssert, ActionEffectAssertLogical, ActionEffectModify, ActionEffectRetract, ActionEffectEmit, ActionEffectBind, ActionEffectPushFocus, ActionEffectPopFocus, ActionEffectClearFocus, ActionEffectHalt”
const (
ActionEffectAssert ActionEffectKind = iota
ActionEffectAssertLogical
ActionEffectModify
ActionEffectRetract
ActionEffectEmit
ActionEffectBind
ActionEffectPushFocus
ActionEffectPopFocus
ActionEffectClearFocus
ActionEffectHalt
)

ActionEffectSpec is a declarative, expression-backed rule action.

type ActionEffectSpec struct {
Kind ActionEffectKind
// Target is the fact-binding name for modify/retract, or the local name
// for bind. Unused by emit.
Target string
// TemplateKey/FactName identify the asserted template for assert/-logical.
TemplateKey TemplateKey
FactName string
// Fields names the slots set by assert/modify, parallel to Values.
Fields []string
// Unset names the slots cleared by modify.
Unset []string
// Values are the expression-valued operands.
Values []ExpressionSpec
}

CloneActionEffectSpec returns a defensive copy of s.

func CloneActionEffectSpec(s *ActionEffectSpec) *ActionEffectSpec

ActionFunc is the Go implementation of a rule or query action.

type ActionFunc func(ActionContext) error

ActionSpec names one action implementation registered on a workspace.

type ActionSpec struct {
Name string
Fn ActionFunc
AssertTemplateValues *AssertTemplateValuesActionSpec
Effect *ActionEffectSpec
Call *ActionCallSpec
BindingReads *ActionBindingReadSetSpec
GessSource string
// NonEscaping allows the engine to skip freezing unread bindings after a
// rule fires. Set it only when Fn does not retain ActionContext or any
// binding-derived data that depends on post-return defensive snapshots.
NonEscaping bool
}

CloneActionSpec returns a defensive copy of s.

func CloneActionSpec(s ActionSpec) ActionSpec

ActivationID identifies one activation: a rule paired with the specific facts that matched it.

type ActivationID string
func (id ActivationID) IsZero() bool
func (id ActivationID) String() string

AggregateKind identifies which aggregate an AggregateSpec computes.

type AggregateKind string

AggregateCount, AggregateSum, AggregateMin, AggregateMax, AggregateCollect

Section titled “AggregateCount, AggregateSum, AggregateMin, AggregateMax, AggregateCollect”
const (
AggregateCount AggregateKind = "count"
AggregateSum AggregateKind = "sum"
AggregateMin AggregateKind = "min"
AggregateMax AggregateKind = "max"
AggregateCollect AggregateKind = "collect"
)

AggregateSpec is one aggregate computed over facts matching an accumulate input.

type AggregateSpec struct {
KindValue AggregateKind
ExpressionSpec ExpressionSpec
BindingName string
}

CloneAggregateSpec returns a defensive copy of s.

func CloneAggregateSpec(s AggregateSpec) AggregateSpec

Collect aggregates expression’s value from every matching fact into a list.

func Collect(expression ExpressionSpec) AggregateSpec

Count aggregates to the number of matching facts.

func Count() AggregateSpec

Max aggregates to the running maximum of expression over the group.

func Max(expression ExpressionSpec) AggregateSpec

Min aggregates to the running minimum of expression over the group.

func Min(expression ExpressionSpec) AggregateSpec

Sum aggregates to the running sum of expression over the group.

func Sum(expression ExpressionSpec) AggregateSpec
func (s AggregateSpec) As(binding string) AggregateSpec
func (s AggregateSpec) Binding() string
func (s AggregateSpec) Expression() ExpressionSpec
func (s AggregateSpec) Kind() AggregateKind

And groups condition tree nodes into a conjunction.

type And struct {
Conditions []ConditionSpec
Source SourceSpan
}

ApplyRulesetStatus is the outcome of applying a ruleset to a session.

type ApplyRulesetStatus string

ApplyRulesetApplied, ApplyRulesetUnchanged, ApplyRulesetIncompatible, ApplyRulesetClosed, ApplyRulesetConcurrencyMisuse

Section titled “ApplyRulesetApplied, ApplyRulesetUnchanged, ApplyRulesetIncompatible, ApplyRulesetClosed, ApplyRulesetConcurrencyMisuse”
const (
ApplyRulesetApplied ApplyRulesetStatus = "applied"
ApplyRulesetUnchanged ApplyRulesetStatus = "unchanged"
ApplyRulesetIncompatible ApplyRulesetStatus = "incompatible"
ApplyRulesetClosed ApplyRulesetStatus = "closed"
ApplyRulesetConcurrencyMisuse ApplyRulesetStatus = "concurrency_misuse"
)

AssertResult reports the outcome of an assert.

type AssertResult struct {
Status AssertStatus
Fact FactSnapshot
DuplicateKey DuplicateKey
Delta *MutationDelta
}

CloneAssertResult returns a defensive copy of result.

func CloneAssertResult(result AssertResult) AssertResult

Inserted reports whether the assert inserted a new fact.

func (r AssertResult) Inserted() bool

AssertStatus is the outcome of an assert.

type AssertStatus string

AssertInserted, AssertExisting, AssertReplaced, AssertValidationFailure, AssertClosed, AssertConcurrencyMisuse

Section titled “AssertInserted, AssertExisting, AssertReplaced, AssertValidationFailure, AssertClosed, AssertConcurrencyMisuse”
const (
AssertInserted AssertStatus = "inserted"
AssertExisting AssertStatus = "existing"
AssertReplaced AssertStatus = "replaced"
AssertValidationFailure AssertStatus = "validation_failure"
AssertClosed AssertStatus = "closed"
AssertConcurrencyMisuse AssertStatus = "concurrency_misuse"
)

AssertTemplateValuesActionSpec describes a generated rule action that emits values in template field order.

type AssertTemplateValuesActionSpec struct {
TemplateKey TemplateKey
Values []ExpressionSpec
}

CloneAssertTemplateValuesActionSpec returns a defensive copy of s.

func CloneAssertTemplateValuesActionSpec(s *AssertTemplateValuesActionSpec) *AssertTemplateValuesActionSpec

BindingFieldExpr references a field, or nested path, of an earlier condition’s binding.

type BindingFieldExpr struct {
Binding string
Field string
Path PathSpec
}

BindingPath builds a BindingFieldExpr referencing an earlier condition’s binding through path.

func BindingPath(binding string, path PathSpec) BindingFieldExpr

BindingValueExpr references a value binding, such as an aggregate result, from an earlier condition.

type BindingValueExpr struct {
Binding string
}

BooleanExpr combines Operands with Operator.

type BooleanExpr struct {
Operator ExpressionBooleanOperator
Operands []ExpressionSpec
}

CallExpr invokes a registered pure function by name with Args.

type CallExpr struct {
Name string
Args []ExpressionSpec
}

Call builds a CallExpr invoking the registered pure function name with args.

func Call(name string, args ...ExpressionSpec) CallExpr

CompareExpr compares Left and Right with Operator.

type CompareExpr struct {
Operator ExpressionComparisonOperator
Left ExpressionSpec
Right ExpressionSpec
}

ConditionID is a compiled rule or query condition’s stable identity.

type ConditionID string
func (id ConditionID) IsZero() bool
func (id ConditionID) String() string

ConditionSpec is a rule or query left-hand-side condition tree node.

type ConditionSpec interface {
// contains filtered or unexported methods
}

CloneConditionSpec returns a defensive copy of spec.

func CloneConditionSpec(spec ConditionSpec) ConditionSpec

ConditionTreeKind identifies the shape of a RuleConditionTree node.

type ConditionTreeKind string

ConditionTreeKindUnknown, ConditionTreeKindAnd, ConditionTreeKindMatch, ConditionTreeKindTest, ConditionTreeKindNot, ConditionTreeKindOr, ConditionTreeKindExists, ConditionTreeKindForall, ConditionTreeKindAccumulate

Section titled “ConditionTreeKindUnknown, ConditionTreeKindAnd, ConditionTreeKindMatch, ConditionTreeKindTest, ConditionTreeKindNot, ConditionTreeKindOr, ConditionTreeKindExists, ConditionTreeKindForall, ConditionTreeKindAccumulate”
const (
ConditionTreeKindUnknown ConditionTreeKind = ""
ConditionTreeKindAnd ConditionTreeKind = "and"
ConditionTreeKindMatch ConditionTreeKind = "match"
ConditionTreeKindTest ConditionTreeKind = "test"
ConditionTreeKindNot ConditionTreeKind = "not"
ConditionTreeKindOr ConditionTreeKind = "or"
ConditionTreeKindExists ConditionTreeKind = "exists"
ConditionTreeKindForall ConditionTreeKind = "forall"
ConditionTreeKindAccumulate ConditionTreeKind = "accumulate"
)

ConstExpr is a literal value in an expression tree.

type ConstExpr struct {
Value any
}

CurrentFieldExpr references a field, or nested path, of the fact matched by the current condition.

type CurrentFieldExpr struct {
Field string
Path PathSpec
}

CurrentPath builds a CurrentFieldExpr referencing the current condition’s fact through path.

func CurrentPath(path PathSpec) CurrentFieldExpr

DSLCallFunc is a host-provided action call implementation.

type DSLCallFunc func(ActionContext, []Value) error

DemandCascadeLimitError reports that a session stopped a backward-chaining demand cascade before processing another demand request.

type DemandCascadeLimitError struct {
Limit int
Steps int
}
func (e *DemandCascadeLimitError) Error() string
func (e *DemandCascadeLimitError) Is(target error) bool
func (e *DemandCascadeLimitError) Unwrap() error

DuplicateKey is the computed duplicate-detection key for a fact.

type DuplicateKey string

DuplicatePolicy controls how a template deduplicates facts.

type DuplicatePolicy int

DuplicateStructural, DuplicateAllow, DuplicateUniqueKey

Section titled “DuplicateStructural, DuplicateAllow, DuplicateUniqueKey”
const (
DuplicateStructural DuplicatePolicy = iota
DuplicateAllow
DuplicateUniqueKey
)

ExistsCondition tests whether at least one tuple matching Condition exists.

type ExistsCondition struct {
Condition ConditionSpec
Source SourceSpan
}

Exists builds an ExistsCondition.

func Exists(condition ConditionSpec) ExistsCondition

Explicit marks a positive match as ineligible for backward-chaining demand generation while keeping ordinary match behavior unchanged.

type Explicit struct {
Condition ConditionSpec
Source SourceSpan
}

ExpressionBooleanOperator is the operator in a BooleanExpr.

type ExpressionBooleanOperator string

ExpressionBoolUnknown, ExpressionBoolAnd, ExpressionBoolOr, ExpressionBoolNot

Section titled “ExpressionBoolUnknown, ExpressionBoolAnd, ExpressionBoolOr, ExpressionBoolNot”
const (
ExpressionBoolUnknown ExpressionBooleanOperator = ""
ExpressionBoolAnd ExpressionBooleanOperator = "and"
ExpressionBoolOr ExpressionBooleanOperator = "or"
ExpressionBoolNot ExpressionBooleanOperator = "not"
)

ExpressionComparisonOperator is the operator in a CompareExpr.

type ExpressionComparisonOperator string

ExpressionCompareUnknown, ExpressionCompareEqual, ExpressionCompareNotEqual, ExpressionCompareLessThan, ExpressionCompareLessOrEqual, ExpressionCompareGreaterThan, ExpressionCompareGreaterOrEqual

Section titled “ExpressionCompareUnknown, ExpressionCompareEqual, ExpressionCompareNotEqual, ExpressionCompareLessThan, ExpressionCompareLessOrEqual, ExpressionCompareGreaterThan, ExpressionCompareGreaterOrEqual”
const (
ExpressionCompareUnknown ExpressionComparisonOperator = ""
ExpressionCompareEqual ExpressionComparisonOperator = "eq"
ExpressionCompareNotEqual ExpressionComparisonOperator = "neq"
ExpressionCompareLessThan ExpressionComparisonOperator = "lt"
ExpressionCompareLessOrEqual ExpressionComparisonOperator = "lte"
ExpressionCompareGreaterThan ExpressionComparisonOperator = "gt"
ExpressionCompareGreaterOrEqual ExpressionComparisonOperator = "gte"
)

ExpressionFunctionParamSpec declares one named, typed parameter of an expression-backed function.

type ExpressionFunctionParamSpec struct {
Name string
Kind ValueKind
}

ExpressionFunctionSpec defines a pure function whose body is an expression.

type ExpressionFunctionSpec struct {
Name string
Params []ExpressionFunctionParamSpec
Return ValueKind
Expression ExpressionSpec
Description string
Source SourceSpan
}

CloneExpressionFunctionSpec returns a defensive copy of s.

func CloneExpressionFunctionSpec(s ExpressionFunctionSpec) ExpressionFunctionSpec

ExpressionPredicate wraps a compiled predicate for inspection.

type ExpressionPredicate struct {
ExpressionSpec ExpressionSpec
PlacementValue ExpressionPredicatePlacement
Order int
SourceSpan SourceSpan
}

CloneExpressionPredicate returns a defensive copy of p.

func CloneExpressionPredicate(p ExpressionPredicate) ExpressionPredicate

CloneExpressionPredicates returns a defensive copy of predicates.

func CloneExpressionPredicates(predicates []ExpressionPredicate) []ExpressionPredicate
func (p ExpressionPredicate) DeclarationOrder() int
func (p ExpressionPredicate) Expression() ExpressionSpec
func (p ExpressionPredicate) Placement() ExpressionPredicatePlacement
func (p ExpressionPredicate) Source() SourceSpan

ExpressionPredicatePlacement reports where the compiler placed a predicate.

type ExpressionPredicatePlacement string

ExpressionPredicatePlacementUnknown, ExpressionPredicatePlacementAlpha, ExpressionPredicatePlacementBetaResidual, ExpressionPredicatePlacementUnsupported

Section titled “ExpressionPredicatePlacementUnknown, ExpressionPredicatePlacementAlpha, ExpressionPredicatePlacementBetaResidual, ExpressionPredicatePlacementUnsupported”
const (
ExpressionPredicatePlacementUnknown ExpressionPredicatePlacement = ""
ExpressionPredicatePlacementAlpha ExpressionPredicatePlacement = "alpha"
ExpressionPredicatePlacementBetaResidual ExpressionPredicatePlacement = "beta-residual"
ExpressionPredicatePlacementUnsupported ExpressionPredicatePlacement = "unsupported"
)

ExpressionSpec is a deterministic rule predicate expression tree node.

type ExpressionSpec interface {
// contains filtered or unexported methods
}

CloneExpressionSpec returns a defensive copy of spec when it is one of the built-in expression spec nodes.

func CloneExpressionSpec(spec ExpressionSpec) ExpressionSpec

FactID identifies a fact, stable across modifies within a generation.

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

NewFactID constructs a FactID for engine-owned fact allocation and tests.

func NewFactID(generation Generation, sequence uint64) FactID
func (id FactID) Generation() Generation
func (id FactID) IsZero() bool
func (id FactID) Sequence() uint64
func (id FactID) String() string

FactLimitError reports that a session refused to retain another fact.

type FactLimitError struct {
Limit int
Facts int
}
func (e *FactLimitError) Error() string
func (e *FactLimitError) Is(target error) bool
func (e *FactLimitError) Unwrap() error

FactPatch describes a fact modification: Set overwrites the named fields and Unset clears the named fields, restoring their template defaults.

type FactPatch struct {
Set Fields
Unset []string
}

FactSnapshot is an immutable, detached view of one fact’s identity, fields, and support state.

type FactSnapshot struct {
IDValue FactID
NameValue string
TemplateKeyValue TemplateKey
VersionValue FactVersion
RecencyValue Recency
GenerationValue Generation
FieldValues Fields
FieldPresenceValues map[string]FieldPresence
SupportValue FactSupportProvenance
}

CloneFactSnapshot returns a defensive copy of f.

func CloneFactSnapshot(f FactSnapshot) FactSnapshot

CloneFactSnapshotPtr returns a defensive copy of f when non-nil.

func CloneFactSnapshotPtr(f *FactSnapshot) *FactSnapshot

CloneFactSnapshots returns a defensive copy of facts.

func CloneFactSnapshots(facts []FactSnapshot) []FactSnapshot

Field returns one field value by name.

func (f FactSnapshot) Field(name string) (Value, bool)

FieldPresence returns whether a template field was defaulted, explicit, or omitted.

func (f FactSnapshot) FieldPresence(field string) (FieldPresence, bool)

FieldPresenceMap returns template field-presence metadata keyed by field name.

func (f FactSnapshot) FieldPresenceMap() map[string]FieldPresence

Fields returns a copy of the fact’s field values.

func (f FactSnapshot) Fields() Fields

Generation returns the working-memory generation that owns this fact.

func (f FactSnapshot) Generation() Generation

ID returns the fact identity.

func (f FactSnapshot) ID() FactID

Name returns the dynamic fact name, if the fact is not template-backed.

func (f FactSnapshot) Name() string

Path returns the value at path, if present.

func (f FactSnapshot) Path(path PathSpec) (Value, bool, error)

Recency returns the mutation recency that ordered this fact.

func (f FactSnapshot) Recency() Recency
func (f FactSnapshot) String() string

Support returns the fact’s logical support classification.

func (f FactSnapshot) Support() FactSupportProvenance

TemplateKey returns the template identity, if the fact is template-backed.

func (f FactSnapshot) TemplateKey() TemplateKey

Version returns the fact version.

func (f FactSnapshot) Version() FactVersion

FactSupportProvenance is a fact’s support classification.

type FactSupportProvenance struct {
State FactSupportState
}

FactSupportState classifies how a fact is supported.

type FactSupportState string

FactSupportStated, FactSupportLogical, FactSupportStatedAndLogical, FactSupportMetadataOnly

Section titled “FactSupportStated, FactSupportLogical, FactSupportStatedAndLogical, FactSupportMetadataOnly”
const (
FactSupportStated FactSupportState = "stated"
FactSupportLogical FactSupportState = "logical"
FactSupportStatedAndLogical FactSupportState = "stated_and_logical"
FactSupportMetadataOnly FactSupportState = "metadata_only"
)

FactTarget names the facts a condition matches.

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

DynamicFact builds a target matching dynamic facts with name.

func DynamicFact(name string) FactTarget

DynamicFactIn builds a target matching dynamic facts in module.

func DynamicFactIn(module ModuleName, name string) FactTarget

TemplateFact builds a target matching facts of the named template.

func TemplateFact(name string) FactTarget

TemplateFactIn builds a target matching facts of the named template in module.

func TemplateFactIn(module ModuleName, name string) FactTarget

TemplateKeyFact builds a target matching facts of the template key.

func TemplateKeyFact(key TemplateKey) FactTarget
func (t FactTarget) Kind() FactTargetKind

Normalized returns t with trimmed names and inferred kind where possible.

func (t FactTarget) Normalized() FactTarget
func (t FactTarget) Ref() NameRef
func (t FactTarget) TemplateKey() TemplateKey

FactTargetKind identifies what kind of fact a FactTarget matches.

type FactTargetKind uint8

FactTargetUnknown, FactTargetDynamic, FactTargetTemplate, FactTargetTemplateKey

Section titled “FactTargetUnknown, FactTargetDynamic, FactTargetTemplate, FactTargetTemplateKey”
const (
FactTargetUnknown FactTargetKind = iota
FactTargetDynamic
FactTargetTemplate
FactTargetTemplateKey
)

FactVersion advances each time a fact is modified; a fact’s FactID stays stable across modifies within a generation.

type FactVersion uint32

FieldChange describes one field’s before and after value.

type FieldChange struct {
Field string
Old Value
New Value
}

CloneFieldChange returns a defensive copy of change.

func CloneFieldChange(change FieldChange) FieldChange

CloneFieldChanges returns a defensive copy of changes.

func CloneFieldChanges(changes []FieldChange) []FieldChange

FieldConstraint is the compiled, inspectable form of a FieldConstraintSpec.

type FieldConstraint struct {
Field string
Path PathSpec
Operator FieldConstraintOperator
Value Value
}

CloneFieldConstraint returns a defensive copy of c.

func CloneFieldConstraint(c FieldConstraint) FieldConstraint

FieldConstraintOperator is the comparison a FieldConstraintSpec applies.

type FieldConstraintOperator string

FieldConstraintSpec constrains one field, or nested path, of a matched fact.

type FieldConstraintSpec struct {
Field string
Path PathSpec
Operator FieldConstraintOperator
Value any
}

CloneFieldConstraintSpec returns a defensive copy of s.

func CloneFieldConstraintSpec(s FieldConstraintSpec) FieldConstraintSpec

FieldPresence reports how a field came to have its value.

type FieldPresence string

FieldPresenceOmitted, FieldPresenceDefault, FieldPresenceExplicit

Section titled “FieldPresenceOmitted, FieldPresenceDefault, FieldPresenceExplicit”
const (
FieldPresenceOmitted FieldPresence = "omitted"
FieldPresenceDefault FieldPresence = "default"
FieldPresenceExplicit FieldPresence = "explicit"
)

FieldRef names a field, or nested path, of an earlier binding.

type FieldRef struct {
Binding string
Field string
Path PathSpec
}

CloneFieldRef returns a defensive copy of r.

func CloneFieldRef(r FieldRef) FieldRef

FieldSpec declares one template field: its name, kind, whether it’s required, an optional default, and an optional closed set of allowed values.

type FieldSpec struct {
Name string
Kind ValueKind
Required bool
Default any
HasDefault bool
AllowedValues []any
}

CloneFieldSpec returns a defensive copy of field.

func CloneFieldSpec(field FieldSpec) FieldSpec

CloneFieldSpecs returns a defensive copy of fields.

func CloneFieldSpecs(fields []FieldSpec) []FieldSpec
type Fields map[string]Value

CloneFields returns a defensive copy of fields.

func CloneFields(in Fields) Fields

MustFields builds fields from alternating string keys and raw values, panicking when the inputs cannot be converted.

func MustFields(pairs ...any) Fields
func NewFields(raw map[string]any) (Fields, error)

NewFieldsFromPairs builds fields from alternating string keys and raw values.

func NewFieldsFromPairs(pairs ...any) (Fields, error)

NormalizeFields returns fields in canonical immutable form.

func NormalizeFields(fields Fields) Fields

DuplicateKey returns a deterministic duplicate key for fields.

func (f Fields) DuplicateKey() string
func (f Fields) Equal(other Fields) bool

ForallCondition tests whether every tuple matching Domain also satisfies Requirement.

type ForallCondition struct {
Domain ConditionSpec
Requirement ConditionSpec
Source SourceSpan
}

Forall builds a ForallCondition.

func Forall(domain ConditionSpec, requirement ConditionSpec) ForallCondition

FunctionEvaluationError reports a pure function that panicked, returned an error, or returned a value of the wrong kind.

type FunctionEvaluationError struct {
RuleName string
QueryName string
ConditionIndex int
PredicateIndex int
FunctionName string
Source SourceSpan
Err error
}
func (e *FunctionEvaluationError) Error() string
func (e *FunctionEvaluationError) Is(target error) bool
func (e *FunctionEvaluationError) Unwrap() error

Generation is the working-memory reset epoch.

type Generation uint64

Global is the compiled, inspectable form of a GlobalSpec.

type Global struct {
NameValue string
KindValue ValueKind
DefaultValue Value
HasDefaultValue bool
DescriptionText string
Order int
}

CloneGlobal returns a defensive copy of g.

func CloneGlobal(g Global) Global
func (g Global) DeclarationOrder() int
func (g Global) Default() (Value, bool)
func (g Global) Description() string
func (g Global) Kind() ValueKind
func (g Global) Name() string

GlobalExpr references a declared session global.

type GlobalExpr struct {
Name string
}

GlobalValue builds an expression reading the named session global.

func GlobalValue(name string) GlobalExpr

GlobalSpec declares a named, typed global with an optional default value.

type GlobalSpec struct {
Name string
Kind ValueKind
Default any
HasDefault bool
Description string
}

CloneGlobalSpec returns a defensive copy of s.

func CloneGlobalSpec(s GlobalSpec) GlobalSpec

HasPathExpr evaluates to true when Path resolves to a present value on the current fact.

type HasPathExpr struct {
Path PathSpec
}

HasPath builds a HasPathExpr testing whether path resolves to a present value on the current fact.

func HasPath(path PathSpec) HasPathExpr

JoinConstraint is the compiled, inspectable form of a JoinConstraintSpec.

type JoinConstraint struct {
Field string
Path PathSpec
Operator FieldConstraintOperator
Ref FieldRef
}

CloneJoinConstraint returns a defensive copy of c.

func CloneJoinConstraint(c JoinConstraint) JoinConstraint

JoinConstraintSpec compares a field of the matched fact against a field of an earlier binding named by Ref.

type JoinConstraintSpec struct {
Field string
Path PathSpec
Operator FieldConstraintOperator
Ref FieldRef
}

CloneJoinConstraintSpec returns a defensive copy of s.

func CloneJoinConstraintSpec(s JoinConstraintSpec) JoinConstraintSpec

ListPatternElement is the compiled, inspectable form of a ListPatternElementSpec.

type ListPatternElement struct {
KindValue ListPatternElementKind
ExpressionSpec ExpressionSpec
BindingName string
Order int
}

CloneListPatternElement returns a defensive copy of e.

func CloneListPatternElement(e ListPatternElement) ListPatternElement
func (e ListPatternElement) Binding() string
func (e ListPatternElement) DeclarationOrder() int
func (e ListPatternElement) Expression() ExpressionSpec
func (e ListPatternElement) Kind() ListPatternElementKind

ListPatternElementKind identifies one element of a ListPatternSpec.

type ListPatternElementKind string

ListPatternElementUnknown, ListPatternElementValue, ListPatternElementWildcard, ListPatternElementSegment, ListPatternElementRestWildcard

Section titled “ListPatternElementUnknown, ListPatternElementValue, ListPatternElementWildcard, ListPatternElementSegment, ListPatternElementRestWildcard”
const (
ListPatternElementUnknown ListPatternElementKind = ""
ListPatternElementValue ListPatternElementKind = "value"
ListPatternElementWildcard ListPatternElementKind = "wildcard"
ListPatternElementSegment ListPatternElementKind = "segment"
ListPatternElementRestWildcard ListPatternElementKind = "rest-wildcard"
)

ListPatternElementSpec is one element of a ListPatternSpec.

type ListPatternElementSpec struct {
Kind ListPatternElementKind
Expression ExpressionSpec
Binding string
}

CloneListPatternElementSpec returns a defensive copy of s.

func CloneListPatternElementSpec(s ListPatternElementSpec) ListPatternElementSpec

ListElem builds a fixed-position list pattern element.

func ListElem(expression ExpressionSpec) ListPatternElementSpec

ListRestWildcard builds a list pattern element matching a variable-length run without capturing it.

func ListRestWildcard() ListPatternElementSpec

ListSegment builds a list pattern element matching a variable-length run.

func ListSegment(binding string) ListPatternElementSpec

ListWildcard builds a list pattern element matching any one element.

func ListWildcard() ListPatternElementSpec

ListPatternSpec is a structural pattern over a LIST-typed field.

type ListPatternSpec struct {
Path PathSpec
Elements []ListPatternElementSpec
}

CloneListPatternSpec returns a defensive copy of s.

func CloneListPatternSpec(s ListPatternSpec) ListPatternSpec

ListPattern builds a ListPatternSpec matching elements positionally against the LIST-typed field at path.

func ListPattern(path PathSpec, elements ...ListPatternElementSpec) ListPatternSpec

Match is a positive fact match condition tree node.

type Match RuleConditionSpec

CloneMatch returns a defensive copy of s.

func CloneMatch(s Match) Match

ModifyResult reports the outcome of a modify.

type ModifyResult struct {
Status ModifyStatus
Fact FactSnapshot
Delta *MutationDelta
}

CloneModifyResult returns a defensive copy of result.

func CloneModifyResult(result ModifyResult) ModifyResult

Changed reports whether the modify changed the fact.

func (r ModifyResult) Changed() bool

ModifyStatus is the outcome of a modify call.

type ModifyStatus string

ModifyChanged, ModifyNoOp, ModifyMissing, ModifyStale, ModifyValidationFailure, ModifyDuplicate, ModifyLogicalSupport, ModifyClosed, ModifyConcurrencyMisuse

Section titled “ModifyChanged, ModifyNoOp, ModifyMissing, ModifyStale, ModifyValidationFailure, ModifyDuplicate, ModifyLogicalSupport, ModifyClosed, ModifyConcurrencyMisuse”
const (
ModifyChanged ModifyStatus = "changed"
ModifyNoOp ModifyStatus = "no_op"
ModifyMissing ModifyStatus = "missing"
ModifyStale ModifyStatus = "stale"
ModifyValidationFailure ModifyStatus = "validation_failure"
ModifyDuplicate ModifyStatus = "duplicate"
ModifyLogicalSupport ModifyStatus = "logical_support"
ModifyClosed ModifyStatus = "closed"
ModifyConcurrencyMisuse ModifyStatus = "concurrency_misuse"
)

Module is the compiled, inspectable form of a ModuleSpec.

type Module struct {
NameValue ModuleName
DescriptionText string
AutoFocusValue *bool
}

CloneModule returns a defensive copy of m.

func CloneModule(m Module) Module
func (m Module) AutoFocusDefault() (bool, bool)
func (m Module) Description() string
func (m Module) Name() ModuleName

ModuleName identifies a module. The zero value renders as MAIN, the default module.

type ModuleName string
const MainModule ModuleName = "MAIN"
func (name ModuleName) IsZero() bool
func (name ModuleName) String() string

ModuleSpec declares a module: its Name and optional default focus behavior.

type ModuleSpec struct {
Name ModuleName
Description string
AutoFocus *bool
}

CloneModuleSpec returns a defensive copy of s.

func CloneModuleSpec(s ModuleSpec) ModuleSpec

ModuleSpecFromModule returns a ModuleSpec equivalent to m.

func ModuleSpecFromModule(m Module) ModuleSpec

MutationDelta describes one mutation’s effect.

type MutationDelta struct {
Kind MutationKind
Generation Generation
OldGeneration Generation
ActivationID ActivationID
RuleID RuleID
RuleRevisionID RuleRevisionID
SupportBefore FactSupportProvenance
SupportAfter FactSupportProvenance
Recency Recency
FactID FactID
OldVersion FactVersion
NewVersion FactVersion
Before *FactSnapshot
After *FactSnapshot
OldDuplicate DuplicateKey
NewDuplicate DuplicateKey
ChangedFields []FieldChange
}

CloneMutationDelta returns a defensive copy of delta.

func CloneMutationDelta(delta MutationDelta) MutationDelta

CloneMutationDeltaPtr returns a defensive copy of delta when non-nil.

func CloneMutationDeltaPtr(delta *MutationDelta) *MutationDelta

FieldChanges returns a cloned copy of changed fields.

func (d MutationDelta) FieldChanges() []FieldChange

MutationKind is the kind of change recorded in a MutationDelta.

type MutationKind string

MutationAssert, MutationModify, MutationRetract, MutationReset

Section titled “MutationAssert, MutationModify, MutationRetract, MutationReset”
const (
MutationAssert MutationKind = "assert"
MutationModify MutationKind = "modify"
MutationRetract MutationKind = "retract"
MutationReset MutationKind = "reset"
)

NameRef is an unresolved reference to a named definition.

type NameRef struct {
Module ModuleName
Name string
}

ModuleRef builds a NameRef explicitly qualified to module.

func ModuleRef(module ModuleName, name string) NameRef

Ref builds an unqualified NameRef.

func Ref(name string) NameRef

Not negates a condition tree node.

type Not struct {
Condition ConditionSpec
Source SourceSpan
}

Or groups condition tree branches into a disjunction.

type Or struct {
Conditions []ConditionSpec
Source SourceSpan
}

ParamExpr references a named query parameter.

type ParamExpr struct {
Name string
}

PathSegment is one step of a PathSpec.

type PathSegment struct {
Kind PathSegmentKind
Key string
Index int
}

ListIndex builds a list-index path segment.

func ListIndex(index int) PathSegment

MapKey builds a map-key path segment.

func MapKey(key string) PathSegment

PathSegmentKind identifies one step of a PathSpec.

type PathSegmentKind string

PathSegmentRoot, PathSegmentMap, PathSegmentIndex

Section titled “PathSegmentRoot, PathSegmentMap, PathSegmentIndex”
const (
PathSegmentRoot PathSegmentKind = "root"
PathSegmentMap PathSegmentKind = "map"
PathSegmentIndex PathSegmentKind = "index"
)

PathSpec describes a path into a structured value.

type PathSpec struct {
Segments []PathSegment
}

Path builds a PathSpec rooted at the field root, followed by segments.

func Path(root string, segments ...PathSegment) PathSpec
func (p PathSpec) String() string

PureFunction is a deterministic, side-effect-free function implementation available to condition and query expressions.

type PureFunction func(context.Context, []Value) (Value, error)

PureFunction0 is a fixed-arity PureFunction taking no arguments.

type PureFunction0 func(context.Context) (Value, error)

PureFunction1 is a fixed-arity PureFunction taking one argument.

type PureFunction1 func(context.Context, Value) (Value, error)

PureFunction2 is a fixed-arity PureFunction taking two arguments.

type PureFunction2 func(context.Context, Value, Value) (Value, error)

PureFunction3 is a fixed-arity PureFunction taking three arguments.

type PureFunction3 func(context.Context, Value, Value, Value) (Value, error)

PureFunctionDefinition is the compiled, inspectable form of a PureFunctionSpec or ExpressionFunctionSpec.

type PureFunctionDefinition struct {
NameValue string
ParamNamesValue []string
ArgsValue []ValueKind
ReturnKind ValueKind
DescriptionText string
ExpressionSpec ExpressionSpec
ExpressionBackedValue bool
Order int
EqualityComparatorValue bool
IndexKeyExtractorValue bool
}

ClonePureFunctionDefinition returns a defensive copy of f.

func ClonePureFunctionDefinition(f PureFunctionDefinition) PureFunctionDefinition
func (f PureFunctionDefinition) Args() []ValueKind
func (f PureFunctionDefinition) DeclarationOrder() int
func (f PureFunctionDefinition) Description() string
func (f PureFunctionDefinition) EqualityComparator() bool
func (f PureFunctionDefinition) Expression() (ExpressionSpec, bool)
func (f PureFunctionDefinition) ExpressionBacked() bool
func (f PureFunctionDefinition) IndexKeyExtractor() bool
func (f PureFunctionDefinition) Name() string
func (f PureFunctionDefinition) ParamNames() []string
func (f PureFunctionDefinition) Return() ValueKind

PureFunctionSpec registers a pure function by Name, its Args and Return value kinds, and exactly one implementation function.

type PureFunctionSpec struct {
Name string
Args []ValueKind
Return ValueKind
Func PureFunction
Func0 PureFunction0
Func1 PureFunction1
Func2 PureFunction2
Func3 PureFunction3
EqualityComparator bool
IndexKeyExtractor bool
}

ClonePureFunctionSpec returns a defensive copy of s.

func ClonePureFunctionSpec(s PureFunctionSpec) PureFunctionSpec

QualifiedName is a module-qualified name, rendered as “MODULE.Name”.

type QualifiedName struct {
Module ModuleName
Name string
}
func (n QualifiedName) String() string

Query is the compiled, inspectable form of a QuerySpec.

type Query struct {
NameValue string
ModuleValue ModuleName
DescriptionText string
SourceSpan SourceSpan
GessSourceText string
ParameterValues []QueryParameter
ConditionValues []RuleCondition
ConditionTreeValue RuleConditionTree
ConditionBranchValues []RuleConditionBranch
ConditionBranchesTruncatedFlag bool
ReturnValues []QueryReturn
}

CloneQuery returns a defensive copy of q.

func CloneQuery(q Query) Query
func (q Query) ConditionBranches() []RuleConditionBranch

ConditionBranchesTruncated reports whether ConditionBranches is a bounded inspection prefix rather than the complete Cartesian expansion.

func (q Query) ConditionBranchesTruncated() bool
func (q Query) ConditionTree() RuleConditionTree
func (q Query) Conditions() []RuleCondition
func (q Query) Description() string
func (q Query) GessSource() string
func (q Query) Module() ModuleName
func (q Query) Name() string
func (q Query) Parameters() []QueryParameter
func (q Query) Returns() []QueryReturn
func (q Query) Source() SourceSpan

QueryParameter is the compiled, inspectable form of a QueryParameterSpec.

type QueryParameter struct {
NameValue string
KindValue ValueKind
Order int
}

CloneQueryParameters returns a defensive copy of parameters.

func CloneQueryParameters(parameters []QueryParameter) []QueryParameter
func (p QueryParameter) DeclarationOrder() int
func (p QueryParameter) Kind() ValueKind
func (p QueryParameter) Name() string

QueryParameterSpec declares one named, typed query parameter.

type QueryParameterSpec struct {
Name string
Kind ValueKind
}

CloneQueryParameterSpec returns a defensive copy of s.

func CloneQueryParameterSpec(s QueryParameterSpec) QueryParameterSpec

QueryReturn is the compiled, inspectable form of a QueryReturnSpec.

type QueryReturn struct {
AliasValue string
BindingName string
ExpressionSpec ExpressionSpec
FactValue bool
Order int
SourceSpan SourceSpan
}

CloneQueryReturn returns a defensive copy of r.

func CloneQueryReturn(r QueryReturn) QueryReturn

CloneQueryReturns returns a defensive copy of returns.

func CloneQueryReturns(returns []QueryReturn) []QueryReturn
func (r QueryReturn) Alias() string
func (r QueryReturn) Binding() string
func (r QueryReturn) DeclarationOrder() int
func (r QueryReturn) Expression() ExpressionSpec
func (r QueryReturn) Fact() bool
func (r QueryReturn) Source() SourceSpan

QueryReturnSpec declares one named query result column.

type QueryReturnSpec struct {
Alias string
Binding string
Expression ExpressionSpec
Source SourceSpan
}

CloneQueryReturnSpec returns a defensive copy of s.

func CloneQueryReturnSpec(s QueryReturnSpec) QueryReturnSpec

ReturnFact builds a QueryReturnSpec returning the whole fact bound to binding under alias.

func ReturnFact(alias, binding string) QueryReturnSpec

ReturnValue builds a QueryReturnSpec returning expression under alias.

func ReturnValue(alias string, expression ExpressionSpec) QueryReturnSpec

QuerySpec defines a named query.

type QuerySpec struct {
Name string
Module ModuleName
Description string
Source SourceSpan
GessSource string
Parameters []QueryParameterSpec
Conditions []RuleConditionSpec
ConditionTree ConditionSpec
Returns []QueryReturnSpec
}

CloneQuerySpec returns a defensive copy of s.

func CloneQuerySpec(s QuerySpec) QuerySpec

RHSBindExpr references a right-hand-side local variable created by a bind action earlier in the same rule firing.

type RHSBindExpr struct {
Name string
}

Recency is a session-wide counter that advances on every fact mutation.

type Recency uint32

ResetStatus is the outcome of a reset.

type ResetStatus string

ResetApplied, ResetValidationFailure, ResetClosed, ResetConcurrencyMisuse

Section titled “ResetApplied, ResetValidationFailure, ResetClosed, ResetConcurrencyMisuse”
const (
ResetApplied ResetStatus = "applied"
ResetValidationFailure ResetStatus = "validation_failure"
ResetClosed ResetStatus = "closed"
ResetConcurrencyMisuse ResetStatus = "concurrency_misuse"
)

RetractResult reports the outcome of a retract.

type RetractResult struct {
Status RetractStatus
Fact FactSnapshot
Delta *MutationDelta
}

CloneRetractResult returns a defensive copy of result.

func CloneRetractResult(result RetractResult) RetractResult

Removed reports whether the retract removed the fact.

func (r RetractResult) Removed() bool

RetractStatus is the outcome of a retract call.

type RetractStatus string

RetractRemoved, RetractStatedSupportRemoved, RetractLogicalOnly, RetractMissing, RetractStale, RetractClosed, RetractValidationFailure, RetractConcurrencyMisuse

Section titled “RetractRemoved, RetractStatedSupportRemoved, RetractLogicalOnly, RetractMissing, RetractStale, RetractClosed, RetractValidationFailure, RetractConcurrencyMisuse”
const (
RetractRemoved RetractStatus = "removed"
RetractStatedSupportRemoved RetractStatus = "stated_support_removed"
RetractLogicalOnly RetractStatus = "logical_only"
RetractMissing RetractStatus = "missing"
RetractStale RetractStatus = "stale"
RetractClosed RetractStatus = "closed"
RetractValidationFailure RetractStatus = "validation_failure"
RetractConcurrencyMisuse RetractStatus = "concurrency_misuse"
)

Rule is the compiled, inspectable form of a RuleSpec.

type Rule struct {
IDValue RuleID
RevisionIDValue RuleRevisionID
NameValue string
ModuleValue ModuleName
DescriptionText string
TagValues []string
SalienceValue int
AutoFocusValue bool
HasAutoFocus bool
EffectiveAutoFocusFlag bool
Order int
SourceSpan SourceSpan
GessSourceText string
ConditionValues []RuleCondition
ConditionTreeValue RuleConditionTree
ConditionBranchValues []RuleConditionBranch
ConditionBranchesTruncatedFlag bool
ActionValues []RuleAction
}

CloneRule returns a defensive copy of r.

func CloneRule(r Rule) Rule

CloneRules returns a defensive copy of rules.

func CloneRules(rules []Rule) []Rule
func (r Rule) Actions() []RuleAction
func (r Rule) AutoFocus() (bool, bool)
func (r Rule) ConditionBranches() []RuleConditionBranch

ConditionBranchesTruncated reports whether ConditionBranches is a bounded inspection prefix rather than the complete Cartesian expansion.

func (r Rule) ConditionBranchesTruncated() bool
func (r Rule) ConditionTree() RuleConditionTree
func (r Rule) Conditions() []RuleCondition
func (r Rule) DeclarationOrder() int
func (r Rule) Description() string
func (r Rule) EffectiveAutoFocus() bool
func (r Rule) GessSource() string
func (r Rule) ID() RuleID
func (r Rule) Module() ModuleName
func (r Rule) Name() string
func (r Rule) RevisionID() RuleRevisionID
func (r Rule) Salience() int
func (r Rule) Source() SourceSpan
func (r Rule) Tags() []string

RuleAction is a compiled, inspectable action reference on a rule.

type RuleAction struct {
NameValue string
Order int
SourceSpan SourceSpan
}

CloneRuleAction returns a defensive copy of a.

func CloneRuleAction(a RuleAction) RuleAction

CloneRuleActions returns a defensive copy of actions.

func CloneRuleActions(actions []RuleAction) []RuleAction
func (a RuleAction) DeclarationOrder() int
func (a RuleAction) Name() string
func (a RuleAction) Source() SourceSpan

RuleActionSpec references, by Name, an action registered on the workspace.

type RuleActionSpec struct {
Name string
Source SourceSpan
}

CloneRuleActionSpec returns a defensive copy of s.

func CloneRuleActionSpec(s RuleActionSpec) RuleActionSpec

RuleCondition is the compiled, inspectable form of a fact match condition.

type RuleCondition struct {
IDValue ConditionID
BindingName string
NameValue string
TemplateKeyValue TemplateKey
FieldConstraintValues []FieldConstraint
ListPatternValues []RuleListPattern
JoinConstraintValues []JoinConstraint
PredicateValues []ExpressionPredicate
ExplicitValue bool
Order int
SourceSpan SourceSpan
}

CloneRuleCondition returns a defensive copy of c.

func CloneRuleCondition(c RuleCondition) RuleCondition

CloneRuleConditions returns a defensive copy of conditions.

func CloneRuleConditions(conditions []RuleCondition) []RuleCondition
func (c RuleCondition) Binding() string
func (c RuleCondition) DeclarationOrder() int
func (c RuleCondition) Explicit() bool
func (c RuleCondition) FieldConstraints() []FieldConstraint
func (c RuleCondition) ID() ConditionID
func (c RuleCondition) JoinConstraints() []JoinConstraint
func (c RuleCondition) ListPatterns() []RuleListPattern
func (c RuleCondition) Name() string
func (c RuleCondition) Predicates() []ExpressionPredicate
func (c RuleCondition) Source() SourceSpan
func (c RuleCondition) Target() FactTarget
func (c RuleCondition) TemplateKey() TemplateKey

RuleConditionBranch is one compiled branch in a condition tree. Flat rules and tree rules without disjunction expose one branch. Disjunctive trees expose expanded alternatives in source order, bounded for structurally compiled programs; Rule.ConditionBranchesTruncated and Query.ConditionBranchesTruncated report whether the returned inspection is incomplete.

type RuleConditionBranch struct {
IDValue int
ConditionValues []RuleConditionBranchCondition
}

CloneRuleConditionBranch returns a defensive copy of b.

func CloneRuleConditionBranch(b RuleConditionBranch) RuleConditionBranch

CloneRuleConditionBranches returns a defensive copy of branches.

func CloneRuleConditionBranches(branches []RuleConditionBranch) []RuleConditionBranch
func (b RuleConditionBranch) Conditions() []RuleConditionBranchCondition
func (b RuleConditionBranch) ID() int

RuleConditionBranchCondition describes a condition within an expanded branch. Path is the authored condition-tree path, while Visible indicates whether the binding is exposed to actions. Negated conditions are local and not visible.

type RuleConditionBranchCondition struct {
ConditionValue RuleCondition
PathValue []int
VisibleValue bool
NegatedValue bool
ExplicitValue bool
}

CloneRuleConditionBranchCondition returns a defensive copy of c.

func CloneRuleConditionBranchCondition(c RuleConditionBranchCondition) RuleConditionBranchCondition

CloneRuleConditionBranchConditions returns a defensive copy of conditions.

func CloneRuleConditionBranchConditions(conditions []RuleConditionBranchCondition) []RuleConditionBranchCondition
func (c RuleConditionBranchCondition) Condition() RuleCondition
func (c RuleConditionBranchCondition) Explicit() bool
func (c RuleConditionBranchCondition) Negated() bool
func (c RuleConditionBranchCondition) Path() []int
func (c RuleConditionBranchCondition) Visible() bool

RuleConditionSpec is the field set behind a positive fact match condition.

type RuleConditionSpec struct {
Binding string
// SyntheticBinding marks a binding generated by a source loader rather
// than authored by the user. User-facing diagnostics may omit its name.
SyntheticBinding bool
// Volatile is a compile-time planning hint that the matched fact is
// expected to be modified frequently. The planner may place an otherwise
// independent volatile match later in a branch to reduce propagation
// churn. It does not change match semantics or revision identity.
Volatile bool
Target FactTarget
FieldConstraints []FieldConstraintSpec
ListPatterns []ListPatternSpec
JoinConstraints []JoinConstraintSpec
Predicates []ExpressionSpec
Source SourceSpan
}

CloneRuleConditionSpec returns a defensive copy of s.

func CloneRuleConditionSpec(s RuleConditionSpec) RuleConditionSpec

RuleConditionTree is the compiled, inspectable condition tree for a rule or query.

type RuleConditionTree struct {
KindValue ConditionTreeKind
ChildrenValue []RuleConditionTree
MatchCondition RuleCondition
HasMatch bool
TestExpression ExpressionSpec
HasTest bool
AggregateValue AccumulateCondition
HasAggregate bool
SourceSpan SourceSpan
}

CloneRuleConditionTree returns a defensive copy of t.

func CloneRuleConditionTree(t RuleConditionTree) RuleConditionTree

CloneRuleConditionTrees returns a defensive copy of trees.

func CloneRuleConditionTrees(trees []RuleConditionTree) []RuleConditionTree
func (t RuleConditionTree) Aggregate() (AccumulateCondition, bool)
func (t RuleConditionTree) Children() []RuleConditionTree
func (t RuleConditionTree) Kind() ConditionTreeKind
func (t RuleConditionTree) Match() (RuleCondition, bool)
func (t RuleConditionTree) Source() SourceSpan
func (t RuleConditionTree) Test() (ExpressionSpec, bool)

RuleFieldConstraint is an alias of FieldConstraint.

type RuleFieldConstraint = FieldConstraint

RuleFieldConstraintSpec is an alias of FieldConstraintSpec, used in rule-condition contexts.

type RuleFieldConstraintSpec = FieldConstraintSpec

RuleID is a rule’s stable identity, surviving ReplaceRule.

type RuleID string
func (id RuleID) IsZero() bool
func (id RuleID) String() string

RuleListPattern is the compiled, inspectable list pattern attached to a rule condition.

type RuleListPattern struct {
PathSpec PathSpec
ElementsValue []ListPatternElement
Order int
}

CloneRuleListPattern returns a defensive copy of p.

func CloneRuleListPattern(p RuleListPattern) RuleListPattern

CloneRuleListPatterns returns a defensive copy of patterns.

func CloneRuleListPatterns(patterns []RuleListPattern) []RuleListPattern
func (p RuleListPattern) DeclarationOrder() int
func (p RuleListPattern) Elements() []ListPatternElement
func (p RuleListPattern) Path() PathSpec

RuleRevisionID identifies one compiled revision of a rule.

type RuleRevisionID string
func (id RuleRevisionID) IsZero() bool
func (id RuleRevisionID) String() string

RuleSpec defines a rule.

type RuleSpec struct {
Name string
Module ModuleName
ID RuleID
Description string
Source SourceSpan
GessSource string
Tags []string
Salience int
AutoFocus *bool
// Conditions is the flat positive conjunction form. When ConditionTree is
// nil, compile normalizes Conditions to And(Match...) without changing
// condition ordering, condition identity, graph topology, or agenda behavior.
Conditions []RuleConditionSpec
// ConditionTree is the structured left-hand side form. It is mutually
// exclusive with Conditions in one RuleSpec.
ConditionTree ConditionSpec
Actions []RuleActionSpec
}

CloneRuleSpec returns a defensive copy of s.

func CloneRuleSpec(s RuleSpec) RuleSpec

Ruleset is an immutable compiled ruleset facade. Its implementation is owned by the engine through a RulesetHandle.

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

Compile compiles workspace into an immutable Ruleset, equivalent to calling workspace.Compile directly.

func Compile(ctx context.Context, workspace *Workspace) (*Ruleset, error)

NewRuleset returns a public Ruleset backed by handle.

func NewRuleset(handle RulesetHandle) *Ruleset
func (r *Ruleset) Action(name string) (Action, bool)
func (r *Ruleset) Actions() []Action
func (r *Ruleset) Function(name string) (PureFunctionDefinition, bool)
func (r *Ruleset) Functions() []PureFunctionDefinition
func (r *Ruleset) Global(name string) (Global, bool)
func (r *Ruleset) Globals() []Global
func (r *Ruleset) ID() RulesetID
func (r *Ruleset) Module(name ModuleName) (Module, bool)
func (r *Ruleset) Modules() []Module
func (r *Ruleset) Queries() []Query
func (r *Ruleset) Query(name string) (Query, bool)
func (r *Ruleset) Rule(name string) (Rule, bool)
func (r *Ruleset) RuleByID(id RuleID) (Rule, bool)
func (r *Ruleset) RuleByRevisionID(id RuleRevisionID) (Rule, bool)
func (r *Ruleset) Rules() []Rule
func (r *Ruleset) Template(name string) (Template, bool)
func (r *Ruleset) TemplateByKey(key TemplateKey) (Template, bool)
func (r *Ruleset) Templates() []Template

RulesetHandle is the engine-owned implementation behind a public Ruleset. Implementations must return detached inspection values.

type RulesetHandle interface {
ID() RulesetID
Module(ModuleName) (Module, bool)
Modules() []Module
Template(string) (Template, bool)
TemplateByKey(TemplateKey) (Template, bool)
Templates() []Template
Action(string) (Action, bool)
Actions() []Action
Function(string) (PureFunctionDefinition, bool)
Functions() []PureFunctionDefinition
Global(string) (Global, bool)
Globals() []Global
Rule(string) (Rule, bool)
RuleByID(RuleID) (Rule, bool)
RuleByRevisionID(RuleRevisionID) (Rule, bool)
Rules() []Rule
Query(string) (Query, bool)
Queries() []Query
}

RulesetHandleOf returns the engine-owned implementation behind r.

func RulesetHandleOf(r *Ruleset) RulesetHandle

RulesetID identifies one compiled ruleset revision. It is derived from the ruleset’s declared shape: templates, rules, queries, globals, and the declared signatures of Go host functions and actions. Host function and action implementations do not contribute, so two rulesets differing only in their Go closures share the same RulesetID.

type RulesetID string
func (id RulesetID) String() string

RunID identifies one session Run call.

type RunID uint64
func (id RunID) IsZero() bool
func (id RunID) String() string

RunStatus is the outcome of a Run.

type RunStatus string

RunCompleted, RunHalted, RunFireLimit, RunCanceled, RunActionFailed, RunClosed, RunConcurrencyMisuse, RunFailed

Section titled “RunCompleted, RunHalted, RunFireLimit, RunCanceled, RunActionFailed, RunClosed, RunConcurrencyMisuse, RunFailed”
const (
RunCompleted RunStatus = "completed"
RunHalted RunStatus = "halted"
RunFireLimit RunStatus = "fire_limit"
RunCanceled RunStatus = "canceled"
RunActionFailed RunStatus = "action_failed"
RunClosed RunStatus = "closed"
RunConcurrencyMisuse RunStatus = "concurrency_misuse"
RunFailed RunStatus = "failed"
)

SessionID identifies a session.

type SessionID string
func (id SessionID) String() string

SourceSpan is a source location range within a .gess file, carried into compiled definitions and runtime errors for rulesets loaded from .gess source.

type SourceSpan struct {
Name string
StartLine int
StartColumn int
EndLine int
EndColumn int
}

String returns the source name and starting line/column.

func (s SourceSpan) String() string

SupportID identifies one logical support edge.

type SupportID string
func (id SupportID) IsZero() bool
func (id SupportID) String() string

Template is the compiled, inspectable form of a TemplateSpec.

type Template struct {
NameValue string
ModuleValue ModuleName
KeyValue TemplateKey
CompatibilityKeyValue TemplateKey
FieldValues []FieldSpec
DuplicatePolicyValue DuplicatePolicy
DuplicateKeyValues []string
BackchainReactiveValue bool
BackchainDemandKey TemplateKey
BackchainDemandValue bool
BackchainSourceKey TemplateKey
SourceSpan SourceSpan
GessSourceText string
}

CloneTemplate returns a defensive copy of t.

func CloneTemplate(t Template) Template

CloneTemplates returns a defensive copy of templates.

func CloneTemplates(templates []Template) []Template
func (t Template) BackchainDemandTemplateKey() (TemplateKey, bool)
func (t Template) BackchainReactive() bool
func (t Template) BackchainSourceTemplateKey() (TemplateKey, bool)
func (t Template) CompatibilityKey() TemplateKey
func (t Template) DuplicateKeys() []string
func (t Template) DuplicatePolicy() DuplicatePolicy
func (t Template) Fields() []FieldSpec
func (t Template) GessSource() string
func (t Template) IsBackchainDemandTemplate() bool
func (t Template) Key() TemplateKey
func (t Template) Module() ModuleName
func (t Template) Name() string
func (t Template) QualifiedName() QualifiedName
func (t Template) Source() SourceSpan

TemplateKey identifies a compiled template within a ruleset.

type TemplateKey string
func (key TemplateKey) String() string

TemplateSpec declares a fact template: its name, module, key, fields, duplicate policy, and whether it’s backward-chaining reactive.

type TemplateSpec struct {
Name string
Module ModuleName
Key TemplateKey
CompatibilityKey TemplateKey
Source SourceSpan
GessSource string
Fields []FieldSpec
DuplicatePolicy DuplicatePolicy
DuplicateKeyNames []string
BackchainReactive bool
}

Test evaluates a standalone boolean expression over earlier local bindings.

type Test struct {
Expression ExpressionSpec
Source SourceSpan
}

ValidationError reports a definition that failed structural or compile-time validation.

type ValidationError struct {
TemplateName string
RuleName string
FunctionName string
GlobalName string
Source SourceSpan
FieldName string
ConditionIndex int
HasConditionIndex bool
ConstraintIndex int
HasConstraintIndex bool
PredicateIndex int
HasPredicateIndex bool
JoinIndex int
HasJoinIndex bool
ActionIndex int
HasActionIndex bool
Reason string
Err error
}
func (e *ValidationError) Error() string
func (e *ValidationError) Is(target error) bool
func (e *ValidationError) Unwrap() error

Value is an immutable, typed field or expression value.

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

BoolValue returns a bool value.

func BoolValue(value bool) Value

CanonicalValue converts raw into a Value.

func CanonicalValue(raw any) (Value, error)

CloneValue returns a defensive copy of v.

func CloneValue(v Value) Value

CloneValueSlice returns a defensive copy of in.

func CloneValueSlice(in []Value) []Value

FloatValue returns a float value.

func FloatValue(value float64) Value

IntValue returns an integer value.

func IntValue(value int64) Value
func NewValue(raw any) (Value, error)
func NullValue() Value

StringValue returns a string value.

func StringValue(value string) Value

AsBool returns the stored bool when the value kind is ValueBool.

func (v Value) AsBool() (bool, bool)

AsFloat64 returns the stored float when the value kind is ValueFloat.

func (v Value) AsFloat64() (float64, bool)

AsInt64 returns the stored integer when the value kind is ValueInt.

func (v Value) AsInt64() (int64, bool)

AsList returns a defensive copy of the stored list when the value kind is ValueList.

func (v Value) AsList() ([]Value, bool)

AsListShared returns the value’s backing list without copying when the kind is ValueList. The returned slice aliases internal storage and must not be modified; use AsList for a defensive copy.

func (v Value) AsListShared() ([]Value, bool)

AsMap returns a defensive copy of the stored map when the value kind is ValueMap.

func (v Value) AsMap() (map[string]Value, bool)

AsMapShared returns the value’s backing map without copying when the kind is ValueMap. The returned map aliases internal storage and must not be modified; use AsMap for a defensive copy.

func (v Value) AsMapShared() (map[string]Value, bool)

AsString returns the stored string when the value kind is ValueString.

func (v Value) AsString() (string, bool)

CanonicalKey returns a deterministic key for duplicate detection and stable ordering.

func (v Value) CanonicalKey() string
func (v Value) Equal(other Value) bool
func (v Value) Kind() ValueKind

ListAt returns one list item when the value kind is ValueList.

func (v Value) ListAt(index int) (Value, bool)

ListLen returns the list length when the value kind is ValueList.

func (v Value) ListLen() (int, bool)

MapGet returns one map value when the value kind is ValueMap.

func (v Value) MapGet(key string) (Value, bool)

RangeList visits list items when the value kind is ValueList.

func (v Value) RangeList(fn func(int, Value) bool) bool

RangeMap visits map entries when the value kind is ValueMap.

func (v Value) RangeMap(fn func(string, Value) bool) bool
func (v Value) String() string

ValueKind is a Value’s type tag.

type ValueKind uint8

ValueAny, ValueNull, ValueBool, ValueInt, ValueFloat, ValueString, ValueList, ValueMap

Section titled “ValueAny, ValueNull, ValueBool, ValueInt, ValueFloat, ValueString, ValueList, ValueMap”
const (
ValueAny ValueKind
ValueNull
ValueBool
ValueInt
ValueFloat
ValueString
ValueList
ValueMap
)
func (k ValueKind) String() string

WhyNotConditionReason classifies why one condition did not extend a partial match.

type WhyNotConditionReason string

WhyNotReasonNone, WhyNotReasonNoAlphaMatches, WhyNotReasonJoinMismatch, WhyNotReasonPredicate, WhyNotReasonNegationBlocked

Section titled “WhyNotReasonNone, WhyNotReasonNoAlphaMatches, WhyNotReasonJoinMismatch, WhyNotReasonPredicate, WhyNotReasonNegationBlocked”
const (
WhyNotReasonNone WhyNotConditionReason = ""
WhyNotReasonNoAlphaMatches WhyNotConditionReason = "no_alpha_matches"
WhyNotReasonJoinMismatch WhyNotConditionReason = "join_mismatch"
WhyNotReasonPredicate WhyNotConditionReason = "predicate_rejected"
WhyNotReasonNegationBlocked WhyNotConditionReason = "negation_blocked"
)

WhyNotOutcome is the top-level answer to “why has this rule not fired?”.

type WhyNotOutcome string

WhyNotActivated, WhyNotAlreadyFired, WhyNotNeverMatched, WhyNotBlocked

Section titled “WhyNotActivated, WhyNotAlreadyFired, WhyNotNeverMatched, WhyNotBlocked”
const (
WhyNotActivated WhyNotOutcome = "activated"
WhyNotAlreadyFired WhyNotOutcome = "already_fired"
WhyNotNeverMatched WhyNotOutcome = "never_matched"
WhyNotBlocked WhyNotOutcome = "blocked"
)

Workspace is a mutable collection of module, template, action, function, rule, and query definitions. Definitions are validated as they’re added; Compile produces an immutable Ruleset.

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

NewWorkspaceWithHandle returns a Workspace backed by handle. Runtime packages use this constructor to make workspace ownership explicit while keeping rules independent of a concrete engine implementation.

func NewWorkspaceWithHandle(handle WorkspaceHandle) *Workspace
func (w *Workspace) AddAction(spec ActionSpec) error

AddExpressionFunction registers a pure function whose body is a single expression over its declared parameters.

func (w *Workspace) AddExpressionFunction(spec ExpressionFunctionSpec) error
func (w *Workspace) AddFunction(spec PureFunctionSpec) error

AddGlobal declares a typed global constant readable from rule, query, and aggregate expressions and from ActionContext.Global. Values bind per session via WithGlobals; a declaration without a default requires every session to supply a value. In .gess sources the equivalent form is (defglobal *name* (type KIND) (default value)).

func (w *Workspace) AddGlobal(spec GlobalSpec) error

AddModule records a module declaration. Compile treats identical repeated declarations as idempotent and rejects conflicting metadata.

func (w *Workspace) AddModule(spec ModuleSpec) error
func (w *Workspace) AddQuery(spec QuerySpec) error
func (w *Workspace) AddRule(spec RuleSpec) error
func (w *Workspace) AddTemplate(spec TemplateSpec) error

Compile compiles workspace into an immutable Ruleset.

func (w *Workspace) Compile(ctx context.Context) (*Ruleset, error)
func (w *Workspace) RemoveAction(name string) error
func (w *Workspace) RemoveFunction(name string) error
func (w *Workspace) RemoveGlobal(name string) error
func (w *Workspace) RemoveQuery(name string) error
func (w *Workspace) RemoveRule(name string) error
func (w *Workspace) ReplaceAction(spec ActionSpec) error
func (w *Workspace) ReplaceFunction(spec PureFunctionSpec) error
func (w *Workspace) ReplaceGlobal(spec GlobalSpec) error
func (w *Workspace) ReplaceQuery(spec QuerySpec) error
func (w *Workspace) ReplaceRule(spec RuleSpec) error

WorkspaceHandle is the engine-owned implementation behind a public Workspace.

type WorkspaceHandle interface {
AddModule(ModuleSpec) error
AddTemplate(TemplateSpec) error
AddGlobal(GlobalSpec) error
ReplaceGlobal(GlobalSpec) error
RemoveGlobal(string) error
AddAction(ActionSpec) error
ReplaceAction(ActionSpec) error
RemoveAction(string) error
AddFunction(PureFunctionSpec) error
AddExpressionFunction(ExpressionFunctionSpec) error
ReplaceFunction(PureFunctionSpec) error
RemoveFunction(string) error
AddRule(RuleSpec) error
ReplaceRule(RuleSpec) error
RemoveRule(string) error
AddQuery(QuerySpec) error
ReplaceQuery(QuerySpec) error
RemoveQuery(string) error
Compile(context.Context) (*Ruleset, error)
}

WorkspaceHandleOf returns the engine-owned implementation behind w.

func WorkspaceHandleOf(w *Workspace) WorkspaceHandle

CompareValues compares string or numeric values.

func CompareValues(left, right Value) (int, bool)

DuplicateKeyValueCapacity returns the expected encoded capacity for value.

func DuplicateKeyValueCapacity(value Value) int

EncodeValueForDuplicateKey appends value’s deterministic duplicate-key representation.

func EncodeValueForDuplicateKey(b *strings.Builder, value Value)

FieldsShareable reports whether all field values can be shared without defensive cloning.

func FieldsShareable(fields Fields) bool

Int64Len returns the decimal byte length of value.

func Int64Len(value int64) int

ValueShareable reports whether v can be shared without defensive cloning.

func ValueShareable(v Value) bool