Skip to content

session package reference

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

const (
// CheckpointFormat identifies the durable-session checkpoint envelope.
CheckpointFormat = engine.CheckpointFormat
// CheckpointVersion is the checkpoint schema version this build writes.
CheckpointVersion = engine.CheckpointVersion
// DefaultCheckpointMaxBytes bounds DecodeCheckpoint input.
DefaultCheckpointMaxBytes = engine.DefaultCheckpointMaxBytes
// MutationLogFormat identifies the durable-session mutation-log envelope.
MutationLogFormat = engine.MutationLogFormat
// MutationLogVersion is the mutation-log schema version this build writes.
MutationLogVersion = engine.MutationLogVersion
// DefaultMutationLogMaxBytes bounds DecodeMutationLog input.
DefaultMutationLogMaxBytes = engine.DefaultMutationLogMaxBytes
)

const (
// WhyNotActivated means the rule has a pending activation.
WhyNotActivated = rules.WhyNotActivated
// WhyNotAlreadyFired means the rule matched and fired (refraction).
WhyNotAlreadyFired = rules.WhyNotAlreadyFired
// WhyNotNeverMatched means no branch produced a complete match.
WhyNotNeverMatched = rules.WhyNotNeverMatched
// WhyNotBlocked means the closest branch failed on a blocked negation.
WhyNotBlocked = rules.WhyNotBlocked
// WhyNotReasonNone is the zero condition reason.
WhyNotReasonNone = rules.WhyNotReasonNone
// WhyNotReasonNoAlphaMatches means the condition's pattern matched no
// fact.
WhyNotReasonNoAlphaMatches = rules.WhyNotReasonNoAlphaMatches
// WhyNotReasonJoinMismatch means facts exist but their join keys do not
// align with the partial match.
WhyNotReasonJoinMismatch = rules.WhyNotReasonJoinMismatch
// WhyNotReasonPredicate means a residual predicate or test rejected the
// candidate.
WhyNotReasonPredicate = rules.WhyNotReasonPredicate
// WhyNotReasonNegationBlocked means a negated condition is blocked by
// one or more facts.
WhyNotReasonNegationBlocked = rules.WhyNotReasonNegationBlocked
// ExplainSchemaVersion is the version of the machine-readable JSON
// explain contract emitted by MarshalJSON on Derivation, WhyNotReport,
// and WhatIfReport.
ExplainSchemaVersion = engine.ExplainSchemaVersion
)

const (
// EventFactAsserted, EventFactModified, and EventFactRetracted report
// working-memory changes; EventReset reports a session Reset.
EventFactAsserted = engine.EventFactAsserted
EventFactModified = engine.EventFactModified
EventFactRetracted = engine.EventFactRetracted
EventReset = engine.EventReset
// EventRuleActivated and EventRuleDeactivated report a match
// entering or leaving the agenda.
EventRuleActivated = engine.EventRuleActivated
EventRuleDeactivated = engine.EventRuleDeactivated
// EventRuleFired reports one activation firing during a Run.
EventRuleFired = engine.EventRuleFired
// EventActionFailed reports a rule action returning an error; its
// [Event] carries ActionName, ActionIndex, and Cause, with severity
// [EventSeverityError].
EventActionFailed = engine.EventActionFailed
// EventLogicalSupportAdded and EventLogicalSupportRemoved report a
// logical support edge being created or removed.
EventLogicalSupportAdded = engine.EventLogicalSupportAdded
EventLogicalSupportRemoved = engine.EventLogicalSupportRemoved
// EventSeverityInfo is the default event severity.
EventSeverityInfo = engine.EventSeverityInfo
// EventSeverityError marks [EventActionFailed] events.
EventSeverityError = engine.EventSeverityError
// StrategyDepth orders equal-salience activations by recency, most
// recent first. It is the default [Strategy].
StrategyDepth = engine.StrategyDepth
// StrategyBreadth orders equal-salience activations by creation
// order, oldest first.
StrategyBreadth = engine.StrategyBreadth
// MutationAssert, MutationModify, MutationRetract, and MutationReset
// tag a [MutationDelta]'s Kind.
MutationAssert = rules.MutationAssert
MutationModify = rules.MutationModify
MutationRetract = rules.MutationRetract
MutationReset = rules.MutationReset
// RunCompleted reports that Run emptied the agenda.
RunCompleted = rules.RunCompleted
// RunHalted reports that an action called Halt; the halting
// activation's remaining actions still ran, and a later Run
// continues with the activations left pending.
RunHalted = rules.RunHalted
// RunFireLimit reports that Run stopped at the [WithMaxFirings]
// limit with activations still pending; a later Run continues them.
RunFireLimit = rules.RunFireLimit
// RunCanceled reports that ctx was canceled during the run.
RunCanceled = rules.RunCanceled
// RunActionFailed reports that an action returned an error; Run
// returns a non-nil error that is an *[ActionFailureError].
RunActionFailed = rules.RunActionFailed
// RunClosed reports that the session was already closed.
RunClosed = rules.RunClosed
// RunConcurrencyMisuse reports that this Run overlapped another Run
// on the same session.
RunConcurrencyMisuse = rules.RunConcurrencyMisuse
// RunFailed reports an internal engine failure that prevented the
// run from completing.
RunFailed = rules.RunFailed
// FactSupportStated marks a fact asserted by host code and not
// logically supported.
FactSupportStated = rules.FactSupportStated
// FactSupportLogical marks a fact asserted only through rule-driven
// logical support; it is retracted automatically when that support
// is removed, and can't be modified or retracted directly.
FactSupportLogical = rules.FactSupportLogical
// FactSupportStatedAndLogical marks a fact that carries both stated
// and logical support at once.
FactSupportStatedAndLogical = rules.FactSupportStatedAndLogical
// FactSupportMetadataOnly marks a fact support classification used
// internally for metadata-only support transitions.
FactSupportMetadataOnly = rules.FactSupportMetadataOnly
// AssertInserted reports that a new fact entered working memory.
AssertInserted = rules.AssertInserted
// AssertExisting reports that the template's duplicate policy
// matched an existing fact with identical fields, so no new fact
// was inserted.
AssertExisting = rules.AssertExisting
// AssertReplaced reports that a unique-key template matched an
// existing fact whose non-key fields differed, so the old fact was
// retracted and a new fact (with a new fact ID) was inserted in its
// place.
AssertReplaced = rules.AssertReplaced
// AssertValidationFailure reports that the fields failed template
// validation; the error wraps [rules.ErrValidation].
AssertValidationFailure = rules.AssertValidationFailure
// AssertClosed reports that the session was already closed.
AssertClosed = rules.AssertClosed
// AssertConcurrencyMisuse reports concurrent misuse of the session.
AssertConcurrencyMisuse = rules.AssertConcurrencyMisuse
// ModifyChanged reports that fields changed and propagated through
// the Rete network.
ModifyChanged = rules.ModifyChanged
// ModifyNoOp reports that the patch made no difference to the
// fact's fields.
ModifyNoOp = rules.ModifyNoOp
// ModifyMissing reports that no such fact exists in the current
// generation.
ModifyMissing = rules.ModifyMissing
// ModifyStale reports that the fact ID's generation predates the
// session's current generation, typically from before a Reset.
ModifyStale = rules.ModifyStale
// ModifyValidationFailure reports that the patched fact fails
// template validation.
ModifyValidationFailure = rules.ModifyValidationFailure
// ModifyDuplicate reports that the patch collides with another
// existing fact under the template's duplicate policy.
ModifyDuplicate = rules.ModifyDuplicate
// ModifyLogicalSupport reports that the fact currently has logical
// support and can't be modified directly.
ModifyLogicalSupport = rules.ModifyLogicalSupport
// ModifyClosed reports that the session was already closed.
ModifyClosed = rules.ModifyClosed
// ModifyConcurrencyMisuse reports concurrent misuse of the session.
ModifyConcurrencyMisuse = rules.ModifyConcurrencyMisuse
// RetractRemoved reports that the fact left working memory; any
// logical facts it alone supported cascade away in the same
// operation.
RetractRemoved = rules.RetractRemoved
// RetractStatedSupportRemoved reports that the fact had both stated
// and logical support, its stated support was removed, and it
// survives as logical-only.
RetractStatedSupportRemoved = rules.RetractStatedSupportRemoved
// RetractLogicalOnly reports that the fact exists only through
// logical support and can't be retracted directly; retract its
// supporting facts instead.
RetractLogicalOnly = rules.RetractLogicalOnly
// RetractMissing reports that no such fact exists in the current
// generation.
RetractMissing = rules.RetractMissing
// RetractStale reports that the fact ID's generation predates the
// session's current generation, typically from before a Reset.
RetractStale = rules.RetractStale
// RetractClosed reports that the session was already closed.
RetractClosed = rules.RetractClosed
// RetractValidationFailure reports an internal propagation error
// during retraction.
RetractValidationFailure = rules.RetractValidationFailure
// RetractConcurrencyMisuse reports concurrent misuse of the session.
RetractConcurrencyMisuse = rules.RetractConcurrencyMisuse
// ResetApplied reports that the reset succeeded: the generation
// advanced, working memory was cleared and reseeded with initial
// facts, logical support and backchain demand were cleared, and the
// focus stack and agenda were rebuilt.
ResetApplied = rules.ResetApplied
// ResetValidationFailure reports that rebuilding initial facts or
// the Rete graph for the new generation failed.
ResetValidationFailure = rules.ResetValidationFailure
// ResetClosed reports that the session was already closed.
ResetClosed = rules.ResetClosed
// ResetConcurrencyMisuse reports concurrent misuse of the session.
ResetConcurrencyMisuse = rules.ResetConcurrencyMisuse
// ApplyRulesetApplied reports that the new ruleset was swapped in
// with working memory kept, and lists which rule revisions were
// added, removed, replaced, or unchanged.
ApplyRulesetApplied = rules.ApplyRulesetApplied
// ApplyRulesetUnchanged reports that the target ruleset has the
// same RulesetID as the current one, so no work was performed.
// RulesetID does not cover Go host function or action
// implementations, so a ruleset differing only in its Go closures
// reports Unchanged and the session keeps executing the previously
// applied closures.
ApplyRulesetUnchanged = rules.ApplyRulesetUnchanged
// ApplyRulesetIncompatible reports that the target ruleset is nil,
// doesn't define the templates live facts depend on with an
// identical spec, or the configured initial facts no longer
// validate against it.
ApplyRulesetIncompatible = rules.ApplyRulesetIncompatible
// ApplyRulesetClosed reports that the session was already closed.
ApplyRulesetClosed = rules.ApplyRulesetClosed
// ApplyRulesetConcurrencyMisuse reports concurrent misuse of the
// session.
ApplyRulesetConcurrencyMisuse = rules.ApplyRulesetConcurrencyMisuse
)

const (
TopologyModeFull = engine.TopologyModeFull
TopologyModeFocused = engine.TopologyModeFocused
TopologyModeSummary = engine.TopologyModeSummary
)

const DiagnosticsSchemaVersion = engine.DiagnosticsSchemaVersion

const MemoryInspectionSchemaVersion = engine.MemoryInspectionSchemaVersion

const TopologySchemaVersion = engine.TopologySchemaVersion

var (
// ErrClosedSession is returned by any session operation called after
// Close, paired with the operation's ...Closed status.
ErrClosedSession = rules.ErrClosedSession
// ErrConcurrencyMisuse is returned when an operation can't acquire
// the session's single-owner lock: overlapping calls from other
// goroutines, or Snapshot/queries attempted while a Run is active.
ErrConcurrencyMisuse = rules.ErrConcurrencyMisuse
// ErrActionFailed is the sentinel [ActionFailureError].Is matches,
// representing a rule action that returned an error during Run.
ErrActionFailed = rules.ErrActionFailed
// ErrFactNotFound is returned by Modify or Retract when the given
// FactID doesn't exist in the current generation.
ErrFactNotFound = rules.ErrFactNotFound
// ErrStaleFactID is returned by Modify or Retract when the given
// FactID's generation predates the session's current generation,
// typically because a Reset happened since the ID was obtained.
ErrStaleFactID = rules.ErrStaleFactID
// ErrDuplicateFact is returned by Modify when the patched fact
// collides with another existing fact under a deduplicating
// duplicate policy.
ErrDuplicateFact = rules.ErrDuplicateFact
// ErrQueryNotFound is returned by Query or QueryAll for an unknown
// query name.
ErrQueryNotFound = rules.ErrQueryNotFound
// ErrQueryArgument is returned when [QueryArgs] names an unknown
// parameter, omits a required parameter, or supplies a value whose
// kind doesn't match the declared parameter kind.
ErrQueryArgument = rules.ErrQueryArgument
// ErrQueryExecution is returned when running a compiled query fails
// internally, independent of the caller's arguments.
ErrQueryExecution = rules.ErrQueryExecution
// ErrLogicalSupportUnavailable is returned when asserting a logical
// fact without a valid activation to support it.
ErrLogicalSupportUnavailable = rules.ErrLogicalSupportUnavailable
// ErrLogicalOnlyRetract is returned by Retract when the fact exists
// only through logical support; retract its supporting facts
// instead.
ErrLogicalOnlyRetract = rules.ErrLogicalOnlyRetract
// ErrLogicalFactModify is returned by Modify when the fact currently
// carries logical support, whether logical-only or stated-and-
// logical.
ErrLogicalFactModify = rules.ErrLogicalFactModify
// ErrExplainLogUnavailable is returned by Session.Explain when the
// session was built without [WithExplainLog]; fall back to
// Snapshot.Explain for a support-only derivation.
ErrExplainLogUnavailable = rules.ErrExplainLogUnavailable
// ErrRuleNotFound is returned by Session.WhyNot when the named rule is
// not in the session's ruleset.
ErrRuleNotFound = rules.ErrRuleNotFound
// ErrDemandCascadeLimit is matched by [DemandCascadeLimitError] when a
// session reaches the bound configured by [WithMaxDemandCascadeSteps].
ErrDemandCascadeLimit = rules.ErrDemandCascadeLimit
// ErrFactLimit is matched by [FactLimitError] when a session reaches the
// bound configured by [WithMaxFacts].
ErrFactLimit = rules.ErrFactLimit
)

ActionFailureError wraps the error an action returned during Run, identifying which activation and action produced it. Unwrap returns the underlying cause; Is matches ErrActionFailed.

type ActionFailureError = engine.ActionFailureError

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

type ActivationID = rules.ActivationID

Agenda is an ordered, immutable view of pending activations, as returned by Session.Agenda in the exact order Run would fire them.

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

Activations returns pending activations in the order Run would fire them.

func (a Agenda) Activations() []AgendaActivation

ActivationsForModule returns pending activations for module in module-local firing order.

func (a Agenda) ActivationsForModule(module ModuleName) []AgendaActivation

FocusStack returns a copy of the captured focus stack from bottom to top.

func (a Agenda) FocusStack() []ModuleName

Len reports the number of activations in fire order.

func (a Agenda) Len() int

AgendaActivation describes one pending activation in an Agenda: its rule, module, salience, and matched facts.

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

ActivationID returns the activation identity.

func (a AgendaActivation) ActivationID() ActivationID

FactIDs returns the fact identities matched by the activation.

func (a AgendaActivation) FactIDs() []FactID

Module returns the agenda module that owns the activation.

func (a AgendaActivation) Module() ModuleName

RuleID returns the rule that produced the activation.

func (a AgendaActivation) RuleID() RuleID

RuleName returns the rule name.

func (a AgendaActivation) RuleName() string

RuleRevisionID returns the concrete rule revision behind the activation.

func (a AgendaActivation) RuleRevisionID() RuleRevisionID

Salience returns the activation salience.

func (a AgendaActivation) Salience() int

ApplyRulesetResult reports the outcome of swapping in a new ruleset: its status and which rule revisions were added, removed, replaced, or left unchanged.

type ApplyRulesetResult struct {
Status ApplyRulesetStatus
PreviousRulesetID RulesetID
CurrentRulesetID RulesetID
AddedRuleRevisions []RuleRevisionSummary
RemovedRuleRevisions []RuleRevisionSummary
ReplacedRuleRevisions []RuleReplacement
UnchangedRuleRevisions []RuleRevisionSummary
}

Applied reports whether the ruleset swap was applied.

func (r ApplyRulesetResult) Applied() bool

ApplyRulesetStatus is the outcome of a Session.ApplyRuleset call.

type ApplyRulesetStatus = rules.ApplyRulesetStatus

AssertResult reports the outcome of an assert: its status, the resulting fact, and the mutation delta.

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

Inserted reports whether the assert inserted a new fact.

func (r AssertResult) Inserted() bool

AssertStatus is the outcome of a Session.Assert or AssertTemplateValues call.

type AssertStatus = rules.AssertStatus

BindingValue is one condition binding and the value an action saw for it, as reported in a Firing.

type BindingValue struct {
Name string
Value Value
FromFact FactID
}

Checkpoint is an opaque, immutable durable-session value. Use EncodeCheckpoint and DecodeCheckpoint for persistence.

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

DecodeCheckpoint reads one canonical checkpoint document. Input is bounded by DefaultCheckpointMaxBytes.

func DecodeCheckpoint(r io.Reader) (Checkpoint, error)

FormatVersion returns the checkpoint wire schema version.

func (c Checkpoint) FormatVersion() int

RulesetID returns the compiled ruleset required to restore the checkpoint.

func (c Checkpoint) RulesetID() RulesetID

SessionID returns the captured session identity.

func (c Checkpoint) SessionID() SessionID

DemandCascadeLimitError reports the configured cascade limit and the number of demand steps completed before it stopped the operation.

type DemandCascadeLimitError = rules.DemandCascadeLimitError

Derivation is the recursive explanation of one fact, as returned by Snapshot.Explain and Session.Explain: its support state, the firing that produced it, its logical supporters, and its mutation lineage.

type Derivation struct {
Fact FactSnapshot
Support FactSupportState
ProducedBy *Firing
DependsOn []Derivation
History []MutationRecord
Truncated bool
}

DOT renders the derivation as a Graphviz DOT graph.

func (d Derivation) DOT() string

MarshalJSON encodes the derivation as a versioned explain document.

func (d Derivation) MarshalJSON() ([]byte, error)
func (d Derivation) String() string

DiagnosticsAgenda summarizes pending work, readiness, strategy, and focus.

type DiagnosticsAgenda struct {
Pending int `json:"pending"`
Ready bool `json:"ready"`
Dirty bool `json:"dirty"`
Strategy string `json:"strategy"`
CurrentFocus ModuleName `json:"currentFocus"`
FocusStack []ModuleName `json:"focusStack"`
}

DiagnosticsAggregates summarizes compiled and retained aggregate state.

type DiagnosticsAggregates struct {
Nodes int `json:"nodes"`
Rows uint64 `json:"rows"`
Buckets uint64 `json:"buckets"`
Indexes uint64 `json:"indexes"`
Bytes uint64 `json:"bytes"`
HighWater uint64 `json:"highWater"`
}

DiagnosticsBackchain summarizes demand facts, support, and cascade activity.

type DiagnosticsBackchain struct {
ActiveDemands int `json:"activeDemands"`
DemandsByTemplate map[TemplateKey]int `json:"demandsByTemplate"`
SupportRows uint64 `json:"supportRows"`
CascadeLimit int `json:"cascadeLimit"`
Cascades int `json:"cascades"`
CascadeSteps int `json:"cascadeSteps"`
CascadeLengthMax int `json:"cascadeLengthMax"`
CascadeLimitHits int `json:"cascadeLimitHits"`
}

DiagnosticsFact is an opt-in detached fact projection.

type DiagnosticsFact struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
TemplateKey TemplateKey `json:"templateKey,omitempty"`
Version FactVersion `json:"version"`
Recency Recency `json:"recency"`
Generation Generation `json:"generation"`
Support FactSupportState `json:"support"`
Fields map[string]any `json:"fields"`
FieldPresence map[string]FieldPresence `json:"fieldPresence,omitempty"`
}

DiagnosticsGraph summarizes the immutable compiled Rete graph.

type DiagnosticsGraph struct {
Runtime string `json:"runtime"`
AlphaNodes int `json:"alphaNodes"`
BetaNodes int `json:"betaNodes"`
UnionNodes int `json:"unionNodes"`
AggregateNodes int `json:"aggregateNodes"`
RuleTerminals int `json:"ruleTerminals"`
QueryTerminals int `json:"queryTerminals"`
RuleBranches int `json:"ruleBranches"`
QueryBranches int `json:"queryBranches"`
}

DiagnosticsMemoryOwner estimates retained state for one runtime owner.

type DiagnosticsMemoryOwner struct {
Owner string `json:"owner"`
Rows uint64 `json:"rows"`
Buckets uint64 `json:"buckets"`
Indexes uint64 `json:"indexes"`
Tombstones uint64 `json:"tombstones"`
Bytes uint64 `json:"bytes"`
HighWater uint64 `json:"highWater"`
}

DiagnosticsOption configures a diagnostics report.

type DiagnosticsOption = engine.DiagnosticsOption

WithDiagnosticsFacts includes detached fact details in a diagnostics report. Fact details are omitted by default so inspection does not clone the working memory payloads.

func WithDiagnosticsFacts() DiagnosticsOption

DiagnosticsQueries summarizes compiled queries and transient query state.

type DiagnosticsQueries struct {
Definitions int `json:"definitions"`
ActiveProof bool `json:"activeProof"`
TerminalRows int `json:"terminalRows"`
}

DiagnosticsReport is a versioned, machine-readable view of session runtime state. The JSON representation is the stable diagnostics contract.

type DiagnosticsReport struct {
Schema int `json:"gessDiagnosticsSchema"`
Session DiagnosticsSession `json:"session"`
Graph DiagnosticsGraph `json:"graph"`
Memory []DiagnosticsMemoryOwner `json:"memory"`
Agenda DiagnosticsAgenda `json:"agenda"`
Terminals DiagnosticsTerminals `json:"terminals"`
Aggregates DiagnosticsAggregates `json:"aggregates"`
Queries DiagnosticsQueries `json:"queries"`
TruthMaintenance DiagnosticsTruthMaintenance `json:"truthMaintenance"`
Backchain DiagnosticsBackchain `json:"backchain"`
Facts []DiagnosticsFact `json:"facts,omitempty"`
}

DiagnosticsSession identifies the inspected session and working-memory epoch.

type DiagnosticsSession struct {
SessionID SessionID `json:"sessionId"`
RulesetID RulesetID `json:"rulesetId"`
Generation Generation `json:"generation"`
FactCount int `json:"factCount"`
}

DiagnosticsTerminals summarizes rule and query terminal state.

type DiagnosticsTerminals struct {
RuleNodes int `json:"ruleNodes"`
QueryNodes int `json:"queryNodes"`
QueryRows int `json:"queryRows"`
MaxQueryRows int `json:"maxQueryRows"`
}

DiagnosticsTruthMaintenance summarizes logical support state and activity.

type DiagnosticsTruthMaintenance struct {
LogicalFacts int `json:"logicalFacts"`
StatedAndLogicalFacts int `json:"statedAndLogicalFacts"`
SupportEdges int `json:"supportEdges"`
SupportEdgesAdded int `json:"supportEdgesAdded"`
SupportEdgesRemoved int `json:"supportEdgesRemoved"`
CascadeRetractions int `json:"cascadeRetractions"`
}

DuplicateKey is the computed duplicate-detection key for a fact under its template’s duplicate policy.

type DuplicateKey = rules.DuplicateKey

Event is one state change delivered to an EventListener: a fact mutation, rule activation or firing, action failure, or logical support change. Listeners receive a cloned copy per event.

type Event struct {
SessionID SessionID
RulesetID RulesetID
RunID RunID
Sequence uint64
Timestamp time.Time
Type EventType
Severity EventSeverity
Generation Generation
Recency Recency
RuleID RuleID
RuleRevisionID RuleRevisionID
ActivationID ActivationID
Source SourceSpan
ActionName string
ActionIndex int
Cause error
FactIDs []FactID
Delta *MutationDelta
SupportEdge *LogicalSupportEdge
}

RelatedFactIDs returns a copy of the fact IDs related to the event.

func (e Event) RelatedFactIDs() []FactID

EventFunc adapts a function to EventListener.

type EventFunc func(context.Context, Event) error
func (f EventFunc) HandleEvent(ctx context.Context, event Event) error

EventListener receives Events as a session’s state changes. Listener errors are ignored: they never fail the mutation that produced the event, and later listeners still run.

type EventListener interface {
HandleEvent(context.Context, Event) error
}

NewTraceListener returns a listener that prints one line per event to w, suitable for tracing a session’s activity.

func NewTraceListener(w io.Writer, opts ...TraceOption) EventListener

EventListenerOption configures a listener registered with WithEventListener, such as ForEventTypes.

type EventListenerOption = engine.EventListenerOption

ForEventTypes restricts a listener registered with WithEventListener to the given event types.

func ForEventTypes(types ...EventType) EventListenerOption

EventSeverity is an Event’s severity: info or error.

type EventSeverity = engine.EventSeverity

EventType discriminates the kind of change an Event reports.

type EventType = engine.EventType

ExplainLogOption configures the bounded explain log installed by WithExplainLog.

type ExplainLogOption = engine.ExplainLogOption

WithExplainLogMaxEntries bounds the explain log to the most recent n fact-mutation entries (default engine.DefaultExplainLogMaxEntries). Evicting a fact’s earliest entries marks its reconstructed history Truncated.

func WithExplainLogMaxEntries(n int) ExplainLogOption

ExplainOption configures an Explain call, bounding derivation depth and node count.

type ExplainOption = engine.ExplainOption

WithExplainMaxDepth caps derivation recursion depth for an Explain call (default engine.DefaultExplainMaxDepth). Depth beyond the cap surfaces as a Truncated derivation node.

func WithExplainMaxDepth(depth int) ExplainOption

WithExplainMaxNodes caps the total derivation node count for one Explain call (default engine.DefaultExplainMaxNodes). Reaching the cap surfaces as a Truncated derivation node.

func WithExplainMaxNodes(nodes int) ExplainOption

FactID identifies a fact, stable across modifies within a generation. IDs from an earlier generation are stale after Reset.

type FactID = rules.FactID

FactLimitError reports the configured working-memory limit and the fact count that the rejected insertion would have produced.

type FactLimitError = rules.FactLimitError

FactModification is one changed fact in a SnapshotDiff.

type FactModification struct {
Before FactSnapshot
After FactSnapshot
ChangedFields []FieldChange
SupportBefore FactSupportState
SupportAfter FactSupportState
}

FactPatch is the argument to Session.Modify: fields to set or overwrite, and field names to remove.

type FactPatch = rules.FactPatch

FactSnapshot is an immutable view of one fact’s identity, fields, and support state as of the snapshot or event that produced it.

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

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 together with FactSnapshot.Support.

type FactSupportProvenance = rules.FactSupportProvenance

FactSupportState classifies how a fact is supported: stated, logical, both, or metadata-only.

type FactSupportState = rules.FactSupportState

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

type FactVersion = rules.FactVersion

FieldChange describes one field’s before and after value from a Modify, as recorded in MutationDelta.ChangedFields.

type FieldChange struct {
Field string
Old Value
New Value
}

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

type FieldPresence = rules.FieldPresence

Fields is a fact’s field values, keyed by field name.

type Fields = rules.Fields

Firing identifies the rule activation that produced a fact state, with the concrete bound values its action evaluated against.

type Firing struct {
RuleID RuleID
RuleName string
RuleRevisionID RuleRevisionID
ActivationID ActivationID
Generation Generation
Action string
Bindings []BindingValue
BindingsPartial bool
SupportingFacts []FactID
}

Generation is the working-memory reset epoch. FactIDs embed a generation, so IDs from before a Reset are stale afterward.

type Generation = rules.Generation

InitialFact describes one fact to assert when a session is constructed and to re-assert on every Reset, matching deffacts in generated .gess code. TemplateKey names the declared template and Fields supplies its slot values.

type InitialFact = engine.SessionInitialFact

LogicalSupportCounters holds running totals for logical support: current logical facts and edges, and lifetime asserts, retracts, and cascades.

type LogicalSupportCounters struct {
CurrentLogicalFacts int
CurrentStatedAndLogicalFacts int
CurrentSupportEdges int
LogicalFactsAsserted int
LogicalFactsRetracted int
SupportEdgesAdded int
SupportEdgesRemoved int
MetadataOnlyTransitions int
CascadeRetractions int
CascadeBreadthMax int
CascadeDepthMax int
}

LogicalSupportEdge is one edge from the facts an activation matched to the logical fact it supports.

type LogicalSupportEdge struct {
SupportID SupportID
FactID FactID
RuleID RuleID
RuleRevisionID RuleRevisionID
ActivationID ActivationID
Generation Generation
SupportingFacts []FactID
}
type MemoryInspectionReport = engine.MemoryInspectionReport
type MemoryInspectionRequest = engine.MemoryInspectionRequest
type MemoryNodeSummary = engine.MemoryNodeSummary
type MemoryOwnerSummary = engine.MemoryOwnerSummary
type MemoryRow = engine.MemoryRow
type MemoryRowCollection = engine.MemoryRowCollection

ModifyResult reports the outcome of a modify: its status, the resulting fact, and the mutation delta.

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

Changed reports whether the modify changed the fact.

func (r ModifyResult) Changed() bool

ModifyStatus is the outcome of a Session.Modify call.

type ModifyStatus = rules.ModifyStatus

ModuleName identifies an agenda focus module.

type ModuleName = rules.ModuleName

MutationDelta describes one mutation’s effect: its kind, the fact before and after, version and support changes, and which activation or rule caused it, if any.

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
}

FieldChanges returns a cloned copy of changed fields.

func (d MutationDelta) FieldChanges() []FieldChange

MutationKind is the kind of change recorded in a MutationDelta: assert, modify, retract, or reset.

type MutationKind = rules.MutationKind

MutationLog is an opaque, immutable sequence of durable semantic commits. Each commit is a canonical checkpoint linked to the preceding commit by a SHA-256 digest.

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

AppendMutationLog returns a new log with checkpoint as its next semantic commit. Existing log values remain unchanged.

func AppendMutationLog(log MutationLog, checkpoint Checkpoint) (MutationLog, error)

DecodeMutationLog reads one canonical mutation-log document. Input is bounded by DefaultMutationLogMaxBytes.

func DecodeMutationLog(r io.Reader) (MutationLog, error)

NewMutationLog anchors an empty mutation log to base.

func NewMutationLog(base Checkpoint) (MutationLog, error)

FormatVersion returns the mutation-log wire schema version.

func (l MutationLog) FormatVersion() int

Len returns the number of committed checkpoints in the log.

func (l MutationLog) Len() int

RulesetID returns the compiled ruleset required to replay the log.

func (l MutationLog) RulesetID() RulesetID

SessionID returns the session identity anchored by the log.

func (l MutationLog) SessionID() SessionID

MutationRecord is one entry in a fact’s assert -> modify… lineage, as reconstructed from a retained explain log.

type MutationRecord struct {
Kind MutationKind
Firing *Firing
ChangedFields []FieldChange
Sequence uint64
}

Option configures a Session at construction time. Each With* function below returns an Option.

type Option = engine.SessionOption

WithEventClock overrides the timestamp source used to stamp Event.Timestamp. A nil clock is ignored, leaving the default time.Now.

func WithEventClock(clock func() time.Time) Option

WithEventListener registers a listener to receive the session’s Events. Repeat the option to register more than one listener; a nil listener is ignored. Pass ForEventTypes to subscribe the listener to a subset of event types; envelopes for unsubscribed types are never constructed.

func WithEventListener(listener EventListener, opts ...EventListenerOption) Option

WithExplainLog attaches a bounded, in-memory recorder of fact-mutation events so Session.Explain can report a fact’s producing firing and its assert -> modify… lineage. Without it, Session.Explain returns ErrExplainLogUnavailable. A fork does not inherit the log; pass this option to Fork to record lineage on the fork. Reset clears the log.

func WithExplainLog(opts ...ExplainLogOption) Option

WithGlobals binds per-session values for globals declared on the ruleset, keyed by global name without the ‘*’ markers. Unnamed globals keep their declared defaults; naming an undeclared global or supplying a value of the wrong kind fails session construction.

func WithGlobals(values map[string]any) Option

WithInitialFacts appends facts to assert at construction and re-assert on every Reset, matching deffacts in generated .gess code. The option can be given more than once; facts accumulate across calls.

func WithInitialFacts(initials ...InitialFact) Option

WithMaxDemandCascadeSteps bounds each backward-chaining demand cascade. The limit spans all demands raised during one Run or query proof; n <= 0 leaves cascades unbounded.

func WithMaxDemandCascadeSteps(n int) Option

WithMaxFacts bounds facts retained in working memory, including initial and rule-generated facts. Duplicate assertions and unique-key replacements do not consume additional capacity. A value <= 0 leaves memory unbounded.

func WithMaxFacts(n int) Option

WithOutputWriter sets the destination for the .gess emit action. When unset, emitted output is discarded. A fork inherits the parent’s writer unless it supplies its own.

func WithOutputWriter(w io.Writer) Option

WithResetBeforeSnapshot controls whether a successful Reset populates ResetResult.Before with a snapshot of working memory immediately before the reset. It defaults to false, since materializing that snapshot has a cost most sessions don’t need to pay.

func WithResetBeforeSnapshot(enabled bool) Option

WithSessionID sets the SessionID returned later by Session.ID.

func WithSessionID(id SessionID) Option

WithStrategy sets the session’s conflict-resolution Strategy for equal-salience activations. The default is StrategyDepth.

func WithStrategy(strategy Strategy) Option

PathSpec describes a path into a structured value.

type PathSpec = rules.PathSpec

QueryArgs maps query parameter names, without the leading ‘?’, to the Go values passed to Query or QueryAll.

type QueryArgs = engine.QueryArgs

QueryIterator iterates the pre-materialized rows produced by Session.Query or Snapshot.Query.

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

All returns every remaining query row.

func (it *QueryIterator) All(ctx context.Context) ([]QueryRow, error)

Next returns the next query row, or ok=false when iteration is complete.

func (it *QueryIterator) Next(ctx context.Context) (QueryRow, bool, error)

QueryRow is one result row from a query, holding fact bindings and computed values under their declared aliases. Its position in a result collection has no semantic meaning because query row order is unspecified.

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

Aliases returns the query result aliases in declared order.

func (r QueryRow) Aliases() []string

Fact returns the fact bound to alias, if alias is a fact binding.

func (r QueryRow) Fact(alias string) (FactSnapshot, bool)

Value returns the value bound to alias, if alias is a computed value.

func (r QueryRow) Value(alias string) (Value, bool)

Recency is a session-wide counter that advances on every fact mutation, used to order which pending activation fires first.

type Recency = rules.Recency

ResetResult reports the outcome of a reset: its status, the new generation, and, if WithResetBeforeSnapshot was set, a snapshot of working memory as it stood immediately before the reset.

type ResetResult struct {
Status ResetStatus
Generation Generation
Before Snapshot
Delta MutationDelta
}

ResetStatus is the outcome of a Session.Reset call.

type ResetStatus = rules.ResetStatus

RetractResult reports the outcome of a retract: its status, the removed fact, and the mutation delta.

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

Removed reports whether the retract removed the fact.

func (r RetractResult) Removed() bool

RetractStatus is the outcome of a Session.Retract call.

type RetractStatus = rules.RetractStatus

RuleID identifies a rule across revisions.

type RuleID = rules.RuleID

RuleReplacement identifies a rule whose compiled revision changed across an ApplyRuleset call, from OldRevisionID to NewRevisionID.

type RuleReplacement struct {
RuleID RuleID
OldRevisionID RuleRevisionID
NewRevisionID RuleRevisionID
}

RuleRevisionID identifies a concrete compiled revision of a rule.

type RuleRevisionID = rules.RuleRevisionID

RuleRevisionSummary identifies one rule revision by rule ID and revision ID, as reported in an ApplyRulesetResult.

type RuleRevisionSummary struct {
RuleID RuleID
RevisionID RuleRevisionID
}

RulesetID identifies one compiled ruleset revision.

type RulesetID = rules.RulesetID

RunID is a per-session sequence number for a Run call.

type RunID = rules.RunID

RunOption configures one Session.Run call, such as WithMaxFirings.

type RunOption = engine.RunOption

WithMaxFirings caps one Run call at n activation firings. A run that stops at the cap with work remaining returns RunFireLimit; n <= 0 fails the run.

func WithMaxFirings(n int) RunOption

RunResult reports the outcome of a Run: its status and how many activations fired.

type RunResult struct {
RunID RunID
Status RunStatus
Fired int
}

RunStatus is the outcome of a Session.Run call.

type RunStatus = rules.RunStatus

Session is the mutable runtime for one compiled ruleset: working memory, the agenda, the focus stack, logical support, backchain demand, and event delivery. A session has one logical owner; overlapping operations from other goroutines fail fast with ErrConcurrencyMisuse rather than blocking, except that mutations from other goroutines queue during an active Run.

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

New builds a session from revision: it compiles the configured initial facts against revision, builds the Rete runtime, seeds working memory, and computes the initial agenda. It returns an error if revision is nil or the initial facts fail to validate against it.

func New(revision *rules.Ruleset, opts ...Option) (*Session, error)

ReplayMutationLog validates every committed checkpoint against revision and restores the final commit.

func ReplayMutationLog(ctx context.Context, revision *rules.Ruleset, base Checkpoint, log MutationLog, opts ...Option) (*Session, error)

Restore builds an independent session from checkpoint against revision. Revision must have the checkpoint’s RulesetID. Options may attach process-local listeners, output, explain capture, an event clock, or a replacement session ID; persisted globals, initial facts, strategy, reset behavior, and demand limits cannot be overridden.

func Restore(ctx context.Context, revision *rules.Ruleset, checkpoint Checkpoint, opts ...Option) (*Session, error)

Agenda returns a point-in-time view of pending activations.

func (s *Session) Agenda(ctx context.Context) (Agenda, error)

AppendMutationLog checkpoints the idle session and appends it to log.

func (s *Session) AppendMutationLog(ctx context.Context, log MutationLog) (MutationLog, error)

ApplyRuleset swaps in a compatible compiled ruleset while preserving working memory.

func (s *Session) ApplyRuleset(ctx context.Context, next *rules.Ruleset) (ApplyRulesetResult, error)

Assert asserts a fact for templateKey using field values keyed by field name.

func (s *Session) Assert(ctx context.Context, templateKey TemplateKey, fields Fields) (AssertResult, error)

AssertTemplateValues asserts a fact using values in template field order.

func (s *Session) AssertTemplateValues(ctx context.Context, templateKey TemplateKey, values ...Value) error

Checkpoint captures the complete durable state of an idle session.

func (s *Session) Checkpoint(ctx context.Context) (Checkpoint, error)

ClearFocusStack empties the session focus stack.

func (s *Session) ClearFocusStack(ctx context.Context) error

Close marks the session closed. Later operations fail with ErrClosedSession.

func (s *Session) Close() error

CurrentFocus returns the current agenda focus.

func (s *Session) CurrentFocus() ModuleName

Diagnostics returns a point-in-time diagnostics report. By default it reports counts and retained-memory estimates without cloning fact payloads.

func (s *Session) Diagnostics(ctx context.Context, opts ...DiagnosticsOption) (DiagnosticsReport, error)

Explain returns a derivation for fact id using the session explain log.

func (s *Session) Explain(ctx context.Context, id FactID, opts ...ExplainOption) (Derivation, error)

FocusStack returns a copy of the focus stack from bottom to top.

func (s *Session) FocusStack() []ModuleName

Fork returns an independent session with the same working state as s.

The fork inherits the parent’s initial facts, globals, agenda strategy, and output writer — rule emits in the fork write to the parent’s writer unless the fork is created with WithOutputWriter. Callers running parent and fork concurrently must use a concurrency-safe shared writer or separate writers. WhatIf instead discards fork output unless explicitly captured. Event listeners and the explain log are not inherited.

func (s *Session) Fork(ctx context.Context, opts ...Option) (*Session, error)

Generation returns the current working-memory generation.

func (s *Session) Generation() Generation

ID returns the session identifier configured with WithSessionID.

func (s *Session) ID() SessionID
func (s *Session) MemoryInspection(ctx context.Context, request MemoryInspectionRequest) (MemoryInspectionReport, error)

Modify applies patch to an existing fact.

func (s *Session) Modify(ctx context.Context, id FactID, patch FactPatch) (ModifyResult, error)

PopFocus removes and returns the current focus frame.

func (s *Session) PopFocus(ctx context.Context) (ModuleName, error)

PushFocus places module on top of the focus stack unless it is already current.

func (s *Session) PushFocus(ctx context.Context, module ModuleName) error

Query returns an iterator over rows produced by a compiled query.

A query whose conditions need backchain-reactive facts generates demand and fires only activations descended from that query’s transient demand. Proof selection preserves agenda priority but is independent of the focus stack; unrelated activations remain pending. Facts derived during the proof persist after the query returns. Queries that generate no demand have no side effects. Rows are deterministic for a fixed session history, but otherwise order is unspecified; callers needing an order must sort.

func (s *Session) Query(ctx context.Context, name string, args QueryArgs) (*QueryIterator, error)

QueryAll materializes all rows produced by a compiled query.

A query whose conditions need backchain-reactive facts generates demand and fires only activations descended from that query’s transient demand. Proof selection preserves agenda priority but is independent of the focus stack; unrelated activations remain pending. Facts derived during the proof persist after the query returns. Queries that generate no demand have no side effects. Rows are deterministic for a fixed session history, but otherwise order is unspecified; callers needing an order must sort.

func (s *Session) QueryAll(ctx context.Context, name string, args QueryArgs) ([]QueryRow, error)

Reset clears working memory, advances the generation, and reapplies initial facts.

func (s *Session) Reset(ctx context.Context) (ResetResult, error)

Retract removes stated support for a fact.

func (s *Session) Retract(ctx context.Context, id FactID) (RetractResult, error)

RulesetID returns the compiled ruleset revision currently installed in the session.

func (s *Session) RulesetID() RulesetID

Run fires pending activations until the agenda drains, a halt is requested, a run option stops it, or an error occurs.

func (s *Session) Run(ctx context.Context, opts ...RunOption) (RunResult, error)

SetFocus has the same practical behavior as PushFocus.

func (s *Session) SetFocus(ctx context.Context, module ModuleName) error

Snapshot returns an immutable, point-in-time view of working memory.

func (s *Session) Snapshot(ctx context.Context) (Snapshot, error)

Topology returns a bounded, immutable projection of the compiled Rete graph. Session state is used only to resolve fact and activation focus selectors.

func (s *Session) Topology(ctx context.Context, request TopologyRequest) (TopologyReport, error)

WhatIf runs scenario against a fork and returns the counterfactual result.

func (s *Session) WhatIf(ctx context.Context, scenario func(ctx context.Context, fork *Session) error, opts ...WhatIfOption) (WhatIfReport, error)

WhyNot diagnoses why ruleName has no pending activation.

func (s *Session) WhyNot(ctx context.Context, ruleName string, opts ...WhyNotOption) (WhyNotReport, error)

SessionID identifies a session, set with WithSessionID.

type SessionID = rules.SessionID

Snapshot is an immutable, point-in-time view of working memory: every fact plus the support graph, as of when Snapshot was called. It does not change as the session mutates afterward.

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

Explain returns a derivation for fact id from the snapshot’s support graph.

func (s Snapshot) Explain(id FactID, opts ...ExplainOption) (Derivation, bool)

Fact returns the fact with id, if present.

func (s Snapshot) Fact(id FactID) (FactSnapshot, bool)

Facts returns snapshot facts in deterministic order.

func (s Snapshot) Facts() []FactSnapshot

FactsByName returns facts with the given dynamic fact name.

func (s Snapshot) FactsByName(name string) []FactSnapshot

FactsByTemplateKey returns facts with templateKey.

func (s Snapshot) FactsByTemplateKey(templateKey TemplateKey) []FactSnapshot

Generation returns the working-memory generation captured by the snapshot.

func (s Snapshot) Generation() Generation

Len returns the number of facts in the snapshot.

func (s Snapshot) Len() int

Query returns an iterator over rows produced by a compiled query against the snapshot.

Each call builds a fresh matching runtime and re-propagates every snapshot fact, so cost grows with snapshot size; for repeated queries over large working memories prefer session queries. Snapshot queries never generate backchain demand: a query that would need backward chaining fails with ErrUnsupportedRuntime. Rows are deterministic for a fixed session history, but otherwise order is unspecified; callers needing an order must sort.

func (s Snapshot) Query(ctx context.Context, name string, args QueryArgs) (*QueryIterator, error)

QueryAll materializes all rows produced by a compiled query against the snapshot.

Each call builds a fresh matching runtime and re-propagates every snapshot fact, so cost grows with snapshot size; for repeated queries over large working memories prefer session queries. Snapshot queries never generate backchain demand: a query that would need backward chaining fails with ErrUnsupportedRuntime. Rows are deterministic for a fixed session history, but otherwise order is unspecified; callers needing an order must sort.

func (s Snapshot) QueryAll(ctx context.Context, name string, args QueryArgs) ([]QueryRow, error)

RulesetID returns the compiled ruleset revision captured by the snapshot.

func (s Snapshot) RulesetID() RulesetID

SessionID returns the session that produced the snapshot.

func (s Snapshot) SessionID() SessionID
func (s Snapshot) String() string

SupportGraph returns the logical support graph captured by the snapshot.

func (s Snapshot) SupportGraph() SupportGraph

SnapshotDiff is the working-memory difference between two snapshots.

type SnapshotDiff struct {
Added []FactSnapshot
Retracted []FactSnapshot
Modified []FactModification
}

DiffSnapshots returns the difference from before to after: facts added, retracted, and modified (by field value or support state), in fact-id order.

func DiffSnapshots(before, after Snapshot) SnapshotDiff

Empty reports whether the diff has no added, retracted, or modified facts.

func (d SnapshotDiff) Empty() bool

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

type SourceSpan = rules.SourceSpan

Strategy selects how equal-salience activations are ordered: StrategyDepth (recency, the default) or StrategyBreadth (creation order). Set it with WithStrategy.

type Strategy = engine.Strategy

SupportGraph is the logical support edges and counters visible in a Snapshot, as of a given generation.

type SupportGraph struct {
Generation Generation
Edges []LogicalSupportEdge
Counters LogicalSupportCounters
}

SupportID identifies one logical support edge.

type SupportID = rules.SupportID

TemplateKey identifies a compiled template within a ruleset.

type TemplateKey = rules.TemplateKey
type TopologyEdge = engine.TopologyEdge
type TopologyFocus = engine.TopologyFocus
type TopologyMode = engine.TopologyMode
type TopologyNode = engine.TopologyNode
type TopologyOwner = engine.TopologyOwner
type TopologyReport = engine.TopologyReport
type TopologyRequest = engine.TopologyRequest
type TopologySelector = engine.TopologySelector
type TopologySource = engine.TopologySource
type TopologyTotals = engine.TopologyTotals

TraceOption configures a NewTraceListener, such as TraceWithTimestamps.

type TraceOption = engine.TraceOption

TraceWithTimestamps prefixes each trace line printed by a NewTraceListener with the event’s timestamp.

func TraceWithTimestamps() TraceOption

Value is a typed field or expression value.

type Value = rules.Value

ValueKind is a Value’s type tag.

type ValueKind = rules.ValueKind

WhatIfFiring is one rule firing during a what-if run.

type WhatIfFiring struct {
RuleID RuleID
RuleName string
RuleRevisionID RuleRevisionID
ActivationID ActivationID
FactIDs []FactID
Sequence uint64
}

WhatIfOption configures a Session.WhatIf run.

type WhatIfOption = engine.WhatIfOption

WithWhatIfExplain attaches an explain log to the what-if fork so the report includes a derivation for every added fact. The optional log options configure its history bound.

func WithWhatIfExplain(opts ...ExplainLogOption) WhatIfOption

WithWhatIfMaxFirings bounds a Session.WhatIf fork run at n firings (default engine.DefaultWhatIfMaxFirings). Pass n <= 0 to opt out of the bound.

func WithWhatIfMaxFirings(n int) WhatIfOption

WithWhatIfOutputWriter captures the emit output of the what-if run to w. By default the fork’s output is discarded so a hypothetical run never writes to the base session’s live output sink.

func WithWhatIfOutputWriter(w io.Writer) WhatIfOption

WithWhatIfRetainFork keeps the what-if fork open and returns it in the report; the caller then owns closing it.

func WithWhatIfRetainFork() WhatIfOption

WhatIfReport is the structured result of a Session.WhatIf run.

type WhatIfReport struct {
Base Snapshot
Fork Snapshot
Run RunResult
Firings []WhatIfFiring
Diff SnapshotDiff
AgendaBefore Agenda
AgendaAfter Agenda
Derivations []Derivation
ForkSession *Session
}

MarshalJSON encodes a what-if report as a versioned explain document.

func (r WhatIfReport) MarshalJSON() ([]byte, error)

WhyNotBranch diagnoses one condition branch of a rule.

type WhyNotBranch struct {
BranchID int
Conditions []WhyNotCondition
FirstFailing int
PartialMatches []WhyNotPartialMatch
}

WhyNotCondition reports one condition’s status within a branch.

type WhyNotCondition struct {
Order int
PlannedOrder int
Binding string
Negated bool
Test bool
Aggregate bool
Source SourceSpan
AlphaMatches int
Satisfied bool
Reason WhyNotConditionReason
RejectingSpan SourceSpan
Blockers []FactID
BlockerCount int
}

WhyNotConditionReason classifies why a condition failed to extend a partial match.

type WhyNotConditionReason = rules.WhyNotConditionReason

WhyNotOption configures a Session.WhyNot probe.

type WhyNotOption = engine.WhyNotOption

WithWhyNotMaxBlockers caps the blocking facts Session.WhyNot lists for a blocked negation (default 16); the reported BlockerCount is still the true total.

func WithWhyNotMaxBlockers(n int) WhyNotOption

WithWhyNotMaxPartialMatches caps the near-miss partial matches Session.WhyNot reports per branch (default 3).

func WithWhyNotMaxPartialMatches(n int) WhyNotOption

WithWhyNotMaxProbedRows bounds the beta rows Session.WhyNot scans per node (default 4096); reaching it sets the report’s Truncated flag.

func WithWhyNotMaxProbedRows(n int) WhyNotOption

WhyNotOutcome is the top-level answer in a WhyNotReport.

type WhyNotOutcome = rules.WhyNotOutcome

WhyNotPartialMatch is one near-miss with its bound values.

type WhyNotPartialMatch struct {
Facts []FactID
Bindings []BindingValue
Satisfied int
RejectedBySpan SourceSpan
}

WhyNotReport is the structured diagnosis of why a rule has no pending activation, as returned by Session.WhyNot.

type WhyNotReport struct {
RuleID RuleID
RuleName string
RuleRevisionID RuleRevisionID
Outcome WhyNotOutcome
Activations []AgendaActivation
Branches []WhyNotBranch
Truncated bool
}

MarshalJSON encodes the report as a versioned explain document.

func (r WhyNotReport) MarshalJSON() ([]byte, error)
func (r WhyNotReport) String() string

EncodeCheckpoint writes checkpoint in the canonical versioned format.

func EncodeCheckpoint(w io.Writer, checkpoint Checkpoint) error

EncodeMutationLog writes the canonical versioned mutation-log document.

func EncodeMutationLog(w io.Writer, log MutationLog) error

NewWorkspace returns an empty engine-backed rule workspace ready for Add calls and compilation.

func NewWorkspace() *rules.Workspace