session package reference
Package path: github.com/cpcf/gess/session
Constants
Section titled “Constants”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.DiagnosticsSchemaVersionconst MemoryInspectionSchemaVersion = engine.MemoryInspectionSchemaVersionconst TopologySchemaVersion = engine.TopologySchemaVersionVariables
Section titled “Variables”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
Section titled “ActionFailureError”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.ActionFailureErrorActivationID
Section titled “ActivationID”ActivationID identifies one activation: a rule paired with the specific facts that matched it.
type ActivationID = rules.ActivationIDAgenda
Section titled “Agenda”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}Agenda.Activations
Section titled “Agenda.Activations”Activations returns pending activations in the order Run would fire them.
func (a Agenda) Activations() []AgendaActivationAgenda.ActivationsForModule
Section titled “Agenda.ActivationsForModule”ActivationsForModule returns pending activations for module in module-local firing order.
func (a Agenda) ActivationsForModule(module ModuleName) []AgendaActivationAgenda.FocusStack
Section titled “Agenda.FocusStack”FocusStack returns a copy of the captured focus stack from bottom to top.
func (a Agenda) FocusStack() []ModuleNameAgenda.Len
Section titled “Agenda.Len”Len reports the number of activations in fire order.
func (a Agenda) Len() intAgendaActivation
Section titled “AgendaActivation”AgendaActivation describes one pending activation in an Agenda: its rule, module, salience, and matched facts.
type AgendaActivation struct { // contains filtered or unexported fields}AgendaActivation.ActivationID
Section titled “AgendaActivation.ActivationID”ActivationID returns the activation identity.
func (a AgendaActivation) ActivationID() ActivationIDAgendaActivation.FactIDs
Section titled “AgendaActivation.FactIDs”FactIDs returns the fact identities matched by the activation.
func (a AgendaActivation) FactIDs() []FactIDAgendaActivation.Module
Section titled “AgendaActivation.Module”Module returns the agenda module that owns the activation.
func (a AgendaActivation) Module() ModuleNameAgendaActivation.RuleID
Section titled “AgendaActivation.RuleID”RuleID returns the rule that produced the activation.
func (a AgendaActivation) RuleID() RuleIDAgendaActivation.RuleName
Section titled “AgendaActivation.RuleName”RuleName returns the rule name.
func (a AgendaActivation) RuleName() stringAgendaActivation.RuleRevisionID
Section titled “AgendaActivation.RuleRevisionID”RuleRevisionID returns the concrete rule revision behind the activation.
func (a AgendaActivation) RuleRevisionID() RuleRevisionIDAgendaActivation.Salience
Section titled “AgendaActivation.Salience”Salience returns the activation salience.
func (a AgendaActivation) Salience() intApplyRulesetResult
Section titled “ApplyRulesetResult”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}ApplyRulesetResult.Applied
Section titled “ApplyRulesetResult.Applied”Applied reports whether the ruleset swap was applied.
func (r ApplyRulesetResult) Applied() boolApplyRulesetStatus
Section titled “ApplyRulesetStatus”ApplyRulesetStatus is the outcome of a Session.ApplyRuleset call.
type ApplyRulesetStatus = rules.ApplyRulesetStatusAssertResult
Section titled “AssertResult”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}AssertResult.Inserted
Section titled “AssertResult.Inserted”Inserted reports whether the assert inserted a new fact.
func (r AssertResult) Inserted() boolAssertStatus
Section titled “AssertStatus”AssertStatus is the outcome of a Session.Assert or AssertTemplateValues call.
type AssertStatus = rules.AssertStatusBindingValue
Section titled “BindingValue”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
Section titled “Checkpoint”Checkpoint is an opaque, immutable durable-session value. Use EncodeCheckpoint and DecodeCheckpoint for persistence.
type Checkpoint struct { // contains filtered or unexported fields}DecodeCheckpoint
Section titled “DecodeCheckpoint”DecodeCheckpoint reads one canonical checkpoint document. Input is bounded by DefaultCheckpointMaxBytes.
func DecodeCheckpoint(r io.Reader) (Checkpoint, error)Checkpoint.FormatVersion
Section titled “Checkpoint.FormatVersion”FormatVersion returns the checkpoint wire schema version.
func (c Checkpoint) FormatVersion() intCheckpoint.RulesetID
Section titled “Checkpoint.RulesetID”RulesetID returns the compiled ruleset required to restore the checkpoint.
func (c Checkpoint) RulesetID() RulesetIDCheckpoint.SessionID
Section titled “Checkpoint.SessionID”SessionID returns the captured session identity.
func (c Checkpoint) SessionID() SessionIDDemandCascadeLimitError
Section titled “DemandCascadeLimitError”DemandCascadeLimitError reports the configured cascade limit and the number of demand steps completed before it stopped the operation.
type DemandCascadeLimitError = rules.DemandCascadeLimitErrorDerivation
Section titled “Derivation”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}Derivation.DOT
Section titled “Derivation.DOT”DOT renders the derivation as a Graphviz DOT graph.
func (d Derivation) DOT() stringDerivation.MarshalJSON
Section titled “Derivation.MarshalJSON”MarshalJSON encodes the derivation as a versioned explain document.
func (d Derivation) MarshalJSON() ([]byte, error)Derivation.String
Section titled “Derivation.String”func (d Derivation) String() stringDiagnosticsAgenda
Section titled “DiagnosticsAgenda”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
Section titled “DiagnosticsAggregates”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
Section titled “DiagnosticsBackchain”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
Section titled “DiagnosticsFact”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
Section titled “DiagnosticsGraph”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
Section titled “DiagnosticsMemoryOwner”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
Section titled “DiagnosticsOption”DiagnosticsOption configures a diagnostics report.
type DiagnosticsOption = engine.DiagnosticsOptionWithDiagnosticsFacts
Section titled “WithDiagnosticsFacts”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() DiagnosticsOptionDiagnosticsQueries
Section titled “DiagnosticsQueries”DiagnosticsQueries summarizes compiled queries and transient query state.
type DiagnosticsQueries struct { Definitions int `json:"definitions"` ActiveProof bool `json:"activeProof"` TerminalRows int `json:"terminalRows"`}DiagnosticsReport
Section titled “DiagnosticsReport”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
Section titled “DiagnosticsSession”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
Section titled “DiagnosticsTerminals”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
Section titled “DiagnosticsTruthMaintenance”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
Section titled “DuplicateKey”DuplicateKey is the computed duplicate-detection key for a fact under its template’s duplicate policy.
type DuplicateKey = rules.DuplicateKeyEvent 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}Event.RelatedFactIDs
Section titled “Event.RelatedFactIDs”RelatedFactIDs returns a copy of the fact IDs related to the event.
func (e Event) RelatedFactIDs() []FactIDEventFunc
Section titled “EventFunc”EventFunc adapts a function to EventListener.
type EventFunc func(context.Context, Event) errorEventFunc.HandleEvent
Section titled “EventFunc.HandleEvent”func (f EventFunc) HandleEvent(ctx context.Context, event Event) errorEventListener
Section titled “EventListener”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
Section titled “NewTraceListener”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) EventListenerEventListenerOption
Section titled “EventListenerOption”EventListenerOption configures a listener registered with WithEventListener, such as ForEventTypes.
type EventListenerOption = engine.EventListenerOptionForEventTypes
Section titled “ForEventTypes”ForEventTypes restricts a listener registered with WithEventListener to the given event types.
func ForEventTypes(types ...EventType) EventListenerOptionEventSeverity
Section titled “EventSeverity”EventSeverity is an Event’s severity: info or error.
type EventSeverity = engine.EventSeverityEventType
Section titled “EventType”EventType discriminates the kind of change an Event reports.
type EventType = engine.EventTypeExplainLogOption
Section titled “ExplainLogOption”ExplainLogOption configures the bounded explain log installed by WithExplainLog.
type ExplainLogOption = engine.ExplainLogOptionWithExplainLogMaxEntries
Section titled “WithExplainLogMaxEntries”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) ExplainLogOptionExplainOption
Section titled “ExplainOption”ExplainOption configures an Explain call, bounding derivation depth and node count.
type ExplainOption = engine.ExplainOptionWithExplainMaxDepth
Section titled “WithExplainMaxDepth”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) ExplainOptionWithExplainMaxNodes
Section titled “WithExplainMaxNodes”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) ExplainOptionFactID
Section titled “FactID”FactID identifies a fact, stable across modifies within a generation. IDs from an earlier generation are stale after Reset.
type FactID = rules.FactIDFactLimitError
Section titled “FactLimitError”FactLimitError reports the configured working-memory limit and the fact count that the rejected insertion would have produced.
type FactLimitError = rules.FactLimitErrorFactModification
Section titled “FactModification”FactModification is one changed fact in a SnapshotDiff.
type FactModification struct { Before FactSnapshot After FactSnapshot ChangedFields []FieldChange SupportBefore FactSupportState SupportAfter FactSupportState}FactPatch
Section titled “FactPatch”FactPatch is the argument to Session.Modify: fields to set or overwrite, and field names to remove.
type FactPatch = rules.FactPatchFactSnapshot
Section titled “FactSnapshot”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}FactSnapshot.Field
Section titled “FactSnapshot.Field”Field returns one field value by name.
func (f FactSnapshot) Field(name string) (Value, bool)FactSnapshot.FieldPresence
Section titled “FactSnapshot.FieldPresence”FieldPresence returns whether a template field was defaulted, explicit, or omitted.
func (f FactSnapshot) FieldPresence(field string) (FieldPresence, bool)FactSnapshot.FieldPresenceMap
Section titled “FactSnapshot.FieldPresenceMap”FieldPresenceMap returns template field-presence metadata keyed by field name.
func (f FactSnapshot) FieldPresenceMap() map[string]FieldPresenceFactSnapshot.Fields
Section titled “FactSnapshot.Fields”Fields returns a copy of the fact’s field values.
func (f FactSnapshot) Fields() FieldsFactSnapshot.Generation
Section titled “FactSnapshot.Generation”Generation returns the working-memory generation that owns this fact.
func (f FactSnapshot) Generation() GenerationFactSnapshot.ID
Section titled “FactSnapshot.ID”ID returns the fact identity.
func (f FactSnapshot) ID() FactIDFactSnapshot.Name
Section titled “FactSnapshot.Name”Name returns the dynamic fact name, if the fact is not template-backed.
func (f FactSnapshot) Name() stringFactSnapshot.Path
Section titled “FactSnapshot.Path”Path returns the value at path, if present.
func (f FactSnapshot) Path(path PathSpec) (Value, bool, error)FactSnapshot.Recency
Section titled “FactSnapshot.Recency”Recency returns the mutation recency that ordered this fact.
func (f FactSnapshot) Recency() RecencyFactSnapshot.String
Section titled “FactSnapshot.String”func (f FactSnapshot) String() stringFactSnapshot.Support
Section titled “FactSnapshot.Support”Support returns the fact’s logical support classification.
func (f FactSnapshot) Support() FactSupportProvenanceFactSnapshot.TemplateKey
Section titled “FactSnapshot.TemplateKey”TemplateKey returns the template identity, if the fact is template-backed.
func (f FactSnapshot) TemplateKey() TemplateKeyFactSnapshot.Version
Section titled “FactSnapshot.Version”Version returns the fact version.
func (f FactSnapshot) Version() FactVersionFactSupportProvenance
Section titled “FactSupportProvenance”FactSupportProvenance is a fact’s support classification together with FactSnapshot.Support.
type FactSupportProvenance = rules.FactSupportProvenanceFactSupportState
Section titled “FactSupportState”FactSupportState classifies how a fact is supported: stated, logical, both, or metadata-only.
type FactSupportState = rules.FactSupportStateFactVersion
Section titled “FactVersion”FactVersion advances each time a fact is modified; a fact’s FactID stays stable across modifies within a generation.
type FactVersion = rules.FactVersionFieldChange
Section titled “FieldChange”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
Section titled “FieldPresence”FieldPresence records whether a template field was defaulted, explicit, or omitted.
type FieldPresence = rules.FieldPresenceFields
Section titled “Fields”Fields is a fact’s field values, keyed by field name.
type Fields = rules.FieldsFiring
Section titled “Firing”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
Section titled “Generation”Generation is the working-memory reset epoch. FactIDs embed a generation, so IDs from before a Reset are stale afterward.
type Generation = rules.GenerationInitialFact
Section titled “InitialFact”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.SessionInitialFactLogicalSupportCounters
Section titled “LogicalSupportCounters”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
Section titled “LogicalSupportEdge”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}MemoryInspectionReport
Section titled “MemoryInspectionReport”type MemoryInspectionReport = engine.MemoryInspectionReportMemoryInspectionRequest
Section titled “MemoryInspectionRequest”type MemoryInspectionRequest = engine.MemoryInspectionRequestMemoryNodeSummary
Section titled “MemoryNodeSummary”type MemoryNodeSummary = engine.MemoryNodeSummaryMemoryOwnerSummary
Section titled “MemoryOwnerSummary”type MemoryOwnerSummary = engine.MemoryOwnerSummaryMemoryRow
Section titled “MemoryRow”type MemoryRow = engine.MemoryRowMemoryRowCollection
Section titled “MemoryRowCollection”type MemoryRowCollection = engine.MemoryRowCollectionModifyResult
Section titled “ModifyResult”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}ModifyResult.Changed
Section titled “ModifyResult.Changed”Changed reports whether the modify changed the fact.
func (r ModifyResult) Changed() boolModifyStatus
Section titled “ModifyStatus”ModifyStatus is the outcome of a Session.Modify call.
type ModifyStatus = rules.ModifyStatusModuleName
Section titled “ModuleName”ModuleName identifies an agenda focus module.
type ModuleName = rules.ModuleNameMutationDelta
Section titled “MutationDelta”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}MutationDelta.FieldChanges
Section titled “MutationDelta.FieldChanges”FieldChanges returns a cloned copy of changed fields.
func (d MutationDelta) FieldChanges() []FieldChangeMutationKind
Section titled “MutationKind”MutationKind is the kind of change recorded in a MutationDelta: assert, modify, retract, or reset.
type MutationKind = rules.MutationKindMutationLog
Section titled “MutationLog”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
Section titled “AppendMutationLog”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
Section titled “DecodeMutationLog”DecodeMutationLog reads one canonical mutation-log document. Input is bounded by DefaultMutationLogMaxBytes.
func DecodeMutationLog(r io.Reader) (MutationLog, error)NewMutationLog
Section titled “NewMutationLog”NewMutationLog anchors an empty mutation log to base.
func NewMutationLog(base Checkpoint) (MutationLog, error)MutationLog.FormatVersion
Section titled “MutationLog.FormatVersion”FormatVersion returns the mutation-log wire schema version.
func (l MutationLog) FormatVersion() intMutationLog.Len
Section titled “MutationLog.Len”Len returns the number of committed checkpoints in the log.
func (l MutationLog) Len() intMutationLog.RulesetID
Section titled “MutationLog.RulesetID”RulesetID returns the compiled ruleset required to replay the log.
func (l MutationLog) RulesetID() RulesetIDMutationLog.SessionID
Section titled “MutationLog.SessionID”SessionID returns the session identity anchored by the log.
func (l MutationLog) SessionID() SessionIDMutationRecord
Section titled “MutationRecord”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
Section titled “Option”Option configures a Session at construction time. Each With* function below returns an Option.
type Option = engine.SessionOptionWithEventClock
Section titled “WithEventClock”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) OptionWithEventListener
Section titled “WithEventListener”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) OptionWithExplainLog
Section titled “WithExplainLog”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) OptionWithGlobals
Section titled “WithGlobals”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) OptionWithInitialFacts
Section titled “WithInitialFacts”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) OptionWithMaxDemandCascadeSteps
Section titled “WithMaxDemandCascadeSteps”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) OptionWithMaxFacts
Section titled “WithMaxFacts”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) OptionWithOutputWriter
Section titled “WithOutputWriter”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) OptionWithResetBeforeSnapshot
Section titled “WithResetBeforeSnapshot”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) OptionWithSessionID
Section titled “WithSessionID”WithSessionID sets the SessionID returned later by Session.ID.
func WithSessionID(id SessionID) OptionWithStrategy
Section titled “WithStrategy”WithStrategy sets the session’s conflict-resolution Strategy for equal-salience activations. The default is StrategyDepth.
func WithStrategy(strategy Strategy) OptionPathSpec
Section titled “PathSpec”PathSpec describes a path into a structured value.
type PathSpec = rules.PathSpecQueryArgs
Section titled “QueryArgs”QueryArgs maps query parameter names, without the leading ‘?’, to the Go values passed to Query or QueryAll.
type QueryArgs = engine.QueryArgsQueryIterator
Section titled “QueryIterator”QueryIterator iterates the pre-materialized rows produced by Session.Query or Snapshot.Query.
type QueryIterator struct { // contains filtered or unexported fields}*QueryIterator.All
Section titled “*QueryIterator.All”All returns every remaining query row.
func (it *QueryIterator) All(ctx context.Context) ([]QueryRow, error)*QueryIterator.Next
Section titled “*QueryIterator.Next”Next returns the next query row, or ok=false when iteration is complete.
func (it *QueryIterator) Next(ctx context.Context) (QueryRow, bool, error)QueryRow
Section titled “QueryRow”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}QueryRow.Aliases
Section titled “QueryRow.Aliases”Aliases returns the query result aliases in declared order.
func (r QueryRow) Aliases() []stringQueryRow.Fact
Section titled “QueryRow.Fact”Fact returns the fact bound to alias, if alias is a fact binding.
func (r QueryRow) Fact(alias string) (FactSnapshot, bool)QueryRow.Value
Section titled “QueryRow.Value”Value returns the value bound to alias, if alias is a computed value.
func (r QueryRow) Value(alias string) (Value, bool)Recency
Section titled “Recency”Recency is a session-wide counter that advances on every fact mutation, used to order which pending activation fires first.
type Recency = rules.RecencyResetResult
Section titled “ResetResult”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
Section titled “ResetStatus”ResetStatus is the outcome of a Session.Reset call.
type ResetStatus = rules.ResetStatusRetractResult
Section titled “RetractResult”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}RetractResult.Removed
Section titled “RetractResult.Removed”Removed reports whether the retract removed the fact.
func (r RetractResult) Removed() boolRetractStatus
Section titled “RetractStatus”RetractStatus is the outcome of a Session.Retract call.
type RetractStatus = rules.RetractStatusRuleID
Section titled “RuleID”RuleID identifies a rule across revisions.
type RuleID = rules.RuleIDRuleReplacement
Section titled “RuleReplacement”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
Section titled “RuleRevisionID”RuleRevisionID identifies a concrete compiled revision of a rule.
type RuleRevisionID = rules.RuleRevisionIDRuleRevisionSummary
Section titled “RuleRevisionSummary”RuleRevisionSummary identifies one rule revision by rule ID and revision ID, as reported in an ApplyRulesetResult.
type RuleRevisionSummary struct { RuleID RuleID RevisionID RuleRevisionID}RulesetID
Section titled “RulesetID”RulesetID identifies one compiled ruleset revision.
type RulesetID = rules.RulesetIDRunID is a per-session sequence number for a Run call.
type RunID = rules.RunIDRunOption
Section titled “RunOption”RunOption configures one Session.Run call, such as WithMaxFirings.
type RunOption = engine.RunOptionWithMaxFirings
Section titled “WithMaxFirings”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) RunOptionRunResult
Section titled “RunResult”RunResult reports the outcome of a Run: its status and how many activations fired.
type RunResult struct { RunID RunID Status RunStatus Fired int}RunStatus
Section titled “RunStatus”RunStatus is the outcome of a Session.Run call.
type RunStatus = rules.RunStatusSession
Section titled “Session”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
Section titled “ReplayMutationLog”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
Section titled “Restore”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)*Session.Agenda
Section titled “*Session.Agenda”Agenda returns a point-in-time view of pending activations.
func (s *Session) Agenda(ctx context.Context) (Agenda, error)*Session.AppendMutationLog
Section titled “*Session.AppendMutationLog”AppendMutationLog checkpoints the idle session and appends it to log.
func (s *Session) AppendMutationLog(ctx context.Context, log MutationLog) (MutationLog, error)*Session.ApplyRuleset
Section titled “*Session.ApplyRuleset”ApplyRuleset swaps in a compatible compiled ruleset while preserving working memory.
func (s *Session) ApplyRuleset(ctx context.Context, next *rules.Ruleset) (ApplyRulesetResult, error)*Session.Assert
Section titled “*Session.Assert”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)*Session.AssertTemplateValues
Section titled “*Session.AssertTemplateValues”AssertTemplateValues asserts a fact using values in template field order.
func (s *Session) AssertTemplateValues(ctx context.Context, templateKey TemplateKey, values ...Value) error*Session.Checkpoint
Section titled “*Session.Checkpoint”Checkpoint captures the complete durable state of an idle session.
func (s *Session) Checkpoint(ctx context.Context) (Checkpoint, error)*Session.ClearFocusStack
Section titled “*Session.ClearFocusStack”ClearFocusStack empties the session focus stack.
func (s *Session) ClearFocusStack(ctx context.Context) error*Session.Close
Section titled “*Session.Close”Close marks the session closed. Later operations fail with ErrClosedSession.
func (s *Session) Close() error*Session.CurrentFocus
Section titled “*Session.CurrentFocus”CurrentFocus returns the current agenda focus.
func (s *Session) CurrentFocus() ModuleName*Session.Diagnostics
Section titled “*Session.Diagnostics”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)*Session.Explain
Section titled “*Session.Explain”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)*Session.FocusStack
Section titled “*Session.FocusStack”FocusStack returns a copy of the focus stack from bottom to top.
func (s *Session) FocusStack() []ModuleName*Session.Fork
Section titled “*Session.Fork”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)*Session.Generation
Section titled “*Session.Generation”Generation returns the current working-memory generation.
func (s *Session) Generation() Generation*Session.ID
Section titled “*Session.ID”ID returns the session identifier configured with WithSessionID.
func (s *Session) ID() SessionID*Session.MemoryInspection
Section titled “*Session.MemoryInspection”func (s *Session) MemoryInspection(ctx context.Context, request MemoryInspectionRequest) (MemoryInspectionReport, error)*Session.Modify
Section titled “*Session.Modify”Modify applies patch to an existing fact.
func (s *Session) Modify(ctx context.Context, id FactID, patch FactPatch) (ModifyResult, error)*Session.PopFocus
Section titled “*Session.PopFocus”PopFocus removes and returns the current focus frame.
func (s *Session) PopFocus(ctx context.Context) (ModuleName, error)*Session.PushFocus
Section titled “*Session.PushFocus”PushFocus places module on top of the focus stack unless it is already current.
func (s *Session) PushFocus(ctx context.Context, module ModuleName) error*Session.Query
Section titled “*Session.Query”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)*Session.QueryAll
Section titled “*Session.QueryAll”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)*Session.Reset
Section titled “*Session.Reset”Reset clears working memory, advances the generation, and reapplies initial facts.
func (s *Session) Reset(ctx context.Context) (ResetResult, error)*Session.Retract
Section titled “*Session.Retract”Retract removes stated support for a fact.
func (s *Session) Retract(ctx context.Context, id FactID) (RetractResult, error)*Session.RulesetID
Section titled “*Session.RulesetID”RulesetID returns the compiled ruleset revision currently installed in the session.
func (s *Session) RulesetID() RulesetID*Session.Run
Section titled “*Session.Run”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)*Session.SetFocus
Section titled “*Session.SetFocus”SetFocus has the same practical behavior as PushFocus.
func (s *Session) SetFocus(ctx context.Context, module ModuleName) error*Session.Snapshot
Section titled “*Session.Snapshot”Snapshot returns an immutable, point-in-time view of working memory.
func (s *Session) Snapshot(ctx context.Context) (Snapshot, error)*Session.Topology
Section titled “*Session.Topology”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)*Session.WhatIf
Section titled “*Session.WhatIf”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)*Session.WhyNot
Section titled “*Session.WhyNot”WhyNot diagnoses why ruleName has no pending activation.
func (s *Session) WhyNot(ctx context.Context, ruleName string, opts ...WhyNotOption) (WhyNotReport, error)SessionID
Section titled “SessionID”SessionID identifies a session, set with WithSessionID.
type SessionID = rules.SessionIDSnapshot
Section titled “Snapshot”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}Snapshot.Explain
Section titled “Snapshot.Explain”Explain returns a derivation for fact id from the snapshot’s support graph.
func (s Snapshot) Explain(id FactID, opts ...ExplainOption) (Derivation, bool)Snapshot.Fact
Section titled “Snapshot.Fact”Fact returns the fact with id, if present.
func (s Snapshot) Fact(id FactID) (FactSnapshot, bool)Snapshot.Facts
Section titled “Snapshot.Facts”Facts returns snapshot facts in deterministic order.
func (s Snapshot) Facts() []FactSnapshotSnapshot.FactsByName
Section titled “Snapshot.FactsByName”FactsByName returns facts with the given dynamic fact name.
func (s Snapshot) FactsByName(name string) []FactSnapshotSnapshot.FactsByTemplateKey
Section titled “Snapshot.FactsByTemplateKey”FactsByTemplateKey returns facts with templateKey.
func (s Snapshot) FactsByTemplateKey(templateKey TemplateKey) []FactSnapshotSnapshot.Generation
Section titled “Snapshot.Generation”Generation returns the working-memory generation captured by the snapshot.
func (s Snapshot) Generation() GenerationSnapshot.Len
Section titled “Snapshot.Len”Len returns the number of facts in the snapshot.
func (s Snapshot) Len() intSnapshot.Query
Section titled “Snapshot.Query”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)Snapshot.QueryAll
Section titled “Snapshot.QueryAll”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)Snapshot.RulesetID
Section titled “Snapshot.RulesetID”RulesetID returns the compiled ruleset revision captured by the snapshot.
func (s Snapshot) RulesetID() RulesetIDSnapshot.SessionID
Section titled “Snapshot.SessionID”SessionID returns the session that produced the snapshot.
func (s Snapshot) SessionID() SessionIDSnapshot.String
Section titled “Snapshot.String”func (s Snapshot) String() stringSnapshot.SupportGraph
Section titled “Snapshot.SupportGraph”SupportGraph returns the logical support graph captured by the snapshot.
func (s Snapshot) SupportGraph() SupportGraphSnapshotDiff
Section titled “SnapshotDiff”SnapshotDiff is the working-memory difference between two snapshots.
type SnapshotDiff struct { Added []FactSnapshot Retracted []FactSnapshot Modified []FactModification}DiffSnapshots
Section titled “DiffSnapshots”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) SnapshotDiffSnapshotDiff.Empty
Section titled “SnapshotDiff.Empty”Empty reports whether the diff has no added, retracted, or modified facts.
func (d SnapshotDiff) Empty() boolSourceSpan
Section titled “SourceSpan”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.SourceSpanStrategy
Section titled “Strategy”Strategy selects how equal-salience activations are ordered: StrategyDepth (recency, the default) or StrategyBreadth (creation order). Set it with WithStrategy.
type Strategy = engine.StrategySupportGraph
Section titled “SupportGraph”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
Section titled “SupportID”SupportID identifies one logical support edge.
type SupportID = rules.SupportIDTemplateKey
Section titled “TemplateKey”TemplateKey identifies a compiled template within a ruleset.
type TemplateKey = rules.TemplateKeyTopologyEdge
Section titled “TopologyEdge”type TopologyEdge = engine.TopologyEdgeTopologyFocus
Section titled “TopologyFocus”type TopologyFocus = engine.TopologyFocusTopologyMode
Section titled “TopologyMode”type TopologyMode = engine.TopologyModeTopologyNode
Section titled “TopologyNode”type TopologyNode = engine.TopologyNodeTopologyOwner
Section titled “TopologyOwner”type TopologyOwner = engine.TopologyOwnerTopologyReport
Section titled “TopologyReport”type TopologyReport = engine.TopologyReportTopologyRequest
Section titled “TopologyRequest”type TopologyRequest = engine.TopologyRequestTopologySelector
Section titled “TopologySelector”type TopologySelector = engine.TopologySelectorTopologySource
Section titled “TopologySource”type TopologySource = engine.TopologySourceTopologyTotals
Section titled “TopologyTotals”type TopologyTotals = engine.TopologyTotalsTraceOption
Section titled “TraceOption”TraceOption configures a NewTraceListener, such as TraceWithTimestamps.
type TraceOption = engine.TraceOptionTraceWithTimestamps
Section titled “TraceWithTimestamps”TraceWithTimestamps prefixes each trace line printed by a NewTraceListener with the event’s timestamp.
func TraceWithTimestamps() TraceOptionValue is a typed field or expression value.
type Value = rules.ValueValueKind
Section titled “ValueKind”ValueKind is a Value’s type tag.
type ValueKind = rules.ValueKindWhatIfFiring
Section titled “WhatIfFiring”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
Section titled “WhatIfOption”WhatIfOption configures a Session.WhatIf run.
type WhatIfOption = engine.WhatIfOptionWithWhatIfExplain
Section titled “WithWhatIfExplain”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) WhatIfOptionWithWhatIfMaxFirings
Section titled “WithWhatIfMaxFirings”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) WhatIfOptionWithWhatIfOutputWriter
Section titled “WithWhatIfOutputWriter”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) WhatIfOptionWithWhatIfRetainFork
Section titled “WithWhatIfRetainFork”WithWhatIfRetainFork keeps the what-if fork open and returns it in the report; the caller then owns closing it.
func WithWhatIfRetainFork() WhatIfOptionWhatIfReport
Section titled “WhatIfReport”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}WhatIfReport.MarshalJSON
Section titled “WhatIfReport.MarshalJSON”MarshalJSON encodes a what-if report as a versioned explain document.
func (r WhatIfReport) MarshalJSON() ([]byte, error)WhyNotBranch
Section titled “WhyNotBranch”WhyNotBranch diagnoses one condition branch of a rule.
type WhyNotBranch struct { BranchID int Conditions []WhyNotCondition FirstFailing int PartialMatches []WhyNotPartialMatch}WhyNotCondition
Section titled “WhyNotCondition”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
Section titled “WhyNotConditionReason”WhyNotConditionReason classifies why a condition failed to extend a partial match.
type WhyNotConditionReason = rules.WhyNotConditionReasonWhyNotOption
Section titled “WhyNotOption”WhyNotOption configures a Session.WhyNot probe.
type WhyNotOption = engine.WhyNotOptionWithWhyNotMaxBlockers
Section titled “WithWhyNotMaxBlockers”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) WhyNotOptionWithWhyNotMaxPartialMatches
Section titled “WithWhyNotMaxPartialMatches”WithWhyNotMaxPartialMatches caps the near-miss partial matches Session.WhyNot reports per branch (default 3).
func WithWhyNotMaxPartialMatches(n int) WhyNotOptionWithWhyNotMaxProbedRows
Section titled “WithWhyNotMaxProbedRows”WithWhyNotMaxProbedRows bounds the beta rows Session.WhyNot scans per node (default 4096); reaching it sets the report’s Truncated flag.
func WithWhyNotMaxProbedRows(n int) WhyNotOptionWhyNotOutcome
Section titled “WhyNotOutcome”WhyNotOutcome is the top-level answer in a WhyNotReport.
type WhyNotOutcome = rules.WhyNotOutcomeWhyNotPartialMatch
Section titled “WhyNotPartialMatch”WhyNotPartialMatch is one near-miss with its bound values.
type WhyNotPartialMatch struct { Facts []FactID Bindings []BindingValue Satisfied int RejectedBySpan SourceSpan}WhyNotReport
Section titled “WhyNotReport”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}WhyNotReport.MarshalJSON
Section titled “WhyNotReport.MarshalJSON”MarshalJSON encodes the report as a versioned explain document.
func (r WhyNotReport) MarshalJSON() ([]byte, error)WhyNotReport.String
Section titled “WhyNotReport.String”func (r WhyNotReport) String() stringFunctions
Section titled “Functions”EncodeCheckpoint
Section titled “EncodeCheckpoint”EncodeCheckpoint writes checkpoint in the canonical versioned format.
func EncodeCheckpoint(w io.Writer, checkpoint Checkpoint) errorEncodeMutationLog
Section titled “EncodeMutationLog”EncodeMutationLog writes the canonical versioned mutation-log document.
func EncodeMutationLog(w io.Writer, log MutationLog) errorNewWorkspace
Section titled “NewWorkspace”NewWorkspace returns an empty engine-backed rule workspace ready for Add calls and compilation.
func NewWorkspace() *rules.Workspace