Skip to content

scenario package reference

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

Package scenario defines portable scenario and report data contracts.

const (
ScenarioSchemaVersion = "gess.workbench.scenario.v1"
RunReportSchemaVersion = "gess.workbench.report.v1"
)

var (
ErrInvalidScenario = errors.New("invalid scenario")
ErrUnsupportedScenarioVersion = errors.New("unsupported scenario version")
ErrInvalidRunReport = errors.New("invalid run report")
ErrUnsupportedRunReportVersion = errors.New("unsupported run report version")
)

var (
// ErrRunReportProjection identifies an execution result that cannot be
// represented by the run-report contract.
ErrRunReportProjection = errors.New("run report projection failed")
// ErrRunReportTooLarge identifies a report whose fixed envelope alone is
// larger than maxReportBytes after all bounded detail has been removed.
ErrRunReportTooLarge = errors.New("run report minimum envelope exceeds limit")
)

var (
// ErrInvalidRunnerConfig identifies an invalid process-owned runner bound.
ErrInvalidRunnerConfig = errors.New("invalid scenario runner configuration")
// ErrScenarioLimit identifies a scenario that exceeds a process-owned bound.
ErrScenarioLimit = errors.New("scenario exceeds runner limit")
// ErrSourceResolution identifies a source that could not be resolved or whose digest did not match.
ErrSourceResolution = errors.New("scenario source resolution failed")
// ErrCallbackProfile identifies a scenario callback profile the runner does not provide.
ErrCallbackProfile = errors.New("scenario callback profile unavailable")
// ErrDeffactsSelection identifies a missing or ambiguous named deffacts selection.
ErrDeffactsSelection = errors.New("scenario deffacts selection failed")
)

var ErrInvalidValueJSON = errors.New("invalid Gess value JSON")

AppliedLimits echoes the input, execution, and report limits used for a run.

type AppliedLimits struct {
Input InputLimits `json:"input"`
Run RunOptions `json:"run"`
Report ReportLimits `json:"report"`
}

ArtifactReference identifies a related content-addressed artifact.

type ArtifactReference struct {
Kind string `json:"kind"`
ID string `json:"id"`
SchemaVersion string `json:"schemaVersion"`
Digest string `json:"digest"`
}

ArtifactReferenceCollection is a bounded explanation reference section.

type ArtifactReferenceCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []ArtifactReference `json:"items"`
}

BuildInfo identifies a report producer or engine build.

type BuildInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}

CallbackProfile identifies the callback surface used by a scenario or report.

type CallbackProfile struct {
Name string `json:"name"`
Version string `json:"version"`
Digest string `json:"digest"`
}

DisabledCallbackProfile returns the canonical profile for runners that do not expose host actions, calls, or pure functions.

func DisabledCallbackProfile() CallbackProfile

CheckCollection is a bounded expectation check section.

type CheckCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []CheckResult `json:"items"`
}

CheckResult records one evaluated scenario expectation.

type CheckResult struct {
Path string `json:"path"`
Passed bool `json:"passed"`
Expected string `json:"expected"`
Actual string `json:"actual"`
Message string `json:"message"`
}

Counter is a named non-negative runtime measurement.

type Counter struct {
Name string `json:"name"`
Value DecimalUint64 `json:"value"`
Unit string `json:"unit"`
}

CounterCollection is a bounded report counter section.

type CounterCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []Counter `json:"items"`
}

DecimalUint64 carries an unsigned 64-bit structural counter as a canonical decimal JSON string. String encoding keeps report identities and ordering exact in JavaScript clients.

type DecimalUint64 uint64

NewDecimalUint64 constructs a decimal counter from value.

func NewDecimalUint64(value uint64) DecimalUint64

MarshalJSON implements json.Marshaler.

func (value DecimalUint64) MarshalJSON() ([]byte, error)

String returns the canonical unsigned decimal representation.

func (value DecimalUint64) String() string

Uint64 returns the underlying counter value.

func (value DecimalUint64) Uint64() uint64

UnmarshalJSON implements json.Unmarshaler. The receiver is unchanged when decoding fails.

func (value *DecimalUint64) UnmarshalJSON(data []byte) error

Diagnostic is a stable structured report diagnostic.

type Diagnostic struct {
ID string `json:"id"`
Phase string `json:"phase"`
Severity Severity `json:"severity"`
Code string `json:"code"`
Message string `json:"message"`
Target string `json:"target"`
Span *SourceSpan `json:"span,omitempty"`
Retryable bool `json:"retryable"`
}

DiagnosticCollection is a bounded report diagnostic section.

type DiagnosticCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []Diagnostic `json:"items"`
}

ErrorPayload describes a structured terminal or event error.

type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
Span *SourceSpan `json:"span,omitempty"`
}

Event records one ordered runtime event.

type Event struct {
Sequence DecimalUint64 `json:"sequence"`
RunID string `json:"runId"`
Type EventType `json:"type"`
Severity Severity `json:"severity"`
Generation DecimalUint64 `json:"generation"`
Recency DecimalUint64 `json:"recency"`
RuleID string `json:"ruleId"`
RuleRevisionID string `json:"ruleRevisionId"`
ActivationID string `json:"activationId"`
Source *SourceSpan `json:"source,omitempty"`
ActionName string `json:"actionName"`
ActionIndex *int64 `json:"actionIndex,omitempty"`
FactIDs []string `json:"factIds"`
Error *ErrorPayload `json:"error,omitempty"`
}

EventCapture is a bounded, ordered event capture.

type EventCapture struct {
Items []session.Event
Total int64
Truncated bool
}

EventCollection is a bounded report event section.

type EventCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []Event `json:"items"`
}

EventType identifies a reported runtime event.

type EventType string

EventFactAsserted, EventFactModified, EventFactRetracted, EventReset, EventRuleActivated, EventRuleDeactivated, EventRuleFired, EventActionFailed, EventLogicalSupportAdded, EventLogicalSupportRemoved

Section titled “EventFactAsserted, EventFactModified, EventFactRetracted, EventReset, EventRuleActivated, EventRuleDeactivated, EventRuleFired, EventActionFailed, EventLogicalSupportAdded, EventLogicalSupportRemoved”

EventFactAsserted and the related constants are valid runtime event types.

const (
EventFactAsserted EventType = "fact_asserted"
EventFactModified EventType = "fact_modified"
EventFactRetracted EventType = "fact_retracted"
EventReset EventType = "reset"
EventRuleActivated EventType = "rule_activated"
EventRuleDeactivated EventType = "rule_deactivated"
EventRuleFired EventType = "rule_fired"
EventActionFailed EventType = "action_failed"
EventLogicalSupportAdded EventType = "logical_support_added"
EventLogicalSupportRemoved EventType = "logical_support_removed"
)

ExecutionError preserves a stable phase while wrapping the public Gess error.

type ExecutionError struct {
Stage ExecutionStage
Err error
}
func (e *ExecutionError) Error() string
func (e *ExecutionError) Unwrap() error

ExecutionOutcome classifies the complete scenario operation.

type ExecutionOutcome string

OutcomeCompleted, OutcomeMaxFacts, OutcomeMaxFirings, OutcomeDeadline, OutcomeCanceled, OutcomeHalted, OutcomeValidationError, OutcomeRuntimeError

Section titled “OutcomeCompleted, OutcomeMaxFacts, OutcomeMaxFirings, OutcomeDeadline, OutcomeCanceled, OutcomeHalted, OutcomeValidationError, OutcomeRuntimeError”
const (
OutcomeCompleted ExecutionOutcome = "completed"
OutcomeMaxFacts ExecutionOutcome = "max_facts"
OutcomeMaxFirings ExecutionOutcome = "max_firings"
OutcomeDeadline ExecutionOutcome = "deadline"
OutcomeCanceled ExecutionOutcome = "canceled"
OutcomeHalted ExecutionOutcome = "halted"
OutcomeValidationError ExecutionOutcome = "validation_error"
OutcomeRuntimeError ExecutionOutcome = "runtime_error"
)

ExecutionResult is the bounded semantic result of one scenario execution. It never exposes the mutable session and remains usable after Run returns.

type ExecutionResult struct {
Outcome ExecutionOutcome
Stage ExecutionStage
ScenarioDigest string
Sources []ResolvedSource
RulesetID rules.RulesetID
Rules []rules.Rule
CallbackProfile CallbackProfile
Limits AppliedLimits
Run session.RunResult
Facts FactCapture
Firings EventCapture
Events EventCapture
Output OutputCapture
Queries []QueryExecution
}

ExecutionStage identifies the runner phase that produced an error.

type ExecutionStage string

StageValidate, StageResolve, StageParse, StageLoad, StageCompile, StageSession, StageRun, StageQuery

Section titled “StageValidate, StageResolve, StageParse, StageLoad, StageCompile, StageSession, StageRun, StageQuery”
const (
StageValidate ExecutionStage = "validate"
StageResolve ExecutionStage = "resolve"
StageParse ExecutionStage = "parse"
StageLoad ExecutionStage = "load"
StageCompile ExecutionStage = "compile"
StageSession ExecutionStage = "session"
StageRun ExecutionStage = "run"
StageQuery ExecutionStage = "query"
)

Expectations contains optional assertions checked against a run report.

type Expectations struct {
TerminalStatus TerminalStatus `json:"terminalStatus"`
FactCount *int64 `json:"factCount,omitempty"`
FiringCount *int64 `json:"firingCount,omitempty"`
QueryRowCounts map[string]int64 `json:"queryRowCounts"`
}

Fact is a stable reported fact snapshot.

type Fact struct {
ID string `json:"id"`
Name string `json:"name"`
Template string `json:"template"`
Version DecimalUint64 `json:"version"`
Recency DecimalUint64 `json:"recency"`
Generation DecimalUint64 `json:"generation"`
Sequence DecimalUint64 `json:"sequence"`
Support FactSupport `json:"support"`
Fields map[string]Value `json:"fields"`
FieldPresence map[string]FieldPresence `json:"fieldPresence"`
}

FactCapture is a bounded, ordered final working-memory capture.

type FactCapture struct {
Items []session.FactSnapshot
Total int64
Truncated bool
}

FactCollection is a bounded report fact section.

type FactCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []Fact `json:"items"`
}

FactSupport describes how a reported fact is supported.

type FactSupport string

FactSupportStated, FactSupportLogical, FactSupportStatedAndLogical, FactSupportMetadataOnly

Section titled “FactSupportStated, FactSupportLogical, FactSupportStatedAndLogical, FactSupportMetadataOnly”

FactSupportStated and the related constants are valid fact support modes.

const (
FactSupportStated FactSupport = "stated"
FactSupportLogical FactSupport = "logical"
FactSupportStatedAndLogical FactSupport = "stated_and_logical"
FactSupportMetadataOnly FactSupport = "metadata_only"
)

FieldPresence describes how a reported template field obtained its value.

type FieldPresence string

FieldPresenceOmitted, FieldPresenceDefault, FieldPresenceExplicit

Section titled “FieldPresenceOmitted, FieldPresenceDefault, FieldPresenceExplicit”

FieldPresenceOmitted, FieldPresenceDefault, and FieldPresenceExplicit are the valid template field-presence values.

const (
FieldPresenceOmitted FieldPresence = "omitted"
FieldPresenceDefault FieldPresence = "default"
FieldPresenceExplicit FieldPresence = "explicit"
)

Firing records one ordered rule firing.

type Firing struct {
Sequence DecimalUint64 `json:"sequence"`
RunID string `json:"runId"`
ActivationID string `json:"activationId"`
RuleID string `json:"ruleId"`
RuleRevisionID string `json:"ruleRevisionId"`
RuleName string `json:"ruleName"`
Module string `json:"module"`
Salience int64 `json:"salience"`
Source *SourceSpan `json:"source,omitempty"`
FactIDs []string `json:"factIds"`
}

FiringCollection is a bounded report firing section.

type FiringCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []Firing `json:"items"`
}

InitialFact describes a typed fact asserted before execution.

type InitialFact struct {
Template string `json:"template"`
Fields map[string]Value `json:"fields"`
}

InputLimits bounds accepted scenario request content.

type InputLimits struct {
MaxRequestBytes int64 `json:"maxRequestBytes"`
MaxSourceFiles int64 `json:"maxSourceFiles"`
MaxSourceFileBytes int64 `json:"maxSourceFileBytes"`
MaxInitialFacts int64 `json:"maxInitialFacts"`
}

Output is a byte-bounded captured output section.

type Output struct {
Status SectionStatus `json:"status"`
LimitBytes int64 `json:"limitBytes"`
TotalBytes int64 `json:"totalBytes"`
TotalKnown bool `json:"totalKnown"`
ReturnedBytes int64 `json:"returnedBytes"`
Truncated bool `json:"truncated"`
Text string `json:"text"`
}

OutputCapture is a bounded prefix of emitted output with an exact byte total.

type OutputCapture struct {
Text string
LimitBytes int64
TotalBytes int64
Truncated bool
}

QueryCell contains either a fact reference or a typed value under an alias.

type QueryCell struct {
Alias string `json:"alias"`
FactID *string `json:"factId,omitempty"`
Value *Value `json:"value,omitempty"`
}

QueryExecution is one selected query and its bounded ordered rows.

type QueryExecution struct {
Query ScenarioQuery
Rows []session.QueryRow
Total int64
Truncated bool
}

QueryResult records one ordered scenario query result.

type QueryResult struct {
Name string `json:"name"`
Args map[string]Value `json:"args"`
MaxRows int64 `json:"maxRows"`
Rows QueryRowCollection `json:"rows"`
}

QueryRow contains ordered, aliased query cells.

type QueryRow struct {
Cells []QueryCell `json:"cells"`
}

QueryRowCollection is a bounded query result row section.

type QueryRowCollection struct {
Status SectionStatus `json:"status"`
Limit int64 `json:"limit"`
Total int64 `json:"total"`
TotalKnown bool `json:"totalKnown"`
Returned int64 `json:"returned"`
Truncated bool `json:"truncated"`
Items []QueryRow `json:"items"`
}

ReportLimits bounds report sections and encoded report size.

type ReportLimits struct {
MaxFacts int64 `json:"maxFacts"`
MaxFirings int64 `json:"maxFirings"`
MaxEvents int64 `json:"maxEvents"`
MaxQueryRows int64 `json:"maxQueryRows"`
MaxDiagnostics int64 `json:"maxDiagnostics"`
MaxCounters int64 `json:"maxCounters"`
MaxChecks int64 `json:"maxChecks"`
MaxExplanationRefs int64 `json:"maxExplanationRefs"`
MaxOutputBytes int64 `json:"maxOutputBytes"`
MaxReportBytes int64 `json:"maxReportBytes"`
}

ReportMetadata identifies the producer and Gess build recorded in a report.

type ReportMetadata struct {
Producer BuildInfo
Engine BuildInfo
}

ResolvedSource records a portable source path and required content digest.

type ResolvedSource struct {
Path string `json:"path"`
Digest string `json:"digest"`
}

RunOptions contains bounded execution settings.

type RunOptions struct {
Strategy Strategy `json:"strategy"`
MaxFacts int64 `json:"maxFacts"`
MaxFirings int64 `json:"maxFirings"`
DeadlineMS int64 `json:"deadlineMs"`
}

RunReport is the portable, versioned execution result artifact.

type RunReport struct {
SchemaVersion string `json:"schemaVersion"`
Producer BuildInfo `json:"producer"`
Engine BuildInfo `json:"engine"`
Sources []ResolvedSource `json:"sources"`
ScenarioDigest string `json:"scenarioDigest"`
RulesetID string `json:"rulesetId"`
CallbackProfile CallbackProfile `json:"callbackProfile"`
Limits AppliedLimits `json:"limits"`
Terminal TerminalResult `json:"terminal"`
Output Output `json:"output"`
Facts FactCollection `json:"facts"`
Firings FiringCollection `json:"firings"`
Events EventCollection `json:"events"`
Queries []QueryResult `json:"queries"`
Diagnostics DiagnosticCollection `json:"diagnostics"`
Counters CounterCollection `json:"counters"`
Checks CheckCollection `json:"checks"`
ExplanationRefs ArtifactReferenceCollection `json:"explanationRefs"`
}

BuildRunReport projects a completed runner result into the versioned report DTO. executionErr is the error returned alongside execution, if any.

func BuildRunReport(document Scenario, execution ExecutionResult, executionErr error, metadata ReportMetadata) (RunReport, error)

UnmarshalRunReport decodes one strict run-report JSON document.

func UnmarshalRunReport(data []byte) (RunReport, error)

Runner executes scenarios using only public Gess compile and session APIs.

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

NewRunner validates process-owned ceilings and clones registry collections.

func NewRunner(config RunnerConfig) (*Runner, error)

Run resolves, compiles, and executes document under the runner’s ceilings. Any returned error is also classified by result.Outcome and result.Stage.

func (r *Runner) Run(ctx context.Context, document Scenario, resolver SourceResolver) (ExecutionResult, error)

RunnerConfig contains process-owned ceilings and one exact callback profile.

type RunnerConfig struct {
InputLimits InputLimits
RunLimits RunOptions
ReportLimits ReportLimits
CallbackProfile CallbackProfile
Registry dsl.Registry
MaxDemandCascadeSteps int64
}

Scenario is the portable, versioned execution input artifact.

type Scenario struct {
SchemaVersion string `json:"schemaVersion"`
Name string `json:"name"`
Sources []ScenarioSource `json:"sources"`
InitialFacts []InitialFact `json:"initialFacts"`
Deffacts []string `json:"deffacts"`
Globals map[string]Value `json:"globals"`
CallbackProfile CallbackProfile `json:"callbackProfile"`
Run RunOptions `json:"run"`
ReportLimits ReportLimits `json:"reportLimits"`
Queries []ScenarioQuery `json:"queries"`
Expectations *Expectations `json:"expectations,omitempty"`
}

UnmarshalScenario decodes one strict scenario JSON document.

func UnmarshalScenario(data []byte) (Scenario, error)

ScenarioQuery describes an ordered query and its typed arguments.

type ScenarioQuery struct {
Name string `json:"name"`
Args map[string]Value `json:"args"`
MaxRows int64 `json:"maxRows"`
}

ScenarioSource identifies an ordered portable rule source.

type ScenarioSource struct {
Path string `json:"path"`
Digest string `json:"digest,omitempty"`
}

SectionAvailability describes whether a report section was produced.

type SectionAvailability string

SectionAvailable, SectionOmitted, SectionUnsupported

Section titled “SectionAvailable, SectionOmitted, SectionUnsupported”

SectionAvailable, SectionOmitted, and SectionUnsupported are valid availability states.

const (
SectionAvailable SectionAvailability = "available"
SectionOmitted SectionAvailability = "omitted"
SectionUnsupported SectionAvailability = "unsupported"
)

SectionStatus explains the availability of a bounded report section.

type SectionStatus struct {
Availability SectionAvailability `json:"availability"`
Reason string `json:"reason"`
}

Severity classifies diagnostic and event importance.

type Severity string

SeverityInfo, SeverityWarning, SeverityError

Section titled “SeverityInfo, SeverityWarning, SeverityError”

SeverityInfo, SeverityWarning, and SeverityError are valid severity levels.

const (
SeverityInfo Severity = "info"
SeverityWarning Severity = "warning"
SeverityError Severity = "error"
)

SourceResolver resolves a confined portable path to source bytes.

type SourceResolver interface {
ResolveScenarioSource(context.Context, string) ([]byte, error)
}

SourceResolverFunc adapts a function to SourceResolver.

type SourceResolverFunc func(context.Context, string) ([]byte, error)
func (f SourceResolverFunc) ResolveScenarioSource(ctx context.Context, path string) ([]byte, error)

SourceSpan identifies a portable source range.

type SourceSpan struct {
Path string `json:"path"`
StartLine int64 `json:"startLine"`
StartColumn int64 `json:"startColumn"`
EndLine int64 `json:"endLine"`
EndColumn int64 `json:"endColumn"`
}

Strategy selects agenda conflict resolution order.

type Strategy string

StrategyDepth and StrategyBreadth are the supported agenda strategies.

const (
StrategyDepth Strategy = "depth"
StrategyBreadth Strategy = "breadth"
)

TerminalResult records the outcome of scenario execution.

type TerminalResult struct {
Status TerminalStatus `json:"status"`
RunID string `json:"runId"`
Fired int64 `json:"fired"`
Error *ErrorPayload `json:"error,omitempty"`
}

TerminalStatus describes why scenario execution stopped.

type TerminalStatus string

TerminalQuiescent, TerminalMaxFacts, TerminalMaxFirings, TerminalDeadline, TerminalError, TerminalCanceled, TerminalHalted

Section titled “TerminalQuiescent, TerminalMaxFacts, TerminalMaxFirings, TerminalDeadline, TerminalError, TerminalCanceled, TerminalHalted”

TerminalQuiescent and the other terminal constants are valid execution outcomes.

const (
TerminalQuiescent TerminalStatus = "quiescent"
TerminalMaxFacts TerminalStatus = "max_facts"
TerminalMaxFirings TerminalStatus = "max_firings"
TerminalDeadline TerminalStatus = "deadline"
TerminalError TerminalStatus = "error"
TerminalCanceled TerminalStatus = "canceled"
TerminalHalted TerminalStatus = "halted"
)

Value is an opaque JSON wrapper for a rules.Value.

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

NewValue wraps value for lossless JSON encoding. Container storage is defensively copied.

func NewValue(value rules.Value) Value

MarshalJSON implements json.Marshaler.

func (v Value) MarshalJSON() ([]byte, error)

RulesValue returns a defensive copy of the wrapped value.

func (v Value) RulesValue() rules.Value

UnmarshalJSON implements json.Unmarshaler. The receiver is unchanged when decoding fails.

func (v *Value) UnmarshalJSON(data []byte) error

MarshalRunReport returns the canonical JSON encoding of document.

func MarshalRunReport(document RunReport) ([]byte, error)

MarshalScenario returns the canonical JSON encoding of document.

func MarshalScenario(document Scenario) ([]byte, error)

MarshalValue returns the canonical lossless JSON encoding of value.

func MarshalValue(value rules.Value) ([]byte, error)

RunReportDigest returns the SHA-256 digest of the canonical run-report JSON.

func RunReportDigest(document RunReport) (string, error)

ScenarioDigest returns the SHA-256 digest of the canonical scenario JSON.

func ScenarioDigest(document Scenario) (string, error)

UnmarshalValue decodes one strict lossless Gess value JSON envelope.

func UnmarshalValue(data []byte) (rules.Value, error)

ValidateRunReport reports whether document is a valid run-report artifact.

func ValidateRunReport(document RunReport) error

ValidateScenario reports whether document is a valid scenario artifact.

func ValidateScenario(document Scenario) error